Download src/core/tools/analytics/models.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 7.02 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/tools/analytics/models.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/tools/analytics/models.py
-
curl -L -o models.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/tools/analytics/models.py
7.02 kB
| """ | |
| Analytics Tool - Domain Models | |
| ================================== | |
| Domain-agnostic analytics, metrics, and KPI tracking engine. | |
| Supports real-time dashboards, cohort analysis, funnel tracking, | |
| trend detection, and predictive analytics. | |
| Entities: | |
| AnalyticsDefinition - Reusable metric/KPI blueprint | |
| MetricSnapshot - Point-in-time metric capture | |
| Dashboard - Configurable widget layout | |
| AnalyticsEvent - Hash-chained audit trail | |
| Enums: | |
| MetricType, AggregationMethod, TimeGranularity, | |
| WidgetType, AnalyticsEventType | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| 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, Field | |
| # ============================================================================ | |
| # ENUMS | |
| # ============================================================================ | |
| class MetricType(str, Enum): | |
| COUNTER = "counter" | |
| GAUGE = "gauge" | |
| HISTOGRAM = "histogram" | |
| RATE = "rate" | |
| RATIO = "ratio" | |
| PERCENTILE = "percentile" | |
| TREND = "trend" | |
| COMPOSITE = "composite" | |
| class AggregationMethod(str, Enum): | |
| SUM = "sum" | |
| AVG = "avg" | |
| MIN = "min" | |
| MAX = "max" | |
| COUNT = "count" | |
| MEDIAN = "median" | |
| P95 = "p95" | |
| P99 = "p99" | |
| LAST = "last" | |
| RATE_PER_MINUTE = "rate_per_minute" | |
| class TimeGranularity(str, Enum): | |
| MINUTE = "minute" | |
| HOUR = "hour" | |
| DAY = "day" | |
| WEEK = "week" | |
| MONTH = "month" | |
| QUARTER = "quarter" | |
| YEAR = "year" | |
| class WidgetType(str, Enum): | |
| LINE_CHART = "line_chart" | |
| BAR_CHART = "bar_chart" | |
| PIE_CHART = "pie_chart" | |
| GAUGE = "gauge" | |
| STAT_CARD = "stat_card" | |
| TABLE = "table" | |
| HEATMAP = "heatmap" | |
| FUNNEL = "funnel" | |
| SCATTER = "scatter" | |
| SPARKLINE = "sparkline" | |
| class DashboardStatus(str, Enum): | |
| DRAFT = "draft" | |
| ACTIVE = "active" | |
| ARCHIVED = "archived" | |
| class AnalyticsEventType(str, Enum): | |
| DEFINITION_CREATED = "analytics.definition_created" | |
| METRIC_RECORDED = "analytics.metric_recorded" | |
| DASHBOARD_CREATED = "analytics.dashboard_created" | |
| DASHBOARD_UPDATED = "analytics.dashboard_updated" | |
| THRESHOLD_BREACHED = "analytics.threshold_breached" | |
| TREND_DETECTED = "analytics.trend_detected" | |
| COHORT_COMPUTED = "analytics.cohort_computed" | |
| EXPORT_GENERATED = "analytics.export_generated" | |
| # ============================================================================ | |
| # DOMAIN ENTITIES | |
| # ============================================================================ | |
| class AnalyticsDefinition: | |
| """Reusable metric/KPI definition blueprint.""" | |
| id: UUID = field(default_factory=uuid4) | |
| tenant_id: UUID = field(default_factory=uuid4) | |
| key: str = "" | |
| title: str = "" | |
| description: str = "" | |
| version: str = "1.0.0" | |
| domain: str = "" | |
| metric_type: MetricType = MetricType.GAUGE | |
| aggregation: AggregationMethod = AggregationMethod.AVG | |
| unit: str = "" | |
| data_source: str = "" | |
| query_template: str = "" | |
| thresholds: Dict[str, Any] = field(default_factory=dict) | |
| granularity: TimeGranularity = TimeGranularity.DAY | |
| retention_days: int = 365 | |
| is_active: bool = True | |
| is_system: bool = False | |
| metadata: Dict[str, Any] = field(default_factory=dict) | |
| created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) | |
| class MetricSnapshot: | |
| """Point-in-time metric value capture.""" | |
| id: UUID = field(default_factory=uuid4) | |
| tenant_id: UUID = field(default_factory=uuid4) | |
| definition_id: UUID = field(default_factory=uuid4) | |
| value: float = 0.0 | |
| dimensions: Dict[str, str] = field(default_factory=dict) | |
| timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) | |
| granularity: TimeGranularity = TimeGranularity.DAY | |
| metadata: Dict[str, Any] = field(default_factory=dict) | |
| class DashboardWidget: | |
| """Single widget within a dashboard.""" | |
| widget_id: str = "" | |
| title: str = "" | |
| widget_type: WidgetType = WidgetType.LINE_CHART | |
| definition_keys: List[str] = field(default_factory=list) | |
| position: Dict[str, int] = field(default_factory=lambda: {"x": 0, "y": 0, "w": 6, "h": 4}) | |
| config: Dict[str, Any] = field(default_factory=dict) | |
| class Dashboard: | |
| """Configurable analytics dashboard with widget grid layout.""" | |
| id: UUID = field(default_factory=uuid4) | |
| tenant_id: UUID = field(default_factory=uuid4) | |
| key: str = "" | |
| title: str = "" | |
| description: str = "" | |
| domain: str = "" | |
| widgets: List[DashboardWidget] = field(default_factory=list) | |
| refresh_interval_seconds: int = 60 | |
| status: DashboardStatus = DashboardStatus.ACTIVE | |
| is_system: bool = False | |
| created_by: UUID = field(default_factory=uuid4) | |
| created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) | |
| updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) | |
| class AnalyticsEvent: | |
| """Hash-chained analytics event for audit trail.""" | |
| id: UUID = field(default_factory=uuid4) | |
| tenant_id: UUID = field(default_factory=uuid4) | |
| event_type: AnalyticsEventType = AnalyticsEventType.METRIC_RECORDED | |
| data: Dict[str, Any] = field(default_factory=dict) | |
| prev_hash: str = "" | |
| hash: str = "" | |
| timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) | |
| # ============================================================================ | |
| # PYDANTIC SCHEMAS | |
| # ============================================================================ | |
| class MetricRecordRequest(BaseModel): | |
| definition_key: str = Field(..., min_length=1) | |
| value: float | |
| dimensions: Dict[str, str] = Field(default_factory=dict) | |
| timestamp: Optional[datetime] = None | |
| tenant_id: Optional[UUID] = None | |
| user_id: Optional[UUID] = None | |
| class DashboardCreateRequest(BaseModel): | |
| key: str = Field(..., min_length=1) | |
| title: str = Field(..., min_length=1) | |
| description: str = "" | |
| domain: str = "" | |
| widgets: List[Dict[str, Any]] = Field(default_factory=list) | |
| refresh_interval_seconds: int = 60 | |
| tenant_id: Optional[UUID] = None | |
| user_id: Optional[UUID] = None | |
| class AnalyticsDefinitionResponse(BaseModel): | |
| id: UUID | |
| key: str | |
| title: str | |
| description: str | |
| version: str | |
| domain: str | |
| metric_type: str | |
| aggregation: str | |
| unit: str | |
| data_source: str | |
| thresholds: Dict[str, Any] | |
| granularity: str | |
| is_active: bool | |
| is_system: bool | |
| class MetricSnapshotResponse(BaseModel): | |
| id: UUID | |
| definition_id: UUID | |
| value: float | |
| dimensions: Dict[str, str] | |
| timestamp: datetime | |
| granularity: str | |
| class DashboardResponse(BaseModel): | |
| id: UUID | |
| key: str | |
| title: str | |
| description: str | |
| domain: str | |
| widgets: List[Dict[str, Any]] | |
| refresh_interval_seconds: int | |
| status: str | |
| is_system: bool | |
| created_at: datetime | |