ysharma HF Staff commited on
Commit
e6cfeb7
·
verified ·
1 Parent(s): b8354d3

Workflow1111 — Automatic1111-style diffusion studio on gr.Workflow

Browse files
Files changed (9) hide show
  1. README.md +80 -11
  2. app.py +15 -8
  3. build_workflow.py +66 -1
  4. layout.json +36 -0
  5. nodes.py +204 -0
  6. test_api.py +9 -1
  7. test_nodes.py +92 -0
  8. test_pipelines.py +8 -0
  9. workflow.json +0 -0
README.md CHANGED
@@ -21,7 +21,7 @@ short_description: Automatic1111-style studio on one gr.Workflow canvas
21
  # 05 · Workflow1111 — a Diffusion Studio built from `gr.Workflow`
22
 
23
  An **Automatic1111-shaped image studio expressed as one canvas graph** instead
24
- of a tabbed UI: **64 nodes, 10 pipelines, 18 independently runnable outputs**,
25
  all inside a single `gr.Workflow`.
26
 
27
  ```bash
@@ -43,8 +43,8 @@ if Context.root_block is not None:
43
 
44
  So an A1111 clone genuinely *cannot* be a `gr.Tabs` layout here — the graph **is**
45
  the UI. The analogue of a tab is a **subject group**: a connected cluster of
46
- outputs, which gradio also publishes as its own REST endpoint. Ten pipelines sit
47
- side by side on one canvas, and you run whichever output you want.
48
 
49
  ---
50
 
@@ -62,6 +62,7 @@ side by side on one canvas, and you run whichever output you want.
62
  | 8 | **Extras** | Extras tab | local Lanczos upscale · AuraSR ×4 · background removal |
63
  | 9 | **Annotators** | ControlNet preprocessors | Canny · line art · sketch · luma-depth · posterize · threshold |
64
  | 10 | **PNG Info** | PNG Info tab | read generation parameters back out of a file |
 
65
 
66
  **The txt2img node has the real control surface** — negative prompt, sampling
67
  steps, CFG scale, seed (with `-1` = random), width/height with aspect presets,
@@ -74,20 +75,79 @@ parameter block into the PNG's `parameters` text chunk; the PNG Info pipeline
74
  parses it back out. Images this app makes round-trip through a real A1111
75
  install too.
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  ---
78
 
79
  ## Architecture
80
 
81
  ```
82
- 14 references → 32 operators → 18 subjects 73 edges
83
- ├─ 28 fn 19 pure-local · 9 calling InferenceClient
84
  ├─ 2 model HF Inference Providers
85
  └─ 2 space Gradio Spaces on the Hub
86
  ```
87
 
88
- 19 of the 28 `fn` nodes are pure local Pillow/numpy — all the prompt logic,
89
  post-processing, annotators, masking, grid composition and metadata parsing —
90
- so most of the app keeps working with no token, no quota and no network. 13
91
  nodes in total leave the machine.
92
 
93
  ### Files
@@ -95,11 +155,11 @@ nodes in total leave the machine.
95
  | File | What it is |
96
  |---|---|
97
  | `app.py` | Entry point — 12 lines of actual wiring |
98
- | `nodes.py` | The 21 bound functions (the `fn` node library) |
99
  | `build_workflow.py` | **Generates + verifies** `workflow.json` |
100
  | `workflow.json` | The committed graph |
101
- | `test_nodes.py` | 53 offline unit tests (~2s) |
102
- | `test_pipelines.py` | Runs all 18 outputs through the real `WorkflowExecutor` |
103
  | `test_api.py` | Drives the 9 generated REST endpoints against a running app |
104
  | `make_samples.py` | Regenerates the shipped sample images |
105
  | `deploy_space.py` | Stages + uploads the Space |
@@ -204,6 +264,15 @@ So `_emit` returns **both**: `{"path": <temp file>, "url": <data: URI>}`.
204
  `_from_output` takes `path` first (endpoint happy), the frontend and `_img_url`
205
  take `url` first (canvas and providers happy).
206
 
 
 
 
 
 
 
 
 
 
207
  ### 6. A `json` port silently destroys its value in the canvas
208
 
209
  The canvas serializes a `json`-typed port with JavaScript's `String(obj)`
@@ -239,7 +308,7 @@ Space must stay public.
239
 
240
  ```bash
241
  python apps/05_workflow1111/test_nodes.py # 53 unit tests, offline, ~2s
242
- python apps/05_workflow1111/test_pipelines.py # all 18 outputs, hits HF
243
  python apps/05_workflow1111/test_pipelines.py local # only the offline outputs
244
  python apps/05_workflow1111/test_api.py # the 9 REST endpoints
245
  python apps/05_workflow1111/test_api.py --local # endpoints needing no token
 
21
  # 05 · Workflow1111 — a Diffusion Studio built from `gr.Workflow`
22
 
23
  An **Automatic1111-shaped image studio expressed as one canvas graph** instead
24
+ of a tabbed UI: **73 nodes, 11 pipelines, 20 independently runnable outputs**,
25
  all inside a single `gr.Workflow`.
26
 
27
  ```bash
 
43
 
44
  So an A1111 clone genuinely *cannot* be a `gr.Tabs` layout here — the graph **is**
45
  the UI. The analogue of a tab is a **subject group**: a connected cluster of
46
+ outputs, which gradio also publishes as its own REST endpoint. Eleven pipelines
47
+ sit side by side on one canvas, and you run whichever output you want.
48
 
49
  ---
50
 
 
62
  | 8 | **Extras** | Extras tab | local Lanczos upscale · AuraSR ×4 · background removal |
63
  | 9 | **Annotators** | ControlNet preprocessors | Canny · line art · sketch · luma-depth · posterize · threshold |
64
  | 10 | **PNG Info** | PNG Info tab | read generation parameters back out of a file |
65
+ | 11 | **img2video** | — | that same PNG → motion prompt builder → Wan 2.2 I2V A14B → ~3s clip + parameter readout |
66
 
67
  **The txt2img node has the real control surface** — negative prompt, sampling
68
  steps, CFG scale, seed (with `-1` = random), width/height with aspect presets,
 
75
  parses it back out. Images this app makes round-trip through a real A1111
76
  install too.
77
 
78
+ **Pipeline 11 shares pipeline 10's input.** `PNG to inspect` feeds both
79
+ `png_info` *and* the video's first-frame prep — the same still is read for its
80
+ generation parameters and animated. A reference node may fan out to any number
81
+ of consumers (only an input *port* is limited to one incoming edge), so this
82
+ needs no second upload widget, and both land in one API endpoint group.
83
+
84
+ ---
85
+
86
+ ## The img2video pipeline
87
+
88
+ ```
89
+ PNG to inspect ──┬──→ png_info ─────────────→ 🧾 PNG info · 🧮 Parsed fields
90
+ └──→ ⓶ First frame ─┐
91
+ Motion prompt ──┐ ├──→ ⓷ img2video ─┬──→ 🎬 Video
92
+ Motion preset ──┼→ ⓵ Motion prompt ──┤ Wan 2.2 I2V └──→ 📋 Video parameters
93
+ Camera move ───┘ │ A14B
94
+ ⓵ Video negative ──┘
95
+ ```
96
+
97
+ `Wan-AI/Wan2.2-I2V-A14B` is served for `image-to-video` by **fal-ai** and
98
+ **wavespeed**; `provider="auto"` picks fal-ai. Unlike a still, this node is an
99
+ `fn` node for gotcha #1's reason *and* nothing else — `image_to_video`'s
100
+ canonical schema is exactly `["image", "prompt"]`, so a `model` node would have
101
+ survived the canvas rewrite but would have lost length, steps, guidance, seed
102
+ and resolution.
103
+
104
+ `motion_prompt` is a separate builder from `apply_style` on purpose: an image
105
+ style preset appends look/medium tags, while a video prompt has to describe
106
+ *change over time* or Wan returns a nearly static clip. The default negative
107
+ prompt leads with Wan's own `static, motionless, still image, no movement` for
108
+ the same reason.
109
+
110
+ ### What the provider actually accepts
111
+
112
+ Probed live against fal-ai, not read off a doc page:
113
+
114
+ | Parameter | Behaviour |
115
+ |---|---|
116
+ | `num_frames` | Real. Counted at **16 fps**, and the returned mp4 is interpolated to 32 fps — 49 frames → 3.0s, 81 frames → 5.0s. |
117
+ | `num_inference_steps` | Real. 8 is enough for a short clip. |
118
+ | `guidance_scale` | Real. |
119
+ | `seed` | Real. `-1` is randomized client-side, so the report always names the seed actually used. |
120
+ | `negative_prompt` | Real. |
121
+ | `resolution` | Real **and validated** — `480p` / `580p` / `720p`. |
122
+ | anything else | **Silently dropped**, not rejected. |
123
+
124
+ Two consequences the code is built around:
125
+
126
+ * A bad `resolution` makes the provider answer with a payload that has no
127
+ `video` key, which surfaces out of `huggingface_hub` as a bare
128
+ `KeyError: 'video'` — no status code, no message. `img2video` clamps the
129
+ value with `_choice` *and* catches `KeyError` to turn it into a sentence.
130
+ * Because unknown parameters are dropped rather than rejected, there is no
131
+ feedback when one stops being honoured. Only the six above are sent.
132
+
133
+ The shipped defaults — **49 frames, 8 steps, 480p** — are a deliberately *small*
134
+ clip: measured at ~14s and ~1.2 MB per generation, against ~71s when the
135
+ resolution is left unpinned. Raise `num_frames` to 81 for a 5s clip.
136
+
137
  ---
138
 
139
  ## Architecture
140
 
141
  ```
142
+ 17 references → 36 operators → 20 subjects 82 edges
143
+ ├─ 32 fn 22 pure-local · 10 calling InferenceClient
144
  ├─ 2 model HF Inference Providers
145
  └─ 2 space Gradio Spaces on the Hub
146
  ```
147
 
148
+ 22 of the 32 `fn` nodes are pure local Pillow/numpy — all the prompt logic,
149
  post-processing, annotators, masking, grid composition and metadata parsing —
150
+ so most of the app keeps working with no token, no quota and no network. 14
151
  nodes in total leave the machine.
152
 
153
  ### Files
 
155
  | File | What it is |
156
  |---|---|
157
  | `app.py` | Entry point — 12 lines of actual wiring |
158
+ | `nodes.py` | The 24 bound functions (the `fn` node library) |
159
  | `build_workflow.py` | **Generates + verifies** `workflow.json` |
160
  | `workflow.json` | The committed graph |
161
+ | `test_nodes.py` | 58 offline unit tests (~2s) |
162
+ | `test_pipelines.py` | Runs all 20 outputs through the real `WorkflowExecutor` |
163
  | `test_api.py` | Drives the 9 generated REST endpoints against a running app |
164
  | `make_samples.py` | Regenerates the shipped sample images |
165
  | `deploy_space.py` | Stages + uploads the Space |
 
264
  `_from_output` takes `path` first (endpoint happy), the frontend and `_img_url`
265
  take `url` first (canvas and providers happy).
266
 
267
+ **Video is the one deliberate exception.** `_emit_video` returns
268
+ `{"path", "url": "/gradio_api/file=…", "is_file": True}` — gradio's own
269
+ `_save_tmp` shape — rather than inlining a `data:` URI. A still is tens of
270
+ kilobytes; an mp4 is megabytes, and base64-inlining one into the graph value
271
+ would bloat every canvas update that carries it. The URL resolves because
272
+ `gr.Workflow.launch()` already puts the tempdir on `allowed_paths` for exactly
273
+ this shape. Nothing chains *off* a video port, so the reason `_emit` needs a
274
+ fetchable URI (feeding a remote provider) does not apply.
275
+
276
  ### 6. A `json` port silently destroys its value in the canvas
277
 
278
  The canvas serializes a `json`-typed port with JavaScript's `String(obj)`
 
308
 
309
  ```bash
310
  python apps/05_workflow1111/test_nodes.py # 53 unit tests, offline, ~2s
311
+ python apps/05_workflow1111/test_pipelines.py # all 20 outputs, hits HF
312
  python apps/05_workflow1111/test_pipelines.py local # only the offline outputs
313
  python apps/05_workflow1111/test_api.py # the 9 REST endpoints
314
  python apps/05_workflow1111/test_api.py --local # endpoints needing no token
app.py CHANGED
@@ -3,7 +3,7 @@ Workflow1111 · a Diffusion Studio built entirely from `gr.Workflow`
3
  ==================================================================
4
 
5
  An Automatic1111-shaped image studio expressed as **one canvas graph** instead
6
- of a tabbed UI — 64 nodes across 10 pipelines, every one of them runnable on
7
  its own.
8
 
9
  python apps/05_workflow1111/app.py
@@ -22,6 +22,9 @@ What's on the canvas
22
  8 Extras local upscale, AuraSR ×4, background removal
23
  9 Annotators Canny / line art / sketch / luma-depth previews
24
  10 PNG Info read generation parameters back out of a file
 
 
 
25
 
26
  Why it is shaped like this
27
  --------------------------
@@ -30,27 +33,31 @@ like this genuinely cannot be tabs — the graph *is* the UI. Each output
30
  ("subject") is independently runnable and is also published as an API endpoint,
31
  which is the closest analogue to A1111's tabs.
32
 
33
- Four design rules came out of probing gradio 6.22 / huggingface_hub 1.26
34
- directly, and the app depends on all four (details in `nodes.py` and README):
35
 
36
  • A `model` node's ports get rewritten to the endpoint's canonical schema the
37
  moment a browser loads the graph — and the file is saved back that way. So
38
  anything needing a richer control surface than the schema (`txt2img`,
39
- `chat_llm`, `interrogate`) is an `fn` node calling `InferenceClient`
40
- itself. `build_workflow.py` refuses to build if a `model` node's ports
41
- ever diverge from its schema again.
42
  • `fn` nodes emit images as ``{"path": <file>, "url": <data: URI>}``. The
43
  REST endpoint's `gr.Image` component needs a real file (a bare ``data:``
44
  URI is read as a *filename*); the canvas and a chained `model` node need
45
  the URI. Both keys, one value.
 
 
 
 
46
  • A `model` image output is never wired straight into another `model`'s image
47
  port; `prep_image` sits between them (gradio would otherwise hand the
48
  provider an unresolvable ``/gradio_api/file=`` path).
49
  • `space` nodes only ever take an *uploaded* image.
50
 
51
- 19 of the 26 `fn` nodes are pure local Pillow/numpy — no token, no quota, no
52
  network — so most of the app keeps working even when a provider is having a bad
53
- day. 13 nodes in total leave the machine.
54
 
55
  Setup
56
  -----
 
3
  ==================================================================
4
 
5
  An Automatic1111-shaped image studio expressed as **one canvas graph** instead
6
+ of a tabbed UI — 73 nodes across 11 pipelines, every one of them runnable on
7
  its own.
8
 
9
  python apps/05_workflow1111/app.py
 
22
  8 Extras local upscale, AuraSR ×4, background removal
23
  9 Annotators Canny / line art / sketch / luma-depth previews
24
  10 PNG Info read generation parameters back out of a file
25
+ 11 img2video that same PNG animated into a ~3s clip by Wan 2.2 I2V
26
+ A14B on Inference Providers, with a motion/camera prompt
27
+ builder and real length/steps/guidance/seed/resolution
28
 
29
  Why it is shaped like this
30
  --------------------------
 
33
  ("subject") is independently runnable and is also published as an API endpoint,
34
  which is the closest analogue to A1111's tabs.
35
 
36
+ Five design rules came out of probing gradio 6.22 / huggingface_hub 1.26
37
+ directly, and the app depends on all five (details in `nodes.py` and README):
38
 
39
  • A `model` node's ports get rewritten to the endpoint's canonical schema the
40
  moment a browser loads the graph — and the file is saved back that way. So
41
  anything needing a richer control surface than the schema (`txt2img`,
42
+ `chat_llm`, `interrogate`, `img2video`) is an `fn` node calling
43
+ `InferenceClient` itself. `build_workflow.py` refuses to build if a `model`
44
+ node's ports ever diverge from its schema again.
45
  • `fn` nodes emit images as ``{"path": <file>, "url": <data: URI>}``. The
46
  REST endpoint's `gr.Image` component needs a real file (a bare ``data:``
47
  URI is read as a *filename*); the canvas and a chained `model` node need
48
  the URI. Both keys, one value.
49
+ • Video is the exception to that: `_emit_video` returns
50
+ ``{"path", "url": "/gradio_api/file=…", "is_file": True}`` — gradio's own
51
+ `_save_tmp` shape — because an mp4 is megabytes and base64-inlining one
52
+ into the graph value would bloat every canvas update carrying it.
53
  • A `model` image output is never wired straight into another `model`'s image
54
  port; `prep_image` sits between them (gradio would otherwise hand the
55
  provider an unresolvable ``/gradio_api/file=`` path).
56
  • `space` nodes only ever take an *uploaded* image.
57
 
58
+ 22 of the 32 `fn` nodes are pure local Pillow/numpy — no token, no quota, no
59
  network — so most of the app keeps working even when a provider is having a bad
60
+ day. 14 nodes in total leave the machine.
61
 
62
  Setup
63
  -----
build_workflow.py CHANGED
@@ -65,6 +65,9 @@ def sample(filename):
65
  T2I_MODEL = "black-forest-labs/FLUX.1-schnell"
66
  T2I_QUALITY_MODEL = "black-forest-labs/FLUX.1-dev"
67
  EDIT_MODEL = "black-forest-labs/FLUX.1-Kontext-dev"
 
 
 
68
  LLM_MODEL = "Qwen/Qwen3-4B-Instruct-2507"
69
  VLM_MODEL = "Qwen/Qwen2.5-VL-72B-Instruct"
70
  DETECT_MODEL = "facebook/detr-resnet-50"
@@ -180,7 +183,7 @@ def out(node_id, label, port_type, x, y, width=300):
180
  "outputs": [{"id": "out", "label": label, "type": port_type}],
181
  "data": {},
182
  "x": x, "y": y, "width": width,
183
- "height": 260 if port_type == "image" else 190,
184
  })
185
  return node_id
186
 
@@ -571,6 +574,68 @@ link("ref_pnginfo_image.out", "op_pnginfo.in_image")
571
  link("op_pnginfo.out_0", "sub_png_report.in")
572
  link("op_pnginfo.out_1", "sub_png_fields.in")
573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
 
575
  # ═════════════════════════════════════════════════════════════════════════════
576
  # Verification — catch wiring mistakes here, not at runtime
 
65
  T2I_MODEL = "black-forest-labs/FLUX.1-schnell"
66
  T2I_QUALITY_MODEL = "black-forest-labs/FLUX.1-dev"
67
  EDIT_MODEL = "black-forest-labs/FLUX.1-Kontext-dev"
68
+ # Served for image-to-video by fal-ai and wavespeed; `provider="auto"` picks
69
+ # fal-ai. Probed live — see the parameter notes on `nodes.img2video`.
70
+ I2V_MODEL = "Wan-AI/Wan2.2-I2V-A14B"
71
  LLM_MODEL = "Qwen/Qwen3-4B-Instruct-2507"
72
  VLM_MODEL = "Qwen/Qwen2.5-VL-72B-Instruct"
73
  DETECT_MODEL = "facebook/detr-resnet-50"
 
183
  "outputs": [{"id": "out", "label": label, "type": port_type}],
184
  "data": {},
185
  "x": x, "y": y, "width": width,
186
+ "height": 260 if port_type in ("image", "video") else 190,
187
  })
188
  return node_id
189
 
 
574
  link("op_pnginfo.out_0", "sub_png_report.in")
575
  link("op_pnginfo.out_1", "sub_png_fields.in")
576
 
577
+ # ═════════════════════════════════════════════════════════════════════════════
578
+ # 11 · img2video — animate the inspected PNG with Wan 2.2 (Inference Providers)
579
+ #
580
+ # Shares `ref_pnginfo_image` with pipeline 10: the same still is both read for
581
+ # its generation parameters and used as the first frame of a clip. A reference
582
+ # node may feed any number of consumers (only an *input* port is limited to one
583
+ # incoming edge), so this needs no second upload widget.
584
+ #
585
+ # `img2video` is an `fn` node, not a `model` node, for the reason in gotcha #1:
586
+ # `image_to_video`'s canonical schema is just ("image", "prompt"), so a model
587
+ # node would lose length, steps, guidance, seed and resolution the first time a
588
+ # browser opened the graph.
589
+ # ═════════════════════════════════════════════════════════════════════════════
590
+ Y = 5150
591
+ ref("ref_video_prompt", "Motion prompt", "text", COL[0], Y,
592
+ "the falling snow drifts past and the fox slowly turns its head toward the camera")
593
+ ref("ref_video_motion", "Motion preset", "text", COL[0], Y + 120, "Cinematic")
594
+ ref("ref_video_camera", "Camera move", "text", COL[0], Y + 240, "Slow push-in")
595
+
596
+ fn("op_video_prompt", "motion_prompt", COL[1], Y, label="⓵ Motion prompt",
597
+ required=("prompt",), data={"extra_tags": ""},
598
+ outputs=[("out_0", "prompt", "text")])
599
+
600
+ fn("op_video_negative", "build_video_negative", COL[1], Y + 220,
601
+ label="⓵ Video negative", types={"use_base": "boolean"},
602
+ data={"negative": "", "use_base": True},
603
+ outputs=[("out_0", "negative", "text")])
604
+
605
+ # Wan's native band is 480–832px on the long edge; anything larger is just a
606
+ # slower upload for the same result.
607
+ fn("op_video_prep", "prep_image", COL[1], Y + 400, label="⓶ First frame",
608
+ types={"image": "image", "max_side": "number", "strip_alpha": "boolean"},
609
+ required=("image",),
610
+ data={"max_side": 832, "mode": "Fit", "strip_alpha": True},
611
+ outputs=[("out_0", "image", "image")])
612
+
613
+ fn("op_img2video", "img2video", COL[2], Y, label="⓷ img2video · Wan 2.2 I2V A14B",
614
+ types={"image": "image", "num_frames": "number", "steps": "number",
615
+ "guidance_scale": "number", "seed": "number"},
616
+ required=("image", "prompt"),
617
+ # 49 frames ≈ 3s at Wan's 16 fps, 8 steps, 480p — a *small* clip on purpose.
618
+ # Measured against the live provider: ~14s and ~1.2 MB, versus ~71s when the
619
+ # resolution is left unpinned. Raise `num_frames` to 81 for a 5s clip.
620
+ data={"negative_prompt": "", "num_frames": 49, "steps": 8,
621
+ "guidance_scale": 3.5, "seed": -1, "resolution": "480p",
622
+ "model_id": I2V_MODEL},
623
+ outputs=[("out_0", "video", "video"), ("out_1", "report", "text")])
624
+
625
+ out("sub_video", "🎬 Video", "video", COL[3], Y)
626
+ out("sub_video_params", "📋 Video parameters", "text", COL[3], Y + 300)
627
+
628
+ link("ref_pnginfo_image.out", "op_video_prep.in_image")
629
+ link("ref_video_prompt.out", "op_video_prompt.in_prompt")
630
+ link("ref_video_motion.out", "op_video_prompt.in_motion")
631
+ link("ref_video_camera.out", "op_video_prompt.in_camera")
632
+
633
+ link("op_video_prep.out_0", "op_img2video.in_image")
634
+ link("op_video_prompt.out_0", "op_img2video.in_prompt")
635
+ link("op_video_negative.out_0", "op_img2video.in_negative_prompt")
636
+ link("op_img2video.out_0", "sub_video.in")
637
+ link("op_img2video.out_1", "sub_video_params.in")
638
+
639
 
640
  # ═════════════════════════════════════════════════════════════════════════════
641
  # Verification — catch wiring mistakes here, not at runtime
layout.json CHANGED
@@ -254,5 +254,41 @@
254
  "sub_upscaled": {
255
  "x": 1763.8,
256
  "y": 3908.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  }
258
  }
 
254
  "sub_upscaled": {
255
  "x": 1763.8,
256
  "y": 3908.0
257
+ },
258
+ "ref_video_prompt": {
259
+ "x": 60.0,
260
+ "y": 5150.0
261
+ },
262
+ "ref_video_motion": {
263
+ "x": 60.0,
264
+ "y": 5270.0
265
+ },
266
+ "ref_video_camera": {
267
+ "x": 60.0,
268
+ "y": 5390.0
269
+ },
270
+ "op_video_prompt": {
271
+ "x": 420.0,
272
+ "y": 5150.0
273
+ },
274
+ "op_video_negative": {
275
+ "x": 420.0,
276
+ "y": 5370.0
277
+ },
278
+ "op_video_prep": {
279
+ "x": 420.0,
280
+ "y": 5550.0
281
+ },
282
+ "op_img2video": {
283
+ "x": 800.0,
284
+ "y": 5150.0
285
+ },
286
+ "sub_video": {
287
+ "x": 1180.0,
288
+ "y": 5150.0
289
+ },
290
+ "sub_video_params": {
291
+ "x": 1180.0,
292
+ "y": 5450.0
293
  }
294
  }
nodes.py CHANGED
@@ -36,6 +36,7 @@ import os
36
  import random
37
  import re
38
  import tempfile
 
39
  import urllib.parse
40
  import urllib.request
41
  from typing import Optional
@@ -807,6 +808,206 @@ def top_labels(labels, top_k, min_score):
807
  return "\n".join(lines), json.dumps(rows, indent=2)
808
 
809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810
  # ─────────────────────────────────────────────────────────────────────────────
811
  # 2 · Image operators
812
  # ─────────────────────────────────────────────────────────────────────────────
@@ -1350,6 +1551,9 @@ BIND = {
1350
  "magic_instruction": magic_instruction,
1351
  "clean_prompt": clean_prompt,
1352
  "txt2img": txt2img,
 
 
 
1353
  "chat_llm": chat_llm,
1354
  "interrogate": interrogate,
1355
  "detect_objects": detect_objects,
 
36
  import random
37
  import re
38
  import tempfile
39
+ import time
40
  import urllib.parse
41
  import urllib.request
42
  from typing import Optional
 
808
  return "\n".join(lines), json.dumps(rows, indent=2)
809
 
810
 
811
+ # ─────────────────────────────────────────────────────────────────────────────
812
+ # 1c · Image-to-video — Wan 2.2 on HF Inference Providers
813
+ # ─────────────────────────────────────────────────────────────────────────────
814
+
815
+ # What the still should *do*, as opposed to what it depicts. Wan responds to
816
+ # plain motion language far better than to the comma-salad tag style that suits
817
+ # a diffusion image model, so these read like sentences.
818
+ MOTION_PRESETS = {
819
+ "None": "",
820
+ "Subtle": "subtle natural motion, gentle ambient movement, the scene breathes",
821
+ "Cinematic": "cinematic motion, smooth deliberate movement, film-like motion blur",
822
+ "Living portrait": "the subject blinks and shifts weight slightly, hair and "
823
+ "clothing move naturally, breathing",
824
+ "Weather": "drifting particles in the air, wind moving through the scene, "
825
+ "shifting light",
826
+ "Action": "energetic movement, dynamic action, motion carries through the frame",
827
+ }
828
+
829
+ CAMERA_MOVES = {
830
+ "Static": "locked-off static camera, no camera movement",
831
+ "Slow push-in": "slow steady dolly push-in toward the subject",
832
+ "Slow pull-out": "slow steady dolly pull-out revealing more of the scene",
833
+ "Pan left": "smooth camera pan to the left",
834
+ "Pan right": "smooth camera pan to the right",
835
+ "Orbit": "smooth arcing camera orbit around the subject",
836
+ "Handheld": "subtle handheld camera sway",
837
+ }
838
+
839
+ # Wan's own published negative prompt, trimmed to the terms that matter for a
840
+ # short clip. Sent only when the "use base" flag is on.
841
+ VIDEO_NEGATIVE_BASE = (
842
+ "static, motionless, still image, no movement, blurry, low quality, "
843
+ "overexposed, jpeg artifacts, distorted, deformed, disfigured, extra limbs, "
844
+ "fused fingers, watermark, subtitles, text, cluttered background"
845
+ )
846
+
847
+
848
+ def motion_prompt(prompt, motion, camera, extra_tags):
849
+ """Build the Wan prompt: what moves, and how the camera moves.
850
+
851
+ Kept separate from `apply_style` because the two want opposite things — an
852
+ image style preset appends look/medium tags, while a video prompt has to
853
+ describe *change over time* or Wan returns a nearly static clip.
854
+ """
855
+ base = _text(prompt)
856
+ if not base:
857
+ raise ValueError(
858
+ "Describe what should move — an image-to-video prompt with no motion "
859
+ "in it produces a nearly static clip."
860
+ )
861
+
862
+ parts = [base]
863
+ motion_text = MOTION_PRESETS.get(
864
+ _choice(motion, list(MOTION_PRESETS), "Cinematic"), "")
865
+ if motion_text:
866
+ parts.append(motion_text)
867
+ camera_text = CAMERA_MOVES.get(
868
+ _choice(camera, list(CAMERA_MOVES), "Slow push-in"), "")
869
+ if camera_text:
870
+ parts.append(camera_text)
871
+ extra = _text(extra_tags)
872
+ if extra:
873
+ parts.append(extra)
874
+ return ", ".join(parts)
875
+
876
+
877
+ def build_video_negative(negative, use_base):
878
+ """The negative prompt for a Wan clip — the caller's terms plus Wan's own
879
+ base list, which is what keeps the model from returning an unmoving still."""
880
+ terms = []
881
+ if _flag(use_base, True):
882
+ terms.append(VIDEO_NEGATIVE_BASE)
883
+ extra = _text(negative)
884
+ if extra:
885
+ terms.append(extra)
886
+ return ", ".join(terms)
887
+
888
+
889
+ def _emit_video(raw, ext="mp4"):
890
+ """Raw mp4 bytes → the value a video output port should carry.
891
+
892
+ Mirrors the ``{"path", "url": "/gradio_api/file=…", "is_file": True}`` shape
893
+ gradio's own `_save_tmp` produces for a `model` node's video output, which
894
+ is what `gr.Video` and the REST endpoint both consume (`_from_output` takes
895
+ ``path`` first, the canvas follows ``url``, and `launch()` puts the tempdir
896
+ on `allowed_paths` so the URL resolves).
897
+
898
+ Unlike `_emit`, this does **not** inline a ``data:`` URI. A still is tens of
899
+ kilobytes; an mp4 is megabytes, and base64-inlining one into the graph value
900
+ would bloat every canvas update that carries it.
901
+ """
902
+ path = os.path.join(tempfile.gettempdir(),
903
+ f"wf1111_{os.urandom(8).hex()}.{ext}")
904
+ with open(path, "wb") as f:
905
+ f.write(raw)
906
+ return {"path": path, "url": f"/gradio_api/file={path}", "is_file": True}
907
+
908
+
909
+ # Verified against the live provider rather than read off a doc page:
910
+ # • `num_frames` sets the *generated* length at 16 fps, and the returned mp4
911
+ # is interpolated to 32 fps — 49 frames → 3.0s, 81 frames → 5.0s.
912
+ # • `resolution` IS validated. A value outside this set makes the provider
913
+ # answer with a payload that has no `video` key, which surfaces out of
914
+ # huggingface_hub as a bare `KeyError: 'video'` — hence the `_choice` clamp
915
+ # below *and* the KeyError branch in the error handler.
916
+ # • Unknown parameters are silently dropped rather than rejected, so there is
917
+ # nothing to gain from sending anything outside this set.
918
+ VIDEO_RESOLUTIONS = ["480p", "580p", "720p"]
919
+ VIDEO_FPS = 16 # the rate `num_frames` is counted at, for the duration readout
920
+
921
+
922
+ def img2video(image, prompt, negative_prompt, num_frames, steps, guidance_scale,
923
+ seed, resolution, model_id,
924
+ oauth_token: Optional[OAuthToken] = None):
925
+ """Image-to-video against HF Inference Providers — Wan 2.2 I2V A14B.
926
+
927
+ An `fn` node rather than a `model` node for the same reason as `txt2img`:
928
+ the canvas rewrites a `model` node's ports to the endpoint's canonical
929
+ schema, and `image_to_video`'s schema is just ``(image, prompt)`` — so
930
+ length, steps, guidance, seed, resolution and the negative prompt would all
931
+ be silently dropped the first time the graph was opened in a browser.
932
+
933
+ Returns ``(video, report)``.
934
+ """
935
+ from huggingface_hub import InferenceClient
936
+
937
+ prompt = _text(prompt)
938
+ if not prompt:
939
+ raise ValueError("Prompt is empty — describe the motion you want.")
940
+
941
+ # A path, not bytes: the router needs a MIME type it can infer (see
942
+ # `_image_file`), and Wan wants a sanely-sized still, not a 4000px upload.
943
+ source = _image_file(image, "source image for the video")
944
+
945
+ frames = _num(num_frames, 49, lo=17, hi=121, integer=True)
946
+ model = _text(model_id, "Wan-AI/Wan2.2-I2V-A14B")
947
+ res = _choice(resolution, VIDEO_RESOLUTIONS, "480p")
948
+
949
+ kwargs = {
950
+ "prompt": prompt,
951
+ "num_frames": frames,
952
+ "num_inference_steps": _num(steps, 8, lo=2, hi=40, integer=True),
953
+ "guidance_scale": round(_num(guidance_scale, 3.5, lo=1.0, hi=10.0), 2),
954
+ "resolution": res,
955
+ }
956
+ negative = _text(negative_prompt)
957
+ if negative:
958
+ kwargs["negative_prompt"] = negative
959
+ seed = _num(seed, -1, lo=-1, hi=_MAX_SEED, integer=True)
960
+ if seed < 0:
961
+ seed = _RNG.randint(0, _MAX_SEED)
962
+ kwargs["seed"] = seed
963
+
964
+ started = time.time()
965
+ try:
966
+ raw = InferenceClient(model=model, token=_hf_token(oauth_token),
967
+ provider="auto").image_to_video(source, **kwargs)
968
+ except KeyError as e:
969
+ # The provider answered, but with no video in the payload — in practice
970
+ # that means it rejected a parameter rather than that generation failed.
971
+ raise ValueError(
972
+ f"{model} returned no video (missing {e}). That usually means a "
973
+ f"parameter was rejected — resolution must be one of "
974
+ f"{', '.join(VIDEO_RESOLUTIONS)}."
975
+ ) from e
976
+ except Exception as e:
977
+ detail = str(e)
978
+ if "402" in detail or "quota" in detail.lower() or "credits" in detail.lower():
979
+ raise ValueError(
980
+ f"Inference credits exhausted for {model}. Video is by far the "
981
+ "most expensive node here — wait for the quota to reset, or "
982
+ "lower the frame count."
983
+ ) from e
984
+ if "401" in detail or "403" in detail:
985
+ raise ValueError(f"Not authorized for {model} — check your token.") from e
986
+ if "not supported" in detail.lower():
987
+ raise ValueError(
988
+ f"No enabled provider serves {model} for image-to-video. Try "
989
+ "Wan-AI/Wan2.2-I2V-A14B or Wan-AI/Wan2.1-I2V-14B-720P."
990
+ ) from e
991
+ raise ValueError(f"{model} failed: {detail[:300]}") from e
992
+
993
+ elapsed = time.time() - started
994
+ if not raw:
995
+ raise ValueError(f"{model} returned an empty video.")
996
+
997
+ report = "\n".join([
998
+ f"Model: {model}",
999
+ f"Prompt: {prompt}",
1000
+ *([f"Negative prompt: {negative}"] if negative else []),
1001
+ f"Frames: {frames} generated at {VIDEO_FPS} fps "
1002
+ f"(~{frames / VIDEO_FPS:.1f}s, returned interpolated to 32 fps)",
1003
+ f"Steps: {kwargs['num_inference_steps']}, "
1004
+ f"Guidance: {kwargs['guidance_scale']}, "
1005
+ f"Resolution: {res}, Seed: {seed}",
1006
+ f"Size: {len(raw) / 1_048_576:.1f} MB, generated in {elapsed:.0f}s",
1007
+ ])
1008
+ return _emit_video(raw), report
1009
+
1010
+
1011
  # ─────────────────────────────────────────────────────────────────────────────
1012
  # 2 · Image operators
1013
  # ─────────────────────────────────────────────────────────────────────────────
 
1551
  "magic_instruction": magic_instruction,
1552
  "clean_prompt": clean_prompt,
1553
  "txt2img": txt2img,
1554
+ "motion_prompt": motion_prompt,
1555
+ "build_video_negative": build_video_negative,
1556
+ "img2video": img2video,
1557
  "chat_llm": chat_llm,
1558
  "interrogate": interrogate,
1559
  "detect_objects": detect_objects,
test_api.py CHANGED
@@ -52,7 +52,15 @@ def sample(name):
52
  # (api_name, args, needs_token)
53
  CASES = [
54
  ("/annotator_map", lambda: [sample("control.jpg")], False),
55
- ("/png_info", lambda: [sample("with_parameters.png")], False),
 
 
 
 
 
 
 
 
56
  ("/upscaled_local", lambda: [sample("extras.jpg")], True), # also hits 2 Spaces
57
  ("/image", lambda: ["a red fox in a snowy pine forest", "", "Cinematic",
58
  "enhance fine detail"], True),
 
52
  # (api_name, args, needs_token)
53
  CASES = [
54
  ("/annotator_map", lambda: [sample("control.jpg")], False),
55
+ # `/png_info` covers pipelines 10 AND 11: they share the `PNG to inspect`
56
+ # reference, so they are one weakly-connected component and therefore one
57
+ # endpoint (`subject_groups`), returning all four outputs and generating a
58
+ # video on every call. Hence four arguments and needs_token=True — the
59
+ # *canvas* still runs each output on its own, so this is an API-surface
60
+ # consequence only.
61
+ ("/png_info", lambda: [sample("with_parameters.png"),
62
+ "the snow drifts past and the fox turns its head",
63
+ "Cinematic", "Slow push-in"], True),
64
  ("/upscaled_local", lambda: [sample("extras.jpg")], True), # also hits 2 Spaces
65
  ("/image", lambda: ["a red fox in a snowy pine forest", "", "Cinematic",
66
  "enhance fine detail"], True),
test_nodes.py CHANGED
@@ -225,6 +225,98 @@ def t_labels():
225
 
226
  check("top_labels formats + filters", t_labels)
227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  print("\n── image operators ───────────────────────────────────────────")
229
  check("postprocess full chain",
230
  lambda: is_img(N.postprocess(DATA_URI, 1.5, "Lanczos", 0.6, 1.2, 1.1, 1.0,
 
225
 
226
  check("top_labels formats + filters", t_labels)
227
 
228
+ print("\n── video prompt / emit ───────────────────────────────────────")
229
+
230
+
231
+ def t_motion_prompt():
232
+ p = N.motion_prompt("a red fox in snow", "Cinematic", "Slow push-in", "35mm")
233
+ assert p.startswith("a red fox in snow"), p
234
+ assert "cinematic motion" in p and "push-in" in p and p.endswith("35mm")
235
+ # An unknown preset falls back rather than vanishing or raising.
236
+ assert "cinematic motion" in N.motion_prompt("x", "nonsense", "nonsense", "")
237
+ # "None" motion + "Static" camera still yields the camera clause only.
238
+ bare = N.motion_prompt("x", "None", "Static", "")
239
+ assert bare == "x, locked-off static camera, no camera movement", bare
240
+ for empty in ("", " ", None):
241
+ try:
242
+ N.motion_prompt(empty, "Cinematic", "Static", "")
243
+ except ValueError:
244
+ pass
245
+ else:
246
+ raise AssertionError(f"empty prompt {empty!r} should raise")
247
+
248
+
249
+ check("motion_prompt builds a motion sentence", t_motion_prompt)
250
+
251
+
252
+ def t_video_negative():
253
+ full = N.build_video_negative("ugly hands", True)
254
+ assert full.startswith(N.VIDEO_NEGATIVE_BASE) and full.endswith("ugly hands")
255
+ assert N.build_video_negative("ugly hands", False) == "ugly hands"
256
+ assert N.build_video_negative("", True) == N.VIDEO_NEGATIVE_BASE
257
+ assert N.build_video_negative("", False) == ""
258
+
259
+
260
+ check("build_video_negative composes base + extra", t_video_negative)
261
+
262
+
263
+ def t_emit_video():
264
+ """A video port value must carry a real file *and* a `/gradio_api/file=`
265
+ URL — the same shape gradio's own `_save_tmp` makes for a model node."""
266
+ raw = b"\x00\x00\x00\x18ftypmp42" + os.urandom(64)
267
+ v = N._emit_video(raw)
268
+ assert set(v) == {"path", "url", "is_file"}, v
269
+ assert v["is_file"] is True
270
+ assert v["path"].endswith(".mp4") and os.path.isfile(v["path"])
271
+ assert open(v["path"], "rb").read() == raw
272
+ assert v["url"] == f"/gradio_api/file={v['path']}"
273
+ # Emphatically NOT a data: URI — an mp4 is megabytes (see `_emit_video`).
274
+ assert not v["url"].startswith("data:")
275
+
276
+
277
+ check("_emit_video writes a file + gradio URL", t_emit_video)
278
+
279
+
280
+ def t_img2video_guards():
281
+ """The cheap failures must happen before any billable call is made."""
282
+ from PIL import Image as _I
283
+ tmp = os.path.join(tempfile.gettempdir(), "wf1111_t_i2v.png")
284
+ sample().save(tmp)
285
+
286
+ # Empty prompt: rejected before the image is even materialized.
287
+ try:
288
+ N.img2video(tmp, " ", "", 49, 8, 3.5, -1, "480p", "Wan-AI/Wan2.2-I2V-A14B")
289
+ except ValueError as e:
290
+ assert "Prompt is empty" in str(e), e
291
+ else:
292
+ raise AssertionError("empty prompt should raise")
293
+
294
+ # Missing image: likewise, no network.
295
+ try:
296
+ N.img2video(None, "motion", "", 49, 8, 3.5, -1, "480p", "Wan-AI/Wan2.2-I2V-A14B")
297
+ except ValueError as e:
298
+ assert "source image" in str(e), e
299
+ else:
300
+ raise AssertionError("missing image should raise")
301
+
302
+ assert _I # keep the import meaningful if the asserts above are edited
303
+
304
+
305
+ check("img2video validates before spending quota", t_img2video_guards)
306
+
307
+
308
+ def t_video_constants():
309
+ assert N.VIDEO_RESOLUTIONS == ["480p", "580p", "720p"]
310
+ # `resolution` is validated provider-side, so `_choice` must clamp rather
311
+ # than pass an arbitrary string through (a bad one yields KeyError:'video').
312
+ assert N._choice("1080p", N.VIDEO_RESOLUTIONS, "480p") == "480p"
313
+ assert N._choice("720p", N.VIDEO_RESOLUTIONS, "480p") == "720p"
314
+ # 49 frames at 16 fps is the ~3s default the pipeline ships.
315
+ assert round(49 / N.VIDEO_FPS, 1) == 3.1
316
+
317
+
318
+ check("video constants match the probed provider", t_video_constants)
319
+
320
  print("\n── image operators ───────────────────────────────────────────")
321
  check("postprocess full chain",
322
  lambda: is_img(N.postprocess(DATA_URI, 1.5, "Lanczos", 0.6, 1.2, 1.1, 1.0,
test_pipelines.py CHANGED
@@ -139,6 +139,14 @@ def save(subject_id, value):
139
  return f"image {im.width}×{im.height} {ext.upper()}, {len(raw) // 1024} KB"
140
 
141
  if isinstance(value, str) and os.path.isfile(value):
 
 
 
 
 
 
 
 
142
  from PIL import Image
143
  try:
144
  with Image.open(value) as im:
 
139
  return f"image {im.width}×{im.height} {ext.upper()}, {len(raw) // 1024} KB"
140
 
141
  if isinstance(value, str) and os.path.isfile(value):
142
+ ext = os.path.splitext(value)[1].lower()
143
+ if ext in (".mp4", ".webm", ".mov"):
144
+ import shutil
145
+ dst = os.path.join(OUTDIR, f"{subject_id}{ext}")
146
+ shutil.copyfile(value, dst)
147
+ size = os.path.getsize(dst)
148
+ return f"video {ext[1:].upper()}, {size // 1024} KB → {os.path.basename(dst)}"
149
+
150
  from PIL import Image
151
  try:
152
  with Image.open(value) as im:
workflow.json CHANGED
The diff for this file is too large to render. See raw diff