Spaces:
Running
Running
Download safety_checker.py from build-small-hackathon/cliniq: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/build-small-hackathon/cliniq/resolve/main/safety_checker.py
- Command line
-
hf download hf://spaces/build-small-hackathon/cliniq/safety_checker.py
-
curl -L -o safety_checker.py https://huggingface.co/spaces/build-small-hackathon/cliniq/resolve/main/safety_checker.py
10.2 kB
| """ | |
| ClinIQ — Proactive Drug Safety Checker. | |
| Design: | |
| Step 1 — Regex extraction: pull MEDICATIONS and ALLERGIES sections directly | |
| from the text (fast, 100% reliable, no LLM needed). | |
| Step 2 — LLM safety reasoning: feed the clean extracted lists to the model | |
| and ask only "are there any dangerous combinations?" | |
| This avoids all JSON key confusion and context overflow issues. | |
| """ | |
| from __future__ import annotations | |
| import json, re | |
| from dataclasses import dataclass, field | |
| from typing import Any, List, Optional | |
| # ── JSON helpers ─────────────────────────────────────────────────────────────── | |
| def _parse_json(text: str) -> Optional[Any]: | |
| for candidate in [text.strip(), _brace_extract(text), _fix(_brace_extract(text))]: | |
| if not candidate: | |
| continue | |
| try: | |
| return json.loads(candidate) | |
| except Exception: | |
| pass | |
| return None | |
| def _brace_extract(text: str) -> str: | |
| start = text.find('{') | |
| if start == -1: | |
| return "" | |
| depth = 0 | |
| for i, ch in enumerate(text[start:], start): | |
| if ch == '{': | |
| depth += 1 | |
| elif ch == '}': | |
| depth -= 1 | |
| if depth == 0: | |
| return text[start:i + 1] | |
| return text[start:] | |
| def _fix(s: str) -> str: | |
| if not s: | |
| return s | |
| s = re.sub(r',\s*([}\]])', r'\1', s) | |
| s = re.sub(r'[\x00-\x1f\x7f]', ' ', s) | |
| open_b = s.count('[') - s.count(']') | |
| open_c = s.count('{') - s.count('}') | |
| return s + ']' * max(0, open_b) + '}' * max(0, open_c) | |
| # ── Data classes ─────────────────────────────────────────────────────────────── | |
| class SafetyAlert: | |
| level: str | |
| title: str | |
| detail: str | |
| recommendation: str | |
| class SafetyReport: | |
| medications: List[str] = field(default_factory=list) | |
| allergies: List[str] = field(default_factory=list) | |
| alerts: List[SafetyAlert] = field(default_factory=list) | |
| overall_safety: str = "SAFE" | |
| error: Optional[str] = None | |
| def has_danger(self) -> bool: | |
| return any(a.level == "DANGER" for a in self.alerts) | |
| # ── Regex extraction (Step 1 — no LLM) ──────────────────────────────────────── | |
| _SECTION_HEADER = re.compile( | |
| r'^(PHYSICAL|HISTORY|HOSPITAL|PROCEDURE|ASSESSMENT|PLAN|IMPRESSION|FOLLOW|NOTE|REASON|' | |
| r'DISCHARGE|PRIMARY|SECONDARY|VITAL|GENERAL|CARDIO|RESPIRATORY|EXAM|INVEST|PATIENT)', | |
| re.IGNORECASE, | |
| ) | |
| def _extract_lines(context: str) -> tuple[List[str], List[str]]: | |
| """ | |
| Pull medication and allergy lines directly from document text using regex. | |
| Covers many real-world clinical document formats, not just standard headers. | |
| Finds ALL matching sections per document (not just the first). | |
| """ | |
| meds: List[str] = [] | |
| allgs: List[str] = [] | |
| seen_m: set = set() | |
| seen_a: set = set() | |
| def _clean(line: str) -> str: | |
| return re.sub(r'^[\d\.\-\*\•\s]+', '', line).strip() | |
| def _is_noise(line: str) -> bool: | |
| """Filter out section headers accidentally captured.""" | |
| return bool(_SECTION_HEADER.match(line)) or len(line) < 3 | |
| # ── Medication section headers — covers common real-world formats ────────── | |
| # Examples: "MEDICATIONS:", "Current Medications:", "Active Medications:", | |
| # "Medication List:", "Rx:", "Prescriptions:", "Drug List:", | |
| # "Home Medications:", "Discharge Medications:", "Outpatient Meds:" | |
| MED_HEADER = re.compile( | |
| r'(?:current\s+|active\s+|home\s+|discharge\s+|outpatient\s+|admission\s+|' | |
| r'inpatient\s+|chronic\s+|long.?term\s+)?' | |
| r'(?:medications?|meds?|medicines?|drugs?|prescriptions?|rx)' | |
| r'(?:\s+list)?' | |
| r'[^\n]{0,30}\n', | |
| re.IGNORECASE, | |
| ) | |
| # ── Allergy section headers — covers common real-world formats ───────────── | |
| # Examples: "ALLERGIES:", "Drug Allergies:", "Known Allergies:", | |
| # "Allergy List:", "Sensitivities:", "Adverse Reactions:", | |
| # "Drug Intolerances:", "NKA" (no known allergies) | |
| ALLERGY_HEADER = re.compile( | |
| r'(?:drug\s+|food\s+|environmental\s+|known\s+|reported\s+)?' | |
| r'(?:allergies?|allergy|sensitivities|sensitivity|intolerances?|' | |
| r'adverse\s+reactions?|hypersensitivities?)' | |
| r'(?:\s+list)?' | |
| r'[^\n]{0,30}\n', | |
| re.IGNORECASE, | |
| ) | |
| # ── Also catch inline bullet/colon lists after a header on the same line ─── | |
| # e.g. "Allergies: Penicillin (rash), Sulfa" | |
| ALLERGY_INLINE = re.compile( | |
| r'(?:drug\s+|known\s+)?(?:allergies?|allergy|sensitivities?|adverse\s+reactions?)' | |
| r'\s*:\s*([^\n]{3,200})', | |
| re.IGNORECASE, | |
| ) | |
| MED_INLINE = re.compile( | |
| r'(?:current\s+|active\s+|home\s+)?(?:medications?|meds?|rx)' | |
| r'\s*:\s*([^\n]{3,200})', | |
| re.IGNORECASE, | |
| ) | |
| def _harvest(pattern, context, seen, out, max_lines=20): | |
| """Find all sections matching pattern and extract bullet/numbered lines.""" | |
| for match in re.finditer(pattern, context): | |
| # Grab the block of lines after the header | |
| start = match.end() | |
| block = context[start:start + 1200] | |
| count = 0 | |
| for line in block.splitlines(): | |
| if count >= max_lines: | |
| break | |
| # Stop if we hit another section header (blank-ish line or ALL CAPS heading) | |
| stripped = line.strip() | |
| if not stripped: | |
| continue | |
| if re.match(r'^[A-Z][A-Z\s]{4,}:', stripped) and not re.match(r'^[A-Z][a-z]', stripped): | |
| break | |
| cleaned = _clean(stripped) | |
| key = cleaned.lower()[:30] | |
| if cleaned and not _is_noise(cleaned) and key not in seen: | |
| seen.add(key) | |
| out.append(cleaned) | |
| count += 1 | |
| def _harvest_inline(pattern, context, seen, out): | |
| """Catch single-line format: 'Allergies: Penicillin, Sulfa'""" | |
| for match in re.finditer(pattern, context): | |
| raw = match.group(1) | |
| # Split on commas or semicolons | |
| for part in re.split(r'[,;]', raw): | |
| cleaned = _clean(part.strip()) | |
| key = cleaned.lower()[:30] | |
| if cleaned and not _is_noise(cleaned) and key not in seen: | |
| seen.add(key) | |
| out.append(cleaned) | |
| _harvest(MED_HEADER, context, seen_m, meds, max_lines=20) | |
| _harvest(ALLERGY_HEADER, context, seen_a, allgs, max_lines=10) | |
| _harvest_inline(MED_INLINE, context, seen_m, meds) | |
| _harvest_inline(ALLERGY_INLINE, context, seen_a, allgs) | |
| return meds, allgs | |
| # ── LLM safety prompt (Step 2) ───────────────────────────────────────────────── | |
| _SAFETY_PROMPT = ( | |
| "<|im_start|>system\n" | |
| "You are a senior clinical pharmacist. Output ONLY valid JSON.<|im_end|>\n" | |
| "<|im_start|>user\n" | |
| "A patient has these medications and allergies. Find ALL safety concerns.\n\n" | |
| "MEDICATIONS:\n{meds}\n\n" | |
| "ALLERGIES:\n{allgs}\n\n" | |
| "Look for:\n" | |
| "- Drug-allergy contraindications (same class as allergen)\n" | |
| "- Dangerous drug-drug interactions\n" | |
| "- Drug-disease contraindications (e.g. beta-blockers in asthma)\n\n" | |
| "Output ONLY this JSON:\n" | |
| '{{"alerts":[{{"level":"DANGER","title":"...","detail":"...","recommendation":"..."}}],' | |
| '"overall_safety":"SAFE"}}\n' | |
| "level must be DANGER, WARNING, or INFO. " | |
| "overall_safety must be SAFE, REVIEW_NEEDED, or URGENT.\n" | |
| "<|im_end|>\n<|im_start|>assistant\n" | |
| ) | |
| # ── Main ─────────────────────────────────────────────────────────────────────── | |
| def run_safety_check(context: str, call_model_fn) -> SafetyReport: | |
| report = SafetyReport() | |
| if not context.strip(): | |
| return report | |
| # Sanitize | |
| context = re.sub(r'[^\x00-\x7F]', '-', context) | |
| # Step 1: regex extraction — fast, reliable, no LLM | |
| meds, allgs = _extract_lines(context) | |
| if not meds and not allgs: | |
| report.overall_safety = "SAFE" | |
| return report | |
| report.medications = [{"name": m} for m in meds] | |
| report.allergies = [{"substance": a} for a in allgs] | |
| # Step 2: LLM safety reasoning on clean lists | |
| meds_text = "\n".join(f"- {m}" for m in meds[:15]) | |
| allgs_text = "\n".join(f"- {a}" for a in allgs[:10]) | |
| prompt = _SAFETY_PROMPT.format(meds=meds_text, allgs=allgs_text) | |
| try: | |
| raw = call_model_fn(prompt, 600, False) | |
| data = _parse_json(raw) or {} | |
| report.overall_safety = data.get("overall_safety", "REVIEW_NEEDED") | |
| report.alerts = [ | |
| SafetyAlert( | |
| level = a.get("level", "INFO"), | |
| title = a.get("title", ""), | |
| detail = a.get("detail", ""), | |
| recommendation = a.get("recommendation", ""), | |
| ) | |
| for a in data.get("alerts", []) | |
| if isinstance(a, dict) and a.get("title") | |
| ] | |
| except Exception as e: | |
| report.error = f"Safety analysis error: {e}" | |
| return report | |
| def report_to_dict(report: SafetyReport) -> dict: | |
| return { | |
| "overall_safety": report.overall_safety, | |
| "medications": report.medications, | |
| "allergies": report.allergies, | |
| "alerts": [ | |
| {"level": a.level, "title": a.title, | |
| "detail": a.detail, "recommendation": a.recommendation} | |
| for a in report.alerts | |
| ], | |
| "error": report.error, | |
| } | |