ilhianois commited on
Commit
c1b5a16
·
verified ·
1 Parent(s): 999995c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -37
app.py CHANGED
@@ -15,12 +15,16 @@ API_TIMEOUT = 60 # seconds
15
  PROTOCOLS_DIR = Path('./tools/protocols/json-protocols')
16
  PROTOCOLS_DIR.mkdir(parents=True, exist_ok=True) # Add parents=True to create intermediate directories
17
 
 
 
 
 
18
  def create_demo():
19
  # Initialize state
20
  session_id = str(uuid.uuid4())
21
 
22
  def save_protocol(keys, values):
23
- """Save a protocol object to a file with proper formatting"""
24
  try:
25
  # Parse keys and values (one per line)
26
  key_list = [k.strip() for k in keys.split('\n') if k.strip()]
@@ -49,32 +53,41 @@ def create_demo():
49
  # Add creation timestamp
50
  protocol_object['_created_at'] = datetime.now().isoformat()
51
 
52
- # Generate filename using timestamp and first key-value pair
53
- first_key = key_list[0] if key_list else "protocol"
54
- first_value = str(protocol_object[first_key]) if key_list else "unnamed"
55
- safe_name = "".join(c for c in f"{first_key}_{first_value}" if c.isalnum() or c in (' ', '-', '_')).strip()
56
- safe_name = safe_name.replace(' ', '_').lower()
57
- filename = f"protocol_{safe_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
58
-
59
- # Save to file
60
- filepath = PROTOCOLS_DIR / filename
61
- with open(filepath, 'w', encoding='utf-8') as f:
62
- json.dump(protocol_object, f, indent=2, ensure_ascii=False)
63
-
64
- return f"Successfully saved protocol to {filename}", json.dumps(protocol_object, indent=2)
 
 
 
 
 
 
 
65
  except Exception as e:
66
  return f"Error saving protocol: {str(e)}", None
67
 
68
  def list_saved_protocols():
69
  """List all saved protocol files with their contents"""
70
  try:
71
- files = sorted(PROTOCOLS_DIR.glob('protocol_*.json'), key=lambda x: x.stat().st_mtime, reverse=True)
72
- result = []
73
- for file in files:
74
- with open(file, 'r', encoding='utf-8') as f:
75
- content = json.load(f)
76
- result.append(f"Protocol: {file.name}\n```json\n{json.dumps(content, indent=2)}\n```\n")
77
- return "\n".join(result) if result else "No protocols found."
 
 
78
  except Exception as e:
79
  return f"Error listing protocols: {str(e)}"
80
 
@@ -87,12 +100,11 @@ def create_demo():
87
  if not filename.startswith('protocol_'):
88
  return "Invalid protocol filename format."
89
 
90
- filepath = PROTOCOLS_DIR / filename.strip()
91
- if not filepath.exists():
92
- return f"Protocol {filename} not found."
93
-
94
- filepath.unlink()
95
- return f"Successfully deleted protocol {filename}"
96
  except Exception as e:
97
  return f"Error deleting protocol: {str(e)}"
98
 
@@ -176,16 +188,11 @@ def create_demo():
176
 
177
  def send_to_langgraph(research_prompt, lab_prompt):
178
  try:
179
-
180
- # Format the message as expected by the server
181
- message = f"Research Prompt: {research_prompt.strip()}\nLab Prompt: {lab_prompt.strip()}"
182
-
183
  payload = {
184
  "session_id": session_id,
185
- "message": message, # Changed to use the required 'message' field
186
- "type": "prompt",
187
- "research_prompt": research_prompt,
188
- "lab_prompt": lab_prompt
189
  }
190
 
191
  response = requests.post(
@@ -195,7 +202,7 @@ def create_demo():
195
  )
196
 
197
  if response.status_code == 200:
198
- return "Successfully sent prompts to langgraph", "", ""
199
  else:
200
  error_msg = f"Error sending to langgraph (Status: {response.status_code})"
201
  if response.text:
@@ -206,7 +213,102 @@ def create_demo():
206
  error_msg = f"Error connecting to server: {str(e)}"
207
  print(error_msg)
208
  return error_msg, research_prompt, lab_prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  with gr.Blocks(css="#chatbot { height: 500px; } .upload-box { height: 40px; min-height: 40px; }") as demo:
211
  gr.Markdown("# 🧬 Longevity Assistant")
212
 
@@ -305,6 +407,35 @@ def create_demo():
305
  saved_protocols = gr.Markdown(label="Saved Protocols")
306
  refresh_btn = gr.Button("Refresh List")
307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  # Event handlers
309
  txt.submit(handle_chat, [txt, file_output, chatbot], [txt, file_output, chatbot])
310
  btn.click(handle_chat, [txt, file_output, chatbot], [txt, file_output, chatbot])
@@ -352,6 +483,23 @@ def create_demo():
352
  outputs=[saved_protocols]
353
  )
354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
  # Tab change handler to hide/show prompts
356
  def on_tab_change(tab):
357
  return gr.update(visible=tab == "Chat")
@@ -369,7 +517,7 @@ def create_demo():
369
  outputs=prompts_container
370
  )
371
 
372
- # Initialize welcome message and suggested questions
373
  demo.load(
374
  get_welcome_message,
375
  outputs=[chatbot, prompts_container]
@@ -380,6 +528,12 @@ def create_demo():
380
  list_saved_protocols,
381
  outputs=[saved_protocols]
382
  )
 
 
 
 
 
 
383
 
384
  return demo
385
 
 
15
  PROTOCOLS_DIR = Path('./tools/protocols/json-protocols')
16
  PROTOCOLS_DIR.mkdir(parents=True, exist_ok=True) # Add parents=True to create intermediate directories
17
 
18
+ # Constants for text file upload limitations
19
+ MAX_TEXT_FILES = 5
20
+ MAX_WORDS_PER_FILE = 500
21
+
22
  def create_demo():
23
  # Initialize state
24
  session_id = str(uuid.uuid4())
25
 
26
  def save_protocol(keys, values):
27
+ """Save a protocol object by sending it to the API"""
28
  try:
29
  # Parse keys and values (one per line)
30
  key_list = [k.strip() for k in keys.split('\n') if k.strip()]
 
53
  # Add creation timestamp
54
  protocol_object['_created_at'] = datetime.now().isoformat()
55
 
56
+ # Send to API
57
+ payload = {
58
+ "session_id": session_id,
59
+ "protocols": [protocol_object] # API expects a list of protocols
60
+ }
61
+
62
+ response = requests.post(
63
+ f"{API_URL}/upload_protocols",
64
+ json=payload,
65
+ timeout=API_TIMEOUT
66
+ )
67
+
68
+ if response.status_code == 200:
69
+ response_data = response.json()
70
+ if 'filename' in response_data:
71
+ return f"Successfully saved protocol to {response_data['filename']}", json.dumps(protocol_object, indent=2)
72
+ return "Successfully saved protocol", json.dumps(protocol_object, indent=2)
73
+ else:
74
+ return f"Error saving protocol: {response.text}", None
75
+
76
  except Exception as e:
77
  return f"Error saving protocol: {str(e)}", None
78
 
79
  def list_saved_protocols():
80
  """List all saved protocol files with their contents"""
81
  try:
82
+ response = requests.get(f"{API_URL}/protocols", timeout=API_TIMEOUT)
83
+ if response.status_code == 200:
84
+ data = response.json()
85
+ result = []
86
+ for protocol in data["protocols"]:
87
+ result.append(f"Protocol: {protocol['filename']}\n```json\n{json.dumps(protocol['content'], indent=2)}\n```\n")
88
+ return "\n".join(result) if result else "No protocols found."
89
+ else:
90
+ return f"Error listing protocols: {response.text}"
91
  except Exception as e:
92
  return f"Error listing protocols: {str(e)}"
93
 
 
100
  if not filename.startswith('protocol_'):
101
  return "Invalid protocol filename format."
102
 
103
+ response = requests.delete(f"{API_URL}/protocols/{filename.strip()}", timeout=API_TIMEOUT)
104
+ if response.status_code == 200:
105
+ return f"Successfully deleted protocol {filename}"
106
+ else:
107
+ return f"Error deleting protocol: {response.text}"
 
108
  except Exception as e:
109
  return f"Error deleting protocol: {str(e)}"
110
 
 
188
 
189
  def send_to_langgraph(research_prompt, lab_prompt):
190
  try:
191
+ # Format the message and send to API
 
 
 
192
  payload = {
193
  "session_id": session_id,
194
+ "research_prompt": research_prompt.strip(),
195
+ "lab_prompt": lab_prompt.strip()
 
 
196
  }
197
 
198
  response = requests.post(
 
202
  )
203
 
204
  if response.status_code == 200:
205
+ return "Successfully sent prompts to langgraph", research_prompt, lab_prompt
206
  else:
207
  error_msg = f"Error sending to langgraph (Status: {response.status_code})"
208
  if response.text:
 
213
  error_msg = f"Error connecting to server: {str(e)}"
214
  print(error_msg)
215
  return error_msg, research_prompt, lab_prompt
216
+
217
+ def load_saved_prompts():
218
+ """Load prompts from the API"""
219
+ try:
220
+ response = requests.get(f"{API_URL}/prompts", timeout=API_TIMEOUT)
221
+ if response.status_code == 200:
222
+ prompts_data = response.json()
223
+ return prompts_data.get("research_prompt", ""), prompts_data.get("lab_prompt", "")
224
+ except Exception as e:
225
+ print(f"Error loading prompts: {str(e)}")
226
+ return "", ""
227
+
228
+ def get_current_file_count():
229
+ """Get the current number of files uploaded for this session"""
230
+ try:
231
+ response = requests.get(
232
+ f"{API_URL}/text_files_count/{session_id}",
233
+ timeout=API_TIMEOUT
234
+ )
235
+ if response.status_code == 200:
236
+ return response.json().get("count", 0)
237
+ return 0
238
+ except Exception:
239
+ return 0
240
+
241
+ def validate_text_file(file_obj):
242
+ """Validate a text file's content against word limit."""
243
+ try:
244
+ with open(file_obj.name, 'r', encoding='utf-8') as f:
245
+ content = f.read()
246
+ word_count = len(content.split())
247
+ return word_count <= MAX_WORDS_PER_FILE, word_count
248
+ except Exception as e:
249
+ return False, 0
250
 
251
+ def handle_text_files_upload(files):
252
+ """Handle text file uploads with validation."""
253
+ if not files:
254
+ return "No files uploaded."
255
+
256
+ # Get current file count from server
257
+ current_count = get_current_file_count()
258
+ total_files = current_count + len(files)
259
+
260
+ if total_files > MAX_TEXT_FILES:
261
+ return f"Error: You already have {current_count} files uploaded. Adding {len(files)} more would exceed the limit of {MAX_TEXT_FILES} files."
262
+
263
+ results = []
264
+ valid_files = []
265
+
266
+ if current_count > 0:
267
+ results.append(f"Currently uploaded files: {current_count}")
268
+
269
+ for file in files:
270
+ is_valid, word_count = validate_text_file(file)
271
+ if not is_valid:
272
+ results.append(f"❌ {file.name}: Exceeds {MAX_WORDS_PER_FILE} words limit (contains {word_count} words)")
273
+ else:
274
+ results.append(f"✅ {file.name}: {word_count} words")
275
+ valid_files.append(file)
276
+
277
+ if valid_files:
278
+ try:
279
+ # Read content of valid files
280
+ files_content = []
281
+ for file in valid_files:
282
+ with open(file.name, 'r', encoding='utf-8') as f:
283
+ content = f.read()
284
+ files_content.append({
285
+ "filename": file.name,
286
+ "content": content
287
+ })
288
+
289
+ # Send to API
290
+ payload = {
291
+ "session_id": session_id,
292
+ "text_files": files_content
293
+ }
294
+
295
+ response = requests.post(
296
+ f"{API_URL}/upload_text_files",
297
+ json=payload,
298
+ timeout=API_TIMEOUT
299
+ )
300
+
301
+ if response.status_code == 200:
302
+ new_count = response.json().get("total_files", total_files)
303
+ results.append(f"\n✨ Successfully uploaded! Total files now: {new_count}/{MAX_TEXT_FILES}")
304
+ else:
305
+ results.append(f"\n❌ Error uploading to server: {response.text}")
306
+
307
+ except Exception as e:
308
+ results.append(f"\n❌ Error processing files: {str(e)}")
309
+
310
+ return "\n".join(results)
311
+
312
  with gr.Blocks(css="#chatbot { height: 500px; } .upload-box { height: 40px; min-height: 40px; }") as demo:
313
  gr.Markdown("# 🧬 Longevity Assistant")
314
 
 
407
  saved_protocols = gr.Markdown(label="Saved Protocols")
408
  refresh_btn = gr.Button("Refresh List")
409
 
410
+ with gr.Tab("Text Files") as text_tab:
411
+ with gr.Column():
412
+ gr.Markdown("## Upload Text Files")
413
+ gr.Markdown(f"""
414
+ Upload text files with size and word count limitations:
415
+ - Maximum {MAX_TEXT_FILES} files allowed (across all uploads)
416
+ - Maximum {MAX_WORDS_PER_FILE} words per file
417
+ - Supported file extensions: .txt
418
+ """)
419
+
420
+ with gr.Row():
421
+ text_files = gr.File(
422
+ file_count="multiple",
423
+ label="Upload text files",
424
+ file_types=[".txt"],
425
+ scale=1,
426
+ container=True
427
+ )
428
+ text_files_output = gr.Textbox(
429
+ label="Upload Results",
430
+ interactive=False,
431
+ lines=10
432
+ )
433
+
434
+ with gr.Row():
435
+ upload_btn = gr.Button("Upload Files", variant="primary")
436
+ clear_btn = gr.Button("Clear")
437
+ refresh_count_btn = gr.Button("Refresh Count")
438
+
439
  # Event handlers
440
  txt.submit(handle_chat, [txt, file_output, chatbot], [txt, file_output, chatbot])
441
  btn.click(handle_chat, [txt, file_output, chatbot], [txt, file_output, chatbot])
 
483
  outputs=[saved_protocols]
484
  )
485
 
486
+ # Event handlers for Text Files
487
+ upload_btn.click(
488
+ handle_text_files_upload,
489
+ inputs=[text_files],
490
+ outputs=[text_files_output]
491
+ )
492
+ clear_btn.click(
493
+ lambda: (None, ""),
494
+ inputs=[],
495
+ outputs=[text_files, text_files_output]
496
+ )
497
+ refresh_count_btn.click(
498
+ lambda: f"Current file count: {get_current_file_count()}/{MAX_TEXT_FILES}",
499
+ inputs=[],
500
+ outputs=[text_files_output]
501
+ )
502
+
503
  # Tab change handler to hide/show prompts
504
  def on_tab_change(tab):
505
  return gr.update(visible=tab == "Chat")
 
517
  outputs=prompts_container
518
  )
519
 
520
+ # Initialize welcome message, suggested questions, and saved prompts
521
  demo.load(
522
  get_welcome_message,
523
  outputs=[chatbot, prompts_container]
 
528
  list_saved_protocols,
529
  outputs=[saved_protocols]
530
  )
531
+
532
+ # Load saved prompts
533
+ demo.load(
534
+ load_saved_prompts,
535
+ outputs=[research_prompt_text, lab_prompt_text]
536
+ )
537
 
538
  return demo
539