"""Batch-process historical webcam snapshots from infonieve.es. This script identifies missing crowd density data for historical dates, downloads the corresponding webcam snapshots from Infonieve's archive, runs YOLOv8 object detection via CrowdAnalyzer, and persists results. Usage: # Process a specific range python -m scripts.collect_historical_webcams --start-date 2025-02-01 --end-date 2025-03-10 # Process all missing dates for all stations (recommended) python -m scripts.collect_historical_webcams --auto """ import argparse import logging import time from datetime import date, datetime, timedelta from pathlib import Path import pandas as pd import requests from data_sources.crowd_analyzer import CrowdAnalyzer from storage import SQLiteStore, HISTORICAL_STATION_TABLE logger = logging.getLogger(__name__) # Configuration for historical cameras HISTORICAL_CONFIG = { "pajares": { "slug": "valgrande-pajares", "cam_id": 3197, }, "sanisidro": { "slug": "san-isidro", "cam_id": 305, }, "fuentes": { "slug": "fuentes-de-invierno", "cam_id": 1808, }, } # Preferred hour for crowd estimation (peak hour) PEAK_HOUR = 10 _BASE_URL = "https://www.infonieve.es/estacion-esqui/{slug}/historico-webcams/{cam_id}-{date_str}-{hour}" _USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" class HistoricalWebcamCollector: def __init__(self, store: SQLiteStore | None = None): self.store = store if store is not None else SQLiteStore() self.analyzer = CrowdAnalyzer(store=self.store) self.session = requests.Session() self.session.headers.update({"User-Agent": _USER_AGENT}) self.temp_dir = Path("data/raw/webcams/historical") self.temp_dir.mkdir(parents=True, exist_ok=True) def process_range(self, start_date: date, end_date: date, station_ids: list[str] | None = None): """Process all stations for a given date range.""" if station_ids is None: station_ids = list(HISTORICAL_CONFIG.keys()) current = start_date while current <= end_date: for sid in station_ids: if sid not in HISTORICAL_CONFIG: continue # Skip if we already have analysis for this date/station if self._is_already_processed(sid, current): logger.debug("Skipping %s for %s (already processed)", sid, current) continue self.process_day(sid, current) # Be polite to Infonieve time.sleep(1.0) current += timedelta(days=1) def auto_sync(self, station_ids: list[str] | None = None): """Find all dates in historical_station_raw that lack crowd analysis and fill them.""" if station_ids is None: station_ids = list(HISTORICAL_CONFIG.keys()) for sid in station_ids: missing_dates = self.get_missing_dates(sid) if not missing_dates: logger.info("No missing crowd dates for station=%s", sid) continue logger.info("Found %d missing dates for station=%s. Starting sync...", len(missing_dates), sid) for day in missing_dates: self.process_day(sid, day) # Be polite to Infonieve time.sleep(1.0) def get_missing_dates(self, station_id: str) -> list[date]: """Return a list of dates that have snow data but no crowd analysis.""" # 1. Get all dates with historical station data station_df = self.store.read_dataframe(HISTORICAL_STATION_TABLE, parse_dates=("date",)) if station_df.empty: logger.warning("No historical station data found for %s. Cannot auto-sync.", station_id) return [] station_dates = set(station_df[station_df["station_id"] == station_id]["date"].dt.date) # 2. Get dates that already have crowd analysis crowd_df = self.store.load_crowd_analyses(station_id=station_id) if crowd_df.empty: existing_dates = set() else: existing_dates = set(pd.to_datetime(crowd_df["timestamp"]).dt.date) # 3. Missing is the difference missing = sorted(list(station_dates - existing_dates)) return missing def _is_already_processed(self, station_id: str, day: date) -> bool: """Check if we have an entry in crowd_analysis for this exact date.""" df = self.store.load_crowd_analyses(station_id=station_id) if df.empty: return False # Convert timestamp strings to date objects df['date_only'] = pd.to_datetime(df['timestamp']).dt.date return day in df['date_only'].values def process_day(self, station_id: str, day: date): """Download and analyze a single snapshot for one day.""" cfg = HISTORICAL_CONFIG[station_id] date_str = day.strftime("%Y-%m-%d") url = _BASE_URL.format( slug=cfg["slug"], cam_id=cfg["cam_id"], date_str=date_str, hour=PEAK_HOUR ) logger.info("Processing %s for %s (URL: %s)", station_id, date_str, url) try: resp = self.session.get(url, timeout=20) if resp.status_code == 404: logger.warning("No historical image for %s on %s (404)", station_id, date_str) # Optionally save an "unknown" result to avoid re-polling forever self._save_unknown_result(station_id, day) return resp.raise_for_status() # Save temporary file img_path = self.temp_dir / f"{station_id}_{date_str}_{PEAK_HOUR}h.jpg" img_path.write_bytes(resp.content) # Analyze image analysis = self.analyzer.analyze_image(str(img_path)) # Adjust timestamp to represent the historical date, not "now" analysis["timestamp"] = datetime.combine(day, datetime.min.time().replace(hour=PEAK_HOUR)).isoformat() analysis["station_id"] = station_id analysis["image_path"] = str(img_path) # Save to DB self.analyzer._save_result(analysis) logger.info("Successfully analyzed and saved %s for %s: %s", station_id, date_str, analysis["crowd_density"]) except Exception as exc: logger.error("Failed to process %s for %s: %s", station_id, date_str, exc) def _save_unknown_result(self, station_id: str, day: date): """Save a placeholder result for dates with missing images to avoid re-processing.""" result = { "timestamp": datetime.combine(day, datetime.min.time().replace(hour=PEAK_HOUR)).isoformat(), "station_id": station_id, "image_path": None, "cars_detected": 0, "people_detected": 0, "buses_detected": 0, "total_vehicles": 0, "crowd_density": "unknown", "confidence_scores": [], } self.analyzer._save_result(result) def main(): parser = argparse.ArgumentParser(description="Collect historical webcam data") parser.add_argument("--start-date", type=str, help="YYYY-MM-DD") parser.add_argument("--end-date", type=str, help="YYYY-MM-DD") parser.add_argument("--stations", type=str, help="Comma-separated station IDs") parser.add_argument("--auto", action="store_true", help="Automatically find missing dates from historical_station_raw") args = parser.parse_args() logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s") collector = HistoricalWebcamCollector() stations = args.stations.split(",") if args.stations else None if args.auto: collector.auto_sync(stations) elif args.start_date and args.end_date: start_date = datetime.strptime(args.start_date, "%Y-%m-%d").date() end_date = datetime.strptime(args.end_date, "%Y-%m-%d").date() collector.process_range(start_date, end_date, stations) else: parser.print_help() if __name__ == "__main__": main()