File size: 18,399 Bytes
7a00767
 
 
 
57cb63a
 
7a00767
 
57cb63a
7a00767
3d47039
57cb63a
 
 
 
7a00767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57cb63a
 
 
7a00767
 
 
 
 
 
 
57cb63a
7a00767
57cb63a
 
7a00767
 
57cb63a
7a00767
57cb63a
 
7a00767
 
 
 
 
 
57cb63a
7a00767
 
 
 
 
 
 
 
 
 
 
 
 
 
57cb63a
 
7a00767
57cb63a
 
7a00767
 
 
 
 
 
 
 
57cb63a
7a00767
 
 
 
 
57cb63a
7a00767
 
 
 
 
 
 
 
 
 
 
 
 
 
57cb63a
7a00767
57cb63a
7a00767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57cb63a
7a00767
 
 
 
 
 
 
57cb63a
7a00767
 
57cb63a
7a00767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57cb63a
7a00767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57cb63a
3d47039
7a00767
 
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
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import base64
import io
from PIL import Image
from lab_analyzer import LabReportAnalyzer
import logging
import os

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

# Initialize FastAPI app
app = FastAPI(
    title="Lab Report Analysis API",
    description="AI-powered lab report analysis service using Google AI Studio",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure this properly for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize the lab analyzer
analyzer = LabReportAnalyzer()

@app.get("/health")
async def health_check():
    """Health check endpoint for monitoring"""
    return {"status": "healthy", "service": "lab-report-analyzer"}

@app.post("/analyze")
async def analyze_lab_report(file: UploadFile = File(...)):
    """

    Analyze a lab report image and return structured results

    

    Args:

        file: Uploaded image file (jpg, jpeg, png, bmp, tiff, webp)

    

    Returns:

        JSON response with analysis results

    """
    try:
        # Validate file type
        if not file.content_type.startswith('image/'):
            raise HTTPException(
                status_code=400, 
                detail="File must be an image (jpg, jpeg, png, bmp, tiff, webp)"
            )
        
        # Read and validate image
        contents = await file.read()
        if len(contents) == 0:
            raise HTTPException(status_code=400, detail="Empty file uploaded")
        
        # Validate image can be opened
        try:
            image = Image.open(io.BytesIO(contents))
            image.verify()  # Verify it's a valid image
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"Invalid image file: {str(e)}")
        
        # Convert to base64 for analysis
        image_b64 = base64.b64encode(contents).decode("utf-8")
        
        # Analyze the lab report
        logger.info(f"Analyzing lab report: {file.filename}")
        analysis_result = await analyzer.analyze_report(image_b64)
        
        return JSONResponse(
            status_code=200,
            content={
                "success": True,
                "filename": file.filename,
                "analysis": analysis_result
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error analyzing lab report: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

@app.post("/analyze-base64")
async def analyze_lab_report_base64(data: dict):
    """

    Analyze a lab report from base64 encoded image

    

    Args:

        data: JSON with 'image' key containing base64 encoded image

    

    Returns:

        JSON response with analysis results

    """
    try:
        if 'image' not in data:
            raise HTTPException(status_code=400, detail="Missing 'image' field in request body")
        
        image_b64 = data['image']
        
        # Remove data:image/...;base64, prefix if present
        if image_b64.startswith('data:image'):
            image_b64 = image_b64.split(',')[1]
        
        # Validate base64 and image
        try:
            image_bytes = base64.b64decode(image_b64)
            image = Image.open(io.BytesIO(image_bytes))
            image.verify()
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"Invalid base64 image: {str(e)}")
        
        # Analyze the lab report
        logger.info("Analyzing lab report from base64 data")
        analysis_result = await analyzer.analyze_report(image_b64)
        
        return JSONResponse(
            status_code=200,
            content={
                "success": True,
                "analysis": analysis_result
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error analyzing base64 lab report: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

# Flutter-friendly endpoint aliases
@app.post("/api/analyze-lab")
async def analyze_lab_api(file: UploadFile = File(...)):
    """Flutter-friendly endpoint for lab analysis"""
    return await analyze_lab_report(file)

@app.post("/api/analyze-lab-base64")
async def analyze_lab_base64_api(data: dict):
    """Flutter-friendly endpoint for base64 lab analysis"""
    return await analyze_lab_report_base64(data)

@app.get("/", response_class=HTMLResponse)
async def root():
    """Main page with upload interface"""
    return """

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>πŸ₯ Lab Report Analysis AI</title>

        <style>

            * { margin: 0; padding: 0; box-sizing: border-box; }

            body { 

                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 

                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

                min-height: 100vh;

                padding: 20px;

            }

            .container { 

                max-width: 1200px; 

                margin: 0 auto; 

                background: white; 

                border-radius: 20px; 

                box-shadow: 0 20px 60px rgba(0,0,0,0.1);

                overflow: hidden;

            }

            .header { 

                background: linear-gradient(45deg, #2196F3, #21CBF3);

                color: white; 

                padding: 40px; 

                text-align: center; 

            }

            .header h1 { font-size: 2.5em; margin-bottom: 10px; }

            .header p { font-size: 1.2em; opacity: 0.9; }

            .content { padding: 40px; }

            .upload-area { 

                border: 3px dashed #2196F3; 

                border-radius: 15px; 

                padding: 40px; 

                text-align: center; 

                margin: 20px 0;

                transition: all 0.3s ease;

                cursor: pointer;

            }

            .upload-area:hover { 

                border-color: #1976D2; 

                background-color: #f5f5f5; 

            }

            .upload-area.dragover { 

                border-color: #4CAF50; 

                background-color: #e8f5e8; 

            }

            input[type="file"] { display: none; }

            .btn { 

                background: linear-gradient(45deg, #2196F3, #21CBF3);

                color: white; 

                border: none; 

                padding: 15px 30px; 

                border-radius: 25px; 

                cursor: pointer; 

                font-size: 16px;

                margin: 10px;

                transition: transform 0.2s ease;

            }

            .btn:hover { transform: translateY(-2px); }

            .btn:disabled { 

                background: #ccc; 

                cursor: not-allowed; 

                transform: none;

            }

            .result { 

                margin-top: 30px; 

                padding: 20px; 

                border-radius: 10px; 

                background: #f8f9fa;

                border-left: 5px solid #2196F3;

            }

            .loading { 

                text-align: center; 

                color: #2196F3; 

                font-size: 18px;

            }

            .error { 

                background: #ffebee; 

                border-left-color: #f44336; 

                color: #c62828;

            }

            .success { 

                background: #e8f5e8; 

                border-left-color: #4CAF50; 

            }

            .api-info {

                background: #f0f4f8;

                padding: 30px;

                margin-top: 40px;

                border-radius: 15px;

            }

            .endpoint {

                background: #fff;

                padding: 15px;

                margin: 10px 0;

                border-radius: 8px;

                border-left: 4px solid #2196F3;

            }

            .method {

                background: #2196F3;

                color: white;

                padding: 4px 8px;

                border-radius: 4px;

                font-weight: bold;

                font-size: 12px;

            }

            pre {

                background: #2d3748;

                color: #e2e8f0;

                padding: 15px;

                border-radius: 8px;

                overflow-x: auto;

                margin: 10px 0;

            }

            .features {

                display: grid;

                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

                gap: 20px;

                margin: 30px 0;

            }

            .feature {

                text-align: center;

                padding: 20px;

                border-radius: 10px;

                background: #f8f9fa;

            }

            .feature-icon {

                font-size: 2em;

                margin-bottom: 10px;

            }

        </style>

    </head>

    <body>

        <div class="container">

            <div class="header">

                <h1>πŸ₯ Lab Report Analysis AI</h1>

                <p>AI-powered medical lab report analysis using Google AI Studio</p>

            </div>

            

            <div class="content">

                <div class="features">

                    <div class="feature">

                        <div class="feature-icon">πŸ“Έ</div>

                        <h3>Image Upload</h3>

                        <p>Support for JPG, PNG, TIFF, and more</p>

                    </div>

                    <div class="feature">

                        <div class="feature-icon">πŸ€–</div>

                        <h3>AI Analysis</h3>

                        <p>Google Gemini 2.0 Flash model</p>

                    </div>

                    <div class="feature">

                        <div class="feature-icon">πŸ“Š</div>

                        <h3>Structured Results</h3>

                        <p>Summary, findings, and interpretations</p>

                    </div>

                    <div class="feature">

                        <div class="feature-icon">⚑</div>

                        <h3>Fast Processing</h3>

                        <p>Real-time analysis results</p>

                    </div>

                </div>



                <div class="upload-area" onclick="document.getElementById('fileInput').click()">

                    <h3>πŸ“€ Upload Lab Report Image</h3>

                    <p>Click here or drag and drop your lab report image</p>

                    <input type="file" id="fileInput" accept="image/*">

                </div>

                

                <div style="text-align: center;">

                    <button class="btn" onclick="analyzeImage()" id="analyzeBtn" disabled>

                        πŸ”¬ Analyze Report

                    </button>

                    <button class="btn" onclick="clearResults()">

                        πŸ—‘οΈ Clear

                    </button>

                </div>

                

                <div id="result"></div>



                <div class="api-info">

                    <h2>πŸ”§ API Documentation</h2>

                    <p>This service provides RESTful API endpoints for programmatic access:</p>

                    

                    <div class="endpoint">

                        <span class="method">POST</span> <strong>/analyze</strong>

                        <p>Upload lab report image file for analysis</p>

                    </div>

                    

                    <div class="endpoint">

                        <span class="method">POST</span> <strong>/analyze-base64</strong>

                        <p>Analyze lab report from base64 encoded image</p>

                    </div>

                    

                    <div class="endpoint">

                        <span class="method">POST</span> <strong>/api/analyze-lab</strong>

                        <p>Flutter-friendly endpoint for file upload</p>

                    </div>

                    

                    <div class="endpoint">

                        <span class="method">POST</span> <strong>/api/analyze-lab-base64</strong>

                        <p>Flutter-friendly endpoint for base64 analysis</p>

                    </div>



                    <p><strong>πŸ“š Interactive Documentation:</strong></p>

                    <button class="btn" onclick="window.open('/docs', '_blank')">

                        πŸ“– OpenAPI Docs

                    </button>

                    <button class="btn" onclick="window.open('/redoc', '_blank')">

                        πŸ“˜ ReDoc

                    </button>

                </div>



                <div style="text-align: center; margin-top: 40px; color: #666;">

                    <p>⚠️ This tool is for educational purposes only. Always consult healthcare professionals for medical advice.</p>

                </div>

            </div>

        </div>



        <script>

            let selectedFile = null;



            document.getElementById('fileInput').addEventListener('change', function(e) {

                selectedFile = e.target.files[0];

                if (selectedFile) {

                    document.querySelector('.upload-area h3').innerHTML = 'βœ… ' + selectedFile.name;

                    document.getElementById('analyzeBtn').disabled = false;

                }

            });



            // Drag and drop functionality

            const uploadArea = document.querySelector('.upload-area');

            uploadArea.addEventListener('dragover', (e) => {

                e.preventDefault();

                uploadArea.classList.add('dragover');

            });

            uploadArea.addEventListener('dragleave', () => {

                uploadArea.classList.remove('dragover');

            });

            uploadArea.addEventListener('drop', (e) => {

                e.preventDefault();

                uploadArea.classList.remove('dragover');

                const files = e.dataTransfer.files;

                if (files.length > 0) {

                    selectedFile = files[0];

                    document.querySelector('.upload-area h3').innerHTML = 'βœ… ' + selectedFile.name;

                    document.getElementById('analyzeBtn').disabled = false;

                }

            });



            async function analyzeImage() {

                if (!selectedFile) {

                    alert('Please select an image first');

                    return;

                }



                const resultDiv = document.getElementById('result');

                resultDiv.innerHTML = '<div class="result loading">πŸ”„ Analyzing lab report...</div>';

                

                const analyzeBtn = document.getElementById('analyzeBtn');

                analyzeBtn.disabled = true;

                analyzeBtn.innerHTML = '⏳ Processing...';



                const formData = new FormData();

                formData.append('file', selectedFile);



                try {

                    const response = await fetch('/analyze', {

                        method: 'POST',

                        body: formData

                    });



                    const data = await response.json();



                    if (data.success) {

                        const analysis = data.analysis;

                        resultDiv.innerHTML = `

                            <div class="result success">

                                <h3>πŸ“Š Analysis Results</h3>

                                <h4>πŸ“‹ Summary</h4>

                                <p>${analysis.summary || 'No summary available'}</p>

                                

                                <h4>πŸ” Key Findings</h4>

                                <ul>

                                    ${analysis.key_findings?.map(finding => `<li>${finding}</li>`).join('') || '<li>No specific findings identified</li>'}

                                </ul>

                                

                                <h4>πŸ’‘ Interpretation</h4>

                                <p>${analysis.interpretation || 'No interpretation available'}</p>

                                

                                <h4>⚠️ Important Note</h4>

                                <p><em>${analysis.note || 'This analysis is for educational purposes only and should not replace professional medical advice.'}</em></p>

                            </div>

                        `;

                    } else {

                        resultDiv.innerHTML = `<div class="result error">❌ Error: ${data.error || 'Analysis failed'}</div>`;

                    }

                } catch (error) {

                    resultDiv.innerHTML = `<div class="result error">❌ Error: ${error.message}</div>`;

                } finally {

                    analyzeBtn.disabled = false;

                    analyzeBtn.innerHTML = 'πŸ”¬ Analyze Report';

                }

            }



            function clearResults() {

                document.getElementById('result').innerHTML = '';

                document.getElementById('fileInput').value = '';

                document.querySelector('.upload-area h3').innerHTML = 'πŸ“€ Upload Lab Report Image';

                document.getElementById('analyzeBtn').disabled = true;

                selectedFile = null;

            }

        </script>

    </body>

    </html>

    """

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)