File size: 17,814 Bytes
ff519d5
b8d9590
9ab4e1d
ff519d5
 
9ab4e1d
 
 
c18f374
9ab4e1d
 
b8d9590
 
9ab4e1d
 
 
 
 
 
 
 
 
0927daf
 
9ab4e1d
b8d9590
 
 
f6054eb
ff519d5
 
 
9ab4e1d
 
afa0891
f6054eb
 
afa0891
 
 
 
 
 
9ab4e1d
f6054eb
 
 
 
9ab4e1d
 
 
 
f6054eb
 
9ab4e1d
 
 
 
b8d9590
 
 
f6054eb
 
b8d9590
f6054eb
 
ff519d5
 
b8d9590
 
f6054eb
 
 
 
ff519d5
 
 
 
f6054eb
b8d9590
 
 
 
 
 
 
 
 
f6054eb
 
 
 
ff519d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ab4e1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6054eb
 
 
ff519d5
f6054eb
b8d9590
 
 
 
 
 
 
ff519d5
b8d9590
 
ff519d5
 
 
b8d9590
 
c18f374
f6054eb
9ab4e1d
 
 
ff519d5
9ab4e1d
f6054eb
9ab4e1d
c18f374
9ab4e1d
f6054eb
9ab4e1d
 
b8d9590
 
 
 
ff519d5
b8d9590
f6054eb
 
 
b8d9590
 
ff519d5
 
 
 
 
 
b8d9590
f6054eb
b8d9590
ff519d5
b8d9590
f6054eb
b8d9590
 
ff519d5
 
f6054eb
ff519d5
f6054eb
 
 
ff519d5
 
 
 
 
 
 
 
 
f6054eb
ff519d5
 
 
f6054eb
ff519d5
 
f6054eb
ff519d5
f6054eb
ff519d5
f6054eb
ff519d5
9ab4e1d
 
afa0891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ab4e1d
f6054eb
9ab4e1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6054eb
 
 
 
 
 
 
 
 
 
 
c18f374
 
 
 
 
 
f6054eb
 
 
 
 
 
 
 
 
 
 
ff519d5
f6054eb
b1a55b1
f6054eb
 
 
 
 
 
 
 
 
 
ff519d5
 
f6054eb
 
 
 
ff519d5
 
 
f6054eb
 
 
 
ff519d5
f6054eb
ff519d5
f6054eb
 
 
 
 
 
 
 
 
 
 
 
 
ff519d5
f6054eb
 
 
 
 
ff519d5
 
 
 
 
 
 
 
 
f6054eb
ff519d5
 
f6054eb
 
 
9ab4e1d
 
f6054eb
 
9ab4e1d
 
f6054eb
 
ff519d5
f6054eb
 
 
9ab4e1d
 
 
ff519d5
 
 
 
 
9ab4e1d
f6054eb
c18f374
f6054eb
9ab4e1d
ff519d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ab4e1d
ff519d5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
419
420
import hashlib
import logging
import random
import tempfile
from pathlib import Path

import gradio as gr

from lyrics import STRUCTURES, HfLyricsWriter, LyricsError, section_tags
from song_engine import render_song

logger = logging.getLogger(__name__)

STYLE_PRESETS = {
    "Pop": "Pop, catchy hook, bright synth, tight drums, female lead vocal",
    "Ballad": "Ballad, emotional, piano, warm strings, male lead vocal",
    "Lo-fi": "Lo-fi hip hop, mellow, warm keys, vinyl crackle, soft female vocal",
    "Rock": "Rock, energetic, electric guitar, live drums, bass, male lead vocal",
    "EDM": "Electronic dance, uplifting, supersaw lead, four-on-the-floor drums, female lead vocal",
    "R&B": "R&B, smooth, soulful, electric piano, groove bass, female lead vocal",
    "Acoustic": "Folk, acoustic guitar, gentle, intimate, male lead vocal",
    "Cinematic": "Cinematic pop, orchestral, epic build, choir, female lead vocal",
    "Anime OP": "Anime opening, J-rock, energetic, fast electric guitar riffs, driving drums, bright synth, "
    "soaring female lead vocal, uplifting, 170 BPM",
}
PLANNING_CHOICES = [("Melody + chords", "full"), ("Melody only", "melody"), ("No score", "off")]
QUALITY_CHOICES = [("Fast · 16 steps", 16), ("Best quality · 32 steps", 32)]
MAX_SEED = 2**31 - 1
RENDER_WAIT = "This usually takes a few minutes."
LYRICS_FILENAME = "lyrics.txt"
SCORE_FILENAME = "abc_score.txt"
DOWNLOAD_DIR = Path(tempfile.gettempdir()) / "tune-studio-downloads"

CSS = """
html, body { background: var(--body-background-fill) !important; color-scheme: light; }
#page { max-width: 1400px; margin: 0 auto; }
.hero { text-align: center; padding-top: 8px; }
#page .hero h1 {
  font-size: 2.1rem; margin-bottom: 2px; font-weight: 800;
  background: linear-gradient(90deg, #14B8A6, #0EA5E9) !important;
  -webkit-background-clip: text !important; background-clip: text !important;
  color: transparent !important;
}
.hero p { opacity: 0.75; margin-top: 0; }
#status { min-height: 1.6em; text-align: center; font-weight: 600; }
.step-title h3 { margin: 0; }
.hint { opacity: 0.7; font-size: 0.88rem; }
#score textarea { font-family: ui-monospace, Consolas, monospace; font-size: 0.85rem; }
"""

HERO_HTML = """
<div class="hero">
  <h1>Tune Studio</h1>
  <p>Type a topic. We write English lyrics, compose a score, and sing it.</p>
</div>
"""

writer = HfLyricsWriter()
KEEP = object()


def keep_or(item):
    return gr.skip() if item is KEEP else item


def results(status, song, *, busy=False, lyrics=KEEP, audio=KEEP, score=KEEP, seed=KEEP):
    """Values for every result component. Actions are disabled while a job runs."""
    action = gr.update(interactive=not busy)
    return (
        status,
        keep_or(lyrics),
        keep_or(audio),
        keep_or(score),
        keep_or(seed),
        gr.update(interactive=not busy, value="New song" if song else "Create song"),
        action,
        action,
        action,
        song,
    )


def pick_seed(seed, randomize: bool) -> int:
    if randomize or seed is None:
        return random.randint(0, MAX_SEED)
    return int(seed)


def chosen_style(style_label: str, custom_style: str) -> str:
    return (custom_style or "").strip() or STYLE_PRESETS[style_label]


def settings_song(style_label, custom_style, cot, steps, seed, randomize) -> dict:
    """Render settings taken from the Idea column."""
    return {
        "style": chosen_style(style_label, custom_style),
        "cot": cot,
        "steps": int(steps),
        "seed": pick_seed(seed, randomize),
    }


def score_song(current: dict | None, settings: dict) -> dict:
    """Settings for rendering on a given score.

    The last song's style and seed are reused so only the edited lyrics or score change; without
    a last song the Idea column settings apply. A supplied score needs melody or full planning.
    """
    base = {key: current[key] for key in ("style", "cot", "steps", "seed")} if current else settings
    return {**base, "cot": base["cot"] if base["cot"] in ("full", "melody") else "full"}


def require_lyrics(lyrics: str) -> str:
    lyrics = (lyrics or "").strip()
    if not lyrics:
        raise gr.Error("Add lyrics in column 2 first, or create a song from a topic.")
    if not section_tags(lyrics):
        raise gr.Error("Lyrics need section tags on their own lines, such as [Verse] and [Chorus].")
    return lyrics


def require_score(score: str) -> str:
    score = (score or "").strip()
    if not score:
        raise gr.Error("Add an ABC score in column 3 first. Songs made with 'No score' have none.")
    return score


def require_token(token: str) -> str:
    token = (token or "").strip()
    if not token:
        raise gr.Error("Add your Hugging Face token in Settings first.")
    return token


def text_download(text: str, filename: str):
    """Point a download button at a file holding `text`, or disable it when there is nothing."""
    text = (text or "").strip()
    if not text:
        return gr.update(value=None, interactive=False)
    folder = DOWNLOAD_DIR / hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
    folder.mkdir(parents=True, exist_ok=True)
    path = folder / filename
    path.write_text(text + "\n", encoding="utf-8")
    return gr.update(value=str(path), interactive=True)


def verify_token(token: str):
    token = (token or "").strip()
    if not token:
        return "Paste your Hugging Face token first.", gr.skip()
    try:
        username = writer.verify(token)
    except LyricsError as exc:
        return str(exc), gr.skip()
    return f"Connected as **{username}**. Saved in this browser.", token


def remove_token():
    return "", "", "Token removed from this browser."


def render(song: dict, success: str):
    """Sing `song` on the GPU and yield the finished result or an error.

    On failure the lyrics stay in column 2, so the song can be retried without rewriting them.
    """
    try:
        audio_path, abc = render_song(
            song["style"], song["lyrics"], song["seed"], song["cot"], song["steps"], song.get("abc")
        )
    except Exception as exc:
        logger.exception("Song rendering failed")
        message = exc.message if isinstance(exc, gr.Error) else "Something went wrong while making the song."
        yield results(f"Could not make the song: {message}", song, audio=None)
        return
    song = {**song, "abc": abc}
    if abc is None:
        success += " This song has no score because it used 'No score' planning."
    yield results(success, song, audio=audio_path, score=abc or "", seed=song["seed"])


def new_song(topic, structure, style_label, custom_style, cot, steps, seed, randomize, token, current):
    """New lyrics, new score and new audio from the topic."""
    topic = (topic or "").strip()
    if len(topic) < 3:
        raise gr.Error("Describe your song in at least 3 characters.")
    token = require_token(token)

    yield results("Step 1 of 2 · Writing lyrics…", current, busy=True)
    try:
        lyrics = writer.write(topic, token, structure)
    except LyricsError as exc:
        yield results(f"Could not write lyrics: {exc}", current)
        return

    song = {
        "topic": topic,
        "lyrics": lyrics,
        "abc": None,
        **settings_song(style_label, custom_style, cot, steps, seed, randomize),
    }
    yield results(f"Step 2 of 2 · Composing and singing. {RENDER_WAIT}", current, busy=True,
                  lyrics=lyrics, audio=None, score="", seed=song["seed"])
    yield from render(song, "Your song is ready.")


def rewrite_lyrics(topic, lyrics, score, direction, style_label, custom_style, cot, steps, seed,
                   randomize, token, current):
    """New words for the lyrics in column 2, sung on the score in column 3."""
    lyrics = require_lyrics(lyrics)
    score = require_score(score)
    token = require_token(token)

    yield results("Step 1 of 2 · Writing new lyrics for the same melody…", current, busy=True)
    try:
        new_lyrics = writer.rewrite((topic or "").strip() or "this song", lyrics, direction or "", token)
    except LyricsError as exc:
        yield results(f"Could not write new lyrics: {exc}", current)
        return

    settings = settings_song(style_label, custom_style, cot, steps, seed, randomize)
    song = {"topic": topic, "lyrics": new_lyrics, "abc": score, **score_song(current, settings)}
    yield results(f"Step 2 of 2 · Singing the new lyrics on the same melody. {RENDER_WAIT}", current,
                  busy=True, lyrics=new_lyrics, audio=None)
    yield from render(song, "New lyrics are ready on the same melody.")


def sing_score(topic, lyrics, score, style_label, custom_style, cot, steps, seed, randomize, current):
    """Sing the lyrics in column 2 on the score in column 3, as they are now."""
    lyrics = require_lyrics(lyrics)
    score = require_score(score)
    settings = settings_song(style_label, custom_style, cot, steps, seed, randomize)
    song = {"topic": topic, "lyrics": lyrics, "abc": score, **score_song(current, settings)}
    yield results(f"Singing your lyrics on this score. {RENDER_WAIT}", current, busy=True, audio=None)
    yield from render(song, "Your lyrics are sung on this score.")


def new_music(topic, lyrics, style_label, custom_style, cot, steps, seed, randomize, current):
    """A new score and audio for the lyrics in column 2, using the Idea column settings."""
    lyrics = require_lyrics(lyrics)
    song = {
        "topic": topic,
        "lyrics": lyrics,
        "abc": None,
        **settings_song(style_label, custom_style, cot, steps, seed, randomize),
    }
    yield results(f"Composing new music for these lyrics. {RENDER_WAIT}", current, busy=True,
                  audio=None, score="", seed=song["seed"])
    yield from render(song, "New music is ready for these lyrics.")


THEME = gr.themes.Soft(
    primary_hue="teal",
    secondary_hue="sky",
    neutral_hue="slate",
    font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
).set(
    button_primary_background_fill="linear-gradient(90deg, #0D9488, #0284C7)",
    button_primary_background_fill_hover="linear-gradient(90deg, #0F766E, #0369A1)",
    button_primary_text_color="white",
)

# The Ocean theme is designed for light mode, so keep it light even when the viewer's system is dark.
FORCE_LIGHT_JS = "() => { document.body.classList.remove('dark'); document.documentElement.classList.remove('dark'); }"

with gr.Blocks(title="Tune Studio", theme=THEME, css=CSS, js=FORCE_LIGHT_JS) as demo:
    token_state = gr.BrowserState("")
    current_song = gr.State(None)

    with gr.Column(elem_id="page"):
        gr.HTML(HERO_HTML)

        with gr.Accordion("Settings: Hugging Face token", open=False):
            token_input = gr.Textbox(
                label="Hugging Face token",
                type="password",
                placeholder="hf_…",
                info="Needs the 'Make calls to Inference Providers' permission. Stored only in this browser.",
            )
            with gr.Row():
                verify_button = gr.Button("Save and verify", variant="secondary")
                remove_button = gr.Button("Remove token", variant="stop")
            settings_status = gr.Markdown()

        status = gr.Markdown(elem_id="status")

        with gr.Row(equal_height=False):
            with gr.Column(variant="panel", min_width=320):
                gr.Markdown("### 1 · Idea", elem_classes="step-title")
                topic_input = gr.Textbox(
                    label="Topic",
                    placeholder="e.g. a rainy night in the city, missing someone who left",
                    lines=3,
                    max_lines=5,
                )
                structure_input = gr.Dropdown(
                    choices=list(STRUCTURES),
                    value=STRUCTURES[0],
                    label="Lyric structure",
                    info="The order of sections the lyrics are written in.",
                )
                style_input = gr.Radio(choices=list(STYLE_PRESETS), value="Pop", label="Style")
                with gr.Accordion("Describe your own style (optional)", open=False):
                    custom_style_input = gr.Textbox(
                        placeholder="e.g. jazz piano, smooth male vocal",
                        show_label=False,
                    )
                with gr.Accordion("Advanced", open=False):
                    planning_input = gr.Radio(
                        choices=PLANNING_CHOICES,
                        value="full",
                        label="Symbolic planning",
                        info="The model writes a score, then sings it. 'No score' skips the score.",
                    )
                    quality_input = gr.Radio(choices=QUALITY_CHOICES, value=32, label="Render quality")
                    with gr.Row():
                        seed_input = gr.Number(value=42, precision=0, minimum=0, maximum=MAX_SEED, label="Seed")
                        randomize_input = gr.Checkbox(value=True, label="New random seed each time")
                create_button = gr.Button("Create song", variant="primary", size="lg")
                gr.Markdown("Writes new lyrics and new music from your topic.", elem_classes="hint")

            with gr.Column(variant="panel", min_width=320):
                gr.Markdown("### 2 · Lyrics", elem_classes="step-title")
                lyrics_output = gr.Textbox(
                    label="Lyrics",
                    placeholder="Type or paste lyrics with section tags on their own lines, "
                    "e.g. [Verse], [Chorus], [Bridge].",
                    lines=16,
                    max_lines=30,
                    show_copy_button=True,
                )
                lyrics_download = gr.DownloadButton(
                    f"Download {LYRICS_FILENAME}", interactive=False, size="sm", variant="secondary"
                )
                direction_input = gr.Textbox(
                    label="What should change? (optional)",
                    placeholder="e.g. more hopeful, mention the ocean",
                )
                rewrite_button = gr.Button("Rewrite lyrics · keep melody")
                gr.Markdown(
                    "AI rewrites these lyrics with the same sections and sings them on the score in column 3.",
                    elem_classes="hint",
                )

            with gr.Column(variant="panel", min_width=320):
                gr.Markdown("### 3 · Music", elem_classes="step-title")
                audio_output = gr.Audio(
                    label="Your song",
                    type="filepath",
                    interactive=False,
                    show_download_button=True,
                )
                score_output = gr.Textbox(
                    label="Score (ABC notation)",
                    placeholder="Paste or edit an ABC score here.",
                    lines=10,
                    max_lines=20,
                    show_copy_button=True,
                    elem_id="score",
                )
                score_download = gr.DownloadButton(
                    f"Download {SCORE_FILENAME}", interactive=False, size="sm", variant="secondary"
                )
                sing_button = gr.Button("Sing with this score")
                gr.Markdown(
                    "Sings the lyrics in column 2 on this score as it is now. Use it after editing either one.",
                    elem_classes="hint",
                )
                music_button = gr.Button("New music · keep lyrics")
                gr.Markdown(
                    "Composes a new score for the lyrics in column 2, using the style and Advanced settings "
                    "in column 1.",
                    elem_classes="hint",
                )

        gr.Markdown(
            "Lyrics: DeepSeek V4.1 Flash via Hugging Face Inference Providers, billed to your account. "
            "Music: YuE2-3B on ZeroGPU. Model weights are CC BY-NC 4.0.",
            elem_classes="hint",
        )

    result_components = [
        status, lyrics_output, audio_output, score_output, seed_input,
        create_button, rewrite_button, sing_button, music_button, current_song,
    ]
    settings_inputs = [style_input, custom_style_input, planning_input, quality_input, seed_input, randomize_input]

    demo.load(lambda saved: saved, token_state, token_input)
    verify_button.click(verify_token, token_input, [settings_status, token_state])
    remove_button.click(remove_token, None, [token_input, token_state, settings_status])
    # Download files follow the text as it changes. They skip the queue so typing never waits on a render.
    lyrics_output.change(lambda text: text_download(text, LYRICS_FILENAME), lyrics_output, lyrics_download,
                         queue=False, show_progress="hidden")
    score_output.change(lambda text: text_download(text, SCORE_FILENAME), score_output, score_download,
                        queue=False, show_progress="hidden")
    create_button.click(
        new_song,
        [topic_input, structure_input, *settings_inputs, token_input, current_song],
        result_components,
    )
    rewrite_button.click(
        rewrite_lyrics,
        [topic_input, lyrics_output, score_output, direction_input, *settings_inputs, token_input, current_song],
        result_components,
    )
    sing_button.click(
        sing_score,
        [topic_input, lyrics_output, score_output, *settings_inputs, current_song],
        result_components,
    )
    music_button.click(
        new_music,
        [topic_input, lyrics_output, *settings_inputs, current_song],
        result_components,
    )

if __name__ == "__main__":
    demo.queue(default_concurrency_limit=1).launch()