from __future__ import annotations import csv import json from dataclasses import dataclass, field from pathlib import Path from typing import Any from .fixtures import ensure_synthetic_fixture DATASET_NAMES = [ "youcook2", "ave", "ava_active_speaker", "tvqa", "activitynet_captions", ] @dataclass(frozen=True) class Clip: dataset: str video_id: str media_path: Path | None duration: float windows: list[dict[str, Any]] = field(default_factory=list) metadata: dict[str, Any] = field(default_factory=dict) def _load_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle) def _read_csv_rows(path: Path) -> list[dict[str, str]]: with path.open("r", encoding="utf-8", newline="") as handle: return list(csv.DictReader(handle)) def _duration_from_manifest(meta: dict[str, Any], default: float = 10.0) -> float: for key in ("duration", "duration_seconds", "end_time"): if key in meta: try: return float(meta[key]) except (TypeError, ValueError): pass return default def discover_dataset(dataset: str, root: Path, limit: int | None = None) -> list[Clip]: dataset_root = root / dataset videos = sorted((dataset_root / "videos").glob("*.mp4")) clips: list[Clip] = [] if not videos: return clips annotation_json: dict[str, Any] = {} for candidate in [ dataset_root / "annotations.json", dataset_root / "captions.json", dataset_root / "labels.json", ]: if candidate.exists(): loaded = _load_json(candidate) if isinstance(loaded, dict): annotation_json = loaded break annotation_csv: list[dict[str, str]] = [] for candidate in [ dataset_root / "annotations.csv", dataset_root / "labels.csv", ]: if candidate.exists(): annotation_csv = _read_csv_rows(candidate) break csv_by_video: dict[str, list[dict[str, str]]] = {} for row in annotation_csv: vid = row.get("video_id") or row.get("id") or row.get("video") or "" if vid: csv_by_video.setdefault(vid, []).append(row) for video in videos[:limit]: video_id = video.stem meta = annotation_json.get(video_id, {}) if isinstance(annotation_json, dict) else {} if not isinstance(meta, dict): meta = {"annotation": meta} rows = csv_by_video.get(video_id, []) windows = _windows_from_annotations(dataset, video_id, meta, rows) clips.append( Clip( dataset=dataset, video_id=video_id, media_path=video, duration=_duration_from_manifest(meta, default=max(10.0, len(windows) * 2.0)), windows=windows, metadata={"source": "real_adapter", "annotation_rows": len(rows), **meta}, ) ) return clips def _windows_from_annotations( dataset: str, video_id: str, meta: dict[str, Any], rows: list[dict[str, str]], ) -> list[dict[str, Any]]: windows: list[dict[str, Any]] = [] segments = meta.get("segments") or meta.get("annotations") or meta.get("timestamps") or [] if isinstance(segments, list): for idx, segment in enumerate(segments): if not isinstance(segment, dict): continue start = float(segment.get("start", segment.get("start_time", idx * 2.0))) end = float(segment.get("end", segment.get("end_time", start + 2.0))) label = " ".join( str(segment.get(key, "")) for key in ["label", "caption", "sentence", "activity", "action"] ).lower() windows.append(_annotation_window(dataset, video_id, idx, start, end, label)) for row in rows: idx = len(windows) start = float(row.get("start", row.get("start_time", idx * 2.0)) or idx * 2.0) end = float(row.get("end", row.get("end_time", start + 2.0)) or start + 2.0) label = " ".join(str(v) for v in row.values()).lower() windows.append(_annotation_window(dataset, video_id, idx, start, end, label)) return windows def _annotation_window( dataset: str, video_id: str, index: int, start: float, end: float, label: str, ) -> dict[str, Any]: visual = {"motion_continuous"} audio = set() subtitle = set() if any(word in label for word in ["speak", "speaker", "dialog", "talk", "voice"]): visual.update({"person_visible", "speaker_visible", "mouth_open"}) audio.add("speech") subtitle.add("subtitle_speech") if any(word in label for word in ["cook", "chop", "cut", "food", "recipe"]): visual.update({"scene_kitchen", "cooking_action", "object_food"}) subtitle.add("recipe_step") if any(word in label for word in ["chop", "cut"]): visual.add("chopping") audio.add("chop_sound") if any(word in label for word in ["music", "sound", "audio", "event"]): audio.add("event_sound") visual.add("event_visible") if dataset == "ava_active_speaker": visual.update({"person_visible", "speaker_visible", "mouth_open"}) audio.add("speech") subtitle.add("subtitle_speech") if dataset == "tvqa": subtitle.add("subtitle_speech") return { "video_id": video_id, "index": index, "start": start, "end": end, "visual_atoms": sorted(visual), "audio_atoms": sorted(audio), "subtitle_ocr_atoms": sorted(subtitle), } def load_clips( root: Path, datasets: list[str] | None = None, limit: int | None = None, synthetic_if_empty: bool = True, fixture_root: Path = Path("data/fixtures"), ) -> list[Clip]: wanted = datasets or DATASET_NAMES clips: list[Clip] = [] per_dataset_limit = None if limit is None else max(1, limit) for dataset in wanted: clips.extend(discover_dataset(dataset, root, per_dataset_limit)) if limit is not None and len(clips) >= limit: return clips[:limit] if clips or not synthetic_if_empty: return clips[:limit] return ensure_synthetic_fixture(fixture_root, limit=limit or 10) def adapter_status(root: Path) -> list[dict[str, Any]]: status: list[dict[str, Any]] = [] for dataset in DATASET_NAMES: dataset_root = root / dataset videos = sorted((dataset_root / "videos").glob("*.mp4")) missing = None if not dataset_root.exists(): missing = str(dataset_root) elif not videos: missing = str(dataset_root / "videos/*.mp4") status.append( { "dataset": dataset, "root": str(dataset_root), "clips_found": len(videos), "ready": bool(videos), "smallest_missing_path": missing, } ) return status