Skip to content

The open-source AI voice studio. Clone, dictate, create.

fix(stories): address review — ffmpeg timeout, lint, docstrings

liubaofeng75df983e2adc
diff --git a/backend/routes/stories.py b/backend/routes/stories.py
index e250e913..a58e14f0 100644
--- a/backend/routes/stories.py
+++ b/backend/routes/stories.py
@@ -2,7 +2,7 @@
import io
-from fastapi import APIRouter, Depends, HTTPException
+from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
@@ -216,7 +216,10 @@ _EXPORT_MIME = {
@router.get("/stories/{story_id}/export-audio")
async def export_story_audio(
story_id: str,
- format: str = "wav",
+ # ``format_`` shadows the builtin ``format`` if exposed directly (Ruff
+ # A002), so the local identifier is renamed while the public query-param
+ # name stays ``format`` via the Query alias.
+ format_: str = Query("wav", alias="format"),
chapters: str = "none",
db: Session = Depends(get_db),
):
@@ -227,9 +230,9 @@ async def export_story_audio(
chapters: ``none`` (default) or ``auto``. ``auto`` emits one chapter
per story item, titled from its generation text. WAV ignores this.
"""
- fmt = (format or "wav").lower()
+ fmt = (format_ or "wav").lower()
if fmt not in _EXPORT_MIME:
- raise HTTPException(status_code=400, detail=f"Unsupported format: {format}")
+ raise HTTPException(status_code=400, detail=f"Unsupported format: {format_}")
chapters_mode = (chapters or "none").lower()
if chapters_mode not in ("none", "auto"):
raise HTTPException(status_code=400, detail=f"Unsupported chapters mode: {chapters}")
@@ -244,8 +247,8 @@ async def export_story_audio(
story_id, db, fmt=fmt, chapters_mode=chapters_mode
)
except RuntimeError as e:
- # Most likely: ffmpeg missing or ffmpeg returned non-zero.
- raise HTTPException(status_code=503, detail=str(e))
+ # Most likely: ffmpeg missing, timed out, or returned non-zero.
+ raise HTTPException(status_code=503, detail=str(e)) from e
if not audio_bytes:
raise HTTPException(status_code=400, detail="Story has no audio items")
diff --git a/backend/services/stories.py b/backend/services/stories.py
index d50b1caf..dadfb0d9 100644
--- a/backend/services/stories.py
+++ b/backend/services/stories.py
@@ -5,6 +5,8 @@ Story management module.
from typing import List, Optional
from dataclasses import dataclass
from datetime import UTC, datetime
+import asyncio
+import os
import re
import shutil
import subprocess
@@ -839,6 +841,8 @@ async def set_story_item_version(
@dataclass
class _Chapter:
+ """Single chapter boundary used when exporting a story to m4b/mp3."""
+
start_ms: int
end_ms: int
title: str
@@ -894,7 +898,12 @@ def _derive_chapters_auto(
def _escape_ffmetadata(value: str) -> str:
- # Per https://ffmpeg.org/ffmpeg-formats.html#Metadata-1 — escape =, ;, #, \, newline.
+ """Escape a metadata value for an FFMETADATA1 file.
+
+ Per the spec (https://ffmpeg.org/ffmpeg-formats.html#Metadata-1) ``=``,
+ ``;``, ``#``, ``\\``, and literal newlines must be backslash-escaped, or
+ ffmpeg will reject (or silently mangle) the chapter entry.
+ """
return (
value.replace("\\", "\\\\")
.replace("=", "\\=")
@@ -905,6 +914,7 @@ def _escape_ffmetadata(value: str) -> str:
def _write_ffmetadata(chapters: List[_Chapter], path: Path) -> None:
+ """Serialize chapter list to an FFMETADATA1 file ffmpeg can ingest via ``-i``."""
lines = [";FFMETADATA1"]
for ch in chapters:
lines.extend(
@@ -951,7 +961,13 @@ def _ffmpeg_encode(
raise ValueError(f"Unsupported export format: {fmt}")
cmd.append(str(out_path))
- result = subprocess.run(cmd, capture_output=True, check=False)
+ try:
+ # Hard ceiling — a stuck ffmpeg must not pin server resources
+ # indefinitely. 10 minutes is generous enough for a multi-hour
+ # audiobook on slow hardware but still bounded.
+ result = subprocess.run(cmd, capture_output=True, check=False, timeout=600)
+ except subprocess.TimeoutExpired as exc:
+ raise RuntimeError("ffmpeg timed out during story export") from exc
if result.returncode != 0:
stderr = result.stderr.decode("utf-8", errors="replace").strip()
raise RuntimeError(f"ffmpeg exited {result.returncode}: {stderr}")
@@ -960,6 +976,18 @@ def _ffmpeg_encode(
meta_path.unlink(missing_ok=True)
+def _make_tempfile(suffix: str) -> Path:
+ """Create a closed-on-return temp file path with the given suffix.
+
+ Uses ``tempfile.mkstemp`` rather than ``NamedTemporaryFile(delete=False).name``
+ so the OS file descriptor is released immediately instead of lingering
+ until garbage collection (Ruff SIM115).
+ """
+ fd, name = tempfile.mkstemp(suffix=suffix)
+ os.close(fd)
+ return Path(name)
+
+
async def export_story_audio(
story_id: str,
db: Session,
@@ -1103,7 +1131,7 @@ async def export_story_audio(
if fmt != "wav" and chapters_mode == "auto":
chapters = _derive_chapters_auto(audio_data, max_end_time_ms) or None
- wav_path = Path(tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name)
+ wav_path = _make_tempfile(suffix=".wav")
out_path: Optional[Path] = None
try:
save_audio(final_audio, str(wav_path), sample_rate)
@@ -1111,8 +1139,11 @@ async def export_story_audio(
return wav_path.read_bytes()
out_suffix = ".m4b" if fmt == "m4b" else ".mp3"
- out_path = Path(tempfile.NamedTemporaryFile(suffix=out_suffix, delete=False).name)
- _ffmpeg_encode(wav_path, out_path, fmt, chapters)
+ out_path = _make_tempfile(suffix=out_suffix)
+ # ffmpeg is CPU-bound and can run for several seconds on a real
+ # audiobook — offload to a worker thread so it doesn't block the
+ # FastAPI event loop while it runs.
+ await asyncio.to_thread(_ffmpeg_encode, wav_path, out_path, fmt, chapters)
return out_path.read_bytes()
finally:
wav_path.unlink(missing_ok=True)
diff --git a/backend/tests/test_story_export.py b/backend/tests/test_story_export.py
index 8cc11f9b..3351adaa 100644
--- a/backend/tests/test_story_export.py
+++ b/backend/tests/test_story_export.py
@@ -143,7 +143,8 @@ class TestFFmpegEncodeIntegration:
_Chapter(start_ms=4000, end_ms=12000, title="Closing"),
]
_ffmpeg_encode(wav_path, out_path, fmt="m4b", chapters=chapters)
- assert out_path.exists() and out_path.stat().st_size > 0
+ assert out_path.exists()
+ assert out_path.stat().st_size > 0
probe = subprocess.run(
[