Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (4)
- README.md+18-6
- app.pyAdded+417
- packages.txtAdded+2
- requirements.txtAdded+3
12345678910111213---title: Waveforge Forgeemoji: 🏃colorFrom: graycolorTo: indigosdk: gradiosdk_version: 6.30.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425---title: WaveForge Forgeemoji: 🎛️colorFrom: yellowcolorTo: graysdk: gradiosdk_version: 6.30.0app_file: app.pypython_version: "3.12"short_description: Turn an audio clip into a branded visualizer MP4pinned: false---# WaveForge ForgeDrop an audio clip, type a phrase, get a real H.264 MP4 back.- numpy reads the real audio envelope and spectrum (RMS + onset + 72 log-spaced bands)- PIL draws every frame: forge black `#0A0908`, gold `#D4A843`, your phrase in kinetic type- ffmpeg encodes libx264 / yuv420p / `+faststart`, original audio muxed in- CPU-only, 1280x720 @ 30 fps, capped at 10 seconds so a render finishes in secondsNothing is mocked. Every output is a real encoded video.[waveforge.net](https://waveforge.net)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417"""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 functoolsimport mathimport osimport shutilimport subprocessimport tempfile
import gradio as grimport numpy as npimport soundfile as sffrom PIL import Image, ImageDraw, ImageFont
# ---------------------------------------------------------------- brandFORGE_BLACK = "#0A0908"BLACK_2 = "#12100D"GOLD = "#D4A843"GOLD_LIGHT = "#E8C56D"GOLD_MUTED = "#8A7440"STONE = "#6B6560"BONE = "#F0EDE8"HAIRLINE = "#2A2418"
W, H = 1280, 720FPS = 30MAX_SECONDS = 10.0 # hard cap: the demo always stays fastANALYSIS_SR = 44100N_BARS = 72
# --- fixed layout of the 1280x720 frameTYPE_CY = 300 # vertical center of the kinetic type blockBAR_BASE = 540 # baseline of the bar arrayBAR_MAX = 150 # tallest bar, before the energy multiplierWAVE_Y = 622 # baseline of the waveform contourBAR_GAP = 5BAR_W = max(3, int((W - 160 - (N_BARS - 1) * BAR_GAP) / N_BARS))BAR_TOTAL = N_BARS * BAR_W + (N_BARS - 1) * BAR_GAPBAR_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 audiodef 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
# ---------------------------------------------------------------- analysisdef 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
# ---------------------------------------------------------------- framesdef _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
# ---------------------------------------------------------------- entrypointdef 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)12ffmpegfonts-dejavu-core123numpypillowsoundfileREADME.md+18-6
app.pyAdded+417
packages.txtAdded+2
requirements.txtAdded+3