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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
"""
WaveForge Forge β€” turn an audio clip into a real branded music-video visualizer MP4.

CPU-only by design: numpy for the audio envelope + spectrum, PIL for frame generation,
ffmpeg (libx264 / yuv420p / +faststart) for the encode. No diffusion, no GPU, no quota.
"""

from __future__ import annotations

import functools
import math
import os
import shutil
import subprocess
import tempfile

import gradio as gr
import numpy as np
import soundfile as sf
from PIL import Image, ImageDraw, ImageFont

# ---------------------------------------------------------------- brand
FORGE_BLACK = "#0A0908"
BLACK_2 = "#12100D"
GOLD = "#D4A843"
GOLD_LIGHT = "#E8C56D"
GOLD_MUTED = "#8A7440"
STONE = "#6B6560"
BONE = "#F0EDE8"
HAIRLINE = "#2A2418"

W, H = 1280, 720
FPS = 30
MAX_SECONDS = 10.0          # hard cap: the demo always stays fast
ANALYSIS_SR = 44100
N_BARS = 72

# --- fixed layout of the 1280x720 frame
TYPE_CY = 300               # vertical center of the kinetic type block
BAR_BASE = 540              # baseline of the bar array
BAR_MAX = 150               # tallest bar, before the energy multiplier
WAVE_Y = 622                # baseline of the waveform contour
BAR_GAP = 5
BAR_W = max(3, int((W - 160 - (N_BARS - 1) * BAR_GAP) / N_BARS))
BAR_TOTAL = N_BARS * BAR_W + (N_BARS - 1) * BAR_GAP
BAR_X0 = (W - BAR_TOTAL) // 2

HERE = os.path.dirname(os.path.abspath(__file__))
DEMO_WAV = os.path.join(HERE, "demo_beat.wav")
FONT_DIR = os.path.join(HERE, "fonts")


def _find_font() -> str | None:
    """First usable TrueType font on disk. Returns None -> Pillow's bundled fallback."""
    candidates = [
        os.path.join(FONT_DIR, "DejaVuSans-Bold.ttf"),
        os.path.join(FONT_DIR, "DejaVuSans.ttf"),
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
        "/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf",
        "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
        "/usr/share/fonts/truetype/freefont/FreeSansBold.ttf",
        "C:/Windows/Fonts/arialbd.ttf",
        "C:/Windows/Fonts/arial.ttf",
    ]
    for c in candidates:
        if os.path.exists(c):
            return c
    return None


FONT_PATH = _find_font()


@functools.lru_cache(maxsize=256)
def load_font(size: int) -> ImageFont.FreeTypeFont:
    if FONT_PATH:
        return ImageFont.truetype(FONT_PATH, size)
    try:
        return ImageFont.load_default(size=size)
    except TypeError:  # Pillow < 10.1
        return ImageFont.load_default()


def text_size(draw: ImageDraw.ImageDraw, txt: str, font) -> tuple[int, int, int]:
    box = draw.textbbox((0, 0), txt, font=font)
    return box[2] - box[0], box[3] - box[1], box[1]


@functools.lru_cache(maxsize=512)
def render_tracked_text(txt: str, size: int, fill: str, tracking: int) -> Image.Image:
    """Render text with manual letter tracking onto a transparent RGBA tile."""
    font = load_font(size)
    probe = ImageDraw.Draw(Image.new("RGBA", (1, 1)))
    widths = [probe.textlength(ch, font=font) for ch in txt]
    total = int(sum(widths) + tracking * max(0, len(txt) - 1))
    box = probe.textbbox((0, 0), "Ag", font=font)
    asc, desc = -box[1], box[3]
    tile = Image.new("RGBA", (max(1, total + 8), max(1, asc + desc + 8)), (0, 0, 0, 0))
    d = ImageDraw.Draw(tile)
    x = 4
    for ch, wd in zip(txt, widths):
        d.text((x, 4 - box[1]), ch, font=font, fill=fill)
        x += wd + tracking
    return tile


def wrap_phrase(draw: ImageDraw.ImageDraw, phrase: str, font, max_w: int) -> list[str]:
    words = phrase.split()
    lines, cur = [], ""
    for wd in words:
        trial = (cur + " " + wd).strip()
        if draw.textlength(trial, font=font) <= max_w or not cur:
            cur = trial
        else:
            lines.append(cur)
            cur = wd
    if cur:
        lines.append(cur)
    return lines[:3]


# ---------------------------------------------------------------- demo audio
def build_demo_beat(path: str = DEMO_WAV, seconds: float = 6.0, sr: int = 44100) -> str:
    """Synthesize a short original beat (kick + hats + bass tone) β€” no copyrighted audio."""
    if os.path.exists(path):
        return path
    n = int(seconds * sr)
    t = np.arange(n) / sr
    out = np.zeros(n, dtype=np.float64)

    bpm = 100.0
    beat = 60.0 / bpm
    kick_times = np.arange(0.0, seconds, beat / 2.0)
    for i, kt in enumerate(kick_times):
        accented = (i % 2 == 0)
        env = np.exp(-np.arange(int(0.22 * sr)) / (0.045 * sr))
        f = 120.0 * np.exp(-np.arange(int(0.22 * sr)) / (0.02 * sr)) + 45.0
        tone = np.sin(2 * np.pi * np.cumsum(f) / sr) * env
        s = int(kt * sr)
        amp = 0.85 if accented else 0.45
        out[s:s + tone.size] += amp * tone[: max(0, n - s)]

    hat_times = np.arange(0.0, seconds, beat / 4.0)
    rng = np.random.default_rng(7)
    for ht in hat_times:
        env = np.exp(-np.arange(int(0.05 * sr)) / (0.008 * sr))
        noise = rng.standard_normal(env.size) * env
        s = int(ht * sr)
        out[s:s + noise.size] += 0.12 * noise[: max(0, n - s)]

    bass_notes = [(55.0, 4), (73.42, 2), (65.41, 2), (49.0, 4)]
    idx = 0
    for freq, beats in bass_notes:
        dur = beats * beat
        seg_n = int(dur * sr)
        if seg_n <= 0 or idx >= n:
            continue
        seg_n = min(seg_n, n - idx)
        tt = np.arange(seg_n) / sr
        env = np.minimum(1.0, tt / 0.01) * np.exp(-tt / (dur * 0.9))
        seg = (np.sin(2 * np.pi * freq * tt) * 0.5
               + np.sin(2 * np.pi * freq * 2 * tt) * 0.18) * env
        out[idx:idx + seg_n] += 0.35 * seg
        idx += seg_n

    peak = float(np.max(np.abs(out))) or 1.0
    out = (out / peak * 0.92).astype(np.float32)
    stereo = np.stack([out, out], axis=1)
    sf.write(path, stereo, sr, subtype="PCM_16")
    return path


# ---------------------------------------------------------------- analysis
def analyze(wav_path: str, fps: int = FPS, n_bars: int = N_BARS):
    """Return per-frame RMS, onset, and log-spaced spectrum bands from the real audio."""
    data, sr = sf.read(wav_path, always_2d=True, dtype="float32")
    mono = data.mean(axis=1)
    hop = max(1, int(sr / fps))
    n_frames = max(1, len(mono) // hop)
    mono = mono[: n_frames * hop]
    frames = mono.reshape(n_frames, hop)

    rms = np.sqrt(np.mean(frames ** 2, axis=1) + 1e-12)
    rms_n = rms / max(1e-9, float(rms.max()))
    onset = np.diff(np.concatenate([[0.0], rms_n]))
    onset = np.clip(onset, 0.0, None)
    onset = onset / max(1e-9, float(onset.max()))

    win = np.hanning(hop).astype(np.float32)
    spec = np.abs(np.fft.rfft(frames * win, axis=1))
    nfreq = spec.shape[1]
    freq = np.fft.rfftfreq(hop, 1.0 / sr)
    useful = max(1, int(np.searchsorted(freq, 8000.0)))
    edges = np.unique(
        np.round(np.geomspace(1, useful, n_bars + 1)).astype(int)
    )
    bands = np.zeros((n_frames, n_bars), dtype=np.float32)
    for i in range(min(n_bars, len(edges) - 1)):
        a, b = edges[i], max(edges[i] + 1, edges[i + 1])
        bands[:, i] = spec[:, a:b].mean(axis=1)
    bands = np.log1p(bands)
    # per-band normalization over the clip so every band participates visually
    col_max = np.maximum(bands.max(axis=0, keepdims=True), 1e-6)
    bands = np.clip(bands / col_max, 0.0, 1.0)
    bands = 0.12 + 0.88 * bands          # keep a visible floor at every bar
    return rms_n.astype(np.float32), onset.astype(np.float32), bands.astype(np.float32), sr


# ---------------------------------------------------------------- frames
def _lerp(a, b, t):
    return a + (b - a) * t


def _make_background(e: float, intensity: float, chrome: dict) -> Image.Image:
    """One composited background layer: forge black, breathing hairline grid, soft gold disc, chrome."""
    img = Image.new("RGB", (W, H), FORGE_BLACK)
    d = ImageDraw.Draw(img, "RGBA")
    grid_a = int(255 * (0.10 + 0.30 * e))
    for gy in range(0, H + 1, 60):
        d.line([(0, gy), (W, gy)], fill=(42, 36, 24, grid_a))
    for gx in range(0, W + 1, 80):
        d.line([(gx, 0), (gx, H)], fill=(42, 36, 24, grid_a))
    glow_r = int(190 + 130 * e * intensity)
    for i in range(6):
        rr = int(glow_r * (1 - i / 7))
        d.ellipse([W // 2 - rr, TYPE_CY - int(rr * 0.42), W // 2 + rr, TYPE_CY + int(rr * 0.42)],
                  fill=(212, 168, 67, int(8 + 11 * e)))
    d.rectangle([30, 30, W - 30, H - 30], outline=HAIRLINE, width=2)
    d.text((60, 46), "W A V E F O R G E", font=chrome["label"], fill=GOLD)
    d.line([(60, 78), (280, 78)], fill=GOLD_MUTED, width=2)
    d.text((60, H - 52), "forge your sound into a picture", font=chrome["tiny"], fill=STONE)
    d.text((W - 60 - chrome["wm_w"], H - 52), "waveforge.net", font=chrome["tiny"], fill=STONE)
    return img


def render_and_encode(work: str, phrase: str, intensity: float, out_path: str, progress=None) -> int:
    """Draw every frame with PIL and stream raw RGB straight into ffmpeg. Returns frame count."""
    ffmpeg = shutil.which("ffmpeg")
    if not ffmpeg:
        raise RuntimeError("ffmpeg not found in PATH β€” the Space needs packages.txt with 'ffmpeg'")

    rms, onset, bands, sr = analyze(os.path.join(work, "audio.wav"))
    n_frames = len(rms)

    base_size = 92 if len(phrase) > 22 else 118
    probe = ImageDraw.Draw(Image.new("RGBA", (1, 1)))
    lines = wrap_phrase(probe, phrase.upper(), load_font(base_size), 1120) if phrase.strip() else []
    tiny = load_font(18)
    chrome = {"label": load_font(20), "tiny": tiny, "wm_w": probe.textlength("waveforge.net", font=tiny)}

    # Cache one composited background per quantized energy level β€” the expensive part, done once.
    LEVELS = 14
    bgs = [_make_background(k / (LEVELS - 1), intensity, chrome) for k in range(LEVELS)]

    cmd = [
        ffmpeg, "-y", "-loglevel", "error",
        "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{W}x{H}", "-framerate", str(FPS), "-i", "-",
        "-i", os.path.join(work, "audio.wav"),
        "-c:v", "libx264", "-preset", "veryfast", "-crf", "20",
        "-pix_fmt", "yuv420p",
        "-c:a", "aac", "-b:a", "192k",
        "-shortest", "-movflags", "+faststart",
        out_path,
    ]
    proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
    try:
        for f in range(n_frames):
            e = float(rms[f])
            on = float(onset[f])
            fade = min(1.0, f / (0.55 * FPS), (n_frames - 1 - f) / (0.55 * FPS) + 1e-9)
            fade = max(0.0, min(1.0, fade))
            amp = min(1.35, (0.35 + 0.65 * intensity) * (0.55 + 0.9 * e) * fade)

            k = int(round(max(0.0, min(1.0, e * fade)) * (LEVELS - 1)))
            img = bgs[k].copy()
            d = ImageDraw.Draw(img, "RGBA")

            # mirrored bar array: spectrum on the bottom half, faint reflection under it
            for b in range(N_BARS):
                v = float(bands[f, b])
                hgt = int(max(2, (v ** 0.80) * BAR_MAX * amp))
                x0 = BAR_X0 + b * (BAR_W + BAR_GAP)
                top = GOLD_LIGHT if hgt > BAR_MAX * 0.72 else GOLD
                d.rectangle([x0, BAR_BASE - hgt, x0 + BAR_W, BAR_BASE], fill=top)
                d.rectangle([x0, BAR_BASE + 3, x0 + BAR_W, BAR_BASE + 3 + int(hgt * 0.34)],
                            fill=(138, 116, 64, int(max(70, min(255, 140 + 115 * v * amp)))))
            d.line([(BAR_X0 - 30, BAR_BASE), (BAR_X0 + BAR_TOTAL + 30, BAR_BASE)], fill=GOLD, width=2)

            # waveform contour under the bars
            pts = [(BAR_X0 + b * (BAR_W + BAR_GAP) + BAR_W / 2,
                    WAVE_Y - (float(bands[f, b]) - 0.32) * 52 * amp) for b in range(N_BARS)]
            d.line(pts, fill=(232, 197, 109, int(120 + 130 * e)), width=2, joint="curve")

            # onset flash rule
            if on > 0.42:
                d.line([(60, 96), (W - 60, 96)], fill=(232, 197, 109, int(70 + 170 * on)), width=2)

            # kinetic type: scales, tracks and drifts with the audio
            if lines:
                size = max(24, int(base_size * (1.0 + 0.12 * intensity * e + 0.035 * on)))
                track = max(1, int(size * 0.07))
                tiles = [render_tracked_text(ln, size, BONE, track) for ln in lines]
                gap = int(size * 0.20)
                total_h = sum(t.height for t in tiles) + gap * (len(tiles) - 1)
                y = TYPE_CY - total_h // 2
                for i, tile in enumerate(tiles):
                    x = (W - tile.width) // 2 + int((e - 0.5) * 30 * intensity) * (1 if i % 2 == 0 else -1)
                    img.paste(tile, (x, y), tile)
                    y += tile.height + gap

            proc.stdin.write(img.tobytes("raw", "RGB"))
            if progress is not None and (f % 10 == 0 or f == n_frames - 1):
                progress(0.15 + (f + 1) / n_frames * 0.70, desc=f"forging frame {f + 1}/{n_frames}")
    finally:
        try:
            proc.stdin.close()
        except Exception:
            pass
    err = proc.stderr.read().decode("utf-8", "replace")
    proc.wait(timeout=300)
    if proc.returncode != 0:
        raise RuntimeError(f"ffmpeg failed ({proc.returncode}): {err[-800:]}")
    return n_frames


# ---------------------------------------------------------------- entrypoint
def forge(audio_path: str | None, phrase: str, intensity: float, progress=gr.Progress()):
    """Forge an uploaded audio clip into a WaveForge visualizer MP4.

    Args:
        audio_path: uploaded audio file (mp3/wav/m4a/ogg) β€” or None to use the bundled demo beat.
        phrase: short phrase or track title rendered as kinetic type.
        intensity: visual intensity, 0.5 (calm) to 2.0 (max).

    Returns:
        Path to a real H.264 MP4 (1280x720, audio muxed in).
    """
    src = audio_path or DEMO_WAV
    src = build_demo_beat() if not os.path.exists(src) else src
    phrase = (phrase or "").strip() or "WAVEFORGE"
    intensity = float(intensity or 1.0)

    work = tempfile.mkdtemp(prefix="forge_")
    progress(0.02, desc="reading the audio")
    ffmpeg = shutil.which("ffmpeg")
    if not ffmpeg:
        raise RuntimeError("ffmpeg missing β€” add packages.txt with 'ffmpeg'")

    # Decode anything (mp3/wav/m4a/ogg) to a trimmed wav: the analysis source AND the muxed track.
    trimmed = os.path.join(work, "audio.wav")
    subprocess.run(
        [ffmpeg, "-y", "-loglevel", "error", "-i", src,
         "-t", str(MAX_SECONDS), "-ar", str(ANALYSIS_SR), "-ac", "2",
         "-c:a", "pcm_s16le", trimmed],
        check=True, capture_output=True, timeout=180,
    )

    out = os.path.join(work, "waveforge_forge.mp4")
    n_frames = render_and_encode(work, phrase, intensity, out, progress=progress)
    progress(0.92, desc="finishing the mp4")
    if not os.path.exists(out) or os.path.getsize(out) < 2000:
        raise RuntimeError("ffmpeg produced no usable video")
    progress(1.0, desc="done")
    return out


build_demo_beat()  # seed the zero-upload demo path at boot

CSS = """
body, .gradio-container { background: #0A0908 !important; }
.gradio-container { color: #F0EDE8; font-family: ui-sans-serif, system-ui, sans-serif; }
#title h1 { color: #D4A843; letter-spacing: .12em; font-weight: 700; margin-bottom: .15em; }
#title p { color: #B7B0A4; margin-top: 0; }
footer { display: none !important; }
"""

with gr.Blocks(title="WaveForge Forge") as demo:
    with gr.Column(elem_id="title"):
        gr.Markdown(
            "# WAVEFORGE FORGE\n"
            "Drop a clip. Get a real MP4. Audio-reactive bars, your phrase in kinetic type, "
            "black and gold. 10 seconds, rendered on CPU in about a minute.\n\n"
            "`waveforge.net`"
        )
    with gr.Row():
        with gr.Column(scale=1):
            audio_in = gr.Audio(
                label="Your audio (mp3 / wav / m4a / ogg) β€” or leave empty for the demo beat",
                type="filepath", sources=["upload", "microphone"],
            )
            phrase_in = gr.Textbox(
                label="Phrase / track title", value="I built this at 2am",
                placeholder="short phrase, 3-6 words works best", max_lines=1,
            )
            intensity_in = gr.Slider(
                0.5, 2.0, value=1.0, step=0.1,
                label="Visual intensity",
            )
            go = gr.Button("FORGE THE VIDEO", variant="primary")
        with gr.Column(scale=1):
            video_out = gr.Video(label="Your visualizer (MP4)", format="mp4", autoplay=True)
        gr.Examples(
            examples=[[DEMO_WAV, "I built this at 2am", 1.2],
                      [DEMO_WAV, "LOUD", 2.0]],
            inputs=[audio_in, phrase_in, intensity_in],
            label="Zero-upload demo",
        )
    gr.Markdown(
        "Built by WaveForge. Every render is real: numpy reads the audio envelope, "
        "PIL draws the frames, ffmpeg encodes H.264. Nothing is mocked.\n\n"
        "[waveforge.net](https://waveforge.net)"
    )
    go.click(forge, [audio_in, phrase_in, intensity_in], video_out, api_name="forge")

if __name__ == "__main__":
    demo.launch(mcp_server=True, css=CSS)