File size: 5,678 Bytes
e0dcb27
b777317
e0dcb27
 
7f4fb8e
e0dcb27
 
7f4fb8e
e0dcb27
7f4fb8e
b777317
 
e0dcb27
 
b777317
 
e0dcb27
7f4fb8e
b777317
7f4fb8e
e0dcb27
b777317
 
 
e0dcb27
 
b777317
e0dcb27
7f4fb8e
e0dcb27
b777317
 
e0dcb27
 
 
b777317
 
 
 
 
 
e0dcb27
 
b777317
 
 
 
e0dcb27
 
b777317
 
7f4fb8e
b777317
 
e0dcb27
 
b777317
 
 
e0dcb27
 
b777317
 
 
 
e0dcb27
 
b777317
 
7f4fb8e
b777317
 
e0dcb27
b777317
e0dcb27
 
b777317
e0dcb27
b777317
7f4fb8e
e0dcb27
b777317
7f4fb8e
b777317
7f4fb8e
e0dcb27
b777317
 
 
 
 
e0dcb27
b777317
7f4fb8e
 
e0dcb27
 
b777317
e0dcb27
 
b777317
e0dcb27
 
b777317
 
 
e0dcb27
 
 
 
b777317
 
 
e0dcb27
b777317
e0dcb27
 
 
b777317
 
 
e0dcb27
b777317
7f4fb8e
e0dcb27
 
b777317
 
e0dcb27
 
7f4fb8e
e0dcb27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import os
# Brute force installation to ensure world-class visuals
os.system("pip install plotly pandas numpy pypdf")

import gradio as gr
import json
import pandas as pd
from huggingface_hub import InferenceClient
from datetime import datetime

# --- 1. SECURE INITIALIZATION ---
# Using .strip() to kill any accidental newlines or spaces from the secret
RAW_TOKEN = os.getenv("HF_TOKEN")
HF_TOKEN = RAW_TOKEN.strip() if RAW_TOKEN else None

# The Elite Brain: Qwen 2.5 7B (Reliable for 2026 Reasoning)
client = InferenceClient("Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)

# --- 2. ORCHESTRATION ENGINE LOGIC ---

def clinical_orchestrator(symptoms, history, wearable_data):
    if not HF_TOKEN:
        yield "### ❌ ACCESS DENIED\nHF_TOKEN missing or invalid. Please check Space Secrets.", "", ""
        return
    
    if not symptoms:
        yield "### ⚠️ SYSTEM READY\nAwaiting clinical data ingestion...", "", ""
        return

    try:
        # --- PHASE 1: REASONING TRACE (XAI) ---
        yield "### 🧠 PHASE 1: ACTIVATING CLINICAL REASONING PATHWAY...", "", ""
        
        prompt_1 = f"""
        System: Act as a Senior Clinical Orchestrator. 
        Input Symptoms: {symptoms}
        Input History: {history}
        Biometrics: {wearable_data}
        
        TASK: Perform a Step-by-Step Clinical Reasoning Trace for a Differential Diagnosis. 
        Show your 'chain of thought'.
        """
        
        reasoning = "## 🧠 Clinical Reasoning Trace\n"
        stream_1 = client.chat_completion(messages=[{"role": "user", "content": prompt_1}], max_tokens=800, stream=True)
        
        for chunk in stream_1:
            token = chunk.choices[0].delta.content
            if token:
                reasoning += token
                yield reasoning, "", ""

        # --- PHASE 2: MASTER HEALTH REPORT ---
        yield reasoning, "### πŸ“Š PHASE 2: SYNTHESIZING MASTER HEALTH REPORT...", ""
        
        prompt_2 = f"""
        Based on this reasoning: {reasoning}
        Generate a professional Master Health Report. 
        Include: Primary Diagnosis, Guideline Cross-Check (WHO/ACC), and 2026 Pharmacological Protocol.
        """
        
        report = "## πŸ“Š Master Health Report\n"
        stream_2 = client.chat_completion(messages=[{"role": "user", "content": prompt_2}], max_tokens=1000, stream=True)
        
        for chunk in stream_2:
            token = chunk.choices[0].delta.content
            if token:
                report += token
                yield reasoning, report, ""

        # --- PHASE 3: SPECIALIST REFERRAL ---
        yield reasoning, report, "### βœ‰οΈ PHASE 3: DRAFTING AUTONOMOUS REFERRAL..."
        
        prompt_3 = f"Diagnosis: {report}. Draft a professional medical referral letter to the appropriate specialist. Include ICD-11 codes."
        
        res_3 = client.chat_completion(messages=[{"role": "user", "content": prompt_3}], max_tokens=800)
        referral = res_3.choices[0].message.content
        
        yield reasoning, report, f"## βœ‰οΈ Autonomous Specialist Referral\n{referral}"

    except Exception as e:
        yield f"### ❌ UPLINK FAILURE\n{str(e)}", "", ""

# --- 3. THE LUXURY "PRESTIGE" UI ---

css = """
body, .gradio-container { background-color: #050505 !important; color: #d4af37 !important; font-family: 'Georgia', serif; }
.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); }
.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; }
.gold-btn:hover { box-shadow: 0 0 40px #d4af37; transform: scale(1.02); }
textarea, input { background: #111 !important; color: #fff !important; border: 1px solid #333 !important; }
.tabs { border-color: #d4af37 !important; }
h1 { letter-spacing: 4px; text-transform: uppercase; }
"""

with gr.Blocks(theme=gr.themes.Default(), css=css) as demo:
    gr.Markdown("# AETHER-HEALTH")
    gr.Markdown("### πŸ›οΈ AUTONOMOUS CLINICAL ORCHESTRATOR β€’ PRESTIGE EDITION")
    
    with gr.Row():
        # INPUT COLUMN
        with gr.Column(scale=1, elem_classes="prestige-card"):
            gr.Markdown("### πŸ“₯ CLINICAL INGESTION")
            symp = gr.Textbox(label="Presenting Symptoms", lines=3)
            hist = gr.Textbox(label="Clinical History (PDF/EHR)", lines=3)
            wear = gr.Textbox(label="Wearable Stream", value="HR: 72bpm, HRV: 50ms, SpO2: 98%")
            
            run_btn = gr.Button("⚑ ORCHESTRATE CARE", elem_classes="gold-btn")
            
            gr.Markdown("---")
            gr.Markdown("#### πŸ›‘οΈ SYSTEM PROTOCOL")
            gr.Markdown("XAI Trace: <span style='color:#00ff00'>ACTIVE</span>")
            gr.Markdown("Token Security: <span style='color:#00ff00'>ENFORCED</span>")

        # OUTPUT COLUMN
        with gr.Column(scale=2, elem_classes="prestige-card"):
            with gr.Tabs(elem_classes="tabs"):
                with gr.TabItem("🧠 REASONING TRACE"):
                    out_1 = gr.Markdown("### *System Idle...*")
                with gr.TabItem("πŸ“Š MASTER REPORT"):
                    out_2 = gr.Markdown("### *Awaiting Phase 1...*")
                with gr.TabItem("βœ‰οΈ AUTONOMOUS REFERRAL"):
                    out_3 = gr.Markdown("### *Awaiting Phase 2...*")

    run_btn.click(
        fn=clinical_orchestrator,
        inputs=[symp, hist, wear],
        outputs=[out_1, out_2, out_3],
        api_name=False
    )

demo.launch()