Download scripts/data/build_swa_charades_ego.py from Tinghong-Ye22/code-HFD: direct link, hf CLI and curl.
- Browser
- Download file 18.8 kB
-
https://huggingface.co/Tinghong-Ye22/code-HFD/resolve/main/scripts/data/build_swa_charades_ego.py
- Command line
-
hf download hf://Tinghong-Ye22/code-HFD/scripts/data/build_swa_charades_ego.py
-
curl -L -o build_swa_charades_ego.py https://huggingface.co/Tinghong-Ye22/code-HFD/resolve/main/scripts/data/build_swa_charades_ego.py
18.8 kB
| #!/usr/bin/env python3 | |
| """Build a conservative, non-repeated Charades-Ego SWA candidate cohort. | |
| Only official first-person rows marked verified are considered. Questions are | |
| derived from human temporal action intervals, and train/val/test are separated | |
| by original video before any HFD motion is paired. Ordinary/no-question hard | |
| negatives use distinct timestamps, rather than duplicated positive sources. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import io | |
| import json | |
| import subprocess | |
| import sys | |
| import zipfile | |
| from collections import Counter | |
| from pathlib import Path | |
| from typing import Any | |
| def sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as stream: | |
| for block in iter(lambda: stream.read(2**20), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def stable_order(*parts: object) -> str: | |
| return hashlib.sha256("\0".join(map(str, parts)).encode()).hexdigest() | |
| def load_csv(archive: zipfile.ZipFile, name: str) -> list[dict[str, str]]: | |
| text = archive.read(f"CharadesEgo/{name}").decode("utf-8") | |
| return list(csv.DictReader(io.StringIO(text))) | |
| def parse_actions(value: str, classes: dict[str, str]) -> list[dict[str, Any]]: | |
| output = [] | |
| for encoded in value.split(";") if value else (): | |
| action_id, start, end = encoded.split() | |
| start_value, end_value = float(start), float(end) | |
| if action_id in classes and end_value > start_value: | |
| output.append( | |
| { | |
| "action_id": action_id, | |
| "start": start_value, | |
| "end": end_value, | |
| "label": classes[action_id], | |
| } | |
| ) | |
| return output | |
| def natural_action(label: str) -> str: | |
| value = label.strip().rstrip(".") | |
| for prefix in ("Someone is ", "Someone "): | |
| if value.startswith(prefix): | |
| value = value[len(prefix) :] | |
| break | |
| return value[:1].lower() + value[1:] | |
| def interval_distance(moment: float, action: dict[str, Any]) -> float: | |
| if action["start"] <= moment <= action["end"]: | |
| return 0.0 | |
| return min(abs(moment - action["start"]), abs(moment - action["end"])) | |
| def words(value: str) -> set[str]: | |
| stop = {"a", "an", "the", "some", "someone", "something", "is", "from", "to", "of", "on", "in"} | |
| return { | |
| token.strip(".,/()[]").lower() | |
| for token in value.split() | |
| if token.strip(".,/()[]").lower() not in stop | |
| } | |
| def probe_duration(path: Path) -> float: | |
| result = subprocess.run( | |
| [ | |
| "ffprobe", | |
| "-v", | |
| "error", | |
| "-show_entries", | |
| "format=duration", | |
| "-of", | |
| "default=noprint_wrappers=1:nokey=1", | |
| str(path), | |
| ], | |
| check=True, | |
| capture_output=True, | |
| text=True, | |
| ) | |
| return float(result.stdout.strip()) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--annotations", type=Path, required=True) | |
| parser.add_argument("--video-root", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--camera-root", type=Path, required=True) | |
| parser.add_argument("--review-frame-root", type=Path) | |
| parser.add_argument("--min-quality", type=int, default=6) | |
| parser.add_argument("--min-relevance", type=int, default=6) | |
| parser.add_argument("--min-action-seconds", type=float, default=3.0) | |
| # Prefer video diversity over many correlated timestamps from one clip. | |
| parser.add_argument("--max-positive-per-video", type=int, default=3) | |
| parser.add_argument("--max-negative-per-video", type=int, default=2) | |
| args = parser.parse_args() | |
| sys.path.insert(0, str(args.camera_root / "compat/deps310")) | |
| sys.path.insert(0, str(args.camera_root)) | |
| from fast_camera import decode_causal # type: ignore | |
| videos = {path.stem: path for path in args.video_root.rglob("*.mp4")} | |
| if not videos: | |
| raise RuntimeError(f"No Charades-Ego videos found under {args.video_root}") | |
| output: list[dict[str, Any]] = [] | |
| rejected = Counter() | |
| seen_video_splits: dict[str, str] = {} | |
| hash_cache: dict[Path, str] = {} | |
| duration_cache: dict[Path, float] = {} | |
| with zipfile.ZipFile(args.annotations) as archive: | |
| classes = dict( | |
| line.split(" ", 1) | |
| for line in archive.read( | |
| "CharadesEgo/Charades_v1_classes.txt" | |
| ).decode().splitlines() | |
| if line.strip() | |
| ) | |
| sources = ( | |
| ("train", load_csv(archive, "CharadesEgo_v1_train_only1st.csv")), | |
| ("heldout", load_csv(archive, "CharadesEgo_v1_test_only1st.csv")), | |
| ) | |
| license_sha = hashlib.sha256( | |
| archive.read("CharadesEgo/license.txt") | |
| ).hexdigest() | |
| for upstream_split, rows in sources: | |
| for row in rows: | |
| try: | |
| quality = int(row["quality"]) | |
| relevance = int(row["relevance"]) | |
| except (TypeError, ValueError): | |
| rejected["missing_quality"] += 1 | |
| continue | |
| if row.get("verified") != "Yes": | |
| rejected["not_verified"] += 1 | |
| continue | |
| if quality < args.min_quality or relevance < args.min_relevance: | |
| rejected["quality_or_relevance"] += 1 | |
| continue | |
| video_id = row["id"] | |
| video_path = videos.get(video_id) | |
| if video_path is None: | |
| rejected["video_missing"] += 1 | |
| continue | |
| split = ( | |
| "train" | |
| if upstream_split == "train" | |
| else ( | |
| "val" | |
| if int(stable_order("split", video_id)[:8], 16) % 2 == 0 | |
| else "test" | |
| ) | |
| ) | |
| previous = seen_video_splits.setdefault(video_id, split) | |
| if previous != split: | |
| raise RuntimeError(f"Video split conflict: {video_id}") | |
| if video_path not in duration_cache: | |
| duration_cache[video_path] = probe_duration(video_path) | |
| if video_path not in hash_cache: | |
| hash_cache[video_path] = sha256(video_path) | |
| duration = duration_cache[video_path] | |
| video_sha = hash_cache[video_path] | |
| all_actions = parse_actions(row.get("actions", ""), classes) | |
| eligible = [ | |
| action | |
| for action in all_actions | |
| if action["end"] - action["start"] >= args.min_action_seconds | |
| and 0.0 <= action["start"] | |
| and (action["start"] + action["end"]) / 2 <= duration - 0.2 | |
| ] | |
| if not eligible: | |
| rejected["no_long_action"] += 1 | |
| continue | |
| eligible.sort( | |
| key=lambda action: stable_order( | |
| "positive", video_id, action["action_id"], action["start"] | |
| ) | |
| ) | |
| positives = eligible[: args.max_positive_per_video] | |
| pending_examples: list[dict[str, Any]] = [] | |
| def queue_example( | |
| *, | |
| target: dict[str, Any], | |
| moment: float, | |
| has_question: bool, | |
| answer: str, | |
| ordinal: int, | |
| ) -> None: | |
| suffix = ( | |
| "qa_yes" | |
| if has_question and answer == "Yes." | |
| else "qa_no" if has_question else "ordinary" | |
| ) | |
| item_id = ( | |
| f"charades_{video_id}_{suffix}_{ordinal:02d}_" | |
| f"{target['action_id']}" | |
| ) | |
| action_text = natural_action(target["label"]) | |
| pending_examples.append( | |
| { | |
| "id": item_id, | |
| "source_dataset": "CharadesEgo", | |
| "video_id": video_id, | |
| "original_video": row.get("charades_video", ""), | |
| "question": ( | |
| f"Is the camera wearer currently {action_text}?" | |
| ), | |
| "answer": answer, | |
| "category": "presence_state", | |
| "interval_start": float(target["start"]), | |
| "interval_end": float(target["end"]), | |
| "query_video_seconds": float(moment), | |
| "video_path": str(video_path.resolve()), | |
| "video_duration": duration, | |
| "video_sha256": video_sha, | |
| "original_split": upstream_split, | |
| "research_split": split, | |
| "quality": quality, | |
| "relevance": relevance, | |
| "verified": True, | |
| "swa_has_question": has_question, | |
| "reference_unchanged": True, | |
| "reference_provenance": ( | |
| "official_human_temporal_action_annotation_" | |
| "derived_binary_QA" | |
| ), | |
| "licence_applicability": ( | |
| "Charades-Ego non-commercial research license" | |
| ), | |
| "status": ( | |
| "official_verified_temporal_interval_with_" | |
| "causal_frame_contract" | |
| ), | |
| } | |
| ) | |
| for ordinal, action in enumerate(positives): | |
| queue_example( | |
| target=action, | |
| moment=(action["start"] + action["end"]) / 2, | |
| has_question=True, | |
| answer="Yes.", | |
| ordinal=ordinal, | |
| ) | |
| # Distinct no-question windows are retained as reply-readiness | |
| # hard negatives. Their target action is absent by the human | |
| # intervals, at least two seconds away, and lexically distinct | |
| # from the action actually occurring at the sampled moment. | |
| negative_candidates = [] | |
| for target in positives: | |
| target_words = words(target["label"]) | |
| for actual in eligible: | |
| if actual["action_id"] == target["action_id"]: | |
| continue | |
| moment = (actual["start"] + actual["end"]) / 2 | |
| same_class = [ | |
| action | |
| for action in all_actions | |
| if action["action_id"] == target["action_id"] | |
| ] | |
| if any(interval_distance(moment, action) < 2.0 for action in same_class): | |
| continue | |
| if target_words & words(actual["label"]): | |
| continue | |
| negative_candidates.append((target, actual, moment)) | |
| negative_candidates.sort( | |
| key=lambda pair: stable_order( | |
| "negative", | |
| video_id, | |
| pair[0]["action_id"], | |
| pair[1]["action_id"], | |
| pair[2], | |
| ) | |
| ) | |
| used_targets = set() | |
| chosen = [] | |
| for candidate in negative_candidates: | |
| target_id = candidate[0]["action_id"] | |
| if target_id in used_targets: | |
| continue | |
| used_targets.add(target_id) | |
| chosen.append(candidate) | |
| if len(chosen) >= args.max_negative_per_video: | |
| break | |
| for ordinal, (target, _actual, moment) in enumerate(chosen): | |
| queue_example( | |
| target=target, | |
| moment=moment, | |
| # The first distinct absent-action timestamp is a real | |
| # negative QA target; the second is a no-question | |
| # reply-readiness negative. Both are unique source | |
| # moments rather than repeated variants. | |
| has_question=ordinal == 0, | |
| answer="No.", | |
| ordinal=ordinal, | |
| ) | |
| # Decode all selected moments from a video in one pass. This | |
| # preserves the exact causal frame contract while avoiding up | |
| # to twelve independent container opens for the same clip. | |
| pending_examples.sort(key=lambda item: item["query_video_seconds"]) | |
| requests: list[tuple[float, int]] = [] | |
| for item_index, item in enumerate(pending_examples): | |
| moment = float(item["query_video_seconds"]) | |
| start = float(item["interval_start"]) | |
| review_times = ( | |
| sorted( | |
| { | |
| max(start + 0.05, moment - offset) | |
| for offset in (1.5, 1.0, 0.5, 0.0) | |
| } | |
| ) | |
| if item["swa_has_question"] | |
| else [moment] | |
| ) | |
| item["review_frame_times"] = review_times | |
| requests.extend((value, item_index) for value in review_times) | |
| requests.sort() | |
| moments = [value for value, _ in requests] | |
| if moments: | |
| try: | |
| decoded_images, decoded_pts = decode_causal( | |
| str(video_path), moments, 224 | |
| ) | |
| except (AssertionError, RuntimeError, ValueError): | |
| rejected["causal_decode_failed"] += 1 | |
| continue | |
| if len(decoded_pts) != len(requests): | |
| raise RuntimeError( | |
| f"Causal decoder returned {len(decoded_pts)} timestamps " | |
| f"for {len(requests)} queries in {video_id}" | |
| ) | |
| grouped_pts: list[list[float]] = [ | |
| [] for _ in pending_examples | |
| ] | |
| grouped_images: list[list[Any]] = [ | |
| [] for _ in pending_examples | |
| ] | |
| for image, pts, (_, item_index) in zip( | |
| decoded_images, decoded_pts, requests | |
| ): | |
| grouped_pts[item_index].append(float(pts)) | |
| grouped_images[item_index].append(image) | |
| for item, pts_values, images in zip( | |
| pending_examples, grouped_pts, grouped_images | |
| ): | |
| item["decoded_pts"] = pts_values | |
| if ( | |
| args.review_frame_root is not None | |
| and item["swa_has_question"] | |
| ): | |
| from PIL import Image | |
| frame_dir = args.review_frame_root / item["id"] | |
| frame_dir.mkdir(parents=True, exist_ok=True) | |
| paths = [] | |
| for frame_index, image in enumerate(images): | |
| path = frame_dir / f"{frame_index:02d}.jpg" | |
| Image.fromarray(image).save(path, quality=92) | |
| paths.append(str(path.resolve())) | |
| item["images"] = paths | |
| output.append(item) | |
| for job_index, item in enumerate(output): | |
| item["job_index"] = job_index | |
| identities = [item["id"] for item in output] | |
| if len(identities) != len(set(identities)): | |
| raise RuntimeError("Duplicate Charades-Ego SWA ids") | |
| split_videos = { | |
| split: {item["video_id"] for item in output if item["research_split"] == split} | |
| for split in ("train", "val", "test") | |
| } | |
| if any( | |
| split_videos[left] & split_videos[right] | |
| for left, right in (("train", "val"), ("train", "test"), ("val", "test")) | |
| ): | |
| raise RuntimeError("Charades-Ego video leakage across splits") | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text( | |
| json.dumps(output, ensure_ascii=False, indent=2), encoding="utf-8" | |
| ) | |
| review_jobs = [item for item in output if item["swa_has_question"]] | |
| args.output.with_name(args.output.stem + "_review.json").write_text( | |
| json.dumps(review_jobs, ensure_ascii=False, indent=2), encoding="utf-8" | |
| ) | |
| report = { | |
| "sources": len(output), | |
| "unique_videos": len({item["video_id"] for item in output}), | |
| "split_sources": dict(Counter(item["research_split"] for item in output)), | |
| "split_videos": {key: len(value) for key, value in split_videos.items()}, | |
| "qa_sources": sum(item["swa_has_question"] for item in output), | |
| "ordinary_sources": sum(not item["swa_has_question"] for item in output), | |
| "rejected_rows": dict(rejected), | |
| "annotation_sha256": sha256(args.annotations), | |
| "license_sha256": license_sha, | |
| "filters": { | |
| "first_person_only": True, | |
| "official_verified_only": True, | |
| "min_quality": args.min_quality, | |
| "min_relevance": args.min_relevance, | |
| "min_action_seconds": args.min_action_seconds, | |
| "max_positive_per_video": args.max_positive_per_video, | |
| "max_negative_per_video": args.max_negative_per_video, | |
| "negative_same_action_margin_seconds": 2.0, | |
| }, | |
| } | |
| args.output.with_suffix(".audit.json").write_text( | |
| json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8" | |
| ) | |
| print(json.dumps(report, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |