├── .gitignore ├── LICENSE ├── README.md ├── ThirdParty-Licenses ├── README.md ├── colorama │ └── LICENSE.txt ├── faiss │ └── LICENSE.txt ├── fastapi │ └── LICENSE.txt ├── huggingface-datasets │ └── LICENSE.txt ├── numpy │ └── LICENSE.txt ├── txtai │ └── LICENSE.txt └── uvicorn │ └── LICENSE.md ├── Untested ├── README.md └── run_macos.sh ├── config.json ├── requirements.txt ├── run_linux.sh ├── run_windows.bat └── start_api.py /.gitignore: -------------------------------------------------------------------------------- 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/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | .idea/ 163 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 [yyyy] [name of copyright owner] 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Offline Wikipedia Text API 2 | 3 | Welcome to the Offline Wikipedia Text API! This project provides a simple way to search and retrieve Wikipedia articles from an offline dataset using the `txtai` library. The API offers three endpoints to get full articles by title, full articles by search prompt, and summary snippets of articles by search prompt. 4 | 5 | ## Features 6 | 7 | - **Offline Access**: All Wikipedia article texts are stored offline, allowing for fast and private access. 8 | - **Search Functionality**: Uses the powerful `txtai` library to search for articles by prompts. 9 | 10 | ## Requirements 11 | 12 | * This project requires a minimum of 60GB of hard disk space to store the related datasets 13 | * This project utilizes Git to pull down the needed datasets (https://git-scm.com/downloads) 14 | * This can be skipped by downloading the datasets into their respective folders in the project directory. 15 | * "wiki-dataset" folder: https://huggingface.co/datasets/NeuML/wikipedia-20240101 16 | * "txtai-wikipedia" folder: https://huggingface.co/NeuML/txtai-wikipedia 17 | * The existence of the two dataset folders should skip the git calls, bypassing their need. 18 | * This project is a Python project, and requires Python to run. 19 | 20 | ## Important Notes 21 | 22 | There ARE scripts for Mac and Windows, but they are in the "Untested" folder because of two reasons: 23 | - A) On Mac, I ran into an issue with the XCode supplied git that it doesn't handle large files well. The result 24 | is that I can't download the wikipedia datasets cleanly in that script. Once the sets are in their respective locations, the 25 | script works great. You can find more in the "Untested" folder readme. 26 | - B) I don't have a Linux machine to test with. I've had a couple of people tell me it works fine, so I have 27 | an expectation that it will. 28 | 29 | During first run, the app will first download about 60GB worth of datasets (see above), and then will take about 10-15 30 | minutes to do some indexing. This will only occur on first run; just let it do its thing. If, for any reason, you kill 31 | the process halfway through and need to redo it, you can simply delete the "title_to_index.json" file and it will be 32 | recreated. You can also delete the "wiki-dataset" and "txtai-wikipedia" folders to redownload. 33 | 34 | If you're dataset savvy and want to make new, more up to date, datasets to use with this- NeuML's Hugging Face repos give 35 | instructions on how. 36 | 37 | This project relies heavily on [txtai](https://github.com/neuml/txtai/), which uses various libraries to download 38 | and utilize small models itself for searching. Please see that project for an understanding of what gets downloaded 39 | and where. 40 | 41 | 42 | 43 | 1. **Clone the Repository** 44 | ```sh 45 | git clone https://github.com/SomeOddCodeGuy/OfflineWikipediaTextApi 46 | cd OfflineWikipediaTextApi 47 | ``` 48 | ### Installation via Scripts 49 | 50 | 2. **Run the API** 51 | - **For Windows**: 52 | 53 | *To run with the default configuration (current directory as the base for datasets):* 54 | ```cmd 55 | run_windows.bat 56 | ``` 57 | *To run with a custom directory for the wiki data (parent of `wiki-dataset` and `txtai-wikipedia`):* 58 | ```cmd 59 | run_windows.bat --database_dir path\to\datadirs 60 | ``` 61 | 62 | - **For Linux or MacOS**: 63 | 64 | *To run with the default configuration (current directory as the base for datasets):* 65 | ```sh 66 | ./run_linux.sh 67 | ``` 68 | *Or with custom directory for the wiki data (parent of wiki-dataset and txtai-wikipedia):* 69 | ```sh 70 | ./run_linux.sh --database_dir path/to/datadirs 71 | ``` 72 | - The script was tested on Linux and it might work on MacOS. 73 | - There are currently scripts within "Untested", though there is a known issue for MacOS related to git. A workaround 74 | is presented in the README for that folder. 75 | 76 | ### Manual Installation 77 | 78 | 1) Pull down the code from https://github.com/SomeOddCodeGuy/OfflineWikipediaTextApi 79 | `git clone https://github.com/SomeOddCodeGuy/OfflineWikipediaTextApi` 80 | 2) Open command prompt and navigate to the folder containing the code 81 | `cd OfflineWikipediaTextApi` 82 | 3) Optional: create a python virtual environment. 83 | 1) Windows: `python -m venv venv` 84 | 2) MacOS: `python3 -m venv venv` 85 | 3) Linux: `python -m venv venv` 86 | 4) Optional: activate python virtual environment. 87 | 1) Windows: `venv\Scripts\activate` 88 | 2) MacOS/Linux: `venv/bin/activate` 89 | 3) Fish shell: `venv/bin/activate.fish` 90 | 5) Pip install the requirements from requirements.txt 91 | 1) Windows: `python -m pip install -r requirements.txt` 92 | 2) MacOS: `python3 -m pip install -r requirements.txt` 93 | 3) Linux: `python -m pip install -r requirements.txt` 94 | 6) Pull down the two needed datasets into the following folders within the project folder: 95 | 1) `wiki-dataset` folder: https://huggingface.co/datasets/NeuML/wikipedia-20240901 96 | You would need git-lfs installed to clone it 97 | Windows: https://git-lfs.com/ 98 | Mac: https://git-lfs.com/ or `brew install git-lfs` 99 | Linux Ubuntu/Debian: `sudo apt install git-lfs` 100 | Then run: 101 | `git lfs install` 102 | `git clone https://huggingface.co/datasets/NeuML/wikipedia-20240901` 103 | The dataset requieres to be called `wiki-dataset` so rename it: 104 | `mv wikipedia-20240901 wiki-dataset` 105 | 2) `txtai-wikipedia` folder: https://huggingface.co/NeuML/txtai-wikipedia 106 | `git clone https://huggingface.co/NeuML/txtai-wikipedia` 107 | 3) See project structure below to make sure you did it right 108 | 7) Run start_api.py 109 | 1) Windows: python start_api.py 110 | 2) MacOS/Linux: python3 start_api.py 111 | 112 | Step 7 will take between 10-15 minutes on the first run only. This is to index some stuff for future runs. After that 113 | it should be fast. 114 | 115 | Your project should look like this: 116 | 117 | ```plain 118 | 119 | - OfflineWikipediaTextApi/ 120 | - wiki-dataset/ 121 | - train/ 122 | - data-00000-of-00044.arrow 123 | - data-00001-of-00044.arrow 124 | - ... 125 | - pageviews.sqlite 126 | - README.md 127 | - txtai-wikipedia 128 | - config.json 129 | - documents 130 | - embeddings 131 | - README.md 132 | - start_api.py 133 | - ... 134 | ``` 135 | 136 | 137 | ## Configuration 138 | 139 | The API configuration is managed through the `config.json` file: 140 | 141 | ```json 142 | { 143 | "host": "0.0.0.0", 144 | "port": 5728, 145 | "verbose": false 146 | } 147 | ``` 148 | 149 | The "verbose" is for changing whether the API library uvicorn outputs all logs vs just warning logs. Set to 150 | warning by default. 151 | 152 | ## Endpoints 153 | 154 | ### 1. Get Top Article by Prompt Query 155 | 156 | **Endpoint**: `/top_article` 157 | 158 | #### Example cURL Command 159 | ```sh 160 | curl -G "http://localhost:5728/top_article" --data-urlencode "prompt=Quantum Physics" --data-urlencode "percentile=0.5" --data-urlencode "num_results=10" 161 | ``` 162 | 163 | `NOTE: The num_results for top_article is the number of results to compare to find the top article. This endpoint 164 | always returns a single result, but the higher your num_results the more articles it will compare in an attempt to 165 | find the top scoring` 166 | 167 | ### 2. Get Top N Articles by Prompt Query 168 | 169 | **Endpoint**: `/top_n_articles` 170 | 171 | #### Example cURL Command 172 | ```sh 173 | curl -G "http://localhost:5728/top_n_articles" --data-urlencode "prompt=quantum physics and gravity" --data-urlencode "percentile=0.4" --data-urlencode "num_results=80" --data-urlencode "num_top_articles=6" 174 | ``` 175 | 176 | `NOTE: The num_results for top_n_articles is the number of results to compare to find the top N articles, where num_top_articles is N. 177 | The output articles are given in order of score, where largest scored article is first by default (descending). 178 | If percentile, num_results, and num_top_articles are not specified, then default values of 0.5, 20, and 8 will be used respectively. 179 | num_top_articles can also be negative, where a negative number will give the results as ascending score rather then descending - this is useful 180 | when context is truncated by LLM.` 181 | 182 | ### 3. Get Full Article by Title 183 | 184 | **Endpoint**: `/articles/{title}` 185 | 186 | #### Example cURL Command 187 | ```sh 188 | curl -X GET "http://localhost:5728/articles/Applications%20of%20quantum%20mechanics" 189 | ``` 190 | 191 | ### 4. Get Wiki Summaries by Prompt Query 192 | 193 | **Endpoint**: `/summaries` 194 | 195 | #### Example cURL Command 196 | ```sh 197 | curl -G "http://localhost:5728/summaries" --data-urlencode "prompt=Quantum Physics" --data-urlencode "percentile=0.5" --data-urlencode "num_results=1" 198 | ``` 199 | 200 | ### 5. Get Full Wiki Articles by Prompt Query 201 | 202 | **Endpoint**: `/articles` 203 | 204 | #### Example cURL Command 205 | ```sh 206 | curl -G "http://localhost:5728/articles" --data-urlencode "prompt=Artificial Intelligence" --data-urlencode "percentile=0.5" --data-urlencode "num_results=1" 207 | ``` 208 | 209 | ## License 210 | 211 | This project is licensed under the Apache 2.0 License. See the `LICENSE` file for more details. 212 | 213 | ### Third-Party Licenses 214 | 215 | This project imports dependencies in the requirements.txt: 216 | 217 | - [Uvicorn](https://github.com/encode/uvicorn/) 218 | - [FastAPI](https://github.com/tiangolo/fastapi/) 219 | - [Datasets](https://github.com/huggingface/datasets/) 220 | - [Txtai](https://github.com/neuml/txtai/) 221 | - [Faiss-cpu](https://github.com/facebookresearch/faiss/) 222 | - [Colorama](https://github.com/tartley/colorama/) 223 | - [NumPy](https://github.com/numpy/numpy/) 224 | 225 | Please see ThirdParty-Licenses directory for details on their licenses. 226 | 227 | ## License and Copyright 228 | 229 | OfflineWikipediaTextApi 230 | Copyright (C) 2024 Christopher Smith -------------------------------------------------------------------------------- /ThirdParty-Licenses/README.md: -------------------------------------------------------------------------------- 1 | ## Third Party Licensing Section 2 | 3 | _Last Updated: 2023-07-27_ 4 | 5 | This folder contains the licenses, pulled directly from the relevant repositories, of libraries called within 6 | requirements.txt and utilized via Imports. 7 | 8 | This project does not modify or extend any of those packages, but for due diligence the author is including their full text 9 | licensing within the project. 10 | 11 | ### Current Libraries Utilized: 12 | 13 | #### Uvicorn: 14 | 15 | * License Type: `BSD 3-Clause "New" or "Revised" License` 16 | * Code: https://github.com/encode/uvicorn/ 17 | * License: https://github.com/encode/uvicorn/blob/master/LICENSE.md 18 | 19 | #### FastAPI: 20 | 21 | * License Type: `MIT License` 22 | * Code: https://github.com/tiangolo/fastapi/ 23 | * License: https://github.com/tiangolo/fastapi/blob/master/LICENSE 24 | 25 | #### Datasets: 26 | 27 | * License Type: `Apache License 2.0` 28 | * Code: https://github.com/huggingface/datasets/ 29 | * License: https://github.com/huggingface/datasets/blob/main/LICENSE 30 | 31 | #### Txtai: 32 | 33 | * License Type: `Apache License 2.0` 34 | * Code: https://github.com/neuml/txtai/ 35 | * License: https://github.com/neuml/txtai/blob/master/LICENSE 36 | 37 | #### Faiss-cpu: 38 | 39 | * License Type: `MIT License` 40 | * Code: https://github.com/facebookresearch/faiss/ 41 | * License: https://github.com/facebookresearch/faiss/blob/main/LICENSE 42 | 43 | #### Colorama: 44 | 45 | * License Type: `BSD 3-Clause "New" or "Revised" License` 46 | * Code: https://github.com/tartley/colorama/ 47 | * License: https://github.com/tartley/colorama/blob/master/LICENSE.txt 48 | 49 | #### NumPy: 50 | 51 | * License Type: `NumPy License` 52 | * Code: https://github.com/numpy/numpy/ 53 | * License: https://github.com/numpy/numpy/blob/main/LICENSE.txt 54 | -------------------------------------------------------------------------------- /ThirdParty-Licenses/colorama/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010 Jonathan Hartley 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holders, nor those of its contributors 15 | may be used to endorse or promote products derived from this software without 16 | specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /ThirdParty-Licenses/faiss/LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Facebook, Inc. and its affiliates. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ThirdParty-Licenses/fastapi/LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Sebastián Ramírez 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /ThirdParty-Licenses/huggingface-datasets/LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /ThirdParty-Licenses/numpy/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2005-2024, NumPy Developers. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | 11 | * Redistributions in binary form must reproduce the above 12 | copyright notice, this list of conditions and the following 13 | disclaimer in the documentation and/or other materials provided 14 | with the distribution. 15 | 16 | * Neither the name of the NumPy Developers nor the names of any 17 | contributors may be used to endorse or promote products derived 18 | from this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | -------------------------------------------------------------------------------- /ThirdParty-Licenses/txtai/LICENSE.txt: -------------------------------------------------------------------------------- 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 | Copyright 2020- NeuML LLC 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. -------------------------------------------------------------------------------- /ThirdParty-Licenses/uvicorn/LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright © 2017-present, [Encode OSS Ltd](https://www.encode.io/). 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /Untested/README.md: -------------------------------------------------------------------------------- 1 | ## Contents of this Directory 2 | Any file within this directory (other than the readme) is something that is untested. 3 | Use at your own peril. 4 | 5 | To use the below files, pull them into the root directory of the application (with the run_windows.bat file) and then 6 | run them. 7 | 8 | Current Contents: 9 | ------------------------ 10 | **run_macos.sh** This I have run on my own Mac Studio and it worked EXCEPT for the 11 | git clone call. I need to find a workaround for that. More information in the "KNOWN ISSUE" 12 | section below. 13 | 14 | 15 | ## KNOWN ISSUE: 16 | 17 | ### MacOS 18 | When running the bash script for MacOS, it tries to git clone the two datasets mentioned above. This works fine on my 19 | Windows computer, but if you are using the XCode provided git on MacOS then it does not come with git-lfs. 20 | I tested the script on my Mac, and it only seemed to pull the file headers for the datasets. So instead of 21 | 60GB of dataset files, it pulled down 4KB of dataset files. 22 | 23 | The result is that when it tries to start the API, the api complains about a memory issue. That's because it's trying to 24 | read the datasets and failing. 25 | 26 | The workaround for Mac users is to manually download the two datasets and put them in their respective folders: 27 | * "wiki-dataset" folder: https://huggingface.co/datasets/NeuML/wikipedia-20240101 28 | * "txtai-wikipedia" folder: https://huggingface.co/NeuML/txtai-wikipedia 29 | 30 | The structure for the two datasets in the project, as of 2024-07-28, would look like: 31 | ```plain 32 | - OfflineWikipediaTextApi/ 33 | - wiki-dataset/ 34 | - train/ 35 | - data-00000-of-00044.arrow 36 | - data-00001-of-00044.arrow 37 | - ... 38 | - pageviews.sqlite 39 | - README.md 40 | - txtai-wikipedia 41 | - config.json 42 | - documents 43 | - embeddings 44 | - README.md 45 | - start_api.py 46 | - ... 47 | ``` -------------------------------------------------------------------------------- /Untested/run_macos.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Step 0: Parse any arguments we care about 4 | DATABASE_DIR="." 5 | 6 | while [[ $# -gt 0 ]]; do 7 | case $1 in 8 | --database_dir|-d) 9 | DATABASE_DIR="$2" 10 | shift 2 11 | ;; 12 | --help|-h) 13 | echo "Usage: $0 [--database_dir ]" 14 | exit 0 15 | ;; 16 | *) 17 | shift 18 | ;; 19 | esac 20 | done 21 | 22 | WIKI_DATASET_DIR="${DATABASE_DIR}/wiki-dataset" 23 | TXT_AI_WIKIPEDIA_DIR="${DATABASE_DIR}/txtai-wikipedia" 24 | 25 | # Step A: Create and activate a Python virtual environment 26 | echo "Creating virtual environment" 27 | if [ ! -d "venv" ]; then 28 | python3 -m venv venv 29 | else 30 | echo "Existing venv detected. Activating." 31 | fi 32 | 33 | echo "Activating virtual environment" 34 | source venv/bin/activate 35 | 36 | # Step B: Install requirements from requirements.txt 37 | echo "---------------------------------------------------------------" 38 | echo "Installing python requirements from requirements.txt" 39 | pip install -r requirements.txt 40 | 41 | # Step C: Clone the git repository for full wiki articles 42 | echo "---------------------------------------------------------------" 43 | echo "Downloading Wikipedia dataset. As of 2024-11-14, this is about 44GB" 44 | if [ ! -d "${WIKI_DATASET_DIR}" ]; then 45 | git clone https://huggingface.co/datasets/NeuML/wikipedia-20240901 "${WIKI_DATASET_DIR}" 46 | else 47 | echo "Existing wiki-dataset directory detected." 48 | fi 49 | 50 | # Step D: Clone the git repository for txtai wiki summaries 51 | echo "---------------------------------------------------------------" 52 | echo "Downloading txtai-wikipedia dataset. As of 2024-11-14, this is about 15GB." 53 | if [ ! -d "${TXT_AI_WIKIPEDIA_DIR}" ]; then 54 | git clone https://huggingface.co/NeuML/txtai-wikipedia "${TXT_AI_WIKIPEDIA_DIR}" 55 | else 56 | echo "Existing txtai-wikipedia directory detected." 57 | fi 58 | 59 | # Finally: Start the API 60 | echo "---------------------------------------------------------------" 61 | echo "Starting API. If this is the first run, setup may take 10-15 minutes depending on your machine." 62 | echo "Setup time is due to indexing wikipedia article titles into a json file for API speed." 63 | echo "---------------------------------------------------------------" 64 | echo "API Starting..." 65 | python3 start_api.py --database_dir "${DATABASE_DIR}" -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "host": "0.0.0.0", 3 | "port": 5728, 4 | "verbose": false 5 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | uvicorn~=0.34.0 2 | fastapi~=0.115.12 3 | datasets~=3.5.0 4 | txtai~=8.4.0 5 | colorama~=0.4.6 6 | numpy<2.0.0 7 | accelerate~=1.6.0 8 | -------------------------------------------------------------------------------- /run_linux.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Stop script on any error code and trap errors for easier debugging 4 | set -eE 5 | trap 'echo >&2 "Error - exited with status $? at line $LINENO"' ERR 6 | 7 | # Step 0: Parse any arguments we care about 8 | DATABASE_DIR="." 9 | WIKI_DATA_SET_DIR="$DATABASE_DIR/wiki-dataset" 10 | TXTAI_WIKIPEDIA_DIR="$DATABASE_DIR/txtai-wikipedia" 11 | OTHER_ARGS=() 12 | 13 | function help() { 14 | echo "usage: $0 [-h] [-d DATABASE_DIR]" 15 | echo 16 | echo "Offline Wikipedia Text API" 17 | echo 18 | echo "options:" 19 | echo "-h, --help show this help message and exit" 20 | echo "-d DATABASE_DIR, --database_dir DATABASE_DIR" 21 | echo " Base directory containing the wiki-dataset and txtai-wikipedia" 22 | echo " folders." 23 | } 24 | 25 | while [[ $# -gt 0 ]]; do 26 | case $1 in 27 | --database_dir|-d) 28 | DATABASE_DIR="$2" 29 | WIKI_DATA_SET_DIR="$DATABASE_DIR/wiki-dataset" 30 | TXTAI_WIKIPEDIA_DIR="$DATABASE_DIR/txtai-wikipedia" 31 | shift 2 32 | ;; 33 | --help|-h) 34 | help 35 | exit 0 36 | ;; 37 | *) 38 | # For any unrecognized args, store them to pass through 39 | OTHER_ARGS+=("$1") 40 | shift 41 | ;; 42 | esac 43 | done 44 | 45 | 46 | # Step A: Create and activate a Python virtual environment 47 | echo Creating virtual environment 48 | if [ ! -d "venv" ]; then 49 | python -m venv venv 50 | else 51 | echo Existing venv detected. Activating. 52 | fi 53 | 54 | echo Activating virtual environment 55 | source venv/bin/activate 56 | 57 | # Step B: Install requirements from requirements.txt 58 | echo --------------------------------------------------------------- 59 | echo Installing python requirements from requirements.txt 60 | pip install --upgrade pip 61 | pip install -r requirements.txt 62 | 63 | # Step C: Clone the git repository for full wiki articles into a directory called "wiki-dataset" 64 | echo --------------------------------------------------------------- 65 | echo Downloading Wikipedia dataset. As of 2024-11-14, this is about 44GB 66 | if [ ! -d "$WIKI_DATA_SET_DIR" ]; then 67 | # Clone with Git LFS support 68 | GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/NeuML/wikipedia-20240901 "$WIKI_DATA_SET_DIR" 69 | echo "Pulling LFS files for wiki dataset (this may take a while)..." 70 | cd "$WIKI_DATA_SET_DIR" && git lfs pull && cd - || echo "LFS pull failed for wiki dataset" 71 | else 72 | echo Existing wiki-dataset directory detected. 73 | echo "Checking for LFS files in wiki dataset..." 74 | cd "$WIKI_DATA_SET_DIR" && git lfs pull && cd - || echo "LFS pull failed for wiki dataset" 75 | fi 76 | 77 | # Step D: Clone the git repository for txtai wiki summaries into a directory called txtai-wikipedia 78 | echo --------------------------------------------------------------- 79 | echo Downloading txtai-wikipedia dataset. As of 2024-11-14, this is about 15GB. 80 | if [ ! -d "$TXTAI_WIKIPEDIA_DIR" ]; then 81 | # Clone with Git LFS support 82 | GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/NeuML/txtai-wikipedia "$TXTAI_WIKIPEDIA_DIR" 83 | echo "Pulling LFS files for txtai dataset (this may take a while)..." 84 | cd "$TXTAI_WIKIPEDIA_DIR" && git lfs pull && cd - || echo "LFS pull failed for txtai dataset" 85 | else 86 | echo Existing txtai-wikipedia directory detected. 87 | echo "Checking for LFS files in txtai dataset..." 88 | cd "$TXTAI_WIKIPEDIA_DIR" && git lfs pull && cd - || echo "LFS pull failed for txtai dataset" 89 | fi 90 | 91 | # Finally: Start the API 92 | echo --------------------------------------------------------------- 93 | echo Starting API. If this is the first run, setup may take 10-15 minutes depending on your machine. 94 | echo Setup time is due to indexing wikipedia article titles into a json file for API speed. 95 | echo --------------------------------------------------------------- 96 | echo API Starting... 97 | python start_api.py --database_dir "$DATABASE_DIR" "${OTHER_ARGS[@]}" -------------------------------------------------------------------------------- /run_windows.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | setlocal 3 | 4 | :: Step 0: Parse input arguments for database directory 5 | set DATABASE_DIR=. 6 | 7 | :parse_args 8 | if "%~1"=="" goto args_done 9 | if /i "%~1"=="--database_dir" ( 10 | set DATABASE_DIR=%~2 11 | shift 12 | shift 13 | ) else ( 14 | shift 15 | ) 16 | goto parse_args 17 | :args_done 18 | 19 | :: Normalize paths 20 | set WIKI_DATASET_DIR=%DATABASE_DIR%\wiki-dataset 21 | set TXT_AI_DIR=%DATABASE_DIR%\txtai-wikipedia 22 | 23 | :: Step A: Create and activate a Python virtual environment 24 | echo Creating virtual environment 25 | if not exist venv ( 26 | python -m venv venv 27 | ) else ( 28 | echo Existing venv detected. Activating. 29 | ) 30 | 31 | echo Activating virtual environment 32 | call venv\Scripts\activate 33 | 34 | :: Step B: Install requirements from requirements.txt 35 | echo --------------------------------------------------------------- 36 | echo Installing python requirements from requirements.txt 37 | pip install -r requirements.txt 38 | 39 | :: Step C: Clone the git repository for full wiki articles into the specified directory 40 | echo --------------------------------------------------------------- 41 | echo Downloading Wikipedia dataset. As of 2024-11-14, this is about 44GB 42 | if not exist "%WIKI_DATASET_DIR%" ( 43 | git clone https://huggingface.co/datasets/NeuML/wikipedia-20240901 "%WIKI_DATASET_DIR%" 44 | ) else ( 45 | echo Existing wiki-dataset directory detected. 46 | ) 47 | 48 | :: Step D: Clone the git repository for txtai wiki summaries into the specified directory 49 | echo --------------------------------------------------------------- 50 | echo Downloading txtai-wikipedia dataset. As of 2024-11-14, this is about 15GB. 51 | if not exist "%TXT_AI_DIR%" ( 52 | git clone https://huggingface.co/NeuML/txtai-wikipedia "%TXT_AI_DIR%" 53 | ) else ( 54 | echo Existing txtai-wikipedia directory detected. 55 | ) 56 | 57 | :: Finally: Start the API 58 | echo --------------------------------------------------------------- 59 | echo Starting API. If this is the first run, setup may take 10-15 minutes depending on your machine. 60 | echo Setup time is due to indexing Wikipedia article titles into a json file for API speed. 61 | echo --------------------------------------------------------------- 62 | echo API Starting... 63 | python start_api.py --database_dir "%DATABASE_DIR%" 64 | 65 | endlocal -------------------------------------------------------------------------------- /start_api.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import json 4 | from typing import List, Dict 5 | 6 | import colorama 7 | from colorama import Fore, Style 8 | from fastapi import FastAPI, HTTPException, Query 9 | from datasets import Dataset, concatenate_datasets 10 | import uvicorn 11 | from txtai.embeddings import Embeddings 12 | 13 | from collections import Counter 14 | import re 15 | 16 | # Correcting an issue in Windows 17 | os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" 18 | 19 | parser = argparse.ArgumentParser(description="Offline Wikipedia Text API") 20 | parser.add_argument( 21 | "-d", 22 | "--database_dir", 23 | default=".", 24 | help="Base directory containing the wiki-dataset and txtai-wikipedia folders." 25 | ) 26 | args = parser.parse_args() 27 | 28 | DATABASE_DIR = args.database_dir 29 | WIKI_DATASET_DIR = os.path.join(DATABASE_DIR, "wiki-dataset", "train") 30 | TXT_AI_DIR = os.path.join(DATABASE_DIR, "txtai-wikipedia") 31 | DICTIONARY_FILE = "title_to_index.json" 32 | CONFIG_FILE = "config.json" 33 | 34 | def load_config(): 35 | """Load the configuration from the JSON file.""" 36 | with open(CONFIG_FILE, 'r') as f: 37 | return json.load(f) 38 | 39 | def load_wiki_dataset(): 40 | """Load the Wikipedia dataset.""" 41 | arrow_files = [os.path.join(WIKI_DATASET_DIR, f) for f in os.listdir(WIKI_DATASET_DIR) if f.endswith('.arrow')] 42 | datasets = [Dataset.from_file(file) for file in arrow_files] 43 | return concatenate_datasets(datasets) 44 | 45 | def load_title_to_index(ds): 46 | """Load or create the title to index mapping.""" 47 | if os.path.exists(DICTIONARY_FILE): 48 | with open(DICTIONARY_FILE, 'r') as f: 49 | return json.load(f) 50 | else: 51 | title_to_index = {record['title']: i for i, record in enumerate(ds)} 52 | with open(DICTIONARY_FILE, 'w') as f: 53 | json.dump(title_to_index, f) 54 | return title_to_index 55 | 56 | # Load configuration 57 | config = load_config() 58 | host = config.get("host", "0.0.0.0") 59 | port = config.get("port", 5728) 60 | verbose = config.get("verbose", False) 61 | log_level = "info" if verbose else "warning" 62 | 63 | # Load datasets and mappings 64 | ds = load_wiki_dataset() 65 | title_to_index = load_title_to_index(ds) 66 | 67 | # Initialize FastAPI app 68 | app = FastAPI() 69 | 70 | # Initialize txtai embeddings 71 | embeddings = Embeddings() 72 | embeddings.load(path=TXT_AI_DIR) 73 | 74 | def escape_sql_string(s) -> str: 75 | s = s.replace("'", "") 76 | s = s.replace("\"", "") 77 | s = s.replace(";", "") 78 | return s 79 | 80 | @app.get("/articles/{title}") 81 | async def get_full_article_by_title(title: str): 82 | """Get the full article by title.""" 83 | title = escape_sql_string(title) 84 | index = title_to_index.get(title) 85 | if index is not None: 86 | record = ds[index] 87 | return {"title": record["title"], "text": record["text"]} 88 | else: 89 | raise HTTPException(status_code=404, detail=f"No record found with title {title}") 90 | 91 | @app.get("/summaries") 92 | async def get_wiki_summary_by_prompt( 93 | prompt: str = Query(..., description="Search prompt"), 94 | percentile: float = Query(0.5, description="Percentile for search relevance"), 95 | num_results: int = Query(5, description="Number of results to return") 96 | ): 97 | prompt = escape_sql_string(prompt) 98 | """Get wiki summaries by search prompt.""" 99 | search_query = f"SELECT id, title, text FROM txtai WHERE similar('{prompt}') and percentile >= {percentile}" 100 | try: 101 | results = embeddings.search(search_query, num_results) 102 | except Exception as e: 103 | raise HTTPException(status_code=500, detail=f"Search error: {e}") 104 | 105 | if not results: 106 | raise HTTPException(status_code=404, detail="No results found for prompt") 107 | 108 | summaries = [] 109 | for result in results: 110 | index = title_to_index.get(result['id']) 111 | if index is not None: 112 | record = ds[index] 113 | summary_text = record["text"][:500] # Return a summary snippet of the first 500 characters 114 | summaries.append({"title": record["title"], "text": summary_text}) 115 | else: 116 | raise HTTPException(status_code=404, detail=f"No record found with title {result['id']}") 117 | 118 | return summaries 119 | 120 | @app.get("/articles") 121 | async def get_full_wiki_articles_by_prompt( 122 | prompt: str = Query(..., description="Search prompt"), 123 | percentile: float = Query(0.5, description="Percentile for search relevance"), 124 | num_results: int = Query(5, description="Number of results to return") 125 | ): 126 | """Get full wiki articles by search prompt.""" 127 | prompt = escape_sql_string(prompt) 128 | search_query = f"SELECT id FROM txtai WHERE similar('{prompt}') and percentile >= {percentile}" 129 | try: 130 | results = embeddings.search(search_query, num_results) 131 | except Exception as e: 132 | raise HTTPException(status_code=500, detail=f"Search error: {e}") 133 | 134 | if not results: 135 | raise HTTPException(status_code=404, detail="No results found for prompt") 136 | 137 | articles = [] 138 | for result in results: 139 | title_id = result['id'] 140 | index = title_to_index.get(title_id) 141 | if index is not None: 142 | record = ds[index] 143 | articles.append({"title": record["title"], "text": record["text"]}) 144 | else: 145 | raise HTTPException(status_code=404, detail=f"No record found with title {title_id}") 146 | 147 | return articles 148 | 149 | @app.get("/top_article") 150 | async def get_top_full_article_by_prompt( 151 | prompt: str = Query(..., description="Search prompt"), 152 | percentile: float = Query(0.5, description="Percentile for search relevance"), 153 | num_results: int = Query(5, description="Number of results to return") 154 | ): 155 | prompt = escape_sql_string(prompt) 156 | """Get the top wiki article by search prompt.""" 157 | search_query = f"SELECT id, text FROM txtai WHERE similar('{prompt}') and percentile >= {percentile}" 158 | try: 159 | results = embeddings.search(search_query, num_results) 160 | except Exception as e: 161 | raise HTTPException(status_code=500, detail=f"Search error: {e}") 162 | 163 | if not results: 164 | raise HTTPException(status_code=404, detail="No results found for prompt") 165 | 166 | articles = [] 167 | for result in results: 168 | index = title_to_index.get(result['id']) 169 | if index is not None: 170 | record = ds[index] 171 | article_text = record["text"] 172 | articles.append({"title": record["title"], "text": article_text}) 173 | else: 174 | raise HTTPException(status_code=404, detail=f"No record found with title {result['id']}") 175 | 176 | best_article = select_best_wikipedia_article(prompt, articles) 177 | if best_article: 178 | return best_article 179 | else: 180 | raise HTTPException(status_code=404, detail="No suitable article found") 181 | 182 | @app.get("/top_n_articles") 183 | async def get_top_n_full_articles_by_prompt( 184 | prompt: str = Query(..., description="Search prompt"), 185 | percentile: float = Query(0.5, description="Percentile for search relevance"), 186 | num_results: int = Query(20, description="Number of results to return"), 187 | num_top_articles: int = Query(8, description="number of top articles to return") 188 | ): 189 | prompt = escape_sql_string(prompt) 190 | """Get the top N wiki articles by search prompt.""" 191 | search_query = f"SELECT id, text FROM txtai WHERE similar('{prompt}') and percentile >= {percentile}" 192 | try: 193 | results = embeddings.search(search_query, num_results) 194 | except Exception as e: 195 | raise HTTPException(status_code=500, detail=f"Search error: {e}") 196 | 197 | if not results: 198 | raise HTTPException(status_code=404, detail="No results found for prompt") 199 | 200 | articles = [] 201 | for result in results: 202 | index = title_to_index.get(result['id']) 203 | if index is not None: 204 | record = ds[index] 205 | article_text = record["text"] 206 | articles.append({"title": record["title"], "text": article_text}) 207 | else: 208 | raise HTTPException(status_code=404, detail=f"No record found with title {result['id']}") 209 | 210 | top_n_articles = select_top_n_wikipedia_articles(prompt, articles, num_top_articles) 211 | if top_n_articles: 212 | return top_n_articles 213 | else: 214 | raise HTTPException(status_code=404, detail="No suitable article found") 215 | 216 | def select_best_wikipedia_article(prompt: str, articles: List[Dict[str, str]]) -> Dict[str, str]: 217 | """ 218 | Select the best matching article based on the prompt, accounting for token frequencies. 219 | 220 | Args: 221 | prompt (str): The original prompt. 222 | articles (list): List of dictionaries with 'title' and 'text'. 223 | 224 | Returns: 225 | dict: The article dictionary with the highest similarity score. 226 | """ 227 | 228 | def tokenize(text): 229 | return re.findall(r'\w+', text.lower()) 230 | 231 | prompt_tokens = tokenize(prompt) 232 | prompt_counter = Counter(prompt_tokens) 233 | best_score = -1 234 | best_article = None 235 | 236 | for article in articles: 237 | title_tokens = tokenize(article.get('title', '')) 238 | text_tokens = tokenize(article.get('text', '')) 239 | 240 | title_counter = Counter(title_tokens) 241 | text_counter = Counter(text_tokens) 242 | 243 | title_overlap = sum((prompt_counter & title_counter).values()) 244 | text_overlap = sum((prompt_counter & text_counter).values()) 245 | 246 | # Assign weights (title matches are more significant) 247 | score = title_overlap * 2 + text_overlap 248 | 249 | if verbose: 250 | print(f"Article Title: {article.get('title', '')}") 251 | print(f"Title Overlap Count: {title_overlap}, Text Overlap Count: {text_overlap}, Score: {score}") 252 | 253 | if score > best_score: 254 | best_score = score 255 | best_article = article 256 | 257 | return best_article 258 | 259 | def select_top_n_wikipedia_articles(prompt: str, articles: List[Dict[str, str]], num_top_articles: int) -> List[Dict[str, str]]: 260 | """ 261 | Select the top_n articles based on the prompt, accounting for token frequencies. 262 | 263 | Args: 264 | prompt (str): The original prompt. 265 | articles (list): List of dictionaries with 'title' and 'text'. 266 | num_top_articles (int): The number of top articles to return. 267 | 268 | Returns: 269 | List of dict: The articles dictionaries with the highest similarity score. 270 | """ 271 | 272 | def tokenize(text): 273 | return re.findall(r'\w+', text.lower()) 274 | 275 | prompt_tokens = tokenize(prompt) 276 | prompt_counter = Counter(prompt_tokens) 277 | best_score = -1 278 | best_article = None 279 | 280 | scored_articles = [] 281 | 282 | for article in articles: 283 | title_tokens = tokenize(article.get('title', '')) 284 | text_tokens = tokenize(article.get('text', '')) 285 | 286 | title_counter = Counter(title_tokens) 287 | text_counter = Counter(text_tokens) 288 | 289 | title_overlap = sum((prompt_counter & title_counter).values()) 290 | text_overlap = sum((prompt_counter & text_counter).values()) 291 | 292 | # Assign weights (title matches are more significant) 293 | score = title_overlap * 2 + text_overlap 294 | 295 | if verbose: 296 | print(f"Article Title: {article.get('title', '')}") 297 | print(f"Title Overlap Count: {title_overlap}, Text Overlap Count: {text_overlap}, Score: {score}") 298 | 299 | scored_articles.append((score, article)) 300 | 301 | #positive will be decending top articles, negative ascending 302 | if num_top_articles >= 0: 303 | # Sort articles by score in descending order and select the top_n articles 304 | scored_articles.sort(reverse=True, key=lambda x: x[0]) 305 | top_n_articles = [article for score, article in scored_articles[:num_top_articles]] 306 | else: 307 | # Sort articles by score in ascending order and select the top_n articles 308 | #useful to have top article last as LLM chat context length truncated from top 309 | scored_articles.sort(reverse=False, key=lambda x: x[0]) 310 | #since num_top_articles is already negative, this takes last n articles 311 | top_n_articles = [article for score, article in scored_articles[num_top_articles:]] 312 | 313 | return top_n_articles 314 | 315 | 316 | 317 | 318 | 319 | if __name__ == "__main__": 320 | colorama.init(autoreset=True) 321 | print("---------------------------------------------------------------") 322 | print("API started!") 323 | print(f"Host: {Fore.CYAN}{host}") 324 | print(f"Port: {Fore.CYAN}{port}") 325 | 326 | if log_level == "info": 327 | log_color = Fore.GREEN 328 | else: 329 | log_color = Fore.YELLOW 330 | 331 | print(f"Log level: {log_color}{log_level}") 332 | print(f"Please {Fore.RED}ctrl + c{Style.RESET_ALL} to end") 333 | 334 | uvicorn.run(app, host=host, port=port, log_level=log_level) 335 | --------------------------------------------------------------------------------