Skip to content

Commit

Permalink
merge in setup refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
enjalot committed Nov 6, 2024
2 parents 2330bea + a93d5ce commit 1cb6a29
Show file tree
Hide file tree
Showing 67 changed files with 5,505 additions and 3,299 deletions.
128 changes: 128 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[email protected].
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series
of actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.

Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
30 changes: 30 additions & 0 deletions CONTRIBUTION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Contributing to Latent Scope

Thank you for considering contributing to Latent Scope! We welcome contributions from the community and are grateful for your support.

## Case Studies

We are looking for case studies of how Latent Scope has been used to solve real-world problems. If you have a case study to share, please open an issue or send an email to [[email protected]](mailto:[email protected]).

## Development Guide

For detailed information on setting up the development environment and the structure of the project, please refer to the [Development Guide](DEVELOPMENT.md).

## Help Wanted

We have a list of issues that are good entry points for new contributors. Check out the [Help Wanted Issues](https://github.com/enjalot/latent-scope/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) to get started.

## Roadmap

We have organized the roadmap into a list of features and improvements that we would like to make to Latent Scope in [Milestones](https://github.com/enjalot/latent-scope/milestones).
The goal is to launch [1.0 by the end of 2024](https://github.com/enjalot/latent-scope/milestone/1), which will be a polished and refined version of the current Latent Scope process. This work is being done with the support of the [Mozilla Builders Accelerator](https://future.mozilla.org/builders/2024_cohort/).

We have a set of features planned to advance the UX around clustering and add more methods slated for [2.0](https://github.com/enjalot/latent-scope/milestone/3).

Additionally there are some more speculative research ideas captured in [Research Ideas](https://github.com/enjalot/latent-scope/milestone/2) that focus more on the meta process of comparing embeddings, umaps and clusters.

## Code of Conduct

Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.

Thank you for your contributions!
23 changes: 9 additions & 14 deletions documentation/DEVELOPMENT.md → DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
If you are interested in customizing or contributing to latent-scope this document explains the ways to develop it.

## Python module
The `latentscope` directory contains the python source code for the [latent scope pip module](). There are three primary parts to the module:
The `latentscope` directory contains the python source code for the [latent scope pip module](https://pypi.org/project/latentscope/). There are three primary parts to the module:

1. server - contains the flask app and API routes
2. scripts -
Expand All @@ -15,11 +15,12 @@ If you modify the python code and want to try out your changes, you can run loca

```
python -m venv testenv
source venv/bin/activate
source testenv/bin/activate
pip install -e .
ls-serve ~/latent-scope-data
```

We recommend python 3.12 as that's what the project is developed with.

## Web client
The `web` directory contains the JavaScript React source code for the web interface. Node.js is required to be installed on your system to run the development server or build a new version of the module.
Expand All @@ -36,17 +37,11 @@ This will call the local API at http://localhost:5001 as set in `web/.env.develo
## Building for distribution
You can build a new version of the module, this will package the latest version of the web interface as well.

```
python setup.py sdist bdist_wheel
```
This builds the package, including the React app, and bundles it all up.

```
deactivate
python setup.py sdist bdist_wheel
source testenv/bin/activate
pip install dist/latentscope-0.1.0-py3-none-any.whl
You can use the included `build.sh` script to build and install the wheel in a test environment:
```bash
./build.sh 0.4.4
source testenv-whl/bin/activate
ls-serve
```


Expand Down Expand Up @@ -78,7 +73,7 @@ There is a `get_embedding_model(id)` function which will load the appropriate cl

### Chat models
Chat models for summarization of clusters are prepared in [latentscope/models/chat_models.json](latentscope/models/chat_models.json).
There is a `get_chat_model(id)` function which will load the appropriate class based on the model provider. Each provider can support a chat model if the interface is implemented. Adding more chat providers should be relatively straightforward and is still a TODO item.
There is a `get_chat_model(id)` function which will load the appropriate class based on the model provider. Each provider can support a chat model if the interface is implemented. Adding more chat models is captured in [this issue](https://github.com/enjalot/latent-scope/issues/2).

## Scripts
The scripts are outlined in the [README.md](README.md). Each one provides a python interface as well as a command line interface for running its part of the process. They all use ids to read relevant data from disk and then output any relevant information to disk.
Expand Down
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
[![](https://dcbadge.vercel.app/api/server/x7NvpnM4pY?style=flat)](https://discord.gg/x7NvpnM4pY)
[![PyPI version](https://img.shields.io/pypi/v/latentscope.svg)](https://pypi.org/project/latentscope/)

[Docs](https://enjalot.github.io/latent-scope/)

Quickly embed, project, cluster and explore a dataset. This project is a new kind of workflow + tool for visualizing and exploring datasets through the lens of latent spaces.

<img src="https://github.com/enjalot/latent-scope/blob/main/documentation/end.png?raw=true" width="45%" alt="Setup your scope"><img src="https://github.com/enjalot/latent-scope/blob/main/documentation/curate-combined-cluster.png?raw=true" width="45%" alt="Explore and Curate your data">
Expand All @@ -27,18 +29,21 @@ What can you do with Latent Scope? The following examples demonstrate the kinds


### Quick Start
To get started, install the [latent-scope module](https://pypi.org/project/latentscope/) and run the server via the Command Line:
Latent Scope works on Mac, Linux and Windows. Python 3.12 is the recommended python version.

To get started, install the [latent-scope python module](https://pypi.org/project/latentscope/) and run the server via the Command Line:

```bash
python -m venv venv
source venv/bin/activate
pip install latentscope
ls-init ~/local-scope-data --openai_key=XXX --mistral_key=YYY # optional api keys to enable API models
ls-init ~/latent-scope-data --openai_key=XXX --mistral_key=YYY # optional api keys to enable API models
ls-serve
```

Then open your browser to http://localhost:5001 and start processing your first dataset!


See the [Your First Scope](https://enjalot.github.io/latent-scope/your-first-scope) guide for a detailed walk-through of the process.

### Python interface
Expand Down Expand Up @@ -92,7 +97,7 @@ ls-serve
### Repository overview
This repository is currently meant to run locally, with a React frontend that communicates with a python server backend. We support several popular open source embedding models that can run locally as well as proprietary API embedding services. Adding new models and services should be quick and easy.

To learn more about customizing, extending and contributing see [DEVELOPMENT.md](documentation/DEVELOPMENT.md)
To learn more about contributing and the project roadmap see [CONTRIBUTION.md](CONTRIBUTION.md), for technical details see [DEVELOPMENT.md](DEVELOPMENT.md).


### Design principles
Expand Down
2 changes: 1 addition & 1 deletion latentscope/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '0.4.1'
__version__ = '0.4.4'
42 changes: 5 additions & 37 deletions latentscope/models/chat_models.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,6 @@
"max_tokens": 128000
}
},
{
"provider": "openai",
"name": "gpt-4-turbo-preview",
"id": "openai-gpt-4-turbo-preview",
"params": {
"max_tokens": 128000
}
},
{
"provider": "openai",
"name": "gpt-4-turbo",
Expand All @@ -47,38 +39,14 @@
"params": {
"max_tokens": 8192
}
},
{
"provider": "mistralai",
"name": "mistral-tiny",
"id": "mistralai-mistral-tiny",
"params": {
"max_tokens": 8192
}
},
{
"provider": "mistralai",
"name": "mistral-small",
"id": "mistralai-mistral-small",
"params": {
"max_tokens": 8192
}
},
{
"provider": "mistralai",
"name": "mistral-medium",
"id": "mistralai-mistral-medium",
"params": {
"max_tokens": 8192
}
},
},
{
"provider": "transformers",
"name": "meta-llama/Meta-Llama-3-8B-Instruct",
"sanitized_name": "meta-llama___Meta-Llama-3-8B-Instruct",
"id": "transformers-meta-llama___Meta-Llama-3-8B-Instruct",
"name": "meta-llama/Meta-Llama-3.1-8B-Instruct",
"sanitized_name": "meta-llama___Meta-Llama-3.1-8B-Instruct",
"id": "transformers-meta-llama___Meta-Llama-3.1-8B-Instruct",
"params": {
"max_tokens": 8192
"max_tokens": 128000
}
}
]
8 changes: 7 additions & 1 deletion latentscope/models/providers/nltk.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,13 @@ def decode(self, tokens):

def chat(self, messages):
# TODO: this is kind of hacky, since we aren't really using a chat model
tokens = self.encoder.encode(messages[1]["content"])
# We are slicing off the first 86 characters because it contains the prompt for LLMs
text = messages[1]["content"][86:]
text = text.replace("<ListItem>", "")
text = text.replace("< ListItem >", "")
text = text.replace("</ListItem>", "")
text = text.replace("</ ListItem >", "")
tokens = self.encoder.encode(text)
# Remove stopwords
tokens = [word for word in tokens if word.isalpha() and word.lower() not in self.stopwords.words('english')]
# Get the top 3 words
Expand Down
7 changes: 3 additions & 4 deletions latentscope/models/providers/transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def load_model(self):
# from transformers import AutoTokenizer, AutoModel
from sentence_transformers import SentenceTransformer

self.model = SentenceTransformer(self.name, trust_remote_code=True, device=self.device)
self.model = SentenceTransformer(self.name, trust_remote_code=True, device=self.device)#, backend="onnx")
self.tokenizer = self.model.tokenizer

# if "rps" in self.params and self.params["rps"]:
Expand Down Expand Up @@ -74,12 +74,11 @@ def __init__(self, name, params):
from transformers import pipeline
self.torch = torch
self.pipeline = pipeline
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def load_model(self):
# self.pipe = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", torch_dtype=torch.bfloat16, device_map="auto")
# self.pipe = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", torch_dtype=torch.bfloat16, device_map="cpu")
# TODO: support bfloat16 for non mac environmentss
self.pipe = self.pipeline("text-generation", model=self.name, torch_dtype=self.torch.float16, device_map="auto")
self.pipe = self.pipeline("text-generation", model=self.name, torch_dtype=self.torch.float16, device=self.device, trust_remote_code=True)
self.encoder = self.pipe.tokenizer

def chat(self, messages, max_new_tokens=24):
Expand Down
16 changes: 10 additions & 6 deletions latentscope/scripts/export_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,19 @@ def get_next_plot_number():
label_sizes.reset_index()
print(label_sizes)


threshold = -1
if plot_config:
plot_config = json.loads(plot_config)
threshold = plot_config.get("threshold", -1)
del plot_config["threshold"]
plot_config["noise_label"] = "No Topic"

simplified_labels = scope_parquet["label"].copy()
# TODO: optional cut clusters with less than threshold
threshold = 100
# simplified_labels[np.in1d(simplified_labels, label_sizes[label_sizes < threshold].index)] = "No Topic"
if threshold >= 0:
simplified_labels[np.in1d(simplified_labels, label_sizes[label_sizes < threshold].index)] = "No Topic"

highlight_labels = np.unique(simplified_labels)

if plot_config:
plot_config = json.loads(plot_config)
if plot_config is None:
plot_config = {
"label_over_points": True,
Expand Down
Loading

0 comments on commit 1cb6a29

Please sign in to comment.