File size: 7,185 Bytes
31e731e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/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 ===")