sahilursa commited on
Commit
b14547c
Β·
verified Β·
1 Parent(s): 2bcde99

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +218 -84
app.py CHANGED
@@ -8,88 +8,147 @@ import pickle
8
  import os
9
 
10
  # Step 2: Configure API Key from Hugging Face Secrets
 
 
 
11
  try:
12
  GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
13
  if GOOGLE_API_KEY is None:
14
- raise ValueError("GOOGLE_API_KEY not found in environment variables.")
15
- genai.configure(api_key=GOOGLE_API_KEY)
16
- print("API Key configured successfully.")
 
 
 
17
  except Exception as e:
18
- print(f"ERROR: Could not configure API key. Please ensure 'GOOGLE_API_KEY' is set in your Hugging Face Space secrets. Details: {e}")
 
19
 
20
  # Step 3: Define Data Path
21
  DATA_PATH = "data"
22
  vector_store_file = os.path.join(DATA_PATH, "vector_store.index")
23
  data_file = os.path.join(DATA_PATH, "data.pkl")
24
 
25
- # Step 4: Load Models and Pre-processed Data
26
  vector_store_data = None
 
 
 
 
 
 
 
27
  if os.path.exists(vector_store_file) and os.path.exists(data_file):
28
  try:
29
  print(f"Loading pre-processed data from the '{DATA_PATH}' directory...")
 
 
30
  index = faiss.read_index(vector_store_file)
 
 
31
  with open(data_file, "rb") as f:
32
  stored_data = pickle.load(f)
33
- texts = stored_data["texts"]
34
- sources = stored_data["sources"]
35
- print("βœ… Data loaded successfully.")
36
-
37
- vector_store_data = (index, texts, sources)
38
-
39
- print("Loading AI and embedding models...")
40
  embedding_model = SentenceTransformer('BAAI/bge-large-en-v1.5')
41
- llm = genai.GenerativeModel('gemini-1.5-flash-latest')
42
- print("βœ… Models loaded successfully.")
43
-
 
 
 
 
 
 
 
 
44
  except Exception as e:
45
  print(f"❌ ERROR: An error occurred during data or model loading: {e}")
 
 
46
  vector_store_data = None
47
  else:
48
  print(f"❌ ERROR: Pre-processed data not found in the '{DATA_PATH}' directory.")
49
  print(f"Please make sure '{vector_store_file}' and '{data_file}' exist.")
50
-
 
 
 
51
 
52
  # Step 5: RAG and Chat Functions (with Updated System Prompt)
53
- def get_relevant_context(query, index, top_k=5):
54
- query_embedding = embedding_model.encode([query])
55
- distances, indices = index.search(query_embedding, top_k)
56
- context = []
57
- for i in indices[0]:
58
- if i < len(texts):
59
- context.append({"text": texts[i], "source": sources[i]})
60
- return context
 
 
 
 
 
 
 
 
61
 
62
  def chat_with_rag(message, history, vector_store_data):
63
- index, texts, sources = vector_store_data
64
- relevant_context = get_relevant_context(message, index)
65
- context_str = "\n\n".join([f"Source: {c['source']}\nContent: {c['text']}" for c in relevant_context])
66
-
67
- # --- NEW, ROBUST SYSTEM PROMPT ---
68
- prompt = f"""
69
- You are a friendly and engaging science communicator for the Halassa Lab at MIT.
70
- Your goal is to explain the lab's complex computational neuroscience research to a general audience that has little to no scientific background.
71
-
72
- Follow these rules strictly:
73
- 1. **Simplify, Don't Dumb Down:** Break down complex topics into simple, easy-to-understand concepts. Use analogies and real-world examples (e.g., "think of the thalamus as a busy switchboard operator for the brain").
74
- 2. **Be Engaging and Accessible:** Write in a clear, conversational, and friendly tone. Avoid jargon at all costs. If you must use a technical term, explain it immediately in simple terms.
75
- 3. **Synthesize and Explain:** Do not just copy-paste from the provided research papers. Read the relevant context and formulate a comprehensive, well-written answer in your own words.
76
- 4. **Cite Your Sources:** At the end of your response, if you used information from the provided papers, you MUST include a "Sources:" list. Use the format [filename - Page X]. This adds credibility.
77
- 5. **Stay Focused:** Only answer questions related to the Halassa Lab's work based on the provided context. If the context doesn't contain the answer, state that the information isn't available in the provided documents.
78
-
79
- Context from the Halassa Lab's papers:
80
- ---
81
- {context_str}
82
- ---
83
-
84
- User Question: {message}
85
-
86
- Your Friendly Explanation:
87
- """
88
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  response = llm.generate_content(prompt)
90
  return response.text
 
91
  except Exception as e:
92
- return f"An error occurred with the AI model: {str(e)}"
 
 
 
 
93
 
94
  # Step 6: Polished Gradio User Interface
95
  # Define a professional, clean theme for a science lab
@@ -117,44 +176,119 @@ example_questions = [
117
  "Explain the role of the thalamic reticular nucleus like I'm a high school student.",
118
  ]
119
 
120
- with gr.Blocks(theme=theme, title="Halassa Lab AI Explainer") as demo:
121
- with gr.Column():
122
- # --- Header Section ---
123
- gr.Image("https://d39w22sdwnt1s2.cloudfront.net/wp-content/uploads/2023/10/Halassa-M-2023-Option-2-1200x675.jpg", show_label=False, show_download_button=False, container=False)
124
- gr.Markdown("# Hello! ")
125
- gr.Markdown("Ask me anything about the work we do in the Halassa Lab!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
- # --- Chatbot Interface ---
128
- chatbot_ui = gr.Chatbot(label="Conversation", height=500, layout="panel", bubble_full_width=False)
129
- message_box = gr.Textbox(label="Ask your question here...", lines=3, placeholder="e.g., How does the brain filter out distractions?")
130
-
131
- with gr.Row():
132
- submit_button = gr.Button("Submit", variant="primary", scale=2)
133
- clear_button = gr.ClearButton(components=[chatbot_ui, message_box], value="Clear Conversation", scale=1)
134
-
135
- # --- Example Questions Section ---
136
- gr.Examples(
137
- examples=example_questions,
138
- inputs=message_box,
139
- label="Click an example to get started:"
140
- )
 
 
 
 
 
 
141
 
142
- # --- Logic to make the chatbot respond ---
143
- def respond(message, history):
144
- response_text = chat_with_rag(message, history, vector_store_data)
145
- history.append((message, response_text))
146
- return "", history
 
147
 
148
- submit_button.click(respond, inputs=[message_box, chatbot_ui], outputs=[message_box, chatbot_ui])
149
- message_box.submit(respond, inputs=[message_box, chatbot_ui], outputs=[message_box, chatbot_ui])
 
 
 
 
 
 
 
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  # Step 7: Launch the app
153
- if vector_store_data:
154
- demo.launch()
155
- else:
156
- # Display a clear error message in the UI if data loading failed
157
- with gr.Blocks() as demo:
158
- gr.Markdown("## ⚠️ Application Error")
159
- gr.Markdown("Could not load the necessary data and models. Please check the Hugging Face Space logs for details. This may be due to missing data files or an incorrect API key.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  demo.launch()
 
8
  import os
9
 
10
  # Step 2: Configure API Key from Hugging Face Secrets
11
+ GOOGLE_API_KEY = None
12
+ api_configured = False
13
+
14
  try:
15
  GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
16
  if GOOGLE_API_KEY is None:
17
+ print("WARNING: GOOGLE_API_KEY not found in environment variables.")
18
+ print("Please add it to your Hugging Face Space secrets.")
19
+ else:
20
+ genai.configure(api_key=GOOGLE_API_KEY)
21
+ api_configured = True
22
+ print("βœ… API Key configured successfully.")
23
  except Exception as e:
24
+ print(f"ERROR: Could not configure API key. Details: {e}")
25
+ api_configured = False
26
 
27
  # Step 3: Define Data Path
28
  DATA_PATH = "data"
29
  vector_store_file = os.path.join(DATA_PATH, "vector_store.index")
30
  data_file = os.path.join(DATA_PATH, "data.pkl")
31
 
32
+ # Step 4: Initialize variables
33
  vector_store_data = None
34
+ embedding_model = None
35
+ llm = None
36
+ texts = []
37
+ sources = []
38
+ index = None
39
+
40
+ # Step 4: Load Models and Pre-processed Data
41
  if os.path.exists(vector_store_file) and os.path.exists(data_file):
42
  try:
43
  print(f"Loading pre-processed data from the '{DATA_PATH}' directory...")
44
+
45
+ # Load FAISS index
46
  index = faiss.read_index(vector_store_file)
47
+
48
+ # Load texts and sources
49
  with open(data_file, "rb") as f:
50
  stored_data = pickle.load(f)
51
+ texts = stored_data.get("texts", [])
52
+ sources = stored_data.get("sources", [])
53
+
54
+ print(f"βœ… Data loaded successfully. Found {len(texts)} text chunks.")
55
+
56
+ # Load embedding model
57
+ print("Loading embedding model...")
58
  embedding_model = SentenceTransformer('BAAI/bge-large-en-v1.5')
59
+ print("βœ… Embedding model loaded successfully.")
60
+
61
+ # Load LLM if API is configured
62
+ if api_configured:
63
+ print("Loading Gemini model...")
64
+ llm = genai.GenerativeModel('gemini-1.5-flash-latest')
65
+ print("βœ… Gemini model loaded successfully.")
66
+ vector_store_data = (index, texts, sources)
67
+ else:
68
+ print("⚠️ Gemini model not loaded due to missing API key.")
69
+
70
  except Exception as e:
71
  print(f"❌ ERROR: An error occurred during data or model loading: {e}")
72
+ import traceback
73
+ traceback.print_exc()
74
  vector_store_data = None
75
  else:
76
  print(f"❌ ERROR: Pre-processed data not found in the '{DATA_PATH}' directory.")
77
  print(f"Please make sure '{vector_store_file}' and '{data_file}' exist.")
78
+ if not os.path.exists(DATA_PATH):
79
+ print(f"The '{DATA_PATH}' directory does not exist.")
80
+ else:
81
+ print(f"Contents of '{DATA_PATH}' directory: {os.listdir(DATA_PATH) if os.path.exists(DATA_PATH) else 'N/A'}")
82
 
83
  # Step 5: RAG and Chat Functions (with Updated System Prompt)
84
+ def get_relevant_context(query, index, texts, sources, top_k=5):
85
+ """Retrieve relevant context from the vector store."""
86
+ if embedding_model is None:
87
+ return []
88
+
89
+ try:
90
+ query_embedding = embedding_model.encode([query])
91
+ distances, indices = index.search(query_embedding, top_k)
92
+ context = []
93
+ for i in indices[0]:
94
+ if 0 <= i < len(texts): # Ensure index is valid
95
+ context.append({"text": texts[i], "source": sources[i]})
96
+ return context
97
+ except Exception as e:
98
+ print(f"Error in get_relevant_context: {e}")
99
+ return []
100
 
101
  def chat_with_rag(message, history, vector_store_data):
102
+ """Generate response using RAG."""
103
+ if vector_store_data is None:
104
+ return "❌ The AI system is not properly initialized. Please check the configuration."
105
+
106
+ if not api_configured or llm is None:
107
+ return "❌ The Google API key is not configured. Please add GOOGLE_API_KEY to your Hugging Face Space secrets."
108
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  try:
110
+ index, texts, sources = vector_store_data
111
+
112
+ # Get relevant context
113
+ relevant_context = get_relevant_context(message, index, texts, sources)
114
+
115
+ if not relevant_context:
116
+ return "I couldn't find relevant information in the Halassa Lab's papers to answer your question. Could you try rephrasing or asking about a different aspect of the lab's research?"
117
+
118
+ context_str = "\n\n".join([f"Source: {c['source']}\nContent: {c['text']}" for c in relevant_context])
119
+
120
+ # System prompt
121
+ prompt = f"""
122
+ You are a friendly and engaging science communicator for the Halassa Lab at MIT.
123
+ Your goal is to explain the lab's complex computational neuroscience research to a general audience that has little to no scientific background.
124
+
125
+ Follow these rules strictly:
126
+ 1. **Simplify, Don't Dumb Down:** Break down complex topics into simple, easy-to-understand concepts. Use analogies and real-world examples (e.g., "think of the thalamus as a busy switchboard operator for the brain").
127
+ 2. **Be Engaging and Accessible:** Write in a clear, conversational, and friendly tone. Avoid jargon at all costs. If you must use a technical term, explain it immediately in simple terms.
128
+ 3. **Synthesize and Explain:** Do not just copy-paste from the provided research papers. Read the relevant context and formulate a comprehensive, well-written answer in your own words.
129
+ 4. **Cite Your Sources:** At the end of your response, if you used information from the provided papers, you MUST include a "Sources:" list. Use the format [filename - Page X]. This adds credibility.
130
+ 5. **Stay Focused:** Only answer questions related to the Halassa Lab's work based on the provided context. If the context doesn't contain the answer, state that the information isn't available in the provided documents.
131
+
132
+ Context from the Halassa Lab's papers:
133
+ ---
134
+ {context_str}
135
+ ---
136
+
137
+ User Question: {message}
138
+
139
+ Your Friendly Explanation:
140
+ """
141
+
142
+ # Generate response
143
  response = llm.generate_content(prompt)
144
  return response.text
145
+
146
  except Exception as e:
147
+ error_msg = f"An error occurred while generating the response: {str(e)}"
148
+ print(error_msg)
149
+ import traceback
150
+ traceback.print_exc()
151
+ return f"❌ {error_msg}"
152
 
153
  # Step 6: Polished Gradio User Interface
154
  # Define a professional, clean theme for a science lab
 
176
  "Explain the role of the thalamic reticular nucleus like I'm a high school student.",
177
  ]
178
 
179
+ # Create the Gradio interface
180
+ def create_demo():
181
+ """Create the Gradio demo interface."""
182
+ with gr.Blocks(theme=theme, title="Halassa Lab AI Explainer") as demo:
183
+ with gr.Column():
184
+ # --- Header Section ---
185
+ try:
186
+ gr.Image(
187
+ "https://d39w22sdwnt1s2.cloudfront.net/wp-content/uploads/2023/10/Halassa-M-2023-Option-2-1200x675.jpg",
188
+ show_label=False,
189
+ show_download_button=False,
190
+ container=False
191
+ )
192
+ except:
193
+ # If image fails to load, continue without it
194
+ pass
195
+
196
+ gr.Markdown("# Hello! πŸ‘‹")
197
+ gr.Markdown("Ask me anything about the work we do in the Halassa Lab!")
198
+
199
+ # Show status
200
+ if vector_store_data is not None and api_configured:
201
+ gr.Markdown("βœ… **System Status:** Ready to answer your questions!")
202
+ elif vector_store_data is not None and not api_configured:
203
+ gr.Markdown("⚠️ **System Status:** Data loaded but Google API key is missing. Please configure it in Space secrets.")
204
+ else:
205
+ gr.Markdown("❌ **System Status:** System not properly initialized. Check logs for details.")
206
 
207
+ # --- Chatbot Interface ---
208
+ chatbot_ui = gr.Chatbot(
209
+ label="Conversation",
210
+ height=500,
211
+ layout="panel",
212
+ bubble_full_width=False
213
+ )
214
+ message_box = gr.Textbox(
215
+ label="Ask your question here...",
216
+ lines=3,
217
+ placeholder="e.g., How does the brain filter out distractions?"
218
+ )
219
+
220
+ with gr.Row():
221
+ submit_button = gr.Button("Submit", variant="primary", scale=2)
222
+ clear_button = gr.ClearButton(
223
+ components=[chatbot_ui, message_box],
224
+ value="Clear Conversation",
225
+ scale=1
226
+ )
227
 
228
+ # --- Example Questions Section ---
229
+ gr.Examples(
230
+ examples=example_questions,
231
+ inputs=message_box,
232
+ label="Click an example to get started:"
233
+ )
234
 
235
+ # --- Logic to make the chatbot respond ---
236
+ def respond(message, history):
237
+ """Handle user messages and generate responses."""
238
+ if not message.strip():
239
+ return "", history
240
+
241
+ response_text = chat_with_rag(message, history, vector_store_data)
242
+ history.append((message, response_text))
243
+ return "", history
244
 
245
+ # Connect event handlers
246
+ submit_button.click(
247
+ respond,
248
+ inputs=[message_box, chatbot_ui],
249
+ outputs=[message_box, chatbot_ui]
250
+ )
251
+ message_box.submit(
252
+ respond,
253
+ inputs=[message_box, chatbot_ui],
254
+ outputs=[message_box, chatbot_ui]
255
+ )
256
+
257
+ return demo
258
 
259
  # Step 7: Launch the app
260
+ if __name__ == "__main__":
261
+ if vector_store_data is not None:
262
+ print("Launching application with full functionality...")
263
+ demo = create_demo()
264
+ else:
265
+ print("Launching application in error mode...")
266
+ # Display a clear error message in the UI if data loading failed
267
+ with gr.Blocks(theme=theme) as demo:
268
+ gr.Markdown("## ⚠️ Application Error")
269
+ gr.Markdown("""
270
+ Could not load the necessary data and models.
271
+
272
+ **Possible issues:**
273
+ 1. Missing data files (`vector_store.index` and `data.pkl` in the `data/` directory)
274
+ 2. Missing or incorrect Google API key in Hugging Face Space secrets
275
+ 3. Model loading errors
276
+
277
+ Please check the Hugging Face Space logs for detailed error messages.
278
+ """)
279
+
280
+ # Show current status
281
+ gr.Markdown("### Debug Information:")
282
+ status_text = []
283
+ status_text.append(f"- Data directory exists: {os.path.exists(DATA_PATH)}")
284
+ status_text.append(f"- Vector store file exists: {os.path.exists(vector_store_file)}")
285
+ status_text.append(f"- Data pickle file exists: {os.path.exists(data_file)}")
286
+ status_text.append(f"- Google API key configured: {api_configured}")
287
+
288
+ if os.path.exists(DATA_PATH):
289
+ files = os.listdir(DATA_PATH)
290
+ status_text.append(f"- Files in data directory: {files if files else 'Empty directory'}")
291
+
292
+ gr.Markdown("\n".join(status_text))
293
+
294
  demo.launch()