app / backend /processor.py
sabareesh4317
Increase processing timeout and fix error handling
0c78c26
Raw History Blame Contribute Delete
19.1 kB
"""
Main Prescription Processor
Combines OCR and NLP for complete prescription analysis
"""
import os
import json
import logging
from typing import Dict, Any, Optional, List
from datetime import datetime
import asyncio
from pathlib import Path
from .ocr_engine import PrescriptionOCR
from .nlp_analyzer import PrescriptionNLPAnalyzer, PrescriptionData
from .gemini_analyzer import GeminiPrescriptionAnalyzer
from .pdf_generator import PrescriptionPDFGenerator
from .utils import ImageValidator, FileHandler
class PrescriptionProcessor:
"""
Main processor for prescription image analysis
Orchestrates OCR, NLP, and export functionality
"""
def __init__(self, config: Optional[Dict] = None):
"""
Initialize processor with configuration
Args:
config: Optional configuration dictionary
"""
self.config = config or self._default_config()
# Initialize components
self.ocr_engine = PrescriptionOCR(
languages=self.config.get('languages', ['en']),
use_gpu=self.config.get('use_gpu', False),
fallback_to_tesseract=self.config.get('fallback_to_tesseract', True)
)
# Try to use Gemini analyzer, fallback to basic NLP if API key invalid
try:
gemini_api_key = os.getenv('GEMINI_API_KEY', 'AIzaSyD72bMoC9tuQyz2QZTWEQqaM2TXk4M_wI0') # Valid API key
self.nlp_analyzer = GeminiPrescriptionAnalyzer(gemini_api_key)
self.use_gemini = True
print("βœ… Using Gemini Expert Pharmacist Analyzer")
except Exception as e:
print(f"❌ Gemini unavailable: {e}")
print("πŸ”„ Falling back to basic NLP analyzer")
self.nlp_analyzer = PrescriptionNLPAnalyzer()
self.use_gemini = False
self.pdf_generator = PrescriptionPDFGenerator()
self.image_validator = ImageValidator()
self.file_handler = FileHandler(self.config.get('upload_dir', 'uploads'))
# Setup logging
self._setup_logging()
# Processing history (in-memory for demo, use database in production)
self.processing_history = []
def _default_config(self) -> Dict:
"""Default configuration"""
return {
'languages': ['en'],
'use_gpu': False,
'fallback_to_tesseract': True,
'max_file_size_mb': 10,
'allowed_extensions': ['.jpg', '.jpeg', '.png', '.pdf'],
'upload_dir': 'uploads',
'output_dir': 'outputs',
'enable_history': True,
'ocr_confidence_threshold': 0.3,
'processing_timeout': 300,
}
def _setup_logging(self):
"""Setup logging configuration"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
self.logger = logging.getLogger(__name__)
async def process_prescription(self, file_path: str, options: Optional[Dict] = None) -> Dict[str, Any]:
"""
Main processing function for prescription images
Args:
file_path: Path to the prescription image
options: Processing options
Returns:
Complete processing result dictionary
"""
start_time = datetime.now()
processing_id = f"proc_{int(start_time.timestamp())}"
self.logger.info(f"Starting prescription processing: {processing_id}")
try:
# Validate file
validation_result = await self._validate_file(file_path)
if not validation_result['valid']:
return {
'success': False,
'error': validation_result['error'],
'processing_id': processing_id,
'timestamp': start_time.isoformat()
}
# Process with timeout
result = await asyncio.wait_for(
self._process_internal(file_path, options, processing_id),
timeout=self.config.get('processing_timeout', 60)
)
# Add processing metadata
result.update({
'processing_id': processing_id,
'timestamp': start_time.isoformat(),
'processing_time_seconds': (datetime.now() - start_time).total_seconds(),
'file_info': validation_result['file_info']
})
# Save to history
if self.config.get('enable_history', True):
self.processing_history.append(result)
self.logger.info(f"Processing completed: {processing_id}")
return result
except asyncio.TimeoutError:
error_msg = f"Processing timeout after {self.config.get('processing_timeout', 60)} seconds"
self.logger.error(f"{error_msg}: {processing_id}")
return {
'success': False,
'error': error_msg,
'processing_id': processing_id,
'timestamp': start_time.isoformat()
}
except Exception as e:
error_msg = f"Processing failed: {str(e)}"
self.logger.error(f"{error_msg}: {processing_id}")
return {
'success': False,
'error': error_msg,
'processing_id': processing_id,
'timestamp': start_time.isoformat()
}
async def _validate_file(self, file_path: str) -> Dict:
"""Validate uploaded file"""
return self.image_validator.validate(file_path, self.config)
async def _process_internal(self, file_path: str, options: Dict, processing_id: str) -> Dict[str, Any]:
"""Internal processing logic"""
result = {
'success': True,
'stages': {}
}
# Stage 1: OCR Text Extraction
self.logger.info(f"Stage 1: OCR extraction - {processing_id}")
ocr_result = await self._extract_text(file_path, options)
result['stages']['ocr'] = ocr_result
if not ocr_result['success']:
result['success'] = False
result['error'] = f"OCR failed: {ocr_result.get('error', 'Unknown error')}"
return result
# Stage 2: NLP Analysis
self.logger.info(f"Stage 2: NLP analysis - {processing_id}")
nlp_result = await self._analyze_text(ocr_result['text'], options, file_path=file_path)
result['stages']['nlp'] = nlp_result
# Stage 3: Generate outputs
self.logger.info(f"Stage 3: Generate outputs - {processing_id}")
output_result = await self._generate_outputs(nlp_result['prescription_data'], options, processing_id)
result['stages']['output'] = output_result
# Compile final result
result.update({
'raw_text': ocr_result['text'],
'prescription_data': nlp_result['prescription_data'],
'summary': nlp_result['summary'],
'exports': output_result.get('exports', {}),
'confidence': {
'ocr_confidence': ocr_result.get('avg_confidence', 0),
'extraction_confidence': nlp_result.get('extraction_confidence', 0),
'overall_confidence': (
ocr_result.get('avg_confidence', 0) * 0.4 +
nlp_result.get('extraction_confidence', 0) * 0.6
)
}
})
return result
async def _extract_text(self, file_path: str, options: Dict) -> Dict:
"""Extract text using OCR"""
try:
# Run OCR in thread pool to avoid blocking
loop = asyncio.get_event_loop()
ocr_result = await loop.run_in_executor(
None,
self.ocr_engine.extract_text_smart,
file_path
)
return ocr_result
except Exception as e:
return {
'success': False,
'error': f"OCR extraction failed: {str(e)}"
}
async def _analyze_text(self, raw_text: str, options: Dict, file_path: Optional[str] = None) -> Dict:
"""Analyze text using NLP"""
try:
if self.use_gemini:
try:
# Try Gemini analysis first (with Vision if file_path provided)
gemini_prescription = self.nlp_analyzer.analyze_prescription(raw_text, image_path=file_path)
# Convert Gemini response to our standard format
prescription_data = self._convert_gemini_to_standard_format(gemini_prescription)
# Generate summary using Gemini's own summary method
summary = self.nlp_analyzer.get_medical_summary(gemini_prescription)
print("βœ… Gemini analysis successful")
except Exception as gemini_error:
print(f"❌ Gemini failed during processing: {gemini_error}")
print("πŸ”„ Falling back to basic NLP analyzer...")
# Fallback to basic NLP analyzer
basic_analyzer = PrescriptionNLPAnalyzer()
prescription_data = basic_analyzer.analyze_prescription(raw_text)
summary = basic_analyzer.get_summary_text(prescription_data)
print("βœ… Basic NLP fallback successful")
else:
# Run basic NLP analysis
prescription_data = self.nlp_analyzer.analyze_prescription(raw_text)
# Generate summary
summary = self.nlp_analyzer.get_summary_text(prescription_data)
return {
'success': True,
'prescription_data': prescription_data,
'summary': summary,
'extraction_confidence': prescription_data.extraction_confidence
}
except Exception as e:
analyzer_type = "Gemini" if self.use_gemini else "NLP"
print(f"❌ All analyzers failed: {e}")
return {
'success': False,
'error': f"{analyzer_type} analysis failed: {str(e)}"
}
def _convert_gemini_to_standard_format(self, gemini_prescription) -> PrescriptionData:
"""Convert Gemini prescription format to standard PrescriptionData format"""
try:
from .nlp_analyzer import MedicineInfo as Medicine
except ImportError:
# Define Medicine class inline if import fails
from dataclasses import dataclass
@dataclass
class Medicine:
name: str = ""
strength: str = ""
frequency: str = ""
duration: str = ""
instructions: str = ""
confidence_score: float = 0.0
# Convert Gemini medicines to standard format
medicines = []
for gemini_med in gemini_prescription.medicines:
medicine = Medicine(
name=gemini_med.name,
strength=gemini_med.strength, # Use 'strength' instead of 'dosage'
frequency=gemini_med.frequency,
duration=gemini_med.duration,
instructions=gemini_med.instructions,
confidence_score=gemini_med.confidence_score # Use 'confidence_score'
)
medicines.append(medicine)
# Create PrescriptionData object using only compatible fields
prescription_data = PrescriptionData(
patient_name=gemini_prescription.patient_name,
doctor_name=gemini_prescription.doctor_name,
date=gemini_prescription.prescription_date,
medicines=medicines,
raw_text="",
extraction_confidence=gemini_prescription.analysis_confidence
)
# Add is_prescription flag dynamically since it's not in the standard dataclass yet
prescription_data.is_prescription = gemini_prescription.is_prescription
prescription_data.health_tip = gemini_prescription.health_tip
return prescription_data
async def _generate_outputs(self, prescription_data: PrescriptionData, options: Dict, processing_id: str) -> Dict:
"""Generate output files (JSON, PDF)"""
try:
outputs = {}
# Generate JSON
json_content = self.nlp_analyzer.to_json(prescription_data)
json_filename = f"{processing_id}_prescription.json"
json_path = os.path.join(self.config.get('output_dir', 'outputs'), json_filename)
# Ensure output directory exists
os.makedirs(os.path.dirname(json_path), exist_ok=True)
with open(json_path, 'w', encoding='utf-8') as f:
f.write(json_content)
outputs['json'] = {
'filename': json_filename,
'path': json_path,
'content': json_content
}
# Generate PDF
pdf_filename = f"{processing_id}_prescription.pdf"
pdf_path = os.path.join(self.config.get('output_dir', 'outputs'), pdf_filename)
pdf_result = await self._generate_pdf(prescription_data, pdf_path)
if pdf_result['success']:
outputs['pdf'] = {
'filename': pdf_filename,
'path': pdf_path
}
return {
'success': True,
'exports': outputs
}
except Exception as e:
return {
'success': False,
'error': f"Output generation failed: {str(e)}"
}
async def _generate_pdf(self, prescription_data: PrescriptionData, output_path: str) -> Dict:
"""Generate PDF report"""
try:
loop = asyncio.get_event_loop()
await loop.run_in_executor(
None,
self.pdf_generator.generate_prescription_pdf,
prescription_data,
output_path
)
return {'success': True}
except Exception as e:
return {
'success': False,
'error': f"PDF generation failed: {str(e)}"
}
def get_processing_history(self, limit: int = 50) -> List[Dict]:
"""Get recent processing history"""
return self.processing_history[-limit:] if self.processing_history else []
def get_processing_stats(self) -> Dict:
"""Get processing statistics"""
if not self.processing_history:
return {
'total_processed': 0,
'success_rate': 0,
'avg_confidence': 0,
'avg_processing_time': 0
}
successful = [p for p in self.processing_history if p.get('success')]
total = len(self.processing_history)
return {
'total_processed': total,
'success_rate': len(successful) / total if total > 0 else 0,
'avg_confidence': sum(
p.get('confidence', {}).get('overall_confidence', 0)
for p in successful
) / len(successful) if successful else 0,
'avg_processing_time': sum(
p.get('processing_time_seconds', 0)
for p in self.processing_history
) / total if total > 0 else 0
}
async def extract_text_regions(self, file_path: str) -> Dict:
"""
Extract text regions with bounding boxes (for UI highlighting)
"""
try:
loop = asyncio.get_event_loop()
regions = await loop.run_in_executor(
None,
self.ocr_engine.get_text_regions,
file_path
)
return {
'success': True,
'regions': regions
}
except Exception as e:
return {
'success': False,
'error': f"Region extraction failed: {str(e)}"
}
async def batch_process(self, file_paths: List[str], options: Optional[Dict] = None) -> Dict:
"""
Process multiple prescription images in batch
"""
results = []
for file_path in file_paths:
try:
result = await self.process_prescription(file_path, options)
results.append(result)
except Exception as e:
results.append({
'success': False,
'error': str(e),
'file_path': file_path
})
# Calculate batch statistics
successful = [r for r in results if r.get('success')]
return {
'success': True,
'total_files': len(file_paths),
'successful': len(successful),
'failed': len(file_paths) - len(successful),
'results': results,
'batch_stats': {
'success_rate': len(successful) / len(file_paths) if file_paths else 0,
'avg_confidence': sum(
r.get('confidence', {}).get('overall_confidence', 0)
for r in successful
) / len(successful) if successful else 0
}
}
class ProcessorFactory:
"""Factory for creating prescription processors with different configurations"""
@staticmethod
def create_standard_processor() -> PrescriptionProcessor:
"""Create processor with standard configuration"""
return PrescriptionProcessor()
@staticmethod
def create_high_accuracy_processor() -> PrescriptionProcessor:
"""Create processor optimized for accuracy"""
config = {
'languages': ['en'],
'use_gpu': False,
'fallback_to_tesseract': True,
'ocr_confidence_threshold': 0.5,
'processing_timeout': 120
}
return PrescriptionProcessor(config)
@staticmethod
def create_fast_processor() -> PrescriptionProcessor:
"""Create processor optimized for speed"""
config = {
'languages': ['en'],
'use_gpu': True, # If available
'fallback_to_tesseract': False,
'ocr_confidence_threshold': 0.2,
'processing_timeout': 30
}
return PrescriptionProcessor(config)