drkareemkamal commited on
Commit
f41a8fc
·
verified ·
1 Parent(s): 39ee040

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -0
app.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ custom_prompt_template = '''use the following pieces of information to answer the user's questions.
15
+ If you don't know the answer, please just say that don't know the answer, don't try to make uo an answer.
16
+ Context : {context}
17
+ Question : {question}
18
+ only return the helpful answer below and nothing else.
19
+ '''
20
+
21
+ def set_custom_prompt():
22
+ """
23
+ Prompt template for QA retrieval for vector stores
24
+ """
25
+ prompt = PromptTemplate(template = custom_prompt_template,
26
+ input_variables = ['context','question'])
27
+
28
+ return prompt
29
+
30
+
31
+ def load_llm():
32
+ llm = CTransformers(
33
+ model = 'TheBloke/Llama-2-7B-Chat-GGML',
34
+ model_type = 'llama',
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
+
55
+
56
+ db = FAISS.load_local(DB_FAISS_PATH, embeddings, allow_dangerous_deserialization=True)
57
+ llm = load_llm()
58
+ qa_prompt = set_custom_prompt()
59
+ qa = retrieval_qa_chain(llm,qa_prompt, db)
60
+
61
+ return qa
62
+
63
+ def final_result(query):
64
+ qa_result = qa_bot()
65
+ response = qa_result({'query' : query})
66
+
67
+ return response
68
+
69
+ def get_pdf_page_as_image(pdf_path, page_number):
70
+ document = fitz.open(pdf_path)
71
+ page = document.load_page(page_number - 1) # Page numbers are 0-based in PyMuPDF
72
+ pix = page.get_pixmap()
73
+ img = Image.open(io.BytesIO(pix.tobytes()))
74
+ return img
75
+
76
+ # Streamlit webpage title
77
+ st.title('Medical Chatbot')
78
+
79
+ # User input
80
+ user_query = st.text_input("Please enter your question:")
81
+
82
+ # Button to get answer
83
+ if st.button('Get Answer'):
84
+ if user_query:
85
+ # Call the function from your chatbot script
86
+ response = final_result(user_query)
87
+ if response:
88
+ # Displaying the response
89
+ st.write("### Answer")
90
+ st.write(response['result'])
91
+
92
+ # Displaying source document details if available
93
+ if 'source_documents' in response:
94
+ st.write("### Source Document Information")
95
+ for doc in response['source_documents']:
96
+ # Retrieve and format page content by replacing '\n' with new line
97
+ formatted_content = doc.page_content.replace("\\n", "\n")
98
+ st.write("#### Document Content")
99
+ st.text_area(label="Page Content", value=formatted_content, height=300)
100
+
101
+ # Retrieve source and page from metadata
102
+ source = doc.metadata['source']
103
+ page = doc.metadata['page']
104
+ st.write(f"Source: {source}")
105
+ st.write(f"Page Number: {page}")
106
+
107
+ # Display the PDF page as an image
108
+ pdf_page_image = get_pdf_page_as_image(source, page)
109
+ st.image(pdf_page_image, caption=f"Page {page} from {source}")
110
+
111
+ else:
112
+ st.write("Sorry, I couldn't find an answer to your question.")
113
+ else:
114
+ st.write("Please enter a question to get an answer.")