feat: Refactor audio utility functions and update sound services to use shared methods

This commit is contained in:
JSC
2025-07-28 16:55:13 +02:00
parent 71da295827
commit a17cb7c5bc
6 changed files with 487 additions and 195 deletions

View File

@@ -1,15 +1,14 @@
"""Sound scanner service for scanning and importing audio files."""
import hashlib
from pathlib import Path
from typing import TypedDict
import ffmpeg # type: ignore[import-untyped]
from sqlmodel.ext.asyncio.session import AsyncSession
from app.core.logging import get_logger
from app.models.sound import Sound
from app.repositories.sound import SoundRepository
from app.utils.audio import get_audio_duration, get_file_hash, get_file_size
logger = get_logger(__name__)
@@ -57,27 +56,6 @@ class SoundScannerService:
".aac",
}
def get_file_hash(self, file_path: Path) -> str:
"""Calculate SHA-256 hash of a file."""
hash_sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
def get_audio_duration(self, file_path: Path) -> int:
"""Get audio duration in milliseconds using ffmpeg."""
try:
probe = ffmpeg.probe(str(file_path))
duration = float(probe["format"]["duration"])
return int(duration * 1000) # Convert to milliseconds
except Exception as e:
logger.warning("Failed to get duration for %s: %s", file_path, e)
return 0
def get_file_size(self, file_path: Path) -> int:
"""Get file size in bytes."""
return file_path.stat().st_size
def extract_name_from_filename(self, filename: str) -> str:
"""Extract a clean name from filename."""
@@ -207,9 +185,9 @@ class SoundScannerService:
) -> None:
"""Sync a single audio file (add new or update existing)."""
filename = file_path.name
file_hash = self.get_file_hash(file_path)
duration = self.get_audio_duration(file_path)
size = self.get_file_size(file_path)
file_hash = get_file_hash(file_path)
duration = get_audio_duration(file_path)
size = get_file_size(file_path)
name = self.extract_name_from_filename(filename)
if existing_sound is None: