File size: 27,835 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#!/usr/bin/env python3
"""One-to-one image-clip pairing by best ImageBind cosine: every view keeps at most one clip and
every clip at most one view.

Drop-in alternative to select_best_image_audio_pairs.py (same input: the per-view candidate table
with ImageBind paths). Matching rules (--matching):
  greedy     (default) all candidate edges in descending cosine order; an edge is taken when both
             its view and its clip are still free. Each pair is the most similar one available,
             and a view whose best clip went to a more similar view takes its next free clip.
  best_only  each view proposes only its single most similar clip; a clip proposed by several
             views keeps the most similar one and the other views are dropped (no fallback).
  hungarian  maximum total cosine per connected group (may give a view a non-best clip).
Video sources (--video-frames, on by default) are handled by time first, then similarity:
  * per video, 4 frames (videos shorter than --long-video-seconds) or 6 frames, evenly spaced;
  * every view of a chosen frame may pair only with clips whose midpoint lies within
    --time-window-seconds of the frame (for TAU, which has no time offsets, only its own clip);
  * greedy best-cosine one-to-one matching, so the four views of a panorama frame get four
    different clips and no clip is used twice.
Other sources (e.g. Ann Arbor/Detroit) are matched by similarity only among their candidates.

Optional --max-pairs-per-video limits how many pairs one video (or recording spot) contributes,
keeping pairs spread evenly in time. Use the same cap for every split so validation is not
dominated by a few long 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 re
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import numpy as np
import pandas as pd
from scipy.optimize import linear_sum_assignment
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components

from select_best_image_audio_pairs import embedding


def normalized_path(value) -> str:
    """Case- and slash-insensitive key that does not depend on the working directory."""
    return str(value).replace("/", "\\").casefold()

DEFAULT_VIDEO_KEYS = {
    "360x_outdoor": "recording_id",
    "tau_urban_audio_visual_2021_nonoverlap": "location",
    "urbansas_whole": "parent_location_id",
    "qoevave_outdoor": "recording_id",
    "yfcc100m_street": "recording_id",
    "sonicurban": "recording_id",
}
TIME_COLUMNS = (
    "segment_start_seconds", "clip_start_seconds", "selected_frame_timestamp_seconds",
    "segment_index", "clip_index",
)


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--manifest", type=Path, required=True)
    p.add_argument("--output", type=Path, required=True)
    p.add_argument("--image-key-column", default="view_id")
    p.add_argument("--clip-key-column", default="audio_path")
    p.add_argument("--vision-column", default="imagebind_vision_path")
    p.add_argument("--audio-column", default="imagebind_audio_path")
    p.add_argument("--view-token-column", default=None, help="optional: column with per-view ImageBind vector files (view_paths + view_global_embeddings)")
    p.add_argument("--view-path-column", default="view_path")
    p.add_argument("--known-cosines", type=Path, default=None,
                   help="CSV with image key, clip key and image_audio_cosine already computed by the same "
                        "method (e.g. the previous view_clip_selected.csv); only the other edges are scored.")
    p.add_argument("--matching", choices=("greedy", "best_only", "hungarian"), default="greedy")
    p.add_argument("--exclude-dataset", action="append", default=None,
                   help="Datasets to leave out entirely (default: supplied_sipset).")
    p.add_argument("--subset-output", type=Path, default=None,
                   help="Only write the rows needed after frame sampling (chosen frame views plus one row "
                        "per clip of each video) and exit, so ImageBind runs on a small set.")
    p.add_argument("--video-frames", action=argparse.BooleanOptionalAction, default=True,
                   help="Sample frames per video and pair them with time-nearby clips (see docstring).")
    p.add_argument("--short-video-frames", type=int, default=4)
    p.add_argument("--long-video-frames", type=int, default=6)
    p.add_argument("--long-video-seconds", type=float, default=120.0,
                   help="Videos at least this long get --long-video-frames frames.")
    p.add_argument("--frames-override", action="append", default=[],
                   help="DATASET=N frames per video for that dataset, replacing the 4/6 rule "
                        "(e.g. binaural_perception_outdoor=4 to reduce near-repeat pairs).")
    p.add_argument("--time-window-seconds", type=float, default=20.0,
                   help="Max distance between a frame and a candidate clip's midpoint.")
    p.add_argument("--max-pairs-per-video", type=int, default=None)
    p.add_argument("--per-clip-video", action="append", default=[],
                   help="DATASET (repeatable): treat every clip of this dataset as its own video, so each clip "
                        "keeps its own frame (e.g. tau_urban_audio_visual_2021_nonoverlap: TAU clips are separate recordings).")
    p.add_argument("--video-key", action="append", default=[],
                   help="dataset=column (repeatable); overrides the built-in video grouping.")
    p.add_argument("--cap-preview", type=int, nargs="*", default=[],
                   help="Report how many pairs each of these caps would keep.")
    p.add_argument("--path-from", default=None, help="Rewrite stored paths (for running outside Windows).")
    p.add_argument("--path-to", default=None)
    p.add_argument("--workers", type=int, default=16)
    p.add_argument("--embedding-cache", type=Path, default=None,
                   help="npz cache of loaded audio/view vectors; lets an interrupted run resume.")
    p.add_argument("--time-budget", type=float, default=None,
                   help="Seconds to spend loading vectors before saving the cache and exiting (code 3).")
    p.add_argument("--selection-method", default="one_to_one_best_cosine")
    return p.parse_args()


def rewrite(path: str, args) -> str:
    path = str(path)
    if args.path_from and path.startswith(args.path_from):
        path = (args.path_to + path[len(args.path_from):]).replace("\\", "/")
    return path


def compute_cosines(frame: pd.DataFrame, args) -> np.ndarray:
    """Same vectors as select_best_image_audio_pairs.py (per-view token cache first, then image file)."""
    token_cache: dict[str, dict[str, np.ndarray]] = {}

    def load_tokens(path):
        result = {}
        try:
            with np.load(rewrite(path, args), allow_pickle=False) as archive:
                if {"view_paths", "view_global_embeddings"}.issubset(archive.files):
                    vectors = archive["view_global_embeddings"].astype(np.float32)
                    vectors /= np.clip(np.linalg.norm(vectors, axis=1, keepdims=True), 1e-9, None)
                    for view, vector in zip(archive["view_paths"], vectors):
                        result[normalized_path(view)] = vector
        except FileNotFoundError:
            pass
        return path, result

    def load_embedding(path):
        return path, embedding(rewrite(path, args))

    tokens = frame.get(args.view_token_column, pd.Series(dtype=str)).dropna().astype(str).unique()
    audio, token_cache = {}, {}
    cache = args.embedding_cache
    if cache is not None and cache.exists():
        with np.load(cache, allow_pickle=False) as archive:
            audio = dict(zip(archive["audio_paths"].tolist(), archive["audio_vectors"]))
            if "token_key_version" in archive.files and int(archive["token_key_version"]) == 2:
                for token, view, vector in zip(archive["token_paths"].tolist(), archive["token_views"].tolist(), archive["token_vectors"]):
                    token_cache.setdefault(token, {})[view] = vector
                for token in archive["token_done"].tolist():
                    token_cache.setdefault(token, {})
    view_paths = frame[args.view_path_column] if args.view_path_column in frame else frame[args.image_key_column]
    token_paths = frame[args.view_token_column] if args.view_token_column in frame else pd.Series([None] * len(frame))
    start, out_of_time = time.time(), False

    def run(jobs, loader, store):
        nonlocal out_of_time
        with ThreadPoolExecutor(args.workers) as pool:
            for begin in range(0, len(jobs), 300):
                if args.time_budget and time.time() - start > args.time_budget:
                    out_of_time = True
                    return
                store.update(pool.map(loader, jobs[begin:begin + 300]))

    missing_tokens = [t for t in tokens if t not in token_cache]
    missing_audio = [a for a in frame[args.audio_column].astype(str).unique() if a not in audio]
    run(missing_tokens, load_tokens, token_cache)
    run(missing_audio, load_embedding, audio)
    # Image-file vectors for views without a per-view token (stored with a "V::" prefix).
    need_vision = []
    if not out_of_time:
        for token_path, view_path, vision_path in zip(token_paths, view_paths, frame[args.vision_column]):
            if not (isinstance(token_path, str) and normalized_path(view_path) in token_cache.get(token_path, {})):
                need_vision.append(str(vision_path))
        need_vision = sorted({v for v in need_vision if v.lower() != "nan" and "V::" + v not in audio})
        run(need_vision, lambda v: ("V::" + v, embedding(rewrite(v, args))), audio)
    if cache is not None and (missing_tokens or missing_audio or need_vision):
        cache.parent.mkdir(parents=True, exist_ok=True)
        flat = [(t, v, vec) for t, views in token_cache.items() for v, vec in views.items()]
        np.savez(
            cache, audio_paths=np.asarray(list(audio), dtype=str),
            audio_vectors=np.stack(list(audio.values())) if audio else np.zeros((0, 1024), np.float32),
            token_paths=np.asarray([f[0] for f in flat], dtype=str), token_views=np.asarray([f[1] for f in flat], dtype=str),
            token_vectors=np.stack([f[2] for f in flat]) if flat else np.zeros((0, 1024), np.float32),
            token_done=np.asarray(list(token_cache), dtype=str), token_key_version=np.asarray(2),
        )
    if out_of_time:
        print(f"Time budget reached after loading {len(audio)} audio/image and {len(token_cache)} token files. "
              "Cache saved; rerun to continue.")
        raise SystemExit(3)
    scores = np.empty(len(frame), dtype=np.float32)
    for position, (token_path, view_path, vision_path, audio_path) in enumerate(zip(
        token_paths, view_paths, frame[args.vision_column], frame[args.audio_column]
    )):
        vector = None
        if isinstance(token_path, str) and token_path in token_cache:
            vector = token_cache[token_path].get(normalized_path(view_path))
        if vector is None:
            vector = audio.get("V::" + str(vision_path))
        if vector is None:
            scores[position] = np.nan  # no image vector available: edge is dropped
            continue
        scores[position] = float(vector @ audio[str(audio_path)])
    return scores


def match_greedy(frame: pd.DataFrame, image_key: str, clip_key: str, fallback: bool = True) -> np.ndarray:
    """Greedy best-cosine one-to-one pairing (stable tie-break on row order)."""
    cosine = frame.image_audio_cosine.to_numpy(np.float64)
    order = np.lexsort((np.arange(len(frame)), -cosine))
    images = frame[image_key].astype(str).to_numpy()
    clips = frame[clip_key].astype(str).to_numpy()
    if not fallback:
        best = frame.assign(_row=np.arange(len(frame))).sort_values(
            ["image_audio_cosine", "_row"], ascending=[False, True], kind="mergesort"
        ).drop_duplicates(image_key)["_row"].to_numpy()
        allowed = np.zeros(len(frame), bool)
        allowed[best] = True
        order = order[allowed[order]]
    used_images, used_clips, keep = set(), set(), []
    for row in order:
        if images[row] in used_images or clips[row] in used_clips:
            continue
        used_images.add(images[row]); used_clips.add(clips[row]); keep.append(row)
    return np.sort(np.asarray(keep, dtype=np.int64))


def match(frame: pd.DataFrame, image_key: str, clip_key: str, method: str = "hungarian") -> np.ndarray:
    if method == "greedy":
        return match_greedy(frame, image_key, clip_key, fallback=True)
    if method == "best_only":
        return match_greedy(frame, image_key, clip_key, fallback=False)
    """Return row positions of a maximum-weight one-to-one matching per connected component."""
    images, image_index = np.unique(frame[image_key].astype(str), return_inverse=True)
    clips, clip_index = np.unique(frame[clip_key].astype(str), return_inverse=True)
    n_images = len(images)
    graph = coo_matrix(
        (np.ones(len(frame)), (image_index, n_images + clip_index)),
        shape=(n_images + len(clips),) * 2,
    )
    _, component = connected_components(graph, directed=False)
    edge_component = component[image_index]
    keep = []
    cosine = frame.image_audio_cosine.to_numpy(np.float64)
    order = np.argsort(edge_component, kind="stable")
    boundaries = np.flatnonzero(np.diff(edge_component[order])) + 1
    for rows in np.split(order, boundaries):
        if len(rows) == 1:
            keep.append(rows[0])
            continue
        local_images, li = np.unique(image_index[rows], return_inverse=True)
        local_clips, lc = np.unique(clip_index[rows], return_inverse=True)
        cost = np.full((len(local_images), len(local_clips)), 1e6)
        best_row = np.full(cost.shape, -1)
        for position, (a, b) in enumerate(zip(li, lc)):
            value = -cosine[rows[position]]
            if value < cost[a, b]:
                cost[a, b], best_row[a, b] = value, rows[position]
        r, c = linear_sum_assignment(cost)
        keep.extend(best_row[a, b] for a, b in zip(r, c) if cost[a, b] < 1e5)
    return np.sort(np.asarray(keep, dtype=np.int64))


def spread_cap(selected: pd.DataFrame, cap: int, video_keys: dict[str, str]) -> pd.Series:
    """Boolean mask keeping at most `cap` pairs per video, evenly spaced in time."""
    keep = pd.Series(True, index=selected.index)
    for dataset, column in video_keys.items():
        subset = selected[selected.training_dataset.astype(str).eq(dataset)]
        if subset.empty or column not in subset:
            continue
        time_column = next((c for c in TIME_COLUMNS if c in subset and subset[c].notna().any()), None)
        for _, group in subset.groupby(subset[column].astype(str)):
            if len(group) <= cap:
                continue
            ordered = group.sort_values(time_column, kind="mergesort") if time_column else group
            chosen = ordered.index[np.unique(np.round(np.linspace(0, len(ordered) - 1, cap)).astype(int))]
            keep.loc[group.index.difference(chosen)] = False
    return keep


# How each video source is ordered in time. "stem_suffix": clip start = 10 s x the trailing
# _N of the audio file name, video = the name without it. "own_clip": no time offsets
# (each clip is its own short video), so a frame may only pair with its own clip.
VIDEO_SOURCES = {
    "360x_outdoor": {"video": "recording_id", "clip_start": "segment_start_seconds"},
    "qoevave_outdoor": {"video": "recording_id", "clip_start": "segment_start_seconds"},
    "yfcc100m_street": {"video": "recording_id", "clip_start": "segment_start_seconds"},
    "urbansas_whole": {"video": "stem_suffix", "clip_start": "stem_suffix"},
    "tau_urban_audio_visual_2021_nonoverlap": {"video": "location", "clip_start": "own_clip"},
    "binaural_perception_outdoor": {"video": "recording_id", "clip_start": "segment_start_seconds"},
    "sonicurban": {"video": "recording_id", "clip_start": "segment_start_seconds"},
}
FRAME_SUFFIX = r"_(?:yaw\d+|view\d+)(?=\.\w+$)"  # strip the view part of a split-panorama file name
VIEW_SIDE_HINTS = ("view", "photo", "vision", "frame", "yaw", "attention", "localization_token", "openclip", "image")


def _stem(path) -> str:
    return re.split(r"[\\/]", str(path))[-1].rsplit(".", 1)[0]


def build_video_edges(frame: pd.DataFrame, args) -> pd.DataFrame:
    """Replace candidate edges of video sources by (sampled frame view) x (time-nearby clip) edges."""
    view_columns = [c for c in frame.columns if any(h in c.lower() for h in VIEW_SIDE_HINTS)
                    and c not in ("imagebind_audio_path",)]
    pieces, report, subset_rows = [], {}, []
    overrides = {item.split("=", 1)[0]: int(item.split("=", 1)[1]) for item in args.frames_override}
    for dataset, spec in VIDEO_SOURCES.items():
        rows = frame[frame.training_dataset.astype(str).eq(dataset)].copy()
        if rows.empty:
            continue
        stems = rows[args.clip_key_column].map(_stem)
        if dataset in set(getattr(args, "per_clip_video", []) or []):
            rows["_video"] = rows[args.clip_key_column].astype(str)
        elif spec["video"] == "stem_suffix":
            rows["_video"] = stems.str.replace(r"_\d+$", "", regex=True)
        else:
            rows["_video"] = rows[spec["video"]].astype(str)
        if spec["clip_start"] == "stem_suffix":
            rows["_clip_start"] = stems.str.extract(r"_(\d+)$")[0].astype(float) * 10.0
        elif spec["clip_start"] == "own_clip":
            rows["_clip_start"] = rows.groupby("_video")[args.clip_key_column].rank(method="dense") * 10.0 - 10.0
        else:
            rows["_clip_start"] = pd.to_numeric(rows[spec["clip_start"]], errors="coerce")
        offset = pd.Series(5.0, index=rows.index)
        if "selected_frame_timestamp_seconds" in rows:
            offset = pd.to_numeric(rows.selected_frame_timestamp_seconds, errors="coerce").fillna(offset)
        if "candidate_timestamp_seconds" in rows:
            absolute = pd.to_numeric(rows.candidate_timestamp_seconds, errors="coerce")
            offset = (absolute - rows._clip_start).where(absolute.notna(), offset)
        rows["_frame_time"] = rows._clip_start + offset.clip(0, 10)
        rows["_frame_key"] = rows[args.view_path_column if args.view_path_column in rows else "photo_path"].astype(str) \
            .str.replace(FRAME_SUFFIX, "", regex=True)
        clips = rows.drop_duplicates(args.clip_key_column)
        clip_side = [c for c in clips.columns if c not in view_columns]
        kept_frames = 0
        for video, group in rows.groupby("_video", sort=False):
            frames = group.drop_duplicates("_frame_key").sort_values(["_frame_time", "_frame_key"])
            video_clips = clips[clips._video.eq(video)]
            duration = float(video_clips._clip_start.max() - video_clips._clip_start.min() + 10.0)
            count = args.long_video_frames if duration >= args.long_video_seconds else args.short_video_frames
            count = overrides.get(dataset, count)
            # Centres of equal time slices (not the first/last moment), so end frames still have
            # clips on both sides of the +/- window for all four panorama views.
            k = min(count, len(frames))
            positions = np.unique(np.round((np.arange(k) + 0.5) / k * (len(frames) - 1)).astype(int))
            chosen = frames._frame_key.iloc[positions]
            kept_frames += len(chosen)
            views = group[group._frame_key.isin(set(chosen))].drop_duplicates(args.image_key_column)
            subset_rows.extend(views.index.tolist())
            subset_rows.extend(group.drop_duplicates(args.clip_key_column).index.tolist())
            for _, view in views.iterrows():
                if spec["clip_start"] == "own_clip":
                    near = video_clips[video_clips[args.clip_key_column].eq(view[args.clip_key_column])]
                else:
                    near = video_clips[(video_clips._clip_start + 5.0 - view._frame_time).abs()
                                       <= args.time_window_seconds + 1e-6]
                    if near.empty:
                        near = video_clips[video_clips[args.clip_key_column].eq(view[args.clip_key_column])]
                edge = near[clip_side].copy()
                for column in view_columns:
                    edge[column] = view[column]
                edge["frame_clip_time_offset_seconds"] = (near._clip_start + 5.0 - view._frame_time).to_numpy()
                pieces.append(edge)
        report[dataset] = {"videos": int(rows._video.nunique()), "frames_kept": kept_frames}
    other = frame[~frame.training_dataset.astype(str).isin(VIDEO_SOURCES)]
    edges = pd.concat([other] + pieces, ignore_index=True) if pieces else other.copy()
    edges = edges.drop(columns=[c for c in edges.columns if c.startswith("_")])
    edges = edges.drop_duplicates([args.image_key_column, args.clip_key_column]).reset_index(drop=True)
    edges.attrs["video_report"] = report
    edges.attrs["subset_rows"] = sorted(set(subset_rows))
    return edges


def main() -> None:
    args = parse_args()
    frame = pd.read_csv(args.manifest, low_memory=False)
    input_rows = len(frame)
    if "audio_target_status" in frame:
        frame = frame[frame.audio_target_status.fillna("").astype(str).str.lower().eq("ok")].copy()
    excluded = {name.casefold() for name in (args.exclude_dataset if args.exclude_dataset is not None else ["supplied_sipset"])}
    if "training_dataset" in frame and excluded:
        frame = frame[~frame.training_dataset.astype(str).str.casefold().isin(excluded)]
    frame = frame.reset_index(drop=True)
    video_report = {}
    if args.video_frames:
        before = len(frame)
        source = frame
        frame = build_video_edges(frame, args)
        video_report = frame.attrs.get("video_report", {})
        if args.subset_output is not None:
            other = source[~source.training_dataset.astype(str).isin(VIDEO_SOURCES)].index.tolist()
            subset = source.loc[sorted(set(frame.attrs["subset_rows"]) | set(other))]
            args.subset_output.parent.mkdir(parents=True, exist_ok=True)
            subset.to_csv(args.subset_output, index=False)
            print(json.dumps({"subset_rows": len(subset), "input_rows": len(source), "video_report": video_report,
                              "images": int(subset[args.image_key_column].nunique()),
                              "clips": int(subset[args.clip_key_column].nunique())}, indent=2))
            print(f"Wrote {args.subset_output}")
            return
        print(f"Video sources: {before} candidate edges -> {len(frame)} edges after frame sampling and time windows")
    frame["image_audio_cosine"] = np.nan
    if args.known_cosines is not None:
        known = pd.read_csv(args.known_cosines, usecols=[args.image_key_column, args.clip_key_column, "image_audio_cosine"])
        known = known.drop_duplicates([args.image_key_column, args.clip_key_column])
        lookup = frame[[args.image_key_column, args.clip_key_column]].merge(
            known, on=[args.image_key_column, args.clip_key_column], how="left")
        frame["image_audio_cosine"] = lookup.image_audio_cosine.to_numpy()
    todo = frame.image_audio_cosine.isna().to_numpy()
    print(f"{len(frame)} candidate edges; {int((~todo).sum())} cosines reused, scoring {int(todo.sum())}", flush=True)
    if todo.any():
        frame.loc[todo, "image_audio_cosine"] = compute_cosines(frame[todo].reset_index(drop=True), args)
    unscored = frame.image_audio_cosine.isna()
    if unscored.any():
        print(f"Dropping {int(unscored.sum())} edges without an image vector: "
              f"{frame[unscored].training_dataset.value_counts().to_dict()}")
        frame = frame[~unscored].reset_index(drop=True)
    frame["image_candidate_count"] = frame.groupby(args.image_key_column)[args.clip_key_column].transform("size")
    frame["clip_candidate_count"] = frame.groupby(args.clip_key_column)[args.image_key_column].transform("size")
    selected = frame.iloc[match(frame, args.image_key_column, args.clip_key_column, args.matching)].copy()
    matched_images = int(len(selected))
    assert not selected[args.image_key_column].duplicated().any(), "image used twice"
    assert not selected[args.clip_key_column].duplicated().any(), "clip used twice"

    video_keys = dict(DEFAULT_VIDEO_KEYS)
    for item in args.video_key:
        dataset, column = item.split("=", 1)
        video_keys[dataset] = column
    preview = {}
    for cap in args.cap_preview:
        mask = spread_cap(selected, cap, video_keys)
        preview[str(cap)] = selected[mask].training_dataset.value_counts().sort_index().to_dict()
    if args.max_pairs_per_video:
        selected = selected[spread_cap(selected, args.max_pairs_per_video, video_keys)].copy()
    selected["pair_selection_method"] = f"{args.selection_method}:{args.matching}"
    selected["clip_rank_for_view"] = (
        frame.groupby(args.image_key_column).image_audio_cosine.rank(ascending=False, method="first")
        .reindex(selected.index).astype(int).to_numpy()
    )
    selected["max_pairs_per_video"] = args.max_pairs_per_video
    selected = selected.reset_index(drop=True)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    selected.to_csv(args.output, index=False)

    def per_dataset(table):
        return table.training_dataset.value_counts().sort_index().to_dict()

    best_per_image = frame.loc[frame.groupby(args.image_key_column).image_audio_cosine.idxmax()]
    summary = {
        "input_rows": int(input_rows), "candidate_edges": int(len(frame)),
        "images": int(frame[args.image_key_column].nunique()),
        "clips": int(frame[args.clip_key_column].nunique()),
        "pairs_kept": int(len(selected)),
        "selection_method": args.selection_method, "matching": args.matching,
        "max_pairs_per_video": args.max_pairs_per_video,
        "video_frames": bool(args.video_frames),
        "video_rules": {"short_video_frames": args.short_video_frames, "long_video_frames": args.long_video_frames,
                        "long_video_seconds": args.long_video_seconds, "time_window_seconds": args.time_window_seconds,
                        "frames_override": args.frames_override},
        "video_report": video_report,
        "video_keys": video_keys,
        "previous_rule_pairs_by_dataset": per_dataset(best_per_image),
        "pairs_by_dataset": per_dataset(selected),
        "pairs_by_dataset_and_split": selected.groupby(["training_dataset", "split"]).size().unstack(fill_value=0).to_dict(orient="index"),
        "cap_preview_pairs_by_dataset": preview,
        "cosine_kept": {"mean": float(selected.image_audio_cosine.mean()),
                        "median": float(selected.image_audio_cosine.median())},
        "images_without_a_free_clip": int(frame[args.image_key_column].nunique() - matched_images),
        "pairs_after_matching_before_cap": matched_images,
    }
    args.output.with_suffix(".summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print(json.dumps({k: v for k, v in summary.items() if k != "pairs_by_dataset_and_split"}, indent=2))
    print(f"Wrote {args.output}")


if __name__ == "__main__":
    main()