File size: 6,532 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
#!/usr/bin/env python3
"""Pick YFCC100M street-level videos and assign leakage-aware splits (stage 2a).

Input: data/yfcc_geovideos_manifest.csv from prepare_yfcc_geovideos.py.
Keeps videos with Flickr geotag accuracy == 16 (street level, --min-accuracy), no
indoor/staged keyword flag, and at least one full 10-second segment.

Splits keep whole uploaders (Flickr uid = same
camera, habits and places) go to one split, filling test then val to their fractions;
then train videos within --buffer-km of a val/test video, and val videos within
--buffer-km of a test video, are marked "excluded". Videos within --buffer-km of any
local Ann Arbor/Detroit place (data/local_pairs_manifest.csv) are marked
"excluded_local" so they can never leak into local cross-validation.
One row per video; segments are cut later by prepare_yfcc_candidates.py.
"""
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
from pathlib import Path

import numpy as np
import pandas as pd


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--manifest", type=Path, default=Path("data/yfcc_geovideos_manifest.csv"))
    p.add_argument("--local-manifest", type=Path, default=Path("data/local_pairs_manifest.csv"))
    p.add_argument("--output", type=Path, default=Path("data/yfcc_street_videos.csv"))
    p.add_argument("--min-accuracy", type=int, default=16)
    p.add_argument("--clip-seconds", type=float, default=10.0)
    p.add_argument("--keep-text-flagged", action="store_true")
    p.add_argument("--buffer-km", type=float, default=1.0)
    p.add_argument("--val-fraction", type=float, default=0.15)
    p.add_argument("--test-fraction", type=float, default=0.15)
    p.add_argument("--seed", type=int, default=42)
    return p.parse_args()


def haversine_nearest_km(lat, lon, rows, targets, tlat=None, tlon=None):
    """Distance from each row to its nearest target (radians in, km out)."""
    tlat = lat[targets] if tlat is None else tlat
    tlon = lon[targets] if tlon is None else tlon
    if not len(rows) or not len(tlat):
        return np.full(len(rows), np.inf)
    out = np.empty(len(rows))
    for s in range(0, len(rows), 256):
        i = rows[s:s + 256]
        d = (np.sin((tlat - lat[i][:, None]) / 2) ** 2
             + np.cos(lat[i][:, None]) * np.cos(tlat) * np.sin((tlon - lon[i][:, None]) / 2) ** 2)
        out[s:s + 256] = (2 * 6371.0 * np.arcsin(np.sqrt(np.clip(d, 0, 1)))).min(1)
    return out


def main() -> None:
    args = parse_args()
    m = pd.read_csv(args.manifest, low_memory=False, dtype={"uid": str, "hash": str})
    counts = {"geotagged_with_mp4": int(len(m))}
    m["duration_s"] = pd.to_numeric(m.duration_s, errors="coerce")
    m = m[pd.to_numeric(m.accuracy, errors="coerce").fillna(0) >= args.min_accuracy]
    counts["accuracy_ok"] = int(len(m))
    if not args.keep_text_flagged:
        m = m[m.text_flag.astype(int) == 0]
    counts["no_text_flag"] = int(len(m))
    m = m[m.duration_s >= args.clip_seconds].copy()
    counts["at_least_one_segment"] = int(len(m))
    m = m.drop_duplicates("hash").reset_index(drop=True)
    m["video_id"] = "yfcc_" + m.photoid.astype(str)
    m["split_group"] = "yfcc_uid:" + m.uid.astype(str)

    sizes = m.split_group.value_counts()
    rng = np.random.default_rng(args.seed)
    total, filled, assign = len(m), {"test": 0, "val": 0}, {}
    for group in sizes.index[rng.permutation(len(sizes))]:
        target = None
        for name, frac in (("test", args.test_fraction), ("val", args.val_fraction)):
            if filled[name] + sizes[group] <= frac * total * 1.1 and filled[name] < frac * total:
                target = name
                break
        assign[group] = target or "train"
        if target:
            filled[target] += sizes[group]
    split = m.split_group.map(assign).to_numpy().copy()
    initial = pd.Series(split).value_counts().to_dict()

    lat = np.radians(m.latitude.to_numpy(float))
    lon = np.radians(m.longitude.to_numpy(float))
    test_idx = np.flatnonzero(split == "test")
    held_idx = np.flatnonzero(split != "train")
    train_idx, val_idx = np.flatnonzero(split == "train"), np.flatnonzero(split == "val")
    near_train = haversine_nearest_km(lat, lon, train_idx, held_idx) < args.buffer_km
    near_val = haversine_nearest_km(lat, lon, val_idx, test_idx) < args.buffer_km
    split[train_idx[near_train]] = "excluded"
    split[val_idx[near_val]] = "excluded"

    local_excluded = 0
    if args.local_manifest.exists():
        loc = pd.read_csv(args.local_manifest, usecols=["location_id", "lat", "lon"]).drop_duplicates("location_id")
        llat, llon = np.radians(loc.lat.to_numpy(float)), np.radians(loc.lon.to_numpy(float))
        allidx = np.arange(len(m))
        near_local = haversine_nearest_km(lat, lon, allidx, None, llat, llon) < args.buffer_km
        local_excluded = int(near_local.sum())
        split[near_local] = "excluded_local"
    m["split"] = split
    m["segments_available"] = (m.duration_s // args.clip_seconds).astype(int)

    args.output.parent.mkdir(parents=True, exist_ok=True)
    m.to_csv(args.output, index=False)
    used = m[~m.split.str.startswith("excluded")]
    report = {
        "filters": counts,
        "min_accuracy": args.min_accuracy,
        "videos": int(len(m)),
        "initial_split_videos": {str(k): int(v) for k, v in initial.items()},
        "final_split_videos": m.split.value_counts().to_dict(),
        "final_split_segments": m.groupby("split").segments_available.sum().astype(int).to_dict(),
        "uploaders_used": int(used.split_group.nunique()),
        "uploaders_in_two_used_splits": int(used.groupby("split_group").split.nunique().gt(1).sum()),
        "excluded_near_local_places": local_excluded,
        "buffer_km": args.buffer_km,
        "used_hours": round(float(used.duration_s.sum()) / 3600, 1),
        "licenses_used": used.licensename.value_counts().to_dict(),
    }
    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}")


if __name__ == "__main__":
    main()