""" DatasetStore — HuggingFace Dataset read/write helper ═════════════════════════════════════════════════════ Dual-dataset mode: - HF_DATASET (primary, always required) - HF_DATASET_2 (secondary, optional — set in HF Space secrets) Save: picks a dataset by hashing the pipeline_id (deterministic — same pipeline always goes to the same dataset, so re-runs and multi-file pipelines are always consistent within one repo). Load: reads from whichever dataset that pipeline was assigned to. If the file is missing there, falls back to checking the other dataset automatically. Delete: operates on the correct dataset for that pipeline. 412 retry: 2 retries with exponential backoff before giving up. """ import asyncio import logging import time from typing import Optional logger = logging.getLogger(__name__) HF_RAW_URL = "https://huggingface.co/datasets/{repo}/resolve/main/{path}" INTERMEDIATE_FILES = [ "audio.wav", "tts_timestamps.json", "align_timestamps.json", ] # ── Retry config ────────────────────────────────────────────────────────────── MAX_UPLOAD_RETRIES = 2 RETRY_BASE_DELAY = 2.0 RETRY_BACKOFF = 2.0 RETRYABLE_STATUSES = {412, 500, 502, 503, 504} class DatasetStore: def __init__(self, hf_token: str, dataset_repo: str, dataset_repo_2: str = ""): logger.info( f"DatasetStore.__init__ called with: " f"hf_token={'SET (len=' + str(len(hf_token)) + ')' if hf_token else 'EMPTY'}, " f"dataset_repo='{dataset_repo}', " f"dataset_repo_2='{dataset_repo_2}'" ) self.token = hf_token self.repo_1 = dataset_repo self.repo_2 = dataset_repo_2.strip() if dataset_repo_2 else "" self._ready = bool(hf_token and dataset_repo) self._dual = bool(self._ready and self.repo_2) logger.info( f"DatasetStore initialized: " f"repo_1='{self.repo_1}', " f"repo_2='{self.repo_2}', " f"_ready={self._ready}, " f"_dual={self._dual}" ) if not self._ready: logger.warning( "DatasetStore: HF_TOKEN or HF_DATASET not set. " "Assets will not persist across controller restarts." ) elif self._dual: logger.info( f"DatasetStore: ✓ DUAL-DATASET mode initialized — " f"PRIMARY: {self.repo_1} | SECONDARY: {self.repo_2}" ) else: logger.info(f"DatasetStore: SINGLE-DATASET mode initialized — {self.repo_1}") # ── Dataset picker ──────────────────────────────────────────────────────── def _repo_for(self, pipeline_id: str) -> str: """ Deterministically pick a repo for this pipeline. Uses the first hex char of the UUID — even = repo_1, odd = repo_2. Same pipeline always maps to the same repo so all its files stay together. """ if not self._dual: logger.info( f"DatasetStore._repo_for: SINGLE-DATASET mode active " f"(HF_DATASET_2 not set) — {pipeline_id[:8]} → {self.repo_1}" ) return self.repo_1 first_hex = pipeline_id[0] hex_value = int(first_hex, 16) is_odd = hex_value % 2 == 1 chosen_repo = self.repo_2 if is_odd else self.repo_1 logger.info( f"DatasetStore._repo_for: DUAL-DATASET routing — " f"pipeline {pipeline_id[:8]} | first_char='{first_hex}' | " f"hex_value={hex_value} | is_odd={is_odd} | " f"chosen={'SECONDARY (repo_2)' if is_odd else 'PRIMARY (repo_1)'} | " f"repo={chosen_repo}" ) return chosen_repo def _other_repo(self, repo: str) -> Optional[str]: """Return the other repo (for fallback reads).""" if not self._dual: return None return self.repo_2 if repo == self.repo_1 else self.repo_1 # ── Public API ──────────────────────────────────────────────────────────── async def save( self, pipeline_id: str, filename: str, data: bytes, content_type: str = "application/octet-stream", ) -> str: if not self._ready: logger.warning(f"DatasetStore not configured — {filename} not persisted.") return f"memory://{pipeline_id}/{filename}" repo = self._repo_for(pipeline_id) path_in_repo = f"{pipeline_id}/{filename}" loop = asyncio.get_running_loop() logger.info( f"DatasetStore.save: {pipeline_id[:8]}/{filename} → {repo} " f"({len(data):,} bytes, type={content_type})" ) await loop.run_in_executor( None, self._upload_with_retry, repo, path_in_repo, data, content_type ) final_url = HF_RAW_URL.format(repo=repo, path=path_in_repo) logger.info( f"DatasetStore.save: SUCCESS — {pipeline_id[:8]}/{filename} → {final_url}" ) return final_url async def load(self, pipeline_id: str, filename: str) -> bytes: if not self._ready: raise RuntimeError("DatasetStore not configured.") repo = self._repo_for(pipeline_id) path_in_repo = f"{pipeline_id}/{filename}" url = HF_RAW_URL.format(repo=repo, path=path_in_repo) loop = asyncio.get_running_loop() logger.info( f"DatasetStore.load: attempting {pipeline_id[:8]}/{filename} from {repo}" ) try: data = await loop.run_in_executor(None, self._download_sync, url) logger.info( f"DatasetStore.load: SUCCESS — loaded {len(data):,} bytes from {repo}" ) return data except Exception as primary_err: other = self._other_repo(repo) if not other: logger.error( f"DatasetStore.load: FAILED — no fallback available, error: {primary_err}" ) raise logger.warning( f"DatasetStore.load: primary repo {repo} failed for {path_in_repo}, " f"trying fallback {other}: {primary_err}" ) fallback_url = HF_RAW_URL.format(repo=other, path=path_in_repo) data = await loop.run_in_executor(None, self._download_sync, fallback_url) logger.info( f"DatasetStore.load: SUCCESS (fallback) — loaded {len(data):,} bytes from {other}" ) return data async def delete_intermediates(self, pipeline_id: str) -> None: if not self._ready: logger.warning( f"DatasetStore not configured — cannot delete intermediates " f"for {pipeline_id}." ) return repo = self._repo_for(pipeline_id) logger.info( f"DatasetStore.delete_intermediates: {pipeline_id[:8]} from {repo}" ) loop = asyncio.get_running_loop() await loop.run_in_executor( None, self._delete_intermediates_sync, repo, pipeline_id ) async def delete_pipeline(self, pipeline_id: str) -> None: if not self._ready: logger.warning( f"DatasetStore not configured — cannot delete {pipeline_id}." ) return repo = self._repo_for(pipeline_id) logger.info( f"DatasetStore.delete_pipeline: deleting entire folder {pipeline_id[:8]} from {repo}" ) loop = asyncio.get_running_loop() await loop.run_in_executor(None, self._delete_sync, repo, pipeline_id) # ── Upload with retry ───────────────────────────────────────────────────── def _upload_with_retry( self, repo: str, path_in_repo: str, data: bytes, content_type: str ) -> None: last_exc: Optional[Exception] = None delay = RETRY_BASE_DELAY for attempt in range(1, MAX_UPLOAD_RETRIES + 2): try: self._upload_sync(repo, path_in_repo, data, content_type) if attempt > 1: logger.info( f"DatasetStore: upload succeeded on attempt {attempt} " f"for {path_in_repo} → {repo}" ) return except Exception as exc: last_exc = exc status = self._extract_status(exc) if status not in RETRYABLE_STATUSES: logger.error( f"DatasetStore: non-retryable error uploading " f"{path_in_repo} to {repo} (HTTP {status}): {exc}" ) raise if attempt <= MAX_UPLOAD_RETRIES: logger.warning( f"DatasetStore: upload attempt {attempt} failed with " f"HTTP {status} for {path_in_repo} → {repo} — " f"retrying in {delay:.1f}s …" ) time.sleep(delay) delay *= RETRY_BACKOFF else: logger.error( f"DatasetStore: all {MAX_UPLOAD_RETRIES + 1} upload " f"attempts failed for {path_in_repo} → {repo}: {exc}" ) raise last_exc @staticmethod def _extract_status(exc: Exception) -> int: response = getattr(exc, "response", None) if response is not None: return getattr(response, "status_code", 0) return getattr(exc, "status_code", 0) # ── Sync internals ──────────────────────────────────────────────────────── def _upload_sync( self, repo: str, path_in_repo: str, data: bytes, content_type: str ) -> None: from huggingface_hub import HfApi import io api = HfApi(token=self.token) api.upload_file( path_or_fileobj=io.BytesIO(data), path_in_repo=path_in_repo, repo_id=repo, repo_type="dataset", commit_message=f"Pipeline asset: {path_in_repo}", ) logger.info( f"DatasetStore._upload_sync: uploaded {path_in_repo} → {repo} ({len(data):,} bytes)" ) def _download_sync(self, url: str) -> bytes: import requests headers = {"Authorization": f"Bearer {self.token}"} r = requests.get(url, headers=headers, timeout=60) r.raise_for_status() return r.content def _delete_intermediates_sync(self, repo: str, pipeline_id: str) -> None: from huggingface_hub import HfApi api = HfApi(token=self.token) deleted = [] skipped = [] for filename in INTERMEDIATE_FILES: path_in_repo = f"{pipeline_id}/{filename}" try: api.delete_file( path_in_repo=path_in_repo, repo_id=repo, repo_type="dataset", commit_message=( f"Pipeline {pipeline_id}: cleanup intermediate {filename}" ), ) deleted.append(filename) except Exception as e: skipped.append(filename) logger.debug(f"DatasetStore: skip delete {path_in_repo}: {e}") logger.info( f"DatasetStore: intermediates for {pipeline_id} → {repo} — " f"deleted={deleted}, skipped={skipped}" ) def _delete_sync(self, repo: str, pipeline_id: str) -> None: from huggingface_hub import HfApi api = HfApi(token=self.token) try: api.delete_folder( path_in_repo=pipeline_id, repo_id=repo, repo_type="dataset", commit_message=( f"Pipeline {pipeline_id} abandoned: deleted all assets" ), ) logger.info(f"DatasetStore: deleted folder {pipeline_id} from {repo}") except Exception as e: logger.warning( f"DatasetStore: failed to delete {pipeline_id} from {repo}: {e}" )