File size: 13,064 Bytes
82e32a4
 
 
9504c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82e32a4
 
 
 
a141e1e
82e32a4
 
 
 
 
 
d52cde0
 
 
 
 
 
a141e1e
9504c1e
 
 
 
a141e1e
82e32a4
 
9504c1e
a069344
 
 
 
 
 
 
d52cde0
9504c1e
 
d52cde0
9504c1e
82e32a4
a069344
 
 
 
 
 
 
 
82e32a4
 
 
 
 
9504c1e
 
a069344
 
9504c1e
 
a069344
9504c1e
 
 
 
 
 
 
 
 
 
a069344
 
 
7cf11f8
9504c1e
7cf11f8
 
a069344
 
7cf11f8
 
 
a069344
 
 
 
 
7cf11f8
 
 
9504c1e
 
 
 
 
 
82e32a4
 
 
 
 
 
 
 
 
 
 
 
 
 
9504c1e
82e32a4
9504c1e
 
7cf11f8
 
 
 
 
a141e1e
9504c1e
a141e1e
7cf11f8
 
 
 
 
 
 
82e32a4
 
 
 
9504c1e
 
82e32a4
9504c1e
 
 
7cf11f8
 
 
 
9504c1e
7cf11f8
 
 
 
 
9504c1e
 
 
7cf11f8
 
 
9504c1e
 
7cf11f8
 
9504c1e
 
7cf11f8
 
 
 
 
82e32a4
d52cde0
 
a141e1e
 
 
 
d52cde0
 
9504c1e
7cf11f8
 
 
d52cde0
a141e1e
9504c1e
a141e1e
d52cde0
 
 
a141e1e
 
 
d52cde0
 
9504c1e
7cf11f8
 
 
d52cde0
9504c1e
d52cde0
a141e1e
 
 
9504c1e
a141e1e
 
 
 
9504c1e
a141e1e
9504c1e
a141e1e
 
 
9504c1e
a141e1e
9504c1e
a141e1e
 
 
9504c1e
a141e1e
 
 
 
9504c1e
a141e1e
 
 
 
 
 
9504c1e
a141e1e
 
 
 
 
 
 
9504c1e
a141e1e
 
9504c1e
a141e1e
 
 
 
 
 
 
 
d52cde0
82e32a4
a141e1e
9504c1e
a141e1e
82e32a4
 
 
 
 
 
 
9504c1e
82e32a4
 
 
a141e1e
7cf11f8
a141e1e
82e32a4
 
 
 
 
 
1176c4b
 
9504c1e
d52cde0
 
9504c1e
d52cde0
 
 
 
 
 
 
 
9504c1e
d52cde0
a141e1e
 
 
d52cde0
 
 
 
9504c1e
d52cde0
 
9504c1e
d52cde0
 
 
9504c1e
1176c4b
d52cde0
1176c4b
 
 
d52cde0
9504c1e
1176c4b
a141e1e
 
 
1176c4b
9504c1e
1176c4b
a141e1e
9504c1e
a141e1e
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
"""
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}"
            )