diff --git a/LESSONS.md b/LESSONS.md index 3ca4ecd..76bed97 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -1,3 +1,17 @@ +## Webcam Historical Download Validation - 2026-03-13 + +**What went wrong:** Historical webcam downloads were saved directly from `historico-webcams/...` page URLs, which can return HTML wrappers instead of binary images. + +**Root cause:** The collector assumed the historical page URL always returned raw image bytes and did not validate payload type before running YOLO analysis. + +**Prevention rule:** In this repository, historical webcam ingestion must resolve the real image URL through `webcams/historico.php?showimg=1...` and reject HTML payloads before saving `.jpg` files. + +**Example:** In [collect_historical_webcams.py](/home/dasemu/Hacking/DarĂ­o Sevilla/skipredictor/scripts/collect_historical_webcams.py), `process_day()` now uses `_resolve_historical_image_url()` and `_download_image_bytes()`; HTML payloads are discarded and the day is stored as `unknown`. + +**Files affected:** `scripts/collect_historical_webcams.py`, `tests/test_collect_historical_webcams.py` + +--- + ## Deployment Assumptions - 2026-03-12 **What went wrong:** I assumed the Telegram bot running on the server might differ from the repository after seeing a schema mismatch between the bot code and the predictions JSON. diff --git a/scripts/collect_historical_webcams.py b/scripts/collect_historical_webcams.py index e0ae68b..14c984f 100644 --- a/scripts/collect_historical_webcams.py +++ b/scripts/collect_historical_webcams.py @@ -13,6 +13,7 @@ Usage: """ import argparse +import html import logging import re import time @@ -48,7 +49,18 @@ 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: @@ -64,6 +76,81 @@ class HistoricalWebcamCollector: # 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: @@ -124,7 +211,14 @@ class HistoricalWebcamCollector: 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): + 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()) @@ -153,7 +247,7 @@ class HistoricalWebcamCollector: current = actual_start while current <= actual_end: # Skip if we already have analysis for this date/station - if self._is_already_processed(sid, current): + 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) @@ -162,13 +256,18 @@ class HistoricalWebcamCollector: current += timedelta(days=1) - def auto_sync(self, station_ids: list[str] | None = None): + 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) + 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 @@ -180,8 +279,13 @@ class HistoricalWebcamCollector: # 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, filtered by available archive range.""" + 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: @@ -204,6 +308,8 @@ class HistoricalWebcamCollector: 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() @@ -213,12 +319,21 @@ class HistoricalWebcamCollector: missing = sorted(list(station_dates - existing_dates)) return missing - def _is_already_processed(self, station_id: str, day: date) -> bool: + 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() ) @@ -228,27 +343,59 @@ class HistoricalWebcamCollector: """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( + 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, url) + logger.info("Processing %s for %s (URL: %s)", station_id, date_str, page_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 + 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 - 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) + img_path.write_bytes(image_bytes) # Analyze image analysis = self.analyzer.analyze_image(str(img_path)) @@ -288,6 +435,11 @@ def main(): 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() @@ -301,11 +453,16 @@ def main(): logger.info( "No date range provided; defaulting to automatic sync mode." ) - collector.auto_sync(stations) + 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) + 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.") diff --git a/tests/test_collect_historical_webcams.py b/tests/test_collect_historical_webcams.py index 4746dec..6ebdf5f 100644 --- a/tests/test_collect_historical_webcams.py +++ b/tests/test_collect_historical_webcams.py @@ -3,6 +3,7 @@ from __future__ import annotations from datetime import date +from pathlib import Path import pandas as pd @@ -30,6 +31,61 @@ def _collector_with_store(store: _StoreStub) -> HistoricalWebcamCollector: return collector +class _ResponseStub: + def __init__( + self, + *, + status_code: int = 200, + text: str = "", + content: bytes = b"", + headers: dict[str, str] | None = None, + ): + self.status_code = status_code + self.text = text + self.content = content + self.headers = headers or {} + + def raise_for_status(self) -> None: + if self.status_code >= 400: + raise RuntimeError(f"HTTP {self.status_code}") + + +class _SessionStub: + def __init__(self, responses: dict[str, _ResponseStub]): + self._responses = responses + + def get(self, url: str, timeout: int = 20) -> _ResponseStub: + for key, value in self._responses.items(): + if key in url: + return value + raise AssertionError(f"Unexpected URL in test: {url}") + + +class _RaisingSessionStub: + def get(self, url: str, timeout: int = 20) -> _ResponseStub: + raise RuntimeError(f"network error for {url}") + + +class _AnalyzerStub: + def __init__(self): + self.saved: list[dict] = [] + + def analyze_image(self, image_path: str) -> dict: + assert Path(image_path).exists() + return { + "cars_detected": 1, + "people_detected": 2, + "buses_detected": 0, + "total_vehicles": 1, + "crowd_density": "low", + "confidence_scores": [0.9], + "timestamp": "2026-03-13T00:00:00", + } + + def _save_result(self, result: dict) -> None: + self.saved.append(result) + + def test_get_missing_dates_uses_analysis_date_column(): """Missing-date detection must use analysis_date instead of timestamp.""" station_df = pd.DataFrame( @@ -67,3 +123,142 @@ def test_is_already_processed_uses_analysis_date_column(): assert collector._is_already_processed("pajares", date(2026, 3, 10)) assert not collector._is_already_processed("pajares", date(2026, 3, 11)) + + +def test_retry_unknown_treats_unknown_as_pending(): + """With retry_unknown enabled, unknown rows must be considered unprocessed.""" + collector = _collector_with_store( + _StoreStub( + station_df=pd.DataFrame( + { + "date": pd.to_datetime(["2026-03-10"]), + "station_id": ["pajares"], + } + ), + crowd_df=pd.DataFrame( + { + "analysis_date": ["2026-03-10"], + "station_id": ["pajares"], + "crowd_density": ["unknown"], + } + ), + ) + ) + + assert collector._is_already_processed("pajares", date(2026, 3, 10)) + assert not collector._is_already_processed( + "pajares", date(2026, 3, 10), retry_unknown=True + ) + assert collector.get_missing_dates("pajares", retry_unknown=True) == [ + date(2026, 3, 10) + ] + + +def test_extract_webcam_jpg_url_accepts_relative_urls(): + """Relative /webcams/*.jpg paths must be normalized to absolute URLs.""" + html = '
' + url = HistoricalWebcamCollector._extract_webcam_jpg_url(html) + assert url == "https://www.infonieve.es/webcams/pajares-test_2025-03-03-10.jpg" + + +def test_extract_webcam_jpg_url_accepts_historico_files_urls(): + """Historico image URLs under files/historico must be accepted.""" + html = '' + url = HistoricalWebcamCollector._extract_webcam_jpg_url(html) + assert ( + url + == "https://www.infonieve.es/files/historico/2025/2025-04-30/3197_2025-04-30-10-714.jpg" + ) + + +def test_extract_webcam_jpg_url_accepts_escaped_relative_historico_urls(): + """Escaped relative paths like ``\\/files\\/historico\\/...`` must normalize.""" + html = '{"src":"\\/files\\/historico\\/2025\\/2025-04-30\\/3197_2025-04-30-10-714.jpg"}' + url = HistoricalWebcamCollector._extract_webcam_jpg_url(html) + assert ( + url + == "https://www.infonieve.es/files/historico/2025/2025-04-30/3197_2025-04-30-10-714.jpg" + ) + + +def test_download_image_bytes_rejects_html_responses(): + """Downloader must reject HTML payloads even if URL ends in .jpg.""" + collector = object.__new__(HistoricalWebcamCollector) + collector.session = _SessionStub( + { + "webcams/fake.jpg": _ResponseStub( + text="not an image", + content=b"not an image", + headers={"Content-Type": "text/html; charset=utf-8"}, + ) + } + ) + + result = collector._download_image_bytes("https://www.infonieve.es/webcams/fake.jpg") + assert result is None + + +def test_process_day_resolves_showimg_and_persists_analysis(tmp_path): + """process_day must resolve showimg URL, download bytes, and save analysis.""" + collector = object.__new__(HistoricalWebcamCollector) + collector.store = _StoreStub(pd.DataFrame(), pd.DataFrame()) + collector.analyzer = _AnalyzerStub() + collector.temp_dir = tmp_path + collector.session = _SessionStub( + { + "showimg=1": _ResponseStub( + text='' + ), + "webcams/pajares-sample.jpg": _ResponseStub( + content=b"\xff\xd8\xff\xdbJPEGDATA", + headers={"Content-Type": "image/jpeg"}, + ), + } + ) + + collector.process_day("pajares", date(2025, 3, 3)) + + assert len(collector.analyzer.saved) == 1 + saved = collector.analyzer.saved[0] + assert saved["station_id"] == "pajares" + assert saved["crowd_density"] == "low" + assert str(saved["image_path"]).endswith("pajares_2025-03-03_10h.jpg") + + +def test_process_day_with_historico_file_url(tmp_path): + """process_day must support resolved URLs under /files/historico/.""" + collector = object.__new__(HistoricalWebcamCollector) + collector.store = _StoreStub(pd.DataFrame(), pd.DataFrame()) + collector.analyzer = _AnalyzerStub() + collector.temp_dir = tmp_path + collector.session = _SessionStub( + { + "showimg=1": _ResponseStub( + text='' + ), + "files/historico/2025/2025-04-30/3197_2025-04-30-10-714.jpg": _ResponseStub( + content=b"\xff\xd8\xff\xdbJPEGDATA", + headers={"Content-Type": "image/jpeg"}, + ), + } + ) + + collector.process_day("pajares", date(2025, 4, 30)) + + assert len(collector.analyzer.saved) == 1 + saved = collector.analyzer.saved[0] + assert saved["station_id"] == "pajares" + assert saved["crowd_density"] == "low" + + +def test_process_day_does_not_persist_unknown_on_network_errors(tmp_path): + """Transient errors must not be persisted as unknown crowd rows.""" + collector = object.__new__(HistoricalWebcamCollector) + collector.store = _StoreStub(pd.DataFrame(), pd.DataFrame()) + collector.analyzer = _AnalyzerStub() + collector.temp_dir = tmp_path + collector.session = _RaisingSessionStub() + + collector.process_day("pajares", date(2025, 3, 3)) + + assert collector.analyzer.saved == []