drkareemkamal commited on
Commit
402c5da
1 Parent(s): 5210b32

Create app.py

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