"""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 html import logging import re import time from datetime import date, datetime, timedelta from pathlib import Path from urllib.parse import quote 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}" _HISTORICO_AJAX_URL = "https://www.infonieve.es/webcams/historico.php?id={cam_id}&anyo={anyo}&mes={mes}&dia={dia}&hora=&base={base}" _HISTORICO_SHOWIMG_URL = ( "https://www.infonieve.es/webcams/historico.php?" "id={cam_id}&showimg=1&anyo={anyo}&mes={mes}&dia={dia}&hora={hour}&base={base}" ) _USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" _VALID_DENSITIES = {"low", "medium", "high"} _WEBCAM_JPG_PATTERN = re.compile( r"https?://www\.infonieve\.es/(?:webcams|files/historico)/[^\s\"'<>]+\.jpg(?:\?[^\s\"'<>]*)?" r"|/(?:webcams|files/historico)/[^\s\"'<>]+\.jpg(?:\?[^\s\"'<>]*)?" r"|(?:webcams|files/historico)/[^\s\"'<>]+\.jpg(?:\?[^\s\"'<>]*)?", flags=re.IGNORECASE, ) 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) # Cache for discovered date ranges per station self._available_ranges: dict[str, tuple[date, date]] = {} @staticmethod def _extract_webcam_jpg_url(raw_html: str) -> str | None: """Extract the first webcam JPG URL from a HTML fragment/page.""" if not raw_html: return None # Some responses escape slashes as \/ and HTML entities. normalized_html = raw_html.replace("\\/", "/") normalized_html = html.unescape(normalized_html) match = _WEBCAM_JPG_PATTERN.search(normalized_html) if not match: return None url = match.group(0) if url.startswith("http://") or url.startswith("https://"): return url if url.startswith("/"): return f"https://www.infonieve.es{url}" if url.startswith("//"): return f"https:{url}" if url.startswith("./"): return f"https://www.infonieve.es/{url[2:]}" if url.startswith("webcams/") or url.startswith("files/"): return f"https://www.infonieve.es/{url}" return url @staticmethod def _looks_like_html(content: bytes) -> bool: """Heuristic check to avoid saving HTML pages as .jpg files.""" head = content[:256].lstrip().lower() return head.startswith(b" str | None: """Resolve the actual historical webcam JPG URL for a station-day.""" cfg = HISTORICAL_CONFIG[station_id] base_path = quote(f"estacion-esqui/{cfg['slug']}/historico-webcams/") showimg_url = _HISTORICO_SHOWIMG_URL.format( cam_id=cfg["cam_id"], anyo=day.year, mes=day.month, dia=day.day, hour=PEAK_HOUR, base=base_path, ) resp = self.session.get(showimg_url, timeout=20) if resp.status_code == 404: return None resp.raise_for_status() image_url = self._extract_webcam_jpg_url(resp.text) if image_url is None: logger.warning( "No webcam JPG URL found in showimg response for %s on %s", station_id, day.isoformat(), ) return image_url def _download_image_bytes(self, image_url: str) -> bytes | None: """Download image bytes and reject HTML responses.""" resp = self.session.get(image_url, timeout=20) if resp.status_code == 404: return None resp.raise_for_status() content = resp.content if not content: return None content_type = (resp.headers.get("Content-Type") or "").lower() if "text/html" in content_type or self._looks_like_html(content): logger.warning("Resolved image URL returned HTML instead of image: %s", image_url) return None return content def get_available_date_range(self, station_id: str) -> tuple[date, date] | None: """Query Infonieve's AJAX endpoint to find the actual available date range for a station.""" if station_id in self._available_ranges: return self._available_ranges[station_id] cfg = HISTORICAL_CONFIG.get(station_id) if not cfg: return None logger.info("Discovering available historical range for %s...", station_id) try: base_path = quote(f"estacion-esqui/{cfg['slug']}/historico-webcams/") # 1. Find years url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo="", mes="", dia="", base=base_path) resp = self.session.get(url, timeout=15) resp.raise_for_status() years = sorted([int(y) for y in set(re.findall(r'rel="anyo-(\d{4})"', resp.text))]) if not years: logger.warning("No historical years found for %s", station_id) return None min_year, max_year = years[0], years[-1] # 2. Find min month/day url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=min_year, mes="", dia="", base=base_path) resp = self.session.get(url, timeout=15) months = sorted([int(m) for m in set(re.findall(r'rel="mes-(\d+)"', resp.text))]) min_month = months[0] if months else 1 url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=min_year, mes=f"{min_month:02d}", dia="", base=base_path) resp = self.session.get(url, timeout=15) days = sorted([int(d) for d in set(re.findall(r'reldia="(\d+)"', resp.text))]) min_day = days[0] if days else 1 start_date = date(min_year, min_month, min_day) # 3. Find max month/day url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=max_year, mes="", dia="", base=base_path) resp = self.session.get(url, timeout=15) months = sorted([int(m) for m in set(re.findall(r'rel="mes-(\d+)"', resp.text))]) max_month = months[-1] if months else 12 url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=max_year, mes=f"{max_month:02d}", dia="", base=base_path) resp = self.session.get(url, timeout=15) days = sorted([int(d) for d in set(re.findall(r'reldia="(\d+)"', resp.text))]) max_day = days[-1] if days else 28 end_date = date(max_year, max_month, max_day) logger.info("Range for %s: %s to %s", station_id, start_date, end_date) self._available_ranges[station_id] = (start_date, end_date) return start_date, end_date except Exception as exc: logger.error("Failed to discover range for %s: %s", station_id, exc) return None def process_range( self, start_date: date, end_date: date, station_ids: list[str] | None = None, *, retry_unknown: bool = False, ): """Process all stations for a given date range, respecting the discovered archive range.""" if station_ids is None: station_ids = list(HISTORICAL_CONFIG.keys()) for sid in station_ids: if sid not in HISTORICAL_CONFIG: continue # Discover available archive range archive_range = self.get_available_date_range(sid) actual_start = start_date actual_end = end_date if archive_range: start_limit, end_limit = archive_range actual_start = max(start_date, start_limit) actual_end = min(end_date, end_limit) if actual_start > actual_end: logger.info("Requested range for %s is outside available archive range (%s to %s)", sid, start_limit, end_limit) continue logger.info("Adjusted range for %s: %s to %s", sid, actual_start, actual_end) current = actual_start while current <= actual_end: # Skip if we already have analysis for this date/station if self._is_already_processed(sid, current, retry_unknown=retry_unknown): logger.debug("Skipping %s for %s (already processed)", sid, current) else: 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, *, retry_unknown: bool = False, ): """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, retry_unknown=retry_unknown) 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, *, retry_unknown: bool = False, ) -> list[date]: """Return dates that need crowd analysis for the given station.""" # 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. Discover available webcam archive range archive_range = self.get_available_date_range(station_id) if archive_range: start_limit, end_limit = archive_range station_dates = {d for d in station_dates if start_limit <= d <= end_limit} if not station_dates: logger.info("No station data dates fall within the discovered archive range for %s", station_id) return [] # 3. 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: if retry_unknown: crowd_df = crowd_df[crowd_df["crowd_density"].isin(_VALID_DENSITIES)] existing_dates = set( pd.to_datetime(crowd_df["analysis_date"], errors="coerce") .dt.date.dropna() ) # 4. Missing is the difference missing = sorted(list(station_dates - existing_dates)) return missing def _is_already_processed( self, station_id: str, day: date, *, retry_unknown: bool = False, ) -> 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 if retry_unknown: df = df[df["crowd_density"].isin(_VALID_DENSITIES)] processed_dates = set( pd.to_datetime(df["analysis_date"], errors="coerce").dt.date.dropna() ) return day in processed_dates 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") page_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, page_url) try: try: image_url = self._resolve_historical_image_url(station_id, day) except Exception as exc: logger.error( "Failed to resolve historical image URL for %s on %s: %s", station_id, date_str, exc, ) # Do not persist "unknown" on transient network/server errors. return if not image_url: logger.warning("No historical image URL for %s on %s", station_id, date_str) self._save_unknown_result(station_id, day) return try: image_bytes = self._download_image_bytes(image_url) except Exception as exc: logger.error( "Failed to download webcam image for %s on %s (%s): %s", station_id, date_str, image_url, exc, ) # Do not persist "unknown" on transient network/server errors. return if image_bytes is None: logger.warning( "Could not download a valid image for %s on %s from %s", station_id, date_str, image_url, ) self._save_unknown_result(station_id, day) return # Save temporary file img_path = self.temp_dir / f"{station_id}_{date_str}_{PEAK_HOUR}h.jpg" img_path.write_bytes(image_bytes) # 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") parser.add_argument( "--retry-unknown", action="store_true", help="Treat previously saved 'unknown' rows as pending and retry them.", ) 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 or (not args.start_date and not args.end_date): if not args.auto: logger.info( "No date range provided; defaulting to automatic sync mode." ) collector.auto_sync(stations, retry_unknown=args.retry_unknown) 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, retry_unknown=args.retry_unknown, ) else: parser.error("Use --auto or provide both --start-date and --end-date.") if __name__ == "__main__": main()