Spaces:
Sleeping
Sleeping
use gradio workflow
#1
by akhaliq HF Staff - opened
Files changed (4)
- .gitignoreAdded+3
- README.md+5-2
- app.py+20-8
- workflow_app.pyAdded+248
123__pycache__/*.pycworkflow.json3 unmodified lines456789101112133 unmodified linescolorFrom: indigocolorTo: purplesdk: gradiosdk_version: 5.50.0python_version: "3.10"app_file: app.pyhf_oauth: truepinned: falsemodels:- Viggle/Viggle-Animate3 unmodified lines456789101112131415163 unmodified linescolorFrom: indigocolorTo: purplesdk: gradiosdk_version: 6.27.0python_version: "3.10"app_file: workflow_app.pyhf_oauth: truehf_oauth_scopes:- inference-api- write-repospinned: falsemodels:- Viggle/Viggle-Animate
554 unmodified lines555556557558559560561562563564565566567568569570536 unmodified lines11071108110911101111554 unmodified linesreturn (ref, cond, keep, frames, apath, ref, None,f"canvas {w}x{h}{note}, {keep:.1f}s out{', audio pinned' if apath else ''}")# The counter is taken here, not at the top: it exists for the OpenAI spend below, so the# painted path is uncounted and a rejected upload never costs one of the day's five.left = gate(request)# `OpenAI()` picks up OPENAI_API_KEY *and* OPENAI_BASE_URL from the environment, so which# provider serves the repaint is a Space-secret decision, not a code one. The two have to# agree: a relay key against the default endpoint is a 401 on every request.if not os.environ.get("OPENAI_API_KEY"):raise gr.Error("OPENAI_API_KEY is not set on this Space")frame0 = str(work / "frame0.png")run("ffmpeg", "-y", "-loglevel", "error", "-i", cond, "-frames:v", "1", frame0)# gpt-image-2 accepts exactly three sizes -- anything else is a 400 whose generic message# happens to contain "size", which made every failure here look like an aspect problem536 unmodified lines# `max_file_size` matters more than it looks: gradio writes the upload to disk before# `prepare` can refuse it, and that disk also holds 80 GB of weights. The default is# None, i.e. unlimited. 10 s of 4K is comfortably under 200 MB.demo.queue(max_size=32).launch(show_error=True, allowed_paths=[str(EX)],max_file_size="200mb")554 unmodified lines555556557558559560561562563564565566567568569570571572573574575576577578579536 unmodified lines11161117111811191120112111221123554 unmodified linesreturn (ref, cond, keep, frames, apath, ref, None,f"canvas {w}x{h}{note}, {keep:.1f}s out{', audio pinned' if apath else ''}")frame0 = str(work / "frame0.png")run("ffmpeg", "-y", "-loglevel", "error", "-i", cond, "-frames:v", "1", frame0)# `OpenAI()` picks up OPENAI_API_KEY *and* OPENAI_BASE_URL from the environment, so which# provider serves the repaint is a Space-secret decision, not a code one. The two have to# agree: a relay key against the default endpoint is a 401 on every request.# Without a key there is no repaint to pay for, so instead of refusing, fall back to the# clip's own frame 0 as the reference: the render then re-animates the original performer.# Useless for the swap, but it exercises the whole render path on a test deployment.if not os.environ.get("OPENAI_API_KEY"):fit(Image.open(frame0).convert("RGB"), w, h).save(ref)return (ref, cond, keep, frames, apath, ref, None,f"OPENAI_API_KEY not set -- frame 0 used UNPAINTED as the reference, "f"canvas {w}x{h}{note}, {keep:.1f}s out{', audio pinned' if apath else ''}")# The counter is taken here, not at the top: it exists for the OpenAI spend below, so the# painted and keyless paths are uncounted and a rejected upload never costs one of the# day's five.left = gate(request)# gpt-image-2 accepts exactly three sizes -- anything else is a 400 whose generic message# happens to contain "size", which made every failure here look like an aspect problem536 unmodified lines# `max_file_size` matters more than it looks: gradio writes the upload to disk before# `prepare` can refuse it, and that disk also holds 80 GB of weights. The default is# None, i.e. unlimited. 10 s of 4K is comfortably under 200 MB.# Guarded so workflow_app.py can import this module (for prepare/render/finish and the# boot-time weight load) without starting a second server.if __name__ == "__main__":demo.queue(max_size=32).launch(show_error=True, allowed_paths=[str(EX)],max_file_size="200mb")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248# SPDX-License-Identifier: Apache-2.0"""Viggle-Animate as a gr.Workflow: the same prepare -> render -> finish pipeline as app.py,exposed as bound function nodes on the node-based canvas, at feature parity with the Blocksapp where the canvas allows it:
- the pipeline itself is literally the same code (app.py is imported, not reimplemented); ZeroGPU xlarge admission/billing, the audio pin, the daily repaint gate, the cuDNN retry and AOTI wiring all live in va.render/va.prepare and are untouched. - each node also returns its log line on a `text` port, wired to a subject, so the "repainted in 42s, canvas 480x832, 3 repaints left" feedback of the Blocks app survives. - the reference nodes are preloaded with the bundled `prop` example (drive clip + painted frame), so the canvas opens ready to run: deterministic at seed 42, no OpenAI call -- the workflow counterpart of the Blocks app's examples row. The graph is GENERATED at boot (only when workflow.json is absent) so those preloads carry this machine's absolute paths; a shipped file would bake in the author's. - the AOTI maintenance build is the fourth node. app.py gates it on gr.OAuthProfile, which workflow fn nodes never inject; gradio.workflow.has_write_access(request, token) is the same check (Space owner / org write member), so the node gates on that instead.
What the canvas cannot replicate: the 14-click examples grid and the "What it produces"gallery (no examples mechanism), and the gradio-5 preprocess monkeypatch (inert on 6.x;prepare's own path-exists backstop still covers stale uploads).
Run with `python workflow_app.py` (requires gradio>=6.26). Importing app.py performs thesame boot-time weight load the Blocks app does; the launch there is guarded by __main__, sonothing is double-served.
The canvas's write-access link is printed at launch; keep it private. workflow.json next tothis file holds the graph and is autosaved on edits through that link."""
import ioimport jsonfrom pathlib import Path
import gradio as grfrom gradio.oauth import OAuthTokenfrom gradio.workflow import has_write_accessfrom gradio_client.utils import encode_file_pathfrom huggingface_hub import HfApi
import app as va
GRAPH = Path(__file__).parent / "workflow.json"
def _job(v): """A `json` port leaves prepare as a dict but can arrive at the next node as its JSON string (the canvas serializes values between nodes). Accept both.""" return json.loads(v) if isinstance(v, str) else v
def _path(v): """Media ports arrive as {"path": ...}/{"url": ...} dicts on the canvas and as bare filepaths through the API executor; accept all three. A canvas file value often carries NO path at all -- only a percent-encoded /gradio_api/file= URL (gradio's own _file_ref documents this) -- so the prefix is stripped and unquoted back to a local path.""" if isinstance(v, dict): v = v.get("path") or v.get("url") if isinstance(v, str) and v.startswith("/gradio_api/file="): from urllib.parse import unquote v = unquote(v.removeprefix("/gradio_api/file=")) return v
def _media(p): """Return media as the {path, url, is_file} shape the canvas needs to actually display it (mirrors workflow._save_tmp). A bare /tmp path has no URL the browser can load, so subjects fed one sit at 'Waiting for output...' forever. Workflow.launch adds the tempdir to allowed_paths, which is what makes the /gradio_api/file= URL resolve. The URL is percent-encoded like gradio 6.27's own _save_tmp/call_space do.""" return ({"path": p, "url": f"/gradio_api/file={encode_file_path(p)}", "is_file": True} if p else None)
def prepare(video, character=None, painted=None, seed: float = 42): """CPU stage: retime/crop the driving clip onto the ladder canvas, repaint frame 0 with gpt-image-2 (unless a pre-painted frame is supplied -- or no API key is set, in which case frame 0 is used unpainted), extract the soundtrack for the pin. `request` is injected by the workflow's call_fn and used only for the daily repaint gate. Returns the repainted reference frame, the opaque job payload the GPU stage needs, and the Blocks app's log line.""" ref, cond, keep, frames, apath, _shown, _out, msg = va.prepare( _path(video), _path(character), _path(painted)) job = {"ref": ref, "cond": cond, "keep": keep, "frames": frames, "apath": apath, "seed": int(seed if seed is not None else 42)} return _media(ref), job, msg
def render(job: dict): """GPU stage: 4-step ref2va render on ZeroGPU xlarge (va.render carries the @spaces.GPU decorator and its admission budget). Returns the untrimmed render, the job payload finish still needs, and the Blocks app's log line.""" job = _job(job) (raw, _keep, _apath), msg = va.render(job["ref"], job["cond"], job["keep"], job["frames"], job["apath"], job["seed"]) return _media(raw), job, msg
def finish(raw, job: dict): """CPU stage: trim the frozen 17k+5 tail, watermark, remux the original soundtrack.""" job = _job(job) out = va.finish((_path(raw), job["keep"], job["apath"])) return _media(out), f"trimmed to {job['keep']:.1f}s, watermarked, remuxed"
def build_aoti(request: gr.Request = None, token: OAuthToken = None): """Owner-only maintenance node: compile the transformer's repeated block classes on this GPU and upload the packages to the weights repo. app.py's button gates on gr.OAuthProfile.username in OWNERS; the workflow injects Request/OAuthToken instead, and gradio's own has_write_access is the equivalent check (Space owner or org write/admin). """ if not has_write_access(request, token): raise gr.Error("owner-only maintenance node -- open the write-access link, or sign " "in as the Space owner") packages, log = va.build_aoti() for name, blob in packages.items(): # HF_TOKEN comes from the Space secrets via the environment; HfApi picks it up itself. HfApi().upload_file(path_or_fileobj=io.BytesIO(blob), path_in_repo=f"{name}/{va.PACKAGE_FILENAME}", repo_id=va.AOTI_REPO, repo_type="model") return log + "\nuploaded -- restart the Space to pick the packages up"
def _media_ref(name): """Preload value for a media reference node: a bundled example file, so the canvas opens with a ready-to-run pipeline. Absolute paths make this generation-time only.""" p = str(va.EX / name) return {"path": p, "url": f"/gradio_api/file={encode_file_path(p)}", "is_file": True}
def _port(pid, label, ptype, **kw): return {"id": pid, "label": label, "type": ptype, **kw}
def _default_graph(): return { "schema_version": "2", "name": "Viggle-Animate", "references": [ {"id": "ref_video", "label": "Driving Video", "role": "reference", "asset_type": "video", "inputs": [_port("in", "Video", "video")], "outputs": [_port("out", "Video", "video")], # prop: deterministic at seed 42 and needs no OpenAI call (frame pre-painted). "data": {"out": _media_ref("prop_drive.mp4")}}, {"id": "ref_character", "label": "Character Image (optional)", "role": "reference", "asset_type": "image", "inputs": [_port("in", "Image", "image")], "outputs": [_port("out", "Image", "image")]}, {"id": "ref_painted", "label": "Pre-painted Frame 0 (optional)", "role": "reference", "asset_type": "image", "inputs": [_port("in", "Image", "image")], "outputs": [_port("out", "Image", "image")], "data": {"out": _media_ref("prop_ref.png")}}, {"id": "ref_seed", "label": "Seed", "role": "reference", "asset_type": "number", "inputs": [_port("in", "Seed", "number")], "outputs": [_port("out", "Seed", "number")], "data": {"out": 42}}, ], "operators": [ {"id": "op_prepare", "label": "Prepare — retime, repaint frame 0", "role": "operator", "kind": "fn", "fn": "prepare", "inputs": [_port("video", "video", "video", required=True), _port("character", "character", "image"), _port("painted", "painted", "image"), _port("seed", "seed", "number")], "outputs": [_port("ref", "Repainted frame", "image", output_index=0), _port("job", "job", "json", output_index=1), _port("log", "log", "text", output_index=2)]}, {"id": "op_render", "label": "Render — 4 steps on ZeroGPU xlarge", "role": "operator", "kind": "fn", "fn": "render", "inputs": [_port("job", "job", "json", required=True)], "outputs": [_port("raw", "Raw video", "video", output_index=0), _port("job", "job", "json", output_index=1), _port("log", "log", "text", output_index=2)]}, {"id": "op_finish", "label": "Finish — trim, watermark, remux audio", "role": "operator", "kind": "fn", "fn": "finish", "inputs": [_port("raw", "raw", "video", required=True), _port("job", "job", "json", required=True)], "outputs": [_port("out_0", "Video", "video", output_index=0), _port("log", "log", "text", output_index=1)]}, # build_aoti is deliberately NOT in the default graph: a zero-input operator # feeding a subject is a complete runnable pipeline, so every Run -- every # visitor's -- would fire the GPU maintenance build and hit the owner gate. # It stays in bind=, and the owner adds it from the canvas's Functions menu # on the rare occasion it is needed. ], "subjects": [ {"id": "sub_frame", "label": "Repainted Frame", "role": "subject", "asset_type": "image", "inputs": [_port("in", "Image", "image")], "outputs": [_port("out", "Image", "image")]}, {"id": "sub_video", "label": "Output Video", "role": "subject", "asset_type": "video", "inputs": [_port("in", "Video", "video")], "outputs": [_port("out", "Video", "video")]}, {"id": "sub_plog", "label": "Prepare Log", "role": "subject", "asset_type": "text", "inputs": [_port("in", "Text", "text")], "outputs": [_port("out", "Text", "text")]}, {"id": "sub_rlog", "label": "Render Log", "role": "subject", "asset_type": "text", "inputs": [_port("in", "Text", "text")], "outputs": [_port("out", "Text", "text")]}, {"id": "sub_flog", "label": "Finish Log", "role": "subject", "asset_type": "text", "inputs": [_port("in", "Text", "text")], "outputs": [_port("out", "Text", "text")]}, ], "edges": [ {"id": "e1", "from_node_id": "ref_video", "from_port_id": "out", "to_node_id": "op_prepare", "to_port_id": "video", "type": "video"}, {"id": "e2", "from_node_id": "ref_character", "from_port_id": "out", "to_node_id": "op_prepare", "to_port_id": "character", "type": "image"}, {"id": "e3", "from_node_id": "ref_painted", "from_port_id": "out", "to_node_id": "op_prepare", "to_port_id": "painted", "type": "image"}, {"id": "e4", "from_node_id": "ref_seed", "from_port_id": "out", "to_node_id": "op_prepare", "to_port_id": "seed", "type": "number"}, {"id": "e5", "from_node_id": "op_prepare", "from_port_id": "ref", "to_node_id": "sub_frame", "to_port_id": "in", "type": "image"}, {"id": "e6", "from_node_id": "op_prepare", "from_port_id": "job", "to_node_id": "op_render", "to_port_id": "job", "type": "json"}, {"id": "e7", "from_node_id": "op_render", "from_port_id": "raw", "to_node_id": "op_finish", "to_port_id": "raw", "type": "video"}, {"id": "e8", "from_node_id": "op_render", "from_port_id": "job", "to_node_id": "op_finish", "to_port_id": "job", "type": "json"}, {"id": "e9", "from_node_id": "op_finish", "from_port_id": "out_0", "to_node_id": "sub_video", "to_port_id": "in", "type": "video"}, {"id": "e10", "from_node_id": "op_prepare", "from_port_id": "log", "to_node_id": "sub_plog", "to_port_id": "in", "type": "text"}, {"id": "e11", "from_node_id": "op_render", "from_port_id": "log", "to_node_id": "sub_rlog", "to_port_id": "in", "type": "text"}, {"id": "e12", "from_node_id": "op_finish", "from_port_id": "log", "to_node_id": "sub_flog", "to_port_id": "in", "type": "text"}, ], }
if not GRAPH.exists(): GRAPH.write_text(json.dumps(_default_graph(), indent=2))
gr.Workflow( graph=str(GRAPH), bind={"prepare": prepare, "render": render, "finish": finish, "build_aoti": build_aoti},).launch(show_error=True, max_file_size="200mb", allowed_paths=[str(va.EX)]).gitignoreAdded+3
README.md+5-2
app.py+20-8
workflow_app.pyAdded+248