ajh-code commited on
Commit
93cc2db
·
verified ·
1 Parent(s): daa0579

Add vendor/mage_flow/app.py

Browse files
Files changed (1) hide show
  1. vendor/mage_flow/app.py +199 -0
vendor/mage_flow/app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio app for MageFlow — text-to-image and instruction-based image editing.
2
+
3
+ python app.py # serve on 0.0.0.0:7860
4
+ python app.py --share --port 7861
5
+
6
+ Each tab has a model preset dropdown (base / rl / turbo) plus a free-form
7
+ "Custom model" box for any Hugging Face repo id or local path. Models load
8
+ lazily on first use and are cached. Notes:
9
+ - By default the presets point at the `microsoft/Mage-Flow*` Hugging Face
10
+ repos (downloaded + cached on first use). Set ``MAGEFLOW_HF_DIR`` to load
11
+ local checkpoint dirs instead.
12
+ - Turbo checkpoints are few-step: use steps=4, cfg=1.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import os
18
+
19
+ import gradio as gr
20
+ from PIL import Image
21
+
22
+ from mage_flow.pipeline import MageFlowPipeline
23
+
24
+ # Default to Hugging Face repo ids; if MAGEFLOW_HF_DIR is set, use local
25
+ # checkpoint dirs under it instead (local dir names match the HF repo basename).
26
+ HF_DIR = os.environ.get("MAGEFLOW_HF_DIR")
27
+
28
+
29
+ def _repo(hf_id: str, local_name: str) -> str:
30
+ return f"{HF_DIR}/{local_name}" if HF_DIR else hf_id
31
+
32
+
33
+ T2I_MODELS = {
34
+ "base": _repo("microsoft/Mage-Flow-Base", "Mage-Flow-Base"),
35
+ "rl": _repo("microsoft/Mage-Flow", "Mage-Flow"),
36
+ "turbo": _repo("microsoft/Mage-Flow-Turbo", "Mage-Flow-Turbo"),
37
+ }
38
+ EDIT_MODELS = {
39
+ "base": _repo("microsoft/Mage-Flow-Edit-Base", "Mage-Flow-Edit-Base"),
40
+ "rl": _repo("microsoft/Mage-Flow-Edit", "Mage-Flow-Edit"),
41
+ "turbo": _repo("microsoft/Mage-Flow-Edit-Turbo", "Mage-Flow-Edit-Turbo"),
42
+ }
43
+
44
+ DEVICE = "cuda"
45
+ _CACHE: dict[str, MageFlowPipeline] = {}
46
+
47
+
48
+ def _get_pipe(repo: str) -> MageFlowPipeline:
49
+ """Load (and cache) a pipeline from a local dir OR a Hugging Face repo id.
50
+
51
+ ``MageFlowPipeline.from_pretrained`` resolves a repo id via
52
+ ``snapshot_download`` automatically, so both are accepted here.
53
+ """
54
+ repo = (repo or "").strip()
55
+ if not repo:
56
+ raise gr.Error("No model specified.")
57
+ if repo not in _CACHE:
58
+ try:
59
+ _CACHE[repo] = MageFlowPipeline.from_pretrained(repo, device=DEVICE)
60
+ except Exception as e: # noqa: BLE001
61
+ raise gr.Error(f"Failed to load model '{repo}': {type(e).__name__}: {e}")
62
+ return _CACHE[repo]
63
+
64
+
65
+ def _resolve(preset_map, model_key, custom_model):
66
+ """Custom repo id / path (if given) overrides the preset dropdown."""
67
+ return (custom_model or "").strip() or preset_map[model_key]
68
+
69
+
70
+ def run_t2i(model_key, custom_model, prompt, neg_prompt, steps, cfg, height, width, seed,
71
+ progress=gr.Progress(track_tqdm=False)):
72
+ if not (prompt or "").strip():
73
+ raise gr.Error("Prompt is empty.")
74
+ repo = _resolve(T2I_MODELS, model_key, custom_model)
75
+ progress(0.1, desc=f"loading {repo} …")
76
+ pipe = _get_pipe(repo)
77
+ progress(0.4, desc="generating …")
78
+ img = pipe.generate(
79
+ [prompt], neg_prompts=[neg_prompt or " "], seeds=[int(seed)],
80
+ steps=int(steps), cfg=float(cfg),
81
+ heights=[int(height)], widths=[int(width)],
82
+ )[0]
83
+ return img
84
+
85
+
86
+ def run_edit(model_key, custom_model, prompt, neg_prompt, ref_img, extra_files, steps, cfg, max_size, seed,
87
+ progress=gr.Progress(track_tqdm=False)):
88
+ if not (prompt or "").strip():
89
+ raise gr.Error("Edit instruction is empty.")
90
+ refs = []
91
+ if ref_img is not None:
92
+ refs.append(ref_img if isinstance(ref_img, Image.Image) else Image.open(ref_img))
93
+ for f in (extra_files or []):
94
+ refs.append(Image.open(f).convert("RGB"))
95
+ if not refs:
96
+ raise gr.Error("Upload at least one reference image.")
97
+ refs = [r.convert("RGB") for r in refs]
98
+ repo = _resolve(EDIT_MODELS, model_key, custom_model)
99
+ progress(0.1, desc=f"loading {repo} …")
100
+ pipe = _get_pipe(repo)
101
+ progress(0.4, desc="editing …")
102
+ out = pipe.edit(
103
+ [prompt], [refs], neg_prompts=[neg_prompt or " "], seeds=[int(seed)],
104
+ steps=int(steps), cfg=float(cfg),
105
+ max_size=int(max_size) if max_size else None,
106
+ )[0]
107
+ return out
108
+
109
+
110
+ _NOTE = (
111
+ "Pick a **preset** (base / rl / turbo) or type a **custom model** — any "
112
+ "Hugging Face repo id (e.g. `microsoft/Mage-Flow-Turbo`) or local path; it "
113
+ "is downloaded and cached on first use. **Turbo** models are few-step: set "
114
+ "**steps=4, cfg=1**."
115
+ )
116
+
117
+ _CUSTOM_PH_T2I = "microsoft/Mage-Flow (repo id or local path — overrides preset)"
118
+ _CUSTOM_PH_EDIT = "microsoft/Mage-Flow-Edit (repo id or local path — overrides preset)"
119
+
120
+
121
+ def build_ui():
122
+ with gr.Blocks(title="MageFlow") as demo:
123
+ gr.Markdown("# MageFlow\nText-to-image generation and instruction-based image editing.")
124
+ gr.Markdown(_NOTE)
125
+
126
+ with gr.Tab("Text → Image"):
127
+ with gr.Row():
128
+ with gr.Column(scale=1):
129
+ t_model = gr.Dropdown(list(T2I_MODELS), value="base", label="Model preset")
130
+ t_custom = gr.Textbox(label="Custom model (optional)", placeholder=_CUSTOM_PH_T2I, lines=1)
131
+ t_prompt = gr.Textbox(label="Prompt", lines=3,
132
+ value="A close-up portrait of an elderly African man with deep wrinkles, wearing a traditional hat, soft natural lighting, ultra realistic.")
133
+ t_neg = gr.Textbox(label="Negative prompt", value=" ", lines=1)
134
+ with gr.Row():
135
+ t_steps = gr.Slider(1, 50, value=30, step=1, label="Steps")
136
+ t_cfg = gr.Slider(1.0, 10.0, value=5.0, step=0.5, label="CFG")
137
+ with gr.Row():
138
+ t_h = gr.Slider(256, 1536, value=1024, step=16, label="Height")
139
+ t_w = gr.Slider(256, 1536, value=1024, step=16, label="Width")
140
+ t_seed = gr.Number(value=42, precision=0, label="Seed")
141
+ t_btn = gr.Button("Generate", variant="primary")
142
+ with gr.Column(scale=1):
143
+ t_out = gr.Image(type="pil", label="Output", height=560)
144
+ # Clear the previous output first so the stale image isn't shown as
145
+ # the result while the new one is still transferring (esp. over a
146
+ # gradio share tunnel, where the image download can lag a few seconds).
147
+ t_btn.click(lambda: None, None, t_out).then(
148
+ run_t2i,
149
+ [t_model, t_custom, t_prompt, t_neg, t_steps, t_cfg, t_h, t_w, t_seed],
150
+ t_out)
151
+
152
+ with gr.Tab("Image Edit"):
153
+ with gr.Row():
154
+ with gr.Column(scale=1):
155
+ e_model = gr.Dropdown(list(EDIT_MODELS), value="base", label="Model preset")
156
+ e_custom = gr.Textbox(label="Custom model (optional)", placeholder=_CUSTOM_PH_EDIT, lines=1)
157
+ e_prompt = gr.Textbox(label="Edit instruction", lines=2,
158
+ value="change the background to a city street")
159
+ e_neg = gr.Textbox(label="Negative prompt", value=" ", lines=1)
160
+ e_ref = gr.Image(type="pil", label="Reference image", height=280,
161
+ value=os.path.join(os.path.dirname(__file__), "assets", "dog.jpg"))
162
+ e_extra = gr.File(file_count="multiple", type="filepath",
163
+ label="Extra references (optional, multi-image edit)")
164
+ with gr.Row():
165
+ e_steps = gr.Slider(1, 50, value=30, step=1, label="Steps")
166
+ e_cfg = gr.Slider(1.0, 10.0, value=5.0, step=0.5, label="CFG")
167
+ e_max = gr.Slider(0, 1536, value=1024, step=16,
168
+ label="Max output side (0 = keep source size)")
169
+ e_seed = gr.Number(value=42, precision=0, label="Seed")
170
+ e_btn = gr.Button("Edit", variant="primary")
171
+ with gr.Column(scale=1):
172
+ e_out = gr.Image(type="pil", label="Output", height=560)
173
+ e_btn.click(lambda: None, None, e_out).then(
174
+ run_edit,
175
+ [e_model, e_custom, e_prompt, e_neg, e_ref, e_extra, e_steps, e_cfg, e_max, e_seed],
176
+ e_out)
177
+ return demo
178
+
179
+
180
+ def main():
181
+ global DEVICE
182
+ ap = argparse.ArgumentParser()
183
+ ap.add_argument("--device", default="cuda")
184
+ ap.add_argument("--host", default="0.0.0.0")
185
+ ap.add_argument("--port", type=int, default=7860)
186
+ ap.add_argument("--share", action="store_true")
187
+ ap.add_argument("--preload", default=None,
188
+ help="comma-separated repo ids / paths to load at startup (else lazy)")
189
+ args = ap.parse_args()
190
+ DEVICE = args.device
191
+ if args.preload:
192
+ for repo in args.preload.split(","):
193
+ _get_pipe(repo.strip())
194
+ build_ui().queue().launch(server_name=args.host, server_port=args.port,
195
+ share=args.share, theme=gr.themes.Soft())
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()