Gerasimo commited on
Commit
cd47f99
·
verified ·
1 Parent(s): b5511e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1187
app.py CHANGED
@@ -1178,1193 +1178,6 @@ with gr.Blocks() as demo:
1178
  queue=False,
1179
  )
1180
 
1181
- if __name__ == "__main__":
1182
- demo.queue(max_size=50).launch(
1183
- css=css,
1184
- mcp_server=True,
1185
- ssr_mode=False,
1186
- show_error=True,
1187
- allowed_paths=["examples"],
1188
- )import os
1189
- import gc
1190
- import gradio as gr
1191
- import numpy as np
1192
- import spaces
1193
- import torch
1194
- import random
1195
- import base64
1196
- import json
1197
- import html as html_lib
1198
- from io import BytesIO
1199
- from PIL import Image
1200
-
1201
- MAX_SEED = np.iinfo(np.int32).max
1202
- LANCZOS = getattr(Image, "Resampling", Image).LANCZOS
1203
-
1204
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
1205
-
1206
- print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
1207
- print("torch.__version__ =", torch.__version__)
1208
- print("torch.version.cuda =", torch.version.cuda)
1209
- print("cuda available:", torch.cuda.is_available())
1210
- print("cuda device count:", torch.cuda.device_count())
1211
- if torch.cuda.is_available():
1212
- print("current device:", torch.cuda.current_device())
1213
- print("device name:", torch.cuda.get_device_name(torch.cuda.current_device()))
1214
-
1215
- print("Using device:", device)
1216
-
1217
- from diffusers import FlowMatchEulerDiscreteScheduler
1218
- from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
1219
- from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
1220
- from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3
1221
-
1222
- dtype = torch.bfloat16
1223
-
1224
- pipe = QwenImageEditPlusPipeline.from_pretrained(
1225
- "FireRedTeam/FireRed-Image-Edit-1.1",
1226
- transformer=QwenImageTransformer2DModel.from_pretrained(
1227
- "prithivMLmods/Qwen-Image-Edit-Rapid-AIO-V19",
1228
- torch_dtype=dtype,
1229
- device_map="cuda",
1230
- ),
1231
- torch_dtype=dtype,
1232
- safety_checker=None, # <-- Добавьте эту строку
1233
- feature_extractor=None, # <-- Добавьте эту строку
1234
- ).to(device)
1235
-
1236
- # Отключение проверки на уровне экземпляра pipeline
1237
- if hasattr(pipe, "safety_checker"):
1238
- pipe.safety_checker = None
1239
-
1240
- try:
1241
- pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())
1242
- print("Flash Attention 3 Processor set successfully.")
1243
- except Exception as e:
1244
- print(f"Warning: Could not set FA3 processor: {e}")
1245
-
1246
- EXAMPLES_CONFIG = [
1247
- {
1248
- "images": ["examples/1.jpg"],
1249
- "prompt": "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed 'Fire-Edit' preserving realistic texture and details.",
1250
- },
1251
- {
1252
- "images": ["examples/2.jpg"],
1253
- "prompt": "Transform the image into a dotted cartoon style.",
1254
- },
1255
- {
1256
- "images": ["examples/3.jpeg"],
1257
- "prompt": "Convert it to black and white.",
1258
- },
1259
- {
1260
- "images": ["examples/4.jpg", "examples/5.jpg"],
1261
- "prompt": "Replace her glasses with the new glasses from image 1.",
1262
- },
1263
- {
1264
- "images": ["examples/8.jpg", "examples/9.png"],
1265
- "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.",
1266
- },
1267
- {
1268
- "images": ["examples/10.jpg", "examples/11.png"],
1269
- "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.",
1270
- },
1271
- ]
1272
-
1273
-
1274
- def make_thumb_b64(path, max_dim=220):
1275
- if not os.path.exists(path):
1276
- return ""
1277
- try:
1278
- img = Image.open(path).convert("RGB")
1279
- img.thumbnail((max_dim, max_dim), LANCZOS)
1280
- buf = BytesIO()
1281
- img.save(buf, format="JPEG", quality=65)
1282
- return f"data:image/jpeg;base64,{base64.b64encode(buf.getvalue()).decode()}"
1283
- except Exception as e:
1284
- print(f"Thumbnail error for {path}: {e}")
1285
- return ""
1286
-
1287
-
1288
- def encode_full_image(path):
1289
- if not os.path.exists(path):
1290
- return ""
1291
- try:
1292
- with open(path, "rb") as f:
1293
- data = f.read()
1294
- ext = path.rsplit(".", 1)[-1].lower()
1295
- mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp"}.get(ext, "image/jpeg")
1296
- return f"data:{mime};base64,{base64.b64encode(data).decode()}"
1297
- except Exception as e:
1298
- print(f"Encode error for {path}: {e}")
1299
- return ""
1300
-
1301
-
1302
- def build_example_cards_html():
1303
- cards = ""
1304
- for i, ex in enumerate(EXAMPLES_CONFIG):
1305
- thumbs_html = ""
1306
- for path in ex["images"]:
1307
- thumb = make_thumb_b64(path)
1308
- if thumb:
1309
- thumbs_html += f'<img src="{thumb}" alt="">'
1310
- else:
1311
- thumbs_html += '<div class="example-thumb-placeholder">Preview</div>'
1312
- n = len(ex["images"])
1313
- badge = f'{n} image{"s" if n > 1 else ""}'
1314
- prompt_short = html_lib.escape(ex["prompt"][:90])
1315
- if len(ex["prompt"]) > 90:
1316
- prompt_short += "..."
1317
- cards += f'''<div class="example-card" data-idx="{i}">
1318
- <div class="example-thumbs">{thumbs_html}</div>
1319
- <div class="example-meta"><span class="example-badge">{badge}</span></div>
1320
- <div class="example-prompt-text">{prompt_short}</div>
1321
- </div>'''
1322
- return cards
1323
-
1324
-
1325
- def load_example_data(idx_str):
1326
- try:
1327
- idx = int(float(idx_str)) if idx_str and idx_str.strip() else -1
1328
- except (ValueError, TypeError):
1329
- idx = -1
1330
- if idx < 0 or idx >= len(EXAMPLES_CONFIG):
1331
- return json.dumps({"images": [], "prompt": "", "names": [], "status": "error"})
1332
- ex = EXAMPLES_CONFIG[idx]
1333
- b64_list, names = [], []
1334
- for path in ex["images"]:
1335
- b64 = encode_full_image(path)
1336
- if b64:
1337
- b64_list.append(b64)
1338
- names.append(os.path.basename(path))
1339
- return json.dumps({"images": b64_list, "prompt": ex["prompt"], "names": names, "status": "ok"})
1340
-
1341
-
1342
- print("Building example thumbnails...")
1343
- EXAMPLE_CARDS_HTML = build_example_cards_html()
1344
- print(f"Built {len(EXAMPLES_CONFIG)} example cards.")
1345
-
1346
-
1347
- def b64_to_pil_list(b64_json_str):
1348
- if not b64_json_str or b64_json_str.strip() in ("", "[]"):
1349
- return []
1350
- try:
1351
- b64_list = json.loads(b64_json_str)
1352
- except Exception:
1353
- return []
1354
- pil_images = []
1355
- for b64_str in b64_list:
1356
- if not b64_str or not isinstance(b64_str, str):
1357
- continue
1358
- try:
1359
- if b64_str.startswith("data:image"):
1360
- _, data = b64_str.split(",", 1)
1361
- else:
1362
- data = b64_str
1363
- image_data = base64.b64decode(data)
1364
- pil_images.append(Image.open(BytesIO(image_data)).convert("RGB"))
1365
- except Exception as e:
1366
- print(f"Error decoding image: {e}")
1367
- return pil_images
1368
-
1369
-
1370
- def update_dimensions_on_upload(image):
1371
- if image is None:
1372
- return 1024, 1024
1373
- w, h = image.size
1374
- target_dim = 1024
1375
- if w > h:
1376
- nw = target_dim
1377
- nh = int(nw * h / w)
1378
- else:
1379
- nh = target_dim
1380
- nw = int(nh * w / h)
1381
- return (nw // 8) * 8, (nh // 8) * 8
1382
-
1383
-
1384
- @spaces.GPU(size="xlarge")
1385
- def infer(images_b64_json, prompt, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress(track_tqdm=True)):
1386
- gc.collect()
1387
- torch.cuda.empty_cache()
1388
- pil_images = b64_to_pil_list(images_b64_json)
1389
- if not pil_images:
1390
- raise gr.Error("Please upload at least one image to edit.")
1391
- if not prompt or prompt.strip() == "":
1392
- raise gr.Error("Please enter an edit prompt.")
1393
- if randomize_seed:
1394
- seed = random.randint(0, MAX_SEED)
1395
- generator = torch.Generator(device=device).manual_seed(seed)
1396
- negative_prompt = "blurry, low resolution, low quality, soft details, artifacts, pixelated, plastic skin, smooth skin, 3d render, cartoon, anime, blurry, low resolution, bad anatomy, overprocessed, oversaturated, painting, drawing"
1397
- width, height = update_dimensions_on_upload(pil_images[0])
1398
- try:
1399
- result_image = pipe(
1400
- image=pil_images, prompt=prompt, negative_prompt=negative_prompt,
1401
- height=height, width=width, num_inference_steps=steps,
1402
- generator=generator, true_cfg_scale=guidance_scale,
1403
- ).images[0]
1404
- return result_image, seed
1405
- except Exception as e:
1406
- raise e
1407
- finally:
1408
- gc.collect()
1409
- torch.cuda.empty_cache()
1410
-
1411
-
1412
- css = r"""
1413
- @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');
1414
- *{box-sizing:border-box;margin:0;padding:0}
1415
- body,.gradio-container{
1416
- background:#0f0f13!important;font-family:'Inter',system-ui,-apple-system,sans-serif!important;
1417
- font-size:14px!important;color:#e4e4e7!important;min-height:100vh;
1418
- }
1419
- .dark body,.dark .gradio-container{background:#0f0f13!important;color:#e4e4e7!important}
1420
- footer{display:none!important}
1421
- .hidden-input{display:none!important;height:0!important;overflow:hidden!important;margin:0!important;padding:0!important}
1422
- #example-load-btn{
1423
- position:absolute!important;left:-9999px!important;top:-9999px!important;
1424
- width:1px!important;height:1px!important;opacity:0.01!important;
1425
- pointer-events:none!important;overflow:hidden!important;
1426
- }
1427
- #gradio-run-btn{
1428
- position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;
1429
- opacity:0.01;pointer-events:none;overflow:hidden;
1430
- }
1431
- /* ── App shell ── */
1432
- .app-shell{
1433
- background:#18181b;border:1px solid #27272a;border-radius:16px;
1434
- margin:12px auto;max-width:1400px;overflow:hidden;
1435
- box-shadow:0 25px 50px -12px rgba(0,0,0,.6),0 0 0 1px rgba(255,255,255,.03);
1436
- }
1437
- /* ── Header ── */
1438
- .app-header{
1439
- background:linear-gradient(135deg,#18181b,#1e1e24);border-bottom:1px solid #27272a;
1440
- padding:14px 24px;display:flex;align-items:center;justify-content:space-between;
1441
- flex-wrap:wrap;gap:12px;
1442
- }
1443
- .app-header-left{display:flex;align-items:center;gap:12px}
1444
- .app-logo{
1445
- width:36px;height:36px;background:linear-gradient(135deg,#FF0000,#FF3333,#FF8080);
1446
- border-radius:10px;display:flex;align-items:center;justify-content:center;
1447
- box-shadow:0 4px 12px rgba(255,0,0,.35);flex-shrink:0;
1448
- }
1449
- .app-logo svg{width:20px;height:20px;fill:#fff;flex-shrink:0}
1450
- .app-title{
1451
- font-size:18px;font-weight:700;background:linear-gradient(135deg,#e4e4e7,#a1a1aa);
1452
- -webkit-background-clip:text;-webkit-text-fill-color:transparent;letter-spacing:-.3px;
1453
- }
1454
- .app-badge{
1455
- font-size:11px;font-weight:600;padding:3px 10px;border-radius:20px;
1456
- background:rgba(255,0,0,.15);color:#FF3333;border:1px solid rgba(255,0,0,.25);letter-spacing:.3px;
1457
- }
1458
- .app-badge.fast{background:rgba(34,197,94,.12);color:#4ade80;border:1px solid rgba(34,197,94,.25)}
1459
- /* ── GitHub button ── */
1460
- .gh-btn{
1461
- display:inline-flex!important;align-items:center!important;gap:7px!important;
1462
- padding:7px 16px!important;border-radius:8px!important;text-decoration:none!important;
1463
- font-family:'Inter',sans-serif!important;font-size:13px!important;font-weight:700!important;
1464
- letter-spacing:.1px!important;background:#FF0000!important;
1465
- color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;
1466
- border:1px solid rgba(255,255,255,.18)!important;
1467
- box-shadow:0 2px 10px rgba(255,0,0,.45),0 1px 0 rgba(255,255,255,.1) inset!important;
1468
- transition:transform .15s ease,box-shadow .15s ease,background .15s ease!important;
1469
- cursor:pointer!important;flex-shrink:0!important;
1470
- }
1471
- .gh-btn:hover{
1472
- background:#FF3333!important;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;
1473
- transform:translateY(-1px)!important;
1474
- box-shadow:0 5px 18px rgba(255,0,0,.6),0 1px 0 rgba(255,255,255,.12) inset!important;
1475
- }
1476
- .gh-btn:active{
1477
- background:#CC0000!important;transform:translateY(0)!important;
1478
- box-shadow:0 1px 5px rgba(255,0,0,.35)!important;
1479
- }
1480
- .gh-btn svg{fill:#ffffff!important;flex-shrink:0;width:15px!important;height:15px!important}
1481
- .gh-btn span{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
1482
- /* ── Toolbar ── */
1483
- .app-toolbar{
1484
- background:#18181b;border-bottom:1px solid #27272a;padding:8px 16px;
1485
- display:flex;gap:4px;align-items:center;flex-wrap:wrap;
1486
- }
1487
- .tb-sep{width:1px;height:28px;background:#27272a;margin:0 8px}
1488
- .modern-tb-btn{
1489
- display:inline-flex;align-items:center;justify-content:center;gap:6px;
1490
- min-width:32px;height:34px;background:transparent;border:1px solid transparent;
1491
- border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;padding:0 12px;
1492
- font-family:'Inter',sans-serif;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;
1493
- transition:all .15s ease;
1494
- }
1495
- .modern-tb-btn:hover{background:rgba(255,0,0,.15);border-color:rgba(255,0,0,.3)}
1496
- .modern-tb-btn:active,.modern-tb-btn.active{background:rgba(255,0,0,.25);border-color:rgba(255,0,0,.45)}
1497
- .modern-tb-btn .tb-label{font-size:13px;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;font-weight:600}
1498
- .modern-tb-btn .tb-svg{width:15px;height:15px;flex-shrink:0;color:#ffffff!important}
1499
- .modern-tb-btn .tb-svg,
1500
- .modern-tb-btn .tb-svg *{stroke:#ffffff!important;fill:none!important}
1501
- .tb-info{font-family:'JetBrains Mono',monospace;font-size:12px;color:#71717a;padding:0 8px;display:flex;align-items:center}
1502
- body:not(.dark) .modern-tb-btn,body:not(.dark) .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
1503
- body:not(.dark) .modern-tb-btn .tb-svg,body:not(.dark) .modern-tb-btn .tb-svg *{stroke:#ffffff!important}
1504
- .dark .modern-tb-btn,.dark .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
1505
- .dark .modern-tb-btn .tb-svg,.dark .modern-tb-btn .tb-svg *{stroke:#ffffff!important}
1506
- .gradio-container .modern-tb-btn,.gradio-container .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
1507
- .gradio-container .modern-tb-btn .tb-svg,.gradio-container .modern-tb-btn .tb-svg *{stroke:#ffffff!important}
1508
- /* ── Main layout ── */
1509
- .app-main-row{display:flex;gap:0;flex:1;overflow:hidden}
1510
- .app-main-left{flex:1;display:flex;flex-direction:column;min-width:0;border-right:1px solid #27272a}
1511
- .app-main-right{width:420px;display:flex;flex-direction:column;flex-shrink:0;background:#18181b}
1512
- /* ── Drop zone ── */
1513
- #gallery-drop-zone{position:relative;background:#09090b;min-height:440px;overflow:auto}
1514
- #gallery-drop-zone.drag-over{outline:2px solid #FF0000;outline-offset:-2px;background:rgba(255,0,0,.04)}
1515
- .upload-prompt-modern{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:20}
1516
- .upload-click-area{
1517
- display:flex;flex-direction:column;align-items:center;justify-content:center;
1518
- cursor:pointer;padding:36px 52px;border:2px dashed #3f3f46;border-radius:16px;
1519
- background:rgba(255,0,0,.03);transition:all .2s ease;gap:8px;
1520
- }
1521
- .upload-click-area:hover{background:rgba(255,0,0,.08);border-color:#FF0000;transform:scale(1.03)}
1522
- .upload-click-area:active{background:rgba(255,0,0,.12);transform:scale(.98)}
1523
- .upload-click-area svg{width:80px;height:80px}
1524
- .upload-main-text{color:#71717a;font-size:14px;font-weight:500;margin-top:4px}
1525
- .upload-sub-text{color:#52525b;font-size:12px;text-align:center;max-width:280px;line-height:1.5}
1526
- /* ── Gallery grid ── */
1527
- .image-gallery-grid{
1528
- display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));
1529
- gap:12px;padding:16px;align-content:start;
1530
- }
1531
- .gallery-thumb{
1532
- position:relative;aspect-ratio:1;border-radius:10px;overflow:hidden;
1533
- cursor:pointer;border:2px solid #27272a;transition:all .2s ease;background:#18181b;
1534
- }
1535
- .gallery-thumb:hover{border-color:#3f3f46;transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,.4)}
1536
- .gallery-thumb.selected{border-color:#FF0000!important;box-shadow:0 0 0 3px rgba(255,0,0,.2)}
1537
- .gallery-thumb img{width:100%;height:100%;object-fit:cover}
1538
- .thumb-badge{
1539
- position:absolute;top:6px;left:6px;background:#FF0000;color:#fff;
1540
- padding:2px 8px;border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:600;
1541
- }
1542
- .thumb-remove{
1543
- position:absolute;top:6px;right:6px;width:24px;height:24px;background:rgba(0,0,0,.75);
1544
- color:#fff;border:1px solid rgba(255,255,255,.15);border-radius:50%;cursor:pointer;
1545
- display:none;align-items:center;justify-content:center;font-size:12px;transition:all .15s;line-height:1;
1546
- }
1547
- .gallery-thumb:hover .thumb-remove{display:flex}
1548
- .thumb-remove:hover{background:#FF0000;border-color:#FF0000}
1549
- .gallery-add-card{
1550
- aspect-ratio:1;border-radius:10px;border:2px dashed #3f3f46;
1551
- display:flex;flex-direction:column;align-items:center;justify-content:center;
1552
- cursor:pointer;transition:all .2s ease;background:rgba(255,0,0,.03);gap:4px;
1553
- }
1554
- .gallery-add-card:hover{border-color:#FF0000;background:rgba(255,0,0,.08)}
1555
- .gallery-add-card .add-icon{font-size:28px;color:#71717a;font-weight:300}
1556
- .gallery-add-card .add-text{font-size:12px;color:#71717a;font-weight:500}
1557
- /* ── Hint bar ── */
1558
- .hint-bar{
1559
- background:rgba(255,0,0,.06);border-top:1px solid #27272a;border-bottom:1px solid #27272a;
1560
- padding:10px 20px;font-size:13px;color:#a1a1aa;line-height:1.7;
1561
- }
1562
- .hint-bar b{color:#FF8080;font-weight:600}
1563
- .hint-bar kbd{
1564
- display:inline-block;padding:1px 6px;background:#27272a;border:1px solid #3f3f46;
1565
- border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#a1a1aa;
1566
- }
1567
- /* ── Suggestions ── */
1568
- .suggestions-section{border-top:1px solid #27272a;padding:12px 16px}
1569
- .suggestions-title,.examples-title{
1570
- font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;
1571
- letter-spacing:.8px;margin-bottom:10px;
1572
- }
1573
- .suggestions-wrap{display:flex;flex-wrap:wrap;gap:6px}
1574
- .suggestion-chip{
1575
- display:inline-flex;align-items:center;gap:4px;padding:5px 12px;
1576
- background:rgba(255,0,0,.08);border:1px solid rgba(255,0,0,.2);border-radius:20px;
1577
- color:#FF8080;font-size:12px;font-weight:500;font-family:'Inter',sans-serif;
1578
- cursor:pointer;transition:all .15s;white-space:nowrap;
1579
- }
1580
- .suggestion-chip:hover{background:rgba(255,0,0,.15);border-color:rgba(255,0,0,.35);color:#FF3333;transform:translateY(-1px)}
1581
- /* ── Examples ── */
1582
- .examples-section{border-top:1px solid #27272a;padding:12px 16px}
1583
- .examples-scroll{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px}
1584
- .examples-scroll::-webkit-scrollbar{height:6px}
1585
- .examples-scroll::-webkit-scrollbar-track{background:#09090b;border-radius:3px}
1586
- .examples-scroll::-webkit-scrollbar-thumb{background:#27272a;border-radius:3px}
1587
- .examples-scroll::-webkit-scrollbar-thumb:hover{background:#3f3f46}
1588
- .example-card{
1589
- flex-shrink:0;width:210px;background:#09090b;border:1px solid #27272a;
1590
- border-radius:10px;overflow:hidden;cursor:pointer;transition:all .2s ease;
1591
- }
1592
- .example-card:hover{border-color:#FF0000;transform:translateY(-2px);box-shadow:0 4px 12px rgba(255,0,0,.15)}
1593
- .example-card.loading{opacity:.5;pointer-events:none}
1594
- .example-thumbs{display:flex;height:110px;overflow:hidden;background:#18181b}
1595
- .example-thumbs img{flex:1;object-fit:cover;min-width:0;border-bottom:1px solid #27272a}
1596
- .example-thumb-placeholder{
1597
- flex:1;display:flex;align-items:center;justify-content:center;
1598
- background:#18181b;color:#3f3f46;font-size:11px;min-width:0;
1599
- }
1600
- .example-meta{padding:6px 10px;display:flex;align-items:center;gap:6px}
1601
- .example-badge{
1602
- display:inline-flex;padding:2px 7px;background:rgba(255,0,0,.1);border-radius:4px;
1603
- font-size:10px;font-weight:600;color:#FF3333;font-family:'JetBrains Mono',monospace;white-space:nowrap;
1604
- }
1605
- .example-prompt-text{
1606
- padding:0 10px 8px;font-size:11px;color:#a1a1aa;line-height:1.4;
1607
- display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;
1608
- }
1609
- /* ── Right panel ── */
1610
- .panel-card{border-bottom:1px solid #27272a}
1611
- .panel-card-title{
1612
- padding:12px 20px;font-size:12px;font-weight:600;color:#71717a;
1613
- text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid rgba(39,39,42,.6);
1614
- }
1615
- .panel-card-body{padding:16px 20px;display:flex;flex-direction:column;gap:8px}
1616
- .modern-label{font-size:13px;font-weight:500;color:#a1a1aa;margin-bottom:4px;display:block}
1617
- .modern-textarea{
1618
- width:100%;background:#09090b;border:1px solid #27272a;border-radius:8px;
1619
- padding:10px 14px;font-family:'Inter',sans-serif;font-size:14px;color:#e4e4e7;
1620
- resize:vertical;outline:none;min-height:42px;transition:border-color .2s;
1621
- }
1622
- .modern-textarea:focus{border-color:#FF0000;box-shadow:0 0 0 3px rgba(255,0,0,.15)}
1623
- .modern-textarea::placeholder{color:#3f3f46}
1624
- .modern-textarea.error-flash{
1625
- border-color:#ef4444!important;box-shadow:0 0 0 3px rgba(239,68,68,.2)!important;animation:shake .4s ease;
1626
- }
1627
- @keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-4px)}40%,80%{transform:translateX(4px)}}
1628
- /* ── Toast ── */
1629
- .toast-notification{
1630
- position:fixed;top:24px;left:50%;transform:translateX(-50%) translateY(-120%);
1631
- z-index:9999;padding:10px 24px;border-radius:10px;font-family:'Inter',sans-serif;
1632
- font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px;
1633
- box-shadow:0 8px 24px rgba(0,0,0,.5);
1634
- transition:transform .35s cubic-bezier(.34,1.56,.64,1),opacity .35s ease;opacity:0;pointer-events:none;
1635
- }
1636
- .toast-notification.visible{transform:translateX(-50%) translateY(0);opacity:1;pointer-events:auto}
1637
- .toast-notification.error{background:linear-gradient(135deg,#dc2626,#b91c1c);color:#fff;border:1px solid rgba(255,255,255,.15)}
1638
- .toast-notification.warning{background:linear-gradient(135deg,#d97706,#b45309);color:#fff;border:1px solid rgba(255,255,255,.15)}
1639
- .toast-notification.info{background:linear-gradient(135deg,#2563eb,#1d4ed8);color:#fff;border:1px solid rgba(255,255,255,.15)}
1640
- .toast-notification .toast-icon{font-size:16px;line-height:1}
1641
- .toast-notification .toast-text{line-height:1.3}
1642
- /* ── Run button ── */
1643
- .btn-run{
1644
- display:flex;align-items:center;justify-content:center;gap:8px;width:100%;
1645
- background:linear-gradient(135deg,#FF0000,#CC0000);border:none;border-radius:10px;
1646
- padding:12px 24px;cursor:pointer;font-size:15px;font-weight:600;font-family:'Inter',sans-serif;
1647
- color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;transition:all .2s ease;letter-spacing:-.2px;
1648
- box-shadow:0 4px 16px rgba(255,0,0,.3),inset 0 1px 0 rgba(255,255,255,.1);
1649
- }
1650
- .btn-run:hover{
1651
- background:linear-gradient(135deg,#FF3333,#FF0000);transform:translateY(-1px);
1652
- box-shadow:0 6px 24px rgba(255,0,0,.45),inset 0 1px 0 rgba(255,255,255,.15);
1653
- }
1654
- .btn-run:active{transform:translateY(0);box-shadow:0 2px 8px rgba(255,0,0,.3)}
1655
- .btn-run svg{width:18px;height:18px;fill:#ffffff!important}
1656
- .btn-run svg path{fill:#ffffff!important}
1657
- #custom-run-btn,#custom-run-btn *,#custom-run-btn span,#custom-run-btn svg,
1658
- #custom-run-btn svg path,#run-btn-label,.btn-run,.btn-run *{
1659
- color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important;
1660
- }
1661
- body:not(.dark) .btn-run,body:not(.dark) .btn-run *,body:not(.dark) #custom-run-btn,
1662
- body:not(.dark) #custom-run-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important}
1663
- .dark .btn-run,.dark .btn-run *,.dark #custom-run-btn,.dark #custom-run-btn *{
1664
- color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important;
1665
- }
1666
- .gradio-container .btn-run,.gradio-container .btn-run *,.gradio-container #custom-run-btn,
1667
- .gradio-container #custom-run-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important}
1668
- /* ── Output ── */
1669
- .output-frame{border-bottom:1px solid #27272a;display:flex;flex-direction:column;position:relative}
1670
- .output-frame .out-title{
1671
- padding:10px 20px;font-size:13px;font-weight:700;color:#ffffff!important;
1672
- -webkit-text-fill-color:#ffffff!important;text-transform:uppercase;letter-spacing:.8px;
1673
- border-bottom:1px solid rgba(39,39,42,.6);display:flex;align-items:center;justify-content:space-between;
1674
- }
1675
- .output-frame .out-title span{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
1676
- .output-frame .out-body{
1677
- flex:1;background:#09090b;display:flex;align-items:center;justify-content:center;
1678
- overflow:hidden;min-height:240px;position:relative;
1679
- }
1680
- .output-frame .out-body img{max-width:100%;max-height:460px;image-rendering:auto}
1681
- .output-frame .out-placeholder{color:#3f3f46;font-size:13px;text-align:center;padding:20px}
1682
- .out-download-btn{
1683
- display:none;align-items:center;justify-content:center;background:rgba(255,0,0,.1);
1684
- border:1px solid rgba(255,0,0,.2);border-radius:6px;cursor:pointer;padding:3px 10px;
1685
- font-size:11px;font-weight:500;color:#FF8080!important;gap:4px;height:24px;transition:all .15s;
1686
- }
1687
- .out-download-btn:hover{background:rgba(255,0,0,.2);border-color:rgba(255,0,0,.35);color:#ffffff!important}
1688
- .out-download-btn.visible{display:inline-flex}
1689
- .out-download-btn svg{width:12px;height:12px;fill:#FF8080}
1690
- /* ── Loader ── */
1691
- .modern-loader{
1692
- display:none;position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(9,9,11,.92);
1693
- z-index:15;flex-direction:column;align-items:center;justify-content:center;gap:16px;backdrop-filter:blur(4px);
1694
- }
1695
- .modern-loader.active{display:flex}
1696
- .modern-loader .loader-spinner{
1697
- width:36px;height:36px;border:3px solid #27272a;border-top-color:#FF0000;
1698
- border-radius:50%;animation:spin .8s linear infinite;
1699
- }
1700
- @keyframes spin{to{transform:rotate(360deg)}}
1701
- .modern-loader .loader-text{font-size:13px;color:#a1a1aa;font-weight:500}
1702
- .loader-bar-track{width:200px;height:4px;background:#27272a;border-radius:2px;overflow:hidden}
1703
- .loader-bar-fill{
1704
- height:100%;background:linear-gradient(90deg,#FF0000,#FF3333,#FF0000);
1705
- background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:2px;
1706
- }
1707
- @keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}
1708
- /* ── Settings ── */
1709
- .settings-group{border:1px solid #27272a;border-radius:10px;margin:12px 16px;padding:0;overflow:hidden}
1710
- .settings-group-title{
1711
- font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px;
1712
- padding:10px 16px;border-bottom:1px solid #27272a;background:rgba(24,24,27,.5);
1713
- }
1714
- .settings-group-body{padding:14px 16px;display:flex;flex-direction:column;gap:12px}
1715
- .slider-row{display:flex;align-items:center;gap:10px;min-height:28px}
1716
- .slider-row label{font-size:13px;font-weight:500;color:#a1a1aa;min-width:72px;flex-shrink:0}
1717
- .slider-row input[type="range"]{
1718
- flex:1;-webkit-appearance:none;appearance:none;height:6px;background:#27272a;
1719
- border-radius:3px;outline:none;min-width:0;
1720
- }
1721
- .slider-row input[type="range"]::-webkit-slider-thumb{
1722
- -webkit-appearance:none;width:16px;height:16px;background:linear-gradient(135deg,#FF0000,#CC0000);
1723
- border-radius:50%;cursor:pointer;box-shadow:0 2px 6px rgba(255,0,0,.4);transition:transform .15s;
1724
- }
1725
- .slider-row input[type="range"]::-webkit-slider-thumb:hover{transform:scale(1.2)}
1726
- .slider-row input[type="range"]::-moz-range-thumb{
1727
- width:16px;height:16px;background:linear-gradient(135deg,#FF0000,#CC0000);
1728
- border-radius:50%;cursor:pointer;border:none;box-shadow:0 2px 6px rgba(255,0,0,.4);
1729
- }
1730
- .slider-row .slider-val{
1731
- min-width:52px;text-align:right;font-family:'JetBrains Mono',monospace;font-size:12px;
1732
- font-weight:500;padding:3px 8px;background:#09090b;border:1px solid #27272a;
1733
- border-radius:6px;color:#a1a1aa;flex-shrink:0;
1734
- }
1735
- .checkbox-row{display:flex;align-items:center;gap:8px;font-size:13px;color:#a1a1aa}
1736
- .checkbox-row input[type="checkbox"]{accent-color:#FF0000;width:16px;height:16px;cursor:pointer}
1737
- .checkbox-row label{color:#a1a1aa;font-size:13px;cursor:pointer}
1738
- /* ── Status bar ── */
1739
- .app-statusbar{
1740
- background:#18181b;border-top:1px solid #27272a;padding:6px 20px;
1741
- display:flex;gap:12px;height:34px;align-items:center;font-size:12px;
1742
- }
1743
- .app-statusbar .sb-section{
1744
- padding:0 12px;flex:1;display:flex;align-items:center;font-family:'JetBrains Mono',monospace;
1745
- font-size:12px;color:#52525b;overflow:hidden;white-space:nowrap;
1746
- }
1747
- .app-statusbar .sb-section.sb-fixed{
1748
- flex:0 0 auto;min-width:90px;text-align:center;justify-content:center;
1749
- padding:3px 12px;background:rgba(255,0,0,.08);border-radius:6px;color:#FF3333;font-weight:500;
1750
- }
1751
- /* ── Footer note ── */
1752
- .exp-note{
1753
- padding:10px 20px;font-size:12px;color:#52525b;
1754
- border-top:1px solid #27272a;text-align:center;font-weight:500;
1755
- background:#18181b;font-family:'Inter',sans-serif;
1756
- }
1757
- .exp-note a{color:#FF3333;text-decoration:none}
1758
- .exp-note a:hover{text-decoration:underline}
1759
- /* ── Dark overrides ── */
1760
- .dark .app-shell{background:#18181b}
1761
- .dark .upload-prompt-modern{background:transparent}
1762
- .dark .panel-card{background:#18181b}
1763
- .dark .settings-group{background:#18181b}
1764
- .dark .output-frame .out-title{color:#ffffff!important}
1765
- .dark .output-frame .out-title span{color:#ffffff!important}
1766
- .dark .out-download-btn{color:#FF8080!important}
1767
- .dark .out-download-btn:hover{color:#ffffff!important}
1768
- /* ── Scrollbars ── */
1769
- ::-webkit-scrollbar{width:8px;height:8px}
1770
- ::-webkit-scrollbar-track{background:#09090b}
1771
- ::-webkit-scrollbar-thumb{background:#27272a;border-radius:4px}
1772
- ::-webkit-scrollbar-thumb:hover{background:#3f3f46}
1773
- /* ── Responsive ── */
1774
- @media(max-width:840px){
1775
- .app-main-row{flex-direction:column}
1776
- .app-main-right{width:100%}
1777
- .app-main-left{border-right:none;border-bottom:1px solid #27272a}
1778
- }
1779
- """
1780
-
1781
- gallery_js = r"""
1782
- () => {
1783
- function init() {
1784
- if (window.__fireRedInitDone) return;
1785
- const galleryGrid = document.getElementById('image-gallery-grid');
1786
- const dropZone = document.getElementById('gallery-drop-zone');
1787
- const uploadPrompt = document.getElementById('upload-prompt');
1788
- const uploadClick = document.getElementById('upload-click-area');
1789
- const fileInput = document.getElementById('custom-file-input');
1790
- const btnUpload = document.getElementById('tb-upload');
1791
- const btnRemove = document.getElementById('tb-remove');
1792
- const btnClear = document.getElementById('tb-clear');
1793
- const promptInput = document.getElementById('custom-prompt-input');
1794
- const runBtnEl = document.getElementById('custom-run-btn');
1795
- const imgCountTb = document.getElementById('tb-image-count');
1796
- const imgCountSb = document.getElementById('sb-image-count');
1797
- if (!galleryGrid || !fileInput || !dropZone) {
1798
- setTimeout(init, 250);
1799
- return;
1800
- }
1801
- window.__fireRedInitDone = true;
1802
- let images = [];
1803
- window.__uploadedImages = images;
1804
- let selectedIdx = -1;
1805
- let toastTimer = null;
1806
- /* ── GitHub button hover ── */
1807
- function enforceGhBtn() {
1808
- const ghBtn = document.querySelector('.gh-btn');
1809
- if (ghBtn && !ghBtn.__hoverBound) {
1810
- ghBtn.__hoverBound = true;
1811
- ghBtn.addEventListener('mouseenter', () => {
1812
- ghBtn.style.setProperty('background','#FF3333','important');
1813
- ghBtn.style.setProperty('transform','translateY(-1px)','important');
1814
- ghBtn.style.setProperty('box-shadow','0 5px 18px rgba(255,0,0,.6)','important');
1815
- });
1816
- ghBtn.addEventListener('mouseleave', () => {
1817
- ghBtn.style.setProperty('background','#FF0000','important');
1818
- ghBtn.style.setProperty('transform','translateY(0)','important');
1819
- ghBtn.style.setProperty('box-shadow','0 2px 10px rgba(255,0,0,.45)','important');
1820
- });
1821
- ghBtn.addEventListener('mousedown', () => ghBtn.style.setProperty('background','#CC0000','important'));
1822
- ghBtn.addEventListener('mouseup', () => ghBtn.style.setProperty('background','#FF3333','important'));
1823
- }
1824
- }
1825
- enforceGhBtn();
1826
- setInterval(enforceGhBtn, 1000);
1827
- function showToast(message, type) {
1828
- let toast = document.getElementById('app-toast');
1829
- if (!toast) {
1830
- toast = document.createElement('div');
1831
- toast.id = 'app-toast';
1832
- toast.className = 'toast-notification';
1833
- toast.innerHTML = '<span class="toast-icon"></span><span class="toast-text"></span>';
1834
- document.body.appendChild(toast);
1835
- }
1836
- const icon = toast.querySelector('.toast-icon');
1837
- const text = toast.querySelector('.toast-text');
1838
- toast.className = 'toast-notification ' + (type || 'error');
1839
- if (type === 'warning') icon.textContent = '\u26A0';
1840
- else if (type === 'info') icon.textContent = '\u2139';
1841
- else icon.textContent = '\u2717';
1842
- text.textContent = message;
1843
- if (toastTimer) clearTimeout(toastTimer);
1844
- void toast.offsetWidth;
1845
- toast.classList.add('visible');
1846
- toastTimer = setTimeout(() => toast.classList.remove('visible'), 3500);
1847
- }
1848
- window.__showToast = showToast;
1849
- function flashPromptError() {
1850
- if (!promptInput) return;
1851
- promptInput.classList.add('error-flash');
1852
- promptInput.focus();
1853
- setTimeout(() => promptInput.classList.remove('error-flash'), 800);
1854
- }
1855
- function setGradioValue(containerId, value) {
1856
- const container = document.getElementById(containerId);
1857
- if (!container) return;
1858
- container.querySelectorAll('input, textarea').forEach(el => {
1859
- if (el.type === 'file' || el.type === 'range' || el.type === 'checkbox') return;
1860
- const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
1861
- const ns = Object.getOwnPropertyDescriptor(proto, 'value');
1862
- if (ns && ns.set) {
1863
- ns.set.call(el, value);
1864
- el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));
1865
- el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));
1866
- }
1867
- });
1868
- }
1869
- window.__setGradioValue = setGradioValue;
1870
- function syncImagesToGradio() {
1871
- window.__uploadedImages = images;
1872
- const b64Array = images.map(img => img.b64);
1873
- setGradioValue('hidden-images-b64', JSON.stringify(b64Array));
1874
- updateCounts();
1875
- }
1876
- function syncPromptToGradio() {
1877
- if (promptInput) setGradioValue('prompt-gradio-input', promptInput.value);
1878
- }
1879
- function updateCounts() {
1880
- const n = images.length;
1881
- const txt = n > 0 ? n + ' image' + (n > 1 ? 's' : '') : 'No images';
1882
- if (imgCountTb) imgCountTb.textContent = txt;
1883
- if (imgCountSb) imgCountSb.textContent = n > 0 ? txt + ' uploaded' : 'No images uploaded';
1884
- }
1885
- function addImage(b64, name) {
1886
- images.push({id: Date.now() + Math.random(), b64: b64, name: name});
1887
- renderGallery();
1888
- syncImagesToGradio();
1889
- }
1890
- window.__addImage = addImage;
1891
- function removeImage(idx) {
1892
- images.splice(idx, 1);
1893
- if (selectedIdx === idx) selectedIdx = -1;
1894
- else if (selectedIdx > idx) selectedIdx--;
1895
- renderGallery();
1896
- syncImagesToGradio();
1897
- }
1898
- function clearAll() {
1899
- images = [];
1900
- window.__uploadedImages = images;
1901
- selectedIdx = -1;
1902
- renderGallery();
1903
- syncImagesToGradio();
1904
- }
1905
- window.__clearAll = clearAll;
1906
- function selectImage(idx) {
1907
- selectedIdx = (selectedIdx === idx) ? -1 : idx;
1908
- renderGallery();
1909
- }
1910
- function renderGallery() {
1911
- if (images.length === 0) {
1912
- galleryGrid.innerHTML = '';
1913
- galleryGrid.style.display = 'none';
1914
- if (uploadPrompt) uploadPrompt.style.display = '';
1915
- return;
1916
- }
1917
- if (uploadPrompt) uploadPrompt.style.display = 'none';
1918
- galleryGrid.style.display = 'grid';
1919
- let html = '';
1920
- images.forEach((img, i) => {
1921
- const sel = i === selectedIdx ? ' selected' : '';
1922
- html += '<div class="gallery-thumb' + sel + '" data-idx="' + i + '">'
1923
- + '<img src="' + img.b64 + '" alt="' + (img.name||'image') + '">'
1924
- + '<span class="thumb-badge">#' + (i+1) + '</span>'
1925
- + '<button class="thumb-remove" data-remove="' + i + '">\u2715</button>'
1926
- + '</div>';
1927
- });
1928
- html += '<div class="gallery-add-card" id="gallery-add-card">'
1929
- + '<span class="add-icon">+</span>'
1930
- + '<span class="add-text">Add</span>'
1931
- + '</div>';
1932
- galleryGrid.innerHTML = html;
1933
- galleryGrid.querySelectorAll('.gallery-thumb').forEach(thumb => {
1934
- thumb.addEventListener('click', (e) => {
1935
- if (e.target.closest('.thumb-remove')) return;
1936
- selectImage(parseInt(thumb.dataset.idx));
1937
- });
1938
- });
1939
- galleryGrid.querySelectorAll('.thumb-remove').forEach(btn => {
1940
- btn.addEventListener('click', (e) => {
1941
- e.stopPropagation();
1942
- removeImage(parseInt(btn.dataset.remove));
1943
- });
1944
- });
1945
- const addCard = document.getElementById('gallery-add-card');
1946
- if (addCard) addCard.addEventListener('click', () => fileInput.click());
1947
- }
1948
- function processFiles(files) {
1949
- Array.from(files).forEach(file => {
1950
- if (!file.type.startsWith('image/')) return;
1951
- const reader = new FileReader();
1952
- reader.onload = (e) => addImage(e.target.result, file.name);
1953
- reader.readAsDataURL(file);
1954
- });
1955
- }
1956
- fileInput.addEventListener('change', (e) => { processFiles(e.target.files); e.target.value = ''; });
1957
- if (uploadClick) uploadClick.addEventListener('click', () => fileInput.click());
1958
- if (btnUpload) btnUpload.addEventListener('click', () => fileInput.click());
1959
- if (btnRemove) btnRemove.addEventListener('click', () => {
1960
- if (selectedIdx >= 0 && selectedIdx < images.length) removeImage(selectedIdx);
1961
- });
1962
- if (btnClear) btnClear.addEventListener('click', clearAll);
1963
- dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); });
1964
- dropZone.addEventListener('dragleave', (e) => { e.preventDefault(); dropZone.classList.remove('drag-over'); });
1965
- dropZone.addEventListener('drop', (e) => {
1966
- e.preventDefault(); dropZone.classList.remove('drag-over');
1967
- if (e.dataTransfer.files.length) processFiles(e.dataTransfer.files);
1968
- });
1969
- if (promptInput) promptInput.addEventListener('input', syncPromptToGradio);
1970
- window.__setPrompt = function(text) {
1971
- if (promptInput) { promptInput.value = text; syncPromptToGradio(); }
1972
- };
1973
- document.querySelectorAll('.example-card[data-idx]').forEach(card => {
1974
- card.addEventListener('click', () => {
1975
- const idx = card.getAttribute('data-idx');
1976
- document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
1977
- card.classList.add('loading');
1978
- showToast('Loading example...', 'info');
1979
- setGradioValue('example-result-data', '');
1980
- setGradioValue('example-idx-input', idx);
1981
- setTimeout(() => {
1982
- const btn = document.getElementById('example-load-btn');
1983
- if (btn) {
1984
- const b = btn.querySelector('button');
1985
- if (b) b.click(); else btn.click();
1986
- }
1987
- }, 150);
1988
- setTimeout(() => card.classList.remove('loading'), 12000);
1989
- });
1990
- });
1991
- function syncSlider(customId, gradioId) {
1992
- const slider = document.getElementById(customId);
1993
- const valSpan = document.getElementById(customId + '-val');
1994
- if (!slider) return;
1995
- slider.addEventListener('input', () => {
1996
- if (valSpan) valSpan.textContent = slider.value;
1997
- const container = document.getElementById(gradioId);
1998
- if (!container) return;
1999
- container.querySelectorAll('input[type="range"],input[type="number"]').forEach(el => {
2000
- const ns = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
2001
- if (ns && ns.set) {
2002
- ns.set.call(el, slider.value);
2003
- el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));
2004
- el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));
2005
- }
2006
- });
2007
- });
2008
- }
2009
- syncSlider('custom-seed', 'gradio-seed');
2010
- syncSlider('custom-guidance', 'gradio-guidance');
2011
- syncSlider('custom-steps', 'gradio-steps');
2012
- const randCheck = document.getElementById('custom-randomize');
2013
- if (randCheck) {
2014
- randCheck.addEventListener('change', () => {
2015
- const container = document.getElementById('gradio-randomize');
2016
- if (!container) return;
2017
- const cb = container.querySelector('input[type="checkbox"]');
2018
- if (cb && cb.checked !== randCheck.checked) cb.click();
2019
- });
2020
- }
2021
- function showLoader() {
2022
- const l = document.getElementById('output-loader');
2023
- if (l) l.classList.add('active');
2024
- const sb = document.querySelector('.sb-fixed');
2025
- if (sb) sb.textContent = 'Processing...';
2026
- }
2027
- function hideLoader() {
2028
- const l = document.getElementById('output-loader');
2029
- if (l) l.classList.remove('active');
2030
- const sb = document.querySelector('.sb-fixed');
2031
- if (sb) sb.textContent = 'Done';
2032
- }
2033
- window.__showLoader = showLoader;
2034
- window.__hideLoader = hideLoader;
2035
- function validateBeforeRun() {
2036
- const promptVal = promptInput ? promptInput.value.trim() : '';
2037
- const hasImages = images.length > 0;
2038
- if (!hasImages && !promptVal) { showToast('Please upload an image and enter a prompt', 'error'); flashPromptError(); return false; }
2039
- if (!hasImages) { showToast('Please upload at least one image', 'error'); return false; }
2040
- if (!promptVal) { showToast('Please enter an edit prompt', 'warning'); flashPromptError(); return false; }
2041
- return true;
2042
- }
2043
- window.__clickGradioRunBtn = function() {
2044
- if (!validateBeforeRun()) return;
2045
- syncPromptToGradio(); syncImagesToGradio(); showLoader();
2046
- setTimeout(() => {
2047
- const gradioBtn = document.getElementById('gradio-run-btn');
2048
- if (!gradioBtn) return;
2049
- const btn = gradioBtn.querySelector('button');
2050
- if (btn) btn.click(); else gradioBtn.click();
2051
- }, 200);
2052
- };
2053
- if (runBtnEl) runBtnEl.addEventListener('click', () => window.__clickGradioRunBtn());
2054
- renderGallery();
2055
- updateCounts();
2056
- }
2057
- init();
2058
- }
2059
- """
2060
-
2061
- wire_outputs_js = r"""
2062
- () => {
2063
- function watchOutputs() {
2064
- const resultContainer = document.getElementById('gradio-result');
2065
- const outBody = document.getElementById('output-image-container');
2066
- const outPh = document.getElementById('output-placeholder');
2067
- const dlBtn = document.getElementById('dl-btn-output');
2068
- if (!resultContainer || !outBody) { setTimeout(watchOutputs, 500); return; }
2069
- if (dlBtn) {
2070
- dlBtn.addEventListener('click', (e) => {
2071
- e.stopPropagation();
2072
- const img = outBody.querySelector('img.modern-out-img');
2073
- if (img && img.src) {
2074
- const a = document.createElement('a');
2075
- a.href = img.src; a.download = 'firered_output.webp';
2076
- document.body.appendChild(a); a.click(); document.body.removeChild(a);
2077
- }
2078
- });
2079
- }
2080
- function syncImage() {
2081
- const resultImg = resultContainer.querySelector('img');
2082
- if (resultImg && resultImg.src) {
2083
- if (outPh) outPh.style.display = 'none';
2084
- let existing = outBody.querySelector('img.modern-out-img');
2085
- if (!existing) {
2086
- existing = document.createElement('img');
2087
- existing.className = 'modern-out-img';
2088
- outBody.appendChild(existing);
2089
- }
2090
- if (existing.src !== resultImg.src) {
2091
- existing.src = resultImg.src;
2092
- if (dlBtn) dlBtn.classList.add('visible');
2093
- if (window.__hideLoader) window.__hideLoader();
2094
- }
2095
- }
2096
- }
2097
- const observer = new MutationObserver(syncImage);
2098
- observer.observe(resultContainer, {childList:true, subtree:true, attributes:true, attributeFilter:['src']});
2099
- setInterval(syncImage, 800);
2100
- }
2101
- watchOutputs();
2102
- function watchSeed() {
2103
- const seedContainer = document.getElementById('gradio-seed');
2104
- const seedSlider = document.getElementById('custom-seed');
2105
- const seedVal = document.getElementById('custom-seed-val');
2106
- if (!seedContainer || !seedSlider) { setTimeout(watchSeed, 500); return; }
2107
- function sync() {
2108
- const el = seedContainer.querySelector('input[type="range"],input[type="number"]');
2109
- if (el && el.value) { seedSlider.value = el.value; if (seedVal) seedVal.textContent = el.value; }
2110
- }
2111
- const obs = new MutationObserver(sync);
2112
- obs.observe(seedContainer, {childList:true, subtree:true, attributes:true, attributeFilter:['value']});
2113
- setInterval(sync, 1000);
2114
- }
2115
- watchSeed();
2116
- function watchExampleResults() {
2117
- const container = document.getElementById('example-result-data');
2118
- if (!container) { setTimeout(watchExampleResults, 500); return; }
2119
- let lastProcessed = '';
2120
- function checkResult() {
2121
- const el = container.querySelector('textarea') || container.querySelector('input');
2122
- if (!el) return;
2123
- const val = el.value;
2124
- if (!val || val === lastProcessed || val.length < 20) return;
2125
- try {
2126
- const data = JSON.parse(val);
2127
- if (data.status === 'ok' && data.images && data.images.length > 0) {
2128
- lastProcessed = val;
2129
- if (window.__clearAll) window.__clearAll();
2130
- if (window.__setPrompt && data.prompt) window.__setPrompt(data.prompt);
2131
- data.images.forEach((b64, i) => {
2132
- if (b64 && window.__addImage) {
2133
- const name = (data.names && data.names[i]) ? data.names[i] : ('example_' + (i+1) + '.jpg');
2134
- window.__addImage(b64, name);
2135
- }
2136
- });
2137
- document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
2138
- if (window.__showToast) window.__showToast('Example loaded \u2014 ' + data.images.length + ' image(s)', 'info');
2139
- } else if (data.status === 'error') {
2140
- document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
2141
- if (window.__showToast) window.__showToast('Could not load example images', 'error');
2142
- }
2143
- } catch(e) {
2144
- console.error('Example parse error:', e);
2145
- }
2146
- }
2147
- const obs = new MutationObserver(checkResult);
2148
- obs.observe(container, {childList:true, subtree:true, characterData:true, attributes:true});
2149
- setInterval(checkResult, 500);
2150
- }
2151
- watchExampleResults();
2152
- }
2153
- """
2154
-
2155
- # ── SVG assets ─────────────────────────────────────────────────────────────────
2156
- 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>'
2157
-
2158
- 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>'
2159
-
2160
- 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>'
2161
-
2162
- 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>'
2163
-
2164
- GITHUB_SVG = '<svg width="15" height="15" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path fill="#ffffff" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>'
2165
-
2166
- 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>'
2167
-
2168
- # ── Gradio app ─────────────────────────────────────────────────────────────────
2169
- with gr.Blocks() as demo:
2170
-
2171
- hidden_images_b64 = gr.Textbox(value="[]", elem_id="hidden-images-b64", elem_classes="hidden-input", container=False)
2172
- prompt = gr.Textbox(value="", elem_id="prompt-gradio-input", elem_classes="hidden-input", container=False)
2173
- seed = gr.Slider(minimum=0, maximum=MAX_SEED, step=1, value=0, elem_id="gradio-seed", elem_classes="hidden-input", container=False)
2174
- randomize_seed = gr.Checkbox(value=True, elem_id="gradio-randomize", elem_classes="hidden-input", container=False)
2175
- 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)
2176
- steps = gr.Slider(minimum=1, maximum=50, step=1, value=4, elem_id="gradio-steps", elem_classes="hidden-input", container=False)
2177
- result = gr.Image(elem_id="gradio-result", elem_classes="hidden-input", container=False, format="webp")
2178
-
2179
- example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
2180
- example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
2181
- example_load_btn = gr.Button("Load Example", elem_id="example-load-btn")
2182
-
2183
- gr.HTML(f"""
2184
- <div class="app-shell">
2185
- <!-- Header with GitHub top-right -->
2186
- <div class="app-header">
2187
- <div class="app-header-left">
2188
- <div class="app-logo">{FIRE_LOGO_SVG}</div>
2189
- <span class="app-title">FireRed-Image-Edit</span>
2190
- <span class="app-badge">v1.1</span>
2191
- <span class="app-badge fast">4-Step Fast</span>
2192
- </div>
2193
- <a href="https://github.com/PRITHIVSAKTHIUR/FireRed-Image-Edit-1.0-Fast"
2194
- target="_blank" class="gh-btn">
2195
- {GITHUB_SVG}
2196
- <span>GitHub</span>
2197
- </a>
2198
- </div>
2199
- <!-- Toolbar -->
2200
- <div class="app-toolbar">
2201
- <button id="tb-upload" class="modern-tb-btn" title="Upload images">
2202
- {UPLOAD_SVG}<span class="tb-label">Upload</span>
2203
- </button>
2204
- <button id="tb-remove" class="modern-tb-btn" title="Remove selected image">
2205
- {REMOVE_SVG}<span class="tb-label">Remove</span>
2206
- </button>
2207
- <button id="tb-clear" class="modern-tb-btn" title="Clear all images">
2208
- {CLEAR_SVG}<span class="tb-label">Clear All</span>
2209
- </button>
2210
- <div class="tb-sep"></div>
2211
- <span id="tb-image-count" class="tb-info">No images</span>
2212
- </div>
2213
- <!-- Main row -->
2214
- <div class="app-main-row">
2215
- <!-- Left panel -->
2216
- <div class="app-main-left">
2217
- <div id="gallery-drop-zone">
2218
- <div id="upload-prompt" class="upload-prompt-modern">
2219
- <div id="upload-click-area" class="upload-click-area">
2220
- <svg viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
2221
- <rect x="8" y="14" width="64" height="52" rx="6" fill="none"
2222
- stroke="#FF0000" stroke-width="2" stroke-dasharray="4 3"/>
2223
- <polygon points="12,62 30,40 42,50 54,34 68,62"
2224
- fill="rgba(255,0,0,0.15)" stroke="#FF0000" stroke-width="1.5"/>
2225
- <circle cx="28" cy="30" r="6"
2226
- fill="rgba(255,0,0,0.2)" stroke="#FF0000" stroke-width="1.5"/>
2227
- </svg>
2228
- <span class="upload-main-text">Click or drag images here</span>
2229
- <span class="upload-sub-text">Supports multiple images for reference-based editing and guided manipulation</span>
2230
- </div>
2231
- </div>
2232
- <input id="custom-file-input" type="file" accept="image/*" multiple style="display:none;" />
2233
- <div id="image-gallery-grid" class="image-gallery-grid" style="display:none;"></div>
2234
- </div>
2235
- <div class="hint-bar">
2236
- <b>Upload:</b> Click or drag to add images &nbsp;&middot;&nbsp;
2237
- <b>Multi-image:</b> Upload multiple images for reference-based editing &nbsp;&middot;&nbsp;
2238
- <kbd>Remove</kbd> deletes selected &nbsp;&middot;&nbsp;
2239
- <kbd>Clear All</kbd> removes everything
2240
- </div>
2241
- <div class="suggestions-section">
2242
- <div class="suggestions-title">Quick Prompts</div>
2243
- <div class="suggestions-wrap">
2244
- <button class="suggestion-chip" onclick="window.__setPrompt('Transform the image into a dotted cartoon style.')">Cartoon Style</button>
2245
- <button class="suggestion-chip" onclick="window.__setPrompt('Convert it to black and white.')">Black and White</button>
2246
- <button class="suggestion-chip" onclick="window.__setPrompt('Add cinematic lighting with warm orange tones and film grain.')">Cinematic</button>
2247
- <button class="suggestion-chip" onclick="window.__setPrompt('Transform into anime style illustration.')">Anime Style</button>
2248
- <button class="suggestion-chip" onclick="window.__setPrompt('Apply oil painting effect with visible brush strokes.')">Oil Painting</button>
2249
- <button class="suggestion-chip" onclick="window.__setPrompt('Enhance and upscale with more detail and clarity.')">Enhance</button>
2250
- <button class="suggestion-chip" onclick="window.__setPrompt('Make it look like a watercolor painting with soft edges.')">Watercolor</button>
2251
- <button class="suggestion-chip" onclick="window.__setPrompt('Add dramatic sunset sky and warm lighting.')">Sunset Glow</button>
2252
- <button class="suggestion-chip" onclick="window.__setPrompt('Convert to detailed pencil sketch with cross-hatching and shading.')">Pencil Sketch</button>
2253
- <button class="suggestion-chip" onclick="window.__setPrompt('Apply pop art style with bold colors and halftone patterns.')">Pop Art</button>
2254
- <button class="suggestion-chip" onclick="window.__setPrompt('Apply a vintage retro film look with faded colors and light leaks.')">Vintage Retro</button>
2255
- <button class="suggestion-chip" onclick="window.__setPrompt('Add neon glow effects with vibrant colors against a dark background.')">Neon Glow</button>
2256
- <button class="suggestion-chip" onclick="window.__setPrompt('Convert to pixel art style with a retro 16-bit aesthetic.')">Pixel Art</button>
2257
- <button class="suggestion-chip" onclick="window.__setPrompt('Simplify into a clean minimalist illustration with flat colors.')">Minimalist</button>
2258
- <button class="suggestion-chip" onclick="window.__setPrompt('Convert to low poly 3D geometric art style.')">Low Poly 3D</button>
2259
- <button class="suggestion-chip" onclick="window.__setPrompt('Transform into comic book style with bold outlines and cel shading.')">Comic Book</button>
2260
- </div>
2261
- </div>
2262
- <div class="examples-section">
2263
- <div class="examples-title">Quick Examples &mdash; click to load</div>
2264
- <div class="examples-scroll">
2265
- {EXAMPLE_CARDS_HTML}
2266
- </div>
2267
- </div>
2268
- </div>
2269
- <!-- Right panel -->
2270
- <div class="app-main-right">
2271
- <div class="panel-card">
2272
- <div class="panel-card-title">Edit Instruction</div>
2273
- <div class="panel-card-body">
2274
- <label class="modern-label" for="custom-prompt-input">Prompt</label>
2275
- <textarea id="custom-prompt-input" class="modern-textarea" rows="3"
2276
- placeholder="e.g., transform into anime, upscale, change lighting..."></textarea>
2277
- </div>
2278
- </div>
2279
- <div style="padding:12px 20px;">
2280
- <button id="custom-run-btn" class="btn-run">
2281
- <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="18" height="18">
2282
- <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" fill="white"/>
2283
- </svg>
2284
- <span id="run-btn-label">Edit Image</span>
2285
- </button>
2286
- </div>
2287
- <div class="output-frame" style="flex:1">
2288
- <div class="out-title">
2289
- <span>Output</span>
2290
- <span id="dl-btn-output" class="out-download-btn" title="Download">
2291
- {DOWNLOAD_SVG} Save
2292
- </span>
2293
- </div>
2294
- <div class="out-body" id="output-image-container">
2295
- <div class="modern-loader" id="output-loader">
2296
- <div class="loader-spinner"></div>
2297
- <div class="loader-text">Processing image...</div>
2298
- <div class="loader-bar-track"><div class="loader-bar-fill"></div></div>
2299
- </div>
2300
- <div class="out-placeholder" id="output-placeholder">Result will appear here</div>
2301
- </div>
2302
- </div>
2303
- <div class="settings-group">
2304
- <div class="settings-group-title">Advanced Settings</div>
2305
- <div class="settings-group-body">
2306
- <div class="slider-row">
2307
- <label>Seed</label>
2308
- <input type="range" id="custom-seed" min="0" max="2147483647" step="1" value="0">
2309
- <span class="slider-val" id="custom-seed-val">0</span>
2310
- </div>
2311
- <div class="checkbox-row">
2312
- <input type="checkbox" id="custom-randomize" checked>
2313
- <label for="custom-randomize">Randomize seed</label>
2314
- </div>
2315
- <div class="slider-row">
2316
- <label>Guidance</label>
2317
- <input type="range" id="custom-guidance" min="1" max="10" step="0.1" value="1.0">
2318
- <span class="slider-val" id="custom-guidance-val">1.0</span>
2319
- </div>
2320
- <div class="slider-row">
2321
- <label>Steps</label>
2322
- <input type="range" id="custom-steps" min="1" max="50" step="1" value="4">
2323
- <span class="slider-val" id="custom-steps-val">4</span>
2324
- </div>
2325
- </div>
2326
- </div>
2327
- </div>
2328
- </div>
2329
- <!-- Footer: only model credit, no GitHub link -->
2330
- <div class="exp-note">
2331
- Experimental Space for
2332
- <a href="https://huggingface.co/FireRedTeam/FireRed-Image-Edit-1.1" target="_blank">FireRed-Image-Edit-1.1</a>
2333
- </div>
2334
- <!-- Status bar -->
2335
- <div class="app-statusbar">
2336
- <div class="sb-section" id="sb-image-count">No images uploaded</div>
2337
- <div class="sb-section sb-fixed">Ready</div>
2338
- </div>
2339
- </div><!-- /app-shell -->
2340
- """)
2341
-
2342
- run_btn = gr.Button("Run", elem_id="gradio-run-btn")
2343
-
2344
- demo.load(fn=None, js=gallery_js)
2345
- demo.load(fn=None, js=wire_outputs_js)
2346
-
2347
- run_btn.click(
2348
- fn=infer,
2349
- inputs=[hidden_images_b64, prompt, seed, randomize_seed, guidance_scale, steps],
2350
- outputs=[result, seed],
2351
- js=r"""(imgs, p, s, rs, gs, st) => {
2352
- const images = window.__uploadedImages || [];
2353
- const b64Array = images.map(img => img.b64);
2354
- const imgsJson = JSON.stringify(b64Array);
2355
- const promptEl = document.getElementById('custom-prompt-input');
2356
- const promptVal = promptEl ? promptEl.value : p;
2357
- return [imgsJson, promptVal, s, rs, gs, st];
2358
- }""",
2359
- )
2360
-
2361
- example_load_btn.click(
2362
- fn=load_example_data,
2363
- inputs=[example_idx],
2364
- outputs=[example_result],
2365
- queue=False,
2366
- )
2367
-
2368
  if __name__ == "__main__":
2369
  demo.queue(max_size=50).launch(
2370
  css=css,
 
1178
  queue=False,
1179
  )
1180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1181
  if __name__ == "__main__":
1182
  demo.queue(max_size=50).launch(
1183
  css=css,