File size: 7,772 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 | #!/usr/bin/env python3
"""Score images with the user's street-view-like classifier (LORA_J) and filter a manifest.
Classifier: --classifier-root (default $STREETVIEW_CLASSIFIER_ROOT or models/third_party/classify_street_like_view; weights in
<root>/../models/lora_J):
DINOv3-L + LoRA (r=32) CLS || SegFormer-b0 GAP (512) || Places365 softmax (365) -> MLP -> sigmoid.
Threshold from its metrics.json (0.687 = max recall at precision >= 0.90 on its validation set).
Positive = an image that could function as a street-level urban observation (street-view-like):
no single object/person/animal/plant close-ups, no indoor/transit interiors, no parks/beaches/natural
scenes without street context, no skylines or aerial views.
Two uses in runners/run_yfcc_expansion.sh / runners/run_sonicurban.sh:
keyframes score the keyframes of each video; a video passes if >= --min-group-fraction of its
keyframes are street-view-like (--filter-list: write the filtered video list)
frames score candidate frames; only street-view-like frames stay candidates
(optionally also require --min-group-fraction per --group-column)
Scores are cached in <output>.scores.csv so reruns only score new images.
"""
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 sys
from pathlib import Path
import numpy as np
import pandas as pd
import os
DEFAULT_ROOT = Path(os.environ.get("STREETVIEW_CLASSIFIER_ROOT", "models/third_party/classify_street_like_view"))
def parse_args():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--input", type=Path, required=True, help="CSV with an image path column")
p.add_argument("--path-column", default="photo_path")
p.add_argument("--group-column", default=None, help="e.g. video_id / recording_id for a per-group rule")
p.add_argument("--min-group-fraction", type=float, default=0.0)
p.add_argument("--output", type=Path, required=True, help="kept rows (same columns + scores)")
p.add_argument("--filter-list", type=Path, default=None, help="keyframes mode: video list to filter by group")
p.add_argument("--filter-key", default="video_id")
p.add_argument("--filter-output", type=Path, default=None)
p.add_argument("--classifier-root", type=Path, default=DEFAULT_ROOT)
p.add_argument("--model-dir", type=Path, default=None, help="default <classifier-root>/../models/lora_J")
p.add_argument("--threshold", type=float, default=None)
p.add_argument("--places365-cache", type=Path, default=Path.home() / ".cache" / "places365")
p.add_argument("--batch-size", type=int, default=16)
p.add_argument("--device", default="cuda")
return p.parse_args()
def main():
a = parse_args()
import torch
from PIL import Image
from tqdm import tqdm
sys.path.insert(0, str(a.classifier_root))
from core.features import (download_places365_weights, load_places365, load_segformer, # noqa: E402
places365_embed, segformer_embed)
from core.model import load_trained_model # noqa: E402
model_dir = a.model_dir or (a.classifier_root.parent / "models" / "lora_J")
if not (model_dir / "head.pt").exists():
model_dir = a.classifier_root / "models" / "lora_J"
device = torch.device(a.device if torch.cuda.is_available() else "cpu")
frame = pd.read_csv(a.input, low_memory=False)
if a.filter_list is not None and a.group_column: # only score groups that are still candidates
allowed = set(pd.read_csv(a.filter_list, usecols=[a.filter_key], low_memory=False)[a.filter_key].astype(str))
frame = frame[frame[a.group_column].astype(str).isin(allowed)].reset_index(drop=True)
paths = frame[a.path_column].astype(str)
cache = a.output.with_suffix(".scores.csv")
scores = {}
if cache.exists():
old = pd.read_csv(cache)
scores = dict(zip(old.path.astype(str), old.streetview_probability))
todo = sorted(set(paths) - set(scores))
print(f"{len(frame)} rows, {paths.nunique()} images, {len(todo)} to score with {model_dir}", flush=True)
processor, model, meta = load_trained_model(model_dir, device)
threshold = a.threshold if a.threshold is not None else float(meta["threshold"])
if todo:
seg_proc, seg_model = load_segformer(device=device)
p365, p365_tf = load_places365(download_places365_weights(a.places365_cache), device=device)
new = []
for start in tqdm(range(0, len(todo), a.batch_size), desc="Street-view-like"):
batch = todo[start:start + a.batch_size]
images, extras, ok = [], [], []
for path in batch:
try:
with Image.open(path) as im:
img = im.convert("RGB")
extras.append(np.concatenate([segformer_embed(img, seg_proc, seg_model, device),
places365_embed(img, p365, p365_tf, device)]))
images.append(img); ok.append(True)
except Exception:
images.append(Image.new("RGB", (224, 224))); extras.append(np.zeros(877, np.float32)); ok.append(False)
pixels = processor(images=images, return_tensors="pt").pixel_values.to(device)
with torch.no_grad():
prob = torch.sigmoid(model(pixels, torch.tensor(np.stack(extras), dtype=torch.float32, device=device)))
prob = prob.float().cpu().numpy().reshape(-1)
for path, pr, good in zip(batch, prob, ok):
scores[path] = float(pr) if good else np.nan
new.append((path, scores[path]))
if (start // a.batch_size) % 200 == 0 or start + a.batch_size >= len(todo):
a.output.parent.mkdir(parents=True, exist_ok=True)
pd.DataFrame(list(scores.items()), columns=["path", "streetview_probability"]).to_csv(cache, index=False)
frame["streetview_probability"] = paths.map(scores)
frame["is_streetview_like"] = frame.streetview_probability.ge(threshold)
keep = frame.is_streetview_like.copy()
if a.group_column:
frame["group_streetview_fraction"] = frame.is_streetview_like.groupby(frame[a.group_column]).transform("mean")
if a.min_group_fraction > 0:
keep &= frame.group_streetview_fraction.ge(a.min_group_fraction)
a.output.parent.mkdir(parents=True, exist_ok=True)
frame.to_csv(a.output.with_suffix(".all.csv"), index=False)
frame[keep].to_csv(a.output, index=False)
print(f"threshold {threshold:.3f}: {int(frame.is_streetview_like.sum())}/{len(frame)} images street-view-like; "
f"{int(keep.sum())} rows kept -> {a.output}")
if a.group_column:
g = frame.groupby(a.group_column).group_streetview_fraction.first()
passed = set(g.index[g.ge(max(a.min_group_fraction, 1e-9))])
print(f"groups: {len(passed)}/{len(g)} pass (fraction >= {a.min_group_fraction})")
if a.filter_list is not None:
lst = pd.read_csv(a.filter_list, low_memory=False, dtype={"hash": str, "uid": str})
out = lst[lst[a.filter_key].astype(str).isin({str(x) for x in passed})]
target = a.filter_output or a.output.with_name(a.output.stem + "_videos.csv")
out.to_csv(target, index=False)
print(f"filtered list: {len(out)}/{len(lst)} -> {target}")
if __name__ == "__main__":
main()
|