drkareemkamal commited on
Commit
6e6b189
1 Parent(s): d64fa54

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -0
app.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.prompts import PromptTemplate
2
+ import os
3
+ from langchain_community.embeddings import HuggingFaceBgeEmbeddings
4
+ from langchain_community.vectorstores import FAISS
5
+ from langchain_community.llms.ctransformers import CTransformers
6
+ #from langchain.chains import RetrievalQA
7
+ from langchain.chains.retrieval_qa.base import RetrievalQA
8
+ import streamlit as st
9
+
10
+ DB_FAISS_PATH = 'vectorstores/'
11
+
12
+ custom_prompt_template = '''use the following pieces of information to answer the user's questions.
13
+ If you don't know the answer, please just say that don't know the answer, don't try to make uo an answer.
14
+ Context : {context}
15
+ Question : {question}
16
+ only return the helpful answer below and nothing else.
17
+ '''
18
+
19
+ def set_custom_prompt():
20
+ """
21
+ Prompt template for QA retrieval for vector stores
22
+ """
23
+ prompt = PromptTemplate(template = custom_prompt_template,
24
+ input_variables = ['context','question'])
25
+
26
+ return prompt
27
+
28
+
29
+ def load_llm():
30
+ llm = CTransformers(
31
+ #model = 'TheBloke/Llama-2-7B-Chat-GGML',
32
+ #model = AutoModel.from_pretrained("TheBloke/Llama-2-7B-Chat-GGML"),
33
+ model = 'MaziyarPanahi/BioMistral-7B-GGUF',
34
+ model_type = 'mistral',
35
+ max_new_token = 512,
36
+ temperature = 0.5
37
+ )
38
+ return llm
39
+
40
+ def retrieval_qa_chain(llm,prompt,db):
41
+ qa_chain = RetrievalQA.from_chain_type(
42
+ llm = llm,
43
+ chain_type = 'stuff',
44
+ retriever = db.as_retriever(search_kwargs= {'k': 2}),
45
+ return_source_documents = True,
46
+ chain_type_kwargs = {'prompt': prompt}
47
+ )
48
+
49
+ return qa_chain
50
+
51
+ def qa_bot():
52
+ #embeddings = HuggingFaceBgeEmbeddings(model_name = 'sentence-transformers/all-MiniLM-L6-v2',
53
+ # model_kwargs = {'device':'cpu'})
54
+ embeddings = HuggingFaceBgeEmbeddings(model_name = 'NeuML/pubmedbert-base-embeddings',
55
+ model_kwargs = {'device':'cpu'} )
56
+
57
+
58
+ db = FAISS.load_local(DB_FAISS_PATH, embeddings,allow_dangerous_deserialization=True)
59
+ llm = load_llm()
60
+ qa_prompt = set_custom_prompt()
61
+ qa = retrieval_qa_chain(llm,qa_prompt, db)
62
+
63
+ return qa
64
+
65
+ def final_result(query):
66
+ qa_result = qa_bot()
67
+ response = qa_result({'query' : query})
68
+
69
+ return response
70
+
71
+
72
+ import streamlit as st
73
+
74
+ # Initialize the bot
75
+ bot = qa_bot()
76
+
77
+ # def process_query(query):
78
+ # # Here you would include the logic to process the query and return a response
79
+ # response, sources = bot.answer_query(query) # Modify this according to your bot implementation
80
+ # if sources:
81
+ # response += f"\nSources: {', '.join(sources)}"
82
+ # else:
83
+ # response += "\nNo Sources Found"
84
+ # return response
85
+
86
+
87
+ # Streamlit webpage title
88
+ st.title('Medical Chatbot')
89
+
90
+ # User input
91
+ user_query = st.text_input("Please enter your question:")
92
+
93
+ # Button to get answer
94
+ if st.button('Get Answer'):
95
+ if user_query:
96
+ # Call the function from your chatbot script
97
+ response = final_result(user_query)
98
+ if response:
99
+ # Displaying the response
100
+ st.write("### Answer")
101
+ st.write(response['result'])
102
+
103
+ #Displaying source document details if available
104
+ if 'source_documents' in response:
105
+ st.write("### Source Document Information")
106
+ for doc in response['source_documents']:
107
+ # Retrieve and format page content by replacing '\n' with new line
108
+ formatted_content = doc.page_content.replace("\\n", "\n")
109
+ st.write("#### Document Content")
110
+ st.text_area(label="Page Content", value=formatted_content, height=300)
111
+
112
+ # Retrieve source and page from metadata
113
+ source = doc.metadata['source']
114
+ page = doc.metadata['page']
115
+ st.write(f"Source: {source}")
116
+ st.write(f"Page Number: {page}")
117
+
118
+ else:
119
+ st.write("Sorry, I couldn't find an answer to your question.")
120
+ else:
121
+ st.write("Please enter a question to get an answer.")