Spaces:
Sleeping
Sleeping
Upload app.py
Browse filesLinked agentic framework with the Langchain framework
app.py
CHANGED
@@ -40,8 +40,6 @@ whisper_model = whisper.load_model("base")
|
|
40 |
load_dotenv()
|
41 |
|
42 |
hf_token = os.getenv("HF_TOKEN")
|
43 |
-
# resend_api_key = os.getenv("RESEND_API_KEY")
|
44 |
-
|
45 |
login(token=hf_token)
|
46 |
|
47 |
|
@@ -71,7 +69,7 @@ feedback_file_path = "./feedback_logs.csv"
|
|
71 |
if not os.path.exists(log_file_path):
|
72 |
with open(log_file_path, "w", newline="", encoding="utf-8") as f:
|
73 |
writer = csv.writer(f)
|
74 |
-
writer.writerow(["timestamp", "input_type", "query", "diagnosis", "confidence_score", "status"])
|
75 |
|
76 |
# -------------------------------
|
77 |
# π§ Feedback setup
|
@@ -80,10 +78,11 @@ if not os.path.exists(feedback_file_path):
|
|
80 |
with open(feedback_file_path, "w", newline="", encoding="utf-8") as f:
|
81 |
writer = csv.writer(f)
|
82 |
writer.writerow([
|
83 |
-
"feedback_id", "timestamp", "input_type", "query",
|
84 |
-
"diagnosis", "
|
85 |
])
|
86 |
|
|
|
87 |
# Ensure directory exists
|
88 |
#os.makedirs(save_path_bge, exist_ok=True)
|
89 |
|
@@ -280,9 +279,17 @@ def process_query(user_query, input_type="text"):
|
|
280 |
|
281 |
# Log interaction
|
282 |
log_query(input_type=input_type, query=user_query, diagnosis=diagnosis, confidence_score=severity_score, status=status)
|
283 |
-
download_path =
|
|
|
|
|
|
|
284 |
|
285 |
-
|
|
|
|
|
|
|
|
|
|
|
286 |
|
287 |
# Dashboard Interface
|
288 |
def diagnosis_dashboard():
|
@@ -315,17 +322,47 @@ def diagnosis_dashboard():
|
|
315 |
return f"β οΈ Error loading dashboard: {str(e)}"
|
316 |
|
317 |
# For logs functionality
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
318 |
def log_query(input_type, query, diagnosis, confidence_score, status):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
319 |
with open(log_file_path, "a", newline="", encoding="utf-8") as f:
|
320 |
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
|
321 |
writer.writerow([
|
322 |
-
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
323 |
-
|
324 |
-
|
325 |
-
|
|
|
326 |
str(confidence_score),
|
327 |
-
status
|
328 |
])
|
|
|
|
|
329 |
def show_logs():
|
330 |
try:
|
331 |
df = pd.read_csv(log_file_path)
|
@@ -357,18 +394,45 @@ def create_summary_pdf(text, filename_prefix="diagnosis_report"):
|
|
357 |
return None
|
358 |
|
359 |
|
360 |
-
|
|
|
|
|
361 |
filename = f"{filename_prefix}_{uuid.uuid4().hex[:6]}.txt"
|
362 |
with open(filename, "w", encoding="utf-8") as f:
|
363 |
-
f.write(
|
|
|
364 |
return filename
|
365 |
|
366 |
|
367 |
|
368 |
# π₯ Feedback
|
369 |
-
feedback_data = []
|
370 |
-
def submit_feedback(feedback, input_type, query, diagnosis, confidence_score, status):
|
371 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
372 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
373 |
|
374 |
with open(feedback_file_path, "a", newline="", encoding="utf-8") as f:
|
@@ -376,11 +440,11 @@ def submit_feedback(feedback, input_type, query, diagnosis, confidence_score, st
|
|
376 |
writer.writerow([
|
377 |
feedback_id,
|
378 |
timestamp,
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
status,
|
384 |
feedback.replace('"', '""')
|
385 |
])
|
386 |
|
@@ -400,24 +464,37 @@ def download_feedback_log():
|
|
400 |
# })
|
401 |
# return "β
Diagnosis report sent to your email!" if response.get("id") else "β οΈ Failed to send email."
|
402 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
403 |
|
404 |
def unified_handler(audio, text):
|
405 |
if audio:
|
406 |
-
response,
|
407 |
else:
|
408 |
-
response,
|
409 |
|
410 |
-
#
|
411 |
-
|
412 |
-
|
413 |
-
# return response, None
|
414 |
|
415 |
-
if download_path and os.path.exists(download_path):
|
416 |
-
return response, download_path
|
417 |
-
else:
|
418 |
-
print("β PDF not found or failed to generate.")
|
419 |
-
return response, None
|
420 |
-
|
421 |
#Agentic Framework from HF spaces
|
422 |
# agent_iframe = gr.HTML(
|
423 |
# '<iframe src="https://jaamie-mental-health-agent.hf.space" width="100%" height="700px" style="border:none;"></iframe>'
|
@@ -440,7 +517,7 @@ main_assistant_tab = gr.Interface(
|
|
440 |
gr.Textbox(lines=2, placeholder="Or type your mental health concern here...")
|
441 |
],
|
442 |
outputs=[
|
443 |
-
gr.Textbox(label="π§ Personalized Diagnosis", lines=
|
444 |
gr.File(label="π₯ Download Diagnosis Report")
|
445 |
],
|
446 |
title="π§ SafeSpace AI",
|
@@ -478,28 +555,19 @@ logs_tab = gr.Interface(
|
|
478 |
# title="π Submit Feedback With Session Metadata"
|
479 |
# )
|
480 |
|
481 |
-
def feedback_handler(fb, inp_type, query, diag, score, status):
|
482 |
-
|
483 |
|
484 |
feedback_tab = gr.Interface(
|
485 |
-
fn=
|
486 |
-
inputs=[
|
487 |
-
|
488 |
-
|
489 |
-
gr.Textbox(label="Query"),
|
490 |
-
gr.Textbox(label="Diagnosis"),
|
491 |
-
gr.Textbox(label="Confidence Score"),
|
492 |
-
gr.Textbox(label="Status")
|
493 |
-
],
|
494 |
-
outputs=[
|
495 |
-
gr.Textbox(label="π§ Personalized Diagnosis", lines=8),
|
496 |
-
gr.File(label="π₯ Download Diagnosis Report")
|
497 |
-
],
|
498 |
-
title="π Submit Feedback With Session Metadata"
|
499 |
)
|
500 |
|
501 |
|
502 |
|
|
|
503 |
feedback_download_tab = gr.Interface(
|
504 |
fn=download_feedback_log,
|
505 |
inputs=[],
|
@@ -508,14 +576,19 @@ feedback_download_tab = gr.Interface(
|
|
508 |
)
|
509 |
|
510 |
agent_tab = gr.Interface(
|
511 |
-
fn=lambda: "
|
512 |
inputs=[],
|
513 |
-
outputs=gr.
|
514 |
-
|
|
|
|
|
|
|
515 |
),
|
516 |
-
title="π€ Agent
|
517 |
)
|
518 |
|
|
|
|
|
519 |
# Add to your tab list
|
520 |
app = gr.TabbedInterface(
|
521 |
interface_list=[
|
@@ -524,7 +597,7 @@ app = gr.TabbedInterface(
|
|
524 |
logs_tab,
|
525 |
feedback_tab,
|
526 |
feedback_download_tab,
|
527 |
-
agent_tab
|
528 |
],
|
529 |
tab_names=[
|
530 |
"π§ Assistant",
|
@@ -532,7 +605,7 @@ app = gr.TabbedInterface(
|
|
532 |
"π Logs",
|
533 |
"π Feedback",
|
534 |
"π Feedback CSV",
|
535 |
-
"π€ Agent"
|
536 |
]
|
537 |
)
|
538 |
|
|
|
40 |
load_dotenv()
|
41 |
|
42 |
hf_token = os.getenv("HF_TOKEN")
|
|
|
|
|
43 |
login(token=hf_token)
|
44 |
|
45 |
|
|
|
69 |
if not os.path.exists(log_file_path):
|
70 |
with open(log_file_path, "w", newline="", encoding="utf-8") as f:
|
71 |
writer = csv.writer(f)
|
72 |
+
writer.writerow(["timestamp", "user_id", "input_type", "query", "diagnosis", "confidence_score", "status"])
|
73 |
|
74 |
# -------------------------------
|
75 |
# π§ Feedback setup
|
|
|
78 |
with open(feedback_file_path, "w", newline="", encoding="utf-8") as f:
|
79 |
writer = csv.writer(f)
|
80 |
writer.writerow([
|
81 |
+
"feedback_id", "timestamp", "user_id", "input_type", "query",
|
82 |
+
"diagnosis", "status", "feedback"
|
83 |
])
|
84 |
|
85 |
+
|
86 |
# Ensure directory exists
|
87 |
#os.makedirs(save_path_bge, exist_ok=True)
|
88 |
|
|
|
279 |
|
280 |
# Log interaction
|
281 |
log_query(input_type=input_type, query=user_query, diagnosis=diagnosis, confidence_score=severity_score, status=status)
|
282 |
+
download_path = create_summary_txt(answer)
|
283 |
+
|
284 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
285 |
+
user_id = session_data["latest"]["user_id"] # grab it from session
|
286 |
|
287 |
+
# Prepend to the answer string
|
288 |
+
answer_header = f"π§Ύ Session ID: {user_id}\nπ
Timestamp: {timestamp}\n\n"
|
289 |
+
return answer_header + answer, download_path
|
290 |
+
|
291 |
+
|
292 |
+
#return answer, download_path
|
293 |
|
294 |
# Dashboard Interface
|
295 |
def diagnosis_dashboard():
|
|
|
322 |
return f"β οΈ Error loading dashboard: {str(e)}"
|
323 |
|
324 |
# For logs functionality
|
325 |
+
# def log_query(input_type, query, diagnosis, confidence_score, status):
|
326 |
+
# with open(log_file_path, "a", newline="", encoding="utf-8") as f:
|
327 |
+
# writer = csv.writer(f, quoting=csv.QUOTE_ALL)
|
328 |
+
# writer.writerow([
|
329 |
+
# datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
330 |
+
# input_type.replace('"', '""'),
|
331 |
+
# query.replace('"', '""'),
|
332 |
+
# diagnosis.replace('"', '""'),
|
333 |
+
# str(confidence_score),
|
334 |
+
# status
|
335 |
+
# ])
|
336 |
+
|
337 |
+
session_data = {}
|
338 |
+
|
339 |
def log_query(input_type, query, diagnosis, confidence_score, status):
|
340 |
+
|
341 |
+
user_id = f"SSuser_ID_{uuid.uuid4().hex[:8]}"
|
342 |
+
|
343 |
+
# Store in-memory session data for feedback use
|
344 |
+
session_data["latest"] = {
|
345 |
+
"user_id": user_id,
|
346 |
+
"input_type": input_type,
|
347 |
+
"query": query,
|
348 |
+
"diagnosis": diagnosis,
|
349 |
+
"confidence_score": confidence_score,
|
350 |
+
"status": status
|
351 |
+
}
|
352 |
+
|
353 |
with open(log_file_path, "a", newline="", encoding="utf-8") as f:
|
354 |
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
|
355 |
writer.writerow([
|
356 |
+
str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
|
357 |
+
str(user_id),
|
358 |
+
str(input_type).replace('"', '""'),
|
359 |
+
str(query).replace('"', '""'),
|
360 |
+
str(diagnosis).replace('"', '""'),
|
361 |
str(confidence_score),
|
362 |
+
str(status)
|
363 |
])
|
364 |
+
|
365 |
+
|
366 |
def show_logs():
|
367 |
try:
|
368 |
df = pd.read_csv(log_file_path)
|
|
|
394 |
return None
|
395 |
|
396 |
|
397 |
+
|
398 |
+
|
399 |
+
def create_summary_txt(text, filename_prefix="diagnosis_report"):
|
400 |
filename = f"{filename_prefix}_{uuid.uuid4().hex[:6]}.txt"
|
401 |
with open(filename, "w", encoding="utf-8") as f:
|
402 |
+
f.write(text)
|
403 |
+
print(f"β
TXT report created: {filename}")
|
404 |
return filename
|
405 |
|
406 |
|
407 |
|
408 |
# π₯ Feedback
|
409 |
+
# feedback_data = []
|
410 |
+
# def submit_feedback(feedback, input_type, query, diagnosis, confidence_score, status):
|
411 |
+
# feedback_id = str(uuid.uuid4())
|
412 |
+
# timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
413 |
+
|
414 |
+
# with open(feedback_file_path, "a", newline="", encoding="utf-8") as f:
|
415 |
+
# writer = csv.writer(f, quoting=csv.QUOTE_ALL)
|
416 |
+
# writer.writerow([
|
417 |
+
# feedback_id,
|
418 |
+
# timestamp,
|
419 |
+
# input_type.replace('"', '""'),
|
420 |
+
# query.replace('"', '""'),
|
421 |
+
# diagnosis.replace('"', '""'),
|
422 |
+
# str(confidence_score),
|
423 |
+
# status,
|
424 |
+
# feedback.replace('"', '""')
|
425 |
+
# ])
|
426 |
+
|
427 |
+
# return f"β
Feedback received! Your Feedback ID: {feedback_id}"
|
428 |
+
|
429 |
+
|
430 |
+
def submit_feedback(feedback):
|
431 |
+
# if "latest" not in session_data:
|
432 |
+
# return "β οΈ No diagnosis found for this session. Please get a diagnosis first."
|
433 |
+
|
434 |
+
user_info = session_data["latest"]
|
435 |
+
feedback_id = f"fb_{uuid.uuid4().hex[:8]}"
|
436 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
437 |
|
438 |
with open(feedback_file_path, "a", newline="", encoding="utf-8") as f:
|
|
|
440 |
writer.writerow([
|
441 |
feedback_id,
|
442 |
timestamp,
|
443 |
+
user_info["user_id"],
|
444 |
+
user_info["input_type"],
|
445 |
+
user_info["query"],
|
446 |
+
user_info["diagnosis"],
|
447 |
+
user_info["status"],
|
448 |
feedback.replace('"', '""')
|
449 |
])
|
450 |
|
|
|
464 |
# })
|
465 |
# return "β
Diagnosis report sent to your email!" if response.get("id") else "β οΈ Failed to send email."
|
466 |
|
467 |
+
# For pdf
|
468 |
+
|
469 |
+
# def unified_handler(audio, text):
|
470 |
+
# if audio:
|
471 |
+
# response, download_path = process_whisper_query(audio)
|
472 |
+
# else:
|
473 |
+
# response, download_path = process_query(text, input_type="text")
|
474 |
+
|
475 |
+
# # Ensure download path is valid
|
476 |
+
# # if not (download_path and os.path.exists(download_path)):
|
477 |
+
# # print("β PDF not found or failed to generate.")
|
478 |
+
# # return response, None
|
479 |
+
|
480 |
+
# if download_path and os.path.exists(download_path):
|
481 |
+
# return response, download_path
|
482 |
+
# else:
|
483 |
+
# print("β PDF not found or failed to generate.")
|
484 |
+
# return response, None
|
485 |
+
|
486 |
+
# for text doc download
|
487 |
|
488 |
def unified_handler(audio, text):
|
489 |
if audio:
|
490 |
+
response, _ = process_whisper_query(audio)
|
491 |
else:
|
492 |
+
response, _ = process_query(text, input_type="text")
|
493 |
|
494 |
+
download_path = create_summary_txt(response) # <- save as txt instead
|
495 |
+
|
496 |
+
return response, download_path
|
|
|
497 |
|
|
|
|
|
|
|
|
|
|
|
|
|
498 |
#Agentic Framework from HF spaces
|
499 |
# agent_iframe = gr.HTML(
|
500 |
# '<iframe src="https://jaamie-mental-health-agent.hf.space" width="100%" height="700px" style="border:none;"></iframe>'
|
|
|
517 |
gr.Textbox(lines=2, placeholder="Or type your mental health concern here...")
|
518 |
],
|
519 |
outputs=[
|
520 |
+
gr.Textbox(label="π§ Personalized Diagnosis", lines=15, show_copy_button=True),
|
521 |
gr.File(label="π₯ Download Diagnosis Report")
|
522 |
],
|
523 |
title="π§ SafeSpace AI",
|
|
|
555 |
# title="π Submit Feedback With Session Metadata"
|
556 |
# )
|
557 |
|
558 |
+
# def feedback_handler(fb, inp_type, query, diag, score, status):
|
559 |
+
# return submit_feedback(fb, inp_type, query, diag, score, status)
|
560 |
|
561 |
feedback_tab = gr.Interface(
|
562 |
+
fn=submit_feedback,
|
563 |
+
inputs=[gr.Textbox(label="π Share your thoughts")],
|
564 |
+
outputs="text",
|
565 |
+
title="π Submit Feedback"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
566 |
)
|
567 |
|
568 |
|
569 |
|
570 |
+
|
571 |
feedback_download_tab = gr.Interface(
|
572 |
fn=download_feedback_log,
|
573 |
inputs=[],
|
|
|
576 |
)
|
577 |
|
578 |
agent_tab = gr.Interface(
|
579 |
+
fn=lambda: "",
|
580 |
inputs=[],
|
581 |
+
outputs=gr.HTML(
|
582 |
+
"""<button onclick="window.open('https://jaamie-mental-health-agent.hf.space', '_blank')"
|
583 |
+
style='padding:10px 20px; font-size:16px; background-color:#4CAF50; color:white; border:none; border-radius:5px;'>
|
584 |
+
π§ Launch Agent SafeSpace 001
|
585 |
+
</button>"""
|
586 |
),
|
587 |
+
title="π€ Agent SafeSpace 001"
|
588 |
)
|
589 |
|
590 |
+
|
591 |
+
|
592 |
# Add to your tab list
|
593 |
app = gr.TabbedInterface(
|
594 |
interface_list=[
|
|
|
597 |
logs_tab,
|
598 |
feedback_tab,
|
599 |
feedback_download_tab,
|
600 |
+
agent_tab
|
601 |
],
|
602 |
tab_names=[
|
603 |
"π§ Assistant",
|
|
|
605 |
"π Logs",
|
606 |
"π Feedback",
|
607 |
"π Feedback CSV",
|
608 |
+
"π€ Agent 001"
|
609 |
]
|
610 |
)
|
611 |
|