Jindra Snobl commited on
Commit
633d9b3
·
1 Parent(s): 93b73cc

Added all files from first attempt

Browse files
Files changed (7) hide show
  1. .env.example +6 -0
  2. .gitignore +165 -0
  3. Dockerfile +35 -0
  4. README.md +5 -3
  5. api/app.py +54 -0
  6. api/embed.py +45 -0
  7. requirements.txt +0 -0
.env.example ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ DATABASE_URL=postgresql://postgres:cocoon@localhost:5432/cocoon
2
+ HASURA_SECRET_HEADER_VALUE=secret
3
+ HASURA_EVENTS_HEADER=x-hasura-event-secret
4
+ DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/1234567890/secret
5
+ TOKENIZERS_PARALLELISM=false
6
+ HF_TOKEN=
.gitignore ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ .venv/
128
+ ENV/
129
+ env.bak/
130
+ venv.bak/
131
+
132
+ # Spyder project settings
133
+ .spyderproject
134
+ .spyproject
135
+
136
+ # Rope project settings
137
+ .ropeproject
138
+
139
+ # mkdocs documentation
140
+ /site
141
+
142
+ # mypy
143
+ .mypy_cache/
144
+ .dmypy.json
145
+ dmypy.json
146
+
147
+ # Pyre type checker
148
+ .pyre/
149
+
150
+ # pytype static type analyzer
151
+ .pytype/
152
+
153
+ # Cython debug symbols
154
+ cython_debug/
155
+
156
+ # PyCharm
157
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
158
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
159
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
160
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
161
+ #.idea/
162
+
163
+ playground/dumps/
164
+ api/tokenizer
165
+ .DS_STORE
Dockerfile ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official Python runtime as a parent image
2
+ FROM python:3.12-slim-bookworm
3
+
4
+ # Set environment variables
5
+ ENV PYTHONDONTWRITEBYTECODE 1
6
+ ENV PYTHONUNBUFFERED 1
7
+
8
+ # Ensure HF_TOKEN is picked up from the environment
9
+ ENV HF_TOKEN=${HUGGINGFACE_TOKEN}
10
+
11
+ # Set work directory in the container
12
+ WORKDIR /code
13
+
14
+ # Install system dependencies
15
+ RUN apt-get update && apt-get install -y --no-install-recommends \
16
+ gcc \
17
+ default-libmysqlclient-dev \
18
+ && rm -rf /var/lib/apt/lists/*
19
+
20
+ # Create the cache directory
21
+ RUN mkdir -p /models/cache
22
+
23
+ # Ensure the directory is writable
24
+ RUN chmod -R 777 /models/cache
25
+
26
+ # Install Python dependencies
27
+ COPY requirements.txt .
28
+ RUN pip install --no-cache-dir -r requirements.txt
29
+
30
+ # Copy the current directory contents into the container at /code
31
+ COPY ./api /code/api
32
+
33
+ # Run the command to start uWSGI
34
+ # Run Huggingface CLI login during runtime
35
+ CMD ["sh", "-c", "huggingface-cli login --token $HF_TOKEN --add-to-git-credential && gunicorn -b 0.0.0.0:7860 api.app:app"]
README.md CHANGED
@@ -1,10 +1,12 @@
1
  ---
2
- title: VectorSearch
3
- emoji: 📚
4
  colorFrom: green
5
- colorTo: pink
6
  sdk: docker
7
  pinned: false
 
 
8
  ---
9
 
10
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: GenerateEmbeddings
3
+ emoji: 💻
4
  colorFrom: green
5
+ colorTo: yellow
6
  sdk: docker
7
  pinned: false
8
+ license: mit
9
+ short_description: Used to generate embeddings of subsidy text/queries
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
api/app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, Blueprint
2
+ import os
3
+ from dotenv import load_dotenv
4
+ from api.embed import get_embeddings
5
+ # from huggingface_hub import login
6
+
7
+ load_dotenv()
8
+
9
+ app = Flask(__name__)
10
+
11
+ hf_token = os.environ.get("HF_TOKEN", "")
12
+
13
+ # login(hf_token)
14
+
15
+ HASURA_SECRET_HEADER_VALUE = os.getenv("HASURA_SECRET_HEADER_VALUE", "secret")
16
+ HASURA_EVENTS_HEADER = os.getenv("HASURA_EVENTS_HEADER", "x-hasura-event-secret")
17
+
18
+ @app.route("/health", methods=["GET"])
19
+ def health_check():
20
+ return jsonify({"status": "OK"}), 200
21
+
22
+ # Create a blueprint for the routes that require middleware
23
+ api_bp = Blueprint("api", __name__)
24
+
25
+ # @api_bp.before_request
26
+ # def verify_hasura_secret():
27
+ # secret = request.headers.get(HASURA_EVENTS_HEADER)
28
+ # if not secret or secret != HASURA_SECRET_HEADER_VALUE:
29
+ # return jsonify({"message": "Invalid secret"}), 401
30
+
31
+ @api_bp.route("/get_embedding", methods=["post"])
32
+ def get_embedding():
33
+ try:
34
+ data = request.get_json()
35
+ query = data.get("query")
36
+ if not query:
37
+ return jsonify({"message": "Query is required"}), 400
38
+ embeddings = get_embeddings(query)
39
+ return (
40
+ jsonify(
41
+ {
42
+ "query": query,
43
+ "embeddings": embeddings,
44
+ }
45
+ ),
46
+ 200,
47
+ )
48
+ except Exception as e:
49
+ return jsonify({"message": f"Error: {str(e)}"}), 500
50
+
51
+ app.register_blueprint(api_bp)
52
+
53
+ if __name__ == "__main__":
54
+ app.run(debug=True)
api/embed.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ import torch
4
+ # from huggingface_hub import login
5
+ from transformers import AutoTokenizer, AutoModel
6
+
7
+ load_dotenv()
8
+
9
+ huggingface_token = os.environ.get("HF_TOKEN", "")
10
+
11
+ print(huggingface_token)
12
+
13
+ # login(huggingface_token)
14
+
15
+ auto_tokenizer = AutoTokenizer.from_pretrained(
16
+ "CocoonBusiness/VectorSearch", token=huggingface_token, low_cpu_mem_usage=True
17
+ )
18
+ model = AutoModel.from_pretrained(
19
+ "jegorkitskerkin/robbert-v2-dutch-base-mqa-finetuned", low_cpu_mem_usage=True
20
+ )
21
+
22
+
23
+ def get_embeddings(text_list):
24
+ encoded_input = auto_tokenizer(
25
+ text_list,
26
+ padding=True,
27
+ truncation=True,
28
+ max_length=500,
29
+ return_tensors="pt",
30
+ add_special_tokens=True,
31
+ )
32
+ model_output = model(**encoded_input)
33
+ embeddings = mean_pooling(model_output, encoded_input["attention_mask"])
34
+ # Make 1D vector
35
+ return embeddings.detach().numpy().flatten().tolist()
36
+
37
+
38
+ def mean_pooling(model_output, attention_mask):
39
+ token_embeddings = model_output[0]
40
+ input_mask_expanded = (
41
+ attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
42
+ )
43
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
44
+ input_mask_expanded.sum(1), min=1e-9
45
+ )
requirements.txt ADDED
The diff for this file is too large to render. See raw diff