feat(storage): migrate project to sqlite

This commit is contained in:
dasemu committed 2026-03-13 06:50:18 +01:00
1 parent 1bc1e58781
commit 9c8ba03574
17 files changed
+1204 -688

No files matched your search

+18 -46
View File
@@ -10,8 +10,7 @@ Detected object counts are mapped to three crowd density levels:
* **medium** – 20–50 cars OR 10–30 people
* **high** – more than 50 cars OR more than 30 people
Analysis results are persisted as JSON files in ``data/raw/`` following the
naming pattern ``crowd_{station_id}_{date}.json``.
Analysis results are persisted in the project SQLite database.
Typical usage::
@@ -22,20 +21,19 @@ Typical usage::
from __future__ import annotations
import json
import logging
import warnings
from datetime import date, datetime
from datetime import datetime
from pathlib import Path
from typing import Any
import yaml
from storage import SQLiteStore
logger = logging.getLogger(__name__)
BASE_DIR = Path(__file__).resolve().parent.parent
CONFIG_PATH = BASE_DIR / "config" / "stations.yaml"
RAW_DATA_DIR = BASE_DIR / "data" / "raw"
# YOLO model weights file – downloaded automatically on first use.
YOLO_MODEL_WEIGHTS = "yolov8n.pt"
@@ -70,22 +68,20 @@ class CrowdAnalyzer:
model_weights:
YOLOv8 weights identifier passed to ``ultralytics.YOLO()``.
Defaults to ``"yolov8n.pt"`` (nano model).
output_dir:
Directory where JSON result files are written. Created if it does
not exist. Defaults to ``data/raw/``.
store:
SQLite store where analysis results are written.
"""
def __init__(
self,
config_path: Path = CONFIG_PATH,
model_weights: str = YOLO_MODEL_WEIGHTS,
output_dir: Path = RAW_DATA_DIR,
store: SQLiteStore | None = None,
) -> None:
self.config_path = config_path
self.model_weights = model_weights
self.output_dir = output_dir
self.store = store if store is not None else SQLiteStore()
self.stations = self._load_stations()
self.output_dir.mkdir(parents=True, exist_ok=True)
self._model: Any = None # Lazy-loaded on first inference call.
# ------------------------------------------------------------------
@@ -170,7 +166,7 @@ class CrowdAnalyzer:
"""Capture the latest webcam snapshot for *station_id* and analyse it.
Downloads one image via :class:`~data_sources.webcam_collector.WebcamCollector`,
runs object detection, saves the result as a JSON file and returns the
runs object detection, saves the result to SQLite, and returns the
analysis dict.
Parameters
@@ -199,7 +195,7 @@ class CrowdAnalyzer:
station_id,
)
result = self._empty_result(station_id, image_path=None)
self._save_result(result, station_id)
self._save_result(result)
return result
# Analyse only the first captured image to keep latency low.
@@ -215,12 +211,12 @@ class CrowdAnalyzer:
exc,
)
result = self._empty_result(station_id, image_path=image_path)
self._save_result(result, station_id)
self._save_result(result)
return result
analysis["station_id"] = station_id
analysis["image_path"] = image_path
self._save_result(analysis, station_id)
self._save_result(analysis)
return analysis
def analyze_all_stations(self) -> dict[str, dict[str, Any]]:
@@ -334,35 +330,11 @@ class CrowdAnalyzer:
"timestamp": datetime.now().isoformat(timespec="seconds"),
}
def _save_result(self, result: dict[str, Any], station_id: str) -> None:
"""Persist an analysis result dict as a JSON file.
Filename format: ``crowd_{station_id}_{date}.json``
Parameters
----------
result:
Analysis dict to serialise.
station_id:
Used to construct the output filename.
"""
today = date.today().strftime("%Y-%m-%d")
filename = self.output_dir / f"crowd_{station_id}_{today}.json"
# Append to an existing file (list of results) or create a new one.
if filename.exists():
try:
existing = json.loads(filename.read_text(encoding="utf-8"))
if not isinstance(existing, list):
existing = [existing]
except (json.JSONDecodeError, OSError):
existing = []
else:
existing = []
existing.append(result)
filename.write_text(
json.dumps(existing, indent=2, ensure_ascii=False),
encoding="utf-8",
def _save_result(self, result: dict[str, Any]) -> None:
"""Persist an analysis result dict to SQLite."""
row_id = self.store.save_crowd_analysis(result)
logger.info(
"Saved crowd analysis row %d for station=%s",
row_id,
result.get("station_id"),
)
logger.info("Saved crowd analysis to %s", filename)