CoolFace
Apppublic

BytecodeApps/docverse-api

sourceHugging Faceapache-2.0updated 7mo agoView on Hugging Face
0likes
risk_engine.py92 linesDownload Raw Back to services
1# AI Medical Document Scanner - Risk Engine Pseudo-Code2# Role: Evaluates the extracted variables from the OCR/NLP pipeline and flags3# potential risks, interactions, or medical anomalies.4# Safety Rule: NEVER diagnose. Only provide "Advisory / Informative" context.5 6from typing import List, Dict, Any7 8class SeverityLevels:9    INFO = "INFO"10    LOW = "LOW"11    MEDIUM = "MEDIUM"12    HIGH = "HIGH"13    EMERGENCY = "EMERGENCY"14 15class RiskEngine:16    def __init__(self, patient_history: Dict[str, Any]):17        self.patient_history = patient_history18        self.flags = []19    20    def evaluate_lab_results(self, lab_results: List[Dict[str, Any]]) -> List[Dict]:21        """22        Evaluate extracted lab results against known reference ranges.23        lab_results format: [{'test': 'hemoglobin', 'value': 6.5, 'unit': 'g/dL'}]24        """25        for result in lab_results:26            test_name = result.get("test", "").lower()27            value = float(result.get("value", 0))28 29            if test_name == "hemoglobin":30                if value < 7.0:31                    self.add_flag(SeverityLevels.EMERGENCY, 32                                  "Hemoglobin level is critically low (< 7.0 g/dL).",33                                  "Seek immediate medical attention.")34                elif value < 12.0:35                    self.add_flag(SeverityLevels.HIGH, 36                                  "Hemoglobin level is below normal range.",37                                  "Please consult your physician regarding potential anemia.")38            39            elif test_name == "ldl" or test_name == "ldl cholesterol":40                if value > 160:41                    self.add_flag(SeverityLevels.HIGH, 42                                  "LDL Cholesterol is significantly elevated (> 160 mg/dL).",43                                  "Consider discussing dietary changes or medication with your doctor.")44            45            elif test_name == "potassium":46                if value > 6.0:47                    self.add_flag(SeverityLevels.EMERGENCY, 48                                  "Potassium level is critically high (> 6.0 mEq/L).",49                                  "This can affect heart rhythm. Seek emergency care immediately.")50                elif value < 3.0:51                    self.add_flag(SeverityLevels.EMERGENCY,52                                  "Potassium level is critically low (< 3.0 mEq/L).",53                                  "Seek immediate medical attention.")54        55        return self.flags56    57    def evaluate_medications(self, medications: List[Dict[str, Any]]) -> List[Dict]:58        """59        Evaluate extracted medications for interactions or duplicates.60        medications format: [{'drug': 'Lisinopril', 'class': 'ACE Inhibitor'}]61        """62        drug_names = [med.get("drug").lower() for med in medications]63        drug_classes = [med.get("class").lower() for med in medications]64 65        # 1. Duplicate check66        if len(drug_names) != len(set(drug_names)):67            self.add_flag(SeverityLevels.MEDIUM, 68                          "Duplicate medications detected in the prescription.",69                          "Ensure you are not taking the same medication twice.")70 71        # 2. Interaction check (Pseudo-rule example)72        if "sildenafil" in drug_names and any("nitrate" in cls for cls in drug_classes):73            self.add_flag(SeverityLevels.EMERGENCY,74                          "Severe drug interaction detected: Sildenafil + Nitrates.",75                          "Do NOT take these together. It can cause a fatal drop in blood pressure. Contact your doctor immediately.")76 77        return self.flags78    79    def add_flag(self, severity: str, description: str, advisory_action: str):80        self.flags.append({81            "severity": severity,82            "description": f"[ADVISORY] {description}",83            "action": advisory_action,84            "disclaimer": "This system provides insights only and does not constitute medical advice. Please consult a qualified healthcare provider."85        })86 87# --- Usage Example ---88# engine = RiskEngine(patient_history={})89# engine.evaluate_lab_results([{'test': 'potassium', 'value': 6.2, 'unit': 'mEq/L'}])90# engine.evaluate_medications([{'drug': 'Sildenafil'}, {'drug': 'Isosorbide', 'class': 'Nitrate'}])91# print(engine.flags)92