File size: 34,820 Bytes
08e06c9
3249e1b
08e06c9
 
 
 
3249e1b
 
 
08e06c9
 
 
3249e1b
 
08e06c9
 
 
3249e1b
 
 
 
 
08e06c9
3249e1b
 
08e06c9
 
3249e1b
 
 
 
 
08e06c9
3249e1b
 
08e06c9
3249e1b
 
 
 
 
 
 
 
08e06c9
 
 
 
 
 
 
3249e1b
08e06c9
 
 
 
3249e1b
 
08e06c9
 
 
 
3249e1b
08e06c9
 
 
 
 
 
3249e1b
08e06c9
 
 
 
 
 
 
 
 
3249e1b
 
08e06c9
 
 
 
 
 
 
 
3249e1b
 
08e06c9
3249e1b
08e06c9
 
 
3249e1b
08e06c9
 
 
 
 
 
 
 
 
3249e1b
 
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
 
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
 
 
 
 
 
 
 
 
08e06c9
 
3249e1b
 
 
 
 
 
 
08e06c9
3249e1b
 
 
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
08e06c9
 
 
 
 
 
 
 
3249e1b
 
 
 
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
08e06c9
 
 
 
 
 
 
3249e1b
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
08e06c9
3249e1b
 
 
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
 
 
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3249e1b
08e06c9
 
703118a
08e06c9
3249e1b
 
08e06c9
3249e1b
08e06c9
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
"""AI KING©️ Studio: all-in-one free AI creative studio by KING OF MUSIC©️ (Chad Syphrett).

Real generators run on this Space's ZeroGPU slot with open models only:
  FLUX.1 [schnell] (text→image, image→image) and LTX-Video 0.9.5 (text/image→video, seamless loops).
CPU tools: Audio Lab (ffmpeg remix/loop), Music Video Maker, Loop & Export, Cover Checker, Captions, Prompt Studio.
No paid inference providers. Non-explicit content only. MiniMax-H3 excluded (US license).
"""
import json, os, pathlib

HERE = pathlib.Path(__file__).parent.resolve()
os.chdir(HERE)

import gradio as gr

import gen  # loads models at import time (ZeroGPU best practice)
import audio_tools
import brand
import captions
import cover_tools
import loop_tools
import prompt_studio as ps
import remote
import stats
from safety import CONSENT_NOTE, check_prompt

gr.set_static_paths(paths=[HERE / "static"])

try:
    PROMPTS = json.loads((HERE / "prompts.json").read_text(encoding="utf-8"))
except Exception:
    PROMPTS = []
SECTIONS = ["All"] + sorted({c["section"] for c in PROMPTS})
TAB_IDS = {"create", "edit", "video", "audio", "loops", "studio", "release", "labs", "about"}


# ---------------- helpers ----------------

def _guard(*texts):
    for t in texts:
        err = check_prompt(t)
        if err:
            raise gr.Error(err)


def hero():
    return brand.hero_html(stats.snapshot(), stats.MODE)


def on_load(request: gr.Request):
    stats.hit("visits")
    tab = None
    try:
        tab = (request.query_params.get("tab") or "").lower() if request else None
    except Exception:
        tab = None
    return hero(), (gr.Tabs(selected=tab) if tab in TAB_IDS else gr.Tabs())


def _engine_check(kind):
    if gen.STATUS.get(kind) != "ready":
        msg = gen.ERRORS.get(kind) or ("preview mode, models off" if gen.NO_MODELS else "warming up, try again in a minute")
        raise gr.Error(f"{'Image' if kind == 'image' else 'Video'} engine not ready: {msg}")


# ---------------- GPU handlers ----------------

def do_create(prompt, style, aspect, n, seed):
    if not (prompt or "").strip():
        raise gr.Error("Describe what you want to create.")
    _guard(prompt)
    _engine_check("image")
    try:
        paths, s = gen.text_to_image(prompt, style, aspect, int(n), seed)
    except gr.Error:
        raise
    except Exception as e:
        raise gr.Error(f"Generation failed: {str(e)[:300]}")
    stats.hit("images", len(paths))
    return paths, f"✅ {len(paths)} image(s) · seed {s} · FLUX.1 [schnell] on ZeroGPU", paths, paths[0]


def pick_from_gallery(evt: gr.SelectData, paths):
    try:
        v = evt.value
        if isinstance(v, dict):
            v = (v.get("image") or {}).get("path") or v.get("path")
        return v or (paths[evt.index] if paths else None)
    except Exception:
        return None


def do_edit(img, prompt, style, strength, seed):
    if not img:
        raise gr.Error("Upload an image to edit.")
    if not (prompt or "").strip():
        raise gr.Error("Describe the new look.")
    _guard(prompt)
    _engine_check("image")
    try:
        path, s = gen.image_to_image(img, prompt, style, strength, seed)
    except gr.Error:
        raise
    except Exception as e:
        raise gr.Error(f"Edit failed: {str(e)[:300]}")
    stats.hit("edits")
    return path, f"✅ Restyled · strength {strength} · seed {s}"


def do_video(prompt, image, mode, seconds, aspect, quality, seed):
    if not (prompt or "").strip():
        raise gr.Error("Describe the scene and motion.")
    if mode == "Image → Video" and not image:
        raise gr.Error("Upload a start image (or switch to Text → Video).")
    _guard(prompt)
    _engine_check("video")
    steps = {"⚡ Fast": 20, "✨ Balanced": 30, "👑 Max": 40}.get(quality, 30)
    try:
        path, s = gen.make_video(prompt, image, mode, float(seconds), aspect, steps, seed)
    except gr.Error:
        raise
    except Exception as e:
        raise gr.Error(f"Video failed: {str(e)[:300]}")
    stats.hit("videos")
    return path, f"✅ {mode} · {seconds}s · {steps} steps · seed {s} · LTX-Video on ZeroGPU"


# ---------------- CPU handlers ----------------

def do_remix(track, effects, start, end, fin, fout, loop_min, beat, beat_vol, fmt):
    try:
        out = audio_tools.remix(track, effects, start, end, fin, fout, loop_min, beat, beat_vol, fmt)
    except Exception as e:
        raise gr.Error(str(e)[:400])
    stats.hit("audio")
    return out, out, f"✅ Remix ready · {audio_tools.duration(out):.1f}s"


def do_music_video(image, clip, audio, size, motion, wave, minutes):
    src = clip or image
    try:
        out = audio_tools.music_video(src, audio, size, motion, wave, minutes)
    except Exception as e:
        raise gr.Error(str(e)[:400])
    stats.hit("loops")
    return out, f"✅ Music video ready · {audio_tools.duration(out):.0f}s"


def do_ffmpeg_loop(video, style, xfade, minutes, audio, aspect):
    if not video:
        raise gr.Error("Upload a video clip first.")
    try:
        out = loop_tools.make_loop(video, style, xfade, float(minutes or 0) * 60, audio, aspect)
    except Exception as e:
        raise gr.Error(str(e)[:400])
    stats.hit("loops")
    return out, "✅ Loop ready."


def do_cover(img, mode):
    if not img:
        raise gr.Error("Upload a cover image first.")
    report = cover_tools.check_cover(img)
    files = cover_tools.export_sizes(img, "crop" if mode.startswith("Crop") else "pad")
    stats.hit("covers")
    return report, files, files[0]


def _remote(fn, *args, request=None):
    try:
        path, used = fn(*args, request=request)
    except remote.ToolError as e:
        raise gr.Error(str(e))
    if not path:
        raise gr.Error("The remote tool finished but returned no file.")
    stats.hit("edits")
    return path, f"✅ Done with {used}."


def do_outpaint(img, target, prompt, align, request: gr.Request):
    if not img:
        raise gr.Error("Upload an image first.")
    _guard(prompt)
    w, h = {"Vertical 9:16": (720, 1280), "Wide 16:9": (1280, 720), "Square": (1024, 1024)}[target]
    return _remote(remote.outpaint, img, w, h, prompt, align, request=request)


def do_upscale(img, factor, request: gr.Request):
    if not img:
        raise gr.Error("Upload an image first.")
    return _remote(remote.upscale, img, factor, request=request)


def filter_prompts(section, query):
    q = (query or "").lower().strip()
    cards = [c for c in PROMPTS if (section == "All" or c["section"] == section) and (not q or q in (c["prompt"] + c["label"] + c["section"]).lower())]
    choices = [f'{i+1:03d} · {c["section"][:48]} · {c["label"][:60]}' for i, c in enumerate(cards)]
    return gr.update(choices=choices, value=choices[0] if choices else None), cards, (cards[0]["prompt"] if cards else "No prompts match.")


def pick_prompt(choice, cards):
    if not choice or not cards:
        return ""
    idx = int(choice.split(" · ")[0]) - 1
    return cards[idx]["prompt"] if 0 <= idx < len(cards) else ""


def coach_chat(msg, history):
    history = history or []
    if not (msg or "").strip():
        return "", history
    return "", history + [{"role": "user", "content": msg}, {"role": "assistant", "content": ps.coach_reply(msg)}]


def counted(fn, key="prompts"):
    def w(*a):
        stats.hit(key)
        return fn(*a)
    return w


def engine_md():
    icon = {"ready": "🟢 ready", "error": "🔴 error", "off": "⚪ off (preview)"}
    lines = [f"- **Image engine** (FLUX.1 [schnell]): {icon.get(gen.STATUS['image'], gen.STATUS['image'])}",
             f"- **Video engine** (LTX-Video 0.9.5): {icon.get(gen.STATUS['video'], gen.STATUS['video'])}",
             f"- **Stats store:** {stats.MODE}"]
    for k, v in gen.ERRORS.items():
        lines.append(f"- `{k}` error: {v[:200]}")
    return "\n".join(lines)


def H(title, sub=""):
    return gr.HTML(f'<div class="aik-h"><h2>{title}</h2><span>{sub}</span></div>')


STYLE_CHOICES = list(gen.STYLES)
EXAMPLES = [
    "KING OF MUSIC on a golden throne in a futuristic concert arena, crowd lights, crown glowing",
    "Luxury black and gold sneaker floating in zero gravity above a neon city, product shot",
    "Cozy lofi studio at midnight, rain on the window, vinyl spinning, city skyline",
    "Movie poster: a hero in a navy suit and grey fedora walking out of a glowing portal",
    "Futuristic chrome supercar parked in front of a castle at sunset",
]

# ---------------- UI ----------------

with gr.Blocks(title="AI KING©️ Studio") as demo:
    hero_box = gr.HTML(hero())
    last_img = gr.State(None)

    with gr.Tabs() as tabs:
        # ---- CREATE ----
        with gr.Tab("✨ Create", id="create"):
            with gr.Row(equal_height=False):
                with gr.Column(scale=5, elem_classes="aik-card"):
                    H("Create", "text → image · FLUX.1 [schnell] · ~5–15 s")
                    c_prompt = gr.Textbox(show_label=False, lines=3, elem_id="aik-prompt",
                                          placeholder="Imagine anything… e.g. KING OF MUSIC on a golden throne in a futuristic arena")
                    c_style = gr.Radio(STYLE_CHOICES, value="🎬 ARRI ALEXA 35", label="Style", elem_classes="aik-chips")
                    c_aspect = gr.Radio(list(gen.ASPECTS), value="9:16 Story", label="Frame", elem_classes="aik-chips")
                    with gr.Row():
                        c_n = gr.Slider(1, 4, value=2, step=1, label="Images")
                        c_seed = gr.Number(value=-1, label="Seed (-1 = surprise me)", precision=0)
                    c_btn = gr.Button("✨ Generate", variant="primary", size="lg")
                    gr.Examples(EXAMPLES, c_prompt, label="Try one")
                with gr.Column(scale=6, elem_classes="aik-card"):
                    c_gallery = gr.Gallery(label="Results", columns=2, height=560, object_fit="contain", preview=False, buttons=["download", "fullscreen"])
                    c_msg = gr.Markdown(elem_classes="aik-note")
                    with gr.Row():
                        c_to_edit = gr.Button("🎨 Edit this", size="sm")
                        c_to_video = gr.Button("🎬 Animate this", size="sm")
            c_paths = gr.State([])

        # ---- EDIT ----
        with gr.Tab("🎨 Edit", id="edit"):
            with gr.Row(equal_height=False):
                with gr.Column(scale=5, elem_classes="aik-card"):
                    H("Edit & Restyle", "image → image · keep the layout, change the look")
                    e_img = gr.Image(type="filepath", label="Your photo", height=360)
                    e_prompt = gr.Textbox(label="New look", lines=3, placeholder="same pose and outfit, cinematic gold-lit throne room, ARRI ALEXA 35, shallow depth of field")
                    e_style = gr.Radio(STYLE_CHOICES, value="None", label="Style", elem_classes="aik-chips")
                    e_strength = gr.Slider(0.2, 0.95, value=0.6, step=0.05, label="Change amount (low = subtle, high = reimagine)")
                    e_seed = gr.Number(value=-1, label="Seed", precision=0)
                    e_btn = gr.Button("🎨 Restyle", variant="primary", size="lg")
                    gr.HTML(f'<div class="aik-note">⚠️ {CONSENT_NOTE}</div>')
                with gr.Column(scale=6, elem_classes="aik-card"):
                    e_out = gr.Image(type="filepath", label="Result", height=560, buttons=["download", "fullscreen"])
                    e_msg = gr.Markdown(elem_classes="aik-note")
                    e_to_video = gr.Button("🎬 Animate this", size="sm")

        # ---- VIDEO ----
        with gr.Tab("🎬 Video", id="video"):
            with gr.Row(equal_height=False):
                with gr.Column(scale=5, elem_classes="aik-card"):
                    H("Video", "text/image → video · seamless loops · LTX-Video")
                    v_mode = gr.Radio(["Text → Video", "Image → Video", "Seamless Loop"], value="Text → Video", label="Mode", elem_classes="aik-chips")
                    v_img = gr.Image(type="filepath", label="Start image (optional for Text → Video & Loop)", height=260)
                    v_prompt = gr.Textbox(label="Scene + motion", lines=3, elem_id="aik-prompt",
                                          value="A man in a navy suit and grey fedora on a mountain lake dock at golden hour, slow cinematic push-in, jacket moving in the breeze, sparkling water")
                    v_aspect = gr.Radio(list(gen.VIDEO_ASPECTS), value="9:16 Story", label="Frame", elem_classes="aik-chips")
                    with gr.Row():
                        v_sec = gr.Slider(1, 5, value=4, step=1, label="Seconds")
                        v_quality = gr.Radio(["⚡ Fast", "✨ Balanced", "👑 Max"], value="✨ Balanced", label="Quality")
                    v_seed = gr.Number(value=-1, label="Seed", precision=0)
                    v_btn = gr.Button("🎬 Make video", variant="primary", size="lg")
                    gr.HTML('<div class="aik-note">Text → Video first paints a cinematic keyframe with FLUX, then animates it. '
                            'Seamless Loop makes the last frame match the first: perfect for 24/7 lofi streams (repeat it in Loops & Export).</div>')
                with gr.Column(scale=6, elem_classes="aik-card"):
                    v_out = gr.Video(label="Video", height=560, autoplay=True, loop=True)
                    v_msg = gr.Markdown(elem_classes="aik-note")

        # ---- AUDIO ----
        with gr.Tab("🎧 Audio Lab", id="audio"):
            with gr.Tabs():
                with gr.Tab("🎛️ Remix"):
                    with gr.Row(equal_height=False):
                        with gr.Column(scale=5, elem_classes="aik-card"):
                            H("Remix", "trim · effects · loop · mix a beat")
                            a_track = gr.Audio(type="filepath", label="Song or sound")
                            a_fx = gr.CheckboxGroup(audio_tools.EFFECTS, value=["🌙 Lofi warmth"], label="Effects", elem_classes="aik-chips")
                            with gr.Row():
                                a_start = gr.Number(value=0, label="Start (s)")
                                a_end = gr.Number(value=0, label="End (s, 0 = full)")
                            with gr.Row():
                                a_fin = gr.Slider(0, 10, value=1, step=0.5, label="Fade in (s)")
                                a_fout = gr.Slider(0, 15, value=3, step=0.5, label="Fade out (s)")
                            a_loop = gr.Slider(0, 15, value=0, step=1, label="Loop to length (minutes, 0 = off)")
                            with gr.Accordion("Mix a second track (beat / ambience)", open=False):
                                a_beat = gr.Audio(type="filepath", label="Beat or ambience")
                                a_bvol = gr.Slider(0.05, 1.5, value=0.6, step=0.05, label="Beat volume")
                            a_fmt = gr.Radio(["mp3", "wav"], value="mp3", label="Export")
                            a_btn = gr.Button("🎛️ Remix", variant="primary", size="lg")
                        with gr.Column(scale=6, elem_classes="aik-card"):
                            a_out = gr.Audio(type="filepath", label="Remix", buttons=["download"])
                            a_file = gr.File(label="Download")
                            a_msg = gr.Markdown(elem_classes="aik-note")
                with gr.Tab("📼 Music Video Maker"):
                    with gr.Row(equal_height=False):
                        with gr.Column(scale=5, elem_classes="aik-card"):
                            H("Music Video Maker", "cover or clip + song → MP4 with gold waveform")
                            mv_img = gr.Image(type="filepath", label="Cover art", height=240)
                            mv_clip = gr.Video(label="…or a looping clip (optional, overrides the image)")
                            mv_audio = gr.Audio(type="filepath", label="Song")
                            mv_size = gr.Radio(list(audio_tools.VIDEO_SIZES), value="9:16 TikTok/Shorts (720x1280)", label="Format", elem_classes="aik-chips")
                            with gr.Row():
                                mv_motion = gr.Radio(["Slow zoom", "Still"], value="Slow zoom", label="Image motion")
                                mv_wave = gr.Checkbox(value=True, label="Gold waveform")
                            mv_min = gr.Slider(0.25, 10, value=1, step=0.25, label="Max length (minutes)")
                            mv_btn = gr.Button("📼 Render music video", variant="primary", size="lg")
                        with gr.Column(scale=6, elem_classes="aik-card"):
                            mv_out = gr.Video(label="Music video", height=560)
                            mv_msg = gr.Markdown(elem_classes="aik-note")
                with gr.Tab("🎼 Text → Music (soon)"):
                    gr.HTML('<div class="aik-soon"><h3>🎼 Text → Music & AI vocals: coming soon</h3>'
                            '<p>We only ship open models whose licenses allow commercial use of the music you make. '
                            'Until then: remix your own songs above, or bring stems from your DAW.</p></div>')

        # ---- LOOPS & EXPORT ----
        with gr.Tab("🔁 Loops & Export", id="loops"):
            with gr.Row(equal_height=False):
                with gr.Column(scale=5, elem_classes="aik-card"):
                    H("Loop & Export", "ping-pong / crossfade · repeat to 1 h · add your song")
                    ff_vid = gr.Video(label="Clip")
                    ff_style = gr.Radio(["ping-pong", "crossfade"], value="ping-pong", label="Loop style", elem_classes="aik-chips")
                    ff_x = gr.Slider(0.2, 2.0, value=0.75, step=0.05, label="Crossfade seconds")
                    ff_min = gr.Number(value=0, label="Repeat to length (minutes, 0 = one loop, 60 = 1 hour)")
                    ff_audio = gr.Audio(type="filepath", label="Song (optional)")
                    ff_aspect = gr.Radio(list(loop_tools.ASPECTS), value="keep", label="Export frame", elem_classes="aik-chips")
                    ff_btn = gr.Button("🔁 Make loop", variant="primary", size="lg")
                with gr.Column(scale=6, elem_classes="aik-card"):
                    ff_out = gr.Video(label="Loop", height=560)
                    ff_msg = gr.Markdown(elem_classes="aik-note")

        # ---- PROMPT STUDIO ----
        with gr.Tab("👑 Prompt Studio", id="studio"):
            with gr.Column(elem_classes="aik-card"):
                H("Prompt Studio", "the KING OF MUSIC prompt builder · copy into any generator")
                with gr.Tabs():
                    with gr.Tab("Text → Image"):
                        with gr.Row():
                            with gr.Column():
                                ti_idea = gr.Textbox(label="Core idea", lines=4, placeholder="A futuristic music producer at a midnight control desk, gold crown on the console")
                                ti_fast = gr.Radio(list(ps.FAST_STARTS), label="Fast starts", elem_classes="aik-chips")
                                with gr.Row():
                                    ti_ratio = gr.Dropdown(ps.TI_RATIOS, value=ps.TI_RATIOS[0], label="Frame")
                                    ti_shot = gr.Dropdown(ps.TI_SHOTS, value=ps.TI_SHOTS[0], label="Camera")
                                with gr.Row():
                                    ti_light = gr.Dropdown(ps.TI_LIGHTS, value=ps.TI_LIGHTS[0], label="Lighting")
                                    ti_finish = gr.Dropdown(ps.TI_FINISHES, value=ps.TI_FINISHES[0], label="Finish")
                                ti_detail = gr.Slider(1, 5, value=4, step=1, label="Detail level")
                                ti_notes = gr.Textbox(label="Must include / avoid (optional)")
                                ti_lock = gr.Checkbox(label="Add CHAD likeness lock + logo lock", value=False)
                                ti_btn = gr.Button("Build prompt", variant="primary")
                            with gr.Column():
                                ti_out = gr.Textbox(label="IMAGE_PROMPT.TXT", lines=16, buttons=["copy"])
                                ti_send = gr.Button("✨ Send to Create")
                        ti_fast.change(lambda k: ps.FAST_STARTS.get(k, ""), ti_fast, ti_idea)
                        ti_btn.click(counted(ps.build_ti), [ti_idea, ti_ratio, ti_shot, ti_light, ti_finish, ti_detail, ti_notes, ti_lock], ti_out)
                    with gr.Tab("Image → Image"):
                        with gr.Row():
                            with gr.Column():
                                ii_edit = gr.Textbox(label="What should change?", lines=4)
                                ii_lock = gr.Textbox(label="Preserve", value="identity, facial structure, pose, body proportions, key wardrobe details")
                                ii_strength = gr.Slider(1, 5, value=3, step=1, label="Transformation strength")
                                with gr.Row():
                                    ii_finish = gr.Dropdown(ps.II_FINISHES, value=ps.II_FINISHES[0], label="Finish")
                                    ii_ratio = gr.Dropdown(ps.II_RATIOS, value=ps.II_RATIOS[0], label="Output frame")
                                ii_logo = gr.Checkbox(label="Add logo lock (keep my emblems exactly)", value=True)
                                ii_btn = gr.Button("Build edit prompt", variant="primary")
                            ii_out = gr.Textbox(label="EDIT_DIRECTIVE.TXT", lines=16, buttons=["copy"])
                        ii_btn.click(counted(lambda e, l, s, f, r, lk: ps.build_ii(e, l, s, f, r, True, lk)),
                                     [ii_edit, ii_lock, ii_strength, ii_finish, ii_ratio, ii_logo], ii_out)
                    with gr.Tab("Image → Video"):
                        with gr.Row():
                            with gr.Column():
                                iv_action = gr.Textbox(label="Motion direction", lines=3, value="Make this image come alive with cinematic motion and smooth animation.")
                                with gr.Row():
                                    iv_cam = gr.Dropdown(ps.IV_CAMERAS, value=ps.IV_CAMERAS[0], label="Camera move")
                                    iv_dur = gr.Dropdown(ps.IV_DURATIONS, value="10", label="Duration (s)")
                                iv_cont = gr.Textbox(label="Continuity lock", value="preserve face, anatomy, wardrobe, environment geometry, and lighting direction")
                                iv_beats = gr.Textbox(label="Motion beats (optional)")
                                iv_loop = gr.Checkbox(label="Seamless loop (first frame = last frame)")
                                iv_btn = gr.Button("Build video prompt", variant="primary")
                            iv_out = gr.Textbox(label="MOTION_PLAN.TXT", lines=16, buttons=["copy"])
                        iv_btn.click(counted(lambda a, c, d, co, b, lp: ps.build_iv(a, c, d, co, b, True, lp)),
                                     [iv_action, iv_cam, iv_dur, iv_cont, iv_beats, iv_loop], iv_out)
                    with gr.Tab("Prompt Library"):
                        gr.Markdown(f"{len(PROMPTS)} ready prompts from the KING OF MUSIC prompt pack.")
                        with gr.Row():
                            lib_sec = gr.Dropdown(SECTIONS, value="All", label="Section")
                            lib_q = gr.Textbox(label="Search", placeholder="cover, loop, sneaker…")
                        lib_cards = gr.State(PROMPTS)
                        lib_pick = gr.Dropdown([], label="Prompt")
                        lib_text = gr.Textbox(label="Prompt text", lines=8, buttons=["copy"])
                        lib_sec.change(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])
                        lib_q.change(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])
                        lib_pick.change(pick_prompt, [lib_pick, lib_cards], lib_text)
                    with gr.Tab("Coach & Enhancer"):
                        coach = gr.Chatbot(value=[{"role": "assistant", "content": "Tell me what you're creating and where it will be used. I'll suggest structure, camera language, lighting, motion and negatives."}], height=320, label="Prompt Coach")
                        with gr.Row():
                            coach_in = gr.Textbox(placeholder="How do I make this feel like a premium music video?", scale=5, show_label=False)
                            coach_btn = gr.Button("Ask", variant="primary", scale=1)
                        coach_btn.click(coach_chat, [coach_in, coach], [coach_in, coach])
                        coach_in.submit(coach_chat, [coach_in, coach], [coach_in, coach])
                        with gr.Row():
                            with gr.Column():
                                en_in = gr.Textbox(label="Draft prompt", lines=5)
                                en_goal = gr.Dropdown(list(ps.EN_GOALS), value="Cinematic impact", label="Primary goal")
                                en_emph = gr.CheckboxGroup(ps.EN_EMPHASIS, value=["composition", "lighting", "quality"], label="Emphasis")
                                en_btn = gr.Button("Enhance prompt", variant="primary")
                            en_out = gr.Textbox(label="Enhanced result", lines=12, buttons=["copy"])
                        en_btn.click(counted(ps.enhance), [en_in, en_goal, en_emph], en_out)

        # ---- RELEASE KIT ----
        with gr.Tab("💿 Release Kit", id="release"):
            with gr.Row(equal_height=False):
                with gr.Column(elem_classes="aik-card"):
                    H("Cover Checker", "DistroKid-ready 3000×3000 + 9:16 + 16:9")
                    cv_img = gr.Image(type="filepath", label="Cover art", height=280)
                    cv_mode = gr.Radio(["Crop to fill", "Pad with blurred background (no crop)"], value="Crop to fill", label="Other sizes")
                    cv_btn = gr.Button("💿 Check + export", variant="primary")
                    cv_report = gr.Textbox(label="Report", lines=7)
                    cv_preview = gr.Image(type="filepath", label="3000×3000 preview", height=280)
                    cv_files = gr.File(label="Downloads", file_count="multiple")
                with gr.Column(elem_classes="aik-card"):
                    H("Captions & CTA", "TikTok · IG · Shorts · X · FB · Pinterest")
                    cp_plat = gr.Radio(captions.PLATFORMS, value="TikTok", label="Platform", elem_classes="aik-chips")
                    cp_song = gr.Textbox(label="Song title", value="KUNG FU COFFEE")
                    cp_hook = gr.Textbox(label="Hook line", placeholder="Brewed different. ☕👑")
                    cp_tags = gr.Textbox(label="Extra hashtags", placeholder="#kungfucoffee #lofibeats")
                    cp_link = gr.Textbox(label="Store / DistroKid link (optional)")
                    cp_biz = gr.Textbox(label="Business line (optional)")
                    cp_btn = gr.Button("🛍️ Build caption", variant="primary")
                    cp_out = gr.Textbox(label="Caption", lines=10, buttons=["copy"])
                    cp_note = gr.Markdown(elem_classes="aik-note")

        # ---- LABS ----
        with gr.Tab("🧪 Labs", id="labs"):
            gr.HTML('<div class="aik-note" style="margin:4px 4px 10px">Labs tools run on public open-source Hugging Face Spaces and use '
                    '<b>your own</b> free daily GPU minutes. If one is busy, try again later.</div>')
            with gr.Row(equal_height=False):
                with gr.Column(elem_classes="aik-card"):
                    H("Expand", "outpaint to 9:16 / 16:9 / square")
                    op_img = gr.Image(type="filepath", label="Image", height=260)
                    op_target = gr.Radio(["Vertical 9:16", "Wide 16:9", "Square"], value="Vertical 9:16", label="Target", elem_classes="aik-chips")
                    op_align = gr.Dropdown(["Middle", "Left", "Right", "Top", "Bottom"], value="Middle", label="Keep original at")
                    op_prompt = gr.Textbox(label="Describe the surroundings (optional)")
                    op_btn = gr.Button("🖼️ Expand", variant="primary")
                    op_out = gr.Image(type="filepath", label="Expanded", height=320)
                    op_msg = gr.Markdown(elem_classes="aik-note")
                with gr.Column(elem_classes="aik-card"):
                    H("Upscale", "2–4× for posters & merch")
                    up_img = gr.Image(type="filepath", label="Image", height=260)
                    up_f = gr.Radio([2, 3, 4], value=2, label="Factor", elem_classes="aik-chips")
                    up_btn = gr.Button("🔍 Upscale", variant="primary")
                    up_out = gr.Image(type="filepath", label="Upscaled", height=320)
                    up_msg = gr.Markdown(elem_classes="aik-note")
                with gr.Column(elem_classes="aik-card"):
                    gr.HTML('<div class="aik-soon"><h3>🎭 Face Swap: coming soon</h3>'
                            '<p>Face tools will only work with <b>your own face</b> or faces you have <b>written permission</b> to use, '
                            'with a consent check before every run. No explicit content, no minors, no impersonation.</p></div>')
                    gr.HTML('<div class="aik-soon" style="margin-top:12px"><h3>✂️ Timeline editor & captions: coming soon</h3>'
                            '<p>Multi-clip timeline, auto-captions and beat-synced cuts are next on the roadmap.</p></div>')

        # ---- ABOUT ----
        with gr.Tab("ℹ️ About", id="about"):
            with gr.Column(elem_classes="aik-card"):
                H("About AI KING©️", "free · open models · no account needed")
                eng = gr.Markdown(engine_md())
                gr.Markdown(
                    "**Install like an app:** on iPhone open this page in Safari → Share → **Add to Home Screen**. "
                    "On Android/Chrome tap ⋮ → **Install app**.\n\n"
                    "**Models & licenses:** FLUX.1 [schnell] (Apache-2.0) for images; LTX-Video 0.9.5 "
                    "(LTXV Open Weights License, free for creators/companies under $10M revenue) for video; ffmpeg for audio and loops. "
                    "Labs: diffusers-image-outpaint and finegrain-image-enhancer (community Spaces).\n\n"
                    "**Free GPU:** each visitor gets a daily ZeroGPU allowance from Hugging Face (more when logged in to Hugging Face).\n\n"
                    "**Content rules:** non-explicit creative use only; prompts are screened. "
                    "[Privacy](/privacy) · [Terms](/terms)\n\n"
                    "Made by **Chad Syphrett · KING OF MUSIC©️**.")
                gr.Button("↻ Refresh engine status", size="sm").click(engine_md, None, eng)

    gr.HTML(brand.FOOTER)

    # ---------- wiring ----------
    c_btn.click(do_create, [c_prompt, c_style, c_aspect, c_n, c_seed], [c_gallery, c_msg, c_paths, last_img]).then(hero, None, hero_box)
    c_prompt.submit(do_create, [c_prompt, c_style, c_aspect, c_n, c_seed], [c_gallery, c_msg, c_paths, last_img], api_name=False).then(hero, None, hero_box)
    c_gallery.select(pick_from_gallery, c_paths, last_img)
    c_to_edit.click(lambda p: (p, gr.Tabs(selected="edit")), last_img, [e_img, tabs])
    c_to_video.click(lambda p: (p, "Image → Video", gr.Tabs(selected="video")), last_img, [v_img, v_mode, tabs])
    e_btn.click(do_edit, [e_img, e_prompt, e_style, e_strength, e_seed], [e_out, e_msg]).then(hero, None, hero_box)
    e_to_video.click(lambda p: (p, "Image → Video", gr.Tabs(selected="video")), e_out, [v_img, v_mode, tabs])
    v_btn.click(do_video, [v_prompt, v_img, v_mode, v_sec, v_aspect, v_quality, v_seed], [v_out, v_msg]).then(hero, None, hero_box)
    a_btn.click(do_remix, [a_track, a_fx, a_start, a_end, a_fin, a_fout, a_loop, a_beat, a_bvol, a_fmt], [a_out, a_file, a_msg]).then(hero, None, hero_box)
    mv_btn.click(do_music_video, [mv_img, mv_clip, mv_audio, mv_size, mv_motion, mv_wave, mv_min], [mv_out, mv_msg]).then(hero, None, hero_box)
    ff_btn.click(do_ffmpeg_loop, [ff_vid, ff_style, ff_x, ff_min, ff_audio, ff_aspect], [ff_out, ff_msg]).then(hero, None, hero_box)
    ti_send.click(lambda t: (t, gr.Tabs(selected="create")), ti_out, [c_prompt, tabs])
    cv_btn.click(do_cover, [cv_img, cv_mode], [cv_report, cv_files, cv_preview])
    cp_btn.click(counted(captions.build_caption), [cp_plat, cp_song, cp_hook, cp_tags, cp_link, cp_biz], [cp_out, cp_note])
    op_btn.click(do_outpaint, [op_img, op_target, op_prompt, op_align], [op_out, op_msg])
    up_btn.click(do_upscale, [up_img, up_f], [up_out, up_msg])
    demo.load(on_load, None, [hero_box, tabs])
    demo.load(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])


# ---------- PWA + pages (served before Gradio's own routes) ----------

def _install_routes(app):
    from fastapi.responses import FileResponse, HTMLResponse, Response
    from starlette.routing import Route
    st = HERE / "static"

    async def manifest(request):
        return Response((st / "manifest.json").read_text(), media_type="application/manifest+json")

    async def sw(request):
        return Response((st / "sw.js").read_text(), media_type="application/javascript",
                        headers={"Service-Worker-Allowed": "/", "Cache-Control": "no-cache"})

    def page(name):
        async def h(request):
            return HTMLResponse((st / name).read_text())
        return h

    async def apple_icon(request):
        return FileResponse(st / "icons" / "apple-touch-icon.png", media_type="image/png")

    new = [Route("/manifest.json", manifest), Route("/manifest.webmanifest", manifest), Route("/sw.js", sw),
           Route("/privacy", page("privacy.html")), Route("/terms", page("terms.html")), Route("/offline", page("offline.html")),
           Route("/apple-touch-icon.png", apple_icon), Route("/apple-touch-icon-precomposed.png", apple_icon)]
    app.router.routes[0:0] = new


if __name__ == "__main__":
    demo.queue(default_concurrency_limit=2, max_size=64)
    demo.launch(
        theme=brand.THEME, css=brand.CSS, js=brand.JS, head=brand.HEAD + "<style>" + brand.CSS + "</style>",
        favicon_path=str(HERE / "static" / "icons" / "favicon-64.png"),
        server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"),
        server_port=int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", 7860))),
        ssr_mode=False, pwa=True, prevent_thread_lock=True, show_error=True,
    )
    _install_routes(demo.server_app if getattr(demo, "server_app", None) else demo.app)
    demo.block_thread()