File size: 7,114 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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | #!/usr/bin/env python3
"""Expand paired manifests to one row per perspective image and candidate audio clip.
Panoramas are only a source format: every entry in ``photo_view_paths`` becomes an
independent image. Parent locations are retained solely for leakage-safe splitting.
"""
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
from pathlib import Path
import pandas as pd
from soundscape_models.utils import resolve_manifest_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--input", action="append", required=True, metavar="DATASET=MANIFEST",
help="Repeat for every source dataset; DATASET overrides source_dataset.",
)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--summary", type=Path)
parser.add_argument("--exclude-source-dataset", action="append", default=["mumbai"])
return parser.parse_args()
def parse_input(value: str) -> tuple[str, Path]:
if "=" not in value:
raise argparse.ArgumentTypeError(f"Expected DATASET=MANIFEST, received {value!r}")
dataset, path = value.split("=", 1)
if not dataset.strip() or not path.strip():
raise argparse.ArgumentTypeError(f"Expected DATASET=MANIFEST, received {value!r}")
return dataset.strip(), Path(path.strip())
def view_values(row: pd.Series) -> list[str]:
raw = str(row.get("photo_view_paths", ""))
values = [value for value in raw.split("|") if value and value.lower() != "nan"]
return values or [str(row.photo_path)]
def main() -> None:
args = parse_args()
blocked = {value.casefold() for value in args.exclude_source_dataset}
rows: list[dict] = []
source_counts: dict[str, int] = {}
for specification in args.input:
dataset, manifest = parse_input(specification)
automatic_dataset = dataset.casefold() == "auto"
if not automatic_dataset and (
dataset.casefold() in blocked or "mumbai" in dataset.casefold()
):
continue
frame = pd.read_csv(manifest, low_memory=False)
required = {"photo_path", "audio_path", "split"}
missing = required - set(frame.columns)
if missing:
raise ValueError(f"{manifest} lacks {sorted(missing)}")
if "audio_target_status" in frame:
frame = frame[frame.audio_target_status.fillna("").eq("ok")].copy()
if "soundaq_target_status" in frame:
acceptable = frame.soundaq_target_status.fillna("").isin(["", "ok"])
frame = frame[acceptable].copy()
if frame.empty:
continue
for source_index, row in frame.iterrows():
row_dataset = (
str(row.get("source_dataset") or "external")
if automatic_dataset else dataset
)
if row_dataset.casefold() in blocked or "mumbai" in row_dataset.casefold():
continue
source_counts[row_dataset] = source_counts.get(row_dataset, 0) + 1
parent = str(row.get("parent_location_id") or row.get("location_id") or row.get("photo_id"))
root = row.get("asset_root") if isinstance(row.get("asset_root"), str) else None
for view_index, value in enumerate(view_values(row)):
resolved = str(resolve_manifest_path(value, asset_root=root, manifest=manifest))
identity = f"{row_dataset}|{parent}|{resolved.lower()}"
view_digest = hashlib.sha1(identity.encode("utf-8")).hexdigest()[:20]
view_id = f"view_{view_digest}"
candidate_source = str(row.get("photo_id") or source_index)
candidate_id = f"{view_id}__{candidate_source}"
output = row.to_dict()
output.update(
{
"training_dataset": row_dataset,
"parent_location_id": parent,
"view_id": view_id,
"view_index": view_index,
"view_path": resolved,
"source_photo_id": candidate_source,
"source_panorama": row.get("panorama", False),
"source_photo_view_paths": row.get("photo_view_paths", row.get("photo_path", "")),
"candidate_id": candidate_id,
# Downstream image tools now see exactly one ordinary image.
"photo_id": view_id,
"location_id": view_id,
"photo_path": resolved,
"photo_view_paths": resolved,
"asset_root": "",
"panorama": False,
# a source row's ImageBind vector can belong to the whole panorama: every view is embedded
# itself by extract_imagebind.py (the vector the pairing cosine uses)
"imagebind_vision_path": "",
}
)
rows.append(output)
result = pd.DataFrame(rows)
if result.empty:
raise SystemExit("No usable image-audio candidates were found")
split_counts = result.groupby(["training_dataset", "parent_location_id"]).split.nunique()
if (split_counts > 1).any():
raise RuntimeError(
"Parent locations cross splits: "
f"{split_counts[split_counts > 1].head().to_dict()}"
)
view_splits = result.groupby(["training_dataset", "view_id"]).split.nunique()
if (view_splits > 1).any():
raise RuntimeError("The same image view appears in multiple splits")
args.output.parent.mkdir(parents=True, exist_ok=True)
result.to_csv(args.output, index=False)
summary = {
"candidate_rows": int(len(result)),
"unique_views": int(result[["training_dataset", "view_id"]].drop_duplicates().shape[0]),
"parent_locations": int(
result[["training_dataset", "parent_location_id"]].drop_duplicates().shape[0]
),
"source_clip_rows": source_counts,
"candidate_rows_by_dataset": result.training_dataset.value_counts().to_dict(),
"views_by_dataset": (
result.drop_duplicates(["training_dataset", "view_id"])
.training_dataset.value_counts().to_dict()
),
"excluded_datasets": args.exclude_source_dataset,
"grain": "one row per perspective image and candidate 10-second clip",
}
summary_path = args.summary or args.output.with_suffix(".summary.json")
summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
print(json.dumps(summary, indent=2))
print(f"Wrote {args.output}")
if __name__ == "__main__":
main()
|