hkoppen commited on
Commit
7ca3dfa
1 Parent(s): bebe5de

Upload 23 files

Browse files
.DS_Store ADDED
Binary file (10.2 kB). View file
 
.github/workflows/main.yml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+ on:
3
+ push:
4
+ branches: [puma_demo]
5
+ # to run this workflow manually from the Actions tab
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ sync-to-hub:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v3
13
+ with:
14
+ fetch-depth: 0
15
+ lfs: true
16
+ - name: Push to hub
17
+ env:
18
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
19
+ run: git push https://hkoppen:$HF_TOKEN@huggingface.co/spaces/MachineLearningReply/q-and-a-tool-custom-logo puma_demo
.gitignore ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
+
3
+ # dependencies
4
+ node_modules
5
+ .pnp
6
+ .pnp.js
7
+
8
+ # testing
9
+ coverage
10
+
11
+ # next.js
12
+ .next/
13
+ out/
14
+ build
15
+
16
+ # misc
17
+ .DS_Store
18
+ *.pem
19
+
20
+ # debug
21
+ npm-debug.log*
22
+ yarn-debug.log*
23
+ yarn-error.log*
24
+ .pnpm-debug.log*
25
+
26
+ # local env files
27
+ .env.local
28
+ .env.development.local
29
+ .env.test.local
30
+ .env.production.local
31
+
32
+ # turbo
33
+ .turbo
34
+
35
+ .contentlayer
36
+ .env
37
+ .vercel
38
+ .vscode
39
+
40
+ # JetBrains
41
+ .idea
42
+
43
+ # VSCode
44
+ __pycache__/*
45
+
46
+ # datasets directory is used for local development
47
+ /datasets/
.streamlit/config.toml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [theme]
2
+ primaryColor = "#E694FF"
3
+ backgroundColor = "#FFFFFF"
4
+ secondaryBackgroundColor = "#F0F0F0"
5
+ textColor = "#262730"
6
+ font = "sans serif"
.vscode/settings.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "python.languageServer": "Pylance",
3
+ "python.analysis.typeCheckingMode": "basic",
4
+ "typescript.tsserver.maxTsServerMemory": 3072,
5
+ "typescript.tsserver.watchOptions": {
6
+ "watchFile": "dynamicPriorityPolling"
7
+ },
8
+ "javascript.suggest.includeAutomaticOptionalChainCompletions": false,
9
+ "debug.saveBeforeStart": "none",
10
+ "c3.welcome.showFeatureHighlight": false
11
+ }
Dockerfile ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apt-get update && apt-get install -y \
6
+ build-essential \
7
+ curl \
8
+ software-properties-common \
9
+ git \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ COPY requirements.txt .
13
+
14
+ RUN pip3 install -r requirements.txt
15
+
16
+ COPY . .
17
+
18
+ # extract version
19
+ COPY .git ./.git
20
+ RUN git rev-parse --short HEAD > revision.txt
21
+ RUN rm -rf ./.git
22
+
23
+ EXPOSE 8501
24
+
25
+ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
26
+
27
+ ENV PYTHONPATH "${PYTHONPATH}:."
28
+
29
+ ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
README.md CHANGED
@@ -1,12 +1,108 @@
1
- ---
2
- title: Q And A Tool Custom Logo
3
- emoji: 🏃
4
- colorFrom: green
5
- colorTo: gray
6
- sdk: streamlit
7
- sdk_version: 1.36.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: NLP Q&A Tool
3
+ emoji: 👑
4
+ colorFrom: indigo
5
+ colorTo: indigo
6
+ sdk: streamlit
7
+ sdk_version: 1.32.2
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # Document Insights - Extractive & Generative Methods using Haystack
13
+
14
+ This template [Streamlit](https://docs.streamlit.io/) app set up for
15
+ simple [Haystack search applications](https://docs.haystack.deepset.ai/docs/semantic_search). The template is ready to
16
+ do QA with **Retrievel Augmented Generation**, or **Ectractive QA**
17
+
18
+ Below you will also find instructions on how you
19
+ could [push this to Hugging Face Spaces 🤗](#pushing-to-hugging-face-spaces-).
20
+
21
+ ## Installation and Running
22
+
23
+ ### Local development
24
+
25
+ To run the bare application which does _nothing_:
26
+
27
+ 1. Install requirements: `pip install -r requirements.txt`
28
+ 2. Run the streamlit app: `streamlit run app.py`
29
+
30
+ This will start up the app on `localhost:8501` where you will find a simple search bar. Before you start editing, you'll
31
+ notice that the app will only show you instructions on what to edit.
32
+
33
+ ### Docker
34
+
35
+ To run the app in a Docker container:
36
+
37
+ 1. Build the Docker image: `docker build -t haystack-streamlit .`
38
+ 2. Run the Docker container: `docker run -p 8501:8501 haystack-streamlit` (make sure to bind any other ports you need)
39
+ 3. Open your browser and go to `http://localhost:8501`
40
+
41
+ ### Repo structure
42
+
43
+ - `./utils`: This is where we have 3 files:
44
+ - `config.py`: This file extracts all of the configuration settings from a `.env` file. For some config settings, it
45
+ uses default values. An example of this is
46
+ in [this demo project](https://github.com/TuanaCelik/should-i-follow/blob/main/utils/config.py).
47
+ - `haystack.py`: Here you will find some functions already set up for you to start creating your Haystack search
48
+ pipeline. It includes 2 main functions called `start_haystack()` which is what we use to create a pipeline and
49
+ cache it, and `query()` which is the function called by `app.py` once a user query is received.
50
+ - `ui.py`: Use this file for any UI and initial value setups.
51
+ - `app.py`: This is the main Streamlit application file that we will run. In its current state it has a simple search
52
+ bar, a 'Run' button, and a response that you can highlight answers with.
53
+ - `requirements.txt`: This file includes the required libraries to run the Streamlit app.
54
+ - `document_qa_engine.py`: This file includes the QA pipeline with Haystack.
55
+
56
+ ### What to edit?
57
+
58
+ There are default pipelines both in `start_haystack_extractive()` and `start_haystack_rag()`
59
+
60
+ - Change the pipelines to use the embedding models, extractive or generative models as you need.
61
+ - If using the `rag` task, change the `default_prompt_template` to use one of our available ones
62
+ on [PromptHub](https://prompthub.deepset.ai) or create your own `PromptTemplate`
63
+
64
+ ### Using local LLM models
65
+
66
+ To use the `local LLM` mode you can use [LM Studio](https://lmstudio.ai/) or [Ollama](https://ollama.com/).
67
+ For more info on how to run the app with a local LLM model please refer to the documentation of the tool you are using.
68
+ The `local_llm` mode expects an API available at `http://localhost:1234/v1`.
69
+
70
+ ## Pushing to Hugging Face Spaces 🤗
71
+
72
+ Below is an example GitHub action that will let you push your Streamlit app straight to the Hugging Face Hub as a Space.
73
+
74
+ A few things to pay attention to:
75
+
76
+ 1. Create a New Space on Hugging Face with the Streamlit SDK.
77
+ 2. Create a Hugging Face token on your HF account.
78
+ 3. Create a secret on your GitHub repo called `HF_TOKEN` and put your Hugging Face token here.
79
+ 4. If you're using DocumentStores or APIs that require some keys/tokens, make sure these are provided as a secret for
80
+ your HF Space too!
81
+ 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
82
+ changes to the frontmatter of this readme to display the title, emoji etc you desire.
83
+ 6. Create a file in `.github/workflows/hf_sync.yml`. Here's an example that you can change with your own information,
84
+ and an [example workflow](https://github.com/TuanaCelik/should-i-follow/blob/main/.github/workflows/hf_sync.yml)
85
+ working for the [Should I Follow demo](https://huggingface.co/spaces/deepset/should-i-follow)
86
+
87
+ ```yaml
88
+ name: Sync to Hugging Face hub
89
+ on:
90
+ push:
91
+ branches: [ main ]
92
+
93
+ # to run this workflow manually from the Actions tab
94
+ workflow_dispatch:
95
+
96
+ jobs:
97
+ sync-to-hub:
98
+ runs-on: ubuntu-latest
99
+ steps:
100
+ - uses: actions/checkout@v2
101
+ with:
102
+ fetch-depth: 0
103
+ lfs: true
104
+ - name: Push to hub
105
+ env:
106
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
107
+ run: git push --force https://{YOUR_HF_USERNAME}:$HF_TOKEN@{YOUR_HF_SPACE_REPO} main
108
+ ```
__pycache__/document_qa_engine.cpython-310.pyc ADDED
Binary file (5.11 kB). View file
 
__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.61 kB). View file
 
app.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import pandas as pd
3
+ import streamlit as st
4
+ import streamlit_authenticator as stauth
5
+ from streamlit_modal import Modal
6
+
7
+ from utils import new_file, clear_memory, append_documentation_to_sidebar, load_authenticator_config, init_qa, \
8
+ append_header
9
+ from haystack.document_stores.in_memory import InMemoryDocumentStore
10
+ from haystack import Document
11
+
12
+ load_dotenv()
13
+
14
+ OPENAI_MODELS = ['gpt-3.5-turbo',
15
+ "gpt-4",
16
+ "gpt-4-1106-preview"]
17
+
18
+ OPEN_MODELS = [
19
+ 'mistralai/Mistral-7B-Instruct-v0.1',
20
+ 'HuggingFaceH4/zephyr-7b-beta'
21
+ ]
22
+
23
+
24
+ def reset_chat_memory():
25
+ st.button(
26
+ 'Reset chat memory',
27
+ key="reset-memory-button",
28
+ on_click=clear_memory,
29
+ help="Clear the conversational memory. Currently implemented to retain the 4 most recent messages.",
30
+ disabled=False)
31
+
32
+
33
+ def manage_files(modal, document_store):
34
+ open_modal = st.sidebar.button("Manage Files", use_container_width=True)
35
+ if open_modal:
36
+ modal.open()
37
+
38
+ if modal.is_open():
39
+ with modal.container():
40
+ uploaded_file = st.file_uploader(
41
+ "Upload a CV in PDF format",
42
+ type=("pdf",),
43
+ on_change=new_file(),
44
+ disabled=st.session_state['document_qa_model'] is None,
45
+ label_visibility="collapsed",
46
+ help="The document is used to answer your questions. The system will process the document and store it in a RAG to answer your questions.",
47
+ )
48
+ edited_df = st.data_editor(use_container_width=True, data=st.session_state['files'],
49
+ num_rows='dynamic',
50
+ column_order=['name', 'size', 'is_active'],
51
+ column_config={'name': {'editable': False}, 'size': {'editable': False},
52
+ 'is_active': {'editable': True, 'type': 'checkbox',
53
+ 'width': 100}}
54
+ )
55
+ st.session_state['files'] = pd.DataFrame(columns=['name', 'content', 'size', 'is_active'])
56
+
57
+ if uploaded_file:
58
+ st.session_state['file_uploaded'] = True
59
+ st.session_state['files'] = pd.concat([st.session_state['files'], edited_df])
60
+ with st.spinner('Processing the CV content...'):
61
+ store_file_in_table(document_store, uploaded_file)
62
+ ingest_document(uploaded_file)
63
+
64
+
65
+ def ingest_document(uploaded_file):
66
+ if not st.session_state['document_qa_model']:
67
+ st.warning('Please select a model to start asking questions')
68
+ else:
69
+ try:
70
+ st.session_state['document_qa_model'].ingest_pdf(uploaded_file)
71
+ st.success('Document processed successfully')
72
+ except Exception as e:
73
+ st.error(f"Error processing the document: {e}")
74
+ st.session_state['file_uploaded'] = False
75
+
76
+
77
+ def store_file_in_table(document_store, uploaded_file):
78
+ pdf_content = uploaded_file.getvalue()
79
+ st.session_state['pdf_content'] = pdf_content
80
+ st.session_state.messages = []
81
+ document = Document(content=pdf_content, meta={"name": uploaded_file.name})
82
+ df = pd.DataFrame(st.session_state['files'])
83
+ df['is_active'] = False
84
+ st.session_state['files'] = pd.concat([df, pd.DataFrame(
85
+ [{"name": uploaded_file.name, "content": pdf_content, "size": len(pdf_content),
86
+ "is_active": True}])])
87
+ document_store.write_documents([document])
88
+
89
+
90
+ def init_session_state():
91
+ st.session_state.setdefault('files', pd.DataFrame(columns=['name', 'content', 'size', 'is_active']))
92
+ st.session_state.setdefault('models', [])
93
+ st.session_state.setdefault('api_keys', {})
94
+ st.session_state.setdefault('current_selected_model', 'gpt-3.5-turbo')
95
+ st.session_state.setdefault('current_api_key', '')
96
+ st.session_state.setdefault('messages', [])
97
+ st.session_state.setdefault('pdf_content', None)
98
+ st.session_state.setdefault('memory', None)
99
+ st.session_state.setdefault('pdf', None)
100
+ st.session_state.setdefault('document_qa_model', None)
101
+ st.session_state.setdefault('file_uploaded', False)
102
+
103
+
104
+ def set_page_config():
105
+ st.set_page_config(
106
+ page_title="CV Insights AI Assistant",
107
+ page_icon=":shark:",
108
+ initial_sidebar_state="expanded",
109
+ layout="wide",
110
+ menu_items={
111
+ 'Get Help': 'https://www.extremelycoolapp.com/help',
112
+ 'Report a bug': "https://www.extremelycoolapp.com/bug",
113
+ 'About': "# This is a header. This is an *extremely* cool app!"
114
+ }
115
+ )
116
+
117
+
118
+ def update_running_model(api_key, model):
119
+ st.session_state['api_keys'][model] = api_key
120
+ st.session_state['document_qa_model'] = init_qa(model, api_key)
121
+
122
+
123
+ def init_api_key_dict():
124
+ st.session_state['models'] = OPENAI_MODELS + list(OPEN_MODELS) + ['local LLM']
125
+ for model_name in OPENAI_MODELS:
126
+ st.session_state['api_keys'][model_name] = None
127
+
128
+
129
+ def display_chat_messages(chat_box, chat_input):
130
+ with chat_box:
131
+ if chat_input:
132
+ for message in st.session_state.messages:
133
+ with st.chat_message(message["role"]):
134
+ st.markdown(message["content"], unsafe_allow_html=True)
135
+
136
+ st.chat_message("user").markdown(chat_input)
137
+ with st.chat_message("assistant"):
138
+ # process user input and generate response
139
+ response = st.session_state['document_qa_model'].inference(chat_input, st.session_state.messages)
140
+
141
+ st.markdown(response)
142
+ st.session_state.messages.append({"role": "user", "content": chat_input})
143
+ st.session_state.messages.append({"role": "assistant", "content": response})
144
+
145
+
146
+ def setup_model_selection():
147
+ model = st.selectbox(
148
+ "Model:",
149
+ options=st.session_state['models'],
150
+ index=0, # default to the first model in the list gpt-3.5-turbo
151
+ placeholder="Select model",
152
+ help="Select an LLM:"
153
+ )
154
+
155
+ if model:
156
+ if model != st.session_state['current_selected_model']:
157
+ st.session_state['current_selected_model'] = model
158
+ if model == 'local LLM':
159
+ st.session_state['document_qa_model'] = init_qa(model)
160
+
161
+ api_key = st.sidebar.text_input("Enter LLM-authorization Key:", type="password",
162
+ disabled=st.session_state['current_selected_model'] == 'local LLM')
163
+ if api_key and api_key != st.session_state['current_api_key']:
164
+ update_running_model(api_key, model)
165
+ st.session_state['current_api_key'] = api_key
166
+
167
+ return model
168
+
169
+
170
+ def setup_task_selection(model):
171
+ # enable extractive and generative tasks if we're using a local LLM or an OpenAI model with an API key
172
+ if model == 'local LLM' or st.session_state['api_keys'].get(model):
173
+ task_options = ['Extractive', 'Generative']
174
+ else:
175
+ task_options = ['Extractive']
176
+
177
+ task_selection = st.sidebar.radio('Select the task:', task_options)
178
+
179
+ # TODO: Add the task selection logic here (initializing the model based on the task)
180
+
181
+
182
+ def setup_page_body():
183
+ chat_box = st.container(height=350, border=False)
184
+ chat_input = st.chat_input(
185
+ placeholder="Upload a document to start asking questions...",
186
+ disabled=not st.session_state['file_uploaded'],
187
+ )
188
+ if st.session_state['file_uploaded']:
189
+ display_chat_messages(chat_box, chat_input)
190
+
191
+
192
+ class StreamlitApp:
193
+ def __init__(self):
194
+ self.authenticator_config = load_authenticator_config()
195
+ self.document_store = InMemoryDocumentStore()
196
+ set_page_config()
197
+ self.authenticator = self.init_authenticator()
198
+ init_session_state()
199
+ init_api_key_dict()
200
+
201
+ def init_authenticator(self):
202
+ return stauth.Authenticate(
203
+ self.authenticator_config['credentials'],
204
+ self.authenticator_config['cookie']['name'],
205
+ self.authenticator_config['cookie']['key'],
206
+ self.authenticator_config['cookie']['expiry_days']
207
+ )
208
+
209
+ def setup_sidebar(self):
210
+ with st.sidebar:
211
+ st.sidebar.image("resources/puma.png", use_column_width=True)
212
+
213
+ # Sidebar for Task Selection
214
+ st.sidebar.header('Options:')
215
+ model = setup_model_selection()
216
+ setup_task_selection(model)
217
+ st.divider()
218
+ self.authenticator.logout()
219
+ reset_chat_memory()
220
+ modal = Modal("Manage Files", key="demo-modal")
221
+ manage_files(modal, self.document_store)
222
+ st.divider()
223
+ append_documentation_to_sidebar()
224
+
225
+ def run(self):
226
+ name, authentication_status, username = self.authenticator.login()
227
+ if authentication_status:
228
+ self.run_authenticated_app()
229
+ elif st.session_state["authentication_status"] is False:
230
+ st.error('Username/password is incorrect')
231
+ elif st.session_state["authentication_status"] is None:
232
+ st.warning('Please enter your username and password')
233
+
234
+ def run_authenticated_app(self):
235
+ self.setup_sidebar()
236
+ append_header()
237
+ setup_page_body()
238
+
239
+
240
+ app = StreamlitApp()
241
+ app.run()
authenticator_config.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ credentials:
2
+ usernames:
3
+ mlreply:
4
+ email: mlreply@reply.de
5
+ failed_login_attempts: 0 # Will be managed automatically
6
+ logged_in: False # Will be managed automatically
7
+ name: ML Reply
8
+ password: mlreply # Will be hashed automatically
9
+ cookie:
10
+ expiry_days: 1
11
+ key: some_signature_key # Must be string
12
+ name: some_cookie_name
13
+ #pre-authorized:
14
+ # emails:
15
+ # - melsby@gmail.com
document_qa_engine.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ from haystack.dataclasses import ChatMessage
4
+ from pypdf import PdfReader
5
+ from haystack.utils import Secret
6
+ from haystack import Pipeline, Document, component
7
+
8
+ from haystack.components.preprocessors import DocumentCleaner, DocumentSplitter
9
+ from haystack.components.writers import DocumentWriter
10
+ from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder
11
+ from haystack.document_stores.in_memory import InMemoryDocumentStore
12
+ from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
13
+ from haystack.components.builders import DynamicChatPromptBuilder
14
+ from haystack.components.generators.chat import OpenAIChatGenerator, HuggingFaceTGIChatGenerator
15
+ from haystack.document_stores.types import DuplicatePolicy
16
+
17
+ SENTENCE_RETREIVER_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
18
+
19
+ MAX_TOKENS = 500
20
+
21
+ template = """
22
+ As a professional HR recruiter given the following information, answer the question shortly and concisely in 1 or 2 sentences.
23
+
24
+ Context:
25
+ {% for document in documents %}
26
+ {{ document.content }}
27
+ {% endfor %}
28
+
29
+ Question: {{question}}
30
+ Answer:
31
+ """
32
+
33
+
34
+ @component
35
+ class UploadedFileConverter:
36
+ """
37
+ A component to convert uploaded PDF files to Documents
38
+ """
39
+
40
+ @component.output_types(documents=List[Document])
41
+ def run(self, uploaded_file):
42
+ pdf = PdfReader(uploaded_file)
43
+ documents = []
44
+ # uploaded file name without .pdf at the end and with _ and page number at the end
45
+ name = uploaded_file.name.rstrip('.PDF') + '_'
46
+ for page in pdf.pages:
47
+ documents.append(
48
+ Document(
49
+ content=page.extract_text(),
50
+ meta={'name': name + f"_{page.page_number}"}))
51
+ return {"documents": documents}
52
+
53
+
54
+ def create_ingestion_pipeline(document_store):
55
+ doc_embedder = SentenceTransformersDocumentEmbedder(model=SENTENCE_RETREIVER_MODEL)
56
+ doc_embedder.warm_up()
57
+
58
+ pipeline = Pipeline()
59
+ pipeline.add_component("converter", UploadedFileConverter())
60
+ pipeline.add_component("cleaner", DocumentCleaner())
61
+ pipeline.add_component("splitter",
62
+ DocumentSplitter(split_by="passage", split_length=100, split_overlap=10))
63
+ pipeline.add_component("embedder", doc_embedder)
64
+ pipeline.add_component("writer",
65
+ DocumentWriter(document_store=document_store, policy=DuplicatePolicy.OVERWRITE))
66
+
67
+ pipeline.connect("converter", "cleaner")
68
+ pipeline.connect("cleaner", "splitter")
69
+ pipeline.connect("splitter", "embedder")
70
+ pipeline.connect("embedder", "writer")
71
+ return pipeline
72
+
73
+
74
+ def create_inference_pipeline(document_store, model_name, api_key):
75
+ if model_name == "local LLM":
76
+ generator = OpenAIChatGenerator(api_key=Secret.from_token("<local LLM doesn't need an API key>"),
77
+ model=model_name,
78
+ api_base_url="http://localhost:1234/v1",
79
+ generation_kwargs={"max_tokens": MAX_TOKENS}
80
+ )
81
+ elif "gpt" in model_name:
82
+ generator = OpenAIChatGenerator(api_key=Secret.from_token(api_key), model=model_name,
83
+ generation_kwargs={"max_tokens": MAX_TOKENS, "stream": False}
84
+ )
85
+ else:
86
+ generator = HuggingFaceTGIChatGenerator(token=Secret.from_token(api_key), model=model_name,
87
+ generation_kwargs={"max_new_tokens": MAX_TOKENS}
88
+ )
89
+ pipeline = Pipeline()
90
+ pipeline.add_component("text_embedder",
91
+ SentenceTransformersTextEmbedder(model=SENTENCE_RETREIVER_MODEL))
92
+ pipeline.add_component("retriever", InMemoryEmbeddingRetriever(document_store, top_k=3))
93
+ pipeline.add_component("prompt_builder",
94
+ DynamicChatPromptBuilder(runtime_variables=["query", "documents"]))
95
+ pipeline.add_component("llm", generator)
96
+ pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
97
+ pipeline.connect("retriever.documents", "prompt_builder.documents")
98
+ pipeline.connect("prompt_builder.prompt", "llm.messages")
99
+
100
+ return pipeline
101
+
102
+
103
+ class DocumentQAEngine:
104
+ def __init__(self,
105
+ model_name,
106
+ api_key=None
107
+ ):
108
+ self.api_key = api_key
109
+ self.model_name = model_name
110
+ document_store = InMemoryDocumentStore()
111
+ self.chunks = []
112
+ self.inference_pipeline = create_inference_pipeline(document_store, model_name, api_key)
113
+ self.pdf_ingestion_pipeline = create_ingestion_pipeline(document_store)
114
+
115
+ def ingest_pdf(self, uploaded_file):
116
+ self.pdf_ingestion_pipeline.run({"converter": {"uploaded_file": uploaded_file}})
117
+
118
+ def inference(self, query, input_messages: List[dict]):
119
+ system_message = ChatMessage.from_system(
120
+ "You are a professional HR recruiter that answers questions based on the content of the uploaded CV. in 1 or 2 sentences.")
121
+ messages = [system_message]
122
+ for message in input_messages:
123
+ if message["role"] == "user":
124
+ messages.append(ChatMessage.from_system(message["content"]))
125
+ else:
126
+ messages.append(
127
+ ChatMessage.from_user(message["content"]))
128
+ messages.append(ChatMessage.from_user("""
129
+ Relevant information from the uploaded CV:
130
+ {% for doc in documents %}
131
+ {{ doc.content }}
132
+ {% endfor %}
133
+
134
+ \nQuestion: {{query}}
135
+ \nAnswer:
136
+ """))
137
+ res = self.inference_pipeline.run(data={"text_embedder": {"text": query},
138
+ "prompt_builder": {"prompt_source": messages,
139
+ "query": query
140
+ }})
141
+ return res["llm"]["replies"][0].content
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Streamlit
2
+ streamlit~=1.32.2
3
+ streamlit-modal==0.1.2
4
+ streamlit-authenticator==0.3.2
5
+ streamlit-pdf-viewer==0.0.9
6
+
7
+ # LLM
8
+ haystack-ai~=2.0.0
9
+ sentence_transformers~=2.6.0
10
+
11
+ # Utils
12
+ pandas~=2.2.1
13
+ pypdf~=4.2.0
14
+ pytest~=8.1.1
15
+ python-dotenv~=1.0.1
16
+
17
+ # Dev Utils
18
+ watchdog
resources/ml_logo.png ADDED
resources/puma.png ADDED
utils.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from document_qa_engine import DocumentQAEngine
2
+
3
+ import streamlit as st
4
+
5
+ import logging
6
+ from yaml import load, SafeLoader, YAMLError
7
+
8
+
9
+ def load_authenticator_config(file_path='authenticator_config.yaml'):
10
+ try:
11
+ with open(file_path, 'r') as file:
12
+ authenticator_config = load(file, Loader=SafeLoader)
13
+ return authenticator_config
14
+ except FileNotFoundError:
15
+ logging.error(f"File {file_path} not found.")
16
+ except YAMLError as error:
17
+ logging.error(f"Error parsing YAML file: {error}")
18
+
19
+
20
+ def new_file():
21
+ st.session_state['loaded_embeddings'] = None
22
+ st.session_state['doc_id'] = None
23
+ st.session_state['uploaded'] = True
24
+ clear_memory()
25
+
26
+
27
+ def clear_memory():
28
+ if st.session_state['memory']:
29
+ st.session_state['memory'].clear()
30
+
31
+
32
+ def init_qa(model, api_key=None):
33
+ print(f"Initializing QA with model: {model} and API key: {api_key}")
34
+ return DocumentQAEngine(model, api_key=api_key)
35
+
36
+
37
+ def append_header():
38
+ st.header('📄 Document Insights :rainbow[AI] Assistant 📚', divider='rainbow')
39
+ st.text("📥 Upload documents in PDF format. Get insights.. ask questions..")
40
+
41
+
42
+ def append_documentation_to_sidebar():
43
+ with st.expander("Disclaimer"):
44
+ st.markdown(
45
+ """
46
+ :warning: Do not upload sensitive data. We **temporarily** store text from the uploaded PDF documents solely
47
+ for the purpose of processing your request, and we **do not assume responsibility** for any subsequent use
48
+ or handling of the data submitted to third parties LLMs.
49
+ """)
50
+ with st.expander("Documentation"):
51
+ st.markdown(
52
+ """
53
+ Upload a CV as PDF document. Once the spinner stops, you can proceed to ask your questions. The answers will
54
+ be displayed in the right column. The system will answer your questions using the content of the document
55
+ and mark refrences over the PDF viewer.
56
+ """)
utils/__pycache__/config.cpython-38.pyc ADDED
Binary file (1.47 kB). View file
 
utils/__pycache__/haystack.cpython-38.pyc ADDED
Binary file (3.59 kB). View file
 
utils/__pycache__/ui.cpython-38.pyc ADDED
Binary file (733 Bytes). 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