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
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
"""
FastAPI Backend Server for AI Prescription Extraction
Main API endpoints and server configuration
"""

from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import os
import json
import asyncio
import logging
from datetime import datetime
import tempfile

from .processor import PrescriptionProcessor, ProcessorFactory
from .utils import FileHandler, PerformanceMonitor, ConfigManager
from .usage_tracker import UsageTracker

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

# Initialize FastAPI app
app = FastAPI(
    title="AI Prescription Extraction API",
    description="Advanced OCR and NLP for prescription image analysis",
    version="1.0.0",
    docs_url="/api/docs",
    redoc_url="/api/redoc"
)

# CORS configuration
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure appropriately for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize components
config_manager = ConfigManager()
file_handler = FileHandler(config_manager.get('file_handling.upload_dir', 'uploads'))
config_manager = ConfigManager()
file_handler = FileHandler(config_manager.get('file_handling.upload_dir', 'uploads'))
performance_monitor = PerformanceMonitor()
usage_tracker = UsageTracker()

# Initialize processor
processor = ProcessorFactory.create_standard_processor()

# Request/Response Models
class ProcessingOptions(BaseModel):
    ocr_engine: Optional[str] = "smart"  # "easyocr", "tesseract", "smart"
    enhancement_level: Optional[str] = "medium"  # "light", "medium", "heavy"
    include_regions: Optional[bool] = False
    export_formats: Optional[List[str]] = ["json"]  # "json", "pdf"

class ProcessingResponse(BaseModel):
    success: bool
    processing_id: str
    timestamp: str
    processing_time_seconds: Optional[float] = 0.0
    raw_text: Optional[str] = ""
    prescription_data: Optional[Dict[str, Any]] = {}
    summary: Optional[str] = ""
    confidence: Optional[Dict[str, float]] = {}
    exports: Optional[Dict[str, Any]] = None
    error: Optional[str] = None

class BatchProcessingRequest(BaseModel):
    file_urls: List[str]
    options: Optional[ProcessingOptions] = None

# Mount static files
os.makedirs("static", exist_ok=True)
os.makedirs("uploads", exist_ok=True)
os.makedirs("outputs", exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")

# Health check endpoint
@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "version": "1.0.0",
        "services": {
            "ocr": "available",
            "nlp": "available",
            "pdf_generation": "available"
        }
    }

# Main processing endpoint
@app.post("/process", response_model=ProcessingResponse)
async def process_prescription(
    file: UploadFile = File(...),
    options: Optional[str] = None,
    background_tasks: BackgroundTasks = BackgroundTasks()
):
    """
    Process prescription image and extract structured information
    
    Args:
        file: Uploaded prescription image
        options: JSON string with processing options
        
    Returns:
        ProcessingResponse with extracted prescription data
    """
    start_time = datetime.now()
    
    try:
        # Parse options
        processing_options = {}
        if options:
            try:
                processing_options = json.loads(options)
            except json.JSONDecodeError:
                logger.warning("Invalid options JSON, using defaults")
        
        # Validate file
        if not file.filename:
            raise HTTPException(status_code=400, detail="No file provided")
        
        # Save uploaded file
        file_content = await file.read()
        file_path = file_handler.save_uploaded_file(file_content, file.filename)
        
        # Schedule cleanup
        background_tasks.add_task(cleanup_file, file_path, delay_hours=1)
        
        # Process prescription
        result = await processor.process_prescription(file_path, processing_options)
        
        # Record performance metrics
        performance_monitor.record_processing(result)
        
        # Convert prescription data for JSON response
        if result.get('success') and 'prescription_data' in result:
            prescription_data = result['prescription_data']
            # Convert dataclass to dict for JSON serialization
            result['prescription_data'] = {
                'patient_name': prescription_data.patient_name,
                'doctor_name': prescription_data.doctor_name,
                'date': prescription_data.date,
                'medicines': [
                    {
                        'name': med.name,
                        'strength': med.strength,
                        'frequency': med.frequency,
                        'duration': med.duration,
                        'instructions': med.instructions,
                        'confidence_score': med.confidence_score
                    }
                    for med in prescription_data.medicines
                ],
                'extraction_confidence': prescription_data.extraction_confidence,
                'is_prescription': getattr(prescription_data, 'is_prescription', True)
            }
        
        return ProcessingResponse(**result)
        
    except Exception as e:
        error_msg = f"Processing failed: {str(e)}"
        logger.error(error_msg)
        
        # Record failed processing
        error_result = {
            'success': False,
            'error': error_msg,
            'processing_time_seconds': (datetime.now() - start_time).total_seconds()
        }
        performance_monitor.record_processing(error_result)
        
        raise HTTPException(status_code=500, detail=error_msg)

# Text regions endpoint
@app.post("/extract-regions")
async def extract_text_regions(file: UploadFile = File(...)):
    """
    Extract text regions with bounding boxes for UI highlighting
    """
    try:
        # Save uploaded file
        file_content = await file.read()
        file_path = file_handler.save_uploaded_file(file_content, file.filename)
        
        # Extract regions
        regions_result = await processor.extract_text_regions(file_path)
        
        # Cleanup file
        try:
            os.remove(file_path)
        except:
            pass
        
        return regions_result
        
    except Exception as e:
        logger.error(f"Region extraction failed: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Batch processing endpoint
@app.post("/batch-process")
async def batch_process_prescriptions(
    files: List[UploadFile] = File(...),
    options: Optional[str] = None
):
    """
    Process multiple prescription images in batch
    """
    try:
        # Parse options
        processing_options = {}
        if options:
            try:
                processing_options = json.loads(options)
            except json.JSONDecodeError:
                pass
        
        # Save all files
        file_paths = []
        for file in files:
            file_content = await file.read()
            file_path = file_handler.save_uploaded_file(file_content, file.filename)
            file_paths.append(file_path)
        
        # Process in batch
        batch_result = await processor.batch_process(file_paths, processing_options)
        
        # Cleanup files
        for file_path in file_paths:
            try:
                os.remove(file_path)
            except:
                pass
        
        return batch_result
        
    except Exception as e:
        logger.error(f"Batch processing failed: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

class InteractionRequest(BaseModel):
    medicines: List[str]

@app.post("/check-interactions")
async def check_interactions(request: InteractionRequest):
    """
    Check for drug interactions between medicines
    """
    try:
        if not processor.use_gemini:
            return {"interactions": [], "warning": "Gemini not available for interaction check"}
            
        # Create dummy medicine objects for the analyzer
        from .gemini_analyzer import GeminiMedicine
        medicines = [GeminiMedicine(name=name) for name in request.medicines]
        
        interactions = processor.nlp_analyzer.check_interactions(medicines)
        
        return {"interactions": interactions}
        
    except Exception as e:
        logger.error(f"Interaction check failed: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

class CalendarRequest(BaseModel):
    medicine_name: str
    frequency: str
    duration: str

@app.post("/generate-calendar")
async def generate_calendar(request: CalendarRequest):
    """
    Generate ICS calendar file for medicine reminders
    """
    try:
        from .calendar_generator import CalendarGenerator
        generator = CalendarGenerator()
        
        ics_content = generator.generate_ics(
            request.medicine_name,
            request.frequency,
            request.duration
        )
        
        # Save to temporary file
        filename = f"reminder_{int(datetime.now().timestamp())}.ics"
        filepath = os.path.join("outputs", filename)
        
        with open(filepath, "w") as f:
            f.write(ics_content)
            
        return {"download_url": f"/export/calendar/{filename}"}
        
    except Exception as e:
        logger.error(f"Calendar generation failed: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/export/calendar/{filename}")
async def download_calendar(filename: str):
    """Download generated calendar file"""
    file_path = os.path.join("outputs", filename)
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="File not found")
        
    return FileResponse(
        file_path,
        media_type="text/calendar",
        filename=filename
    )

# Export endpoints
@app.get("/export/pdf/{processing_id}")
async def download_pdf(processing_id: str):
    """Download generated PDF report"""
    pdf_path = os.path.join("outputs", f"{processing_id}_prescription.pdf")
    
    if not os.path.exists(pdf_path):
        raise HTTPException(status_code=404, detail="PDF not found")
    
    return FileResponse(
        pdf_path,
        media_type="application/pdf",
        filename=f"prescription_report_{processing_id}.pdf"
    )

@app.get("/export/json/{processing_id}")
async def download_json(processing_id: str):
    """Download JSON data"""
    json_path = os.path.join("outputs", f"{processing_id}_prescription.json")
    
    if not os.path.exists(json_path):
        raise HTTPException(status_code=404, detail="JSON not found")
    
    return FileResponse(
        json_path,
        media_type="application/json",
        filename=f"prescription_data_{processing_id}.json"
    )

# Statistics endpoints
@app.get("/stats/performance")
async def get_performance_stats():
    """Get processing performance statistics"""
    return performance_monitor.get_metrics()

@app.get("/stats/processing-history")
async def get_processing_history(limit: int = 50):
    """Get recent processing history"""
    history = processor.get_processing_history(limit)
    
    # Remove sensitive data for public API
    public_history = []
    for item in history:
        public_item = {
            'processing_id': item.get('processing_id'),
            'timestamp': item.get('timestamp'),
            'success': item.get('success'),
            'processing_time_seconds': item.get('processing_time_seconds'),
            'confidence': item.get('confidence'),
            'medicines_count': len(item.get('prescription_data', {}).get('medicines', []))
        }
        public_history.append(public_item)
    
    return {
        'history': public_history,
        'total_items': len(history)
    }

@app.get("/usage")
async def get_api_usage():
    """Get current API usage stats"""
    return usage_tracker.get_usage()

# Configuration endpoints
@app.get("/config")
async def get_config():
    """Get current configuration"""
    return {
        'ocr_engines': ['easyocr', 'tesseract', 'smart'],
        'enhancement_levels': ['light', 'medium', 'heavy'],
        'export_formats': ['json', 'pdf'],
        'max_file_size_mb': config_manager.get('file_handling.max_file_size_mb', 10),
        'allowed_extensions': config_manager.get('file_handling.allowed_extensions', ['.jpg', '.jpeg', '.png']),
        'languages_supported': ['en']
    }

# Debug endpoints (disable in production)
@app.get("/debug/test-ocr")
async def test_ocr():
    """Test OCR engines availability"""
    try:
        from .ocr_engine import PrescriptionOCR
        test_ocr = PrescriptionOCR()
        
        return {
            'easyocr_available': test_ocr.easyocr_available,
            'tesseract_available': test_ocr.tesseract_available
        }
    except Exception as e:
        return {'error': str(e)}

@app.post("/debug/test-processing")
async def test_processing():
    """Test processing with sample image"""
    # Create a simple test image or use existing sample
    sample_path = "sample_prescription.jpg"
    
    if os.path.exists(sample_path):
        result = await processor.process_prescription(sample_path)
        return {'test_result': result}
    else:
        return {'error': 'No sample image available'}

# Utility functions
async def cleanup_file(file_path: str, delay_hours: int = 1):
    """Background task to cleanup uploaded files"""
    await asyncio.sleep(delay_hours * 3600)  # Convert hours to seconds
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
            logger.info(f"Cleaned up file: {file_path}")
    except Exception as e:
        logger.warning(f"Failed to cleanup file {file_path}: {e}")

# Startup event
@app.on_event("startup")
async def startup_event():
    """Initialize services on startup"""
    logger.info("AI Prescription Extraction API starting up...")
    
    # Create necessary directories
    for directory in ["uploads", "outputs", "static"]:
        os.makedirs(directory, exist_ok=True)
    
    # Test OCR engines
    try:
        from .ocr_engine import PrescriptionOCR
        test_ocr = PrescriptionOCR()
        logger.info(f"OCR Status - EasyOCR: {test_ocr.easyocr_available}, Tesseract: {test_ocr.tesseract_available}")
    except Exception as e:
        logger.warning(f"OCR test failed: {e}")
    
    logger.info("API startup completed successfully")

# Shutdown event
@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown"""
    logger.info("AI Prescription Extraction API shutting down...")
    
    # Save performance metrics
    try:
        metrics = performance_monitor.get_metrics()
        with open("performance_metrics.json", "w") as f:
            json.dump(metrics, f, indent=2)
        logger.info("Performance metrics saved")
    except Exception as e:
        logger.warning(f"Failed to save metrics: {e}")
    
    logger.info("API shutdown completed")

# Error handlers
@app.exception_handler(404)
async def not_found_handler(request, exc):
    return JSONResponse(
        status_code=404,
        content={"error": "Endpoint not found", "detail": "Please check the API documentation"}
    )

@app.exception_handler(500)
async def internal_error_handler(request, exc):
    logger.error(f"Internal server error: {exc}")
    return JSONResponse(
        status_code=500,
        content={"error": "Internal server error", "detail": "Please try again later"}
    )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )