File size: 11,651 Bytes
5399134
 
 
 
 
 
 
 
 
 
 
 
 
1b55f03
5399134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b55f03
5399134
1b55f03
 
5399134
 
 
 
 
 
 
 
 
 
 
 
1b55f03
5399134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b55f03
5399134
 
 
 
1b55f03
 
 
 
 
 
 
 
 
 
 
5399134
 
 
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python
"""Render 24 views (az 0..315 step 45 x elevations low/-20, eye/10, high/40) of ALL
Google Scanned Objects from suvadityamuk/google-scanned-objects webdataset shards.

768x768 RGBA, transparent background, soft three-point lighting, no ground plane.
Z-up meshes converted to Y-up. One camera distance per object, from the bounding
sphere (eye-level projected span ~60% of frame, fov 40 deg). Per-object rejection:
any view with alpha coverage < 8% or projected span > 95% of frame.

Outputs (uploaded to ysharma/gso-orbit-rgba):
  renders/{object_id}/az{000..315}_el{low|eye|high}.png
  metadata.jsonl          one line per view
  split.json              heldout_40 / rejected_objects / train_objects
  contact_sheets/*.jpg    one sheet per sampled category (uploaded after core data)
"""
import os
os.environ['PYOPENGL_PLATFORM'] = 'osmesa'  # must precede pyrender import
import io, json, math, random, tarfile, time, traceback
from concurrent.futures import ProcessPoolExecutor

import numpy as np
import pyrender
import trimesh
from scipy.ndimage import distance_transform_edt
from huggingface_hub import HfApi

DATA = '/data/data'
OUT = '/out'
REPO_ID = 'ysharma/gso-orbit-rgba'
N_SHARDS = 43
SZ = 1536
OUTSZ = 768
FOV_Y = math.radians(40.0)
FOCAL_F = 0.60
DIST = 0.5 / (FOCAL_F * math.tan(FOV_Y / 2.0))
ZNEAR, ZFAR = 0.05, 10.0
ELEVS = [('low', -20.0), ('eye', 10.0), ('high', 40.0)]
AZS = list(range(0, 360, 45))
HALO_RING = 8
BG = [0.0, 0.0, 0.0]
COV_MIN = 0.08
SPAN_MAX = 0.95
WORKERS = 8

T_UP = np.eye(4); T_UP[1, 1] = 0.0; T_UP[1, 2] = -1.0; T_UP[2, 1] = 1.0; T_UP[2, 2] = 0.0


def camera_pose(az_deg, el_deg, dist):
    az, el = math.radians(az_deg), math.radians(el_deg)
    eye = dist * np.array([math.cos(el) * math.cos(az), math.sin(el),
                           math.cos(el) * math.sin(az)])
    zax = eye / np.linalg.norm(eye)
    up = np.array([0.0, 1.0, 0.0])
    xax = np.cross(up, zax); xax /= np.linalg.norm(xax)
    yax = np.cross(zax, xax)
    pose = np.eye(4)
    pose[:3, 0], pose[:3, 1], pose[:3, 2], pose[:3, 3] = xax, yax, zax, eye
    return pose


def rot_y(deg):
    a = math.radians(deg)
    R = np.eye(4)
    R[:3, :3] = [[math.cos(a), 0, math.sin(a)], [0, 1, 0], [-math.sin(a), 0, math.cos(a)]]
    return R


def build_scene(glb_bytes):
    st = trimesh.load(io.BytesIO(glb_bytes), file_type='glb', force='scene')
    geoms = list(st.geometry.values())
    for g in geoms:
        g.apply_transform(T_UP)
    mesh = pyrender.Mesh.from_trimesh(geoms)
    scene = pyrender.Scene(bg_color=BG, ambient_light=[0.30, 0.30, 0.30])
    scene.add(mesh)
    return scene


def add_lights(scene, cam_pose):
    base = cam_pose.copy(); base[:3, 3] = 0.0
    scene.add(pyrender.DirectionalLight(intensity=3.0), pose=base @ rot_y(0.0))    # key
    scene.add(pyrender.DirectionalLight(intensity=1.2), pose=base @ rot_y(35.0))   # fill
    scene.add(pyrender.DirectionalLight(intensity=2.0), pose=base @ rot_y(160.0))  # rim


def tar_read(tf, name):
    m = None
    for cand in (name, name.lower(), name.replace(" ", "_")):
        try:
            m = tf.getmember(cand)
            break
        except KeyError:
            continue
    if m is None:
        for mem in tf.getmembers():
            if mem.name.lower() == name.lower():
                m = mem
                break
    if m is None:
        raise KeyError(name)
    f = tf.extractfile(m)
    return f.read() if f else None


def halo_fill(rgb, mask):
    inv = (~mask)
    if not inv.any() or not mask.any():
        return rgb
    dist, idx = distance_transform_edt(inv, return_indices=True)
    fill = inv & (dist <= HALO_RING)
    rgb = rgb.copy()
    ys, xs = np.nonzero(fill)
    rgb[ys, xs] = rgb[idx[0][ys, xs], idx[1][ys, xs]]
    return rgb


def downsample_rgba(rgb, mask):
    premul = rgb.astype(np.float32) * mask[..., None]
    a = mask.astype(np.float32)
    h2 = SZ // 2
    pm = premul.reshape(h2, 2, h2, 2, 3).mean(axis=(1, 3))
    am = a.reshape(h2, 2, h2, 2).mean(axis=(1, 3))
    out = np.zeros((h2, h2, 4), np.uint8)
    good = am > (1.0 / 255.0)
    denom = np.maximum(am, 1e-6)
    for c in range(3):
        ch = np.clip(pm[..., c] / denom, 0, 255)
        out[..., c] = np.where(good, ch, 0).astype(np.uint8)
    out[..., 3] = np.clip(am * 255.0 + 0.5, 0, 255).astype(np.uint8)
    return out


def render_object(args):
    shard_path, object_id, category = args
    t_start = time.time()
    try:
        with tarfile.open(shard_path, 'r') as tf:
            glb_bytes = tar_read(tf, f'{object_id}.glb')
        os.makedirs(os.path.join(OUT, 'renders', object_id), exist_ok=True)
        scene = build_scene(glb_bytes)
        cam = pyrender.PerspectiveCamera(yfov=FOV_Y, znear=ZNEAR, zfar=ZFAR)
        scene.add(cam, pose=camera_pose(0.0, 10.0, DIST))
        add_lights(scene, camera_pose(0.0, 10.0, DIST))
        renderer = pyrender.OffscreenRenderer(SZ, SZ)
        rows, t_render = [], 0.0
        eye_covs = []
        for el_name, el in ELEVS:
            for az in AZS:
                t0 = time.time()
                scene.set_pose(scene.main_camera_node, camera_pose(az, el, DIST))
                color, depth = renderer.render(scene)
                t_render += time.time() - t0
                mask = (depth > 0.0)
                cov = float(mask.mean())
                ys_m, xs_m = np.nonzero(mask)
                span = max((xs_m.max() - xs_m.min()) / SZ, (ys_m.max() - ys_m.min()) / SZ) if len(xs_m) else 0.0
                if el_name == 'eye':
                    eye_covs.append(cov)
                rgb = halo_fill(color, mask)
                rgba = downsample_rgba(rgb, mask)
                fn = f'az{az:03d}_el{el_name}.png'
                from PIL import Image
                Image.fromarray(rgba, 'RGBA').save(os.path.join(OUT, 'renders', object_id, fn))
                rows.append({
                    'object_id': object_id, 'category': category,
                    'azimuth_deg': az, 'elevation_deg': el, 'elevation_name': el_name,
                    'camera_azimuth_deg': az, 'camera_elevation_deg': el,
                    'distance': round(DIST, 6), 'coverage': round(cov, 6), 'bbox_span': round(span, 6),
                    'file': f'renders/{object_id}/{fn}',
                })
        renderer.delete()
        rejected = any(r['coverage'] < COV_MIN or r['bbox_span'] > SPAN_MAX for r in rows)
        return {'ok': True, 'rows': rows, 'object_id': object_id, 'rejected': rejected,
                's_per_view': round(t_render / 24.0, 3),
                'render_s': round(t_render, 3)}
    except Exception:
        return {'ok': False, 'object_id': object_id, 'error': traceback.format_exc()}


def list_all_objects():
    jobs = []
    for i in range(N_SHARDS):
        shard = os.path.join(DATA, f'gso-train-{i:05d}.tar')
        with tarfile.open(shard, 'r') as tf:
            stems, seen = [], set()
            for m in tf.getnames():
                ext = m.rsplit('.', 1)[1].lower()
                if ext not in ('glb', 'json'):
                    continue
                stem = m.rsplit('.', 1)[0]
                if stem not in seen:
                    seen.add(stem)
                    stems.append(stem)
        for stem in stems:
            with tarfile.open(shard, 'r') as tf:
                j = json.loads(tar_read(tf, f'{stem}.json'))
            jobs.append((shard, stem, j.get('category', '') or 'unlabeled'))
    return jobs


def make_split(jobs, all_flags):
    cats = {}
    for _, oid, cat in jobs:
        cats.setdefault(cat, []).append(oid)
    rng = random.Random(20260923)
    heldout = []
    total = sum(len(v) for v in cats.values())
    for cat in sorted(cats):
        pool = [o for o in cats[cat] if not all_flags.get(o, False)]
        rng.shuffle(pool)
        n = max(1, round(40.0 * len(pool) / total)) if pool else 0
        heldout.extend(pool[:n])
    rng.shuffle(heldout)
    heldout = heldout[:40]
    hs = set(heldout)
    train = [o for _, o, c in jobs
             if o not in hs and not all_flags.get(o, False)]
    return heldout, train


def contact_sheets(sheets_ids):
    from PIL import Image
    os.makedirs(os.path.join(OUT, 'contact_sheets'), exist_ok=True)
    cell = 256
    for sample_id in sheets_ids:
        sheet = Image.new('RGB', (8 * cell, 3 * cell), (128, 128, 128))
        for r, (el_name, _el_deg) in enumerate(ELEVS):
            for c, az in enumerate(AZS):
                im = Image.open(os.path.join(OUT, 'renders', sample_id,
                                             f'az{az:03d}_el{el_name}.png'))
                im = im.resize((cell, cell), Image.LANCZOS)
                sheet.paste(im, (c * cell, r * cell), im)
        sheet.save(os.path.join(OUT, 'contact_sheets', f'{sample_id}.jpg'), quality=88)


def main():
    t0 = time.time()
    jobs = list_all_objects()
    print(f'{len(jobs)} objects listed across {N_SHARDS} shards', flush=True)
    os.makedirs(OUT, exist_ok=True)
    all_rows, ok_flags, sheets_pool = [], {}, []
    s_per_view = []
    n_ok = n_fail = 0
    with ProcessPoolExecutor(max_workers=WORKERS) as ex:
        for k, res in enumerate(ex.map(render_object, jobs)):
            if not res['ok']:
                print(f"FAILED {res['object_id']}: {res['error'][-300:]}", flush=True)
                n_fail += 1
                continue
            n_ok += 1
            all_rows.extend(res['rows'])
            ok_flags[res['object_id']] = res['rejected']
            s_per_view.append(res['s_per_view'])
            if not res['rejected'] and len(sheets_pool) < 8:
                sheets_pool.append(res['object_id'])
            if (k + 1) % 100 == 0:
                print(f'  {k+1}/{len(jobs)} objects | mean s/view {np.mean(s_per_view):.3f} '
                      f'| elapsed {time.time()-t0:.0f}s', flush=True)
    with open(os.path.join(OUT, 'metadata.jsonl'), 'w') as f:
        for r in all_rows:
            f.write(json.dumps(r) + '\n')
    heldout, train = make_split(jobs, ok_flags)
    split = {'heldout_40': heldout, 'train_objects': train,
             'rejected_objects': sorted([o for o, r in ok_flags.items() if r]),
             'failed_objects': [], 'seed': 20260923,
             'n_renders': len(all_rows), 'instructions_version': 'orbit-relative-v1'}
    with open(os.path.join(OUT, 'split.json'), 'w') as f:
        json.dump(split, f, indent=2)
    bad = sum(1 for r in all_rows if r['coverage'] < COV_MIN)
    n_rej = sum(1 for r in ok_flags.values() if r)
    print(f'\nDONE {n_ok} ok / {n_fail} failed | rejected {n_rej} objects | '
          f'views <8% cov: {bad}/{len(all_rows)} | {time.time()-t0:.0f}s total '
          f'| mean {np.mean(s_per_view):.3f} s/view ({WORKERS} workers)', flush=True)
    print(f'split: {len(heldout)} heldout, {len(train)} train', flush=True)

    api = HfApi(token=os.environ.get('HF_TOKEN'))
    print('uploading core data to Hub (upload_large_folder)...', flush=True)
    t_up = time.time()
    api.upload_large_folder(repo_id=REPO_ID, repo_type='dataset', folder_path=OUT)
    print(f'UPLOAD DONE in {time.time()-t_up:.0f}s', flush=True)

    # contact sheets last, guarded: a bug here must never cost the render sweep
    try:
        contact_sheets(sheets_pool[:6])
        api.upload_folder(repo_id=REPO_ID, repo_type='dataset',
                          folder_path=os.path.join(OUT, 'contact_sheets'),
                          path_in_repo='contact_sheets')
        print('contact sheets uploaded', flush=True)
    except Exception:
        print('contact sheets failed (non-fatal):', flush=True)
        traceback.print_exc()


if __name__ == '__main__':
    main()