ysharma HF Staff commited on
Commit
d556e5d
·
verified ·
1 Parent(s): 3f13d35

Workflow1111 — Automatic1111-style diffusion studio on gr.Workflow

Browse files
Files changed (4) hide show
  1. README.md +50 -16
  2. app.py +1 -1
  3. nodes.py +53 -15
  4. workflow.json +0 -0
README.md CHANGED
@@ -1,18 +1,18 @@
1
- ---
2
- title: Workflow1111 Diffusion Studio
3
- emoji: 🎨
4
- colorFrom: indigo
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 6.26.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- hf_oauth: true
12
- hf_oauth_scopes:
13
- - inference-api
14
- short_description: Automatic1111-style studio on one gr.Workflow canvas
15
- ---
16
 
17
  > **Sign in with Hugging Face** (button at the top right) before running
18
  > anything. This Space carries no token of its own — every `model`, `space` and
@@ -345,6 +345,40 @@ image, params, hires = client.predict(
345
  Run `python apps/05_workflow1111/test_pipelines.py local` to print the full
346
  endpoint list with parameter names and types.
347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  ---
349
 
350
  ## Extending it
@@ -356,4 +390,4 @@ plus `link(...)`s — the verifier will tell you what you got wrong before the
356
  file is written.
357
 
358
  > Re-running `build_workflow.py` overwrites node positions, so any layout you
359
- > drag around in the canvas is reset.
 
1
+ ---
2
+ title: Workflow1111 Diffusion Studio
3
+ emoji: 🎨
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 6.22.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ hf_oauth: true
12
+ hf_oauth_scopes:
13
+ - inference-api
14
+ short_description: Automatic1111-style studio on one gr.Workflow canvas
15
+ ---
16
 
17
  > **Sign in with Hugging Face** (button at the top right) before running
18
  > anything. This Space carries no token of its own — every `model`, `space` and
 
345
  Run `python apps/05_workflow1111/test_pipelines.py local` to print the full
346
  endpoint list with parameter names and types.
347
 
348
+ ### Bring your own token (API and MCP callers)
349
+
350
+ The Space holds **no** `HF_TOKEN` secret. In the browser, the Sign-in button
351
+ supplies your token through OAuth; API and MCP callers supply it on the
352
+ request instead. Every node that talks to Inference Providers declares a
353
+ `request: gr.Request` parameter, and `_hf_token()` in `nodes.py` looks for
354
+ the token in this order: OAuth session → `X-HF-Token` header →
355
+ `Authorization: Bearer` header → server `HF_TOKEN` → local `hf auth login`.
356
+ Gradio's MCP server forwards the caller's headers verbatim, so the same
357
+ header works for tools.
358
+
359
+ ```python
360
+ from gradio_client import Client
361
+
362
+ client = Client("https://ysharma-workflow1111.hf.space", token="hf_...") # sends Authorization: Bearer
363
+ prompt = client.predict("an orange cat with a yellow hat", api_name="/generated_prompt")
364
+ ```
365
+
366
+ MCP client config (Claude Code, Cursor, Claude Desktop):
367
+
368
+ ```json
369
+ {
370
+ "mcpServers": {
371
+ "workflow1111": {
372
+ "url": "https://ysharma-workflow1111.hf.space/gradio_api/mcp/",
373
+ "headers": { "X-HF-Token": "hf_..." }
374
+ }
375
+ }
376
+ }
377
+ ```
378
+
379
+ Without a token, model nodes raise `No Hugging Face token ...`; the purely
380
+ local Pillow/numpy nodes never need one.
381
+
382
  ---
383
 
384
  ## Extending it
 
390
  file is written.
391
 
392
  > Re-running `build_workflow.py` overwrites node positions, so any layout you
393
+ > drag around in the canvas is reset.
app.py CHANGED
@@ -103,4 +103,4 @@ if __name__ == "__main__":
103
  " set HF_TOKEN, or sign in from inside the app.\n"
104
  )
105
 
106
- demo.launch(mcp_server=True)
 
103
  " set HF_TOKEN, or sign in from inside the app.\n"
104
  )
105
 
106
+ demo.launch()
nodes.py CHANGED
@@ -46,6 +46,7 @@ import numpy as np
46
  # detects injected parameters by their resolved type, and an unresolvable
47
  # annotation would turn the token into a visible input port.
48
  from gradio.oauth import OAuthToken
 
49
  from huggingface_hub import get_token as _saved_hf_token
50
  from PIL import (
51
  Image,
@@ -564,7 +565,8 @@ def clean_prompt(raw, max_tags):
564
 
565
 
566
  def txt2img(prompt, negative_prompt, steps, cfg_scale, seed, width, height,
567
- model_id, oauth_token: Optional[OAuthToken] = None):
 
568
  """Text-to-image against HF Inference Providers — the A1111 txt2img box.
569
 
570
  This is deliberately an `fn` node rather than a `model` node. The canvas
@@ -582,7 +584,7 @@ def txt2img(prompt, negative_prompt, steps, cfg_scale, seed, width, height,
582
  if not prompt:
583
  raise ValueError("Prompt is empty — describe what you want to see.")
584
 
585
- token = _hf_token(oauth_token)
586
  model = _text(model_id, "black-forest-labs/FLUX.1-schnell")
587
  kwargs = {
588
  "prompt": prompt,
@@ -621,13 +623,44 @@ def txt2img(prompt, negative_prompt, steps, cfg_scale, seed, width, height,
621
  return _emit(image)
622
 
623
 
624
- def _hf_token(oauth_token):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
625
  token = (getattr(oauth_token, "token", None)
 
626
  or os.environ.get("HF_TOKEN") or _saved_hf_token())
627
  if not token:
628
  raise ValueError(
629
- "No Hugging Face token. Run `hf auth login`, set HF_TOKEN, or sign "
630
- "in with the button at the top of the canvas."
 
 
631
  )
632
  return token
633
 
@@ -680,7 +713,8 @@ def _chat(model_id, token, text, image=None, max_tokens=512):
680
  return out
681
 
682
 
683
- def chat_llm(prompt, model_id, max_tokens, oauth_token: Optional[OAuthToken] = None):
 
684
  """Text-only LLM call.
685
 
686
  An `fn` node rather than a `model` node for the same reason as `txt2img`:
@@ -691,12 +725,13 @@ def chat_llm(prompt, model_id, max_tokens, oauth_token: Optional[OAuthToken] = N
691
  if not prompt:
692
  raise ValueError("Nothing to send to the language model.")
693
  return _chat(_text(model_id, "Qwen/Qwen3-4B-Instruct-2507"),
694
- _hf_token(oauth_token), prompt,
695
  max_tokens=_num(max_tokens, 512, lo=32, hi=4096, integer=True))
696
 
697
 
698
  def interrogate(image, instruction, model_id, max_tokens,
699
- oauth_token: Optional[OAuthToken] = None):
 
700
  """Vision-language call — CLIP-interrogate, essentially.
701
 
702
  The image is **required**: without this guard the model cheerfully invents
@@ -705,7 +740,7 @@ def interrogate(image, instruction, model_id, max_tokens,
705
  """
706
  img = _load_image(image, "image to interrogate") # raises if absent
707
  return _chat(_text(model_id, "Qwen/Qwen2.5-VL-72B-Instruct"),
708
- _hf_token(oauth_token),
709
  _text(instruction, "Describe this image."),
710
  image=_emit_uri(img),
711
  max_tokens=_num(max_tokens, 512, lo=32, hi=4096, integer=True))
@@ -724,7 +759,8 @@ def _image_file(image, label="image"):
724
  return path
725
 
726
 
727
- def detect_objects(image, model_id, min_score, oauth_token: Optional[OAuthToken] = None):
 
728
  """Object detection, returning the detections as a **JSON string**.
729
 
730
  An `fn` node calling `InferenceClient` rather than a `model` node, because
@@ -738,7 +774,7 @@ def detect_objects(image, model_id, min_score, oauth_token: Optional[OAuthToken]
738
 
739
  model = _text(model_id, "facebook/detr-resnet-50")
740
  floor = _num(min_score, 0.0, lo=0.0, hi=1.0)
741
- client = InferenceClient(model=model, token=_hf_token(oauth_token), provider="auto")
742
  try:
743
  results = client.object_detection(image=_image_file(image, "image to analyse"))
744
  except Exception as e:
@@ -761,13 +797,14 @@ def detect_objects(image, model_id, min_score, oauth_token: Optional[OAuthToken]
761
  return json.dumps(found)
762
 
763
 
764
- def classify_image(image, model_id, oauth_token: Optional[OAuthToken] = None):
 
765
  """Image classification, returning the labels as a **JSON string**
766
  (same reason as `detect_objects`)."""
767
  from huggingface_hub import InferenceClient
768
 
769
  model = _text(model_id, "google/vit-base-patch16-224")
770
- client = InferenceClient(model=model, token=_hf_token(oauth_token), provider="auto")
771
  try:
772
  results = client.image_classification(
773
  image=_image_file(image, "image to classify"))
@@ -921,7 +958,8 @@ VIDEO_FPS = 16 # the rate `num_frames` is counted at, for the duration readout
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`:
@@ -963,7 +1001,7 @@ def img2video(image, prompt, negative_prompt, num_frames, steps, guidance_scale,
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
 
46
  # detects injected parameters by their resolved type, and an unresolvable
47
  # annotation would turn the token into a visible input port.
48
  from gradio.oauth import OAuthToken
49
+ from gradio.route_utils import Request
50
  from huggingface_hub import get_token as _saved_hf_token
51
  from PIL import (
52
  Image,
 
565
 
566
 
567
  def txt2img(prompt, negative_prompt, steps, cfg_scale, seed, width, height,
568
+ model_id, oauth_token: Optional[OAuthToken] = None,
569
+ request: Optional[Request] = None):
570
  """Text-to-image against HF Inference Providers — the A1111 txt2img box.
571
 
572
  This is deliberately an `fn` node rather than a `model` node. The canvas
 
584
  if not prompt:
585
  raise ValueError("Prompt is empty — describe what you want to see.")
586
 
587
+ token = _hf_token(oauth_token, request)
588
  model = _text(model_id, "black-forest-labs/FLUX.1-schnell")
589
  kwargs = {
590
  "prompt": prompt,
 
623
  return _emit(image)
624
 
625
 
626
+ def _caller_hf_token(request):
627
+ """Token supplied by an API / MCP caller on the HTTP request itself.
628
+
629
+ Gradio injects the originating request into any bound function that
630
+ declares a ``request: gr.Request`` parameter, and its MCP server forwards
631
+ the caller's headers verbatim — so a client can authenticate per call
632
+ without the Space holding a token of its own. Two spellings are accepted:
633
+
634
+ * ``X-HF-Token: hf_...`` (custom header; shown in MCP configs)
635
+ * ``Authorization: Bearer hf_...`` (what ``gradio_client`` sends for
636
+ ``Client(..., hf_token=...)``)
637
+ """
638
+ headers = getattr(request, "headers", None)
639
+ if not headers:
640
+ return None
641
+ lower = {str(k).lower(): v for k, v in dict(headers).items()}
642
+ token = lower.get("x-hf-token")
643
+ if not token:
644
+ auth = lower.get("authorization", "")
645
+ if auth.lower().startswith("bearer "):
646
+ token = auth[7:]
647
+ token = (token or "").strip()
648
+ return token if token.startswith("hf_") else None
649
+
650
+
651
+ def _hf_token(oauth_token, request=None):
652
+ """Resolve the HF token for a node, in priority order: the browser user's
653
+ OAuth session, a token the API/MCP caller put on the request, the
654
+ server's HF_TOKEN, then a locally saved `hf auth login` token."""
655
  token = (getattr(oauth_token, "token", None)
656
+ or _caller_hf_token(request)
657
  or os.environ.get("HF_TOKEN") or _saved_hf_token())
658
  if not token:
659
  raise ValueError(
660
+ "No Hugging Face token. Sign in with the button at the top of the "
661
+ "canvas, or (API/MCP callers) send it as an `X-HF-Token` or "
662
+ "`Authorization: Bearer` header; locally you can also run "
663
+ "`hf auth login` or set HF_TOKEN."
664
  )
665
  return token
666
 
 
713
  return out
714
 
715
 
716
+ def chat_llm(prompt, model_id, max_tokens, oauth_token: Optional[OAuthToken] = None,
717
+ request: Optional[Request] = None):
718
  """Text-only LLM call.
719
 
720
  An `fn` node rather than a `model` node for the same reason as `txt2img`:
 
725
  if not prompt:
726
  raise ValueError("Nothing to send to the language model.")
727
  return _chat(_text(model_id, "Qwen/Qwen3-4B-Instruct-2507"),
728
+ _hf_token(oauth_token, request), prompt,
729
  max_tokens=_num(max_tokens, 512, lo=32, hi=4096, integer=True))
730
 
731
 
732
  def interrogate(image, instruction, model_id, max_tokens,
733
+ oauth_token: Optional[OAuthToken] = None,
734
+ request: Optional[Request] = None):
735
  """Vision-language call — CLIP-interrogate, essentially.
736
 
737
  The image is **required**: without this guard the model cheerfully invents
 
740
  """
741
  img = _load_image(image, "image to interrogate") # raises if absent
742
  return _chat(_text(model_id, "Qwen/Qwen2.5-VL-72B-Instruct"),
743
+ _hf_token(oauth_token, request),
744
  _text(instruction, "Describe this image."),
745
  image=_emit_uri(img),
746
  max_tokens=_num(max_tokens, 512, lo=32, hi=4096, integer=True))
 
759
  return path
760
 
761
 
762
+ def detect_objects(image, model_id, min_score, oauth_token: Optional[OAuthToken] = None,
763
+ request: Optional[Request] = None):
764
  """Object detection, returning the detections as a **JSON string**.
765
 
766
  An `fn` node calling `InferenceClient` rather than a `model` node, because
 
774
 
775
  model = _text(model_id, "facebook/detr-resnet-50")
776
  floor = _num(min_score, 0.0, lo=0.0, hi=1.0)
777
+ client = InferenceClient(model=model, token=_hf_token(oauth_token, request), provider="auto")
778
  try:
779
  results = client.object_detection(image=_image_file(image, "image to analyse"))
780
  except Exception as e:
 
797
  return json.dumps(found)
798
 
799
 
800
+ def classify_image(image, model_id, oauth_token: Optional[OAuthToken] = None,
801
+ request: Optional[Request] = None):
802
  """Image classification, returning the labels as a **JSON string**
803
  (same reason as `detect_objects`)."""
804
  from huggingface_hub import InferenceClient
805
 
806
  model = _text(model_id, "google/vit-base-patch16-224")
807
+ client = InferenceClient(model=model, token=_hf_token(oauth_token, request), provider="auto")
808
  try:
809
  results = client.image_classification(
810
  image=_image_file(image, "image to classify"))
 
958
 
959
  def img2video(image, prompt, negative_prompt, num_frames, steps, guidance_scale,
960
  seed, resolution, model_id,
961
+ oauth_token: Optional[OAuthToken] = None,
962
+ request: Optional[Request] = None):
963
  """Image-to-video against HF Inference Providers — Wan 2.2 I2V A14B.
964
 
965
  An `fn` node rather than a `model` node for the same reason as `txt2img`:
 
1001
 
1002
  started = time.time()
1003
  try:
1004
+ raw = InferenceClient(model=model, token=_hf_token(oauth_token, request),
1005
  provider="auto").image_to_video(source, **kwargs)
1006
  except KeyError as e:
1007
  # The provider answered, but with no video in the payload — in practice
workflow.json CHANGED
The diff for this file is too large to render. See raw diff