Upload folder using huggingface_hub
Browse files- scripts/README.md +52 -0
- scripts/curate_manifest.py +695 -0
- scripts/fetch_flickr.py +287 -0
- scripts/manifest.tsv +0 -0
- scripts/upload_hf.py +103 -0
scripts/README.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# YFCC50K Photo Corpus Scripts
|
| 2 |
+
|
| 3 |
+
Pipeline for curating, fetching, and uploading the Lightcella photo corpus
|
| 4 |
+
from the YFCC100M dataset.
|
| 5 |
+
|
| 6 |
+
## Pipeline
|
| 7 |
+
|
| 8 |
+
### Step 1: Curate (`curate_manifest.py`)
|
| 9 |
+
|
| 10 |
+
Selects 50k photos from YFCC100M with date/GPS/resolution stratification.
|
| 11 |
+
|
| 12 |
+
Requires:
|
| 13 |
+
- YFCC100M SQLite database (~65GB): `yfcc100m_dataset.sql`
|
| 14 |
+
- MediaEval placing subset files (downloaded automatically via AWS CLI)
|
| 15 |
+
- Python packages: `yfcc100m`, `opencv-python-headless`, `awscli`
|
| 16 |
+
|
| 17 |
+
Three phases run sequentially:
|
| 18 |
+
1. **Build metadata** -- scans YFCC SQLite for MediaEval placing hashes, extracts GPS/date/Flickr credentials
|
| 19 |
+
2. **Select subset** -- stratified sampling by date, GPS, faces, resolution tiers
|
| 20 |
+
3. **Upgrade resolution** -- probes Flickr for higher-res versions, assigns fetch tiers
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
python curate_manifest.py --db /path/to/yfcc100m_dataset.sql --out-dir ./output
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
Output: `manifest.tsv` (the same format shipped in this repo).
|
| 27 |
+
|
| 28 |
+
### Step 2: Fetch (`fetch_flickr.py`)
|
| 29 |
+
|
| 30 |
+
Downloads Flickr originals for manifest entries. Resumable, rate-limit aware.
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
python fetch_flickr.py --manifest manifest.tsv --out-dir ./photos
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
Features:
|
| 37 |
+
- Classifies Flickr users as alive/dead/unsampled for efficient probing
|
| 38 |
+
- Validates JPEG dimensions (skips <501px max edge)
|
| 39 |
+
- Restores file mtime from manifest date (fallback for EXIF-less photos)
|
| 40 |
+
- Automatic retry with backoff on 429s
|
| 41 |
+
|
| 42 |
+
### Step 3: Upload (`upload_hf.py`)
|
| 43 |
+
|
| 44 |
+
Creates ~1GB tar shards and uploads them to HuggingFace.
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
python upload_hf.py --src-dir ./photos --repo lightcella/photo-corpus --prefix yfcc
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Features:
|
| 51 |
+
- Resumable (skips already-uploaded shards)
|
| 52 |
+
- Deletes local tar after successful upload to save disk
|
scripts/curate_manifest.py
ADDED
|
@@ -0,0 +1,695 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Curate a 50k YFCC subset for Lightcella testing.
|
| 4 |
+
|
| 5 |
+
Three phases (run sequentially):
|
| 6 |
+
1. build-meta -- Scan YFCC SQLite for MediaEval placing hashes, extract GPS/date/Flickr creds
|
| 7 |
+
2. select -- Stratified sampling by date, GPS, faces, resolution tiers -> manifest
|
| 8 |
+
3. upgrade-res -- Probe Flickr for higher-res versions, assign fetch tiers
|
| 9 |
+
|
| 10 |
+
Requires:
|
| 11 |
+
- YFCC100M SQLite database (~65GB)
|
| 12 |
+
- Python packages: yfcc100m, opencv-python-headless, awscli
|
| 13 |
+
- MediaEval placing subset files (auto-downloaded from S3)
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
# Full pipeline:
|
| 17 |
+
python curate_manifest.py --db /path/to/yfcc100m_dataset.sql --out-dir ./output
|
| 18 |
+
|
| 19 |
+
# Individual phases:
|
| 20 |
+
python curate_manifest.py build-meta --db /path/to/yfcc100m_dataset.sql
|
| 21 |
+
python curate_manifest.py select --meta-jsonl placing_enriched.jsonl
|
| 22 |
+
python curate_manifest.py upgrade-res --db /path/to/yfcc100m_dataset.sql --manifest manifest.tsv
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import bz2
|
| 29 |
+
import csv
|
| 30 |
+
import json
|
| 31 |
+
import random
|
| 32 |
+
import sqlite3
|
| 33 |
+
import struct
|
| 34 |
+
import subprocess
|
| 35 |
+
import sys
|
| 36 |
+
import time
|
| 37 |
+
from collections import defaultdict
|
| 38 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 39 |
+
from dataclasses import dataclass, field
|
| 40 |
+
from datetime import datetime, timezone
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
from typing import Optional
|
| 43 |
+
|
| 44 |
+
# ---------------------------------------------------------------------------
|
| 45 |
+
# Shared utilities
|
| 46 |
+
# ---------------------------------------------------------------------------
|
| 47 |
+
|
| 48 |
+
S3_BUCKET = "multimedia-commons"
|
| 49 |
+
PLACING_FILES = [
|
| 50 |
+
("mediaeval2014_placing_test.bz2", "subsets/YLI-GEO/docs/mediaeval2014_placing_test.bz2"),
|
| 51 |
+
("mediaeval2014_placing_train.bz2", "subsets/YLI-GEO/docs/mediaeval2014_placing_train.bz2"),
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
TIER_SMALL = "small"
|
| 55 |
+
TIER_MEDIUM = "medium"
|
| 56 |
+
TIER_LARGE = "large"
|
| 57 |
+
DEFAULT_QUOTAS = {TIER_SMALL: 20000, TIER_MEDIUM: 15000, TIER_LARGE: 15000}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def tier_from_max_edge(edge: int) -> str:
|
| 61 |
+
if edge > 1600:
|
| 62 |
+
return TIER_LARGE
|
| 63 |
+
elif edge > 800:
|
| 64 |
+
return TIER_MEDIUM
|
| 65 |
+
return TIER_SMALL
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def jpeg_dimensions(path: Path) -> tuple[int, int] | None:
|
| 69 |
+
try:
|
| 70 |
+
with open(path, "rb") as f:
|
| 71 |
+
data = f.read(64 * 1024)
|
| 72 |
+
i = 2
|
| 73 |
+
while i < len(data) - 9:
|
| 74 |
+
if data[i] != 0xFF:
|
| 75 |
+
break
|
| 76 |
+
marker = data[i + 1]
|
| 77 |
+
if marker in (0xC0, 0xC1, 0xC2):
|
| 78 |
+
h = struct.unpack(">H", data[i + 5 : i + 7])[0]
|
| 79 |
+
w = struct.unpack(">H", data[i + 7 : i + 9])[0]
|
| 80 |
+
return w, h
|
| 81 |
+
length = struct.unpack(">H", data[i + 2 : i + 4])[0]
|
| 82 |
+
i += 2 + length
|
| 83 |
+
except Exception:
|
| 84 |
+
pass
|
| 85 |
+
return None
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def yfcc_hash_fallback(url: str) -> str:
|
| 89 |
+
"""Compute YFCC hash from download URL (md5 of URL path)."""
|
| 90 |
+
import hashlib
|
| 91 |
+
from urllib.parse import urlparse
|
| 92 |
+
path = urlparse(url).path
|
| 93 |
+
return hashlib.md5(path.encode()).hexdigest()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_yfcc_hash():
|
| 97 |
+
"""Try to import yfcc100m.convert_metadata.yfcc_hash, fallback to local."""
|
| 98 |
+
try:
|
| 99 |
+
from yfcc100m.convert_metadata import yfcc_hash
|
| 100 |
+
return yfcc_hash
|
| 101 |
+
except ImportError:
|
| 102 |
+
print("WARNING: yfcc100m not installed, using fallback hash", file=sys.stderr)
|
| 103 |
+
return yfcc_hash_fallback
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ---------------------------------------------------------------------------
|
| 107 |
+
# Phase 1: Build enriched metadata
|
| 108 |
+
# ---------------------------------------------------------------------------
|
| 109 |
+
|
| 110 |
+
def load_placing_hashes(cache_dir: Path) -> set[str]:
|
| 111 |
+
hashes: set[str] = set()
|
| 112 |
+
for name, s3_path in PLACING_FILES:
|
| 113 |
+
local = cache_dir / name
|
| 114 |
+
if not local.is_file():
|
| 115 |
+
subprocess.run(
|
| 116 |
+
[sys.executable, "-m", "awscli", "s3", "cp", "--no-sign-request",
|
| 117 |
+
f"s3://{S3_BUCKET}/{s3_path}", str(local)],
|
| 118 |
+
check=True,
|
| 119 |
+
)
|
| 120 |
+
with bz2.open(local, "rt") as f:
|
| 121 |
+
for line in f:
|
| 122 |
+
h = line.split("\t", 1)[0].strip()
|
| 123 |
+
if len(h) == 32:
|
| 124 |
+
hashes.add(h)
|
| 125 |
+
return hashes
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def cmd_build_meta(args) -> int:
|
| 129 |
+
"""Phase 1: Scan YFCC SQLite for placing hashes, output enriched JSONL."""
|
| 130 |
+
cache_dir = args.cache_dir
|
| 131 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 132 |
+
out_path = args.out_dir / "placing_enriched.jsonl"
|
| 133 |
+
|
| 134 |
+
if not args.db.is_file():
|
| 135 |
+
print(f"Missing {args.db}; download from S3 first", file=sys.stderr)
|
| 136 |
+
return 1
|
| 137 |
+
|
| 138 |
+
yfcc_hash = get_yfcc_hash()
|
| 139 |
+
placing = load_placing_hashes(cache_dir)
|
| 140 |
+
print(f"Placing hashes: {len(placing):,}", flush=True)
|
| 141 |
+
|
| 142 |
+
conn = sqlite3.connect(str(args.db))
|
| 143 |
+
conn.execute("PRAGMA query_only = YES")
|
| 144 |
+
conn.execute("PRAGMA journal_mode = OFF")
|
| 145 |
+
cols = [c[0] for c in conn.execute("SELECT * FROM yfcc100m_dataset LIMIT 0").description]
|
| 146 |
+
|
| 147 |
+
found = 0
|
| 148 |
+
with out_path.open("w") as out:
|
| 149 |
+
cur = conn.execute("SELECT * FROM yfcc100m_dataset")
|
| 150 |
+
for i, row in enumerate(cur):
|
| 151 |
+
if i and i % 5_000_000 == 0:
|
| 152 |
+
print(f" scanned {i:,} rows, matched {found:,}", flush=True)
|
| 153 |
+
d = dict(zip(cols, row))
|
| 154 |
+
url = d.get("downloadurl") or ""
|
| 155 |
+
if not url:
|
| 156 |
+
continue
|
| 157 |
+
key = yfcc_hash(url)
|
| 158 |
+
if key not in placing:
|
| 159 |
+
continue
|
| 160 |
+
lat, lon = d.get("latitude"), d.get("longitude")
|
| 161 |
+
if not lat or not lon:
|
| 162 |
+
continue
|
| 163 |
+
try:
|
| 164 |
+
lat_f, lon_f = float(lat), float(lon)
|
| 165 |
+
except ValueError:
|
| 166 |
+
continue
|
| 167 |
+
rec = {
|
| 168 |
+
"hash": key,
|
| 169 |
+
"photoid": d.get("photoid"),
|
| 170 |
+
"uid": d.get("uid"),
|
| 171 |
+
"datetaken": d.get("datetaken"),
|
| 172 |
+
"latitude": lat_f,
|
| 173 |
+
"longitude": lon_f,
|
| 174 |
+
"capturedevice": d.get("capturedevice") or "",
|
| 175 |
+
"ext": d.get("ext") or "jpg",
|
| 176 |
+
"serverid": d.get("serverid"),
|
| 177 |
+
"farmid": d.get("farmid"),
|
| 178 |
+
"secret": str(d.get("secret") or ""),
|
| 179 |
+
"secretoriginal": str(d.get("secretoriginal") or ""),
|
| 180 |
+
"downloadurl": d.get("downloadurl") or "",
|
| 181 |
+
}
|
| 182 |
+
out.write(json.dumps(rec) + "\n")
|
| 183 |
+
found += 1
|
| 184 |
+
|
| 185 |
+
print(f"Wrote {found:,} records to {out_path}", flush=True)
|
| 186 |
+
return 0
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ---------------------------------------------------------------------------
|
| 190 |
+
# Phase 2: Select subset
|
| 191 |
+
# ---------------------------------------------------------------------------
|
| 192 |
+
|
| 193 |
+
@dataclass
|
| 194 |
+
class PhotoMeta:
|
| 195 |
+
hash: str
|
| 196 |
+
photoid: int = 0
|
| 197 |
+
uid: str = ""
|
| 198 |
+
date_iso: str = ""
|
| 199 |
+
lat: Optional[float] = None
|
| 200 |
+
lon: Optional[float] = None
|
| 201 |
+
has_gps: bool = False
|
| 202 |
+
has_face: bool = False
|
| 203 |
+
has_exif_thumb: bool = False
|
| 204 |
+
has_date: bool = False
|
| 205 |
+
trip_id: int = -1
|
| 206 |
+
ext: str = "jpg"
|
| 207 |
+
serverid: int = 0
|
| 208 |
+
farmid: int = 0
|
| 209 |
+
secret: str = ""
|
| 210 |
+
width: int = 0
|
| 211 |
+
height: int = 0
|
| 212 |
+
max_edge: int = 0
|
| 213 |
+
resolution_tier: str = "small"
|
| 214 |
+
fetch_source: str = "s3"
|
| 215 |
+
flickr_size: str = ""
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def parse_datetaken(s: str) -> str:
|
| 219 |
+
if not s:
|
| 220 |
+
return ""
|
| 221 |
+
s = str(s).strip()
|
| 222 |
+
try:
|
| 223 |
+
base = s.split(".", 1)[0] if "." in s else s[:19]
|
| 224 |
+
dt = datetime.strptime(base[:19], "%Y-%m-%d %H:%M:%S")
|
| 225 |
+
return dt.replace(tzinfo=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 226 |
+
except ValueError:
|
| 227 |
+
return ""
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def load_enriched(path: Path) -> list[PhotoMeta]:
|
| 231 |
+
metas: list[PhotoMeta] = []
|
| 232 |
+
with path.open() as f:
|
| 233 |
+
for line in f:
|
| 234 |
+
d = json.loads(line)
|
| 235 |
+
m = PhotoMeta(
|
| 236 |
+
hash=d["hash"],
|
| 237 |
+
photoid=int(d.get("photoid") or 0),
|
| 238 |
+
uid=d.get("uid") or "",
|
| 239 |
+
lat=float(d["latitude"]),
|
| 240 |
+
lon=float(d["longitude"]),
|
| 241 |
+
has_gps=True,
|
| 242 |
+
ext=(d.get("ext") or "jpg").lower(),
|
| 243 |
+
serverid=int(d.get("serverid") or 0),
|
| 244 |
+
farmid=int(d.get("farmid") or 0),
|
| 245 |
+
secret=str(d.get("secret") or ""),
|
| 246 |
+
)
|
| 247 |
+
m.date_iso = parse_datetaken(d.get("datetaken", ""))
|
| 248 |
+
m.has_date = bool(m.date_iso)
|
| 249 |
+
metas.append(m)
|
| 250 |
+
return metas
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def assign_trips_by_uid(metas: list[PhotoMeta], min_len: int = 30) -> None:
|
| 254 |
+
"""Cluster same Flickr user + time proximity + geo cell into trips."""
|
| 255 |
+
by_uid: dict[str, list[PhotoMeta]] = defaultdict(list)
|
| 256 |
+
for m in metas:
|
| 257 |
+
if m.has_date and m.has_gps and m.uid:
|
| 258 |
+
by_uid[m.uid].append(m)
|
| 259 |
+
|
| 260 |
+
tid = 0
|
| 261 |
+
for uid, photos in by_uid.items():
|
| 262 |
+
photos.sort(key=lambda x: x.date_iso)
|
| 263 |
+
current: list[PhotoMeta] = []
|
| 264 |
+
last_ts = 0.0
|
| 265 |
+
last_cell = ""
|
| 266 |
+
|
| 267 |
+
def cell(m: PhotoMeta) -> str:
|
| 268 |
+
return f"{int((m.lat + 90) * 50)}:{int((m.lon + 180) * 50)}"
|
| 269 |
+
|
| 270 |
+
def flush():
|
| 271 |
+
nonlocal tid, current
|
| 272 |
+
if len(current) >= min_len:
|
| 273 |
+
for p in current:
|
| 274 |
+
p.trip_id = tid
|
| 275 |
+
tid += 1
|
| 276 |
+
current = []
|
| 277 |
+
|
| 278 |
+
for m in photos:
|
| 279 |
+
ts = datetime.strptime(m.date_iso, "%Y-%m-%dT%H:%M:%SZ").timestamp()
|
| 280 |
+
c = cell(m)
|
| 281 |
+
if current:
|
| 282 |
+
gap = (ts - last_ts) / 86400.0
|
| 283 |
+
if c != last_cell or gap > 21 or gap < -1:
|
| 284 |
+
flush()
|
| 285 |
+
current.append(m)
|
| 286 |
+
last_ts = ts
|
| 287 |
+
last_cell = c
|
| 288 |
+
flush()
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def stratified_fill(selected: dict, rest: list, target: int, rng: random.Random):
|
| 292 |
+
"""Fill remaining slots with date-stratified random sampling."""
|
| 293 |
+
rng.shuffle(rest)
|
| 294 |
+
for m in rest:
|
| 295 |
+
if len(selected) >= target:
|
| 296 |
+
break
|
| 297 |
+
if m.hash not in selected:
|
| 298 |
+
selected[m.hash] = m
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def select_final(metas: list[PhotoMeta], target: int, seed: int = 42) -> list[PhotoMeta]:
|
| 302 |
+
selected: dict[str, PhotoMeta] = {}
|
| 303 |
+
|
| 304 |
+
# Prioritize trip photos
|
| 305 |
+
trip_sorted = sorted(metas, key=lambda m: (m.trip_id < 0, -m.trip_id, m.date_iso))
|
| 306 |
+
for m in trip_sorted:
|
| 307 |
+
if m.trip_id >= 0 and len(selected) < target:
|
| 308 |
+
selected[m.hash] = m
|
| 309 |
+
|
| 310 |
+
# Fill with faces
|
| 311 |
+
for m in sorted(metas, key=lambda x: x.has_face, reverse=True):
|
| 312 |
+
if sum(1 for x in selected.values() if x.has_face) >= max(2500, int(target * 0.05)):
|
| 313 |
+
break
|
| 314 |
+
if len(selected) < target:
|
| 315 |
+
selected[m.hash] = m
|
| 316 |
+
|
| 317 |
+
# Fill rest randomly
|
| 318 |
+
rng = random.Random(seed)
|
| 319 |
+
rest = [m for m in metas if m.hash not in selected]
|
| 320 |
+
stratified_fill(selected, rest, target, rng)
|
| 321 |
+
|
| 322 |
+
return list(selected.values())
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def cmd_select(args) -> int:
|
| 326 |
+
"""Phase 2: Select 50k subset from enriched metadata."""
|
| 327 |
+
if not args.meta_jsonl.is_file():
|
| 328 |
+
print(f"Missing {args.meta_jsonl}; run build-meta first", file=sys.stderr)
|
| 329 |
+
return 1
|
| 330 |
+
|
| 331 |
+
print("Loading enriched metadata ...", flush=True)
|
| 332 |
+
all_meta = load_enriched(args.meta_jsonl)
|
| 333 |
+
print(f" pool: {len(all_meta):,} geotagged placing photos", flush=True)
|
| 334 |
+
|
| 335 |
+
all_meta.sort(key=lambda m: int(m.hash[:16], 16) ^ args.seed)
|
| 336 |
+
probe_pool = all_meta[: max(args.target * 2, len(all_meta))]
|
| 337 |
+
|
| 338 |
+
assign_trips_by_uid(probe_pool)
|
| 339 |
+
final = select_final(probe_pool, args.target, seed=args.seed)
|
| 340 |
+
|
| 341 |
+
if len(final) < args.target:
|
| 342 |
+
print(f"ERROR: selected {len(final)} < {args.target}", file=sys.stderr)
|
| 343 |
+
return 1
|
| 344 |
+
|
| 345 |
+
out_manifest = args.out_dir / "manifest.tsv"
|
| 346 |
+
args.out_dir.mkdir(parents=True, exist_ok=True)
|
| 347 |
+
|
| 348 |
+
with out_manifest.open("w", newline="") as f:
|
| 349 |
+
w = csv.writer(f, delimiter="\t")
|
| 350 |
+
w.writerow([
|
| 351 |
+
"hash", "date_iso", "lat", "lon", "has_gps", "has_face", "has_exif_thumb",
|
| 352 |
+
"trip_id", "uid", "photoid", "serverid", "secret",
|
| 353 |
+
"width", "height", "max_edge", "resolution_tier", "fetch_source", "flickr_size",
|
| 354 |
+
])
|
| 355 |
+
for m in sorted(final, key=lambda x: (x.trip_id, x.date_iso, x.hash)):
|
| 356 |
+
w.writerow([
|
| 357 |
+
m.hash, m.date_iso,
|
| 358 |
+
f"{m.lat:.6f}" if m.lat is not None else "",
|
| 359 |
+
f"{m.lon:.6f}" if m.lon is not None else "",
|
| 360 |
+
int(m.has_gps), int(m.has_face), int(m.has_exif_thumb),
|
| 361 |
+
m.trip_id, m.uid, m.photoid, m.serverid, m.secret,
|
| 362 |
+
m.width, m.height, m.max_edge, m.resolution_tier, m.fetch_source, m.flickr_size,
|
| 363 |
+
])
|
| 364 |
+
|
| 365 |
+
print(f"Wrote {len(final):,} entries to {out_manifest}")
|
| 366 |
+
return 0
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
# ---------------------------------------------------------------------------
|
| 370 |
+
# Phase 3: Upgrade resolution tiers
|
| 371 |
+
# ---------------------------------------------------------------------------
|
| 372 |
+
|
| 373 |
+
MANIFEST_HEADER = [
|
| 374 |
+
"hash", "date_iso", "lat", "lon", "has_gps", "has_face", "has_exif_thumb",
|
| 375 |
+
"trip_id", "uid", "photoid", "serverid", "secret",
|
| 376 |
+
"width", "height", "max_edge", "resolution_tier", "fetch_source", "flickr_size",
|
| 377 |
+
]
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
@dataclass
|
| 381 |
+
class Row:
|
| 382 |
+
hash: str
|
| 383 |
+
date_iso: str = ""
|
| 384 |
+
lat: str = ""
|
| 385 |
+
lon: str = ""
|
| 386 |
+
has_gps: str = "1"
|
| 387 |
+
has_face: str = "0"
|
| 388 |
+
has_exif_thumb: str = "0"
|
| 389 |
+
trip_id: str = "-1"
|
| 390 |
+
uid: str = ""
|
| 391 |
+
photoid: int = 0
|
| 392 |
+
serverid: int = 0
|
| 393 |
+
secret: str = ""
|
| 394 |
+
width: int = 0
|
| 395 |
+
height: int = 0
|
| 396 |
+
max_edge: int = 0
|
| 397 |
+
resolution_tier: str = TIER_SMALL
|
| 398 |
+
fetch_source: str = "s3"
|
| 399 |
+
flickr_size: str = ""
|
| 400 |
+
s3_max_edge: int = 0
|
| 401 |
+
flickr_max_edge: int = 0
|
| 402 |
+
|
| 403 |
+
def to_manifest_row(self) -> list:
|
| 404 |
+
return [
|
| 405 |
+
self.hash, self.date_iso, self.lat, self.lon, self.has_gps,
|
| 406 |
+
self.has_face, self.has_exif_thumb, self.trip_id, self.uid,
|
| 407 |
+
self.photoid, self.serverid, self.secret, self.width, self.height,
|
| 408 |
+
self.max_edge, self.resolution_tier, self.fetch_source, self.flickr_size,
|
| 409 |
+
]
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def load_manifest(path: Path) -> dict[str, Row]:
|
| 413 |
+
rows: dict[str, Row] = {}
|
| 414 |
+
with path.open(encoding="utf-8") as f:
|
| 415 |
+
reader = csv.DictReader(f, delimiter="\t")
|
| 416 |
+
for d in reader:
|
| 417 |
+
h = d["hash"]
|
| 418 |
+
rows[h] = Row(
|
| 419 |
+
hash=h,
|
| 420 |
+
date_iso=d.get("date_iso", ""),
|
| 421 |
+
lat=d.get("lat", ""),
|
| 422 |
+
lon=d.get("lon", ""),
|
| 423 |
+
has_gps=d.get("has_gps", "1"),
|
| 424 |
+
has_face=d.get("has_face", "0"),
|
| 425 |
+
has_exif_thumb=d.get("has_exif_thumb", "0"),
|
| 426 |
+
trip_id=d.get("trip_id", "-1"),
|
| 427 |
+
uid=d.get("uid", ""),
|
| 428 |
+
photoid=int(d.get("photoid") or 0),
|
| 429 |
+
serverid=int(d.get("serverid") or 0),
|
| 430 |
+
secret=d.get("secret") or "",
|
| 431 |
+
)
|
| 432 |
+
return rows
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def probe_best_flickr(serverid, photoid, secret, cache_dir: Path, h: str) -> tuple[int, str, Optional[Path]]:
|
| 436 |
+
"""Probe Flickr for the best available size. Returns (max_edge, size_suffix, path)."""
|
| 437 |
+
sizes = ["o", "k", "b"] # original, 2048, 1024
|
| 438 |
+
for size in sizes:
|
| 439 |
+
url = f"https://live.staticflickr.com/{serverid}/{photoid}_{secret}_{size}.jpg"
|
| 440 |
+
dest = cache_dir / f"{h}_{size}.jpg"
|
| 441 |
+
if dest.is_file() and dest.stat().st_size > 1000:
|
| 442 |
+
dims = jpeg_dimensions(dest)
|
| 443 |
+
if dims:
|
| 444 |
+
return max(dims), size, dest
|
| 445 |
+
continue
|
| 446 |
+
r = subprocess.run(
|
| 447 |
+
["curl", "-sL", "-o", str(dest), "-w", "%{http_code}", url,
|
| 448 |
+
"--connect-timeout", "3", "--max-time", "8"],
|
| 449 |
+
capture_output=True, text=True, timeout=12,
|
| 450 |
+
)
|
| 451 |
+
if r.stdout.strip() == "200" and dest.is_file() and dest.stat().st_size > 1000:
|
| 452 |
+
dims = jpeg_dimensions(dest)
|
| 453 |
+
if dims:
|
| 454 |
+
return max(dims), size, dest
|
| 455 |
+
dest.unlink(missing_ok=True)
|
| 456 |
+
return 0, "", None
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def probe_row(row: Row, photos_dir: Path, cache_dir: Path, probe_flickr: bool) -> Row:
|
| 460 |
+
row.s3_max_edge = 0
|
| 461 |
+
p = photos_dir / f"{row.hash}.jpg"
|
| 462 |
+
if p.is_file():
|
| 463 |
+
dims = jpeg_dimensions(p)
|
| 464 |
+
if dims:
|
| 465 |
+
row.s3_max_edge = max(dims)
|
| 466 |
+
row.width, row.height = dims
|
| 467 |
+
|
| 468 |
+
row.max_edge = row.s3_max_edge
|
| 469 |
+
row.fetch_source = "s3"
|
| 470 |
+
row.flickr_max_edge = 0
|
| 471 |
+
|
| 472 |
+
if probe_flickr and row.photoid and row.serverid and row.secret:
|
| 473 |
+
flickr_edge, flickr_size, flickr_path = probe_best_flickr(
|
| 474 |
+
row.serverid, row.photoid, row.secret, cache_dir, row.hash
|
| 475 |
+
)
|
| 476 |
+
row.flickr_max_edge = flickr_edge
|
| 477 |
+
row.flickr_size = flickr_size
|
| 478 |
+
if flickr_edge > row.max_edge and flickr_path:
|
| 479 |
+
dims = jpeg_dimensions(flickr_path)
|
| 480 |
+
if dims:
|
| 481 |
+
row.width, row.height = dims
|
| 482 |
+
row.max_edge = max(dims)
|
| 483 |
+
else:
|
| 484 |
+
row.max_edge = flickr_edge
|
| 485 |
+
|
| 486 |
+
return row
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def assign_tiers(rows: list[Row], quotas: dict[str, int], seed: int) -> None:
|
| 490 |
+
"""Assign fetch tier per hash based on available Flickr resolution."""
|
| 491 |
+
upgradable = [r for r in rows if r.flickr_max_edge > r.s3_max_edge and r.flickr_size]
|
| 492 |
+
upgradable.sort(key=lambda r: r.flickr_max_edge, reverse=True)
|
| 493 |
+
|
| 494 |
+
large_quota = quotas.get(TIER_LARGE, 0)
|
| 495 |
+
medium_quota = quotas.get(TIER_MEDIUM, 0)
|
| 496 |
+
|
| 497 |
+
large: list[Row] = []
|
| 498 |
+
medium: list[Row] = []
|
| 499 |
+
for r in upgradable:
|
| 500 |
+
if len(large) < large_quota and r.flickr_max_edge > 1600:
|
| 501 |
+
large.append(r)
|
| 502 |
+
elif len(medium) < medium_quota and r.flickr_max_edge > 500:
|
| 503 |
+
medium.append(r)
|
| 504 |
+
if len(large) >= large_quota and len(medium) >= medium_quota:
|
| 505 |
+
break
|
| 506 |
+
|
| 507 |
+
used = {r.hash for r in large + medium}
|
| 508 |
+
rest = [r for r in upgradable if r.hash not in used]
|
| 509 |
+
rng = random.Random(seed)
|
| 510 |
+
rng.shuffle(rest)
|
| 511 |
+
while len(large) < large_quota and rest:
|
| 512 |
+
large.append(rest.pop())
|
| 513 |
+
while len(medium) < medium_quota and rest:
|
| 514 |
+
medium.append(rest.pop())
|
| 515 |
+
|
| 516 |
+
for r in large:
|
| 517 |
+
r.resolution_tier = TIER_LARGE
|
| 518 |
+
r.fetch_source = "flickr"
|
| 519 |
+
r.max_edge = r.flickr_max_edge
|
| 520 |
+
for r in medium:
|
| 521 |
+
r.resolution_tier = TIER_MEDIUM
|
| 522 |
+
r.fetch_source = "flickr"
|
| 523 |
+
r.max_edge = r.flickr_max_edge
|
| 524 |
+
for r in rows:
|
| 525 |
+
if r.fetch_source == "s3":
|
| 526 |
+
r.resolution_tier = tier_from_max_edge(r.s3_max_edge or 500)
|
| 527 |
+
r.max_edge = r.s3_max_edge or 500
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def join_flickr_metadata(rows: dict[str, Row], db_path: Path, cache_path: Optional[Path] = None) -> int:
|
| 531 |
+
"""Join manifest hashes against YFCC SQLite for Flickr credentials."""
|
| 532 |
+
yfcc_hash = get_yfcc_hash()
|
| 533 |
+
want = set(rows)
|
| 534 |
+
|
| 535 |
+
if cache_path and cache_path.is_file():
|
| 536 |
+
cached = json.loads(cache_path.read_text())
|
| 537 |
+
hit = 0
|
| 538 |
+
for h, meta in cached.items():
|
| 539 |
+
if h not in rows:
|
| 540 |
+
continue
|
| 541 |
+
row = rows[h]
|
| 542 |
+
row.photoid = int(meta.get("photoid") or 0)
|
| 543 |
+
row.serverid = int(meta.get("serverid") or 0)
|
| 544 |
+
row.secret = str(meta.get("secret") or "")
|
| 545 |
+
hit += 1
|
| 546 |
+
print(f" loaded {hit:,} Flickr credentials from cache", flush=True)
|
| 547 |
+
return hit
|
| 548 |
+
|
| 549 |
+
found_meta: dict[str, dict] = {}
|
| 550 |
+
conn = sqlite3.connect(str(db_path))
|
| 551 |
+
conn.execute("PRAGMA query_only = ON")
|
| 552 |
+
conn.execute("PRAGMA journal_mode = OFF")
|
| 553 |
+
cur = conn.execute("SELECT downloadurl, photoid, serverid, secret FROM yfcc100m_dataset")
|
| 554 |
+
for i, raw in enumerate(cur, 1):
|
| 555 |
+
if i % 5_000_000 == 0:
|
| 556 |
+
print(f" SQL scan {i:,} rows, matched {len(found_meta):,}", flush=True)
|
| 557 |
+
url = raw[0]
|
| 558 |
+
if not url:
|
| 559 |
+
continue
|
| 560 |
+
key = yfcc_hash(url)
|
| 561 |
+
if key not in want:
|
| 562 |
+
continue
|
| 563 |
+
found_meta[key] = {"photoid": raw[1], "serverid": raw[2], "secret": raw[3] or ""}
|
| 564 |
+
if len(found_meta) >= len(want):
|
| 565 |
+
break
|
| 566 |
+
conn.close()
|
| 567 |
+
|
| 568 |
+
for h, meta in found_meta.items():
|
| 569 |
+
row = rows[h]
|
| 570 |
+
row.photoid = int(meta.get("photoid") or 0)
|
| 571 |
+
row.serverid = int(meta.get("serverid") or 0)
|
| 572 |
+
row.secret = str(meta.get("secret") or "")
|
| 573 |
+
|
| 574 |
+
if cache_path:
|
| 575 |
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
| 576 |
+
cache_path.write_text(json.dumps(found_meta))
|
| 577 |
+
|
| 578 |
+
return len(found_meta)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def cmd_upgrade_res(args) -> int:
|
| 582 |
+
"""Phase 3: Probe Flickr for higher resolution, assign tiers."""
|
| 583 |
+
if not args.db.is_file():
|
| 584 |
+
print(f"Missing {args.db}", file=sys.stderr)
|
| 585 |
+
return 1
|
| 586 |
+
|
| 587 |
+
manifest_path = args.manifest
|
| 588 |
+
if not manifest_path.is_file():
|
| 589 |
+
print(f"Missing {manifest_path}; run select first", file=sys.stderr)
|
| 590 |
+
return 1
|
| 591 |
+
|
| 592 |
+
quotas = {}
|
| 593 |
+
for part in args.resolution_quotas.split(","):
|
| 594 |
+
tier, count = part.split("=", 1)
|
| 595 |
+
quotas[tier.strip()] = int(count)
|
| 596 |
+
|
| 597 |
+
print("Loading manifest ...", flush=True)
|
| 598 |
+
rows = load_manifest(manifest_path)
|
| 599 |
+
print(f" {len(rows):,} hashes", flush=True)
|
| 600 |
+
|
| 601 |
+
print("Joining Flickr metadata from SQL ...", flush=True)
|
| 602 |
+
cache_path = args.cache_dir / "flickr_meta_cache.json"
|
| 603 |
+
matched = join_flickr_metadata(rows, args.db, cache_path)
|
| 604 |
+
print(f" matched {matched:,}/{len(rows):,}", flush=True)
|
| 605 |
+
|
| 606 |
+
work = list(rows.values())
|
| 607 |
+
if args.limit:
|
| 608 |
+
work = work[:args.limit]
|
| 609 |
+
|
| 610 |
+
args.cache_dir.mkdir(parents=True, exist_ok=True)
|
| 611 |
+
photos_dir = args.photos_dir
|
| 612 |
+
photos_dir.mkdir(parents=True, exist_ok=True)
|
| 613 |
+
|
| 614 |
+
print(f"Probing dimensions ({len(work):,} files, {args.workers} workers) ...", flush=True)
|
| 615 |
+
t0 = time.time()
|
| 616 |
+
with ThreadPoolExecutor(max_workers=max(1, args.workers)) as ex:
|
| 617 |
+
futs = [
|
| 618 |
+
ex.submit(probe_row, row, photos_dir, args.cache_dir, not args.skip_flickr_probe)
|
| 619 |
+
for row in work
|
| 620 |
+
]
|
| 621 |
+
for i, fut in enumerate(as_completed(futs), 1):
|
| 622 |
+
fut.result()
|
| 623 |
+
if i % 2000 == 0:
|
| 624 |
+
print(f" {i:,}/{len(work):,} ({i/(time.time()-t0):.1f}/s)", flush=True)
|
| 625 |
+
|
| 626 |
+
assign_tiers(work, quotas, args.seed)
|
| 627 |
+
|
| 628 |
+
# Write updated manifest
|
| 629 |
+
with manifest_path.open("w", newline="") as f:
|
| 630 |
+
w = csv.writer(f, delimiter="\t")
|
| 631 |
+
w.writerow(MANIFEST_HEADER)
|
| 632 |
+
for r in sorted(work, key=lambda x: (x.trip_id, x.date_iso, x.hash)):
|
| 633 |
+
w.writerow(r.to_manifest_row())
|
| 634 |
+
|
| 635 |
+
tier_counts = defaultdict(int)
|
| 636 |
+
for r in work:
|
| 637 |
+
tier_counts[r.resolution_tier] += 1
|
| 638 |
+
|
| 639 |
+
print(f"Wrote {manifest_path}")
|
| 640 |
+
print(f" small={tier_counts[TIER_SMALL]} medium={tier_counts[TIER_MEDIUM]} large={tier_counts[TIER_LARGE]}")
|
| 641 |
+
return 0
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
# ---------------------------------------------------------------------------
|
| 645 |
+
# Main CLI
|
| 646 |
+
# ---------------------------------------------------------------------------
|
| 647 |
+
|
| 648 |
+
def main() -> int:
|
| 649 |
+
parser = argparse.ArgumentParser(
|
| 650 |
+
description="Curate YFCC50K manifest for Lightcella photo corpus",
|
| 651 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 652 |
+
epilog=__doc__,
|
| 653 |
+
)
|
| 654 |
+
sub = parser.add_subparsers(dest="command")
|
| 655 |
+
|
| 656 |
+
# build-meta
|
| 657 |
+
p1 = sub.add_parser("build-meta", help="Phase 1: extract placing metadata from YFCC SQLite")
|
| 658 |
+
p1.add_argument("--db", type=Path, required=True, help="Path to yfcc100m_dataset.sql")
|
| 659 |
+
p1.add_argument("--cache-dir", type=Path, default=Path("cache"), help="Dir for S3 downloads")
|
| 660 |
+
p1.add_argument("--out-dir", type=Path, default=Path("."), help="Output directory")
|
| 661 |
+
|
| 662 |
+
# select
|
| 663 |
+
p2 = sub.add_parser("select", help="Phase 2: stratified subset selection")
|
| 664 |
+
p2.add_argument("--meta-jsonl", type=Path, default=Path("placing_enriched.jsonl"))
|
| 665 |
+
p2.add_argument("--out-dir", type=Path, default=Path("."))
|
| 666 |
+
p2.add_argument("--target", type=int, default=50000)
|
| 667 |
+
p2.add_argument("--seed", type=int, default=42)
|
| 668 |
+
|
| 669 |
+
# upgrade-res
|
| 670 |
+
p3 = sub.add_parser("upgrade-res", help="Phase 3: probe Flickr, assign resolution tiers")
|
| 671 |
+
p3.add_argument("--db", type=Path, required=True, help="Path to yfcc100m_dataset.sql")
|
| 672 |
+
p3.add_argument("--manifest", type=Path, default=Path("manifest.tsv"))
|
| 673 |
+
p3.add_argument("--photos-dir", type=Path, default=Path("photos"))
|
| 674 |
+
p3.add_argument("--cache-dir", type=Path, default=Path("cache"))
|
| 675 |
+
p3.add_argument("--workers", type=int, default=32)
|
| 676 |
+
p3.add_argument("--limit", type=int, default=0)
|
| 677 |
+
p3.add_argument("--skip-flickr-probe", action="store_true")
|
| 678 |
+
p3.add_argument("--resolution-quotas", default="small=20000,medium=15000,large=15000")
|
| 679 |
+
p3.add_argument("--seed", type=int, default=42)
|
| 680 |
+
|
| 681 |
+
args = parser.parse_args()
|
| 682 |
+
|
| 683 |
+
if args.command == "build-meta":
|
| 684 |
+
return cmd_build_meta(args)
|
| 685 |
+
elif args.command == "select":
|
| 686 |
+
return cmd_select(args)
|
| 687 |
+
elif args.command == "upgrade-res":
|
| 688 |
+
return cmd_upgrade_res(args)
|
| 689 |
+
else:
|
| 690 |
+
parser.print_help()
|
| 691 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Fetch Flickr _o originals for YFCC photos by tier.
|
| 4 |
+
Downloads only if >500px max edge. Resumable -- skips existing files and known-dead hashes.
|
| 5 |
+
Prioritizes known-alive users (fast), probes unsampled users, defers dead users.
|
| 6 |
+
"""
|
| 7 |
+
import csv
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import struct
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
from collections import defaultdict
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
MIN_EDGE = 501
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def jpeg_dimensions(path: Path) -> tuple[int, int] | None:
|
| 21 |
+
try:
|
| 22 |
+
with open(path, "rb") as f:
|
| 23 |
+
data = f.read(64 * 1024)
|
| 24 |
+
i = 2
|
| 25 |
+
while i < len(data) - 9:
|
| 26 |
+
if data[i] != 0xFF:
|
| 27 |
+
break
|
| 28 |
+
marker = data[i + 1]
|
| 29 |
+
if marker in (0xC0, 0xC1, 0xC2):
|
| 30 |
+
h = struct.unpack(">H", data[i + 5 : i + 7])[0]
|
| 31 |
+
w = struct.unpack(">H", data[i + 7 : i + 9])[0]
|
| 32 |
+
return w, h
|
| 33 |
+
length = struct.unpack(">H", data[i + 2 : i + 4])[0]
|
| 34 |
+
i += 2 + length
|
| 35 |
+
except Exception:
|
| 36 |
+
pass
|
| 37 |
+
return None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def restore_mtime(dest: Path, date_iso: str) -> None:
|
| 41 |
+
"""Set file mtime from manifest date so Lightcella uses it as fallback."""
|
| 42 |
+
if not date_iso:
|
| 43 |
+
return
|
| 44 |
+
try:
|
| 45 |
+
from datetime import datetime
|
| 46 |
+
dt = datetime.fromisoformat(date_iso.replace("Z", "+00:00"))
|
| 47 |
+
ts = dt.timestamp()
|
| 48 |
+
if ts > 0:
|
| 49 |
+
os.utime(dest, (ts, ts))
|
| 50 |
+
except (ValueError, OSError):
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def fetch_one(row: dict, out_dir: Path) -> tuple[str, dict | None]:
|
| 55 |
+
"""Returns (status, result). status: 'ok', 'small', 'dead', 'rate_limited'."""
|
| 56 |
+
h = row["hash"]
|
| 57 |
+
dest = out_dir / f"{h}.jpg"
|
| 58 |
+
|
| 59 |
+
if dest.is_file() and dest.stat().st_size > 0:
|
| 60 |
+
dims = jpeg_dimensions(dest)
|
| 61 |
+
if dims and max(dims) >= MIN_EDGE:
|
| 62 |
+
return "ok", {"hash": h, "width": dims[0], "height": dims[1]}
|
| 63 |
+
return "small", None
|
| 64 |
+
|
| 65 |
+
sid, pid, sec = row["serverid"], row["photoid"], row["secret"]
|
| 66 |
+
url = f"https://live.staticflickr.com/{sid}/{pid}_{sec}_o.jpg"
|
| 67 |
+
|
| 68 |
+
r = subprocess.run(
|
| 69 |
+
["curl", "-sL", "-o", str(dest), "-w", "%{http_code}", url,
|
| 70 |
+
"--connect-timeout", "3", "--max-time", "10"],
|
| 71 |
+
capture_output=True, text=True, timeout=15,
|
| 72 |
+
)
|
| 73 |
+
http_code = r.stdout.strip()
|
| 74 |
+
|
| 75 |
+
if http_code == "429":
|
| 76 |
+
dest.unlink(missing_ok=True)
|
| 77 |
+
return "rate_limited", None
|
| 78 |
+
|
| 79 |
+
if r.returncode != 0 or not dest.is_file() or dest.stat().st_size < 1000:
|
| 80 |
+
dest.unlink(missing_ok=True)
|
| 81 |
+
return "dead", None
|
| 82 |
+
|
| 83 |
+
dims = jpeg_dimensions(dest)
|
| 84 |
+
if not dims or max(dims) < MIN_EDGE:
|
| 85 |
+
dest.unlink(missing_ok=True)
|
| 86 |
+
return "small", None
|
| 87 |
+
|
| 88 |
+
restore_mtime(dest, row.get("date_iso", ""))
|
| 89 |
+
return "ok", {"hash": h, "width": dims[0], "height": dims[1]}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def process_batch(rows: list[dict], out_dir: Path, out_f, dead_f, counters: dict,
|
| 93 |
+
base_delay: float = 1.0) -> list[dict]:
|
| 94 |
+
"""Process rows sequentially with per-request delay. Retries 429s inline."""
|
| 95 |
+
skipped = []
|
| 96 |
+
consecutive_429 = 0
|
| 97 |
+
|
| 98 |
+
for row in rows:
|
| 99 |
+
time.sleep(base_delay)
|
| 100 |
+
|
| 101 |
+
status, result = None, None
|
| 102 |
+
for attempt in range(3):
|
| 103 |
+
status, result = fetch_one(row, out_dir)
|
| 104 |
+
if status != "rate_limited":
|
| 105 |
+
break
|
| 106 |
+
wait = 5 + attempt * 5
|
| 107 |
+
print(f" 429 on attempt {attempt+1}, waiting {wait}s...", flush=True)
|
| 108 |
+
time.sleep(wait)
|
| 109 |
+
|
| 110 |
+
if status == "rate_limited":
|
| 111 |
+
consecutive_429 += 1
|
| 112 |
+
if consecutive_429 >= 5:
|
| 113 |
+
print(f" {consecutive_429} consecutive 429s, cooling down 60s...", flush=True)
|
| 114 |
+
time.sleep(60)
|
| 115 |
+
consecutive_429 = 0
|
| 116 |
+
else:
|
| 117 |
+
consecutive_429 = 0
|
| 118 |
+
|
| 119 |
+
if status == "ok":
|
| 120 |
+
counters["ok"] += 1
|
| 121 |
+
out_f.write(json.dumps(result) + "\n")
|
| 122 |
+
out_f.flush()
|
| 123 |
+
elif status == "rate_limited":
|
| 124 |
+
counters["rate_limited"] += 1
|
| 125 |
+
skipped.append(row)
|
| 126 |
+
elif status == "small":
|
| 127 |
+
counters["small"] += 1
|
| 128 |
+
dead_f.write(row["hash"] + "\n")
|
| 129 |
+
dead_f.flush()
|
| 130 |
+
else:
|
| 131 |
+
counters["dead"] += 1
|
| 132 |
+
dead_f.write(row["hash"] + "\n")
|
| 133 |
+
dead_f.flush()
|
| 134 |
+
|
| 135 |
+
return skipped
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def main():
|
| 139 |
+
import argparse
|
| 140 |
+
parser = argparse.ArgumentParser(description="Fetch Flickr originals for YFCC manifest")
|
| 141 |
+
parser.add_argument("--manifest", type=Path, default=Path("manifest.tsv"),
|
| 142 |
+
help="Path to manifest TSV (default: manifest.tsv)")
|
| 143 |
+
parser.add_argument("--out-dir", type=Path, default=Path("photos"),
|
| 144 |
+
help="Directory for downloaded JPEGs (default: photos/)")
|
| 145 |
+
parser.add_argument("--results-file", type=Path, default=Path("flickr_originals.jsonl"),
|
| 146 |
+
help="JSONL tracking successful downloads (default: flickr_originals.jsonl)")
|
| 147 |
+
parser.add_argument("--dead-file", type=Path, default=Path("flickr_dead.txt"),
|
| 148 |
+
help="File tracking dead/small hashes (default: flickr_dead.txt)")
|
| 149 |
+
parser.add_argument("--tiers", default="medium,large",
|
| 150 |
+
help="Comma-separated resolution tiers to fetch (default: medium,large)")
|
| 151 |
+
parser.add_argument("--fast-delay", type=float, default=0.3,
|
| 152 |
+
help="Delay for known-alive users (default: 0.3)")
|
| 153 |
+
parser.add_argument("--probe-delay", type=float, default=1.0,
|
| 154 |
+
help="Delay for probing unsampled users (default: 1.0)")
|
| 155 |
+
args = parser.parse_args()
|
| 156 |
+
|
| 157 |
+
tiers = set(args.tiers.split(","))
|
| 158 |
+
out_dir = args.out_dir
|
| 159 |
+
results_file = args.results_file
|
| 160 |
+
dead_file = args.dead_file
|
| 161 |
+
|
| 162 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 163 |
+
|
| 164 |
+
# Load manifest rows for requested tiers
|
| 165 |
+
all_rows = []
|
| 166 |
+
with open(args.manifest) as f:
|
| 167 |
+
for row in csv.DictReader(f, delimiter="\t"):
|
| 168 |
+
if row["resolution_tier"] in tiers:
|
| 169 |
+
all_rows.append(row)
|
| 170 |
+
|
| 171 |
+
# Resume: skip already-fetched and known-dead
|
| 172 |
+
done_hashes = set()
|
| 173 |
+
if results_file.is_file():
|
| 174 |
+
for line in results_file.read_text().splitlines():
|
| 175 |
+
done_hashes.add(json.loads(line)["hash"])
|
| 176 |
+
dead_hashes = set()
|
| 177 |
+
if dead_file.is_file():
|
| 178 |
+
dead_hashes = set(dead_file.read_text().splitlines())
|
| 179 |
+
|
| 180 |
+
skip = done_hashes | dead_hashes
|
| 181 |
+
|
| 182 |
+
# Group remaining photos by user
|
| 183 |
+
user_rows = defaultdict(list)
|
| 184 |
+
for r in all_rows:
|
| 185 |
+
if r["hash"] not in skip:
|
| 186 |
+
user_rows[r["uid"]].append(r)
|
| 187 |
+
|
| 188 |
+
# Classify users from prior data
|
| 189 |
+
all_by_uid = defaultdict(list)
|
| 190 |
+
for r in all_rows:
|
| 191 |
+
all_by_uid[r["uid"]].append(r["hash"])
|
| 192 |
+
|
| 193 |
+
alive_uids = set()
|
| 194 |
+
dead_uids = set()
|
| 195 |
+
unsampled_uids = set()
|
| 196 |
+
for uid in user_rows:
|
| 197 |
+
if any(h in done_hashes for h in all_by_uid[uid]):
|
| 198 |
+
alive_uids.add(uid)
|
| 199 |
+
elif any(h in dead_hashes for h in all_by_uid[uid]):
|
| 200 |
+
dead_uids.add(uid)
|
| 201 |
+
else:
|
| 202 |
+
unsampled_uids.add(uid)
|
| 203 |
+
|
| 204 |
+
n_remaining = sum(len(v) for v in user_rows.values())
|
| 205 |
+
print(f"Tiers: {args.tiers} | {len(all_rows)} total, {len(done_hashes)} kept, "
|
| 206 |
+
f"{len(dead_hashes)} known dead, {n_remaining} to probe")
|
| 207 |
+
print(f" Users: {len(alive_uids)} alive, {len(unsampled_uids)} unsampled, {len(dead_uids)} dead")
|
| 208 |
+
print(f" Delays: {args.fast_delay}s fast, {args.probe_delay}s probe")
|
| 209 |
+
|
| 210 |
+
counters = {"ok": len(done_hashes), "dead": 0, "small": 0, "rate_limited": 0}
|
| 211 |
+
|
| 212 |
+
with open(results_file, "a") as out_f, open(dead_file, "a") as dead_f:
|
| 213 |
+
|
| 214 |
+
def fetch_user(uid, rows, delay):
|
| 215 |
+
return process_batch(rows, out_dir, out_f, dead_f, counters, base_delay=delay)
|
| 216 |
+
|
| 217 |
+
all_rate_limited = []
|
| 218 |
+
probed = 0
|
| 219 |
+
|
| 220 |
+
# Phase 1: known-alive users (fast)
|
| 221 |
+
for uid in sorted(alive_uids):
|
| 222 |
+
rows = user_rows.pop(uid, [])
|
| 223 |
+
if not rows:
|
| 224 |
+
continue
|
| 225 |
+
rl = fetch_user(uid, rows, args.fast_delay)
|
| 226 |
+
all_rate_limited.extend(rl)
|
| 227 |
+
probed += len(rows)
|
| 228 |
+
|
| 229 |
+
if probed:
|
| 230 |
+
print(f" alive-users done ({probed} photos): {counters['ok']:,} kept, "
|
| 231 |
+
f"{counters['dead']:,} dead, {counters['small']:,} small", flush=True)
|
| 232 |
+
|
| 233 |
+
# Phase 2: unsampled users -- probe 1, if alive fast-fetch rest
|
| 234 |
+
unsampled_list = sorted(unsampled_uids)
|
| 235 |
+
for i, uid in enumerate(unsampled_list):
|
| 236 |
+
rows = user_rows.pop(uid, [])
|
| 237 |
+
if not rows:
|
| 238 |
+
continue
|
| 239 |
+
|
| 240 |
+
rest = rows[1:]
|
| 241 |
+
ok_before = counters["ok"]
|
| 242 |
+
rl = fetch_user(uid, [rows[0]], args.probe_delay)
|
| 243 |
+
all_rate_limited.extend(rl)
|
| 244 |
+
probed += 1
|
| 245 |
+
|
| 246 |
+
if counters["ok"] > ok_before:
|
| 247 |
+
if rest:
|
| 248 |
+
rl = fetch_user(uid, rest, args.fast_delay)
|
| 249 |
+
all_rate_limited.extend(rl)
|
| 250 |
+
probed += len(rest)
|
| 251 |
+
elif rest:
|
| 252 |
+
all_rate_limited.extend(rest)
|
| 253 |
+
|
| 254 |
+
if (i + 1) % 200 == 0:
|
| 255 |
+
print(f" unsampled {i+1:,}/{len(unsampled_list):,} users: {counters['ok']:,} kept, "
|
| 256 |
+
f"{counters['dead']:,} dead, {counters['small']:,} small, "
|
| 257 |
+
f"{counters['rate_limited']:,} rate-limited", flush=True)
|
| 258 |
+
|
| 259 |
+
print(f" unsampled done: {counters['ok']:,} kept, {counters['dead']:,} dead, "
|
| 260 |
+
f"{counters['small']:,} small", flush=True)
|
| 261 |
+
|
| 262 |
+
# Phase 3: known-dead users
|
| 263 |
+
for uid in sorted(dead_uids):
|
| 264 |
+
rows = user_rows.pop(uid, [])
|
| 265 |
+
if not rows:
|
| 266 |
+
continue
|
| 267 |
+
rl = fetch_user(uid, rows, args.probe_delay)
|
| 268 |
+
all_rate_limited.extend(rl)
|
| 269 |
+
probed += len(rows)
|
| 270 |
+
|
| 271 |
+
print(f" dead-users done: {counters['ok']:,} kept, {counters['dead']:,} dead", flush=True)
|
| 272 |
+
|
| 273 |
+
# Phase 4: deferred/rate-limited
|
| 274 |
+
if all_rate_limited:
|
| 275 |
+
print(f" Deferred/rate-limited: {len(all_rate_limited)} remaining at {args.probe_delay}s", flush=True)
|
| 276 |
+
still_rl = process_batch(all_rate_limited, out_dir, out_f, dead_f, counters)
|
| 277 |
+
if still_rl:
|
| 278 |
+
print(f" {len(still_rl)} still rate-limited after final pass", flush=True)
|
| 279 |
+
|
| 280 |
+
n_files = sum(1 for f in out_dir.iterdir() if f.suffix == ".jpg" and f.stat().st_size > 0)
|
| 281 |
+
print(f"\nDone. {counters['ok']:,} hi-res, {counters['dead']:,} dead, "
|
| 282 |
+
f"{counters['small']:,} small, {counters['rate_limited']:,} still rate-limited")
|
| 283 |
+
print(f"{n_files:,} total files on disk")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
if __name__ == "__main__":
|
| 287 |
+
main()
|
scripts/manifest.tsv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/upload_hf.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Create and upload tar shards to HuggingFace, one at a time to save disk."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import tarfile
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import HfApi
|
| 10 |
+
|
| 11 |
+
SHARD_SIZE = 1_000_000_000 # ~1GB per shard
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_existing_shards(api: HfApi, repo_id: str, prefix: str) -> set:
|
| 15 |
+
"""Check which shards already exist on HF."""
|
| 16 |
+
try:
|
| 17 |
+
files = api.list_repo_files(repo_id, repo_type="dataset")
|
| 18 |
+
return {f for f in files if f.startswith(f"{prefix}/") and f.endswith(".tar")}
|
| 19 |
+
except Exception:
|
| 20 |
+
return set()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def upload_folder_as_shards(api: HfApi, repo_id: str, src_dir: Path, prefix: str, tmp_dir: Path):
|
| 24 |
+
"""Create tar shards from src_dir, upload each, delete after upload."""
|
| 25 |
+
existing = get_existing_shards(api, repo_id, prefix)
|
| 26 |
+
if existing:
|
| 27 |
+
print(f" Found {len(existing)} existing shards, will skip them", flush=True)
|
| 28 |
+
|
| 29 |
+
files = sorted(f for f in src_dir.iterdir() if f.is_file())
|
| 30 |
+
shard_idx = 0
|
| 31 |
+
current_size = 0
|
| 32 |
+
shard_files = []
|
| 33 |
+
|
| 34 |
+
for f in files:
|
| 35 |
+
shard_files.append(f)
|
| 36 |
+
current_size += f.stat().st_size
|
| 37 |
+
|
| 38 |
+
if current_size >= SHARD_SIZE:
|
| 39 |
+
_make_and_upload(api, repo_id, shard_files, prefix, shard_idx, existing, tmp_dir)
|
| 40 |
+
shard_idx += 1
|
| 41 |
+
shard_files = []
|
| 42 |
+
current_size = 0
|
| 43 |
+
|
| 44 |
+
if shard_files:
|
| 45 |
+
_make_and_upload(api, repo_id, shard_files, prefix, shard_idx, existing, tmp_dir)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _make_and_upload(api: HfApi, repo_id: str, files: list, prefix: str, idx: int,
|
| 49 |
+
existing: set, tmp_dir: Path):
|
| 50 |
+
name = f"{prefix}-{idx:04d}.tar"
|
| 51 |
+
repo_path = f"{prefix}/{name}"
|
| 52 |
+
if repo_path in existing:
|
| 53 |
+
print(f" Skipping {name} (already uploaded)", flush=True)
|
| 54 |
+
return
|
| 55 |
+
tar_path = tmp_dir / name
|
| 56 |
+
print(f" Creating {name} ({len(files)} files)...", flush=True)
|
| 57 |
+
|
| 58 |
+
with tarfile.open(tar_path, "w") as tar:
|
| 59 |
+
for f in files:
|
| 60 |
+
tar.add(f, arcname=f.name)
|
| 61 |
+
|
| 62 |
+
size_mb = tar_path.stat().st_size / 1_000_000
|
| 63 |
+
print(f" Uploading {name} ({size_mb:.0f} MB)...", flush=True)
|
| 64 |
+
|
| 65 |
+
api.upload_file(
|
| 66 |
+
path_or_fileobj=str(tar_path),
|
| 67 |
+
path_in_repo=repo_path,
|
| 68 |
+
repo_id=repo_id,
|
| 69 |
+
repo_type="dataset",
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
tar_path.unlink()
|
| 73 |
+
print(f" Done {name}", flush=True)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main():
|
| 77 |
+
parser = argparse.ArgumentParser(description="Upload photo shards to HuggingFace")
|
| 78 |
+
parser.add_argument("--src-dir", type=Path, required=True,
|
| 79 |
+
help="Directory containing photos to upload")
|
| 80 |
+
parser.add_argument("--prefix", default="yfcc",
|
| 81 |
+
help="Prefix for shard names in repo (default: yfcc)")
|
| 82 |
+
parser.add_argument("--repo", default="lightcella/photo-corpus",
|
| 83 |
+
help="HuggingFace dataset repo ID")
|
| 84 |
+
parser.add_argument("--tmp-dir", type=Path, default=Path("."),
|
| 85 |
+
help="Directory for temporary tar files (default: current dir)")
|
| 86 |
+
parser.add_argument("--shard-size", type=int, default=SHARD_SIZE,
|
| 87 |
+
help="Target shard size in bytes (default: 1GB)")
|
| 88 |
+
args = parser.parse_args()
|
| 89 |
+
|
| 90 |
+
global SHARD_SIZE
|
| 91 |
+
SHARD_SIZE = args.shard_size
|
| 92 |
+
|
| 93 |
+
api = HfApi()
|
| 94 |
+
args.tmp_dir.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
|
| 96 |
+
n_files = sum(1 for f in args.src_dir.iterdir() if f.is_file())
|
| 97 |
+
print(f"Uploading {n_files} files from {args.src_dir} as '{args.prefix}' shards...")
|
| 98 |
+
upload_folder_as_shards(api, args.repo, args.src_dir, args.prefix, args.tmp_dir)
|
| 99 |
+
print("All done!")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
main()
|