Henryk Borzymowski commited on
Commit
8329090
0 Parent(s):

initial push

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
README.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Haystack Search Pipeline with Streamlit
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,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import streamlit as st
3
+ import logging
4
+ import os
5
+
6
+ from annotated_text import annotation
7
+ from json import JSONDecodeError
8
+ from markdown import markdown
9
+ from utils.config import parser
10
+ from utils.haystack import start_document_store, start_haystack_extractive, start_haystack_rag, query
11
+ from utils.ui import reset_results, set_initial_state
12
+
13
+ try:
14
+ args = parser.parse_args()
15
+ document_store = start_document_store(type = args.store)
16
+ if args.task == 'extractive':
17
+ pipeline = start_haystack_extractive(document_store)
18
+ else:
19
+ pipeline = start_haystack_rag(document_store)
20
+
21
+ set_initial_state()
22
+
23
+ st.write('# '+args.name)
24
+
25
+ # Search bar
26
+ question = st.text_input("Ask a question", value=st.session_state.question, max_chars=100, on_change=reset_results)
27
+ #question = "what is Pi?"
28
+
29
+ run_pressed = st.button("Run")
30
+ #run_pressed = True
31
+
32
+ run_query = (
33
+ run_pressed or question != st.session_state.question
34
+ )
35
+
36
+ # Get results for query
37
+ if run_query and question:
38
+ reset_results()
39
+ st.session_state.question = question
40
+ with st.spinner("🔎    Running your pipeline"):
41
+ try:
42
+ st.session_state.results = query(pipeline, question)
43
+ except JSONDecodeError as je:
44
+ st.error(
45
+ "👓    An error occurred reading the results. Is the document store working?"
46
+ )
47
+ except Exception as e:
48
+ logging.exception(e)
49
+ st.error("🐞    An error occurred during the request.")
50
+
51
+
52
+
53
+ if st.session_state.results:
54
+ results = st.session_state.results
55
+
56
+ if args.task == 'extractive':
57
+ answers = results['answers']
58
+ for count, answer in enumerate(answers):
59
+ if answer.answer:
60
+ text, context = answer.answer, answer.context
61
+ start_idx = context.find(text)
62
+ end_idx = start_idx + len(text)
63
+ st.write(
64
+ f" Answer: {markdown(context[:start_idx] + str(annotation(body=text, label='ANSWER', background='#964448', color='#ffffff')) + context[end_idx:])}",
65
+ unsafe_allow_html=True,
66
+ )
67
+ else:
68
+ st.info(
69
+ "🤔    Haystack is unsure whether any of the documents contain an answer to your question. Try to reformulate it!"
70
+ )
71
+ elif args.task == 'rag':
72
+ st.write(f" Answer: {results['results'][0]}")
73
+
74
+ # Extract and display information from the 'documents' list
75
+ retrieved_documents = results['documents']
76
+ st.subheader("Retriever Results:")
77
+ for document in retrieved_documents:
78
+ st.write(f"Document Name: {document.meta['name']}")
79
+ st.write(f"Score: {document.score}")
80
+ st.write(f"Text: {document.content}")
81
+ except SystemExit as e:
82
+ # This exception will be raised if --help or invalid command line arguments
83
+ # are used. Currently streamlit prevents the program from exiting normally
84
+ # so we have to do a hard exit.
85
+ os._exit(e.code)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ safetensors==0.3.3.post1
2
+ farm-haystack[inference,weaviate,opensearch]==1.20.0
3
+ milvus-haystack
4
+ streamlit==1.23.0
5
+ markdown
6
+ st-annotated-text
7
+ datasets
utils/__pycache__/config.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
utils/__pycache__/haystack.cpython-310.pyc ADDED
Binary file (2.88 kB). View file
 
utils/__pycache__/ui.cpython-310.pyc ADDED
Binary file (678 Bytes). View file
 
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
+ task_choices = ('extractive', 'rag')
11
+ parser.add_argument('--store', choices=document_store_choices, default='inmemory', help='DocumentStore selection (default: %(default)s)')
12
+ parser.add_argument('--task', choices=task_choices, default='rag', help='Task selection (default: %(default)s)')
13
+ parser.add_argument('--name', default="My Search App")
14
+
15
+ model_configs = {
16
+ 'EMBEDDING_MODEL': os.getenv("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L12-v2"),
17
+ 'GENERATIVE_MODEL': os.getenv("GENERATIVE_MODEL", "gpt-4"),
18
+ 'EXTRACTIVE_MODEL': os.getenv("EXTRACTIVE_MODEL", "deepset/roberta-base-squad2"),
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,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
9
+ from milvus_haystack import MilvusDocumentStore
10
+ #Use this file to set up your Haystack pipeline and querying
11
+
12
+ @st.cache_resource(show_spinner=False)
13
+ def start_document_store(type: str):
14
+ #This function starts the documents store of your choice based on your command line preference
15
+ if type == 'inmemory':
16
+ document_store = InMemoryDocumentStore(use_bm25=True, embedding_dim=384)
17
+ documents = [
18
+ {
19
+ 'content': "Pi is a super dog",
20
+ 'meta': {'name': "pi.txt"}
21
+ },
22
+ {
23
+ 'content': "The revenue of siemens is 5 milion Euro",
24
+ 'meta': {'name': "siemens.txt"}
25
+ },
26
+ ]
27
+ document_store.write_documents(documents)
28
+ elif type == 'opensearch':
29
+ document_store = OpenSearchDocumentStore(scheme = document_store_configs['OPENSEARCH_SCHEME'],
30
+ username = document_store_configs['OPENSEARCH_USERNAME'],
31
+ password = document_store_configs['OPENSEARCH_PASSWORD'],
32
+ host = document_store_configs['OPENSEARCH_HOST'],
33
+ port = document_store_configs['OPENSEARCH_PORT'],
34
+ index = document_store_configs['OPENSEARCH_INDEX'],
35
+ embedding_dim = document_store_configs['OPENSEARCH_EMBEDDING_DIM'])
36
+ elif type == 'weaviate':
37
+ document_store = WeaviateDocumentStore(host = document_store_configs['WEAVIATE_HOST'],
38
+ port = document_store_configs['WEAVIATE_PORT'],
39
+ index = document_store_configs['WEAVIATE_INDEX'],
40
+ embedding_dim = document_store_configs['WEAVIATE_EMBEDDING_DIM'])
41
+ elif type == 'milvus':
42
+ document_store = MilvusDocumentStore(uri = document_store_configs['MILVUS_URI'],
43
+ index = document_store_configs['MILVUS_INDEX'],
44
+ embedding_dim = document_store_configs['MILVUS_EMBEDDING_DIM'],
45
+ return_embedding=True)
46
+ return document_store
47
+
48
+ # cached to make index and models load only at start
49
+ @st.cache_resource(show_spinner=False)
50
+ def start_haystack_extractive(_document_store: BaseDocumentStore):
51
+ retriever = EmbeddingRetriever(document_store=_document_store,
52
+ embedding_model=model_configs['EMBEDDING_MODEL'],
53
+ top_k=5)
54
+ _document_store.update_embeddings(retriever)
55
+
56
+ reader = FARMReader(model_name_or_path=model_configs['EXTRACTIVE_MODEL'])
57
+
58
+ pipe = Pipeline()
59
+ pipe.add_node(component=retriever, name="Retriever", inputs=["Query"])
60
+ pipe.add_node(component=reader, name="Reader", inputs=["Retriever"])
61
+
62
+ return pipe
63
+
64
+ @st.cache_resource(show_spinner=False)
65
+ def start_haystack_rag(_document_store: BaseDocumentStore):
66
+ retriever = EmbeddingRetriever(document_store=_document_store,
67
+ embedding_model=model_configs['EMBEDDING_MODEL'],
68
+ top_k=5)
69
+ _document_store.update_embeddings(retriever)
70
+ prompt_node = PromptNode(default_prompt_template="deepset/question-answering",
71
+ model_name_or_path=model_configs['GENERATIVE_MODEL'],
72
+ api_key=model_configs['OPENAI_KEY'])
73
+ pipe = Pipeline()
74
+
75
+ pipe.add_node(component=retriever, name="Retriever", inputs=["Query"])
76
+ pipe.add_node(component=prompt_node, name="PromptNode", inputs=["Retriever"])
77
+
78
+ return pipe
79
+
80
+ @st.cache_data(show_spinner=True)
81
+ def query(_pipeline, question):
82
+ params = {}
83
+ results = _pipeline.run(question, params=params)
84
+ return results
utils/ui.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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", None)
10
+
11
+ def reset_results(*args):
12
+ st.session_state.results = None