Spaces:
Paused
Paused
File size: 4,910 Bytes
04684e6 b5e5993 04684e6 b5e5993 04684e6 | 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | """
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, ""
|