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

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -126
app.py DELETED
@@ -1,126 +0,0 @@
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 = 'Oxford/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
- {context}
25
- Question:{question}
26
- """
27
- def set_custom_prompt():
28
- """
29
- Prompt template for QA retrieval for vector stores
30
- """
31
- prompt = PromptTemplate(template = custom_prompt_template,
32
- input_variables = ['context','question'])
33
-
34
- return prompt
35
-
36
-
37
- def load_llm():
38
- # llm = CTransformers(
39
- # model = 'TheBloke/Llama-2-7B-Chat-GGML',
40
- # model_type = 'llama',
41
- # max_new_token = 512,
42
- # temperature = 0.5
43
- # )
44
- llm = HuggingFaceHub(
45
- repo_id = "mistralai/Mistral-7B-v0.1",
46
- model_kwargs = {'temperature': 0.1, "max_length": 500}
47
- )
48
- return llm
49
-
50
- def retrieval_qa_chain(llm,prompt,db):
51
- qa_chain = RetrievalQA.from_chain_type(
52
- llm = llm,
53
- chain_type = 'stuff',
54
- retriever = db.as_retriever(search_type = 'similarity',search_kwargs = {'k': 3}),
55
- return_source_documents = True,
56
- chain_type_kwargs = {'prompt': prompt}
57
- )
58
-
59
- return qa_chain
60
-
61
- def qa_bot():
62
- embeddings = HuggingFaceBgeEmbeddings(model_name = 'BAAI/bge-small-en-v1.5',#'sentence-transformers/all-MiniLM-L6-v2',
63
- model_kwargs = {'device':'cpu'},
64
- encode_kwargs = {'normalize_embeddings': True})
65
-
66
-
67
- db = FAISS.load_local(DB_FAISS_PATH, embeddings, allow_dangerous_deserialization=True)
68
- llm = load_llm()
69
- qa_prompt = set_custom_prompt()
70
- qa = retrieval_qa_chain(llm,qa_prompt, db)
71
-
72
- return qa
73
-
74
- def final_result(query):
75
- qa_result = qa_bot()
76
- response = qa_result({'query' : query})
77
-
78
- return response
79
-
80
- def get_pdf_page_as_image(pdf_path, page_number):
81
- document = fitz.open(pdf_path)
82
- page = document.load_page(page_number)
83
- pix = page.get_pixmap()
84
- img = Image.open(io.BytesIO(pix.tobytes()))
85
- return img
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+1}")
117
-
118
- # Display the PDF page as an image
119
- #source = r"{source}"
120
- pdf_page_image = get_pdf_page_as_image(pdf_path, page)
121
- st.image(pdf_page_image, caption=f"Page {page+1} from {source}")
122
-
123
- else:
124
- st.write("Sorry, I couldn't find an answer to your question.")
125
- else:
126
- st.write("Please enter a question to get an answer.")