Files
2026-04-14 16:32:36 +09:00

304 lines
11 KiB
Python
Executable File

"""LRC alignment endpoint for creating enhanced ELRC files with word-level timestamps."""
import json
from pathlib import Path
from typing import Optional
from uuid import uuid4
from fastapi import APIRouter, Depends, File, Form, UploadFile, HTTPException
from .. import job_manager as jm
from ..config import UPLOAD_DIR, LRC_SYNC_DIR, PROJECTS_DIR
from ..security import require_admin_token
from ..services.lrc_service import run_lrc_alignment
from ..services.metadata_util import extract_lyrics_from_file
from ..services.upload_io import save_upload_file
router = APIRouter(prefix="/api/lrc", tags=["lrc"])
_ALLOWED_AUDIO_UPLOAD_EXTS = {".mp3", ".wav", ".flac", ".m4a", ".ogg", ".aac", ".wma"}
_ALLOWED_LYRICS_UPLOAD_EXTS = {".lrc", ".txt"}
_MAX_UPLOAD_FILENAME_LEN = 128
def _safe_basename(raw: str | None, fallback: str = "upload") -> str:
name = Path((raw or "").strip()).name.strip()
if not name or name.startswith("."):
name = fallback
if len(name) > _MAX_UPLOAD_FILENAME_LEN:
stem = Path(name).stem
ext = Path(name).suffix
keep_stem_len = max(1, _MAX_UPLOAD_FILENAME_LEN - len(ext))
name = f"{stem[:keep_stem_len]}{ext}" if ext else stem[:_MAX_UPLOAD_FILENAME_LEN]
return name
def _safe_upload_filename(raw: str | None, *, allowed_exts: set[str], fallback: str) -> str:
name = _safe_basename(raw, fallback=fallback)
ext = Path(name).suffix.lower()
if ext not in allowed_exts:
raise HTTPException(
status_code=400,
detail=f"Unsupported upload extension '{ext or '(none)'}'. Allowed: {sorted(allowed_exts)}",
)
return name
def _safe_project_name(raw: str) -> str:
cleaned = Path(raw).name.strip()
if not cleaned or cleaned in {".", ".."}:
raise HTTPException(status_code=400, detail="Invalid project_name")
return cleaned
def _safe_output_filename(raw: str | None, *, default_stem: str) -> str:
if not raw:
return f"{default_stem}.elrc"
name = _safe_basename(raw, fallback=f"{default_stem}.elrc")
stem = Path(name).stem or default_stem
return f"{stem}.elrc"
@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" / uuid4().hex / _safe_upload_filename(
file.filename,
allowed_exts=_ALLOWED_AUDIO_UPLOAD_EXTS,
fallback="upload.mp3",
)
temp_path.parent.mkdir(parents=True, exist_ok=True)
try:
await save_upload_file(file, temp_path)
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
if temp_path.exists():
temp_path.unlink(missing_ok=True)
@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"),
_admin_guard: None = Depends(require_admin_token),
):
"""
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_name = _safe_upload_filename(
audio.filename,
allowed_exts=_ALLOWED_AUDIO_UPLOAD_EXTS,
fallback="audio.mp3",
)
audio_path = upload_dir / audio_name
await save_upload_file(audio, audio_path)
safe_output_filename = _safe_output_filename(output_filename, default_stem=audio_path.stem)
# 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=safe_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"),
_admin_guard: None = Depends(require_admin_token),
):
"""
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_name = _safe_upload_filename(
audio.filename,
allowed_exts=_ALLOWED_AUDIO_UPLOAD_EXTS,
fallback="audio.mp3",
)
audio_path = upload_dir / audio_name
await save_upload_file(audio, audio_path)
# Save lyrics file
lyrics_name = _safe_upload_filename(
lyrics_file.filename,
allowed_exts=_ALLOWED_LYRICS_UPLOAD_EXTS,
fallback="lyrics.txt",
)
lyrics_path = upload_dir / lyrics_name
await save_upload_file(lyrics_file, lyrics_path)
safe_output_filename = _safe_output_filename(output_filename, default_stem=audio_path.stem)
# 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=safe_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"),
_admin_guard: None = Depends(require_admin_token),
):
"""
Align lyrics with an existing vocal file in a project.
Looks for the vocal file in the project's Stems folder.
"""
safe_project_name = _safe_project_name(project_name)
project_dir = PROJECTS_DIR / safe_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: {safe_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 = safe_project_name
for ext in ['.mp3', '.flac', '.wav', '.m4a', '.ogg']:
candidate = project_dir / f"{safe_project_name}{ext}"
if candidate.exists():
source_stem = candidate.stem
break
output_filename = f"{source_stem}.elrc"
output_filename = _safe_output_filename(output_filename, default_stem=Path(output_filename).stem)
# 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}