Download src/apps/traces/intelligence/models.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 24.7 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/traces/intelligence/models.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/apps/traces/intelligence/models.py
-
curl -L -o models.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/traces/intelligence/models.py
24.7 kB
| """ | |
| Case Intelligence — Domain Models | |
| =================================== | |
| Relational models for the case reasoning + decision engine layer. | |
| Architecture: | |
| TrackerCase (parent) | |
| ├── CaseVariable — Typed inputs (measurable facts driving decisions) | |
| ├── CaseHypothesis — Proposed explanations or plans of action | |
| ├── CaseEvidence — Links variables → hypotheses with weight/direction | |
| ├── CaseProtocol — Generated action plans from reasoning chains | |
| └── CaseOutput — Final deliverables (articles, checklists, workflows) | |
| Design: | |
| - Every entity is tenant-isolated (tenant_id MANDATORY) | |
| - Every mutation is event-logged via CaseEvent | |
| - Variables are typed (numeric/categorical/boolean/text/composite) | |
| - Hypotheses follow a lifecycle: draft → testing → supported/refuted/inconclusive | |
| - Evidence quantifies how a variable supports or contradicts a hypothesis | |
| - Protocols are derived from the evidence pattern, not manually assembled | |
| - Outputs are generated artifacts (versioned, immutable once published) | |
| Standards: HIPAA audit trail, FDA 21 CFR Part 11 traceability | |
| Performance: Indexed on tenant_id + case_id for all entities | |
| """ | |
| from datetime import datetime, timezone | |
| from typing import Optional, List, Dict, Any | |
| from enum import Enum | |
| from uuid import UUID, uuid4 | |
| from sqlmodel import SQLModel, Field, Column, JSON | |
| # ============================================================================= | |
| # ENUMS | |
| # ============================================================================= | |
| class VariableType(str, Enum): | |
| """What kind of value does this variable hold?""" | |
| NUMERIC = "numeric" # Measurable quantity (e.g., SpO2 = 94%) | |
| CATEGORICAL = "categorical" # One of N options (e.g., ASA class = III) | |
| BOOLEAN = "boolean" # Yes/no (e.g., consent_signed = true) | |
| TEXT = "text" # Free-form observation | |
| TEMPORAL = "temporal" # Date/time value (e.g., symptom onset) | |
| COMPOSITE = "composite" # Structured sub-values (e.g., blood panel) | |
| class VariableSource(str, Enum): | |
| """Where did this variable value come from?""" | |
| MANUAL = "manual" # Entered by operator | |
| DEVICE = "device" # From monitoring device | |
| LAB = "lab" # From laboratory result | |
| IMAGING = "imaging" # From imaging study | |
| CALCULATED = "calculated" # Derived from other variables | |
| IMPORTED = "imported" # From external system | |
| AI_INFERRED = "ai_inferred" # Suggested by intelligence module | |
| class HypothesisStatus(str, Enum): | |
| """Where is this hypothesis in its lifecycle?""" | |
| DRAFT = "draft" # Proposed, not yet evaluated | |
| TESTING = "testing" # Actively gathering evidence | |
| SUPPORTED = "supported" # Evidence supports this hypothesis | |
| REFUTED = "refuted" # Evidence contradicts this hypothesis | |
| INCONCLUSIVE = "inconclusive" # Insufficient or conflicting evidence | |
| SUPERSEDED = "superseded" # Replaced by a newer hypothesis | |
| class EvidenceDirection(str, Enum): | |
| """Does this evidence support or contradict the hypothesis?""" | |
| SUPPORTS = "supports" | |
| CONTRADICTS = "contradicts" | |
| NEUTRAL = "neutral" | |
| CONDITIONAL = "conditional" # Supports under certain conditions | |
| class ProtocolStatus(str, Enum): | |
| """Lifecycle of a generated protocol.""" | |
| DRAFT = "draft" | |
| PROPOSED = "proposed" # Generated and awaiting review | |
| APPROVED = "approved" # Reviewed and accepted | |
| ACTIVE = "active" # Currently being executed | |
| COMPLETED = "completed" | |
| ABANDONED = "abandoned" | |
| class OutputType(str, Enum): | |
| """What kind of deliverable is this?""" | |
| ARTICLE = "article" # Written summary / case report | |
| CHECKLIST = "checklist" # Structured verification list | |
| WORKFLOW = "workflow" # Multi-step process definition | |
| REPORT = "report" # Analytical report with data | |
| DECISION_TREE = "decision_tree" | |
| PROTOCOL = "protocol" # Standalone protocol document | |
| class OutputStatus(str, Enum): | |
| DRAFT = "draft" | |
| REVIEW = "review" | |
| PUBLISHED = "published" | |
| ARCHIVED = "archived" | |
| # ============================================================================= | |
| # CASE VARIABLE — Typed inputs that drive decisions | |
| # ============================================================================= | |
| class CaseVariable(SQLModel, table=True): | |
| """ | |
| A measurable fact associated with a case. | |
| Variables are the raw inputs to the reasoning engine. | |
| Each variable has a type, value, source, confidence, and optional | |
| normal range for comparison. | |
| Examples: | |
| - SpO2 = 94% (numeric, device, confidence 0.99) | |
| - ASA class = III (categorical, manual, confidence 1.0) | |
| - Consent signed = true (boolean, manual, confidence 1.0) | |
| - Symptom onset = 2026-03-28T14:00 (temporal, manual) | |
| - Blood panel = {WBC: 12.4, Hgb: 11.2, ...} (composite, lab) | |
| """ | |
| __tablename__ = "traces_case_variables" | |
| __table_args__ = ({"extend_existing": True},) | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| case_id: UUID = Field(nullable=False, index=True) | |
| # Identity | |
| key: str = Field(max_length=100, nullable=False, description="Variable identifier (snake_case)") | |
| label: str = Field(max_length=200, nullable=False, description="Human-readable name") | |
| group: Optional[str] = Field(default=None, max_length=100, description="Grouping category (vitals, labs, history)") | |
| # Type and value | |
| var_type: VariableType = Field(nullable=False) | |
| value: str = Field(max_length=2000, nullable=False, description="Stored as string, interpreted by var_type") | |
| unit: Optional[str] = Field(default=None, max_length=50, description="Unit of measurement (%, mmHg, mg/dL)") | |
| # Structured value for composite types | |
| structured_value: Optional[Dict[str, Any]] = Field( | |
| default=None, sa_column=Column(JSON), | |
| description="For composite types: structured sub-values" | |
| ) | |
| # Range and validation | |
| normal_min: Optional[str] = Field(default=None, max_length=50, description="Lower bound of normal range") | |
| normal_max: Optional[str] = Field(default=None, max_length=50, description="Upper bound of normal range") | |
| options: List[str] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="For categorical: list of allowed values" | |
| ) | |
| # Provenance | |
| source: VariableSource = Field(default=VariableSource.MANUAL) | |
| source_detail: Optional[str] = Field(default=None, max_length=300, description="Source specifics (device name, lab ID)") | |
| confidence: float = Field(default=1.0, ge=0.0, le=1.0, description="Confidence in this value (0.0–1.0)") | |
| # Status | |
| is_abnormal: Optional[bool] = Field(default=None, description="True if outside normal range") | |
| is_critical: bool = Field(default=False, description="Flagged as clinically critical") | |
| superseded_by: Optional[UUID] = Field(default=None, description="If updated, points to the newer variable") | |
| # Timestamps | |
| recorded_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="When this value was observed/measured") | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True) | |
| created_by: Optional[str] = Field(default=None, max_length=100) | |
| # ============================================================================= | |
| # CASE HYPOTHESIS — Proposed explanations or plans | |
| # ============================================================================= | |
| class CaseHypothesis(SQLModel, table=True): | |
| """ | |
| A proposed explanation, diagnosis, or plan of action for a case. | |
| Hypotheses are not guesses — they are structured propositions that | |
| the operator evaluates against evidence. Multiple hypotheses can | |
| coexist; the evidence pattern determines which are supported. | |
| Lifecycle: draft → testing → supported | refuted | inconclusive | superseded | |
| Examples: | |
| - "Acute appendicitis" (diagnosis hypothesis) | |
| - "Laparoscopic approach preferred" (procedural hypothesis) | |
| - "Route A via N1 highway" (logistics hypothesis) | |
| - "Claim covered under policy §4.2" (insurance hypothesis) | |
| """ | |
| __tablename__ = "traces_case_hypotheses" | |
| __table_args__ = ({"extend_existing": True},) | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| case_id: UUID = Field(nullable=False, index=True) | |
| # Content | |
| title: str = Field(max_length=300, nullable=False, description="Hypothesis statement") | |
| rationale: Optional[str] = Field(default=None, max_length=2000, description="Why this hypothesis was proposed") | |
| category: Optional[str] = Field(default=None, max_length=100, description="Classification (diagnosis, procedure, plan)") | |
| # Status | |
| status: HypothesisStatus = Field(default=HypothesisStatus.DRAFT, index=True) | |
| confidence: float = Field(default=0.5, ge=0.0, le=1.0, description="Current confidence based on evidence") | |
| rank: int = Field(default=0, description="Display order / priority rank among hypotheses") | |
| # Resolution | |
| resolution_note: Optional[str] = Field(default=None, max_length=2000, description="Why it was supported/refuted") | |
| resolved_at: Optional[datetime] = Field(default=None) | |
| resolved_by: Optional[str] = Field(default=None, max_length=100) | |
| # Lineage | |
| parent_id: Optional[UUID] = Field(default=None, description="If derived from another hypothesis") | |
| superseded_by: Optional[UUID] = Field(default=None, description="If superseded, points to replacement") | |
| # Source | |
| source_intelligence: Optional[str] = Field(default=None, max_length=200, description="Intelligence module that suggested this") | |
| # Timestamps | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True) | |
| created_by: Optional[str] = Field(default=None, max_length=100) | |
| updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) | |
| # ============================================================================= | |
| # CASE EVIDENCE — Links variables to hypotheses | |
| # ============================================================================= | |
| class CaseEvidence(SQLModel, table=True): | |
| """ | |
| A link between a variable and a hypothesis, quantifying how the | |
| variable supports or contradicts the hypothesis. | |
| The evidence chain is the reasoning backbone: | |
| Variable (fact) → Evidence (interpretation) → Hypothesis (conclusion) | |
| Evidence has direction (supports/contradicts/neutral/conditional) | |
| and weight (how strongly it affects the hypothesis). | |
| Examples: | |
| - WBC = 15,000 → supports "Acute appendicitis" (weight 0.7) | |
| - CT: no appendicolith → contradicts "Perforated appendicitis" (weight 0.5) | |
| - Temperature = 38.8°C → supports "Acute appendicitis" (weight 0.6) | |
| """ | |
| __tablename__ = "traces_case_evidence" | |
| __table_args__ = ({"extend_existing": True},) | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| case_id: UUID = Field(nullable=False, index=True) | |
| variable_id: UUID = Field(nullable=False, index=True) | |
| hypothesis_id: UUID = Field(nullable=False, index=True) | |
| # Interpretation | |
| direction: EvidenceDirection = Field(nullable=False, description="Does this support or contradict?") | |
| weight: float = Field(default=0.5, ge=0.0, le=1.0, description="Strength of this evidence link") | |
| reasoning: Optional[str] = Field(default=None, max_length=1000, description="Why this variable matters for this hypothesis") | |
| condition: Optional[str] = Field(default=None, max_length=500, description="For conditional: under what circumstances") | |
| # Source | |
| assessed_by: Optional[str] = Field(default=None, max_length=100, description="Who made this assessment") | |
| source_intelligence: Optional[str] = Field(default=None, max_length=200, description="Intelligence module that suggested this link") | |
| # Timestamps | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True) | |
| # ============================================================================= | |
| # CASE PROTOCOL — Generated action plans | |
| # ============================================================================= | |
| class CaseProtocol(SQLModel, table=True): | |
| """ | |
| A structured action plan generated from the case's evidence pattern. | |
| Protocols are not templates — they are derived from the specific | |
| variables, hypotheses, and evidence of THIS case. They adapt to | |
| the case's unique context. | |
| A protocol has ordered steps, each with conditions, actions, | |
| and verification criteria. | |
| """ | |
| __tablename__ = "traces_case_protocols" | |
| __table_args__ = ({"extend_existing": True},) | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| case_id: UUID = Field(nullable=False, index=True) | |
| # Content | |
| title: str = Field(max_length=300, nullable=False) | |
| summary: Optional[str] = Field(default=None, max_length=2000) | |
| category: Optional[str] = Field(default=None, max_length=100, description="Protocol category (surgical, clinical, logistics)") | |
| # Status | |
| status: ProtocolStatus = Field(default=ProtocolStatus.DRAFT, index=True) | |
| version: int = Field(default=1) | |
| # Steps (ordered) | |
| steps: List[Dict[str, Any]] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="Ordered steps: [{order, title, action, condition, verification, status, completed_at, completed_by}]" | |
| ) | |
| # Derivation chain | |
| derived_from_hypotheses: List[str] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="Hypothesis IDs this protocol addresses" | |
| ) | |
| derived_from_evidence: List[str] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="Key evidence IDs that shaped this protocol" | |
| ) | |
| source_intelligence: Optional[str] = Field( | |
| default=None, max_length=200, | |
| description="Intelligence module that generated this protocol" | |
| ) | |
| # Compliance | |
| compliance_refs: List[str] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="Standards references (WHO-SSC-2.0, ASA, ERAS)" | |
| ) | |
| # Execution tracking | |
| steps_total: int = Field(default=0) | |
| steps_completed: int = Field(default=0) | |
| started_at: Optional[datetime] = Field(default=None) | |
| completed_at: Optional[datetime] = Field(default=None) | |
| # Timestamps | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True) | |
| created_by: Optional[str] = Field(default=None, max_length=100) | |
| updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) | |
| approved_by: Optional[str] = Field(default=None, max_length=100) | |
| approved_at: Optional[datetime] = Field(default=None) | |
| # ============================================================================= | |
| # CASE OUTPUT — Generated deliverables | |
| # ============================================================================= | |
| class CaseOutput(SQLModel, table=True): | |
| """ | |
| A final deliverable generated from the case's reasoning chain. | |
| Outputs are versioned artifacts: articles, checklists, workflows, | |
| reports, or decision trees. Once published, they are immutable. | |
| The generation chain: | |
| Variables → Evidence → Hypotheses → Protocol → Output | |
| """ | |
| __tablename__ = "traces_case_outputs" | |
| __table_args__ = ({"extend_existing": True},) | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| case_id: UUID = Field(nullable=False, index=True) | |
| # Content | |
| title: str = Field(max_length=300, nullable=False) | |
| output_type: OutputType = Field(nullable=False, index=True) | |
| status: OutputStatus = Field(default=OutputStatus.DRAFT, index=True) | |
| version: int = Field(default=1) | |
| # Body (type-dependent structure) | |
| content: Dict[str, Any] = Field( | |
| default_factory=dict, sa_column=Column(JSON), | |
| description="Output content — structure depends on output_type" | |
| ) | |
| # For articles: {body: str, sections: [{title, content}]} | |
| # For checklists: {items: [{text, checked, required}]} | |
| # For workflows: {steps: [{id, title, action, next_step_id, condition}]} | |
| # For reports: {sections: [{title, data, charts}]} | |
| # For decision_trees: {nodes: [{id, question, yes_next, no_next}]} | |
| # Derivation | |
| derived_from_protocol: Optional[UUID] = Field(default=None, description="Protocol that generated this output") | |
| derived_from_hypotheses: List[str] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| ) | |
| # Timestamps | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True) | |
| created_by: Optional[str] = Field(default=None, max_length=100) | |
| published_at: Optional[datetime] = Field(default=None) | |
| published_by: Optional[str] = Field(default=None, max_length=100) | |
| # ============================================================================= | |
| # ENUMS — Decision Options | |
| # ============================================================================= | |
| class OptionStatus(str, Enum): | |
| """Where is this option in the evaluation lifecycle?""" | |
| PROPOSED = "proposed" # Option identified, not yet evaluated | |
| EVALUATING = "evaluating" # Actively comparing against criteria | |
| SELECTED = "selected" # Chosen as the preferred option | |
| REJECTED = "rejected" # Eliminated from consideration | |
| DEFERRED = "deferred" # Valid but postponed | |
| class ResourceType(str, Enum): | |
| """What kind of resource is being allocated?""" | |
| PERSON = "person" # Surgeon, nurse, assistant, driver | |
| EQUIPMENT = "equipment" # Device, instrument, vehicle | |
| ROOM = "room" # OR, clinic room, warehouse | |
| TIME_SLOT = "time_slot" # Scheduled time block | |
| CONSUMABLE = "consumable" # Single-use item | |
| SERVICE = "service" # External service (lab, imaging) | |
| class ResourceStatus(str, Enum): | |
| """Resource allocation lifecycle.""" | |
| REQUESTED = "requested" | |
| CONFIRMED = "confirmed" | |
| IN_USE = "in_use" | |
| RELEASED = "released" | |
| CANCELLED = "cancelled" | |
| # ============================================================================= | |
| # DECISION OPTION — Structured alternative for comparison | |
| # ============================================================================= | |
| class DecisionOption(SQLModel, table=True): | |
| """ | |
| A structured decision alternative for a case. | |
| Options are the core of the decision engine. Each represents a concrete | |
| course of action that can be compared against criteria, scored, and | |
| justified with evidence. The comparison matrix enables systematic | |
| decision-making across any domain. | |
| Flow: Hypotheses → Options → Comparison → Selection → Protocol → Execution | |
| """ | |
| __tablename__ = "traces_decision_options" | |
| __table_args__ = ({"extend_existing": True},) | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| case_id: UUID = Field(nullable=False, index=True) | |
| # Content | |
| title: str = Field(max_length=300, nullable=False, description="Short label for this option") | |
| description: Optional[str] = Field(default=None, max_length=2000, description="Detailed description of what this option entails") | |
| category: Optional[str] = Field(default=None, max_length=100, description="Grouping category (surgical, pharmacological, conservative, etc.)") | |
| # Status | |
| status: OptionStatus = Field(default=OptionStatus.PROPOSED, index=True) | |
| rank: int = Field(default=0, description="Manual or computed ranking (lower = better)") | |
| # Decision criteria scores (0.0 to 1.0) | |
| criteria_scores: Dict[str, Any] = Field( | |
| default_factory=dict, sa_column=Column(JSON), | |
| description="Scores per criterion: {criterion_key: {score: float, weight: float, notes: str}}" | |
| ) | |
| composite_score: Optional[float] = Field(default=None, description="Weighted composite score (computed)") | |
| # Cost/Time/Risk estimates | |
| estimated_cost: Optional[float] = Field(default=None, description="Estimated cost in local currency") | |
| estimated_duration_hours: Optional[float] = Field(default=None, description="Estimated duration in hours") | |
| estimated_risk_level: Optional[float] = Field(default=None, ge=0.0, le=1.0, description="Risk score 0-1") | |
| # Resources needed | |
| resources_required: List[Dict[str, Any]] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="Resources required: [{type, name, quantity, critical}]" | |
| ) | |
| # Evidence & justification | |
| supporting_evidence: List[str] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="Evidence IDs that support this option" | |
| ) | |
| contraindications: List[str] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="Known contraindications or risks" | |
| ) | |
| references: List[str] = Field( | |
| default_factory=list, sa_column=Column(JSON), | |
| description="Literature / guideline references (WHO, NICE, etc.)" | |
| ) | |
| # Outcome prediction | |
| predicted_outcome: Optional[str] = Field(default=None, max_length=1000) | |
| success_probability: Optional[float] = Field(default=None, ge=0.0, le=1.0) | |
| # Selection | |
| selected_by: Optional[str] = Field(default=None, max_length=100) | |
| selected_at: Optional[datetime] = Field(default=None) | |
| selection_rationale: Optional[str] = Field(default=None, max_length=2000) | |
| # Derivation | |
| derived_from_hypothesis: Optional[UUID] = Field(default=None, description="Hypothesis that generated this option") | |
| # Timestamps | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True) | |
| created_by: Optional[str] = Field(default=None, max_length=100) | |
| updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) | |
| # ============================================================================= | |
| # RESOURCE SLOT — Allocated resource for case execution | |
| # ============================================================================= | |
| class ResourceSlot(SQLModel, table=True): | |
| """ | |
| A resource allocated to a case for execution. | |
| Resources are people, equipment, rooms, time slots, or services. | |
| Each slot tracks the full lifecycle: requested → confirmed → in use → released. | |
| """ | |
| __tablename__ = "traces_resource_slots" | |
| __table_args__ = ({"extend_existing": True},) | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| case_id: UUID = Field(nullable=False, index=True) | |
| # What | |
| resource_type: ResourceType = Field(nullable=False, index=True) | |
| name: str = Field(max_length=300, nullable=False, description="Resource name (Dr. Smith, OR-3, Laparoscope)") | |
| role: Optional[str] = Field(default=None, max_length=100, description="Role in the case (lead_surgeon, first_assist, scrub_nurse)") | |
| quantity: int = Field(default=1, ge=1) | |
| # When | |
| scheduled_start: Optional[datetime] = Field(default=None, description="When this resource is needed") | |
| scheduled_end: Optional[datetime] = Field(default=None, description="When this resource is released") | |
| actual_start: Optional[datetime] = Field(default=None) | |
| actual_end: Optional[datetime] = Field(default=None) | |
| # Status | |
| status: ResourceStatus = Field(default=ResourceStatus.REQUESTED, index=True) | |
| # Linked option — which decision option requires this resource | |
| option_id: Optional[UUID] = Field(default=None, index=True, description="Decision option this resource is allocated for") | |
| # Notes | |
| notes: Optional[str] = Field(default=None, max_length=500) | |
| confirmed_by: Optional[str] = Field(default=None, max_length=100) | |
| confirmed_at: Optional[datetime] = Field(default=None) | |
| # Timestamps | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True) | |
| created_by: Optional[str] = Field(default=None, max_length=100) | |