Spaces:
Runtime error
Runtime error
Add quality model option and streamline blocked-content handling
Browse filesAdds a Fast/Quality model selector (Mage-Flow-Turbo vs Mage-Flow) with per-task lazy pipeline swapping and recommended step/CFG defaults. Blocked requests now return a plain blank image.
Files changed (3)
- README.md+5-5
- app.py+66-71
- mage_flow/pipeline.py-2
16 unmodified lines1718192021222324252627282930313233343516 unmodified linesThis Space demonstrates [Mage-Flow](https://huggingface.co/papers/2607.19064) from Microsoft, a 4B-scale image generation and editing foundation model through a single unified interface:- **No image** → the prompt generates a new image (routes to [Mage-Flow-Turbo](https://huggingface.co/microsoft/Mage-Flow-Turbo)).- **With an uploaded image** → the prompt is treated as an edit instruction (routes to [Mage-Flow-Edit-Turbo](https://huggingface.co/microsoft/Mage-Flow-Edit-Turbo)).The demo uses the Turbo variants for fast, few-step inference (4 steps, CFG 1.0).## Usage1. Enter a prompt.2. *(Optional)* Upload an image to edit — the prompt becomes an edit instruction.3. Click **Run**.## References- Paper: [Mage-Flow: An Efficient Native-Resolution Foundation Model for Image Generation and Editing](https://huggingface.co/papers/2607.19064)- GitHub: [microsoft/Mage](https://github.com/microsoft/Mage)- Models: [microsoft/Mage-Flow-Turbo](https://huggingface.co/microsoft/Mage-Flow-Turbo), [microsoft/Mage-Flow-Edit-Turbo](https://huggingface.co/microsoft/Mage-Flow-Edit-Turbo)16 unmodified lines1718192021222324252627282930313233343516 unmodified linesThis Space demonstrates [Mage-Flow](https://huggingface.co/papers/2607.19064) from Microsoft, a 4B-scale image generation and editing foundation model through a single unified interface:- **No image** → text-to-image generation.- **With an uploaded image** → instruction-based image editing.Choose **Mage-Flow-Turbo · Fast** (4 steps, CFG 1.0) or **Mage-Flow · Quality**. The quality variant uses 20 steps / CFG 5.0 for generation and 30 steps / CFG 5.0 for editing; uploading or removing an image updates these defaults automatically.## Usage1. Enter a prompt.2. *(Optional)* Upload an image to edit — the prompt becomes an edit instruction.3. Choose Fast or Quality, then click **Run**.## References- Paper: [Mage-Flow: An Efficient Native-Resolution Foundation Model for Image Generation and Editing](https://huggingface.co/papers/2607.19064)- GitHub: [microsoft/Mage](https://github.com/microsoft/Mage)- Models: [Mage-Flow](https://huggingface.co/microsoft/Mage-Flow), [Mage-Flow-Turbo](https://huggingface.co/microsoft/Mage-Flow-Turbo), [Mage-Flow-Edit](https://huggingface.co/microsoft/Mage-Flow-Edit), [Mage-Flow-Edit-Turbo](https://huggingface.co/microsoft/Mage-Flow-Edit-Turbo)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172734 unmodified lines7879808182838485868788899011 unmodified lines1021031041051061071081091101111121131141151161171181197 unmodified lines12712812913013113213313413513613713813920 unmodified lines16016116216316416516612 unmodified lines17918018118218318447 unmodified lines232233234235236237238"""Mage-Flow: Efficient Native-Resolution Foundation Model for Image Generation and Editing.Gradio Space demo with a single unified interface: enter a prompt and optionallyupload an image. If an image is provided, the request is routed to theMage-Flow-Edit-Turbo model; otherwise it is routed to the Mage-Flow-Turbo model."""import os# Use flash_attention_2 for the HF text encoder (flash_attn is installed via wheel)os.environ.setdefault("VF_HF_ATTN_IMPL", "flash_attention_2")import textwrapimport spaces # MUST be first (after env setup)import torchimport gradio as grfrom PIL import Image, ImageDraw, ImageFontfrom mage_flow.pipeline import MageFlowPipelinefrom mage_flow.models.modules.mage_text import CATEGORY_DISPLAYT2I_MODEL = "microsoft/Mage-Flow-Turbo"EDIT_MODEL = "microsoft/Mage-Flow-Edit-Turbo"pipe_t2i = MageFlowPipeline.from_pretrained(T2I_MODEL, device="cuda")pipe_edit = MageFlowPipeline.from_pretrained(EDIT_MODEL, device="cuda")def _block_reason_text(verdict) -> str:"""Human-readable block reason: '<category> · <explanation>'."""cat = ", ".join(CATEGORY_DISPLAY.get(c, c) for c in verdict.categories) or "policy violation"reason = (verdict.reason or "").strip()return f"{cat} · {reason}" if reason else catdef _blocked_image(reason_text: str, height: int = 1024, width: int = 1024) -> Image.Image:"""Neutral background image with the safety-filter message drawn on it."""img = Image.new("RGB", (int(width), int(height)), color=(245, 245, 245))draw = ImageDraw.Draw(img)try:font = ImageFont.load_default(size=28)except TypeError: # older Pillow: load_default() takes no sizefont = ImageFont.load_default()message = ("The classifiers included by default in the Microsoft Mage Flow model flagged the following:\n\n" + reason_text)# Wrap each paragraph to a column width that fits the image.max_chars = max(20, int(width / 16))lines = []for para in message.split("\n"):if not para:lines.append("")continuelines.extend(textwrap.wrap(para, width=max_chars))# Vertically center the text block.line_h = 38total_h = line_h * len(lines)y = max(20, (int(height) - total_h) // 2)for line in lines:draw.text((40, y), line, fill=(20, 20, 20), font=font)y += line_hreturn img@spaces.GPU(duration=60)def generate(prompt: str,image=None,4 unmodified lineswidth: int = 1024,max_size: int = 1024,seed: int = 42,progress=gr.Progress(track_tqdm=True),):"""Generate or edit an image with Mage-Flow.If ``image`` is provided, the reference image is edited withMage-Flow-Edit-Turbo. Otherwise a new image is generated from the textprompt with Mage-Flow-Turbo.Args:prompt: Text description (generation) or edit instruction (editing).11 unmodified linesif image is not None:# Route to the edit model when an image is provided.if isinstance(image, str):image = Image.open(image)refs = [image.convert("RGB")]# Content-safety gate: surface a block to the user instead of failing# silently (gr.Warning toast + a stamped output image).verdict = pipe_edit.model.txt_enc.screen_edit(prompt, refs)if verdict.violates:reason_text = _block_reason_text(verdict)gr.Warning("The classifiers included by default in the Microsoft Mage Flow model flagged the following: " + reason_text)w, h = refs[0].sizereturn _blocked_image(reason_text, height=h, width=w)out = pipe_edit.edit([prompt],7 unmodified linesreturn out# No image: route to the text-to-image model.# Content-safety gate: surface a block to the user instead of failing# silently (gr.Warning toast + a stamped output image).verdict = pipe_t2i.model.txt_enc.screen_text(prompt)if verdict.violates:reason_text = _block_reason_text(verdict)gr.Warning("The classifiers included by default in the Microsoft Mage Flow model flagged the following: " + reason_text)return _blocked_image(reason_text, height=int(height), width=int(width))img = pipe_t2i.generate([prompt],20 unmodified lines"# Mage-Flow\n""Efficient Native-Resolution Foundation Model for Image Generation and Editing. ""Enter a prompt to generate an image, or upload an image to edit it.\n\n""Models: [Mage-Flow-Turbo](https://huggingface.co/microsoft/Mage-Flow-Turbo) & ""[Mage-Flow-Edit-Turbo](https://huggingface.co/microsoft/Mage-Flow-Edit-Turbo) | ""[Paper](https://huggingface.co/papers/2607.19064) | ""[GitHub](https://github.com/microsoft/Mage)"12 unmodified lines)run_btn = gr.Button("Run", variant="primary", scale=1)with gr.Accordion("Input image (optional — enables editing)", open=True):image = gr.Image(type="pil",47 unmodified linescache_mode="lazy",)inputs = [prompt, image, negative_prompt, steps, cfg, height, width, max_size, seed]run_btn.click(lambda: None, None, result).then(generate, inputs, result, api_name="generate",)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061624 unmodified lines6768697071727374757677787911 unmodified lines9192939495969798991001011021031041051067 unmodified lines11411511611711811912012112212312420 unmodified lines14514614714814915015115215312 unmodified lines16616716816917017117217317417517647 unmodified lines224225226227228229230231232233"""Mage-Flow: Efficient Native-Resolution Foundation Model for Image Generation and Editing.Gradio Space demo with a single unified interface: image presence selectsediting vs. generation, while the model control selects fast vs. quality."""import gcimport osimport threading# Use flash_attention_2 for the HF text encoder (flash_attn is installed via wheel)os.environ.setdefault("VF_HF_ATTN_IMPL", "flash_attention_2")import spaces # MUST be first (after env setup)import torchimport gradio as grfrom PIL import Imagefrom mage_flow.pipeline import MageFlowPipelineMODEL_VARIANTS = {"turbo": {"t2i": "microsoft/Mage-Flow-Turbo", "edit": "microsoft/Mage-Flow-Edit-Turbo","t2i_steps": 4, "edit_steps": 4, "cfg": 1.0,},"quality": {"t2i": "microsoft/Mage-Flow", "edit": "microsoft/Mage-Flow-Edit","t2i_steps": 20, "edit_steps": 30, "cfg": 5.0,},}_pipe_slots = {"t2i": {"variant": "turbo", "pipe": MageFlowPipeline.from_pretrained(MODEL_VARIANTS["turbo"]["t2i"], device="cuda")},"edit": {"variant": "turbo", "pipe": MageFlowPipeline.from_pretrained(MODEL_VARIANTS["turbo"]["edit"], device="cuda")},}_pipe_lock = threading.Lock()def _get_pipe(task: str, variant: str):"""Keep one loaded variant per task, matching the original two-pipeline footprint."""with _pipe_lock:slot = _pipe_slots.get(task)if slot and slot["variant"] == variant:return slot["pipe"]if slot:del _pipe_slots[task]del slotgc.collect()torch.cuda.empty_cache()pipe = MageFlowPipeline.from_pretrained(MODEL_VARIANTS[variant][task], device="cuda")_pipe_slots[task] = {"variant": variant, "pipe": pipe}return pipedef _recommended(variant: str, image):spec = MODEL_VARIANTS[variant]return (spec["edit_steps"] if image is not None else spec["t2i_steps"], spec["cfg"])@spaces.GPU(duration=120)def generate(prompt: str,image=None,4 unmodified lineswidth: int = 1024,max_size: int = 1024,seed: int = 42,model_variant: str = "turbo",progress=gr.Progress(track_tqdm=True),):"""Generate or edit an image with Mage-Flow.If ``image`` is provided, route to the selected edit model; otherwise routeto the selected text-to-image model.Args:prompt: Text description (generation) or edit instruction (editing).11 unmodified linesif image is not None:# Route to the edit model when an image is provided.pipe_edit = _get_pipe("edit", model_variant)if isinstance(image, str):image = Image.open(image)refs = [image.convert("RGB")]# Content-safety gate: blocked requests return a blank image.verdict = pipe_edit.model.txt_enc.screen_edit(prompt, refs)if verdict.violates:w, h = refs[0].sizereturn Image.new("RGB", (w, h), (255, 255, 255))out = pipe_edit.edit([prompt],7 unmodified linesreturn out# No image: route to the text-to-image model.# Content-safety gate: blocked requests return a blank image.pipe_t2i = _get_pipe("t2i", model_variant)verdict = pipe_t2i.model.txt_enc.screen_text(prompt)if verdict.violates:return Image.new("RGB", (int(width), int(height)), (255, 255, 255))img = pipe_t2i.generate([prompt],20 unmodified lines"# Mage-Flow\n""Efficient Native-Resolution Foundation Model for Image Generation and Editing. ""Enter a prompt to generate an image, or upload an image to edit it.\n\n""Models: [Mage-Flow](https://huggingface.co/microsoft/Mage-Flow), ""[Mage-Flow-Turbo](https://huggingface.co/microsoft/Mage-Flow-Turbo), ""[Mage-Flow-Edit](https://huggingface.co/microsoft/Mage-Flow-Edit), ""[Mage-Flow-Edit-Turbo](https://huggingface.co/microsoft/Mage-Flow-Edit-Turbo) | ""[Paper](https://huggingface.co/papers/2607.19064) | ""[GitHub](https://github.com/microsoft/Mage)"12 unmodified lines)run_btn = gr.Button("Run", variant="primary", scale=1)model_variant = gr.Radio([("Mage-Flow-Turbo · Fast", "turbo"), ("Mage-Flow · Quality", "quality")],value="turbo", label="Model",)with gr.Accordion("Input image (optional — enables editing)", open=True):image = gr.Image(type="pil",47 unmodified linescache_mode="lazy",)model_variant.change(_recommended, [model_variant, image], [steps, cfg], api_name=False)image.change(_recommended, [model_variant, image], [steps, cfg], api_name=False)inputs = [prompt, image, negative_prompt, steps, cfg, height, width, max_size, seed, model_variant]run_btn.click(lambda: None, None, result).then(generate, inputs, result, api_name="generate",)
285 unmodified lines286287288289290291292184 unmodified lines477478479480481482483285 unmodified linesverdict = model.txt_enc.screen_text(prompts[i])if verdict.violates:h_, w_ = _make_divisible_by_16(heights[i]), _make_divisible_by_16(widths[i])print(verdict.banner())results[i] = make_refusal_image(verdict, height=h_, width=w_)continueactive.append(i)184 unmodified linesverdict = model.txt_enc.screen_edit(prompts[i], pils_per_sample[i])if verdict.violates:h_, w_ = res_hw[i]print(verdict.banner())results[i] = make_refusal_image(verdict, height=h_, width=w_)continueactive.append(i)285 unmodified lines286287288289290291184 unmodified lines476477478479480481285 unmodified linesverdict = model.txt_enc.screen_text(prompts[i])if verdict.violates:h_, w_ = _make_divisible_by_16(heights[i]), _make_divisible_by_16(widths[i])results[i] = make_refusal_image(verdict, height=h_, width=w_)continueactive.append(i)184 unmodified linesverdict = model.txt_enc.screen_edit(prompts[i], pils_per_sample[i])if verdict.violates:h_, w_ = res_hw[i]results[i] = make_refusal_image(verdict, height=h_, width=w_)continueactive.append(i)
README.md+5-5
app.py+66-71
mage_flow/pipeline.py-2