"""Centralised settings — read from environment, with .env fallback.""" from __future__ import annotations import os from dataclasses import dataclass, field from pathlib import Path from typing import Tuple # Load .env + optional profile overlay (no python-dotenv hard dep). # # Precedence (highest priority wins): # 1. Shell / Docker -e / HF Space "Variables & Secrets" UI # 2. Profile file (``.env.``) # 3. ``.env`` base config # 4. Hard-coded defaults in app/config.py # # To guarantee #1 beats everything, snapshot ``os.environ`` BEFORE any # file load — keys already set there are then skipped by both passes. # # Profile activation: # - Set ``CAKRA_PROFILE=`` (in shell, .env, or platform UI) to # load ``.env.`` after .env. # - HF Spaces deploys auto-apply ``hfspace`` via the SPACE_ID detection # block below, so a Space needs zero extra config. # # Built-in profiles shipped in this repo: # • .env.hfspace — Hugging Face Spaces free CPU tier # • .env.vps — self-managed VPS (no GPU, 4-8 vCPU) # # Profile files only carry RESOURCE TUNING (inference size, fps target, # pool size). Keep DATABASE_URL etc. in .env or platform secret UI. _REPO_ROOT = Path(__file__).resolve().parents[1] # Snapshot of env that was set externally (shell, docker -e, HF UI). # Anything in this set is treated as load-bearing user intent — file # overlays never overwrite it. NOTE: must be captured before any file # load below. _PRELOAD_ENV: set[str] = set(os.environ.keys()) def _load_env_file(path: Path, override: bool) -> None: """Load ``.env``-style key=value file. ``override=True`` lets the file overwrite values that came from previously-loaded files, but NEVER overwrite values that were present in the environment before any file was loaded (shell / UI overrides always win).""" if not path.exists(): return for line in path.read_text().splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue k, v = line.split("=", 1) k = k.strip() v = v.strip() if k in _PRELOAD_ENV: continue if override: os.environ[k] = v else: os.environ.setdefault(k, v) _load_env_file(_REPO_ROOT / ".env", override=False) _profile = os.environ.get("CAKRA_PROFILE", "").strip() if _profile: _load_env_file(_REPO_ROOT / f".env.{_profile}", override=True) # Hugging Face Spaces automatically sets ``SPACE_ID``; presence means we are # running on shared CPU hardware that is 4-5× slower than a typical M2/Xeon. # Apply tuned defaults so the demo stays responsive: smaller inference, lower # encoder output, single concurrent stream. Each value is only injected when # the operator has NOT already set it (via Space "Variables & Secrets") — so # explicit overrides still win. _IS_HF_SPACE = bool(os.environ.get("SPACE_ID")) if _IS_HF_SPACE: _HF_DEFAULTS = { "INFERENCE_SIZE": "640", "TARGET_INFER_FPS": "3", "FRAME_SKIP": "2", "OUTPUT_WIDTH": "854", "OUTPUT_HEIGHT": "480", # HF basic CPU can not run more than one inference pipeline at a # time without collapse; reject the second stream cleanly with 503. "MAX_STREAMS": "1", } for k, v in _HF_DEFAULTS.items(): os.environ.setdefault(k, v) def _get(key: str, default, cast=str): raw = os.getenv(key) if raw is None or raw == "": return default if cast is bool: return str(raw).lower() in ("1", "true", "yes", "y", "on") try: return cast(raw) except Exception: return default @dataclass(frozen=True) class Settings: # --- server host: str = field(default_factory=lambda: _get("HOST", "0.0.0.0")) port: int = field(default_factory=lambda: _get("PORT", 8000, int)) log_level: str = field(default_factory=lambda: _get("LOG_LEVEL", "INFO")) api_prefix: str = "/api/v1" # --- streams (loaded from Postgres `cctv_streams` table) streams_status_filter: str = field( default_factory=lambda: _get("STREAMS_STATUS_FILTER", "online") ) max_streams: int = field(default_factory=lambda: _get("MAX_STREAMS", 50, int)) reconnect_delay: float = field(default_factory=lambda: _get("RECONNECT_DELAY", 5.0, float)) # --- database database_url: str = field(default_factory=lambda: _get("DATABASE_URL", "")) # --- model # Default points at the YOLO-World model the Dockerfile bakes # (17 Indonesian-traffic classes). Override with MODEL_PATH to # use stock YOLOv8 (./models/yolov8n.pt etc.) or any other YOLO # checkpoint without code changes. model_path: str = field(default_factory=lambda: _get("MODEL_PATH", "./models/yolo-world-id.pt")) # Low threshold catches small/distant objects that matter for # CCTV recall (motorcycles in a queue, becak at intersection # edges). Raise to 0.20-0.30 if you need fewer low-confidence # boxes / less label clutter. conf_threshold: float = field(default_factory=lambda: _get("CONF_THRESHOLD", 0.05, float)) iou_threshold: float = field(default_factory=lambda: _get("IOU_THRESHOLD", 0.5, float)) # 960 keeps small far-object recall solid; drop to 640 if you're # CPU-bound (Hugging Face CPU spaces, etc.) and would rather have # faster inference than every distant motorcycle. inference_size: int = field(default_factory=lambda: _get("INFERENCE_SIZE", 960, int)) use_half: bool = field(default_factory=lambda: _get("USE_HALF", True, bool)) # --- processing & streaming frame_skip: int = field(default_factory=lambda: _get("FRAME_SKIP", 1, int)) # Hard cap on inference rate per camera. The decoupled pipeline # means the encoder stays at HLS_FPS regardless of this number; # 8 fps is enough for surveillance (bbox refresh every 125 ms) # and keeps GPU/CPU available for other cameras. target_infer_fps: float = field( default_factory=lambda: _get("TARGET_INFER_FPS", 8.0, float) ) output_width: int = field(default_factory=lambda: _get("OUTPUT_WIDTH", 1280, int)) output_height: int = field(default_factory=lambda: _get("OUTPUT_HEIGHT", 720, int)) stale_frame_seconds: float = field( default_factory=lambda: _get("STALE_FRAME_SECONDS", 2.0, float) ) # --- analytics — WS push cadence (no history table any more) metrics_ws_interval: float = field( default_factory=lambda: _get("METRICS_WS_INTERVAL", 0.1, float) ) # --- scan mode (alerting) — parallel low-fps sessions per CCTV # triggered via right-click in the FE map. No HLS encoder, just # capture → infer → rule engine → alert fire. Multiple sessions # per camera allowed (each carries its own rule set). # # Headroom: 1 fps × 12 sessions = ~12 inference calls/sec total, # which combined with at most 4 preview sessions @ 8 fps still fits # under a 4-core EPYC's yolov8m ONNX budget once the detector lock # serialises calls. max_scan_streams: int = field( default_factory=lambda: _get("MAX_SCAN_STREAMS", 12, int) ) scan_target_fps: float = field( default_factory=lambda: _get("SCAN_TARGET_FPS", 1.0, float) ) scan_ring_buffer_seconds: float = field( default_factory=lambda: _get("SCAN_RING_BUFFER_SECONDS", 30.0, float) ) # Scan ring buffer / clip resolution. 640×360 at 1 fps × 30 s ≈ # 21 MB per session; 12 sessions ≈ 252 MB. 720p would 4× that — fine # on a 32 GB VPS but not on HF Spaces, hence the lower default. scan_output_width: int = field( default_factory=lambda: _get("SCAN_OUTPUT_WIDTH", 640, int) ) scan_output_height: int = field( default_factory=lambda: _get("SCAN_OUTPUT_HEIGHT", 360, int) ) # Where alert JPEG snapshots + MP4 clips land on disk. On the VPS # this is mounted as a Docker volume (deploy.yml) so the artifacts # survive container recreate. On local dev it defaults to a folder # next to the repo so it Just Works without root. alerts_dir: str = field( default_factory=lambda: _get("ALERTS_DIR", "./data/alerts", str) ) # --- Scan rule presets # Right-click "Mulai scan" sends an empty body; FastAPI fills the # default rule set from PRESETS. Operator tuning lives in env so # threshold changes don't need a redeploy. Per-city recommendations: # * Threshold = minimum object count to register as "congested/crowded" # * Sustained seconds = how long threshold must hold before firing # (filters momentary spikes) # * Cooldown seconds = pause between fires for the same rule # within ONE session (anti-spam single-session) # # `traffic_jam` rule = preset key "kemacetan" (vehicle sustained_count). # `crowd` rule = preset key "keramaian" (person sustained_count). scan_traffic_jam_threshold: int = field( default_factory=lambda: _get("SCAN_TRAFFIC_JAM_THRESHOLD", 50, int) ) scan_traffic_jam_sustained_seconds: float = field( default_factory=lambda: _get("SCAN_TRAFFIC_JAM_SUSTAINED_SECONDS", 60.0, float) ) scan_traffic_jam_cooldown_seconds: float = field( default_factory=lambda: _get("SCAN_TRAFFIC_JAM_COOLDOWN_SECONDS", 300.0, float) ) scan_crowd_threshold: int = field( default_factory=lambda: _get("SCAN_CROWD_THRESHOLD", 50, int) ) scan_crowd_sustained_seconds: float = field( default_factory=lambda: _get("SCAN_CROWD_SUSTAINED_SECONDS", 30.0, float) ) scan_crowd_cooldown_seconds: float = field( default_factory=lambda: _get("SCAN_CROWD_COOLDOWN_SECONDS", 120.0, float) ) # --- Geo projection (per detection lat/lng for map overlay) # The cctv_streams table only carries (lat, lng) — no heading, FOV, # or mounting metadata. We assume defaults below; override per-cam # later by adding columns + reading them in app/services/geo.py. geo_default_heading_deg: float = field( default_factory=lambda: _get("GEO_DEFAULT_HEADING_DEG", 0.0, float) ) geo_fov_deg: float = field( default_factory=lambda: _get("GEO_FOV_DEG", 70.0, float) ) geo_max_distance_m: float = field( default_factory=lambda: _get("GEO_MAX_DISTANCE_M", 90.0, float) ) # Camera mounting model for pinhole projection. Defaults represent # a typical street-level CCTV mast: 4 m high, tilted 15° below # horizontal, vertical FOV ~40°. geo_camera_height_m: float = field( default_factory=lambda: _get("GEO_CAMERA_HEIGHT_M", 4.0, float) ) geo_camera_tilt_deg: float = field( default_factory=lambda: _get("GEO_CAMERA_TILT_DEG", 15.0, float) ) geo_v_fov_deg: float = field( default_factory=lambda: _get("GEO_V_FOV_DEG", 40.0, float) ) # --- HUD mask # Many Semarang CCTV streams burn a watermark / agency banner into # the top-left and bottom strips of the frame. YOLO regularly picks # those up as "car" or "truck" at 70-80% confidence. Mask them out # before inference so they don't pollute detections + event log. hud_mask_top_pct: float = field( default_factory=lambda: _get("HUD_MASK_TOP_PCT", 0.06, float) ) hud_mask_bottom_pct: float = field( default_factory=lambda: _get("HUD_MASK_BOTTOM_PCT", 0.05, float) ) # --- HLS server-side encoder # We spawn one ffmpeg per active camera, fed by the render thread's # annotated BGR frames, to produce a self-contained HLS stream with # bboxes baked into the pixels. Segments live in HLS_OUTPUT_DIR / # {camera_id}/ and are cleaned up when the worker stops. hls_output_dir: str = field( default_factory=lambda: _get("HLS_OUTPUT_DIR", "/tmp/cakra-hls", str) ) hls_segment_seconds: float = field( default_factory=lambda: _get("HLS_SEGMENT_SECONDS", 2.0, float) ) hls_playlist_size: int = field( default_factory=lambda: _get("HLS_PLAYLIST_SIZE", 6, int) ) # Match the typical CCTV native rate (25 fps PAL). hls_fps: int = field(default_factory=lambda: _get("HLS_FPS", 25, int)) # H.264 quality. libx264 CRF — lower = sharper + bigger files. # 22 ≈ ffmpeg default with a hair more sharpness; 18 = ~lossless. hls_crf: int = field(default_factory=lambda: _get("HLS_CRF", 22, int)) # libx264 speed preset. faster = lower CPU, larger files at the same # CRF. "veryfast" + CRF 20 is a good live-encode balance. hls_preset: str = field( default_factory=lambda: _get("HLS_PRESET", "veryfast", str) ) # Video encoder. "libx264" = software (universal, CPU heavy). # "videotoolbox" = macOS hardware encoder (h264_videotoolbox), # ~5× lower CPU. "nvenc" = NVIDIA hardware. Auto-fallback to # libx264 if the requested encoder isn't available at runtime, # so the default "videotoolbox" works locally on Mac and falls # back transparently on Linux deploys (Hugging Face, etc.). hls_encoder: str = field( default_factory=lambda: _get("HLS_ENCODER", "videotoolbox", str) ) # --- detection class name filters # Comma-separated names. At boot, Detector reads the loaded model's # `names` dict and maps each class id to a category based on these. # Add aliases for whatever names a Roboflow / custom model uses — # e.g. "motorbike", "scooter", "becak", "bemo", "ojek". vehicle_class_names: str = field( default_factory=lambda: _get( "VEHICLE_CLASS_NAMES", "car,motorcycle,motorbike,bus,truck,scooter,bemo,bajaj,becak,vehicle,pickup,van", str, ) ) person_class_names: str = field( default_factory=lambda: _get( "PERSON_CLASS_NAMES", "person,pedestrian,people,human,rider,cyclist", str, ) ) # --- thresholds (per product spec) traffic_smooth_max: int = 10 traffic_moderate_max: int = 25 crowd_normal_max: int = 10 crowd_busy_max: int = 30 settings = Settings()