Spaces:
Running on Zero
Running on Zero
Download app.py from INTERNETCON/AI-KING-Studio: direct link, hf CLI and curl.
- Browser
- Download file 34.8 kB
-
https://huggingface.co/spaces/INTERNETCON/AI-KING-Studio/resolve/main/app.py
- Command line
-
hf download hf://spaces/INTERNETCON/AI-KING-Studio/app.py
-
curl -L -o app.py https://huggingface.co/spaces/INTERNETCON/AI-KING-Studio/resolve/main/app.py
34.8 kB
| """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() | |