├── uploads └── .gitignore ├── images ├── webapp.png └── example-nt.png ├── app.py ├── LICENSE ├── example.nt ├── server.py ├── README.md └── .gitignore /uploads/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /images/webapp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mommi84/rdf-qa/HEAD/images/webapp.png -------------------------------------------------------------------------------- /images/example-nt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mommi84/rdf-qa/HEAD/images/example-nt.png -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import streamlit as st 4 | import requests 5 | import threading 6 | 7 | import server 8 | 9 | 10 | def start_server(): 11 | if not st.session_state['server_started']: 12 | # start API server 13 | threading.Thread(target=server.run_app).start() 14 | st.session_state['server_started'] = True 15 | 16 | 17 | def render_gui(): 18 | uploaded_file = st.file_uploader("Choose an RDF file.") 19 | 20 | if uploaded_file is not None: 21 | # st.write(document) 22 | st.write(uploaded_file) 23 | 24 | data = requests.post("http://localhost:5050/index", files={'file': uploaded_file}).json() 25 | st.write(data) 26 | 27 | query = st.text_input('Query', 'list all regions') 28 | answer = requests.get("http://localhost:5050/query", params={'id': data['id'], 'query': query}).json() 29 | st.write(answer) 30 | 31 | 32 | if __name__ == '__main__': 33 | st.session_state['server_started'] = False 34 | start_server() 35 | render_gui() 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Tommaso Soru 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 | -------------------------------------------------------------------------------- /example.nt: -------------------------------------------------------------------------------- 1 | . 2 | . 3 | . 4 | . 5 | . 6 | . 7 | . 8 | . 9 | . 10 | . 11 | "Milan"@en . 12 | "city"@en . 13 | "Lombardy"@en . 14 | "place"@en . 15 | "region"@en . 16 | "Beppe Sala"@en . 17 | "person"@en . 18 | "Piedmont"@en . 19 | "thing"@en . 20 | "living being"@en . 21 | "has region"@en . 22 | "has mayor"@en . 23 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from flask import Flask, request 4 | from werkzeug.utils import secure_filename 5 | 6 | from llama_index import GPTSimpleVectorIndex, download_loader 7 | import json 8 | 9 | import secrets 10 | 11 | 12 | app = Flask(__name__) 13 | 14 | 15 | @app.route('/index', methods = ['GET', 'POST']) 16 | def upload_and_index(): 17 | if request.method == "POST": 18 | f = request.files['file'] 19 | filename = f"./uploads/{secure_filename(f.filename)}" 20 | f.save(filename) 21 | 22 | RDFReader = download_loader('RDFReader') 23 | document = RDFReader().load_data(file=filename) 24 | 25 | # avoid collisions of filenames 26 | data_id = secrets.token_hex(15) 27 | 28 | index = GPTSimpleVectorIndex(document) 29 | index.save_to_disk(f"{data_id}.json") 30 | 31 | return {'id': data_id} 32 | 33 | 34 | @app.route('/query') 35 | def query(): 36 | args = request.args 37 | data_id = args.get('id') 38 | query_str = args.get('query') 39 | q_index = GPTSimpleVectorIndex.load_from_disk(f"{data_id}.json") 40 | 41 | result = q_index.query(f"{query_str} - return the answer and explanation in a JSON object") 42 | try: 43 | json_start = result.response.index('{') 44 | answer = json.loads(result.response[json_start:]) 45 | answer.update({'success': True}) 46 | except (ValueError, json.JSONDecodeError): 47 | answer = {'success': False, 'answer': result.response, 'explanation': ''} 48 | 49 | return json.dumps(answer) 50 | 51 | 52 | @app.route('/') 53 | def hello(): 54 | return 'Hello, World!' 55 | 56 | 57 | def run_app(): 58 | app.run(host='0.0.0.0', port=5050) 59 | 60 | 61 | if __name__ == '__main__': 62 | run_app() 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rdf-qa 2 | 3 | _Explainable complex question answering over RDF files via Llama Index._ 4 | 5 | ## Usage 6 | 7 | Install dependencies: 8 | 9 | ```bash 10 | pip3 install --upgrade llama_index openai 11 | ``` 12 | 13 | Store OpenAI API key: 14 | 15 | ```bash 16 | export OPENAI_API_KEY= 17 | ``` 18 | 19 | Example usage: 20 | 21 | ```python 22 | from llama_index import GPTSimpleVectorIndex, download_loader 23 | 24 | RDFReader = download_loader("RDFReader") 25 | document = RDFReader().load_data(file="./example.nt") 26 | index = GPTSimpleVectorIndex(document) 27 | 28 | result = index.query( 29 | "list all places in a quoted Python array, then explain why") 30 | print(result.response) 31 | # >>> ['Lombardy', 'Milan', 'Piedmont'] 32 | # >>> 33 | # >>> The answer is ['Lombardy', 'Milan', 'Piedmont'] because all three 34 | # >>> of these are listed as types of places in the context information. 35 | # >>> Lombardy and Piedmont are both listed as types of regions, and 36 | # >>> Milan is listed as a type of city. All three of these are 37 | # >>> subclasses of the type 'place', which is a subclass of 'thing'. 38 | ``` 39 | 40 | ![Visualisation of the example RDF graph.](https://github.com/mommi84/rdf-qa/raw/main/images/example-nt.png "Visualisation of the example RDF graph.") 41 | 42 | ## API 43 | 44 | ```bash 45 | pip3 install flask 46 | ``` 47 | 48 | ```bash 49 | python3 server.py 50 | ``` 51 | 52 | The endpoint will be available at `localhost:5050` by default. 53 | 54 | ### Indexing 55 | 56 | Endpoint: `/index` (POST) 57 | 58 | Form data: 59 | * `file`: the RDF file to index 60 | 61 | This will return the internal ID of the index, to be used for querying. 62 | 63 | ### Query 64 | 65 | Endpoint: `/query` (GET) 66 | 67 | Parameters: 68 | * `id`: internal ID of the index 69 | * `query`: url-encoded query 70 | 71 | E.g., http://localhost:5050/query?id=5aa30cf341cc0fd1494da302649b04&query=list%20all%20regions 72 | 73 | ## Webapp 74 | 75 | ```bash 76 | pip3 install flask streamlit 77 | ``` 78 | 79 | Refresh terminal session or open new terminal. 80 | 81 | ```bash 82 | streamlit run app.py 83 | ``` 84 | 85 | ![Screenshot of the webapp.](https://github.com/mommi84/rdf-qa/raw/main/images/webapp.png "Screenshot of the webapp.") 86 | 87 | -------------------------------------------------------------------------------- /.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 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 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 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | --------------------------------------------------------------------------------