File size: 11,367 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
#!/usr/bin/env python3
"""Pre-download environment screen for YFCC100M videos, using the mirror's keyframes.

The Multimedia Commons mirror stores small JPEG keyframes for every video at
data/videos/keyframes/<h[:3]>/<h[3:6]>/<hash>-NNN.jpg (~20-50 KB each). For each
selected video this script lists them, downloads up to --keyframes evenly spaced ones,
and scores them with exactly the same OpenCLIP prompts and thresholds as
filter_yfcc_outdoor.py (shared score_images). A video passes only if
>= --min-video-fraction of its keyframes are outdoor environment, so indoor and
non-environment videos are never downloaded or cut. The frame-based screen still runs
after candidate preparation as a second, clip-level check.

Videos whose keyframes are missing on the mirror pass through (status no_keyframes)
and are judged later by the frame-based screen.

Outputs
  --output                 the selected-videos table restricted to passing videos
                           (same columns + keyframe_* columns) -> feed to download/prepare
  <output>.all.csv         every screened video with its decision
  <output>.keyframes.csv   per-keyframe scores (thresholds can be changed offline)
  <output>.quality.json    counts, top prompts of dropped videos, and - when the
                           frame-based screen already ran on some of these videos
                           (--compare-frames) - the agreement between both screens.
"""
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
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

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

from filter_yfcc_outdoor import ZERO_TOLERANCE_PROMPTS, score_images

S3 = "https://multimedia-commons.s3.us-west-2.amazonaws.com/"
KEY_RE = re.compile(r"<Key>([^<]+)</Key>")


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("--keyframe-root", type=Path, required=True)
    p.add_argument("--output", type=Path, default=Path("data/yfcc_street_videos_screened.csv"))
    p.add_argument("--keyframes", type=int, default=8, help="keyframes scored per video (evenly spaced)")
    p.add_argument("--min-frame-prob", type=float, default=0.5)
    p.add_argument("--min-video-fraction", type=float, default=0.8)
    p.add_argument("--min-brightness", type=float, default=12.0)
    p.add_argument("--max-people-frames", type=int, default=0,
                   help="drop a video if more than this many keyframes are selfie/person-to-camera/animal-focused")
    p.add_argument("--openclip-model", default="ViT-B-16")
    p.add_argument("--openclip-pretrained", default="laion2b_s34b_b88k")
    p.add_argument("--batch-size", type=int, default=128)
    p.add_argument("--workers", type=int, default=8, help="image-loading workers for OpenCLIP")
    p.add_argument("--download-workers", type=int, default=16)
    p.add_argument("--device", default="cuda")
    p.add_argument("--strict-subjects", action="store_true",
                   help="see filter_yfcc_outdoor.py: no single object/person/animal/plant or indoor keyframes")
    p.add_argument("--include-excluded", action="store_true")
    p.add_argument("--maximum-videos", type=int, default=0, help="pilot: only the first N videos")
    p.add_argument("--compare-frames", type=Path, default=Path("data/yfcc_street_candidates_outdoor.frames.csv"))
    return p.parse_args()


def http_get(url: str, attempts: int = 6) -> bytes:
    error = None
    for attempt in range(attempts):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "soundscape-generator/0.1"})
            with urllib.request.urlopen(req, timeout=60) as r:
                return r.read()
        except urllib.error.HTTPError as e:
            if e.code in (403, 404):
                raise
            error = e
        except Exception as e:  # network: retry with backoff
            error = e
        time.sleep(min(30, 2 ** attempt))
    raise RuntimeError(f"GET failed: {url}: {error!r}")


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


def fetch_keyframes(h: str, root: Path, n: int) -> tuple[list[str], str | None]:
    """List and download up to n keyframes of one video. Returns local paths and an error."""
    local_dir = root / h[:3]
    cached = sorted(local_dir.glob(f"{h}-*.jpg")) if local_dir.exists() else []
    if cached:
        return [str(p) for p in cached], None
    try:
        prefix = f"data/videos/keyframes/{h[:3]}/{h[3:6]}/{h}-"
        body = http_get(S3 + "?" + urllib.parse.urlencode({"list-type": "2", "prefix": prefix, "max-keys": "1000"}))
        keys = sorted(k for k in KEY_RE.findall(body.decode("utf-8", "replace")) if k.endswith(".jpg"))
        if not keys:
            return [], "no_keyframes"
        local_dir.mkdir(parents=True, exist_ok=True)
        out = []
        for key in evenly(keys, n):
            target = local_dir / Path(key).name
            if not (target.exists() and target.stat().st_size > 0):
                data = http_get(S3 + urllib.parse.quote(key))
                tmp = target.with_name(target.name + ".part")
                tmp.write_bytes(data)
                tmp.replace(target)
            out.append(str(target))
        return out, None
    except Exception as e:
        return [], f"error: {str(e)[:200]}"


def compare(videos: pd.DataFrame, frames_csv: Path, min_frame_prob: float, min_video_fraction: float) -> dict | None:
    """Agreement between keyframe-screen and frame-screen video decisions on shared videos."""
    if not frames_csv.exists():
        return None
    fr = pd.read_csv(frames_csv, usecols=["recording_id", "outdoor_prob"], low_memory=False)
    frac = fr.outdoor_prob.ge(min_frame_prob).groupby(fr.recording_id).mean()
    shared = videos[videos.video_id.isin(frac.index) & videos.keyframe_status.eq("screened")]
    if shared.empty:
        return None
    k = shared.keyframe_keep.astype(bool).to_numpy()
    f = (frac.loc[shared.video_id] >= min_video_fraction).to_numpy()
    return {
        "shared_videos": int(len(shared)),
        "both_keep": int((k & f).sum()),
        "both_drop": int((~k & ~f).sum()),
        "keyframe_keep_frame_drop": int((k & ~f).sum()),
        "keyframe_drop_frame_keep": int((~k & f).sum()),
        "agreement": round(float((k == f).mean()), 3),
        "note": "keyframe_keep_frame_drop are still removed later by the frame screen; "
                "keyframe_drop_frame_keep are videos the pre-screen loses.",
    }


def main() -> None:
    args = parse_args()
    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)
    videos = videos.reset_index(drop=True)
    print(f"{len(videos):,} videos to screen")

    paths_by_video: dict[str, list[str]] = {}
    status: dict[str, str] = {}
    with ThreadPoolExecutor(args.download_workers) as pool:
        futures = {pool.submit(fetch_keyframes, r.hash, args.keyframe_root, args.keyframes): r.video_id
                   for r in videos.itertuples(index=False)}
        for fut in tqdm(as_completed(futures), total=len(futures), desc="Keyframes"):
            vid = futures[fut]
            paths, error = fut.result()
            paths_by_video[vid] = evenly(paths, args.keyframes)
            status[vid] = "screened" if paths else (error or "no_keyframes")

    rows = [(vid, p) for vid, ps in paths_by_video.items() for p in ps]
    kf = pd.DataFrame(rows, columns=["video_id", "keyframe_path"])
    scores = score_images(kf.keyframe_path.tolist(), args.openclip_model, args.openclip_pretrained,
                          args.device, args.batch_size, args.workers, args.min_brightness,
                          strict_subjects=args.strict_subjects)
    kf = pd.concat([kf, scores.reset_index(drop=True)], axis=1)
    kf["keyframe_outdoor"] = kf.outdoor_prob.ge(args.min_frame_prob)
    kf["keyframe_people"] = kf.outdoor_top_prompt.isin(ZERO_TOLERANCE_PROMPTS)
    agg = kf.groupby("video_id").agg(
        keyframe_count=("keyframe_path", "size"),
        keyframe_outdoor_fraction=("keyframe_outdoor", "mean"),
        keyframe_people_frames=("keyframe_people", "sum"),
        keyframe_top_prompt=("outdoor_top_prompt", lambda x: x.value_counts().index[0]),
    )
    videos["keyframe_status"] = videos.video_id.map(status)
    videos = videos.merge(agg, left_on="video_id", right_index=True, how="left")
    screened = videos.keyframe_status.eq("screened")
    videos["keyframe_keep"] = np.where(
        screened,
        videos.keyframe_outdoor_fraction.ge(args.min_video_fraction)
        & videos.keyframe_people_frames.fillna(0).le(args.max_people_frames),
        True)  # unscreened pass through

    args.output.parent.mkdir(parents=True, exist_ok=True)
    kf.to_csv(args.output.with_suffix(".keyframes.csv"), index=False)
    videos.to_csv(args.output.with_suffix(".all.csv"), index=False)
    passed = videos[videos.keyframe_keep.astype(bool)]
    passed.to_csv(args.output, index=False)

    dropped = videos[screened & ~videos.keyframe_keep.astype(bool)]
    report = {
        "videos_screened_input": int(len(videos)),
        "keyframe_status": videos.keyframe_status.value_counts().to_dict(),
        "keyframes_scored": int(len(kf)),
        "keyframes_per_video_median": float(agg.keyframe_count.median()) if len(agg) else 0,
        "videos_passed": int(len(passed)),
        "videos_dropped": int(len(dropped)),
        "pass_rate_screened": round(float(videos.loc[screened, "keyframe_keep"].astype(bool).mean()), 3) if screened.any() else None,
        "passed_by_split": passed.split.value_counts().to_dict(),
        "passed_segments_available_by_split": passed.groupby("split").segments_available.sum().astype(int).to_dict(),
        "top_prompt_of_dropped_videos": dropped.keyframe_top_prompt.value_counts().head(12).to_dict(),
        "min_frame_prob": args.min_frame_prob,
        "min_video_fraction": args.min_video_fraction,
        "min_brightness": args.min_brightness,
        "model": f"{args.openclip_model}/{args.openclip_pretrained}",
        "agreement_with_frame_screen": compare(videos, args.compare_frames, args.min_frame_prob, args.min_video_fraction),
    }
    args.output.with_suffix(".quality.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(json.dumps(report, indent=2))
    print(f"Wrote {args.output} ({len(passed):,} videos pass)")


if __name__ == "__main__":
    main()