Spaces:
Running
Running
Download demo/app.py from ManiacWallnut/ManiTaskGen: direct link, hf CLI and curl.
- Browser
- Download file 19.4 kB
-
https://huggingface.co/spaces/ManiacWallnut/ManiTaskGen/resolve/main/demo/app.py
- Command line
-
hf download hf://spaces/ManiacWallnut/ManiTaskGen/demo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ManiacWallnut/ManiTaskGen/resolve/main/demo/app.py
19.4 kB
| """ | |
| ManiTaskGen — public demo (Gradio, CPU-only). | |
| Visitors can: | |
| - click "Try the built-in example", or | |
| - upload their own scene pack (`scene.zip`, Habitat/ReplicaCAD-style layout), | |
| and get process-based tasks + outcome-based task candidates generated by the | |
| original ManiTaskGen generators. Generation itself never calls a VLM. | |
| Optional: GLM feasibility voting (text-only) on a diverse sample of outcome | |
| candidates — requires the visitor to supply their own API key in the UI; | |
| votes are recorded truthfully (real model name per vote) in tasks.jsonl. | |
| Launch from the repository root: | |
| python demo/app.py | |
| """ | |
| import os | |
| import sys | |
| import time | |
| import shutil | |
| import uuid | |
| DEMO_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| REPO_ROOT = os.path.dirname(DEMO_DIR) | |
| sys.path.insert(0, REPO_ROOT) | |
| sys.path.insert(0, DEMO_DIR) | |
| os.chdir(REPO_ROOT) # mesh paths inside packs are resolved against CWD | |
| import gradio as gr # noqa: E402 | |
| import pipeline # noqa: E402 | |
| from pipeline import ( # noqa: E402 | |
| BUILTIN_ENTRY, | |
| export_jsonl, | |
| generate_builtin, | |
| generate_from_pack, | |
| ) | |
| from scene_pack import ( # noqa: E402 | |
| ScenePackError, | |
| check_pack_assets, | |
| extract_zip, | |
| find_entry_scene, | |
| scene_id_from_entry, | |
| ) | |
| from glm_voter import DEFAULT_MODEL, vote_on_candidates # noqa: E402 | |
| EXAMPLE_ZIP = os.path.join(DEMO_DIR, "assets", "example_scene.zip") | |
| UPLOAD_ROOT = os.path.join(REPO_ROOT, "output", "demo_uploads") | |
| MAX_CARDS = 8 # per-category task cards in the UI (rest goes to tasks.jsonl) | |
| TITLE = "# ManiTaskGen · Task Generation Demo" | |
| DESCRIPTION = ( | |
| "Upload a scene pack (or try the built-in example) and ManiTaskGen " | |
| "generates **process-based tasks** (step-by-step move instructions) and " | |
| "**outcome-based task candidates** (goal-state instructions from " | |
| "ManiTaskOT-200 templates).\n\n" | |
| "🔒 **No API key needed for generation · no VLM · runs on free CPU.** " | |
| "Outcome candidates start *unvoted*; an optional GLM text-voting pass can " | |
| "be run below with your own key." | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Formatting helpers | |
| # --------------------------------------------------------------------------- | |
| def _goal_line(rec): | |
| goals = rec.get("goal") or [] | |
| return f"`{goals[0]}`" if goals else "—" | |
| def process_card_md(i, rec) -> str: | |
| ents = rec.get("entities") or {} | |
| items = ", ".join(f"`{x}`" for x in ents.get("items", [])) | |
| dests = ", ".join(f"`{x}`" for x in ents.get("destinations", [])) | |
| types = ", ".join(t for t in rec.get("task_types", []) if t) | |
| lines = [f"**#{i + 1} · {rec['instruction']}**"] | |
| lines.append(f"🎯 goal: {_goal_line(rec)}") | |
| meta = [] | |
| if items: | |
| meta.append(f"items: {items}") | |
| if dests: | |
| meta.append(f"surfaces: {dests}") | |
| if types: | |
| meta.append(f"steps: {len(rec.get('steps', []))} ({types[0]}…)") | |
| if meta: | |
| lines.append(" · ".join(meta)) | |
| return "\n\n".join(lines) | |
| def outcome_card_md(i, rec) -> str: | |
| badge, vote_line = "⏳ not voted", "" | |
| if rec.get("voting_status") in ("approved", "rejected", "vote_failed"): | |
| st = rec["voting_status"] | |
| n_feas = sum( | |
| 1 for v in rec.get("votes", []) if v.get("answer") == "Feasible" | |
| ) | |
| got = rec.get("votes_received", 0) | |
| if st == "approved": | |
| badge = f"✅ approved ({n_feas}/{got} voters)" | |
| elif st == "rejected": | |
| badge = f"❌ rejected ({n_feas}/{got} voters)" | |
| else: | |
| badge = "⚠️ vote failed" | |
| reasons = [ | |
| f"{v.get('voter','?')}({v.get('temperature')}): {v.get('answer')}" | |
| + (f" — {v.get('reason')}" if v.get("reason") else "") | |
| for v in rec.get("votes", [])[:3] | |
| ] | |
| vote_line = "\n\n🗳 " + " · ".join(reasons) | |
| ents = rec.get("bound_entities") or {} | |
| surfaces = ", ".join(f"`{p}`" for p in ents.get("platforms", [])) | |
| layers = ", ".join(f"`{m}`" for m in ents.get("multilayer_objects", [])) | |
| lines = [f"**#{i + 1} · {rec['instruction']}** \n{badge}"] | |
| meta = [] | |
| if rec.get("pattern_id") is not None: | |
| meta.append(f"template #{rec['pattern_id']}") | |
| if surfaces: | |
| meta.append(f"platform: {surfaces}") | |
| if layers: | |
| meta.append(f"multilayer: {layers}") | |
| if meta: | |
| lines.append("🔎 " + " · ".join(meta)) | |
| if vote_line: | |
| lines.append(vote_line.strip()) | |
| return "\n\n".join(lines) | |
| def status_table_md(result, gen_seconds) -> str: | |
| t = result.timings | |
| vote_note = "" | |
| if result.voting_summary: | |
| vs = result.voting_summary | |
| vote_note = f" | GLM voting: **{vs['approved']}✅ / {vs['rejected']}❌** of {vs['voted']}" | |
| return ( | |
| "| | |\n|---|---|\n" | |
| f"| scene | `{result.scene_id}` ({result.source}) |\n" | |
| f"| process-based tasks | **{len(result.process_tasks)}** " | |
| f"(in {t.get('process_based', '?')}s) |\n" | |
| f"| outcome candidates | **{len(result.outcome_candidates)}** " | |
| f"(in {t.get('outcome_based', '?')}s, generation VLM-free){vote_note} |\n" | |
| f"| wall time | {gen_seconds:.1f}s total |" | |
| ) | |
| def _fill_cards(cards_list, records, count, card_fmt): | |
| updates = [] | |
| shown = min(count, MAX_CARDS) | |
| for i in range(MAX_CARDS): | |
| if i < min(len(records), shown): | |
| updates.append(gr.update(value=card_fmt(i, records[i]), visible=True)) | |
| else: | |
| updates.append(gr.update(visible=False)) | |
| return updates | |
| def _outcome_note_md(records, count): | |
| extra = len(records) - count | |
| if extra > 0: | |
| return f"_Showing {min(count, MAX_CARDS)} of {len(records)} — the rest are in `tasks.jsonl`._" | |
| return "" | |
| def process_outputs(result, count): | |
| cards = _fill_cards(None, result.process_tasks, count, process_card_md) | |
| note = _outcome_note_md(result.process_tasks, count) or ( | |
| "_No process-based tasks could be generated for this scene._" | |
| if not result.process_tasks | |
| else "" | |
| ) | |
| return cards + [note] | |
| def outcome_outputs(result, count): | |
| # show approved candidates first once voting has run | |
| recs = list(result.outcome_candidates) | |
| if result.voting_summary: | |
| recs.sort(key=lambda r: 0 if r.get("voting_status") == "approved" else 1) | |
| cards = _fill_cards(None, recs, count, outcome_card_md) | |
| note = _outcome_note_md(recs, count) | |
| if not recs: | |
| note = ( | |
| "_No outcome-based templates could be bound to this scene. " | |
| "Outcome tasks need platforms with objects on them; categories " | |
| "come from object names before the first `_` (e.g. `book_red_0` " | |
| "→ book)._" | |
| ) | |
| title = ( | |
| "#### 🎯 Outcome-based task candidates · No VLM voting " | |
| "— paste your key in 🗳 panel below and run GLM voting" | |
| ) | |
| if result.voting_summary: | |
| vs = result.voting_summary | |
| title = ( | |
| f"#### 🎯 Outcome-based task candidates · GLM voting " | |
| f"({vs['approved']}✅/{vs['rejected']}❌ of {vs['voted']} sampled, " | |
| f"{len(recs) - vs['voted']} unvoted)" | |
| ) | |
| return [title] + cards + [note] | |
| # --------------------------------------------------------------------------- | |
| # Gradio handlers | |
| # --------------------------------------------------------------------------- | |
| def _cleanup_old_uploads(keep=20): | |
| try: | |
| if not os.path.isdir(UPLOAD_ROOT): | |
| return | |
| dirs = sorted( | |
| (os.path.join(UPLOAD_ROOT, d) for d in os.listdir(UPLOAD_ROOT)), | |
| key=os.path.getmtime, | |
| ) | |
| for old in dirs[:-keep]: | |
| shutil.rmtree(old, ignore_errors=True) | |
| except Exception: | |
| pass | |
| def on_generate_builtin(max_process_tasks, process_task_length, outcome_per_pattern, display_count): | |
| t0 = time.perf_counter() | |
| try: | |
| result = generate_builtin( | |
| max_process_tasks=int(max_process_tasks), | |
| process_task_length=int(process_task_length), | |
| outcome_per_pattern=int(outcome_per_pattern), | |
| ) | |
| except Exception as e: | |
| raise gr.Error(f"Generation failed: {e}") | |
| count = int(display_count) | |
| state = {"result": result} | |
| return ( | |
| status_table_md(result, time.perf_counter() - t0), | |
| *process_outputs(result, count), | |
| *outcome_outputs(result, count), | |
| result.jsonl_path, | |
| state, | |
| ) | |
| def on_generate_upload(file, max_process_tasks, process_task_length, outcome_per_pattern, display_count): | |
| t0 = time.perf_counter() | |
| if file is None: | |
| raise gr.Error("Please upload a scene.zip first, or try the built-in example.") | |
| upload_path = file if isinstance(file, str) else file.name | |
| run_id = uuid.uuid4().hex[:12] | |
| work_dir = os.path.join(UPLOAD_ROOT, run_id) | |
| os.makedirs(work_dir, exist_ok=True) | |
| try: | |
| pack_dir = extract_zip(upload_path, os.path.join(work_dir, "unpacked")) | |
| entry = find_entry_scene(pack_dir) | |
| check_pack_assets(pack_dir, entry) | |
| result = generate_from_pack( | |
| pack_dir, | |
| entry, | |
| work_dir=os.path.join(work_dir, "run"), | |
| max_process_tasks=int(max_process_tasks), | |
| process_task_length=int(process_task_length), | |
| outcome_per_pattern=int(outcome_per_pattern), | |
| ) | |
| except ScenePackError as e: | |
| raise gr.Error(f"Invalid scene pack: {e}") | |
| except FileNotFoundError as e: | |
| raise gr.Error(f"Missing asset in scene pack: {e}") | |
| except Exception as e: | |
| raise gr.Error(f"Generation failed: {e}") | |
| finally: | |
| _cleanup_old_uploads() | |
| count = int(display_count) | |
| state = {"result": result} | |
| return ( | |
| status_table_md(result, time.perf_counter() - t0), | |
| *process_outputs(result, count), | |
| *outcome_outputs(result, count), | |
| result.jsonl_path, | |
| state, | |
| ) | |
| def on_run_voting( | |
| state, api_key, model, n_voters, sample_size, display_count | |
| ): | |
| if not state or "result" not in state: | |
| raise gr.Error("Generate tasks first (built-in example or your scene.zip).") | |
| api_key = (api_key or "").strip() | |
| if not api_key: | |
| raise gr.Error("Please paste your API key (Z.AI / OpenAI-compatible). It is used for this vote only and is never stored.") | |
| result = state["result"] | |
| if result.graph is None: | |
| raise gr.Error("This result has no scene graph attached; regenerate first.") | |
| def progress(done, total): | |
| pass | |
| try: | |
| summary = vote_on_candidates( | |
| result.outcome_candidates, | |
| result.graph, | |
| api_key=api_key, | |
| model=(model or DEFAULT_MODEL).strip(), | |
| n_voters=int(n_voters), | |
| sample_size=int(sample_size), | |
| progress=progress, | |
| ) | |
| except Exception as e: | |
| raise gr.Error(f"Voting failed: {e}") | |
| result.voting_summary = summary | |
| export_jsonl(result) | |
| count = int(display_count) | |
| state["result"] = result | |
| vote_status = ( | |
| f"🗳 **Voting done** — model `{summary['model']}`, {summary['n_voters']} voters: " | |
| f"**{summary['approved']} approved / {summary['rejected']} rejected / " | |
| f"{summary['failed']} failed** out of {summary['voted']} sampled " | |
| f"({len(result.outcome_candidates) - summary['voted']} candidates remain unvoted). " | |
| f"_{summary['voter_note']}_" | |
| ) | |
| return ( | |
| *outcome_outputs(result, count), | |
| result.jsonl_path, | |
| vote_status, | |
| state, | |
| ) | |
| def on_display_count_change(state, display_count): | |
| if not state or "result" not in state: | |
| empty_cards = [gr.update(visible=False)] * MAX_CARDS | |
| return ( | |
| *empty_cards, "", | |
| "#### 🎯 Outcome-based task candidates · No VLM voting " | |
| "— paste your key in 🗳 panel below and run GLM voting", | |
| *empty_cards, "", | |
| ) | |
| result = state["result"] | |
| count = int(display_count) | |
| return (*process_outputs(result, count), *outcome_outputs(result, count)) | |
| # --------------------------------------------------------------------------- | |
| # UI | |
| # --------------------------------------------------------------------------- | |
| def build_ui(): | |
| with gr.Blocks(title="ManiTaskGen Demo") as ui: | |
| gr.Markdown(TITLE) | |
| gr.Markdown(DESCRIPTION) | |
| state = gr.State(value=None) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("### 1 · Choose a scene") | |
| with gr.Accordion("Use your own scene", open=True): | |
| upload = gr.File( | |
| label="Upload scene.zip (Habitat/ReplicaCAD-style pack)", | |
| file_types=[".zip"], | |
| type="filepath", | |
| ) | |
| gr.Markdown( | |
| "The ZIP should contain a `*.scene_instance.json` " | |
| "(e.g. `configs/scenes/...`), its meshes and configs — " | |
| "see the pack format in the README." | |
| ) | |
| with gr.Accordion("Built-in example", open=False): | |
| gr.Markdown( | |
| "A small synthetic 'demo studio' (desk, low table, " | |
| "3-layer shelf, counter + 12 small items). Tiny, " | |
| "license-free, great for a first try." | |
| ) | |
| example_zip = gr.File( | |
| label="Download example_scene.zip", | |
| value=EXAMPLE_ZIP, | |
| interactive=False, | |
| ) | |
| builtin_btn = gr.Button( | |
| "✨ Try the built-in example", variant="primary" | |
| ) | |
| with gr.Accordion("Generation options", open=False): | |
| max_process_tasks = gr.Slider( | |
| 5, 50, value=20, step=1, | |
| label="Process-based tasks to generate", | |
| ) | |
| process_task_length = gr.Slider( | |
| 1, 5, value=3, step=1, | |
| label="Max steps per process task", | |
| ) | |
| outcome_per_pattern = gr.Slider( | |
| 1, 5, value=3, step=1, | |
| label="Outcome candidates per template", | |
| ) | |
| display_count = gr.Slider( | |
| 1, MAX_CARDS, value=5, step=1, | |
| label="Tasks to show per category", | |
| ) | |
| upload_btn = gr.Button( | |
| "🚀 Generate from my scene.zip", variant="primary" | |
| ) | |
| with gr.Column(scale=2): | |
| gr.Markdown("### 2 · Results") | |
| status_md = gr.Markdown("Waiting for a scene…") | |
| with gr.Group(): | |
| gr.Markdown("#### 📋 Process-based tasks (step-by-step)") | |
| process_cards = [ | |
| gr.Markdown("", visible=False) for _ in range(MAX_CARDS) | |
| ] | |
| process_note = gr.Markdown("") | |
| outcome_title = gr.Markdown( | |
| "#### 🎯 Outcome-based task candidates · No VLM voting — paste your key in 🗳 panel below and run GLM voting" | |
| ) | |
| with gr.Group(): | |
| outcome_cards = [ | |
| gr.Markdown("", visible=False) for _ in range(MAX_CARDS) | |
| ] | |
| outcome_note = gr.Markdown("") | |
| jsonl_out = gr.File(label="Download results (tasks.jsonl)") | |
| with gr.Accordion( | |
| "🗳 GLM feasibility voting (optional, text-only) — paste your key and click to filter candidates", | |
| open=True, | |
| ): | |
| gr.Markdown( | |
| "Vote on a **template-diverse sample** of outcome " | |
| "candidates with an OpenAI-compatible chat model " | |
| "(default Z.AI `glm-5.3-flash`). Multiple voters with " | |
| "different personas/temperatures decide by majority. " | |
| "**Your key is used only for this request and never " | |
| "stored**; every vote is recorded with the real model " | |
| "name in `tasks.jsonl`." | |
| ) | |
| with gr.Row(): | |
| vote_key = gr.Textbox( | |
| label="API key", type="password", | |
| placeholder="sk-… (sent only with your vote request)", | |
| ) | |
| vote_model = gr.Textbox( | |
| label="Model", value=DEFAULT_MODEL, | |
| ) | |
| with gr.Row(): | |
| vote_n_voters = gr.Slider( | |
| 1, 5, value=3, step=1, | |
| label="Voters (majority decides)", | |
| ) | |
| vote_sample = gr.Slider( | |
| 5, 50, value=10, step=5, | |
| label="Candidates to vote on", | |
| ) | |
| vote_btn = gr.Button("🗳 Run GLM voting", variant="secondary") | |
| vote_status = gr.Markdown("") | |
| gen_outputs = [ | |
| status_md, | |
| *process_cards, process_note, | |
| outcome_title, *outcome_cards, outcome_note, | |
| jsonl_out, | |
| state, | |
| ] | |
| vote_outputs = [ | |
| outcome_title, *outcome_cards, outcome_note, | |
| jsonl_out, vote_status, state, | |
| ] | |
| display_outputs = [ | |
| *process_cards, process_note, | |
| outcome_title, *outcome_cards, outcome_note, | |
| ] | |
| builtin_btn.click( | |
| on_generate_builtin, | |
| inputs=[max_process_tasks, process_task_length, outcome_per_pattern, display_count], | |
| outputs=gen_outputs, | |
| ) | |
| upload_btn.click( | |
| on_generate_upload, | |
| inputs=[upload, max_process_tasks, process_task_length, outcome_per_pattern, display_count], | |
| outputs=gen_outputs, | |
| ) | |
| vote_btn.click( | |
| on_run_voting, | |
| inputs=[state, vote_key, vote_model, vote_n_voters, vote_sample, display_count], | |
| outputs=vote_outputs, | |
| ) | |
| display_count.change( | |
| on_display_count_change, | |
| inputs=[state, display_count], | |
| outputs=display_outputs, | |
| ) | |
| gr.Markdown( | |
| "Docs: pack format & how to modify a scene → repository README " | |
| "(demo section). Process tasks reuse the ManiTaskGen scene-graph " | |
| "planner; outcome candidates instantiate ManiTaskOT-200 templates " | |
| "on the scene graph; generation is fully offline." | |
| ) | |
| return ui | |
| def main(): | |
| # Pre-build the built-in scene graph once so the first click is fast. | |
| try: | |
| pipeline._get_builtin_graph() | |
| except Exception as e: | |
| print(f"[demo] warning: failed to pre-build built-in graph: {e}") | |
| build_ui().queue(max_size=8).launch( | |
| server_name="0.0.0.0", | |
| server_port=int(os.environ.get("GRADIO_SERVER_PORT", "7860")), | |
| show_error=True, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |