"""Deterministic synthetic spatial-code builder (seed=42). OpenSCAD + CadQuery. Apache-2.0.""" import random, hashlib, json, os, subprocess, tempfile, sys, traceback import trimesh, numpy as np SEED=42; R=random.Random(SEED) ROOT=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) OSC=os.environ.get("OPENSCAD","/tmp/squashfs-root/AppRun") def n(a,b): return R.randint(a,b) def scad_shapes(): out=[] for _ in range(18): x,y,z=n(5,60),n(5,60),n(2,40) out.append((f"A box {x} x {y} x {z} mm.",f"{x}x{y}x{z}mmの直方体。",f"cube([{x}, {y}, {z}]);", f'import cadquery as cq\nresult = cq.Workplane("XY").box({x}, {y}, {z}, centered=False)\n')) for _ in range(14): r,h=n(3,30),n(5,50) out.append((f"A cylinder with radius {r} mm and height {h} mm.",f"半径{r}mm、高さ{h}mmの円柱。",f"cylinder(r={r}, h={h}, $fn=64);", f'import cadquery as cq\nresult = cq.Workplane("XY").circle({r}).extrude({h})\n')) for _ in range(10): r=n(4,30) out.append((f"A sphere with radius {r} mm centered at the origin.",f"原点中心、半径{r}mmの球。",f"sphere(r={r}, $fn=48);", f'import cadquery as cq\nresult = cq.Workplane("XY").sphere({r})\n')) for _ in range(14): w,d,t,hr=n(30,80),n(30,80),n(2,8),n(2,5) m=hr+n(3,6) out.append((f"A {w} x {d} x {t} mm plate with four through-holes of radius {hr} mm, each {m} mm from the adjacent edges.", f"{w}x{d}x{t}mmの板、四隅から{m}mmの位置に半径{hr}mmの貫通穴4つ。", f"difference() {{\n cube([{w}, {d}, {t}]);\n for (p = [[{m},{m}],[{w-m},{m}],[{m},{d-m}],[{w-m},{d-m}]])\n translate([p[0], p[1], -1]) cylinder(r={hr}, h={t+2}, $fn=32);\n}}", f'import cadquery as cq\nresult = (cq.Workplane("XY").box({w}, {d}, {t}, centered=False)\n .faces(">Z").workplane(centerOption="ProjectedOrigin", origin=(0,0,0))\n .pushPoints([({m},{m}),({w-m},{m}),({m},{d-m}),({w-m},{d-m})]).hole({2*hr}))\n')) for _ in range(12): s,r=n(10,40),None; r=R.randint(max(3,s//4),s//2+2) out.append((f"A cube of side {s} mm centered at the origin with a sphere of radius {r} mm subtracted from its center.", f"原点中心の一辺{s}mmの立方体から、中心の半径{r}mmの球をくり抜いた形状。", f"difference() {{\n cube({s}, center=true);\n sphere(r={r}, $fn=48);\n}}", f'import cadquery as cq\nresult = cq.Workplane("XY").box({s},{s},{s}).cut(cq.Workplane("XY").sphere({r}))\n')) for _ in range(12): s,r,h=n(10,40),n(3,12),n(10,40) out.append((f"A union of a {s} mm cube (corner at origin) and a cylinder of radius {r} mm and height {h} mm standing on its top face center.", f"一辺{s}mmの立方体と、その上面中央に立つ半径{r}mm・高さ{h}mmの円柱の和集合。", f"union() {{\n cube({s});\n translate([{s/2}, {s/2}, {s}]) cylinder(r={r}, h={h}, $fn=48);\n}}", f'import cadquery as cq\nresult = cq.Workplane("XY").box({s},{s},{s},centered=False).union(cq.Workplane("XY").workplane(offset={s}).center({s/2},{s/2}).circle({r}).extrude({h}))\n')) for _ in range(12): L,W,H,t=n(20,60),n(10,30),n(15,50),n(2,6) out.append((f"An L-shaped bracket: base {L} x {W} x {t} mm and a vertical wall {t} x {W} x {H} mm at x=0.", f"L字ブラケット:底板{L}x{W}x{t}mm、x=0に縦壁{t}x{W}x{H}mm。", f"union() {{\n cube([{L}, {W}, {t}]);\n cube([{t}, {W}, {H}]);\n}}", f'import cadquery as cq\nresult = cq.Workplane("XY").box({L},{W},{t},centered=False).union(cq.Workplane("XY").box({t},{W},{H},centered=False))\n')) for _ in range(8): ro,ri,h=n(10,30),None,n(5,30); ri=R.randint(3,ro-2) out.append((f"A tube (hollow cylinder) with outer radius {ro} mm, inner radius {ri} mm, height {h} mm.", f"外径半径{ro}mm、内径半径{ri}mm、高さ{h}mmのパイプ。", f"difference() {{\n cylinder(r={ro}, h={h}, $fn=64);\n translate([0,0,-1]) cylinder(r={ri}, h={h+2}, $fn=64);\n}}", f'import cadquery as cq\nresult = cq.Workplane("XY").circle({ro}).circle({ri}).extrude({h})\n')) return out def mesh_gate(path): m=trimesh.load(path,force="mesh") st={"verts":int(len(m.vertices)),"faces":int(len(m.faces))} if st["faces"]==0: return False,st,"empty" b=m.bounds; st["bbox"]=[[round(float(v),3) for v in r] for r in b] if not np.isfinite(b).all(): return False,st,"nonfinite" st["watertight"]=bool(m.is_watertight); st["volume"]=round(float(m.volume),3) if m.is_watertight else None if not m.is_watertight: return False,st,"not_watertight" if st["volume"]<=0: return False,st,"nonpositive_volume" return True,st,"" def run_scad(code,stl): with tempfile.NamedTemporaryFile("w",suffix=".scad",delete=False) as f: f.write(code) p=subprocess.run([OSC,"-o",stl,f.name],capture_output=True,text=True,timeout=120) ok=p.returncode==0 and os.path.exists(stl) and "ERROR" not in p.stderr return ok,(p.stderr[-300:] if not ok else "") def run_cq(code,stl): try: g={}; exec(code,g) import cadquery as cq; cq.exporters.export(g["result"],stl); return True,"" except Exception as e: return False,repr(e)[:300] def split_of(i): h=int(hashlib.sha256(f"{SEED}:{i}".encode()).hexdigest(),16)%100 return "train" if h<80 else ("test" if h<90 else "hold") def main(): rows=[];rej=[];seen=set() for (pe,pj,scad,cqc) in scad_shapes(): for dialect,code,runner in (("openscad",scad,run_scad),("cadquery",cqc,run_cq)): cid=hashlib.sha256((dialect+"\n"+code).encode()).hexdigest()[:16] rid=f"{dialect[:3]}-{cid}" row={"id":rid,"prompt":pe,"prompt_ja":pj,"dialect":dialect,"code":code,"source":"synthetic_v0","license":"Apache-2.0","seed":SEED} if cid in seen: rej.append({**row,"reason":"duplicate_code"}); continue seen.add(cid) stl=os.path.join(ROOT,"data/artifacts",rid+".stl") ok,err=runner(code,stl); row["exec_ok"]=ok if not ok: rej.append({**row,"reason":"exec_fail:"+err}); continue mok,st,why=mesh_gate(stl); row["mesh_ok"]=mok; row["mesh_stats"]=st if not mok: rej.append({**row,"reason":"mesh:"+why}); continue row["artifact_path"]=os.path.relpath(stl,ROOT) row["split"]=split_of(rid.split("-",1)[1] if False else (pe)) # split by prompt -> both dialects of a prompt share a split (no leakage) rows.append(row) for s in ("train","test","hold"): with open(os.path.join(ROOT,f"data/verified/{s}.jsonl"),"w") as f: for r in rows: if r["split"]==s: f.write(json.dumps(r,ensure_ascii=False)+"\n") with open(os.path.join(ROOT,"data/rejected/rejected.jsonl"),"w") as f: for r in rej: f.write(json.dumps(r,ensure_ascii=False)+"\n") gen=len(rows)+len(rej) stats={"seed":SEED,"generated":gen,"verified":len(rows),"rejected":len(rej), "rejected_reasons":{k:sum(1 for r in rej if r["reason"].split(":")[0]==k) for k in {r["reason"].split(":")[0] for r in rej}}, "per_split":{s:sum(1 for r in rows if r["split"]==s) for s in ("train","test","hold")}, "per_dialect":{d:sum(1 for r in rows if r["dialect"]==d) for d in ("openscad","cadquery")}, "unique_prompts":len({r["prompt"] for r in rows}), "tools":{"openscad":subprocess.run([OSC,"--version"],capture_output=True,text=True).stderr.strip(),"cadquery":__import__("cadquery").__version__,"trimesh":trimesh.__version__}} json.dump(stats,open(os.path.join(ROOT,"manifests/stats.json"),"w"),indent=2,ensure_ascii=False); print(json.dumps(stats,indent=1)) main()