AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

huggingface-lora-space-builder

Build and publish a Gradio demo on Hugging Face Spaces for a user-provided LoRA. Use when someone asks to create, generate, ship, or publish a Space, demo, Gradio app, or playground for a LoRA — including LoRAs for Qwen-Image, Qwen-Image-Edit, LTX-Video, Wan, FLUX, SDXL, or other diffusion base models. Also triggers when someone describes a LoRA they trained or hosts on the Hub and wants to share it. Covers picking the right base pipeline and `diffusers` inference recipe, designing a UI tailored to the LoRA's task and inputs (Union/multi-task control, edit, video, image, etc.), respecting model-card recommendations (trigger words, steps, guidance, LoRA scale, example inputs), and shipping to ZeroGPU hardware as a private Space by default.

Original source
huggingface
License
Apache-2.0
Pinned revision
25910b3d0ba31a2ba102f901cdc9e008c278a69c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read huggingface--huggingface-lora-space-builder at revision 25910b3d0ba31a2ba102f901cdc9e008c278a69c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 8

SKILL.md · 24000

esponds once, covering whatever they want changed across any of the three files.

What to avoid:

  • Walking through app.py's structure or design choices after writing it but before writing the others. Save commentary for either the pre-writing announcement (Phase 4 opening) or the single approval message after all three exist.
  • Asking "ready for the next one?" or "want me to continue with requirements?" — those are implicit per-file approvals.
  • Showing one file inline and offering to "show the next when you're ready" — same trap.
  • Treating any of the three files as optional or as a follow-up. They are produced together as one deliverable.

If the user interrupts after seeing the first file with feedback or a question, that's fine — engage with it — but the rule still applies: the next time you produce code, produce all remaining files together, not one at a time.


Phase 5 — Publish the Space

Use the authenticated session from Phase 1. Default to private, so the user can vet the Space before flipping it public. Confirm the target username with the user before creating: "I'll publish to {username}/{space_name} — confirm?"

from huggingface_hub import HfApi, SpaceHardware

api = HfApi(token=hf_token)
username = api.whoami()["name"]
repo_id = f"{username}/{space_name}"

api.create_repo(
    repo_id=repo_id,
    repo_type="space",
    space_sdk="gradio",
    space_hardware=SpaceHardware.ZERO_A10G,
    private=True,
    exist_ok=True,
)

# Upload files
for path in ["app.py", "requirements.txt", "README.md"]:
    api.upload_file(path_or_fileobj=path, path_in_repo=path,
                    repo_id=repo_id, repo_type="space")

If the LoRA repo itself is private/gated, the Space needs the token at runtime to download the LoRA. Set it as a Space secret:

api.add_space_secret(repo_id=repo_id, key="HF_TOKEN", value=HF_TOKEN)

…and in app.py, load the LoRA with token=os.environ["HF_TOKEN"].

After upload, run the smoke-test below before sharing — the build runs asynchronously and silent failures (wrong weight_name, missing dep, wrong pipeline class) only surface at first inference. Once the smoke-test passes, share the Space URL (https://huggingface.co/spaces/{repo_id}) and tell the user the Space is private — they'll need to be logged in to view it. Note that the build takes a few minutes; the logs are at https://huggingface.co/spaces/{repo_id}/logs/container if anything fails.

Publish-time failures (before the build starts):

  • HfHubHTTPError: 400 Bad Request from https://huggingface.co/api/validate-yaml during create_repo or upload_file. The README YAML failed server-side validation. By far the most common cause is a short_description that's too long; sometimes a stray field or malformed value. Fix: shorten short_description to ~60 characters and retry. If shortening doesn't fix it, look for typos in field names or invalid values (e.g. unsupported colors in colorFrom/colorTo, an invalid hardware string).
  • 403 on create_repo with space_hardware="zero-a10g": user isn't on PRO/Team/Enterprise, so they can't request ZeroGPU at creation time. Fix: retry create_repo without space_hardware, leave hardware: zero-a10g in the README YAML — the Space gets created on CPU. The user can then either upgrade to PRO (auto-promotes to ZeroGPU) or apply for a community GPU grant (request via the Space's hardware settings).
  • 401/403 on upload_file: token doesn't have write scope. Fix: ask the user for a write-scoped token.

Common build failures (after the build starts):

  • LoRA weight_name mismatch in load_lora_weights → check the actual filename via list_repo_files.
  • Base model is gated and the token wasn't set as a Space secret.
  • ZeroGPU not allocated (user not on PRO) → Space falls back to CPU and is unusably slow.
  • Diffusers version doesn't recognize the pipeline class → pin to git diffusers in requirements.txt.
  • Missing dependency at module load → see requirements.txt derivation rules above; the most common case is a transitive dep like torchvision for Qwen-Image's text encoder.

If a build fails, offer to read the logs and propose a fix.


Phase 6 — Smoke-test the Space

Before declaring the Space done and handing the URL to the user, exercise it once end-to-end. Several failure modes (wrong weight_name, wrong pipeline class, missing transitive dep, gated-base-model token issue) build cleanly and only surface at first inference. The gradio Python package ships a CLI that does exactly this — gradio info returns the endpoint signature, gradio predict runs an actual inference. Both ship with the gradio pip dependency the Space already needs, so they're available in any environment where this skill ran.

Step 1 — Wait for the build. create_repo returns immediately, but the container image is still building. Poll HfApi().get_space_runtime(repo_id).stage until it reaches RUNNING:

import time
from huggingface_hub import HfApi
api = HfApi(token=hf_token)
while True:
    stage = api.get_space_runtime(repo_id).stage
    if stage == "RUNNING": break
    if stage in {"BUILD_ERROR", "RUNTIME_ERROR", "CONFIG_ERROR"}:
        raise RuntimeError(f"Build failed: {stage}. Logs: https://huggingface.co/spaces/{repo_id}/logs/container")
    time.sleep(15)

If the build fails, fetch the container logs (https://huggingface.co/spaces/{repo_id}/logs/container), read the traceback, and propose a fix. Don't run gradio info against a Space that isn't running — it'll hang or 503.

Step 2 — Verify the endpoint signature. gradio info {repo_id} --token {hf_token} returns the exposed endpoints and their parameter types. Read the output and confirm: (a) the endpoint exists (default is /predict, but Blocks Spaces often have a custom name from the Python function name), (b) the parameters in order match what app.py declares, (c) file-typed params show "type": "filepath" as expected. If any of this is off, the user-facing UI may still appear correct but API calls will fail — fix and re-upload.

Step 3 — Run one real inference. Pick the lightest viable input — the simplest example from the LoRA card, or one of the gr.Examples entries. Pass --token for private Spaces. For file inputs, the payload uses {"path": "...", "meta": {"_type": "gradio.FileData"}}.

# Text-to-image:
gradio predict {repo_id} /predict '{"prompt": "...", "aspect_ratio": "1:1", ...}' --token $HF_TOKEN

# Image-to-image (file input):
gradio predict {repo_id} /predict '{"input_image": {"path": "/tmp/sample.jpg", "meta": {"_type": "gradio.FileData"}}, "prompt": "..."}' --token $HF_TOKEN

If you don't have a local sample image for I2I, lift one from the LoRA repo (hf_hub_download(repo_id, filename="example.png")) or the base model card.

Caveat for creative-mode Spaces. gradio info and gradio predict only exercise the Python endpoint — they tell you nothing about whether custom JS in a gr.HTML widget works. If the Space uses creative mode (see references/creative-mode.md), after the API smoke-test passes, open the Space URL in a browser and verify the interaction once before sharing. Server-side green plus broken JS is the most common failure mode for these.

Step 4 — Interpret the result.

  • Returns successfully and the output looks plausible → done. Share the URL.
  • HTTPError 503 / "Space is sleeping" → the Space spun down between steps 1 and 3. Wake it (api.restart_space(repo_id)) and retry.
  • Inference error mentioning weight_name / safetensors → the LoRA filename in app.py doesn't match the actual file in the LoRA repo. Re-check list_repo_files, fix weight_name=, re-upload app.py.
  • Inference error mentioning a missing pipeline class or attribute → diffusers version too old. Switch requirements.txt to git+https://github.com/huggingface/diffusers and re-upload.
  • ImportError at module load → missing dep. Add it to requirements.txt and re-upload. The runtime logs (/logs/run) name the missing package.
  • OOM → reduce default resolution or step count, or pick a smaller base variant.
  • Timeout / hangs → bump @spaces.GPU(duration=...) and re-upload.

The smoke-test exists to convert these from "user discovers it and reports back" to "you discover it and fix it before sharing." Don't skip it because the build went green — green-build-broken-inference is the most common failure mode for Spaces with a non-trivial pipeline.


What to avoid

  • A generic "one demo for all LoRAs" template. The whole point of this skill is to tailor.
  • Lazy-loading the model inside the GPU function. Slow on ZeroGPU, and hides startup errors until first request.
  • torch.compile. Not supported on ZeroGPU.
  • cache_examples=True without cache_mode="lazy" on ZeroGPU.
  • gr.Examples(fn=…) whose inputs don't cover the inference function's required args — builds green, then crashes on the first example click with a missing-positional-argument error.
  • Uploading the LoRA weights into the Space repo. Pull from the LoRA's own Hub repo at runtime.
  • Asking for the HF token only at the end, then discovering the LoRA was private all along and you couldn't read the model card.
  • Exposing every diffusers knob. Pick the 1–3 controls that matter for this LoRA.
  • Long preambles in the chat reply once the Space is published. The Space URL is the deliverable; keep the wrap-up brief.