dawit45 commited on
Commit
b777317
Β·
verified Β·
1 Parent(s): e0dcb27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -58
app.py CHANGED
@@ -1,126 +1,131 @@
1
  import os
 
2
  os.system("pip install plotly pandas numpy pypdf")
3
 
4
  import gradio as gr
5
  import json
6
  import pandas as pd
7
- import plotly.graph_objects as go
8
  from huggingface_hub import InferenceClient
9
  from datetime import datetime
10
- import re
11
 
12
- # --- 1. INITIALIZATION ---
 
13
  RAW_TOKEN = os.getenv("HF_TOKEN")
14
  HF_TOKEN = RAW_TOKEN.strip() if RAW_TOKEN else None
 
 
15
  client = InferenceClient("Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
16
 
17
- # --- 2. THE ORCHESTRATION ENGINE ---
18
 
19
  def clinical_orchestrator(symptoms, history, wearable_data):
20
- # Initialize UI
21
- reasoning_path = "### πŸ›‘οΈ INITIALIZING CLINICAL REASONING PATHWAY..."
22
- final_report = ""
23
- referral_slip = ""
24
 
25
  if not symptoms:
26
- yield "### ⚠️ System Ready: Waiting for clinical input.", "", ""
27
  return
28
 
29
  try:
30
- # STEP 1: DIFFERENTIAL DIAGNOSIS REASONING (XAI)
31
- yield "### 🧠 PHASE 1: GENERATING DIFFERENTIAL DIAGNOSES...", "", ""
32
 
33
  prompt_1 = f"""
34
  System: Act as a Senior Clinical Orchestrator.
35
- Analyze: Symptoms: {symptoms}, History: {history}, Wearables: {wearable_data}.
36
- Task: Show your step-by-step clinical reasoning for a Differential Diagnosis.
 
 
 
 
37
  """
38
 
39
- reasoning_path = "## 🧠 Clinical Reasoning Trace\n"
40
- for chunk in client.chat_completion(messages=[{"role": "user", "content": prompt_1}], max_tokens=1000, stream=True):
 
 
41
  token = chunk.choices[0].delta.content
42
  if token:
43
- reasoning_path += token
44
- yield reasoning_path, "", ""
45
 
46
- # STEP 2: HOLISTIC HEALTH REPORT & GUIDELINE CHECK
47
- yield reasoning_path, "### πŸ“Š PHASE 2: CROSS-REFERENCING GLOBAL GUIDELINES...", ""
48
 
49
  prompt_2 = f"""
50
- Based on this reasoning: {reasoning_path}
51
- Generate a 'Master Health Report'. Include:
52
- 1. Primary Diagnosis & Likelihood.
53
- 2. Guideline Check (WHO/ACC/NICE 2025).
54
- 3. Genomic/Metabolic Risk Factors.
55
- 4. Immediate Pharmacological/Lifestyle Plan.
56
  """
57
 
58
- for chunk in client.chat_completion(messages=[{"role": "user", "content": prompt_2}], max_tokens=1500, stream=True):
 
 
 
59
  token = chunk.choices[0].delta.content
60
  if token:
61
- final_report += token
62
- yield reasoning_path, final_report, ""
63
 
64
- # STEP 3: AUTONOMOUS SPECIALIST REFERRAL
65
- yield reasoning_path, final_report, "### βœ‰οΈ PHASE 3: DRAFTING SPECIALIST REFERRAL..."
66
 
67
- prompt_3 = f"Based on the diagnosis: {final_report}, draft a professional medical referral letter to the appropriate specialist. Include ICD-11 codes."
68
 
69
  res_3 = client.chat_completion(messages=[{"role": "user", "content": prompt_3}], max_tokens=800)
70
- referral_slip = res_3.choices[0].message.content
71
 
72
- yield reasoning_path, final_report, referral_slip
73
 
74
  except Exception as e:
75
- yield f"### ❌ System Failure\n{str(e)}", "", ""
76
 
77
- # --- 3. THE "PRESTIGE" UI DESIGN ---
78
 
79
  css = """
80
- body, .gradio-container { background-color: #080808 !important; color: #d4af37 !important; font-family: 'Playfair Display', serif; }
81
- .prestige-card { border: 1px solid #d4af37 !important; border-radius: 15px !important; background: #111 !important; padding: 25px; box-shadow: 0 0 30px rgba(212, 175, 55, 0.1); }
82
- .gold-btn { background: linear-gradient(135deg, #d4af37 0%, #f9f295 50%, #d4af37 100%) !important; color: #000 !important; font-weight: 900 !important; border: none !important; cursor: pointer; transition: 0.3s; }
83
- .gold-btn:hover { box-shadow: 0 0 40px rgba(212, 175, 55, 0.5); transform: scale(1.01); }
84
- h1 { color: #d4af37 !important; text-align: center; font-size: 3rem !important; text-transform: uppercase; letter-spacing: 5px; }
85
  .tabs { border-color: #d4af37 !important; }
86
- textarea, input { background: #1a1a1a !important; color: white !important; border: 1px solid #333 !important; }
87
  """
88
 
89
  with gr.Blocks(theme=gr.themes.Default(), css=css) as demo:
90
  gr.Markdown("# AETHER-HEALTH")
91
- gr.Markdown("### AUTONOMOUS CLINICAL ORCHESTRATOR β€’ PRESTIGE EDITION")
92
 
93
  with gr.Row():
94
- # INPUT CHANNEL
95
  with gr.Column(scale=1, elem_classes="prestige-card"):
96
  gr.Markdown("### πŸ“₯ CLINICAL INGESTION")
97
- symptoms_in = gr.Textbox(label="Presenting Symptoms", lines=3, placeholder="Describe current issues...")
98
- history_in = gr.Textbox(label="Patient History (EHR Context)", lines=3, placeholder="Past surgeries, genomics, labs...")
99
- wearable_in = gr.Textbox(label="Wearable Biometrics", value="Heart Rate: 72, Sleep: 7.5h, HRV: 55ms")
100
 
101
  run_btn = gr.Button("⚑ ORCHESTRATE CARE", elem_classes="gold-btn")
102
 
103
  gr.Markdown("---")
104
- gr.Markdown("#### πŸ›‘οΈ ORCHESTRATOR STATUS")
105
- gr.Markdown("Safety Protocol: <span style='color:#00ff00'>VERIFIED</span>")
106
- gr.Markdown("Compliance: <span style='color:#d4af37'>GDPR/HIPAA 2026</span>")
107
 
108
- # INTELLIGENCE HUB
109
  with gr.Column(scale=2, elem_classes="prestige-card"):
110
  with gr.Tabs(elem_classes="tabs"):
111
  with gr.TabItem("🧠 REASONING TRACE"):
112
- reason_out = gr.Markdown("### *System Idle: Awaiting Clinical Data*")
113
-
114
- with gr.TabItem("πŸ“Š MASTER HEALTH REPORT"):
115
- report_out = gr.Markdown("### *Synthesizing Analysis...*")
116
-
117
  with gr.TabItem("βœ‰οΈ AUTONOMOUS REFERRAL"):
118
- referral_out = gr.Markdown("### *Drafting Specialist Communication...*")
119
 
120
  run_btn.click(
121
  fn=clinical_orchestrator,
122
- inputs=[symptoms_in, history_in, wearable_in],
123
- outputs=[reason_out, report_out, referral_out],
124
  api_name=False
125
  )
126
 
 
1
  import os
2
+ # Brute force installation to ensure world-class visuals
3
  os.system("pip install plotly pandas numpy pypdf")
4
 
5
  import gradio as gr
6
  import json
7
  import pandas as pd
 
8
  from huggingface_hub import InferenceClient
9
  from datetime import datetime
 
10
 
11
+ # --- 1. SECURE INITIALIZATION ---
12
+ # Using .strip() to kill any accidental newlines or spaces from the secret
13
  RAW_TOKEN = os.getenv("HF_TOKEN")
14
  HF_TOKEN = RAW_TOKEN.strip() if RAW_TOKEN else None
15
+
16
+ # The Elite Brain: Qwen 2.5 7B (Reliable for 2026 Reasoning)
17
  client = InferenceClient("Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
18
 
19
+ # --- 2. ORCHESTRATION ENGINE LOGIC ---
20
 
21
  def clinical_orchestrator(symptoms, history, wearable_data):
22
+ if not HF_TOKEN:
23
+ yield "### ❌ ACCESS DENIED\nHF_TOKEN missing or invalid. Please check Space Secrets.", "", ""
24
+ return
 
25
 
26
  if not symptoms:
27
+ yield "### ⚠️ SYSTEM READY\nAwaiting clinical data ingestion...", "", ""
28
  return
29
 
30
  try:
31
+ # --- PHASE 1: REASONING TRACE (XAI) ---
32
+ yield "### 🧠 PHASE 1: ACTIVATING CLINICAL REASONING PATHWAY...", "", ""
33
 
34
  prompt_1 = f"""
35
  System: Act as a Senior Clinical Orchestrator.
36
+ Input Symptoms: {symptoms}
37
+ Input History: {history}
38
+ Biometrics: {wearable_data}
39
+
40
+ TASK: Perform a Step-by-Step Clinical Reasoning Trace for a Differential Diagnosis.
41
+ Show your 'chain of thought'.
42
  """
43
 
44
+ reasoning = "## 🧠 Clinical Reasoning Trace\n"
45
+ stream_1 = client.chat_completion(messages=[{"role": "user", "content": prompt_1}], max_tokens=800, stream=True)
46
+
47
+ for chunk in stream_1:
48
  token = chunk.choices[0].delta.content
49
  if token:
50
+ reasoning += token
51
+ yield reasoning, "", ""
52
 
53
+ # --- PHASE 2: MASTER HEALTH REPORT ---
54
+ yield reasoning, "### πŸ“Š PHASE 2: SYNTHESIZING MASTER HEALTH REPORT...", ""
55
 
56
  prompt_2 = f"""
57
+ Based on this reasoning: {reasoning}
58
+ Generate a professional Master Health Report.
59
+ Include: Primary Diagnosis, Guideline Cross-Check (WHO/ACC), and 2026 Pharmacological Protocol.
 
 
 
60
  """
61
 
62
+ report = "## πŸ“Š Master Health Report\n"
63
+ stream_2 = client.chat_completion(messages=[{"role": "user", "content": prompt_2}], max_tokens=1000, stream=True)
64
+
65
+ for chunk in stream_2:
66
  token = chunk.choices[0].delta.content
67
  if token:
68
+ report += token
69
+ yield reasoning, report, ""
70
 
71
+ # --- PHASE 3: SPECIALIST REFERRAL ---
72
+ yield reasoning, report, "### βœ‰οΈ PHASE 3: DRAFTING AUTONOMOUS REFERRAL..."
73
 
74
+ prompt_3 = f"Diagnosis: {report}. Draft a professional medical referral letter to the appropriate specialist. Include ICD-11 codes."
75
 
76
  res_3 = client.chat_completion(messages=[{"role": "user", "content": prompt_3}], max_tokens=800)
77
+ referral = res_3.choices[0].message.content
78
 
79
+ yield reasoning, report, f"## βœ‰οΈ Autonomous Specialist Referral\n{referral}"
80
 
81
  except Exception as e:
82
+ yield f"### ❌ UPLINK FAILURE\n{str(e)}", "", ""
83
 
84
+ # --- 3. THE LUXURY "PRESTIGE" UI ---
85
 
86
  css = """
87
+ body, .gradio-container { background-color: #050505 !important; color: #d4af37 !important; font-family: 'Georgia', serif; }
88
+ .prestige-card { border: 1px solid #d4af37 !important; border-radius: 15px !important; background: rgba(20, 20, 20, 0.9) !important; padding: 25px; box-shadow: 0 0 30px rgba(212, 175, 55, 0.1); }
89
+ .gold-btn { background: linear-gradient(135deg, #d4af37 0%, #f9f295 100%) !important; color: #000 !important; font-weight: 900 !important; border: none !important; cursor: pointer; transition: 0.3s; }
90
+ .gold-btn:hover { box-shadow: 0 0 40px #d4af37; transform: scale(1.02); }
91
+ textarea, input { background: #111 !important; color: #fff !important; border: 1px solid #333 !important; }
92
  .tabs { border-color: #d4af37 !important; }
93
+ h1 { letter-spacing: 4px; text-transform: uppercase; }
94
  """
95
 
96
  with gr.Blocks(theme=gr.themes.Default(), css=css) as demo:
97
  gr.Markdown("# AETHER-HEALTH")
98
+ gr.Markdown("### πŸ›οΈ AUTONOMOUS CLINICAL ORCHESTRATOR β€’ PRESTIGE EDITION")
99
 
100
  with gr.Row():
101
+ # INPUT COLUMN
102
  with gr.Column(scale=1, elem_classes="prestige-card"):
103
  gr.Markdown("### πŸ“₯ CLINICAL INGESTION")
104
+ symp = gr.Textbox(label="Presenting Symptoms", lines=3)
105
+ hist = gr.Textbox(label="Clinical History (PDF/EHR)", lines=3)
106
+ wear = gr.Textbox(label="Wearable Stream", value="HR: 72bpm, HRV: 50ms, SpO2: 98%")
107
 
108
  run_btn = gr.Button("⚑ ORCHESTRATE CARE", elem_classes="gold-btn")
109
 
110
  gr.Markdown("---")
111
+ gr.Markdown("#### πŸ›‘οΈ SYSTEM PROTOCOL")
112
+ gr.Markdown("XAI Trace: <span style='color:#00ff00'>ACTIVE</span>")
113
+ gr.Markdown("Token Security: <span style='color:#00ff00'>ENFORCED</span>")
114
 
115
+ # OUTPUT COLUMN
116
  with gr.Column(scale=2, elem_classes="prestige-card"):
117
  with gr.Tabs(elem_classes="tabs"):
118
  with gr.TabItem("🧠 REASONING TRACE"):
119
+ out_1 = gr.Markdown("### *System Idle...*")
120
+ with gr.TabItem("πŸ“Š MASTER REPORT"):
121
+ out_2 = gr.Markdown("### *Awaiting Phase 1...*")
 
 
122
  with gr.TabItem("βœ‰οΈ AUTONOMOUS REFERRAL"):
123
+ out_3 = gr.Markdown("### *Awaiting Phase 2...*")
124
 
125
  run_btn.click(
126
  fn=clinical_orchestrator,
127
+ inputs=[symp, hist, wear],
128
+ outputs=[out_1, out_2, out_3],
129
  api_name=False
130
  )
131