Spaces:
Running on Zero

kwabs22 Claude Opus 5.5 commited on
Commit
92d401f
·
1 Parent(s): 3de3640

Add papercraft_rings: a printable net from the rings rung

Browse files

First piece of materialization. Each band between two rings unrolls exactly
into one paper strip (triangles laid flat edge to edge; checked: edge-length
error 6e-16, and a cylinder band matches 12 chords of its radius to 0.1 mm).
Bands that would curl past ~120 degrees on paper are split into parts so no
piece overlaps itself. Glue tabs sit on one side of every joint and name
the piece they meet; tiny caps and tabs are dropped.

New MCP tool papercraft_rings(ledger, item_id, rings, samples, height_cm)
returns a pieces report and an SVG net in mm; the UI has a matching panel
with a preview.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Files changed (3) hide show
  1. SPEC.md +15 -1
  2. app.py +70 -1
  3. vli/papercraft.py +179 -0
SPEC.md CHANGED
@@ -100,6 +100,7 @@ Verbs: `sat/stood/lay/rested` → `on` (ground implied), `shone/glowed` → `lig
100
  | `translate_to_scene` | sentence, primitives, seed, html → ledger, PNG, GLB, mini HTML file, mini HTML text |
101
  | `refine_scene` | ledger, changes, seed, html → ledger, PNG, GLB, mini HTML file, mini HTML text |
102
  | `simplify_item` | ledger, item id, html, rings, samples → report, rung PNGs, rung GLBs, mini HTML file, mini HTML text |
 
103
 
104
  `check_words` also returns `maps_to` per noun (the asset it would get), so a word
105
  that exists but maps to the wrong thing shows up before submitting.
@@ -121,6 +122,18 @@ centre and radii, so it can be checked by hand. One stack per object: branching
121
  overhanging parts (a lamp's arm and shade) merge into one envelope, and heights with
122
  no section are skipped.
123
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  ### Mini HTML
125
 
126
  A self-contained page: Three.js (`three@0.160.0` from unpkg) plus one inline `D`
@@ -144,7 +157,8 @@ and download without one. Optional env: `VLI_CACHE`.
144
 
145
  ## Known gaps / open questions
146
 
147
- - **Materialization** (papercraft from a low rung) is not built yet.
 
148
  - **Generation tier** is a stub: rejecting a primitive returns a clear error before
149
  changing the ledger (use `shape` or `height_m` instead).
150
  - SimReady names → words is a heuristic: the name after its category is indexed
 
100
  | `translate_to_scene` | sentence, primitives, seed, html → ledger, PNG, GLB, mini HTML file, mini HTML text |
101
  | `refine_scene` | ledger, changes, seed, html → ledger, PNG, GLB, mini HTML file, mini HTML text |
102
  | `simplify_item` | ledger, item id, html, rings, samples → report, rung PNGs, rung GLBs, mini HTML file, mini HTML text |
103
+ | `papercraft_rings` | ledger, item id, rings, samples, height_cm → pieces report, SVG net (mm) |
104
 
105
  `check_words` also returns `maps_to` per noun (the asset it would get), so a word
106
  that exists but maps to the wrong thing shows up before submitting.
 
122
  overhanging parts (a lamp's arm and shade) merge into one envelope, and heights with
123
  no section are skipped.
124
 
125
+ ### Papercraft (rings)
126
+
127
+ `papercraft_rings` turns the rings rung into a printable net (SVG, millimetres, real size
128
+ or scaled to `height_cm`). Each band between two rings unrolls exactly into one strip:
129
+ its triangles share edges in sequence, so laying them flat keeps every length. A band
130
+ that would curl past ~120° on paper overlaps itself, so it is split into parts (2a, 2b).
131
+ Every joint has glue tabs on one side only, labelled with the piece they meet (band top
132
+ edge → next band or top cap, seam end → own start or next part, bottom cap rim → band 1).
133
+ Caps under 4 mm are dropped and the band closes to a point; tabs under 2 mm are dropped.
134
+ Cut solid lines, fold dashed lines. Pieces are shelf-packed in 180 mm rows; a piece
135
+ wider than that widens the sheet (use `height_cm` to print on A4).
136
+
137
  ### Mini HTML
138
 
139
  A self-contained page: Three.js (`three@0.160.0` from unpkg) plus one inline `D`
 
157
 
158
  ## Known gaps / open questions
159
 
160
+ - **Materialization**: only the rings path exists (`papercraft_rings`). Nets from the
161
+ decimated rungs (general mesh unfolding) are not built yet.
162
  - **Generation tier** is a stub: rejecting a primitive returns a clear error before
163
  changing the ledger (use `shape` or `height_m` instead).
164
  - SimReady names → words is a heuristic: the name after its category is indexed
app.py CHANGED
@@ -16,7 +16,7 @@ import threading
16
  import spaces # ZeroGPU: import before any CUDA-touching library
17
  import gradio as gr
18
 
19
- from vli import assets, pipeline, scene, simplify
20
  from vli import html as html_pages # `html` is the tools' output-mode argument
21
  from vli.grammar import check_words as _check_words
22
  from vli.lexicon import LEXICON, PRIMITIVE_SHAPES
@@ -229,6 +229,57 @@ def simplify_item(ledger_json: str, item_id: str, html: str = "url", rings: str
229
  _fail(e)
230
 
231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  # ---------------- UI-only helpers ----------------
233
 
234
  def _suggestions(words_json):
@@ -264,6 +315,16 @@ def _use_primitive(primitives_json, word, shape):
264
  return json.dumps(prims)
265
 
266
 
 
 
 
 
 
 
 
 
 
 
267
  def _html_preview(path):
268
  """Live preview (sandboxed iframe) of the mini HTML file."""
269
  if not path:
@@ -331,6 +392,12 @@ with gr.Blocks(title="VisualLearningIdea") as demo:
331
  ladder_html = gr.Code(label="HTML", language="html")
332
  ladder_report = gr.Code(label="Report", language="json")
333
  ladder_files = gr.File(label="GLB per rung", file_count="multiple")
 
 
 
 
 
 
334
 
335
  gr.on([sentence.change, primitives.change], check_words, [sentence, primitives], words,
336
  api_name="check_words", trigger_mode="always_last") \
@@ -346,6 +413,8 @@ with gr.Blocks(title="VisualLearningIdea") as demo:
346
  simp.click(simplify_item, [ledger, item_id, html_mode, ring_count, ring_samples],
347
  [ladder_report, ladder_pics, ladder_files, ladder_file, ladder_html], api_name="simplify_item") \
348
  .then(_html_preview, ladder_file, ladder_preview, api_visibility="private")
 
 
349
 
350
  if __name__ == "__main__":
351
  demo.launch(mcp_server=True)
 
16
  import spaces # ZeroGPU: import before any CUDA-touching library
17
  import gradio as gr
18
 
19
+ from vli import assets, papercraft, pipeline, scene, simplify
20
  from vli import html as html_pages # `html` is the tools' output-mode argument
21
  from vli.grammar import check_words as _check_words
22
  from vli.lexicon import LEXICON, PRIMITIVE_SHAPES
 
229
  _fail(e)
230
 
231
 
232
+ def papercraft_rings(ledger_json: str, item_id: str, rings: str = "8", samples: str = "16",
233
+ height_cm: str = "") -> tuple[str, str]:
234
+ """Make a printable papercraft net of one object from its rings rung (see simplify_item).
235
+
236
+ Every band between two rings unrolls exactly into one paper strip; bands that would
237
+ curl past ~120 degrees on paper are split into parts (2a, 2b, ...). Glue tabs sit on
238
+ one side of every joint and name the piece they glue to. Caps under 4 mm are left out
239
+ (the band closes to a point there). Cut solid lines, fold dashed lines.
240
+
241
+ Args:
242
+ ledger_json: Ledger JSON from translate_to_scene or refine_scene.
243
+ item_id: The object item to make, e.g. "n1".
244
+ rings: Number of horizontal sections (2-64). Fewer rings = fewer, simpler pieces.
245
+ samples: Points around each section (3-128). Fewer samples = fewer folds.
246
+ height_cm: Height of the paper model in cm; blank = the object's real size.
247
+
248
+ Returns:
249
+ (report JSON string with the pieces, sheet size and what glues to what, SVG net file in mm).
250
+ """
251
+ try:
252
+ ledger = _json(ledger_json, "ledger_json")
253
+ item = next((i for i in ledger["items"] if i["id"] == item_id), None)
254
+ if item is None or item["kind"] != "object":
255
+ raise ValueError(f"{item_id!r} is not an object item in this ledger")
256
+ count, n = _count(rings, "rings", 2, 64), _count(samples, "samples", 3, 128)
257
+ h = None
258
+ if str(height_cm).strip():
259
+ try:
260
+ h = float(str(height_cm).strip())
261
+ except ValueError:
262
+ raise ValueError(f"height_cm must be a number, got {height_cm!r}")
263
+ if not 1 <= h <= 200:
264
+ raise ValueError(f"height_cm must be between 1 and 200, got {h}")
265
+ _, profile = simplify.rings(assets.settle(item), count, n)
266
+ if len(profile) < 2:
267
+ raise ValueError(f"{item_id!r} has fewer than 2 sections; try more rings")
268
+ pieces, scale = papercraft.net(profile, n, h)
269
+ text, sheet = papercraft.svg(pieces, f"{item['word']}: {len(profile)} rings x {n}")
270
+ path = os.path.join(tempfile.mkdtemp(prefix="vli_paper_"), re.sub(r"\W+", "_", item["word"]) + "_net.svg")
271
+ with open(path, "w", encoding="utf-8") as f:
272
+ f.write(text)
273
+ report = {"item": item_id, "word": item["word"], "rings": len(profile), "samples": n,
274
+ "model_height_cm": round((profile[-1]["y"] - profile[0]["y"]) * scale / 10, 1),
275
+ "sheet_mm": sheet, "pieces": [{"name": pc["name"],
276
+ "glues_to": sorted({t["label"] for t in pc["tabs"] if t["label"]})}
277
+ for pc in pieces]}
278
+ return json.dumps(report, indent=1), path
279
+ except Exception as e:
280
+ _fail(e)
281
+
282
+
283
  # ---------------- UI-only helpers ----------------
284
 
285
  def _suggestions(words_json):
 
315
  return json.dumps(prims)
316
 
317
 
318
+ def _svg_preview(path):
319
+ """Show the SVG net scaled to the panel width."""
320
+ if not path:
321
+ return ""
322
+ with open(path, encoding="utf-8") as f:
323
+ text = f.read()
324
+ text = text.replace("<svg ", '<svg style="width:100%;height:auto" ', 1)
325
+ return f'<div style="background:#fff;padding:8px;border-radius:8px">{text}</div>'
326
+
327
+
328
  def _html_preview(path):
329
  """Live preview (sandboxed iframe) of the mini HTML file."""
330
  if not path:
 
392
  ladder_html = gr.Code(label="HTML", language="html")
393
  ladder_report = gr.Code(label="Report", language="json")
394
  ladder_files = gr.File(label="GLB per rung", file_count="multiple")
395
+ with gr.Accordion("Papercraft net (rings)", open=False):
396
+ paper_height = gr.Textbox(label="Model height in cm (blank = real size)", value="")
397
+ paper = gr.Button("Make net")
398
+ paper_preview = gr.HTML()
399
+ paper_file = gr.File(label="Download .svg (mm)")
400
+ paper_report = gr.Code(label="Pieces", language="json")
401
 
402
  gr.on([sentence.change, primitives.change], check_words, [sentence, primitives], words,
403
  api_name="check_words", trigger_mode="always_last") \
 
413
  simp.click(simplify_item, [ledger, item_id, html_mode, ring_count, ring_samples],
414
  [ladder_report, ladder_pics, ladder_files, ladder_file, ladder_html], api_name="simplify_item") \
415
  .then(_html_preview, ladder_file, ladder_preview, api_visibility="private")
416
+ paper.click(papercraft_rings, [ledger, item_id, ring_count, ring_samples, paper_height],
417
+ [paper_report, paper_file], api_name="papercraft_rings") .then(_svg_preview, paper_file, paper_preview, api_visibility="private")
418
 
419
  if __name__ == "__main__":
420
  demo.launch(mcp_server=True)
vli/papercraft.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Papercraft from the rings rung: every band unrolls into one strip, plus two caps.
2
+
3
+ A band is the ring of quads between two neighbouring rings. Its triangles share
4
+ edges in sequence, so laying them flat one after another is exact (no stretching).
5
+ Each joint gets glue tabs on exactly one side, labelled with the piece it meets:
6
+ band i top edge -> band i+1 (the last band -> top cap)
7
+ band i seam end -> its own seam start (or the next part, when a band is split)
8
+ bottom cap rim -> band 1 bottom edge
9
+ A band that would curl past ~120 degrees on paper is split into parts (2a, 2b, ...).
10
+ Output is an SVG in millimetres, cut lines solid, fold lines dashed.
11
+ """
12
+ import numpy as np
13
+
14
+ TAB_MM = 6.0
15
+ GAP_MM = 8.0
16
+ SHEET_MM = 180.0 # row width for laying out pieces (A4 printable width)
17
+ MIN_CAP_MM = 4.0
18
+ MIN_TAB_MM = 2.0
19
+ LABEL_TAB_MM = 8.0
20
+
21
+
22
+ def _ring_points(p, dirs):
23
+ """3D points of one ring from its profile entry (centre, radii) and sample directions."""
24
+ cx, cz = p["center"]
25
+ r = np.asarray(p["radii"])[:, None]
26
+ return np.c_[cx + r[:, 0] * dirs[:, 0], np.full(len(dirs), p["y"]), cz + r[:, 0] * dirs[:, 1]]
27
+
28
+
29
+ def _place(a2, c2, da, dc, away2):
30
+ """The 2D point at distance da from a2 and dc from c2, on the side away from away2."""
31
+ d = np.linalg.norm(c2 - a2)
32
+ if d < 1e-9:
33
+ return a2.copy()
34
+ x = (da * da - dc * dc + d * d) / (2 * d)
35
+ h = np.sqrt(max(da * da - x * x, 0.0))
36
+ u = (c2 - a2) / d
37
+ n = np.array([-u[1], u[0]])
38
+ base = a2 + x * u
39
+ p1, p2 = base + h * n, base - h * n
40
+ return p1 if np.linalg.norm(p1 - away2) >= np.linalg.norm(p2 - away2) else p2
41
+
42
+
43
+ def _unroll_band(bot, top):
44
+ """Lay a band flat. bot/top: (S, 3) ring points. Returns 2D (S+1, 2) bottom and top rows
45
+ (the seam vertex appears at both ends) and the fold edges between them."""
46
+ S = len(bot)
47
+ B, T = [np.array([0.0, 0.0])], [np.array([0.0, np.linalg.norm(top[0] - bot[0])])]
48
+ prev_b = np.array([-1.0, 0.0]) # strip grows towards +x
49
+ for j in range(S):
50
+ k = (j + 1) % S
51
+ t_next = _place(B[j], T[j], np.linalg.norm(top[k] - bot[j]), np.linalg.norm(top[k] - top[j]), prev_b)
52
+ b_next = _place(B[j], t_next, np.linalg.norm(bot[k] - bot[j]), np.linalg.norm(bot[k] - top[k]), T[j])
53
+ prev_b = B[j]
54
+ T.append(t_next)
55
+ B.append(b_next)
56
+ B, T = np.array(B), np.array(T)
57
+ folds = [(B[j], T[j]) for j in range(1, S)] + [(B[j], T[j + 1]) for j in range(S)]
58
+ return B, T, folds
59
+
60
+
61
+ def _tab(p, q, inside, label):
62
+ """A trapezoid glue tab on edge p-q, on the side away from `inside`.
63
+
64
+ Edges under MIN_TAB_MM get no tab (too small to glue), and only edges of
65
+ LABEL_TAB_MM or more carry the label, so converging edges don't pile up text.
66
+ """
67
+ e = q - p
68
+ L = np.linalg.norm(e)
69
+ if L < MIN_TAB_MM:
70
+ return None
71
+ if L < LABEL_TAB_MM:
72
+ label = ""
73
+ n = np.array([-e[1], e[0]]) / L
74
+ if np.dot(n, inside - p) > 0:
75
+ n = -n
76
+ w, inset = min(TAB_MM, 0.4 * L), min(TAB_MM, 0.25 * L)
77
+ u = e / L
78
+ return {"poly": [p, q, q + n * w - u * inset, p + n * w + u * inset], "label": label,
79
+ "at": (p + q) / 2 + n * w / 2}
80
+
81
+
82
+ def _chunks(B, max_turn_deg=120):
83
+ """Split a strip where its bottom edge has turned too far: a strip that curls
84
+ past a half circle overlaps itself on paper (bands near a pole)."""
85
+ S = len(B) - 1
86
+ edges = np.diff(B, axis=0)
87
+ heading = np.unwrap(np.arctan2(edges[:, 1], edges[:, 0]))
88
+ cuts, start = [0], 0
89
+ for j in range(1, S):
90
+ if abs(heading[j] - heading[start]) > np.radians(max_turn_deg):
91
+ cuts.append(j)
92
+ start = j
93
+ return list(zip(cuts, cuts[1:] + [S]))
94
+
95
+
96
+ def net(profile, samples, height_cm=None):
97
+ """Pieces for the rings rung, scaled to millimetres. Returns (pieces, scale).
98
+
99
+ Caps under MIN_CAP_MM across are left out: the band there closes to a point.
100
+ """
101
+ ang = np.linspace(0, 2 * np.pi, samples, endpoint=False)
102
+ dirs = np.c_[np.cos(ang), np.sin(ang)]
103
+ real_h = profile[-1]["y"] - profile[0]["y"]
104
+ scale = 1000.0 if not height_cm else 10.0 * float(height_cm) / max(real_h, 1e-6)
105
+ rings = [_ring_points(p, dirs) * scale for p in profile]
106
+ caps = {k: 2 * max(profile[i]["radii"]) * scale >= MIN_CAP_MM for k, i in (("bottom", 0), ("top", -1))}
107
+ n = len(rings) - 1
108
+ pieces = []
109
+ for i in range(n):
110
+ B, T, _ = _unroll_band(rings[i], rings[i + 1])
111
+ above = f"band {i + 2}" if i + 1 < n else ("top cap" if caps["top"] else None)
112
+ parts = _chunks(B)
113
+ names = [f"band {i + 1}" + (chr(ord("a") + k) if len(parts) > 1 else "") for k in range(len(parts))]
114
+ for k, (j0, j1) in enumerate(parts):
115
+ mid = (B[j0:j1 + 1].mean(axis=0) + T[j0:j1 + 1].mean(axis=0)) / 2
116
+ tabs = [_tab(T[j], T[j + 1], mid, above) for j in range(j0, j1)] if above else []
117
+ tabs.append(_tab(B[j1], T[j1], B[j1 - 1], names[(k + 1) % len(parts)] + (" start" if k + 1 == len(parts) else "")))
118
+ folds = [(B[j], T[j]) for j in range(j0 + 1, j1)] + [(B[j], T[j + 1]) for j in range(j0, j1)]
119
+ pieces.append({"name": names[k], "outline": list(B[j0:j1 + 1]) + list(T[j0:j1 + 1][::-1]),
120
+ "folds": folds, "tabs": [t for t in tabs if t]})
121
+ for name, ring, key in (("bottom cap", rings[0], "bottom"), ("top cap", rings[-1], "top")):
122
+ if not caps[key]:
123
+ continue
124
+ c = ring.mean(axis=0)
125
+ poly = [np.array([x - c[0], z - c[2]]) for x, _, z in ring]
126
+ if key == "bottom":
127
+ poly = [np.array([x, -y]) for x, y in poly] # seen from below
128
+ tabs = [_tab(poly[j], poly[(j + 1) % samples], np.zeros(2), "band 1") for j in range(samples)] \
129
+ if key == "bottom" else []
130
+ pieces.append({"name": name, "outline": poly, "folds": [], "tabs": [t for t in tabs if t]})
131
+ return pieces, scale
132
+
133
+
134
+ def _bounds(piece):
135
+ pts = np.array(list(piece["outline"]) + [p for t in piece["tabs"] for p in t["poly"]])
136
+ return pts.min(axis=0), pts.max(axis=0)
137
+
138
+
139
+ def svg(pieces, title):
140
+ """Shelf-pack the pieces into rows and draw them. Units are millimetres."""
141
+ x = y = row_h = 0.0
142
+ width = max(SHEET_MM, max(float((hi - lo)[0]) for lo, hi in map(_bounds, pieces)))
143
+ placed = []
144
+ for pc in pieces:
145
+ lo, hi = _bounds(pc)
146
+ w, h = hi - lo
147
+ if x > 0 and x + w > width:
148
+ x, y, row_h = 0.0, y + row_h + GAP_MM, 0.0
149
+ placed.append((pc, np.array([x, y + 10.0]) - lo))
150
+ x, row_h = x + w + GAP_MM, max(row_h, h)
151
+ height = y + row_h + 10.0 + GAP_MM
152
+
153
+ def pts(poly, off):
154
+ return " ".join(f"{p[0] + off[0]:.1f},{p[1] + off[1]:.1f}" for p in poly)
155
+
156
+ out = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{width:.0f}mm" height="{height:.0f}mm" '
157
+ f'viewBox="0 0 {width:.1f} {height:.1f}" font-family="sans-serif">',
158
+ f'<text x="0" y="5" font-size="4">{_esc(title)}: cut solid, fold dashed, glue tabs to the named piece</text>']
159
+ for pc, off in placed:
160
+ for t in pc["tabs"]:
161
+ out.append(f'<polygon points="{pts(t["poly"], off)}" fill="#eee" stroke="#000" stroke-width="0.2"/>')
162
+ if not t["label"]:
163
+ continue
164
+ a = t["at"] + off
165
+ out.append(f'<text x="{a[0]:.1f}" y="{a[1]:.1f}" font-size="2" text-anchor="middle" '
166
+ f'dominant-baseline="middle">{_esc(t["label"])}</text>')
167
+ out.append(f'<polygon points="{pts(pc["outline"], off)}" fill="#fff" stroke="#000" stroke-width="0.3"/>')
168
+ for p, q in pc["folds"]:
169
+ out.append(f'<line x1="{p[0] + off[0]:.1f}" y1="{p[1] + off[1]:.1f}" x2="{q[0] + off[0]:.1f}" '
170
+ f'y2="{q[1] + off[1]:.1f}" stroke="#888" stroke-width="0.2" stroke-dasharray="1.5,1"/>')
171
+ c = np.mean(pc["outline"], axis=0) + off
172
+ out.append(f'<text x="{c[0]:.1f}" y="{c[1]:.1f}" font-size="4" text-anchor="middle" '
173
+ f'dominant-baseline="middle">{_esc(pc["name"])}</text>')
174
+ out.append("</svg>")
175
+ return "\n".join(out), (round(width), round(height))
176
+
177
+
178
+ def _esc(s):
179
+ return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")