""" 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" )