2b-studio / studio /templates.py
2Btainment's picture
2B Studio v2: Toxic-Studio-Redesign, Raum-Leiste, Vorlagen-Bibliothek (30), Verlauf mit Wellenformen, Modell-Status-Chips; Fix MiniMax _studio_state, Paused-Status
d360571 verified
Raw History Blame Contribute Delete
40.2 kB
"""Prompt-Vorlagen-Bibliothek für 2B-Studio.
Eine Vorlage beschreibt Stil, Instrumente, Stimmung, Tempo und Struktur
unabhängig vom Modell. ``render_template`` formatiert sie passend für das
gewählte Modell (MiniMax Structured Caption, ACE-Step-Tags, Stable-Audio-
Kommaliste, AudioLDM-Satz, MusicGen-Beschreibung) und erzeugt bei Bedarf
Lyrics mit den richtigen Sektions-Tags.
Reine Python-Logik ohne Gradio – testbar und vom UI unabhängig.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any
# ---------------------------------------------------------------------------
# Vokabular: deutsche UI-Labels → englische Prompt-Phrasen
# ---------------------------------------------------------------------------
MOODS: dict[str, str] = {
"Euphorisch": "euphoric, uplifting",
"Fröhlich": "happy, bright",
"Entspannt": "relaxed, laid-back",
"Verträumt": "dreamy, floating",
"Melancholisch": "melancholic, bittersweet",
"Nostalgisch": "nostalgic, vintage",
"Romantisch": "romantic, warm",
"Hypnotisch": "hypnotic, driving",
"Spannend": "tense, suspenseful",
"Düster": "dark, ominous",
"Aggressiv": "aggressive, high-energy",
"Episch": "epic, heroic",
"Mystisch": "mystical, ethereal",
"Toxisch / Alien": "alien, toxic, otherworldly",
"Neutral": "neutral, unobtrusive",
}
# Stimmungsfamilie steuert die Lyrics-Bausteine
MOOD_FAMILY: dict[str, str] = {
"Euphorisch": "hell", "Fröhlich": "hell", "Romantisch": "chill",
"Entspannt": "chill", "Verträumt": "chill", "Melancholisch": "chill",
"Nostalgisch": "chill", "Mystisch": "chill", "Neutral": "chill",
"Hypnotisch": "dunkel", "Spannend": "dunkel", "Düster": "dunkel",
"Aggressiv": "dunkel", "Toxisch / Alien": "dunkel", "Episch": "episch",
}
_NOTES_DE = ["C", "Cis", "D", "Es", "E", "F", "Fis", "G", "As", "A", "B", "H"]
_NOTES_EN = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"]
KEY_NONE = "beliebig"
KEYS: list[str] = [KEY_NONE] + [f"{n}-Dur" for n in _NOTES_DE] + [f"{n}-Moll" for n in _NOTES_DE]
_KEY_EN: dict[str, str] = {}
for _de, _en in zip(_NOTES_DE, _NOTES_EN, strict=True):
_KEY_EN[f"{_de}-Dur"] = f"{_en} major"
_KEY_EN[f"{_de}-Moll"] = f"{_en} minor"
VOICES: dict[str, str] = {
"Weiblich": "female lead vocals",
"Männlich": "male lead vocals",
"Duett": "male and female duet vocals",
"Rap": "rap vocals, rhythmic flow",
"Chor": "group chant and choir vocals",
"Vokalisen": "wordless vocal textures",
}
LANGUAGES: dict[str, str] = {
"Deutsch": "German",
"Englisch": "English",
"Spanisch": "Spanish",
}
CATEGORIES: list[tuple[str, str]] = [
("Alle", "all"),
("★ Favoriten", "fav"),
("Einsatz", "usecase"),
("Genres", "genre"),
("Sound-FX", "fx"),
("Eigene", "custom"),
]
CATEGORY_LABEL = {"usecase": "Einsatz", "genre": "Genre", "fx": "Sound-FX", "custom": "Eigene"}
# Modellfamilien → wie der Prompt formatiert wird
MODEL_FAMILY: dict[str, str] = {
"minimax-music3": "minimax",
"ace-step": "acestep",
"stable-audio-open": "stableaudio",
"audioldm2": "audioldm",
"2b-musicgen-small": "musicgen",
"2b-musicgen-medium": "musicgen",
}
FAMILY_LABEL = {
"minimax": "MiniMax · Structured Caption + Lyrics-Tags",
"acestep": "ACE-Step · Tag-Liste + [verse]/[chorus]",
"stableaudio": "Stable Audio · Kommaliste mit BPM",
"audioldm": "AudioLDM 2 · beschreibender Satz",
"musicgen": "MusicGen · Beschreibung mit Tempo & Tonart",
}
VOCAL_FAMILIES = {"minimax", "acestep"}
@dataclass(frozen=True)
class PromptTemplate:
id: str
name: str
category: str # usecase | genre | fx
icon: str
description: str
style: str
instruments: str
mood: str
bpm: int
key: str
duration_s: int
production: str
negative: str
vocals: bool = False
voice: str = "Weiblich"
structure: tuple[str, ...] = ("Intro", "Verse", "Chorus", "Verse", "Chorus", "Bridge", "Chorus", "Outro")
progression: str = "focused opening, developed middle, resolved ending"
models: tuple[str, ...] = ()
tags: tuple[str, ...] = ()
hook: dict[str, str] = field(default_factory=dict) # Sprache → Hook mit {title}
_SONG = ("Intro", "Verse", "Chorus", "Verse", "Chorus", "Bridge", "Chorus", "Outro")
_SHORT = ("Intro", "Verse", "Chorus", "Outro")
_INSTR = ("Intro", "Inst", "Outro")
TEMPLATES: list[PromptTemplate] = [
# ------------------------------------------------------------- Einsatz
PromptTemplate(
"intro", "Intro / Opener", "usecase", "🎬",
"Kurzer Opener für Videos, Streams und Podcasts – baut Spannung auf und endet auf einem Hit.",
"short punchy intro sting, logo reveal build-up", "riser, impact hit, sub boom, synth stabs",
"Spannend", 120, "D-Moll", 8, "tight, loud, clean master, ends on a hard hit",
"long fade-in, vocals, muddy low end, weak ending", structure=("Intro", "Outro"),
progression="instant tension, fast build, final hit", models=("stable-audio-open", "2b-musicgen-medium", "minimax-music3"),
tags=("opener", "logo", "video"),
),
PromptTemplate(
"jingle", "Jingle / Sound-Logo", "usecase", "🔔",
"Ohrwurm mit deinem Namen im Hook – Titel/Marke ausfüllen, er wird gesungen.",
"catchy radio jingle, memorable sonic logo", "bright piano, claps, punchy bass, glockenspiel",
"Fröhlich", 112, "C-Dur", 15, "radio-ready, bright, punchy, instantly memorable",
"dark mood, dissonance, long intro, mumbled vocals", vocals=True, voice="Chor",
structure=("Intro", "Hook", "Outro"), progression="instant hook, repeat, button ending",
models=("minimax-music3", "ace-step"), tags=("werbung", "radio", "marke"),
hook={
"Deutsch": "{title}, {title} –\nso klingt dein Tag!\n{title}!",
"Englisch": "{title}, {title} –\nthat's how your day should sound!\n{title}!",
"Spanisch": "{title}, {title} –\n¡así suena tu día!\n¡{title}!",
},
),
PromptTemplate(
"podcast-bed", "Podcast-Bett", "usecase", "🎙️",
"Dezentes Musikbett unter Sprache – lässt Platz für die Stimme, keine Brüche, loopfähig.",
"unobtrusive background music bed for spoken word", "soft electric piano, light percussion, warm bass",
"Entspannt", 90, "F-Dur", 60, "low dynamics, sparse mid-range to leave room for voice, steady and loop-friendly",
"vocals, loud drums, busy melodies, sudden changes, harsh highs", structure=_INSTR,
progression="steady, even energy from start to end", models=("stable-audio-open", "minimax-music3", "2b-musicgen-medium"),
tags=("podcast", "sprache", "hintergrund"),
),
PromptTemplate(
"trailer", "Trailer / Epic Build", "usecase", "🎞️",
"Drei-Akt-Steigerung mit Taikos, Bläsern und Braams – für Trailer, Teaser und Reveals.",
"epic cinematic trailer music, hybrid orchestral", "taiko drums, brass stabs, staccato strings, braams, risers",
"Episch", 100, "D-Moll", 60, "huge dynamic build in three acts, wide stereo, massive low end",
"lo-fi, thin sound, abrupt ending, cheesy synths", structure=("Intro", "Build", "Climax", "Outro"),
progression="quiet tension, rising second act, massive climax, final hit", models=("minimax-music3", "ace-step", "stable-audio-open"),
tags=("film", "teaser", "orchester"),
),
PromptTemplate(
"werbespot", "Werbespot", "usecase", "📺",
"Positiv, modern, auf den Punkt – Hintergrund für 15- bis 30-Sekunden-Spots.",
"upbeat modern commercial music, feel-good", "acoustic guitar, claps, ukulele, bright synth",
"Fröhlich", 118, "G-Dur", 30, "polished, energetic, clean and broadcast-ready",
"dark mood, distortion, vocals, long intro", structure=_INSTR,
progression="immediate energy, lift at the end", models=("stable-audio-open", "minimax-music3", "2b-musicgen-medium"),
tags=("werbung", "spot", "social"),
),
PromptTemplate(
"outro", "YouTube-Outro", "usecase", "👋",
"Entspannter Abspann für Endscreens – weich, warm, mit sauberem Ausklang.",
"chill outro music for an end screen", "lo-fi drums, warm keys, round bass",
"Entspannt", 85, "A-Moll", 20, "warm, soft, gentle fade at the end",
"vocals, abrupt ending, harsh highs", structure=_INSTR, progression="calm, steady, soft ending",
models=("stable-audio-open", "2b-musicgen-small", "minimax-music3"), tags=("youtube", "abspann"),
),
PromptTemplate(
"game-loop", "Game-Loop", "usecase", "🎮",
"Nahtlos loopbare Spielmusik ohne Intro und Outro – gleichbleibende Energie.",
"seamless looping video game background music", "chiptune lead, synth arpeggio, punchy drums, bass",
"Fröhlich", 140, "E-Moll", 30, "loopable, consistent energy, no intro or outro",
"fade in, fade out, vocals, long silence", structure=("Inst",), progression="constant energy, seamless loop",
models=("stable-audio-open", "2b-musicgen-medium"), tags=("game", "loop", "8-bit"),
),
PromptTemplate(
"meditation", "Meditation / Fokus", "usecase", "🧘",
"Langsame Klangflächen ohne Rhythmus – für Fokus, Yoga und Einschlafen.",
"ambient meditation soundscape", "soft pads, singing bowls, gentle drones",
"Verträumt", 60, KEY_NONE, 120, "slowly evolving, very soft dynamics, no percussion",
"drums, sudden changes, vocals, harsh highs", structure=_INSTR,
progression="breathing, slowly evolving, no peaks", models=("stable-audio-open", "minimax-music3", "ace-step"),
tags=("ruhe", "yoga", "fokus"),
),
# ------------------------------------------------------------- Genres
PromptTemplate(
"lofi", "Lo-Fi Beats", "genre", "☕",
"Staubige Drums, Vinyl-Knistern und jazzige Akkorde – zum Lernen und Entspannen.",
"lo-fi hip hop beat, chillhop", "dusty drums, vinyl crackle, jazzy rhodes, mellow bass",
"Entspannt", 82, "F-Dur", 60, "warm tape saturation, swung drums, soft lowpass",
"harsh highs, clean digital sound, vocals", structure=_INSTR,
models=("stable-audio-open", "2b-musicgen-medium", "minimax-music3"), tags=("chill", "study", "beats"),
),
PromptTemplate(
"techno", "Techno", "genre", "🔊",
"Treibender Peak-Time-Techno mit 909-Kick und Acid-Linie.",
"driving peak-time techno", "punchy 909 kick, rumbling bass, acid 303 line, crisp hats",
"Hypnotisch", 132, "A-Moll", 90, "big-room, hypnotic groove, tight controlled low end",
"pop vocals, acoustic instruments, weak kick, muddy low end", structure=("Intro", "Build", "Drop", "Break", "Drop", "Outro"),
progression="hypnotic build, peak drop, breakdown, second peak", models=("stable-audio-open", "minimax-music3", "2b-musicgen-medium"),
tags=("club", "rave", "acid"),
),
PromptTemplate(
"boom-bap", "Hip-Hop / Boom-Bap", "genre", "🎤",
"Klassischer Boom-Bap mit Sample-Chops und Rap – Lyrics werden passend vorbereitet.",
"boom bap hip hop beat", "punchy drums, vinyl sample chops, deep bass, scratches",
"Nostalgisch", 90, "C-Moll", 120, "gritty, punchy, head-nod groove",
"weak drums, pop vocals, overcompressed", vocals=True, voice="Rap",
structure=("Intro", "Verse", "Hook", "Verse", "Hook", "Outro"), models=("minimax-music3", "ace-step"),
tags=("rap", "90s", "beats"),
),
PromptTemplate(
"trap", "Trap", "genre", "💎",
"Dunkler moderner Trap mit 808, schnellen Hi-Hats und Glocken.",
"dark modern trap", "808 bass, rapid hi-hats, dark bells, synth pads",
"Düster", 140, "Fis-Moll", 90, "hard-hitting 808, crisp hats, wide dark atmosphere",
"weak 808, muddy mix, acoustic guitar", vocals=True, voice="Rap",
structure=("Intro", "Hook", "Verse", "Hook", "Outro"), models=("minimax-music3", "ace-step"),
tags=("rap", "808", "dark"),
),
PromptTemplate(
"ambient", "Ambient", "genre", "🌌",
"Atmosphärische Klanglandschaft aus Flächen und granularen Texturen.",
"atmospheric ambient soundscape", "evolving pads, granular textures, soft piano",
"Verträumt", 70, KEY_NONE, 90, "wide, airy, slowly evolving, deep reverb",
"drums, vocals, harsh transients", structure=_INSTR, progression="floating, slowly evolving",
models=("stable-audio-open", "minimax-music3", "audioldm2"), tags=("atmo", "flächen"),
),
PromptTemplate(
"cinematic", "Cinematic / Score", "genre", "🎻",
"Emotionale Filmmusik mit Streichern, Hörnern und Klavier.",
"emotional cinematic film score", "strings, french horns, piano, choir pads",
"Melancholisch", 80, "D-Moll", 90, "rich orchestral depth, wide dynamics, emotional arc",
"cheap synth strings, thin sound, abrupt transitions", structure=("Intro", "Theme", "Build", "Climax", "Outro"),
progression="intimate opening, swelling theme, emotional climax, quiet resolution",
models=("minimax-music3", "ace-step", "stable-audio-open"), tags=("film", "orchester", "score"),
),
PromptTemplate(
"house", "Deep House", "genre", "🪩",
"Warmer Deep-House-Groove mit rollender Bassline.",
"deep house groove", "four-on-the-floor kick, warm chords, rolling bassline, shakers",
"Euphorisch", 124, "A-Moll", 90, "warm, groovy, club-ready, smooth low end",
"harsh distortion, weak kick, muddy bass", structure=("Intro", "Groove", "Break", "Groove", "Outro"),
models=("stable-audio-open", "minimax-music3", "2b-musicgen-medium"), tags=("club", "groove"),
),
PromptTemplate(
"dnb", "Drum & Bass", "genre", "⚡",
"Liquid Drum & Bass mit schnellen Breaks und Reese-Bass.",
"liquid drum and bass", "fast breakbeats, reese bass, atmospheric pads, soft piano",
"Euphorisch", 174, "F-Moll", 90, "energetic, crisp breaks, deep sub",
"slow tempo, muddy breaks, weak sub", structure=("Intro", "Build", "Drop", "Break", "Drop", "Outro"),
models=("stable-audio-open", "minimax-music3"), tags=("dnb", "breaks", "liquid"),
),
PromptTemplate(
"synthwave", "Synthwave", "genre", "🌆",
"80er-Retro mit Gated Drums, Analog-Bass und Arpeggios.",
"80s retro synthwave", "gated drums, analog synth bass, lush pads, arpeggios",
"Nostalgisch", 100, "E-Moll", 90, "glossy, wide, vintage analog warmth",
"modern trap hats, lo-fi crackle, thin synths", structure=_SHORT,
models=("minimax-music3", "stable-audio-open"), tags=("retro", "80s", "outrun"),
),
PromptTemplate(
"pop", "Pop-Song", "genre", "🎶",
"Radiotauglicher Pop-Song mit Strophe, Refrain und Bridge – Lyrics inklusive.",
"modern radio pop song", "punchy drums, synth bass, bright synths, guitar",
"Euphorisch", 118, "G-Dur", 150, "radio-ready, polished, catchy chorus lift",
"muddy mix, buried vocals, harsh sibilance", vocals=True, voice="Weiblich", structure=_SONG,
models=("minimax-music3", "ace-step"), tags=("radio", "song", "hook"),
),
PromptTemplate(
"rock", "Alternative Rock", "genre", "🎸",
"Energiegeladener Rock mit verzerrten Gitarren und Live-Drums.",
"energetic alternative rock", "distorted guitars, live drums, bass guitar",
"Aggressiv", 140, "E-Moll", 150, "raw, powerful, wide guitars, punchy drums",
"thin guitars, programmed drums, muddy mix", vocals=True, voice="Männlich", structure=_SONG,
models=("minimax-music3", "ace-step"), tags=("band", "gitarre"),
),
PromptTemplate(
"afro-house", "Afro House", "genre", "🥁",
"Organische Percussion, Log Drums und Chants – hypnotisch und warm.",
"afro house groove", "organic percussion, log drums, deep bass, chants",
"Hypnotisch", 122, "A-Moll", 120, "warm, rolling, hypnotic percussion layers",
"harsh synths, weak groove, muddy low end", vocals=True, voice="Chor",
structure=("Intro", "Groove", "Hook", "Groove", "Outro"), models=("minimax-music3", "ace-step", "stable-audio-open"),
tags=("club", "percussion"),
),
PromptTemplate(
"dark-riddim", "Dark Riddim", "genre", "☣️",
"Halbtempo-Bassmusik mit Wobble-Bass und metallischem Sounddesign.",
"dark riddim dubstep", "wobble bass, heavy sub, sparse drums, metallic fx",
"Toxisch / Alien", 140, "F-Moll", 60, "massive low end, aggressive sound design, half-time groove",
"weak sub, happy melodies, acoustic instruments", structure=("Intro", "Build", "Drop", "Break", "Drop"),
models=("stable-audio-open", "minimax-music3"), tags=("bass", "dubstep"),
),
PromptTemplate(
"jazz-lounge", "Jazz Lounge", "genre", "🎷",
"Smoother Lounge-Jazz mit Kontrabass, Besen und Saxofon.",
"smooth jazz lounge", "upright bass, brushed drums, saxophone, piano",
"Entspannt", 95, "Es-Dur", 90, "warm, intimate, live room feel",
"electronic drums, distortion, harsh highs", structure=_INSTR,
models=("minimax-music3", "stable-audio-open", "2b-musicgen-medium"), tags=("bar", "lounge"),
),
PromptTemplate(
"neo-soul", "Neo Soul / R&B", "genre", "💜",
"Laid-back Neo Soul mit Rhodes, Live-Bass und gefühlvollem Gesang.",
"neo soul r&b", "rhodes, live bass, laid-back drums, guitar licks",
"Romantisch", 78, "Es-Dur", 120, "warm, intimate, human timing",
"harsh highs, quantized stiff drums, buried vocals", vocals=True, voice="Weiblich", structure=_SHORT,
models=("minimax-music3", "ace-step"), tags=("soul", "rnb"),
),
PromptTemplate(
"toxic-club", "Toxic Alien Club", "genre", "👽",
"Die 2B-Signatur: säuregrüner Alien-Club mit Acid, Glitches und Sub-Bass.",
"alien toxic club track, futuristic bass music", "acid synth, glitchy percussion, granular vocal chops, sub bass",
"Toxisch / Alien", 128, "Fis-Moll", 60, "wide, glitchy, bioluminescent sound design, heavy sub",
"acoustic instruments, happy pop, muddy low end", structure=("Intro", "Build", "Drop", "Break", "Drop", "Outro"),
models=("stable-audio-open", "minimax-music3"), tags=("2b", "acid", "alien"),
),
# ------------------------------------------------------------- Sound-FX
PromptTemplate(
"whoosh", "Whoosh / Transition", "fx", "💨",
"Schneller Luftzug für Schnitte und Übergänge.",
"fast whoosh transition sound effect", "airy swoosh, filtered noise sweep",
"Neutral", 0, KEY_NONE, 3, "clean, isolated, no music",
"music, melody, drums, vocals", structure=(), models=("stable-audio-open", "audioldm2"), tags=("schnitt", "video"),
),
PromptTemplate(
"riser", "Riser / Build-up", "fx", "📈",
"Spannungsaufbau vor dem Drop oder Reveal.",
"tension riser sound effect", "white noise sweep, rising synth, reverse cymbal",
"Spannend", 0, KEY_NONE, 6, "clean, isolated, steadily rising",
"drums, vocals, melody", structure=(), models=("stable-audio-open", "audioldm2"), tags=("build", "drop"),
),
PromptTemplate(
"impact", "Impact / Hit", "fx", "💥",
"Wuchtiger Einschlag mit Sub-Boom und Hallfahne.",
"cinematic impact hit sound effect", "sub boom, metallic hit, long reverb tail",
"Episch", 0, KEY_NONE, 4, "huge, clean, isolated",
"music, melody, vocals", structure=(), models=("stable-audio-open", "audioldm2"), tags=("trailer", "hit"),
),
PromptTemplate(
"ui-sounds", "UI-Sounds", "fx", "🖱️",
"Kurze Klicks, Glocken und Benachrichtigungen für Apps.",
"short user interface sound effects, notification chime", "clean bells, soft clicks, digital blips",
"Fröhlich", 0, KEY_NONE, 3, "clean, short, isolated, no reverb tail",
"music, drums, vocals, noise", structure=(), models=("stable-audio-open", "audioldm2"), tags=("app", "ux"),
),
PromptTemplate(
"atmo", "Atmo / Field Recording", "fx", "🌧️",
"Regen auf Beton, ferner Verkehr, Stadtbrummen – urbane Atmosphäre.",
"ambient urban field recording", "rain on concrete, distant traffic, city hum",
"Neutral", 0, KEY_NONE, 20, "realistic, immersive stereo, no music",
"music, melody, vocals", structure=(), models=("audioldm2", "stable-audio-open"), tags=("stadt", "regen"),
),
PromptTemplate(
"scifi", "Sci-Fi FX", "fx", "🛸",
"Laser, elektrisches Brummen und Glitches – Alien-Technologie.",
"sci-fi sound effects, alien technology", "laser zaps, electric hum, glitch bursts",
"Toxisch / Alien", 0, KEY_NONE, 8, "futuristic, clean, isolated",
"music, vocals", structure=(), models=("audioldm2", "stable-audio-open"), tags=("alien", "laser"),
),
]
TEMPLATE_BY_ID: dict[str, PromptTemplate] = {t.id: t for t in TEMPLATES}
# ---------------------------------------------------------------------------
# Lyrics-Bausteine je Sprache und Stimmungsfamilie
# ---------------------------------------------------------------------------
LYRIC_BANK: dict[str, dict[str, dict[str, list[str]]]] = {
"Deutsch": {
"hell": {
"verse": ["Die Stadt wacht auf, das Licht wird laut", "Wir laufen los, kein Blick zurück",
"Jeder Schritt ein Herzschlag mehr", "Heute Nacht gehört uns das Glück"],
"chorus": ["Heb die Hände, wir sind hier", "Alles leuchtet, alles wir",
"Kein Morgen, nur das Jetzt", "Wir tanzen bis zum letzten Takt"],
"bridge": ["Und wenn die Lichter ausgehen", "bleiben wir trotzdem stehen"],
},
"dunkel": {
"verse": ["Beton und Regen, grünes Licht", "Die Straße kennt mein Gesicht",
"Signale summen durch die Nacht", "Etwas ist in mir erwacht"],
"chorus": ["Gift im Bass, Strom im Blut", "Wir sind die Nacht, wir sind die Glut",
"Kein Zurück, nur nach vorn", "Aus dem Schatten neu geboren"],
"bridge": ["Hörst du das Rauschen unter der Stadt", "Es ruft uns, bis es uns hat"],
},
"chill": {
"verse": ["Langsam fällt der Tag ins Meer", "Die Gedanken werden leer",
"Kaffee kalt und Fenster auf", "Die Zeit nimmt ihren Lauf"],
"chorus": ["Bleib noch hier, nur einen Moment", "Wo das Licht so weich brennt",
"Nichts muss heut perfekt sein", "Wir zwei und der Abendschein"],
"bridge": ["Atme ein, atme aus", "irgendwann sind wir zu Haus"],
},
"episch": {
"verse": ["Aus der Asche steigen wir", "Tausend Stimmen, eine hier",
"Über Berge, durch den Sturm", "Wir bauen unseren eigenen Turm"],
"chorus": ["Steht auf, die Welt gehört uns", "Ein Feuer, das nie verglüht",
"Wir sind mehr als nur ein Traum", "Wir sind das Licht im Raum"],
"bridge": ["Wenn alles fällt, bleiben wir stehen", "und sehen die Sonne aufgehen"],
},
},
"Englisch": {
"hell": {
"verse": ["City lights are calling out", "We don't need to wait around",
"Every heartbeat turning loud", "Tonight we own the crowd"],
"chorus": ["Hands up, we're alive", "Burning brighter than the sky",
"No tomorrow, only now", "Dance until the lights go down"],
"bridge": ["When the music fades away", "we'll still have tonight to stay"],
},
"dunkel": {
"verse": ["Concrete rain and neon green", "Shadows move where I have been",
"Static humming through the wire", "Something wakes and feeds the fire"],
"chorus": ["Poison bass and electric blood", "We are the night, we are the flood",
"No way back, just straight ahead", "Born again from what we shed"],
"bridge": ["Can you hear it underground", "calling till we're lost and found"],
},
"chill": {
"verse": ["Slowly sinks the afternoon", "Coffee cold and half a tune",
"Windows open, thoughts run free", "Time is moving gently"],
"chorus": ["Stay a while, just one more song", "Where the light is soft and long",
"Nothing has to be just right", "You and me and evening light"],
"bridge": ["Breathe in, breathe out", "nothing left to doubt"],
},
"episch": {
"verse": ["From the ashes we will rise", "Thousand voices, fire in our eyes",
"Over mountains, through the storm", "Every scar a brand new form"],
"chorus": ["Stand up, the world is ours", "A fire burning past the stars",
"We are more than just a dream", "We are the light, the endless stream"],
"bridge": ["When it all falls, we remain", "rising through the pouring rain"],
},
},
"Spanisch": {
"hell": {
"verse": ["La ciudad despierta ya", "Nadie nos detendrá",
"Cada paso, un latido más", "Esta noche brillarás"],
"chorus": ["Manos arriba, aquí estamos", "Todo brilla, nos llevamos",
"No hay mañana, solo hoy", "Bailando hasta el final voy"],
"bridge": ["Cuando se apague la luz", "seguiremos yo y tú"],
},
"dunkel": {
"verse": ["Lluvia gris y luz verde", "La calle nunca me pierde",
"Señales en la oscuridad", "Algo despierta de verdad"],
"chorus": ["Veneno en el bajo, corriente en la piel", "La noche es nuestra, la noche es fiel",
"Sin regreso, solo avanzar", "Desde la sombra vuelvo a empezar"],
"bridge": ["¿Oyes el ruido bajo la ciudad?", "Nos llama hasta la eternidad"],
},
"chill": {
"verse": ["Lento cae el atardecer", "Nada más que hacer",
"Café frío, ventana abierta", "La calma está despierta"],
"chorus": ["Quédate un momento más", "Donde la luz es suave y en paz",
"Nada tiene que ser perfecto", "Tú y yo, el cielo abierto"],
"bridge": ["Respira lento, respira hondo", "el mundo gira en el fondo"],
},
"episch": {
"verse": ["De las cenizas volveremos", "Mil voces, un solo fuego",
"Sobre montañas, contra el viento", "Cada herida es un comienzo"],
"chorus": ["Levántate, el mundo es nuestro", "Un fuego eterno en el pecho",
"Somos más que un sueño", "Somos la luz, somos dueños"],
"bridge": ["Si todo cae, seguimos aquí", "viendo el sol volver a salir"],
},
},
}
_VOCALISE = ["Ooh, ooh, ah", "Ah, ah, ooh", "Mm, mm, ah", "Ooh, ah"]
# ---------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------
@dataclass
class TemplateVars:
bpm: int = 0
key: str = KEY_NONE
mood: str = "Neutral"
instruments: str = ""
duration_s: int = 30
vocals: bool = False
voice: str = "Weiblich"
language: str = "Deutsch"
title: str = ""
extra: str = ""
@dataclass
class RenderedPrompt:
genre: str
lyrics: str
negative: str
duration_s: int
instrumental: bool
studio: dict[str, str]
family: str
notes: list[str] = field(default_factory=list)
def as_dict(self) -> dict[str, Any]:
return {
"genre": self.genre, "lyrics": self.lyrics, "negative": self.negative,
"duration_s": self.duration_s, "instrumental": self.instrumental,
"studio": dict(self.studio), "family": self.family, "notes": list(self.notes),
}
def defaults_for(template: PromptTemplate) -> TemplateVars:
return TemplateVars(
bpm=template.bpm, key=template.key, mood=template.mood, instruments=template.instruments,
duration_s=template.duration_s, vocals=template.vocals, voice=template.voice,
language="Deutsch", title="", extra="",
)
def family_for(model_id: str | None) -> str:
return MODEL_FAMILY.get(model_id or "", "musicgen")
def _clean(text: str) -> str:
text = re.sub(r"\s+", " ", text or "").strip()
text = re.sub(r"\s*,\s*,+", ",", text)
return text.strip(" ,")
def _join(*parts: str, sep: str = ", ") -> str:
return _clean(sep.join(p.strip() for p in parts if p and p.strip()))
def _tag(section: str, family: str) -> str:
base = {"Inst": "Inst", "Groove": "Inst", "Theme": "Inst", "Build": "Build", "Drop": "Drop",
"Break": "Break", "Climax": "Inst"}.get(section, section)
if family == "acestep":
return f"[{base.lower()}]"
return f"[{base}]"
def _section_lines(section: str, bank: dict[str, list[str]], voice: str) -> list[str]:
if voice == "Vokalisen":
return _VOCALISE[:2] if section in {"Verse", "Chorus", "Hook", "Bridge"} else []
if section == "Verse":
return bank["verse"]
if section == "Chorus":
return bank["chorus"]
if section == "Hook":
return bank["chorus"][:2] * 2
if section == "Pre-Chorus":
return bank["chorus"][:2]
if section == "Bridge":
return bank["bridge"]
return []
def _song_structure(template: PromptTemplate, duration_s: int) -> tuple[str, ...]:
structure = template.structure or ("Intro", "Verse", "Chorus", "Outro")
if not any(s in {"Verse", "Chorus", "Hook", "Bridge"} for s in structure):
structure = ("Intro", "Verse", "Chorus", "Outro")
if duration_s < 25:
return ("Hook",) if "Hook" in structure else ("Chorus",)
if duration_s < 60:
core = [s for s in structure if s in {"Intro", "Verse", "Hook", "Chorus", "Outro"}]
seen: list[str] = []
for s in core:
if s in {"Verse", "Chorus", "Hook"} and s in seen:
continue
seen.append(s)
return tuple(seen)
return structure
def build_lyrics(template: PromptTemplate, tv: TemplateVars, family: str, duration_s: int) -> str:
lang = tv.language if tv.language in LYRIC_BANK else "Deutsch"
title = tv.title.strip()
if template.hook and title and tv.voice != "Vokalisen":
hook = template.hook.get(lang) or template.hook.get("Englisch", "")
body = hook.format(title=title)
parts = []
for section in template.structure or ("Hook",):
if section == "Hook":
parts.append(f"{_tag('Hook', family)}\n{body}")
else:
parts.append(_tag(section, family))
return "\n\n".join(parts)
bank = LYRIC_BANK[lang][MOOD_FAMILY.get(tv.mood, "chill")]
blocks: list[str] = []
verse_count = 0
for section in _song_structure(template, duration_s):
lines = list(_section_lines(section, bank, tv.voice))
if section == "Verse":
verse_count += 1
if verse_count % 2 == 0 and lines: # zweite Strophe: Zeilen variieren
lines = lines[2:] + lines[:2]
if section == "Hook" and title and lines:
lines = [title] + lines[1:]
blocks.append("\n".join([_tag(section, family), *lines]))
return "\n\n".join(blocks)
def render_template(
template: PromptTemplate,
model_id: str | None,
tv: TemplateVars,
max_duration_s: int = 600,
) -> RenderedPrompt:
family = family_for(model_id)
notes: list[str] = []
mood_en = MOODS.get(tv.mood, tv.mood or "")
key_en = _KEY_EN.get(tv.key, "") if tv.key and tv.key != KEY_NONE else ""
bpm = int(tv.bpm or 0)
instruments = _clean(tv.instruments or template.instruments)
extra = _clean(tv.extra)
is_fx = template.category == "fx"
duration = int(tv.duration_s or template.duration_s or 30)
duration = max(3, duration)
if duration > max_duration_s:
notes.append(f"Dauer auf {max_duration_s} s gekürzt (Modell-Maximum).")
duration = max_duration_s
if duration < 5:
notes.append("Generator braucht mindestens 5 s – kurze FX danach im Player trimmen.")
duration = 5
wants_vocals = bool(tv.vocals) and not is_fx
vocals_ok = family in VOCAL_FAMILIES
if wants_vocals and not vocals_ok:
notes.append("Dieses Modell singt nicht – Vorlage wird instrumental gerendert. Für Gesang MiniMax oder ACE-Step wählen.")
wants_vocals = False
voice_en = VOICES.get(tv.voice, "lead vocals")
lang_en = LANGUAGES.get(tv.language, "German")
vocal_phrase = (
f"{voice_en}" if tv.voice == "Vokalisen" else f"{voice_en} in {lang_en}"
) if wants_vocals else ""
tempo = f"{bpm} BPM" if bpm and not is_fx else ""
key_phrase = key_en if not is_fx else ""
if family == "minimax":
genre = _join(template.style, mood_en, tempo, key_phrase, instruments, vocal_phrase, template.production, extra)
elif family == "acestep":
tags = [template.style, instruments, mood_en, tempo.lower(), key_phrase, f"{voice_en}" if wants_vocals else "instrumental", extra]
genre = _join(*tags)
elif family == "stableaudio":
genre = _join(template.style, instruments, mood_en, tempo, key_phrase, template.production, extra,
"" if is_fx else "high quality, stereo")
elif family == "audioldm":
article = "An" if (mood_en[:1].lower() in "aeiou") else "A"
lead = f"{article} {mood_en.split(',')[0].strip()} {template.style}" if mood_en else template.style.capitalize()
detail = _join(f"with {instruments}" if instruments else "", f"around {bpm} BPM" if tempo else "",
template.production, extra)
genre = _clean(f"{lead} {detail}".strip()) + ", high quality recording."
else: # musicgen
lead = _join(mood_en.split(",")[0] if mood_en else "", template.style, sep=" ")
at = " ".join(x for x in (f"at {bpm} BPM" if tempo else "", f"in {key_en}" if key_phrase else "") if x)
with_part = f" with {instruments}" if instruments else ""
genre = _clean(f"{lead} {at}{with_part}. {template.production}. {extra}".replace(". .", ".")).rstrip(". ") + "."
negative = template.negative
# Instrumental bei Modellen mit Negativ-Prompt: Gesang explizit ausschließen
if not wants_vocals and not is_fx and family in ("stableaudio", "audioldm") and "vocal" not in negative:
negative = _join(negative, "vocals, singing")
if is_fx and "music" not in negative:
negative = _join(negative, "music")
if wants_vocals:
lyrics = build_lyrics(template, tv, family, duration)
instrumental = False
else:
lyrics = "[Instrumental]"
instrumental = True
studio: dict[str, str] = {}
if family == "minimax":
attrs = _join(template.style, tempo, f"key {key_en}" if key_phrase else "", f"mood {mood_en}" if mood_en else "", sep="; ")
studio = {
"global_metadata": (
f"Basic Attributes: {attrs}. Global Emotional Progression: {template.progression}. "
f"Sonics & Production Profile: {template.production}."
),
"vocal_details": (
f"Vocal Gender & Timbre: {voice_en}, sung in {lang_en}, clear diction, emotionally matched to a {mood_en.split(',')[0] or 'focused'} mood."
if wants_vocals else "Vocal Direction: instrumental, no lead vocals."
),
"arrangement": (
f"Instrument Lifecycle Description: {instruments}. "
f"Structure: {' → '.join(template.structure) or 'single continuous section'}. "
f"Avoid: {negative or 'mud, clipping, haze'}."
),
}
if family == "audioldm" and template.negative:
notes.append("AudioLDM 2 ignoriert den Negativ-Prompt weitgehend – Ausschlüsse eher positiv umschreiben.")
if template.models and model_id and model_id not in template.models:
notes.append("Empfohlen für diese Vorlage: " + ", ".join(template.models) + ".")
return RenderedPrompt(genre, lyrics, negative, duration, instrumental, studio, family, notes)
# ---------------------------------------------------------------------------
# Eigene Vorlagen (im Browser gespeichert) und Filter
# ---------------------------------------------------------------------------
_PLACEHOLDER = re.compile(r"\{(bpm|key|mood|title|instruments)\}")
def render_custom(custom: dict[str, Any], tv: TemplateVars, family: str, max_duration_s: int) -> RenderedPrompt:
"""Eigene Vorlage einsetzen; {bpm} {key} {mood} {title} {instruments} werden ersetzt."""
mapping = {
"bpm": str(tv.bpm or ""), "key": _KEY_EN.get(tv.key, ""), "mood": MOODS.get(tv.mood, tv.mood),
"title": tv.title, "instruments": tv.instruments,
}
def fill(text: str) -> str:
return _PLACEHOLDER.sub(lambda m: mapping.get(m.group(1), ""), text or "")
duration = max(5, min(int(tv.duration_s or custom.get("duration_s") or 30), max_duration_s))
lyrics = fill(str(custom.get("lyrics", "")))
instrumental = bool(custom.get("instrumental")) or lyrics.strip().casefold() in {"", "[instrumental]"}
notes: list[str] = []
if not instrumental and family not in VOCAL_FAMILIES:
notes.append("Dieses Modell singt nicht – Lyrics werden ignoriert.")
return RenderedPrompt(
genre=_clean(fill(str(custom.get("genre", "")))),
lyrics="[Instrumental]" if instrumental else lyrics,
negative=_clean(fill(str(custom.get("negative", "")))),
duration_s=duration, instrumental=instrumental, studio={}, family=family, notes=notes,
)
def make_custom(name: str, genre: str, lyrics: str, negative: str, duration_s: int,
instrumental: bool, model_id: str, stamp: str) -> dict[str, Any]:
clean_name = re.sub(r"\s+", " ", name or "").strip()[:48] or "Eigene Vorlage"
return {
"id": f"custom-{stamp}", "name": clean_name, "icon": "✦", "category": "custom",
"genre": genre or "", "lyrics": lyrics or "", "negative": negative or "",
"duration_s": int(duration_s or 30), "instrumental": bool(instrumental), "model_id": model_id,
}
def _matches(text: str, query: str) -> bool:
q = query.casefold().strip()
return not q or all(part in text.casefold() for part in q.split())
def filter_choices(category: str, query: str, favorites: list[str] | None,
custom: list[dict[str, Any]] | None) -> list[tuple[str, str]]:
favs = set(favorites or [])
out: list[tuple[str, str]] = []
for t in TEMPLATES:
if category == "custom" or (category == "fav" and t.id not in favs):
continue
if category not in {"all", "fav", t.category}:
continue
hay = " ".join([t.name, t.description, t.style, t.instruments, t.mood, *t.tags, CATEGORY_LABEL[t.category]])
if not _matches(hay, query):
continue
star = " ★" if t.id in favs else ""
out.append((f"{t.icon} {t.name}{star}", t.id))
if category in {"all", "custom", "fav"}:
for c in custom or []:
if category == "fav" and c.get("id") not in favs:
continue
if not _matches(f"{c.get('name', '')} {c.get('genre', '')}", query):
continue
star = " ★" if c.get("id") in favs else ""
out.append((f"✦ {c.get('name', 'Eigene Vorlage')}{star}", str(c.get("id"))))
return out
def find_custom(template_id: str | None, custom: list[dict[str, Any]] | None) -> dict[str, Any] | None:
return next((c for c in custom or [] if c.get("id") == template_id), None)