#!/usr/bin/env python3 """ Fix all 18 city datasets to SIGMOD-compatible object_dict format. Dutch cities: download lod12 + lod22 joblibs → combine as cands/index Tokyo/Kansai: download object_dict_combined.joblib → fix mesh records SIGMOD format: {'cands': {id: {'polygon_mesh': [...], 'vertices': array, 'centroid': array}}, 'index': {id: {'polygon_mesh': [...], 'vertices': array, 'centroid': array}}, 'mapping_dict': {'cands': {int→id}, 'index': {int→id}}, 'inv_mapping_dict': {'cands': {id→int}, 'index': {id→int}}} """ import os, sys, gc, numpy as np from huggingface_hub import hf_hub_download, HfApi api = HfApi() REPO = "eduzrh/STER" TMPDIR = "/root/autodl-tmp/fix_tmp" os.makedirs(TMPDIR, exist_ok=True) DUTCH = ["amsterdam", "rotterdam", "hague", "utrecht", "eindhoven", "groningen", "maastricht"] JAPAN = ["chiyoda", "shinjuku", "setagaya", "chuo", "ota", "minato", "bunkyo", "koto", "kyoto", "osaka", "sakai"] def compute_vertices_centroid(mesh): """Given polygon_mesh (list of surfaces as [[x,y,z],...]), return (unique_vertices, centroid).""" if isinstance(mesh, dict): mesh = mesh.get("polygon_mesh", []) if not mesh: return np.zeros((0, 3), dtype=np.float64), np.zeros(3, dtype=np.float64) all_v = [] for surf in mesh: if isinstance(surf, (list, np.ndarray)) and len(surf) >= 3: all_v.extend(surf) if not all_v: return np.zeros((0, 3), dtype=np.float64), np.zeros(3, dtype=np.float64) arr = np.asarray(all_v, dtype=np.float64) unique = np.unique(arr, axis=0) centroid = unique.mean(axis=0) return unique, centroid def fix_mesh_records(side_dict): """Convert {id: mesh} to {id: {polygon_mesh, vertices, centroid}}.""" fixed = {} for bid, mesh in side_dict.items(): pm = mesh.get("polygon_mesh", mesh) if isinstance(mesh, dict) else mesh vertices, centroid = compute_vertices_centroid(pm) fixed[bid] = { 'polygon_mesh': pm, 'vertices': vertices, 'centroid': centroid, } return fixed def build_object_dict(cands_dict, index_dict): """Build full SIGMOD object_dict from two side dicts.""" fixed_cands = fix_mesh_records(cands_dict) fixed_index = fix_mesh_records(index_dict) od = {'cands': fixed_cands, 'index': fixed_index} od['mapping_dict'] = { 'cands': {i: k for i, k in enumerate(sorted(fixed_cands))}, 'index': {i: k for i, k in enumerate(sorted(fixed_index))}, } od['inv_mapping_dict'] = { 'cands': {k: i for i, k in enumerate(sorted(fixed_cands))}, 'index': {k: i for i, k in enumerate(sorted(fixed_index))}, } return od def download_file(city, fname): """Download a file from HF and return local path.""" local = os.path.join(TMPDIR, f"{city}_{fname}") if os.path.exists(local): os.unlink(local) try: # Try direct download path = hf_hub_download(REPO, f"data/{city}/{fname}", repo_type="dataset", cache_dir=TMPDIR, local_files_only=False) # Copy to our temp location import shutil shutil.copy(path, local) return local except Exception as e: print(f" ERROR downloading {fname}: {e}") return None def process_dutch(city): """Fix one Dutch city: lod12→cands, lod22→index.""" import joblib print(f"\n{'='*60}") print(f"[{city}] Dutch format: merging lod12 + lod22") # Download p12 = download_file(city, "object_dict_lod12.joblib") p22 = download_file(city, "object_dict_lod22.joblib") if not p12 or not p22: return False mb12 = os.path.getsize(p12)/1e6 mb22 = os.path.getsize(p22)/1e6 print(f" lod12: {mb12:.1f} MB, lod22: {mb22:.1f} MB") od12 = joblib.load(p12) od22 = joblib.load(p22) print(f" lod12: {len(od12)} buildings, lod22: {len(od22)} buildings") # Find common buildings common = sorted(set(od12) & set(od22)) print(f" Common (both LODs): {len(common)}") # Build SIGMOD dict cands = {bid: od12[bid] for bid in common} index = {bid: od22[bid] for bid in common} od = build_object_dict(cands, index) print(f" Built: cands={len(od['cands'])}, index={len(od['index'])}") # Verify sid = next(iter(od['cands'])) s = od['cands'][sid] print(f" Sample: keys={list(s.keys())}, vertices shape={s['vertices'].shape}, centroid={s['centroid']}") # Save local = os.path.join(TMPDIR, f"{city}_object_dict_raw.joblib") joblib.dump(od, local, compress=3) new_mb = os.path.getsize(local)/1e6 print(f" Saved: {new_mb:.1f} MB (was {mb12+mb22:.1f} MB)") # Upload print(f" Uploading...") api.upload_file(path_or_fileobj=local, path_in_repo=f"data/{city}/object_dict_raw.joblib", repo_id=REPO, repo_type="dataset") print(f" Done.") os.unlink(p12); os.unlink(p22); os.unlink(local) gc.collect() return True def process_japan(city): """Fix one Japan city: fix mesh records in existing combined joblib.""" import joblib print(f"\n{'='*60}") print(f"[{city}] Japan format: fixing mesh records") p = download_file(city, "object_dict_combined.joblib") if not p: return False mb = os.path.getsize(p)/1e6 print(f" Size: {mb:.1f} MB") od = joblib.load(p) print(f" Keys: {list(od.keys())}") if 'cands' not in od or 'index' not in od: print(f" ERROR: missing cands/index keys") os.unlink(p) return False print(f" cands: {len(od['cands'])}, index: {len(od['index'])}") # Fix fixed = build_object_dict(od['cands'], od['index']) print(f" Fixed: cands={len(fixed['cands'])}, index={len(fixed['index'])}") sid = next(iter(fixed['cands'])) s = fixed['cands'][sid] print(f" Sample: keys={list(s.keys())}, vertices shape={s['vertices'].shape}") local = os.path.join(TMPDIR, f"{city}_object_dict_raw.joblib") joblib.dump(fixed, local, compress=3) new_mb = os.path.getsize(local)/1e6 print(f" Saved: {new_mb:.1f} MB") print(f" Uploading...") api.upload_file(path_or_fileobj=local, path_in_repo=f"data/{city}/object_dict_raw.joblib", repo_id=REPO, repo_type="dataset") print(f" Done.") os.unlink(p); os.unlink(local) gc.collect() return True if __name__ == "__main__": import sys city_arg = sys.argv[1] if len(sys.argv) > 1 else None if city_arg: if city_arg in DUTCH: process_dutch(city_arg) elif city_arg in JAPAN: process_japan(city_arg) else: print(f"Unknown: {city_arg}") else: for city in JAPAN: try: process_japan(city) except Exception as e: print(f"[{city}] FAILED: {e}") for city in DUTCH: try: process_dutch(city) except Exception as e: print(f"[{city}] FAILED: {e}") print("\n=== ALL DONE ===")