File size: 3,918 Bytes
e2abd1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""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"}))