Files
stemengine_old/backend/routers_root_backup/lrc.py
T
2026-03-03 14:52:19 +09:00

239 lines
8.2 KiB
Python
Executable File

"""LRC alignment endpoint for creating enhanced ELRC files with word-level timestamps."""
import json
import shutil
from pathlib import Path
from typing import Optional
from fastapi import APIRouter, File, Form, UploadFile, HTTPException
from .. import job_manager as jm
from ..config import UPLOAD_DIR, LRC_SYNC_DIR, PROJECTS_DIR
from ..services.lrc_service import run_lrc_alignment
from ..services.metadata_util import extract_lyrics_from_file
router = APIRouter(prefix="/api/lrc", tags=["lrc"])
@router.get("/sources")
def get_lyrics_sources():
"""Get available lyrics source options."""
return [
{"id": "auto", "label": "Auto-detect (tags → LRC file)"},
{"id": "tag", "label": "Audio file metadata tags only"},
{"id": "file", "label": "Upload LRC/TXT file"},
{"id": "text", "label": "Type lyrics directly"},
]
@router.post("/extract")
async def extract_lyrics(
file: UploadFile = File(...),
):
"""
Extract lyrics from an uploaded audio file.
Returns lyrics source info and plain text.
"""
temp_path = UPLOAD_DIR / "temp" / file.filename
temp_path.parent.mkdir(parents=True, exist_ok=True)
try:
with open(temp_path, "wb") as f:
shutil.copyfileobj(file.file, f)
result = extract_lyrics_from_file(str(temp_path))
return {
"source": result["source"],
"synced": result["synced"],
"lyrics": result["plain"],
"raw": result["raw"],
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to extract lyrics: {e}")
finally:
# Cleanup
try:
if temp_path.exists():
temp_path.unlink()
except:
pass
@router.post("/align")
async def align_lyrics(
audio: UploadFile = File(..., description="Audio file with vocals"),
lyrics_source: str = Form("auto", description="Source of lyrics: auto, tag, file, text"),
lyrics_text: Optional[str] = Form(None, description="Lyrics text when source='text'"),
output_filename: Optional[str] = Form(None, description="Custom output filename"),
style_options: Optional[str] = Form(None, description="JSON string of style options for lyrics display"),
):
"""
Align lyrics with audio to create ELRC file with word-level timestamps.
- lyrics_source='auto': Try metadata tags, then external LRC file
- lyrics_source='tag': Only use metadata tags from audio file
- lyrics_source='text': Use provided lyrics_text
"""
if lyrics_source not in ("auto", "tag", "file", "text"):
raise HTTPException(status_code=400, detail=f"Invalid lyrics_source: {lyrics_source}")
if lyrics_source == "text" and not lyrics_text:
raise HTTPException(status_code=400, detail="lyrics_text required when source='text'")
# Create job
job_id = jm.create_job("lrc_align")
upload_dir = UPLOAD_DIR / job_id
upload_dir.mkdir(parents=True, exist_ok=True)
# Save audio file
audio_path = upload_dir / audio.filename
with open(audio_path, "wb") as f:
shutil.copyfileobj(audio.file, f)
# Parse style options
parsed_style_options = None
if style_options:
try:
parsed_style_options = json.loads(style_options)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid style_options JSON")
# Submit job
jm.submit_gpu(
run_lrc_alignment,
job_id,
str(audio_path),
lyrics_source=lyrics_source,
lyrics_content=lyrics_text,
output_filename=output_filename,
style_options=parsed_style_options,
)
return {"job_id": job_id}
@router.post("/align-with-file")
async def align_lyrics_with_file(
audio: UploadFile = File(..., description="Audio file with vocals"),
lyrics_file: UploadFile = File(..., description="LRC or TXT file with lyrics"),
output_filename: Optional[str] = Form(None, description="Custom output filename"),
style_options: Optional[str] = Form(None, description="JSON string of style options for lyrics display"),
):
"""
Align lyrics from uploaded file with audio to create ELRC file.
"""
job_id = jm.create_job("lrc_align")
upload_dir = UPLOAD_DIR / job_id
upload_dir.mkdir(parents=True, exist_ok=True)
# Save audio file
audio_path = upload_dir / audio.filename
with open(audio_path, "wb") as f:
shutil.copyfileobj(audio.file, f)
# Save lyrics file
lyrics_path = upload_dir / lyrics_file.filename
with open(lyrics_path, "wb") as f:
shutil.copyfileobj(lyrics_file.file, f)
# Parse style options
parsed_style_options = None
if style_options:
try:
parsed_style_options = json.loads(style_options)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid style_options JSON")
# Submit job
jm.submit_gpu(
run_lrc_alignment,
job_id,
str(audio_path),
lyrics_source="file",
lyrics_file_path=str(lyrics_path),
output_filename=output_filename,
style_options=parsed_style_options,
)
return {"job_id": job_id}
@router.post("/align-existing")
async def align_lyrics_existing(
project_name: str = Form(..., description="Project name (e.g., 'Artist - Title')"),
lyrics_source: str = Form("auto", description="Source of lyrics: auto, tag, text"),
lyrics_text: Optional[str] = Form(None, description="Lyrics text when source='text'"),
output_filename: Optional[str] = Form(None, description="Custom output filename"),
style_options: Optional[str] = Form(None, description="JSON string of style options for lyrics display"),
):
"""
Align lyrics with an existing vocal file in a project.
Looks for the vocal file in the project's Stems folder.
"""
project_dir = PROJECTS_DIR / project_name
stems_dir = project_dir / "Stems"
if not stems_dir.exists():
raise HTTPException(status_code=404, detail=f"Stems folder not found for project: {project_name}")
# Find vocals file
vocal_file = None
for name in ["vocals", "vocals.mp3", "vocals.wav", "vocals.flac"]:
for ext in ["", ".mp3", ".wav", ".flac"]:
candidate = stems_dir / f"{name}{ext}"
if candidate.exists():
vocal_file = candidate
break
if vocal_file:
break
if not vocal_file:
# Try any file with "vocal" in the name
for f in stems_dir.iterdir():
if "vocal" in f.name.lower() and f.suffix in [".mp3", ".wav", ".flac"]:
vocal_file = f
break
if not vocal_file:
raise HTTPException(status_code=404, detail="No vocals file found in Stems folder")
job_id = jm.create_job("lrc_align")
# Save ELRC/LRC directly into the project root folder so it sits alongside
# the source audio (which is also named after the project).
project_dir.mkdir(parents=True, exist_ok=True)
# Determine output filename — must match the source audio base name
if not output_filename:
# Check whether a source audio file exists and use its stem
source_stem = project_name
for ext in ['.mp3', '.flac', '.wav', '.m4a', '.ogg']:
candidate = project_dir / f"{project_name}{ext}"
if candidate.exists():
source_stem = candidate.stem
break
output_filename = f"{source_stem}.elrc"
# Parse style options
parsed_style_options = None
if style_options:
try:
parsed_style_options = json.loads(style_options)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid style_options JSON")
# Submit job — vocal file is already separated, so skip Demucs extraction
jm.submit_gpu(
run_lrc_alignment,
job_id,
str(vocal_file),
lyrics_source=lyrics_source,
lyrics_content=lyrics_text,
output_filename=output_filename,
style_options=parsed_style_options,
is_vocals=True,
output_dir=str(project_dir),
)
return {"job_id": job_id}