Download prepare_delivery.py from flashdata-dev/yt-temporal-1b-tempura-sample: direct link, hf CLI and curl.
- Browser
- Download file 3.92 kB
-
https://huggingface.co/datasets/flashdata-dev/yt-temporal-1b-tempura-sample/resolve/main/prepare_delivery.py
- Command line
-
hf download hf://datasets/flashdata-dev/yt-temporal-1b-tempura-sample/prepare_delivery.py
-
curl -L -o prepare_delivery.py https://huggingface.co/datasets/flashdata-dev/yt-temporal-1b-tempura-sample/resolve/main/prepare_delivery.py
3.92 kB
| """Normalize a local CSV/JSONL into a unique YouTube source manifest. | |
| This script performs no network requests. Source references do not grant media | |
| rights or establish current video availability. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import re | |
| from pathlib import Path | |
| from urllib.parse import parse_qs, urlsplit | |
| ID = re.compile(r"[A-Za-z0-9_-]{11}\Z") | |
| HOSTS = {"youtube.com", "www.youtube.com", "m.youtube.com", "music.youtube.com", | |
| "youtube-nocookie.com", "www.youtube-nocookie.com"} | |
| def youtube_id(value: object) -> str | None: | |
| if not isinstance(value, str): | |
| return None | |
| value = value.strip() | |
| if ID.fullmatch(value): | |
| return value | |
| try: | |
| parsed = urlsplit(value) | |
| if parsed.scheme not in {"http", "https"} or parsed.username or parsed.password: | |
| return None | |
| parts = parsed.path.strip("/").split("/") | |
| if parsed.hostname in {"youtu.be", "www.youtu.be"}: | |
| candidate = parts[0] | |
| elif parsed.hostname in HOSTS: | |
| if parsed.path == "/watch": | |
| candidate = parse_qs(parsed.query).get("v", [""])[0] | |
| elif len(parts) == 2 and parts[0] in {"embed", "shorts", "live", "v"}: | |
| candidate = parts[1] | |
| else: | |
| return None | |
| else: | |
| return None | |
| except ValueError: | |
| return None | |
| return candidate if ID.fullmatch(candidate) else None | |
| def normalize(records: list[dict]) -> tuple[list[dict], dict]: | |
| unique: dict[str, dict] = {} | |
| outcomes = [] | |
| for index, row in enumerate(records): | |
| video_id = next((identifier for key in ("video_id", "id", "source_video_id", "source_video_url", "video_link", "url") | |
| if (identifier := youtube_id(row.get(key)))), None) | |
| if video_id is None: | |
| outcomes.append({"input_row": index, "status": "invalid_youtube_reference"}) | |
| continue | |
| repeated = video_id in unique | |
| if not repeated: | |
| unique[video_id] = {"video_id": video_id, | |
| "source_video_url": f"https://www.youtube.com/watch?v={video_id}", | |
| "input_rows": []} | |
| unique[video_id]["input_rows"].append(index) | |
| outcomes.append({"input_row": index, "video_id": video_id, | |
| "status": "duplicate" if repeated else "accepted"}) | |
| return list(unique.values()), { | |
| "input_rows": len(records), "unique_videos": len(unique), | |
| "invalid_rows": sum(x["status"] == "invalid_youtube_reference" for x in outcomes), | |
| "duplicate_rows": sum(x["status"] == "duplicate" for x in outcomes), | |
| "network_requests": 0, "media_availability_checked": False, | |
| "outcomes": outcomes, | |
| } | |
| def read_records(path: Path) -> list[dict]: | |
| with path.open(encoding="utf-8-sig", newline="") as stream: | |
| if path.suffix.lower() == ".csv": | |
| return list(csv.DictReader(stream)) | |
| return [json.loads(line) for line in stream if line.strip()] | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("input", type=Path) | |
| parser.add_argument("--output", type=Path, default=Path("delivery-manifest.jsonl")) | |
| parser.add_argument("--report", type=Path, default=Path("normalization-report.json")) | |
| args = parser.parse_args() | |
| if len({p.resolve() for p in (args.input, args.output, args.report)}) != 3: | |
| parser.error("Input, output and report must have different paths") | |
| manifest, report = normalize(read_records(args.input)) | |
| args.output.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in manifest), encoding="utf-8") | |
| args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") | |
| print(json.dumps({key: value for key, value in report.items() if key != "outcomes"})) | |