"""One exact matched representative per automatically grouped collection point. Safe batch membership is joined only after the dashboard's metadata and ODD filters. All details describe the selected current frame, never merged labels. """ from __future__ import annotations from collections import OrderedDict from collections.abc import Callable, Iterable, Mapping from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from datetime import date from functools import lru_cache from itertools import zip_longest import hashlib from http.client import HTTPException import html import math from pathlib import Path import re from threading import Lock from time import monotonic from urllib.request import Request import streamlit as st from annotation_statistics import AnnotationRecord, definitions from classic_statistics import selection_label from city_labels import city_display_name _PAGE_SIZE = 12 _LOCATION_CODE = re.compile(r'L-[0-9a-f]{16}\Z') _BATCH_CODE = re.compile(r'B-[0-9a-f]{16}\Z') _FRAME_KEY = re.compile(r'[0-9a-f]{64}\.jpg\Z') _PAGE_KEY = 'representative_gallery_page' _CITIES_KEY = 'representative_gallery_cities' _LEGACY_CITY_KEY = 'representative_gallery_city' _SELECTION_KEY = '_representative_gallery_selection' _POPULATION_KEY = '_representative_gallery_population' _MAX_FRAME_BYTES = 4 * 1024 * 1024 _THUMBNAIL_TIMEOUT_SECONDS = 5 _IMAGE_FAILURE_COOLDOWN_SECONDS = 30 _IMAGE_FAILURES: OrderedDict[str, float] = OrderedDict() _IMAGE_FAILURE_LOCK = Lock() # Gallery visibility only; source records and duration statistics remain intact. _HIDDEN_LOCATION_CODES = frozenset({'L-8a9f37a3fe972582'}) _STYLE = """ """ @dataclass(frozen=True) class LocationExample: """Filtered members of one safe location, in representative priority order.""" code: str city: str records: tuple[AnnotationRecord, ...] total_batches: int @property def record(self) -> AnnotationRecord: return self.records[0] @property def matching_batches(self) -> int: return len(self.records) @property def collected_on(self) -> date | None: return self.record.collected_on @property def batch_code(self) -> str: return self.record.batch_code def location_examples(records: Iterable[AnnotationRecord], locations ) -> tuple[tuple[LocationExample, ...], int]: """Join exact safe batch codes after filtering; unmapped batches stay pending.""" records = tuple(records) matched = {record.batch_code: record for record in records if isinstance(getattr(record, 'batch_code', None), str) and _BATCH_CODE.fullmatch(record.batch_code)} grouped = set() examples = [] for group in locations.groups: if not isinstance(group.code, str) or not _LOCATION_CODE.fullmatch(group.code): continue members = tuple(dict.fromkeys(code for code in group.batch_codes if isinstance(code, str) and _BATCH_CODE.fullmatch(code))) candidates = tuple(sorted((matched[code] for code in members if code in matched and code not in grouped and matched[code].city == group.city), key=lambda record: ( not (isinstance(getattr(record, 'frame_key', None), str) and _FRAME_KEY.fullmatch(record.frame_key)), -(record.collected_on or date.min).toordinal(), record.batch_code))) if candidates: examples.append(LocationExample(group.code, group.city, candidates, len(members))) grouped.update(record.batch_code for record in candidates) return tuple(examples), sum(getattr(record, 'batch_code', None) not in grouped for record in records) def _reset_gallery_page() -> None: st.session_state[_PAGE_KEY] = 1 def gallery_page(records: Iterable[AnnotationRecord], page: int = 1 ) -> tuple[tuple[AnnotationRecord, ...], int, int]: """Interleave cities, retaining newest-date/safe-code priority within each.""" by_city = {} for record in sorted(records, key=lambda record: ( -(record.collected_on or date.min).toordinal(), getattr(record, 'batch_code', None) or '', )): by_city.setdefault(record.city, []).append(record) ordered = [record for row in zip_longest(*(by_city[city] for city in sorted(by_city))) for record in row if record is not None] pages = (len(ordered) + _PAGE_SIZE - 1) // _PAGE_SIZE try: page = int(page) except (TypeError, ValueError, OverflowError): page = 1 selected = min(max(1, page), max(1, pages)) start = (selected - 1) * _PAGE_SIZE return tuple(ordered[start:start + _PAGE_SIZE]), selected, pages def _location_hours(example: LocationExample, batch_hours: Mapping[str, float | None] | None ) -> tuple[float | None, int, int]: """Sum distinct filtered members; missing coverage never becomes measured zero.""" codes = {record.batch_code for record in example.records} known = [] for code in codes: value = batch_hours.get(code) if batch_hours is not None else None if (not isinstance(value, bool) and isinstance(value, (int, float)) and math.isfinite(value) and value >= 0): known.append(value) return math.fsum(known) if known else None, len(known), len(codes) @lru_cache(maxsize=256) def _public_gallery_image(key: str) -> bytes: """Cache verified JPEG bytes; briefly defer failed transfers on cache misses.""" from public_snapshot import _open_public_url from representative_frames import public_frame_url # A successful LRU hit bypasses this check, including when an overlapping # request failed after another request successfully cached the same key. with _IMAGE_FAILURE_LOCK: if _IMAGE_FAILURES.get(key, 0) > monotonic(): raise OSError('Representative frame is temporarily unavailable') _IMAGE_FAILURES.pop(key, None) try: request = Request(public_frame_url(key), headers={'Accept': 'image/jpeg', 'User-Agent': 'NDS-statistics/1'}) with _open_public_url(request, timeout=_THUMBNAIL_TIMEOUT_SECONDS) as response: length = response.headers.get('Content-Length') if length is not None and not 0 <= int(length) <= _MAX_FRAME_BYTES: raise ValueError('Representative frame transfer is too large') content = response.read(_MAX_FRAME_BYTES + 1) if (len(content) > _MAX_FRAME_BYTES or not content.startswith(b'\xff\xd8\xff') or not content.endswith(b'\xff\xd9') or hashlib.sha256(content).hexdigest() + '.jpg' != key): raise ValueError('Representative frame integrity check failed') except (OSError, HTTPException, ValueError, TypeError, OverflowError): with _IMAGE_FAILURE_LOCK: _IMAGE_FAILURES[key] = monotonic() + _IMAGE_FAILURE_COOLDOWN_SECONDS _IMAGE_FAILURES.move_to_end(key) while len(_IMAGE_FAILURES) > 256: _IMAGE_FAILURES.popitem(last=False) raise _retry_gallery_images((key,)) return content def _retry_gallery_images(keys: Iterable[str]) -> None: """Retry visible unavailable images without discarding successful bytes.""" with _IMAGE_FAILURE_LOCK: for key in keys: _IMAGE_FAILURES.pop(key, None) def gallery_image(key: str | None, *, cache_root: Path | None = None) -> bytes | None: """Serve sanitized local or public JPEG bytes from the dashboard's domain.""" if not isinstance(key, str) or not _FRAME_KEY.fullmatch(key): return None from representative_frames import frame_file cached = frame_file(key, cache_root=cache_root) if cached is not None: try: return cached.read_bytes() except OSError: pass try: return _public_gallery_image(key) except (OSError, HTTPException, ValueError, TypeError, OverflowError): return None def _page_images(records: Iterable[AnnotationRecord], image_loader: Callable) -> dict: """Load only the visible page's unique valid keys, with four requests at once.""" keys = tuple(dict.fromkeys(key for record in records if isinstance(key := getattr(record, 'frame_key', None), str) and _FRAME_KEY.fullmatch(key))) if not keys: return {} def load(key): try: return image_loader(key) except (OSError, HTTPException, ValueError, TypeError, OverflowError): return None with ThreadPoolExecutor(max_workers=4) as executor: return dict(zip(keys, executor.map(load, keys))) @st.fragment def render_representative_gallery( records: Iterable[AnnotationRecord], translate: Callable[[str], str], *, locations=None, location_status: str = 'not_published', language: str = 'zh', field_label: Callable[[str], str] | None = None, image_loader: Callable[[str], bytes | str | None] | None = None, batch_hours: Mapping[str, float | None] | None = None, incomplete_batches: Iterable[str] = (), core: bool | None = None, ) -> None: """Show one matched frame and filtered member hours per point, twelve per page.""" records = tuple(records) incomplete_batches = frozenset(incomplete_batches) core = any(label.field == 'scene.type' for record in records for label in record.labels) if core is None else core if core: from core_annotations import definitions_v2 fields = definitions_v2() else: fields = definitions() def tr(zh: str, en: str) -> str: translated = translate(zh) return en if language == 'en' and translated == zh else translated def label_value(label) -> str: if label is None: return tr('未标注', 'Unlabeled') if label.state != 'observed': return translate(selection_label('@' + label.state, language)) return '、'.join(translate(value) for value in label.values) st.markdown(_STYLE, unsafe_allow_html=True) st.markdown("
', unsafe_allow_html=True) if locations is None or location_status != 'ok': if location_status in ('not_published', 'not_configured'): st.info(tr('地点归组尚未发布,暂不展示地点示例。', 'Location grouping has not been published; point examples are not available yet.')) else: st.warning(tr('地点归组暂不可用,请稍后刷新。', 'Location grouping is unavailable. Please refresh later.')) return examples, pending = location_examples(records, locations) examples = tuple(example for example in examples if example.code not in _HIDDEN_LOCATION_CODES) pending_summary = tr(f'全部城市匹配 {len(examples):,} 个采集点 · 待归组 {pending:,} 个批次', f'All cities: {len(examples):,} matching points · {pending:,} matching batches await grouping') st.markdown("' + html.escape(tr( '采集点为自动归组结果,同城组内最大距离 100 米,未经人工确认为路口。每点展示一张匹配代表帧,标签仅描述该帧。' '场景时长汇总当前城市、日期、编码、时段及场景/ODD 筛选后,同一点不同匹配批次的关联视频已知时长(h);' '它不是条件持续时长。未知时长不计入已知小计,缺少定位信息或待归组的批次不列入地点示例。', 'Collection points are automatically grouped with a maximum within-group distance of 100 metres, ' 'not reviewed intersection identities. Each point shows one matching frame; its labels describe only that frame. ' 'Scene hours sum known associated video hours for distinct matching batches at that point after current city, ' 'date, codec, period and scene/ODD filters; they do not measure time spent in a condition. Unknown hours are ' 'excluded from known subtotals. Batches without location data or awaiting grouping are omitted.')) + '
' + html.escape(pending_summary) + '