File size: 10,751 Bytes
2394f31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/env python3
"""Cut the audio clips of meetween/mumospee_v3 from source videos you have downloaded.

The dataset contains no audio. Each row gives the YouTube video (`video_id`), the clip
interval (`start`, `end`, in seconds) and the relative path of the clip audio
(`audio_input_path`). This script takes a local copy of a source video and the dataset
rows of that video, and writes each clip to `<out-dir>/<audio_input_path>` as a 16 kHz
mono FLAC file, with the same processing that produced the dataset:

  1. decode the audio track of the video to 16 kHz mono 16-bit PCM with ffmpeg
     (ffmpeg -vn -ac 1 -ar 16000 -c:a pcm_s16le)
  2. take the samples from int(start * 16000) to int(end * 16000)
  3. write them as FLAC

Downloading the videos is up to you; the script does not access YouTube.

Requirements: Python 3.9+, pyarrow, soundfile, and the ffmpeg program.

Rows (--rows) can be a Parquet file, folder or glob of the dataset (for example a local
copy made with `huggingface-cli download meetween/mumospee_v3 --repo-type dataset
--include "data/asr/nl/*" --local-dir mumospee`), or a CSV / JSON Lines file with at least the columns video_id,
clip_id, start, end and audio_input_path.

Examples:
  # one video
  python make_clips.py --rows mumospee/data/asr/nl --video downloads/-H9G_NHn4Xc.mp4 \\
      --video-id -H9G_NHn4Xc --out-dir clips

  # all videos in a folder; the video ID is read from each file name
  # (<video_id>.<ext>, <video_id>_<anything>.<ext> or <anything>[<video_id>].<ext>)
  python make_clips.py --rows mumospee/data/asr/nl --videos-dir downloads --out-dir clips

The audio of a row is then clips/<audio_input_path>. A report of every clip (written,
skipped, failed) is appended to <out-dir>/make_clips_report.csv.
"""
import argparse
import csv
import glob
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path

import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.dataset as ds

SAMPLE_RATE = 16000
REQUIRED = ["video_id", "clip_id", "start", "end", "audio_input_path"]
MIN_SAMPLES = int(0.2 * SAMPLE_RATE)       # clips shorter than this were never written
DURATION_TOLERANCE = 0.01                  # seconds; a shorter clip means the source is shorter
VIDEO_ID = re.compile(r"[A-Za-z0-9_-]{11}")
VIDEO_SUFFIXES = {".mp4", ".mkv", ".webm", ".m4a", ".mp3", ".opus", ".ogg", ".wav", ".flac", ".aac", ".mov"}
REPORT_NAME = "make_clips_report.csv"


# ---------------------------------------------------------------- dataset rows

def load_rows(spec, video_ids):
    """Rows of the given videos (pyarrow Table with the REQUIRED columns), sorted by clip."""
    paths = sorted(glob.glob(spec)) if any(ch in spec for ch in "*?[") else [spec]
    if not paths:
        sys.exit(f"no files match {spec}")
    tables = []
    for p in paths:
        p = Path(p)
        if p.suffix in (".csv", ".jsonl", ".json"):
            import pyarrow.csv as pcsv
            import pyarrow.json as pjson
            t = (pcsv.read_csv(p) if p.suffix == ".csv" else pjson.read_json(p))
            missing = [c for c in REQUIRED if c not in t.column_names]
            if missing:
                sys.exit(f"{p}: missing columns {missing}")
            t = t.select(REQUIRED)
            t = t.filter(pc.is_in(t["video_id"].cast(pa.string()), value_set=pa.array(sorted(video_ids))))
        else:
            d = ds.dataset(str(p), format="parquet")
            missing = [c for c in REQUIRED if c not in d.schema.names]
            if missing:
                sys.exit(f"{p}: missing columns {missing}")
            t = d.to_table(columns=REQUIRED,
                           filter=ds.field("video_id").isin(sorted(video_ids)))
        tables.append(t.cast(pa.schema([("video_id", pa.string()), ("clip_id", pa.string()),
                                        ("start", pa.float64()), ("end", pa.float64()),
                                        ("audio_input_path", pa.string())])))
    t = pa.concat_tables(tables)
    return t.sort_by([("video_id", "ascending"), ("clip_id", "ascending")])


def video_id_from_name(path):
    """<id>.<ext>, <id>_<anything>.<ext> or <anything>[<id>].<ext> -> id (or None)."""
    stem = Path(path).stem
    m = re.search(r"\[([A-Za-z0-9_-]{11})\]", stem)
    if m:
        return m.group(1)
    if VIDEO_ID.fullmatch(stem):
        return stem
    if len(stem) > 11 and VIDEO_ID.fullmatch(stem[:11]) and stem[11] in "_.":
        return stem[:11]
    return None


# ---------------------------------------------------------------- cutting

def decode(ffmpeg, video_path, wav_path):
    """Audio track -> 16 kHz mono 16-bit PCM WAV (the decoding used for the dataset)."""
    r = subprocess.run([ffmpeg, "-nostdin", "-y", "-vn", "-i", str(video_path), "-ac", "1",
                        "-ar", str(SAMPLE_RATE), "-c:a", "pcm_s16le", str(wav_path)],
                       capture_output=True, text=True)
    if r.returncode != 0:
        raise RuntimeError(f"ffmpeg failed: {r.stderr.strip().splitlines()[-1] if r.stderr.strip() else r.returncode}")


def cut_video(video_path, video_id, rows, out_dir, ffmpeg, overwrite, tmp_root):
    """Write the clips of one video. Returns report records."""
    import soundfile as sf
    records = []
    todo = []
    for clip_id, start, end, rel in zip(*(rows[c].to_pylist() for c in ("clip_id", "start", "end", "audio_input_path"))):
        target = out_dir / rel
        if target.exists() and not overwrite:
            records.append((video_id, clip_id, "skipped", "exists"))
        else:
            todo.append((clip_id, start, end, target))
    if not todo:
        return records
    with tempfile.TemporaryDirectory(dir=tmp_root) as tmp:
        wav = Path(tmp) / f"{video_id}.wav"
        try:
            decode(ffmpeg, video_path, wav)
        except RuntimeError as e:
            return records + [(video_id, c[0], "failed", str(e)) for c in todo]
        with sf.SoundFile(str(wav)) as f:
            n_frames = f.frames
            for clip_id, start, end, target in todo:
                a = int(start * SAMPLE_RATE)
                b = min(n_frames, int(end * SAMPLE_RATE))
                if b - a < MIN_SAMPLES:
                    records.append((video_id, clip_id, "failed",
                                    f"source audio ends at {n_frames / SAMPLE_RATE:.2f} s, before the clip"))
                    continue
                f.seek(a)
                audio = f.read(b - a, dtype="int16")
                target.parent.mkdir(parents=True, exist_ok=True)
                part = target.with_name(target.name + ".part")
                sf.write(str(part), audio, SAMPLE_RATE, format="FLAC", subtype="PCM_16")
                os.replace(part, target)
                short = (end - start) - (b - a) / SAMPLE_RATE
                note = (f"shorter than the row by {short:.2f} s (source audio ends at "
                        f"{n_frames / SAMPLE_RATE:.2f} s)") if short > DURATION_TOLERANCE else ""
                records.append((video_id, clip_id, "written", note))
    return records


# ---------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--rows", required=True,
                    help="dataset rows: Parquet file, folder or glob; or a CSV / JSON Lines file")
    src = ap.add_mutually_exclusive_group(required=True)
    src.add_argument("--video", help="one local video or audio file")
    src.add_argument("--videos-dir", help="folder of local video or audio files, named by video ID")
    ap.add_argument("--video-id", help="video ID of --video (default: read from the file name)")
    ap.add_argument("--out-dir", required=True, help="output root; clips are written to <out-dir>/<audio_input_path>")
    ap.add_argument("--ffmpeg", default=shutil.which("ffmpeg") or "ffmpeg", help="ffmpeg program (default: %(default)s)")
    ap.add_argument("--overwrite", action="store_true", help="rewrite clips that already exist")
    ap.add_argument("--tmp-dir", help="folder for the temporary WAV of one video (default: system temp)")
    args = ap.parse_args()

    if not shutil.which(args.ffmpeg) and not Path(args.ffmpeg).exists():
        sys.exit(f"ffmpeg not found: {args.ffmpeg} (install ffmpeg or pass --ffmpeg)")

    # local videos -> video IDs
    videos = {}
    if args.video:
        vid = args.video_id or video_id_from_name(args.video)
        if not vid:
            sys.exit("cannot read the video ID from the file name; pass --video-id")
        videos[vid] = Path(args.video)
    else:
        for p in sorted(Path(args.videos_dir).iterdir()):
            if p.suffix.lower() in VIDEO_SUFFIXES:
                vid = video_id_from_name(p)
                if vid and vid not in videos:
                    videos[vid] = p
        if not videos:
            sys.exit(f"no video files named by video ID in {args.videos_dir}")
    for p in videos.values():
        if not p.exists():
            sys.exit(f"not found: {p}")

    rows = load_rows(args.rows, set(videos))
    by_video = {}
    vids = rows["video_id"].to_pylist()
    for i, v in enumerate(vids):
        by_video.setdefault(v, []).append(i)
    without_rows = sorted(set(videos) - set(by_video))
    print(f"{len(videos)} video file(s); {rows.num_rows:,} clips of {len(by_video)} video(s) in the rows"
          + (f"; no rows for {len(without_rows)} video(s): {without_rows[:5]}" if without_rows else ""), flush=True)

    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    report = out_dir / REPORT_NAME
    new_report = not report.exists()
    counts = {}
    t0 = time.time()
    with report.open("a", newline="", encoding="utf-8") as rf:
        w = csv.writer(rf)
        if new_report:
            w.writerow(["video_id", "clip_id", "status", "note"])
        for k, (vid, idx) in enumerate(sorted(by_video.items()), 1):
            recs = cut_video(videos[vid], vid, rows.take(idx), out_dir, args.ffmpeg, args.overwrite, args.tmp_dir)
            w.writerows(recs)
            rf.flush()
            for r in recs:
                counts[r[2]] = counts.get(r[2], 0) + 1
            print(f"  [{k}/{len(by_video)}] {vid}: " + ", ".join(
                f"{s} {sum(1 for r in recs if r[2] == s)}" for s in ("written", "skipped", "failed")
                if any(r[2] == s for r in recs)), flush=True)
    summary = ", ".join(f"{k} {v:,}" for k, v in sorted(counts.items())) or "no clips to cut"
    print(f"done in {time.time() - t0:.0f} s: {summary}; report: {report}")
    if counts.get("failed"):
        sys.exit(1)


if __name__ == "__main__":
    main()