The open-source AI voice studio. Clone, dictate, create.
feat(history): MP3 export for single generations (format=mp3)
Jonathan Rodríguezfdcccdf3f0a3
diff --git a/backend/routes/history.py b/backend/routes/history.pyindex 4b7e2222..c1e4c200 100644--- a/backend/routes/history.py+++ b/backend/routes/history.py@@ -1,13 +1,18 @@"""Generation history endpoints."""+import asyncioimport io+import os+import tempfile+from pathlib import Path-from fastapi import APIRouter, Depends, File, HTTPException, UploadFile-from fastapi.responses import FileResponse, StreamingResponse+from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile+from fastapi.responses import FileResponse, Response, StreamingResponsefrom sqlalchemy.orm import Sessionfrom .. import config, modelsfrom ..services import export_import, history+from ..utils.ffmpeg import encode_audiofrom ..utils.http import safe_content_dispositionfrom ..database import Generation as DBGeneration, VoiceProfile as DBVoiceProfile, get_db@@ -162,12 +167,24 @@ async def export_generation()+_EXPORT_MIME = {"wav": "audio/wav", "mp3": "audio/mpeg"}++@router.get("/history/{generation_id}/export-audio")async def export_generation_audio(generation_id: str,+ format_: str = Query("wav", alias="format"),db: Session = Depends(get_db),):- """Export only the audio file from a generation."""+ """Export only the audio file from a generation.++ ``format=wav`` (default) returns the stored file unchanged; ``format=mp3``+ transcodes it with ffmpeg (192 kbps) and returns 503 when ffmpeg is missing.+ """+ fmt = (format_ or "wav").lower()+ if fmt not in _EXPORT_MIME:+ raise HTTPException(status_code=400, detail=f"Unsupported format: {format_}")+generation = db.query(DBGeneration).filter_by(id=generation_id).first()if not generation:raise HTTPException(status_code=404, detail="Generation not found")@@ -184,10 +201,22 @@ async def export_generation_audio(safe_text = "generation"# Append a short id so exports of similarly-worded generations don't collide# on the same filename (the first 30 chars are frequently identical).- filename = f"{safe_text}-{generation_id[:8]}.wav"+ filename = f"{safe_text}-{generation_id[:8]}.{fmt}"+ headers = {"Content-Disposition": safe_content_disposition("attachment", filename)}- return FileResponse(- audio_path,- media_type="audio/wav",- headers={"Content-Disposition": safe_content_disposition("attachment", filename)},- )+ if fmt == "wav":+ return FileResponse(audio_path, media_type="audio/wav", headers=headers)++ fd, tmp_name = tempfile.mkstemp(suffix=".mp3")+ os.close(fd)+ tmp_path = Path(tmp_name)+ try:+ # ffmpeg is CPU-bound; keep it off the event loop.+ await asyncio.to_thread(encode_audio, audio_path, tmp_path, fmt)+ mp3_bytes = tmp_path.read_bytes()+ except RuntimeError as e:+ raise HTTPException(status_code=503, detail=str(e)) from e+ finally:+ tmp_path.unlink(missing_ok=True)++ return Response(content=mp3_bytes, media_type=_EXPORT_MIME[fmt], headers=headers)diff --git a/backend/utils/ffmpeg.py b/backend/utils/ffmpeg.pyindex 149e89bc..b3032365 100644--- a/backend/utils/ffmpeg.py+++ b/backend/utils/ffmpeg.py@@ -10,7 +10,6 @@ import shutilimport subprocessimport sysfrom pathlib import Path-from typing import List, Optional# GUI-launched apps on macOS get a minimal PATH (/usr/bin:/bin:/usr/sbin:/sbin),# so a Homebrew or MacPorts ffmpeg is invisible to shutil.which. Windows package@@ -39,7 +38,7 @@ ENCODERS = {}-def find_ffmpeg(name: str = "ffmpeg") -> Optional[str]:+def find_ffmpeg(name: str = "ffmpeg") -> str | None:"""Return the path to ``name`` (ffmpeg/ffprobe) or None when not installed."""override = os.environ.get("VOICEBOX_FFMPEG_DIR")if override:@@ -60,7 +59,7 @@ def encode_audio(wav_path: Path,out_path: Path,fmt: str,- metadata_path: Optional[Path] = None,+ metadata_path: Path | None = None,timeout: int = 600,) -> None:"""Transcode ``wav_path`` to ``fmt`` ("mp3" or "m4b") at ``out_path``.@@ -76,7 +75,7 @@ def encode_audio(if ffmpeg is None:raise RuntimeError(MISSING_MESSAGE)- cmd: List[str] = [ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-i", str(wav_path)]+ cmd: list[str] = [ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-i", str(wav_path)]if metadata_path is not None:cmd.extend(["-i", str(metadata_path), "-map_metadata", "1", "-map_chapters", "1"])cmd.extend(["-map", "0:a", *ENCODERS[fmt], str(out_path)])