Anirudh Madhigiri Gopinath commited on
Commit
fa2034d
1 Parent(s): 4053944
.DS_Store ADDED
Binary file (6.15 kB). View file
 
README 2.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Document Insights - Extractive & Generative Methods
3
+ emoji: 👑
4
+ colorFrom: indigo
5
+ colorTo: indigo
6
+ sdk: streamlit
7
+ sdk_version: 1.23.0
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # Template Streamlit App for Haystack Search Pipelines
13
+
14
+ This template [Streamlit](https://docs.streamlit.io/) app set up for simple [Haystack search applications](https://docs.haystack.deepset.ai/docs/semantic_search). The template is ready to do QA with **Retrievel Augmented Generation**, or **Ectractive QA**
15
+
16
+ See the ['How to use this template'](#how-to-use-this-template) instructions below to create a simple UI for your own Haystack search pipelines.
17
+
18
+ Below you will also find instructions on how you could [push this to Hugging Face Spaces 🤗](#pushing-to-hugging-face-spaces-).
19
+
20
+ ## Installation and Running
21
+ To run the bare application which does _nothing_:
22
+ 1. Install requirements: `pip install -r requirements.txt`
23
+ 2. Run the streamlit app: `streamlit run app.py`
24
+
25
+ This will start up the app on `localhost:8501` where you will find a simple search bar. Before you start editing, you'll notice that the app will only show you instructions on what to edit.
26
+
27
+ ### Optional Configurations
28
+
29
+ You can set optional cofigurations to set the:
30
+ - `--task` you want to start the app with: `rag` or `extractive` (default: rag)
31
+ - `--store` you want to use: `inmemory`, `opensearch`, `weaviate` or `milvus` (default: inmemory)
32
+ - `--name` you want to have for the app. (default: 'My Search App')
33
+
34
+ E.g.:
35
+
36
+ ```bash
37
+ streamlit run app.py -- --store opensearch --task extractive --name 'My Opensearch Documentation Search'
38
+ ```
39
+
40
+ In a `.env` file, include all the config settings that you would like to use based on:
41
+ - The DocumentStore of your choice
42
+ - The Extractive/Generative model of your choice
43
+
44
+ While the `/utils/config.py` will create default values for some configurations, others have to be set in the `.env` such as the `OPENAI_KEY`
45
+
46
+ Example `.env`
47
+
48
+ ```
49
+ OPENAI_KEY=YOUR_KEY
50
+ EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L12-v2
51
+ GENERATIVE_MODEL=text-davinci-003
52
+ ```
53
+
54
+
55
+ ## How to use this template
56
+ 1. Create a new repository from this template or simply open it in a codespace to start playing around 💙
57
+ 2. Make sure your `requirements.txt` file includes the Haystack and Streamlit versions you would like to use.
58
+ 3. Change the code in `utils/haystack.py` if you would like a different pipeline.
59
+ 4. Create a `.env`file with all of your configuration settings.
60
+ 5. Make any UI edits you'd like to and [share with the Haystack community](https://haystack.deepeset.ai/community)
61
+ 6. Run the app as show in [installation and running](#installation-and-running)
62
+
63
+ ### Repo structure
64
+ - `./utils`: This is where we have 3 files:
65
+ - `config.py`: This file extracts all of the configuration settings from a `.env` file. For some config settings, it uses default values. An example of this is in [this demo project](https://github.com/TuanaCelik/should-i-follow/blob/main/utils/config.py).
66
+ - `haystack.py`: Here you will find some functions already set up for you to start creating your Haystack search pipeline. It includes 2 main functions called `start_haystack()` which is what we use to create a pipeline and cache it, and `query()` which is the function called by `app.py` once a user query is received.
67
+ - `ui.py`: Use this file for any UI and initial value setups.
68
+ - `app.py`: This is the main Streamlit application file that we will run. In its current state it has a simple search bar, a 'Run' button, and a response that you can highlight answers with.
69
+
70
+ ### What to edit?
71
+ There are default pipelines both in `start_haystack_extractive()` and `start_haystack_rag()`
72
+
73
+ - Change the pipelines to use the embedding models, extractive or generative models as you need.
74
+ - If using the `rag` task, change the `default_prompt_template` to use one of our available ones on [PromptHub](https://prompthub.deepset.ai) or create your own `PromptTemplate`
75
+
76
+
77
+ ## Pushing to Hugging Face Spaces 🤗
78
+
79
+ Below is an example GitHub action that will let you push your Streamlit app straight to the Hugging Face Hub as a Space.
80
+
81
+ A few things to pay attention to:
82
+
83
+ 1. Create a New Space on Hugging Face with the Streamlit SDK.
84
+ 2. Create a Hugging Face token on your HF account.
85
+ 3. Create a secret on your GitHub repo called `HF_TOKEN` and put your Hugging Face token here.
86
+ 4. If you're using DocumentStores or APIs that require some keys/tokens, make sure these are provided as a secret for your HF Space too!
87
+ 5. This readme is set up to tell HF spaces that it's using streamlit and that the app is running on `app.py`, make any changes to the frontmatter of this readme to display the title, emoji etc you desire.
88
+ 6. Create a file in `.github/workflows/hf_sync.yml`. Here's an example that you can change with your own information, and an [example workflow](https://github.com/TuanaCelik/should-i-follow/blob/main/.github/workflows/hf_sync.yml) working for the [Should I Follow demo](https://huggingface.co/spaces/deepset/should-i-follow)
89
+
90
+ ```yaml
91
+ name: Sync to Hugging Face hub
92
+ on:
93
+ push:
94
+ branches: [main]
95
+
96
+ # to run this workflow manually from the Actions tab
97
+ workflow_dispatch:
98
+
99
+ jobs:
100
+ sync-to-hub:
101
+ runs-on: ubuntu-latest
102
+ steps:
103
+ - uses: actions/checkout@v2
104
+ with:
105
+ fetch-depth: 0
106
+ lfs: true
107
+ - name: Push to hub
108
+ env:
109
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
110
+ run: git push --force https://{YOUR_HF_USERNAME}:$HF_TOKEN@{YOUR_HF_SPACE_REPO} main
111
+ ```
app.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utils.check_pydantic_version import use_pydantic_v1
2
+ use_pydantic_v1() #This function has to be run before importing haystack. as haystack requires pydantic v1 to run
3
+
4
+
5
+ from operator import index
6
+ import streamlit as st
7
+ import logging
8
+ import os
9
+
10
+ from annotated_text import annotation
11
+ from json import JSONDecodeError
12
+ from markdown import markdown
13
+ from utils.config import parser
14
+ from utils.haystack import start_document_store, query, initialize_pipeline, start_preprocessor_node, start_retriever, start_reader
15
+ from utils.ui import reset_results, set_initial_state
16
+ import pandas as pd
17
+ import haystack
18
+
19
+ from datetime import datetime
20
+ import streamlit.components.v1 as components
21
+ import streamlit_authenticator as stauth
22
+ import pickle
23
+
24
+ from streamlit_modal import Modal
25
+ import numpy as np
26
+
27
+
28
+
29
+ names = ['mlreply']
30
+ usernames = ['docwhiz']
31
+ with open('hashed_password.pkl','rb') as f:
32
+ hashed_passwords = pickle.load(f)
33
+
34
+
35
+
36
+ # Whether the file upload should be enabled or not
37
+ DISABLE_FILE_UPLOAD = bool(os.getenv("DISABLE_FILE_UPLOAD"))
38
+
39
+
40
+ def show_documents_list(retrieved_documents):
41
+ data = []
42
+ for i, document in enumerate(retrieved_documents):
43
+ data.append([document.meta['name']])
44
+ df = pd.DataFrame(data, columns=['Uploaded Document Name'])
45
+ df.drop_duplicates(subset=['Uploaded Document Name'], inplace=True)
46
+ df.index = np.arange(1, len(df) + 1)
47
+ return df
48
+
49
+ # Define a function to handle file uploads
50
+ def upload_files():
51
+ uploaded_files = upload_container.file_uploader(
52
+ "upload", type=["pdf", "txt", "docx"], accept_multiple_files=True, label_visibility="hidden", key=1
53
+ )
54
+ return uploaded_files
55
+
56
+
57
+ # Define a function to process a single file
58
+ def process_file(data_file, preprocesor, document_store):
59
+ # read file and add content
60
+ file_contents = data_file.read().decode("utf-8")
61
+ docs = [{
62
+ 'content': str(file_contents),
63
+ 'meta': {'name': str(data_file.name)}
64
+ }]
65
+ try:
66
+ names = [item.meta.get('name') for item in document_store.get_all_documents()]
67
+ #if args.store == 'inmemory':
68
+ # doc = converter.convert(file_path=files, meta=None)
69
+ if data_file.name in names:
70
+ print(f"{data_file.name} already processed")
71
+ else:
72
+ print(f'preprocessing uploaded doc {data_file.name}.......')
73
+ #print(data_file.read().decode("utf-8"))
74
+ preprocessed_docs = preprocesor.process(docs)
75
+ print('writing to document store.......')
76
+ document_store.write_documents(preprocessed_docs)
77
+ print('updating emebdding.......')
78
+ document_store.update_embeddings(retriever)
79
+ except Exception as e:
80
+ print(e)
81
+
82
+
83
+ # Define a function to upload the documents to haystack document store
84
+ def upload_document():
85
+ if data_files is not None:
86
+ for data_file in data_files:
87
+ # Upload file
88
+ if data_file:
89
+ try:
90
+ #raw_json = upload_doc(data_file)
91
+ # Call the process_file function for each uploaded file
92
+ if args.store == 'inmemory':
93
+ processed_data = process_file(data_file, preprocesor, document_store)
94
+ #upload_container.write(str(data_file.name) + "    ✅ ")
95
+ except Exception as e:
96
+ upload_container.write(str(data_file.name) + "    ❌ ")
97
+ upload_container.write("_This file could not be parsed, see the logs for more information._")
98
+
99
+ # Define a function to reset the documents in haystack document store
100
+ def reset_documents():
101
+ print('\nReseting documents list at ' + str(datetime.now()) + '\n')
102
+ st.session_state.data_files = None
103
+ document_store.delete_documents()
104
+
105
+ try:
106
+ args = parser.parse_args()
107
+ preprocesor = start_preprocessor_node()
108
+ document_store = start_document_store(type=args.store)
109
+ document_store.get_all_documents()
110
+ retriever = start_retriever(document_store)
111
+ reader = start_reader()
112
+ st.set_page_config(
113
+ page_title="MLReplySearch",
114
+ layout="centered",
115
+ page_icon=":shark:",
116
+ menu_items={
117
+ 'Get Help': 'https://www.extremelycoolapp.com/help',
118
+ 'Report a bug': "https://www.extremelycoolapp.com/bug",
119
+ 'About': "# This is a header. This is an *extremely* cool app!"
120
+ }
121
+ )
122
+ st.sidebar.image("ml_logo.png", use_column_width=True)
123
+
124
+ authenticator = stauth.Authenticate(names, usernames, hashed_passwords, "document_search", "random_text", cookie_expiry_days=1)
125
+
126
+ name, authentication_status, username = authenticator.login("Login", "main")
127
+
128
+ if authentication_status == False:
129
+ st.error("Username/Password is incorrect")
130
+
131
+ if authentication_status == None:
132
+ st.warning("Please enter your username and password")
133
+
134
+ if authentication_status:
135
+
136
+ # Sidebar for Task Selection
137
+ st.sidebar.header('Options:')
138
+
139
+ # OpenAI Key Input
140
+ openai_key = st.sidebar.text_input("Enter LLM-authorization Key:", type="password")
141
+
142
+ if openai_key:
143
+ task_options = ['Extractive', 'Generative']
144
+ else:
145
+ task_options = ['Extractive']
146
+
147
+ task_selection = st.sidebar.radio('Select the task:', task_options)
148
+
149
+ # Check the task and initialize pipeline accordingly
150
+ if task_selection == 'Extractive':
151
+ pipeline_extractive = initialize_pipeline("extractive", document_store, retriever, reader)
152
+ elif task_selection == 'Generative' and openai_key: # Check for openai_key to ensure user has entered it
153
+ pipeline_rag = initialize_pipeline("rag", document_store, retriever, reader, openai_key=openai_key)
154
+
155
+
156
+ set_initial_state()
157
+
158
+ modal = Modal("Manage Files", key="demo-modal")
159
+ open_modal = st.sidebar.button("Manage Files", use_container_width=True)
160
+ if open_modal:
161
+ modal.open()
162
+
163
+ st.write('# ' + args.name)
164
+ if modal.is_open():
165
+ with modal.container():
166
+ if not DISABLE_FILE_UPLOAD:
167
+ upload_container = st.container()
168
+ data_files = upload_files()
169
+ upload_document()
170
+ st.session_state.sidebar_state = 'collapsed'
171
+ st.table(show_documents_list(document_store.get_all_documents()))
172
+
173
+ # File upload block
174
+ # if not DISABLE_FILE_UPLOAD:
175
+ # upload_container = st.sidebar.container()
176
+ # upload_container.write("## File Upload:")
177
+ # data_files = upload_files()
178
+ # Button to update files in the documentStore
179
+ # upload_container.button('Upload Files', on_click=upload_document, args=())
180
+
181
+ # Button to reset the documents in DocumentStore
182
+ st.sidebar.button("Reset documents", on_click=reset_documents, args=(), use_container_width=True)
183
+
184
+ if "question" not in st.session_state:
185
+ st.session_state.question = ""
186
+ # Search bar
187
+ question = st.text_input("Question", value=st.session_state.question, max_chars=100, on_change=reset_results, label_visibility="hidden")
188
+
189
+ run_pressed = st.button("Run")
190
+
191
+ run_query = (
192
+ run_pressed or question != st.session_state.question #or task_selection != st.session_state.task
193
+ )
194
+
195
+ # Get results for query
196
+ if run_query and question:
197
+ if task_selection == 'Extractive':
198
+ reset_results()
199
+ st.session_state.question = question
200
+ with st.spinner("🔎    Running your pipeline"):
201
+ try:
202
+ st.session_state.results_extractive = query(pipeline_extractive, question)
203
+ st.session_state.task = task_selection
204
+ except JSONDecodeError as je:
205
+ st.error(
206
+ "👓    An error occurred reading the results. Is the document store working?"
207
+ )
208
+ except Exception as e:
209
+ logging.exception(e)
210
+ st.error("🐞    An error occurred during the request.")
211
+
212
+ elif task_selection == 'Generative':
213
+ reset_results()
214
+ st.session_state.question = question
215
+ with st.spinner("🔎    Running your pipeline"):
216
+ try:
217
+ st.session_state.results_generative = query(pipeline_rag, question)
218
+ st.session_state.task = task_selection
219
+ except JSONDecodeError as je:
220
+ st.error(
221
+ "👓    An error occurred reading the results. Is the document store working?"
222
+ )
223
+ except Exception as e:
224
+ if "API key is invalid" in str(e):
225
+ logging.exception(e)
226
+ st.error("🐞    incorrect API key provided. You can find your API key at https://platform.openai.com/account/api-keys.")
227
+ else:
228
+ logging.exception(e)
229
+ st.error("🐞    An error occurred during the request.")
230
+ # Display results
231
+ if (st.session_state.results_extractive or st.session_state.results_generative) and run_query:
232
+
233
+ # Handle Extractive Answers
234
+ if task_selection == 'Extractive':
235
+ results = st.session_state.results_extractive
236
+
237
+ st.subheader("Extracted Answers:")
238
+
239
+ if 'answers' in results:
240
+ answers = results['answers']
241
+ treshold = 0.2
242
+ higher_then_treshold = any(ans.score > treshold for ans in answers)
243
+ if not higher_then_treshold:
244
+ st.markdown(f"<span style='color:red'>Please note none of the answers achieved a score higher then {int(treshold) * 100}%. Which probably means that the desired answer is not in the searched documents.</span>", unsafe_allow_html=True)
245
+ for count, answer in enumerate(answers):
246
+ if answer.answer:
247
+ text, context = answer.answer, answer.context
248
+ start_idx = context.find(text)
249
+ end_idx = start_idx + len(text)
250
+ score = round(answer.score, 3)
251
+ st.markdown(f"**Answer {count + 1}:**")
252
+ st.markdown(
253
+ context[:start_idx] + str(annotation(body=text, label=f'SCORE {score}', background='#964448', color='#ffffff')) + context[end_idx:],
254
+ unsafe_allow_html=True,
255
+ )
256
+ else:
257
+ st.info(
258
+ "🤔 &nbsp;&nbsp; Haystack is unsure whether any of the documents contain an answer to your question. Try to reformulate it!"
259
+ )
260
+
261
+ # Handle Generative Answers
262
+ elif task_selection == 'Generative':
263
+ results = st.session_state.results_generative
264
+ st.subheader("Generated Answer:")
265
+ if 'results' in results:
266
+ st.markdown("**Answer:**")
267
+ st.write(results['results'][0])
268
+
269
+ # Handle Retrieved Documents
270
+ if 'documents' in results:
271
+ retrieved_documents = results['documents']
272
+ st.subheader("Retriever Results:")
273
+
274
+ data = []
275
+ for i, document in enumerate(retrieved_documents):
276
+ # Truncate the content
277
+ truncated_content = (document.content[:150] + '...') if len(document.content) > 150 else document.content
278
+ data.append([i + 1, document.meta['name'], truncated_content])
279
+
280
+ # Convert data to DataFrame and display using Streamlit
281
+ df = pd.DataFrame(data, columns=['Ranked Context', 'Document Name', 'Content'])
282
+ st.table(df)
283
+ except SystemExit as e:
284
+ os._exit(e.code)
generate_keys.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import pickle
4
+ from pathlib import Path
5
+
6
+ import streamlit_authenticator as stauth
7
+
8
+ names = ['mlreply']
9
+ usernames = ['docwhiz']
10
+ passwords = ['Docwhiz']
11
+
12
+ hashed_passwords = stauth.Hasher((passwords)).generate()
13
+
14
+ with open('hashed_password.pkl','wb') as f:
15
+ pickle.dump(hashed_passwords, f)
hashed_password.pkl ADDED
Binary file (78 Bytes). View file
 
ml_logo.png ADDED
requirements.txt ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.24.1
2
+ aiohttp==3.8.6
3
+ aiosignal==1.3.1
4
+ altair==5.1.2
5
+ annotated-types==0.6.0
6
+ appdirs==1.4.4
7
+ argon2-cffi==23.1.0
8
+ argon2-cffi-bindings==21.2.0
9
+ async-timeout==4.0.3
10
+ attrs==23.1.0
11
+ Authlib==1.2.1
12
+ backoff==2.2.1
13
+ blinker==1.7.0
14
+ boilerpy3==1.0.7
15
+ cachetools==5.3.2
16
+ canals==0.7.0
17
+ cattrs==23.1.2
18
+ certifi==2023.7.22
19
+ cffi==1.16.0
20
+ charset-normalizer==3.3.2
21
+ click==8.1.7
22
+ cryptography==41.0.5
23
+ datasets==2.15.0
24
+ dill==0.3.7
25
+ docopt==0.6.2
26
+ environs==9.5.0
27
+ Events==0.5
28
+ farm-haystack==1.20.0
29
+ filelock==3.13.1
30
+ frozenlist==1.4.0
31
+ fsspec==2023.10.0
32
+ gitdb==4.0.11
33
+ GitPython==3.1.40
34
+ grpcio==1.58.0
35
+ htbuilder==0.6.2
36
+ huggingface-hub==0.19.4
37
+ idna==3.4
38
+ importlib-metadata==6.8.0
39
+ inflect==7.0.0
40
+ Jinja2==3.1.2
41
+ joblib==1.3.2
42
+ jsonschema==4.20.0
43
+ jsonschema-specifications==2023.11.1
44
+ lazy-imports==0.3.1
45
+ Markdown==3.5.1
46
+ markdown-it-py==3.0.0
47
+ MarkupSafe==2.1.3
48
+ marshmallow==3.20.1
49
+ mdurl==0.1.2
50
+ milvus-haystack==0.0.2
51
+ minio==7.2.0
52
+ monotonic==1.6
53
+ more-itertools==10.1.0
54
+ mpmath==1.3.0
55
+ multidict==6.0.4
56
+ multiprocess==0.70.15
57
+ networkx==3.2.1
58
+ nltk==3.8.1
59
+ num2words==0.5.13
60
+ numpy==1.26.2
61
+ opensearch-py==2.4.1
62
+ packaging==23.2
63
+ pandas==2.1.3
64
+ Pillow==9.5.0
65
+ platformdirs==4.0.0
66
+ posthog==3.0.2
67
+ prompthub-py==4.0.0
68
+ protobuf==4.25.1
69
+ psutil==5.9.6
70
+ pyarrow==14.0.1
71
+ pyarrow-hotfix==0.5
72
+ pycparser==2.21
73
+ pycryptodome==3.19.0
74
+ pydantic==1.10.13
75
+ pydantic_core==2.14.3
76
+ pydeck==0.8.1b0
77
+ Pygments==2.16.1
78
+ pymilvus==2.3.3
79
+ Pympler==1.0.1
80
+ python-dateutil==2.8.2
81
+ python-dotenv==1.0.0
82
+ pytz==2023.3.post1
83
+ pytz-deprecation-shim==0.1.0.post0
84
+ PyYAML==6.0.1
85
+ quantulum3==0.9.0
86
+ rank-bm25==0.2.2
87
+ referencing==0.31.0
88
+ regex==2023.10.3
89
+ requests==2.31.0
90
+ requests-cache==0.9.8
91
+ rich==13.7.0
92
+ rpds-py==0.13.0
93
+ safetensors==0.3.3.post1
94
+ scikit-learn==1.3.2
95
+ scipy==1.11.3
96
+ sentence-transformers==2.2.2
97
+ sentencepiece==0.1.99
98
+ six==1.16.0
99
+ smmap==5.0.1
100
+ sseclient-py==1.8.0
101
+ st-annotated-text==4.0.1
102
+ streamlit==1.23.0
103
+ sympy==1.12
104
+ tenacity==8.2.3
105
+ threadpoolctl==3.2.0
106
+ tiktoken==0.5.1
107
+ tokenizers==0.13.3
108
+ toml==0.10.2
109
+ toolz==0.12.0
110
+ torch==2.1.1
111
+ torchvision==0.16.1
112
+ tornado==6.3.3
113
+ tqdm==4.66.1
114
+ transformers==4.32.1
115
+ typing_extensions==4.8.0
116
+ tzdata==2023.3
117
+ tzlocal==4.3.1
118
+ ujson==5.8.0
119
+ url-normalize==1.4.3
120
+ urllib3==2.1.0
121
+ validators==0.22.0
122
+ weaviate-client==3.25.3
123
+ xxhash==3.4.1
124
+ yarl==1.9.2
125
+ zipp==3.17.0
126
+ streamlit-authenticator==0.1.5
127
+ streamlit-modal==0.1.0
utils/.DS_Store ADDED
Binary file (6.15 kB). View file
 
utils/__pycache__/check_pydantic_version.cpython-310.pyc ADDED
Binary file (1.04 kB). View file
 
utils/__pycache__/check_pydantic_version.cpython-311.pyc ADDED
Binary file (2.04 kB). View file
 
utils/__pycache__/check_pydantic_version.cpython-39.pyc ADDED
Binary file (1.02 kB). View file
 
utils/__pycache__/config.cpython-310.pyc ADDED
Binary file (1.51 kB). View file
 
utils/__pycache__/config.cpython-311.pyc ADDED
Binary file (2.51 kB). View file
 
utils/__pycache__/config.cpython-39.pyc ADDED
Binary file (1.51 kB). View file
 
utils/__pycache__/haystack.cpython-310.pyc ADDED
Binary file (3.61 kB). View file
 
utils/__pycache__/haystack.cpython-311.pyc ADDED
Binary file (5.81 kB). View file
 
utils/__pycache__/haystack.cpython-39.pyc ADDED
Binary file (3.61 kB). View file
 
utils/__pycache__/ui.cpython-310.pyc ADDED
Binary file (739 Bytes). View file
 
utils/__pycache__/ui.cpython-311.pyc ADDED
Binary file (1.14 kB). View file
 
utils/check_pydantic_version.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pydantic
2
+ import os
3
+ import fileinput
4
+
5
+ def replace_string_in_files(folder_path, old_str, new_str):
6
+ for subdir, dirs, files in os.walk(folder_path):
7
+ for file in files:
8
+ file_path = os.path.join(subdir, file)
9
+
10
+ # Check if the file is a text file (you can modify this condition based on your needs)
11
+ if file.endswith(".txt") or file.endswith(".py"):
12
+ # Open the file in place for editing
13
+ with fileinput.FileInput(file_path, inplace=True) as f:
14
+ for line in f:
15
+ # Replace the old string with the new string
16
+ print(line.replace(old_str, new_str), end='')
17
+
18
+
19
+ def use_pydantic_v1():
20
+ module_file_path = pydantic.__file__
21
+ module_file_path = module_file_path.split('pydantic')[0] + 'haystack'
22
+ with open(module_file_path+'/schema.py','r') as f:
23
+ haystack_schema_file = f.read()
24
+
25
+ if 'from pydantic.v1' not in haystack_schema_file:
26
+ replace_string_in_files(module_file_path, 'from pydantic', 'from pydantic.v1')
utils/config.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import os
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+ parser = argparse.ArgumentParser(description='This app lists animals')
8
+
9
+ document_store_choices = ('inmemory', 'weaviate', 'milvus', 'opensearch')
10
+ parser.add_argument('--store', choices=document_store_choices, default='inmemory', help='DocumentStore selection (default: %(default)s)')
11
+ parser.add_argument('--name', default="Document Insights: Extractive & Generative Methods")
12
+
13
+ model_configs = {
14
+ 'EMBEDDING_MODEL': os.getenv("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L12-v2"),
15
+ 'GENERATIVE_MODEL': os.getenv("GENERATIVE_MODEL", "gpt-4"),
16
+ #'EXTRACTIVE_MODEL': os.getenv("EXTRACTIVE_MODEL", "deepset/roberta-base-squad2"),
17
+ 'EXTRACTIVE_MODEL': os.getenv("EXTRACTIVE_MODEL", "deepset/gelectra-large-germanquad"),
18
+ #'EXTRACTIVE_MODEL': os.getenv("EXTRACTIVE_MODEL", "MachineLearningReply/bert-base-german-legal-qa"),
19
+ 'OPENAI_KEY': os.getenv("OPENAI_KEY"),
20
+ 'COHERE_KEY': os.getenv("COHERE_KEY"),
21
+ }
22
+
23
+ document_store_configs = {
24
+ # Weaviate Config
25
+ 'WEAVIATE_HOST': os.getenv("WEAVIATE_HOST", "http://localhost"),
26
+ 'WEAVIATE_PORT': os.getenv("WEAVIATE_PORT", 8080),
27
+ 'WEAVIATE_INDEX': os.getenv("WEAVIATE_INDEX", "Document"),
28
+ 'WEAVIATE_EMBEDDING_DIM': os.getenv("WEAVIATE_EMBEDDING_DIM", 768),
29
+
30
+ # OpenSearch Config
31
+ 'OPENSEARCH_SCHEME': os.getenv("OPENSEARCH_SCHEME", "https"),
32
+ 'OPENSEARCH_USERNAME': os.getenv("OPENSEARCH_USERNAME", "admin"),
33
+ 'OPENSEARCH_PASSWORD': os.getenv("OPENSEARCH_PASSWORD", "admin"),
34
+ 'OPENSEARCH_HOST': os.getenv("OPENSEARCH_HOST", "localhost"),
35
+ 'OPENSEARCH_PORT': os.getenv("OPENSEARCH_PORT", 9200),
36
+ 'OPENSEARCH_INDEX': os.getenv("OPENSEARCH_INDEX", "document"),
37
+ 'OPENSEARCH_EMBEDDING_DIM': os.getenv("OPENSEARCH_EMBEDDING_DIM", 768),
38
+
39
+ # Milvus Config
40
+ 'MILVUS_URI': os.getenv("MILVUS_URI", "http://localhost:19530/default"),
41
+ 'MILVUS_INDEX': os.getenv("MILVUS_INDEX", "document"),
42
+ 'MILVUS_EMBEDDING_DIM': os.getenv("MILVUS_EMBEDDING_DIM", 768),
43
+ }
utils/haystack.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ from utils.config import document_store_configs, model_configs
4
+ from haystack import Pipeline
5
+ from haystack.schema import Answer
6
+ from haystack.document_stores import BaseDocumentStore
7
+ from haystack.document_stores import InMemoryDocumentStore, OpenSearchDocumentStore, WeaviateDocumentStore
8
+ from haystack.nodes import EmbeddingRetriever, FARMReader, PromptNode, PreProcessor
9
+ #from haystack.nodes import TextConverter, FileTypeClassifier, PDFToTextConverter
10
+ from milvus_haystack import MilvusDocumentStore
11
+ #Use this file to set up your Haystack pipeline and querying
12
+
13
+ @st.cache_resource(show_spinner=False)
14
+ def start_preprocessor_node():
15
+ print('initializing preprocessor node')
16
+ processor = PreProcessor(
17
+ clean_empty_lines= True,
18
+ clean_whitespace=True,
19
+ clean_header_footer=True,
20
+ #remove_substrings=None,
21
+ split_by="word",
22
+ split_length=100,
23
+ split_respect_sentence_boundary=True,
24
+ #split_overlap=0,
25
+ #max_chars_check= 10_000
26
+ )
27
+ return processor
28
+ #return docs
29
+
30
+ @st.cache_resource(show_spinner=False)
31
+ def start_document_store(type: str):
32
+ #This function starts the documents store of your choice based on your command line preference
33
+ print('initializing document store')
34
+ if type == 'inmemory':
35
+ document_store = InMemoryDocumentStore(use_bm25=True, embedding_dim=384)
36
+ '''
37
+ documents = [
38
+ {
39
+ 'content': "Pi is a super dog",
40
+ 'meta': {'name': "pi.txt"}
41
+ },
42
+ {
43
+ 'content': "The revenue of siemens is 5 milion Euro",
44
+ 'meta': {'name': "siemens.txt"}
45
+ },
46
+ ]
47
+ document_store.write_documents(documents)
48
+ '''
49
+ elif type == 'opensearch':
50
+ document_store = OpenSearchDocumentStore(scheme = document_store_configs['OPENSEARCH_SCHEME'],
51
+ username = document_store_configs['OPENSEARCH_USERNAME'],
52
+ password = document_store_configs['OPENSEARCH_PASSWORD'],
53
+ host = document_store_configs['OPENSEARCH_HOST'],
54
+ port = document_store_configs['OPENSEARCH_PORT'],
55
+ index = document_store_configs['OPENSEARCH_INDEX'],
56
+ embedding_dim = document_store_configs['OPENSEARCH_EMBEDDING_DIM'])
57
+ elif type == 'weaviate':
58
+ document_store = WeaviateDocumentStore(host = document_store_configs['WEAVIATE_HOST'],
59
+ port = document_store_configs['WEAVIATE_PORT'],
60
+ index = document_store_configs['WEAVIATE_INDEX'],
61
+ embedding_dim = document_store_configs['WEAVIATE_EMBEDDING_DIM'])
62
+ elif type == 'milvus':
63
+ document_store = MilvusDocumentStore(uri = document_store_configs['MILVUS_URI'],
64
+ index = document_store_configs['MILVUS_INDEX'],
65
+ embedding_dim = document_store_configs['MILVUS_EMBEDDING_DIM'],
66
+ return_embedding=True)
67
+ return document_store
68
+
69
+ # cached to make index and models load only at start
70
+ @st.cache_resource(show_spinner=False)
71
+ def start_retriever(_document_store: BaseDocumentStore):
72
+ print('initializing retriever')
73
+ retriever = EmbeddingRetriever(document_store=_document_store,
74
+ embedding_model=model_configs['EMBEDDING_MODEL'],
75
+ top_k=5)
76
+ #
77
+
78
+ #_document_store.update_embeddings(retriever)
79
+ return retriever
80
+
81
+
82
+ @st.cache_resource(show_spinner=False)
83
+ def start_reader():
84
+ print('initializing reader')
85
+ reader = FARMReader(model_name_or_path=model_configs['EXTRACTIVE_MODEL'])
86
+ return reader
87
+
88
+
89
+
90
+ # cached to make index and models load only at start
91
+ @st.cache_resource(show_spinner=False)
92
+ def start_haystack_extractive(_document_store: BaseDocumentStore, _retriever: EmbeddingRetriever, _reader: FARMReader):
93
+ print('initializing pipeline')
94
+ pipe = Pipeline()
95
+ pipe.add_node(component=_retriever, name="Retriever", inputs=["Query"])
96
+ pipe.add_node(component= _reader, name="Reader", inputs=["Retriever"])
97
+ return pipe
98
+
99
+ @st.cache_resource(show_spinner=False)
100
+ def start_haystack_rag(_document_store: BaseDocumentStore, _retriever: EmbeddingRetriever, openai_key):
101
+ prompt_node = PromptNode(default_prompt_template="deepset/question-answering",
102
+ model_name_or_path=model_configs['GENERATIVE_MODEL'],
103
+ api_key=openai_key,
104
+ max_length=500)
105
+ pipe = Pipeline()
106
+
107
+ pipe.add_node(component=_retriever, name="Retriever", inputs=["Query"])
108
+ pipe.add_node(component=prompt_node, name="PromptNode", inputs=["Retriever"])
109
+
110
+ return pipe
111
+
112
+ #@st.cache_data(show_spinner=True)
113
+ def query(_pipeline, question):
114
+ params = {}
115
+ results = _pipeline.run(question, params=params)
116
+ return results
117
+
118
+ def initialize_pipeline(task, document_store, retriever, reader, openai_key = ""):
119
+ if task == 'extractive':
120
+ return start_haystack_extractive(document_store, retriever, reader)
121
+ elif task == 'rag':
122
+ return start_haystack_rag(document_store, retriever, openai_key)
123
+
124
+
utils/ui.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ def set_state_if_absent(key, value):
4
+ if key not in st.session_state:
5
+ st.session_state[key] = value
6
+
7
+ def set_initial_state():
8
+ set_state_if_absent("question", "Ask something here?")
9
+ set_state_if_absent("results_extractive", None)
10
+ set_state_if_absent("results_generative", None)
11
+ set_state_if_absent("task", None)
12
+
13
+ def reset_results(*args):
14
+ st.session_state.results_extractive = None
15
+ st.session_state.results_generative = None
16
+ st.session_state.task = None