File size: 13,378 Bytes
16231ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env python3
"""Cut YFCC100M street-level videos into synchronized 10-second candidates (stage 2b).

Same pairing design as the other video datasets:
every 10-second audio clip gets several candidate frames taken from inside the same
10 seconds of the same video (--candidate-fps), so extract_imagebind.py followed by
select_best_image_audio_pairs.py --image-key-column segment_id keeps the one frame with
the highest ImageBind image-audio cosine per clip. The training-only cosine cut
(--min-train-pair-cosine 0.2 in the direct_aq trainers) applies afterwards as usual.

Per video: needs an audio stream; audio -> 48 kHz mono 16-bit PCM; up to --max-segments
complete 10-second segments spread evenly over the video; segments quieter than
--min-rms-dbfs are dropped (muted / silent soundtracks). Frames are scaled so the long
side is --frame-size (ImageBind uses 224 px). Videos are not panoramas, so each frame is
one view (candidate_view_index 0). Per-video results are cached in
<output-root>/_status/<video_id>.json, so re-runs only process new videos.
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts")
_sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"]

import argparse
import json
import math
import shutil
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

import numpy as np
import pandas as pd
import soundfile as sf
from tqdm import tqdm


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--videos", type=Path, default=Path("data/yfcc_street_videos.csv"))
    p.add_argument("--video-root", type=Path, required=True, help="download_yfcc_videos.py --out-root")
    p.add_argument("--output-root", type=Path, required=True)
    p.add_argument("--output-manifest", type=Path, default=Path("data/yfcc_street_candidates.csv"))
    p.add_argument("--ffmpeg", default="ffmpeg")
    p.add_argument("--ffprobe", default="ffprobe")
    p.add_argument("--clip-seconds", type=float, default=10.0)
    p.add_argument("--candidate-fps", type=float, default=1.0)
    p.add_argument("--max-segments", type=int, default=6)
    p.add_argument("--min-rms-dbfs", type=float, default=-60.0)
    p.add_argument("--frame-size", type=int, default=640)
    p.add_argument("--workers", type=int, default=6)
    p.add_argument("--include-excluded", action="store_true")
    p.add_argument("--maximum-videos", type=int, default=0, help="debug: only the first N videos")
    return p.parse_args()


def run(cmd: list[str]) -> subprocess.CompletedProcess:
    return subprocess.run(cmd, capture_output=True, text=True)


def probe(path: Path, ffprobe: str) -> dict:
    r = run([ffprobe, "-v", "error", "-show_entries", "stream=codec_type,codec_name,sample_rate,channels:format=duration",
             "-of", "json", str(path)])
    if r.returncode:
        raise RuntimeError(f"ffprobe: {r.stderr.strip()[:300]}")
    info = json.loads(r.stdout)
    streams = info.get("streams", [])
    audio = [s for s in streams if s.get("codec_type") == "audio"]
    return {
        "duration": float(info.get("format", {}).get("duration") or 0),
        "has_video": any(s.get("codec_type") == "video" for s in streams),
        "audio": audio[0] if audio else None,
    }


def evenly(n_available: int, n_keep: int) -> list[int]:
    if n_available <= n_keep:
        return list(range(n_available))
    return sorted({int(round(i * (n_available - 1) / (n_keep - 1))) for i in range(n_keep)}) if n_keep > 1 else [n_available // 2]


def process(video: dict, args: argparse.Namespace) -> dict:
    vid = video["video_id"]
    status_file = args.output_root / "_status" / f"{vid}.json"
    if status_file.exists():
        return json.loads(status_file.read_text(encoding="utf-8"))
    src = args.video_root / video["hash"][:3] / f"{video['hash']}.mp4"
    out = args.output_root / vid
    result = {"video_id": vid, "status": "ok", "rows": [], "segments_kept": 0, "segments_silent": 0}
    try:
        if not src.exists():
            raise FileNotFoundError("mp4 not downloaded")
        info = probe(src, args.ffprobe)
        if not info["has_video"]:
            raise RuntimeError("no video stream")
        if info["audio"] is None:
            result["status"] = "no_audio"
            raise StopIteration
        result["audio_codec"] = info["audio"].get("codec_name")
        result["audio_sample_rate"] = info["audio"].get("sample_rate")
        out.mkdir(parents=True, exist_ok=True)
        mono = out / "mono_48k.wav"
        r = run([args.ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-i", str(src), "-vn",
                 "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", str(mono)])
        if r.returncode or not mono.exists():
            raise RuntimeError(f"audio decode: {r.stderr.strip()[:300]}")
        audio_dur = sf.info(mono).duration
        common = min(audio_dur, info["duration"] or audio_dur)
        n_avail = math.floor((common + 1e-6) / args.clip_seconds)
        if n_avail < 1:
            result["status"] = "too_short"
            raise StopIteration
        chosen = evenly(n_avail, args.max_segments)
        per_seg = max(1, round(args.clip_seconds * args.candidate_fps))
        clip_n = round(args.clip_seconds * 48000)
        with sf.SoundFile(mono) as f:
            for seg in chosen:
                seg_id = f"{vid}_{seg:03d}"
                start = seg * args.clip_seconds
                f.seek(seg * clip_n)
                x = f.read(clip_n, dtype="float32", always_2d=False)
                if len(x) != clip_n:
                    continue
                rms = float(np.sqrt(np.mean(np.square(x), dtype=np.float64)))
                dbfs = 20 * math.log10(max(rms, 1e-12))
                if dbfs < args.min_rms_dbfs:
                    result["segments_silent"] += 1
                    continue
                clip = out / "audio_10s" / f"{seg_id}.wav"
                clip.parent.mkdir(parents=True, exist_ok=True)
                if not clip.exists():
                    sf.write(clip, x, 48000, subtype="PCM_16")
                frames_dir = out / "candidate_frames"
                frames_dir.mkdir(parents=True, exist_ok=True)
                pattern = frames_dir / f"{seg_id}_frame%02d.jpg"
                expected = [frames_dir / f"{seg_id}_frame{i:02d}.jpg" for i in range(per_seg)]
                if not all(p.exists() for p in expected):
                    # Sample at the centre of each 1/fps interval inside this segment.
                    offset = 0.5 / args.candidate_fps
                    scale = (f"scale='if(gt(iw,ih),{args.frame_size},-2)':'if(gt(iw,ih),-2,{args.frame_size})'")
                    r = run([args.ffmpeg, "-hide_banner", "-loglevel", "error", "-y",
                             "-ss", f"{start + offset:.3f}", "-i", str(src), "-t", f"{args.clip_seconds - offset:.3f}",
                             "-vf", f"fps={args.candidate_fps:g},{scale}", "-frames:v", str(per_seg),
                             "-start_number", "0", "-q:v", "3", str(pattern)])
                    if r.returncode:
                        raise RuntimeError(f"frames: {r.stderr.strip()[:300]}")
                frames = [p for p in expected if p.exists() and p.stat().st_size > 0]
                if not frames:
                    continue
                result["segments_kept"] += 1
                for i, frame in enumerate(frames):
                    result["rows"].append({
                        "photo_id": f"{seg_id}_frame{i:02d}_view0",
                        "photo_path": str(frame.resolve()),
                        "audio_path": str(clip.resolve()),
                        "segment_id": seg_id,
                        "segment_index": seg,
                        "segment_start_seconds": start,
                        "candidate_frame_index": i,
                        "candidate_timestamp_seconds": start + (i + 0.5) / args.candidate_fps,
                        "candidate_view_index": 0,
                        "segment_rms_dbfs": round(dbfs, 2),
                    })
        mono.unlink(missing_ok=True)
        if not result["rows"]:
            result["status"] = "no_usable_segments"
    except StopIteration:
        pass
    except Exception as exc:  # recorded, video skipped
        result["status"] = "error"
        result["error"] = str(exc)[:500]
    status_file.parent.mkdir(parents=True, exist_ok=True)
    status_file.write_text(json.dumps(result), encoding="utf-8")
    return result


def main() -> None:
    args = parse_args()
    for exe in (args.ffmpeg, args.ffprobe):
        if shutil.which(exe) is None and not Path(exe).exists():
            raise SystemExit(f"Executable not found: {exe}")
    videos = pd.read_csv(args.videos, dtype={"hash": str, "uid": str}, low_memory=False)
    if not args.include_excluded:
        videos = videos[~videos.split.astype(str).str.startswith("excluded")]
    if args.maximum_videos:
        videos = videos.head(args.maximum_videos)
    meta = {r["video_id"]: r for r in videos.to_dict("records")}
    results = []
    with ThreadPoolExecutor(args.workers) as pool:
        futures = [pool.submit(process, v, args) for v in meta.values()]
        for fut in tqdm(as_completed(futures), total=len(futures), desc="YFCC candidates"):
            results.append(fut.result())

    rows = []
    for res in results:
        v = meta[res["video_id"]]
        for row in res.get("rows", []):
            row.update({
                "recording_id": v["video_id"],
                "parent_location_id": f"yfcc:{v['video_id']}",
                "location_id": row["segment_id"],
                "owner_or_session": v["split_group"],
                "split_group": v["split_group"],
                "split": v["split"],
                "dataset": "yfcc100m_street",
                "source_dataset": "yfcc100m_street",
                "training_dataset": "yfcc100m_street",
                "pairing_status": "candidate_synchronized_same_10s_segment",
                "pairing_strength": "strong",
                "use_for_training": True,
                "panorama": False,
                "source_panorama": False,
                "lat": v["latitude"], "lon": v["longitude"], "geotag_accuracy": v["accuracy"],
                "yfcc_photoid": v["photoid"], "yfcc_hash": v["hash"], "uploader_uid": v["uid"],
                "datetaken": v["datetaken"], "audio_codec": res.get("audio_codec"),
                "license": v["licensename"], "license_url": v["licenseurl"],
                "license_nd": v["license_nd"], "license_commercial": v["license_commercial"],
                "source_url": v["pageurl"],
                "source_video_path": str((args.video_root / v["hash"][:3] / f"{v['hash']}.mp4").resolve()),
            })
            rows.append(row)
    frame = pd.DataFrame(rows)
    if frame.empty:
        raise SystemExit("No candidates were prepared")
    if frame.photo_id.duplicated().any():
        raise RuntimeError("Duplicate photo IDs")
    if frame.groupby("split_group").split.nunique().max() != 1:
        raise RuntimeError("An uploader crosses splits")
    if frame.groupby("segment_id").audio_path.nunique().max() != 1:
        raise RuntimeError("A segment maps to multiple clips")
    args.output_manifest.parent.mkdir(parents=True, exist_ok=True)
    frame.to_csv(args.output_manifest, index=False)
    status = pd.Series([r["status"] for r in results]).value_counts().to_dict()
    errors = [{"video_id": r["video_id"], "error": r.get("error")} for r in results if r["status"] == "error"][:50]
    seg = frame.drop_duplicates("segment_id")
    summary = {
        "dataset": "yfcc100m_street",
        "videos_input": len(meta),
        "video_status": status,
        "videos_with_candidates": int(frame.recording_id.nunique()),
        "segments": int(len(seg)),
        "segments_silent_dropped": int(sum(r.get("segments_silent", 0) for r in results)),
        "candidate_rows": int(len(frame)),
        "split_segments": seg.split.value_counts().to_dict(),
        "split_videos": frame.drop_duplicates("recording_id").split.value_counts().to_dict(),
        "audio_codecs": pd.Series([r.get("audio_codec") for r in results if r.get("audio_codec")]).value_counts().to_dict(),
        "clip_seconds": args.clip_seconds, "candidate_fps": args.candidate_fps,
        "max_segments_per_video": args.max_segments, "min_rms_dbfs": args.min_rms_dbfs,
        "audio_rule": "first audio stream downmixed to 48 kHz mono PCM 16-bit (source is lossy consumer audio)",
        "pairing_rule": "one highest-ImageBind-cosine candidate frame per synchronized 10-second clip",
        "split_rule": "uploader-grouped split + 1 km buffer (select_yfcc_candidates.py)",
        "first_errors": errors,
    }
    args.output_manifest.with_suffix(".quality.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print(json.dumps({k: v for k, v in summary.items() if k != "first_errors"}, indent=2))
    print(f"Wrote {args.output_manifest}")


if __name__ == "__main__":
    main()