drkareemkamal commited on
Commit
d3110a2
1 Parent(s): 0d88c6c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -0
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.prompts import PromptTemplate
2
+ from langchain_community.embeddings import HuggingFaceBgeEmbeddings
3
+ from langchain_community.vectorstores import FAISS
4
+ from langchain_community.llms.ctransformers import CTransformers
5
+ from langchain.chains.retrieval_qa.base import RetrievalQA
6
+ from langchain_community.llms import HuggingFaceHub
7
+
8
+ from langchain.document_loaders import PyPDFLoader
9
+ from langchain.document_loaders import PyPDFDirectoryLoader
10
+
11
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
12
+ from langchain.vectorstores import FAISS
13
+
14
+ from langchain_community.embeddings import HuggingFaceBgeEmbeddings
15
+
16
+ from langchain.prompts import PromptTemplate
17
+
18
+ from langchain.chains import create_retrieval_chain
19
+ from langchain.chains import RetrievalQA
20
+
21
+ from langchain.chains.combine_documents import create_stuff_documents_chain
22
+
23
+ import os
24
+ import streamlit as st
25
+ import fitz # PyMuPDF
26
+ from PIL import Image
27
+ import io
28
+
29
+ DB_FAISS_PATH = 'vectorstores/'
30
+ pdf_path = 'Oxford/Oxford-psychiatric-handbook-1-760.pdf'
31
+
32
+ # custom_prompt_template = '''use the following pieces of information to answer the user's questions.
33
+ # If you don't know the answer, please just say that don't know the answer, don't try to make uo an answer.
34
+ # Context : {context}
35
+ # Question : {question}
36
+ # only return the helpful answer below and nothing else.
37
+ # '''
38
+ custom_prompt_template = prompt_template="""
39
+ Use the following piece of context to answer the question asked.
40
+ Please try to provide the answer only based on the context
41
+ {context}
42
+ Question:{question}
43
+ """
44
+ def set_custom_prompt():
45
+ """
46
+ Prompt template for QA retrieval for vector stores
47
+ """
48
+ prompt = PromptTemplate(template = custom_prompt_template,
49
+ input_variables = ['context','question'])
50
+
51
+ return prompt
52
+
53
+
54
+ def load_llm():
55
+ # llm = CTransformers(
56
+ # model = 'TheBloke/Llama-2-7B-Chat-GGML',
57
+ # model_type = 'llama',
58
+ # max_new_token = 512,
59
+ # temperature = 0.5
60
+ # )
61
+ llm = HuggingFaceHub(
62
+ repo_id = "mistralai/Mistral-7B-v0.1",
63
+ model_kwargs = {'temperature': 0.1, "max_length": 500}
64
+ )
65
+ return llm
66
+
67
+ def retrieval_qa_chain(llm,prompt,db):
68
+ qa_chain = RetrievalQA.from_chain_type(
69
+ llm = llm,
70
+ chain_type = 'stuff',
71
+ retriever = db.as_retriever(search_type = 'similarity',search_kwargs = {'k': 3}),
72
+ return_source_documents = True,
73
+ chain_type_kwargs = {'prompt': prompt}
74
+ )
75
+
76
+ return qa_chain
77
+
78
+ def qa_bot():
79
+ embeddings = HuggingFaceBgeEmbeddings(model_name = 'BAAI/bge-small-en-v1.5',#'sentence-transformers/all-MiniLM-L6-v2',
80
+ model_kwargs = {'device':'cpu'},
81
+ encode_kwargs = {'normalize_embeddings': True})
82
+
83
+
84
+ db = FAISS.load_local(DB_FAISS_PATH, embeddings, allow_dangerous_deserialization=True)
85
+ llm = load_llm()
86
+ qa_prompt = set_custom_prompt()
87
+ qa = retrieval_qa_chain(llm,qa_prompt, db)
88
+
89
+ return qa
90
+
91
+ def final_result(query):
92
+ qa_result = qa_bot()
93
+ response = qa_result({'query' : query})
94
+
95
+ return response
96
+
97
+ def get_pdf_page_as_image(pdf_path, page_number):
98
+ document = fitz.open(pdf_path)
99
+ page = document.load_page(page_number)
100
+ pix = page.get_pixmap()
101
+ img = Image.open(io.BytesIO(pix.tobytes()))
102
+ return img
103
+
104
+ # Streamlit webpage title
105
+ st.title('Medical Chatbot')
106
+
107
+ # User input
108
+ user_query = st.text_input("Please enter your question:")
109
+
110
+ # Button to get answer
111
+ if st.button('Get Answer'):
112
+ if user_query:
113
+ # Call the function from your chatbot script
114
+ response = final_result(user_query)
115
+ if response:
116
+ # Displaying the response
117
+ st.write("### Answer")
118
+ st.write(response['result'])
119
+
120
+ # Displaying source document details if available
121
+ if 'source_documents' in response:
122
+ st.write("### Source Document Information")
123
+ for doc in response['source_documents']:
124
+ # Retrieve and format page content by replacing '\n' with new line
125
+ formatted_content = doc.page_content.replace("\\n", "\n")
126
+ st.write("#### Document Content")
127
+ st.text_area(label="Page Content", value=formatted_content, height=300)
128
+
129
+ # Retrieve source and page from metadata
130
+ source = doc.metadata['source']
131
+ page = doc.metadata['page']
132
+ st.write(f"Source: {source}")
133
+ st.write(f"Page Number: {page+1}")
134
+
135
+ # Display the PDF page as an image
136
+ #source = r"{source}"
137
+ pdf_page_image = get_pdf_page_as_image(pdf_path, page)
138
+ st.image(pdf_page_image, caption=f"Page {page+1} from {source}")
139
+
140
+ else:
141
+ st.write("Sorry, I couldn't find an answer to your question.")
142
+ else:
143
+ st.write("Please enter a question to get an answer.")