Spaces:
Paused
Paused
Download app.py from JayLL13/tune-studio: direct link, hf CLI and curl.
- Browser
- Download file 17.8 kB
-
https://huggingface.co/spaces/JayLL13/tune-studio/resolve/main/app.py
- Command line
-
hf download hf://spaces/JayLL13/tune-studio/app.py
-
curl -L -o app.py https://huggingface.co/spaces/JayLL13/tune-studio/resolve/main/app.py
17.8 kB
| 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() | |