File size: 4,331 Bytes
00ba0a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""
MedPanel - HuggingFace Spaces Gradio App
"""

import gradio as gr
import torch
import json
import os
from PIL import Image

# Import your MedPanel functions
from medpanel import initialize_models, run_medpanel

# Initialize models
print("πŸš€ Initializing MedPanel...")
HF_TOKEN = os.environ.get('HF_TOKEN')
initialize_models(HF_TOKEN)
print("βœ… Ready!")


def analyze_case(image, clinical_notes):
    """
    Main analysis function for Gradio interface
    
    Args:
        image: PIL Image or None
        clinical_notes: str
    
    Returns:
        JSON string with results
    """
    try:
        if not clinical_notes or len(clinical_notes.strip()) < 10:
            return json.dumps({
                "success": False,
                "error": "Please provide clinical notes (at least 10 characters)"
            }, indent=2)
        
        # Run MedPanel
        result = run_medpanel(image, clinical_notes)
        
        # Parse report
        report = result["final_report"]
        if isinstance(report, dict) and "raw_response" in report:
            try:
                raw = report["raw_response"]
                if not raw.strip().endswith('}'):
                    last_complete = raw.rfind('",')
                    if last_complete > 0:
                        raw = raw[:last_complete+2] + '\n}'
                report = json.loads(raw)
            except:
                pass
        
        # Return formatted response
        response = {
            "success": True,
            "report": report,
            "trace": result["panel_trace"]
        }
        
        return json.dumps(response, indent=2)
        
    except Exception as e:
        return json.dumps({
            "success": False,
            "error": str(e)
        }, indent=2)


# Create Gradio Interface
with gr.Blocks(theme=gr.themes.Soft(), title="MedPanel API") as demo:
    gr.Markdown("""
    # πŸ₯ MedPanel - Multi-Agent Clinical AI
    
    **Multi-specialist AI system for clinical decision support**
    
    *Built for Google MedGemma Impact Challenge 2025*
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### Input")
            image_input = gr.Image(
                type="pil",
                label="πŸ“· Medical Image (Optional)",
                height=300
            )
            notes_input = gr.Textbox(
                lines=8,
                label="πŸ“ Clinical Notes & Symptoms (Required)",
                placeholder="""Example:
65 year old male. Persistent cough for 6 weeks.
Night sweats, 8kg weight loss over 2 months.
Low grade fever. Recently moved from high TB prevalence region.
No prior TB diagnosis. Mild fatigue."""
            )
            submit_btn = gr.Button("β–Ά Run Panel Review", variant="primary", size="lg")
        
        with gr.Column(scale=2):
            gr.Markdown("### Results")
            output = gr.JSON(label="πŸ“‹ MedPanel Report")
    
    gr.Markdown("""
    ---
    ### About
    - 🩻 **Radiologist Agent** - Analyzes medical images
    - 🩺 **Internist Agent** - Analyzes symptoms
    - πŸ“š **Evidence Reviewer** - Searches PubMed
    - 😈 **Devil's Advocate** - Challenges diagnoses
    - 🎯 **Orchestrator** - Synthesizes final report
    
    **⚠️ Disclaimer:** This is a proof-of-concept for research purposes only. Not for actual medical use.
    
    **API Access:** You can call this Space programmatically via the API endpoint shown below.
    """)
    
    # Examples
    gr.Examples(
        examples=[
            [
                None,
                """45 year old female. Severe headache for 3 days.
Fever, stiff neck, photophobia.
No recent travel. No known sick contacts."""
            ],
            [
                None,
                """65 year old male. Persistent cough for 6 weeks.
Night sweats, 8kg weight loss over 2 months.
Low grade fever. Recently moved from high TB prevalence region."""
            ]
        ],
        inputs=[image_input, notes_input],
        label="Try Sample Cases"
    )
    
    submit_btn.click(
        fn=analyze_case,
        inputs=[image_input, notes_input],
        outputs=output
    )

# Launch
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )