GoodML commited on
Commit
e444da0
·
verified ·
1 Parent(s): c5ccc09

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +224 -0
app.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+
4
+ import time
5
+ import dotenv
6
+ import streamlit as st
7
+ from langchain_core.messages import HumanMessage, AIMessage
8
+ from dotenv import load_dotenv
9
+
10
+
11
+ from langchain_core.prompts import PromptTemplate
12
+ from langchain.chains import RetrievalQA
13
+ from langchain_community.embeddings import HuggingFaceEmbeddings
14
+ from langchain_community.vectorstores import Pinecone
15
+
16
+
17
+ import pinecone
18
+ from langchain_community.document_loaders import PyPDFLoader, DirectoryLoader
19
+
20
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
21
+ from langchain_core.prompts import PromptTemplate
22
+ from langchain_community.llms import CTransformers
23
+
24
+
25
+
26
+ load_dotenv()
27
+ st.set_page_config(page_title= "Medical chatbot", page_icon=":bot:")
28
+
29
+ if "chat_history" not in st.session_state:
30
+ st.session_state.chat_history = []
31
+
32
+ PINECONE_API_KEY = "1bae0d8e-019e-4e87-8080-ecf523e5f25f"
33
+ def get_response(user_query):
34
+ # Initilize the prompt
35
+ # create prompt template, integrate chatHistory component as well
36
+ prompt_template = """
37
+ Use the following pieces of information to answer the user's question.
38
+ If you don't know the answer, just say that you don't know, don't try to make up an answer.
39
+
40
+ Context: {context}
41
+ Question: {question}
42
+
43
+ Only return the helpful answer below nothing else.
44
+ Helpful Answer:
45
+ """
46
+
47
+ PROMPT = PromptTemplate(template = prompt_template, input_variables=["context", "question"])
48
+ chain_type_kwargs = {"prompt":PROMPT}
49
+
50
+ llm = CTransformers(model="TheBloke/Llama-2-7B-Chat-GGML", model_type="llama", config={'max_new_tokens': 1024, 'temperature': 1})
51
+
52
+ index_name = "medical-chatbot"
53
+ index=pinecone.Index(api_key=PINECONE_API_KEY, host="https://medical-chatbot-pv4ded8.svc.aped-4627-b74a.pinecone.io")
54
+
55
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
56
+ # Create Pinecone retriever
57
+ vector_store = Pinecone(index, embeddings, text_key="text")
58
+
59
+
60
+ qa = RetrievalQA.from_chain_type(llm, chain_type="stuff",retriever = vector_store.as_retriever(search_kwargs={"k": 2}), chain_type_kwargs=chain_type_kwargs)
61
+ answer = qa.invoke({"query":user_query, "context": st.session_state.chat_history})
62
+
63
+ return answer
64
+ # answer = vector_store.similarity_search(user_query, k=3)
65
+ # return answer.stream().get("answer")
66
+
67
+ # Function to simulate typing effect
68
+ def type_effect(text):
69
+ for char in text:
70
+ st.write(char)
71
+ time.sleep(0.05)
72
+ st.write("")
73
+
74
+
75
+ st.title("Medical chatbot")
76
+
77
+ st.write("Welcome to the medical chatbot. Please enter your symptoms below and I will try to help you.")
78
+
79
+ if "chat_history" in st.session_state:
80
+ for message in st.session_state.chat_history:
81
+ if "user" in message:
82
+ with st.chat_message("Human"):
83
+ st.markdown(message["user"])
84
+ elif "bot" in message:
85
+ with st.chat_message("AI"):
86
+ st.markdown(message["bot"])
87
+
88
+ user_query = st.chat_input("Enter your symptoms here")
89
+ if user_query is not None and user_query != "":
90
+
91
+
92
+ with st.chat_message("Human"):
93
+ st.markdown(user_query)
94
+ st.session_state.chat_history.append({"user": user_query})
95
+
96
+ with st.chat_message("AI"):
97
+ # =""
98
+ # for message in st.session_state.chat_history:
99
+ # if "user" in message:
100
+ # += f"User: {message['user']}\n"
101
+ # elif "bot" in message:
102
+ # += f"Bot: {message['bot']}\n"
103
+
104
+ ai_response = get_response(user_query)
105
+ # st.write(type(ai_response))
106
+ result = ai_response["result"]
107
+ # type_effect(result)
108
+ st.markdown(result)
109
+
110
+ # Get the response from backend and present it here
111
+ st.session_state.chat_history.append({"bot": result})
112
+
113
+
114
+
115
+ # import os
116
+ # import time
117
+ # import dotenv
118
+ # import streamlit as st
119
+ # from dotenv import load_dotenv
120
+
121
+ # from langchain import PromptTemplate
122
+ # from langchain.chains import RetrievalQA
123
+ # from langchain.embeddings import HuggingFaceEmbeddings
124
+ # from langchain.vectorstores import Pinecone
125
+
126
+ # import pinecone
127
+ # from langchain.llms import CTransformers
128
+
129
+ # # Load environment variables
130
+ # load_dotenv()
131
+
132
+ # # Initialize Streamlit page config
133
+ # st.set_page_config(page_title="Medical Chatbot", page_icon=":bot:")
134
+
135
+ # # Initialize chat history in session state
136
+ # if "chat_history" not in st.session_state:
137
+ # st.session_state.chat_history = []
138
+
139
+ # PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
140
+ # HUGGING_FACE_TOKEN = os.getenv("HUGGING_FACE_TOKEN")
141
+
142
+ # # Cache models and vector store initialization
143
+ # embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
144
+ # @st.cache_resource
145
+ # def initialize_models():
146
+ # # Load language model
147
+
148
+ # llm = CTransformers(model="model/llama-2-7b-chat.ggmlv3.q4_0.bin", model_type="llama", config={'max_new_tokens': 1024, 'temperature': 1})
149
+
150
+
151
+ # # Initialize Pinecone index
152
+ # index = pinecone.Index(api_key=PINECONE_API_KEY, host="https://medical-chatbot-pv4ded8.svc.aped-4627-b74a.pinecone.io")
153
+
154
+ # # Initialize embeddings
155
+
156
+ # # Create Pinecone retriever
157
+ # vector_store = Pinecone(index, embeddings, text_key="text")
158
+
159
+ # return llm, vector_store
160
+
161
+ # llm, vector_store = initialize_models()
162
+
163
+ # # Define prompt template
164
+ # prompt_template = """
165
+ # Use the following pieces of information to answer the user's question.
166
+ # If you don't know the answer, just say that I don't know, don't try to make up an answer.
167
+
168
+ # Context: {context}
169
+ # Question: {question}
170
+
171
+ # Only return the helpful answer below nothing else.
172
+ # Helpful Answer:
173
+ # """
174
+ # PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
175
+
176
+ # # Cache QA chain initialization
177
+ # @st.cache_resource
178
+ # def _initialize_qa(_llm, _vector_store):
179
+ # return RetrievalQA.from_chain_type(
180
+ # _llm,
181
+ # chain_type="stuff",
182
+ # retriever=_vector_store.as_retriever(search_kwargs={"k": 2}),
183
+ # chain_type_kwargs={"prompt": PROMPT}
184
+ # )
185
+
186
+ # qa = _initialize_qa(llm, vector_store)
187
+
188
+ # def get_response(user_query):
189
+ # # chat_context = "\n".join([f"User: {msg['user']}" if 'user' in msg else f"Bot: {msg['bot']}" for msg in st.session_state.chat_history])
190
+ # answer = qa.invoke({"query": user_query, "context": st.session_state.chat_history})
191
+ # return answer
192
+
193
+ # # Function to simulate typing effect
194
+ # # def type_effect(text):
195
+ # # for char in text:
196
+ # # st.write(char, end="")
197
+ # # time.sleep(0.05)
198
+ # # st.write("")
199
+
200
+ # # Streamlit UI
201
+ # st.title("Medical Chatbot")
202
+ # st.write("Welcome to the medical chatbot. Please enter your symptoms below and I will try to help you.")
203
+
204
+ # # Display chat history
205
+ # for message in st.session_state.chat_history:
206
+ # if "user" in message:
207
+ # with st.chat_message("Human"):
208
+ # st.markdown(message["user"])
209
+ # elif "bot" in message:
210
+ # with st.chat_message("AI"):
211
+ # st.markdown(message["bot"])
212
+
213
+ # # Chat input and response handling
214
+ # user_query = st.chat_input("Enter your symptoms here")
215
+ # if user_query:
216
+ # with st.chat_message("Human"):
217
+ # st.markdown(user_query)
218
+ # st.session_state.chat_history.append({"user": user_query})
219
+
220
+ # with st.chat_message("AI"):
221
+ # ai_response = get_response(user_query)
222
+ # result = ai_response["result"]
223
+ # st.markdown(result)
224
+ # st.session_state.chat_history.append({"bot": result})