Spaces:
Sleeping
Sleeping
Commit ·
ca65887
1
Parent(s): b52be84
feat(core): add on-demand audio fetch service with ephemeral cache
Browse files
src/cache/ephemeral_cache_manager.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import tempfile
|
| 3 |
+
import time
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass(slots=True)
|
| 9 |
+
class CacheEntry:
|
| 10 |
+
key: str
|
| 11 |
+
path: Path
|
| 12 |
+
created_at: float
|
| 13 |
+
expires_at: float
|
| 14 |
+
size_bytes: int
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class EphemeralCacheManager:
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
cache_dir: str | None = None,
|
| 21 |
+
ttl_seconds: int = 300,
|
| 22 |
+
max_files: int = 256,
|
| 23 |
+
) -> None:
|
| 24 |
+
self._base_dir = Path(cache_dir) if cache_dir else Path(tempfile.gettempdir()) / "birdnet-validator-cache"
|
| 25 |
+
self._base_dir.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
self._ttl_seconds = ttl_seconds
|
| 27 |
+
self._max_files = max_files
|
| 28 |
+
self._entries: dict[str, CacheEntry] = {}
|
| 29 |
+
|
| 30 |
+
def get(self, key: str) -> Path | None:
|
| 31 |
+
self.cleanup_expired()
|
| 32 |
+
entry = self._entries.get(key)
|
| 33 |
+
if not entry:
|
| 34 |
+
return None
|
| 35 |
+
if not entry.path.exists():
|
| 36 |
+
self._entries.pop(key, None)
|
| 37 |
+
return None
|
| 38 |
+
return entry.path
|
| 39 |
+
|
| 40 |
+
def put_bytes(self, key: str, data: bytes, suffix: str = ".bin") -> Path:
|
| 41 |
+
self.cleanup_expired()
|
| 42 |
+
self._enforce_capacity()
|
| 43 |
+
|
| 44 |
+
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
|
| 45 |
+
file_path = self._base_dir / f"{digest}{suffix}"
|
| 46 |
+
file_path.write_bytes(data)
|
| 47 |
+
|
| 48 |
+
now = time.time()
|
| 49 |
+
self._entries[key] = CacheEntry(
|
| 50 |
+
key=key,
|
| 51 |
+
path=file_path,
|
| 52 |
+
created_at=now,
|
| 53 |
+
expires_at=now + self._ttl_seconds,
|
| 54 |
+
size_bytes=len(data),
|
| 55 |
+
)
|
| 56 |
+
return file_path
|
| 57 |
+
|
| 58 |
+
def cleanup_key(self, key: str) -> None:
|
| 59 |
+
entry = self._entries.pop(key, None)
|
| 60 |
+
if not entry:
|
| 61 |
+
return
|
| 62 |
+
if entry.path.exists():
|
| 63 |
+
entry.path.unlink()
|
| 64 |
+
|
| 65 |
+
def cleanup_expired(self) -> None:
|
| 66 |
+
now = time.time()
|
| 67 |
+
expired_keys = [key for key, entry in self._entries.items() if entry.expires_at <= now or not entry.path.exists()]
|
| 68 |
+
for key in expired_keys:
|
| 69 |
+
self.cleanup_key(key)
|
| 70 |
+
|
| 71 |
+
def clear(self) -> None:
|
| 72 |
+
for key in list(self._entries.keys()):
|
| 73 |
+
self.cleanup_key(key)
|
| 74 |
+
|
| 75 |
+
def _enforce_capacity(self) -> None:
|
| 76 |
+
if len(self._entries) < self._max_files:
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
oldest_keys = sorted(self._entries.keys(), key=lambda key: self._entries[key].created_at)
|
| 80 |
+
overflow = (len(self._entries) - self._max_files) + 1
|
| 81 |
+
for key in oldest_keys[:overflow]:
|
| 82 |
+
self.cleanup_key(key)
|
src/services/audio_fetch_service.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from huggingface_hub import hf_hub_download
|
| 5 |
+
|
| 6 |
+
from src.cache.ephemeral_cache_manager import EphemeralCacheManager
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
SUPPORTED_AUDIO_EXTENSIONS = (".wav", ".mp3", ".flac", ".ogg", ".m4a")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass(slots=True)
|
| 13 |
+
class AudioFetchResult:
|
| 14 |
+
cache_key: str
|
| 15 |
+
local_path: str
|
| 16 |
+
source: str
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class AudioFetchService:
|
| 20 |
+
def __init__(self, cache_manager: EphemeralCacheManager) -> None:
|
| 21 |
+
self._cache = cache_manager
|
| 22 |
+
|
| 23 |
+
def fetch(self, dataset_repo: str, audio_id: str) -> AudioFetchResult:
|
| 24 |
+
cache_key = f"{dataset_repo}:{audio_id}"
|
| 25 |
+
cached_path = self._cache.get(cache_key)
|
| 26 |
+
if cached_path:
|
| 27 |
+
return AudioFetchResult(cache_key=cache_key, local_path=str(cached_path), source="cache")
|
| 28 |
+
|
| 29 |
+
target_filename, downloaded_path = self._resolve_remote_filename(dataset_repo=dataset_repo, audio_id=audio_id)
|
| 30 |
+
if downloaded_path is None:
|
| 31 |
+
downloaded = hf_hub_download(repo_id=dataset_repo, repo_type="dataset", filename=target_filename)
|
| 32 |
+
downloaded_path = Path(downloaded)
|
| 33 |
+
|
| 34 |
+
suffix = downloaded_path.suffix if downloaded_path.suffix else ".bin"
|
| 35 |
+
local_path = self._cache.put_bytes(cache_key, downloaded_path.read_bytes(), suffix=suffix)
|
| 36 |
+
return AudioFetchResult(cache_key=cache_key, local_path=str(local_path), source="remote")
|
| 37 |
+
|
| 38 |
+
def cleanup_after_validation(self, cache_key: str) -> None:
|
| 39 |
+
self._cache.cleanup_key(cache_key)
|
| 40 |
+
|
| 41 |
+
def _resolve_remote_filename(self, dataset_repo: str, audio_id: str) -> tuple[str, Path | None]:
|
| 42 |
+
audio_path = Path(audio_id)
|
| 43 |
+
if audio_path.suffix:
|
| 44 |
+
return f"audio/{audio_id}", None
|
| 45 |
+
|
| 46 |
+
for extension in SUPPORTED_AUDIO_EXTENSIONS:
|
| 47 |
+
candidate = f"audio/{audio_id}{extension}"
|
| 48 |
+
try:
|
| 49 |
+
downloaded = hf_hub_download(repo_id=dataset_repo, repo_type="dataset", filename=candidate)
|
| 50 |
+
return candidate, Path(downloaded)
|
| 51 |
+
except Exception:
|
| 52 |
+
continue
|
| 53 |
+
|
| 54 |
+
raise FileNotFoundError(f"Unable to locate audio file for audio_id: {audio_id}")
|