File size: 30,012 Bytes
c6a232e
cfb8694
 
 
 
 
699420d
13f19ce
 
 
699420d
 
 
cfb8694
 
699420d
cfb8694
 
 
 
 
 
 
 
 
87e38ae
cfb8694
 
 
 
 
 
 
 
 
13f19ce
cfb8694
 
 
 
 
 
 
 
 
 
 
 
7265b7e
cfb8694
 
 
 
 
 
87e38ae
cfb8694
699420d
cfb8694
 
 
 
699420d
 
cfb8694
699420d
cfb8694
 
 
699420d
 
cfb8694
 
 
 
 
 
 
 
 
699420d
 
 
 
 
 
cfb8694
 
 
 
13f19ce
 
 
 
699420d
 
 
 
 
 
 
 
 
 
 
 
 
 
cfb8694
699420d
 
cfb8694
 
 
 
13f19ce
699420d
 
 
cfb8694
 
 
 
699420d
cfb8694
699420d
cfb8694
699420d
cfb8694
ce18b01
699420d
 
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
699420d
 
 
cfb8694
 
 
 
 
 
 
 
699420d
 
cfb8694
699420d
 
 
 
 
 
 
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699420d
 
cfb8694
699420d
 
 
 
 
13f19ce
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699420d
 
 
 
 
 
cfb8694
 
 
 
 
 
 
 
 
699420d
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699420d
 
 
cfb8694
 
 
 
 
 
 
 
 
 
 
699420d
 
cfb8694
699420d
 
 
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699420d
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699420d
7265b7e
cfb8694
699420d
7265b7e
 
 
 
 
 
cfb8694
699420d
7265b7e
699420d
 
7265b7e
699420d
 
7265b7e
699420d
 
7265b7e
699420d
 
7265b7e
699420d
 
cfb8694
 
 
 
 
 
 
7265b7e
cfb8694
 
 
 
 
 
 
 
 
699420d
cfb8694
 
 
699420d
 
 
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699420d
 
cfb8694
699420d
 
 
 
 
13f19ce
699420d
c6a232e
 
 
 
 
 
 
 
 
 
699420d
 
13f19ce
699420d
13f19ce
699420d
 
 
 
13f19ce
699420d
 
 
 
c6a232e
 
d3c50a6
 
699420d
 
 
 
c6a232e
 
d3c50a6
 
 
 
 
 
 
 
 
 
 
 
 
c6a232e
d3c50a6
 
 
699420d
 
c6a232e
699420d
 
 
 
 
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699420d
 
 
 
 
 
 
 
 
 
 
 
 
 
13f19ce
699420d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfb8694
 
 
699420d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f19ce
699420d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13f19ce
699420d
 
 
 
cfb8694
 
 
 
 
 
 
 
 
13f19ce
cfb8694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
# Suppress TensorFlow warnings
import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# Import with error handling
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import json
from PIL import Image
from typing import Dict, List, Tuple, Optional
import warnings
warnings.filterwarnings('ignore')

# Optional imports with fallbacks
try:
    import librosa
    import librosa.display
    LIBROSA_AVAILABLE = True
    print("βœ… Librosa loaded successfully")
except ImportError:
    print("⚠️ Warning: librosa not available. Audio processing will be limited.")
    LIBROSA_AVAILABLE = False

try:
    import tensorflow as tf
    # Suppress TF warnings
    tf.get_logger().setLevel('ERROR')
    TF_AVAILABLE = True
    print("βœ… TensorFlow loaded successfully")
except ImportError:
    print("⚠️ Warning: TensorFlow not available. Using mock predictions.")
    TF_AVAILABLE = False

try:
    import google.generativeai as genai
    GEMINI_AVAILABLE = True
    print("βœ… Google Generative AI loaded successfully")
except ImportError:
    print("⚠️ Warning: google-generativeai not available. AI features will be limited.")
    GEMINI_AVAILABLE = False

# Configure Gemini AI with error handling
if GEMINI_AVAILABLE and os.getenv("GOOGLE_API_KEY"):
    try:
        genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
        gemini_model = genai.GenerativeModel('gemini-2.0-flash')
    except Exception as e:
        print(f"Warning: Failed to initialize Gemini: {e}")
        GEMINI_AVAILABLE = False
        gemini_model = None
else:
    gemini_model = None

# Load the pre-trained ResNet model with error handling
def load_heartbeat_model():
    if not TF_AVAILABLE:
        print("πŸ“‹ TensorFlow not available - using mock predictions")
        return None
        
    try:
        model = tf.keras.models.load_model('Heart_ResNet.h5')
        print("🎯 Heart_ResNet.h5 model loaded successfully")
        return model
    except Exception as e:
        print(f"πŸ“‹ Could not load Heart_ResNet.h5 model: {e}")
        print("πŸ“‹ Using mock predictions instead")
        return None

# Initialize model (removed @gr.utils.cache decorator)
heartbeat_model = None

def get_heartbeat_model():
    """Get or load the heartbeat model (lazy loading)"""
    global heartbeat_model
    if heartbeat_model is None:
        heartbeat_model = load_heartbeat_model()
    return heartbeat_model

# Global storage for patient data (in production, use a proper database)
patient_data = {}

def process_audio(file_path: str) -> Tuple[np.ndarray, np.ndarray, int]:
    """Process audio file and extract MFCC features."""
    if not LIBROSA_AVAILABLE:
        print("Librosa not available - cannot process audio")
        return None, None, None
        
    SAMPLE_RATE = 22050
    DURATION = 10
    input_length = int(SAMPLE_RATE * DURATION)
    
    try:
        X, sr = librosa.load(file_path, sr=SAMPLE_RATE, duration=DURATION)
        
        if len(X) < input_length:
            pad_width = input_length - len(X)
            X = np.pad(X, (0, pad_width), mode='constant')
        
        mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sr, n_mfcc=52,
                                            n_fft=512, hop_length=256).T, axis=0)
        return mfccs, X, sr
    except Exception as e:
        print(f"Error processing audio: {e}")
        return None, None, None

def analyze_heartbeat(audio_file) -> Tuple[str, str]:
    """Analyze heartbeat audio and return results with visualization."""
    if audio_file is None:
        return "No audio file provided", None
    
    if not LIBROSA_AVAILABLE:
        return "Audio processing not available (librosa not installed)", None
    
    try:
        mfccs, waveform, sr = process_audio(audio_file)
        if mfccs is None:
            return "Error processing audio file", None
        
        # Get model lazily
        model = get_heartbeat_model()
        
        if model is not None and TF_AVAILABLE:
            features = mfccs.reshape(1, 52, 1)
            preds = model.predict(features, verbose=0)  # Suppress prediction output
            class_names = ["artifact", "murmur", "normal"]
            # Convert to percentages and round to nearest 0.1
            results = {name: round(float(preds[0][i]) * 100, 1) for i, name in enumerate(class_names)}
        else:
            # Mock results for demonstration
            import random
            random.seed(42)  # For consistent demo results
            results = {
                "artifact": round(random.uniform(0.5, 2.5), 1),
                "murmur": round(random.uniform(1.5, 3.5), 1), 
                "normal": round(random.uniform(94.0, 98.0), 1)
            }
            # Ensure they sum to 100.0
            total = sum(results.values())
            if total != 100.0:
                # Adjust the largest value to make sum exactly 100.0
                max_key = max(results, key=results.get)
                results[max_key] = round(results[max_key] + (100.0 - total), 1)
        
        # Create waveform visualization
        fig, ax = plt.subplots(figsize=(12, 4))
        if LIBROSA_AVAILABLE:
            librosa.display.waveshow(waveform, sr=sr, ax=ax)
        else:
            # Simple plot if librosa.display not available
            time_axis = np.linspace(0, len(waveform)/sr, len(waveform))
            ax.plot(time_axis, waveform)
            
        ax.set_title("Heartbeat Waveform Analysis", fontsize=14, fontweight='bold')
        ax.set_xlabel("Time (seconds)")
        ax.set_ylabel("Amplitude")
        ax.grid(True, alpha=0.3)
        plt.tight_layout()
        
        # Save plot
        plot_path = f"temp_waveform_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
        plt.savefig(plot_path, dpi=150, bbox_inches='tight')
        plt.close()
        
        # Determine primary classification
        max_class = max(results, key=results.get)
        confidence = results[max_class]
        
        # Status and interpretation
        status = "Model-based analysis" if model else "Demo mode (model not loaded)"
        
        if max_class == "normal" and confidence >= 90.0:
            interpretation = "βœ… Normal heartbeat detected"
        elif max_class == "murmur" and confidence >= 70.0:
            interpretation = "⚠️ Heart murmur detected - recommend medical evaluation"
        elif max_class == "artifact" and confidence >= 50.0:
            interpretation = "πŸ”Š Audio artifact detected - consider re-recording"
        else:
            interpretation = "❓ Inconclusive result - recommend professional evaluation"
        
        # Format results as text
        results_text = f"""🩺 HEART SOUNDS ANALYSIS RESULTS
{'='*45}

πŸ“Š Classification Probabilities:
β€’ Normal Heartbeat: {results['normal']}%
β€’ Heart Murmur: {results['murmur']}%
β€’ Audio Artifact: {results['artifact']}%

🎯 Primary Classification: {max_class.upper()} ({confidence}%)
πŸ” Interpretation: {interpretation}

πŸ“ˆ Analysis Status: {status}
πŸ”Š Audio Duration: {len(waveform)/sr:.1f} seconds
πŸ“ Sample Rate: {sr} Hz

⚠️ Note: This analysis is for educational purposes only.
Always consult a qualified healthcare professional."""
        
        return results_text, plot_path
        
    except Exception as e:
        return f"Error analyzing heartbeat: {str(e)}", None

def analyze_medical_image(image) -> str:
    """Analyze medical images using Gemini Vision."""
    if image is None:
        return "No image provided"
    
    if not GEMINI_AVAILABLE or gemini_model is None:
        return """πŸ”¬ MEDICAL IMAGE ANALYSIS
{'='*40}

⚠️ AI Analysis Not Available
Gemini AI is not configured or installed.

πŸ“‹ MOCK ANALYSIS REPORT:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

πŸ₯ Investigation Type: Medical Image/Scan
πŸ“Š Image Quality: Acceptable for review
πŸ” General Findings: Image appears to show medical investigation

πŸ“ RECOMMENDATIONS:
β€’ Ensure proper medical interpretation by qualified radiologist
β€’ Correlate findings with clinical presentation
β€’ Consider additional imaging if clinically indicated
β€’ Follow institutional protocols for image review

⚠️ IMPORTANT: This is a demonstration mode.
To enable full AI analysis:
1. Install: pip install google-generativeai
2. Set environment variable: GOOGLE_API_KEY
3. Restart the application

🩺 Always consult qualified healthcare professionals for medical interpretation."""
    
    try:
        # Convert to PIL Image if needed
        if not isinstance(image, Image.Image):
            image = Image.fromarray(image)
        
        prompt = """
        As a medical AI assistant, analyze this medical image/investigation result. Please provide a structured report with:

        1. IMAGE TYPE & QUALITY:
        - Type of investigation/scan
        - Image quality assessment
        
        2. TECHNICAL PARAMETERS:
        - Visible technical details
        - Imaging modality characteristics
        
        3. ANATOMICAL STRUCTURES:
        - Clearly visible structures
        - Anatomical landmarks
        
        4. FINDINGS:
        - Normal findings
        - Any abnormalities or areas of concern
        - Measurements if applicable
        
        5. CLINICAL CORRELATION:
        - Significance of findings
        - Recommendations for follow-up
        
        6. LIMITATIONS:
        - Any limitations of the study
        - Areas requiring further evaluation
        
        Please format your response professionally and remember this is for educational purposes only. Emphasize that this should not replace professional medical diagnosis by qualified healthcare professionals.
        """
        
        response = gemini_model.generate_content([prompt, image])
        
        formatted_response = f"""πŸ”¬ AI MEDICAL IMAGE ANALYSIS
{'='*45}

{response.text}

{'='*45}
⚠️ DISCLAIMER: This AI analysis is for educational purposes only.
Always consult qualified healthcare professionals for definitive diagnosis."""
        
        return formatted_response
        
    except Exception as e:
        return f"🚨 Error analyzing image: {str(e)}\n\nPlease check your Gemini API configuration and try again."

def generate_comprehensive_assessment(patient_info: Dict) -> str:
    """Generate comprehensive medical assessment using Gemini AI."""
    if not GEMINI_AVAILABLE or gemini_model is None:
        # Calculate BMI if height and weight available
        bmi_info = ""
        if patient_info.get('weight') and patient_info.get('height'):
            try:
                weight = float(patient_info.get('weight'))
                height = float(patient_info.get('height')) / 100  # Convert cm to m
                bmi = weight / (height * height)
                bmi_info = f"BMI: {bmi:.1f} kg/mΒ²"
            except:
                bmi_info = "BMI: Unable to calculate"
        
        return f"""# πŸ₯ COMPREHENSIVE MEDICAL ASSESSMENT

## πŸ‘€ PATIENT DEMOGRAPHICS
**Name:** {patient_info.get('name', 'Not provided')}  
**Age:** {patient_info.get('age', 'Not provided')} years  
**Sex:** {patient_info.get('sex', 'Not provided')}  
**Weight:** {patient_info.get('weight', 'Not provided')} kg  
**Height:** {patient_info.get('height', 'Not provided')} cm  
{bmi_info}

---

## 🩺 CLINICAL PRESENTATION

### Chief Complaint
{patient_info.get('complaint', 'Not provided')}

### Medical History
{patient_info.get('medical_history', 'Not provided')}

### Physical Examination
{patient_info.get('examination', 'Not provided')}

---

## πŸ”¬ DIAGNOSTIC RESULTS

### Heart Sounds Analysis
{patient_info.get('heartbeat_analysis', 'Not performed')}

### Investigations
{patient_info.get('investigation_analysis', 'Not provided')}

---

## ⚠️ SYSTEM STATUS
**AI-powered comprehensive assessment not available.**  
Please install google-generativeai and configure GOOGLE_API_KEY for full AI features.

---

## πŸ“‹ BASIC RECOMMENDATIONS
1. **Immediate:** Review all clinical findings with qualified healthcare professional
2. **Assessment:** Correlate examination findings with investigation results  
3. **Follow-up:** Consider appropriate follow-up based on clinical presentation
4. **Documentation:** Ensure proper documentation and patient safety protocols

---

## 🍎 GENERAL NUTRITION GUIDELINES
- **Hydration:** Maintain adequate fluid intake (8-10 glasses water/day)
- **Balanced Diet:** Include fruits, vegetables, whole grains, lean proteins
- **Heart Health:** Limit sodium, saturated fats, processed foods
- **Portion Control:** Maintain healthy portion sizes based on BMI

---

**⚠️ DISCLAIMER:** This assessment is for educational purposes only. Always consult qualified healthcare professionals for medical decisions."""
    
    try:
        # Calculate BMI if available
        bmi_calculation = ""
        if patient_info.get('weight') and patient_info.get('height'):
            try:
                weight = float(patient_info.get('weight'))
                height = float(patient_info.get('height')) / 100  # Convert cm to m
                bmi = weight / (height * height)
                
                if bmi < 18.5:
                    bmi_status = "Underweight"
                elif 18.5 <= bmi < 25:
                    bmi_status = "Normal weight"
                elif 25 <= bmi < 30:
                    bmi_status = "Overweight"
                else:
                    bmi_status = "Obese"
                    
                bmi_calculation = f"BMI: {bmi:.1f} kg/mΒ² ({bmi_status})"
            except:
                bmi_calculation = "BMI: Unable to calculate"
        
        # Prepare enhanced prompt with nutrition requirements
        prompt = f"""
        **As a comprehensive medical AI, provide a detailed professional medical assessment based on the following patient data**
        Format your response with clear headings and professional medical language:

        ## PATIENT DEMOGRAPHICS:
        -**Name:** {patient_info.get('name', 'Not provided')}
        - **Age:** {patient_info.get('age', 'Not provided')} years
        - **Sex:** {patient_info.get('sex', 'Not provided')}
        - **Weight:** {patient_info.get('weight', 'Not provided')} kg
        - **Height:** {patient_info.get('height', 'Not provided')} cm
        - {bmi_calculation}

        ## CHIEF COMPLAINT:
        {patient_info.get('complaint', 'Not provided')}

        ## MEDICAL HISTORY:
        {patient_info.get('medical_history', 'Not provided')}

        ## PHYSICAL EXAMINATION:
        {patient_info.get('examination', 'Not provided')}

        ## HEART SOUNDS ANALYSIS:
        {patient_info.get('heartbeat_analysis', 'Not performed')}

        ## INVESTIGATIONS:
        {patient_info.get('investigation_analysis', 'Not provided')}

        Please provide a comprehensive medical assessment with the following structure:

        1. **CLINICAL SUMMARY** - Concise overview of the case
        2. **DIFFERENTIAL DIAGNOSIS** - List possible conditions with rationale
        3. **RISK FACTORS ASSESSMENT** - Identify relevant risk factors
        4. **RECOMMENDED TREATMENT PLAN** - Detailed treatment approach
        5. **FOLLOW-UP RECOMMENDATIONS** - Specific follow-up plans
        6. **NUTRITIONAL MANAGEMENT PLAN** - summerized nutrition recommendations based on:
           - Patient's current condition
           - Age and sex-specific requirements
           - Weight management if needed
           - Heart health considerations
           - Specific dietary modifications for the condition
           - Meal planning suggestions
           - Hydration recommendations
        7. **PATIENT EDUCATION POINTS** - Key points for patient understanding
        8. **PROGNOSIS** - Expected outcomes and timeline

        Please use professional medical terminology and format with clear headings. 
        Make the nutritional section comprehensive and specific to this patient's needs.
        Remember this is for educational purposes and emphasize the need for professional medical consultation.
        """
        
        response = gemini_model.generate_content(prompt)
        
        # Format the response with better styling
        formatted_response = f"""# πŸ₯ COMPREHENSIVE MEDICAL ASSESSMENT

## πŸ‘€ PATIENT INFORMATION
**Name:** {patient_info.get('name', 'Not provided')}  
**Age:** {patient_info.get('age', 'Not provided')} years  
**Sex:** {patient_info.get('sex', 'Not provided')}  
**Weight:** {patient_info.get('weight', 'Not provided')} kg  
**Height:** {patient_info.get('height', 'Not provided')} cm  
**{bmi_calculation}**

---

{response.text}

---

## ⚠️ IMPORTANT DISCLAIMERS
- **Educational Purpose:** This assessment is for educational purposes only
- **Professional Consultation:** Always consult qualified healthcare professionals
- **Emergency:** Seek immediate medical attention for urgent symptoms
- **AI Limitations:** AI analysis supplements but does not replace clinical judgment

---

**Generated on:** {datetime.now().strftime('%Y-%m-%d at %H:%M:%S')}"""
        
        return formatted_response
        
    except Exception as e:
        return f"# ❌ Error Generating Assessment\n\n**Error Details:** {str(e)}\n\nPlease check your Gemini API configuration and try again."

def save_patient_data(name, age, sex, weight, height, complaint, medical_history, 
                     examination, heartbeat_results, investigation_analysis):
    """Save all patient data to global storage."""
    global patient_data
    
    patient_data = {
        'name': name if name else 'Not provided',
        'age': age if age else 'Not provided',
        'sex': sex if sex else 'Not provided',
        'weight': weight if weight else 'Not provided',
        'height': height if height else 'Not provided',
        'complaint': complaint if complaint else 'Not provided',
        'medical_history': medical_history if medical_history else 'Not provided',
        'examination': examination if examination else 'Not provided',
        'heartbeat_analysis': heartbeat_results if heartbeat_results else 'Not performed',
        'investigation_analysis': investigation_analysis if investigation_analysis else 'Not provided',
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    
    return "Patient data saved successfully!"

def process_complete_consultation(name, age, sex, weight, height, complaint, 
                                medical_history, examination, audio_file, 
                                investigation_image):
    """Process complete medical consultation."""
    
    # Analyze heartbeat if audio provided
    heartbeat_results = ""
    waveform_plot = None
    if audio_file is not None:
        heartbeat_analysis, plot_path = analyze_heartbeat(audio_file)
        heartbeat_results = heartbeat_analysis if heartbeat_analysis else ""
        waveform_plot = plot_path
    
    # Analyze investigation image if provided
    investigation_analysis = ""
    if investigation_image is not None:
        investigation_analysis = analyze_medical_image(investigation_image)
    
    # Create patient data dictionary with proper handling
    patient_data_dict = {
        'name': name if name else 'Not provided',
        'age': age if age else 'Not provided',
        'sex': sex if sex else 'Not provided',
        'weight': weight if weight else 'Not provided',
        'height': height if height else 'Not provided',
        'complaint': complaint if complaint else 'Not provided',
        'medical_history': medical_history if medical_history else 'Not provided',
        'examination': examination if examination else 'Not provided',
        'heartbeat_analysis': heartbeat_results if heartbeat_results else 'Not performed',
        'investigation_analysis': investigation_analysis if investigation_analysis else 'Not provided'
    }
    
    # Save patient data to global variable
    global patient_data
    patient_data = patient_data_dict.copy()
    patient_data['timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # Generate comprehensive assessment
    comprehensive_assessment = generate_comprehensive_assessment(patient_data_dict)
    
    return comprehensive_assessment, waveform_plot, heartbeat_results, investigation_analysis

# Create Gradio interface
def create_interface():
    with gr.Blocks(
        title="Comprehensive Medical Consultation System", 
        theme=gr.themes.Soft(),
        css="""
        .medical-assessment textarea {
            font-size: 16px !important;
            line-height: 1.6 !important;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
        }
        .gradio-container {
            font-size: 14px;
        }
        .gr-textbox textarea {
            font-size: 14px !important;
        }
        h1, h2, h3 {
            color: #2c3e50 !important;
        }
        .medical-assessment .gr-textbox {
            background-color: #f8f9fa !important;
        }
        """
    ) as demo:
        
        gr.Markdown("""
        # πŸ₯ Comprehensive Medical Consultation System
        ### Integrated AI-Powered Medical Assessment Platform
        """)
        
        with gr.Tab("πŸ“‹ Patient Information"):
            gr.Markdown("## Patient Demographics")
            
            with gr.Row():
                with gr.Column():
                    name = gr.Textbox(label="Full Name", placeholder="Enter patient's full name")
                    age = gr.Number(label="Age (years)", minimum=0, maximum=120)
                    sex = gr.Radio(["Male", "Female", "Other"], label="Sex")
                
                with gr.Column():
                    weight = gr.Number(label="Weight (kg)", minimum=0, maximum=300)
                    height = gr.Number(label="Height (cm)", minimum=0, maximum=250)
            
            gr.Markdown("## Chief Complaint")
            complaint = gr.Textbox(
                label="Chief Complaint", 
                placeholder="Describe the main symptoms or reason for consultation...",
                lines=3
            )
            
            gr.Markdown("## Medical History")
            medical_history = gr.Textbox(
                label="Past Medical History",
                placeholder="Include previous illnesses, surgeries, medications, allergies, family history...",
                lines=5
            )
        
        with gr.Tab("🩺 Physical Examination"):
            gr.Markdown("## Physical Examination Findings")
            
            examination = gr.Textbox(
                label="Examination Findings",
                placeholder="General appearance, vital signs, systemic examination findings...",
                lines=6
            )
            
            gr.Markdown("## Heart Sounds Analysis")
            audio_file = gr.Audio(
                label="Heart Sounds Recording",
                type="filepath",
                sources=["upload", "microphone"]
            )
            
            heartbeat_analyze_btn = gr.Button("πŸ” Analyze Heart Sounds", variant="secondary")
            heartbeat_results = gr.Textbox(label="Heart Sounds Analysis Results", lines=4)
            waveform_plot = gr.Image(label="Heart Sounds Waveform")
            
            heartbeat_analyze_btn.click(
                fn=analyze_heartbeat,
                inputs=[audio_file],
                outputs=[heartbeat_results, waveform_plot]
            )
        
        with gr.Tab("πŸ”¬ Investigations"):
            gr.Markdown("## Medical Investigations & Imaging")
            
            investigation_image = gr.Image(
                label="Upload Investigation Results (X-ray, ECG, Lab reports, etc.)",
                type="pil"
            )
            
            investigate_btn = gr.Button("πŸ” Analyze Investigation", variant="secondary")
            investigation_results = gr.Textbox(
                label="Investigation Analysis", 
                lines=6,
                placeholder="AI analysis of uploaded investigation will appear here..."
            )
            
            investigate_btn.click(
                fn=analyze_medical_image,
                inputs=[investigation_image],
                outputs=[investigation_results]
            )
        
        with gr.Tab("πŸ€– AI Assessment"):
            gr.Markdown("## Comprehensive Medical Assessment")
            
            generate_btn = gr.Button(
                "🧠 Generate Comprehensive Assessment", 
                variant="primary",
                size="lg"
            )
            
            assessment_output = gr.Textbox(
                label="AI-Generated Medical Assessment",
                lines=20,  # Increased from 15 to 20 for more space
                placeholder="Complete medical assessment will be generated here based on all provided information...",
                elem_classes=["medical-assessment"]  # Add CSS class for styling
            )
            
            # Hidden outputs to collect all data
            hidden_heartbeat = gr.Textbox(visible=False)
            hidden_investigation = gr.Textbox(visible=False)
            hidden_waveform = gr.Image(visible=False)
            
            generate_btn.click(
                fn=process_complete_consultation,
                inputs=[name, age, sex, weight, height, complaint, medical_history,
                       examination, audio_file, investigation_image],
                outputs=[assessment_output, hidden_waveform, hidden_heartbeat, 
                        hidden_investigation]
            )
        
        with gr.Tab("πŸ“Š Patient Summary"):
            gr.Markdown("## Patient Data Summary")
            
            refresh_btn = gr.Button("πŸ”„ Refresh Patient Data", variant="secondary")
            
            with gr.Row():
                with gr.Column():
                    summary_demographics = gr.JSON(label="Demographics")
                    summary_clinical = gr.JSON(label="Clinical Data")
                
                with gr.Column():
                    summary_results = gr.JSON(label="Investigation Results")
            
            def refresh_patient_summary():
                if patient_data:
                    demographics = {
                        "Name": patient_data.get('name', 'N/A'),
                        "Age": patient_data.get('age', 'N/A'),
                        "Sex": patient_data.get('sex', 'N/A'),
                        "Weight": f"{patient_data.get('weight', 'N/A')} kg",
                        "Height": f"{patient_data.get('height', 'N/A')} cm"
                    }
                    
                    clinical = {
                        "Chief Complaint": patient_data.get('complaint', 'N/A'),
                        "Medical History": patient_data.get('medical_history', 'N/A')[:100] + "..." if len(patient_data.get('medical_history', '')) > 100 else patient_data.get('medical_history', 'N/A'),
                        "Examination": patient_data.get('examination', 'N/A')[:100] + "..." if len(patient_data.get('examination', '')) > 100 else patient_data.get('examination', 'N/A')
                    }
                    
                    results = {
                        "Heartbeat Analysis": "Completed" if patient_data.get('heartbeat_analysis') else "Not performed",
                        "Investigation Analysis": "Completed" if patient_data.get('investigation_analysis') else "Not performed",
                        "Last Updated": patient_data.get('timestamp', 'N/A')
                    }
                    
                    return demographics, clinical, results
                else:
                    return {}, {}, {}
            
            refresh_btn.click(
                fn=refresh_patient_summary,
                outputs=[summary_demographics, summary_clinical, summary_results]
            )
        
        gr.Markdown("""
        ---
        ### πŸ“ Important Notes:
        - This system is for educational and research purposes only
        - Always consult qualified healthcare professionals for medical decisions  
        - Ensure patient privacy and data protection compliance
        - AI assessments should supplement, not replace, clinical judgment
        """)
    
    return demo

# Launch the application
if __name__ == "__main__":
    print("\nπŸ₯ MEDICAL CONSULTATION SYSTEM")
    print("=" * 50)
    
    # Check system status
    print("πŸ“‹ System Status Check:")
    print(f"βœ… Gradio: Available")
    print(f"{'βœ…' if LIBROSA_AVAILABLE else '⚠️'} Librosa: {'Available' if LIBROSA_AVAILABLE else 'Not installed'}")
    print(f"{'βœ…' if TF_AVAILABLE else '⚠️'} TensorFlow: {'Available' if TF_AVAILABLE else 'Not installed'}")
    print(f"{'βœ…' if GEMINI_AVAILABLE else '⚠️'} Gemini AI: {'Available' if GEMINI_AVAILABLE else 'Not installed'}")
    
    # Check Gemini API key
    if GEMINI_AVAILABLE:
        if os.getenv("GOOGLE_API_KEY"):
            print("πŸ”‘ Gemini API Key: Configured")
        else:
            print("⚠️ Gemini API Key: Not set (AI features limited)")
            print("   Set with: export GOOGLE_API_KEY='your_api_key_here'")
    
    print("\nπŸš€ Starting application...")
    print("🌐 The app will be available at: http://localhost:7860")
    print("=" * 50)
    
    try:
        demo = create_interface()
        demo.launch(
            server_name="0.0.0.0",
            server_port=7860,
            share=True,
            debug=False,  # Set to False to reduce console output
            show_error=True
        )
    except Exception as e:
        print(f"❌ Error starting application: {e}")
        print("Please check the error message above and ensure all dependencies are installed correctly.")