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)
+7 -9
View File
@@ -11,7 +11,7 @@ Columns in the TSV:
pistasprocessed, minprocessed, maxprocessed, idestado
This module downloads all available seasons for the three target stations
and saves the combined data as CSVs in data/raw/.
and stores the combined raw history in SQLite.
"""
import io
@@ -22,11 +22,11 @@ from pathlib import Path
import pandas as pd
import requests
from storage import SQLiteStore
logger = logging.getLogger(__name__)
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
_RAW_DIR = _PROJECT_ROOT / "data" / "raw"
_BASE_URL = "https://www.infonieve.es/estacion-esqui.historico-nieve.tsv.php"
# Infonieve internal IDs for our stations
@@ -101,7 +101,7 @@ def download_season(
return df
def download_all_history() -> pd.DataFrame:
def download_all_history(store: SQLiteStore | None = None) -> pd.DataFrame:
"""Download all available historical data for all three stations.
Returns
@@ -145,11 +145,9 @@ def download_all_history() -> pd.DataFrame:
# Sort
combined = combined.sort_values(["station_id", "date"]).reset_index(drop=True)
# Save
_RAW_DIR.mkdir(parents=True, exist_ok=True)
output_path = _RAW_DIR / "station_historical_all.csv"
combined.to_csv(output_path, index=False)
logger.info("Historical data saved to %s: %d total rows.", output_path, len(combined))
effective_store = store if store is not None else SQLiteStore()
effective_store.save_historical_station_raw(combined)
logger.info("Historical data saved to SQLite: %d total rows.", len(combined))
# Summary
for sid in _STATION_IDS:
+1 -21
View File
@@ -10,12 +10,8 @@ managed by the government of Asturias/León:
Primary source: infonieve.es (https://www.infonieve.es/estacion-esqui/{slug}/)
Fallback: returns None values with a logged warning when scraping fails.
Raw responses are saved to:
data/raw/station_{station_id}_{date}.json
"""
import json
import logging
import re
from datetime import date
@@ -34,8 +30,6 @@ logger = logging.getLogger(__name__)
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
_CONFIG_PATH = _PROJECT_ROOT / "config" / "stations.yaml"
_RAW_DATA_DIR = _PROJECT_ROOT / "data" / "raw"
_USER_AGENT = (
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
@@ -94,19 +88,6 @@ def _get_session() -> requests.Session:
return session
def _save_raw(station_id: str, payload: dict) -> None:
"""Persist raw scraped payload to data/raw/ as JSON."""
_RAW_DATA_DIR.mkdir(parents=True, exist_ok=True)
today = date.today().isoformat()
filename = _RAW_DATA_DIR / f"station_{station_id}_{today}.json"
try:
with open(filename, "w", encoding="utf-8") as fh:
json.dump(payload, fh, ensure_ascii=False, indent=2)
logger.debug("Raw data saved to %s", filename)
except OSError as exc:
logger.warning("Could not save raw data for %s: %s", station_id, exc)
def _parse_float(text: Optional[str]) -> Optional[float]:
"""Extract the first float-like value from a string, or return None."""
if not text:
@@ -305,7 +286,6 @@ class StationScraper:
logger.info("Scraping station: %s", station_id)
record = self._scrape_infonieve(station_id)
_save_raw(station_id, record)
return record
def scrape_all_stations(self) -> list[dict]:
@@ -402,4 +382,4 @@ if __name__ == "__main__":
)
scraper = StationScraper()
records = scraper.scrape_all_stations()
print(json.dumps(records, indent=2, ensure_ascii=False))
print(records)
+1 -26
View File
@@ -1,7 +1,7 @@
"""Weather data collector using Open-Meteo API.
Fetches historical and forecast weather data for ski stations
defined in config/stations.yaml. No API key required.
defined in config/stations.yaml and persists snapshots in SQLite.
Historical endpoint: https://archive-api.open-meteo.com/v1/archive
Forecast endpoint: https://api.open-meteo.com/v1/forecast
@@ -24,8 +24,6 @@ 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"
HISTORICAL_URL = "https://archive-api.open-meteo.com/v1/archive"
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
@@ -65,7 +63,6 @@ class WeatherCollector:
def __init__(self, config_path: Path = CONFIG_PATH) -> None:
self.config_path = config_path
self.stations = self._load_stations()
RAW_DATA_DIR.mkdir(parents=True, exist_ok=True)
# ------------------------------------------------------------------
# Public API
@@ -126,8 +123,6 @@ class WeatherCollector:
raw = self._request(HISTORICAL_URL, params)
df = self._parse_response(raw, station_id)
self._save(df, station_id)
return df
def get_forecast(
@@ -169,8 +164,6 @@ class WeatherCollector:
raw = self._request(FORECAST_URL, params)
df = self._parse_response(raw, station_id)
self._save(df, station_id)
return df
def collect_all_stations(
@@ -338,21 +331,3 @@ class WeatherCollector:
# Keep only the expected column order
columns = ["date"] + DAILY_VARIABLES + ["station_id"]
return df[columns]
def _save(self, df: pd.DataFrame, station_id: str) -> None:
"""Persist a weather DataFrame to a CSV file.
Filename format: ``weather_{station_id}_{date}.csv``
where ``{date}`` is today's date (the collection date).
Parameters
----------
df:
DataFrame to save.
station_id:
Station identifier used in the filename.
"""
today = date.today().strftime("%Y-%m-%d")
filename = RAW_DATA_DIR / f"weather_{station_id}_{today}.csv"
df.to_csv(filename, index=False)
logger.info("Saved weather data to %s", filename)