Give every page the same three tabs and open the workflow canvas as its own page
Browse filesClassic UI, Studio and Workflow each show the same tabs. The workflow canvas is its own page (canvas view only: the App toggle is hidden and a URL without ?ui= opens the canvas), so gradio attaches the visitor's ZeroGPU token to its requests like on the other pages. This drops the per-IP token relay that the studio kept for the iframe-embedded canvas, which could bill one visitor's runs to another behind the same IP.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Files changed (2)
- app.py+44-144
- studio.html+5-37
1234567891011272 unmodified lines28428528628728828929099 unmodified lines3903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145158 unmodified lines5245255265275285295305315325335345355361 unmodified line5385395405415425435442 unmodified lines54754854955055155255320 unmodified lines5745755765775785795805815825835845855865875885895905915925935945955965975985996001 unmodified line602603604605606607608import base64import hashlibimport jsonimport mathimport osimport randomimport tempfileimport threadingimport timefrom types import SimpleNamespacefrom urllib.parse import unquote, urlparse272 unmodified lines'text-decoration:none!important;color:var(--body-text-color)!important}''.pih3-tabs a.active{background:var(--body-text-color);color:var(--background-fill-primary)!important}</style>''<div class="pih3-head prose"><h1>pi-H3 Demo 1.0</h1><div class="pih3-tabs"><a class="active">Classic UI</a>''<a href="/studio" onclick="this.href=\'/studio\'+location.search">Studio</a></div></div>')def build_interface(generate):99 unmodified linesraise gr.Error(message)# ---- ZeroGPU quota on the workflow canvas -----------------------------------# The canvas is nested inside the studio iframe, so gradio's postMessage handshake with# huggingface.co — which would attach the visitor's x-ip-token to the canvas's requests —# never completes, and its @spaces.GPU calls bill the Space's anonymous allowance. The# studio page's own @gradio/client calls do carry the header, so every studio API call# stashes it per client IP, and workflow runs from the same IP re-attach it here.# Pattern from akhaliq/idol-studio._TOKEN_TTL = 1800 # seconds_tokens: dict[str, tuple[str, float]] = {}_tokens_lock = threading.Lock()def _token_claims(token: str) -> dict:"""The unverified JWT payload, to tell user-attributed tokens from anonymous ones."""try:payload = token.split('.')[1]return json.loads(base64.urlsafe_b64decode(payload + '=' * (-len(payload) % 4)))except Exception: # noqa: BLE001 - not a JWTreturn {}def _client_ip(request) -> str:forwarded = (request.headers.get('x-forwarded-for') or '').split(',')[0].strip()return forwarded or (request.client.host if request.client else '')def _is_user_token(token: str) -> bool:return bool(_token_claims(token).get('user'))def _is_fresh_user_token(token: str) -> bool:"""User-attributed and not expiring in the next few seconds (proxy tokens live ~2-4 min)."""claims = _token_claims(token)return bool(claims.get('user')) and claims.get('exp', 0) > time.time() + 5def _remember_token(request) -> None:if request is None:returntoken = request.headers.get('x-ip-token')if not token:returnip = _client_ip(request)with _tokens_lock:now = time.time()for stale in [stale for stale, (_, at) in _tokens.items() if now - at > _TOKEN_TTL]:del _tokens[stale]existing = _tokens.get(ip)# never downgrade: an anonymous edge token must not replace a usable user-attributed oneif existing and _is_fresh_user_token(existing[0]) and not _is_user_token(token):return_tokens[ip] = (token, now)def _fake_starlette_request(token_or_headers) -> StarletteRequest:"""A real starlette request carrying just an x-ip-token (or a full header dict), so thegradio Request built on top of it behaves like one served over HTTP."""if isinstance(token_or_headers, str):headers = {'x-ip-token': token_or_headers}else:headers = token_or_headersscope = {'type': 'http','method': 'GET','path': '/','scheme': 'https','query_string': b'','headers': [(k.lower().encode('ascii'), str(v).encode('latin-1'))for k, v in headers.items() if v is not None],}return StarletteRequest(scope)def _as_gradio_request(request):"""A gradio Request with a live underlying starlette request — the shape spaces' ZeroGPUhook expects in LocalContext (it reads `request.request`). The workflow runtime and someServer-mode paths inject a raw starlette Request, and queue-created gradio Requests carryno live one; both are wrapped so ZeroGPU can read the visitor's x-ip-token."""if request is None:return Noneif isinstance(request, gr.Request):if request.request is not None:return requestreturn gr.Request(request=_fake_starlette_request(dict(getattr(request, 'headers', {}) or {})))if isinstance(request, StarletteRequest):return gr.Request(request=request)return gr.Request(request=_fake_starlette_request(str(request)))def _zerogpu_request(request):"""The gradio Request to bind to LocalContext for the GPU call, or None to run anonymously.The studio's handshaken token (stored per IP) wins over the injected request's own header:that one may be an anonymous edge-minted token, which bills the Space's anonymous allowance."""direct = request.headers.get('x-ip-token') if request is not None else Noneip = _client_ip(request) if request is not None else ''with _tokens_lock:hit = _tokens.get(ip)stored = hit[0] if hit and time.time() - hit[1] <= _TOKEN_TTL else Noneif stored and _is_user_token(stored) and not _is_fresh_user_token(stored):stored = None # expired: the scheduler would reject it anywayif stored and (_is_user_token(stored) or not direct):return _as_gradio_request(stored)if direct:return _as_gradio_request(request)return Nonedef _on_visitor_quota(request, fn, *args):"""Run one GPU call on the visitor's quota when their token is known, else anonymously."""zerogpu_request = _zerogpu_request(request)if zerogpu_request is None:return _run(fn, *args)reset = LocalContext.request.set(zerogpu_request)try:return _run(fn, *args)finally:LocalContext.request.reset(reset)def _parse_bool(value) -> bool:"""The canvas passes DWD as a text reference; accept any spelling."""return value if isinstance(value, bool) else str(value).strip().lower() in ('true', '1', 'yes', 'on')8 unmodified linesdef build_app(generate):"""The Space's ASGI app: the Blocks demo, the studio and the workflow canvas over one generate()."""def generate_studio(request, seed, prompt, in_image, in_last_image, aspect_ratio, megapixels, duration, steps,remove_decoder):"""One generate() call on the visitor's ZeroGPU quota -> (published mp4 path, run info note)."""start = time.perf_counter()path = _on_visitor_quota(request, generate, seed, prompt, _open_rgb(in_image), _open_rgb(in_last_image), aspect_ratio,megapixels, duration, steps, remove_decoder)height, width = canvas_size(aspect_ratio, megapixels * 1e6)note = (f"{2 if steps < 3 else 4} steps · {'DWD (no decoder)' if remove_decoder else 'VAE decoded'} · "f'{width}x{height} · {time.perf_counter() - start:.1f} s')1 unmodified linedef pi_h3_generate(prompt: str = '', in_image: str = '', in_last_image: str = '', seed: str = '42',aspect_ratio: str = '16:9', duration: str = '5.0', steps: str = '2',remove_decoder: str = 'true', request: gr.Request = None) -> dict:"""Generate one video with pi-H3 from a prompt and optional first/last keyframes.gr.Workflow passes the node's inputs positionally, so the parameters follow the order of the2 unmodified linesif not (prompt or '').strip() and not in_image:raise gr.Error('Write a prompt or add a first frame.')path, _ = generate_studio(request, min(max(int(float(seed)), 0), MAX_SEED), prompt, in_image, in_last_image, aspect_ratio, 1.0,float(duration) if duration else 5.0, int(float(steps)) if steps else 2, _parse_bool(remove_decoder))return _as_media(path)20 unmodified lines@server.api(name='generate', concurrency_limit=1)def api_generate(prompt: str = '', seed: float = 0, randomize: bool = True, in_image: str = '',in_last_image: str = '', aspect_ratio: str = '16:9', megapixels: float = 1.0,duration: float = 5.0, steps: float = 2, remove_decoder: bool = True,request: gr.Request = None) -> dict:"""Generate one video with pi-H3 (2 or 4 steps, optional VAE-free DWD decoding)."""_remember_token(request)_check_choice(aspect_ratio, ASPECT_RATIOS, 'Aspect ratio')if not (prompt or '').strip() and not in_image:raise gr.Error('Write a prompt or add a first frame.')seed_value = _resolve_seed(seed, randomize)path, note = generate_studio(request, seed_value, prompt, in_image, in_last_image, aspect_ratio, megapixels, duration, steps,remove_decoder)return {'video_url': _as_media(path)['url'], 'info': note, 'seed': seed_value}@server.api(name='handshake')def api_handshake(request: gr.Request = None) -> dict:"""No-op the studio page calls on load and every minute; @gradio/client only attachesthe visitor's ZeroGPU user token to queued calls, which _remember_token then stashesfor the workflow canvas's runs (whose iframe never completes the handshake)."""_remember_token(request)return {'ok': True}workflow = gr.Workflow(graph=os.path.join(ROOT, 'workflow.json'), bind={'pi_h3_generate': pi_h3_generate})workflow.title = 'pi-H3 Workflow'return SimpleNamespace(server=server, mounts={1 unmodified lineallowed_paths=[os.path.join(ROOT, 'demo/examples/minimax_h3')],css_paths=os.path.join(ROOT, 'lakonlab/ui/gradio/style.css'),head_paths=os.path.join(ROOT, 'lakonlab/ui/gradio/head.html'))),'/workflow': (workflow, {})})def launch_demo(app, port=None):123456789272 unmodified lines28228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932099 unmodified lines4204214224234244258 unmodified lines4344354364374384394404414424434444454464471 unmodified line4494504514524534544552 unmodified lines45845946046146246346420 unmodified lines4854864874884894904914924934944954964974984995001 unmodified line502503504505506507508import hashlibimport jsonimport mathimport osimport randomimport tempfileimport timefrom types import SimpleNamespacefrom urllib.parse import unquote, urlparse272 unmodified lines'text-decoration:none!important;color:var(--body-text-color)!important}''.pih3-tabs a.active{background:var(--body-text-color);color:var(--background-fill-primary)!important}</style>''<div class="pih3-head prose"><h1>pi-H3 Demo 1.0</h1><div class="pih3-tabs"><a class="active">Classic UI</a>''<a href="/studio" onclick="this.href=\'/studio\'+location.search">Studio</a>''<a href="/workflow/?ui=canvas" onclick="this.href=\'/workflow/?ui=canvas\'+location.search.replace(\'?\',\'&\')">''Workflow</a></div></div>')# The workflow page: the same three tabs in the canvas toolbar, and the canvas only. gr.Workflow has no option to# turn off its App view, so its toggle is hidden and a URL without ?ui= (which opens the App view) gets ui=canvas.WORKFLOW_HEAD = """<style>.view-toggle { display: none !important; }.pih3-wf-tabs { display: flex; gap: 4px; padding: 3px; margin-left: 8px; border: 1px solid var(--border-color-primary);border-radius: 9px; }.pih3-wf-tabs a { padding: 4px 12px; border-radius: 6px; font-weight: 600; font-size: 13px; text-decoration: none;color: var(--body-text-color); }.pih3-wf-tabs a.active { background: var(--body-text-color); color: var(--background-fill-primary); }</style><script>(() => {const query = new URLSearchParams(location.search);if (!query.has('ui')) {query.set('ui', 'canvas');location.replace(location.pathname + '?' + query);return;}query.delete('ui');const rest = query.toString() ? '?' + query : '';const tabs = `<div class="pih3-wf-tabs"><a href="/demo/${rest}">Classic UI</a><a href="/studio${rest}">Studio</a>`+ '<a class="active">Workflow</a></div>';// the canvas renders (and may re-render) its toolbar after load, so keep the tabs next to its titlenew MutationObserver(() => {const title = document.querySelector('.toolbar-left .name-text');if (title && !title.parentElement.querySelector('.pih3-wf-tabs')) title.insertAdjacentHTML('afterend', tabs);}).observe(document.documentElement, {childList: true, subtree: true});})();</script>"""def build_interface(generate):99 unmodified linesraise gr.Error(message)def _parse_bool(value) -> bool:"""The canvas passes DWD as a text reference; accept any spelling."""return value if isinstance(value, bool) else str(value).strip().lower() in ('true', '1', 'yes', 'on')8 unmodified linesdef build_app(generate):"""The Space's ASGI app: the Blocks demo, the studio and the workflow canvas over one generate()."""def generate_studio(seed, prompt, in_image, in_last_image, aspect_ratio, megapixels, duration, steps,remove_decoder):"""One generate() call -> (published mp4 path, run info note). ZeroGPU bills the visitor whose token camewith the calling page's request."""start = time.perf_counter()path = _run(generate, seed, prompt, _open_rgb(in_image), _open_rgb(in_last_image), aspect_ratio, megapixels,duration, steps, remove_decoder)height, width = canvas_size(aspect_ratio, megapixels * 1e6)note = (f"{2 if steps < 3 else 4} steps · {'DWD (no decoder)' if remove_decoder else 'VAE decoded'} · "f'{width}x{height} · {time.perf_counter() - start:.1f} s')1 unmodified linedef pi_h3_generate(prompt: str = '', in_image: str = '', in_last_image: str = '', seed: str = '42',aspect_ratio: str = '16:9', duration: str = '5.0', steps: str = '2',remove_decoder: str = 'true') -> dict:"""Generate one video with pi-H3 from a prompt and optional first/last keyframes.gr.Workflow passes the node's inputs positionally, so the parameters follow the order of the2 unmodified linesif not (prompt or '').strip() and not in_image:raise gr.Error('Write a prompt or add a first frame.')path, _ = generate_studio(min(max(int(float(seed)), 0), MAX_SEED), prompt, in_image, in_last_image, aspect_ratio, 1.0,float(duration) if duration else 5.0, int(float(steps)) if steps else 2, _parse_bool(remove_decoder))return _as_media(path)20 unmodified lines@server.api(name='generate', concurrency_limit=1)def api_generate(prompt: str = '', seed: float = 0, randomize: bool = True, in_image: str = '',in_last_image: str = '', aspect_ratio: str = '16:9', megapixels: float = 1.0,duration: float = 5.0, steps: float = 2, remove_decoder: bool = True) -> dict:"""Generate one video with pi-H3 (2 or 4 steps, optional VAE-free DWD decoding)."""_check_choice(aspect_ratio, ASPECT_RATIOS, 'Aspect ratio')if not (prompt or '').strip() and not in_image:raise gr.Error('Write a prompt or add a first frame.')seed_value = _resolve_seed(seed, randomize)path, note = generate_studio(seed_value, prompt, in_image, in_last_image, aspect_ratio, megapixels, duration, steps, remove_decoder)return {'video_url': _as_media(path)['url'], 'info': note, 'seed': seed_value}workflow = gr.Workflow(graph=os.path.join(ROOT, 'workflow.json'), bind={'pi_h3_generate': pi_h3_generate})workflow.title = 'pi-H3 Workflow'return SimpleNamespace(server=server, mounts={1 unmodified lineallowed_paths=[os.path.join(ROOT, 'demo/examples/minimax_h3')],css_paths=os.path.join(ROOT, 'lakonlab/ui/gradio/style.css'),head_paths=os.path.join(ROOT, 'lakonlab/ui/gradio/head.html'))),'/workflow': (workflow, dict(head=WORKFLOW_HEAD))})def launch_demo(app, port=None):
87 unmodified lines8889909192939495149 unmodified lines24524624724824925025111 unmodified lines26326426526626726826927027119 unmodified lines29129229329429529629729829987 unmodified lines38738838939039139239364 unmodified lines45845946046146246346446546646746846947047147247347447547647747847967 unmodified lines54754854955055155255337 unmodified lines59159259359459559659718 unmodified lines61661761861962062162262362462562662762862980 unmodified lines71071171271371471571687 unmodified lines}.rail button:hover { background: var(--panel2); color: var(--text); }.viewport { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow: auto; position: relative; }.workflow-view { position: absolute; inset: 0; padding: 16px; background: var(--bg); }.workflow-view iframe { width: 100%; height: 100%; border: 1px solid var(--border); border-radius: 12px; background: var(--panel); }.doc-grid { flex: 1; min-height: 0; display: flex; gap: 16px; width: 100%; align-items: stretch; justify-content: center; padding: 20px 20px 10px; }.doc {flex: 1; min-width: 0; display: flex; flex-direction: column;149 unmodified lines}.rail button { width: 44px; height: 44px; }.viewport { display: block; padding: 10px; overflow: visible; }.workflow-view { position: static; height: 78vh; padding: 0 0 10px; }.doc-grid { flex-direction: column; align-items: stretch; height: auto; }.doc { max-width: 100%; width: 100%; }.doc .stage { min-height: 220px; }11 unmodified lines<header class="topbar"><div class="brand"><span class="pi">pi</span><span class="dash">-</span><span class="h3">H3</span><span class="studio-badge">Video Studio</span></div><div class="mode-tabs"><button onclick="location.href='/demo/' + location.search">Classic UI</button><button id="mode-generate" class="active">Generate</button><button id="mode-workflow">Workflow</button></div><div class="spacer"></div><a class="ml-badge-img" href="https://hf.co/chat?mode=ml-intern" target="_blank" rel="noopener">19 unmodified lines</div><div class="viewport"><div class="workflow-view" id="workflow-view" hidden><iframe src="/workflow/?ui=canvas" title="pi-H3 workflow canvas"></iframe></div><div class="doc-grid"><figure class="doc" id="doc-after"><figcaption>Output video</figcaption>87 unmodified linesimport { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js";const $ = (id) => document.getElementById(id);const state = { mode: "generate", firstPath: null, lastName: null, lastPath: null, app: null,target: "first" }; // which slot the file input / drop targets fill// The three demo examples (demo/examples/minimax_h3/examples.json), prompts included.64 unmodified linesapplyTheme(mode);})();function setMode(mode) {state.mode = mode;for (const m of ["generate", "workflow"]) $(`mode-${m}`).classList.toggle("active", mode === m);const workflow = mode === "workflow";$("workflow-view").hidden = !workflow;document.querySelector(".doc-grid").style.display = workflow ? "none" : "";document.querySelector(".rail").style.display = workflow ? "none" : "";document.querySelector(".panels").style.display = workflow ? "none" : "";$("history-strip").style.display = workflow ? "none" : "";setStatus(workflow? "Chain nodes into one pipeline: prompt and keyframes feed the pi-H3 generate node": "Idle");}$("mode-generate").onclick = () => setMode("generate");$("mode-workflow").onclick = () => setMode("workflow");// ---------- keyframes ----------const fileInput = $("file-input");// one keyframe slot ("first" or "last"): its uploaded path, thumbnail and clear button67 unmodified linesrenderHistory();}function restoreRun(h) {setMode("generate");$("prompt").value = h.prompt || "";$("aspect").value = h.aspect || "16:9";$("steps").value = h.steps || "2";37 unmodified lineschip.appendChild(label);chip.appendChild(tag);chip.onclick = async () => {setMode("generate");setStatus("Loading example…", true);try {$("prompt").value = ex.prompt;18 unmodified lines});}// ---------- ZeroGPU quota handshake for the workflow canvas ----------// The canvas iframe can't complete gradio's postMessage handshake with huggingface.co, so its// GPU calls would bill the Space's anonymous allowance. The studio page's own @gradio/client// calls carry the visitor's x-ip-token; /handshake stashes it server-side per client IP for// the canvas's runs to re-attach.getApp().then((app) => app.predict("/handshake", {})).catch(() => {});setInterval(() => { getApp().then((app) => app.predict("/handshake", {})).catch(() => {}); }, 60000);// ---------- run ----------function unwrap(result) {const data = Array.isArray(result?.data) ? result.data[0] : result?.data;80 unmodified lines$("run-info").value = "";};setMode("generate");renderExamples();</script></body>87 unmodified lines888990919293149 unmodified lines24324424524624724811 unmodified lines26026126226326426526626726819 unmodified lines28828929029129229387 unmodified lines38138238338438538638764 unmodified lines45245345445545645767 unmodified lines52552652752852953037 unmodified lines56856957057157257318 unmodified lines59259359459559659780 unmodified lines67867968068168268368487 unmodified lines}.rail button:hover { background: var(--panel2); color: var(--text); }.viewport { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow: auto; position: relative; }.doc-grid { flex: 1; min-height: 0; display: flex; gap: 16px; width: 100%; align-items: stretch; justify-content: center; padding: 20px 20px 10px; }.doc {flex: 1; min-width: 0; display: flex; flex-direction: column;149 unmodified lines}.rail button { width: 44px; height: 44px; }.viewport { display: block; padding: 10px; overflow: visible; }.doc-grid { flex-direction: column; align-items: stretch; height: auto; }.doc { max-width: 100%; width: 100%; }.doc .stage { min-height: 220px; }11 unmodified lines<header class="topbar"><div class="brand"><span class="pi">pi</span><span class="dash">-</span><span class="h3">H3</span><span class="studio-badge">Video Studio</span></div><div class="mode-tabs"><button onclick="location.href = '/demo/' + location.search">Classic UI</button><button class="active">Studio</button><button onclick="location.href = '/workflow/?ui=canvas' + location.search.replace('?', '&')">Workflow</button></div><div class="spacer"></div><a class="ml-badge-img" href="https://hf.co/chat?mode=ml-intern" target="_blank" rel="noopener">19 unmodified lines</div><div class="viewport"><div class="doc-grid"><figure class="doc" id="doc-after"><figcaption>Output video</figcaption>87 unmodified linesimport { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js";const $ = (id) => document.getElementById(id);const state = { firstPath: null, lastName: null, lastPath: null, app: null,target: "first" }; // which slot the file input / drop targets fill// The three demo examples (demo/examples/minimax_h3/examples.json), prompts included.64 unmodified linesapplyTheme(mode);})();// ---------- keyframes ----------const fileInput = $("file-input");// one keyframe slot ("first" or "last"): its uploaded path, thumbnail and clear button67 unmodified linesrenderHistory();}function restoreRun(h) {$("prompt").value = h.prompt || "";$("aspect").value = h.aspect || "16:9";$("steps").value = h.steps || "2";37 unmodified lineschip.appendChild(label);chip.appendChild(tag);chip.onclick = async () => {setStatus("Loading example…", true);try {$("prompt").value = ex.prompt;18 unmodified lines});}// ---------- run ----------function unwrap(result) {const data = Array.isArray(result?.data) ? result.data[0] : result?.data;80 unmodified lines$("run-info").value = "";};setStatus("Idle");renderExamples();</script></body>
app.py+44-144
studio.html+5-37