Spaces:
Running on Zero
gradio workflow app (#1)
Browse files- Add workflow graph: 16 reference inputs -> generate -> gallery + status subjects, example 007 prefill (6efb787f49d4130c4e959ef839e0f95ad4035551)
- Replace demo entry point with gr.Workflow app (node canvas + styled App view) (f1539b30af4e45f532d9ab4b3d7e256eb4b5ef02)
- Add gradio_client dependency for media serialization helpers (aeba2d2e89cfb82127985c5317c8976f216ea2ec)
- README for the Workflow version: parity table, design notes, hf_oauth scopes (4dbd7c78cde6952af9bc81b548c0c2fa34b369e6)
- Add PR description (257f01db4ea8dbe92a27adee1f6f727ea8c5beee)
- Carry over upstream README badge row (homepage, discord, QQ, feishu) so the merge doesn't drop it (82c6b4f536fe04e02e046d0be552f4d8f2024c70)
Co-authored-by: AK <akhaliq@users.noreply.huggingface.co>
Files changed (4)
- README.md+66-73
- app.py+576-36
- requirements.txt+1
- workflow.jsonAdded+191
123451 unmodified line78910111213141516171819 unmodified lines3839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119---title: MOSS Imageemoji: 🖼colorFrom: bluecolorTo: indigo1 unmodified linesdk_version: 6.30.0python_version: "3.12"app_file: app.pypinned: falselicense: apache-2.0short_description: Official demo of MOSS-Image.---# MOSS-Image Demo<p align="center"><a href="https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base"><img alt="Hugging Face · MOSS-Image-Base" src="https://img.shields.io/badge/🤗%20Hugging%20Face-MOSS--Image--Base-ffc107?style=flat-square"></a>19 unmodified lines<a href="https://discord.gg/nXFWEyvbb"><img alt="MOSS-Image Discord Community" src="https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white"></a></p>Gradio interface for [MOSS-Image](https://github.com/OpenMOSS/MOSS-Image),including resolution and aspect-ratio presets, sampling controls, a selectableexample gallery, advanced guidance controls, and live example/default-prompt updates.## Model loadingThe Space preloads **MOSS-Image-Base** and **MOSS-Image-SFT** with`snapshot_download(repo_id, revision=resolved_commit)`, followed by`MOSSImagePipeline.from_pretrained(snapshot_path, local_files_only=True, ...)`.The Space explicitly loads its bundled pipeline, transformer and scheduler classesfrom `pipeline_moss_image.py` for the ZeroGPU AOT lifecycle. The bundled inferenceimplementation follows the current Base pipeline, including negative-branch skippingand standard SLG. Progress is reported using the same bridge as the standalone app.Weights are downloaded into the Hugging Face cache; no local model directoryor model weights in this repository are required.Select **MOSS-Image-Base** or **MOSS-Image-SFT** in the Model dropdown beforeclicking Generate. Base is selected by default. The optional `MOSS_MODEL_ID`Space variable changes this initial selection.Both transformers are loaded at startup. The text encoder, tokenizer and VAEare each shared only when their Hub file hashes match at the resolved revisions.Components that differ, such as model-specific VAEs, are loaded separately. Each model retains its ownscheduler, prompt cache and revision metadata. Generation requests run serially;changing the dropdown does not change an already submitted request.While the model repositories are private, configure an `HF_TOKEN` **Space secret**with read access to both models. Do not put a token in source files orordinary Space variables. Local development uses the same environment variableor your cached Hugging Face login.## ZeroGPUBoth pipelines are loaded and placed on CUDA before the UI starts. Generation runsunder `@spaces.GPU(duration=80)`. At startup, a separate GPU allocation exportsand AOT-compiles the repeated DiT and text-projection blocks with dynamic sequencelengths. Both models reuse the compiled graphs with their own weights. Compilationis validated against eager block outputs before the UI starts. This uses ZeroGPUAOTInductor support, not runtime `torch.compile`; GPU residency is fixed.Set the Space variable `MOSS_AOTI=0` to run the eager baseline. Compilation happensonce per container start and is not part of image generation latency.The 80-second budget is scaled to 120 seconds by the current RTX PRO 6000ZeroGPU SDK configuration; it is not a measured latency guarantee.Large images or batches may require more time or memory than the allocation allows.Outputs and version-2 parameter JSON files are stored under `outputs/gradio/`. Recordsinclude the model repository and resolved revision, actual seed, samplingparameters, component configuration hashes, execution backend, and software versions. Space storageis ephemeral; save generated images you want to keep.## Local development```bashpip install -r requirements.txtpython app.py```To inspect the UI without downloading weights or allocating a GPU:```bashpython app.py --preview --port 7861```The UI and size presets follow the MOSS-Image development repository (main at`8a3223c`). CFG defaults to 3; advanced settings contain CFG, shift and theOff / Negative-branch skipping / Standard SLG modes. Aspect ratios span 1:8–8:1.Examples restore their prompts, sampling settings and seed; unknown seeds becomerandom (-1). Example files and default prompts refresh every two seconds.ZeroGPU keeps the two official model choices, startup preloading, matching-componentsharing and AOT compilation. Memory mode and runtime Compile DiT controls are notshown because GPU residency and compilation are managed at startup. The generationAPI returns the gallery and status, matching the standalone interface.## LicensesModel weights use Apache-2.0. Bundled pipeline code retains its BSD 3-Clauselicense in [LICENSE-CODE](LICENSE-CODE). See [NOTICE.md](NOTICE.md) for componentattribution and the licenses in `third_party/`.123451 unmodified line789101112131415161718192021222324252619 unmodified lines464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112---title: MOSS-Image Workflowemoji: 🖼colorFrom: bluecolorTo: indigo1 unmodified linesdk_version: 6.30.0python_version: "3.12"app_file: app.pyhf_oauth: truehf_oauth_scopes:- inference-api- write-repospinned: falselicense: apache-2.0tags:- ml-internshort_description: MOSS-Image text-to-image as a gr.Workflow node canvas.---[](https://hf.co/chat?mode=ml-intern)# MOSS-Image Workflow<p align="center"><a href="https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base"><img alt="Hugging Face · MOSS-Image-Base" src="https://img.shields.io/badge/🤗%20Hugging%20Face-MOSS--Image--Base-ffc107?style=flat-square"></a>19 unmodified lines<a href="https://discord.gg/nXFWEyvbb"><img alt="MOSS-Image Discord Community" src="https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white"></a></p>A [Gradio Workflow](https://www.gradio.app/guides/workflows) (node-canvas) version of the official[OpenMOSS-Team/MOSS-Image](https://huggingface.co/spaces/OpenMOSS-Team/MOSS-Image) demo, built on`gr.Workflow` in gradio 6.30.0, with the App view styled after the MOSS-Image landing page.## Feature parity with the official demoEvery sampling control of the original Space is a reference node wired into the`MOSS-Image Generate` function node:| Original demo | Here ||---|---|| Model dropdown (Base / SFT) | **Model** reference (`base` or `sft`); both checkpoints loaded at startup || Prompt / Negative Prompt | **Prompt** / **Negative Prompt** references (same default text) || Width × Height (presets) | **Width** / **Height** references (multiples of 16) || Steps / CFG / Shift / Seed | **Steps** / **CFG** / **Shift** / **Seed** references (`-1` = random) || Images per prompt | **Images** reference → gallery output || Max text length | **Max Text Length** reference (1–4096) || Skip-layer modes (Off / Negative-branch skipping / Standard SLG) | **Skip Layers** (`22` = negative-branch skipping, empty = off), **SLG Layers**, **SLG Scale**, **Skip Start**, **Skip Stop** references || Example gallery with one-click restore | **Examples strip** under the hero: the original Space's 20 showcase images, hot-linked; clicking one fetches its `parameters.json` and restores prompt, model, size, sampling and SLG settings into the form |Not ported: showcase add/delete with live refresh (the Workflow App view isgenerated from the graph and has no upload-to-gallery mechanism), and ZeroGPU AOTcompilation (this app runs the eager backend — set it up like the original if youneed the extra speed).## DesignThe App view is auto-generated by `gr.Workflow`, so the landing-page look is appliedthrough `launch(theme=…, css=…, head=…)`: Inter type, a light gradient canvas, theofficial MOSS-Image lockup (light/dark aware) above the"Text-to-Image Generation with Native Layout Control" headline, a top nav withmodel/code links, and a Soft blue theme. The canvas view is untouched.## Running itGeneration runs on GPU via `@spaces.GPU(duration=80)` per node call, so this Space needs**ZeroGPU hardware** (Settings → Hardware). `hf_oauth: true` is enabled so the owner can edit thecanvas and signed-in visitors spend their own ZeroGPU quota; anonymous visitors fall back to thesmall shared allowance.Local development:```bashpip install -r requirements.txtpython app.py # full run, needs a CUDA GPUMOSS_WORKFLOW_PREVIEW=1 python app.py # canvas + styling only, no model download```The bundled `pipeline_moss_image.py` is copied verbatim from the[original Space](https://huggingface.co/spaces/OpenMOSS-Team/MOSS-Image) (BSD 3-Clause); modelweights are Apache-2.0. The lockup artwork is hot-linked from the original Space's assets.The form is prefilled with showcase example 007 (the photorealistic Kazusa ata Tokyo crosswalk: 1184×1776, 50 steps, CFG 3, shift 5, skip layer 22, seed3537712559) so visitors can just hit **Run** and reproduce it exactly. Otherdefaults match the official demo: Euler sampling and negative-branch skipping.## API example```pythonfrom gradio_client import Clientclient = Client("akhaliq/moss-image-workflow")client.view_api() # exact parameters of /generated_images```
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Space entry point. Load both Hub models before serving GPU requests."""import argparseimport loggingimport osimport spaces # Initialize ZeroGPU before importing PyTorch or Diffusers.from gradio_app import (DEFAULT_MODEL, EXAMPLES, MODEL_IDS, UI_ASSETS,ModelRunner, build_app, load_pipeline,)def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--preview", action="store_true", help="Preview UI without downloading weights")parser.add_argument("--port", type=int, default=7860)args = parser.parse_args()logging.basicConfig(level=logging.INFO)model = os.environ.get("MOSS_MODEL_ID", DEFAULT_MODEL)if model not in MODEL_IDS:parser.error("MOSS_MODEL_ID must be OpenMOSS-Team/MOSS-Image-Base or OpenMOSS-Team/MOSS-Image-SFT")runner = ModelRunner("outputs/gradio")if not args.preview:shared_pipe = load_pipeline(model)runner.pipelines[model] = shared_pipefor repo in MODEL_IDS:if repo != model:runner.pipelines[repo] = load_pipeline(repo, shared_pipe=shared_pipe)if os.environ.get("MOSS_AOTI", "1") == "1":from aoti import prepare_aotiprepare_aoti(runner.pipelines.values())demo = build_app(model=model, runner=runner)generate_fn = next(fn for fn in demo.fns.values() if fn.api_name == "generate")logging.info("Generation queue: SPACES_ZERO_GPU=%r, concurrency_limit=%s",os.environ.get("SPACES_ZERO_GPU"), generate_fn.concurrency_limit,)demo.launch(server_name="0.0.0.0", server_port=args.port, share=False,allowed_paths=[str(runner.output_dir), str(EXAMPLES.resolve()), str(UI_ASSETS.resolve())],)if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587"""MOSS-Image as a gr.Workflow app — node-canvas text-to-image pipeline.A reimagining of https://huggingface.co/spaces/OpenMOSS-Team/MOSS-Image as aGradio Workflow (gradio 6.30.0): generation is a bound Python-function node ona drag-and-drop canvas, fed by reference nodes (prompt, size, and everysampling knob of the original demo) and writing into an output-gallery subject.Edit the graph on the canvas or in workflow.json; the App view and REST APIstay in sync automatically.Both checkpoints are loaded once at module scope (ZeroGPU packs and transfersthem when a GPU is actually allocated) and shared by every run of the node."""import osimport secretsimport tempfileimport timefrom collections import OrderedDictfrom pathlib import Path# `spaces` must be imported before anything that initializes CUDA.import spaces # ty: ignore[unresolved-import]from gradio_client import utils as client_utilsimport gradio as grfrom gradio import workflow_api as _wf_api# Workaround for gradio 6.30.0: the App view hands a subject's value to its# output component via `_from_output`, which unwraps a top-level file dict to# its path but leaves dicts nested in a LIST untouched — and gr.Gallery only# accepts path strings, not file dicts. A gallery subject fed by an fn node# (which must return file dicts for the canvas) therefore crashes the App# view. Unwrap list items the same way so both views work._orig_from_output = _wf_api._from_outputdef _from_output_unwrapping_lists(value):if isinstance(value, list):return [_orig_from_output(item) for item in value]return _orig_from_output(value)_wf_api._from_output = _from_output_unwrapping_listsdef _install_component_server_keepalive():"""Keep `/gradio_api/component_server` connections alive during long fn calls.Canvas fn nodes call back through the component_server route — a plainPOST that awaits the bound function synchronously, unlike App-viewendpoints, which run through the queue with SSE heartbeats. A MOSS-Imagegeneration takes 45-130s, and the silent connection is dropped by theproxy chain, surfacing on the canvas as "Connection errored out" (theApp view is unaffected). Wrap the route so it streams whitespaceheartbeat bytes — legal leading whitespace in JSON — until the realresult is ready."""import asyncioimport loggingfrom fastapi import Requestfrom fastapi.dependencies.utils import get_dependantfrom fastapi.routing import APIRoutefrom starlette.responses import StreamingResponsefrom starlette.routing import request_responsefrom gradio.routes import App as _RoutesApporiginal_create_app = _RoutesApp.create_appdef _wrap(endpoint):async def component_server_with_keepalive(request: Request):task = asyncio.create_task(endpoint(request))async def body():try:while not task.done():yield b" "await asyncio.sleep(10)payload = json.dumps(task.result(), default=str).encode()except Exception as exc: # keep the canvas error path readablepayload = json.dumps({"error": str(exc)}).encode()yield payloadreturn StreamingResponse(body(), media_type="application/json")return component_server_with_keepalive@staticmethoddef create_app(blocks, *args, **kwargs):app = original_create_app(blocks, *args, **kwargs)for route in app.routes:if isinstance(route, APIRoute) and route.path.rstrip("/").endswith("/component_server"):route.endpoint = _wrap(route.endpoint)dependant = get_dependant(path=route.path_format, endpoint=route.endpoint)# Keep the route-level dependencies (e.g. Depends(login_check)).dependant.dependencies = (route.dependant.dependencies + dependant.dependencies)route.dependant = dependantroute.app = request_response(route.get_route_handler())logging.getLogger(__name__).info("component_server keep-alive wrapper installed")return app_RoutesApp.create_app = create_app_install_component_server_keepalive()MODEL_IDS = {"base": "OpenMOSS-Team/MOSS-Image-Base","sft": "OpenMOSS-Team/MOSS-Image-SFT",}# Set MOSS_WORKFLOW_PREVIEW=1 to open the canvas without downloading weights# (useful for local UI work on a CPU-only machine).PREVIEW = os.environ.get("MOSS_WORKFLOW_PREVIEW") == "1"def _load_pipeline(model_id, shared_pipe=None):"""Load one MOSS-Image checkpoint with the bundled inference classes.Text encoder, tokenizer and VAE are shared with `shared_pipe` when theirHub file hashes match — this is what keeps both checkpoints inside aZeroGPU worker's GPU memory (two full copies do not fit)."""import torchfrom huggingface_hub import HfApi, snapshot_downloadfrom pipeline_moss_image import (MOSSImagePipeline,MOSSImageScheduler,MOSSImageTransformer,)info = HfApi().model_info(model_id, files_metadata=True)revision = info.shashared_hashes = {item.rfilename: item.lfs.sha256 if item.lfs else item.blob_idfor item in info.siblingsif item.rfilename.startswith(("text_encoder/", "tokenizer/", "vae/"))}components = {}if shared_pipe is not None:for name in ("text_encoder", "tokenizer", "vae"):current = {k: v for k, v in shared_hashes.items() if k.startswith(f"{name}/")}previous = {k: v for k, v in shared_pipe._shared_component_hashes.items()if k.startswith(f"{name}/")}if current and all(current.values()) and current == previous:components[name] = getattr(shared_pipe, name)snapshot = snapshot_download(model_id, revision=revision, ignore_patterns=[f"{name}/*" for name in components])pipe = MOSSImagePipeline.from_pretrained(snapshot,custom_pipeline=str(Path(__file__).with_name("pipeline_moss_image")),trust_remote_code=True,transformer=MOSSImageTransformer.from_pretrained(snapshot, subfolder="transformer", torch_dtype=torch.bfloat16),scheduler=MOSSImageScheduler.from_pretrained(snapshot, subfolder="scheduler"),local_files_only=True,torch_dtype={"default": torch.bfloat16, "vae": torch.float32},**components,)# On ZeroGPU the `spaces` package intercepts this move, packs the weights,# and transfers them when a GPU is allocated — module scope costs no GPU time.pipe.to("cuda")pipe._prompt_cache = OrderedDict()pipe._shared_component_hashes = shared_hashesreturn pipePIPELINES = {}if not PREVIEW:PIPELINES["base"] = _load_pipeline(MODEL_IDS["base"])PIPELINES["sft"] = _load_pipeline(MODEL_IDS["sft"], shared_pipe=PIPELINES["base"])def _as_media(path: str) -> dict:"""The dict shape the workflow canvas renders media from."""return {"path": path,"url": f"/gradio_api/file={client_utils.encode_file_path(path)}","is_file": True,}def _parse_layers(value: str, name: str) -> tuple:"""'22' -> (22,); '' -> (). Same rules as the original demo."""if not (value or "").strip():return ()try:layers = tuple(int(item.strip()) for item in value.split(","))except ValueError:raise gr.Error(f"{name} must be comma-separated integer indices, e.g. 22.") from Noneif any(layer < 0 for layer in layers) or len(set(layers)) != len(layers):raise gr.Error(f"{name} indices must be nonnegative and unique.")return layers@spaces.GPU(duration=80)def generate(prompt: str,negative_prompt: str,model: str,width: float,height: float,steps: float,cfg: float,shift: float,seed: float,num_images: float,max_sequence_length: float,uncond_skip_layers: str,slg_layers: str,slg_scale: float,slg_start: float,slg_stop: float,) -> list:"""Generate images with MOSS-Image (Base or SFT). Full sampling controls."""import torchif PREVIEW:raise gr.Error("Preview mode: models are not loaded (MOSS_WORKFLOW_PREVIEW=1).")if not (prompt or "").strip():raise gr.Error("Enter a prompt.")key = (model or "").strip().lower().replace("moss-image-", "")if key not in PIPELINES:raise gr.Error(f"Unknown model {model!r}. Choose 'base' or 'sft'.")width, height, steps, num_images, max_sequence_length = (round(width), round(height), round(steps), round(num_images),round(max_sequence_length),)seed = round(seed)if width <= 0 or height <= 0 or width % 16 or height % 16:raise gr.Error("Width and height must be positive multiples of 16.")if steps < 1 or num_images < 1:raise gr.Error("Steps and image count must be positive.")if not 0 <= cfg or shift <= 0:raise gr.Error("CFG must be nonnegative; shift must be positive.")if not 1 <= max_sequence_length <= 4096:raise gr.Error("Maximum text length must be between 1 and 4096.")if slg_scale < 0 or not 0 <= slg_start <= slg_stop <= 1:raise gr.Error("Require SLG scale >= 0 and 0 <= SLG start <= SLG stop <= 1.")if seed == -1:seed = secrets.randbelow(2**32)if not 0 <= seed < 2**53:raise gr.Error("Seed must be -1 (random) or an integer from 0 to 2^53 - 1.")pipe = PIPELINES[key]depth = pipe.transformer.config.num_layersskip = _parse_layers(uncond_skip_layers, "Skip layers")slg = _parse_layers(slg_layers, "SLG layers")if any(layer >= depth for layer in skip + slg):raise gr.Error(f"Skip-layer indices must be below {depth}.")pipe.scheduler = type(pipe.scheduler).from_config(pipe.scheduler.config, shift=shift)start = time.monotonic()try:images = pipe(prompt=prompt,negative_prompt=negative_prompt or "",width=width,height=height,num_inference_steps=steps,guidance_scale=float(cfg),num_images_per_prompt=num_images,max_sequence_length=max_sequence_length,uncond_skip_layers=skip,slg_layers=slg,slg_scale=float(slg_scale),slg_start=float(slg_start),slg_stop=float(slg_stop),generator=torch.Generator("cpu").manual_seed(seed),).imagesexcept torch.cuda.OutOfMemoryError as exc:torch.cuda.empty_cache()raise gr.Error("GPU memory exhausted. Try fewer or smaller images.") from excresults = []batch = os.urandom(8).hex()for i, image in enumerate(images):path = os.path.join(tempfile.gettempdir(), f"moss_{batch}_{i + 1:02d}.png")image.save(path)results.append(_as_media(path))elapsed = time.monotonic() - startstatus = (f"{len(results)} image(s) · {MODEL_IDS[key].rsplit('/', 1)[-1]} "f"· seed {seed} · {width}×{height} · {steps} steps "f"· CFG {cfg:g} · shift {shift:g} · {elapsed:.1f}s")# call_fn maps a fn's returned list/tuple onto the node's output PORTS# (one element per port), so the gallery — one port holding many images —# must come back as a single element containing the list: [results].# Returning `results` bare would hand the gallery port only image #1.return [results, status]demo = gr.Workflow(graph=str(Path(__file__).with_name("workflow.json")),bind={"generate": generate},)demo.title = "MOSS-Image"# --- Landing-page styling for the auto-generated App view -------------------# gr.Workflow builds its App view inside #workflow-app; launch() threads# theme/css/head straight through to Blocks.launch(). The hero uses the# official lockup SVGs from the original Space (hot-linked, Apache-2.0)._LOCKUP_LIGHT = ("https://huggingface.co/spaces/OpenMOSS-Team/MOSS-Image""/resolve/main/assets/lockup-light.svg")_LOCKUP_DARK = ("https://huggingface.co/spaces/OpenMOSS-Team/MOSS-Image""/resolve/main/assets/lockup-dark.svg")HEAD = """<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">"""# Custom JS for launch(js=...): the gradio frontend executes this function once# the page is up. A <script> tag in head= is unreliable for this under gradio 6# SSR — the frontend can inject head HTML after the window load event, and# innerHTML-inserted <script> tags never execute.## Two pieces: the top nav, and the examples strip — the original Space's# showcase, hot-linked. Clicking a thumbnail fetches its parameters.json and# restores every field of the generated App-view form, replicating the# original's click-to-restore.JS = """() => {const ORIGIN = "https://huggingface.co/spaces/OpenMOSS-Team/MOSS-Image/resolve/main/assets/images";const IDS = Array.from({length: 20}, (_, i) => String(i + 1).padStart(3, "0"));function setField(prefix, value) {if (value === undefined || value === null) return;const labels = Array.from(document.querySelectorAll('#workflow-app label'));const match = labels.find(l => (l.textContent || "").trim().toLowerCase().startsWith(prefix));if (!match) return;let root = match;for (let i = 0; i < 6 && root; i++) {const input = root.querySelector('input:not([type="hidden"]), textarea');if (input) {input.value = value;input.dispatchEvent(new Event("input", {bubbles: true}));input.dispatchEvent(new Event("change", {bubbles: true}));return;}root = root.parentElement;}}function applyRecord(rec) {const p = rec.parameters || {};let uncond = p.uncond_skip_layers ?? "";let slgLayers = p.slg_layers ?? "";let slgScale = p.slg_scale ?? 0;if ((rec.schema_version ?? 2) === 1) {// v1 records called negative-branch skipping "slg_layers".uncond = (p.slg ?? true) ? (p.slg_layers ?? "") : "";slgLayers = "";slgScale = 0;}const model = (rec.model_repo || rec.model || "").toLowerCase().includes("sft") ? "sft" : "base";setField("negative", p.negative_prompt ?? "");setField("prompt", p.prompt ?? "");setField("model", model);setField("width", p.width);setField("height", p.height);setField("steps", p.steps);setField("cfg", p.cfg);setField("shift", p.shift);setField("seed", p.seed ?? -1);setField("images", p.num_images ?? 1);setField("max text", p.max_sequence_length ?? 4096);setField("skip start", p.slg_start ?? 0);setField("skip stop", p.slg_stop ?? 1);setField("skip layers", uncond);setField("slg layers", slgLayers);setField("slg scale", slgScale);}const recordCache = {};function fetchRecord(id) {if (!recordCache[id]) {recordCache[id] = fetch(`${ORIGIN}/${id}/parameters.json`).then(r => (r.ok ? r.json() : null)).catch(() => null);}return recordCache[id];}function buildStrip(app) {if (document.getElementById('moss-examples')) return true;const wrap = document.createElement('div');wrap.id = 'moss-examples';const title = document.createElement('div');title.className = 'mx-title';title.textContent = 'Examples · click to restore prompt & settings';wrap.appendChild(title);const row = document.createElement('div');row.className = 'mx-row';IDS.forEach((id, i) => {const fig = document.createElement('button');fig.className = 'mx-item';fig.type = 'button';fig.title = 'Load this example into the form';const img = document.createElement('img');img.loading = 'lazy';img.alt = `Example ${i + 1}`;img.src = `${ORIGIN}/${id}/image.webp`;img.onerror = () => fig.remove();fig.appendChild(img);fig.addEventListener('click', () => {fetchRecord(id).then(rec => { if (rec) applyRecord(rec); });});row.appendChild(fig);});wrap.appendChild(row);app.prepend(wrap);return true;}if (!document.getElementById('moss-nav')) {const nav = document.createElement('nav');nav.id = 'moss-nav';nav.innerHTML = `<span class="moss-brand">MOSS-Image</span><span class="moss-links"><a href="https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base" target="_blank" rel="noopener">Base</a><a href="https://huggingface.co/OpenMOSS-Team/MOSS-Image-SFT" target="_blank" rel="noopener">SFT</a><a href="https://huggingface.co/spaces/OpenMOSS-Team/MOSS-Image" target="_blank" rel="noopener">Original Demo</a><a href="https://github.com/OpenMOSS/MOSS-Image" target="_blank" rel="noopener">GitHub ↗</a></span>`;document.body.prepend(nav);}// #workflow-app appears when the frontend mounts; poll briefly for it.let tries = 0;const timer = setInterval(() => {const app = document.getElementById('workflow-app');if ((app && buildStrip(app)) || ++tries > 75) clearInterval(timer);}, 400);}"""CSS = f"""body, .gradio-container {{font-family: 'Inter', ui-sans-serif, system-ui, sans-serif !important;}}.gradio-container {{background: linear-gradient(180deg, #eef3fc 0%, #ffffff 460px) !important;}}.dark .gradio-container {{background: linear-gradient(180deg, #0d1526 0%, #0b0f19 460px) !important;}}#moss-nav {{display: flex;align-items: center;justify-content: space-between;padding: 14px 24px 0;max-width: 1200px;margin: 0 auto;font-size: 14px;}}#moss-nav .moss-brand {{font-weight: 800;font-size: 16px;letter-spacing: -0.01em;background: linear-gradient(90deg, #3b7fe0, #4aa5f2, #7fe6fb);-webkit-background-clip: text;background-clip: text;color: transparent;}}#moss-nav .moss-links a {{color: #475569;text-decoration: none;font-weight: 500;margin-left: 22px;}}#moss-nav .moss-links a:hover {{ color: #2563eb; }}.dark #moss-nav .moss-links a {{ color: #94a3b8; }}.dark #moss-nav .moss-links a:hover {{ color: #7fe6fb; }}#workflow-app::before {{content: "MOSS-Image: Text-to-Image Generation\\Awith Native Layout Control";white-space: pre-wrap;display: block;text-align: center;font-weight: 800;font-size: clamp(24px, 4.2vw, 40px);line-height: 1.15;letter-spacing: -0.02em;color: #0b1220;max-width: 860px;margin: 0 auto 12px;padding: 158px 16px 26px;background: url("{_LOCKUP_LIGHT}") no-repeat top 26px center / min(480px, 78%) auto;}}.dark #workflow-app::before {{color: #f1f5f9;background-image: url("{_LOCKUP_DARK}");}}#workflow-app::after {{content: "Models by the OpenMOSS Team · MOSS-Image-Base & MOSS-Image-SFT (Apache-2.0) · Rebuilt as a Gradio Workflow";display: block;text-align: center;font-size: 13px;color: #64748b;padding: 8px 16px 36px;}}.dark #workflow-app::after {{ color: #94a3b8; }}/* Examples strip (injected by the head script; hot-linked from the original Space). */#moss-examples {{max-width: 960px;margin: 0 auto 18px;padding: 0 16px;}}#moss-examples .mx-title {{text-align: center;font-size: 13px;font-weight: 600;letter-spacing: 0.02em;color: #64748b;margin-bottom: 10px;}}.dark #moss-examples .mx-title {{ color: #94a3b8; }}#moss-examples .mx-row {{display: flex;gap: 10px;overflow-x: auto;padding-bottom: 6px;scrollbar-width: thin;}}#moss-examples .mx-item {{flex: 0 0 auto;height: 128px;padding: 0;border: 2px solid transparent;border-radius: 12px;overflow: hidden;cursor: pointer;background: #e2e8f0;transition: border-color 0.15s ease, transform 0.15s ease;}}#moss-examples .mx-item:hover {{border-color: #2563eb;transform: translateY(-2px);}}#moss-examples .mx-item img {{height: 128px;width: auto;display: block;}}/* Soften the generated form into landing-page cards. */#workflow-app .form, #workflow-app .panel, #workflow-app .block {{border-radius: 14px !important;}}#workflow-app button.primary, #workflow-app button.lg {{border-radius: 10px !important;}}"""if __name__ == "__main__":demo.launch(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"),css=CSS,head=HEAD,js=JS,)
5 unmodified lines6785 unmodified linesPillow>=10spaces>=0.51.3,<0.52gradio==6.30.05 unmodified lines67895 unmodified linesPillow>=10spaces>=0.51.3,<0.52gradio==6.30.0gradio_client>=1.13
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191{ "schema_version": "2", "name": "MOSS-Image Text-to-Image", "references": [ { "id": "ref_prompt", "label": "Prompt", "role": "reference", "asset_type": "text", "inputs": [{"id": "in", "label": "Text", "type": "text"}], "outputs": [{"id": "out", "label": "Text", "type": "text"}], "x": 60, "y": 60, "width": 280, "data": {"out": "A young anime woman, Kazusa from Blue Archive, stands still at the edge of a crowded Tokyo crosswalk outside a busy train station on a damp, overcast dusk. Her short dark hair with soft magenta inner highlights frames her face, cat ears perked slightly beneath her distinctive glowing pink halo. She wears an oversized charcoal wool coat over a beige knit hoodie, a short pleated black skirt, black crew socks, and scuffed loafers, with a canvas tote bag slung over her shoulder. She holds a wired earphone in one hand as if pausing her music, looking slightly sideways with a quiet, unguarded expression while the evening rush hour flows around her.\n\nIn the immediate foreground, a heavily motion-blurred commuter in a dark coat walks right past the lens, partially framing the edge of the shot and giving it the raw, accidental feel of a candid street photograph. Around and behind Kazusa, a bustling crowd of out-of-focus pedestrians moves across the wet asphalt crosswalk under the muted glow of neon department store signs, traffic signals, and concrete office buildings. The image blends Kazusa’s anime appearance seamlessly into a gritty, photorealistic modern city environment, using natural ambient dusk lighting, shallow depth of field, motion blur on the passing crowd, muted cool tones, and a cinematic sense of stillness amid urban chaos."} }, { "id": "ref_negative", "label": "Negative Prompt", "role": "reference", "asset_type": "text", "inputs": [{"id": "in", "label": "Text", "type": "text"}], "outputs": [{"id": "out", "label": "Text", "type": "text"}], "x": 60, "y": 250, "width": 280, "data": {"out": "watermark, bad anatomy"} }, { "id": "ref_model", "label": "Model (base or sft)", "role": "reference", "asset_type": "text", "inputs": [{"id": "in", "label": "Text", "type": "text"}], "outputs": [{"id": "out", "label": "Text", "type": "text"}], "x": 60, "y": 440, "width": 280, "data": {"out": "base"} }, { "id": "ref_width", "label": "Width", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 400, "y": 60, "width": 200, "data": {"out": 1184} }, { "id": "ref_height", "label": "Height", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 400, "y": 210, "width": 200, "data": {"out": 1776} }, { "id": "ref_steps", "label": "Steps", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 400, "y": 360, "width": 200, "data": {"out": 50} }, { "id": "ref_cfg", "label": "CFG", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 400, "y": 510, "width": 200, "data": {"out": 3} }, { "id": "ref_shift", "label": "Shift", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 400, "y": 660, "width": 200, "data": {"out": 5} }, { "id": "ref_seed", "label": "Seed (-1 = random)", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 60, "y": 630, "width": 200, "data": {"out": 3537712559} }, { "id": "ref_num_images", "label": "Images", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 60, "y": 790, "width": 200, "data": {"out": 1} }, { "id": "ref_max_seq", "label": "Max Text Length", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 660, "y": 60, "width": 200, "data": {"out": 4096} }, { "id": "ref_uncond_skip", "label": "Skip Layers (uncond, empty = off)", "role": "reference", "asset_type": "text", "inputs": [{"id": "in", "label": "Text", "type": "text"}], "outputs": [{"id": "out", "label": "Text", "type": "text"}], "x": 660, "y": 210, "width": 200, "data": {"out": "22"} }, { "id": "ref_slg_layers", "label": "SLG Layers (empty = off)", "role": "reference", "asset_type": "text", "inputs": [{"id": "in", "label": "Text", "type": "text"}], "outputs": [{"id": "out", "label": "Text", "type": "text"}], "x": 660, "y": 360, "width": 200, "data": {"out": ""} }, { "id": "ref_slg_scale", "label": "SLG Scale", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 660, "y": 510, "width": 200, "data": {"out": 0} }, { "id": "ref_slg_start", "label": "Skip Start", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 660, "y": 660, "width": 200, "data": {"out": 0} }, { "id": "ref_slg_stop", "label": "Skip Stop", "role": "reference", "asset_type": "number", "inputs": [{"id": "in", "label": "Number", "type": "number"}], "outputs": [{"id": "out", "label": "Number", "type": "number"}], "x": 660, "y": 810, "width": 200, "data": {"out": 1} }, { "id": "ref_example_image", "label": "Example 007 Result (prefill target)", "role": "reference", "asset_type": "image", "inputs": [{"id": "in", "label": "Image", "type": "image"}], "outputs": [{"id": "out", "label": "Image", "type": "image"}], "x": 1300, "y": 60, "width": 340, "data": {"out": {"url": "https://huggingface.co/spaces/OpenMOSS-Team/MOSS-Image/resolve/main/assets/images/007/image.webp", "name": "image.webp", "mime": "image/webp"}} } ], "operators": [ { "id": "op_generate", "label": "MOSS-Image Generate", "role": "operator", "kind": "fn", "fn": "generate", "inputs": [ {"id": "prompt", "label": "Prompt", "type": "text", "required": true}, {"id": "negative_prompt", "label": "Negative Prompt", "type": "text", "required": false}, {"id": "model", "label": "Model", "type": "text", "required": true}, {"id": "width", "label": "Width", "type": "number", "required": true}, {"id": "height", "label": "Height", "type": "number", "required": true}, {"id": "steps", "label": "Steps", "type": "number", "required": true}, {"id": "cfg", "label": "CFG", "type": "number", "required": true}, {"id": "shift", "label": "Shift", "type": "number", "required": true}, {"id": "seed", "label": "Seed", "type": "number", "required": true}, {"id": "num_images", "label": "Images", "type": "number", "required": true}, {"id": "max_sequence_length", "label": "Max Text Length", "type": "number", "required": true}, {"id": "uncond_skip_layers", "label": "Skip Layers", "type": "text", "required": false}, {"id": "slg_layers", "label": "SLG Layers", "type": "text", "required": false}, {"id": "slg_scale", "label": "SLG Scale", "type": "number", "required": true}, {"id": "slg_start", "label": "Skip Start", "type": "number", "required": true}, {"id": "slg_stop", "label": "Skip Stop", "type": "number", "required": true} ], "outputs": [ {"id": "out_0", "label": "Images", "type": "gallery"}, {"id": "out_1", "label": "Status", "type": "text"} ], "x": 940, "y": 380, "width": 280, "data": {} } ], "subjects": [ { "id": "sub_gallery", "label": "Generated Images", "role": "subject", "asset_type": "gallery", "inputs": [{"id": "in", "label": "Images", "type": "gallery"}], "outputs": [{"id": "out", "label": "Images", "type": "gallery"}], "x": 1300, "y": 380, "width": 340, "data": {} }, { "id": "sub_status", "label": "Status", "role": "subject", "asset_type": "text", "inputs": [{"id": "in", "label": "Status", "type": "text"}], "outputs": [{"id": "out", "label": "Status", "type": "text"}], "x": 1300, "y": 620, "width": 340, "data": {} } ], "edges": [ {"id": "e_prompt", "from_node_id": "ref_prompt", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "prompt", "type": "text"}, {"id": "e_negative", "from_node_id": "ref_negative", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "negative_prompt", "type": "text"}, {"id": "e_model", "from_node_id": "ref_model", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "model", "type": "text"}, {"id": "e_width", "from_node_id": "ref_width", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "width", "type": "number"}, {"id": "e_height", "from_node_id": "ref_height", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "height", "type": "number"}, {"id": "e_steps", "from_node_id": "ref_steps", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "steps", "type": "number"}, {"id": "e_cfg", "from_node_id": "ref_cfg", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "cfg", "type": "number"}, {"id": "e_shift", "from_node_id": "ref_shift", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "shift", "type": "number"}, {"id": "e_seed", "from_node_id": "ref_seed", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "seed", "type": "number"}, {"id": "e_num_images", "from_node_id": "ref_num_images", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "num_images", "type": "number"}, {"id": "e_max_seq", "from_node_id": "ref_max_seq", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "max_sequence_length", "type": "number"}, {"id": "e_uncond_skip", "from_node_id": "ref_uncond_skip", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "uncond_skip_layers", "type": "text"}, {"id": "e_slg_layers", "from_node_id": "ref_slg_layers", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "slg_layers", "type": "text"}, {"id": "e_slg_scale", "from_node_id": "ref_slg_scale", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "slg_scale", "type": "number"}, {"id": "e_slg_start", "from_node_id": "ref_slg_start", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "slg_start", "type": "number"}, {"id": "e_slg_stop", "from_node_id": "ref_slg_stop", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "slg_stop", "type": "number"}, {"id": "e_gallery", "from_node_id": "op_generate", "from_port_id": "out_0", "to_node_id": "sub_gallery", "to_port_id": "in", "type": "gallery"}, {"id": "e_status", "from_node_id": "op_generate", "from_port_id": "out_1", "to_node_id": "sub_status", "to_port_id": "in", "type": "text"} ]}