INTERNETCON commited on
Commit
08e06c9
·
verified ·
1 Parent(s): 3249e1b

AI KING Studio v2: real ZeroGPU generators (FLUX.1 schnell + LTX-Video), Audio Lab, stats, PWA, redesign

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ static/icons/icon-1024.png filter=lfs diff=lfs merge=lfs -text
37
+ static/icons/icon-512.png filter=lfs diff=lfs merge=lfs -text
.gitignore CHANGED
@@ -1 +1,3 @@
1
  __pycache__/
 
 
 
1
  __pycache__/
2
+ *.pyc
3
+ stats.json
README.md CHANGED
@@ -2,63 +2,51 @@
2
  title: AI KING Studio
3
  emoji: 👑
4
  colorFrom: yellow
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.29.1
8
- python_version: "3.11"
9
  app_file: app.py
10
  pinned: true
11
  license: mit
12
- short_description: KING OF MUSIC creator studio, prompts to video & covers
 
13
  tags:
14
- - image-editing
 
15
  - image-to-video
16
- - prompt-engineering
17
- - music
 
 
 
 
18
  ---
19
 
20
  # AI KING©️ Studio
21
 
22
- KING OF MUSIC©️ / KING OF POLICE + MUSIC & MOVIES©️ all-in-one creative console by Chad Syphrett.
23
- Live at: https://huggingface.co/spaces/INTERNETCON/AI-KING-Studio
24
 
25
- **Non-explicit only.** Prompts pass a content filter before any remote call, and upstream safety checks stay on.
26
- Only upload faces you own or have written permission to use.
27
-
28
- ## Tabs
29
- | Tab | What it does | Runs on |
30
  |---|---|---|
31
- | 👑 Prompt Studio | Text→Image, Image→Image, Image→Video prompt builders, Prompt Coach, Enhancer (ported from the Muse AI KING build) + CHAD likeness/logo locks | this Space (CPU) |
32
- | 📚 Prompt Library | Searchable cards from the KING OF MUSIC prompt pack (`prompts.json`) | CPU |
33
- | 🎨 Photo Edit | Instruction edits | FLUX.1 Kontext Dev → Qwen-Image-Edit-2509 |
34
- | 🧑 Same-Face | New scenes keeping one face | PuLID-FLUX → InstantID |
35
- | 🖼️ Expand | Outpaint to 9:16 / 16:9 / square | diffusers-image-outpaint |
36
- | 🎬 Image → Video | Animate a still | Wan2.2 (zerogpu-aoti) → LTX-Video distilled |
37
- | 🔁 Loop Maker | AI first/last-frame loop; ffmpeg ping-pong / crossfade / repeat-to-1h / add song | LTX-2.3 First-Last-Frame; CPU ffmpeg |
38
- | 🔍 Upscale | 2–4× image upscale | finegrain-image-enhancer |
39
- | 💿 Cover Checker | 3000×3000 / RGB / JPG check, exports 3000², 1080×1920, 1920×1080 | CPU |
40
- | 🛍️ Captions & CTA | Platform caption templates with KING OF MUSIC CTAs | CPU |
41
- | 🚦 Tool Status | Live status + model license of every remote Space | CPU |
42
-
43
- ## How GPU costs work
44
- This Space runs on free **CPU Basic**. GPU tools call public **ZeroGPU** Spaces with `gradio_client`,
45
- forwarding the visitor's `x-ip-token`, so each visitor's own free daily GPU minutes are used.
46
- Logged-in Hugging Face users get more minutes.
47
-
48
- ## Excluded on purpose
49
- - **MiniMax-H3** (and its Turbo LoRA Space): the MiniMax H3 Community License excludes use of the model
50
- *or its outputs* in the US, EU, UK and South Korea.
51
- - Any NSFW / "uncensored" model or generator.
52
-
53
- ## Credits & licenses
54
- Our code: MIT. Each remote tool keeps its own license (see the Tool Status tab):
55
- FLUX.1 Kontext [dev] (BFL FLUX.1 [dev] Non-Commercial License), Qwen-Image-Edit (Apache-2.0),
56
- PuLID (Apache-2.0), InstantID (Apache-2.0), Wan2.2 (Apache-2.0), LTX-Video / LTX-2 (Lightricks open-weights
57
- licenses, free under $10M annual revenue), diffusers-image-outpaint and finegrain enhancer (community Spaces).
58
-
59
- ## Local run
60
- ```bash
61
- pip install -r requirements.txt # plus ffmpeg on PATH
62
- python build_prompts.py # optional: refresh prompts.json from prompt-pack.md
63
- python app.py # http://localhost:7860
64
- ```
 
2
  title: AI KING Studio
3
  emoji: 👑
4
  colorFrom: yellow
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 6.29.1
8
+ python_version: "3.10"
9
  app_file: app.py
10
  pinned: true
11
  license: mit
12
+ startup_duration_timeout: 1h
13
+ short_description: Free AI images, videos, loops, remixes & music videos
14
  tags:
15
+ - text-to-image
16
+ - image-to-image
17
  - image-to-video
18
+ - text-to-video
19
+ - audio
20
+ - zerogpu
21
+ models:
22
+ - black-forest-labs/FLUX.1-schnell
23
+ - Lightricks/LTX-Video-0.9.5
24
  ---
25
 
26
  # AI KING©️ Studio
27
 
28
+ **An all-in-one free AI creative studio by KING OF MUSIC©️ (Chad Syphrett).**
29
+ Install it like an app: iPhone Safari → Share → *Add to Home Screen* · Android Chrome → ⋮ → *Install app*.
30
 
31
+ | Tab | What it does | Engine |
 
 
 
 
32
  |---|---|---|
33
+ | ✨ Create | Text → image, 8 style presets, 4 frames, up to 4 images | FLUX.1 [schnell] on ZeroGPU |
34
+ | 🎨 Edit | Image → image restyle with change-amount slider | FLUX.1 [schnell] img2img on ZeroGPU |
35
+ | 🎬 Video | Text → video (FLUX keyframe + motion), image → video, **seamless loops** | LTX-Video 0.9.5 on ZeroGPU |
36
+ | 🎧 Audio Lab | Remix (lofi, bass boost, sped up, slowed + reverb, echo, 8D, -14 LUFS), trim, fades, loop to length, mix a beat · **Music Video Maker** (cover/clip + song → MP4 with gold waveform) | ffmpeg (CPU) |
37
+ | 🔁 Loops & Export | Ping-pong / crossfade loops, repeat to 1 h, add your song, 9:16 / 16:9 / 1:1 | ffmpeg (CPU) |
38
+ | 👑 Prompt Studio | KING OF MUSIC prompt builder, library, coach, enhancer | CPU |
39
+ | 💿 Release Kit | DistroKid cover checker (3000×3000 + 9:16 + 16:9), caption & CTA builder | CPU |
40
+ | 🧪 Labs | Expand (outpaint), Upscale via public Spaces; Face Swap *coming soon (consent-only)* | visitor's own ZeroGPU minutes |
41
+
42
+ - **Free:** open models on this Space's ZeroGPU; no paid inference providers. Each visitor uses their own daily ZeroGPU allowance.
43
+ - **Stats:** visits/creations are counted in a private dataset repo (`INTERNETCON/ai-king-stats`), falling back to local JSON.
44
+ - **PWA:** `/manifest.json`, `/sw.js`, apple-touch-icon, theme color. Privacy: `/privacy` · Terms: `/terms`.
45
+ - **Content rules:** non-explicit only; prompts are screened. MiniMax-H3 is excluded (its license bars US use).
46
+
47
+ ## Licenses
48
+ Code: MIT. FLUX.1 [schnell]: Apache-2.0. LTX-Video 0.9.5: LTXV Open Weights License (free under $10M annual revenue).
49
+ AI KING©️ and KING OF MUSIC©️ marks © Chad Syphrett.
50
+
51
+ ## Links
52
+ [YouTube @ChadSyphrett](https://www.youtube.com/@ChadSyphrett) · [TikTok @MusicVideosTM](https://www.tiktok.com/@MusicVideosTM) · [Instagram @InternetThemePark](https://www.instagram.com/InternetThemePark)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,48 +1,39 @@
1
- """AI KING©️ Studio: KING OF MUSIC©️ all-in-one creator app (Gradio Space).
2
 
3
- Runs on free CPU Basic. Heavy GPU work is sent to public ZeroGPU Spaces through
4
- gradio_client, forwarding the visitor's x-ip-token so their own free minutes are used.
5
- Non-explicit only. MiniMax-H3 is excluded (license bans US use).
 
6
  """
7
  import json, os, pathlib
8
 
 
 
 
9
  import gradio as gr
10
 
 
 
 
11
  import captions
12
  import cover_tools
13
  import loop_tools
14
  import prompt_studio as ps
15
  import remote
 
16
  from safety import CONSENT_NOTE, check_prompt
17
 
18
- HERE = pathlib.Path(__file__).parent
 
19
  try:
20
  PROMPTS = json.loads((HERE / "prompts.json").read_text(encoding="utf-8"))
21
  except Exception:
22
  PROMPTS = []
23
  SECTIONS = ["All"] + sorted({c["section"] for c in PROMPTS})
 
24
 
25
- HEADER = """
26
- <div style="text-align:center;padding:10px 0 4px">
27
- <h1 style="margin:0;font-family:Georgia,serif;font-size:2.4rem"><span style="color:#d2a330">AI KING©️</span> Studio</h1>
28
- <p style="margin:6px 0 0;opacity:.8">KING OF POLICE + MUSIC &amp; MOVIES©️ creative console · prompts, edits, same-face scenes, video, loops, covers &amp; captions</p>
29
- <p style="margin:4px 0 0;font-size:.85rem;opacity:.7">GPU tools use <b>your own</b> free daily Hugging Face minutes (log in for more). Nothing is posted anywhere.</p>
30
- </div>
31
- """
32
- FOOTER = """
33
- <div style="text-align:center;font-size:.85rem;opacity:.8;padding:12px 0">
34
- <a href="https://instagram.com/internetthemepark" target="_blank">@InternetThemePark ↗</a> ·
35
- <a href="https://buymeacoffee.com/KingOfMusic" target="_blank">@KINGOFMUSIC ↗</a> ·
36
- <a href="https://youtube.com/@ChadSyphrett" target="_blank">YouTube ↗</a><br>
37
- Everyday Is A Lesson. Be Thankful To YHWH! — KING OF MUSIC©️
38
- </div>
39
- """
40
- CSS = """
41
- .gradio-container {max-width: 1400px !important}
42
- #aiking-out textarea {font-family: ui-monospace, Menlo, monospace; font-size: .85rem}
43
- """
44
- THEME = gr.themes.Soft(primary_hue="amber", secondary_hue="teal", neutral_hue="stone")
45
 
 
46
 
47
  def _guard(*texts):
48
  for t in texts:
@@ -51,55 +42,107 @@ def _guard(*texts):
51
  raise gr.Error(err)
52
 
53
 
54
- def _run(fn, *args, request=None, **kw):
 
 
 
 
 
 
55
  try:
56
- path, used = fn(*args, request=request, **kw)
57
- except remote.ToolError as e:
58
- raise gr.Error(str(e))
59
- if not path:
60
- raise gr.Error("The remote tool finished but returned no file.")
61
- return path, f"Done with {used}."
62
 
63
 
64
- # ---------------- handlers ----------------
 
 
 
65
 
66
- def do_edit(img, prompt, keep_logos, request: gr.Request):
67
- if not img:
68
- raise gr.Error("Upload an image first.")
 
 
 
69
  _guard(prompt)
70
- if keep_logos:
71
- prompt = prompt.rstrip(". ") + ". " + ps.LOGO_LOCK
72
- return _run(remote.edit_image, img, prompt, request=request)
 
 
 
 
 
 
73
 
74
 
75
- def do_same_face(face, prompt, negative, frame, request: gr.Request):
76
- if not face:
77
- raise gr.Error("Upload a clear face photo first.")
78
- _guard(prompt, negative)
79
- w, h = {"Vertical 9:16": (768, 1344), "Square 1:1": (1024, 1024), "Wide 16:9": (1344, 768), "Portrait 4:5": (896, 1152)}[frame]
80
- return _run(remote.same_face, face, prompt, negative or ps.UNIVERSAL_NEGATIVE, w, h, request=request)
 
 
81
 
82
 
83
- def do_outpaint(img, target, prompt, align, request: gr.Request):
84
  if not img:
85
- raise gr.Error("Upload an image first.")
 
 
86
  _guard(prompt)
87
- w, h = {"Vertical 9:16 (720x1280)": (720, 1280), "Wide 16:9 (1280x720)": (1280, 720), "Square (1024x1024)": (1024, 1024)}[target]
88
- return _run(remote.outpaint, img, w, h, prompt, align, request=request)
 
 
 
 
 
 
 
89
 
90
 
91
- def do_i2v(img, prompt, negative, seconds, request: gr.Request):
92
- if not img:
93
- raise gr.Error("Upload a start frame first.")
94
- _guard(prompt, negative)
95
- return _run(remote.image_to_video, img, prompt, negative, seconds, request=request)
 
 
 
 
 
 
 
 
 
 
 
96
 
97
 
98
- def do_flf(first, last, prompt, seconds, request: gr.Request):
99
- if not first:
100
- raise gr.Error("Upload at least a first frame (it is reused as the last frame for a perfect loop).")
101
- _guard(prompt)
102
- return _run(remote.first_last_loop, first, last, prompt, seconds, request=request)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
 
105
  def do_ffmpeg_loop(video, style, xfade, minutes, audio, aspect):
@@ -109,13 +152,8 @@ def do_ffmpeg_loop(video, style, xfade, minutes, audio, aspect):
109
  out = loop_tools.make_loop(video, style, xfade, float(minutes or 0) * 60, audio, aspect)
110
  except Exception as e:
111
  raise gr.Error(str(e)[:400])
112
- return out, "Loop ready."
113
-
114
-
115
- def do_upscale(img, factor, request: gr.Request):
116
- if not img:
117
- raise gr.Error("Upload an image first.")
118
- return _run(remote.upscale, img, factor, request=request)
119
 
120
 
121
  def do_cover(img, mode):
@@ -123,9 +161,35 @@ def do_cover(img, mode):
123
  raise gr.Error("Upload a cover image first.")
124
  report = cover_tools.check_cover(img)
125
  files = cover_tools.export_sizes(img, "crop" if mode.startswith("Crop") else "pad")
 
126
  return report, files, files[0]
127
 
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  def filter_prompts(section, query):
130
  q = (query or "").lower().strip()
131
  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())]
@@ -144,232 +208,375 @@ def coach_chat(msg, history):
144
  history = history or []
145
  if not (msg or "").strip():
146
  return "", history
147
- history = history + [{"role": "user", "content": msg}, {"role": "assistant", "content": ps.coach_reply(msg)}]
148
- return "", history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
 
 
 
 
 
 
 
 
150
 
151
  # ---------------- UI ----------------
152
 
153
  with gr.Blocks(title="AI KING©️ Studio") as demo:
154
- gr.HTML(HEADER)
155
-
156
- with gr.Tab("👑 Prompt Studio"):
157
- gr.Markdown("Ported from the Muse **AI KING** build. Build a production prompt, then send it to the GPU tabs or copy it into Grok / Muse / Perchance.")
158
- with gr.Tab("01 Text → Image"):
159
- with gr.Row():
160
- with gr.Column():
161
- ti_idea = gr.Textbox(label="Core idea", lines=4, placeholder="A futuristic music producer at a midnight control desk, gold crown on the console, city lights beyond the studio glass")
162
- ti_fast = gr.Radio(list(ps.FAST_STARTS), label="Fast starts")
 
 
 
 
163
  with gr.Row():
164
- ti_ratio = gr.Dropdown(ps.TI_RATIOS, value=ps.TI_RATIOS[0], label="Frame")
165
- ti_shot = gr.Dropdown(ps.TI_SHOTS, value=ps.TI_SHOTS[0], label="Camera")
 
 
 
 
 
166
  with gr.Row():
167
- ti_light = gr.Dropdown(ps.TI_LIGHTS, value=ps.TI_LIGHTS[0], label="Lighting")
168
- ti_finish = gr.Dropdown(ps.TI_FINISHES, value=ps.TI_FINISHES[0], label="Finish")
169
- ti_detail = gr.Slider(1, 5, value=4, step=1, label="Detail level")
170
- ti_notes = gr.Textbox(label="Must include / avoid (optional)", placeholder="Exact wardrobe, color palette, no logos, no text…")
171
- ti_lock = gr.Checkbox(label="Add CHAD likeness lock + logo lock", value=False)
172
- ti_btn = gr.Button("Build prompt", variant="primary")
173
- ti_out = gr.Textbox(label="IMAGE_PROMPT.TXT", lines=18, buttons=["copy"], elem_id="aiking-out")
174
- ti_fast.change(lambda k: ps.FAST_STARTS.get(k, ""), ti_fast, ti_idea)
175
- ti_btn.click(ps.build_ti, [ti_idea, ti_ratio, ti_shot, ti_light, ti_finish, ti_detail, ti_notes, ti_lock], ti_out)
176
- with gr.Tab("02 Image → Image"):
177
- with gr.Row():
178
- with gr.Column():
179
- ii_img = gr.Image(type="filepath", label="Reference image (optional, for your eyes only)")
180
- ii_edit = gr.Textbox(label="What should change?", lines=4, placeholder="Replace the background with a futuristic stage, preserve the person's face, pose, clothing silhouette, and body proportions")
181
- ii_lock = gr.Textbox(label="Preserve", value="identity, facial structure, pose, body proportions, key wardrobe details")
182
- ii_strength = gr.Slider(1, 5, value=3, step=1, label="Transformation strength")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  with gr.Row():
184
- ii_finish = gr.Dropdown(ps.II_FINISHES, value=ps.II_FINISHES[0], label="Finish")
185
- ii_ratio = gr.Dropdown(ps.II_RATIOS, value=ps.II_RATIOS[0], label="Output frame")
186
- ii_logo = gr.Checkbox(label="Add logo lock (keep my emblems exactly)", value=True)
187
- ii_btn = gr.Button("Build edit prompt", variant="primary")
188
- ii_out = gr.Textbox(label="EDIT_DIRECTIVE.TXT", lines=18, buttons=["copy"], elem_id="aiking-out")
189
- ii_btn.click(lambda e, l, s, f, r, img, lk: ps.build_ii(e, l, s, f, r, bool(img), lk),
190
- [ii_edit, ii_lock, ii_strength, ii_finish, ii_ratio, ii_img, ii_logo], ii_out)
191
- with gr.Tab("03 Image → Video"):
192
- with gr.Row():
193
- with gr.Column():
194
- iv_img = gr.Image(type="filepath", label="Starting image (optional)")
195
- iv_action = gr.Textbox(label="Motion direction", lines=3, value="Make this image come alive with cinematic motion and smooth animation.")
196
- with gr.Row():
197
- iv_cam = gr.Dropdown(ps.IV_CAMERAS, value=ps.IV_CAMERAS[0], label="Camera move")
198
- iv_dur = gr.Dropdown(ps.IV_DURATIONS, value="10", label="Duration (s)")
199
- iv_cont = gr.Textbox(label="Continuity lock", value="preserve face, anatomy, wardrobe, environment geometry, and lighting direction")
200
- iv_beats = gr.Textbox(label="Motion beats (optional, comma-separated)", placeholder="Eyes lift, fabric moves in the breeze, lights pulse, camera settles")
201
- iv_loop = gr.Checkbox(label="Seamless loop (first frame = last frame)")
202
- iv_btn = gr.Button("Build video prompt", variant="primary")
203
- iv_out = gr.Textbox(label="MOTION_PLAN.TXT", lines=18, buttons=["copy"], elem_id="aiking-out")
204
- iv_btn.click(lambda a, c, d, co, b, img, lp: ps.build_iv(a, c, d, co, b, bool(img), lp),
205
- [iv_action, iv_cam, iv_dur, iv_cont, iv_beats, iv_img, iv_loop], iv_out)
206
- with gr.Tab("04 Prompt Coach"):
207
- coach = gr.Chatbot(value=[{"role": "assistant", "content": "Tell me what you are creating and where it will be used. I can suggest structure, camera language, lighting, motion, or negative constraints."}], height=380, label="Coach")
208
- with gr.Row():
209
- coach_in = gr.Textbox(placeholder="Ask: How do I make this feel like a premium music video?", scale=5, show_label=False)
210
- coach_btn = gr.Button("Ask coach", variant="primary", scale=1)
211
- gr.Examples(ps.COACH_PRESETS, coach_in)
212
- coach_btn.click(coach_chat, [coach_in, coach], [coach_in, coach])
213
- coach_in.submit(coach_chat, [coach_in, coach], [coach_in, coach])
214
- with gr.Tab("05 Enhancer"):
215
- with gr.Row():
216
- with gr.Column():
217
- en_in = gr.Textbox(label="Draft prompt", lines=8)
218
- en_goal = gr.Dropdown(list(ps.EN_GOALS), value="Cinematic impact", label="Primary goal")
219
- en_emph = gr.CheckboxGroup(ps.EN_EMPHASIS, value=["composition", "lighting", "quality"], label="Emphasis")
220
- en_btn = gr.Button("Enhance prompt", variant="primary")
221
- en_out = gr.Textbox(label="Enhanced result", lines=18, buttons=["copy"], elem_id="aiking-out")
222
- en_btn.click(ps.enhance, [en_in, en_goal, en_emph], en_out)
223
-
224
- with gr.Tab("📚 Prompt Library"):
225
- gr.Markdown(f"{len(PROMPTS)} ready prompts from the KING OF MUSIC prompt pack (likeness locks, ALEXA 35 stills, covers, sneaker ads, loops, negatives).")
226
- with gr.Row():
227
- lib_sec = gr.Dropdown(SECTIONS, value="All", label="Section", scale=2)
228
- lib_q = gr.Textbox(label="Search", placeholder="cover, loop, WAIATA, sneaker…", scale=2)
229
- lib_cards = gr.State(PROMPTS)
230
- lib_pick = gr.Dropdown([], label="Prompt")
231
- lib_text = gr.Textbox(label="Prompt text", lines=10, buttons=["copy"], elem_id="aiking-out")
232
- lib_sec.change(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])
233
- lib_q.change(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])
234
- lib_pick.change(pick_prompt, [lib_pick, lib_cards], lib_text)
235
-
236
- with gr.Tab("🎨 Photo Edit"):
237
- gr.Markdown(f"Instruction edits with FLUX.1 Kontext (fallback: Qwen-Image-Edit). ⚠️ {CONSENT_NOTE}")
238
- with gr.Row():
239
- with gr.Column():
240
- ed_img = gr.Image(type="filepath", label="Image to edit")
241
- ed_prompt = gr.Textbox(label="Edit instruction", lines=3, placeholder="Remove the watermark in the bottom-right corner and extend the background naturally")
242
- ed_logo = gr.Checkbox(label="Keep my logos/emblems exactly", value=True)
243
- ed_btn = gr.Button("Edit image", variant="primary")
244
- with gr.Column():
245
- ed_out = gr.Image(type="filepath", label="Result")
246
- ed_msg = gr.Markdown()
247
- ed_btn.click(do_edit, [ed_img, ed_prompt, ed_logo], [ed_out, ed_msg])
248
-
249
- with gr.Tab("🧑 Same-Face"):
250
- gr.Markdown(f"New scenes that keep one face (PuLID-FLUX, fallback InstantID). ⚠️ {CONSENT_NOTE}")
251
- with gr.Row():
252
- with gr.Column():
253
- sf_face = gr.Image(type="filepath", label="Face reference (clear, front-facing)")
254
- sf_prompt = gr.Textbox(label="Scene prompt", lines=4, value=ps.CHAD_LOCK + " Navy suit, grey fedora, cinematic ARRI ALEXA 35 portrait, moody jazz lounge.")
255
- sf_neg = gr.Textbox(label="Negative prompt", lines=2, value=ps.UNIVERSAL_NEGATIVE)
256
- sf_frame = gr.Radio(["Vertical 9:16", "Portrait 4:5", "Square 1:1", "Wide 16:9"], value="Portrait 4:5", label="Frame")
257
- sf_btn = gr.Button("Generate", variant="primary")
258
- with gr.Column():
259
- sf_out = gr.Image(type="filepath", label="Result")
260
- sf_msg = gr.Markdown()
261
- sf_btn.click(do_same_face, [sf_face, sf_prompt, sf_neg, sf_frame], [sf_out, sf_msg])
262
-
263
- with gr.Tab("🖼️ Expand (Outpaint)"):
264
- gr.Markdown("Fix screenshot leftovers, black/white bars, or make vertical/wide versions by **expanding** the scene instead of cropping.")
265
- with gr.Row():
266
- with gr.Column():
267
- op_img = gr.Image(type="filepath", label="Image")
268
- op_target = gr.Radio(["Vertical 9:16 (720x1280)", "Wide 16:9 (1280x720)", "Square (1024x1024)"], value="Vertical 9:16 (720x1280)", label="Target")
269
- op_align = gr.Dropdown(["Middle", "Left", "Right", "Top", "Bottom"], value="Middle", label="Keep original at")
270
- op_prompt = gr.Textbox(label="Describe the surroundings (optional)")
271
- op_btn = gr.Button("Expand", variant="primary")
272
- with gr.Column():
273
- op_out = gr.Image(type="filepath", label="Expanded")
274
- op_msg = gr.Markdown()
275
- op_btn.click(do_outpaint, [op_img, op_target, op_prompt, op_align], [op_out, op_msg])
276
-
277
- with gr.Tab("🎬 Image → Video"):
278
- gr.Markdown("Animate a still with Wan2.2 (fallback: LTX-Video distilled).")
279
- with gr.Row():
280
- with gr.Column():
281
- v_img = gr.Image(type="filepath", label="Start frame")
282
- v_prompt = gr.Textbox(label="Motion prompt", lines=4, value="Slow cinematic push-in, subtle head turn, fabric moving in a light breeze, lights glinting on the gold pendant.")
283
- v_neg = gr.Textbox(label="Negative prompt", value="worst quality, blurry, distorted face, morphing, extra limbs, text, watermark")
284
- v_sec = gr.Slider(2, 8, value=5, step=0.5, label="Seconds")
285
- v_btn = gr.Button("Make video", variant="primary")
286
- with gr.Column():
287
- v_out = gr.Video(label="Video")
288
- v_msg = gr.Markdown()
289
- v_btn.click(do_i2v, [v_img, v_prompt, v_neg, v_sec], [v_out, v_msg])
290
-
291
- with gr.Tab("🔁 Loop Maker"):
292
- with gr.Tab("True loop (AI, first = last frame)"):
293
- gr.Markdown("Uses LTX-2.3 First/Last-Frame. Leave **Last frame** empty to reuse the first frame → seamless lofi loop.")
294
- with gr.Row():
295
- with gr.Column():
296
- fl_first = gr.Image(type="filepath", label="First frame")
297
- fl_last = gr.Image(type="filepath", label="Last frame (optional)")
298
- fl_prompt = gr.Textbox(label="Prompt", lines=3, value="Seamless looping lofi scene, locked camera, subtle motion only: rain on the window, steam rising, city lights twinkling, slow head nod.")
299
- fl_sec = gr.Slider(2, 8, value=4, step=0.5, label="Seconds")
300
- fl_btn = gr.Button("Make AI loop", variant="primary")
301
- with gr.Column():
302
- fl_out = gr.Video(label="Loop")
303
- fl_msg = gr.Markdown()
304
- fl_btn.click(do_flf, [fl_first, fl_last, fl_prompt, fl_sec], [fl_out, fl_msg])
305
- with gr.Tab("ffmpeg loop (free, CPU)"):
306
- gr.Markdown("Turn any clip into a loop, repeat it for a 24/7 stream, and add your song.")
307
- with gr.Row():
308
- with gr.Column():
309
  ff_vid = gr.Video(label="Clip")
310
- ff_style = gr.Radio(["ping-pong", "crossfade"], value="ping-pong", label="Loop style")
311
  ff_x = gr.Slider(0.2, 2.0, value=0.75, step=0.05, label="Crossfade seconds")
312
  ff_min = gr.Number(value=0, label="Repeat to length (minutes, 0 = one loop, 60 = 1 hour)")
313
  ff_audio = gr.Audio(type="filepath", label="Song (optional)")
314
- ff_aspect = gr.Dropdown(list(loop_tools.ASPECTS), value="keep", label="Export frame")
315
- ff_btn = gr.Button("Make loop", variant="primary")
316
- with gr.Column():
317
- ff_out = gr.Video(label="Loop")
318
- ff_msg = gr.Markdown()
319
- ff_btn.click(do_ffmpeg_loop, [ff_vid, ff_style, ff_x, ff_min, ff_audio, ff_aspect], [ff_out, ff_msg])
320
-
321
- with gr.Tab("🔍 Upscale"):
322
- with gr.Row():
323
- with gr.Column():
324
- up_img = gr.Image(type="filepath", label="Image")
325
- up_f = gr.Radio([2, 3, 4], value=2, label="Factor")
326
- up_btn = gr.Button("Upscale", variant="primary")
327
- with gr.Column():
328
- up_out = gr.Image(type="filepath", label="Upscaled")
329
- up_msg = gr.Markdown()
330
- up_btn.click(do_upscale, [up_img, up_f], [up_out, up_msg])
331
-
332
- with gr.Tab("💿 Cover Checker"):
333
- with gr.Row():
334
- with gr.Column():
335
- cv_img = gr.Image(type="filepath", label="Cover art")
336
- cv_mode = gr.Radio(["Crop to fill", "Pad with blurred background (no crop)"], value="Crop to fill", label="How to make other sizes")
337
- cv_btn = gr.Button("Check + make 3000x3000 / 9:16 / 16:9", variant="primary")
338
- with gr.Column():
339
- cv_report = gr.Textbox(label="Report", lines=10)
340
- cv_preview = gr.Image(type="filepath", label="3000x3000 preview")
341
- cv_files = gr.File(label="Downloads", file_count="multiple")
342
- cv_btn.click(do_cover, [cv_img, cv_mode], [cv_report, cv_files, cv_preview])
343
-
344
- with gr.Tab("🛍️ Captions & CTA"):
345
- with gr.Row():
346
- with gr.Column():
347
- cp_plat = gr.Dropdown(captions.PLATFORMS, value="TikTok", label="Platform")
348
- cp_song = gr.Textbox(label="Song title", value="KUNG FU COFFEE")
349
- cp_hook = gr.Textbox(label="Hook line", placeholder="Brewed different. ☕👑")
350
- cp_tags = gr.Textbox(label="Extra hashtags", placeholder="#kungfucoffee #lofibeats")
351
- cp_link = gr.Textbox(label="Store / DistroKid link (optional)")
352
- cp_biz = gr.Textbox(label="Business line sentence (optional)")
353
- cp_btn = gr.Button("Build caption", variant="primary")
354
- with gr.Column():
355
- cp_out = gr.Textbox(label="Caption", lines=12, buttons=["copy"])
356
- cp_note = gr.Markdown()
357
- cp_btn.click(captions.build_caption, [cp_plat, cp_song, cp_hook, cp_tags, cp_link, cp_biz], [cp_out, cp_note])
358
-
359
- with gr.Tab("🚦 Tool Status"):
360
- gr.Markdown("Live status of the public Spaces AI KING uses, with model licenses. If a primary is down, the fallback is used automatically.")
361
- st_tbl = gr.Dataframe(headers=["tool", "role", "space", "status", "license"], interactive=False, wrap=True)
362
- st_btn = gr.Button("Refresh status")
363
- st_btn.click(remote.status_table, None, st_tbl)
364
-
365
- gr.HTML(FOOTER)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  demo.load(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])
367
 
368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369
  if __name__ == "__main__":
370
- demo.queue(default_concurrency_limit=4).launch(
371
- theme=THEME, css=CSS,
 
 
372
  server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"),
373
  server_port=int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", 7860))),
374
- ssr_mode=False,
375
  )
 
 
 
1
+ """AI KING©️ Studio: all-in-one free AI creative studio by KING OF MUSIC©️ (Chad Syphrett).
2
 
3
+ Real generators run on this Space's ZeroGPU slot with open models only:
4
+ FLUX.1 [schnell] (text→image, image→image) and LTX-Video 0.9.5 (text/image→video, seamless loops).
5
+ CPU tools: Audio Lab (ffmpeg remix/loop), Music Video Maker, Loop & Export, Cover Checker, Captions, Prompt Studio.
6
+ No paid inference providers. Non-explicit content only. MiniMax-H3 excluded (US license).
7
  """
8
  import json, os, pathlib
9
 
10
+ HERE = pathlib.Path(__file__).parent.resolve()
11
+ os.chdir(HERE)
12
+
13
  import gradio as gr
14
 
15
+ import gen # loads models at import time (ZeroGPU best practice)
16
+ import audio_tools
17
+ import brand
18
  import captions
19
  import cover_tools
20
  import loop_tools
21
  import prompt_studio as ps
22
  import remote
23
+ import stats
24
  from safety import CONSENT_NOTE, check_prompt
25
 
26
+ gr.set_static_paths(paths=[HERE / "static"])
27
+
28
  try:
29
  PROMPTS = json.loads((HERE / "prompts.json").read_text(encoding="utf-8"))
30
  except Exception:
31
  PROMPTS = []
32
  SECTIONS = ["All"] + sorted({c["section"] for c in PROMPTS})
33
+ TAB_IDS = {"create", "edit", "video", "audio", "loops", "studio", "release", "labs", "about"}
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ # ---------------- helpers ----------------
37
 
38
  def _guard(*texts):
39
  for t in texts:
 
42
  raise gr.Error(err)
43
 
44
 
45
+ def hero():
46
+ return brand.hero_html(stats.snapshot(), stats.MODE)
47
+
48
+
49
+ def on_load(request: gr.Request):
50
+ stats.hit("visits")
51
+ tab = None
52
  try:
53
+ tab = (request.query_params.get("tab") or "").lower() if request else None
54
+ except Exception:
55
+ tab = None
56
+ return hero(), (gr.Tabs(selected=tab) if tab in TAB_IDS else gr.Tabs())
 
 
57
 
58
 
59
+ def _engine_check(kind):
60
+ if gen.STATUS.get(kind) != "ready":
61
+ msg = gen.ERRORS.get(kind) or ("preview mode, models off" if gen.NO_MODELS else "warming up, try again in a minute")
62
+ raise gr.Error(f"{'Image' if kind == 'image' else 'Video'} engine not ready: {msg}")
63
 
64
+
65
+ # ---------------- GPU handlers ----------------
66
+
67
+ def do_create(prompt, style, aspect, n, seed):
68
+ if not (prompt or "").strip():
69
+ raise gr.Error("Describe what you want to create.")
70
  _guard(prompt)
71
+ _engine_check("image")
72
+ try:
73
+ paths, s = gen.text_to_image(prompt, style, aspect, int(n), seed)
74
+ except gr.Error:
75
+ raise
76
+ except Exception as e:
77
+ raise gr.Error(f"Generation failed: {str(e)[:300]}")
78
+ stats.hit("images", len(paths))
79
+ return paths, f"✅ {len(paths)} image(s) · seed {s} · FLUX.1 [schnell] on ZeroGPU", paths, paths[0]
80
 
81
 
82
+ def pick_from_gallery(evt: gr.SelectData, paths):
83
+ try:
84
+ v = evt.value
85
+ if isinstance(v, dict):
86
+ v = (v.get("image") or {}).get("path") or v.get("path")
87
+ return v or (paths[evt.index] if paths else None)
88
+ except Exception:
89
+ return None
90
 
91
 
92
+ def do_edit(img, prompt, style, strength, seed):
93
  if not img:
94
+ raise gr.Error("Upload an image to edit.")
95
+ if not (prompt or "").strip():
96
+ raise gr.Error("Describe the new look.")
97
  _guard(prompt)
98
+ _engine_check("image")
99
+ try:
100
+ path, s = gen.image_to_image(img, prompt, style, strength, seed)
101
+ except gr.Error:
102
+ raise
103
+ except Exception as e:
104
+ raise gr.Error(f"Edit failed: {str(e)[:300]}")
105
+ stats.hit("edits")
106
+ return path, f"✅ Restyled · strength {strength} · seed {s}"
107
 
108
 
109
+ def do_video(prompt, image, mode, seconds, aspect, quality, seed):
110
+ if not (prompt or "").strip():
111
+ raise gr.Error("Describe the scene and motion.")
112
+ if mode == "Image → Video" and not image:
113
+ raise gr.Error("Upload a start image (or switch to Text → Video).")
114
+ _guard(prompt)
115
+ _engine_check("video")
116
+ steps = {"⚡ Fast": 20, "✨ Balanced": 30, "👑 Max": 40}.get(quality, 30)
117
+ try:
118
+ path, s = gen.make_video(prompt, image, mode, float(seconds), aspect, steps, seed)
119
+ except gr.Error:
120
+ raise
121
+ except Exception as e:
122
+ raise gr.Error(f"Video failed: {str(e)[:300]}")
123
+ stats.hit("videos")
124
+ return path, f"✅ {mode} · {seconds}s · {steps} steps · seed {s} · LTX-Video on ZeroGPU"
125
 
126
 
127
+ # ---------------- CPU handlers ----------------
128
+
129
+ def do_remix(track, effects, start, end, fin, fout, loop_min, beat, beat_vol, fmt):
130
+ try:
131
+ out = audio_tools.remix(track, effects, start, end, fin, fout, loop_min, beat, beat_vol, fmt)
132
+ except Exception as e:
133
+ raise gr.Error(str(e)[:400])
134
+ stats.hit("audio")
135
+ return out, out, f"✅ Remix ready · {audio_tools.duration(out):.1f}s"
136
+
137
+
138
+ def do_music_video(image, clip, audio, size, motion, wave, minutes):
139
+ src = clip or image
140
+ try:
141
+ out = audio_tools.music_video(src, audio, size, motion, wave, minutes)
142
+ except Exception as e:
143
+ raise gr.Error(str(e)[:400])
144
+ stats.hit("loops")
145
+ return out, f"✅ Music video ready · {audio_tools.duration(out):.0f}s"
146
 
147
 
148
  def do_ffmpeg_loop(video, style, xfade, minutes, audio, aspect):
 
152
  out = loop_tools.make_loop(video, style, xfade, float(minutes or 0) * 60, audio, aspect)
153
  except Exception as e:
154
  raise gr.Error(str(e)[:400])
155
+ stats.hit("loops")
156
+ return out, "✅ Loop ready."
 
 
 
 
 
157
 
158
 
159
  def do_cover(img, mode):
 
161
  raise gr.Error("Upload a cover image first.")
162
  report = cover_tools.check_cover(img)
163
  files = cover_tools.export_sizes(img, "crop" if mode.startswith("Crop") else "pad")
164
+ stats.hit("covers")
165
  return report, files, files[0]
166
 
167
 
168
+ def _remote(fn, *args, request=None):
169
+ try:
170
+ path, used = fn(*args, request=request)
171
+ except remote.ToolError as e:
172
+ raise gr.Error(str(e))
173
+ if not path:
174
+ raise gr.Error("The remote tool finished but returned no file.")
175
+ stats.hit("edits")
176
+ return path, f"✅ Done with {used}."
177
+
178
+
179
+ def do_outpaint(img, target, prompt, align, request: gr.Request):
180
+ if not img:
181
+ raise gr.Error("Upload an image first.")
182
+ _guard(prompt)
183
+ w, h = {"Vertical 9:16": (720, 1280), "Wide 16:9": (1280, 720), "Square": (1024, 1024)}[target]
184
+ return _remote(remote.outpaint, img, w, h, prompt, align, request=request)
185
+
186
+
187
+ def do_upscale(img, factor, request: gr.Request):
188
+ if not img:
189
+ raise gr.Error("Upload an image first.")
190
+ return _remote(remote.upscale, img, factor, request=request)
191
+
192
+
193
  def filter_prompts(section, query):
194
  q = (query or "").lower().strip()
195
  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())]
 
208
  history = history or []
209
  if not (msg or "").strip():
210
  return "", history
211
+ return "", history + [{"role": "user", "content": msg}, {"role": "assistant", "content": ps.coach_reply(msg)}]
212
+
213
+
214
+ def counted(fn, key="prompts"):
215
+ def w(*a):
216
+ stats.hit(key)
217
+ return fn(*a)
218
+ return w
219
+
220
+
221
+ def engine_md():
222
+ icon = {"ready": "🟢 ready", "error": "🔴 error", "off": "⚪ off (preview)"}
223
+ lines = [f"- **Image engine** (FLUX.1 [schnell]): {icon.get(gen.STATUS['image'], gen.STATUS['image'])}",
224
+ f"- **Video engine** (LTX-Video 0.9.5): {icon.get(gen.STATUS['video'], gen.STATUS['video'])}",
225
+ f"- **Stats store:** {stats.MODE}"]
226
+ for k, v in gen.ERRORS.items():
227
+ lines.append(f"- `{k}` error: {v[:200]}")
228
+ return "\n".join(lines)
229
+
230
+
231
+ def H(title, sub=""):
232
+ return gr.HTML(f'<div class="aik-h"><h2>{title}</h2><span>{sub}</span></div>')
233
+
234
 
235
+ STYLE_CHOICES = list(gen.STYLES)
236
+ EXAMPLES = [
237
+ "KING OF MUSIC on a golden throne in a futuristic concert arena, crowd lights, crown glowing",
238
+ "Luxury black and gold sneaker floating in zero gravity above a neon city, product shot",
239
+ "Cozy lofi studio at midnight, rain on the window, vinyl spinning, city skyline",
240
+ "Movie poster: a hero in a navy suit and grey fedora walking out of a glowing portal",
241
+ "Futuristic chrome supercar parked in front of a castle at sunset",
242
+ ]
243
 
244
  # ---------------- UI ----------------
245
 
246
  with gr.Blocks(title="AI KING©️ Studio") as demo:
247
+ hero_box = gr.HTML(hero())
248
+ last_img = gr.State(None)
249
+
250
+ with gr.Tabs() as tabs:
251
+ # ---- CREATE ----
252
+ with gr.Tab("✨ Create", id="create"):
253
+ with gr.Row(equal_height=False):
254
+ with gr.Column(scale=5, elem_classes="aik-card"):
255
+ H("Create", "text → image · FLUX.1 [schnell] · ~5–15 s")
256
+ c_prompt = gr.Textbox(show_label=False, lines=3, elem_id="aik-prompt",
257
+ placeholder="Imagine anything… e.g. KING OF MUSIC on a golden throne in a futuristic arena")
258
+ c_style = gr.Radio(STYLE_CHOICES, value="🎬 ARRI ALEXA 35", label="Style", elem_classes="aik-chips")
259
+ c_aspect = gr.Radio(list(gen.ASPECTS), value="9:16 Story", label="Frame", elem_classes="aik-chips")
260
  with gr.Row():
261
+ c_n = gr.Slider(1, 4, value=2, step=1, label="Images")
262
+ c_seed = gr.Number(value=-1, label="Seed (-1 = surprise me)", precision=0)
263
+ c_btn = gr.Button("✨ Generate", variant="primary", size="lg")
264
+ gr.Examples(EXAMPLES, c_prompt, label="Try one")
265
+ with gr.Column(scale=6, elem_classes="aik-card"):
266
+ c_gallery = gr.Gallery(label="Results", columns=2, height=560, object_fit="contain", preview=False, buttons=["download", "fullscreen"])
267
+ c_msg = gr.Markdown(elem_classes="aik-note")
268
  with gr.Row():
269
+ c_to_edit = gr.Button("🎨 Edit this", size="sm")
270
+ c_to_video = gr.Button("🎬 Animate this", size="sm")
271
+ c_paths = gr.State([])
272
+
273
+ # ---- EDIT ----
274
+ with gr.Tab("🎨 Edit", id="edit"):
275
+ with gr.Row(equal_height=False):
276
+ with gr.Column(scale=5, elem_classes="aik-card"):
277
+ H("Edit & Restyle", "image → image · keep the layout, change the look")
278
+ e_img = gr.Image(type="filepath", label="Your photo", height=360)
279
+ 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")
280
+ e_style = gr.Radio(STYLE_CHOICES, value="None", label="Style", elem_classes="aik-chips")
281
+ e_strength = gr.Slider(0.2, 0.95, value=0.6, step=0.05, label="Change amount (low = subtle, high = reimagine)")
282
+ e_seed = gr.Number(value=-1, label="Seed", precision=0)
283
+ e_btn = gr.Button("🎨 Restyle", variant="primary", size="lg")
284
+ gr.HTML(f'<div class="aik-note">⚠️ {CONSENT_NOTE}</div>')
285
+ with gr.Column(scale=6, elem_classes="aik-card"):
286
+ e_out = gr.Image(type="filepath", label="Result", height=560, buttons=["download", "fullscreen"])
287
+ e_msg = gr.Markdown(elem_classes="aik-note")
288
+ e_to_video = gr.Button("🎬 Animate this", size="sm")
289
+
290
+ # ---- VIDEO ----
291
+ with gr.Tab("🎬 Video", id="video"):
292
+ with gr.Row(equal_height=False):
293
+ with gr.Column(scale=5, elem_classes="aik-card"):
294
+ H("Video", "text/image → video · seamless loops · LTX-Video")
295
+ v_mode = gr.Radio(["Text → Video", "Image → Video", "Seamless Loop"], value="Text → Video", label="Mode", elem_classes="aik-chips")
296
+ v_img = gr.Image(type="filepath", label="Start image (optional for Text → Video & Loop)", height=260)
297
+ v_prompt = gr.Textbox(label="Scene + motion", lines=3, elem_id="aik-prompt",
298
+ 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")
299
+ v_aspect = gr.Radio(list(gen.VIDEO_ASPECTS), value="9:16 Story", label="Frame", elem_classes="aik-chips")
300
  with gr.Row():
301
+ v_sec = gr.Slider(1, 5, value=4, step=1, label="Seconds")
302
+ v_quality = gr.Radio(["⚡ Fast", "✨ Balanced", "👑 Max"], value="✨ Balanced", label="Quality")
303
+ v_seed = gr.Number(value=-1, label="Seed", precision=0)
304
+ v_btn = gr.Button("🎬 Make video", variant="primary", size="lg")
305
+ gr.HTML('<div class="aik-note">Text → Video first paints a cinematic keyframe with FLUX, then animates it. '
306
+ 'Seamless Loop makes the last frame match the first: perfect for 24/7 lofi streams (repeat it in Loops & Export).</div>')
307
+ with gr.Column(scale=6, elem_classes="aik-card"):
308
+ v_out = gr.Video(label="Video", height=560, autoplay=True, loop=True)
309
+ v_msg = gr.Markdown(elem_classes="aik-note")
310
+
311
+ # ---- AUDIO ----
312
+ with gr.Tab("🎧 Audio Lab", id="audio"):
313
+ with gr.Tabs():
314
+ with gr.Tab("🎛️ Remix"):
315
+ with gr.Row(equal_height=False):
316
+ with gr.Column(scale=5, elem_classes="aik-card"):
317
+ H("Remix", "trim · effects · loop · mix a beat")
318
+ a_track = gr.Audio(type="filepath", label="Song or sound")
319
+ a_fx = gr.CheckboxGroup(audio_tools.EFFECTS, value=["🌙 Lofi warmth"], label="Effects", elem_classes="aik-chips")
320
+ with gr.Row():
321
+ a_start = gr.Number(value=0, label="Start (s)")
322
+ a_end = gr.Number(value=0, label="End (s, 0 = full)")
323
+ with gr.Row():
324
+ a_fin = gr.Slider(0, 10, value=1, step=0.5, label="Fade in (s)")
325
+ a_fout = gr.Slider(0, 15, value=3, step=0.5, label="Fade out (s)")
326
+ a_loop = gr.Slider(0, 15, value=0, step=1, label="Loop to length (minutes, 0 = off)")
327
+ with gr.Accordion("Mix a second track (beat / ambience)", open=False):
328
+ a_beat = gr.Audio(type="filepath", label="Beat or ambience")
329
+ a_bvol = gr.Slider(0.05, 1.5, value=0.6, step=0.05, label="Beat volume")
330
+ a_fmt = gr.Radio(["mp3", "wav"], value="mp3", label="Export")
331
+ a_btn = gr.Button("🎛️ Remix", variant="primary", size="lg")
332
+ with gr.Column(scale=6, elem_classes="aik-card"):
333
+ a_out = gr.Audio(type="filepath", label="Remix", buttons=["download"])
334
+ a_file = gr.File(label="Download")
335
+ a_msg = gr.Markdown(elem_classes="aik-note")
336
+ with gr.Tab("📼 Music Video Maker"):
337
+ with gr.Row(equal_height=False):
338
+ with gr.Column(scale=5, elem_classes="aik-card"):
339
+ H("Music Video Maker", "cover or clip + song → MP4 with gold waveform")
340
+ mv_img = gr.Image(type="filepath", label="Cover art", height=240)
341
+ mv_clip = gr.Video(label="…or a looping clip (optional, overrides the image)")
342
+ mv_audio = gr.Audio(type="filepath", label="Song")
343
+ mv_size = gr.Radio(list(audio_tools.VIDEO_SIZES), value="9:16 TikTok/Shorts (720x1280)", label="Format", elem_classes="aik-chips")
344
+ with gr.Row():
345
+ mv_motion = gr.Radio(["Slow zoom", "Still"], value="Slow zoom", label="Image motion")
346
+ mv_wave = gr.Checkbox(value=True, label="Gold waveform")
347
+ mv_min = gr.Slider(0.25, 10, value=1, step=0.25, label="Max length (minutes)")
348
+ mv_btn = gr.Button("📼 Render music video", variant="primary", size="lg")
349
+ with gr.Column(scale=6, elem_classes="aik-card"):
350
+ mv_out = gr.Video(label="Music video", height=560)
351
+ mv_msg = gr.Markdown(elem_classes="aik-note")
352
+ with gr.Tab("🎼 Text → Music (soon)"):
353
+ gr.HTML('<div class="aik-soon"><h3>🎼 Text → Music & AI vocals: coming soon</h3>'
354
+ '<p>We only ship open models whose licenses allow commercial use of the music you make. '
355
+ 'Until then: remix your own songs above, or bring stems from your DAW.</p></div>')
356
+
357
+ # ---- LOOPS & EXPORT ----
358
+ with gr.Tab("🔁 Loops & Export", id="loops"):
359
+ with gr.Row(equal_height=False):
360
+ with gr.Column(scale=5, elem_classes="aik-card"):
361
+ H("Loop & Export", "ping-pong / crossfade · repeat to 1 h · add your song")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  ff_vid = gr.Video(label="Clip")
363
+ ff_style = gr.Radio(["ping-pong", "crossfade"], value="ping-pong", label="Loop style", elem_classes="aik-chips")
364
  ff_x = gr.Slider(0.2, 2.0, value=0.75, step=0.05, label="Crossfade seconds")
365
  ff_min = gr.Number(value=0, label="Repeat to length (minutes, 0 = one loop, 60 = 1 hour)")
366
  ff_audio = gr.Audio(type="filepath", label="Song (optional)")
367
+ ff_aspect = gr.Radio(list(loop_tools.ASPECTS), value="keep", label="Export frame", elem_classes="aik-chips")
368
+ ff_btn = gr.Button("🔁 Make loop", variant="primary", size="lg")
369
+ with gr.Column(scale=6, elem_classes="aik-card"):
370
+ ff_out = gr.Video(label="Loop", height=560)
371
+ ff_msg = gr.Markdown(elem_classes="aik-note")
372
+
373
+ # ---- PROMPT STUDIO ----
374
+ with gr.Tab("👑 Prompt Studio", id="studio"):
375
+ with gr.Column(elem_classes="aik-card"):
376
+ H("Prompt Studio", "the KING OF MUSIC prompt builder · copy into any generator")
377
+ with gr.Tabs():
378
+ with gr.Tab("Text → Image"):
379
+ with gr.Row():
380
+ with gr.Column():
381
+ ti_idea = gr.Textbox(label="Core idea", lines=4, placeholder="A futuristic music producer at a midnight control desk, gold crown on the console")
382
+ ti_fast = gr.Radio(list(ps.FAST_STARTS), label="Fast starts", elem_classes="aik-chips")
383
+ with gr.Row():
384
+ ti_ratio = gr.Dropdown(ps.TI_RATIOS, value=ps.TI_RATIOS[0], label="Frame")
385
+ ti_shot = gr.Dropdown(ps.TI_SHOTS, value=ps.TI_SHOTS[0], label="Camera")
386
+ with gr.Row():
387
+ ti_light = gr.Dropdown(ps.TI_LIGHTS, value=ps.TI_LIGHTS[0], label="Lighting")
388
+ ti_finish = gr.Dropdown(ps.TI_FINISHES, value=ps.TI_FINISHES[0], label="Finish")
389
+ ti_detail = gr.Slider(1, 5, value=4, step=1, label="Detail level")
390
+ ti_notes = gr.Textbox(label="Must include / avoid (optional)")
391
+ ti_lock = gr.Checkbox(label="Add CHAD likeness lock + logo lock", value=False)
392
+ ti_btn = gr.Button("Build prompt", variant="primary")
393
+ with gr.Column():
394
+ ti_out = gr.Textbox(label="IMAGE_PROMPT.TXT", lines=16, buttons=["copy"])
395
+ ti_send = gr.Button("✨ Send to Create")
396
+ ti_fast.change(lambda k: ps.FAST_STARTS.get(k, ""), ti_fast, ti_idea)
397
+ 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)
398
+ with gr.Tab("Image → Image"):
399
+ with gr.Row():
400
+ with gr.Column():
401
+ ii_edit = gr.Textbox(label="What should change?", lines=4)
402
+ ii_lock = gr.Textbox(label="Preserve", value="identity, facial structure, pose, body proportions, key wardrobe details")
403
+ ii_strength = gr.Slider(1, 5, value=3, step=1, label="Transformation strength")
404
+ with gr.Row():
405
+ ii_finish = gr.Dropdown(ps.II_FINISHES, value=ps.II_FINISHES[0], label="Finish")
406
+ ii_ratio = gr.Dropdown(ps.II_RATIOS, value=ps.II_RATIOS[0], label="Output frame")
407
+ ii_logo = gr.Checkbox(label="Add logo lock (keep my emblems exactly)", value=True)
408
+ ii_btn = gr.Button("Build edit prompt", variant="primary")
409
+ ii_out = gr.Textbox(label="EDIT_DIRECTIVE.TXT", lines=16, buttons=["copy"])
410
+ ii_btn.click(counted(lambda e, l, s, f, r, lk: ps.build_ii(e, l, s, f, r, True, lk)),
411
+ [ii_edit, ii_lock, ii_strength, ii_finish, ii_ratio, ii_logo], ii_out)
412
+ with gr.Tab("Image → Video"):
413
+ with gr.Row():
414
+ with gr.Column():
415
+ iv_action = gr.Textbox(label="Motion direction", lines=3, value="Make this image come alive with cinematic motion and smooth animation.")
416
+ with gr.Row():
417
+ iv_cam = gr.Dropdown(ps.IV_CAMERAS, value=ps.IV_CAMERAS[0], label="Camera move")
418
+ iv_dur = gr.Dropdown(ps.IV_DURATIONS, value="10", label="Duration (s)")
419
+ iv_cont = gr.Textbox(label="Continuity lock", value="preserve face, anatomy, wardrobe, environment geometry, and lighting direction")
420
+ iv_beats = gr.Textbox(label="Motion beats (optional)")
421
+ iv_loop = gr.Checkbox(label="Seamless loop (first frame = last frame)")
422
+ iv_btn = gr.Button("Build video prompt", variant="primary")
423
+ iv_out = gr.Textbox(label="MOTION_PLAN.TXT", lines=16, buttons=["copy"])
424
+ iv_btn.click(counted(lambda a, c, d, co, b, lp: ps.build_iv(a, c, d, co, b, True, lp)),
425
+ [iv_action, iv_cam, iv_dur, iv_cont, iv_beats, iv_loop], iv_out)
426
+ with gr.Tab("Prompt Library"):
427
+ gr.Markdown(f"{len(PROMPTS)} ready prompts from the KING OF MUSIC prompt pack.")
428
+ with gr.Row():
429
+ lib_sec = gr.Dropdown(SECTIONS, value="All", label="Section")
430
+ lib_q = gr.Textbox(label="Search", placeholder="cover, loop, sneaker…")
431
+ lib_cards = gr.State(PROMPTS)
432
+ lib_pick = gr.Dropdown([], label="Prompt")
433
+ lib_text = gr.Textbox(label="Prompt text", lines=8, buttons=["copy"])
434
+ lib_sec.change(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])
435
+ lib_q.change(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])
436
+ lib_pick.change(pick_prompt, [lib_pick, lib_cards], lib_text)
437
+ with gr.Tab("Coach & Enhancer"):
438
+ 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")
439
+ with gr.Row():
440
+ coach_in = gr.Textbox(placeholder="How do I make this feel like a premium music video?", scale=5, show_label=False)
441
+ coach_btn = gr.Button("Ask", variant="primary", scale=1)
442
+ coach_btn.click(coach_chat, [coach_in, coach], [coach_in, coach])
443
+ coach_in.submit(coach_chat, [coach_in, coach], [coach_in, coach])
444
+ with gr.Row():
445
+ with gr.Column():
446
+ en_in = gr.Textbox(label="Draft prompt", lines=5)
447
+ en_goal = gr.Dropdown(list(ps.EN_GOALS), value="Cinematic impact", label="Primary goal")
448
+ en_emph = gr.CheckboxGroup(ps.EN_EMPHASIS, value=["composition", "lighting", "quality"], label="Emphasis")
449
+ en_btn = gr.Button("Enhance prompt", variant="primary")
450
+ en_out = gr.Textbox(label="Enhanced result", lines=12, buttons=["copy"])
451
+ en_btn.click(counted(ps.enhance), [en_in, en_goal, en_emph], en_out)
452
+
453
+ # ---- RELEASE KIT ----
454
+ with gr.Tab("💿 Release Kit", id="release"):
455
+ with gr.Row(equal_height=False):
456
+ with gr.Column(elem_classes="aik-card"):
457
+ H("Cover Checker", "DistroKid-ready 3000×3000 + 9:16 + 16:9")
458
+ cv_img = gr.Image(type="filepath", label="Cover art", height=280)
459
+ cv_mode = gr.Radio(["Crop to fill", "Pad with blurred background (no crop)"], value="Crop to fill", label="Other sizes")
460
+ cv_btn = gr.Button("💿 Check + export", variant="primary")
461
+ cv_report = gr.Textbox(label="Report", lines=7)
462
+ cv_preview = gr.Image(type="filepath", label="3000×3000 preview", height=280)
463
+ cv_files = gr.File(label="Downloads", file_count="multiple")
464
+ with gr.Column(elem_classes="aik-card"):
465
+ H("Captions & CTA", "TikTok · IG · Shorts · X · FB · Pinterest")
466
+ cp_plat = gr.Radio(captions.PLATFORMS, value="TikTok", label="Platform", elem_classes="aik-chips")
467
+ cp_song = gr.Textbox(label="Song title", value="KUNG FU COFFEE")
468
+ cp_hook = gr.Textbox(label="Hook line", placeholder="Brewed different. ☕👑")
469
+ cp_tags = gr.Textbox(label="Extra hashtags", placeholder="#kungfucoffee #lofibeats")
470
+ cp_link = gr.Textbox(label="Store / DistroKid link (optional)")
471
+ cp_biz = gr.Textbox(label="Business line (optional)")
472
+ cp_btn = gr.Button("🛍️ Build caption", variant="primary")
473
+ cp_out = gr.Textbox(label="Caption", lines=10, buttons=["copy"])
474
+ cp_note = gr.Markdown(elem_classes="aik-note")
475
+
476
+ # ---- LABS ----
477
+ with gr.Tab("🧪 Labs", id="labs"):
478
+ gr.HTML('<div class="aik-note" style="margin:4px 4px 10px">Labs tools run on public open-source Hugging Face Spaces and use '
479
+ '<b>your own</b> free daily GPU minutes. If one is busy, try again later.</div>')
480
+ with gr.Row(equal_height=False):
481
+ with gr.Column(elem_classes="aik-card"):
482
+ H("Expand", "outpaint to 9:16 / 16:9 / square")
483
+ op_img = gr.Image(type="filepath", label="Image", height=260)
484
+ op_target = gr.Radio(["Vertical 9:16", "Wide 16:9", "Square"], value="Vertical 9:16", label="Target", elem_classes="aik-chips")
485
+ op_align = gr.Dropdown(["Middle", "Left", "Right", "Top", "Bottom"], value="Middle", label="Keep original at")
486
+ op_prompt = gr.Textbox(label="Describe the surroundings (optional)")
487
+ op_btn = gr.Button("🖼️ Expand", variant="primary")
488
+ op_out = gr.Image(type="filepath", label="Expanded", height=320)
489
+ op_msg = gr.Markdown(elem_classes="aik-note")
490
+ with gr.Column(elem_classes="aik-card"):
491
+ H("Upscale", "2–4× for posters & merch")
492
+ up_img = gr.Image(type="filepath", label="Image", height=260)
493
+ up_f = gr.Radio([2, 3, 4], value=2, label="Factor", elem_classes="aik-chips")
494
+ up_btn = gr.Button("🔍 Upscale", variant="primary")
495
+ up_out = gr.Image(type="filepath", label="Upscaled", height=320)
496
+ up_msg = gr.Markdown(elem_classes="aik-note")
497
+ with gr.Column(elem_classes="aik-card"):
498
+ gr.HTML('<div class="aik-soon"><h3>🎭 Face Swap: coming soon</h3>'
499
+ '<p>Face tools will only work with <b>your own face</b> or faces you have <b>written permission</b> to use, '
500
+ 'with a consent check before every run. No explicit content, no minors, no impersonation.</p></div>')
501
+ gr.HTML('<div class="aik-soon" style="margin-top:12px"><h3>✂️ Timeline editor & captions: coming soon</h3>'
502
+ '<p>Multi-clip timeline, auto-captions and beat-synced cuts are next on the roadmap.</p></div>')
503
+
504
+ # ---- ABOUT ----
505
+ with gr.Tab("ℹ️ About", id="about"):
506
+ with gr.Column(elem_classes="aik-card"):
507
+ H("About AI KING©️", "free · open models · no account needed")
508
+ eng = gr.Markdown(engine_md())
509
+ gr.Markdown(
510
+ "**Install like an app:** on iPhone open this page in Safari → Share → **Add to Home Screen**. "
511
+ "On Android/Chrome tap ⋮ → **Install app**.\n\n"
512
+ "**Models & licenses:** FLUX.1 [schnell] (Apache-2.0) for images; LTX-Video 0.9.5 "
513
+ "(LTXV Open Weights License, free for creators/companies under $10M revenue) for video; ffmpeg for audio and loops. "
514
+ "Labs: diffusers-image-outpaint and finegrain-image-enhancer (community Spaces).\n\n"
515
+ "**Free GPU:** each visitor gets a daily ZeroGPU allowance from Hugging Face (more when logged in to Hugging Face).\n\n"
516
+ "**Content rules:** non-explicit creative use only; prompts are screened. "
517
+ "[Privacy](/privacy) · [Terms](/terms)\n\n"
518
+ "Made by **Chad Syphrett · KING OF MUSIC©️**.")
519
+ gr.Button("↻ Refresh engine status", size="sm").click(engine_md, None, eng)
520
+
521
+ gr.HTML(brand.FOOTER)
522
+
523
+ # ---------- wiring ----------
524
+ 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)
525
+ 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)
526
+ c_gallery.select(pick_from_gallery, c_paths, last_img)
527
+ c_to_edit.click(lambda p: (p, gr.Tabs(selected="edit")), last_img, [e_img, tabs])
528
+ c_to_video.click(lambda p: (p, "Image → Video", gr.Tabs(selected="video")), last_img, [v_img, v_mode, tabs])
529
+ e_btn.click(do_edit, [e_img, e_prompt, e_style, e_strength, e_seed], [e_out, e_msg]).then(hero, None, hero_box)
530
+ e_to_video.click(lambda p: (p, "Image → Video", gr.Tabs(selected="video")), e_out, [v_img, v_mode, tabs])
531
+ 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)
532
+ 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)
533
+ 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)
534
+ 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)
535
+ ti_send.click(lambda t: (t, gr.Tabs(selected="create")), ti_out, [c_prompt, tabs])
536
+ cv_btn.click(do_cover, [cv_img, cv_mode], [cv_report, cv_files, cv_preview])
537
+ cp_btn.click(counted(captions.build_caption), [cp_plat, cp_song, cp_hook, cp_tags, cp_link, cp_biz], [cp_out, cp_note])
538
+ op_btn.click(do_outpaint, [op_img, op_target, op_prompt, op_align], [op_out, op_msg])
539
+ up_btn.click(do_upscale, [up_img, up_f], [up_out, up_msg])
540
+ demo.load(on_load, None, [hero_box, tabs])
541
  demo.load(filter_prompts, [lib_sec, lib_q], [lib_pick, lib_cards, lib_text])
542
 
543
 
544
+ # ---------- PWA + pages (served before Gradio's own routes) ----------
545
+
546
+ def _install_routes(app):
547
+ from fastapi.responses import FileResponse, HTMLResponse, Response
548
+ from starlette.routing import Route
549
+ st = HERE / "static"
550
+
551
+ async def manifest(request):
552
+ return Response((st / "manifest.json").read_text(), media_type="application/manifest+json")
553
+
554
+ async def sw(request):
555
+ return Response((st / "sw.js").read_text(), media_type="application/javascript",
556
+ headers={"Service-Worker-Allowed": "/", "Cache-Control": "no-cache"})
557
+
558
+ def page(name):
559
+ async def h(request):
560
+ return HTMLResponse((st / name).read_text())
561
+ return h
562
+
563
+ async def apple_icon(request):
564
+ return FileResponse(st / "icons" / "apple-touch-icon.png", media_type="image/png")
565
+
566
+ new = [Route("/manifest.json", manifest), Route("/manifest.webmanifest", manifest), Route("/sw.js", sw),
567
+ Route("/privacy", page("privacy.html")), Route("/terms", page("terms.html")), Route("/offline", page("offline.html")),
568
+ Route("/apple-touch-icon.png", apple_icon), Route("/apple-touch-icon-precomposed.png", apple_icon)]
569
+ app.router.routes[0:0] = new
570
+
571
+
572
  if __name__ == "__main__":
573
+ demo.queue(default_concurrency_limit=2, max_size=64)
574
+ demo.launch(
575
+ theme=brand.THEME, css=brand.CSS, js=brand.JS, head=brand.HEAD,
576
+ favicon_path=str(HERE / "static" / "icons" / "favicon-64.png"),
577
  server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"),
578
  server_port=int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", 7860))),
579
+ ssr_mode=False, pwa=True, prevent_thread_lock=True, show_error=True,
580
  )
581
+ _install_routes(demo.server_app if getattr(demo, "server_app", None) else demo.app)
582
+ demo.block_thread()
audio_tools.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AI KING©️ Audio Lab + Music Video Maker (CPU, ffmpeg). No models, no GPU."""
2
+ from __future__ import annotations
3
+
4
+ import os, shutil, subprocess, tempfile, time
5
+
6
+ OUT = os.path.join(tempfile.gettempdir(), "aiking_audio")
7
+ os.makedirs(OUT, exist_ok=True)
8
+ MAX_SECONDS = 900 # 15 min cap keeps the free CPU responsive
9
+
10
+ EFFECTS = ["🌙 Lofi warmth", "🔊 Bass boost", "⚡ Sped up (nightcore)", "🐢 Slowed + reverb", "🏟️ Stadium echo", "🎧 8D rotate", "📏 Loudness normalize (streaming -14 LUFS)"]
11
+
12
+
13
+ def _ff(args, timeout=900):
14
+ if not shutil.which("ffmpeg"):
15
+ raise RuntimeError("ffmpeg is not installed on this Space.")
16
+ p = subprocess.run(["ffmpeg", "-hide_banner", "-y", *args], capture_output=True, text=True, timeout=timeout)
17
+ if p.returncode != 0:
18
+ raise RuntimeError("ffmpeg: " + p.stderr[-500:])
19
+
20
+
21
+ def duration(path) -> float:
22
+ out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", path],
23
+ capture_output=True, text=True).stdout.strip()
24
+ try:
25
+ return float(out)
26
+ except Exception:
27
+ return 0.0
28
+
29
+
30
+ def remix(track, effects=None, start=0.0, end=0.0, fade_in=0.0, fade_out=0.0, loop_minutes=0.0,
31
+ beat=None, beat_vol=0.6, fmt="mp3"):
32
+ if not track:
33
+ raise RuntimeError("Upload a song or sound first.")
34
+ effects = effects or []
35
+ total = duration(track)
36
+ start = max(0.0, float(start or 0))
37
+ end = float(end or 0)
38
+ if end <= 0 or end > total:
39
+ end = total
40
+ if end - start <= 0.2:
41
+ raise RuntimeError("Trim range is empty.")
42
+ seg = end - start
43
+ chain = []
44
+ if "⚡ Sped up (nightcore)" in effects:
45
+ chain += ["asetrate=44100*1.25", "aresample=44100"]
46
+ if "🐢 Slowed + reverb" in effects:
47
+ chain += ["asetrate=44100*0.85", "aresample=44100", "aecho=0.8:0.88:60|120:0.35|0.25"]
48
+ if "🌙 Lofi warmth" in effects:
49
+ chain += ["lowpass=f=3800", "highpass=f=60", "acompressor=threshold=0.2:ratio=3", "volume=1.1"]
50
+ if "🔊 Bass boost" in effects:
51
+ chain += ["bass=g=9:f=90", "alimiter=limit=0.95"]
52
+ if "🏟️ Stadium echo" in effects:
53
+ chain += ["aecho=0.8:0.7:180|360:0.3|0.18"]
54
+ if "🎧 8D rotate" in effects:
55
+ chain += ["apulsator=hz=0.09"]
56
+ seg_len = seg / (1.25 if "⚡ Sped up (nightcore)" in effects else 0.85 if "🐢 Slowed + reverb" in effects else 1)
57
+ loops = 1
58
+ lm = float(loop_minutes or 0)
59
+ if lm > 0:
60
+ target = min(lm * 60, MAX_SECONDS)
61
+ loops = max(1, int(target // max(seg_len, 1)) + 1)
62
+ out_len = min(target, seg_len * loops)
63
+ else:
64
+ out_len = min(seg_len, MAX_SECONDS)
65
+ fi, fo = float(fade_in or 0), float(fade_out or 0)
66
+ post = []
67
+ if loops > 1:
68
+ post.append(f"aloop=loop={loops - 1}:size=2e9")
69
+ post.append(f"atrim=0:{out_len:.3f}")
70
+ if fi > 0:
71
+ post.append(f"afade=t=in:d={fi}")
72
+ if fo > 0:
73
+ post.append(f"afade=t=out:st={max(0, out_len - fo):.3f}:d={fo}")
74
+ if "📏 Loudness normalize (streaming -14 LUFS)" in effects:
75
+ post.append("loudnorm=I=-14:TP=-1.5:LRA=11")
76
+ base = ",".join(["aformat=sample_rates=44100:channel_layouts=stereo", *chain, *post])
77
+ out = os.path.join(OUT, f"aiking-remix-{int(time.time()*1000)}.{fmt}")
78
+ codec = ["-c:a", "libmp3lame", "-b:a", "256k"] if fmt == "mp3" else ["-c:a", "pcm_s16le"]
79
+ if beat:
80
+ fc = (f"[0:a]{base}[a0];[1:a]aformat=sample_rates=44100:channel_layouts=stereo,aloop=loop=-1:size=2e9,"
81
+ f"atrim=0:{out_len:.3f},volume={float(beat_vol):.2f}[a1];[a0][a1]amix=inputs=2:duration=first:normalize=0,alimiter=limit=0.95[out]")
82
+ _ff(["-ss", f"{start}", "-t", f"{seg:.3f}", "-i", track, "-i", beat, "-filter_complex", fc, "-map", "[out]", *codec, out])
83
+ else:
84
+ _ff(["-ss", f"{start}", "-t", f"{seg:.3f}", "-i", track, "-af", base, *codec, out])
85
+ return out
86
+
87
+
88
+ VIDEO_SIZES = {"9:16 TikTok/Shorts (720x1280)": (720, 1280), "16:9 YouTube (1280x720)": (1280, 720), "1:1 Instagram (1080x1080)": (1080, 1080)}
89
+
90
+
91
+ def music_video(image, audio, size_key, motion="Slow zoom", waveform=True, max_minutes=10.0):
92
+ """Still image (or short clip) + song -> MP4 with optional slow zoom and gold waveform."""
93
+ if not image or not audio:
94
+ raise RuntimeError("Add a cover image (or clip) and a song.")
95
+ w, h = VIDEO_SIZES.get(size_key, (720, 1280))
96
+ dur = min(duration(audio) or 30, float(max_minutes or 10) * 60, MAX_SECONDS)
97
+ fps = 24
98
+ is_video = str(image).lower().endswith((".mp4", ".mov", ".webm", ".m4v"))
99
+ out = os.path.join(OUT, f"aiking-musicvideo-{int(time.time()*1000)}.mp4")
100
+ if is_video:
101
+ vin = ["-stream_loop", "-1", "-i", image]
102
+ bg = f"[0:v]scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},fps={fps},setsar=1[bg]"
103
+ else:
104
+ vin = ["-loop", "1", "-framerate", str(fps), "-i", image]
105
+ if motion == "Slow zoom":
106
+ frames = int(dur * fps) + fps
107
+ bg = (f"[0:v]scale={w*2}:{h*2}:force_original_aspect_ratio=increase,crop={w*2}:{h*2},"
108
+ f"zoompan=z='min(1+0.00025*on,1.25)':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d={frames}:s={w}x{h}:fps={fps},setsar=1[bg]")
109
+ else:
110
+ bg = f"[0:v]scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},setsar=1[bg]"
111
+ if waveform:
112
+ wh = max(80, h // 7)
113
+ fc = (f"{bg};[1:a]aformat=channel_layouts=stereo,showwaves=s={w}x{wh}:mode=cline:rate={fps}:colors=0xF5C542|0x9FD8FF,"
114
+ f"format=rgba,colorchannelmixer=aa=0.85[wv];[bg][wv]overlay=0:{h - wh - h // 14}:format=auto,format=yuv420p[v]")
115
+ else:
116
+ fc = f"{bg};[bg]format=yuv420p[v]"
117
+ _ff([*vin, "-i", audio, "-filter_complex", fc, "-map", "[v]", "-map", "1:a", "-t", f"{dur:.2f}",
118
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "22", "-c:a", "aac", "-b:a", "192k",
119
+ "-movflags", "+faststart", "-shortest", out], timeout=1800)
120
+ return out
brand.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AI KING©️ look & feel: theme, CSS, starfield JS, head tags, hero/footer HTML."""
2
+ import os
3
+
4
+ import gradio as gr
5
+
6
+ S = "/gradio_api/file=static" # static files (gr.set_static_paths)
7
+ YT = "https://www.youtube.com/@ChadSyphrett"
8
+ TT = "https://www.tiktok.com/@MusicVideosTM"
9
+ IG = "https://www.instagram.com/InternetThemePark"
10
+ # Replace with the DistroKid HyperFollow link once it exists (Space variable MUSIC_URL).
11
+ MUSIC = os.environ.get("MUSIC_URL", "https://open.spotify.com/search/Chad%20Syphrett")
12
+
13
+ THEME = gr.themes.Base(
14
+ primary_hue=gr.themes.colors.amber,
15
+ secondary_hue=gr.themes.colors.sky,
16
+ neutral_hue=gr.themes.colors.slate,
17
+ radius_size=gr.themes.sizes.radius_lg,
18
+ font=[gr.themes.GoogleFont("Inter"), "-apple-system", "SF Pro Text", "Segoe UI", "Roboto", "sans-serif"],
19
+ font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "Menlo", "monospace"],
20
+ ).set(
21
+ body_background_fill="#03040a", body_background_fill_dark="#03040a",
22
+ body_text_color="#e8ecf6", body_text_color_dark="#e8ecf6",
23
+ body_text_color_subdued="#9aa3b8", body_text_color_subdued_dark="#9aa3b8",
24
+ background_fill_primary="rgba(14,16,28,0.55)", background_fill_primary_dark="rgba(14,16,28,0.55)",
25
+ background_fill_secondary="rgba(255,255,255,0.03)", background_fill_secondary_dark="rgba(255,255,255,0.03)",
26
+ block_background_fill="rgba(14,16,28,0.55)", block_background_fill_dark="rgba(14,16,28,0.55)",
27
+ block_border_color="rgba(255,255,255,0.08)", block_border_color_dark="rgba(255,255,255,0.08)",
28
+ block_label_background_fill="rgba(255,255,255,0.05)", block_label_background_fill_dark="rgba(255,255,255,0.05)",
29
+ block_label_text_color="#c9d2e6", block_label_text_color_dark="#c9d2e6",
30
+ block_title_text_color="#e8ecf6", block_title_text_color_dark="#e8ecf6",
31
+ border_color_primary="rgba(255,255,255,0.10)", border_color_primary_dark="rgba(255,255,255,0.10)",
32
+ input_background_fill="rgba(5,7,14,0.65)", input_background_fill_dark="rgba(5,7,14,0.65)",
33
+ input_border_color="rgba(255,255,255,0.10)", input_border_color_dark="rgba(255,255,255,0.10)",
34
+ input_border_color_focus="rgba(245,197,66,0.65)", input_border_color_focus_dark="rgba(245,197,66,0.65)",
35
+ button_primary_background_fill="linear-gradient(135deg,#fff1b0 0%,#f5c542 38%,#e39b12 100%)",
36
+ button_primary_background_fill_dark="linear-gradient(135deg,#fff1b0 0%,#f5c542 38%,#e39b12 100%)",
37
+ button_primary_background_fill_hover="linear-gradient(135deg,#fff7d1 0%,#ffd45c 38%,#f0a81c 100%)",
38
+ button_primary_background_fill_hover_dark="linear-gradient(135deg,#fff7d1 0%,#ffd45c 38%,#f0a81c 100%)",
39
+ button_primary_text_color="#1a1203", button_primary_text_color_dark="#1a1203",
40
+ button_primary_border_color="rgba(255,240,190,0.6)", button_primary_border_color_dark="rgba(255,240,190,0.6)",
41
+ button_secondary_background_fill="rgba(255,255,255,0.06)", button_secondary_background_fill_dark="rgba(255,255,255,0.06)",
42
+ button_secondary_background_fill_hover="rgba(255,255,255,0.12)", button_secondary_background_fill_hover_dark="rgba(255,255,255,0.12)",
43
+ button_secondary_text_color="#e8ecf6", button_secondary_text_color_dark="#e8ecf6",
44
+ button_secondary_border_color="rgba(255,255,255,0.12)", button_secondary_border_color_dark="rgba(255,255,255,0.12)",
45
+ slider_color="#f5c542", slider_color_dark="#f5c542",
46
+ checkbox_background_color_selected="#f5c542", checkbox_background_color_selected_dark="#f5c542",
47
+ checkbox_label_background_fill="rgba(255,255,255,0.04)", checkbox_label_background_fill_dark="rgba(255,255,255,0.04)",
48
+ checkbox_label_background_fill_selected="rgba(245,197,66,0.16)", checkbox_label_background_fill_selected_dark="rgba(245,197,66,0.16)",
49
+ checkbox_label_border_color_selected="rgba(245,197,66,0.7)", checkbox_label_border_color_selected_dark="rgba(245,197,66,0.7)",
50
+ color_accent_soft="rgba(245,197,66,0.14)", color_accent_soft_dark="rgba(245,197,66,0.14)",
51
+ shadow_drop="0 10px 40px rgba(0,0,0,.45)", shadow_drop_lg="0 18px 60px rgba(0,0,0,.55)",
52
+ block_shadow="0 10px 40px rgba(0,0,0,.35)", block_shadow_dark="0 10px 40px rgba(0,0,0,.35)",
53
+ layout_gap="14px",
54
+ )
55
+
56
+ HEAD = f"""
57
+ <meta name="theme-color" content="#05040c">
58
+ <meta name="color-scheme" content="dark">
59
+ <meta name="apple-mobile-web-app-capable" content="yes">
60
+ <meta name="mobile-web-app-capable" content="yes">
61
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
62
+ <meta name="apple-mobile-web-app-title" content="AI KING">
63
+ <meta name="application-name" content="AI KING">
64
+ <meta name="description" content="AI KING©️ Studio by KING OF MUSIC©️: free AI images, edits, videos, loops, audio remixes and music videos in one glossy studio.">
65
+ <meta property="og:title" content="AI KING©️ Studio">
66
+ <meta property="og:description" content="Create images, videos, loops and music videos free. By KING OF MUSIC©️ Chad Syphrett.">
67
+ <meta property="og:image" content="{S}/icons/icon-1024.png">
68
+ <link rel="apple-touch-icon" sizes="180x180" href="{S}/icons/apple-touch-icon.png">
69
+ <link rel="icon" type="image/png" sizes="64x64" href="{S}/icons/favicon-64.png">
70
+ <link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
71
+ <link href="https://fonts.googleapis.com/css2?family=Michroma&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
72
+ """
73
+
74
+ JS = r"""
75
+ () => {
76
+ document.documentElement.classList.add('dark');
77
+ document.body.classList.add('dark');
78
+ if (!document.getElementById('aik-stars')) {
79
+ const c = document.createElement('canvas'); c.id = 'aik-stars'; document.body.prepend(c);
80
+ const neb = document.createElement('div'); neb.id = 'aik-nebula'; document.body.prepend(neb);
81
+ const x = c.getContext('2d'); let W, H, stars = [], comets = [], dpr = Math.min(window.devicePixelRatio || 1, 2);
82
+ const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
83
+ function size() {
84
+ W = c.width = innerWidth * dpr; H = c.height = innerHeight * dpr;
85
+ c.style.width = innerWidth + 'px'; c.style.height = innerHeight + 'px';
86
+ const n = Math.min(260, Math.floor(innerWidth * innerHeight / 5200));
87
+ stars = Array.from({length: n}, () => ({x: Math.random()*W, y: Math.random()*H, z: Math.random()*0.8+0.2,
88
+ r: (Math.random()*1.3+0.25)*dpr, t: Math.random()*6.28, hue: Math.random() < .12 ? 45 : (Math.random() < .5 ? 210 : 265)}));
89
+ }
90
+ size(); addEventListener('resize', size);
91
+ function frame(ts) {
92
+ x.clearRect(0, 0, W, H);
93
+ for (const s of stars) {
94
+ s.t += 0.015 * s.z; s.y += 0.06 * s.z * dpr; if (s.y > H) { s.y = 0; s.x = Math.random()*W; }
95
+ const a = 0.35 + 0.65 * Math.abs(Math.sin(s.t));
96
+ x.beginPath(); x.arc(s.x, s.y, s.r, 0, 6.283);
97
+ x.fillStyle = `hsla(${s.hue}, 90%, ${s.hue===45?70:88}%, ${a*s.z})`; x.fill();
98
+ }
99
+ if (Math.random() < 0.006 && comets.length < 2) comets.push({x: Math.random()*W*0.7, y: Math.random()*H*0.35, vx: (4+Math.random()*4)*dpr, vy: (1.6+Math.random()*1.6)*dpr, life: 1});
100
+ comets = comets.filter(m => m.life > 0);
101
+ for (const m of comets) {
102
+ const g = x.createLinearGradient(m.x, m.y, m.x - m.vx*22, m.y - m.vy*22);
103
+ g.addColorStop(0, `rgba(255,255,255,${m.life})`); g.addColorStop(0.3, `rgba(159,216,255,${m.life*0.5})`); g.addColorStop(1, 'rgba(180,140,255,0)');
104
+ x.strokeStyle = g; x.lineWidth = 2*dpr; x.beginPath(); x.moveTo(m.x, m.y); x.lineTo(m.x - m.vx*22, m.y - m.vy*22); x.stroke();
105
+ m.x += m.vx; m.y += m.vy; m.life -= 0.012;
106
+ }
107
+ if (!reduce) requestAnimationFrame(frame);
108
+ }
109
+ requestAnimationFrame(frame);
110
+ }
111
+ // quick-launch cards switch tabs
112
+ window.aikGo = (label) => {
113
+ const want = (label || '').toLowerCase();
114
+ const btns = [...document.querySelectorAll('.tabs button')].filter(b => b.getAttribute('tabindex') !== '-1'
115
+ && b.textContent.trim().toLowerCase().includes(want));
116
+ const vis = btns.find(b => b.getAttribute('role') === 'tab' && b.offsetParent !== null);
117
+ const over = btns.find(b => !b.getAttribute('role'));
118
+ const t = vis || over || btns[0];
119
+ if (t) { t.click(); setTimeout(() => { const w = document.querySelector('.tabs'); w && w.scrollIntoView({behavior: 'smooth', block: 'start'}); }, 80); }
120
+ };
121
+ // inside the AI KING iOS app (Capacitor): route downloads to the native share sheet
122
+ const cap = window.Capacitor;
123
+ if (cap && cap.isNativePlatform && cap.isNativePlatform()) {
124
+ document.body.classList.add('aik-native');
125
+ document.addEventListener('click', (e) => {
126
+ const a = e.target.closest && e.target.closest('a[download]');
127
+ const share = cap.Plugins && cap.Plugins.Share;
128
+ if (a && share) { e.preventDefault(); share.share({title: 'Made with AI KING', url: new URL(a.href, location.href).href}).catch(() => {}); }
129
+ }, true);
130
+ }
131
+ if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(() => {}); }
132
+ }
133
+ """
134
+
135
+ CSS = r"""
136
+ @property --aik-angle { syntax: '<angle>'; initial-value: 0deg; inherits: false; }
137
+ html, body, gradio-app { background: #03040a !important; }
138
+ #aik-stars { position: fixed; inset: 0; z-index: 0; pointer-events: none; }
139
+ #aik-nebula { position: fixed; inset: -20%; z-index: 0; pointer-events: none;
140
+ background:
141
+ radial-gradient(40% 35% at 18% 12%, rgba(124, 58, 237, .22), transparent 70%),
142
+ radial-gradient(35% 30% at 85% 8%, rgba(14, 165, 233, .16), transparent 70%),
143
+ radial-gradient(45% 40% at 70% 92%, rgba(245, 197, 66, .10), transparent 70%),
144
+ radial-gradient(30% 30% at 8% 85%, rgba(236, 72, 153, .10), transparent 70%);
145
+ filter: blur(10px); animation: aikDrift 38s ease-in-out infinite alternate; }
146
+ @keyframes aikDrift { from { transform: translate3d(0,0,0) scale(1); } to { transform: translate3d(2%, -2%, 0) scale(1.06); } }
147
+ .gradio-container { position: relative; z-index: 1; max-width: min(1240px, 100vw) !important; min-width: 0 !important; margin: 0 auto !important;
148
+ padding: max(10px, env(safe-area-inset-top)) clamp(10px, 2.4vw, 28px) 40px !important; background: transparent !important;
149
+ font-feature-settings: "ss01", "cv11"; -webkit-font-smoothing: antialiased; }
150
+ footer { display: none !important; }
151
+
152
+ /* ---------- glass panels with intergalactic edge glow ---------- */
153
+ .block, .form { backdrop-filter: blur(18px) saturate(140%); -webkit-backdrop-filter: blur(18px) saturate(140%); }
154
+ .block { border-radius: 20px !important; }
155
+ .aik-card { position: relative; border-radius: 26px !important; padding: 16px !important;
156
+ background: linear-gradient(180deg, rgba(22,24,40,.72), rgba(10,12,22,.62)) !important;
157
+ border: 1px solid rgba(255,255,255,.07) !important;
158
+ box-shadow: inset 0 1px 0 rgba(255,255,255,.07), 0 24px 70px rgba(0,0,0,.5) !important; isolation: isolate; }
159
+ .aik-card::before { content: ""; position: absolute; inset: -1px; border-radius: inherit; padding: 1.2px; z-index: -1;
160
+ background: conic-gradient(from var(--aik-angle), rgba(245,197,66,.0) 0deg, rgba(245,197,66,.75) 40deg, rgba(159,216,255,.65) 110deg,
161
+ rgba(180,140,255,.55) 170deg, rgba(245,197,66,0) 230deg, rgba(236,72,153,.35) 300deg, rgba(245,197,66,0) 360deg);
162
+ -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); -webkit-mask-composite: xor; mask-composite: exclude;
163
+ animation: aikSpin 9s linear infinite; opacity: .85; }
164
+ .aik-card::after { content: ""; position: absolute; inset: 0; border-radius: inherit; pointer-events: none; z-index: -1;
165
+ background: radial-gradient(120% 60% at 50% -10%, rgba(255,255,255,.07), transparent 60%); }
166
+ @keyframes aikSpin { to { --aik-angle: 360deg; } }
167
+
168
+ /* ---------- hero ---------- */
169
+ #aik-hero { text-align: center; padding: 18px 8px 6px; max-width: 100%; min-width: 0; overflow: hidden; }
170
+ .html-container, .html-container > .prose, .block:has(#aik-hero), .block:has(#aik-foot) { min-width: 0 !important; max-width: 100% !important; }
171
+ html, body { overflow-x: hidden; }
172
+ .aik-top { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
173
+ .aik-brand { display: flex; align-items: center; gap: 10px; text-decoration: none !important; }
174
+ .aik-brand img { width: 40px; height: 40px; border-radius: 11px; box-shadow: 0 0 22px rgba(245,197,66,.35); }
175
+ .aik-brand b { font-family: Michroma, Inter, sans-serif; letter-spacing: .14em; font-size: .82rem; color: #f3f5fb; }
176
+ .aik-pill-row { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; }
177
+ .aik-pill { display: inline-flex; align-items: center; gap: 6px; padding: 7px 13px; border-radius: 999px; font-size: .78rem; font-weight: 600;
178
+ color: #e8ecf6 !important; text-decoration: none !important; background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.10);
179
+ transition: transform .2s, background .2s, box-shadow .2s; }
180
+ .aik-pill:hover { transform: translateY(-1px); background: rgba(255,255,255,.12); box-shadow: 0 0 22px rgba(159,216,255,.18); }
181
+ .aik-pill.gold { background: linear-gradient(135deg, rgba(255,241,176,.22), rgba(227,155,18,.18)); border-color: rgba(245,197,66,.45); }
182
+ .aik-word { font-family: Michroma, Inter, sans-serif; font-weight: 400; font-size: clamp(2.3rem, 8.5vw, 5.4rem); line-height: 1.02;
183
+ letter-spacing: .06em; margin: 18px 0 4px; background: linear-gradient(100deg, #8a5a06 0%, #f5c542 18%, #fff6cf 30%, #f5c542 42%, #d09a1c 60%, #fff2b8 75%, #f5c542 90%);
184
+ background-size: 220% 100%; -webkit-background-clip: text; background-clip: text; color: transparent;
185
+ animation: aikShine 7s linear infinite; filter: drop-shadow(0 0 26px rgba(245,197,66,.28)); }
186
+ .aik-word sup { font-size: .32em; vertical-align: super; letter-spacing: 0; }
187
+ @keyframes aikShine { to { background-position: -220% 0; } }
188
+ .aik-sub { font-family: Michroma, Inter, sans-serif; letter-spacing: .42em; font-size: clamp(.62rem, 1.9vw, .82rem); color: #9fd8ff; opacity: .9; }
189
+ .aik-tag { margin: 14px auto 0; max-width: 680px; color: #b7c0d6; font-size: clamp(.92rem, 2.6vw, 1.06rem); line-height: 1.55; }
190
+ .aik-stats { display: flex; justify-content: center; gap: 10px; flex-wrap: wrap; margin: 18px 0 6px; }
191
+ .aik-stat { min-width: 108px; padding: 10px 14px; border-radius: 18px; background: rgba(255,255,255,.04); border: 1px solid rgba(255,255,255,.08); }
192
+ .aik-stat b { display: block; font-size: 1.32rem; font-weight: 800; color: #fff; font-variant-numeric: tabular-nums; }
193
+ .aik-stat span { font-size: .68rem; letter-spacing: .14em; text-transform: uppercase; color: #8f9ab3; }
194
+ .aik-stat.live b { background: linear-gradient(90deg,#fff6cf,#f5c542); -webkit-background-clip: text; background-clip: text; color: transparent; }
195
+ .aik-store { font-size: .66rem; color: #6f7a93; margin-top: 4px; }
196
+
197
+ /* stories row (Instagram-style) */
198
+ .aik-stories { width: 100%; max-width: 100%; min-width: 0; display: flex; gap: 14px; overflow-x: auto; padding: 14px 4px 6px; scrollbar-width: none; justify-content: flex-start; }
199
+ .aik-stories::-webkit-scrollbar { display: none; }
200
+ .aik-story { flex: 0 0 auto; text-align: center; width: 78px; }
201
+ .aik-story i { display: block; width: 72px; height: 72px; margin: 0 auto 6px; border-radius: 50%; padding: 3px;
202
+ background: conic-gradient(from 210deg, #f5c542, #ec4899, #8b5cf6, #38bdf8, #f5c542); animation: aikPulse 4s ease-in-out infinite; }
203
+ .aik-story img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; border: 3px solid #03040a; display: block; }
204
+ .aik-story span { font-size: .66rem; color: #aab3c8; white-space: nowrap; }
205
+ @keyframes aikPulse { 50% { filter: brightness(1.25) saturate(1.2); } }
206
+
207
+ /* quick-launch grid (Gemini-style cards) */
208
+ .aik-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin: 16px 0 4px; }
209
+ .aik-tile { cursor: pointer; text-align: left; padding: 16px; border-radius: 22px; background: linear-gradient(160deg, rgba(255,255,255,.06), rgba(255,255,255,.02));
210
+ border: 1px solid rgba(255,255,255,.08); transition: transform .25s, box-shadow .25s, border-color .25s; position: relative; overflow: hidden; }
211
+ .aik-tile:hover { transform: translateY(-3px); border-color: rgba(245,197,66,.45); box-shadow: 0 14px 40px rgba(0,0,0,.45), 0 0 30px rgba(245,197,66,.14); }
212
+ .aik-tile::after { content: ""; position: absolute; top: -60%; left: -30%; width: 40%; height: 220%; transform: rotate(25deg);
213
+ background: linear-gradient(90deg, transparent, rgba(255,255,255,.10), transparent); transition: left .6s; }
214
+ .aik-tile:hover::after { left: 120%; }
215
+ .aik-tile em { font-style: normal; font-size: 1.5rem; }
216
+ .aik-tile b { display: block; margin-top: 8px; color: #fff; font-size: .95rem; }
217
+ .aik-tile span { display: block; margin-top: 3px; font-size: .76rem; color: #8f9ab3; line-height: 1.35; }
218
+ @media (max-width: 860px) { .aik-grid { grid-template-columns: repeat(2, 1fr); } }
219
+
220
+ /* ---------- tabs as a glossy pill nav ---------- */
221
+ .tabs > .tab-wrapper, div[role="tablist"] { position: sticky; top: 0; z-index: 20; }
222
+ .tab-wrapper { background: rgba(6,8,16,.72) !important; backdrop-filter: blur(20px) saturate(160%); -webkit-backdrop-filter: blur(20px) saturate(160%);
223
+ border: 1px solid rgba(255,255,255,.08) !important; border-radius: 999px !important; padding: 5px !important; margin: 8px 0 14px !important;
224
+ box-shadow: 0 10px 40px rgba(0,0,0,.45); }
225
+ .tabs, .tab-wrapper { min-width: 0 !important; max-width: 100% !important; }
226
+ .tab-container, div[role="tablist"] { gap: 4px !important; border: none !important; min-width: 0 !important; max-width: 100% !important; overflow: hidden; }
227
+ .tab-container::-webkit-scrollbar { display: none; }
228
+ button[role="tab"] { border-radius: 999px !important; padding: 9px 15px !important; font-weight: 600 !important; font-size: .86rem !important;
229
+ color: #aab3c8 !important; border: 1px solid transparent !important; background: transparent !important; white-space: nowrap; transition: all .2s; }
230
+ button[role="tab"]:hover { color: #fff !important; background: rgba(255,255,255,.06) !important; }
231
+ button[role="tab"][aria-selected="true"], button[role="tab"].selected { color: #1a1203 !important;
232
+ background: linear-gradient(135deg, #fff1b0, #f5c542 45%, #e39b12) !important; box-shadow: 0 0 22px rgba(245,197,66,.35); }
233
+ button[role="tab"][aria-selected="true"]::after, button[role="tab"].selected::after { display: none !important; }
234
+ .tabitem { border: none !important; background: transparent !important; padding: 0 !important; }
235
+
236
+ /* ---------- buttons ---------- */
237
+ button.primary, .primary { position: relative; overflow: hidden; border-radius: 999px !important; font-weight: 800 !important; letter-spacing: .02em;
238
+ box-shadow: 0 8px 30px rgba(245,197,66,.28), inset 0 1px 0 rgba(255,255,255,.65) !important; }
239
+ button.primary::after { content: ""; position: absolute; top: 0; left: -60%; width: 40%; height: 100%; transform: skewX(-20deg);
240
+ background: linear-gradient(90deg, transparent, rgba(255,255,255,.55), transparent); animation: aikSweep 3.8s ease-in-out infinite; }
241
+ @keyframes aikSweep { 0%, 60% { left: -60%; } 100% { left: 140%; } }
242
+ button.secondary { border-radius: 999px !important; }
243
+ button.lg { min-height: 50px; font-size: 1rem !important; }
244
+
245
+ /* ---------- inputs ---------- */
246
+ textarea, input[type="text"], input[type="number"] { border-radius: 16px !important; }
247
+ textarea:focus, input:focus { box-shadow: 0 0 0 3px rgba(245,197,66,.18), 0 0 24px rgba(159,216,255,.12) !important; }
248
+ #aik-prompt textarea { font-size: 1.05rem !important; line-height: 1.5; min-height: 96px; }
249
+ label > span, .block-title, [data-testid="block-label"] { letter-spacing: .02em; }
250
+ .aik-chips .wrap { gap: 8px !important; }
251
+ .aik-chips label { border-radius: 999px !important; padding: 7px 13px !important; font-size: .84rem !important; }
252
+ .aik-chips label input { display: none; }
253
+
254
+ /* gallery / media */
255
+ .grid-wrap, .gallery { border-radius: 18px; }
256
+ .thumbnail-item { border-radius: 14px !important; overflow: hidden; }
257
+ video, .image-frame img { border-radius: 16px; }
258
+
259
+ /* section headers */
260
+ .aik-h { display: flex; align-items: baseline; gap: 10px; margin: 2px 2px 10px; }
261
+ .aik-h h2 { margin: 0; font-size: 1.28rem; font-weight: 800; color: #fff; letter-spacing: -.01em; }
262
+ .aik-h span { color: #8f9ab3; font-size: .85rem; }
263
+ .aik-note { font-size: .8rem; color: #8f9ab3; }
264
+ .aik-soon { padding: 22px; border-radius: 22px; border: 1px dashed rgba(245,197,66,.35); background: rgba(245,197,66,.05); }
265
+ .aik-soon h3 { margin: 0 0 6px; color: #fff; }
266
+ .prose, .md { color: #c9d2e6; }
267
+ .prose a, .md a { color: #9fd8ff; }
268
+
269
+ /* footer */
270
+ #aik-foot { text-align: center; padding: 26px 8px 10px; color: #8f9ab3; font-size: .8rem; }
271
+ #aik-foot .aik-pill-row { margin-bottom: 12px; }
272
+ #aik-foot a.l { color: #9fd8ff; }
273
+
274
+ /* ---------- mobile (iPhone Safari etc.) ---------- */
275
+ @media (max-width: 640px) {
276
+ .gradio-container { padding-left: 8px !important; padding-right: 8px !important; }
277
+ .gradio-container > .main, .gradio-container .main > .wrap, main.contain { padding-left: 0 !important; padding-right: 0 !important; }
278
+ .aik-sub { letter-spacing: .22em; }
279
+ .aik-stats { gap: 6px; }
280
+ .aik-stat { flex: 1 1 28%; min-width: 0; }
281
+ .aik-stat span { letter-spacing: .06em; font-size: .6rem; }
282
+ .aik-card { padding: 10px !important; border-radius: 22px !important; }
283
+ .aik-stat { min-width: 84px; padding: 8px 10px; }
284
+ .aik-stat b { font-size: 1.05rem; }
285
+ .aik-top .aik-pill-row { display: none; }
286
+ button[role="tab"] { padding: 8px 12px !important; font-size: .8rem !important; }
287
+ .aik-grid { gap: 8px; }
288
+ .aik-tile { padding: 12px; border-radius: 18px; }
289
+ .aik-tile span { display: none; }
290
+ }
291
+ @media (prefers-reduced-motion: reduce) { .aik-card::before, .aik-word, #aik-nebula, button.primary::after, .aik-story i { animation: none !important; } }
292
+ """
293
+
294
+
295
+ def hero_html(stats: dict, store: str) -> str:
296
+ def f(n):
297
+ return f"{n:,}"
298
+ stories = "".join(
299
+ f'<div class="aik-story"><i><img src="{S}/showcase/s{i}.webp" alt="" loading="lazy"></i><span>{t}</span></div>'
300
+ for i, t in enumerate(["Throne", "Monarchs", "Holo Kicks", "Fedora", "World Peace", "Portrait", "CAR MAN", "Navy Suit"], 1))
301
+ return f"""
302
+ <div id="aik-hero">
303
+ <div class="aik-top">
304
+ <a class="aik-brand" href="/"><img src="{S}/icons/icon-192.png" alt="AI KING"><b>AI KING</b></a>
305
+ <div class="aik-pill-row">
306
+ <a class="aik-pill" href="{YT}" target="_blank" rel="noopener">▶ YouTube</a>
307
+ <a class="aik-pill" href="{TT}" target="_blank" rel="noopener">♪ TikTok</a>
308
+ <a class="aik-pill" href="{IG}" target="_blank" rel="noopener">◎ Instagram</a>
309
+ <a class="aik-pill gold" href="{MUSIC}" target="_blank" rel="noopener">🎵 Stream my music</a>
310
+ </div>
311
+ </div>
312
+ <div class="aik-word">AI KING<sup>©️</sup></div>
313
+ <div class="aik-sub">STUDIO · BY KING OF MUSIC©️</div>
314
+ <p class="aik-tag">Images, edits, videos, loops, remixes &amp; music videos. One glossy studio, free, right in your browser.
315
+ Add it to your iPhone home screen and create anywhere.</p>
316
+ <div class="aik-stats">
317
+ <div class="aik-stat live"><b>{f(stats.get('visits', 0))}</b><span>Visits</span></div>
318
+ <div class="aik-stat live"><b>{f(stats.get('creations', 0))}</b><span>Creations</span></div>
319
+ <div class="aik-stat"><b>{f(stats.get('images', 0) + stats.get('edits', 0))}</b><span>Images</span></div>
320
+ <div class="aik-stat"><b>{f(stats.get('videos', 0))}</b><span>Videos</span></div>
321
+ <div class="aik-stat"><b>{f(stats.get('audio', 0) + stats.get('loops', 0))}</b><span>Audio · Loops</span></div>
322
+ </div>
323
+ <div class="aik-store">Live counter · stored in {store}</div>
324
+ <div class="aik-stories">{stories}</div>
325
+ <div class="aik-grid">
326
+ <div class="aik-tile" onclick="aikGo('Create')"><em>✨</em><b>Create</b><span>Text → image in seconds (FLUX)</span></div>
327
+ <div class="aik-tile" onclick="aikGo('Edit')"><em>🎨</em><b>Edit</b><span>Restyle any photo: image → image</span></div>
328
+ <div class="aik-tile" onclick="aikGo('Video')"><em>🎬</em><b>Video</b><span>Text/image → video &amp; seamless loops (LTX)</span></div>
329
+ <div class="aik-tile" onclick="aikGo('Audio')"><em>🎧</em><b>Audio Lab</b><span>Remix, slow, speed up, loop, music videos</span></div>
330
+ </div>
331
+ <div class="aik-pill-row" style="margin-top:10px">
332
+ <a class="aik-pill" href="javascript:aikGo('Loops')">🔁 Loops &amp; Export</a>
333
+ <a class="aik-pill" href="javascript:aikGo('Prompt Studio')">👑 Prompt Studio</a>
334
+ <a class="aik-pill" href="javascript:aikGo('Release Kit')">💿 Release Kit</a>
335
+ <a class="aik-pill" href="javascript:aikGo('Labs')">🧪 Labs</a>
336
+ <a class="aik-pill" href="javascript:aikGo('About')">📲 Install &amp; About</a>
337
+ </div>
338
+ </div>
339
+ """
340
+
341
+
342
+ FOOTER = f"""
343
+ <div id="aik-foot">
344
+ <div class="aik-pill-row">
345
+ <a class="aik-pill" href="{YT}" target="_blank" rel="noopener">▶ youtube.com/@ChadSyphrett</a>
346
+ <a class="aik-pill" href="{TT}" target="_blank" rel="noopener">♪ tiktok.com/@MusicVideosTM</a>
347
+ <a class="aik-pill" href="{IG}" target="_blank" rel="noopener">◎ instagram.com/InternetThemePark</a>
348
+ <a class="aik-pill gold" href="{MUSIC}" target="_blank" rel="noopener">🎵 KING OF MUSIC on streaming</a>
349
+ </div>
350
+ <div>AI KING©️ · KING OF MUSIC©️ · Chad Syphrett · Non-explicit creative use only ·
351
+ <a class="l" href="/privacy" target="_blank">Privacy</a> · <a class="l" href="/terms" target="_blank">Terms</a></div>
352
+ <div style="margin-top:6px;opacity:.75">📲 iPhone: Share → <b>Add to Home Screen</b> · Android: ⋮ → <b>Install app</b></div>
353
+ <div style="margin-top:8px;opacity:.6">Everyday Is A Lesson. Be Thankful To YHWH! 👑</div>
354
+ </div>
355
+ """
gen.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AI KING©️ generators on ZeroGPU (open models only, no paid inference).
2
+
3
+ - Text → Image and Image → Image: FLUX.1 [schnell] (Apache-2.0), 4-step distilled.
4
+ - Text/Image → Video + seamless loops: LTX-Video 0.9.5 (2B, LTXV Open Weights License,
5
+ free for companies under $10M annual revenue). Shares FLUX's T5-XXL text encoder
6
+ (byte-identical weights) so both fit in one ZeroGPU slot.
7
+ Set AIKING_NO_MODELS=1 to run the UI without loading models (local design work).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import math, os, random, tempfile, time, traceback
12
+
13
+ import numpy as np
14
+ from PIL import Image, ImageOps
15
+
16
+ try:
17
+ import spaces # ZeroGPU
18
+ except Exception: # local / non-Spaces
19
+ class _S:
20
+ @staticmethod
21
+ def GPU(*a, **k):
22
+ if a and callable(a[0]):
23
+ return a[0]
24
+ return lambda f: f
25
+ spaces = _S()
26
+
27
+ NO_MODELS = os.environ.get("AIKING_NO_MODELS") == "1"
28
+ HUB_TOKEN = os.environ.get("AIKING_HUB_TOKEN") or None
29
+ FLUX_ID = "black-forest-labs/FLUX.1-schnell"
30
+ LTX_ID = "Lightricks/LTX-Video-0.9.5"
31
+ OUT_DIR = os.path.join(tempfile.gettempdir(), "aiking_out")
32
+ os.makedirs(OUT_DIR, exist_ok=True)
33
+
34
+ STATUS = {"image": "off", "video": "off"}
35
+ ERRORS: dict[str, str] = {}
36
+ t2i = i2i = ltx = None
37
+ LTXVideoCondition = None
38
+
39
+ STYLES = {
40
+ "None": "",
41
+ "🎬 ARRI ALEXA 35": "cinematic film still shot on ARRI ALEXA 35, anamorphic lens, shallow depth of field, natural film grain, hyperrealistic skin texture, dramatic motivated lighting",
42
+ "💿 Album Cover": "premium album cover art, bold centered composition, iconic silhouette, luxury finish, high contrast, crisp detail",
43
+ "👑 Royal Gold": "black and gold luxury aesthetic, regal, glossy reflections, crown motifs, studio rim light, hyperdetailed",
44
+ "🌃 Neon Lofi": "cozy lofi aesthetic, neon city at night, rain on glass, soft bloom, warm desk lamp, cinematic anime-inspired color",
45
+ "🚀 Intergalactic": "cosmic nebula backdrop, starfield, iridescent rim light, epic sci-fi scale, glossy chrome accents",
46
+ "📸 Editorial": "luxury fashion editorial photograph, softbox key light, magazine cover quality, clean background",
47
+ "🧸 3D Toy": "glossy 3D render, collectible vinyl toy style, soft global illumination, studio backdrop",
48
+ "🎮 Game Cinematic": "AAA video game cinematic key art, unreal engine 5 render, volumetric light, epic composition",
49
+ }
50
+ ASPECTS = {"9:16 Story": (768, 1344), "1:1 Square": (1024, 1024), "4:5 Portrait": (896, 1120), "16:9 Cinema": (1344, 768)}
51
+ VIDEO_ASPECTS = {"9:16 Story": (480, 832), "1:1 Square": (640, 640), "16:9 Cinema": (832, 480)}
52
+ VIDEO_NEG = "worst quality, inconsistent motion, blurry, jittery, distorted face, morphing, warped hands, text, watermark, logo"
53
+
54
+
55
+ def _load():
56
+ global t2i, i2i, ltx, LTXVideoCondition
57
+ import torch
58
+ from huggingface_hub import snapshot_download
59
+ from diffusers import FluxImg2ImgPipeline, FluxPipeline
60
+ flux_dir = snapshot_download(FLUX_ID, token=HUB_TOKEN, allow_patterns=[
61
+ "model_index.json", "scheduler/*", "text_encoder/*", "text_encoder_2/*",
62
+ "tokenizer/*", "tokenizer_2/*", "transformer/*", "vae/*"])
63
+ t2i = FluxPipeline.from_pretrained(flux_dir, dtype=torch.bfloat16).to("cuda")
64
+ i2i = FluxImg2ImgPipeline.from_pipe(t2i, dtype=torch.bfloat16) # from_pipe defaults to fp32!
65
+ STATUS["image"] = "ready"
66
+ try:
67
+ from diffusers import (AutoencoderKLLTXVideo, FlowMatchEulerDiscreteScheduler,
68
+ LTXConditionPipeline, LTXVideoTransformer3DModel)
69
+ from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition as _C
70
+ LTXVideoCondition = _C
71
+ ltx_dir = snapshot_download(LTX_ID, token=HUB_TOKEN, allow_patterns=[
72
+ "model_index.json", "scheduler/*", "transformer/*", "vae/*", "tokenizer/*"])
73
+ ltx = LTXConditionPipeline(
74
+ scheduler=FlowMatchEulerDiscreteScheduler.from_pretrained(ltx_dir, subfolder="scheduler"),
75
+ vae=AutoencoderKLLTXVideo.from_pretrained(ltx_dir, subfolder="vae", dtype=torch.bfloat16),
76
+ text_encoder=t2i.text_encoder_2, # identical T5-XXL v1.1 weights
77
+ tokenizer=t2i.tokenizer_2,
78
+ transformer=LTXVideoTransformer3DModel.from_pretrained(ltx_dir, subfolder="transformer", dtype=torch.bfloat16),
79
+ ).to("cuda")
80
+ STATUS["video"] = "ready"
81
+ except Exception as e: # keep images working even if video can't load
82
+ ERRORS["video"] = f"{type(e).__name__}: {e}"[:500]
83
+ STATUS["video"] = "error"
84
+ traceback.print_exc()
85
+
86
+
87
+ if not NO_MODELS:
88
+ try:
89
+ _load()
90
+ except Exception as e:
91
+ ERRORS["image"] = f"{type(e).__name__}: {e}"[:500]
92
+ STATUS["image"] = STATUS["image"] if STATUS["image"] == "ready" else "error"
93
+ traceback.print_exc()
94
+
95
+
96
+ class GenError(RuntimeError):
97
+ pass
98
+
99
+
100
+ def _seed(seed):
101
+ try:
102
+ s = int(seed)
103
+ except Exception:
104
+ s = -1
105
+ return random.randint(0, 2**31 - 1) if s < 0 else s
106
+
107
+
108
+ def style_prompt(prompt: str, style: str) -> str:
109
+ extra = STYLES.get(style, "")
110
+ p = (prompt or "").strip().rstrip(".")
111
+ return f"{p}, {extra}" if extra else p
112
+
113
+
114
+ def _save_png(img: Image.Image, tag: str) -> str:
115
+ path = os.path.join(OUT_DIR, f"aiking-{tag}-{int(time.time()*1000)}-{random.randint(100,999)}.png")
116
+ img.save(path)
117
+ return path
118
+
119
+
120
+ def _fit16(img: Image.Image, max_side=1024) -> Image.Image:
121
+ img = ImageOps.exif_transpose(img).convert("RGB")
122
+ w, h = img.size
123
+ s = min(1.0, max_side / max(w, h))
124
+ w, h = max(256, int(w * s) // 16 * 16), max(256, int(h * s) // 16 * 16)
125
+ return img.resize((w, h), Image.LANCZOS)
126
+
127
+
128
+ def _cover(img: Image.Image, w: int, h: int) -> Image.Image:
129
+ return ImageOps.fit(ImageOps.exif_transpose(img).convert("RGB"), (w, h), Image.LANCZOS)
130
+
131
+
132
+ def _need(kind):
133
+ if STATUS.get(kind) != "ready":
134
+ msg = ERRORS.get(kind) or ("models are disabled in this preview" if NO_MODELS else "model is still loading, try again in a minute")
135
+ raise GenError(f"{'Image' if kind == 'image' else 'Video'} engine not ready ({msg}).")
136
+
137
+
138
+ # ---------------- GPU functions ----------------
139
+
140
+ def _t2i_dur(prompt, style, aspect, n, seed):
141
+ return min(90, 20 + 8 * int(n or 1))
142
+
143
+
144
+ @spaces.GPU(duration=_t2i_dur)
145
+ def text_to_image(prompt, style, aspect, n, seed):
146
+ import torch
147
+ _need("image")
148
+ w, h = ASPECTS.get(aspect, (1024, 1024))
149
+ s = _seed(seed)
150
+ imgs = t2i(prompt=style_prompt(prompt, style), width=w, height=h, num_inference_steps=4, guidance_scale=0.0,
151
+ num_images_per_prompt=int(n or 1), max_sequence_length=256,
152
+ generator=torch.Generator("cpu").manual_seed(s)).images
153
+ return [_save_png(im, "img") for im in imgs], s
154
+
155
+
156
+ def _i2i_dur(image_path, prompt, style, strength, seed):
157
+ return 40
158
+
159
+
160
+ @spaces.GPU(duration=_i2i_dur)
161
+ def image_to_image(image_path, prompt, style, strength, seed):
162
+ import torch
163
+ _need("image")
164
+ src = _fit16(Image.open(image_path))
165
+ st = float(strength)
166
+ steps = max(4, math.ceil(4 / max(st, 0.05)))
167
+ s = _seed(seed)
168
+ img = i2i(prompt=style_prompt(prompt, style), image=src, strength=st, width=src.width, height=src.height,
169
+ num_inference_steps=min(steps, 16), guidance_scale=0.0, max_sequence_length=256,
170
+ generator=torch.Generator("cpu").manual_seed(s)).images[0]
171
+ return _save_png(img, "edit"), s
172
+
173
+
174
+ def _frames(seconds: float) -> int:
175
+ n = int(round(float(seconds) * 24 / 8)) * 8 + 1
176
+ return max(25, min(n, 129))
177
+
178
+
179
+ def _vid_dur(prompt, image_path, mode, seconds, aspect, steps, seed):
180
+ return int(min(170, 35 + int(steps) * (_frames(seconds) / 97) * 2.2))
181
+
182
+
183
+ def _write_mp4(frames, fps=24) -> str:
184
+ import imageio.v2 as imageio
185
+ path = os.path.join(OUT_DIR, f"aiking-video-{int(time.time()*1000)}.mp4")
186
+ arr = (np.clip(np.asarray(frames), 0, 1) * 255).astype(np.uint8) if np.asarray(frames).dtype != np.uint8 else np.asarray(frames)
187
+ with imageio.get_writer(path, fps=fps, codec="libx264", quality=8, pixelformat="yuv420p", macro_block_size=16,
188
+ ffmpeg_params=["-movflags", "+faststart"]) as wr:
189
+ for f in arr:
190
+ wr.append_data(f)
191
+ return path
192
+
193
+
194
+ @spaces.GPU(duration=_vid_dur)
195
+ def make_video(prompt, image_path, mode, seconds, aspect, steps, seed):
196
+ """mode: 'Text → Video', 'Image → Video', 'Seamless Loop'."""
197
+ import torch
198
+ _need("video")
199
+ w, h = VIDEO_ASPECTS.get(aspect, (832, 480))
200
+ n = _frames(seconds)
201
+ s = _seed(seed)
202
+ gen = torch.Generator("cpu").manual_seed(s)
203
+ keyframe = None
204
+ if image_path:
205
+ keyframe = _cover(Image.open(image_path), w, h)
206
+ elif mode != "Text → Video" or STATUS["image"] == "ready":
207
+ # cinematic keyframe from FLUX first: sharper, more on-brand than raw text-to-video
208
+ _need("image")
209
+ kw, kh = (w * 2 // 16 * 16, h * 2 // 16 * 16)
210
+ k = t2i(prompt=style_prompt(prompt, "🎬 ARRI ALEXA 35"), width=kw, height=kh, num_inference_steps=4,
211
+ guidance_scale=0.0, max_sequence_length=256, generator=torch.Generator("cpu").manual_seed(s)).images[0]
212
+ keyframe = k.resize((w, h), Image.LANCZOS)
213
+ conds = None
214
+ if keyframe is not None:
215
+ conds = [LTXVideoCondition(image=keyframe, frame_index=0)]
216
+ if mode == "Seamless Loop":
217
+ conds.append(LTXVideoCondition(image=keyframe, frame_index=n - 1))
218
+ motion = (prompt or "").strip().rstrip(".") + ". Smooth natural motion, cinematic camera, consistent identity and lighting, high detail."
219
+ out = ltx(conditions=conds, prompt=motion, negative_prompt=VIDEO_NEG, width=w, height=h, num_frames=n,
220
+ num_inference_steps=int(steps), guidance_scale=3.0, decode_timestep=0.05, decode_noise_scale=0.025,
221
+ generator=gen, output_type="np").frames[0]
222
+ return _write_mp4(out), s
requirements.txt CHANGED
@@ -1,3 +1,12 @@
1
- gradio>=6.0
2
- gradio_client>=2.0
 
 
 
 
 
 
 
 
3
  pillow>=10.0
 
 
1
+ torch==2.8.0
2
+ diffusers==0.41.0
3
+ transformers>=4.51,<6
4
+ accelerate>=1.2
5
+ sentencepiece
6
+ protobuf
7
+ imageio>=2.34
8
+ imageio-ffmpeg>=0.5
9
+ huggingface_hub>=0.30
10
+ gradio_client>=1.0
11
  pillow>=10.0
12
+ numpy
static/icons/apple-touch-icon.png ADDED
static/icons/favicon-64.png ADDED
static/icons/icon-1024.png ADDED

Git LFS Details

  • SHA256: 151b17f2f241e856d3879308068d51dd78065c211b26021416cc71fdf1584aa5
  • Pointer size: 131 Bytes
  • Size of remote file: 420 kB
static/icons/icon-192.png ADDED
static/icons/icon-512.png ADDED

Git LFS Details

  • SHA256: b48680199eae4df2e82aebbfb706ad9b17fc0ee3e20a10b4bd0ebdd81bc78ab9
  • Pointer size: 131 Bytes
  • Size of remote file: 153 kB
static/icons/icon-maskable-512.png ADDED
static/logo-mark.svg ADDED
static/manifest.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "/",
3
+ "name": "AI KING©️ Studio",
4
+ "short_name": "AI KING",
5
+ "description": "Free AI images, edits, videos, loops, remixes and music videos by KING OF MUSIC©️.",
6
+ "start_url": "/?source=pwa",
7
+ "scope": "/",
8
+ "display": "standalone",
9
+ "display_override": ["standalone", "minimal-ui"],
10
+ "orientation": "any",
11
+ "background_color": "#03040a",
12
+ "theme_color": "#05040c",
13
+ "categories": ["photo", "music", "entertainment", "productivity"],
14
+ "icons": [
15
+ {"src": "/gradio_api/file=static/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"},
16
+ {"src": "/gradio_api/file=static/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"},
17
+ {"src": "/gradio_api/file=static/icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"},
18
+ {"src": "/gradio_api/file=static/icons/apple-touch-icon.png", "sizes": "180x180", "type": "image/png", "purpose": "any"}
19
+ ],
20
+ "shortcuts": [
21
+ {"name": "Create image", "url": "/?tab=create", "icons": [{"src": "/gradio_api/file=static/icons/icon-192.png", "sizes": "192x192"}]},
22
+ {"name": "Make video", "url": "/?tab=video", "icons": [{"src": "/gradio_api/file=static/icons/icon-192.png", "sizes": "192x192"}]}
23
+ ]
24
+ }
static/offline.html ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
2
+ <meta name="theme-color" content="#05040c"><title>AI KING©️ · Offline</title>
3
+ <style>body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:radial-gradient(60% 50% at 50% 20%,#2a1a4a,#03040a);color:#e8ecf6;font-family:-apple-system,Inter,sans-serif;text-align:center}
4
+ img{width:96px;border-radius:24px;box-shadow:0 0 40px rgba(245,197,66,.35)}h1{font-weight:800;margin:18px 0 6px}p{color:#9aa3b8}a{color:#f5c542}</style></head>
5
+ <body><div><img src="/gradio_api/file=static/icons/icon-192.png" alt=""><h1>You're offline</h1><p>AI KING©️ needs a connection to create. Reconnect and <a href="/">try again</a>.</p></div></body></html>
static/privacy.html ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
2
+ <meta name="theme-color" content="#05040c"><title>AI KING©️ Studio · Privacy Policy</title>
3
+ <style>body{margin:0;background:#03040a;color:#d7deee;font:16px/1.65 -apple-system,Inter,Segoe UI,sans-serif}main{max-width:760px;margin:0 auto;padding:40px 20px 80px}
4
+ h1{color:#fff;font-size:2rem;margin:0 0 4px}h2{color:#f5c542;font-size:1.1rem;margin-top:32px}a{color:#9fd8ff}.m{color:#8f9ab3;font-size:.9rem}li{margin:4px 0}</style></head>
5
+ <body><main>
6
+ <h1>Privacy Policy</h1>
7
+ <div class="m">AI KING©️ Studio (web app and iOS app) · Operated by Chad Syphrett (KING OF MUSIC©️) · Effective October 8, 2026</div>
8
+
9
+ <h2>Short version</h2>
10
+ <ul>
11
+ <li>No account is needed. We don't sell your data and we don't run ads or ad trackers.</li>
12
+ <li>Prompts and files you upload are processed only to make your result, then deleted automatically when the server restarts or clears its temporary cache (usually within 24 hours).</li>
13
+ <li>We keep anonymous totals (number of visits and creations by type). These counters contain no names, IP addresses, prompts or files.</li>
14
+ </ul>
15
+
16
+ <h2>What we process</h2>
17
+ <ul>
18
+ <li><b>Content you submit:</b> text prompts, images, audio and video you upload, and the results the app generates. This is used only to perform the tool you choose.</li>
19
+ <li><b>Technical data:</b> the hosting provider (Hugging Face) processes standard request data such as IP address, browser type and timestamps to deliver the service, prevent abuse and apply free GPU usage limits. See the <a href="https://huggingface.co/privacy" target="_blank" rel="noopener">Hugging Face Privacy Policy</a>.</li>
20
+ <li><b>Fonts:</b> the web app loads fonts from Google Fonts, which receives your IP address. See the <a href="https://policies.google.com/privacy" target="_blank" rel="noopener">Google Privacy Policy</a>.</li>
21
+ <li><b>Labs tools:</b> the optional Expand and Upscale tools send your image to third-party open-source apps hosted on Hugging Face Spaces. Those apps are labeled in the Labs tab.</li>
22
+ </ul>
23
+
24
+ <h2>AI-generated content</h2>
25
+ <ul>
26
+ <li>Images, videos and audio are created by open AI models (FLUX.1 [schnell], LTX-Video) and by ffmpeg audio and video processing. Results can be inaccurate or unexpected.</li>
27
+ <li>Content rules: non-explicit creative use only. Prompts are screened for explicit, hateful, or harmful terms, and requests involving minors are blocked.</li>
28
+ <li>Only upload photos of people when you own them or have their permission. Don't use AI KING to impersonate, harass, or deceive anyone.</li>
29
+ <li>You're responsible for how you use and share what you create. Check the model licenses on the About tab before commercial use.</li>
30
+ </ul>
31
+
32
+ <h2>Children</h2>
33
+ <p>AI KING©️ is not directed to children under 13, and we do not knowingly collect personal information from them.</p>
34
+
35
+ <h2>Storage &amp; security</h2>
36
+ <p>Files are stored temporarily on the hosting server only as long as needed to deliver your result. Connections use HTTPS. The anonymous counters are kept in a private repository.</p>
37
+
38
+ <h2>Your choices</h2>
39
+ <p>Don't upload anything you don't want processed. To ask a question or request removal of anything you believe we hold, open a discussion on the app's
40
+ <a href="https://huggingface.co/spaces/INTERNETCON/AI-KING-Studio/discussions" target="_blank" rel="noopener">community page</a>.</p>
41
+
42
+ <h2>Changes</h2>
43
+ <p>If this policy changes, we'll update the effective date above.</p>
44
+ <p class="m"><a href="/">← Back to AI KING©️ Studio</a></p>
45
+ </main></body></html>
static/showcase/s1.webp ADDED
static/showcase/s2.webp ADDED
static/showcase/s3.webp ADDED
static/showcase/s4.webp ADDED
static/showcase/s5.webp ADDED
static/showcase/s6.webp ADDED
static/showcase/s7.webp ADDED
static/showcase/s8.webp ADDED
static/sw.js ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // AI KING©️ service worker: network-first, tiny offline fallback. Never caches API/queue traffic.
2
+ const CACHE = 'aiking-v2';
3
+ const OFFLINE = '/offline';
4
+ self.addEventListener('install', e => {
5
+ e.waitUntil(caches.open(CACHE).then(c => c.addAll([OFFLINE, '/gradio_api/file=static/icons/icon-192.png'])).then(() => self.skipWaiting()));
6
+ });
7
+ self.addEventListener('activate', e => {
8
+ e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k)))).then(() => self.clients.claim()));
9
+ });
10
+ self.addEventListener('fetch', e => {
11
+ const r = e.request;
12
+ if (r.method !== 'GET' || r.mode !== 'navigate') return; // only page loads
13
+ e.respondWith(fetch(r).catch(() => caches.match(OFFLINE)));
14
+ });
static/terms.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
2
+ <meta name="theme-color" content="#05040c"><title>AI KING©️ Studio · Terms</title>
3
+ <style>body{margin:0;background:#03040a;color:#d7deee;font:16px/1.65 -apple-system,Inter,Segoe UI,sans-serif}main{max-width:760px;margin:0 auto;padding:40px 20px 80px}
4
+ h1{color:#fff}h2{color:#f5c542;font-size:1.1rem;margin-top:28px}a{color:#9fd8ff}</style></head><body><main>
5
+ <h1>Terms of Use</h1>
6
+ <p>AI KING©️ Studio is provided free, as-is, without warranties. Free GPU time is limited per visitor per day.</p>
7
+ <h2>Acceptable use</h2>
8
+ <p>No explicit, sexual, hateful, violent, or illegal content. No content involving minors. No impersonation, deepfakes of real people without consent, harassment, or deception. Don't upload content you don't have rights to.</p>
9
+ <h2>Your content</h2>
10
+ <p>You keep the rights you have in your uploads. Generated outputs are subject to the licenses of the underlying models (FLUX.1 [schnell]: Apache-2.0; LTX-Video: LTXV Open Weights License). AI KING©️, KING OF MUSIC©️ and related marks belong to Chad Syphrett.</p>
11
+ <h2>Contact</h2>
12
+ <p>Via the <a href="https://huggingface.co/spaces/INTERNETCON/AI-KING-Studio/discussions" target="_blank" rel="noopener">community page</a>.</p>
13
+ <p><a href="/">← Back to AI KING©️ Studio</a></p></main></body></html>
stats.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persistent visit/creation counter for AI KING©️.
2
+
3
+ Primary store: a small private dataset repo (INTERNETCON/ai-king-stats, file stats.json),
4
+ synced every ~90 s by a background thread (needs the AIKING_HUB_TOKEN Space secret).
5
+ Fallback: /data/stats.json if Space persistent storage exists, else ./stats.json
6
+ (local JSON resets when the Space restarts; the UI says which store is active).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json, os, threading, time
11
+
12
+ REPO = os.environ.get("AIKING_STATS_REPO", "INTERNETCON/ai-king-stats")
13
+ TOKEN = os.environ.get("AIKING_HUB_TOKEN") or None
14
+ KEYS = ["visits", "images", "edits", "videos", "audio", "loops", "covers", "prompts"]
15
+ _lock = threading.Lock()
16
+ _data = {k: 0 for k in KEYS}
17
+ _dirty = False
18
+ MODE = "local JSON"
19
+ _local = "/data/stats.json" if os.path.isdir("/data") and os.access("/data", os.W_OK) else os.path.join(os.path.dirname(__file__), "stats.json")
20
+ if _local.startswith("/data"):
21
+ MODE = "Space persistent storage (/data)"
22
+
23
+
24
+ def _merge(d: dict):
25
+ for k in KEYS:
26
+ try:
27
+ _data[k] = max(_data[k], int(d.get(k, 0)))
28
+ except Exception:
29
+ pass
30
+
31
+
32
+ def _init():
33
+ global MODE
34
+ if os.path.exists(_local):
35
+ try:
36
+ _merge(json.load(open(_local)))
37
+ except Exception:
38
+ pass
39
+ if TOKEN and os.environ.get("AIKING_STATS_LOCAL") != "1":
40
+ try:
41
+ from huggingface_hub import HfApi, hf_hub_download
42
+ api = HfApi(token=TOKEN)
43
+ api.create_repo(REPO, repo_type="dataset", private=True, exist_ok=True)
44
+ try:
45
+ p = hf_hub_download(REPO, "stats.json", repo_type="dataset", token=TOKEN, force_download=True)
46
+ _merge(json.load(open(p)))
47
+ except Exception:
48
+ pass
49
+ MODE = f"HF dataset repo ({REPO})"
50
+ except Exception as e:
51
+ print("stats: dataset unavailable, using local JSON:", type(e).__name__)
52
+
53
+
54
+ def _flush_loop():
55
+ global _dirty
56
+ while True:
57
+ time.sleep(90)
58
+ with _lock:
59
+ if not _dirty:
60
+ continue
61
+ snap = dict(_data, updated=int(time.time()))
62
+ _dirty = False
63
+ try:
64
+ json.dump(snap, open(_local, "w"))
65
+ except Exception:
66
+ pass
67
+ if MODE.startswith("HF dataset"):
68
+ try:
69
+ from huggingface_hub import HfApi
70
+ HfApi(token=TOKEN).upload_file(path_or_fileobj=json.dumps(snap, indent=1).encode(), path_in_repo="stats.json",
71
+ repo_id=REPO, repo_type="dataset", commit_message="stats sync")
72
+ except Exception as e:
73
+ print("stats: sync failed:", type(e).__name__)
74
+ with _lock:
75
+ _dirty = True
76
+
77
+
78
+ def hit(key: str, n: int = 1):
79
+ global _dirty
80
+ with _lock:
81
+ _data[key] = _data.get(key, 0) + n
82
+ _dirty = True
83
+
84
+
85
+ def snapshot() -> dict:
86
+ with _lock:
87
+ d = dict(_data)
88
+ d["creations"] = sum(d[k] for k in KEYS if k != "visits")
89
+ return d
90
+
91
+
92
+ _init()
93
+ threading.Thread(target=_flush_loop, daemon=True).start()