File size: 12,751 Bytes
8009765
 
 
 
 
 
ad45b6e
8009765
 
 
 
 
 
 
 
 
 
 
 
78c8cdc
8009765
 
ad45b6e
78c8cdc
8009765
ad45b6e
8009765
ad45b6e
 
 
8009765
 
 
 
78c8cdc
 
ad45b6e
 
8009765
 
ad45b6e
78c8cdc
ad45b6e
78c8cdc
ad45b6e
 
8009765
ad45b6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8009765
 
78c8cdc
8009765
 
 
 
78c8cdc
ad45b6e
 
 
 
 
 
 
 
 
78c8cdc
8009765
 
78c8cdc
 
 
 
 
 
 
 
8009765
 
 
913377b
 
 
 
 
78c8cdc
913377b
78c8cdc
 
 
ad45b6e
 
 
 
 
 
 
 
 
78c8cdc
ad45b6e
78c8cdc
913377b
 
78c8cdc
8009765
913377b
 
8009765
913377b
8009765
 
 
 
913377b
78c8cdc
 
913377b
8009765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad45b6e
 
 
 
 
8009765
 
 
 
913377b
8009765
 
 
 
913377b
 
 
 
 
 
 
 
 
 
 
 
 
 
8009765
 
 
 
913377b
 
78c8cdc
ad45b6e
78c8cdc
8009765
 
 
 
 
 
 
78c8cdc
 
8009765
78c8cdc
8009765
 
 
 
 
 
 
 
 
ad45b6e
 
78c8cdc
 
8009765
 
 
 
 
 
 
913377b
 
8009765
 
78c8cdc
 
 
 
 
 
 
 
 
 
 
ad45b6e
 
 
 
 
 
 
 
 
 
 
 
78c8cdc
 
8009765
ad45b6e
78c8cdc
 
8009765
 
 
 
 
 
 
 
 
 
ad45b6e
8009765
 
ad45b6e
 
8009765
 
78c8cdc
 
 
 
 
 
8009765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78c8cdc
 
8009765
 
 
 
 
ad45b6e
8009765
 
 
 
 
 
913377b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8009765
78c8cdc
8009765
 
ad45b6e
 
 
 
 
 
8009765
 
 
78c8cdc
 
ad45b6e
 
8009765
 
 
 
 
 
 
ad45b6e
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
import os
import torch
import time
import gradio as gr
import requests
from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
from peft import PeftModel
from PIL import Image
from io import BytesIO
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Global variables for model
model = None
processor = None
device = None
model_loaded = False

def load_model():
    """Load the AI model with PEFT adapter (Colab style)"""
    global model, processor, device, model_loaded
    
    logger.info("Loading AI model with PEFT adapter (Colab style)...")
    
    # === Load AI Model === (base model + adapter)
    base_model_id = "google/paligemma-3b-mix-448"
    adapter_model_id = "mychen76/paligemma-3b-mix-448-med_30k-ct-brain"
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    dtype = torch.float16 if torch.cuda.is_available() else torch.float32
    
    logger.info(f"Using device: {device}")
    logger.info(f"Using dtype: {dtype}")
    logger.info(f"CUDA available: {torch.cuda.is_available()}")
    logger.info(f"Base model: {base_model_id}")
    logger.info(f"Adapter model: {adapter_model_id}")
    
    try:
        # Load processor from base model
        logger.info("Loading processor...")
        processor = AutoProcessor.from_pretrained(base_model_id)
        
        # Load base model
        logger.info("Loading base model...")
        model = PaliGemmaForConditionalGeneration.from_pretrained(
            base_model_id, 
            torch_dtype=dtype,
            device_map="auto" if torch.cuda.is_available() else None
        )
        
        # Load PEFT adapter
        logger.info("Loading PEFT adapter...")
        model = PeftModel.from_pretrained(model, adapter_model_id)
        
        # Set to eval mode
        model.eval()
        
        # Move to device if not using device_map
        if not torch.cuda.is_available():
            model = model.to(device)
        
        logger.info("Model loaded successfully!")
        model_loaded = True
        return True
        
    except Exception as e:
        logger.error(f"Error loading model: {e}")
        logger.error(f"Error type: {type(e)}")
        
        # If license error, provide helpful message
        if "license" in str(e).lower() or "access" in str(e).lower():
            logger.error("This appears to be a license/access issue with the base model.")
            logger.error("You may need to:")
            logger.error("1. Accept the license for google/paligemma-3b-mix-448 on HuggingFace")
            logger.error("2. Login with: huggingface-cli login")
            logger.error("3. Use your HuggingFace token")
        
        model_loaded = False
        return False

def run_model(img):
    """Run model inference exactly like Colab"""
    prompt = "<image> Findings:"
    inputs = processor(images=img, text=prompt, return_tensors="pt").to(device, dtype=torch.float16 if torch.cuda.is_available() else torch.float32)
    generated_ids = model.generate(**inputs, max_new_tokens=100)
    result = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
    return result

def analyze_brain_scan(image, patient_name="", patient_age="", symptoms=""):
    """Analyze brain scan image and return medical findings"""
    try:
        logger.info(f"=== ANALYZE FUNCTION CALLED ===")
        logger.info(f"Image received: {image is not None}")
        logger.info(f"Model loaded: {model_loaded}")
        logger.info(f"Model object: {model is not None}")
        
        if not model_loaded or model is None:
            error_msg = """
## ⚠️ Model Loading Error

The AI model is not available. This could be due to:
- **License Issue**: The base model requires accepting Google's license
- **PEFT Loading Issue**: Problem loading the medical adapter
- **Memory limitations**: Insufficient resources
- **Network connectivity**: Download issues

**To fix this:**
1. Accept the license for `google/paligemma-3b-mix-448` on HuggingFace
2. Login with your HuggingFace token: `huggingface-cli login`
3. Restart the application

Please check the logs for more details.
"""
            logger.error("Model not loaded - returning error message")
            return error_msg
        
        if image is None:
            logger.warning("No image provided")
            return "## ⚠️ No Image\n\nPlease upload a brain scan image first, then click 'Analyze Brain Scan'."
        
        logger.info("Converting image to PIL format...")
        # Convert to PIL Image if needed
        if not isinstance(image, Image.Image):
            image = Image.fromarray(image).convert("RGB")
        
        logger.info("Starting AI inference...")
        # Run AI inference using Colab method
        result = run_model(image)
        logger.info(f"AI inference completed. Result length: {len(result) if result else 0}")
        
        # Format the response
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
        
        formatted_result = f"""
## Brain CT Analysis Results

**Patient Information:**
- Name: {patient_name or 'Not provided'}
- Age: {patient_age or 'Not provided'}
- Symptoms: {symptoms or 'Not provided'}
- Analysis Date: {timestamp}

**AI Findings:**
{result}

**Model Info:**
- Base Model: google/paligemma-3b-mix-448
- Medical Adapter: mychen76/paligemma-3b-mix-448-med_30k-ct-brain
- Device: {device}

**Note:** This is an AI-generated analysis for educational purposes only. 
Always consult with qualified medical professionals for actual diagnosis.
"""
        
        logger.info("Analysis completed successfully")
        return formatted_result
        
    except Exception as e:
        logger.error(f"Analysis error: {e}")
        logger.error(f"Error type: {type(e)}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")
        return f"""
## ❌ Analysis Error

An error occurred during analysis:

**Error**: {str(e)}

**Error Type**: {type(e).__name__}

Please check the logs for more details and try again.
"""

def create_api_response(image, patient_name="", patient_age="", symptoms=""):
    """Create API-compatible response for integration"""
    try:
        logger.info(f"=== API RESPONSE FUNCTION CALLED ===")
        
        if not model_loaded or model is None:
            return {"error": "Model not loaded - check license and authentication"}
        
        if image is None:
            return {"error": "No image provided"}
        
        # Convert to PIL Image if needed
        if not isinstance(image, Image.Image):
            image = Image.fromarray(image).convert("RGB")
        
        # Run AI inference using Colab method
        result = run_model(image)
        
        # Create API response (matching your original format)
        response = {
            "prediction": result,
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
            "patient_info": {
                "name": patient_name,
                "age": patient_age,
                "symptoms": symptoms
            },
            "model_info": {
                "base_model": "google/paligemma-3b-mix-448",
                "adapter_model": "mychen76/paligemma-3b-mix-448-med_30k-ct-brain",
                "device": str(device),
                "model_loaded": model_loaded
            }
        }
        
        return response
        
    except Exception as e:
        logger.error(f"API error: {e}")
        import traceback
        logger.error(f"API Traceback: {traceback.format_exc()}")
        return {"error": f"Analysis failed: {str(e)}"}

def get_model_status():
    """Get current model status"""
    return f"""
## πŸ€– Model Status

- **Model Loaded**: {model_loaded}
- **Device**: {device}
- **CUDA Available**: {torch.cuda.is_available()}
- **Model Object**: {type(model).__name__ if model else 'None'}
- **Processor Object**: {type(processor).__name__ if processor else 'None'}
- **PyTorch Version**: {torch.__version__}

## πŸ“‹ Model Configuration

- **Base Model**: google/paligemma-3b-mix-448
- **Medical Adapter**: mychen76/paligemma-3b-mix-448-med_30k-ct-brain
- **Model Type**: PEFT/LoRA Fine-tuned

## ⚠️ Requirements

- HuggingFace account with accepted license for PaliGemma
- HuggingFace token authentication
- PEFT library for adapter loading
"""

# Load model at startup
logger.info("Initializing Brain CT Analyzer with PEFT (Colab Style)...")
load_success = load_model()
if load_success:
    logger.info("Model loaded successfully!")
else:
    logger.error("Failed to load model!")

# Create Gradio interface
with gr.Blocks(title="Brain CT Analyzer", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🧠 Brain CT Analyzer
    
    Upload a brain CT scan image for AI-powered analysis. This tool uses the PaliGemma medical model 
    with specialized medical fine-tuning to provide preliminary findings.
    
    **⚠️ Important:** This is for educational/research purposes only. Always consult qualified medical professionals.
    
    **πŸ”‘ Requirements:** This model requires accepting Google's PaliGemma license and HuggingFace authentication.
    """)
    
    # Model status section
    with gr.Accordion("πŸ”§ Model Status", open=not model_loaded):
        status_output = gr.Markdown(value=get_model_status())
        refresh_btn = gr.Button("πŸ”„ Refresh Status")
        refresh_btn.click(fn=get_model_status, outputs=status_output)
    
    with gr.Row():
        with gr.Column(scale=1):
            image_input = gr.Image(
                label="Upload Brain CT Scan",
                type="pil",
                height=400
            )
            
            with gr.Group():
                patient_name = gr.Textbox(
                    label="Patient Name (Optional)",
                    placeholder="Enter patient name"
                )
                patient_age = gr.Textbox(
                    label="Patient Age (Optional)",
                    placeholder="Enter patient age"
                )
                symptoms = gr.Textbox(
                    label="Symptoms (Optional)",
                    placeholder="Describe symptoms",
                    lines=3
                )
            
            analyze_btn = gr.Button(
                "πŸ” Analyze Brain Scan",
                variant="primary",
                size="lg",
                interactive=model_loaded
            )
        
        with gr.Column(scale=1):
            result_output = gr.Markdown(
                label="Analysis Results",
                value="Upload an image and click 'Analyze Brain Scan' to see results." if model_loaded else "⚠️ Model not loaded. Check status above and ensure license acceptance."
            )
    
    # API endpoint simulation
    with gr.Accordion("πŸ”Œ API Response (for developers)", open=False):
        api_output = gr.JSON(label="API Response Format")
    
    # Test function for debugging
    def test_function():
        logger.info("=== TEST BUTTON CLICKED ===")
        return f"βœ… Test button works! Model loaded: {model_loaded}"
    
    # Add test button for debugging
    with gr.Row():
        test_btn = gr.Button("πŸ§ͺ Test Button (Debug)", variant="secondary")
    test_output = gr.Textbox(label="Test Output", visible=True)
    
    test_btn.click(fn=test_function, outputs=test_output)
    
    # Event handlers - ALWAYS attach, let the function handle the logic
    analyze_btn.click(
        fn=analyze_brain_scan,
        inputs=[image_input, patient_name, patient_age, symptoms],
        outputs=result_output
    )
    
    analyze_btn.click(
        fn=create_api_response,
        inputs=[image_input, patient_name, patient_age, symptoms],
        outputs=api_output
    )
    
    # Instructions
    gr.Markdown("""
    ## πŸ“‹ Usage Instructions:
    1. **Accept License**: Go to [google/paligemma-3b-mix-448](https://huggingface.co/google/paligemma-3b-mix-448) and accept the license
    2. **Authenticate**: Login with `huggingface-cli login` using your token
    3. Upload a brain CT scan image (JPEG or PNG)
    4. Optionally fill in patient information
    5. Click "Analyze Brain Scan" to get AI findings
    6. Review the results in the output panel
    
    ## πŸ”— Integration:
    This interface can be integrated with your medical app using the Gradio API.
    
    ## βœ… Based on Working Colab Code:
    This version uses PEFT to load the medical fine-tuned adapter on top of the base PaliGemma model,
    exactly matching your working Google Colab setup.
    """)

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