feat: Refactor audio utility functions and update sound services to use shared methods
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
"""Sound normalizer service for normalizing audio files using ffmpeg loudnorm."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -14,6 +13,7 @@ from app.core.config import settings
|
||||
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__)
|
||||
|
||||
@@ -107,27 +107,6 @@ class SoundNormalizerService:
|
||||
original_dir = type_to_original_dir.get(sound_type, "sounds/originals/other")
|
||||
return Path(original_dir) / filename
|
||||
|
||||
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_file_size(self, file_path: Path) -> int:
|
||||
"""Get file size in bytes."""
|
||||
return file_path.stat().st_size
|
||||
|
||||
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
|
||||
|
||||
async def _normalize_audio_one_pass(
|
||||
self,
|
||||
@@ -341,9 +320,9 @@ class SoundNormalizerService:
|
||||
await self._normalize_audio_two_pass(original_path, normalized_path)
|
||||
|
||||
# Get normalized file info
|
||||
normalized_duration = self._get_audio_duration(normalized_path)
|
||||
normalized_size = self._get_file_size(normalized_path)
|
||||
normalized_hash = self._get_file_hash(normalized_path)
|
||||
normalized_duration = get_audio_duration(normalized_path)
|
||||
normalized_size = get_file_size(normalized_path)
|
||||
normalized_hash = get_file_hash(normalized_path)
|
||||
normalized_filename = normalized_path.name
|
||||
|
||||
# Update sound in database
|
||||
|
||||
Reference in New Issue
Block a user