kwabs22 Claude Opus 5.5 commited on
Commit
f9a8763
·
1 Parent(s): e6c37a7

Return the mini HTML as a URL by default to keep chat context small

Browse files

Inline geometry cost tens of thousands of tokens per tool call (QA P0-0).
translate_to_scene, refine_scene and simplify_item take html="url" (default),
"inline" or "skip" and return the page as a file plus its text, which is
filled only for "inline". Models iterate on the ledger and picture and ask
for the text when they build on the page. The UI preview reads the file, so
it works in every mode. Vertices in the page are rounded to cm.

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

Files changed (3) hide show
  1. SPEC.md +12 -6
  2. app.py +65 -30
  3. vli/html.py +3 -2
SPEC.md CHANGED
@@ -97,9 +97,9 @@ Verbs: `sat/stood/lay/rested` → `on` (ground implied), `shone/glowed` → `lig
97
  | Tool | In → out |
98
  |---|---|
99
  | `check_words` | sentence, primitives → per-word status, missing words, completions |
100
- | `translate_to_scene` | sentence, primitives, seed → ledger, PNG, GLB, mini HTML |
101
- | `refine_scene` | ledger, changes, seed → ledger, PNG, GLB, mini HTML |
102
- | `simplify_item` | ledger, item id → report, rung PNGs, rung GLBs, mini HTML |
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.
@@ -113,9 +113,15 @@ A self-contained page: Three.js (`three@0.160.0` from unpkg) plus one inline `D`
113
  data object holding the sentence, the reading (word → commits), relations,
114
  unresolved questions, sun, ground, and each object's position, yaw and colour.
115
  Each object also has either inline low-poly geometry (≤400 faces in a scene,
116
- rungs ≤1000 faces in a ladder) or a primitive spec. The geometry is inline, so the
117
- page works after Gradio's temporary file URLs expire, and it stays small enough
118
- for a model's context.
 
 
 
 
 
 
119
 
120
  **No secrets.** The Space is public and stores no token; the datasets are public
121
  and download without one. Optional env: `VLI_CACHE`.
 
97
  | Tool | In → out |
98
  |---|---|
99
  | `check_words` | sentence, primitives → per-word status, missing words, completions |
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 → 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.
 
113
  data object holding the sentence, the reading (word → commits), relations,
114
  unresolved questions, sun, ground, and each object's position, yaw and colour.
115
  Each object also has either inline low-poly geometry (≤400 faces in a scene,
116
+ rungs ≤1000 faces in a ladder) or a primitive spec. Vertices are rounded to cm.
117
+ The geometry is inline, so a saved page works after Gradio's temporary file URLs expire.
118
+
119
+ **Geometry is for the handoff, not the loop.** Even at 400 faces a page costs
120
+ thousands of tokens, which a multi-turn chat can't afford on every refine. So
121
+ `html` defaults to `"url"`: the page comes back as a file URL and the text field is
122
+ empty. Models iterate on the ledger and the picture, and pass `html="inline"` only
123
+ when they build on the page (`"skip"` omits it). An expired URL costs nothing: the
124
+ ledger fully determines the scene, and the next refine re-creates the page.
125
 
126
  **No secrets.** The Space is public and stores no token; the datasets are public
127
  and download without one. Optional env: `VLI_CACHE`.
app.py CHANGED
@@ -4,6 +4,7 @@ One Space for people (this UI) and for models (every public event below is an
4
  MCP tool: demo.launch(mcp_server=True)). Helper events are api_visibility="private".
5
  The Space only visualises; discussion happens in the chat that calls it. Every
6
  picture comes back with a mini HTML page, because HTML is the final destination.
 
7
  """
8
  import html as html_lib
9
  import json
@@ -15,7 +16,8 @@ import threading
15
  import spaces # ZeroGPU: import before any CUDA-touching library
16
  import gradio as gr
17
 
18
- from vli import assets, html, pipeline, scene, simplify
 
19
  from vli.grammar import check_words as _check_words
20
  from vli.lexicon import LEXICON, PRIMITIVE_SHAPES
21
 
@@ -46,6 +48,26 @@ def _seed(value):
46
  raise ValueError(f"seed must be a whole number, got {value!r}")
47
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  @spaces.GPU(duration=60)
50
  def generate_mesh(prompt):
51
  """GPU entry point for the generation tier (last in the fallback chain).
@@ -82,7 +104,8 @@ def check_words(sentence: str, primitives_json: str = "{}") -> str:
82
  _fail(e)
83
 
84
 
85
- def translate_to_scene(sentence: str, primitives_json: str = "{}", seed: str = "0") -> tuple[str, str, str, str]:
 
86
  """Translate an English sentence into a 3D scene.
87
 
88
  Produces the serial ledger (tokens in reading order, the items each word commits,
@@ -95,17 +118,22 @@ def translate_to_scene(sentence: str, primitives_json: str = "{}", seed: str = "
95
  sentence: A sentence using available words, e.g. "the cat sat and the lamp glowed".
96
  primitives_json: JSON object mapping missing words to shapes, e.g. {"sun": "sphere"}.
97
  seed: Picks one of the configurations that satisfy the ledger (positions, facing, sun).
 
 
 
98
 
99
  Returns:
100
- (ledger JSON string, rendered PNG, GLB scene file, mini HTML page).
101
  """
102
  try:
103
- return pipeline.translate(sentence, _json(primitives_json, "primitives_json", {}), _seed(seed))
 
104
  except Exception as e:
105
  _fail(e)
106
 
107
 
108
- def refine_scene(ledger_json: str, changes_json: str = "[]", seed: str = "0") -> tuple[str, str, str, str]:
 
109
  """Refine a ledger: freeze some decisions and change the others, then re-render.
110
 
111
  Changes are a JSON list of:
@@ -126,19 +154,21 @@ def refine_scene(ledger_json: str, changes_json: str = "[]", seed: str = "0") ->
126
  changes_json: JSON list of changes, as above.
127
  seed: Picks the configuration (placement, sun). Placement scales with each
128
  asset's size, so swapping an asset shifts offsets even at the same seed.
 
129
 
130
  Returns:
131
- (ledger JSON string, rendered PNG, GLB scene file, mini HTML page).
132
  """
133
  try:
134
  ledger = _json(ledger_json, "ledger_json")
135
  pipeline.apply_changes(ledger, _json(changes_json, "changes_json", []))
136
- return pipeline.outputs(ledger, _seed(seed))
 
137
  except Exception as e:
138
  _fail(e)
139
 
140
 
141
- def simplify_item(ledger_json: str, item_id: str) -> tuple[str, list, list, str]:
142
  """Build the simplification ladder for one object: full asset -> fewer faces -> convex hull -> box.
143
 
144
  Look at where the object stops reading as its word: that rung is the least geometry
@@ -148,10 +178,12 @@ def simplify_item(ledger_json: str, item_id: str) -> tuple[str, list, list, str]
148
  Args:
149
  ledger_json: Ledger JSON from translate_to_scene or refine_scene.
150
  item_id: The object item to simplify, e.g. "n1".
 
 
151
 
152
  Returns:
153
  (report JSON string, gallery of rung pictures, GLB file per rung,
154
- mini HTML page with the low rungs side by side).
155
  """
156
  try:
157
  ledger = _json(ledger_json, "ledger_json")
@@ -170,7 +202,8 @@ def simplify_item(ledger_json: str, item_id: str) -> tuple[str, list, list, str]
170
  report["rungs"].append({"rung": label, **simplify.stats(rung)})
171
  gallery.append((png, label))
172
  files.append(glb)
173
- return json.dumps(report, indent=1), gallery, files, html.ladder_page(item, rungs)
 
174
  except Exception as e:
175
  _fail(e)
176
 
@@ -210,16 +243,14 @@ def _use_primitive(primitives_json, word, shape):
210
  return json.dumps(prims)
211
 
212
 
213
- def _html_views(page):
214
- """Live preview (sandboxed iframe) and a downloadable .html file."""
215
- if not page:
216
- return "", None
217
- path = os.path.join(tempfile.mkdtemp(prefix="vli_html_"), "scene.html")
218
- with open(path, "w", encoding="utf-8") as f:
219
- f.write(page)
220
- frame = (f'<iframe sandbox="allow-scripts" srcdoc="{html_lib.escape(page, quote=True)}" '
221
- 'style="width:100%;height:460px;border:0;border-radius:8px"></iframe>')
222
- return frame, path
223
 
224
 
225
  EXAMPLE_CHANGES = '[\n {"id": "n1", "freeze": true},\n {"reroll": true}\n]'
@@ -234,7 +265,8 @@ DATASETS_MD = """
234
  3. Missing words: a primitive you choose (box, sphere, cylinder, cone, plane). Generation comes later.
235
 
236
  This Space only visualises and stores no token. Discuss the results in your chat
237
- (e.g. HuggingChat via MCP): every picture comes with a mini HTML page to build on.
 
238
  """
239
 
240
  with gr.Blocks(title="VisualLearningIdea") as demo:
@@ -257,6 +289,8 @@ with gr.Blocks(title="VisualLearningIdea") as demo:
257
  picture = gr.Image(label="Picture", type="filepath")
258
  model = gr.Model3D(label="3D")
259
  with gr.Accordion("Mini HTML", open=False):
 
 
260
  scene_preview = gr.HTML()
261
  scene_file = gr.File(label="Download .html")
262
  scene_html = gr.Code(label="HTML", language="html")
@@ -269,6 +303,7 @@ with gr.Blocks(title="VisualLearningIdea") as demo:
269
  simp = gr.Button("Simplify")
270
  ladder_pics = gr.Gallery(label="Rungs", columns=4)
271
  ladder_preview = gr.HTML()
 
272
  ladder_html = gr.Code(label="HTML", language="html")
273
  ladder_report = gr.Code(label="Report", language="json")
274
  ladder_files = gr.File(label="GLB per rung", file_count="multiple")
@@ -278,15 +313,15 @@ with gr.Blocks(title="VisualLearningIdea") as demo:
278
  .then(_suggestions, words, [status, suggest, missing], api_visibility="private")
279
  suggest.select(_complete, [sentence, suggest], sentence, api_visibility="private")
280
  use_prim.click(_use_primitive, [primitives, missing, shape], primitives, api_visibility="private")
281
- go.click(translate_to_scene, [sentence, primitives, seed], [ledger, picture, model, scene_html],
282
- api_name="translate_to_scene") \
283
- .then(_html_views, scene_html, [scene_preview, scene_file], api_visibility="private")
284
- refine.click(refine_scene, [ledger, changes, seed], [ledger, picture, model, scene_html],
285
- api_name="refine_scene") \
286
- .then(_html_views, scene_html, [scene_preview, scene_file], api_visibility="private")
287
- simp.click(simplify_item, [ledger, item_id], [ladder_report, ladder_pics, ladder_files, ladder_html],
288
- api_name="simplify_item") \
289
- .then(lambda page: _html_views(page)[0], ladder_html, ladder_preview, api_visibility="private")
290
 
291
  if __name__ == "__main__":
292
  demo.launch(mcp_server=True)
 
4
  MCP tool: demo.launch(mcp_server=True)). Helper events are api_visibility="private".
5
  The Space only visualises; discussion happens in the chat that calls it. Every
6
  picture comes back with a mini HTML page, because HTML is the final destination.
7
+ The page is a URL by default: geometry is for the handoff, not the loop.
8
  """
9
  import html as html_lib
10
  import json
 
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
23
 
 
48
  raise ValueError(f"seed must be a whole number, got {value!r}")
49
 
50
 
51
+ HTML_MODES = ["url", "inline", "skip"]
52
+
53
+
54
+ def _html_out(page, mode):
55
+ """The mini HTML as (file, text): a file for "url", file and text for "inline", neither for "skip".
56
+
57
+ Inline geometry costs thousands of tokens, so a model iterating on the ledger
58
+ gets the file URL and asks for the text only when it builds on the page.
59
+ """
60
+ mode = (mode or "url").strip().lower()
61
+ if mode not in HTML_MODES:
62
+ raise ValueError(f"html must be one of {HTML_MODES}, got {mode!r}")
63
+ if mode == "skip" or not page:
64
+ return None, ""
65
+ path = os.path.join(tempfile.mkdtemp(prefix="vli_html_"), "scene.html")
66
+ with open(path, "w", encoding="utf-8") as f:
67
+ f.write(page)
68
+ return path, page if mode == "inline" else ""
69
+
70
+
71
  @spaces.GPU(duration=60)
72
  def generate_mesh(prompt):
73
  """GPU entry point for the generation tier (last in the fallback chain).
 
104
  _fail(e)
105
 
106
 
107
+ def translate_to_scene(sentence: str, primitives_json: str = "{}", seed: str = "0",
108
+ html: str = "url") -> tuple[str, str, str, str, str]:
109
  """Translate an English sentence into a 3D scene.
110
 
111
  Produces the serial ledger (tokens in reading order, the items each word commits,
 
118
  sentence: A sentence using available words, e.g. "the cat sat and the lamp glowed".
119
  primitives_json: JSON object mapping missing words to shapes, e.g. {"sun": "sphere"}.
120
  seed: Picks one of the configurations that satisfy the ledger (positions, facing, sun).
121
+ html: "url" (default) returns the mini HTML as a file URL only; "inline" also returns
122
+ its text (thousands of tokens: ask for it when building on the page); "skip" omits it.
123
+ Iterate on the ledger and picture; the ledger can always re-create the page.
124
 
125
  Returns:
126
+ (ledger JSON string, rendered PNG, GLB scene file, mini HTML file, mini HTML text or "").
127
  """
128
  try:
129
+ *rest, page = pipeline.translate(sentence, _json(primitives_json, "primitives_json", {}), _seed(seed))
130
+ return (*rest, *_html_out(page, html))
131
  except Exception as e:
132
  _fail(e)
133
 
134
 
135
+ def refine_scene(ledger_json: str, changes_json: str = "[]", seed: str = "0",
136
+ html: str = "url") -> tuple[str, str, str, str, str]:
137
  """Refine a ledger: freeze some decisions and change the others, then re-render.
138
 
139
  Changes are a JSON list of:
 
154
  changes_json: JSON list of changes, as above.
155
  seed: Picks the configuration (placement, sun). Placement scales with each
156
  asset's size, so swapping an asset shifts offsets even at the same seed.
157
+ html: "url" (default), "inline" or "skip", as in translate_to_scene.
158
 
159
  Returns:
160
+ (ledger JSON string, rendered PNG, GLB scene file, mini HTML file, mini HTML text or "").
161
  """
162
  try:
163
  ledger = _json(ledger_json, "ledger_json")
164
  pipeline.apply_changes(ledger, _json(changes_json, "changes_json", []))
165
+ *rest, page = pipeline.outputs(ledger, _seed(seed))
166
+ return (*rest, *_html_out(page, html))
167
  except Exception as e:
168
  _fail(e)
169
 
170
 
171
+ def simplify_item(ledger_json: str, item_id: str, html: str = "url") -> tuple[str, list, list, str, str]:
172
  """Build the simplification ladder for one object: full asset -> fewer faces -> convex hull -> box.
173
 
174
  Look at where the object stops reading as its word: that rung is the least geometry
 
178
  Args:
179
  ledger_json: Ledger JSON from translate_to_scene or refine_scene.
180
  item_id: The object item to simplify, e.g. "n1".
181
+ html: "url" (default), "inline" or "skip", as in translate_to_scene. The ladder page
182
+ holds several rungs of up to 1000 faces each, so inline is especially large.
183
 
184
  Returns:
185
  (report JSON string, gallery of rung pictures, GLB file per rung,
186
+ mini HTML file with the low rungs side by side, mini HTML text or "").
187
  """
188
  try:
189
  ledger = _json(ledger_json, "ledger_json")
 
202
  report["rungs"].append({"rung": label, **simplify.stats(rung)})
203
  gallery.append((png, label))
204
  files.append(glb)
205
+ return (json.dumps(report, indent=1), gallery, files,
206
+ *_html_out(html_pages.ladder_page(item, rungs), html))
207
  except Exception as e:
208
  _fail(e)
209
 
 
243
  return json.dumps(prims)
244
 
245
 
246
+ def _html_preview(path):
247
+ """Live preview (sandboxed iframe) of the mini HTML file."""
248
+ if not path:
249
+ return ""
250
+ with open(path, encoding="utf-8") as f:
251
+ page = f.read()
252
+ return (f'<iframe sandbox="allow-scripts" srcdoc="{html_lib.escape(page, quote=True)}" '
253
+ 'style="width:100%;height:460px;border:0;border-radius:8px"></iframe>')
 
 
254
 
255
 
256
  EXAMPLE_CHANGES = '[\n {"id": "n1", "freeze": true},\n {"reroll": true}\n]'
 
265
  3. Missing words: a primitive you choose (box, sphere, cylinder, cone, plane). Generation comes later.
266
 
267
  This Space only visualises and stores no token. Discuss the results in your chat
268
+ (e.g. HuggingChat via MCP): every picture comes with a mini HTML page to build on,
269
+ as a URL by default (`html="inline"` returns its text).
270
  """
271
 
272
  with gr.Blocks(title="VisualLearningIdea") as demo:
 
289
  picture = gr.Image(label="Picture", type="filepath")
290
  model = gr.Model3D(label="3D")
291
  with gr.Accordion("Mini HTML", open=False):
292
+ html_mode = gr.Radio(label="HTML text in the result", choices=HTML_MODES, value="url",
293
+ info="url: file only · inline: also the text · skip: no page")
294
  scene_preview = gr.HTML()
295
  scene_file = gr.File(label="Download .html")
296
  scene_html = gr.Code(label="HTML", language="html")
 
303
  simp = gr.Button("Simplify")
304
  ladder_pics = gr.Gallery(label="Rungs", columns=4)
305
  ladder_preview = gr.HTML()
306
+ ladder_file = gr.File(label="Download .html")
307
  ladder_html = gr.Code(label="HTML", language="html")
308
  ladder_report = gr.Code(label="Report", language="json")
309
  ladder_files = gr.File(label="GLB per rung", file_count="multiple")
 
313
  .then(_suggestions, words, [status, suggest, missing], api_visibility="private")
314
  suggest.select(_complete, [sentence, suggest], sentence, api_visibility="private")
315
  use_prim.click(_use_primitive, [primitives, missing, shape], primitives, api_visibility="private")
316
+ go.click(translate_to_scene, [sentence, primitives, seed, html_mode],
317
+ [ledger, picture, model, scene_file, scene_html], api_name="translate_to_scene") \
318
+ .then(_html_preview, scene_file, scene_preview, api_visibility="private")
319
+ refine.click(refine_scene, [ledger, changes, seed, html_mode],
320
+ [ledger, picture, model, scene_file, scene_html], api_name="refine_scene") \
321
+ .then(_html_preview, scene_file, scene_preview, api_visibility="private")
322
+ simp.click(simplify_item, [ledger, item_id, html_mode],
323
+ [ladder_report, ladder_pics, ladder_files, ladder_file, ladder_html], api_name="simplify_item") \
324
+ .then(_html_preview, ladder_file, ladder_preview, api_visibility="private")
325
 
326
  if __name__ == "__main__":
327
  demo.launch(mcp_server=True)
vli/html.py CHANGED
@@ -3,7 +3,8 @@
3
  HTML is the final destination: a chat model reads this page, edits it and
4
  builds its own on it. The page is self-contained Three.js. Geometry is inlined
5
  at low poly (a rung of the simplification ladder), so it outlives Gradio's
6
- temporary file URLs and stays small enough for a model's context.
 
7
  """
8
  import json
9
 
@@ -29,7 +30,7 @@ def _sky_hex(sun):
29
  def _geometry(mesh, budget):
30
  m = decimate(mesh, budget) if len(mesh.faces) > budget else mesh
31
  return {"faces": int(len(m.faces)),
32
- "p": np.round(m.vertices, 3).ravel().tolist(),
33
  "i": m.faces.ravel().astype(int).tolist()}
34
 
35
 
 
3
  HTML is the final destination: a chat model reads this page, edits it and
4
  builds its own on it. The page is self-contained Three.js. Geometry is inlined
5
  at low poly (a rung of the simplification ladder), so it outlives Gradio's
6
+ temporary file URLs. Even low poly costs thousands of tokens, so the tools
7
+ return the page as a URL unless the caller asks for its text.
8
  """
9
  import json
10
 
 
30
  def _geometry(mesh, budget):
31
  m = decimate(mesh, budget) if len(mesh.faces) > budget else mesh
32
  return {"faces": int(len(m.faces)),
33
+ "p": np.round(m.vertices, 2).ravel().tolist(), # cm: plenty at low poly, fewer tokens
34
  "i": m.faces.ravel().astype(int).tolist()}
35
 
36