Commit ·
fd20bd2
1
Parent(s): 3cbb4d9
Add automatic PII removal during file extraction
Browse filesFiles changed (7)
- Dockerfile+3
- requirements.txt+5-3
- src/api/routes.py+25-13
- src/models/response_models.py+53-27
- src/services/file_service.py+32-6
- src/services/pii_detector.pyAdded+197
- tests/test_api.py+28-3
7 unmodified lines89101112137 unmodified lines# Install dependenciesRUN pip install --no-cache-dir -r requirements.txt# Copy the entire backendCOPY . .7 unmodified lines89101112131415167 unmodified lines# Install dependenciesRUN pip install --no-cache-dir -r requirements.txt# Download spaCy model for Presidio (required for PII detection)RUN python -m spacy download en_core_web_lg# Copy the entire backendCOPY . .
1234567fastapi==0.104.1uvicorn==0.24.0python-dotenv==1.0.0groq==0.9.0httpx==0.27.0pydantic==2.5.0python-multipart==0.0.6123456789fastapi==0.104.1uvicorn==0.24.0python-dotenv==1.0.0groq==0.4.1pydantic==2.5.0python-multipart==0.0.6presidio-analyzer==2.2.354presidio-anonymizer==2.2.354spacy==3.7.2
28 unmodified lines2930313233343516 unmodified lines525354555657585960616263646566676869707172737475767778798081828384858687888990919293943 unmodified lines989910010110210310428 unmodified linesdetail="Provider notes must be at least 10 characters long")# Process through Groq service - CORRECT METHOD NAMEresult = await groq_service.analyze_provider_notes(provider_notes)logger.info("Successfully processed coding request")16 unmodified lines)# NEW ENDPOINT - File Upload@router.post("/upload-file", response_model=FileUploadResponse)async def upload_provider_notes_file(file: UploadFile = File(...)):"""Upload a TXT file containing provider notes and extract ICD-10 and CPT codesThis endpoint accepts a TXT file, extracts the text, and processes it through the LLM.Args:file: TXT file containing provider notesReturns:FileUploadResponse with extracted codes and explanations"""try:logger.info(f"Received file upload request: {file.filename}")# Step 1: Extract text from uploaded fileextraction_result = await file_service.extract_text_from_file(file)extracted_text = extraction_result["text"]filename = extraction_result["filename"]text_length = extraction_result["text_length"]logger.info(f"Extracted {text_length} characters from {filename}")# Step 2: Process extracted text through Groq LLM# FIXED: Use the correct method name 'analyze_provider_notes'coding_result = await groq_service.analyze_provider_notes(extracted_text)logger.info(f"Successfully processed file: {filename}")# Step 3: Return combined responsereturn FileUploadResponse(success=True,filename=filename,extracted_text_length=text_length,cpt_codes=coding_result.get("CPT", []),cpt_explanation=coding_result.get("CPT_explanation", ""),icd_codes=coding_result.get("ICD", []),3 unmodified linesexcept HTTPException:raiseexcept Exception as e:logger.error(f"Error in upload_provider_notes_file: {str(e)}")raise HTTPException(status_code=500,detail=f"Error processing uploaded file: {str(e)}"28 unmodified lines2930313233343516 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051063 unmodified lines11011111211311411511628 unmodified linesdetail="Provider notes must be at least 10 characters long")# Process through Groq serviceresult = await groq_service.analyze_provider_notes(provider_notes)logger.info("Successfully processed coding request")16 unmodified lines)# UPDATED ENDPOINT - File Upload with PII Removal@router.post("/upload-file", response_model=FileUploadResponse)async def upload_provider_notes_file(file: UploadFile = File(...)):"""Upload a TXT file containing provider notes and extract ICD-10 and CPT codesThis endpoint:1. Extracts text from uploaded TXT file2. Automatically detects and removes patient personal information (PII)3. Processes sanitized text through LLM4. Returns ICD-10 and CPT codesArgs:file: TXT file containing provider notesReturns:FileUploadResponse with codes, explanations, and PII removal info"""try:logger.info(f"📁 Received file upload request: {file.filename}")# Step 1: Extract text from file with automatic PII removalextraction_result = await file_service.extract_text_from_file(file=file,remove_pii=True # Always remove PII for safety)extracted_text = extraction_result["text"]filename = extraction_result["filename"]text_length = extraction_result["text_length"]pii_info = extraction_result["pii_info"]logger.info(f"✅ Extracted {text_length} characters from {filename}")if pii_info["pii_removed"]:logger.info(f"🔒 Removed {pii_info['pii_count']} PII entities before processing")# Step 2: Process sanitized text through Groq LLMcoding_result = await groq_service.analyze_provider_notes(extracted_text)logger.info(f"✅ Successfully processed file: {filename}")# Step 3: Return combined response with PII inforeturn FileUploadResponse(success=True,filename=filename,extracted_text_length=text_length,pii_removed=pii_info["pii_removed"],pii_count=pii_info["pii_count"],cpt_codes=coding_result.get("CPT", []),cpt_explanation=coding_result.get("CPT_explanation", ""),icd_codes=coding_result.get("ICD", []),3 unmodified linesexcept HTTPException:raiseexcept Exception as e:logger.error(f"❌ Error in upload_provider_notes_file: {str(e)}")raise HTTPException(status_code=500,detail=f"Error processing uploaded file: {str(e)}"
1234567891011121314151617181920212223242526272829303132333435363738from pydantic import BaseModel, Fieldfrom typing import Listclass ICDCode(BaseModel):code: str = Field(..., description="ICD-10 diagnosis code")description: str = Field(..., description="Description of the diagnosis")explanation: str = Field(..., description="Explanation for why this code was selected")class CPTCode(BaseModel):code: str = Field(..., description="CPT procedure code")description: str = Field(..., description="Description of the procedure/service")explanation: str = Field(..., description="Explanation for why this code was selected")class CodingResponse(BaseModel):icd_codes: List[ICDCode] = Field(default_factory=list, description="List of ICD-10 codes")cpt_codes: List[CPTCode] = Field(default_factory=list, description="List of CPT codes")overall_summary: str = Field(..., description="Overall summary of coding decisions")class Config:json_schema_extra = {"example": {"icd_codes": [{"code": "J20.9","description": "Acute bronchitis, unspecified","explanation": "Patient presents with acute bronchitis as documented in provider notes"}],"cpt_codes": [{"code": "99213","description": "Office visit, established patient","explanation": "Comprehensive examination performed as documented"}],"overall_summary": "Patient encounter for acute bronchitis with examination and treatment"}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from pydantic import BaseModel, Fieldfrom typing import List, Optionalclass ProviderNotesRequest(BaseModel):provider_notes: str = Field(...,description="The medical provider notes to analyze",min_length=10,example="Patient presents with acute bronchitis. Performed comprehensive examination and prescribed antibiotics.")class Config:json_schema_extra = {"example": {"provider_notes": "Patient presents with acute bronchitis. Cough for 5 days, productive with yellow sputum. Lung exam reveals diffuse wheezing. Prescribed azithromycin 500mg."}}class ProviderNote(BaseModel):note: strclass CodingResponse(BaseModel):cpt_codes: listcpt_explanation: stricd_codes: listicd_explanation: str# PII Detection Detail Modelclass PIIDetail(BaseModel):"""Details of detected PII entity"""entity_type: str = Field(description="Type of PII detected (e.g., PERSON, PHONE_NUMBER)")start: int = Field(description="Start position in original text")end: int = Field(description="End position in original text")score: float = Field(description="Confidence score")# Updated File Upload Response with PII infoclass FileUploadResponse(BaseModel):"""Response model for file upload endpoint with PII removal info"""success: bool = Field(description="Whether file processing was successful")filename: str = Field(description="Name of uploaded file")extracted_text_length: int = Field(description="Length of extracted text (after PII removal)")pii_removed: bool = Field(description="Whether PII was detected and removed")pii_count: int = Field(description="Number of PII entities removed")cpt_codes: list = Field(description="List of CPT codes")cpt_explanation: str = Field(description="Explanation of CPT codes")icd_codes: list = Field(description="List of ICD codes")icd_explanation: str = Field(description="Explanation of ICD codes")class Config:json_schema_extra = {"example": {"success": True,"filename": "provider_notes.txt","extracted_text_length": 450,"pii_removed": True,"pii_count": 3,"cpt_codes": ["99213", "93000"],"cpt_explanation": "Office visit and EKG","icd_codes": ["I20.0", "R07.9"],"icd_explanation": "Unstable angina and chest pain"}}
1 unmodified line23456728 unmodified lines36373839404142434445464748495035 unmodified lines86878889909192939495969798991001011021031041 unmodified lineimport osfrom typing import Dictimport logginglogger = logging.getLogger(__name__)28 unmodified lines)@staticmethodasync def extract_text_from_file(file: UploadFile) -> Dict[str, any]:"""Extract text content from uploaded fileArgs:file: Uploaded file objectReturns:Dictionary containing extracted text and metadata"""try:# Validate file35 unmodified linesdetail="Extracted text is too short. Please provide more detailed provider notes")logger.info(f"Successfully extracted {len(text)} characters from {file.filename}")return {"text": text,"filename": file.filename,"file_size": file_size,"text_length": len(text)}except HTTPException:raiseexcept Exception as e:logger.error(f"Error extracting text from file: {str(e)}")raise HTTPException(status_code=500,detail=f"Error processing file: {str(e)}"1 unmodified line234567828 unmodified lines3738394041424344454647484950515235 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301 unmodified lineimport osfrom typing import Dictimport loggingfrom services.pii_detector import pii_detectorlogger = logging.getLogger(__name__)28 unmodified lines)@staticmethodasync def extract_text_from_file(file: UploadFile, remove_pii: bool = True) -> Dict[str, any]:"""Extract text content from uploaded file and optionally remove PIIArgs:file: Uploaded file objectremove_pii: Whether to remove PII from extracted text (default: True)Returns:Dictionary containing extracted text, PII removal info, and metadata"""try:# Validate file35 unmodified linesdetail="Extracted text is too short. Please provide more detailed provider notes")logger.info(f"✅ Successfully extracted {len(text)} characters from {file.filename}")# Remove PII if requestedpii_info = {"pii_removed": False,"pii_count": 0,"pii_details": []}if remove_pii:logger.info("🔒 Removing PII from extracted text...")pii_result = pii_detector.remove_pii(text)text = pii_result["sanitized_text"]pii_info = {"pii_removed": pii_result["was_pii_removed"],"pii_count": pii_result["pii_count"],"pii_details": pii_result["pii_detected"]}if pii_result["was_pii_removed"]:logger.info(f"✅ Removed {pii_result['pii_count']} PII entities")else:logger.info("✅ No PII detected in text")return {"text": text,"filename": file.filename,"file_size": file_size,"text_length": len(text),"pii_info": pii_info}except HTTPException:raiseexcept Exception as e:logger.error(f"❌ Error extracting text from file: {str(e)}")raise HTTPException(status_code=500,detail=f"Error processing file: {str(e)}"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197from presidio_analyzer import AnalyzerEnginefrom presidio_anonymizer import AnonymizerEnginefrom typing import Dict, Listimport reimport logging
logger = logging.getLogger(__name__)
class PIIDetector: """Service to detect and remove Personal Identifiable Information from medical notes""" def __init__(self): """Initialize PII detection engines""" try: self.analyzer = AnalyzerEngine() self.anonymizer = AnonymizerEngine() # Entities to detect (common in medical notes) self.entities_to_detect = [ "PERSON", # Names "EMAIL_ADDRESS", # Email "PHONE_NUMBER", # Phone numbers "US_SSN", # Social Security Number "CREDIT_CARD", # Credit card numbers "US_DRIVER_LICENSE", # Driver's license "LOCATION", # Addresses, cities "DATE_TIME", # Birth dates, appointment dates "US_PASSPORT", # Passport numbers "MEDICAL_LICENSE", # Medical license numbers "IP_ADDRESS", # IP addresses "URL" # URLs ] logger.info("✅ PII Detector initialized successfully") except Exception as e: logger.error(f"❌ Failed to initialize PII Detector: {str(e)}") raise def detect_pii(self, text: str) -> List[Dict]: """ Detect PII entities in text Args: text: Input text to analyze Returns: List of detected PII entities with details """ try: results = self.analyzer.analyze( text=text, entities=self.entities_to_detect, language='en' ) pii_findings = [] for result in results: pii_findings.append({ "entity_type": result.entity_type, "start": result.start, "end": result.end, "score": result.score, "text": text[result.start:result.end] }) logger.info(f"🔍 Detected {len(pii_findings)} PII entities") return pii_findings except Exception as e: logger.error(f"❌ Error detecting PII: {str(e)}") return [] def remove_pii(self, text: str) -> Dict[str, any]: """ Remove PII from text while preserving medical information Args: text: Input text containing potential PII Returns: Dictionary with sanitized text and PII removal report """ try: # Step 1: Detect PII analyzer_results = self.analyzer.analyze( text=text, entities=self.entities_to_detect, language='en' ) if not analyzer_results: logger.info("✅ No PII detected in text") return { "sanitized_text": text, "pii_detected": [], "pii_count": 0, "was_pii_removed": False } # Step 2: Anonymize detected PII anonymized_result = self.anonymizer.anonymize( text=text, analyzer_results=analyzer_results ) sanitized_text = anonymized_result.text # Step 3: Additional pattern-based cleaning for medical notes # Replace common medical note PII patterns sanitized_text = self._clean_medical_patterns(sanitized_text) # Step 4: Collect PII detection details pii_detected = [] for result in analyzer_results: pii_detected.append({ "entity_type": result.entity_type, "start": result.start, "end": result.end, "score": result.score }) logger.info(f"✅ Removed {len(pii_detected)} PII entities from text") return { "sanitized_text": sanitized_text, "pii_detected": pii_detected, "pii_count": len(pii_detected), "was_pii_removed": True } except Exception as e: logger.error(f"❌ Error removing PII: {str(e)}") # Return original text if PII removal fails return { "sanitized_text": text, "pii_detected": [], "pii_count": 0, "was_pii_removed": False, "error": str(e) } def _clean_medical_patterns(self, text: str) -> str: """ Clean common medical note PII patterns that might be missed Args: text: Text to clean Returns: Cleaned text """ # Pattern 1: "Patient: <NAME>" or "Pt: <NAME>" text = re.sub( r'(Patient|Pt|Patient Name):\s*<[A-Z_]+>', r'\1: [REDACTED]', text, flags=re.IGNORECASE ) # Pattern 2: "DOB: <DATE>" text = re.sub( r'(DOB|Date of Birth|Birth Date):\s*<[A-Z_]+>', r'\1: [REDACTED]', text, flags=re.IGNORECASE ) # Pattern 3: "Address: <LOCATION>" text = re.sub( r'(Address|Addr|Home Address):\s*<[A-Z_]+>', r'\1: [REDACTED]', text, flags=re.IGNORECASE ) # Pattern 4: "Phone: <PHONE_NUMBER>" text = re.sub( r'(Phone|Tel|Telephone|Cell|Mobile):\s*<[A-Z_]+>', r'\1: [REDACTED]', text, flags=re.IGNORECASE ) # Pattern 5: "MRN: <NUMBER>" (Medical Record Number) text = re.sub( r'(MRN|Medical Record Number|Record #):\s*<[A-Z_]+>', r'\1: [REDACTED]', text, flags=re.IGNORECASE ) return text
# Singleton instancepii_detector = PIIDetector()22 unmodified lines232425262728298 unmodified lines3839404142434445464722 unmodified linesdef test_file_upload_endpoint():"""Test new file upload endpoint"""# Create a sample TXT filefile_content = b"Patient John Doe presents with acute bronchitis. Cough for 5 days, productive with yellow sputum. Lung exam reveals diffuse wheezing."files = {8 unmodified linesassert data["success"] is Trueassert data["filename"] == "provider_notes.txt"assert data["extracted_text_length"] > 0assert "cpt_codes" in dataassert "icd_codes" in dataassert isinstance(data["cpt_codes"], list)assert isinstance(data["icd_codes"], list)def test_file_upload_invalid_extension():22 unmodified lines2324252627288 unmodified lines37383940414243444546474849505152535455565758596061626364656667686970717222 unmodified linesdef test_file_upload_endpoint():"""Test new file upload endpoint"""file_content = b"Patient John Doe presents with acute bronchitis. Cough for 5 days, productive with yellow sputum. Lung exam reveals diffuse wheezing."files = {8 unmodified linesassert data["success"] is Trueassert data["filename"] == "provider_notes.txt"assert data["extracted_text_length"] > 0assert "pii_removed" in dataassert "pii_count" in dataassert "cpt_codes" in dataassert "icd_codes" in datadef test_file_upload_with_pii():"""Test file upload with PII - should be removed"""file_content = b"""Patient: John DoeDOB: 01/15/1980Phone: 555-123-4567Address: 123 Main St, New York, NYChief Complaint: Chest painHistory: Patient presents with acute chest pain..."""files = {"file": ("notes_with_pii.txt", BytesIO(file_content), "text/plain")}response = client.post("/api/upload-file", files=files)assert response.status_code == 200data = response.json()# PII should be detected and removedassert data["pii_removed"] is Trueassert data["pii_count"] > 0def test_file_upload_invalid_extension():
Dockerfile+3
requirements.txt+5-3
src/api/routes.py+25-13
src/models/response_models.py+53-27
src/services/file_service.py+32-6
src/services/pii_detector.pyAdded+197
tests/test_api.py+28-3