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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
497
498
"""
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': 60
        }
    
    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 = ""
                dosage_status: str = "Normal"
                dosage_warning: 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,
                dosage_status=gemini_med.dosage_status,
                dosage_warning=gemini_med.dosage_warning,
                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)