File size: 3,284 Bytes
7ca0188 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | """Transient audio validation and lightweight duration inspection."""
from __future__ import annotations
import wave
from pathlib import Path
from typing import Any
from src.config import Settings, get_settings
class AudioProcessor:
"""Validate short audio inputs without copying or retaining uploaded files."""
SUPPORTED_EXTENSIONS = {".wav", ".mp3", ".m4a", ".ogg", ".flac", ".webm"}
def __init__(self, settings: Settings | None = None) -> None:
self.settings = settings or get_settings()
def validate_audio_file(self, file_path: str | None) -> dict[str, Any]:
"""Validate presence, file type, and supported extension."""
result = {"valid": False, "file_path": file_path or "", "extension": "", "error": None}
if file_path is None or not str(file_path).strip():
result["error"] = "No audio file was provided."
return result
path = Path(str(file_path).strip())
result["file_path"] = str(path)
result["extension"] = path.suffix.lower()
if not path.is_file():
result["error"] = f"Audio file not found: {path}"
return result
if path.suffix.lower() not in self.SUPPORTED_EXTENSIONS:
result["error"] = (
f"Unsupported audio extension '{path.suffix.lower()}'. "
f"Supported: {', '.join(sorted(self.SUPPORTED_EXTENSIONS))}."
)
return result
result["valid"] = True
return result
def get_audio_duration_seconds(self, file_path: str) -> float | None:
"""Return WAV duration when readable, otherwise ``None`` without conversion."""
path = Path(file_path)
if path.suffix.lower() != ".wav":
return None
try:
with wave.open(str(path), "rb") as audio:
frame_rate = audio.getframerate()
if frame_rate <= 0:
return None
return float(audio.getnframes() / frame_rate)
except (OSError, EOFError, wave.Error):
return None
def prepare_audio(self, file_path: str | None) -> dict[str, Any]:
"""Validate audio and enforce the configured maximum when duration is known."""
validation = self.validate_audio_file(file_path)
result = {
"valid": validation["valid"],
"file_path": validation["file_path"],
"duration_seconds": None,
"within_limit": False,
"max_audio_seconds": self.settings.max_audio_seconds,
"warning": None,
"error": validation["error"],
}
if not validation["valid"]:
return result
duration = self.get_audio_duration_seconds(validation["file_path"])
result["duration_seconds"] = duration
if duration is None:
result["within_limit"] = True
result["warning"] = "Audio duration could not be determined before transcription."
elif duration > self.settings.max_audio_seconds:
result["error"] = (
f"Audio duration {duration:.2f}s exceeds the "
f"{self.settings.max_audio_seconds}s limit."
)
else:
result["within_limit"] = True
return result
|