"""Drop anything: objects made from photos are dropped and dragged on a table, and a learned particle world model
predicts the next 2 seconds. A Gradio app for a Hugging Face Space on ZeroGPU: each visitor has their own table, and each
Run predicts 3 model windows (48 frames) in one GPU call.
The models and their code come from a private model repository (PWM_MODEL_REPO, read with the Space's HF_TOKEN secret),
or from a local copy (PWM_MODEL_DIR) when testing: pwm_infer (the library's inference modules), weights/, shelf/.
The page is one custom component (web/viewer.*: three.js, the live demo's renderer). It sends {op, actions, req} with
trigger('click', ...); the reply (JSON text) goes to a hidden Textbox and back to the page with a client-side .then().
Light lookups (the shelf, an object's drawing) are server functions; only the model call uses the GPU queue.
"""
from __future__ import annotations
import json
import os
import re
import secrets
import sys
import time
from pathlib import Path
import gradio as gr
import numpy as np
import spaces
APP = Path(__file__).resolve().parent
def model_dir():
local = os.environ.get("PWM_MODEL_DIR")
if local:
return Path(local)
from huggingface_hub import snapshot_download
# real files in a plain folder, not the cache's symlinks: Gradio serves the shelf thumbnails only from inside the
# folder it was given, and a symlink's target lies elsewhere
return Path(snapshot_download(os.environ["PWM_MODEL_REPO"], token=os.environ.get("HF_TOKEN"),
local_dir=str(APP / "model"), ignore_patterns=["**/__pycache__/**", "*.pyc"]))
MODEL = model_dir()
sys.path.insert(0, str(MODEL))
import pwm_infer # noqa: E402
pwm_infer.install()
from demo import config, golden # noqa: E402
from demo.encode import frames_text # noqa: E402
from demo.engine import Engine # noqa: E402
from demo.shelf import Shelf # noqa: E402
from demo.world import World # noqa: E402
ENGINE = Engine(pwm_infer.WEIGHTS, device="cuda") # ZeroGPU: models go to cuda at start, the GPU comes per call
SHELF = Shelf(pwm_infer.SHELF)
THUMBS = (pwm_infer.SHELF / "thumbs").resolve()
gr.set_static_paths(paths=[str(THUMBS)])
MAX_ACTIONS = 25
def gpu_seconds(state, windows):
"""The GPU time to ask for: generous for the objects on the table (a window takes about 0.1-0.6 s on a full card)."""
n = len(state["objects"]) + sum(1 for _, a in state["due"] if a["kind"] == "drop")
return int(min(60, 15 + windows * (1 + 0.2 * n)))
@spaces.GPU(duration=gpu_seconds)
def advance(state, windows):
"""Predict up to `windows` windows of a table (its plain state) on the GPU: (frames [L, N, 3] or None, first frame,
the new state, timings)."""
import torch
world = World.from_state(ENGINE, SHELF, state)
outs = []
for _ in range(windows):
out = world.step()
if out is None:
break
outs.append(out)
info = dict(gpu=torch.cuda.get_device_name() if torch.cuda.is_available() else "cpu",
models=[o["model"] for o in outs], ms=[round(o["ms"], 1) for o in outs])
frames = np.concatenate([o["frames"] for o in outs]) if outs else None
return frames, (outs[0]["first"] if outs else None), world.export_state(), info
@spaces.GPU(duration=60)
def check_model():
"""The golden scenes on this GPU against the training cluster's frames (demo/golden.py)."""
import torch
frames = golden.run_scenes(ENGINE, golden.load_scenes(MODEL / "golden" / "scenes.npz"))
rows = golden.compare(frames, MODEL / "golden" / "original.npz")
return dict(gpu=torch.cuda.get_device_name() if torch.cuda.is_available() else "cpu", torch=torch.__version__,
cuda=str(torch.version.cuda), scenes=rows)
def apply_action(world, a):
"""One visitor action onto the table (applied at the next window boundary): None or why it was refused."""
kind = a.get("type")
if kind == "drop":
mat = a.get("material")
_, err = world.drop(str(a["id"]), float(a["x"]), float(a["y"]), float(a.get("height", 0.25)),
None if mat is None else int(mat), None if a.get("E") is None else float(a["E"]))
return err
if kind == "rain":
return None if world.rain(int(a.get("count", 5))) else "the table is full"
if kind == "pull":
return world.pull(int(a["uid"]), (float(a["dx"]), float(a["dy"])))
if kind == "lift":
return world.pull(int(a["uid"]), None, lift=True, height=float(a.get("height", 0.12)))
if kind == "material":
return world.material(int(a["uid"]), int(a["material"]), float(a["E"]))
return f"unknown action {kind!r}"
def reply(world, req, frames=None, first=None, info=None, notes=()):
"""What the page needs: the objects (uid, shelf id, particle range, material), the run's frames (from `first`), the
table's last frame (so a page that missed something can show it), whether anything still moves, notes."""
objects = [dict(uid=o["uid"], shelf_id=o["shelf_id"], label=o["label"].replace("_", " "), start=o["start"], n=o["n"],
material=int(o["mat_type"]), E=float(o["E"])) for o in world.objects]
out = dict(req=req, version=world.version, objects=objects, frame=world.frame, still=world.still(),
notes=list(notes), last=frames_text(world.frames[-1:], world.frame) if world.objects else None)
if frames is not None:
out.update(first=int(first), count=int(len(frames)), frames=frames_text(frames, first))
if info:
out.update(info)
return json.dumps(out)
def on_viewer(state, evt: gr.EventData):
"""The page's request: {op: run | reset, actions: [...], req}. Returns (reply JSON, the new state)."""
data = getattr(evt, "_data", None) or {}
req = data.get("req")
world = World.from_state(ENGINE, SHELF, state) if state else World(ENGINE, SHELF, seed=secrets.randbits(31))
if data.get("op") == "reset":
world.reset()
return reply(world, req, notes=["The table is clear."]), world.export_state()
if data.get("op") == "check": # the maintainer's self-check (the page shows it with ?check=1)
try:
c = check_model()
except Exception as e:
return reply(world, req, notes=[f"The self-check could not run: {e}"]), state
rows = list(c["scenes"].values())
same = all(r["identical"] for r in rows)
means = ", ".join("%.2f" % r["mean_mm"] for r in rows)
worst = max(r["max_mm"] for r in rows)
where = "Self-check on %s (torch %s, CUDA %s): the 4 golden scenes are " % (c["gpu"], c["torch"], c["cuda"])
note = where + ("bit-identical to the training cluster's frames." if same else
"not bit-identical; mean differences %s mm, largest %.1f mm (floating-point rounding; a different "
"seed moves frames 10-25 mm)." % (means, worst))
print(note, c, flush=True)
return reply(world, req, notes=[note]), state
notes = []
for a in (data.get("actions") or [])[:MAX_ACTIONS]:
try:
err = apply_action(world, a)
except (KeyError, TypeError, ValueError) as e:
err = f"a malformed action ({type(e).__name__})"
if err:
notes.append(err)
if world.still():
return reply(world, req, notes=notes or ["Nothing to predict: drop or pull something first."]), world.export_state()
t = time.perf_counter()
try:
frames, first, new_state, info = advance(world.export_state(), config.RUN_WINDOWS)
except Exception as e: # e.g. the visitor's daily GPU time is used up
return reply(world, req, notes=notes + [gpu_note(e)]), state
info["call_s"] = round(time.perf_counter() - t, 2)
world = World.from_state(ENGINE, SHELF, new_state)
return reply(world, req, frames, first, info, notes), new_state
def gpu_note(e):
"""What to tell the visitor when the model call fails; ZeroGPU's limits in plain words (spaces 0.51: a visitor
without a login gets a few runs a day, "runs limit"; a logged-in one a daily quota with "Try again in h:mm:ss")."""
text = str(e)
low = text.lower()
if "runs limit" in low or "reached its gpu limit" in low:
return ("The free GPU runs for visitors without a login are used up for today. Log in to Hugging Face to keep "
"going: free accounts get 5 GPU minutes a day.")
if "quota" in low:
wait = re.search(r"try again in ([0-9:]+)", low)
return "Your Hugging Face GPU time for today is used up." + (f" It comes back in {wait.group(1)}." if wait else "")
return f"The model could not run: {text}"
def shelf_menu(args=None):
return SHELF.menu(lambda path: f"/gradio_api/file={path}")
def object_drawing(args):
shelf_id = args[0] if isinstance(args, (list, tuple)) else args
if SHELF.entry(shelf_id) is None:
raise gr.Error("unknown object")
return SHELF.drawing(shelf_id)
def read(name):
return (APP / "web" / name).read_text()
FONTS = ('')
# one light look in both of Gradio's themes (the 3D view is drawn light); the page around the component matches it
PAGE_CSS = """
:root, .dark { --body-background-fill: #f4f5f2; --background-fill-primary: #f4f5f2; --body-text-color: #1d2124;
--body-text-color-subdued: #5d6670; --border-color-primary: rgba(29, 33, 36, 0.1); color-scheme: light; }
body, gradio-app, .gradio-container { background: #f4f5f2 !important; }
.gradio-container { width: 100% !important; max-width: 1480px !important; margin: 0 auto !important; }
"""
with gr.Blocks(title="GPWM Simulation", fill_width=True) as demo:
state = gr.State(None)
viewer = gr.HTML(html_template=read("viewer.html"), css_template=read("viewer.css"), js_on_load=read("viewer.js"),
server_functions=[shelf_menu, object_drawing], apply_default_css=False, container=False,
elem_id="drop-anything")
answer = gr.Textbox(visible=False)
viewer.click(on_viewer, inputs=[state], outputs=[answer, state], show_progress="hidden").then(
None, inputs=[answer], outputs=None,
js="(text) => { if (window.dropAnything) window.dropAnything.receive(text); return []; }")
if __name__ == "__main__":
demo.queue(default_concurrency_limit=4).launch(server_name=os.environ.get("HOST", "0.0.0.0"),
server_port=int(os.environ.get("PORT", 7860)), footer_links=[],
css=PAGE_CSS, head=FONTS) # Gradio 6: page css and head go to launch()