Spaces:
Runtime error
Runtime error
Commit
Β·
b0df4b4
1
Parent(s):
2b95436
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,39 +1,96 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import os
|
|
|
|
|
|
|
| 3 |
from haystack.utils import fetch_archive_from_http, clean_wiki_text, convert_files_to_docs
|
| 4 |
from haystack.schema import Answer
|
| 5 |
from haystack.document_stores import InMemoryDocumentStore
|
| 6 |
-
from haystack.pipelines import ExtractiveQAPipeline
|
| 7 |
-
from haystack.nodes import FARMReader,
|
|
|
|
|
|
|
|
|
|
| 8 |
import logging
|
| 9 |
from markdown import markdown
|
| 10 |
from annotated_text import annotation
|
| 11 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
os.environ['TOKENIZERS_PARALLELISM'] ="false"
|
| 14 |
|
| 15 |
-
#Haystack Components
|
| 16 |
-
@st.cache(hash_funcs={"builtins.SwigPyObject": lambda _: None},allow_output_mutation=True)
|
|
|
|
| 17 |
def start_haystack():
|
| 18 |
-
document_store = InMemoryDocumentStore()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
load_and_write_data(document_store)
|
| 20 |
-
retriever = TfidfRetriever(document_store=document_store)
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
def load_and_write_data(document_store):
|
| 26 |
doc_dir = './dao_data'
|
| 27 |
-
docs = convert_files_to_docs(dir_path=doc_dir, clean_func=clean_wiki_text,
|
|
|
|
| 28 |
|
| 29 |
document_store.write_documents(docs)
|
| 30 |
|
|
|
|
| 31 |
pipeline = start_haystack()
|
| 32 |
|
|
|
|
| 33 |
def set_state_if_absent(key, value):
|
| 34 |
if key not in st.session_state:
|
| 35 |
st.session_state[key] = value
|
| 36 |
|
|
|
|
| 37 |
set_state_if_absent("question", "What is the goal of VitaDAO?")
|
| 38 |
set_state_if_absent("results", None)
|
| 39 |
|
|
@@ -41,31 +98,38 @@ set_state_if_absent("results", None)
|
|
| 41 |
def reset_results(*args):
|
| 42 |
st.session_state.results = None
|
| 43 |
|
| 44 |
-
|
|
|
|
| 45 |
|
| 46 |
image = Image.open('got-haystack.png')
|
| 47 |
st.image(image)
|
| 48 |
|
| 49 |
-
st.markdown(
|
| 50 |
-
This QA demo uses a [Haystack Extractive QA Pipeline](
|
| 51 |
-
|
|
|
|
|
|
|
| 52 |
Go ahead and ask questions about the marvellous kingdom!
|
| 53 |
""", unsafe_allow_html=True)
|
| 54 |
|
| 55 |
-
question = st.text_input("", value=st.session_state.question, max_chars=100,
|
|
|
|
|
|
|
| 56 |
|
| 57 |
def ask_question(question):
|
| 58 |
-
prediction = pipeline.run(query=question, params={"Retriever": {"top_k": 10}, "Reader": {"top_k": 5}})
|
|
|
|
| 59 |
results = []
|
| 60 |
for answer in prediction["answers"]:
|
| 61 |
answer = answer.to_dict()
|
| 62 |
if answer["answer"]:
|
|
|
|
| 63 |
results.append(
|
| 64 |
{
|
| 65 |
-
"context": "..." + answer["context"] + "...",
|
| 66 |
"answer": answer["answer"],
|
| 67 |
-
"relevance": round(answer["score"] * 100, 2),
|
| 68 |
-
"offset_start_in_doc": answer["offsets_in_document"][0]["start"],
|
| 69 |
}
|
| 70 |
)
|
| 71 |
else:
|
|
@@ -73,21 +137,20 @@ def ask_question(question):
|
|
| 73 |
{
|
| 74 |
"context": None,
|
| 75 |
"answer": None,
|
| 76 |
-
"relevance": round(answer["score"] * 100, 2),
|
| 77 |
}
|
| 78 |
)
|
| 79 |
return results
|
| 80 |
|
|
|
|
| 81 |
if question:
|
| 82 |
with st.spinner("π Performing semantic search on royal scripts..."):
|
| 83 |
try:
|
| 84 |
msg = 'Asked ' + question
|
| 85 |
logging.info(msg)
|
| 86 |
-
st.session_state.results = ask_question(question)
|
| 87 |
except Exception as e:
|
| 88 |
logging.exception(e)
|
| 89 |
-
|
| 90 |
-
|
| 91 |
|
| 92 |
if st.session_state.results:
|
| 93 |
st.write('## Top Results')
|
|
@@ -97,11 +160,14 @@ if st.session_state.results:
|
|
| 97 |
start_idx = context.find(answer)
|
| 98 |
end_idx = start_idx + len(answer)
|
| 99 |
st.write(
|
| 100 |
-
markdown(context[:start_idx] + str(
|
|
|
|
|
|
|
| 101 |
unsafe_allow_html=True,
|
| 102 |
)
|
| 103 |
-
st.markdown(f"**Relevance:** {result['relevance']}")
|
| 104 |
else:
|
| 105 |
st.info(
|
| 106 |
-
"π€ Haystack is unsure whether any of the documents contain an
|
|
|
|
| 107 |
)
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import os
|
| 3 |
+
|
| 4 |
+
from haystack import Pipeline
|
| 5 |
from haystack.utils import fetch_archive_from_http, clean_wiki_text, convert_files_to_docs
|
| 6 |
from haystack.schema import Answer
|
| 7 |
from haystack.document_stores import InMemoryDocumentStore
|
| 8 |
+
from haystack.pipelines import DocumentSearchPipeline, ExtractiveQAPipeline, GenerativeQAPipeline
|
| 9 |
+
from haystack.nodes import (DensePassageRetriever, EmbeddingRetriever, FARMReader,
|
| 10 |
+
OpenAIAnswerGenerator, Seq2SeqGenerator,
|
| 11 |
+
TfidfRetriever)
|
| 12 |
+
from haystack.nodes import RAGenerator
|
| 13 |
import logging
|
| 14 |
from markdown import markdown
|
| 15 |
from annotated_text import annotation
|
| 16 |
from PIL import Image
|
| 17 |
+
logging.basicConfig(format="%(levelname)s - %(name)s - %(message)s", level=logging.WARNING)
|
| 18 |
+
logging.getLogger("haystack").setLevel(logging.INFO)
|
| 19 |
+
|
| 20 |
+
os.environ['TOKENIZERS_PARALLELISM'] = "false"
|
| 21 |
+
MY_API_KEY = os.environ.get("MY_API_KEY")
|
| 22 |
|
|
|
|
| 23 |
|
| 24 |
+
# Haystack Components
|
| 25 |
+
# @st.cache(hash_funcs={"builtins.SwigPyObject": lambda _: None}, allow_output_mutation=True)
|
| 26 |
+
@st.cache_data
|
| 27 |
def start_haystack():
|
| 28 |
+
# document_store = InMemoryDocumentStore()
|
| 29 |
+
# For dense retriever
|
| 30 |
+
document_store = InMemoryDocumentStore(embedding_dim=128)
|
| 31 |
+
# For OPEN AI retriever
|
| 32 |
+
# document_store = InMemoryDocumentStore(embedding_dim=1024)
|
| 33 |
load_and_write_data(document_store)
|
| 34 |
+
# retriever = TfidfRetriever(document_store=document_store)
|
| 35 |
+
retriever = DensePassageRetriever(
|
| 36 |
+
document_store=document_store,
|
| 37 |
+
query_embedding_model="vblagoje/dpr-question_encoder-single-lfqa-wiki",
|
| 38 |
+
passage_embedding_model="vblagoje/dpr-ctx_encoder-single-lfqa-wiki",
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# retriever = EmbeddingRetriever(
|
| 42 |
+
# document_store=document_store,
|
| 43 |
+
# embedding_model="sentence-transformers/multi-qa-mpnet-base-dot-v1",
|
| 44 |
+
# model_format="sentence_transformers",
|
| 45 |
+
# )
|
| 46 |
+
document_store.update_embeddings(retriever)
|
| 47 |
+
|
| 48 |
+
# OPEN AI
|
| 49 |
+
# retriever = EmbeddingRetriever(
|
| 50 |
+
# document_store=document_store,
|
| 51 |
+
# batch_size=8,
|
| 52 |
+
# embedding_model="ada",
|
| 53 |
+
# api_key=MY_API_KEY,
|
| 54 |
+
# max_seq_len=1024
|
| 55 |
+
# )
|
| 56 |
+
# document_store.update_embeddings(retriever)
|
| 57 |
+
|
| 58 |
+
# reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2", use_gpu=True)
|
| 59 |
+
# pipeline = ExtractiveQAPipeline(reader, retriever)
|
| 60 |
+
|
| 61 |
+
generator = Seq2SeqGenerator(model_name_or_path="vblagoje/bart_lfqa")
|
| 62 |
+
# generator = OpenAIAnswerGenerator(
|
| 63 |
+
# api_key=MY_API_KEY,
|
| 64 |
+
# model="text-davinci-003",
|
| 65 |
+
# max_tokens=50,
|
| 66 |
+
# presence_penalty=0.1,
|
| 67 |
+
# frequency_penalty=0.1,
|
| 68 |
+
# top_k=3,
|
| 69 |
+
# temperature=0.9
|
| 70 |
+
# )
|
| 71 |
+
# pipe.add_node(component=retriever, name="Retriever", inputs=["Query"])
|
| 72 |
+
# pipe.add_node(component=generator, name="prompt_node", inputs=["Query"])
|
| 73 |
+
pipe = GenerativeQAPipeline(generator=generator, retriever=retriever)
|
| 74 |
+
|
| 75 |
+
return pipe
|
| 76 |
+
|
| 77 |
|
| 78 |
def load_and_write_data(document_store):
|
| 79 |
doc_dir = './dao_data'
|
| 80 |
+
docs = convert_files_to_docs(dir_path=doc_dir, clean_func=clean_wiki_text,
|
| 81 |
+
split_paragraphs=True)
|
| 82 |
|
| 83 |
document_store.write_documents(docs)
|
| 84 |
|
| 85 |
+
|
| 86 |
pipeline = start_haystack()
|
| 87 |
|
| 88 |
+
|
| 89 |
def set_state_if_absent(key, value):
|
| 90 |
if key not in st.session_state:
|
| 91 |
st.session_state[key] = value
|
| 92 |
|
| 93 |
+
|
| 94 |
set_state_if_absent("question", "What is the goal of VitaDAO?")
|
| 95 |
set_state_if_absent("results", None)
|
| 96 |
|
|
|
|
| 98 |
def reset_results(*args):
|
| 99 |
st.session_state.results = None
|
| 100 |
|
| 101 |
+
|
| 102 |
+
# Streamlit App
|
| 103 |
|
| 104 |
image = Image.open('got-haystack.png')
|
| 105 |
st.image(image)
|
| 106 |
|
| 107 |
+
st.markdown("""
|
| 108 |
+
This QA demo uses a [Haystack Extractive QA Pipeline](
|
| 109 |
+
https://haystack.deepset.ai/components/ready-made-pipelines#extractiveqapipeline) with
|
| 110 |
+
an [InMemoryDocumentStore](https://haystack.deepset.ai/components/document-store) which contains
|
| 111 |
+
documents about Game of Thrones π
|
| 112 |
Go ahead and ask questions about the marvellous kingdom!
|
| 113 |
""", unsafe_allow_html=True)
|
| 114 |
|
| 115 |
+
question = st.text_input("", value=st.session_state.question, max_chars=100,
|
| 116 |
+
on_change=reset_results)
|
| 117 |
+
|
| 118 |
|
| 119 |
def ask_question(question):
|
| 120 |
+
# prediction = pipeline.run(query=question, params={"Retriever": {"top_k": 10}, "Reader": {"top_k": 5}})
|
| 121 |
+
prediction = pipeline.run(query=question, params={"Retriever": {"top_k": 10}, "Generator": {"top_k": 1}})
|
| 122 |
results = []
|
| 123 |
for answer in prediction["answers"]:
|
| 124 |
answer = answer.to_dict()
|
| 125 |
if answer["answer"]:
|
| 126 |
+
print(answer)
|
| 127 |
results.append(
|
| 128 |
{
|
| 129 |
+
"context": "..." + str(answer["context"]) + "...",
|
| 130 |
"answer": answer["answer"],
|
| 131 |
+
# "relevance": round(answer["score"] * 100, 2),
|
| 132 |
+
# "offset_start_in_doc": answer["offsets_in_document"][0]["start"],
|
| 133 |
}
|
| 134 |
)
|
| 135 |
else:
|
|
|
|
| 137 |
{
|
| 138 |
"context": None,
|
| 139 |
"answer": None,
|
| 140 |
+
# "relevance": round(answer["score"] * 100, 2),
|
| 141 |
}
|
| 142 |
)
|
| 143 |
return results
|
| 144 |
|
| 145 |
+
|
| 146 |
if question:
|
| 147 |
with st.spinner("π Performing semantic search on royal scripts..."):
|
| 148 |
try:
|
| 149 |
msg = 'Asked ' + question
|
| 150 |
logging.info(msg)
|
| 151 |
+
st.session_state.results = ask_question(question)
|
| 152 |
except Exception as e:
|
| 153 |
logging.exception(e)
|
|
|
|
|
|
|
| 154 |
|
| 155 |
if st.session_state.results:
|
| 156 |
st.write('## Top Results')
|
|
|
|
| 160 |
start_idx = context.find(answer)
|
| 161 |
end_idx = start_idx + len(answer)
|
| 162 |
st.write(
|
| 163 |
+
markdown(context[:start_idx] + str(
|
| 164 |
+
annotation(body=answer, label="ANSWER", background="#964448",
|
| 165 |
+
color='#ffffff')) + context[end_idx:]),
|
| 166 |
unsafe_allow_html=True,
|
| 167 |
)
|
| 168 |
+
# st.markdown(f"**Relevance:** {result['relevance']}")
|
| 169 |
else:
|
| 170 |
st.info(
|
| 171 |
+
"π€ Haystack is unsure whether any of the documents contain an "
|
| 172 |
+
"answer to your question. Try to reformulate it!"
|
| 173 |
)
|