""" Utility functions and classes for prescription processing """ import os import mimetypes from typing import Dict, List, Optional from pathlib import Path from PIL import Image import logging import logging class ImageValidator: """Validates uploaded image files""" def __init__(self): self.logger = logging.getLogger(__name__) def validate(self, file_path: str, config: Dict) -> Dict: """ Validate uploaded file Args: file_path: Path to file config: Configuration dictionary Returns: Validation result """ try: if not os.path.exists(file_path): return { 'valid': False, 'error': 'File not found' } # Check file size file_size = os.path.getsize(file_path) max_size = config.get('max_file_size_mb', 10) * 1024 * 1024 if file_size > max_size: return { 'valid': False, 'error': f'File size ({file_size / 1024 / 1024:.1f}MB) exceeds limit ({config.get("max_file_size_mb", 10)}MB)' } # Check file extension file_ext = Path(file_path).suffix.lower() allowed_extensions = config.get('allowed_extensions', ['.jpg', '.jpeg', '.png', '.pdf']) if file_ext not in allowed_extensions: return { 'valid': False, 'error': f'File type {file_ext} not supported. Allowed: {", ".join(allowed_extensions)}' } # Check MIME type mime_type, _ = mimetypes.guess_type(file_path) if not mime_type or not mime_type.startswith('image/'): if file_ext != '.pdf': # PDF is special case return { 'valid': False, 'error': 'Invalid file type detected' } # Try to open as image (if not PDF) if file_ext != '.pdf': try: with Image.open(file_path) as img: # Check image dimensions width, height = img.size if width < 100 or height < 100: return { 'valid': False, 'error': 'Image too small (minimum 100x100 pixels)' } if width > 10000 or height > 10000: return { 'valid': False, 'error': 'Image too large (maximum 10000x10000 pixels)' } file_info = { 'filename': os.path.basename(file_path), 'size_bytes': file_size, 'size_mb': round(file_size / 1024 / 1024, 2), 'dimensions': f"{width}x{height}", 'format': img.format, 'mode': img.mode, 'mime_type': mime_type } except Exception as e: return { 'valid': False, 'error': f'Invalid image file: {str(e)}' } else: # PDF validation file_info = { 'filename': os.path.basename(file_path), 'size_bytes': file_size, 'size_mb': round(file_size / 1024 / 1024, 2), 'format': 'PDF', 'mime_type': 'application/pdf' } return { 'valid': True, 'file_info': file_info } except Exception as e: return { 'valid': False, 'error': f'Validation error: {str(e)}' } class FileHandler: """Handles file operations""" def __init__(self, upload_dir: str = 'uploads'): self.upload_dir = upload_dir self.logger = logging.getLogger(__name__) # Create upload directory if it doesn't exist os.makedirs(upload_dir, exist_ok=True) def save_uploaded_file(self, file_data: bytes, filename: str) -> str: """ Save uploaded file to disk Args: file_data: File binary data filename: Original filename Returns: Path to saved file """ # Generate safe filename safe_filename = self._generate_safe_filename(filename) file_path = os.path.join(self.upload_dir, safe_filename) try: with open(file_path, 'wb') as f: f.write(file_data) self.logger.info(f"File saved: {file_path}") return file_path except Exception as e: self.logger.error(f"Failed to save file: {e}") raise def _generate_safe_filename(self, filename: str) -> str: """Generate safe filename""" import re from datetime import datetime # Remove unsafe characters safe_name = re.sub(r'[^a-zA-Z0-9._-]', '_', filename) # Add timestamp to avoid conflicts timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') name_parts = safe_name.rsplit('.', 1) if len(name_parts) == 2: return f"{name_parts[0]}_{timestamp}.{name_parts[1]}" else: return f"{safe_name}_{timestamp}" def cleanup_old_files(self, max_age_hours: int = 24): """Clean up old uploaded files""" import time try: now = time.time() cutoff = now - (max_age_hours * 3600) for filename in os.listdir(self.upload_dir): file_path = os.path.join(self.upload_dir, filename) if os.path.isfile(file_path): file_age = os.path.getmtime(file_path) if file_age < cutoff: os.remove(file_path) self.logger.info(f"Cleaned up old file: {filename}") except Exception as e: self.logger.error(f"Cleanup failed: {e}") class TextProcessor: """Text processing utilities""" @staticmethod def clean_extracted_text(text: str) -> str: """Clean and normalize extracted text""" if not text: return "" import re # Remove extra whitespace text = re.sub(r'\s+', ' ', text.strip()) # Fix common OCR errors replacements = { r'[|l1I](\d)': r'1\1', # Fix | or l before numbers r'(\d)[|l1I]': r'\10', # Fix | or l after numbers r'[O](\d)': r'0\1', # Fix O before numbers r'(\d)[O]': r'\10', # Fix O after numbers r'rn': 'm', # Common OCR error r'cl': 'd', # Common OCR error } for pattern, replacement in replacements.items(): text = re.sub(pattern, replacement, text) return text @staticmethod def extract_lines(text: str) -> List[str]: """Extract meaningful lines from text""" if not text: return [] lines = [line.strip() for line in text.split('\n') if line.strip()] # Filter out very short lines (likely noise) filtered_lines = [line for line in lines if len(line) > 2] return filtered_lines @staticmethod def find_medicine_candidates(text: str) -> List[str]: """Find potential medicine names in text""" import re # Common patterns for medicine names patterns = [ r'\b[A-Z][a-z]{3,}(?:\s+[A-Z][a-z]+)*\b', # Capitalized words r'\b[a-z]{4,}(?:cillin|mycin|prazole|statin|sartan|dipine)\b', # Medicine suffixes ] candidates = set() for pattern in patterns: matches = re.findall(pattern, text, re.IGNORECASE) candidates.update(matches) # Filter out common non-medicine words stop_words = { 'Patient', 'Doctor', 'Name', 'Date', 'Prescription', 'Instructions', 'Signature', 'Address', 'Phone' } filtered_candidates = [ candidate for candidate in candidates if candidate not in stop_words and len(candidate) > 3 ] return filtered_candidates class ConfigManager: """Configuration management""" DEFAULT_CONFIG = { 'ocr': { 'languages': ['en'], 'use_gpu': False, 'confidence_threshold': 0.3, 'fallback_to_tesseract': True }, 'nlp': { 'enable_spacy': False, # Optional advanced NLP 'confidence_threshold': 0.5 }, 'file_handling': { 'max_file_size_mb': 10, 'allowed_extensions': ['.jpg', '.jpeg', '.png', '.pdf'], 'upload_dir': 'uploads', 'output_dir': 'outputs' }, 'processing': { 'timeout_seconds': 60, 'enable_batch_processing': True, 'max_batch_size': 10 }, 'export': { 'enable_pdf': True, 'enable_json': True, 'include_confidence_scores': True } } def __init__(self, config_file: Optional[str] = None): self.config = self.DEFAULT_CONFIG.copy() if config_file and os.path.exists(config_file): self.load_from_file(config_file) def load_from_file(self, config_file: str): """Load configuration from JSON file""" import json try: with open(config_file, 'r') as f: file_config = json.load(f) # Deep merge configurations self._deep_merge(self.config, file_config) except Exception as e: logging.warning(f"Failed to load config file {config_file}: {e}") def _deep_merge(self, base_dict: Dict, update_dict: Dict): """Deep merge dictionaries""" for key, value in update_dict.items(): if key in base_dict and isinstance(base_dict[key], dict) and isinstance(value, dict): self._deep_merge(base_dict[key], value) else: base_dict[key] = value def get(self, key_path: str, default=None): """Get configuration value using dot notation""" keys = key_path.split('.') value = self.config try: for key in keys: value = value[key] return value except (KeyError, TypeError): return default def set(self, key_path: str, value): """Set configuration value using dot notation""" keys = key_path.split('.') config = self.config for key in keys[:-1]: if key not in config: config[key] = {} config = config[key] config[keys[-1]] = value def save_to_file(self, config_file: str): """Save configuration to JSON file""" import json try: with open(config_file, 'w') as f: json.dump(self.config, f, indent=2) except Exception as e: logging.error(f"Failed to save config file {config_file}: {e}") class PerformanceMonitor: """Monitor processing performance""" def __init__(self): self.metrics = { 'total_requests': 0, 'successful_requests': 0, 'failed_requests': 0, 'total_processing_time': 0, 'avg_processing_time': 0, 'avg_ocr_confidence': 0, 'avg_extraction_confidence': 0 } def record_processing(self, result: Dict): """Record processing result for metrics""" self.metrics['total_requests'] += 1 if result.get('success'): self.metrics['successful_requests'] += 1 # Update timing metrics processing_time = result.get('processing_time_seconds', 0) self.metrics['total_processing_time'] += processing_time # Update confidence metrics confidence = result.get('confidence', {}) if confidence.get('ocr_confidence'): # Running average current_avg = self.metrics['avg_ocr_confidence'] count = self.metrics['successful_requests'] new_avg = ((current_avg * (count - 1)) + confidence['ocr_confidence']) / count self.metrics['avg_ocr_confidence'] = new_avg if confidence.get('extraction_confidence'): current_avg = self.metrics['avg_extraction_confidence'] count = self.metrics['successful_requests'] new_avg = ((current_avg * (count - 1)) + confidence['extraction_confidence']) / count self.metrics['avg_extraction_confidence'] = new_avg else: self.metrics['failed_requests'] += 1 # Update average processing time if self.metrics['total_requests'] > 0: self.metrics['avg_processing_time'] = ( self.metrics['total_processing_time'] / self.metrics['total_requests'] ) def get_metrics(self) -> Dict: """Get current performance metrics""" metrics = self.metrics.copy() # Calculate additional metrics if metrics['total_requests'] > 0: metrics['success_rate'] = metrics['successful_requests'] / metrics['total_requests'] else: metrics['success_rate'] = 0 return metrics def reset_metrics(self): """Reset all metrics""" for key in self.metrics: self.metrics[key] = 0