prithivMLmods commited on
Commit
18a9431
Β·
verified Β·
1 Parent(s): 4393dd1

update app

Browse files
Files changed (1) hide show
  1. app.py +1087 -145
app.py CHANGED
@@ -5,8 +5,14 @@ import numpy as np
5
  import spaces
6
  import torch
7
  import random
 
 
 
 
8
  from PIL import Image
9
- from typing import Iterable
 
 
10
 
11
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
 
@@ -22,13 +28,13 @@ from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3
22
  dtype = torch.bfloat16
23
 
24
  pipe = QwenImageEditPlusPipeline.from_pretrained(
25
- "FireRedTeam/FireRed-Image-Edit-1.0",
26
  transformer=QwenImageTransformer2DModel.from_pretrained(
27
  "prithivMLmods/Qwen-Image-Edit-Rapid-AIO-V19",
28
  torch_dtype=dtype,
29
- device_map='cuda'
30
  ),
31
- torch_dtype=dtype
32
  ).to(device)
33
 
34
  try:
@@ -37,180 +43,1116 @@ try:
37
  except Exception as e:
38
  print(f"Warning: Could not set FA3 processor: {e}")
39
 
40
- MAX_SEED = np.iinfo(np.int32).max
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- def update_dimensions_on_upload(image):
43
- if image is None:
44
- return 1024, 1024
45
 
46
- original_width, original_height = image.size
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- if original_width > original_height:
49
- new_width = 1024
50
- aspect_ratio = original_height / original_width
51
- new_height = int(new_width * aspect_ratio)
52
- else:
53
- new_height = 1024
54
- aspect_ratio = original_width / original_height
55
- new_width = int(new_height * aspect_ratio)
56
 
57
- new_width = (new_width // 8) * 8
58
- new_height = (new_height // 8) * 8
 
 
 
 
 
 
 
 
 
 
59
 
60
- return new_width, new_height
61
 
62
- @spaces.GPU
63
- def infer(
64
- images,
65
- prompt,
66
- seed,
67
- randomize_seed,
68
- guidance_scale,
69
- steps,
70
- progress=gr.Progress(track_tqdm=True)
71
- ):
72
- gc.collect()
73
- torch.cuda.empty_cache()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- if not images:
76
- raise gr.Error("Please upload at least one image to edit.")
77
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  pil_images = []
79
- if images is not None:
80
- for item in images:
81
- try:
82
- if isinstance(item, tuple) or isinstance(item, list):
83
- path_or_img = item[0]
84
- else:
85
- path_or_img = item
86
-
87
- if isinstance(path_or_img, str):
88
- pil_images.append(Image.open(path_or_img).convert("RGB"))
89
- elif isinstance(path_or_img, Image.Image):
90
- pil_images.append(path_or_img.convert("RGB"))
91
- else:
92
- pil_images.append(Image.open(path_or_img.name).convert("RGB"))
93
- except Exception as e:
94
- print(f"Skipping invalid image item: {e}")
95
- continue
96
 
97
- if not pil_images:
98
- raise gr.Error("Could not process uploaded images.")
99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  if randomize_seed:
101
  seed = random.randint(0, MAX_SEED)
102
-
103
  generator = torch.Generator(device=device).manual_seed(seed)
104
  negative_prompt = "worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry"
105
-
106
  width, height = update_dimensions_on_upload(pil_images[0])
107
-
108
  try:
109
  result_image = pipe(
110
- image=pil_images,
111
- prompt=prompt,
112
- negative_prompt=negative_prompt,
113
- height=height,
114
- width=width,
115
- num_inference_steps=steps,
116
- generator=generator,
117
- true_cfg_scale=guidance_scale,
118
  ).images[0]
119
-
120
  return result_image, seed
121
-
122
  except Exception as e:
123
  raise e
124
  finally:
125
  gc.collect()
126
  torch.cuda.empty_cache()
127
 
128
- @spaces.GPU
129
- def infer_example(images, prompt):
130
- if not images:
131
- return None, 0
132
 
133
- if isinstance(images, str):
134
- images_list = [images]
135
- else:
136
- images_list = images
137
-
138
- result, seed = infer(
139
- images=images_list,
140
- prompt=prompt,
141
- seed=0,
142
- randomize_seed=True,
143
- guidance_scale=1.0,
144
- steps=4
145
- )
146
- return result, seed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
- css = """
149
- #col-container {
150
- margin: 0 auto;
151
- max-width: 1000px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  }
153
- #main-title h1 {font-size: 2.4em !important;}
154
  """
155
 
 
 
 
 
 
 
 
 
 
 
156
  with gr.Blocks() as demo:
157
- with gr.Column(elem_id="col-container"):
158
- gr.Markdown("# **FireRed-Image-Edit-1.0-Fast**", elem_id="main-title")
159
- gr.Markdown("Perform image edits using [FireRed-Image-Edit-1.0](https://huggingface.co/FireRedTeam/FireRed-Image-Edit-1.0) with 4-step fast inference.")
160
-
161
- with gr.Row(equal_height=True):
162
- with gr.Column():
163
- images = gr.Gallery(
164
- label="Upload Images",
165
- #sources=["upload", "clipboard"],
166
- type="filepath",
167
- columns=2,
168
- rows=1,
169
- height=300,
170
- allow_preview=True
171
- )
172
-
173
- prompt = gr.Text(
174
- label="Edit Prompt",
175
- show_label=True,
176
- max_lines=2,
177
- placeholder="e.g., transform into anime, upscale, change lighting...",
178
- )
179
-
180
- run_button = gr.Button("Edit Image", variant="primary")
181
-
182
- with gr.Column():
183
- output_image = gr.Image(label="Output Image", interactive=False, format="png", height=395)
184
-
185
- with gr.Accordion("Advanced Settings", open=False, visible=False):
186
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
187
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
188
- guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0)
189
- steps = gr.Slider(label="Inference Steps", minimum=1, maximum=50, step=1, value=4)
190
-
191
- gr.Examples(
192
- examples=[
193
- [["examples/1.jpg"], "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed 'Fire-Edit' preserving realistic texture and details."],
194
- [["examples/2.jpg"], "Transform the image into a dotted cartoon style."],
195
- [["examples/3.jpeg"], "Convert it to black and white."],
196
- [["examples/4.jpg", "examples/5.jpg"], "Replace her glasses with the new glasses from image 1."],
197
- [["examples/8.jpg", "examples/9.png"], "Replace the current clothing with the clothing from the reference image 2. Keep the person’s face, hairstyle, body pose, background, lighting, and camera angle unchanged. Ensure the new outfit fits naturally with realistic fabric texture, proper shadows, folds, and accurate proportions. Match the lighting, color tone, and overall style for a seamless and high-quality result."],
198
- [["examples/10.jpg", "examples/11.png"], "Replace the current clothing with the clothing from the reference image 2. Keep the person’s face, hairstyle, body pose, background, lighting, and camera angle unchanged. Ensure the new outfit fits naturally with realistic fabric texture, proper shadows, folds, and accurate proportions. Match the lighting, color tone, and overall style for a seamless and high-quality result."],
199
- ],
200
- inputs=[images, prompt],
201
- outputs=[output_image, seed],
202
- fn=infer_example,
203
- cache_examples=False,
204
- label="Examples"
205
- )
206
-
207
- gr.Markdown("[*](https://huggingface.co/FireRedTeam/FireRed-Image-Edit-1.0)This is still an experimental Space for FireRed-Image-Edit-1.0.")
208
-
209
- run_button.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  fn=infer,
211
- inputs=[images, prompt, seed, randomize_seed, guidance_scale, steps],
212
- outputs=[output_image, seed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  )
214
 
215
  if __name__ == "__main__":
216
- demo.queue(max_size=30).launch(css=css, mcp_server=True, ssr_mode=False, show_error=True)
 
 
 
 
 
 
 
5
  import spaces
6
  import torch
7
  import random
8
+ import base64
9
+ import json
10
+ import html as html_lib
11
+ from io import BytesIO
12
  from PIL import Image
13
+
14
+ MAX_SEED = np.iinfo(np.int32).max
15
+ LANCZOS = getattr(Image, "Resampling", Image).LANCZOS
16
 
17
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
 
 
28
  dtype = torch.bfloat16
29
 
30
  pipe = QwenImageEditPlusPipeline.from_pretrained(
31
+ "FireRedTeam/FireRed-Image-Edit-1.1",
32
  transformer=QwenImageTransformer2DModel.from_pretrained(
33
  "prithivMLmods/Qwen-Image-Edit-Rapid-AIO-V19",
34
  torch_dtype=dtype,
35
+ device_map="cuda",
36
  ),
37
+ torch_dtype=dtype,
38
  ).to(device)
39
 
40
  try:
 
43
  except Exception as e:
44
  print(f"Warning: Could not set FA3 processor: {e}")
45
 
46
+ EXAMPLES_CONFIG = [
47
+ {
48
+ "images": ["examples/1.jpg"],
49
+ "prompt": "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed 'Fire-Edit' preserving realistic texture and details.",
50
+ },
51
+ {
52
+ "images": ["examples/2.jpg"],
53
+ "prompt": "Transform the image into a dotted cartoon style.",
54
+ },
55
+ {
56
+ "images": ["examples/3.jpeg"],
57
+ "prompt": "Convert it to black and white.",
58
+ },
59
+ {
60
+ "images": ["examples/4.jpg", "examples/5.jpg"],
61
+ "prompt": "Replace her glasses with the new glasses from image 1.",
62
+ },
63
+ {
64
+ "images": ["examples/8.jpg", "examples/9.png"],
65
+ "prompt": "Replace the current clothing with the clothing from the reference image 2. Keep the person's face, hairstyle, body pose, background, lighting, and camera angle unchanged. Ensure the new outfit fits naturally with realistic fabric texture, proper shadows, folds, and accurate proportions. Match the lighting, color tone, and overall style for a seamless and high-quality result.",
66
+ },
67
+ {
68
+ "images": ["examples/10.jpg", "examples/11.png"],
69
+ "prompt": "Replace the current clothing with the clothing from the reference image 2. Keep the person's face, hairstyle, body pose, background, lighting, and camera angle unchanged. Ensure the new outfit fits naturally with realistic fabric texture, proper shadows, folds, and accurate proportions. Match the lighting, color tone, and overall style for a seamless and high-quality result.",
70
+ },
71
+ ]
72
 
 
 
 
73
 
74
+ def make_thumb_b64(path, max_dim=220):
75
+ if not os.path.exists(path):
76
+ return ""
77
+ try:
78
+ img = Image.open(path).convert("RGB")
79
+ img.thumbnail((max_dim, max_dim), LANCZOS)
80
+ buf = BytesIO()
81
+ img.save(buf, format="JPEG", quality=65)
82
+ return f"data:image/jpeg;base64,{base64.b64encode(buf.getvalue()).decode()}"
83
+ except Exception as e:
84
+ print(f"Thumbnail error for {path}: {e}")
85
+ return ""
86
 
 
 
 
 
 
 
 
 
87
 
88
+ def encode_full_image(path):
89
+ if not os.path.exists(path):
90
+ return ""
91
+ try:
92
+ with open(path, "rb") as f:
93
+ data = f.read()
94
+ ext = path.rsplit(".", 1)[-1].lower()
95
+ mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp"}.get(ext, "image/jpeg")
96
+ return f"data:{mime};base64,{base64.b64encode(data).decode()}"
97
+ except Exception as e:
98
+ print(f"Encode error for {path}: {e}")
99
+ return ""
100
 
 
101
 
102
+ def build_example_cards_html():
103
+ cards = ""
104
+ for i, ex in enumerate(EXAMPLES_CONFIG):
105
+ thumbs_html = ""
106
+ for path in ex["images"]:
107
+ thumb = make_thumb_b64(path)
108
+ if thumb:
109
+ thumbs_html += f'<img src="{thumb}" alt="">'
110
+ else:
111
+ thumbs_html += '<div class="example-thumb-placeholder">Preview</div>'
112
+ n = len(ex["images"])
113
+ badge = f'{n} image{"s" if n > 1 else ""}'
114
+ prompt_short = html_lib.escape(ex["prompt"][:90])
115
+ if len(ex["prompt"]) > 90:
116
+ prompt_short += "..."
117
+ cards += f'''<div class="example-card" data-idx="{i}">
118
+ <div class="example-thumbs">{thumbs_html}</div>
119
+ <div class="example-meta"><span class="example-badge">{badge}</span></div>
120
+ <div class="example-prompt-text">{prompt_short}</div>
121
+ </div>'''
122
+ return cards
123
+
124
+
125
+ def load_example_data(idx_str):
126
+ try:
127
+ idx = int(float(idx_str)) if idx_str and idx_str.strip() else -1
128
+ except (ValueError, TypeError):
129
+ idx = -1
130
+ if idx < 0 or idx >= len(EXAMPLES_CONFIG):
131
+ return json.dumps({"images": [], "prompt": "", "names": [], "status": "error"})
132
+ ex = EXAMPLES_CONFIG[idx]
133
+ b64_list, names = [], []
134
+ for path in ex["images"]:
135
+ b64 = encode_full_image(path)
136
+ if b64:
137
+ b64_list.append(b64)
138
+ names.append(os.path.basename(path))
139
+ return json.dumps({"images": b64_list, "prompt": ex["prompt"], "names": names, "status": "ok"})
140
 
 
 
141
 
142
+ print("Building example thumbnails...")
143
+ EXAMPLE_CARDS_HTML = build_example_cards_html()
144
+ print(f"Built {len(EXAMPLES_CONFIG)} example cards.")
145
+
146
+
147
+ def b64_to_pil_list(b64_json_str):
148
+ if not b64_json_str or b64_json_str.strip() in ("", "[]"):
149
+ return []
150
+ try:
151
+ b64_list = json.loads(b64_json_str)
152
+ except Exception:
153
+ return []
154
  pil_images = []
155
+ for b64_str in b64_list:
156
+ if not b64_str or not isinstance(b64_str, str):
157
+ continue
158
+ try:
159
+ if b64_str.startswith("data:image"):
160
+ _, data = b64_str.split(",", 1)
161
+ else:
162
+ data = b64_str
163
+ image_data = base64.b64decode(data)
164
+ pil_images.append(Image.open(BytesIO(image_data)).convert("RGB"))
165
+ except Exception as e:
166
+ print(f"Error decoding image: {e}")
167
+ return pil_images
 
 
 
 
168
 
 
 
169
 
170
+ def update_dimensions_on_upload(image):
171
+ if image is None:
172
+ return 1024, 1024
173
+ w, h = image.size
174
+ if w > h:
175
+ nw = 1024
176
+ nh = int(nw * h / w)
177
+ else:
178
+ nh = 1024
179
+ nw = int(nh * w / h)
180
+ return (nw // 8) * 8, (nh // 8) * 8
181
+
182
+
183
+ @spaces.GPU
184
+ def infer(images_b64_json, prompt, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress(track_tqdm=True)):
185
+ gc.collect()
186
+ torch.cuda.empty_cache()
187
+ pil_images = b64_to_pil_list(images_b64_json)
188
+ if not pil_images:
189
+ raise gr.Error("Please upload at least one image to edit.")
190
+ if not prompt or prompt.strip() == "":
191
+ raise gr.Error("Please enter an edit prompt.")
192
  if randomize_seed:
193
  seed = random.randint(0, MAX_SEED)
 
194
  generator = torch.Generator(device=device).manual_seed(seed)
195
  negative_prompt = "worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry"
 
196
  width, height = update_dimensions_on_upload(pil_images[0])
 
197
  try:
198
  result_image = pipe(
199
+ image=pil_images, prompt=prompt, negative_prompt=negative_prompt,
200
+ height=height, width=width, num_inference_steps=steps,
201
+ generator=generator, true_cfg_scale=guidance_scale,
 
 
 
 
 
202
  ).images[0]
 
203
  return result_image, seed
 
204
  except Exception as e:
205
  raise e
206
  finally:
207
  gc.collect()
208
  torch.cuda.empty_cache()
209
 
 
 
 
 
210
 
211
+ css = r"""
212
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');
213
+ *{box-sizing:border-box;margin:0;padding:0}
214
+ body,.gradio-container{
215
+ background:#0f0f13!important;font-family:'Inter',system-ui,-apple-system,sans-serif!important;
216
+ font-size:14px!important;color:#e4e4e7!important;min-height:100vh;
217
+ }
218
+ .dark body,.dark .gradio-container{background:#0f0f13!important;color:#e4e4e7!important}
219
+ footer{display:none!important}
220
+ .hidden-input{display:none!important;height:0!important;overflow:hidden!important;margin:0!important;padding:0!important}
221
+
222
+ #example-load-btn{
223
+ position:absolute!important;left:-9999px!important;top:-9999px!important;
224
+ width:1px!important;height:1px!important;opacity:0.01!important;
225
+ pointer-events:none!important;overflow:hidden!important;
226
+ }
227
+ #gradio-run-btn{
228
+ position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;
229
+ opacity:0.01;pointer-events:none;overflow:hidden;
230
+ }
231
+
232
+ .app-shell{
233
+ background:#18181b;border:1px solid #27272a;border-radius:16px;
234
+ margin:12px auto;max-width:1400px;overflow:hidden;
235
+ box-shadow:0 25px 50px -12px rgba(0,0,0,.6),0 0 0 1px rgba(255,255,255,.03);
236
+ }
237
+ .app-header{
238
+ background:linear-gradient(135deg,#18181b,#1e1e24);border-bottom:1px solid #27272a;
239
+ padding:14px 24px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;
240
+ }
241
+ .app-header-left{display:flex;align-items:center;gap:12px}
242
+ .app-logo{
243
+ width:36px;height:36px;background:linear-gradient(135deg,#1E90FF,#47A3FF,#7CB8FF);
244
+ border-radius:10px;display:flex;align-items:center;justify-content:center;
245
+ box-shadow:0 4px 12px rgba(30,144,255,.35);
246
+ }
247
+ .app-logo svg{width:20px;height:20px;fill:#fff;flex-shrink:0}
248
+ .app-title{
249
+ font-size:18px;font-weight:700;background:linear-gradient(135deg,#e4e4e7,#a1a1aa);
250
+ -webkit-background-clip:text;-webkit-text-fill-color:transparent;letter-spacing:-.3px;
251
+ }
252
+ .app-badge{
253
+ font-size:11px;font-weight:600;padding:3px 10px;border-radius:20px;
254
+ background:rgba(30,144,255,.15);color:#47A3FF;border:1px solid rgba(30,144,255,.25);letter-spacing:.3px;
255
+ }
256
+ .app-badge.fast{background:rgba(34,197,94,.12);color:#4ade80;border:1px solid rgba(34,197,94,.25)}
257
+
258
+ .app-toolbar{
259
+ background:#18181b;border-bottom:1px solid #27272a;padding:8px 16px;
260
+ display:flex;gap:4px;align-items:center;flex-wrap:wrap;
261
+ }
262
+ .tb-sep{width:1px;height:28px;background:#27272a;margin:0 8px}
263
+ .modern-tb-btn{
264
+ display:inline-flex;align-items:center;justify-content:center;gap:6px;
265
+ min-width:32px;height:34px;background:transparent;border:1px solid transparent;
266
+ border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;padding:0 12px;
267
+ font-family:'Inter',sans-serif;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;
268
+ transition:all .15s ease;
269
+ }
270
+ .modern-tb-btn:hover{background:rgba(30,144,255,.15);border-color:rgba(30,144,255,.3)}
271
+ .modern-tb-btn:active,.modern-tb-btn.active{background:rgba(30,144,255,.25);border-color:rgba(30,144,255,.45)}
272
+ .modern-tb-btn .tb-label{font-size:13px;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;font-weight:600}
273
+ .modern-tb-btn .tb-svg{width:15px;height:15px;flex-shrink:0;color:#ffffff!important}
274
+ .modern-tb-btn .tb-svg,
275
+ .modern-tb-btn .tb-svg *{stroke:#ffffff!important;fill:none!important}
276
+ .tb-info{font-family:'JetBrains Mono',monospace;font-size:12px;color:#71717a;padding:0 8px;display:flex;align-items:center}
277
+
278
+ body:not(.dark) .modern-tb-btn,body:not(.dark) .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
279
+ body:not(.dark) .modern-tb-btn .tb-svg,body:not(.dark) .modern-tb-btn .tb-svg *{stroke:#ffffff!important}
280
+ .dark .modern-tb-btn,.dark .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
281
+ .dark .modern-tb-btn .tb-svg,.dark .modern-tb-btn .tb-svg *{stroke:#ffffff!important}
282
+ .gradio-container .modern-tb-btn,.gradio-container .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
283
+ .gradio-container .modern-tb-btn .tb-svg,.gradio-container .modern-tb-btn .tb-svg *{stroke:#ffffff!important}
284
+
285
+ .app-main-row{display:flex;gap:0;flex:1;overflow:hidden}
286
+ .app-main-left{flex:1;display:flex;flex-direction:column;min-width:0;border-right:1px solid #27272a}
287
+ .app-main-right{width:420px;display:flex;flex-direction:column;flex-shrink:0;background:#18181b}
288
+
289
+ #gallery-drop-zone{position:relative;background:#09090b;min-height:440px;overflow:auto}
290
+ #gallery-drop-zone.drag-over{outline:2px solid #1E90FF;outline-offset:-2px;background:rgba(30,144,255,.04)}
291
+
292
+ .upload-prompt-modern{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:20}
293
+ .upload-click-area{
294
+ display:flex;flex-direction:column;align-items:center;justify-content:center;
295
+ cursor:pointer;padding:36px 52px;border:2px dashed #3f3f46;border-radius:16px;
296
+ background:rgba(30,144,255,.03);transition:all .2s ease;gap:8px;
297
+ }
298
+ .upload-click-area:hover{background:rgba(30,144,255,.08);border-color:#1E90FF;transform:scale(1.03)}
299
+ .upload-click-area:active{background:rgba(30,144,255,.12);transform:scale(.98)}
300
+ .upload-click-area svg{width:80px;height:80px}
301
+ .upload-main-text{color:#71717a;font-size:14px;font-weight:500;margin-top:4px}
302
+ .upload-sub-text{color:#52525b;font-size:12px}
303
+
304
+ .image-gallery-grid{
305
+ display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));
306
+ gap:12px;padding:16px;align-content:start;
307
+ }
308
+ .gallery-thumb{
309
+ position:relative;aspect-ratio:1;border-radius:10px;overflow:hidden;
310
+ cursor:pointer;border:2px solid #27272a;transition:all .2s ease;background:#18181b;
311
+ }
312
+ .gallery-thumb:hover{border-color:#3f3f46;transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,.4)}
313
+ .gallery-thumb.selected{border-color:#1E90FF!important;box-shadow:0 0 0 3px rgba(30,144,255,.2)}
314
+ .gallery-thumb img{width:100%;height:100%;object-fit:cover}
315
+ .thumb-badge{
316
+ position:absolute;top:6px;left:6px;background:#1E90FF;color:#fff;
317
+ padding:2px 8px;border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:600;
318
+ }
319
+ .thumb-remove{
320
+ position:absolute;top:6px;right:6px;width:24px;height:24px;background:rgba(0,0,0,.75);
321
+ color:#fff;border:1px solid rgba(255,255,255,.15);border-radius:50%;cursor:pointer;
322
+ display:none;align-items:center;justify-content:center;font-size:12px;transition:all .15s;line-height:1;
323
+ }
324
+ .gallery-thumb:hover .thumb-remove{display:flex}
325
+ .thumb-remove:hover{background:#1E90FF;border-color:#1E90FF}
326
+ .gallery-add-card{
327
+ aspect-ratio:1;border-radius:10px;border:2px dashed #3f3f46;
328
+ display:flex;flex-direction:column;align-items:center;justify-content:center;
329
+ cursor:pointer;transition:all .2s ease;background:rgba(30,144,255,.03);gap:4px;
330
+ }
331
+ .gallery-add-card:hover{border-color:#1E90FF;background:rgba(30,144,255,.08)}
332
+ .gallery-add-card .add-icon{font-size:28px;color:#71717a;font-weight:300}
333
+ .gallery-add-card .add-text{font-size:12px;color:#71717a;font-weight:500}
334
+
335
+ .hint-bar{
336
+ background:rgba(30,144,255,.06);border-top:1px solid #27272a;border-bottom:1px solid #27272a;
337
+ padding:10px 20px;font-size:13px;color:#a1a1aa;line-height:1.7;
338
+ }
339
+ .hint-bar b{color:#7CB8FF;font-weight:600}
340
+ .hint-bar kbd{
341
+ display:inline-block;padding:1px 6px;background:#27272a;border:1px solid #3f3f46;
342
+ border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#a1a1aa;
343
+ }
344
+
345
+ .suggestions-section{border-top:1px solid #27272a;padding:12px 16px}
346
+ .suggestions-title,.examples-title{
347
+ font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;
348
+ letter-spacing:.8px;margin-bottom:10px;
349
+ }
350
+ .suggestions-wrap{display:flex;flex-wrap:wrap;gap:6px}
351
+ .suggestion-chip{
352
+ display:inline-flex;align-items:center;gap:4px;padding:5px 12px;
353
+ background:rgba(30,144,255,.08);border:1px solid rgba(30,144,255,.2);border-radius:20px;
354
+ color:#7CB8FF;font-size:12px;font-weight:500;font-family:'Inter',sans-serif;
355
+ cursor:pointer;transition:all .15s;white-space:nowrap;
356
+ }
357
+ .suggestion-chip:hover{background:rgba(30,144,255,.15);border-color:rgba(30,144,255,.35);color:#47A3FF;transform:translateY(-1px)}
358
+
359
+ .examples-section{border-top:1px solid #27272a;padding:12px 16px}
360
+ .examples-scroll{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px}
361
+ .examples-scroll::-webkit-scrollbar{height:6px}
362
+ .examples-scroll::-webkit-scrollbar-track{background:#09090b;border-radius:3px}
363
+ .examples-scroll::-webkit-scrollbar-thumb{background:#27272a;border-radius:3px}
364
+ .examples-scroll::-webkit-scrollbar-thumb:hover{background:#3f3f46}
365
+ .example-card{
366
+ flex-shrink:0;width:210px;background:#09090b;border:1px solid #27272a;
367
+ border-radius:10px;overflow:hidden;cursor:pointer;transition:all .2s ease;
368
+ }
369
+ .example-card:hover{border-color:#1E90FF;transform:translateY(-2px);box-shadow:0 4px 12px rgba(30,144,255,.15)}
370
+ .example-card.loading{opacity:.5;pointer-events:none}
371
+ .example-thumbs{display:flex;height:110px;overflow:hidden;background:#18181b}
372
+ .example-thumbs img{flex:1;object-fit:cover;min-width:0;border-bottom:1px solid #27272a}
373
+ .example-thumb-placeholder{
374
+ flex:1;display:flex;align-items:center;justify-content:center;
375
+ background:#18181b;color:#3f3f46;font-size:11px;min-width:0;
376
+ }
377
+ .example-meta{padding:6px 10px;display:flex;align-items:center;gap:6px}
378
+ .example-badge{
379
+ display:inline-flex;padding:2px 7px;background:rgba(30,144,255,.1);border-radius:4px;
380
+ font-size:10px;font-weight:600;color:#47A3FF;font-family:'JetBrains Mono',monospace;white-space:nowrap;
381
+ }
382
+ .example-prompt-text{
383
+ padding:0 10px 8px;font-size:11px;color:#a1a1aa;line-height:1.4;
384
+ display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;
385
+ }
386
+
387
+ .panel-card{border-bottom:1px solid #27272a}
388
+ .panel-card-title{
389
+ padding:12px 20px;font-size:12px;font-weight:600;color:#71717a;
390
+ text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid rgba(39,39,42,.6);
391
+ }
392
+ .panel-card-body{padding:16px 20px;display:flex;flex-direction:column;gap:8px}
393
+ .modern-label{font-size:13px;font-weight:500;color:#a1a1aa;margin-bottom:4px;display:block}
394
+ .modern-textarea{
395
+ width:100%;background:#09090b;border:1px solid #27272a;border-radius:8px;
396
+ padding:10px 14px;font-family:'Inter',sans-serif;font-size:14px;color:#e4e4e7;
397
+ resize:vertical;outline:none;min-height:42px;transition:border-color .2s;
398
+ }
399
+ .modern-textarea:focus{border-color:#1E90FF;box-shadow:0 0 0 3px rgba(30,144,255,.15)}
400
+ .modern-textarea::placeholder{color:#3f3f46}
401
+ .modern-textarea.error-flash{
402
+ border-color:#ef4444!important;box-shadow:0 0 0 3px rgba(239,68,68,.2)!important;animation:shake .4s ease;
403
+ }
404
+ @keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-4px)}40%,80%{transform:translateX(4px)}}
405
+
406
+ .toast-notification{
407
+ position:fixed;top:24px;left:50%;transform:translateX(-50%) translateY(-120%);
408
+ z-index:9999;padding:10px 24px;border-radius:10px;font-family:'Inter',sans-serif;
409
+ font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px;
410
+ box-shadow:0 8px 24px rgba(0,0,0,.5);
411
+ transition:transform .35s cubic-bezier(.34,1.56,.64,1),opacity .35s ease;opacity:0;pointer-events:none;
412
+ }
413
+ .toast-notification.visible{transform:translateX(-50%) translateY(0);opacity:1;pointer-events:auto}
414
+ .toast-notification.error{background:linear-gradient(135deg,#dc2626,#b91c1c);color:#fff;border:1px solid rgba(255,255,255,.15)}
415
+ .toast-notification.warning{background:linear-gradient(135deg,#d97706,#b45309);color:#fff;border:1px solid rgba(255,255,255,.15)}
416
+ .toast-notification.info{background:linear-gradient(135deg,#2563eb,#1d4ed8);color:#fff;border:1px solid rgba(255,255,255,.15)}
417
+ .toast-notification .toast-icon{font-size:16px;line-height:1}
418
+ .toast-notification .toast-text{line-height:1.3}
419
+
420
+ .btn-run{
421
+ display:flex;align-items:center;justify-content:center;gap:8px;width:100%;
422
+ background:linear-gradient(135deg,#1E90FF,#1873CC);border:none;border-radius:10px;
423
+ padding:12px 24px;cursor:pointer;font-size:15px;font-weight:600;font-family:'Inter',sans-serif;
424
+ color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;transition:all .2s ease;letter-spacing:-.2px;
425
+ box-shadow:0 4px 16px rgba(30,144,255,.3),inset 0 1px 0 rgba(255,255,255,.1);
426
+ }
427
+ .btn-run:hover{
428
+ background:linear-gradient(135deg,#47A3FF,#1E90FF);transform:translateY(-1px);
429
+ box-shadow:0 6px 24px rgba(30,144,255,.45),inset 0 1px 0 rgba(255,255,255,.15);
430
+ }
431
+ .btn-run:active{transform:translateY(0);box-shadow:0 2px 8px rgba(30,144,255,.3)}
432
+ .btn-run svg{width:18px;height:18px;fill:#ffffff!important}
433
+ .btn-run svg path{fill:#ffffff!important}
434
+ #custom-run-btn,#custom-run-btn *,#custom-run-btn span,#custom-run-btn svg,
435
+ #custom-run-btn svg path,#run-btn-label,.btn-run,.btn-run *{
436
+ color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important;
437
+ }
438
+ body:not(.dark) .btn-run,body:not(.dark) .btn-run *,body:not(.dark) #custom-run-btn,
439
+ body:not(.dark) #custom-run-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important}
440
+ .dark .btn-run,.dark .btn-run *,.dark #custom-run-btn,.dark #custom-run-btn *{
441
+ color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important;
442
+ }
443
+ .gradio-container .btn-run,.gradio-container .btn-run *,.gradio-container #custom-run-btn,
444
+ .gradio-container #custom-run-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important}
445
+
446
+ .output-frame{border-bottom:1px solid #27272a;display:flex;flex-direction:column;position:relative}
447
+ .output-frame .out-title{
448
+ padding:10px 20px;font-size:13px;font-weight:700;color:#ffffff!important;
449
+ -webkit-text-fill-color:#ffffff!important;text-transform:uppercase;letter-spacing:.8px;
450
+ border-bottom:1px solid rgba(39,39,42,.6);display:flex;align-items:center;justify-content:space-between;
451
+ }
452
+ .output-frame .out-title span{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
453
+ .output-frame .out-body{
454
+ flex:1;background:#09090b;display:flex;align-items:center;justify-content:center;
455
+ overflow:hidden;min-height:240px;position:relative;
456
+ }
457
+ .output-frame .out-body img{max-width:100%;max-height:460px;image-rendering:auto}
458
+ .output-frame .out-placeholder{color:#3f3f46;font-size:13px;text-align:center;padding:20px}
459
+ .out-download-btn{
460
+ display:none;align-items:center;justify-content:center;background:rgba(30,144,255,.1);
461
+ border:1px solid rgba(30,144,255,.2);border-radius:6px;cursor:pointer;padding:3px 10px;
462
+ font-size:11px;font-weight:500;color:#7CB8FF!important;gap:4px;height:24px;transition:all .15s;
463
+ }
464
+ .out-download-btn:hover{background:rgba(30,144,255,.2);border-color:rgba(30,144,255,.35);color:#ffffff!important}
465
+ .out-download-btn.visible{display:inline-flex}
466
+ .out-download-btn svg{width:12px;height:12px;fill:#7CB8FF}
467
+
468
+ .modern-loader{
469
+ display:none;position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(9,9,11,.92);
470
+ z-index:15;flex-direction:column;align-items:center;justify-content:center;gap:16px;backdrop-filter:blur(4px);
471
+ }
472
+ .modern-loader.active{display:flex}
473
+ .modern-loader .loader-spinner{
474
+ width:36px;height:36px;border:3px solid #27272a;border-top-color:#1E90FF;
475
+ border-radius:50%;animation:spin .8s linear infinite;
476
+ }
477
+ @keyframes spin{to{transform:rotate(360deg)}}
478
+ .modern-loader .loader-text{font-size:13px;color:#a1a1aa;font-weight:500}
479
+ .loader-bar-track{width:200px;height:4px;background:#27272a;border-radius:2px;overflow:hidden}
480
+ .loader-bar-fill{
481
+ height:100%;background:linear-gradient(90deg,#1E90FF,#47A3FF,#1E90FF);
482
+ background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:2px;
483
+ }
484
+ @keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}
485
+
486
+ .settings-group{border:1px solid #27272a;border-radius:10px;margin:12px 16px;padding:0;overflow:hidden}
487
+ .settings-group-title{
488
+ font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px;
489
+ padding:10px 16px;border-bottom:1px solid #27272a;background:rgba(24,24,27,.5);
490
+ }
491
+ .settings-group-body{padding:14px 16px;display:flex;flex-direction:column;gap:12px}
492
+ .slider-row{display:flex;align-items:center;gap:10px;min-height:28px}
493
+ .slider-row label{font-size:13px;font-weight:500;color:#a1a1aa;min-width:72px;flex-shrink:0}
494
+ .slider-row input[type="range"]{
495
+ flex:1;-webkit-appearance:none;appearance:none;height:6px;background:#27272a;
496
+ border-radius:3px;outline:none;min-width:0;
497
+ }
498
+ .slider-row input[type="range"]::-webkit-slider-thumb{
499
+ -webkit-appearance:none;width:16px;height:16px;background:linear-gradient(135deg,#1E90FF,#1873CC);
500
+ border-radius:50%;cursor:pointer;box-shadow:0 2px 6px rgba(30,144,255,.4);transition:transform .15s;
501
+ }
502
+ .slider-row input[type="range"]::-webkit-slider-thumb:hover{transform:scale(1.2)}
503
+ .slider-row input[type="range"]::-moz-range-thumb{
504
+ width:16px;height:16px;background:linear-gradient(135deg,#1E90FF,#1873CC);
505
+ border-radius:50%;cursor:pointer;border:none;box-shadow:0 2px 6px rgba(30,144,255,.4);
506
+ }
507
+ .slider-row .slider-val{
508
+ min-width:52px;text-align:right;font-family:'JetBrains Mono',monospace;font-size:12px;
509
+ font-weight:500;padding:3px 8px;background:#09090b;border:1px solid #27272a;
510
+ border-radius:6px;color:#a1a1aa;flex-shrink:0;
511
+ }
512
+ .checkbox-row{display:flex;align-items:center;gap:8px;font-size:13px;color:#a1a1aa}
513
+ .checkbox-row input[type="checkbox"]{accent-color:#1E90FF;width:16px;height:16px;cursor:pointer}
514
+ .checkbox-row label{color:#a1a1aa;font-size:13px;cursor:pointer}
515
+
516
+ .app-statusbar{
517
+ background:#18181b;border-top:1px solid #27272a;padding:6px 20px;
518
+ display:flex;gap:12px;height:34px;align-items:center;font-size:12px;
519
+ }
520
+ .app-statusbar .sb-section{
521
+ padding:0 12px;flex:1;display:flex;align-items:center;font-family:'JetBrains Mono',monospace;
522
+ font-size:12px;color:#52525b;overflow:hidden;white-space:nowrap;
523
+ }
524
+ .app-statusbar .sb-section.sb-fixed{
525
+ flex:0 0 auto;min-width:90px;text-align:center;justify-content:center;
526
+ padding:3px 12px;background:rgba(30,144,255,.08);border-radius:6px;color:#47A3FF;font-weight:500;
527
+ }
528
+
529
+ .exp-note{padding:10px 20px;font-size:12px;color:#52525b;border-top:1px solid #27272a;text-align:center}
530
+ .exp-note a{color:#47A3FF;text-decoration:none}
531
+ .exp-note a:hover{text-decoration:underline}
532
+
533
+ .dark .app-shell{background:#18181b}
534
+ .dark .upload-prompt-modern{background:transparent}
535
+ .dark .panel-card{background:#18181b}
536
+ .dark .settings-group{background:#18181b}
537
+ .dark .output-frame .out-title{color:#ffffff!important}
538
+ .dark .output-frame .out-title span{color:#ffffff!important}
539
+ .dark .out-download-btn{color:#7CB8FF!important}
540
+ .dark .out-download-btn:hover{color:#ffffff!important}
541
+
542
+ ::-webkit-scrollbar{width:8px;height:8px}
543
+ ::-webkit-scrollbar-track{background:#09090b}
544
+ ::-webkit-scrollbar-thumb{background:#27272a;border-radius:4px}
545
+ ::-webkit-scrollbar-thumb:hover{background:#3f3f46}
546
+
547
+ @media(max-width:840px){
548
+ .app-main-row{flex-direction:column}
549
+ .app-main-right{width:100%}
550
+ .app-main-left{border-right:none;border-bottom:1px solid #27272a}
551
+ }
552
+ """
553
+
554
+ gallery_js = r"""
555
+ () => {
556
+ function init() {
557
+ if (window.__fireRedInitDone) return;
558
+
559
+ const galleryGrid = document.getElementById('image-gallery-grid');
560
+ const dropZone = document.getElementById('gallery-drop-zone');
561
+ const uploadPrompt = document.getElementById('upload-prompt');
562
+ const uploadClick = document.getElementById('upload-click-area');
563
+ const fileInput = document.getElementById('custom-file-input');
564
+ const btnUpload = document.getElementById('tb-upload');
565
+ const btnRemove = document.getElementById('tb-remove');
566
+ const btnClear = document.getElementById('tb-clear');
567
+ const promptInput = document.getElementById('custom-prompt-input');
568
+ const runBtnEl = document.getElementById('custom-run-btn');
569
+ const imgCountTb = document.getElementById('tb-image-count');
570
+ const imgCountSb = document.getElementById('sb-image-count');
571
+
572
+ if (!galleryGrid || !fileInput || !dropZone) {
573
+ setTimeout(init, 250);
574
+ return;
575
+ }
576
+
577
+ window.__fireRedInitDone = true;
578
+
579
+ let images = [];
580
+ window.__uploadedImages = images;
581
+ let selectedIdx = -1;
582
+ let toastTimer = null;
583
+
584
+ function showToast(message, type) {
585
+ let toast = document.getElementById('app-toast');
586
+ if (!toast) {
587
+ toast = document.createElement('div');
588
+ toast.id = 'app-toast';
589
+ toast.className = 'toast-notification';
590
+ toast.innerHTML = '<span class="toast-icon"></span><span class="toast-text"></span>';
591
+ document.body.appendChild(toast);
592
+ }
593
+ const icon = toast.querySelector('.toast-icon');
594
+ const text = toast.querySelector('.toast-text');
595
+ toast.className = 'toast-notification ' + (type || 'error');
596
+ if (type === 'warning') icon.textContent = '\u26A0';
597
+ else if (type === 'info') icon.textContent = '\u2139';
598
+ else icon.textContent = '\u2717';
599
+ text.textContent = message;
600
+ if (toastTimer) clearTimeout(toastTimer);
601
+ void toast.offsetWidth;
602
+ toast.classList.add('visible');
603
+ toastTimer = setTimeout(() => toast.classList.remove('visible'), 3500);
604
+ }
605
+ window.__showToast = showToast;
606
+
607
+ function flashPromptError() {
608
+ if (!promptInput) return;
609
+ promptInput.classList.add('error-flash');
610
+ promptInput.focus();
611
+ setTimeout(() => promptInput.classList.remove('error-flash'), 800);
612
+ }
613
+
614
+ function setGradioValue(containerId, value) {
615
+ const container = document.getElementById(containerId);
616
+ if (!container) return;
617
+ container.querySelectorAll('input, textarea').forEach(el => {
618
+ if (el.type === 'file' || el.type === 'range' || el.type === 'checkbox') return;
619
+ const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
620
+ const ns = Object.getOwnPropertyDescriptor(proto, 'value');
621
+ if (ns && ns.set) {
622
+ ns.set.call(el, value);
623
+ el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));
624
+ el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));
625
+ }
626
+ });
627
+ }
628
+ window.__setGradioValue = setGradioValue;
629
+
630
+ function syncImagesToGradio() {
631
+ window.__uploadedImages = images;
632
+ const b64Array = images.map(img => img.b64);
633
+ setGradioValue('hidden-images-b64', JSON.stringify(b64Array));
634
+ updateCounts();
635
+ }
636
+
637
+ function syncPromptToGradio() {
638
+ if (promptInput) setGradioValue('prompt-gradio-input', promptInput.value);
639
+ }
640
+
641
+ function updateCounts() {
642
+ const n = images.length;
643
+ const txt = n > 0 ? n + ' image' + (n > 1 ? 's' : '') : 'No images';
644
+ if (imgCountTb) imgCountTb.textContent = txt;
645
+ if (imgCountSb) imgCountSb.textContent = n > 0 ? txt + ' uploaded' : 'No images uploaded';
646
+ }
647
+
648
+ function addImage(b64, name) {
649
+ images.push({id: Date.now() + Math.random(), b64: b64, name: name});
650
+ renderGallery();
651
+ syncImagesToGradio();
652
+ }
653
+ window.__addImage = addImage;
654
+
655
+ function removeImage(idx) {
656
+ images.splice(idx, 1);
657
+ if (selectedIdx === idx) selectedIdx = -1;
658
+ else if (selectedIdx > idx) selectedIdx--;
659
+ renderGallery();
660
+ syncImagesToGradio();
661
+ }
662
+
663
+ function clearAll() {
664
+ images = [];
665
+ window.__uploadedImages = images;
666
+ selectedIdx = -1;
667
+ renderGallery();
668
+ syncImagesToGradio();
669
+ }
670
+ window.__clearAll = clearAll;
671
+
672
+ function selectImage(idx) {
673
+ selectedIdx = (selectedIdx === idx) ? -1 : idx;
674
+ renderGallery();
675
+ }
676
+
677
+ function renderGallery() {
678
+ if (images.length === 0) {
679
+ galleryGrid.innerHTML = '';
680
+ galleryGrid.style.display = 'none';
681
+ if (uploadPrompt) uploadPrompt.style.display = '';
682
+ return;
683
+ }
684
+ if (uploadPrompt) uploadPrompt.style.display = 'none';
685
+ galleryGrid.style.display = 'grid';
686
+
687
+ let html = '';
688
+ images.forEach((img, i) => {
689
+ const sel = i === selectedIdx ? ' selected' : '';
690
+ html += '<div class="gallery-thumb' + sel + '" data-idx="' + i + '">'
691
+ + '<img src="' + img.b64 + '" alt="' + (img.name||'image') + '">'
692
+ + '<span class="thumb-badge">#' + (i+1) + '</span>'
693
+ + '<button class="thumb-remove" data-remove="' + i + '">\u2715</button>'
694
+ + '</div>';
695
+ });
696
+ html += '<div class="gallery-add-card" id="gallery-add-card">'
697
+ + '<span class="add-icon">+</span>'
698
+ + '<span class="add-text">Add</span>'
699
+ + '</div>';
700
+ galleryGrid.innerHTML = html;
701
+
702
+ galleryGrid.querySelectorAll('.gallery-thumb').forEach(thumb => {
703
+ thumb.addEventListener('click', (e) => {
704
+ if (e.target.closest('.thumb-remove')) return;
705
+ selectImage(parseInt(thumb.dataset.idx));
706
+ });
707
+ });
708
+ galleryGrid.querySelectorAll('.thumb-remove').forEach(btn => {
709
+ btn.addEventListener('click', (e) => {
710
+ e.stopPropagation();
711
+ removeImage(parseInt(btn.dataset.remove));
712
+ });
713
+ });
714
+ const addCard = document.getElementById('gallery-add-card');
715
+ if (addCard) addCard.addEventListener('click', () => fileInput.click());
716
+ }
717
+
718
+ function processFiles(files) {
719
+ Array.from(files).forEach(file => {
720
+ if (!file.type.startsWith('image/')) return;
721
+ const reader = new FileReader();
722
+ reader.onload = (e) => addImage(e.target.result, file.name);
723
+ reader.readAsDataURL(file);
724
+ });
725
+ }
726
+
727
+ fileInput.addEventListener('change', (e) => { processFiles(e.target.files); e.target.value = ''; });
728
+ if (uploadClick) uploadClick.addEventListener('click', () => fileInput.click());
729
+ if (btnUpload) btnUpload.addEventListener('click', () => fileInput.click());
730
+ if (btnRemove) btnRemove.addEventListener('click', () => {
731
+ if (selectedIdx >= 0 && selectedIdx < images.length) removeImage(selectedIdx);
732
+ });
733
+ if (btnClear) btnClear.addEventListener('click', clearAll);
734
+
735
+ dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); });
736
+ dropZone.addEventListener('dragleave', (e) => { e.preventDefault(); dropZone.classList.remove('drag-over'); });
737
+ dropZone.addEventListener('drop', (e) => {
738
+ e.preventDefault(); dropZone.classList.remove('drag-over');
739
+ if (e.dataTransfer.files.length) processFiles(e.dataTransfer.files);
740
+ });
741
+
742
+ if (promptInput) promptInput.addEventListener('input', syncPromptToGradio);
743
+
744
+ window.__setPrompt = function(text) {
745
+ if (promptInput) { promptInput.value = text; syncPromptToGradio(); }
746
+ };
747
+
748
+ document.querySelectorAll('.example-card[data-idx]').forEach(card => {
749
+ card.addEventListener('click', () => {
750
+ const idx = card.getAttribute('data-idx');
751
+ document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
752
+ card.classList.add('loading');
753
+ showToast('Loading example...', 'info');
754
+
755
+ setGradioValue('example-result-data', '');
756
+ setGradioValue('example-idx-input', idx);
757
+
758
+ setTimeout(() => {
759
+ const btn = document.getElementById('example-load-btn');
760
+ if (btn) {
761
+ const b = btn.querySelector('button');
762
+ if (b) b.click(); else btn.click();
763
+ }
764
+ }, 150);
765
+
766
+ setTimeout(() => card.classList.remove('loading'), 12000);
767
+ });
768
+ });
769
+
770
+ function syncSlider(customId, gradioId) {
771
+ const slider = document.getElementById(customId);
772
+ const valSpan = document.getElementById(customId + '-val');
773
+ if (!slider) return;
774
+ slider.addEventListener('input', () => {
775
+ if (valSpan) valSpan.textContent = slider.value;
776
+ const container = document.getElementById(gradioId);
777
+ if (!container) return;
778
+ container.querySelectorAll('input[type="range"],input[type="number"]').forEach(el => {
779
+ const ns = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
780
+ if (ns && ns.set) {
781
+ ns.set.call(el, slider.value);
782
+ el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));
783
+ el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));
784
+ }
785
+ });
786
+ });
787
+ }
788
+ syncSlider('custom-seed', 'gradio-seed');
789
+ syncSlider('custom-guidance', 'gradio-guidance');
790
+ syncSlider('custom-steps', 'gradio-steps');
791
+
792
+ const randCheck = document.getElementById('custom-randomize');
793
+ if (randCheck) {
794
+ randCheck.addEventListener('change', () => {
795
+ const container = document.getElementById('gradio-randomize');
796
+ if (!container) return;
797
+ const cb = container.querySelector('input[type="checkbox"]');
798
+ if (cb && cb.checked !== randCheck.checked) cb.click();
799
+ });
800
+ }
801
+
802
+ function showLoader() {
803
+ const l = document.getElementById('output-loader');
804
+ if (l) l.classList.add('active');
805
+ const sb = document.querySelector('.sb-fixed');
806
+ if (sb) sb.textContent = 'Processing...';
807
+ }
808
+ function hideLoader() {
809
+ const l = document.getElementById('output-loader');
810
+ if (l) l.classList.remove('active');
811
+ const sb = document.querySelector('.sb-fixed');
812
+ if (sb) sb.textContent = 'Done';
813
+ }
814
+ window.__showLoader = showLoader;
815
+ window.__hideLoader = hideLoader;
816
 
817
+ function validateBeforeRun() {
818
+ const promptVal = promptInput ? promptInput.value.trim() : '';
819
+ const hasImages = images.length > 0;
820
+ if (!hasImages && !promptVal) { showToast('Please upload an image and enter a prompt', 'error'); flashPromptError(); return false; }
821
+ if (!hasImages) { showToast('Please upload at least one image', 'error'); return false; }
822
+ if (!promptVal) { showToast('Please enter an edit prompt', 'warning'); flashPromptError(); return false; }
823
+ return true;
824
+ }
825
+
826
+ window.__clickGradioRunBtn = function() {
827
+ if (!validateBeforeRun()) return;
828
+ syncPromptToGradio(); syncImagesToGradio(); showLoader();
829
+ setTimeout(() => {
830
+ const gradioBtn = document.getElementById('gradio-run-btn');
831
+ if (!gradioBtn) return;
832
+ const btn = gradioBtn.querySelector('button');
833
+ if (btn) btn.click(); else gradioBtn.click();
834
+ }, 200);
835
+ };
836
+
837
+ if (runBtnEl) runBtnEl.addEventListener('click', () => window.__clickGradioRunBtn());
838
+
839
+ renderGallery();
840
+ updateCounts();
841
+ }
842
+ init();
843
+ }
844
+ """
845
+
846
+ wire_outputs_js = r"""
847
+ () => {
848
+ function watchOutputs() {
849
+ const resultContainer = document.getElementById('gradio-result');
850
+ const outBody = document.getElementById('output-image-container');
851
+ const outPh = document.getElementById('output-placeholder');
852
+ const dlBtn = document.getElementById('dl-btn-output');
853
+
854
+ if (!resultContainer || !outBody) { setTimeout(watchOutputs, 500); return; }
855
+
856
+ if (dlBtn) {
857
+ dlBtn.addEventListener('click', (e) => {
858
+ e.stopPropagation();
859
+ const img = outBody.querySelector('img.modern-out-img');
860
+ if (img && img.src) {
861
+ const a = document.createElement('a');
862
+ a.href = img.src; a.download = 'firered_output.png';
863
+ document.body.appendChild(a); a.click(); document.body.removeChild(a);
864
+ }
865
+ });
866
+ }
867
+
868
+ function syncImage() {
869
+ const resultImg = resultContainer.querySelector('img');
870
+ if (resultImg && resultImg.src) {
871
+ if (outPh) outPh.style.display = 'none';
872
+ let existing = outBody.querySelector('img.modern-out-img');
873
+ if (!existing) { existing = document.createElement('img'); existing.className = 'modern-out-img'; outBody.appendChild(existing); }
874
+ if (existing.src !== resultImg.src) {
875
+ existing.src = resultImg.src;
876
+ if (dlBtn) dlBtn.classList.add('visible');
877
+ if (window.__hideLoader) window.__hideLoader();
878
+ }
879
+ }
880
+ }
881
+ const observer = new MutationObserver(syncImage);
882
+ observer.observe(resultContainer, {childList:true, subtree:true, attributes:true, attributeFilter:['src']});
883
+ setInterval(syncImage, 800);
884
+ }
885
+ watchOutputs();
886
+
887
+ function watchSeed() {
888
+ const seedContainer = document.getElementById('gradio-seed');
889
+ const seedSlider = document.getElementById('custom-seed');
890
+ const seedVal = document.getElementById('custom-seed-val');
891
+ if (!seedContainer || !seedSlider) { setTimeout(watchSeed, 500); return; }
892
+ function sync() {
893
+ const el = seedContainer.querySelector('input[type="range"],input[type="number"]');
894
+ if (el && el.value) { seedSlider.value = el.value; if (seedVal) seedVal.textContent = el.value; }
895
+ }
896
+ const obs = new MutationObserver(sync);
897
+ obs.observe(seedContainer, {childList:true, subtree:true, attributes:true, attributeFilter:['value']});
898
+ setInterval(sync, 1000);
899
+ }
900
+ watchSeed();
901
+
902
+ function watchExampleResults() {
903
+ const container = document.getElementById('example-result-data');
904
+ if (!container) { setTimeout(watchExampleResults, 500); return; }
905
+
906
+ let lastProcessed = '';
907
+
908
+ function checkResult() {
909
+ const el = container.querySelector('textarea') || container.querySelector('input');
910
+ if (!el) return;
911
+ const val = el.value;
912
+ if (!val || val === lastProcessed || val.length < 20) return;
913
+
914
+ try {
915
+ const data = JSON.parse(val);
916
+ if (data.status === 'ok' && data.images && data.images.length > 0) {
917
+ lastProcessed = val;
918
+
919
+ if (window.__clearAll) window.__clearAll();
920
+ if (window.__setPrompt && data.prompt) window.__setPrompt(data.prompt);
921
+
922
+ data.images.forEach((b64, i) => {
923
+ if (b64 && window.__addImage) {
924
+ const name = (data.names && data.names[i]) ? data.names[i] : ('example_' + (i+1) + '.jpg');
925
+ window.__addImage(b64, name);
926
+ }
927
+ });
928
+
929
+ document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
930
+ if (window.__showToast) window.__showToast('Example loaded β€” ' + data.images.length + ' image(s)', 'info');
931
+ } else if (data.status === 'error') {
932
+ document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
933
+ if (window.__showToast) window.__showToast('Could not load example images', 'error');
934
+ }
935
+ } catch(e) {
936
+ console.error('Example parse error:', e);
937
+ }
938
+ }
939
+
940
+ const obs = new MutationObserver(checkResult);
941
+ obs.observe(container, {childList:true, subtree:true, characterData:true, attributes:true});
942
+ setInterval(checkResult, 500);
943
+ }
944
+ watchExampleResults();
945
  }
 
946
  """
947
 
948
+ DOWNLOAD_SVG = '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 16l-5-5h3V4h4v7h3l-5 5z"/><path d="M20 18H4v2h16v-2z"/></svg>'
949
+
950
+ UPLOAD_SVG = '<svg class="tb-svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>'
951
+
952
+ REMOVE_SVG = '<svg class="tb-svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>'
953
+
954
+ CLEAR_SVG = '<svg class="tb-svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>'
955
+
956
+ FIRE_LOGO_SVG = '<svg viewBox="0 0 24 24" fill="white" xmlns="http://www.w3.org/2000/svg"><path d="M12 23c-3.6 0-8-2.69-8-7.5 0-3.5 3-6.5 4.5-8 .27-.27.75-.08.75.28v2.44c0 .42.5.63.72.28C12.28 7.5 13 3 13 1c0-.42.48-.64.8-.35C18 4.5 20 9 20 12c0 5.5-3.5 11-8 11z"/></svg>'
957
+
958
  with gr.Blocks() as demo:
959
+
960
+ hidden_images_b64 = gr.Textbox(value="[]", elem_id="hidden-images-b64", elem_classes="hidden-input", container=False)
961
+ prompt = gr.Textbox(value="", elem_id="prompt-gradio-input", elem_classes="hidden-input", container=False)
962
+ seed = gr.Slider(minimum=0, maximum=MAX_SEED, step=1, value=0, elem_id="gradio-seed", elem_classes="hidden-input", container=False)
963
+ randomize_seed = gr.Checkbox(value=True, elem_id="gradio-randomize", elem_classes="hidden-input", container=False)
964
+ guidance_scale = gr.Slider(minimum=1.0, maximum=10.0, step=0.1, value=1.0, elem_id="gradio-guidance", elem_classes="hidden-input", container=False)
965
+ steps = gr.Slider(minimum=1, maximum=50, step=1, value=4, elem_id="gradio-steps", elem_classes="hidden-input", container=False)
966
+ result = gr.Image(elem_id="gradio-result", elem_classes="hidden-input", container=False, format="png")
967
+
968
+ example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
969
+ example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
970
+ example_load_btn = gr.Button("Load Example", elem_id="example-load-btn")
971
+
972
+ gr.HTML(f"""
973
+ <div class="app-shell">
974
+
975
+ <div class="app-header">
976
+ <div class="app-header-left">
977
+ <div class="app-logo">{FIRE_LOGO_SVG}</div>
978
+ <span class="app-title">FireRed-Image-Edit</span>
979
+ <span class="app-badge">v1.1</span>
980
+ <span class="app-badge fast">4-Step Fast</span>
981
+ </div>
982
+ </div>
983
+
984
+ <div class="app-toolbar">
985
+ <button id="tb-upload" class="modern-tb-btn" title="Upload images">
986
+ {UPLOAD_SVG}<span class="tb-label">Upload</span>
987
+ </button>
988
+ <button id="tb-remove" class="modern-tb-btn" title="Remove selected image">
989
+ {REMOVE_SVG}<span class="tb-label">Remove</span>
990
+ </button>
991
+ <button id="tb-clear" class="modern-tb-btn" title="Clear all images">
992
+ {CLEAR_SVG}<span class="tb-label">Clear All</span>
993
+ </button>
994
+ <div class="tb-sep"></div>
995
+ <span id="tb-image-count" class="tb-info">No images</span>
996
+ </div>
997
+
998
+ <div class="app-main-row">
999
+ <div class="app-main-left">
1000
+ <div id="gallery-drop-zone">
1001
+ <div id="upload-prompt" class="upload-prompt-modern">
1002
+ <div id="upload-click-area" class="upload-click-area">
1003
+ <svg viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
1004
+ <rect x="8" y="14" width="64" height="52" rx="6" fill="none" stroke="#1E90FF" stroke-width="2" stroke-dasharray="4 3"/>
1005
+ <polygon points="12,62 30,40 42,50 54,34 68,62" fill="rgba(30,144,255,0.15)" stroke="#1E90FF" stroke-width="1.5"/>
1006
+ <circle cx="28" cy="30" r="6" fill="rgba(30,144,255,0.2)" stroke="#1E90FF" stroke-width="1.5"/>
1007
+ </svg>
1008
+ <span class="upload-main-text">Click or drag images here</span>
1009
+ <span class="upload-sub-text">Supports multiple images for reference-based editing and guided manipulation</span>
1010
+ </div>
1011
+ </div>
1012
+ <input id="custom-file-input" type="file" accept="image/*" multiple style="display:none;" />
1013
+ <div id="image-gallery-grid" class="image-gallery-grid" style="display:none;"></div>
1014
+ </div>
1015
+
1016
+ <div class="hint-bar">
1017
+ <b>Upload:</b> Click or drag to add images &nbsp;&middot;&nbsp;
1018
+ <b>Multi-image:</b> Upload multiple images for reference-based editing &nbsp;&middot;&nbsp;
1019
+ <kbd>Remove</kbd> deletes selected &nbsp;&middot;&nbsp;
1020
+ <kbd>Clear All</kbd> removes everything
1021
+ </div>
1022
+
1023
+ <div class="suggestions-section">
1024
+ <div class="suggestions-title">Quick Prompts</div>
1025
+ <div class="suggestions-wrap">
1026
+ <button class="suggestion-chip" onclick="window.__setPrompt('Transform the image into a dotted cartoon style.')">Cartoon Style</button>
1027
+ <button class="suggestion-chip" onclick="window.__setPrompt('Convert it to black and white.')">Black and White</button>
1028
+ <button class="suggestion-chip" onclick="window.__setPrompt('Add cinematic lighting with warm orange tones and film grain.')">Cinematic</button>
1029
+ <button class="suggestion-chip" onclick="window.__setPrompt('Transform into anime style illustration.')">Anime Style</button>
1030
+ <button class="suggestion-chip" onclick="window.__setPrompt('Apply oil painting effect with visible brush strokes.')">Oil Painting</button>
1031
+ <button class="suggestion-chip" onclick="window.__setPrompt('Enhance and upscale with more detail and clarity.')">Enhance</button>
1032
+ <button class="suggestion-chip" onclick="window.__setPrompt('Make it look like a watercolor painting with soft edges.')">Watercolor</button>
1033
+ <button class="suggestion-chip" onclick="window.__setPrompt('Add dramatic sunset sky and warm lighting.')">Sunset Glow</button>
1034
+ <button class="suggestion-chip" onclick="window.__setPrompt('Convert to detailed pencil sketch with cross-hatching and shading.')">Pencil Sketch</button>
1035
+ <button class="suggestion-chip" onclick="window.__setPrompt('Apply pop art style with bold colors and halftone patterns.')">Pop Art</button>
1036
+ <button class="suggestion-chip" onclick="window.__setPrompt('Apply a vintage retro film look with faded colors and light leaks.')">Vintage Retro</button>
1037
+ <button class="suggestion-chip" onclick="window.__setPrompt('Add neon glow effects with vibrant colors against a dark background.')">Neon Glow</button>
1038
+ <button class="suggestion-chip" onclick="window.__setPrompt('Convert to pixel art style with a retro 16-bit aesthetic.')">Pixel Art</button>
1039
+ <button class="suggestion-chip" onclick="window.__setPrompt('Simplify into a clean minimalist illustration with flat colors.')">Minimalist</button>
1040
+ <button class="suggestion-chip" onclick="window.__setPrompt('Convert to low poly 3D geometric art style.')">Low Poly 3D</button>
1041
+ <button class="suggestion-chip" onclick="window.__setPrompt('Transform into comic book style with bold outlines and cel shading.')">Comic Book</button>
1042
+ </div>
1043
+ </div>
1044
+
1045
+ <div class="examples-section">
1046
+ <div class="examples-title">Quick Examples</div>
1047
+ <div class="examples-scroll">
1048
+ {EXAMPLE_CARDS_HTML}
1049
+ </div>
1050
+ </div>
1051
+ </div>
1052
+
1053
+ <div class="app-main-right">
1054
+ <div class="panel-card">
1055
+ <div class="panel-card-title">Edit Instruction</div>
1056
+ <div class="panel-card-body">
1057
+ <label class="modern-label" for="custom-prompt-input">Prompt</label>
1058
+ <textarea id="custom-prompt-input" class="modern-textarea" rows="3" placeholder="e.g., transform into anime, upscale, change lighting..."></textarea>
1059
+ </div>
1060
+ </div>
1061
+
1062
+ <div style="padding:12px 20px;">
1063
+ <button id="custom-run-btn" class="btn-run">
1064
+ <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 23c-3.6 0-8-2.69-8-7.5 0-3.5 3-6.5 4.5-8 .27-.27.75-.08.75.28v2.44c0 .42.5.63.72.28C12.28 7.5 13 3 13 1c0-.42.48-.64.8-.35C18 4.5 20 9 20 12c0 5.5-3.5 11-8 11z"/></svg>
1065
+ <span id="run-btn-label">Edit Image</span>
1066
+ </button>
1067
+ </div>
1068
+
1069
+ <div class="output-frame" style="flex:1">
1070
+ <div class="out-title">
1071
+ <span>Output</span>
1072
+ <span id="dl-btn-output" class="out-download-btn" title="Download">
1073
+ {DOWNLOAD_SVG} Save
1074
+ </span>
1075
+ </div>
1076
+ <div class="out-body" id="output-image-container">
1077
+ <div class="modern-loader" id="output-loader">
1078
+ <div class="loader-spinner"></div>
1079
+ <div class="loader-text">Processing image...</div>
1080
+ <div class="loader-bar-track"><div class="loader-bar-fill"></div></div>
1081
+ </div>
1082
+ <div class="out-placeholder" id="output-placeholder">Result will appear here</div>
1083
+ </div>
1084
+ </div>
1085
+
1086
+ <div class="settings-group">
1087
+ <div class="settings-group-title">Advanced Settings</div>
1088
+ <div class="settings-group-body">
1089
+ <div class="slider-row">
1090
+ <label>Seed</label>
1091
+ <input type="range" id="custom-seed" min="0" max="2147483647" step="1" value="0">
1092
+ <span class="slider-val" id="custom-seed-val">0</span>
1093
+ </div>
1094
+ <div class="checkbox-row">
1095
+ <input type="checkbox" id="custom-randomize" checked>
1096
+ <label for="custom-randomize">Randomize seed</label>
1097
+ </div>
1098
+ <div class="slider-row">
1099
+ <label>Guidance</label>
1100
+ <input type="range" id="custom-guidance" min="1" max="10" step="0.1" value="1.0">
1101
+ <span class="slider-val" id="custom-guidance-val">1.0</span>
1102
+ </div>
1103
+ <div class="slider-row">
1104
+ <label>Steps</label>
1105
+ <input type="range" id="custom-steps" min="1" max="50" step="1" value="4">
1106
+ <span class="slider-val" id="custom-steps-val">4</span>
1107
+ </div>
1108
+ </div>
1109
+ </div>
1110
+ </div>
1111
+ </div>
1112
+
1113
+ <div class="exp-note">
1114
+ Experimental Space for <a href="https://huggingface.co/FireRedTeam/FireRed-Image-Edit-1.1" target="_blank">FireRed-Image-Edit-1.1</a>
1115
+ &middot; Open on <a href="https://github.com/PRITHIVSAKTHIUR/FireRed-Image-Edit-1.0-Fast" target="_blank">GitHub</a>
1116
+ </div>
1117
+
1118
+ <div class="app-statusbar">
1119
+ <div class="sb-section" id="sb-image-count">No images uploaded</div>
1120
+ <div class="sb-section sb-fixed">Ready</div>
1121
+ </div>
1122
+ </div>
1123
+ """)
1124
+
1125
+ run_btn = gr.Button("Run", elem_id="gradio-run-btn")
1126
+
1127
+ demo.load(fn=None, js=gallery_js)
1128
+ demo.load(fn=None, js=wire_outputs_js)
1129
+
1130
+ run_btn.click(
1131
  fn=infer,
1132
+ inputs=[hidden_images_b64, prompt, seed, randomize_seed, guidance_scale, steps],
1133
+ outputs=[result, seed],
1134
+ js=r"""(imgs, p, s, rs, gs, st) => {
1135
+ const images = window.__uploadedImages || [];
1136
+ const b64Array = images.map(img => img.b64);
1137
+ const imgsJson = JSON.stringify(b64Array);
1138
+ const promptEl = document.getElementById('custom-prompt-input');
1139
+ const promptVal = promptEl ? promptEl.value : p;
1140
+ return [imgsJson, promptVal, s, rs, gs, st];
1141
+ }""",
1142
+ )
1143
+
1144
+ example_load_btn.click(
1145
+ fn=load_example_data,
1146
+ inputs=[example_idx],
1147
+ outputs=[example_result],
1148
+ queue=False,
1149
  )
1150
 
1151
  if __name__ == "__main__":
1152
+ demo.queue(max_size=30).launch(
1153
+ css=css,
1154
+ mcp_server=True,
1155
+ ssr_mode=False,
1156
+ show_error=True,
1157
+ allowed_paths=["examples"],
1158
+ )