NovaGuide / src /preprocessing /audio_processor.py
DKLPDV15\eB
Deploy NovaGuide with versioned runtime configuration
7ca0188
Raw History Blame Contribute Delete
3.28 kB
"""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