Download scripts/fetch_flickr.py from lightcella/photo-corpus: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/lightcella/photo-corpus/resolve/main/scripts/fetch_flickr.py
- Command line
-
hf download hf://datasets/lightcella/photo-corpus/scripts/fetch_flickr.py
-
curl -L -o fetch_flickr.py https://huggingface.co/datasets/lightcella/photo-corpus/resolve/main/scripts/fetch_flickr.py
10.6 kB
| #!/usr/bin/env python3 | |
| """ | |
| Fetch Flickr _o originals for YFCC photos by tier. | |
| Downloads only if >500px max edge. Resumable -- skips existing files and known-dead hashes. | |
| Prioritizes known-alive users (fast), probes unsampled users, defers dead users. | |
| """ | |
| import csv | |
| import json | |
| import os | |
| import struct | |
| import subprocess | |
| import sys | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| MIN_EDGE = 501 | |
| def jpeg_dimensions(path: Path) -> tuple[int, int] | None: | |
| try: | |
| with open(path, "rb") as f: | |
| data = f.read(64 * 1024) | |
| i = 2 | |
| while i < len(data) - 9: | |
| if data[i] != 0xFF: | |
| break | |
| marker = data[i + 1] | |
| if marker in (0xC0, 0xC1, 0xC2): | |
| h = struct.unpack(">H", data[i + 5 : i + 7])[0] | |
| w = struct.unpack(">H", data[i + 7 : i + 9])[0] | |
| return w, h | |
| length = struct.unpack(">H", data[i + 2 : i + 4])[0] | |
| i += 2 + length | |
| except Exception: | |
| pass | |
| return None | |
| def restore_mtime(dest: Path, date_iso: str) -> None: | |
| """Set file mtime from manifest date so Lightcella uses it as fallback.""" | |
| if not date_iso: | |
| return | |
| try: | |
| from datetime import datetime | |
| dt = datetime.fromisoformat(date_iso.replace("Z", "+00:00")) | |
| ts = dt.timestamp() | |
| if ts > 0: | |
| os.utime(dest, (ts, ts)) | |
| except (ValueError, OSError): | |
| pass | |
| def fetch_one(row: dict, out_dir: Path) -> tuple[str, dict | None]: | |
| """Returns (status, result). status: 'ok', 'small', 'dead', 'rate_limited'.""" | |
| h = row["hash"] | |
| dest = out_dir / f"{h}.jpg" | |
| if dest.is_file() and dest.stat().st_size > 0: | |
| dims = jpeg_dimensions(dest) | |
| if dims and max(dims) >= MIN_EDGE: | |
| return "ok", {"hash": h, "width": dims[0], "height": dims[1]} | |
| return "small", None | |
| sid, pid, sec = row["serverid"], row["photoid"], row["secret"] | |
| url = f"https://live.staticflickr.com/{sid}/{pid}_{sec}_o.jpg" | |
| r = subprocess.run( | |
| ["curl", "-sL", "-o", str(dest), "-w", "%{http_code}", url, | |
| "--connect-timeout", "3", "--max-time", "10"], | |
| capture_output=True, text=True, timeout=15, | |
| ) | |
| http_code = r.stdout.strip() | |
| if http_code == "429": | |
| dest.unlink(missing_ok=True) | |
| return "rate_limited", None | |
| if r.returncode != 0 or not dest.is_file() or dest.stat().st_size < 1000: | |
| dest.unlink(missing_ok=True) | |
| return "dead", None | |
| dims = jpeg_dimensions(dest) | |
| if not dims or max(dims) < MIN_EDGE: | |
| dest.unlink(missing_ok=True) | |
| return "small", None | |
| restore_mtime(dest, row.get("date_iso", "")) | |
| return "ok", {"hash": h, "width": dims[0], "height": dims[1]} | |
| def process_batch(rows: list[dict], out_dir: Path, out_f, dead_f, counters: dict, | |
| base_delay: float = 1.0) -> list[dict]: | |
| """Process rows sequentially with per-request delay. Retries 429s inline.""" | |
| skipped = [] | |
| consecutive_429 = 0 | |
| for row in rows: | |
| time.sleep(base_delay) | |
| status, result = None, None | |
| for attempt in range(3): | |
| status, result = fetch_one(row, out_dir) | |
| if status != "rate_limited": | |
| break | |
| wait = 5 + attempt * 5 | |
| print(f" 429 on attempt {attempt+1}, waiting {wait}s...", flush=True) | |
| time.sleep(wait) | |
| if status == "rate_limited": | |
| consecutive_429 += 1 | |
| if consecutive_429 >= 5: | |
| print(f" {consecutive_429} consecutive 429s, cooling down 60s...", flush=True) | |
| time.sleep(60) | |
| consecutive_429 = 0 | |
| else: | |
| consecutive_429 = 0 | |
| if status == "ok": | |
| counters["ok"] += 1 | |
| out_f.write(json.dumps(result) + "\n") | |
| out_f.flush() | |
| elif status == "rate_limited": | |
| counters["rate_limited"] += 1 | |
| skipped.append(row) | |
| elif status == "small": | |
| counters["small"] += 1 | |
| dead_f.write(row["hash"] + "\n") | |
| dead_f.flush() | |
| else: | |
| counters["dead"] += 1 | |
| dead_f.write(row["hash"] + "\n") | |
| dead_f.flush() | |
| return skipped | |
| def main(): | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Fetch Flickr originals for YFCC manifest") | |
| parser.add_argument("--manifest", type=Path, default=Path("manifest.tsv"), | |
| help="Path to manifest TSV (default: manifest.tsv)") | |
| parser.add_argument("--out-dir", type=Path, default=Path("photos"), | |
| help="Directory for downloaded JPEGs (default: photos/)") | |
| parser.add_argument("--results-file", type=Path, default=Path("flickr_originals.jsonl"), | |
| help="JSONL tracking successful downloads (default: flickr_originals.jsonl)") | |
| parser.add_argument("--dead-file", type=Path, default=Path("flickr_dead.txt"), | |
| help="File tracking dead/small hashes (default: flickr_dead.txt)") | |
| parser.add_argument("--tiers", default="medium,large", | |
| help="Comma-separated resolution tiers to fetch (default: medium,large)") | |
| parser.add_argument("--fast-delay", type=float, default=0.3, | |
| help="Delay for known-alive users (default: 0.3)") | |
| parser.add_argument("--probe-delay", type=float, default=1.0, | |
| help="Delay for probing unsampled users (default: 1.0)") | |
| args = parser.parse_args() | |
| tiers = set(args.tiers.split(",")) | |
| out_dir = args.out_dir | |
| results_file = args.results_file | |
| dead_file = args.dead_file | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| # Load manifest rows for requested tiers | |
| all_rows = [] | |
| with open(args.manifest) as f: | |
| for row in csv.DictReader(f, delimiter="\t"): | |
| if row["resolution_tier"] in tiers: | |
| all_rows.append(row) | |
| # Resume: skip already-fetched and known-dead | |
| done_hashes = set() | |
| if results_file.is_file(): | |
| for line in results_file.read_text().splitlines(): | |
| done_hashes.add(json.loads(line)["hash"]) | |
| dead_hashes = set() | |
| if dead_file.is_file(): | |
| dead_hashes = set(dead_file.read_text().splitlines()) | |
| skip = done_hashes | dead_hashes | |
| # Group remaining photos by user | |
| user_rows = defaultdict(list) | |
| for r in all_rows: | |
| if r["hash"] not in skip: | |
| user_rows[r["uid"]].append(r) | |
| # Classify users from prior data | |
| all_by_uid = defaultdict(list) | |
| for r in all_rows: | |
| all_by_uid[r["uid"]].append(r["hash"]) | |
| alive_uids = set() | |
| dead_uids = set() | |
| unsampled_uids = set() | |
| for uid in user_rows: | |
| if any(h in done_hashes for h in all_by_uid[uid]): | |
| alive_uids.add(uid) | |
| elif any(h in dead_hashes for h in all_by_uid[uid]): | |
| dead_uids.add(uid) | |
| else: | |
| unsampled_uids.add(uid) | |
| n_remaining = sum(len(v) for v in user_rows.values()) | |
| print(f"Tiers: {args.tiers} | {len(all_rows)} total, {len(done_hashes)} kept, " | |
| f"{len(dead_hashes)} known dead, {n_remaining} to probe") | |
| print(f" Users: {len(alive_uids)} alive, {len(unsampled_uids)} unsampled, {len(dead_uids)} dead") | |
| print(f" Delays: {args.fast_delay}s fast, {args.probe_delay}s probe") | |
| counters = {"ok": len(done_hashes), "dead": 0, "small": 0, "rate_limited": 0} | |
| with open(results_file, "a") as out_f, open(dead_file, "a") as dead_f: | |
| def fetch_user(uid, rows, delay): | |
| return process_batch(rows, out_dir, out_f, dead_f, counters, base_delay=delay) | |
| all_rate_limited = [] | |
| probed = 0 | |
| # Phase 1: known-alive users (fast) | |
| for uid in sorted(alive_uids): | |
| rows = user_rows.pop(uid, []) | |
| if not rows: | |
| continue | |
| rl = fetch_user(uid, rows, args.fast_delay) | |
| all_rate_limited.extend(rl) | |
| probed += len(rows) | |
| if probed: | |
| print(f" alive-users done ({probed} photos): {counters['ok']:,} kept, " | |
| f"{counters['dead']:,} dead, {counters['small']:,} small", flush=True) | |
| # Phase 2: unsampled users -- probe 1, if alive fast-fetch rest | |
| unsampled_list = sorted(unsampled_uids) | |
| for i, uid in enumerate(unsampled_list): | |
| rows = user_rows.pop(uid, []) | |
| if not rows: | |
| continue | |
| rest = rows[1:] | |
| ok_before = counters["ok"] | |
| rl = fetch_user(uid, [rows[0]], args.probe_delay) | |
| all_rate_limited.extend(rl) | |
| probed += 1 | |
| if counters["ok"] > ok_before: | |
| if rest: | |
| rl = fetch_user(uid, rest, args.fast_delay) | |
| all_rate_limited.extend(rl) | |
| probed += len(rest) | |
| elif rest: | |
| all_rate_limited.extend(rest) | |
| if (i + 1) % 200 == 0: | |
| print(f" unsampled {i+1:,}/{len(unsampled_list):,} users: {counters['ok']:,} kept, " | |
| f"{counters['dead']:,} dead, {counters['small']:,} small, " | |
| f"{counters['rate_limited']:,} rate-limited", flush=True) | |
| print(f" unsampled done: {counters['ok']:,} kept, {counters['dead']:,} dead, " | |
| f"{counters['small']:,} small", flush=True) | |
| # Phase 3: known-dead users | |
| for uid in sorted(dead_uids): | |
| rows = user_rows.pop(uid, []) | |
| if not rows: | |
| continue | |
| rl = fetch_user(uid, rows, args.probe_delay) | |
| all_rate_limited.extend(rl) | |
| probed += len(rows) | |
| print(f" dead-users done: {counters['ok']:,} kept, {counters['dead']:,} dead", flush=True) | |
| # Phase 4: deferred/rate-limited | |
| if all_rate_limited: | |
| print(f" Deferred/rate-limited: {len(all_rate_limited)} remaining at {args.probe_delay}s", flush=True) | |
| still_rl = process_batch(all_rate_limited, out_dir, out_f, dead_f, counters) | |
| if still_rl: | |
| print(f" {len(still_rl)} still rate-limited after final pass", flush=True) | |
| n_files = sum(1 for f in out_dir.iterdir() if f.suffix == ".jpg" and f.stat().st_size > 0) | |
| print(f"\nDone. {counters['ok']:,} hi-res, {counters['dead']:,} dead, " | |
| f"{counters['small']:,} small, {counters['rate_limited']:,} still rate-limited") | |
| print(f"{n_files:,} total files on disk") | |
| if __name__ == "__main__": | |
| main() | |