drkareemkamal commited on
Commit
87307ea
·
verified ·
1 Parent(s): 90af230

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -0
app.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_type = 'llama',
34
+ max_new_token = 512,
35
+ temperature = 0.5
36
+ )
37
+ return llm
38
+
39
+ def retrieval_qa_chain(llm,prompt,db):
40
+ qa_chain = RetrievalQA.from_chain_type(
41
+ llm = llm,
42
+ chain_type = 'stuff',
43
+ retriever = db.as_retriever(search_kwargs= {'k': 2}),
44
+ return_source_documents = True,
45
+ chain_type_kwargs = {'prompt': prompt}
46
+ )
47
+
48
+ return qa_chain
49
+
50
+ def qa_bot():
51
+ embeddings = HuggingFaceBgeEmbeddings(model_name = 'sentence-transformers/all-MiniLM-L6-v2',
52
+ model_kwargs = {'device':'cpu'})
53
+
54
+
55
+ db = FAISS.load_local(DB_FAISS_PATH, embeddings,allow_dangerous_deserialization=True)
56
+ llm = load_llm()
57
+ qa_prompt = set_custom_prompt()
58
+ qa = retrieval_qa_chain(llm,qa_prompt, db)
59
+
60
+ return qa
61
+
62
+ def final_result(query):
63
+ qa_result = qa_bot()
64
+ response = qa_result({'query' : query})
65
+
66
+ return response
67
+
68
+
69
+ import streamlit as st
70
+
71
+ # Initialize the bot
72
+ bot = qa_bot()
73
+
74
+ # def process_query(query):
75
+ # # Here you would include the logic to process the query and return a response
76
+ # response, sources = bot.answer_query(query) # Modify this according to your bot implementation
77
+ # if sources:
78
+ # response += f"\nSources: {', '.join(sources)}"
79
+ # else:
80
+ # response += "\nNo Sources Found"
81
+ # return response
82
+
83
+
84
+ # Streamlit webpage title
85
+ st.title('Medical Chatbot')
86
+
87
+ # User input
88
+ user_query = st.text_input("Please enter your question:")
89
+
90
+ # Button to get answer
91
+ if st.button('Get Answer'):
92
+ if user_query:
93
+ # Call the function from your chatbot script
94
+ response = final_result(user_query)
95
+ if response:
96
+ # Displaying the response
97
+ st.write("### Answer")
98
+ st.write(response['result'])
99
+
100
+ #Displaying source document details if available
101
+ if 'source_documents' in response:
102
+ st.write("### Source Document Information")
103
+ for doc in response['source_documents']:
104
+ # Retrieve and format page content by replacing '\n' with new line
105
+ formatted_content = doc.page_content.replace("\\n", "\n")
106
+ st.write("#### Document Content")
107
+ st.text_area(label="Page Content", value=formatted_content, height=300)
108
+
109
+ # Retrieve source and page from metadata
110
+ source = doc.metadata['source']
111
+ page = doc.metadata['page']
112
+ st.write(f"Source: {source}")
113
+ st.write(f"Page Number: {page}")
114
+
115
+ else:
116
+ st.write("Sorry, I couldn't find an answer to your question.")
117
+ else:
118
+ st.write("Please enter a question to get an answer.")