Spaces:
Sleeping
Sleeping
Download backend/nlp_analyzer.py from Presight-AI/app: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/spaces/Presight-AI/app/resolve/main/backend/nlp_analyzer.py
- Command line
-
hf download hf://spaces/Presight-AI/app/backend/nlp_analyzer.py
-
curl -L -o nlp_analyzer.py https://huggingface.co/spaces/Presight-AI/app/resolve/main/backend/nlp_analyzer.py
19.2 kB
| """ | |
| Advanced NLP Analyzer for Prescription Information Extraction | |
| Extracts structured data: medicines, dosages, frequencies, durations, instructions | |
| """ | |
| import re | |
| import json | |
| from typing import Dict, List, Optional, Tuple | |
| from dataclasses import dataclass, asdict | |
| import logging | |
| class MedicineInfo: | |
| """Structured medicine information""" | |
| name: str = "" | |
| strength: str = "" | |
| frequency: str = "" | |
| duration: str = "" | |
| instructions: str = "" | |
| confidence_score: float = 0.0 | |
| class PrescriptionData: | |
| """Complete prescription information""" | |
| patient_name: str = "" | |
| doctor_name: str = "" | |
| date: str = "" | |
| medicines: List[MedicineInfo] = None | |
| raw_text: str = "" | |
| raw_text: str = "" | |
| extraction_confidence: float = 0.0 | |
| is_prescription: bool = True | |
| health_tip: str = "" | |
| def __post_init__(self): | |
| if self.medicines is None: | |
| self.medicines = [] | |
| class PrescriptionNLPAnalyzer: | |
| """ | |
| Advanced NLP analyzer for prescription text processing | |
| """ | |
| def __init__(self): | |
| self.medicine_patterns = self._compile_medicine_patterns() | |
| self.frequency_patterns = self._compile_frequency_patterns() | |
| self.duration_patterns = self._compile_duration_patterns() | |
| self.instruction_patterns = self._compile_instruction_patterns() | |
| self.name_patterns = self._compile_name_patterns() | |
| # Common medicine names (expandable database) | |
| self.common_medicines = [] # load_medicine_database() | |
| def _compile_medicine_patterns(self) -> Dict: | |
| """Compile regex patterns for medicine detection""" | |
| return { | |
| 'medicine_with_strength': re.compile( | |
| r'([A-Za-z][A-Za-z\s]{2,25})\s*(?:\(.*?\))?\s*(\d+(?:\.\d+)?\s*(?:mg|ML|mcg|g|IU|units?)\b)', | |
| re.IGNORECASE | |
| ), | |
| 'medicine_standalone': re.compile( | |
| r'\b([A-Z][a-z]{3,}(?:\s+[A-Z][a-z]+)*)\b' | |
| ), | |
| 'strength_only': re.compile( | |
| r'\b(\d+(?:\.\d+)?\s*(?:mg|ML|mcg|g|IU|units?|tablets?|capsules?))\b', | |
| re.IGNORECASE | |
| ), | |
| 'dosage_form': re.compile( | |
| r'\b(tablets?|capsules?|syrup|injection|drops?|cream|ointment|suspension)\b', | |
| re.IGNORECASE | |
| ) | |
| } | |
| def _compile_frequency_patterns(self) -> Dict: | |
| """Compile patterns for dosage frequency""" | |
| return { | |
| 'numeric_pattern': re.compile( | |
| r'\b(\d+[-β]\d+[-β]\d+)\b' # 1-0-1, 1-1-1 pattern | |
| ), | |
| 'times_daily': re.compile( | |
| r'\b(?:(\d+)\s*(?:times?|x)\s*(?:daily|per\s*day|a\s*day))\b', | |
| re.IGNORECASE | |
| ), | |
| 'medical_abbreviations': re.compile( | |
| r'\b(OD|BD|TID|QID|QDS|BID|TDS|QD|Q\d+H|PRN)\b', | |
| re.IGNORECASE | |
| ), | |
| 'descriptive_frequency': re.compile( | |
| r'\b(once|twice|thrice|three\s*times?|four\s*times?|morning|evening|night|bedtime)\s*(?:daily|per\s*day|a\s*day)?\b', | |
| re.IGNORECASE | |
| ), | |
| 'specific_times': re.compile( | |
| r'\b(?:at\s*)?(morning|afternoon|evening|night|bedtime|dawn|dusk)\b', | |
| re.IGNORECASE | |
| ) | |
| } | |
| def _compile_duration_patterns(self) -> Dict: | |
| """Compile patterns for treatment duration""" | |
| return { | |
| 'days_weeks': re.compile( | |
| r'\b(?:for\s*)?(\d+)\s*(days?|weeks?|months?)\b', | |
| re.IGNORECASE | |
| ), | |
| 'until_finished': re.compile( | |
| r'\b(?:until\s*(?:finished|complete|empty)|complete\s*(?:the\s*)?course)\b', | |
| re.IGNORECASE | |
| ), | |
| 'as_needed': re.compile( | |
| r'\b(?:as\s*(?:needed|required)|PRN|SOS|when\s*(?:needed|required))\b', | |
| re.IGNORECASE | |
| ) | |
| } | |
| def _compile_instruction_patterns(self) -> Dict: | |
| """Compile patterns for medicine instructions""" | |
| return { | |
| 'food_relation': re.compile( | |
| r'\b(?:(before|after|with)\s*(?:food|meals?|eating|breakfast|lunch|dinner))\b', | |
| re.IGNORECASE | |
| ), | |
| 'empty_stomach': re.compile( | |
| r'\b(?:(?:on\s*)?empty\s*stomach|before\s*(?:food|meals?))\b', | |
| re.IGNORECASE | |
| ), | |
| 'water_instruction': re.compile( | |
| r'\b(?:with\s*(?:water|milk|juice)|drink\s*(?:plenty\s*of\s*)?water)\b', | |
| re.IGNORECASE | |
| ), | |
| 'special_instructions': re.compile( | |
| r'\b(?:do\s*not\s*crush|swallow\s*whole|dissolve|shake\s*well|refrigerate|avoid\s*alcohol)\b', | |
| re.IGNORECASE | |
| ), | |
| 'time_specific': re.compile( | |
| r'\b(?:in\s*the\s*)?(morning|afternoon|evening|night|bedtime|before\s*sleep)\b', | |
| re.IGNORECASE | |
| ) | |
| } | |
| def _compile_name_patterns(self) -> Dict: | |
| """Compile patterns for patient and doctor names""" | |
| return { | |
| 'patient_name': re.compile( | |
| r'(?:patient\s*(?:name)?[:β\s]*|name\s*[:β\s]*|mr\.?\s*|mrs\.?\s*|ms\.?\s*)([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,3})', | |
| re.IGNORECASE | |
| ), | |
| 'doctor_name': re.compile( | |
| r'(?:dr\.?\s*|doctor\s*[:β\s]*)([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,3})(?:\s*,?\s*(?:M\.?D\.?|MBBS|MD))?', | |
| re.IGNORECASE | |
| ), | |
| 'date_pattern': re.compile( | |
| r'\b(\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}|\d{1,2}\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{2,4})\b', | |
| re.IGNORECASE | |
| ) | |
| } | |
| # def _load_medicine_database(self) -> List[str]: | |
| # """Load common medicine names for better detection""" | |
| # # Use shared database from utils | |
| # return load_medicine_database() | |
| def analyze_prescription(self, raw_text: str) -> PrescriptionData: | |
| """ | |
| Main analysis function to extract structured prescription data | |
| Args: | |
| raw_text: Raw OCR extracted text | |
| Returns: | |
| PrescriptionData object with structured information | |
| """ | |
| # Clean and normalize text | |
| cleaned_text = self._clean_text(raw_text) | |
| # Initialize prescription data | |
| prescription = PrescriptionData(raw_text=raw_text) | |
| # Extract basic information | |
| prescription.patient_name = self._extract_patient_name(cleaned_text) | |
| prescription.doctor_name = self._extract_doctor_name(cleaned_text) | |
| prescription.date = self._extract_date(cleaned_text) | |
| # Extract medicine information | |
| prescription.medicines = self._extract_medicines(cleaned_text) | |
| # Calculate overall confidence | |
| prescription.extraction_confidence = self._calculate_confidence(prescription) | |
| return prescription | |
| def _clean_text(self, text: str) -> str: | |
| """Clean and normalize OCR text""" | |
| if not text: | |
| return "" | |
| # Remove extra whitespace and normalize | |
| text = re.sub(r'\s+', ' ', text.strip()) | |
| # Fix common OCR errors | |
| text = re.sub(r'[|l1](?=\d)', '1', text) # Fix | or l before numbers | |
| text = re.sub(r'(?<=\d)[|l]', '1', text) # Fix | or l after numbers | |
| text = re.sub(r'[O0](?=\d)', '0', text) # Fix O vs 0 | |
| text = re.sub(r'(?<=\d)[O]', '0', text) # Fix O vs 0 | |
| return text | |
| def _extract_patient_name(self, text: str) -> str: | |
| """Extract patient name from text""" | |
| matches = self.name_patterns['patient_name'].findall(text) | |
| for match in matches: | |
| name = match.strip() | |
| if len(name.split()) <= 4 and len(name) > 2: # Reasonable name length | |
| return name | |
| return "" | |
| def _extract_doctor_name(self, text: str) -> str: | |
| """Extract doctor name from text""" | |
| matches = self.name_patterns['doctor_name'].findall(text) | |
| for match in matches: | |
| name = match.strip() | |
| if len(name.split()) <= 4 and len(name) > 2: # Reasonable name length | |
| return name | |
| return "" | |
| def _extract_date(self, text: str) -> str: | |
| """Extract prescription date""" | |
| matches = self.name_patterns['date_pattern'].findall(text) | |
| if matches: | |
| return matches[0].strip() | |
| return "" | |
| def _extract_medicines(self, text: str) -> List[MedicineInfo]: | |
| """Extract medicine information from text""" | |
| medicines = [] | |
| # Split text into potential medicine sections | |
| lines = [line.strip() for line in text.split('\n') if line.strip()] | |
| current_medicine = None | |
| for line in lines: | |
| # Skip header lines | |
| if any(header in line.lower() for header in ['prescription', 'doctor', 'patient', 'date', 'signature']): | |
| continue | |
| # Detect medicine with strength | |
| medicine_match = self.medicine_patterns['medicine_with_strength'].search(line) | |
| if medicine_match: | |
| # Save previous medicine if exists | |
| if current_medicine and current_medicine.name: | |
| medicines.append(current_medicine) | |
| # Start new medicine | |
| current_medicine = MedicineInfo() | |
| current_medicine.name = medicine_match.group(1).strip() | |
| current_medicine.strength = medicine_match.group(2).strip() | |
| # Extract other information from the same line | |
| current_medicine.frequency = self._extract_frequency(line) | |
| current_medicine.duration = self._extract_duration(line) | |
| current_medicine.instructions = self._extract_instructions(line) | |
| else: | |
| # Check if line contains medicine information for current medicine | |
| if current_medicine: | |
| if not current_medicine.frequency: | |
| current_medicine.frequency = self._extract_frequency(line) | |
| if not current_medicine.duration: | |
| current_medicine.duration = self._extract_duration(line) | |
| if not current_medicine.instructions: | |
| current_medicine.instructions = self._extract_instructions(line) | |
| else: | |
| # Try to detect standalone medicine names | |
| potential_medicine = self._detect_standalone_medicine(line) | |
| if potential_medicine: | |
| current_medicine = MedicineInfo() | |
| current_medicine.name = potential_medicine | |
| current_medicine.frequency = self._extract_frequency(line) | |
| current_medicine.duration = self._extract_duration(line) | |
| current_medicine.instructions = self._extract_instructions(line) | |
| # Add the last medicine | |
| if current_medicine and current_medicine.name: | |
| medicines.append(current_medicine) | |
| # Calculate confidence scores for each medicine | |
| for medicine in medicines: | |
| medicine.confidence_score = self._calculate_medicine_confidence(medicine) | |
| return medicines | |
| def _detect_standalone_medicine(self, line: str) -> Optional[str]: | |
| """Detect medicine names without explicit strength""" | |
| # Check against known medicine database | |
| words = line.split() | |
| for i, word in enumerate(words): | |
| # Check if word matches known medicine | |
| for known_med in self.common_medicines: | |
| if word.lower() in known_med.lower() or known_med.lower() in word.lower(): | |
| if len(word) > 3: # Avoid short false positives | |
| return word | |
| # Check for medicine-like patterns | |
| medicine_match = self.medicine_patterns['medicine_standalone'].search(line) | |
| if medicine_match: | |
| potential = medicine_match.group(1) | |
| if len(potential) > 3 and potential not in ['Patient', 'Doctor', 'Date']: | |
| return potential | |
| return None | |
| def _extract_frequency(self, text: str) -> str: | |
| """Extract dosage frequency from text""" | |
| # Check numeric patterns first (1-0-1, 1-1-1) | |
| numeric_match = self.frequency_patterns['numeric_pattern'].search(text) | |
| if numeric_match: | |
| return numeric_match.group(1) | |
| # Check medical abbreviations | |
| abbrev_match = self.frequency_patterns['medical_abbreviations'].search(text) | |
| if abbrev_match: | |
| return abbrev_match.group(1).upper() | |
| # Check times daily | |
| times_match = self.frequency_patterns['times_daily'].search(text) | |
| if times_match: | |
| return f"{times_match.group(1)} times daily" | |
| # Check descriptive frequency | |
| desc_match = self.frequency_patterns['descriptive_frequency'].search(text) | |
| if desc_match: | |
| return desc_match.group(1).lower() | |
| return "" | |
| def _extract_duration(self, text: str) -> str: | |
| """Extract treatment duration from text""" | |
| # Check for specific duration | |
| duration_match = self.duration_patterns['days_weeks'].search(text) | |
| if duration_match: | |
| return f"{duration_match.group(1)} {duration_match.group(2)}" | |
| # Check for "until finished" patterns | |
| finished_match = self.duration_patterns['until_finished'].search(text) | |
| if finished_match: | |
| return "until finished" | |
| # Check for "as needed" | |
| needed_match = self.duration_patterns['as_needed'].search(text) | |
| if needed_match: | |
| return "as needed" | |
| return "" | |
| def _extract_instructions(self, text: str) -> str: | |
| """Extract medicine taking instructions""" | |
| instructions = [] | |
| # Food relation | |
| food_match = self.instruction_patterns['food_relation'].search(text) | |
| if food_match: | |
| instructions.append(f"{food_match.group(1)} food") | |
| # Empty stomach | |
| empty_match = self.instruction_patterns['empty_stomach'].search(text) | |
| if empty_match: | |
| instructions.append("empty stomach") | |
| # Water instruction | |
| water_match = self.instruction_patterns['water_instruction'].search(text) | |
| if water_match: | |
| instructions.append("with water") | |
| # Time specific | |
| time_match = self.instruction_patterns['time_specific'].search(text) | |
| if time_match: | |
| instructions.append(f"in the {time_match.group(1)}") | |
| # Special instructions | |
| special_match = self.instruction_patterns['special_instructions'].search(text) | |
| if special_match: | |
| instructions.append(special_match.group(0)) | |
| return ", ".join(instructions) if instructions else "" | |
| def _calculate_medicine_confidence(self, medicine: MedicineInfo) -> float: | |
| """Calculate confidence score for medicine extraction""" | |
| confidence = 0.0 | |
| # Name confidence (40%) | |
| if medicine.name: | |
| confidence += 0.4 | |
| # Bonus if name is in known medicine database | |
| if any(known.lower() in medicine.name.lower() for known in self.common_medicines): | |
| confidence += 0.1 | |
| # Strength confidence (25%) | |
| if medicine.strength and re.search(r'\d+\s*(?:mg|ML|mcg|g)', medicine.strength, re.IGNORECASE): | |
| confidence += 0.25 | |
| # Frequency confidence (20%) | |
| if medicine.frequency: | |
| confidence += 0.2 | |
| # Duration confidence (10%) | |
| if medicine.duration: | |
| confidence += 0.1 | |
| # Instructions confidence (5%) | |
| if medicine.instructions: | |
| confidence += 0.05 | |
| return min(confidence, 1.0) | |
| def _calculate_confidence(self, prescription: PrescriptionData) -> float: | |
| """Calculate overall extraction confidence""" | |
| confidence = 0.0 | |
| # Basic information confidence | |
| if prescription.patient_name: | |
| confidence += 0.2 | |
| if prescription.doctor_name: | |
| confidence += 0.1 | |
| if prescription.date: | |
| confidence += 0.1 | |
| # Medicine information confidence (60% weight) | |
| if prescription.medicines: | |
| medicine_confidence = sum(med.confidence_score for med in prescription.medicines) / len(prescription.medicines) | |
| confidence += medicine_confidence * 0.6 | |
| return min(confidence, 1.0) | |
| def to_json(self, prescription: PrescriptionData) -> str: | |
| """Convert prescription data to JSON""" | |
| return json.dumps(asdict(prescription), indent=2, ensure_ascii=False) | |
| def get_summary_text(self, prescription: PrescriptionData) -> str: | |
| """Generate human-readable prescription summary""" | |
| summary = [] | |
| summary.append("=== PRESCRIPTION SUMMARY ===") | |
| summary.append("") | |
| # Basic information | |
| summary.append(f"Patient Name: {prescription.patient_name or 'Not detected'}") | |
| summary.append(f"Doctor Name: {prescription.doctor_name or 'Not detected'}") | |
| summary.append(f"Date: {prescription.date or 'Not detected'}") | |
| summary.append("") | |
| # Medicines | |
| if prescription.medicines: | |
| summary.append("MEDICINES:") | |
| summary.append("β" * 40) | |
| for i, med in enumerate(prescription.medicines, 1): | |
| summary.append(f"{i}) {med.name}") | |
| if med.strength: | |
| summary.append(f" β’ Strength: {med.strength}") | |
| if med.frequency: | |
| summary.append(f" β’ Frequency: {med.frequency}") | |
| if med.duration: | |
| summary.append(f" β’ Duration: {med.duration}") | |
| if med.instructions: | |
| summary.append(f" β’ Instructions: {med.instructions}") | |
| summary.append(f" β’ Confidence: {med.confidence_score:.1%}") | |
| summary.append("") | |
| else: | |
| summary.append("MEDICINES: None detected") | |
| summary.append("") | |
| summary.append(f"Overall Extraction Confidence: {prescription.extraction_confidence:.1%}") | |
| summary.append("") | |
| summary.append("β οΈ DISCLAIMER: This is not a medical diagnosis.") | |
| summary.append(" Always consult with healthcare professionals.") | |
| return "\n".join(summary) |