iamviveksrk commited on
Commit
508732a
β€’
1 Parent(s): 6d6ff0d

working overhaul

Browse files
Files changed (1) hide show
  1. app.py +98 -20
app.py CHANGED
@@ -1,21 +1,99 @@
1
  import streamlit as st
2
- import time
3
- from pipeline import pipeline
4
-
5
- st.title('Welcome to SRM RP explorer!')
6
- query = st.text_input('Enter a query to get started:', 'Applications of AI and deep learning')
7
- noof_results = st.slider('Number of results required', 1, 3, 1)
8
-
9
- start = time.time()
10
- pred = pipeline.run(query=query, params={"Retriever": {"top_k": 5}, "Reader": {"top_k": noof_results}})
11
- st.write('Time taken: %s s' % round(time.time()-start, 2))
12
-
13
- for i in pred['answers']:
14
-
15
- ans, name, link, context, score = i.answer, i.meta['name'],i.meta['link'], i.context, i.score
16
- st.write(f'Score: {score}')
17
- st.write(f'Answer: {ans}')
18
- st.write(f'Title: {name}')
19
- # st.write(f'Abstract: {context}')
20
- st.write(f'Link: {link}')
21
- st.write(f'-------------')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from markdown import markdown
3
+ from annotated_text import annotation
4
+ import logging
5
+
6
+ from haystack.document_stores import InMemoryDocumentStore
7
+ from haystack.nodes import TfidfRetriever
8
+ from haystack.pipelines import ExtractiveQAPipeline
9
+ from haystack.nodes import FARMReader
10
+ import joblib
11
+
12
+ @st.cache(hash_funcs={"builtins.SwigPyObject": lambda _: None},allow_output_mutation=True)
13
+ def create_pipeline():
14
+ docs = joblib.load('docs.joblib')
15
+
16
+ document_store = InMemoryDocumentStore()
17
+ document_store.write_documents(docs)
18
+
19
+ retriever = TfidfRetriever(document_store)
20
+ reader = FARMReader(model_name_or_path="ixa-ehu/SciBERT-SQuAD-QuAC")
21
+
22
+ pipeline = ExtractiveQAPipeline(reader, retriever)
23
+
24
+ return pipeline
25
+
26
+ pipeline = create_pipeline()
27
+
28
+ def set_state_if_absent(key, value):
29
+ if key not in st.session_state:
30
+ st.session_state[key] = value
31
+
32
+ set_state_if_absent("question", 'Applications of AI and deep learning')
33
+ set_state_if_absent("results", None)
34
+
35
+ def reset_results(*args):
36
+ st.session_state.results = None
37
+
38
+ st.markdown('''#Welcome to **SRM RP explorer**!
39
+ This QA demo uses a [Haystack Extractive QA Pipeline](https://haystack.deepset.ai/components/ready-made-pipelines#extractiveqapipeline) with
40
+ an [InMemoryDocumentStore](https://haystack.deepset.ai/components/document-store) which contains abstracts of 17k+ research papers associated with SRM university''')
41
+
42
+ query = st.text_input('Enter a query to get started:', value=st.session_state.question, max_chars=100, on_change=reset_results)
43
+
44
+ def ask_question(query):
45
+ start = time.time()
46
+ prediction = pipeline.run(query=query, params={"Retriever": {"top_k": 10}, "Reader": {"top_k": 5}})
47
+ st.write('Time taken: %s s' % round(time.time()-start, 2))
48
+
49
+ results = []
50
+ for answer in prediction["answers"]:
51
+ answer = answer.to_dict()
52
+ if answer["answer"]:
53
+ results.append(
54
+ {
55
+ "title":answer["meta"]["name"],
56
+ "link":answer["meta"]["link"],
57
+ "context": "..." + answer["context"] + "...",
58
+ "answer": answer["answer"],
59
+ "score": round(answer["score"] * 100, 2),
60
+ "offset_start_in_doc": answer["offsets_in_document"][0]["start"],
61
+ }
62
+ )
63
+ else:
64
+ results.append(
65
+ {
66
+ "title":None,
67
+ "link":None,
68
+ "context": None,
69
+ "answer": None,
70
+ "relevance": round(answer["score"] * 100, 2),
71
+ }
72
+ )
73
+ return results
74
+
75
+ if query:
76
+ with st.spinner("πŸ‘‘    Performing semantic search on abstracts..."):
77
+ try:
78
+ msg = 'Asked ' + question
79
+ logging.info(msg)
80
+ st.session_state.results = ask_question(question)
81
+ except Exception as e:
82
+ logging.exception(e)
83
+
84
+ if st.session_state.results:
85
+ st.write('## Top Results')
86
+ for count, result in enumerate(st.session_state.results):
87
+ if result["answer"]:
88
+ answer, context = result["answer"], result["context"]
89
+ start_idx = context.find(answer)
90
+ end_idx = start_idx + len(answer)
91
+ st.write(
92
+ markdown(context[:start_idx] + str(annotation(body=answer, label="RELEVANT", background="#964448", color='#ffffff')) + context[end_idx:]),
93
+ unsafe_allow_html=True,
94
+ )
95
+ st.markdown(f"**Title:** [{result['name']}]({result['link']})\n**Relevance:** {result['relevance']}")
96
+ else:
97
+ st.info(
98
+ "πŸ€”    Haystack is unsure whether any of the documents contain an answer to your question. Try to reformulate it!"
99
+ )