Download scripts/surgery/seed_programme.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 23.3 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/surgery/seed_programme.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/scripts/surgery/seed_programme.py
-
curl -L -o seed_programme.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/surgery/seed_programme.py
23.3 kB
| #!/usr/bin/env python3 | |
| """ | |
| Seed Programme Chirurgical — Import structured cases into DB | |
| Reads PROGRAM_CASES from data/seeds/programs.py, creates BlocCase + | |
| TrackerCase entries in the database. Supports idempotent re-runs. | |
| Usage: | |
| PYTHONPATH=src python3 scripts/surgery/seed_programme.py | |
| PYTHONPATH=src python3 scripts/surgery/seed_programme.py --dry-run | |
| PYTHONPATH=src python3 scripts/surgery/seed_programme.py --report-only | |
| Deduplication: patient_name + program_category + import_batch_id | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import os | |
| import sys | |
| from datetime import datetime, date | |
| from enum import Enum | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional | |
| from uuid import UUID, uuid4 | |
| # Ensure workspace root is on path | |
| workspace = Path(__file__).resolve().parent.parent.parent | |
| sys.path.insert(0, str(workspace / "src")) | |
| sys.path.insert(0, str(workspace)) | |
| import structlog | |
| from sqlalchemy import text | |
| from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine | |
| from sqlalchemy.orm import sessionmaker | |
| from apps.surgio.bloc.models import BlocCase | |
| logger = structlog.get_logger(__name__) | |
| # ═══════════════════════════════════════════════════════════ | |
| # DEFAULT TENANT — discovered from database or fallback | |
| # ═══════════════════════════════════════════════════════════ | |
| BATCH_ID = "prog_chirurgie_2024_04" | |
| async def discover_tenant(session: AsyncSession) -> tuple[UUID, UUID]: | |
| """Find the first tenant and user in the database, or create fallbacks.""" | |
| # Find tenant | |
| result = await session.execute(text("SELECT id FROM tenants LIMIT 1")) | |
| row = result.fetchone() | |
| if row: | |
| tenant_id = UUID(row[0]) if isinstance(row[0], str) else row[0] | |
| else: | |
| tenant_id = uuid4() | |
| logger.warning("no_tenant_found", using_random=str(tenant_id)) | |
| # Find user | |
| result = await session.execute(text("SELECT id FROM users LIMIT 1")) | |
| row = result.fetchone() | |
| if row: | |
| user_id = UUID(row[0]) if isinstance(row[0], str) else row[0] | |
| else: | |
| user_id = uuid4() | |
| logger.warning("no_user_found", using_random=str(user_id)) | |
| logger.info("tenant_discovered", tenant_id=str(tenant_id), user_id=str(user_id)) | |
| return tenant_id, user_id | |
| # ═══════════════════════════════════════════════════════════ | |
| # SCHEMA MIGRATION — add missing columns if needed | |
| # ═══════════════════════════════════════════════════════════ | |
| REQUIRED_COLUMNS = { | |
| "surgeon": "VARCHAR(200)", | |
| "site": "VARCHAR(100)", | |
| "programme_category": "VARCHAR(30)", | |
| "procedure_type": "VARCHAR(50)", | |
| "equipment_requirements": "VARCHAR(500)", | |
| "blood_requirements": "VARCHAR(200)", | |
| "consent_status": "VARCHAR(14) DEFAULT 'missing'", | |
| "logistics_flag": "VARCHAR(30) DEFAULT 'none'", | |
| "cancellation_reason": "VARCHAR(500)", | |
| "complications_30d": "JSON", | |
| "readmission_30d": "BOOLEAN DEFAULT 0", | |
| # Import tracking fields | |
| "source_program": "VARCHAR(100)", | |
| "raw_source_text": "TEXT", | |
| "import_batch_id": "VARCHAR(50)", | |
| "created_from_import": "BOOLEAN DEFAULT 0", | |
| "review_required": "BOOLEAN DEFAULT 0", | |
| "contact_status": "VARCHAR(30)", | |
| "next_action": "VARCHAR(100)", | |
| "operational_group": "VARCHAR(30)", | |
| } | |
| async def ensure_columns(session: AsyncSession) -> List[str]: | |
| """Add missing columns to bloc_cases table. Returns list of added columns.""" | |
| added = [] | |
| result = await session.execute(text("PRAGMA table_info(bloc_cases)")) | |
| existing = {row[1] for row in result.fetchall()} | |
| for col_name, col_type in REQUIRED_COLUMNS.items(): | |
| if col_name not in existing: | |
| await session.execute( | |
| text(f"ALTER TABLE bloc_cases ADD COLUMN {col_name} {col_type}") | |
| ) | |
| added.append(col_name) | |
| logger.info("column_added", table="bloc_cases", column=col_name) | |
| if added: | |
| await session.commit() | |
| return added | |
| # ═══════════════════════════════════════════════════════════ | |
| # DEDUPLICATION | |
| # ═══════════════════════════════════════════════════════════ | |
| async def find_existing( | |
| session: AsyncSession, | |
| tenant_id: UUID, | |
| patient_name: str, | |
| program_category: Optional[str], | |
| batch_id: str, | |
| ) -> Optional[BlocCase]: | |
| """Check if a case already exists (dedup by name + category + batch).""" | |
| from sqlalchemy import select, and_ | |
| conditions = [ | |
| BlocCase.tenant_id == tenant_id, | |
| BlocCase.patient_name == patient_name, | |
| ] | |
| if program_category: | |
| conditions.append(BlocCase.program_category == program_category) | |
| conditions.append(BlocCase.import_batch_id == batch_id) | |
| result = await session.execute( | |
| select(BlocCase).where(and_(*conditions)) | |
| ) | |
| return result.scalar_one_or_none() | |
| # ═══════════════════════════════════════════════════════════ | |
| # TRACES BRIDGE — create TrackerCase for each BlocCase | |
| # ═══════════════════════════════════════════════════════════ | |
| async def create_trace_for_bloc( | |
| session: AsyncSession, | |
| tenant_id: UUID, | |
| bloc: BlocCase, | |
| ) -> Optional[UUID]: | |
| """Create a TrackerCase linked to this BlocCase via raw SQL (table: traker_cases).""" | |
| try: | |
| from apps.traces.models import CaseState, CasePriority | |
| # Map decision → state | |
| state_map = { | |
| "operate": "scheduled" if bloc.scheduled_date else "preparing", | |
| "optimize": "preparing", | |
| "observe": "preparing", | |
| "transfer": "waiting", | |
| "cancel": "cancelled", | |
| "completed": "done", | |
| } | |
| # Map urgency → priority | |
| priority_map = { | |
| "urgent": "high", | |
| "semi_urgent": "high", | |
| "elective": "normal", | |
| } | |
| # Extract string value from decision/urgency (works with enum or plain str) | |
| raw_decision = bloc.decision | |
| decision_val = raw_decision.value if isinstance(raw_decision, Enum) else str(raw_decision) | |
| raw_urgency = bloc.urgency | |
| urgency_val = raw_urgency.value if isinstance(raw_urgency, Enum) else str(raw_urgency) | |
| # Generate display ID | |
| now = datetime.utcnow() | |
| count_result = await session.execute( | |
| text("SELECT COUNT(*) FROM traker_cases WHERE tenant_id = :tid"), | |
| {"tid": str(tenant_id)}, | |
| ) | |
| count = count_result.scalar() or 0 | |
| display_id = f"TRK-{now.strftime('%Y%m%d')}-{count + 1:03d}" | |
| # Blocking reason from missing items (handle plain strings from import) | |
| blocking = None | |
| try: | |
| missing = [] | |
| bio = bloc.biology_status if isinstance(bloc.biology_status, str) else str(bloc.biology_status) | |
| img = bloc.imaging_status if isinstance(bloc.imaging_status, str) else str(bloc.imaging_status) | |
| anes = bloc.anesthesia_clearance if isinstance(bloc.anesthesia_clearance, str) else str(bloc.anesthesia_clearance) | |
| consent = bloc.consent_status if isinstance(bloc.consent_status, str) else str(bloc.consent_status) | |
| ok_values = ("ok", "not_applicable") | |
| if bio not in ok_values: | |
| missing.append(f"biology ({bio})") | |
| if img not in ok_values: | |
| missing.append(f"imaging ({img})") | |
| if anes not in ok_values: | |
| missing.append(f"anesthesia ({anes})") | |
| if consent not in ok_values: | |
| missing.append(f"consent ({consent})") | |
| if missing: | |
| blocking = "; ".join(missing[:3]) | |
| except Exception: | |
| pass | |
| trace_id = uuid4() | |
| state = state_map.get(decision_val, "preparing") | |
| priority = priority_map.get(urgency_val, "normal") | |
| planned_action = bloc.planned_procedure or f"{decision_val}: {bloc.diagnosis}" | |
| decision_date = str(bloc.scheduled_date) if bloc.scheduled_date else str(now.date()) | |
| action_date = str(bloc.scheduled_date) if bloc.scheduled_date else None | |
| # Check readiness without calling model methods (which expect enum types) | |
| ok_values = ("ok", "not_applicable") | |
| bio = bloc.biology_status if isinstance(bloc.biology_status, str) else str(bloc.biology_status) | |
| img = bloc.imaging_status if isinstance(bloc.imaging_status, str) else str(bloc.imaging_status) | |
| anes = bloc.anesthesia_clearance if isinstance(bloc.anesthesia_clearance, str) else str(bloc.anesthesia_clearance) | |
| consent_str = bloc.consent_status if isinstance(bloc.consent_status, str) else str(bloc.consent_status) | |
| prep_ready = 1 if all(v in ok_values for v in (bio, img, anes, consent_str)) else 0 | |
| await session.execute( | |
| text(""" | |
| INSERT INTO traker_cases ( | |
| id, display_id, tenant_id, subject_name, contact, | |
| problem, planned_action, priority, state, | |
| decision_date, action_date, | |
| preparation_ready, safety_check, | |
| blocking_reason, source_engine, source_ref, | |
| is_deleted, created_at, updated_at | |
| ) VALUES ( | |
| :id, :display_id, :tenant_id, :subject_name, :contact, | |
| :problem, :planned_action, :priority, :state, | |
| :decision_date, :action_date, | |
| :preparation_ready, :safety_check, | |
| :blocking_reason, :source_engine, :source_ref, | |
| :is_deleted, :created_at, :updated_at | |
| ) | |
| """), | |
| { | |
| "id": str(trace_id), | |
| "display_id": display_id, | |
| "tenant_id": str(tenant_id), | |
| "subject_name": bloc.patient_name, | |
| "contact": bloc.phone, | |
| "problem": bloc.diagnosis, | |
| "planned_action": planned_action[:500], | |
| "priority": priority, | |
| "state": state, | |
| "decision_date": decision_date, | |
| "action_date": action_date, | |
| "preparation_ready": prep_ready, | |
| "safety_check": 0, | |
| "blocking_reason": blocking, | |
| "source_engine": "surgio", | |
| "source_ref": str(bloc.id), | |
| "is_deleted": 0, | |
| "created_at": now.isoformat(), | |
| "updated_at": now.isoformat(), | |
| }, | |
| ) | |
| return trace_id | |
| except Exception as e: | |
| logger.warning("trace_creation_skipped", error=str(e), patient=bloc.patient_name) | |
| return None | |
| # ═══════════════════════════════════════════════════════════ | |
| # MAIN IMPORT | |
| # ═══════════════════════════════════════════════════════════ | |
| async def seed_programme( | |
| database_url: str, | |
| dry_run: bool = False, | |
| report_only: bool = False, | |
| ) -> Dict[str, Any]: | |
| """ | |
| Import programme chirurgical into database. | |
| Returns import report dict. | |
| """ | |
| from data.seeds.programs import PROGRAM_CASES, _IMPORT_META | |
| engine = create_async_engine(database_url, echo=False) | |
| async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) | |
| report = { | |
| "total_parsed": len(PROGRAM_CASES), | |
| "imported": 0, | |
| "skipped_duplicate": 0, | |
| "skipped_error": 0, | |
| "traces_created": 0, | |
| "columns_added": [], | |
| "by_group": {}, | |
| "by_category": {}, | |
| "by_decision": {}, | |
| "missing_phone": [], | |
| "missing_asa": [], | |
| "uncertain_diagnosis": [], | |
| "review_required": [], | |
| "errors": [], | |
| } | |
| async with async_session() as session: | |
| # Step 0: Discover tenant and user | |
| tenant_id, user_id = await discover_tenant(session) | |
| # Step 1: Ensure schema has all columns | |
| added_cols = await ensure_columns(session) | |
| report["columns_added"] = added_cols | |
| if report_only: | |
| # Just classify and report without inserting | |
| for case_data in PROGRAM_CASES: | |
| _classify_for_report(case_data, report) | |
| await engine.dispose() | |
| return report | |
| # Step 2: Import each case | |
| for idx, case_data in enumerate(PROGRAM_CASES): | |
| try: | |
| # Merge import metadata | |
| merged = {**_IMPORT_META, **case_data} | |
| patient_name = merged["patient_name"] | |
| program_category = merged.get("program_category") | |
| batch_id = merged.get("import_batch_id", BATCH_ID) | |
| # Classify for report | |
| _classify_for_report(merged, report) | |
| if dry_run: | |
| report["imported"] += 1 | |
| continue | |
| # Dedup check | |
| existing = await find_existing( | |
| session, tenant_id, patient_name, program_category, batch_id | |
| ) | |
| if existing: | |
| report["skipped_duplicate"] += 1 | |
| logger.info("case_skipped_duplicate", patient=patient_name) | |
| continue | |
| # Build BlocCase | |
| bloc = _build_bloc_case(merged, tenant_id, user_id) | |
| session.add(bloc) | |
| await session.flush() | |
| # Create Traces entry | |
| trace_id = await create_trace_for_bloc(session, tenant_id, bloc) | |
| if trace_id: | |
| report["traces_created"] += 1 | |
| report["imported"] += 1 | |
| logger.info( | |
| "case_imported", | |
| patient=patient_name, | |
| group=merged.get("operational_group"), | |
| decision=merged.get("decision"), | |
| ) | |
| except Exception as e: | |
| report["skipped_error"] += 1 | |
| report["errors"].append({"index": idx, "error": str(e)}) | |
| logger.error("case_import_error", index=idx, error=str(e)) | |
| if not dry_run: | |
| await session.commit() | |
| await engine.dispose() | |
| return report | |
| def _build_bloc_case(data: Dict[str, Any], tenant_id: UUID, user_id: UUID) -> BlocCase: | |
| """Build a BlocCase from merged case data dict.""" | |
| now = datetime.utcnow() | |
| # Handle date fields | |
| scheduled_date = data.get("scheduled_date") | |
| if isinstance(scheduled_date, str): | |
| try: | |
| scheduled_date = date.fromisoformat(scheduled_date) | |
| except ValueError: | |
| scheduled_date = None | |
| # Handle evidence: strip result_date strings → date objects | |
| evidence = [] | |
| for e in data.get("evidence", []): | |
| ev = dict(e) | |
| if "result_date" in ev and isinstance(ev["result_date"], str): | |
| ev["result_date"] = ev["result_date"] # Keep as string in JSON | |
| evidence.append(ev) | |
| return BlocCase( | |
| id=uuid4(), | |
| tenant_id=tenant_id, | |
| created_by=user_id, | |
| updated_by=user_id, | |
| created_at=now, | |
| updated_at=now, | |
| # Identity | |
| patient_name=data["patient_name"], | |
| phone=data.get("phone"), | |
| surgeon=data.get("surgeon"), | |
| site=data.get("site"), | |
| administrative_status=data.get("administrative_status", "free"), | |
| # Classification | |
| program_category=data.get("program_category"), | |
| procedure_type=data.get("procedure_type"), | |
| # Clinical | |
| diagnosis=data["diagnosis"], | |
| asa_score=data.get("asa_score"), | |
| urgency=data.get("urgency", "elective"), | |
| risk_level=data.get("risk_level", "low"), | |
| comorbidities=data.get("comorbidities", []), | |
| # Evidence | |
| evidence=evidence, | |
| certainty_level=data.get("certainty_level", "uncertain"), | |
| # Readiness | |
| biology_status=data.get("biology_status", "missing"), | |
| imaging_status=data.get("imaging_status", "missing"), | |
| anesthesia_clearance=data.get("anesthesia_clearance", "missing"), | |
| consent_status=data.get("consent_status", "missing"), | |
| optimization_status=data.get("optimization_status", "none"), | |
| # Decision | |
| decision=data.get("decision", "observe"), | |
| decision_reason=data.get("decision_reason"), | |
| decision_at=now, | |
| decision_by=user_id, | |
| # Surgical plan | |
| planned_procedure=data.get("planned_procedure"), | |
| technique=data.get("technique"), | |
| scheduled_date=scheduled_date, | |
| estimated_duration_min=data.get("estimated_duration_min"), | |
| # Logistics | |
| logistics_flag=data.get("logistics_flag", "none"), | |
| logistic_constraints=data.get("logistic_constraints"), | |
| postop_destination=data.get("postop_destination", "ward"), | |
| # Import tracking | |
| source_program=data.get("source_program"), | |
| raw_source_text=data.get("raw_source_text"), | |
| import_batch_id=data.get("import_batch_id", BATCH_ID), | |
| created_from_import=data.get("created_from_import", True), | |
| review_required=data.get("review_required", False), | |
| contact_status=data.get("contact_status"), | |
| next_action=data.get("next_action"), | |
| operational_group=data.get("operational_group"), | |
| ) | |
| def _classify_for_report(data: Dict[str, Any], report: Dict[str, Any]): | |
| """Classify a case for the import report.""" | |
| group = data.get("operational_group", "needs_review") | |
| category = data.get("program_category", "other") | |
| decision = data.get("decision", "observe") | |
| report["by_group"][group] = report["by_group"].get(group, 0) + 1 | |
| report["by_category"][category] = report["by_category"].get(category, 0) + 1 | |
| report["by_decision"][decision] = report["by_decision"].get(decision, 0) + 1 | |
| if not data.get("phone"): | |
| report["missing_phone"].append(data["patient_name"]) | |
| if not data.get("asa_score"): | |
| report["missing_asa"].append(data["patient_name"]) | |
| if data.get("certainty_level") == "uncertain": | |
| report["uncertain_diagnosis"].append(data["patient_name"]) | |
| if data.get("review_required"): | |
| report["review_required"].append(data["patient_name"]) | |
| def print_report(report: Dict[str, Any]): | |
| """Print a human-readable import report.""" | |
| print("\n" + "=" * 70) | |
| print(" PROGRAMME CHIRURGICAL — IMPORT REPORT") | |
| print("=" * 70) | |
| print(f"\n📊 IMPORT SUMMARY") | |
| print(f" Total cases parsed: {report['total_parsed']}") | |
| print(f" Successfully imported: {report['imported']}") | |
| print(f" Skipped (duplicate): {report['skipped_duplicate']}") | |
| print(f" Skipped (error): {report['skipped_error']}") | |
| print(f" Traces created: {report['traces_created']}") | |
| if report["columns_added"]: | |
| print(f"\n🔧 SCHEMA UPDATES") | |
| print(f" Columns added: {', '.join(report['columns_added'])}") | |
| print(f"\n📋 BY OPERATIONAL GROUP") | |
| for group, count in sorted(report["by_group"].items()): | |
| icon = { | |
| "ready_for_bloc": "✅", | |
| "optimize_before_bloc": "⚡", | |
| "awaiting_evidence": "🔍", | |
| "logistics_special": "🚛", | |
| "fast_track_minor": "⚡", | |
| "needs_review": "👁️", | |
| "external": "🔗", | |
| }.get(group, "📌") | |
| print(f" {icon} {group:.<30} {count}") | |
| print(f"\n📂 BY CATEGORY") | |
| for cat, count in sorted(report["by_category"].items()): | |
| print(f" {cat:.<30} {count}") | |
| print(f"\n🎯 BY DECISION") | |
| for dec, count in sorted(report["by_decision"].items()): | |
| print(f" {dec:.<30} {count}") | |
| print(f"\n⚠️ DATA QUALITY") | |
| print(f" Missing phone: {len(report['missing_phone'])}") | |
| if report["missing_phone"]: | |
| for name in report["missing_phone"]: | |
| print(f" → {name}") | |
| print(f" Missing ASA: {len(report['missing_asa'])}") | |
| if report["missing_asa"]: | |
| for name in report["missing_asa"]: | |
| print(f" → {name}") | |
| print(f" Uncertain diagnosis: {len(report['uncertain_diagnosis'])}") | |
| if report["uncertain_diagnosis"]: | |
| for name in report["uncertain_diagnosis"]: | |
| print(f" → {name}") | |
| print(f" Review required: {len(report['review_required'])}") | |
| if report["review_required"]: | |
| for name in report["review_required"]: | |
| print(f" → {name}") | |
| if report["errors"]: | |
| print(f"\n❌ ERRORS") | |
| for err in report["errors"]: | |
| print(f" Case #{err['index']}: {err['error']}") | |
| print("\n" + "=" * 70) | |
| # ═══════════════════════════════════════════════════════════ | |
| # CLI | |
| # ═══════════════════════════════════════════════════════════ | |
| if __name__ == "__main__": | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Seed programme chirurgical into database") | |
| parser.add_argument("--dry-run", action="store_true", help="Parse and validate without inserting") | |
| parser.add_argument("--report-only", action="store_true", help="Only generate classification report") | |
| parser.add_argument("--db-url", default=None, help="Database URL override") | |
| args = parser.parse_args() | |
| db_url = args.db_url or os.getenv( | |
| "DATABASE_URL", | |
| "sqlite+aiosqlite:///./data/databases/yaz_care.db", | |
| ) | |
| # Ensure aiosqlite for SQLite | |
| if db_url.startswith("sqlite://") and "aiosqlite" not in db_url: | |
| db_url = db_url.replace("sqlite://", "sqlite+aiosqlite://") | |
| report = asyncio.run( | |
| seed_programme( | |
| database_url=db_url, | |
| dry_run=args.dry_run, | |
| report_only=args.report_only, | |
| ) | |
| ) | |
| print_report(report) | |
| if args.dry_run: | |
| print("\n🔸 DRY RUN — no data was inserted. Run without --dry-run to import.") | |
| elif args.report_only: | |
| print("\n🔸 REPORT ONLY — no data was inserted.") | |
| else: | |
| print("\n✅ Programme imported successfully. Open SURGIO to start working on cases.") | |