File size: 5,586 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
#!/usr/bin/env python3
"""YFCC expansion: pick NEW geotagged YFCC videos for training only (new places).

The original run (select_yfcc_candidates.py) used only videos with geotag accuracy 16. Here the
remaining geotagged videos (default accuracy >= 11) that are not in data/yfcc_street_videos.csv are
added to TRAINING ONLY, so validation and test stay exactly as they are. A new video is excluded when
  - its uploader already has videos in validation or test (excluded_uploader),
  - it lies within a buffer of any existing validation/test video (excluded_near_heldout), or
  - it lies within a buffer of an Ann Arbor/Detroit place (excluded_local).
The buffer grows as the geotag gets coarser (accuracy 16: 1 km ... 11: 20 km), so an imprecise
location cannot sit next to a held-out place. Keyword-flagged (indoor/concert/edited/pet) videos
and videos shorter than one 10-s segment are dropped as before.
Output has the same columns as data/yfcc_street_videos.csv, so the YFCC prepare scripts run unchanged.
"""
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

from select_yfcc_candidates import haversine_nearest_km

BUFFER_KM = {16: 1.0, 15: 1.5, 14: 2.5, 13: 5.0, 12: 10.0, 11: 20.0}


def parse_args():
    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("--existing", type=Path, default=Path("data/yfcc_street_videos.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_expansion_videos.csv"))
    p.add_argument("--min-accuracy", type=int, default=11)
    p.add_argument("--clip-seconds", type=float, default=10.0)
    p.add_argument("--maximum-videos", type=int, default=0, help="cap on new training videos (random, seeded); 0 = all")
    p.add_argument("--seed", type=int, default=42)
    return p.parse_args()


def main():
    a = parse_args()
    m = pd.read_csv(a.manifest, low_memory=False, dtype={"uid": str, "hash": str})
    old = pd.read_csv(a.existing, 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["accuracy"] = pd.to_numeric(m.accuracy, errors="coerce").fillna(0).astype(int)
    m = m[~m.hash.isin(set(old.hash))]
    counts["not_in_original_pool"] = int(len(m))
    m = m[m.accuracy >= a.min_accuracy]
    counts["accuracy_ok"] = int(len(m))
    m = m[m.text_flag.astype(int) == 0]
    counts["no_text_flag"] = int(len(m))
    m = m[m.duration_s >= a.clip_seconds].drop_duplicates("hash").reset_index(drop=True)
    counts["at_least_one_segment"] = int(len(m))
    m["video_id"] = "yfcc_" + m.photoid.astype(str)
    m = m[~m.video_id.isin(set(old.video_id))].reset_index(drop=True)
    m["split_group"] = "yfcc_uid:" + m.uid.astype(str)

    held = old[old.split.isin(["val", "test"])]
    split = np.array(["train"] * len(m), dtype=object)
    split[m.split_group.isin(set(held.split_group)).to_numpy()] = "excluded_uploader"
    lat, lon = np.radians(m.latitude.to_numpy(float)), np.radians(m.longitude.to_numpy(float))
    buffer = m.accuracy.map(lambda x: BUFFER_KM.get(int(x), 20.0)).to_numpy(float)
    rows = np.flatnonzero(split == "train")
    near = haversine_nearest_km(lat, lon, rows, None, np.radians(held.latitude.to_numpy(float)),
                                np.radians(held.longitude.to_numpy(float)))
    split[rows[near < buffer[rows]]] = "excluded_near_heldout"
    if a.local_manifest.exists():
        loc = pd.read_csv(a.local_manifest, usecols=["location_id", "lat", "lon"]).drop_duplicates("location_id")
        rows = np.flatnonzero(split == "train")
        near = haversine_nearest_km(lat, lon, rows, None, np.radians(loc.lat.to_numpy(float)), np.radians(loc.lon.to_numpy(float)))
        split[rows[near < buffer[rows]]] = "excluded_local"
    m["split"] = split
    if a.maximum_videos:
        train = m.index[m.split.eq("train")]
        drop = np.random.default_rng(a.seed).permutation(train)[a.maximum_videos:]
        m.loc[drop, "split"] = "excluded_cap"
    m["segments_available"] = (m.duration_s // a.clip_seconds).astype(int)
    m["expansion"] = True
    a.output.parent.mkdir(parents=True, exist_ok=True)
    m.to_csv(a.output, index=False)
    used = m[m.split.eq("train")]
    report = {"filters": counts, "min_accuracy": a.min_accuracy, "buffer_km_by_accuracy": BUFFER_KM,
              "split_videos": m.split.value_counts().to_dict(),
              "train_by_accuracy": used.accuracy.value_counts().sort_index().to_dict(),
              "train_uploaders": int(used.split_group.nunique()),
              "train_hours": round(float(used.duration_s.sum()) / 3600, 1),
              "train_segments_available": int(used.segments_available.sum()),
              "existing_pool_videos": int(len(old))}
    a.output.with_suffix(".quality.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(json.dumps(report, indent=2))
    print(f"Wrote {a.output}")


if __name__ == "__main__":
    main()