""" Audio file validator and metadata extractor Author: Maaldeens License: MIT """ from pathlib import Path from typing import Dict, Tuple, Optional import logging from dataclasses import dataclass import soundfile as sf logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @dataclass class AudioMetadata: """Audio file metadata container.""" filename: str format: str sample_rate: int channels: int duration: float file_size: int # FIX: subtype from soundfile is a string like "PCM_16", not an int. bit_depth: Optional[str] = None bit_rate: Optional[int] = None class AudioValidator: """Validates audio files and extracts metadata. Supports mp3, wav, m4a, ogg, flac, aac.""" EXTENSION_MAP = { ".mp3": "mp3", ".wav": "wav", ".m4a": "m4a", ".ogg": "ogg", ".flac": "flac", ".aac": "aac", ".mp4": "m4a", ".aiff": "aiff", ".wma": "wma", # Browser recordings (MediaRecorder) and other files the apps accept. ".webm": "webm", ".opus": "opus", ".mov": "m4a", ".mkv": "webm", ".3gp": "3gp", ".amr": "amr", } def __init__(self, max_file_size_mb: int = 500): self.max_file_size_bytes = max_file_size_mb * 1024 * 1024 def validate_file(self, file_path: str) -> Tuple[bool, str]: path = Path(file_path) if not path.exists(): return False, f"File not found: {file_path}" if not path.is_file(): return False, f"Path is not a file: {file_path}" size = path.stat().st_size if size > self.max_file_size_bytes: return False, f"File size ({size/1024/1024:.1f} MB) exceeds limit ({self.max_file_size_bytes/1024/1024:.0f} MB)" if size == 0: return False, "File is empty" return True, "" def detect_format(self, file_path: str) -> Optional[str]: return self.EXTENSION_MAP.get(Path(file_path).suffix.lower()) # Formats where soundfile silently returns wrong duration (e.g. VBR MP3 # reporting 5 s instead of 25 min) — go straight to pydub for these. _PYDUB_FORMATS = {".mp3", ".m4a", ".aac", ".wma", ".aiff", ".mp4", ".webm", ".mov", ".mkv", ".3gp", ".amr"} def _extract_with_pydub(self, file_path: str) -> Optional["AudioMetadata"]: try: from pydub import AudioSegment audio_seg = AudioSegment.from_file(file_path) stats = Path(file_path).stat() return AudioMetadata( filename=Path(file_path).name, format=self.detect_format(file_path) or "unknown", sample_rate=int(audio_seg.frame_rate), channels=audio_seg.channels, duration=len(audio_seg) / 1000.0, file_size=stats.st_size, ) except Exception as e: logger.error(f"pydub metadata extraction failed: {e}") return None def extract_metadata(self, file_path: str) -> Optional[AudioMetadata]: ext = Path(file_path).suffix.lower() # For container formats soundfile may succeed but return wrong duration # for VBR files — no exception is raised, so the old try/except fallback # never triggered. Route these directly to pydub which reads the true # container header and always reports the correct duration. if ext in self._PYDUB_FORMATS: return self._extract_with_pydub(file_path) try: info = sf.info(file_path) stats = Path(file_path).stat() return AudioMetadata( filename=Path(file_path).name, format=self.detect_format(file_path) or "unknown", sample_rate=int(info.samplerate), channels=info.channels, duration=float(info.duration), file_size=stats.st_size, bit_depth=str(info.subtype) if hasattr(info, "subtype") and info.subtype else None, ) except Exception as e: logger.warning(f"soundfile metadata extraction failed ({e}), trying pydub fallback") return self._extract_with_pydub(file_path) def is_valid_audio(self, file_path: str) -> Tuple[bool, Optional[AudioMetadata], str]: is_valid, error = self.validate_file(file_path) if not is_valid: return False, None, error if not self.detect_format(file_path): return False, None, f"Unsupported audio format: {Path(file_path).suffix}" metadata = self.extract_metadata(file_path) if not metadata: return False, None, "Failed to extract audio metadata" if metadata.duration < 0.1: return False, metadata, "Audio too short (< 0.1 s)" return True, metadata, ""