tune-studio / lyrics.py
JayLL13's picture
feat: let users choose the lyric structure
c18f374 verified
Raw History Blame Contribute Delete
6.79 kB
import logging
import re
import httpx
logger = logging.getLogger(__name__)
ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
WHOAMI_URL = "https://huggingface.co/api/whoami-v2"
LYRICS_MODEL = "deepseek-ai/DeepSeek-V4.1-Flash:deepinfra"
# Lyric structures offered in the UI. Each name lists its sections in order.
STRUCTURES = (
"Verse – Chorus – Verse – Chorus – Bridge – Chorus – Outro",
"Verse – Pre-Chorus – Chorus – Verse – Pre-Chorus – Chorus – Bridge – Chorus",
"Intro – Verse – Chorus – Instrumental – Verse – Chorus – Outro",
)
THINK_BLOCK = re.compile(r"<think>.*?</think>", re.DOTALL)
CODE_FENCE = re.compile(r"^```[a-zA-Z]*\s*|\s*```$")
SECTION_TAG = re.compile(r"^\[([A-Za-z -]+?)\s*\d*\]\s*$", re.MULTILINE)
SYSTEM_PROMPT = "You are a professional songwriter. Reply with the song lyrics only."
# Repeated vocables make the sung chorus sound unnatural, so every prompt asks for real words.
NO_FILLER = (
"Do not use filler sounds or looping repeats, such as 'hey hey', 'oh oh', 'la la la', "
"'na na', 'yeah yeah', or the same word or short phrase repeated back to back. "
"Build every chorus hook from meaningful words. "
)
class LyricsError(Exception):
"""The message is written for the end user, so it is safe to show in the UI."""
def clean_lyrics(raw: str) -> str:
"""Strip reasoning blocks and code fences, then check that section tags are present."""
lyrics = THINK_BLOCK.sub("", raw).strip()
lyrics = CODE_FENCE.sub("", lyrics).strip()
if not SECTION_TAG.search(lyrics):
raise LyricsError("The lyrics came back in an unexpected format. Please try again.")
return lyrics
def section_tags(lyrics: str) -> list[str]:
"""Return the section tags in order, normalised so [Verse 1] and [verse] compare equal."""
return [match.group(1).strip().lower() for match in SECTION_TAG.finditer(lyrics)]
def structure_sections(structure: str) -> list[str]:
"""Split a structure name such as "Verse – Chorus" into its section names."""
return [section.strip() for section in structure.split("–")]
def build_messages(topic: str, structure: str = STRUCTURES[0]) -> list[dict]:
sections = structure_sections(structure)
tags = "\n".join(f"[{section}]" for section in sections)
instrumental = (
"Instrumental sections keep their tag but have no lyric lines under them. "
if "Instrumental" in sections
else ""
)
return [
{"role": "system", "content": SYSTEM_PROMPT},
{
"role": "user",
"content": (
f"Write original English song lyrics about: {topic}\n"
"Use these section tags in this exact order, each on its own line, "
"with the lyric lines under each tag:\n"
f"{tags}\n"
"Verses have 4 to 6 short, singable lines. Choruses are catchy and built around one hook line. "
f"{instrumental}{NO_FILLER}"
"No title, no explanation, no markdown."
),
},
]
def build_rewrite_messages(topic: str, original: str, direction: str) -> list[dict]:
"""Ask for new words that fit the melody already written for `original`."""
request = direction.strip() or "Make the lyrics more vivid, specific and memorable."
return [
{"role": "system", "content": SYSTEM_PROMPT},
{
"role": "user",
"content": (
f"These English lyrics about '{topic}' already have a melody:\n\n{original}\n\n"
f"Rewrite them with new words. Direction: {request}\n"
"The new lyrics must fit the same melody, so keep every section tag in the same "
"order, keep the same number of lines in each section, and keep each line close "
"to the syllable count of the line it replaces. "
f"{NO_FILLER}"
"No title, no explanation, no markdown."
),
},
]
def _auth(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
class HfLyricsWriter:
"""Writes lyrics through Hugging Face Inference Providers, using the user's own token."""
def verify(self, token: str) -> str:
"""Return the Hugging Face username that owns the token."""
try:
response = httpx.get(WHOAMI_URL, headers=_auth(token), timeout=20)
except httpx.HTTPError as exc:
raise LyricsError("Could not reach Hugging Face. Check your connection.") from exc
if response.status_code == 401:
raise LyricsError("Hugging Face rejected this token.")
if response.status_code >= 400:
raise LyricsError("Hugging Face could not verify this token. Please try again.")
return response.json()["name"]
def write(self, topic: str, token: str, structure: str = STRUCTURES[0]) -> str:
return self._complete(build_messages(topic, structure), token)
def rewrite(self, topic: str, original: str, direction: str, token: str) -> str:
"""Write new lyrics whose sections follow `original`, so they fit its melody."""
lyrics = self._complete(build_rewrite_messages(topic, original, direction), token)
if section_tags(lyrics) != section_tags(original):
raise LyricsError(
"The new lyrics did not keep the original song structure. Please try again."
)
return lyrics
def _complete(self, messages: list[dict], token: str) -> str:
payload = {
"model": LYRICS_MODEL,
"messages": messages,
"max_tokens": 2500,
"temperature": 0.8,
}
try:
response = httpx.post(ROUTER_URL, headers=_auth(token), json=payload, timeout=120)
except httpx.HTTPError as exc:
raise LyricsError("Could not reach the lyrics service. Please try again.") from exc
if response.status_code == 401:
raise LyricsError("Hugging Face rejected your token. Update it in Settings.")
if response.status_code in (402, 403):
raise LyricsError(
"This token cannot use Inference Providers. Check its permissions and credits."
)
if response.status_code >= 400:
logger.error("Lyrics request failed with HTTP %s", response.status_code)
raise LyricsError("The lyrics service returned an error. Please try again.")
content = response.json()["choices"][0]["message"].get("content") or ""
return clean_lyrics(content)