ViewingSoundPAQ / scripts /data_preparation /datasets /select_urbansas_semantic_frames.py
xiaohaoy's picture
Initial release
16231ab verified
Raw History Blame Contribute Delete
13 kB
#!/usr/bin/env python3
"""Select one vehicle/person/background frame for every UrbanSAS video.
Each ten-second video remains one training unit. A deterministic desired visual
state balances the corpus across visible vehicles, people without visible
vehicles, and background frames. Within the selected state, the frame with the
highest ImageBind audio cosine is retained.
"""
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 hashlib
import json
import shutil
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from PIL import Image, ImageFile
from tqdm import tqdm
from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation
from rebuild_urbansas_best_frames import normalized, write_json
from soundscape_models.utils import select_device
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
STATES = ("vehicle_visible", "person_no_vehicle", "background")
VEHICLE_LABELS = {"car", "bus", "truck", "motorbike"}
def parse_args():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--manifest", type=Path, required=True)
p.add_argument("--score-dir", type=Path, required=True)
p.add_argument("--annotations", type=Path, default=Path("data/urbansas/extracted/annotations/video_annotations.csv"))
p.add_argument("--output-dir", type=Path, default=Path("data/urbansas_whole/semantic_frames"))
p.add_argument("--output-manifest", type=Path, default=Path("data/urbansas_whole_semantic_manifest.csv"))
p.add_argument("--semantic-model", default="nvidia/segformer-b5-finetuned-ade-640-640")
p.add_argument("--person-threshold", type=float, default=0.01)
p.add_argument("--expected-candidates", type=int, default=20)
p.add_argument("--batch-size", type=int, default=20)
p.add_argument("--device", default="cuda")
p.add_argument("--max-rows", type=int, default=None)
p.add_argument("--allow-failures", action="store_true")
return p.parse_args()
def load_audio_index(path):
frame = pd.read_csv(path, low_memory=False)
key = "source_photo_id" if "source_photo_id" in frame else "photo_id"
required = {key, "imagebind_audio_path"}
missing = required - set(frame.columns)
if missing:
raise ValueError(f"Embedding manifest missing {sorted(missing)}")
if frame[key].astype(str).duplicated().any():
raise ValueError(f"Duplicate embedding keys in {path}")
result = {}
for _, row in frame.iterrows():
if "image_audio_cosine" in frame and pd.notna(row.get("image_audio_cosine")):
midpoint = float(row["image_audio_cosine"])
else:
with np.load(row.imagebind_vision_path, allow_pickle=False) as archive:
vision = normalized(archive["embedding"])
with np.load(row.imagebind_audio_path, allow_pickle=False) as archive:
audio = normalized(archive["embedding"])
midpoint = float(np.dot(vision.reshape(-1), audio.reshape(-1)))
result[str(row[key])] = {
"audio_embedding_path": str(row.imagebind_audio_path),
"midpoint_cosine": midpoint,
}
return result
def vehicle_frames(path):
frame = pd.read_csv(path, low_memory=False)
visible = pd.to_numeric(frame.visibility, errors="coerce").fillna(0).gt(0)
selected = frame[
visible & frame.label.astype(str).str.casefold().isin(VEHICLE_LABELS)
]
result = {}
for (filename, frame_id), group in selected.groupby(["filename", "frame_id"]):
result.setdefault(str(filename), {})[int(frame_id)] = int(len(group))
return result
def person_class_ids(model):
labels = {
int(index): str(label).casefold()
for index, label in model.config.id2label.items()
}
ids = [
index for index, label in labels.items()
if any(word in label for word in ("person", "people", "pedestrian", "human"))
]
if not ids:
raise RuntimeError("Semantic model exposes no person class")
return ids
@torch.inference_mode()
def person_scores(processor, model, paths, class_ids, device, batch_size):
values = []
for start in range(0, len(paths), batch_size):
images = []
for path in paths[start:start + batch_size]:
with Image.open(path) as source:
images.append(source.convert("RGB").copy())
pixels = processor(images=images, return_tensors="pt")["pixel_values"].to(device)
with torch.autocast(device.type, dtype=torch.float16, enabled=device.type == "cuda"):
logits = model(pixel_values=pixels).logits
probabilities = logits.float().softmax(1)[:, class_ids].sum(1)
values.append(probabilities.mean(dim=(1, 2)).cpu().numpy())
del pixels, logits, probabilities
return np.concatenate(values)
def desired_state(recording):
digest = hashlib.sha1(str(recording).encode("utf-8")).digest()
return STATES[int.from_bytes(digest[:4], "big") % len(STATES)]
def choose_state(desired, available):
start = STATES.index(desired)
for offset in range(len(STATES)):
state = STATES[(start + offset) % len(STATES)]
if available.get(state):
return state
raise RuntimeError("No semantic frame state is available")
def main():
args = parse_args()
source = pd.read_csv(args.manifest, low_memory=False)
if args.max_rows is not None:
source = source.iloc[:args.max_rows].copy()
if source.empty:
raise ValueError("Input manifest is empty")
vehicle_by_file = vehicle_frames(args.annotations)
selected_dir = args.output_dir / "selected_frames"
record_dir = args.output_dir / "selection_records"
for path in (selected_dir, record_dir):
path.mkdir(parents=True, exist_ok=True)
device = select_device(args.device)
processor = AutoImageProcessor.from_pretrained(args.semantic_model)
semantic = AutoModelForSemanticSegmentation.from_pretrained(args.semantic_model).eval().to(device)
person_ids = person_class_ids(semantic)
rows, failures = [], []
for row in tqdm(source.to_dict(orient="records"), desc="UrbanSAS semantic frames"):
recording = str(row["recording_id"])
photo_id = str(row["photo_id"])
selected_path = (selected_dir / f"{recording}.jpg").resolve()
record_path = record_dir / f"{recording}.json"
try:
if record_path.exists() and selected_path.exists():
selection = json.loads(record_path.read_text(encoding="utf-8"))
else:
score_path = args.score_dir / f"{recording}.json"
if not score_path.exists():
raise FileNotFoundError(f"Missing frame score record: {score_path}")
scored = json.loads(score_path.read_text(encoding="utf-8"))
candidates = [Path(path) for path in scored["candidate_paths"]]
cosine = np.asarray(scored["cosines"], np.float32)
if len(candidates) != len(cosine) or not all(path.exists() for path in candidates):
raise RuntimeError("Frame score record and candidate files disagree")
people = person_scores(
processor, semantic, candidates, person_ids, device,
args.batch_size,
)
vehicle_counts = vehicle_by_file.get(recording, {})
states = []
available = {state: [] for state in STATES}
for index in range(len(candidates)):
vehicle = int(vehicle_counts.get(index, 0))
if vehicle > 0:
state = "vehicle_visible"
elif float(people[index]) >= args.person_threshold:
state = "person_no_vehicle"
else:
state = "background"
states.append(state)
available[state].append(index)
wanted = desired_state(recording)
selected_state = choose_state(wanted, available)
indices = np.asarray(available[selected_state], dtype=np.int64)
best = int(indices[np.argmax(cosine[indices])])
global_order = np.argsort(cosine)[::-1]
second = int(global_order[1]) if len(global_order) > 1 else best
shutil.copy2(candidates[best], selected_path)
selection = {
"recording_id": recording,
"desired_frame_state": wanted,
"selected_frame_state": selected_state,
"state_fallback_used": selected_state != wanted,
"state_counts": {state: int(len(indices)) for state, indices in available.items()},
"selected_frame_index": best,
"selected_timestamp_seconds": float(best / float(scored["candidate_fps"])),
"selected_vehicle_count": int(vehicle_by_file.get(recording, {}).get(best, 0)),
"selected_person_fraction": float(people[best]),
"candidate_count": int(len(cosine)),
"best_state_cosine": float(cosine[best]),
"global_best_cosine": float(cosine[global_order[0]]),
"second_global_cosine": float(cosine[second]),
"midpoint_cosine": float(scored["midpoint_cosine"]),
"semantic_model": args.semantic_model,
"person_threshold": float(args.person_threshold),
"selected_frame": str(selected_path),
}
write_json(record_path, selection)
rebuilt = dict(row)
rebuilt.update({
"photo_path": str(selected_path),
"pairing_status": "accepted_synchronized_semantic_frame",
"pairing_strength": "strong",
"pair_selection_method": "balanced_semantic_state_then_highest_imagebind_cosine",
"frame_state": selection["selected_frame_state"],
"desired_frame_state": selection["desired_frame_state"],
"frame_state_fallback": bool(selection["state_fallback_used"]),
"visible_vehicle_count": selection["selected_vehicle_count"],
"person_fraction": selection["selected_person_fraction"],
"image_audio_cosine": selection["best_state_cosine"],
"unconstrained_best_image_audio_cosine": selection["global_best_cosine"],
"midpoint_image_audio_cosine": selection["midpoint_cosine"],
"semantic_state_cosine_cost": selection["global_best_cosine"] - selection["best_state_cosine"],
"selected_frame_timestamp_seconds": selection["selected_timestamp_seconds"],
"frame_candidate_count": selection["candidate_count"],
"frame_candidate_status": "complete" if not args.expected_candidates or int(selection["candidate_count"]) == args.expected_candidates else "short_source_video",
})
rows.append(rebuilt)
except Exception as error:
failures.append({"recording_id": recording, "error": f"{type(error).__name__}: {error}"})
if failures and not args.allow_failures:
raise RuntimeError(f"Failed {len(failures)} videos: {failures[:5]}")
output = pd.DataFrame(rows)
if output.empty or output.recording_id.duplicated().any():
raise RuntimeError("Semantic output must contain one unique row per video")
if args.max_rows is None and len(output) != 1080:
raise RuntimeError(f"Expected 1,080 completed videos, found {len(output)}")
args.output_manifest.parent.mkdir(parents=True, exist_ok=True)
temporary = args.output_manifest.with_suffix(args.output_manifest.suffix + ".tmp")
output.to_csv(temporary, index=False)
temporary.replace(args.output_manifest)
report = {
"rows": int(len(output)),
"unique_videos": int(output.recording_id.nunique()),
"source_subsets": output.source_subset.value_counts().to_dict(),
"selected_states": output.frame_state.value_counts().to_dict(),
"desired_states": output.desired_frame_state.value_counts().to_dict(),
"fallback_fraction": float(output.frame_state_fallback.mean()),
"mean_semantic_state_cosine_cost": float(output.semantic_state_cosine_cost.mean()),
"failures": failures,
}
write_json(args.output_manifest.with_suffix(".quality.json"), report)
print(json.dumps(report, indent=2))
print(f"Wrote {args.output_manifest}")
if __name__ == "__main__":
main()