multimodalart HF Staff commited on
Commit
fbca883
·
verified ·
1 Parent(s): 3517f6a

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +88 -42
app.py CHANGED
@@ -32,6 +32,7 @@ GGUF = "gguf/Inkling-2-Mini-3D-Coder-Q8_0.gguf"
32
  CTX = 65536 # the context used for training and evaluation
33
  CHUNK_SECONDS = 100 # wall time per GPU call (load + prefill + generation)
34
  GPU_DURATION = 115 # measured: ~100 s pass + ~15% margin
 
35
 
36
  # Exact system prompt from the model card (matches training and evaluation).
37
  SYSTEM_PROMPT = (
@@ -164,55 +165,77 @@ PLACEHOLDER = (
164
  )
165
 
166
 
167
- def generate(scene: str, effort: str = DEFAULT_EFFORT, temperature: float = 0.9, max_new_tokens: int = 60000,
168
- seed: int = 67):
169
- """Generate an interactive Three.js scene (a standalone HTML file) from a text description.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
  Args:
172
  scene: description of the 3D scene to build.
173
  effort: thinking-effort level, one of the keys of EFFORT (low / medium / high).
174
  temperature: sampling temperature.
175
- max_new_tokens: cap on generated tokens (reasoning + HTML).
176
  seed: random seed.
 
 
 
 
177
 
178
  Returns:
179
- The rendered scene (HTML iframe), the HTML source, the model's reasoning, the HTML file and a status line.
180
  """
181
- if not scene or not scene.strip():
182
- raise gr.Error("Describe a scene first.")
 
 
 
183
  prompt = build_prompt(scene, EFFORT.get(effort, "0.2"))
184
- raw, chunk, t_start, done = "", 0, time.time(), False
185
- max_new_tokens = int(max_new_tokens)
186
- yield gr.update(value=PLACEHOLDER.format("Waiting for a GPU…")), "", "", gr.update(), "Starting…"
187
- n_total = 0
188
- while not done:
189
- before = len(raw)
190
- for text, n_new, finished in _gen_chunk(prompt, raw, max_new_tokens - n_total, float(temperature), int(seed) + chunk):
191
- raw += text
192
- n_total += n_new
193
- done = finished
194
- if len(raw) - before > 400 or finished:
195
- before = len(raw)
196
- thinking, answer = split_channels(raw)
197
- phase = "writing the HTML" if answer.strip() else "thinking"
198
- status = f"Pass {chunk + 1} · {phase} · {n_total:,} tokens · {time.time() - t_start:.0f}s"
199
- yield gr.update(), answer[-6000:], thinking[-4000:], gr.update(), status
200
- chunk += 1
201
- if n_total >= max_new_tokens:
202
- done = True
203
- thinking, answer = split_channels(raw)
204
- doc = extract_html(answer)
205
- path = os.path.join(tempfile.mkdtemp(), "index.html")
206
- if doc:
207
- with open(path, "w") as f:
208
- f.write(doc)
209
- status = f"Done in {time.time() - t_start:.0f}s · {n_total:,} tokens · {chunk} GPU pass(es)"
210
- yield gr.update(value=iframe(doc)), doc, thinking, path, status
211
  else:
212
- msg = "The model did not finish a complete HTML file within the token budget. Try again with another seed or a lower thinking effort."
213
- with open(path, "w") as f:
214
- f.write(f"<!-- {msg} -->\n" + answer)
215
- yield gr.update(value=PLACEHOLDER.format(msg)), answer, thinking, path, msg
216
 
217
 
218
  EXAMPLES = [
@@ -227,6 +250,20 @@ EXAMPLES = [
227
  "cargo decks, cranes and a marked rover route across red terrain. Include a slowly driving rover and camera controls."],
228
  ]
229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  CSS = """
231
  #col-container { max-width: 1200px; margin: 0 auto; }
232
  .dark .gradio-container { color: var(--body-text-color); }
@@ -259,11 +296,20 @@ with gr.Blocks(title="Inkling 2 Mini-3D-Coder") as demo:
259
  temperature = gr.Slider(0.0, 1.5, value=0.9, step=0.05, label="Temperature")
260
  max_new_tokens = gr.Slider(2048, 64000, value=60000, step=1024, label="Max new tokens (reasoning + HTML)")
261
  seed = gr.Number(value=67, precision=0, label="Seed")
 
 
 
 
262
  outputs = [viewer, code, thinking, html_file, status]
263
- gr.Examples(examples=EXAMPLES, inputs=[scene], outputs=outputs, fn=generate,
264
- cache_examples=True, cache_mode="lazy")
265
- run.click(generate, inputs=[scene, effort, temperature, max_new_tokens, seed], outputs=outputs, api_name="generate")
266
- scene.submit(generate, inputs=[scene, effort, temperature, max_new_tokens, seed], outputs=outputs)
 
 
 
 
 
267
 
268
  if __name__ == "__main__":
269
  demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
 
32
  CTX = 65536 # the context used for training and evaluation
33
  CHUNK_SECONDS = 100 # wall time per GPU call (load + prefill + generation)
34
  GPU_DURATION = 115 # measured: ~100 s pass + ~15% margin
35
+ MAX_PASSES = 12 # ~5K tokens per pass -> up to ~55K tokens
36
 
37
  # Exact system prompt from the model card (matches training and evaluation).
38
  SYSTEM_PROMPT = (
 
165
  )
166
 
167
 
168
+ def _finalize(raw: str, n_total: int, passes: int):
169
+ thinking, answer = split_channels(raw)
170
+ doc = extract_html(answer)
171
+ path = os.path.join(tempfile.mkdtemp(), "index.html")
172
+ if doc:
173
+ with open(path, "w") as f:
174
+ f.write(doc)
175
+ status = f"✅ Done · {n_total:,} tokens · {passes} GPU pass(es)"
176
+ return iframe(doc), doc, thinking, path, status
177
+ msg = ("The model did not finish a complete HTML file within the token budget. "
178
+ "Try again with another seed or a lower thinking effort.")
179
+ with open(path, "w") as f:
180
+ f.write(f"<!-- {msg} -->\n" + answer)
181
+ return PLACEHOLDER.format(msg), answer, thinking, path, "⚠️ " + msg
182
+
183
+
184
+ def start(scene: str):
185
+ """Reset the generation state for a new scene."""
186
+ if not scene or not scene.strip():
187
+ raise gr.Error("Describe a scene first.")
188
+ return (PLACEHOLDER.format("Waiting for a GPU… (the scene renders here once the HTML is complete)"),
189
+ "", "", None, "Starting…", "", 0, 0, False)
190
+
191
+
192
+ def generate_pass(scene: str, effort: str = DEFAULT_EFFORT, temperature: float = 0.9, max_new_tokens: int = 60000,
193
+ seed: int = 67, raw: str = "", n_total: int = 0, passes: int = 0, done: bool = False):
194
+ """Run one GPU pass (~100 s) of scene generation, continuing from the raw text generated so far.
195
+
196
+ Call repeatedly, feeding back `raw`, `n_total`, `passes` and `done`, until `done` is True.
197
 
198
  Args:
199
  scene: description of the 3D scene to build.
200
  effort: thinking-effort level, one of the keys of EFFORT (low / medium / high).
201
  temperature: sampling temperature.
202
+ max_new_tokens: cap on generated tokens (reasoning + HTML) over all passes.
203
  seed: random seed.
204
+ raw: raw model output so far ("" for a new scene).
205
+ n_total: tokens generated so far.
206
+ passes: GPU passes run so far.
207
+ done: whether generation already finished (the call is then a no-op).
208
 
209
  Returns:
210
+ Rendered scene (iframe HTML), HTML source / answer, reasoning, HTML file, status, raw, n_total, passes, done.
211
  """
212
+ if done or not scene or not scene.strip():
213
+ yield (gr.update(),) * 9
214
+ return
215
+ n_total, passes, max_new_tokens = int(n_total or 0), int(passes or 0), int(max_new_tokens)
216
+ raw = raw or ""
217
  prompt = build_prompt(scene, EFFORT.get(effort, "0.2"))
218
+ before, finished = len(raw), False
219
+ for text, n_new, finished in _gen_chunk(prompt, raw, max_new_tokens - n_total, float(temperature),
220
+ int(seed) + passes):
221
+ raw += text
222
+ n_total += n_new
223
+ if len(raw) - before > 400 and not finished:
224
+ before = len(raw)
225
+ thinking, answer = split_channels(raw)
226
+ phase = "writing the HTML" if answer.strip() else "thinking"
227
+ status = f"⏳ Pass {passes + 1} · {phase} · {n_total:,} tokens"
228
+ yield (gr.update(), answer[-6000:], thinking[-4000:], gr.update(), status,
229
+ gr.update(), gr.update(), gr.update(), gr.update())
230
+ passes += 1
231
+ if n_total >= max_new_tokens or passes >= MAX_PASSES:
232
+ finished = True
233
+ if finished:
234
+ yield (*_finalize(raw, n_total, passes), raw, n_total, passes, True)
 
 
 
 
 
 
 
 
 
 
235
  else:
236
+ thinking, answer = split_channels(raw)
237
+ status = f"⏳ Pass {passes} done · {n_total:,} tokens · continuing…"
238
+ yield (gr.update(), answer[-6000:], thinking[-4000:], gr.update(), status, raw, n_total, passes, False)
 
239
 
240
 
241
  EXAMPLES = [
 
250
  "cargo decks, cranes and a marked rover route across red terrain. Include a slowly driving rover and camera controls."],
251
  ]
252
 
253
+ EXAMPLE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples")
254
+
255
+
256
+ def load_example(scene: str):
257
+ """Show the precomputed scene for an example prompt (generated by this Space at low effort, seed 67)."""
258
+ for i, (p,) in enumerate(EXAMPLES):
259
+ path = os.path.join(EXAMPLE_DIR, f"example_{i}.html")
260
+ if p == scene and os.path.exists(path):
261
+ doc = open(path).read()
262
+ return (iframe(doc), doc, "(precomputed example — press Generate scene for a fresh one)", path,
263
+ "Precomputed example output · press **Generate scene** to run the model on this prompt")
264
+ return (PLACEHOLDER.format("Press Generate scene to build this example."), "", "", None, "")
265
+
266
+
267
  CSS = """
268
  #col-container { max-width: 1200px; margin: 0 auto; }
269
  .dark .gradio-container { color: var(--body-text-color); }
 
296
  temperature = gr.Slider(0.0, 1.5, value=0.9, step=0.05, label="Temperature")
297
  max_new_tokens = gr.Slider(2048, 64000, value=60000, step=1024, label="Max new tokens (reasoning + HTML)")
298
  seed = gr.Number(value=67, precision=0, label="Seed")
299
+ raw_box = gr.Textbox(visible=False)
300
+ ntok_box = gr.Number(value=0, visible=False, precision=0)
301
+ pass_box = gr.Number(value=0, visible=False, precision=0)
302
+ done_box = gr.Checkbox(value=False, visible=False)
303
  outputs = [viewer, code, thinking, html_file, status]
304
+ state = [raw_box, ntok_box, pass_box, done_box]
305
+ gr.Examples(examples=EXAMPLES, inputs=[scene], outputs=outputs, fn=load_example, label="Examples (precomputed outputs from this Space, low effort)",
306
+ cache_examples=False, run_on_click=True)
307
+ pass_inputs = [scene, effort, temperature, max_new_tokens, seed] + state
308
+ for trigger in (run.click, scene.submit):
309
+ ev = trigger(start, inputs=[scene], outputs=outputs + state, api_name=False)
310
+ for k in range(MAX_PASSES):
311
+ ev = ev.then(generate_pass, inputs=pass_inputs, outputs=outputs + state,
312
+ api_name="generate_pass" if (k == 0 and trigger == run.click) else False)
313
 
314
  if __name__ == "__main__":
315
  demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)