Download scripts/surgery/parse_programme.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 20 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/surgery/parse_programme.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/scripts/surgery/parse_programme.py
-
curl -L -o parse_programme.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/surgery/parse_programme.py
20 kB
| #!/usr/bin/env python3 | |
| """ | |
| Parse Raw Programme — Transform pasted surgery lists into structured cases | |
| Accepts raw text (the messy hand-written programme) and produces structured | |
| case dicts compatible with PROGRAM_CASES format / BlocCase creation. | |
| Usage: | |
| # As a module | |
| from scripts.surgery.parse_programme import parse_raw_programme | |
| cases = parse_raw_programme(raw_text) | |
| # CLI | |
| PYTHONPATH=src python3 scripts/surgery/parse_programme.py < programme.txt | |
| PYTHONPATH=src python3 scripts/surgery/parse_programme.py --file programme.txt | |
| Design: | |
| - Regex-based line parser | |
| - Category detection from section headers | |
| - ASA normalization (ASA1/Asa1/ASAI/ASA I → ASA_I) | |
| - Phone extraction and normalization | |
| - Free-text note extraction (blockers, logistics, evidence) | |
| - Preserves raw source text for audit | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import json | |
| import sys | |
| from datetime import datetime | |
| from typing import Any, Dict, List, Optional, Tuple | |
| # ═══════════════════════════════════════════════════════════ | |
| # CATEGORY DETECTION — from section headers | |
| # ═══════════════════════════════════════════════════════════ | |
| SECTION_PATTERNS: List[Tuple[re.Pattern, str, str]] = [ | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*VBL", re.IGNORECASE), "vbl", "simple_vbl"), | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*(?:Hernies?\s+ombilicale|hernie.*ombili)", re.IGNORECASE), "hernia", "umbilical_hernia"), | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*(?:Hernie.*inguino\s*scrotale)", re.IGNORECASE), "hernia", "inguinoscrotal_hernia"), | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*(?:Hernie.*inguinale)", re.IGNORECASE), "hernia", "inguinal_hernia"), | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*Eventration", re.IGNORECASE), "hernia", "eventration"), | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*Lipome", re.IGNORECASE), "wall_soft_tissue", "lipoma"), | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*Paroi", re.IGNORECASE), "wall_soft_tissue", "parietal_hematoma"), | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*Kyste", re.IGNORECASE), "wall_soft_tissue", "cyst"), | |
| (re.compile(r"(?:^|\n)\s*#{1,4}\s*UNKNOWN", re.IGNORECASE), "other", "other"), | |
| ] | |
| # ═══════════════════════════════════════════════════════════ | |
| # ASA NORMALIZATION | |
| # ═══════════════════════════════════════════════════════════ | |
| ASA_PATTERNS = [ | |
| (re.compile(r"\bASA\s*(?:II|2)\b", re.IGNORECASE), 2), | |
| (re.compile(r"\bASA\s*(?:III|3)\b", re.IGNORECASE), 3), | |
| (re.compile(r"\bASA\s*(?:IV|4)\b", re.IGNORECASE), 4), | |
| (re.compile(r"\bASA\s*(?:V|5)\b", re.IGNORECASE), 5), | |
| (re.compile(r"\bASA\s*(?:I|1)\b", re.IGNORECASE), 1), | |
| (re.compile(r"\bAs[a]?\s*1\b", re.IGNORECASE), 1), | |
| (re.compile(r"\bAs[a]?\s*2\b", re.IGNORECASE), 2), | |
| ] | |
| def normalize_asa(text: str) -> Optional[int]: | |
| """Extract and normalize ASA score from text.""" | |
| for pattern, score in ASA_PATTERNS: | |
| if pattern.search(text): | |
| return score | |
| return None | |
| # ═══════════════════════════════════════════════════════════ | |
| # PHONE NORMALIZATION | |
| # ═══════════════════════════════════════════════════════════ | |
| PHONE_RE = re.compile(r"(?:0\d[\s.]?\d{2}[\s.]?\d{2}[\s.]?\d{2}[\s.]?\d{2})") | |
| def normalize_phone(text: str) -> Optional[str]: | |
| """Extract and normalize phone number (Moroccan format).""" | |
| match = PHONE_RE.search(text) | |
| if match: | |
| return re.sub(r"[\s.]", "", match.group()) | |
| return None | |
| # ═══════════════════════════════════════════════════════════ | |
| # DIAGNOSIS NORMALIZATION | |
| # ═══════════════════════════════════════════════════════════ | |
| DIAGNOSIS_MAP: List[Tuple[re.Pattern, str, str]] = [ | |
| (re.compile(r"cholecystite", re.IGNORECASE), "Cholécystite aiguë", "cholecystitis"), | |
| (re.compile(r"vblsa.*pancr|pancr.*vblsa", re.IGNORECASE), "VBLSA + antécédent de pancréatite biliaire", "vbl_pancreatitis_history"), | |
| (re.compile(r"vblsa", re.IGNORECASE), "VBLSA (VBL symptomatique avec antécédent)", "simple_vbl"), | |
| (re.compile(r"vbls(?!a)", re.IGNORECASE), "VBLS (VBL symptomatique)", "simple_vbl"), | |
| (re.compile(r"\bvbl\b", re.IGNORECASE), "VBL (lithiase vésiculaire)", "simple_vbl"), | |
| (re.compile(r"hernie\s+inguino\s*scrotale", re.IGNORECASE), "Hernie inguinoscrotale", "inguinoscrotal_hernia"), | |
| (re.compile(r"hernie\s+sus[\s-]?ombilicale", re.IGNORECASE), "Hernie sus-ombilicale", "supra_umbilical_hernia"), | |
| (re.compile(r"hernie\s+ombilicale", re.IGNORECASE), "Hernie ombilicale", "umbilical_hernia"), | |
| (re.compile(r"hernie\s+inguinale|HIG", re.IGNORECASE), "Hernie inguinale", "inguinal_hernia"), | |
| (re.compile(r"\bhernie\b", re.IGNORECASE), "Hernie (type à préciser)", "other"), | |
| (re.compile(r"lipome", re.IGNORECASE), "Lipome", "lipoma"), | |
| (re.compile(r"hematome\s+parietal|parietal.*hematome", re.IGNORECASE), "Hématome pariétal", "parietal_hematoma"), | |
| (re.compile(r"kyste\s+perin", re.IGNORECASE), "Kyste périnéal", "perineal_cyst"), | |
| (re.compile(r"kyste.*cuir\s+chevel|kyste\s+seb", re.IGNORECASE), "Kyste sébacé cuir chevelu", "scalp_cyst"), | |
| (re.compile(r"kyste", re.IGNORECASE), "Kyste", "cyst"), | |
| (re.compile(r"eventration", re.IGNORECASE), "Éventration", "eventration"), | |
| ] | |
| def normalize_diagnosis(text: str, section_procedure: str) -> Tuple[str, str]: | |
| """Normalize diagnosis from free text. Returns (diagnosis_label, procedure_type).""" | |
| for pattern, label, proc in DIAGNOSIS_MAP: | |
| if pattern.search(text): | |
| return label, proc | |
| return f"À préciser ({text[:60]})", section_procedure | |
| # ═══════════════════════════════════════════════════════════ | |
| # FREE-TEXT NOTE EXTRACTION | |
| # ═══════════════════════════════════════════════════════════ | |
| BLOCKER_PATTERNS = [ | |
| (re.compile(r"bilan\s+non\s+delivree?", re.IGNORECASE), "missing_workup", "Bilan non délivrée"), | |
| (re.compile(r"(?:TP|tp)\s*(\d+)%", re.IGNORECASE), "abnormal_biology", None), | |
| (re.compile(r"non\s+joignable", re.IGNORECASE), "contact_unreachable", "Non joignable"), | |
| (re.compile(r"prisonn?ier", re.IGNORECASE), "prisoner", "Prisonnier"), | |
| (re.compile(r"avis\s+uro", re.IGNORECASE), "external_opinion", "Avis urologique requis"), | |
| (re.compile(r"alitante", re.IGNORECASE), "mobility_issue", "Patiente alitante"), | |
| (re.compile(r"voyage", re.IGNORECASE), "travel_constraint", "Patiente en voyage"), | |
| ] | |
| EVIDENCE_PATTERNS = [ | |
| (re.compile(r"bilan\s+ok|bilan\s+delivree?", re.IGNORECASE), "lab", "ok"), | |
| (re.compile(r"\bCPA\b", re.IGNORECASE), "anesthesia", "ok"), | |
| (re.compile(r"bili[\s-]?irm", re.IGNORECASE), "mri", "pending"), | |
| (re.compile(r"-bilan|-rxthorax|bilan.*manqu", re.IGNORECASE), "lab", "missing"), | |
| (re.compile(r"\btp\s+tck\b", re.IGNORECASE), "lab", "pending"), | |
| ] | |
| STATUS_PATTERNS = [ | |
| (re.compile(r"operer\s+ext|operer$|chirurgie\s+ext", re.IGNORECASE), "external_management"), | |
| (re.compile(r"spasfon", re.IGNORECASE), "current_treatment"), | |
| ] | |
| def extract_notes(text: str) -> Dict[str, Any]: | |
| """Extract structured info from free-text notes.""" | |
| result: Dict[str, Any] = { | |
| "blockers": [], | |
| "evidence_hints": [], | |
| "logistics_flags": [], | |
| "biology_status": "missing", | |
| "imaging_status": "missing", | |
| "anesthesia_clearance": "missing", | |
| "contact_status": "joignable", | |
| "logistic_constraints": None, | |
| } | |
| for pattern, blocker_type, label in BLOCKER_PATTERNS: | |
| m = pattern.search(text) | |
| if m: | |
| if blocker_type == "abnormal_biology": | |
| tp_val = m.group(1) if m.lastindex else "" | |
| result["blockers"].append(f"TP {tp_val}% — coagulation anormale") | |
| result["biology_status"] = "abnormal" | |
| elif blocker_type == "contact_unreachable": | |
| result["contact_status"] = "non_joignable" | |
| result["blockers"].append(label) | |
| elif blocker_type == "prisoner": | |
| result["logistics_flags"].append("prisoner") | |
| result["contact_status"] = "prisonnier" | |
| elif blocker_type == "mobility_issue": | |
| result["logistics_flags"].append("mobility") | |
| result["logistic_constraints"] = label | |
| elif blocker_type == "travel_constraint": | |
| result["logistics_flags"].append("travel") | |
| result["logistic_constraints"] = label | |
| elif blocker_type == "external_opinion": | |
| result["logistics_flags"].append("external_opinion") | |
| result["blockers"].append(label) | |
| elif blocker_type == "missing_workup": | |
| result["blockers"].append(label) | |
| result["biology_status"] = "missing" | |
| for pattern, ev_type, status in EVIDENCE_PATTERNS: | |
| if pattern.search(text): | |
| result["evidence_hints"].append({"type": ev_type, "status": status}) | |
| if ev_type == "lab" and status == "ok": | |
| result["biology_status"] = "ok" | |
| elif ev_type == "lab" and status == "missing": | |
| result["biology_status"] = "missing" | |
| elif ev_type == "anesthesia" and status == "ok": | |
| result["anesthesia_clearance"] = "ok" | |
| elif ev_type == "mri" and status == "pending": | |
| result["imaging_status"] = "pending" | |
| return result | |
| # ═══════════════════════════════════════════════════════════ | |
| # DATE EXTRACTION | |
| # ═══════════════════════════════════════════════════════════ | |
| DATE_RE = re.compile(r"(\d{2})/(\d{2})/(\d{4})") | |
| def extract_date(text: str) -> Optional[str]: | |
| """Extract date in dd/mm/yyyy format and return as ISO string.""" | |
| m = DATE_RE.search(text) | |
| if m: | |
| day, month, year = m.groups() | |
| return f"{year}-{month}-{day}" | |
| return None | |
| # ═══════════════════════════════════════════════════════════ | |
| # CLASSIFY CASE — operational grouping | |
| # ═══════════════════════════════════════════════════════════ | |
| def classify_case(case: Dict[str, Any]) -> Tuple[str, str, str]: | |
| """ | |
| Determine operational_group, decision, and next_action. | |
| Returns (operational_group, decision, next_action) | |
| """ | |
| bio = case.get("biology_status", "missing") | |
| img = case.get("imaging_status", "missing") | |
| anes = case.get("anesthesia_clearance", "missing") | |
| blockers = case.get("blockers", []) | |
| logistics = case.get("logistics_flags", []) | |
| certainty = case.get("certainty_level", "uncertain") | |
| contact = case.get("contact_status", "joignable") | |
| # External management | |
| if any(re.search(r"operer\s+ext|chirurgie\s+ext", b, re.IGNORECASE) for b in blockers): | |
| return "external", "completed", "mark_external_management" | |
| # Logistics special | |
| if "prisoner" in logistics: | |
| return "logistics_special", "operate", "resolve_logistics" | |
| if contact == "non_joignable": | |
| return "logistics_special", "operate", "follow_up_contact" | |
| if any(f in logistics for f in ("mobility", "travel")): | |
| return "logistics_special", "operate", "resolve_logistics" | |
| # All ready | |
| if bio == "ok" and anes == "ok" and img in ("ok", "na") and certainty in ("certain", "probable"): | |
| return "ready_for_bloc", "operate", "send_to_bloc" | |
| # Abnormal biology → optimize | |
| if bio == "abnormal": | |
| return "optimize_before_bloc", "optimize", "correct_biology" | |
| # External opinion pending | |
| if "external_opinion" in logistics: | |
| return "optimize_before_bloc", "optimize", "obtain_external_opinion" | |
| # Missing evidence | |
| if bio == "missing" or img == "missing" or anes == "missing": | |
| return "awaiting_evidence", "observe", "complete_workup" | |
| # Pending imaging | |
| if img == "pending": | |
| return "awaiting_evidence", "observe", "request_imaging" | |
| # Uncertain diagnosis | |
| if certainty == "uncertain": | |
| return "needs_review", "observe", "review_case" | |
| return "needs_review", "observe", "review_case" | |
| # ═══════════════════════════════════════════════════════════ | |
| # MAIN PARSER | |
| # ═══════════════════════════════════════════════════════════ | |
| def parse_raw_programme( | |
| raw_text: str, | |
| batch_id: Optional[str] = None, | |
| ) -> List[Dict[str, Any]]: | |
| """ | |
| Parse raw pasted programme text into structured case dicts. | |
| Each line starting with * is treated as a case entry. | |
| Section headers (#### VBL, #### Hernies, etc.) set the current category. | |
| Returns list of case dicts compatible with BlocCase creation. | |
| """ | |
| if batch_id is None: | |
| batch_id = f"import_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}" | |
| cases: List[Dict[str, Any]] = [] | |
| current_category = "other" | |
| current_procedure = "other" | |
| for line in raw_text.splitlines(): | |
| stripped = line.strip() | |
| if not stripped: | |
| continue | |
| # Check for section headers | |
| for pattern, cat, proc in SECTION_PATTERNS: | |
| if pattern.search(stripped): | |
| current_category = cat | |
| current_procedure = proc | |
| break | |
| # Case lines start with * or - | |
| if not stripped.startswith(("*", "-")): | |
| continue | |
| # Remove leading * or - and whitespace | |
| case_text = stripped.lstrip("*- ").strip() | |
| if not case_text: | |
| continue | |
| # Split on em-dash (—) or double-dash (--) | |
| parts = re.split(r"\s*[—–]\s*|\s+--\s+", case_text) | |
| parts = [p.strip() for p in parts if p.strip()] | |
| if not parts: | |
| continue | |
| # First part is always the name | |
| patient_name = parts[0] | |
| # Rejoin all parts for full-text analysis | |
| full_text = " ".join(parts) | |
| # Extract structured fields | |
| asa = normalize_asa(full_text) | |
| phone = normalize_phone(full_text) | |
| sched_date = extract_date(full_text) | |
| diagnosis, procedure_type = normalize_diagnosis(full_text, current_procedure) | |
| notes = extract_notes(full_text) | |
| # If name looks like a phone number, skip | |
| if re.match(r"^0\d{9}$", patient_name): | |
| continue | |
| # Determine certainty | |
| certainty = "uncertain" | |
| if notes["biology_status"] == "ok" and notes["anesthesia_clearance"] == "ok": | |
| certainty = "certain" | |
| elif notes["biology_status"] == "ok" or notes["anesthesia_clearance"] == "ok": | |
| certainty = "probable" | |
| case: Dict[str, Any] = { | |
| "patient_name": patient_name, | |
| "phone": phone, | |
| "diagnosis": diagnosis, | |
| "program_category": current_category, | |
| "procedure_type": procedure_type, | |
| "certainty_level": certainty, | |
| "asa_score": asa, | |
| "urgency": "elective", | |
| "risk_level": "low", | |
| "biology_status": notes["biology_status"], | |
| "imaging_status": notes["imaging_status"], | |
| "anesthesia_clearance": notes["anesthesia_clearance"], | |
| "consent_status": "missing", | |
| "contact_status": notes["contact_status"], | |
| "logistic_constraints": notes.get("logistic_constraints"), | |
| "logistics_flag": notes["logistics_flags"][0] if notes["logistics_flags"] else "none", | |
| # Import tracking | |
| "source_program": "programme_chirurgie", | |
| "raw_source_text": case_text, | |
| "import_batch_id": batch_id, | |
| "created_from_import": True, | |
| "review_required": True, # All parsed cases need review | |
| } | |
| if sched_date: | |
| case["scheduled_date"] = sched_date | |
| # Build evidence list from hints | |
| evidence = [] | |
| for hint in notes["evidence_hints"]: | |
| evidence.append({ | |
| "evidence_type": hint["type"], | |
| "summary": f"Extrait automatiquement du texte brut", | |
| "is_conclusive": hint["status"] == "ok", | |
| }) | |
| case["evidence"] = evidence | |
| # Classify | |
| group, decision, next_action = classify_case({**case, **notes}) | |
| case["operational_group"] = group | |
| case["decision"] = decision | |
| case["next_action"] = next_action | |
| cases.append(case) | |
| return cases | |
| def print_parsed_cases(cases: List[Dict[str, Any]]): | |
| """Print parsed cases in a readable format.""" | |
| print(f"\n{'=' * 70}") | |
| print(f" PARSED PROGRAMME — {len(cases)} cases") | |
| print(f"{'=' * 70}") | |
| groups: Dict[str, List[Dict]] = {} | |
| for c in cases: | |
| g = c.get("operational_group", "needs_review") | |
| groups.setdefault(g, []).append(c) | |
| for group, group_cases in sorted(groups.items()): | |
| print(f"\n [{group.upper()}] — {len(group_cases)} cases") | |
| for c in group_cases: | |
| asa = f"ASA {c['asa_score']}" if c.get("asa_score") else "ASA ?" | |
| phone = c.get("phone", "—") | |
| decision = c.get("decision", "?") | |
| next_act = c.get("next_action", "?") | |
| print(f" • {c['patient_name']:<25} {asa:<8} ☎ {phone:<15} → {decision} → {next_act}") | |
| if c.get("logistic_constraints"): | |
| print(f" ⚠ {c['logistic_constraints']}") | |
| # ═══════════════════════════════════════════════════════════ | |
| # CLI | |
| # ═══════════════════════════════════════════════════════════ | |
| if __name__ == "__main__": | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Parse raw surgery programme text") | |
| parser.add_argument("--file", "-f", help="Input file (default: stdin)") | |
| parser.add_argument("--json", action="store_true", help="Output as JSON") | |
| parser.add_argument("--batch-id", help="Import batch ID") | |
| args = parser.parse_args() | |
| if args.file: | |
| with open(args.file, "r", encoding="utf-8") as f: | |
| raw = f.read() | |
| else: | |
| raw = sys.stdin.read() | |
| cases = parse_raw_programme(raw, batch_id=args.batch_id) | |
| if args.json: | |
| print(json.dumps(cases, indent=2, ensure_ascii=False, default=str)) | |
| else: | |
| print_parsed_cases(cases) | |