ViewingSoundPAQ / scripts /data_preparation /datasets /prepare_yfcc_geovideos.py
xiaohaoy's picture
Initial release
16231ab verified
Raw History Blame Contribute Delete
8.32 kB
"""Build the geotagged-video manifest for YFCC100M (stage 1 of the YFCC pipeline).
Reads the Multimedia Commons copy of the YFCC100M metadata (SQLite, ~65.6 GB,
table yfcc100m_dataset) with one sequential scan, keeps videos (marker=1) that
have coordinates, and maps each to its Multimedia Commons file hash.
Hash rule (verified 2026-11-06 on two photos): hash = MD5(downloadurl) written
as hex WITHOUT zero padding per byte ('%x' per byte), e.g. 30-char names such as
0023df13b53926d7ee7a479e2d36cf. Every row is checked against video_length.txt
(the list of mp4 files that actually exist), so a wrong rule shows up as a low
match rate in the summary instead of silently producing bad URLs.
All geotagged videos are written (the scan is slow, so nothing is dropped here);
later stages filter on the flag columns:
accuracy Flickr geotag accuracy 1 (world) .. 16 (street)
text_flag tag/title/description keyword hit suggesting indoor/staged/edited content
license_nd No-Derivatives license (ok for training, not for shared renders)
license_commercial license allows commercial use
Usage:
python scripts/data_preparation/datasets/prepare_yfcc_geovideos.py --db /data/.../yfcc100m_dataset.sql \
--video-length /data/.../video_length.txt --out data/yfcc_geovideos_manifest.csv
"""
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 csv
import hashlib
import json
import re
import sqlite3
import time
import urllib.parse
from collections import Counter
from pathlib import Path
S3 = "https://multimedia-commons.s3.us-west-2.amazonaws.com/"
# Keywords that suggest the soundtrack/scene is not an outdoor ambience.
# Matched as whole words on URL-decoded, lower-cased tags + title + description.
TEXT_FLAG_WORDS = [
"indoor", "indoors", "inside", "interior", "room", "bedroom", "kitchen", "livingroom",
"office", "classroom", "studio", "museum", "church interior", "restaurant", "bar", "pub",
"club", "nightclub", "concert", "gig", "live music", "band", "dj", "karaoke", "theater",
"theatre", "stage", "performance", "recital", "orchestra", "choir", "rehearsal",
"slideshow", "timelapse", "time lapse", "stop motion", "stopmotion", "animation",
"screencast", "music video", "lyrics", "trailer", "edited", "montage", "underwater",
"aquarium", "cat", "kitten", "dog", "puppy", "baby", "birthday", "wedding", "party",
]
FLAG_RE = re.compile(r"\b(" + "|".join(re.escape(w) for w in TEXT_FLAG_WORDS) + r")\b")
COLUMNS = [
"photoid", "hash", "s3_url", "duration_s", "latitude", "longitude", "accuracy",
"uid", "unickname", "datetaken", "dateuploaded", "capturedevice",
"title", "usertags", "machinetags", "pageurl", "downloadurl",
"licensename", "licenseurl", "license_commercial", "license_nd",
"text_flag", "text_flag_words",
]
def mc_hash(downloadurl: str) -> str:
return "".join("%x" % b for b in hashlib.md5(downloadurl.encode("utf-8")).digest())
def s3_url(h: str) -> str:
return f"{S3}data/videos/mp4/{h[:3]}/{h[3:6]}/{h}.mp4"
def dec(s):
return urllib.parse.unquote_plus(s or "")
def parse_duration(t: str) -> float:
hh, mm, ss = t.split(":")
return int(hh) * 3600 + int(mm) * 60 + float(ss)
def load_video_lengths(path: Path) -> dict:
out = {}
with open(path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
parts = line.split()
if len(parts) >= 2 and parts[0].endswith(".mp4"):
try:
out[parts[0][:-4]] = parse_duration(parts[1])
except ValueError:
out[parts[0][:-4]] = None
return out
def to_float(s):
try:
return float(s)
except (TypeError, ValueError):
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--db", required=True)
ap.add_argument("--video-length", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--limit", type=int, default=0, help="debug: stop after N video rows")
args = ap.parse_args()
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
lengths = load_video_lengths(Path(args.video_length))
print(f"video_length.txt: {len(lengths):,} mp4 files")
con = sqlite3.connect(f"file:{Path(args.db).as_posix()}?mode=ro", uri=True)
con.execute("PRAGMA query_only=1")
con.execute("PRAGMA cache_size=-262144") # 256 MB
q = ("SELECT photoid, uid, unickname, datetaken, dateuploaded, capturedevice, title, "
"description, usertags, machinetags, longitude, latitude, accuracy, pageurl, "
"downloadurl, licensename, licenseurl FROM yfcc100m_dataset WHERE marker = 1")
stats = Counter()
lic = Counter()
acc = Counter()
t0 = time.time()
tmp = out.with_suffix(out.suffix + ".part")
with open(tmp, "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=COLUMNS)
w.writeheader()
for row in con.execute(q):
(pid, uid, nick, dtaken, dup, dev, title, desc, utags, mtags,
lon, lat, accuracy, pageurl, durl, lname, lurl) = row
stats["videos"] += 1
if stats["videos"] % 50000 == 0:
print(f" {stats['videos']:,} videos scanned, {stats['geotagged']:,} geotagged "
f"({time.time() - t0:.0f} s)", flush=True)
latf, lonf = to_float(lat), to_float(lon)
if latf is None or lonf is None or (latf == 0 and lonf == 0):
continue
stats["geotagged"] += 1
h = mc_hash(durl or "")
if h not in lengths:
stats["geotagged_no_mp4"] += 1
continue
stats["geotagged_with_mp4"] += 1
text = " ".join(dec(x).lower() for x in (utags, title, desc))
hits = sorted(set(m.group(1) for m in FLAG_RE.finditer(text)))
lname = lname or ""
commercial = "noncommercial" not in lname.replace("-", "").replace(" ", "").lower()
nd = "noderiv" in lname.replace("-", "").replace(" ", "").lower()
lic[lname] += 1
acc[int(accuracy or 0)] += 1
if hits:
stats["text_flagged"] += 1
w.writerow({
"photoid": pid, "hash": h, "s3_url": s3_url(h), "duration_s": lengths[h],
"latitude": latf, "longitude": lonf, "accuracy": accuracy,
"uid": uid, "unickname": dec(nick), "datetaken": dtaken, "dateuploaded": dup,
"capturedevice": dec(dev), "title": dec(title), "usertags": dec(utags),
"machinetags": dec(mtags), "pageurl": pageurl, "downloadurl": durl,
"licensename": lname, "licenseurl": lurl,
"license_commercial": int(commercial), "license_nd": int(nd),
"text_flag": int(bool(hits)), "text_flag_words": ";".join(hits),
})
if args.limit and stats["geotagged_with_mp4"] >= args.limit:
break
tmp.replace(out)
summary = {
"counts": dict(stats),
"mp4_match_rate_geotagged": (stats["geotagged_with_mp4"] / stats["geotagged"]) if stats["geotagged"] else None,
"licenses": dict(lic.most_common()),
"accuracy_hist": {str(k): v for k, v in sorted(acc.items())},
"kept_at_min_accuracy": {str(t): sum(v for k, v in acc.items() if k >= t) for t in (6, 11, 13, 14, 15, 16)},
"seconds": round(time.time() - t0, 1),
"hash_rule": "'%x'-per-byte MD5 of downloadurl",
}
Path(str(out) + ".summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
print(json.dumps(summary["counts"], indent=2))
print(f"mp4 match rate among geotagged videos: {summary['mp4_match_rate_geotagged']}")
if stats["geotagged"] and summary["mp4_match_rate_geotagged"] < 0.5:
raise SystemExit("Low mp4 match rate: the hash rule is probably wrong for videos. Stop and report.")
print(f"Wrote {out}")
if __name__ == "__main__":
main()