File size: 3,469 Bytes
e1a9b03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Cut SEMANTIX TED gesture clips from your own local copies of the 10 TED talks.

SEMANTIX does not redistribute TED video (each row links to TED's official YouTube upload instead).
If you have obtained copies of the talks listed in data/ted_talks.csv from TED for your own
non-commercial research use, save each as <talk_dir>/<talk_id>.mp4 (e.g. t0001.mp4) and run:

    python scripts/extract_ted_clips.py --ted-csv data/ted.csv --talks-csv data/ted_talks.csv \
        --talk-dir /path/to/talks --out-dir ted_clips [--pad 0.0]

Timestamps refer to the talk videos used to build the dataset (TED's official YouTube uploads, which
begin with TED's intro sequence). Their durations are listed in data/ted_talks.csv
(source_video_duration_sec); if your copy has a different duration, its timeline may be offset and
clips should be checked before use.

Requires ffmpeg on PATH (or pass --ffmpeg).
"""

import argparse
import csv
import re
import subprocess
from pathlib import Path


def duration(ffmpeg: str, path: Path) -> float:
    err = subprocess.run([ffmpeg, "-hide_banner", "-i", str(path)], capture_output=True, text=True).stderr
    h, m, s = re.search(r"Duration: (\d+):(\d+):([\d.]+)", err).groups()
    return int(h) * 3600 + int(m) * 60 + float(s)


def main() -> None:
    parser = argparse.ArgumentParser(description="Cut SEMANTIX TED clips from local talk videos.")
    parser.add_argument("--ted-csv", default="data/ted.csv")
    parser.add_argument("--talks-csv", default="data/ted_talks.csv")
    parser.add_argument("--talk-dir", required=True, help="Folder with t0001.mp4 ... t0010.mp4")
    parser.add_argument("--out-dir", default="ted_clips")
    parser.add_argument("--pad", type=float, default=0.0, help="Seconds of context added on each side")
    parser.add_argument("--ffmpeg", default="ffmpeg")
    args = parser.parse_args()

    talk_dir, out_dir = Path(args.talk_dir), Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    with open(args.talks_csv, newline="", encoding="utf-8") as fh:
        talks = {row["talk_id"]: row for row in csv.DictReader(fh)}

    lengths = {}
    for talk_id, talk in talks.items():
        path = talk_dir / f"{talk_id}.mp4"
        if not path.exists():
            print(f"missing {path} ({talk['ted_url']}); its clips will be skipped")
            continue
        lengths[talk_id] = duration(args.ffmpeg, path)
        expected = float(talk["source_video_duration_sec"])
        if abs(lengths[talk_id] - expected) > 1.0:
            print(f"warning: {path} lasts {lengths[talk_id]:.1f}s, the dataset's source lasted {expected:.1f}s; "
                  "timestamps may be offset for this talk")

    with open(args.ted_csv, newline="", encoding="utf-8") as fh:
        rows = list(csv.DictReader(fh))
    done = 0
    for row in rows:
        talk_id = row["talk_id"]
        if talk_id not in lengths:
            continue
        start = max(0.0, float(row["start_sec"]) - args.pad)
        end = min(lengths[talk_id], float(row["end_sec"]) + args.pad)
        subprocess.run([
            args.ffmpeg, "-y", "-loglevel", "error", "-ss", f"{start:.3f}", "-i", str(talk_dir / f"{talk_id}.mp4"),
            "-t", f"{end - start:.3f}", "-c:v", "libx264", "-crf", "18", "-c:a", "aac",
            "-movflags", "+faststart", str(out_dir / f"{row['id']}.mp4"),
        ], check=True)
        done += 1
    print(f"wrote {done} clips to {out_dir}")


if __name__ == "__main__":
    main()