Dorcatz123 commited on
Commit
03fdbbb
·
verified ·
1 Parent(s): 6b26454

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +271 -244
app.py CHANGED
@@ -1,244 +1,271 @@
1
- import gradio as gr
2
- import os
3
- from langchain.chains import create_history_aware_retriever, create_retrieval_chain
4
- from langchain.chains.combine_documents import create_stuff_documents_chain
5
- from langchain_community.vectorstores import FAISS
6
- from langchain_community.chat_message_histories import ChatMessageHistory
7
- from langchain_community.document_loaders import WebBaseLoader
8
- from langchain_core.chat_history import BaseChatMessageHistory
9
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
10
- from langchain_core.runnables.history import RunnableWithMessageHistory
11
- from langchain_openai import ChatOpenAI, OpenAIEmbeddings
12
- from langchain_text_splitters import RecursiveCharacterTextSplitter
13
- import pandas as pd
14
- from getpass import getpass
15
- from huggingface_hub import hf_hub_download
16
-
17
- # Download the faiss_index folder from Hugging Face
18
- faiss_index_path = hf_hub_download(
19
- repo_id="Dorcatz123/Cancer_Researcher_AI", # Your Hugging Face Space repo ID
20
- filename="faiss_index", # Folder name in the repo
21
- repo_type="space", # Set this to "space" for a Hugging Face Space
22
- use_auth_token=True # If your repo is private, this ensures authentication
23
- )
24
-
25
- # Load the FAISS index (Adjust path if necessary)
26
- index_path = os.path.join(faiss_index_path, "faiss_index") # Path to the downloaded folder
27
- import faiss
28
- index = faiss.read_index(index_path)
29
-
30
-
31
-
32
- try:
33
- if api:
34
- set_key('.env', 'OPENAI_API_KEY', api)
35
- except Exception as e:
36
- return f"❌ Error: {str(e)}"
37
-
38
- load_dotenv()
39
- dir_path = os.path.dirname(os.path.realpath(__file__))
40
- csv_file_path = os.path.join(dir_path, 'Final_Stacked_Data_without_Duplicates.csv')
41
- df = pd.read_csv(csv_file_path)
42
- df = df.drop(['Unnamed: 0'], axis=1)
43
-
44
- # Combine relevant columns of df 'Title', 'Authors', 'Published', 'Journal', 'Abstract', 'Link' into a single row
45
- df['combined'] = df.apply(
46
- lambda row: f"Title: {row['Title']}\n"
47
- f"Authors: {row['Authors']}\n"
48
- f"Abstract: {row['Abstract']}\n"
49
- f"Link: {row['Link']}\n",
50
- axis=1
51
- )
52
-
53
- # Strip spaces
54
- df['combined'] = df['combined'].str.strip()
55
-
56
- # Check the combined data
57
- # print("Combined Data Example:\n", df['combined'].head())
58
-
59
-
60
- # Ask for the OpenAI API key if not already set
61
- print('''
62
- .d8888b. 8888888b. 888 d8888 8888888
63
- d88P Y88b 888 Y88b 888 d88888 888
64
- 888 888 888 888 888 d88P888 888
65
- 888 8888b. 88888b. .d8888b .d88b. 888d888 888 d88P .d88b. .d8888b .d88b. 8888b. 888d888 .d8888b 88888b. .d88b. 888d888 d88P 888 888
66
- 888 "88b 888 "88b d88P" d8P Y8b 888P" 8888888P" d8P Y8b 88K d8P Y8b "88b 888P" d88P" 888 "88b d8P Y8b 888P" d88P 888 888
67
- 888 888 .d888888 888 888 888 88888888 888 888 T88b 88888888 "Y8888b. 88888888 .d888888 888 888 888 888 88888888 888 d88P 888 888
68
- Y88b d88P 888 888 888 888 Y88b. Y8b. 888 888 T88b Y8b. X88 Y8b. 888 888 888 Y88b. 888 888 Y8b. 888 d8888888888 888
69
- "Y8888P" "Y888888 888 888 "Y8888P "Y8888 888 888 T88b "Y8888 88888P' "Y8888 "Y888888 888 "Y8888P 888 888 "Y8888 888 d88P 888 8888888 ''')
70
-
71
- print("\n\n Hi there! Thank you for reaching out to me!\n\n")
72
-
73
- # LLM
74
- llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
75
-
76
- # Initialize OpenAI embeddings
77
- embeddings = OpenAIEmbeddings()
78
-
79
- # Convert the combined text into a list
80
- documents = df['combined'].tolist()
81
-
82
- # Create FAISS vector store with the embeddings
83
- if os.path.exists(f"{dir_path}/faiss_index"):
84
- vector_store = FAISS.load_local(f"{dir_path}/faiss_index", embeddings, allow_dangerous_deserialization=True)
85
- retriever = vector_store.as_retriever(search_kwargs={"k": 5})
86
- else:
87
- vector_store = FAISS.from_texts(documents, embeddings)
88
- vector_store.save_local(f"{dir_path}/faiss_index")
89
- retriever = vector_store.as_retriever(search_kwargs={"k": 5})
90
-
91
- # Contextualize question
92
- contextualize_q_system_prompt = (
93
- "Given a chat history and the latest user question "
94
- "which might reference context in the chat history, "
95
- "formulate a standalone question which can be understood "
96
- "without the chat history. Do NOT answer the question, "
97
- "just reformulate it if needed and otherwise return it as is."
98
- )
99
- contextualize_q_prompt = ChatPromptTemplate.from_messages(
100
- [
101
- ("system", contextualize_q_system_prompt),
102
- MessagesPlaceholder("chat_history"),
103
- ("human", "{input}"),
104
- ]
105
- )
106
- history_aware_retriever = create_history_aware_retriever(
107
- llm, retriever, contextualize_q_prompt
108
- )
109
-
110
- # Answer question
111
- system_prompt = (
112
- '''You are a cancer research assistant. When the user asks about a specific type of cancer (e.g., brain tumor), you should:
113
- 1. First explain the concept or type of cancer briefly.
114
- 2. Provide at least 5 relevant links to papers related to that cancer from the available dataset. If not, provide however many there are.
115
-
116
- Question: {input}
117
- Context: {context}
118
-
119
- Output:
120
- 1. Brief Explanation:
121
- 2. Relevant Research Papers (with links):
122
-
123
- If the user asks for summaries or explanations of papers that you provided, you should look at the list of papers you provided for the previous question and summarize what is required.
124
- If the user's question is not related to cancer, do not try to find similarities, just say, "I don't know."
125
- '''
126
- )
127
- qa_prompt = ChatPromptTemplate.from_messages(
128
- [
129
- ("system", system_prompt),
130
- MessagesPlaceholder("chat_history"),
131
- ("human", "{input}"),
132
- ]
133
- )
134
- question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
135
-
136
- rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
137
-
138
- # Statefully manage chat history
139
- store = {}
140
-
141
-
142
- def get_session_history(session_id: str) -> BaseChatMessageHistory:
143
- if session_id not in store:
144
- store[session_id] = ChatMessageHistory()
145
- return store[session_id]
146
-
147
-
148
- conversational_rag_chain = RunnableWithMessageHistory(
149
- rag_chain,
150
- get_session_history,
151
- input_messages_key="input",
152
- history_messages_key="chat_history",
153
- output_messages_key="answer",
154
- )
155
-
156
-
157
- # Interactive Loop
158
- # user_input = input("\nAsk a cancer-related question (or type 'exit' to quit): ")
159
- #
160
- # if user_input.lower() == 'exit':
161
- # print("Exiting the interactive question loop.")
162
- # break
163
- #
164
- # response = conversational_rag_chain.invoke(
165
- # {"input": user_input},
166
- # config={"configurable": {"session_id": session_id}}
167
- # )["answer"]
168
- #
169
- # print("\nResponse:")
170
- # print(response)
171
-
172
-
173
- def ask_cancer_question(question, session_id="user_session"):
174
- if question.lower() == "exit":
175
- return "Exiting the interactive question loop."
176
-
177
- response = conversational_rag_chain.invoke(
178
- {"input": question},
179
- config={"configurable": {"session_id": session_id}}
180
- )["answer"]
181
-
182
- return response
183
-
184
-
185
- def interactive_chat():
186
- session_id = "user_session"
187
- chat_history = ""
188
-
189
- def chat_loop(question):
190
- nonlocal chat_history
191
- if question.lower() == "exit":
192
- return chat_history + "\nExiting the interactive question loop."
193
- response = ask_cancer_question(question, session_id)
194
- chat_history += f"\nUser: {question}\nBot: {response}"
195
- return chat_history
196
-
197
- return chat_loop
198
-
199
-
200
- demo = gr.Interface(
201
- fn=chatbot(),
202
- inputs=[gr.Textbox(lines=2, placeholder="Ask a cancer-related question...", elem_id="query_input")],
203
- outputs=gr.Textbox(lines=10, elem_id="Output"),
204
- title="Cancer Research Chatbot",
205
- description="Ask cancer-related questions and receive responses based on relevant research."
206
- )
207
-
208
-
209
-
210
- title="Mini GPT Researcher",
211
-
212
- # Custom CSS to style the input boxes
213
- demo.css = """
214
- #query_input{
215
- border: 2px solid #FFA500; /* Orange border color */
216
- border-radius: 8px; /* Rounded corners */
217
- padding: 10px; /* Padding inside the input box */
218
- margin-bottom: 20px; /* Space below the input box */
219
- transition: border-color 0.3s ease, background-color 0.3s ease; /* Smooth transition */
220
- background-color: #FFEB3B; /* Orange background color */
221
- }
222
- #query_input:focus{
223
- border-color: #1E90FF; /* Blue border color on focus */
224
- background-color: #87CEFA; /* Light blue background color on focus */
225
- }
226
- #query_inputs
227
- background-color: #FFEB3B; /* Orange background color */
228
- }
229
- #Output {
230
- border: 2px solid #1E90FF; /* Blue border color */
231
- border-radius: 8px; /* Rounded corners */
232
- padding: 10px; /* Padding inside the output box */
233
- background-color: #FFEB3B; /* Light blue background color */
234
- margin-top: 20px; /* Space above the output box */
235
- font-size: 16px; /* Font size for readability */
236
- }
237
- """
238
-
239
- # Launch the app
240
- if __name__ == '__main__':
241
- demo.launch()
242
-
243
-
244
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from langchain.chains import create_history_aware_retriever, create_retrieval_chain
4
+ from langchain.chains.combine_documents import create_stuff_documents_chain
5
+ from langchain_community.vectorstores import FAISS
6
+ from langchain_community.chat_message_histories import ChatMessageHistory
7
+ from langchain_community.document_loaders import WebBaseLoader
8
+ from langchain_core.chat_history import BaseChatMessageHistory
9
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
10
+ from langchain_core.runnables.history import RunnableWithMessageHistory
11
+ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
12
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
13
+ import pandas as pd
14
+ from getpass import getpass
15
+ from huggingface_hub import hf_hub_download
16
+
17
+ # Download the faiss_index folder from Hugging Face
18
+ faiss_index_path = hf_hub_download(
19
+ repo_id="Dorcatz123/Cancer_Researcher_AI", # Your Hugging Face Space repo ID
20
+ filename="faiss_index", # Folder name in the repo
21
+ repo_type="space", # Set this to "space" for a Hugging Face Space
22
+ use_auth_token=True # If your repo is private, this ensures authentication
23
+ )
24
+
25
+ # Load the FAISS index (Adjust path if necessary)
26
+ index_path = os.path.join(faiss_index_path, "faiss_index") # Path to the downloaded folder
27
+ import faiss
28
+ index = faiss.read_index(index_path)
29
+
30
+
31
+
32
+ try:
33
+ if api:
34
+ set_key('.env', 'OPENAI_API_KEY', api)
35
+ except Exception as e:
36
+ return f"❌ Error: {str(e)}"
37
+
38
+ load_dotenv()
39
+ dir_path = os.path.dirname(os.path.realpath(__file__))
40
+ csv_file_path = os.path.join(dir_path, 'Final_Stacked_Data_without_Duplicates.csv')
41
+ df = pd.read_csv(csv_file_path)
42
+ df = df.drop(['Unnamed: 0'], axis=1)
43
+
44
+ # Combine relevant columns of df 'Title', 'Authors', 'Published', 'Journal', 'Abstract', 'Link' into a single row
45
+ df['combined'] = df.apply(
46
+ lambda row: f"Title: {row['Title']}\n"
47
+ f"Authors: {row['Authors']}\n"
48
+ f"Abstract: {row['Abstract']}\n"
49
+ f"Link: {row['Link']}\n",
50
+ axis=1
51
+ )
52
+
53
+ # Strip spaces
54
+ df['combined'] = df['combined'].str.strip()
55
+
56
+ # Check the combined data
57
+ # print("Combined Data Example:\n", df['combined'].head())
58
+
59
+
60
+ # Ask for the OpenAI API key if not already set
61
+ print('''
62
+ .d8888b. 8888888b. 888 d8888 8888888
63
+ d88P Y88b 888 Y88b 888 d88888 888
64
+ 888 888 888 888 888 d88P888 888
65
+ 888 8888b. 88888b. .d8888b .d88b. 888d888 888 d88P .d88b. .d8888b .d88b. 8888b. 888d888 .d8888b 88888b. .d88b. 888d888 d88P 888 888
66
+ 888 "88b 888 "88b d88P" d8P Y8b 888P" 8888888P" d8P Y8b 88K d8P Y8b "88b 888P" d88P" 888 "88b d8P Y8b 888P" d88P 888 888
67
+ 888 888 .d888888 888 888 888 88888888 888 888 T88b 88888888 "Y8888b. 88888888 .d888888 888 888 888 888 88888888 888 d88P 888 888
68
+ Y88b d88P 888 888 888 888 Y88b. Y8b. 888 888 T88b Y8b. X88 Y8b. 888 888 888 Y88b. 888 888 Y8b. 888 d8888888888 888
69
+ "Y8888P" "Y888888 888 888 "Y8888P "Y8888 888 888 T88b "Y8888 88888P' "Y8888 "Y888888 888 "Y8888P 888 888 "Y8888 888 d88P 888 8888888 ''')
70
+
71
+ print("\n\n Hi there! Thank you for reaching out to me!\n\n")
72
+
73
+ # LLM
74
+ llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
75
+
76
+ # Initialize OpenAI embeddings
77
+ embeddings = OpenAIEmbeddings()
78
+
79
+ # Convert the combined text into a list
80
+ documents = df['combined'].tolist()
81
+
82
+ # Create FAISS vector store with the embeddings
83
+ if os.path.exists(f"{dir_path}/faiss_index"):
84
+ vector_store = FAISS.load_local(f"{dir_path}/faiss_index", embeddings, allow_dangerous_deserialization=True)
85
+ retriever = vector_store.as_retriever(search_kwargs={"k": 5})
86
+ else:
87
+ vector_store = FAISS.from_texts(documents, embeddings)
88
+ vector_store.save_local(f"{dir_path}/faiss_index")
89
+ retriever = vector_store.as_retriever(search_kwargs={"k": 5})
90
+
91
+ # Contextualize question
92
+ contextualize_q_system_prompt = (
93
+ "Given a chat history and the latest user question "
94
+ "which might reference context in the chat history, "
95
+ "formulate a standalone question which can be understood "
96
+ "without the chat history. Do NOT answer the question, "
97
+ "just reformulate it if needed and otherwise return it as is."
98
+ )
99
+ contextualize_q_prompt = ChatPromptTemplate.from_messages(
100
+ [
101
+ ("system", contextualize_q_system_prompt),
102
+ MessagesPlaceholder("chat_history"),
103
+ ("human", "{input}"),
104
+ ]
105
+ )
106
+ history_aware_retriever = create_history_aware_retriever(
107
+ llm, retriever, contextualize_q_prompt
108
+ )
109
+
110
+ # Answer question
111
+ system_prompt = (
112
+ '''You are a cancer research assistant. When the user asks about a specific type of cancer (e.g., brain tumor), you should:
113
+ 1. First explain the concept or type of cancer briefly.
114
+ 2. Provide at least 5 relevant links to papers related to that cancer from the available dataset. If not, provide however many there are.
115
+
116
+ Question: {input}
117
+ Context: {context}
118
+
119
+ Output:
120
+ 1. Brief Explanation:
121
+ 2. Relevant Research Papers (with links):
122
+
123
+ If the user asks for summaries or explanations of papers that you provided, you should look at the list of papers you provided for the previous question and summarize what is required.
124
+ If the user's question is not related to cancer, do not try to find similarities, just say, "I don't know."
125
+ '''
126
+ )
127
+ qa_prompt = ChatPromptTemplate.from_messages(
128
+ [
129
+ ("system", system_prompt),
130
+ MessagesPlaceholder("chat_history"),
131
+ ("human", "{input}"),
132
+ ]
133
+ )
134
+ question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
135
+
136
+ rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
137
+
138
+ # Statefully manage chat history
139
+ store = {}
140
+
141
+
142
+ def get_session_history(session_id: str) -> BaseChatMessageHistory:
143
+ if session_id not in store:
144
+ store[session_id] = ChatMessageHistory()
145
+ return store[session_id]
146
+
147
+
148
+ conversational_rag_chain = RunnableWithMessageHistory(
149
+ rag_chain,
150
+ get_session_history,
151
+ input_messages_key="input",
152
+ history_messages_key="chat_history",
153
+ output_messages_key="answer",
154
+ )
155
+
156
+
157
+ # Interactive Loop
158
+ # user_input = input("\nAsk a cancer-related question (or type 'exit' to quit): ")
159
+ #
160
+ # if user_input.lower() == 'exit':
161
+ # print("Exiting the interactive question loop.")
162
+ # break
163
+ #
164
+ # response = conversational_rag_chain.invoke(
165
+ # {"input": user_input},
166
+ # config={"configurable": {"session_id": session_id}}
167
+ # )["answer"]
168
+ #
169
+ # print("\nResponse:")
170
+ # print(response)
171
+
172
+
173
+ def ask_cancer_question(question, session_id="user_session"):
174
+ if question.lower() == "exit":
175
+ return "Exiting the interactive question loop."
176
+
177
+ response = conversational_rag_chain.invoke(
178
+ {"input": question},
179
+ config={"configurable": {"session_id": session_id}}
180
+ )["answer"]
181
+
182
+ return response
183
+
184
+
185
+ # def interactive_chat():
186
+ # session_id = "user_session"
187
+ # chat_history = ""
188
+
189
+ # def chat_loop(question):
190
+ # nonlocal chat_history
191
+ # if question.lower() == "exit":
192
+ # return chat_history + "\nExiting the interactive question loop."
193
+ # response = ask_cancer_question(question, session_id)
194
+ # chat_history += f"\nUser: {question}\nBot: {response}"
195
+ # return chat_history
196
+
197
+ # return chat_loop
198
+
199
+ def interactive_chat(question):
200
+ session_id = "user_session"
201
+ chat_history = ""
202
+
203
+ # Inside chat_loop
204
+ if question.lower() == "exit":
205
+ return chat_history + "\nExiting the interactive question loop."
206
+
207
+ response = ask_cancer_question(question, session_id)
208
+ chat_history += f"\nUser: {question}\nBot: {response}"
209
+ return chat_history
210
+
211
+ demo = gr.Interface(
212
+ fn=chatbot(),
213
+ inputs=[gr.Textbox(lines=2, placeholder="Ask a cancer-related question...", elem_id="query_input")],
214
+ outputs=gr.Textbox(lines=10, elem_id="Output"),
215
+ title="Cancer Research Chatbot",
216
+ description="Ask cancer-related questions and receive responses based on relevant research."
217
+ )
218
+
219
+
220
+
221
+ title="Cancer_Researcher_AI",
222
+
223
+ # Custom CSS to style the input boxes
224
+ demo.css = """
225
+ #query_input {
226
+ border: 2px solid #4CAF50; /* Green border for a medical feel */
227
+ border-radius: 8px; /* Rounded corners */
228
+ padding: 12px; /* Slightly more padding */
229
+ margin-bottom: 20px; /* Space below the input box */
230
+ transition: border-color 0.3s ease, background-color 0.3s ease; /* Smooth transition */
231
+ background-color: #E8F5E9; /* Light green background for a soothing medical look */
232
+ font-size: 14px; /* Slightly smaller font for input */
233
+ }
234
+
235
+ #query_input:focus {
236
+ border-color: #66BB6A; /* Darker green when focused */
237
+ background-color: #C8E6C9; /* Slightly darker green background on focus */
238
+ }
239
+
240
+ #query_inputs {
241
+ background-color: #E8F5E9; /* Light green background */
242
+ }
243
+
244
+ #Output {
245
+ border: 2px solid #2196F3; /* Blue border to indicate information */
246
+ border-radius: 8px; /* Rounded corners */
247
+ padding: 15px; /* Added padding inside the output box */
248
+ background-color: #E3F2FD; /* Light blue background for readability */
249
+ margin-top: 20px; /* Space above the output box */
250
+ font-size: 16px; /* Font size for readability */
251
+ font-family: Arial, sans-serif; /* Use a clean font for scientific feel */
252
+ color: #1E88E5; /* Blue text for contrast */
253
+ line-height: 1.5; /* Improve readability */
254
+ }
255
+
256
+ /* Optional: Adding some styling for the chatbot header (title) */
257
+ #title {
258
+ font-size: 22px;
259
+ font-weight: bold;
260
+ color: #1E88E5; /* Blue for a professional, clean look */
261
+ margin-bottom: 15px;
262
+ }
263
+ """
264
+
265
+
266
+ # Launch the app
267
+ if __name__ == '__main__':
268
+ demo.launch()
269
+
270
+
271
+