Download src/core/tools/monitor/models.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 15.6 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/tools/monitor/models.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/tools/monitor/models.py
-
curl -L -o models.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/tools/monitor/models.py
15.6 kB
| """ | |
| Monitor Tool - Data Models | |
| ============================ | |
| Domain-agnostic models for continuous parameter surveillance and alerting. | |
| Follows the same reproducible pattern as Checklist and Journal tools. | |
| Entities: | |
| - MonitorDefinition: Reusable template defining what to watch and thresholds | |
| - MonitorInstance: Active monitor attached to a case / subject | |
| - MonitorReading: Individual data point submitted to a monitor | |
| - MonitorAlert: Triggered when thresholds are breached | |
| - MonitorEvent: Immutable audit trail of all changes | |
| Standards: FDA 21 CFR Part 11 (audit trail), HIPAA (tenant isolation) | |
| Performance: Indexed on tenant_id, case_id for <30ms evaluations | |
| """ | |
| from __future__ import annotations | |
| from datetime import datetime, timezone | |
| from enum import Enum | |
| from typing import Any, Dict, List, Optional | |
| from uuid import UUID, uuid4 | |
| from pydantic import BaseModel, ConfigDict, Field as PydanticField | |
| from sqlmodel import Column, Field, JSON, SQLModel | |
| # ============================================================================ | |
| # ENUMS - Shared vocabulary for all monitor implementations | |
| # ============================================================================ | |
| class MonitorStatus(str, Enum): | |
| """Monitor instance lifecycle states""" | |
| ACTIVE = "active" # Accepting readings, evaluating | |
| PAUSED = "paused" # Temporarily not evaluating | |
| STOPPED = "stopped" # Permanently stopped | |
| ALARMING = "alarming" # Active unacknowledged alert | |
| class MonitorType(str, Enum): | |
| """Types of monitors (domain-agnostic)""" | |
| THRESHOLD = "threshold" # Value crosses a single limit | |
| RANGE = "range" # Value outside min/max bounds | |
| TREND = "trend" # Rate of change exceeds limit | |
| COMPOSITE = "composite" # Multiple parameters combined | |
| HEARTBEAT = "heartbeat" # Signal expected but missing | |
| class AlertSeverity(str, Enum): | |
| """Alert severity levels""" | |
| INFO = "info" # Informational, no action needed | |
| WARNING = "warning" # Attention needed, not urgent | |
| CRITICAL = "critical" # Immediate action required | |
| EMERGENCY = "emergency" # Life-threatening, escalate now | |
| class AlertStatus(str, Enum): | |
| """Alert lifecycle states""" | |
| TRIGGERED = "triggered" # Newly fired, unacknowledged | |
| ACKNOWLEDGED = "acknowledged" # Seen by a user | |
| RESOLVED = "resolved" # Condition cleared | |
| ESCALATED = "escalated" # Sent to higher authority | |
| SUPPRESSED = "suppressed" # Manually muted | |
| class EventType(str, Enum): | |
| """Audit event types for State Bus""" | |
| MONITOR_STARTED = "monitor.started" | |
| MONITOR_PAUSED = "monitor.paused" | |
| MONITOR_RESUMED = "monitor.resumed" | |
| MONITOR_STOPPED = "monitor.stopped" | |
| READING_RECORDED = "monitor.reading_recorded" | |
| ALERT_TRIGGERED = "monitor.alert_triggered" | |
| ALERT_ACKNOWLEDGED = "monitor.alert_acknowledged" | |
| ALERT_RESOLVED = "monitor.alert_resolved" | |
| ALERT_ESCALATED = "monitor.alert_escalated" | |
| # ============================================================================ | |
| # VALUE OBJECTS - Threshold configuration | |
| # ============================================================================ | |
| class ThresholdDef(BaseModel): | |
| """ | |
| Threshold definition for a single parameter. | |
| Stored as JSON in MonitorDefinition.parameters. | |
| Domain-agnostic: works for vital signs, lab values, inventory levels, etc. | |
| """ | |
| key: str = PydanticField(..., description="Unique parameter key e.g. 'heart_rate'") | |
| label: str = PydanticField(..., description="Display label e.g. 'Heart Rate'") | |
| unit: str = PydanticField(default="", description="Unit of measurement e.g. 'bpm'") | |
| monitor_type: MonitorType = PydanticField(default=MonitorType.RANGE, description="Evaluation type") | |
| # Range thresholds | |
| critical_low: Optional[float] = PydanticField(default=None, description="Below = CRITICAL") | |
| warning_low: Optional[float] = PydanticField(default=None, description="Below = WARNING") | |
| warning_high: Optional[float] = PydanticField(default=None, description="Above = WARNING") | |
| critical_high: Optional[float] = PydanticField(default=None, description="Above = CRITICAL") | |
| # Trend threshold (rate of change per hour) | |
| max_rate_of_change: Optional[float] = PydanticField(default=None, description="Max change per hour") | |
| # Heartbeat | |
| expected_interval_sec: Optional[int] = PydanticField(default=None, description="Max seconds between readings") | |
| # Display | |
| order: int = PydanticField(default=0, description="Display order") | |
| decimal_places: int = PydanticField(default=1, description="Display precision") | |
| help_text: Optional[str] = PydanticField(default=None, description="Clinical guidance") | |
| model_config = ConfigDict(frozen=True) | |
| # ============================================================================ | |
| # DATABASE MODELS - Persisted entities | |
| # ============================================================================ | |
| class MonitorDefinition(SQLModel, table=True): | |
| """ | |
| Reusable monitor template defining what parameters to watch. | |
| Examples: | |
| - "Surgical Vitals" (HR, BP, SpO2, Temp, EtCO2) | |
| - "NEWS2 Parameters" (RR, SpO2, BP, HR, Temp, Consciousness) | |
| - "Lab QC - Glucose" (Westgard QC rules) | |
| - "Warehouse Temperature" (cold chain monitoring) | |
| Standards: Schema-driven configuration (Commandment #1) | |
| Security: Tenant-scoped, versioned | |
| """ | |
| __tablename__ = "monitor_definitions" | |
| __table_args__ = {"schema": "monitor"} | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| # Identity | |
| key: str = Field(max_length=100, index=True, description="Slug e.g. 'surgical_vitals'") | |
| title: str = Field(max_length=200, nullable=False) | |
| description: Optional[str] = Field(default=None, max_length=1000) | |
| version: str = Field(default="1.0.0", max_length=20) | |
| # Classification | |
| domain: str = Field(max_length=50, default="general", index=True) | |
| category: str = Field(max_length=50, default="surveillance") | |
| # Parameters (JSON array of ThresholdDef) | |
| parameters: List[Dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) | |
| # Evaluation config | |
| evaluation_interval_sec: int = Field(default=60, description="How often to evaluate (seconds)") | |
| auto_resolve_after_sec: Optional[int] = Field(default=None, description="Auto-resolve alert if condition clears") | |
| # State | |
| is_active: bool = Field(default=True) | |
| is_system: bool = Field(default=False, description="Platform-provided template") | |
| # Audit | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False) | |
| created_by: Optional[UUID] = Field(default=None) | |
| def get_parameters(self) -> List[ThresholdDef]: | |
| """Parse stored JSON into typed ThresholdDef objects""" | |
| return [ThresholdDef(**p) for p in (self.parameters or [])] | |
| def get_parameter(self, key: str) -> Optional[ThresholdDef]: | |
| """Get a specific parameter definition by key""" | |
| for p in self.get_parameters(): | |
| if p.key == key: | |
| return p | |
| return None | |
| class MonitorInstance(SQLModel, table=True): | |
| """ | |
| Active monitor attached to a case / subject. | |
| One instance per case per definition type | |
| (e.g., one "Surgical Vitals" monitor per surgery case). | |
| Performance: Indexed on (tenant_id, case_id) | |
| Security: Tenant-isolated | |
| """ | |
| __tablename__ = "monitor_instances" | |
| __table_args__ = {"schema": "monitor"} | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| # Links | |
| monitor_def_id: UUID = Field(nullable=False, index=True) | |
| case_id: Optional[UUID] = Field(default=None, index=True) | |
| case_type: Optional[str] = Field(default=None, max_length=50) | |
| subject_label: Optional[str] = Field(default=None, max_length=200, description="e.g. patient name or ID") | |
| # State | |
| status: MonitorStatus = Field(default=MonitorStatus.ACTIVE) | |
| title: str = Field(max_length=200, default="") | |
| reading_count: int = Field(default=0) | |
| alert_count: int = Field(default=0) | |
| context: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) | |
| # Latest values (denormalized for fast dashboard reads) | |
| latest_values: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) | |
| # Timing | |
| started_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) | |
| started_by: Optional[UUID] = Field(default=None) | |
| stopped_at: Optional[datetime] = Field(default=None) | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False) | |
| updated_at: Optional[datetime] = Field(default=None) | |
| class MonitorReading(SQLModel, table=True): | |
| """ | |
| Individual data point submitted to a monitor. | |
| Append-only: readings are never modified or deleted. | |
| Evaluated against thresholds to trigger alerts. | |
| Performance: <30ms evaluation target | |
| Security: Hash chain for integrity | |
| """ | |
| __tablename__ = "monitor_readings" | |
| __table_args__ = {"schema": "monitor"} | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| instance_id: UUID = Field(nullable=False, index=True) | |
| # Data | |
| parameter_key: str = Field(max_length=100, nullable=False) | |
| value: float = Field(nullable=False) | |
| unit: str = Field(default="", max_length=50) | |
| source: Optional[str] = Field(default=None, max_length=100, description="manual, device, hl7, etc.") | |
| # Context | |
| notes: Optional[str] = Field(default=None, max_length=500) | |
| recorded_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) | |
| recorded_by: Optional[UUID] = Field(default=None) | |
| # Evaluation result (set after threshold check) | |
| severity: Optional[AlertSeverity] = Field(default=None, description="null=normal, else=alert level") | |
| evaluation_hash: Optional[str] = Field(default=None, max_length=64) | |
| class MonitorAlert(SQLModel, table=True): | |
| """ | |
| Triggered when a reading breaches thresholds. | |
| Lifecycle: TRIGGERED → ACKNOWLEDGED → RESOLVED | |
| Alternative: TRIGGERED → ESCALATED → RESOLVED | |
| Or: TRIGGERED → SUPPRESSED | |
| Security: Immutable, audit-logged | |
| """ | |
| __tablename__ = "monitor_alerts" | |
| __table_args__ = {"schema": "monitor"} | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| instance_id: UUID = Field(nullable=False, index=True) | |
| reading_id: Optional[UUID] = Field(default=None) | |
| # Alert details | |
| parameter_key: str = Field(max_length=100, nullable=False) | |
| severity: AlertSeverity = Field(nullable=False) | |
| status: AlertStatus = Field(default=AlertStatus.TRIGGERED) | |
| message: str = Field(max_length=500, default="") | |
| value: float = Field(nullable=False, description="The value that triggered the alert") | |
| threshold: Optional[float] = Field(default=None, description="The threshold that was breached") | |
| rule: Optional[str] = Field(default=None, max_length=100, description="Which rule fired e.g. 'critical_high'") | |
| # Lifecycle | |
| triggered_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) | |
| acknowledged_at: Optional[datetime] = Field(default=None) | |
| acknowledged_by: Optional[UUID] = Field(default=None) | |
| resolved_at: Optional[datetime] = Field(default=None) | |
| resolved_by: Optional[UUID] = Field(default=None) | |
| resolution_note: Optional[str] = Field(default=None, max_length=500) | |
| class MonitorEvent(SQLModel, table=True): | |
| """ | |
| Immutable audit event for State Bus. | |
| Hash-chained for tamper detection. | |
| """ | |
| __tablename__ = "monitor_events" | |
| __table_args__ = {"schema": "monitor"} | |
| id: UUID = Field(default_factory=uuid4, primary_key=True) | |
| tenant_id: UUID = Field(nullable=False, index=True) | |
| instance_id: Optional[UUID] = Field(default=None, index=True) | |
| event_type: EventType = Field(nullable=False) | |
| payload: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) | |
| actor_id: Optional[UUID] = Field(default=None) | |
| occurred_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False) | |
| event_hash: Optional[str] = Field(default=None, max_length=64) | |
| prev_hash: Optional[str] = Field(default=None, max_length=64) | |
| # ============================================================================ | |
| # API SCHEMAS (Pydantic V2) | |
| # ============================================================================ | |
| class MonitorDefinitionResponse(BaseModel): | |
| """API response for monitor definitions""" | |
| id: UUID | |
| key: str | |
| title: str | |
| description: Optional[str] = None | |
| version: str | |
| domain: str | |
| category: str | |
| parameters: List[Dict[str, Any]] = [] | |
| evaluation_interval_sec: int = 60 | |
| is_active: bool = True | |
| created_at: datetime | |
| model_config = ConfigDict(from_attributes=True) | |
| class InstanceCreateRequest(BaseModel): | |
| """Request to create (start) a new monitor instance""" | |
| monitor_def_id: UUID | |
| case_id: Optional[UUID] = None | |
| case_type: Optional[str] = None | |
| subject_label: Optional[str] = None | |
| title: Optional[str] = None | |
| context: Dict[str, Any] = {} | |
| class InstanceResponse(BaseModel): | |
| """API response for a monitor instance""" | |
| id: UUID | |
| monitor_def_id: UUID | |
| case_id: Optional[UUID] = None | |
| case_type: Optional[str] = None | |
| subject_label: Optional[str] = None | |
| status: MonitorStatus | |
| title: str | |
| reading_count: int | |
| alert_count: int | |
| latest_values: Dict[str, Any] = {} | |
| started_at: datetime | |
| stopped_at: Optional[datetime] = None | |
| model_config = ConfigDict(from_attributes=True) | |
| class ReadingCreateRequest(BaseModel): | |
| """Request to submit a new reading""" | |
| parameter_key: str | |
| value: float | |
| unit: Optional[str] = None | |
| source: Optional[str] = "manual" | |
| notes: Optional[str] = None | |
| recorded_at: Optional[datetime] = None | |
| class ReadingResponse(BaseModel): | |
| """API response for a reading""" | |
| id: UUID | |
| instance_id: UUID | |
| parameter_key: str | |
| value: float | |
| unit: str | |
| source: Optional[str] = None | |
| severity: Optional[AlertSeverity] = None | |
| notes: Optional[str] = None | |
| recorded_at: datetime | |
| model_config = ConfigDict(from_attributes=True) | |
| class AlertResponse(BaseModel): | |
| """API response for an alert""" | |
| id: UUID | |
| instance_id: UUID | |
| parameter_key: str | |
| severity: AlertSeverity | |
| status: AlertStatus | |
| message: str | |
| value: float | |
| threshold: Optional[float] = None | |
| rule: Optional[str] = None | |
| triggered_at: datetime | |
| acknowledged_at: Optional[datetime] = None | |
| acknowledged_by: Optional[UUID] = None | |
| resolved_at: Optional[datetime] = None | |
| resolution_note: Optional[str] = None | |
| model_config = ConfigDict(from_attributes=True) | |
| class BulkReadingRequest(BaseModel): | |
| """Submit multiple readings at once (e.g., full vital signs set)""" | |
| readings: List[ReadingCreateRequest] | |
| class InstanceDetailResponse(BaseModel): | |
| """Full monitor detail with recent readings and active alerts""" | |
| instance: InstanceResponse | |
| definition: MonitorDefinitionResponse | |
| recent_readings: Dict[str, List[ReadingResponse]] = {} | |
| active_alerts: List[AlertResponse] = [] | |
| model_config = ConfigDict(from_attributes=True) | |