Commit d6fa0f2f authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Feed library song genre into the remix planning prompt

songs_info already skipped a fresh identify_audio() call for
library-sourced songs (using the already-known title/artist directly),
but dropped genre even though LibrarySong has it. Genre is now threaded
through into plan_remix's Gemini prompt as an explicit hint per song -
one more piece of already-verified metadata informing the arrangement,
on top of the real audio preview and detected BPM/key it already used.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 1049dc75
Pipeline #1124 passed with stage
in 6 minutes and 35 seconds
......@@ -209,9 +209,10 @@ async def plan_remix(prompt: str, songs_info: list) -> dict:
song_lines = []
parts = []
for info in songs_info:
genre_note = f' Known genre: {info["genre"]}.' if info.get("genre") else ""
song_lines.append(
f'Song {info["index"]}: "{info["title"]}" by {info["artist"]} - '
f'{info["bpm"]:.0f} BPM, detected key {info["key_name"]}.'
f'{info["bpm"]:.0f} BPM, detected key {info["key_name"]}.{genre_note}'
)
parts.append(_make_audio_preview_part(info["path"]))
......@@ -400,14 +401,19 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
bpm = detect_bpm(path)
key = detect_key(path)
fallback_title = os.path.splitext(filenames[i])[0] if i < len(filenames) else f"Track {i + 1}"
title, artist = fallback_title, "Unknown Artist"
title, artist, genre = fallback_title, "Unknown Artist", None
existing_song_id = source_song_ids[i] if i < len(source_song_ids) else None
if existing_song_id is not None:
# Library-sourced: already correctly identified when it was first tagged, so
# this skips a fresh (slower, less reliable) identify_audio() call entirely and
# also picks up genre - never available for a raw upload, since identify_audio
# only returns title/artist candidates, not genre.
existing = db.query(LibrarySong).filter(LibrarySong.id == existing_song_id).first()
if existing:
title = existing.title or title
artist = existing.artist or artist
genre = existing.genre or None
else:
try:
candidates = asyncio.run(identify_audio(path))
......@@ -420,7 +426,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
songs_info.append({
"index": i, "path": path, "bpm": bpm,
"key_tonic": key["tonic"], "key_name": key["name"],
"title": title, "artist": artist,
"title": title, "artist": artist, "genre": genre,
})
set_status("planning", "Listening to each song and directing the arrangement (Gemini)")
......
import asyncio
import json
import os
import numpy as np
import pytest
import src.services.remix_engine as remix_engine
from src.services.remix_engine import (
_coerce_gain_db,
_pad_add,
......@@ -10,8 +13,43 @@ from src.services.remix_engine import (
_sidechain_gain_envelope,
_tile_to_length,
detect_key,
plan_remix,
)
_VALID_PLAN = {
"remix_name": "Test Mix",
"target_bpm": 120.0,
"target_key_tonic": 0,
"style": "none",
"sidechain": {"enabled": False, "source_index": 0, "amount": 0.0},
"sections": [{"name": "full", "start_fraction": 0.0, "end_fraction": 1.0, "song_roles": []}],
"master_effects": {"reverb_room_size": 0.3, "compressor_threshold_db": -12.0, "compressor_ratio": 2.0},
}
class _FakeGeminiResponse:
def __init__(self, text):
self.text = text
class _FakeGeminiModel:
"""Stands in for genai.GenerativeModel - captures the prompt parts passed to
generate_content so a test can assert on the actual text sent to Gemini, without a live
API call."""
last_parts = None
def __init__(self, *args, **kwargs):
pass
def generate_content(self, parts):
_FakeGeminiModel.last_parts = parts
return _FakeGeminiResponse(json.dumps(_VALID_PLAN))
def _songs_info(genre=None):
return [{"index": 0, "path": "/tmp/does-not-matter.wav", "bpm": 120.0, "key_tonic": 0, "key_name": "C major", "title": "Test Song", "artist": "Test Artist", "genre": genre}]
def test_coerce_gain_db_passes_through_numbers():
assert _coerce_gain_db(-3.0) == -3.0
......@@ -125,3 +163,25 @@ def test_tile_to_length_handles_empty_audio():
result = _tile_to_length(np.array([], dtype=np.float32), 4)
assert len(result) == 4
assert np.allclose(result, 0)
def test_plan_remix_includes_known_genre_in_the_prompt(mocker):
mocker.patch.object(remix_engine, "GEMINI_API_KEY", "fake-key-for-test")
mocker.patch.object(remix_engine.genai, "GenerativeModel", _FakeGeminiModel)
mocker.patch.object(remix_engine, "_make_audio_preview_part", return_value={"mime_type": "audio/wav", "data": b""})
asyncio.run(plan_remix("make it upbeat", _songs_info(genre="Synth-pop")))
prompt_text = next(p for p in _FakeGeminiModel.last_parts if isinstance(p, str))
assert "Known genre: Synth-pop" in prompt_text
def test_plan_remix_omits_genre_note_when_unknown(mocker):
mocker.patch.object(remix_engine, "GEMINI_API_KEY", "fake-key-for-test")
mocker.patch.object(remix_engine.genai, "GenerativeModel", _FakeGeminiModel)
mocker.patch.object(remix_engine, "_make_audio_preview_part", return_value={"mime_type": "audio/wav", "data": b""})
asyncio.run(plan_remix("make it upbeat", _songs_info(genre=None)))
prompt_text = next(p for p in _FakeGeminiModel.last_parts if isinstance(p, str))
assert "Known genre" not in prompt_text
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment