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