mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 23:36:17 +00:00
feat(storage): migrate project to sqlite
This commit is contained in:
1 parent
1bc1e58781
commit
9c8ba03574
17 files changed
+1204
-688
No files matched your search
@@ -6,12 +6,11 @@ Tests cover:
|
||||
- analyze_image() with a mocked YOLO model.
|
||||
- estimate_crowd_level() with mocked WebcamCollector and YOLO.
|
||||
- analyze_all_stations() integration across all three stations.
|
||||
- JSON persistence of results.
|
||||
- SQLite persistence of results.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -95,10 +94,11 @@ def _make_analyzer(tmp_path: Path) -> "CrowdAnalyzer":
|
||||
return_value=_STATIONS_CONFIG["stations"],
|
||||
):
|
||||
from data_sources.crowd_analyzer import CrowdAnalyzer
|
||||
from storage import SQLiteStore
|
||||
|
||||
analyzer = CrowdAnalyzer(
|
||||
config_path=tmp_path / "stations.yaml",
|
||||
output_dir=tmp_path,
|
||||
store=SQLiteStore(tmp_path / "skipredictor.db"),
|
||||
)
|
||||
return analyzer
|
||||
|
||||
@@ -146,20 +146,21 @@ class TestInstantiation:
|
||||
# The model must remain un-loaded (lazy) after construction.
|
||||
assert analyzer._model is None
|
||||
|
||||
def test_output_dir_is_created(self, tmp_path):
|
||||
"""The output directory must exist after initialisation."""
|
||||
out_dir = tmp_path / "outputs" / "raw"
|
||||
def test_store_is_initialized(self, tmp_path):
|
||||
"""The analyzer must initialise a writable SQLite store."""
|
||||
with patch(
|
||||
"data_sources.crowd_analyzer.CrowdAnalyzer._load_stations",
|
||||
return_value=_STATIONS_CONFIG["stations"],
|
||||
):
|
||||
from data_sources.crowd_analyzer import CrowdAnalyzer
|
||||
from storage import SQLiteStore
|
||||
|
||||
CrowdAnalyzer(
|
||||
analyzer = CrowdAnalyzer(
|
||||
config_path=tmp_path / "stations.yaml",
|
||||
output_dir=out_dir,
|
||||
store=SQLiteStore(tmp_path / "skipredictor.db"),
|
||||
)
|
||||
assert out_dir.is_dir()
|
||||
assert analyzer.store.db_path == tmp_path / "skipredictor.db"
|
||||
assert analyzer.store.db_path.exists()
|
||||
|
||||
def test_stations_are_loaded(self, tmp_path):
|
||||
"""All three stations must be present in self.stations after init."""
|
||||
@@ -403,39 +404,38 @@ class TestEstimateCrowdLevel:
|
||||
result = self._run_with_mocks(tmp_path, "pajares", [], [], [])
|
||||
assert result["crowd_density"] == "unknown"
|
||||
|
||||
def test_result_is_saved_to_json(self, tmp_path):
|
||||
"""A JSON file must be written to output_dir after analysis."""
|
||||
def test_result_is_saved_to_sqlite(self, tmp_path):
|
||||
"""A crowd-analysis row must be written to SQLite after analysis."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
self._run_with_mocks(tmp_path, "pajares", [img], ["person"] * 3, [0.9] * 3)
|
||||
from datetime import date
|
||||
from storage import SQLiteStore
|
||||
|
||||
today = date.today().strftime("%Y-%m-%d")
|
||||
json_file = tmp_path / f"crowd_pajares_{today}.json"
|
||||
assert json_file.exists()
|
||||
store = SQLiteStore(tmp_path / "skipredictor.db")
|
||||
rows = store.load_crowd_analyses(station_id="pajares")
|
||||
assert len(rows) == 1
|
||||
|
||||
def test_json_contains_valid_list(self, tmp_path):
|
||||
"""The saved JSON file must contain a list with at least one result."""
|
||||
def test_sqlite_contains_saved_row(self, tmp_path):
|
||||
"""The saved SQLite row must retain the analysis payload."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
self._run_with_mocks(tmp_path, "pajares", [img], ["car"], [0.85])
|
||||
from datetime import date
|
||||
from storage import SQLiteStore
|
||||
|
||||
today = date.today().strftime("%Y-%m-%d")
|
||||
json_file = tmp_path / f"crowd_pajares_{today}.json"
|
||||
data = json.loads(json_file.read_text())
|
||||
assert isinstance(data, list)
|
||||
assert len(data) >= 1
|
||||
store = SQLiteStore(tmp_path / "skipredictor.db")
|
||||
rows = store.load_crowd_analyses(station_id="pajares")
|
||||
assert len(rows) == 1
|
||||
assert rows.iloc[0]["crowd_density"] == "low"
|
||||
assert rows.iloc[0]["confidence_scores"] == [0.85]
|
||||
|
||||
def test_multiple_calls_append_to_json(self, tmp_path):
|
||||
"""Successive calls must append results to the same JSON file."""
|
||||
def test_multiple_calls_append_to_sqlite(self, tmp_path):
|
||||
"""Successive calls must append results to SQLite."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
self._run_with_mocks(tmp_path, "sanisidro", [img], ["car"], [0.9])
|
||||
self._run_with_mocks(tmp_path, "sanisidro", [img], ["person"], [0.8])
|
||||
from datetime import date
|
||||
from storage import SQLiteStore
|
||||
|
||||
today = date.today().strftime("%Y-%m-%d")
|
||||
json_file = tmp_path / f"crowd_sanisidro_{today}.json"
|
||||
data = json.loads(json_file.read_text())
|
||||
assert len(data) == 2
|
||||
store = SQLiteStore(tmp_path / "skipredictor.db")
|
||||
rows = store.load_crowd_analyses(station_id="sanisidro")
|
||||
assert len(rows) == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Unit tests for the SQLite-backed persistence layer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from storage import SQLiteStore
|
||||
|
||||
|
||||
def test_prediction_run_roundtrip(tmp_path):
|
||||
"""Prediction payloads must round-trip through SQLite unchanged."""
|
||||
store = SQLiteStore(tmp_path / "skipredictor.db")
|
||||
payload = {
|
||||
"generated_at": "2026-03-13T10:00:00+00:00",
|
||||
"prediction_date": "2026-03-14",
|
||||
"stations": {
|
||||
"pajares": {
|
||||
"station_name": "Valgrande-Pajares",
|
||||
"open_probability": 0.82,
|
||||
"km_open": 12.4,
|
||||
"crowd_level": "medium",
|
||||
"weather_summary": "Temp -2-5 C",
|
||||
"rule_overrides": ["Wind below threshold."],
|
||||
"prediction_source": "ml",
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
store.save_prediction_run(payload)
|
||||
|
||||
loaded = store.load_latest_predictions()
|
||||
assert loaded == payload
|
||||
|
||||
|
||||
def test_feature_importances_replace_latest_values(tmp_path):
|
||||
"""Saving importances twice for the same target must replace older rows."""
|
||||
store = SQLiteStore(tmp_path / "skipredictor.db")
|
||||
|
||||
store.save_feature_importances(
|
||||
target="station_open",
|
||||
importances={"snow_depth": 0.9, "wind_gusts_10m_max": 0.5},
|
||||
)
|
||||
store.save_feature_importances(
|
||||
target="station_open",
|
||||
importances={"snow_depth": 0.2, "temperature_2m_mean": 0.8},
|
||||
)
|
||||
|
||||
assert store.load_feature_importances("station_open") == [
|
||||
("temperature_2m_mean", 0.8),
|
||||
("snow_depth", 0.2),
|
||||
]
|
||||
|
||||
|
||||
def test_evaluation_run_roundtrip(tmp_path):
|
||||
"""Evaluation reports must be persisted and reloaded from SQLite."""
|
||||
store = SQLiteStore(tmp_path / "skipredictor.db")
|
||||
report = {
|
||||
"station_open": {"accuracy": 0.91},
|
||||
"km_open": {"mae": 1.2},
|
||||
}
|
||||
|
||||
run_id = store.save_evaluation_run(
|
||||
dataset_table="historical_featured_dataset",
|
||||
report=report,
|
||||
models_dir="ml/models",
|
||||
)
|
||||
|
||||
loaded = store.load_latest_evaluation_run()
|
||||
assert loaded is not None
|
||||
assert loaded["id"] == run_id
|
||||
assert loaded["dataset_table"] == "historical_featured_dataset"
|
||||
assert loaded["report"] == report
|
||||
assert loaded["models_dir"] == "ml/models"
|
||||
|
||||
|
||||
def test_crowd_analysis_roundtrip(tmp_path):
|
||||
"""Crowd analysis rows must be queryable with parsed confidence scores."""
|
||||
store = SQLiteStore(tmp_path / "skipredictor.db")
|
||||
store.save_crowd_analysis(
|
||||
{
|
||||
"timestamp": "2026-03-13T11:00:00",
|
||||
"station_id": "sanisidro",
|
||||
"image_path": "/tmp/frame.jpg",
|
||||
"cars_detected": 5,
|
||||
"people_detected": 2,
|
||||
"buses_detected": 0,
|
||||
"total_vehicles": 5,
|
||||
"crowd_density": "low",
|
||||
"confidence_scores": [0.91, 0.88],
|
||||
}
|
||||
)
|
||||
store.save_crowd_analysis(
|
||||
{
|
||||
"timestamp": "2026-03-13T12:00:00",
|
||||
"station_id": "sanisidro",
|
||||
"image_path": "/tmp/frame2.jpg",
|
||||
"cars_detected": 25,
|
||||
"people_detected": 4,
|
||||
"buses_detected": 1,
|
||||
"total_vehicles": 26,
|
||||
"crowd_density": "medium",
|
||||
"confidence_scores": [0.77],
|
||||
}
|
||||
)
|
||||
|
||||
rows = store.load_crowd_analyses(
|
||||
station_id="sanisidro",
|
||||
analysis_date="2026-03-13",
|
||||
)
|
||||
|
||||
assert len(rows) == 2
|
||||
assert rows.iloc[0]["confidence_scores"] == [0.91, 0.88]
|
||||
assert rows.iloc[1]["crowd_density"] == "medium"
|
||||
Reference in new issue
Block a user