nsthorat commited on
Commit
e4f9cbe
1 Parent(s): bcfac19
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env +19 -0
  2. Dockerfile +24 -0
  3. LICENSE +201 -0
  4. requirements.txt +130 -0
  5. src/__init__.py +0 -0
  6. src/__pycache__/__init__.cpython-39.pyc +0 -0
  7. src/__pycache__/config.cpython-39.pyc +0 -0
  8. src/__pycache__/conftest.cpython-39-pytest-7.3.1.pyc +0 -0
  9. src/__pycache__/constants.cpython-39.pyc +0 -0
  10. src/__pycache__/data_loader.cpython-39.pyc +0 -0
  11. src/__pycache__/data_loader_test.cpython-39-pytest-7.3.1.pyc +0 -0
  12. src/__pycache__/db_deprecated.cpython-39.pyc +0 -0
  13. src/__pycache__/db_manager.cpython-39.pyc +0 -0
  14. src/__pycache__/json_encoder.cpython-39.pyc +0 -0
  15. src/__pycache__/make_api.cpython-39.pyc +0 -0
  16. src/__pycache__/make_openapi.cpython-39.pyc +0 -0
  17. src/__pycache__/parquet_writer.cpython-39.pyc +0 -0
  18. src/__pycache__/router_concept.cpython-39.pyc +0 -0
  19. src/__pycache__/router_data_loader.cpython-39.pyc +0 -0
  20. src/__pycache__/router_dataset.cpython-39.pyc +0 -0
  21. src/__pycache__/router_dataset_manager.cpython-39.pyc +0 -0
  22. src/__pycache__/router_embed_fn.cpython-39.pyc +0 -0
  23. src/__pycache__/router_embedding.cpython-39.pyc +0 -0
  24. src/__pycache__/router_signal.cpython-39.pyc +0 -0
  25. src/__pycache__/router_tasks.cpython-39.pyc +0 -0
  26. src/__pycache__/router_utils.cpython-39.pyc +0 -0
  27. src/__pycache__/schema.cpython-39-pytest-7.2.2.pyc +0 -0
  28. src/__pycache__/schema.cpython-39.pyc +0 -0
  29. src/__pycache__/schema_test.cpython-39-pytest-7.2.2.pyc +0 -0
  30. src/__pycache__/schema_test.cpython-39-pytest-7.3.1.pyc +0 -0
  31. src/__pycache__/server.cpython-39.pyc +0 -0
  32. src/__pycache__/server_api.cpython-39.pyc +0 -0
  33. src/__pycache__/server_concept_test.cpython-39-pytest-7.3.1.pyc +0 -0
  34. src/__pycache__/server_concepts_test.cpython-39-pytest-7.3.1.pyc +0 -0
  35. src/__pycache__/server_test.cpython-39-pytest-7.2.2.pyc +0 -0
  36. src/__pycache__/server_test.cpython-39-pytest-7.3.1.pyc +0 -0
  37. src/__pycache__/tasks.cpython-39.pyc +0 -0
  38. src/__pycache__/tasks_test.cpython-39-pytest-7.2.2.pyc +0 -0
  39. src/__pycache__/tasks_test.cpython-39-pytest-7.3.1.pyc +0 -0
  40. src/__pycache__/test_utils.cpython-39-pytest-7.2.2.pyc +0 -0
  41. src/__pycache__/test_utils.cpython-39-pytest-7.3.1.pyc +0 -0
  42. src/__pycache__/utils.cpython-39.pyc +0 -0
  43. src/concepts/__init__.py +0 -0
  44. src/concepts/__pycache__/__init__.cpython-39.pyc +0 -0
  45. src/concepts/__pycache__/concept.cpython-39.pyc +0 -0
  46. src/concepts/__pycache__/concept_test.cpython-39-pytest-7.3.1.pyc +0 -0
  47. src/concepts/__pycache__/db_concept.cpython-39.pyc +0 -0
  48. src/concepts/__pycache__/db_concept_test.cpython-39-pytest-7.2.2.pyc +0 -0
  49. src/concepts/__pycache__/db_concept_test.cpython-39-pytest-7.3.1.pyc +0 -0
  50. src/concepts/concept.py +271 -0
.env ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To overwrite these variables, create a .env.local file
2
+
3
+ # The path to the directory where the data will be downloaded on machine
4
+ LILAC_DATA_PATH=./data
5
+
6
+ # Set to 1 for duckdb to use views instead of materialized tables (lower memory usage, but slower).
7
+ DUCKDB_USE_VIEWS=0
8
+
9
+ # Variables that can be set in .env.local
10
+ #
11
+ # Get key from https://www.cohere.ai/api-keys
12
+ # COHERE_API_KEY=
13
+
14
+ # GCS_REGION=
15
+ # GCS_ACCESS_KEY=
16
+ # GCS_SECRET_KEY=
17
+
18
+ # Get key from https://platform.openai.com/account/api-keys
19
+ # OPENAI_API_KEY=
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NOTE: When we upgrade to 3.11 we can use a slimmer docker image which comes with gcc.
2
+ FROM python:3.9-bullseye
3
+
4
+ # Allow statements and log messages to immediately appear in the Knative logs
5
+ ENV PYTHONUNBUFFERED True
6
+
7
+ # Set the working directory in the container.
8
+ WORKDIR /code
9
+
10
+ COPY .env .
11
+ COPY LICENSE .
12
+
13
+ # Copy static files.
14
+ COPY /web/blueprint/build ./web/blueprint/build
15
+
16
+ # Copy python files.
17
+ COPY /src ./src/
18
+
19
+ # Install the dependencies. This requires exporting requirements.txt from poetry first, which
20
+ # happens from ./build_docker.sh.
21
+ COPY requirements.txt .
22
+ RUN pip install --no-cache-dir -r requirements.txt
23
+
24
+ CMD ["uvicorn", "src.server:app", "--host", "0.0.0.0", "--port", "5432"]
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Lilac AI Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
requirements.txt ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiohttp==3.8.4 ; python_version >= "3.9" and python_version < "3.10"
2
+ aiosignal==1.3.1 ; python_version >= "3.9" and python_version < "3.10"
3
+ anyio==3.7.0 ; python_version >= "3.9" and python_version < "3.10"
4
+ async-timeout==4.0.2 ; python_version >= "3.9" and python_version < "3.10"
5
+ attrs==23.1.0 ; python_version >= "3.9" and python_version < "3.10"
6
+ blis==0.7.9 ; python_version >= "3.9" and python_version < "3.10"
7
+ cachetools==5.3.1 ; python_version >= "3.9" and python_version < "3.10"
8
+ catalogue==2.0.8 ; python_version >= "3.9" and python_version < "3.10"
9
+ certifi==2023.5.7 ; python_version >= "3.9" and python_version < "3.10"
10
+ charset-normalizer==3.1.0 ; python_version >= "3.9" and python_version < "3.10"
11
+ click==8.1.3 ; python_version >= "3.9" and python_version < "3.10"
12
+ cloudpickle==2.2.1 ; python_version >= "3.9" and python_version < "3.10"
13
+ cohere==3.10.0 ; python_version >= "3.9" and python_version < "3.10"
14
+ colorama==0.4.6 ; python_version >= "3.9" and python_version < "3.10" and (platform_system == "Windows" or sys_platform == "win32")
15
+ confection==0.0.4 ; python_version >= "3.9" and python_version < "3.10"
16
+ cymem==2.0.7 ; python_version >= "3.9" and python_version < "3.10"
17
+ cytoolz==0.12.1 ; python_version >= "3.9" and python_version < "3.10"
18
+ dask==2023.5.1 ; python_version >= "3.9" and python_version < "3.10"
19
+ datasets==2.12.0 ; python_version >= "3.9" and python_version < "3.10"
20
+ decorator==5.1.1 ; python_version >= "3.9" and python_version < "3.10"
21
+ dill==0.3.6 ; python_version >= "3.9" and python_version < "3.10"
22
+ distributed==2023.5.1 ; python_version >= "3.9" and python_version < "3.10"
23
+ duckdb==0.8.0 ; python_version >= "3.9" and python_version < "3.10"
24
+ email-reply-parser==0.5.12 ; python_version >= "3.9" and python_version < "3.10"
25
+ exceptiongroup==1.1.1 ; python_version >= "3.9" and python_version < "3.10"
26
+ fastapi==0.95.2 ; python_version >= "3.9" and python_version < "3.10"
27
+ filelock==3.12.0 ; python_version >= "3.9" and python_version < "3.10"
28
+ floret==0.10.3 ; python_version >= "3.9" and python_version < "3.10"
29
+ frozenlist==1.3.3 ; python_version >= "3.9" and python_version < "3.10"
30
+ fsspec==2023.5.0 ; python_version >= "3.9" and python_version < "3.10"
31
+ fsspec[http]==2023.5.0 ; python_version >= "3.9" and python_version < "3.10"
32
+ gcsfs==2023.5.0 ; python_version >= "3.9" and python_version < "3.10"
33
+ google-api-core==2.11.0 ; python_version >= "3.9" and python_version < "3.10"
34
+ google-api-python-client==2.88.0 ; python_version >= "3.9" and python_version < "3.10"
35
+ google-auth-httplib2==0.1.0 ; python_version >= "3.9" and python_version < "3.10"
36
+ google-auth-oauthlib==1.0.0 ; python_version >= "3.9" and python_version < "3.10"
37
+ google-auth==2.19.1 ; python_version >= "3.9" and python_version < "3.10"
38
+ google-cloud-core==2.3.2 ; python_version >= "3.9" and python_version < "3.10"
39
+ google-cloud-storage==2.9.0 ; python_version >= "3.9" and python_version < "3.10"
40
+ google-crc32c==1.5.0 ; python_version >= "3.9" and python_version < "3.10"
41
+ google-resumable-media==2.5.0 ; python_version >= "3.9" and python_version < "3.10"
42
+ googleapis-common-protos==1.59.0 ; python_version >= "3.9" and python_version < "3.10"
43
+ h11==0.14.0 ; python_version >= "3.9" and python_version < "3.10"
44
+ httplib2==0.22.0 ; python_version >= "3.9" and python_version < "3.10"
45
+ httptools==0.5.0 ; python_version >= "3.9" and python_version < "3.10"
46
+ huggingface-hub==0.15.1 ; python_version >= "3.9" and python_version < "3.10"
47
+ idna==3.4 ; python_version >= "3.9" and python_version < "3.10"
48
+ importlib-metadata==6.6.0 ; python_version >= "3.9" and python_version < "3.10"
49
+ jellyfish==0.11.2 ; python_version >= "3.9" and python_version < "3.10"
50
+ jinja2==3.1.2 ; python_version >= "3.9" and python_version < "3.10"
51
+ joblib==1.2.0 ; python_version >= "3.9" and python_version < "3.10"
52
+ langcodes==3.3.0 ; python_version >= "3.9" and python_version < "3.10"
53
+ locket==1.0.0 ; python_version >= "3.9" and python_version < "3.10"
54
+ markupsafe==2.1.3 ; python_version >= "3.9" and python_version < "3.10"
55
+ mpmath==1.3.0 ; python_version >= "3.9" and python_version < "3.10"
56
+ msgpack==1.0.5 ; python_version >= "3.9" and python_version < "3.10"
57
+ multidict==6.0.4 ; python_version >= "3.9" and python_version < "3.10"
58
+ multiprocess==0.70.14 ; python_version >= "3.9" and python_version < "3.10"
59
+ murmurhash==1.0.9 ; python_version >= "3.9" and python_version < "3.10"
60
+ networkx==3.1 ; python_version >= "3.9" and python_version < "3.10"
61
+ nltk==3.8.1 ; python_version >= "3.9" and python_version < "3.10"
62
+ numpy==1.24.3 ; python_version >= "3.9" and python_version < "3.10"
63
+ oauthlib==3.2.2 ; python_version >= "3.9" and python_version < "3.10"
64
+ openai-function-call==0.0.5 ; python_version >= "3.9" and python_version < "3.10"
65
+ openai==0.27.8 ; python_version >= "3.9" and python_version < "3.10"
66
+ orjson==3.9.0 ; python_version >= "3.9" and python_version < "3.10"
67
+ packaging==23.1 ; python_version >= "3.9" and python_version < "3.10"
68
+ pandas==2.0.2 ; python_version >= "3.9" and python_version < "3.10"
69
+ partd==1.4.0 ; python_version >= "3.9" and python_version < "3.10"
70
+ pathy==0.10.1 ; python_version >= "3.9" and python_version < "3.10"
71
+ pillow==9.5.0 ; python_version >= "3.9" and python_version < "3.10"
72
+ preshed==3.0.8 ; python_version >= "3.9" and python_version < "3.10"
73
+ protobuf==4.23.2 ; python_version >= "3.9" and python_version < "3.10"
74
+ psutil==5.9.5 ; python_version >= "3.9" and python_version < "3.10"
75
+ pyarrow==9.0.0 ; python_version >= "3.9" and python_version < "3.10"
76
+ pyasn1-modules==0.3.0 ; python_version >= "3.9" and python_version < "3.10"
77
+ pyasn1==0.5.0 ; python_version >= "3.9" and python_version < "3.10"
78
+ pydantic==1.10.9 ; python_version >= "3.9" and python_version < "3.10"
79
+ pyparsing==3.0.9 ; python_version >= "3.9" and python_version < "3.10"
80
+ pyphen==0.14.0 ; python_version >= "3.9" and python_version < "3.10"
81
+ python-dateutil==2.8.2 ; python_version >= "3.9" and python_version < "3.10"
82
+ python-dotenv==1.0.0 ; python_version >= "3.9" and python_version < "3.10"
83
+ pytz==2023.3 ; python_version >= "3.9" and python_version < "3.10"
84
+ pyyaml==6.0 ; python_version >= "3.9" and python_version < "3.10"
85
+ regex==2023.6.3 ; python_version >= "3.9" and python_version < "3.10"
86
+ requests-oauthlib==1.3.1 ; python_version >= "3.9" and python_version < "3.10"
87
+ requests==2.31.0 ; python_version >= "3.9" and python_version < "3.10"
88
+ responses==0.18.0 ; python_version >= "3.9" and python_version < "3.10"
89
+ rsa==4.9 ; python_version >= "3.9" and python_version < "3.10"
90
+ scikit-learn==1.2.2 ; python_version >= "3.9" and python_version < "3.10"
91
+ scipy==1.10.1 ; python_version >= "3.9" and python_version < "3.10"
92
+ sentence-transformers==2.2.2 ; python_version >= "3.9" and python_version < "3.10"
93
+ sentencepiece==0.1.99 ; python_version >= "3.9" and python_version < "3.10"
94
+ setuptools==65.7.0 ; python_version >= "3.9" and python_version < "3.10"
95
+ six==1.16.0 ; python_version >= "3.9" and python_version < "3.10"
96
+ smart-open==6.3.0 ; python_version >= "3.9" and python_version < "3.10"
97
+ sniffio==1.3.0 ; python_version >= "3.9" and python_version < "3.10"
98
+ sortedcontainers==2.4.0 ; python_version >= "3.9" and python_version < "3.10"
99
+ spacy-legacy==3.0.12 ; python_version >= "3.9" and python_version < "3.10"
100
+ spacy-loggers==1.0.4 ; python_version >= "3.9" and python_version < "3.10"
101
+ spacy==3.5.3 ; python_version >= "3.9" and python_version < "3.10"
102
+ srsly==2.4.6 ; python_version >= "3.9" and python_version < "3.10"
103
+ starlette==0.27.0 ; python_version >= "3.9" and python_version < "3.10"
104
+ sympy==1.12 ; python_version >= "3.9" and python_version < "3.10"
105
+ tblib==1.7.0 ; python_version >= "3.9" and python_version < "3.10"
106
+ textacy==0.13.0 ; python_version >= "3.9" and python_version < "3.10"
107
+ thinc==8.1.10 ; python_version >= "3.9" and python_version < "3.10"
108
+ threadpoolctl==3.1.0 ; python_version >= "3.9" and python_version < "3.10"
109
+ tokenizers==0.13.3 ; python_version >= "3.9" and python_version < "3.10"
110
+ toolz==0.12.0 ; python_version >= "3.9" and python_version < "3.10"
111
+ torch==2.0.1 ; python_version >= "3.9" and python_version < "3.10"
112
+ torchvision==0.15.2 ; python_version >= "3.9" and python_version < "3.10"
113
+ tornado==6.3.2 ; python_version >= "3.9" and python_version < "3.10"
114
+ tqdm==4.65.0 ; python_version >= "3.9" and python_version < "3.10"
115
+ transformers==4.29.2 ; python_version >= "3.9" and python_version < "3.10"
116
+ typer==0.7.0 ; python_version >= "3.9" and python_version < "3.10"
117
+ types-psutil==5.9.5.13 ; python_version >= "3.9" and python_version < "3.10"
118
+ typing-extensions==4.6.3 ; python_version >= "3.9" and python_version < "3.10"
119
+ tzdata==2023.3 ; python_version >= "3.9" and python_version < "3.10"
120
+ uritemplate==4.1.1 ; python_version >= "3.9" and python_version < "3.10"
121
+ urllib3==1.26.16 ; python_version >= "3.9" and python_version < "3.10"
122
+ uvicorn[standard]==0.20.0 ; python_version >= "3.9" and python_version < "3.10"
123
+ uvloop==0.17.0 ; (sys_platform != "win32" and sys_platform != "cygwin") and platform_python_implementation != "PyPy" and python_version >= "3.9" and python_version < "3.10"
124
+ wasabi==1.1.1 ; python_version >= "3.9" and python_version < "3.10"
125
+ watchfiles==0.19.0 ; python_version >= "3.9" and python_version < "3.10"
126
+ websockets==11.0.3 ; python_version >= "3.9" and python_version < "3.10"
127
+ xxhash==3.2.0 ; python_version >= "3.9" and python_version < "3.10"
128
+ yarl==1.9.2 ; python_version >= "3.9" and python_version < "3.10"
129
+ zict==3.0.0 ; python_version >= "3.9" and python_version < "3.10"
130
+ zipp==3.15.0 ; python_version >= "3.9" and python_version < "3.10"
src/__init__.py ADDED
File without changes
src/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (129 Bytes). View file
 
src/__pycache__/config.cpython-39.pyc ADDED
Binary file (611 Bytes). View file
 
src/__pycache__/conftest.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (1.41 kB). View file
 
src/__pycache__/constants.cpython-39.pyc ADDED
Binary file (395 Bytes). View file
 
src/__pycache__/data_loader.cpython-39.pyc ADDED
Binary file (4.36 kB). View file
 
src/__pycache__/data_loader_test.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (4.35 kB). View file
 
src/__pycache__/db_deprecated.cpython-39.pyc ADDED
Binary file (9.11 kB). View file
 
src/__pycache__/db_manager.cpython-39.pyc ADDED
Binary file (1.36 kB). View file
 
src/__pycache__/json_encoder.cpython-39.pyc ADDED
Binary file (1.94 kB). View file
 
src/__pycache__/make_api.cpython-39.pyc ADDED
Binary file (1.06 kB). View file
 
src/__pycache__/make_openapi.cpython-39.pyc ADDED
Binary file (1.02 kB). View file
 
src/__pycache__/parquet_writer.cpython-39.pyc ADDED
Binary file (3.06 kB). View file
 
src/__pycache__/router_concept.cpython-39.pyc ADDED
Binary file (6.19 kB). View file
 
src/__pycache__/router_data_loader.cpython-39.pyc ADDED
Binary file (2.97 kB). View file
 
src/__pycache__/router_dataset.cpython-39.pyc ADDED
Binary file (10.8 kB). View file
 
src/__pycache__/router_dataset_manager.cpython-39.pyc ADDED
Binary file (6.12 kB). View file
 
src/__pycache__/router_embed_fn.cpython-39.pyc ADDED
Binary file (1.27 kB). View file
 
src/__pycache__/router_embedding.cpython-39.pyc ADDED
Binary file (1.31 kB). View file
 
src/__pycache__/router_signal.cpython-39.pyc ADDED
Binary file (1.92 kB). View file
 
src/__pycache__/router_tasks.cpython-39.pyc ADDED
Binary file (585 Bytes). View file
 
src/__pycache__/router_utils.cpython-39.pyc ADDED
Binary file (1.31 kB). View file
 
src/__pycache__/schema.cpython-39-pytest-7.2.2.pyc ADDED
Binary file (14 kB). View file
 
src/__pycache__/schema.cpython-39.pyc ADDED
Binary file (15.6 kB). View file
 
src/__pycache__/schema_test.cpython-39-pytest-7.2.2.pyc ADDED
Binary file (9.41 kB). View file
 
src/__pycache__/schema_test.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (9.4 kB). View file
 
src/__pycache__/server.cpython-39.pyc ADDED
Binary file (2.48 kB). View file
 
src/__pycache__/server_api.cpython-39.pyc ADDED
Binary file (4.46 kB). View file
 
src/__pycache__/server_concept_test.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (20.5 kB). View file
 
src/__pycache__/server_concepts_test.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (141 Bytes). View file
 
src/__pycache__/server_test.cpython-39-pytest-7.2.2.pyc ADDED
Binary file (8.39 kB). View file
 
src/__pycache__/server_test.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (12.5 kB). View file
 
src/__pycache__/tasks.cpython-39.pyc ADDED
Binary file (9.67 kB). View file
 
src/__pycache__/tasks_test.cpython-39-pytest-7.2.2.pyc ADDED
Binary file (2.91 kB). View file
 
src/__pycache__/tasks_test.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (2.91 kB). View file
 
src/__pycache__/test_utils.cpython-39-pytest-7.2.2.pyc ADDED
Binary file (889 Bytes). View file
 
src/__pycache__/test_utils.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (1.1 kB). View file
 
src/__pycache__/utils.cpython-39.pyc ADDED
Binary file (8.89 kB). View file
 
src/concepts/__init__.py ADDED
File without changes
src/concepts/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (140 Bytes). View file
 
src/concepts/__pycache__/concept.cpython-39.pyc ADDED
Binary file (9.74 kB). View file
 
src/concepts/__pycache__/concept_test.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (3.74 kB). View file
 
src/concepts/__pycache__/db_concept.cpython-39.pyc ADDED
Binary file (12.1 kB). View file
 
src/concepts/__pycache__/db_concept_test.cpython-39-pytest-7.2.2.pyc ADDED
Binary file (13.2 kB). View file
 
src/concepts/__pycache__/db_concept_test.cpython-39-pytest-7.3.1.pyc ADDED
Binary file (26.9 kB). View file
 
src/concepts/concept.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Defines the concept and the concept models."""
2
+ import random
3
+ from typing import Iterable, Literal, Optional, Union
4
+
5
+ import numpy as np
6
+ from pydantic import BaseModel, validator
7
+ from sklearn.exceptions import NotFittedError
8
+ from sklearn.linear_model import LogisticRegression
9
+
10
+ from ..db_manager import get_dataset
11
+ from ..embeddings.embedding import get_embed_fn
12
+ from ..schema import Path, RichData, SignalInputType, normalize_path
13
+ from ..signals.signal import TextEmbeddingSignal, get_signal_cls
14
+ from ..utils import DebugTimer
15
+
16
+ LOCAL_CONCEPT_NAMESPACE = 'local'
17
+
18
+ # Number of randomly sampled negative examples to use for training. This is used to obtain a more
19
+ # balanced model that works with a specific dataset.
20
+ DEFAULT_NUM_NEG_EXAMPLES = 300
21
+
22
+
23
+ class ConceptColumnInfo(BaseModel):
24
+ """Information about a dataset associated with a concept."""
25
+ # Namespace of the dataset.
26
+ namespace: str
27
+ # Name of the dataset.
28
+ name: str
29
+ # Path holding the text to use for negative examples.
30
+ path: Path
31
+
32
+ num_negative_examples = DEFAULT_NUM_NEG_EXAMPLES
33
+
34
+
35
+ class ExampleOrigin(BaseModel):
36
+ """The origin of an example."""
37
+ # The namespace that holds the dataset.
38
+ dataset_namespace: str
39
+
40
+ # The name of the dataset.
41
+ dataset_name: str
42
+
43
+ # The id of row in the dataset that the example was added from.
44
+ dataset_row_id: str
45
+
46
+
47
+ DraftId = Union[Literal['main'], str]
48
+ DRAFT_MAIN = 'main'
49
+
50
+
51
+ class ExampleIn(BaseModel):
52
+ """An example in a concept without the id (used for adding new examples)."""
53
+ label: bool
54
+ text: Optional[str]
55
+ img: Optional[bytes]
56
+ origin: Optional[ExampleOrigin]
57
+ # The name of the draft to put the example in. If None, puts it in the main draft.
58
+ draft: Optional[DraftId] = DRAFT_MAIN
59
+
60
+ @validator('text')
61
+ def parse_text(cls, text: str) -> str:
62
+ """Fixes surrogate errors in text: https://github.com/ijl/orjson/blob/master/README.md#str ."""
63
+ return text.encode('utf-8', 'replace').decode('utf-8')
64
+
65
+
66
+ class Example(ExampleIn):
67
+ """A single example in a concept used for training a concept model."""
68
+ id: str
69
+
70
+
71
+ class Concept(BaseModel):
72
+ """A concept is a collection of examples."""
73
+ # The namespace of the concept.
74
+ namespace: str = LOCAL_CONCEPT_NAMESPACE
75
+ # The name of the concept.
76
+ concept_name: str
77
+ # The type of the data format that this concept represents.
78
+ type: SignalInputType
79
+ data: dict[str, Example]
80
+ version: int = 0
81
+
82
+ def drafts(self) -> list[DraftId]:
83
+ """Gets all the drafts for the concept."""
84
+ drafts: set[DraftId] = set([DRAFT_MAIN]) # Always return the main draft.
85
+ for example in self.data.values():
86
+ if example.draft:
87
+ drafts.add(example.draft)
88
+ return list(sorted(drafts))
89
+
90
+
91
+ class LogisticEmbeddingModel(BaseModel):
92
+ """A model that uses logistic regression with embeddings."""
93
+
94
+ class Config:
95
+ arbitrary_types_allowed = True
96
+ underscore_attrs_are_private = True
97
+
98
+ version: int = -1
99
+
100
+ # The following fields are excluded from JSON serialization, but still pickleable.
101
+ # See `notebooks/Toxicity.ipynb` for an example of training a concept model.
102
+ _model: LogisticRegression = LogisticRegression(
103
+ class_weight=None, C=30, tol=1e-5, warm_start=True, max_iter=1_000, n_jobs=-1)
104
+
105
+ def score_embeddings(self, embeddings: np.ndarray) -> np.ndarray:
106
+ """Get the scores for the provided embeddings."""
107
+ try:
108
+ return self._model.predict_proba(embeddings)[:, 1]
109
+ except NotFittedError:
110
+ return np.random.rand(len(embeddings))
111
+
112
+ def fit(self, embeddings: np.ndarray, labels: list[bool], sample_weights: list[float]) -> None:
113
+ """Fit the model to the provided embeddings and labels."""
114
+ if len(set(labels)) < 2:
115
+ return
116
+ if len(labels) != len(embeddings):
117
+ raise ValueError(
118
+ f'Length of embeddings ({len(embeddings)}) must match length of labels ({len(labels)})')
119
+ if len(sample_weights) != len(labels):
120
+ raise ValueError(
121
+ f'Length of sample_weights ({len(sample_weights)}) must match length of labels '
122
+ f'({len(labels)})')
123
+ self._model.fit(embeddings, labels, sample_weights)
124
+
125
+
126
+ def draft_examples(concept: Concept, draft: DraftId) -> dict[str, Example]:
127
+ """Get the examples in the provided draft by overriding the main draft."""
128
+ draft_examples: dict[str, dict[str, Example]] = {}
129
+ for id, example in concept.data.items():
130
+ draft_examples.setdefault(example.draft or DRAFT_MAIN, {})[example.id] = example
131
+
132
+ if draft == DRAFT_MAIN:
133
+ return draft_examples.get(DRAFT_MAIN, {})
134
+
135
+ if draft not in draft_examples:
136
+ raise ValueError(
137
+ f'Draft {draft} not found in concept. Found drafts: {list(draft_examples.keys())}')
138
+
139
+ # Map the text of the draft to its id so we can dedup with main.
140
+ draft_text_ids = {example.text: id for id, example in draft_examples[draft].items()}
141
+
142
+ # Write each of examples from main to the draft examples only if the text does not appear in the
143
+ # draft.
144
+ for id, example in draft_examples[DRAFT_MAIN].items():
145
+ if example.text not in draft_text_ids:
146
+ draft_examples[draft][id] = example
147
+
148
+ return draft_examples[draft]
149
+
150
+
151
+ class ConceptModel(BaseModel):
152
+ """A concept model. Stores all concept model drafts and manages syncing."""
153
+ # The concept that this model is for.
154
+ namespace: str
155
+ concept_name: str
156
+
157
+ # The name of the embedding for this model.
158
+ embedding_name: str
159
+ version: int = -1
160
+
161
+ # The following fields are excluded from JSON serialization, but still pickleable.
162
+ # Maps a concept id to the embeddings.
163
+ _embeddings: dict[str, np.ndarray] = {}
164
+ _logistic_models: dict[DraftId, LogisticEmbeddingModel] = {}
165
+ _negative_vectors: Optional[np.ndarray] = None
166
+
167
+ class Config:
168
+ arbitrary_types_allowed = True
169
+ underscore_attrs_are_private = True
170
+
171
+ def calibrate_on_dataset(self, column_info: ConceptColumnInfo) -> None:
172
+ """Calibrate the model on the embeddings in the provided vector store."""
173
+ db = get_dataset(column_info.namespace, column_info.name)
174
+ vector_store = db.get_vector_store(normalize_path(column_info.path))
175
+ keys = vector_store.keys()
176
+ num_samples = min(column_info.num_negative_examples, len(keys))
177
+ sample_keys = random.sample(keys, num_samples)
178
+ self._negative_vectors = vector_store.get(sample_keys)
179
+
180
+ def score_embeddings(self, draft: DraftId, embeddings: np.ndarray) -> np.ndarray:
181
+ """Get the scores for the provided embeddings."""
182
+ return self._get_logistic_model(draft).score_embeddings(embeddings)
183
+
184
+ def score(self, draft: DraftId, examples: Iterable[RichData]) -> list[float]:
185
+ """Get the scores for the provided examples."""
186
+ embedding_signal = get_signal_cls(self.embedding_name)()
187
+ if not isinstance(embedding_signal, TextEmbeddingSignal):
188
+ raise ValueError(f'Only text embedding signals are currently supported for concepts. '
189
+ f'"{self.embedding_name}" is a {type(embedding_signal)}.')
190
+
191
+ embed_fn = get_embed_fn(self.embedding_name)
192
+ embeddings = np.array(embed_fn(examples))
193
+ return self._get_logistic_model(draft).score_embeddings(embeddings).tolist()
194
+
195
+ def coef(self, draft: DraftId) -> np.ndarray:
196
+ """Get the coefficients of the underlying ML model."""
197
+ return self._get_logistic_model(draft)._model.coef_.reshape(-1)
198
+
199
+ def _get_logistic_model(self, draft: DraftId) -> LogisticEmbeddingModel:
200
+ """Get the logistic model for the provided draft."""
201
+ if draft not in self._logistic_models:
202
+ self._logistic_models[draft] = LogisticEmbeddingModel(
203
+ namespace=self.namespace,
204
+ concept_name=self.concept_name,
205
+ embedding_name=self.embedding_name,
206
+ version=-1)
207
+ return self._logistic_models[draft]
208
+
209
+ def sync(self, concept: Concept) -> bool:
210
+ """Update the model with the latest labeled concept data."""
211
+ if concept.version == self.version:
212
+ # The model is up to date.
213
+ return False
214
+
215
+ concept_path = (f'{self.namespace}/{self.concept_name}/'
216
+ f'{self.embedding_name}')
217
+ with DebugTimer(f'Computing embeddings for "{concept_path}"'):
218
+ self._compute_embeddings(concept)
219
+
220
+ # Fit each of the drafts, sort by draft name for deterministic behavior.
221
+ for draft in concept.drafts():
222
+ examples = draft_examples(concept, draft)
223
+ embeddings = np.array([self._embeddings[id] for id in examples.keys()])
224
+ labels = [example.label for example in examples.values()]
225
+ num_pos_labels = len([x for x in labels if x])
226
+ num_neg_labels = len([x for x in labels if not x])
227
+ sample_weights = [(1.0 / num_pos_labels if x else 1.0 / num_neg_labels) for x in labels]
228
+ if self._negative_vectors is not None:
229
+ num_implicit_labels = len(self._negative_vectors)
230
+ embeddings = np.concatenate([self._negative_vectors, embeddings])
231
+ labels = [False] * num_implicit_labels + labels
232
+ sample_weights = [1.0 / num_implicit_labels] * num_implicit_labels + sample_weights
233
+
234
+ model = self._get_logistic_model(draft)
235
+ with DebugTimer(f'Fitting model for "{concept_path}"'):
236
+ model.fit(embeddings, labels, sample_weights)
237
+
238
+ # Synchronize the model version with the concept version.
239
+ model.version = concept.version
240
+
241
+ # Synchronize the model version with the concept version.
242
+ self.version = concept.version
243
+
244
+ return True
245
+
246
+ def _compute_embeddings(self, concept: Concept) -> None:
247
+ embedding_signal = get_signal_cls(self.embedding_name)()
248
+ if not isinstance(embedding_signal, TextEmbeddingSignal):
249
+ raise ValueError(f'Only text embedding signals are currently supported for concepts. '
250
+ f'"{self.embedding_name}" is a {type(embedding_signal)}.')
251
+
252
+ embed_fn = get_embed_fn(self.embedding_name)
253
+ concept_embeddings: dict[str, np.ndarray] = {}
254
+
255
+ # Compute the embeddings for the examples with cache miss.
256
+ texts_of_missing_embeddings: dict[str, str] = {}
257
+ for id, example in concept.data.items():
258
+ if id in self._embeddings:
259
+ # Cache hit.
260
+ concept_embeddings[id] = self._embeddings[id]
261
+ else:
262
+ # Cache miss.
263
+ # TODO(smilkov): Support images.
264
+ texts_of_missing_embeddings[id] = example.text or ''
265
+
266
+ missing_ids = texts_of_missing_embeddings.keys()
267
+ missing_embeddings = embed_fn(list(texts_of_missing_embeddings.values()))
268
+
269
+ for id, embedding in zip(missing_ids, missing_embeddings):
270
+ concept_embeddings[id] = embedding
271
+ self._embeddings = concept_embeddings