Spaces:
Running
Running
Commit
•
c3b45b1
1
Parent(s):
4829090
Delete app.py
Browse files
app.py
DELETED
@@ -1,242 +0,0 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
from langchain.document_loaders import PyPDFLoader, DirectoryLoader
|
3 |
-
from langchain import PromptTemplate
|
4 |
-
from langchain.embeddings import HuggingFaceEmbeddings
|
5 |
-
from langchain.vectorstores import FAISS
|
6 |
-
from langchain.llms import CTransformers
|
7 |
-
from langchain.chains import RetrievalQA
|
8 |
-
import geocoder
|
9 |
-
from geopy.distance import geodesic
|
10 |
-
import pandas as pd
|
11 |
-
import folium
|
12 |
-
from streamlit_folium import folium_static
|
13 |
-
from transformers import pipeline
|
14 |
-
import logging
|
15 |
-
|
16 |
-
|
17 |
-
DB_FAISS_PATH = 'vectorstores/db_faiss'
|
18 |
-
|
19 |
-
# Load the model for text classification
|
20 |
-
classifier = pipeline("zero-shot-classification")
|
21 |
-
|
22 |
-
|
23 |
-
# Set up logging
|
24 |
-
logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s %(message)s')
|
25 |
-
|
26 |
-
|
27 |
-
custom_prompt_template = """Use the following pieces of information to answer the user's question.
|
28 |
-
If you don't know the answer, just say that you don't know, don't try to make up an answer.
|
29 |
-
|
30 |
-
Context: {context}
|
31 |
-
Question: {question}
|
32 |
-
|
33 |
-
Only return the helpful answer below and nothing else.
|
34 |
-
Helpful answer:
|
35 |
-
"""
|
36 |
-
|
37 |
-
def set_custom_prompt():
|
38 |
-
prompt = PromptTemplate(template=custom_prompt_template,
|
39 |
-
input_variables=['context', 'question'])
|
40 |
-
return prompt
|
41 |
-
|
42 |
-
def retrieval_qa_chain(llm, prompt, db):
|
43 |
-
qa_chain = RetrievalQA.from_chain_type(llm=llm,
|
44 |
-
chain_type='stuff',
|
45 |
-
retriever=db.as_retriever(search_kwargs={'k': 2}),
|
46 |
-
return_source_documents=True,
|
47 |
-
chain_type_kwargs={'prompt': prompt}
|
48 |
-
)
|
49 |
-
return qa_chain
|
50 |
-
|
51 |
-
def load_llm():
|
52 |
-
llm = CTransformers(
|
53 |
-
|
54 |
-
#model="sentence-transformers/all-MiniLM-L6-v2",
|
55 |
-
model="TheBloke/Llama-2-7B-Chat-GGML",
|
56 |
-
#model="ThisIs-Developer/Llama-2-GGML-Medical-Chatbot",
|
57 |
-
#model="ksh-nyp/llama-2-7b-chat-TCMKB2",
|
58 |
-
#model="medical-ner-proj/bert-medical-ner-proj",
|
59 |
-
|
60 |
-
model_type="llama",
|
61 |
-
#model_type="bert",
|
62 |
-
|
63 |
-
max_new_tokens=512,
|
64 |
-
temperature=0.5
|
65 |
-
)
|
66 |
-
return llm
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
def qa_bot(query, context=""):
|
71 |
-
logging.info(f"Received query: {query}, Context: {context}")
|
72 |
-
|
73 |
-
if context in ["nearest clinic","nearest TCM clinic","nearest TCM doctor","near me","nearest to me"]:
|
74 |
-
logging.info("Context matched for nearest TCM clinic.")
|
75 |
-
# Get user's current location
|
76 |
-
g = geocoder.ip('me')
|
77 |
-
user_lat, user_lon = g.latlng
|
78 |
-
|
79 |
-
# Load locations from the CSV file
|
80 |
-
locations_df = pd.read_csv("dataset/locations.csv")
|
81 |
-
|
82 |
-
# Filter locations within 5km from user's current location
|
83 |
-
filtered_locations_df = locations_df[locations_df.apply(lambda row: geodesic((user_lat, user_lon), (row['latitude'], row['longitude'])).kilometers <= 5, axis=1)]
|
84 |
-
|
85 |
-
# Create map centered at user's location
|
86 |
-
my_map = folium.Map(location=[user_lat, user_lon], zoom_start=12)
|
87 |
-
|
88 |
-
# Add markers with custom tooltips for filtered locations
|
89 |
-
for index, location in filtered_locations_df.iterrows():
|
90 |
-
folium.Marker(location=[location['latitude'], location['longitude']], tooltip=f"{location['name']}<br>Reviews: {location['Stars_review']}<br>Avg Price $: {location['Price']}<br>Contact No: {location['Contact']}").add_to(my_map)
|
91 |
-
|
92 |
-
# Display map
|
93 |
-
folium_static(my_map)
|
94 |
-
|
95 |
-
return "[Map of Clinic Locations 5km from your current location]"
|
96 |
-
|
97 |
-
elif context in ["buy", "Ointment", "Hong You", "Feng You", "Fengyou", "Po chai pills"]:
|
98 |
-
logging.info("Context matched for buying.")
|
99 |
-
# Create a hyperlink to shopee.sg based on the search query
|
100 |
-
shopee_link = f"<a href='https://shopee.sg/search?keyword={context}'>at this Shopee link!</a>"
|
101 |
-
#shopee_link = f"<iframe src='www.yahoo.com.sg'></iframe> {context} here at Shopee!</a>"
|
102 |
-
return f"You may visit this page to purchase {context} {shopee_link}!"
|
103 |
-
|
104 |
-
else:
|
105 |
-
logging.info("Context not matched for nearest TCM clinic or buying.")
|
106 |
-
# Handle other Textual queries using your existing logic
|
107 |
-
|
108 |
-
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",
|
109 |
-
model_kwargs={'device': 'cpu'})
|
110 |
-
|
111 |
-
#embeddings = HuggingFaceEmbeddings(model_name="TheBloke/Llama-2-7B-Chat-GGML",
|
112 |
-
# model_kwargs={'device': 'cpu'})
|
113 |
-
|
114 |
-
|
115 |
-
db = FAISS.load_local(DB_FAISS_PATH, embeddings)
|
116 |
-
llm = load_llm()
|
117 |
-
qa_prompt = set_custom_prompt()
|
118 |
-
qa = retrieval_qa_chain(llm, qa_prompt, db)
|
119 |
-
|
120 |
-
# Implement the question-answering logic here
|
121 |
-
response = qa({'query': query})
|
122 |
-
return response['result']
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
def add_vertical_space(spaces=1):
|
129 |
-
for _ in range(spaces):
|
130 |
-
st.markdown("---")
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
def main():
|
135 |
-
st.set_page_config(page_title="Ask me anything about TCM")
|
136 |
-
|
137 |
-
with st.sidebar:
|
138 |
-
st.title('Welcome to Nexus AI TCM!')
|
139 |
-
|
140 |
-
st.markdown('''
|
141 |
-
|
142 |
-
<style>
|
143 |
-
[data-testid=stSidebar] {
|
144 |
-
background-color: #ffffff;
|
145 |
-
}
|
146 |
-
</style>
|
147 |
-
<img src="https://huggingface.co/spaces/mathslearn/chatbot_test_streamlit/resolve/main/logo.jpeg" width=200>
|
148 |
-
|
149 |
-
''', unsafe_allow_html=True)
|
150 |
-
add_vertical_space(1) # Adjust the number of spaces as needed
|
151 |
-
#st.write('Made by [@ThisIs-Developer](https://huggingface.co/ThisIs-Developer)')
|
152 |
-
|
153 |
-
st.title("Nexus AI TCM")
|
154 |
-
|
155 |
-
|
156 |
-
st.markdown(
|
157 |
-
"""
|
158 |
-
<style>
|
159 |
-
.chat-container {
|
160 |
-
display: flex;
|
161 |
-
flex-direction: column;
|
162 |
-
height: 400px;
|
163 |
-
overflow-y: auto;
|
164 |
-
padding: 10px;
|
165 |
-
color: white; /* Font color */
|
166 |
-
}
|
167 |
-
.user-bubble {
|
168 |
-
background-color: #007bff; /* Blue color for user */
|
169 |
-
align-self: flex-end;
|
170 |
-
border-radius: 10px;
|
171 |
-
padding: 8px;
|
172 |
-
margin: 5px;
|
173 |
-
max-width: 70%;
|
174 |
-
word-wrap: break-word;
|
175 |
-
}
|
176 |
-
.bot-bubble {
|
177 |
-
background-color: #363636; /* Slightly lighter background color */
|
178 |
-
align-self: flex-start;
|
179 |
-
border-radius: 10px;
|
180 |
-
padding: 8px;
|
181 |
-
margin: 5px;
|
182 |
-
max-width: 70%;
|
183 |
-
word-wrap: break-word;
|
184 |
-
}
|
185 |
-
</style>
|
186 |
-
"""
|
187 |
-
, unsafe_allow_html=True)
|
188 |
-
|
189 |
-
conversation = st.session_state.get("conversation", [])
|
190 |
-
|
191 |
-
|
192 |
-
if "my_text" not in st.session_state:
|
193 |
-
st.session_state.my_text = ""
|
194 |
-
|
195 |
-
|
196 |
-
st.text_input("Enter text here", key="widget", on_change=submit)
|
197 |
-
query = st.session_state.my_text
|
198 |
-
|
199 |
-
|
200 |
-
if st.button("Ask"):
|
201 |
-
if query:
|
202 |
-
with st.spinner("Processing your question..."): # Display the processing message
|
203 |
-
conversation.append({"role": "user", "message": query})
|
204 |
-
# Call your QA function
|
205 |
-
answer = qa_bot(query, infer_context(query))
|
206 |
-
conversation.append({"role": "bot", "message": answer})
|
207 |
-
st.session_state.conversation = conversation
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
else:
|
213 |
-
st.warning("Please input a question.")
|
214 |
-
#
|
215 |
-
|
216 |
-
|
217 |
-
# Display the conversation history
|
218 |
-
chat_container = st.empty()
|
219 |
-
chat_bubbles = ''.join([f'<div class="{c["role"]}-bubble">{c["message"]}</div>' for c in conversation])
|
220 |
-
chat_container.markdown(f'<div class="chat-container">{chat_bubbles}</div>', unsafe_allow_html=True)
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
def submit():
|
225 |
-
st.session_state.my_text = st.session_state.widget
|
226 |
-
st.session_state.widget = ""
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
def infer_context(query):
|
231 |
-
"""
|
232 |
-
Function to infer context based on the user's query.
|
233 |
-
Modify this function to suit your context detection needs.
|
234 |
-
"""
|
235 |
-
labels = ["TCM","sick","herbs","traditional","nearest clinic","nearest TCM clinic","nearest TCM doctor","near me","nearest to me", "Ointment", "Hong You", "Feng You", "Fengyou", "Po chai pills"]
|
236 |
-
result = classifier(query, labels)
|
237 |
-
predicted_label = result["labels"][0]
|
238 |
-
return predicted_label
|
239 |
-
|
240 |
-
|
241 |
-
if __name__ == "__main__":
|
242 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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