YTShortMakerArchx commited on
Commit
9504c1e
Β·
verified Β·
1 Parent(s): e8adbc2

Update dataset.py

Browse files
Files changed (1) hide show
  1. dataset.py +96 -85
dataset.py CHANGED
@@ -1,23 +1,21 @@
1
  """
2
  DatasetStore β€” HuggingFace Dataset read/write helper
3
  ═════════════════════════════════════════════════════
4
- Saves pipeline assets (audio WAV, timestamps JSON, video MP4) to a
5
- private HuggingFace dataset repo and returns public-ish URLs.
6
-
7
- Each pipeline gets its own folder: {pipeline_id}/audio.wav
8
- {pipeline_id}/align_timestamps.json
9
- {pipeline_id}/video.mp4
10
-
11
- Files are overwritten on re-runs (same path = same pipeline stage).
12
-
13
- 412 / concurrent-commit handling
14
- ─────────────────────────────────
15
- HF datasets are Git repos β€” parallel uploads from different pipelines
16
- can collide at commit time and return HTTP 412 "Precondition Failed".
17
- _upload_sync retries up to MAX_UPLOAD_RETRIES times with exponential
18
- backoff before giving up. In practice two retries resolve ~95 % of
19
- collisions because each retry re-fetches the latest HEAD before
20
- committing, so the window for a second collision is tiny.
21
  """
22
 
23
  import asyncio
@@ -36,24 +34,50 @@ INTERMEDIATE_FILES = [
36
  ]
37
 
38
  # ── Retry config ──────────────────────────────────────────────────────────────
39
- MAX_UPLOAD_RETRIES = 2 # extra attempts after the first failure
40
- RETRY_BASE_DELAY = 2.0 # seconds before first retry
41
- RETRY_BACKOFF = 2.0 # multiplier: 2 s β†’ 4 s β†’ …
42
- # HTTP status codes that are worth retrying (git conflicts + transient server errors)
43
- RETRYABLE_STATUSES = {412, 500, 502, 503, 504}
44
 
45
 
46
  class DatasetStore:
47
- def __init__(self, hf_token: str, dataset_repo: str):
48
  self.token = hf_token
49
- self.repo = dataset_repo
 
50
  self._ready = bool(hf_token and dataset_repo)
 
51
 
52
  if not self._ready:
53
  logger.warning(
54
  "DatasetStore: HF_TOKEN or HF_DATASET not set. "
55
  "Assets will not persist across controller restarts."
56
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  # ── Public API ────────────────────────────────────────────────────────────
59
 
@@ -64,32 +88,42 @@ class DatasetStore:
64
  data: bytes,
65
  content_type: str = "application/octet-stream",
66
  ) -> str:
67
- """Upload bytes to {pipeline_id}/{filename}. Returns its URL."""
68
  if not self._ready:
69
  logger.warning(f"DatasetStore not configured β€” {filename} not persisted.")
70
  return f"memory://{pipeline_id}/{filename}"
71
 
 
72
  path_in_repo = f"{pipeline_id}/{filename}"
73
- loop = asyncio.get_running_loop()
 
74
  await loop.run_in_executor(
75
- None, self._upload_with_retry, path_in_repo, data, content_type
76
  )
77
- return HF_RAW_URL.format(repo=self.repo, path=path_in_repo)
78
 
79
  async def load(self, pipeline_id: str, filename: str) -> bytes:
80
- """Fetch file bytes from the dataset."""
81
  if not self._ready:
82
  raise RuntimeError("DatasetStore not configured.")
 
 
83
  path_in_repo = f"{pipeline_id}/{filename}"
84
- url = HF_RAW_URL.format(repo=self.repo, path=path_in_repo)
85
- loop = asyncio.get_running_loop()
86
- return await loop.run_in_executor(None, self._download_sync, url)
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  async def delete_intermediates(self, pipeline_id: str) -> None:
89
- """
90
- Delete audio + timestamp files for a pipeline but KEEP video.mp4.
91
- Called after the frontend confirms it has received the finished video.
92
- """
93
  if not self._ready:
94
  logger.warning(
95
  f"DatasetStore not configured β€” cannot delete intermediates "
@@ -97,69 +131,56 @@ class DatasetStore:
97
  )
98
  return
99
 
 
100
  loop = asyncio.get_running_loop()
101
  await loop.run_in_executor(
102
- None, self._delete_intermediates_sync, pipeline_id
103
  )
104
 
105
  async def delete_pipeline(self, pipeline_id: str) -> None:
106
- """
107
- Delete ALL assets for a pipeline (audio + timestamps + video).
108
- Only called by the abandoned-client watchdog when no video was produced.
109
- """
110
  if not self._ready:
111
  logger.warning(
112
  f"DatasetStore not configured β€” cannot delete {pipeline_id}."
113
  )
114
  return
115
 
 
116
  loop = asyncio.get_running_loop()
117
- await loop.run_in_executor(None, self._delete_sync, pipeline_id)
118
 
119
  # ── Upload with retry ─────────────────────────────────────────────────────
120
 
121
  def _upload_with_retry(
122
- self, path_in_repo: str, data: bytes, content_type: str
123
  ) -> None:
124
- """
125
- Try _upload_sync up to (1 + MAX_UPLOAD_RETRIES) times.
126
-
127
- On a retryable HTTP error (412 git conflict, 5xx transient):
128
- attempt 1 fails β†’ wait RETRY_BASE_DELAY seconds, try again
129
- attempt 2 fails β†’ wait RETRY_BASE_DELAY * RETRY_BACKOFF seconds, try again
130
- attempt 3 fails β†’ re-raise the original exception
131
-
132
- On any other exception (auth error, network down, etc.) β†’ raise immediately.
133
- """
134
  last_exc: Optional[Exception] = None
135
  delay = RETRY_BASE_DELAY
136
 
137
- for attempt in range(1, MAX_UPLOAD_RETRIES + 2): # 1, 2, 3
138
  try:
139
- self._upload_sync(path_in_repo, data, content_type)
140
  if attempt > 1:
141
  logger.info(
142
  f"DatasetStore: upload succeeded on attempt {attempt} "
143
- f"for {path_in_repo}"
144
  )
145
- return # success β€” done
146
 
147
  except Exception as exc:
148
  last_exc = exc
149
- status = self._extract_status(exc)
150
 
151
  if status not in RETRYABLE_STATUSES:
152
- # Non-retryable (401, 403, bad token, etc.) β€” fail fast
153
  logger.error(
154
  f"DatasetStore: non-retryable error uploading "
155
- f"{path_in_repo} (HTTP {status}): {exc}"
156
  )
157
  raise
158
 
159
  if attempt <= MAX_UPLOAD_RETRIES:
160
  logger.warning(
161
  f"DatasetStore: upload attempt {attempt} failed with "
162
- f"HTTP {status} for {path_in_repo} β€” "
163
  f"retrying in {delay:.1f}s …"
164
  )
165
  time.sleep(delay)
@@ -167,28 +188,22 @@ class DatasetStore:
167
  else:
168
  logger.error(
169
  f"DatasetStore: all {MAX_UPLOAD_RETRIES + 1} upload "
170
- f"attempts failed for {path_in_repo}: {exc}"
171
  )
172
 
173
- raise last_exc # type: ignore[misc]
174
 
175
  @staticmethod
176
  def _extract_status(exc: Exception) -> int:
177
- """
178
- Pull the HTTP status code out of a huggingface_hub exception.
179
- Returns 0 if we cannot determine the status (network error, etc.).
180
- """
181
- # huggingface_hub raises HfHubHTTPError which has a .response attribute
182
  response = getattr(exc, "response", None)
183
  if response is not None:
184
  return getattr(response, "status_code", 0)
185
- # Some versions expose the code directly
186
  return getattr(exc, "status_code", 0)
187
 
188
  # ── Sync internals ────────────────────────────────────────────────────────
189
 
190
  def _upload_sync(
191
- self, path_in_repo: str, data: bytes, content_type: str
192
  ) -> None:
193
  from huggingface_hub import HfApi
194
  import io
@@ -197,12 +212,12 @@ class DatasetStore:
197
  api.upload_file(
198
  path_or_fileobj=io.BytesIO(data),
199
  path_in_repo=path_in_repo,
200
- repo_id=self.repo,
201
  repo_type="dataset",
202
  commit_message=f"Pipeline asset: {path_in_repo}",
203
  )
204
  logger.info(
205
- f"DatasetStore: uploaded {path_in_repo} ({len(data):,} bytes)"
206
  )
207
 
208
  def _download_sync(self, url: str) -> bytes:
@@ -212,11 +227,10 @@ class DatasetStore:
212
  r.raise_for_status()
213
  return r.content
214
 
215
- def _delete_intermediates_sync(self, pipeline_id: str) -> None:
216
- """Delete each intermediate file individually, leaving video.mp4 intact."""
217
  from huggingface_hub import HfApi
218
 
219
- api = HfApi(token=self.token)
220
  deleted = []
221
  skipped = []
222
 
@@ -225,7 +239,7 @@ class DatasetStore:
225
  try:
226
  api.delete_file(
227
  path_in_repo=path_in_repo,
228
- repo_id=self.repo,
229
  repo_type="dataset",
230
  commit_message=(
231
  f"Pipeline {pipeline_id}: cleanup intermediate {filename}"
@@ -234,31 +248,28 @@ class DatasetStore:
234
  deleted.append(filename)
235
  except Exception as e:
236
  skipped.append(filename)
237
- logger.debug(
238
- f"DatasetStore: skip delete {path_in_repo}: {e}"
239
- )
240
 
241
  logger.info(
242
- f"DatasetStore: intermediates for {pipeline_id} β€” "
243
  f"deleted={deleted}, skipped={skipped}"
244
  )
245
 
246
- def _delete_sync(self, pipeline_id: str) -> None:
247
- """Delete the entire pipeline folder (used for abandoned pipelines)."""
248
  from huggingface_hub import HfApi
249
 
250
  api = HfApi(token=self.token)
251
  try:
252
  api.delete_folder(
253
  path_in_repo=pipeline_id,
254
- repo_id=self.repo,
255
  repo_type="dataset",
256
  commit_message=(
257
  f"Pipeline {pipeline_id} abandoned: deleted all assets"
258
  ),
259
  )
260
- logger.info(f"DatasetStore: deleted folder {pipeline_id}")
261
  except Exception as e:
262
  logger.warning(
263
- f"DatasetStore: failed to delete {pipeline_id}: {e}"
264
  )
 
1
  """
2
  DatasetStore β€” HuggingFace Dataset read/write helper
3
  ═════════════════════════════════════════════════════
4
+ Dual-dataset mode:
5
+ - HF_DATASET (primary, always required)
6
+ - HF_DATASET_2 (secondary, optional β€” set in HF Space secrets)
7
+
8
+ Save: picks a dataset by hashing the pipeline_id (deterministic β€”
9
+ same pipeline always goes to the same dataset, so re-runs and
10
+ multi-file pipelines are always consistent within one repo).
11
+
12
+ Load: reads from whichever dataset that pipeline was assigned to.
13
+ If the file is missing there, falls back to checking the other
14
+ dataset automatically.
15
+
16
+ Delete: operates on the correct dataset for that pipeline.
17
+
18
+ 412 retry: 2 retries with exponential backoff before giving up.
 
 
19
  """
20
 
21
  import asyncio
 
34
  ]
35
 
36
  # ── Retry config ──────────────────────────────────────────────────────────────
37
+ MAX_UPLOAD_RETRIES = 2
38
+ RETRY_BASE_DELAY = 2.0
39
+ RETRY_BACKOFF = 2.0
40
+ RETRYABLE_STATUSES = {412, 500, 502, 503, 504}
 
41
 
42
 
43
  class DatasetStore:
44
+ def __init__(self, hf_token: str, dataset_repo: str, dataset_repo_2: str = ""):
45
  self.token = hf_token
46
+ self.repo_1 = dataset_repo
47
+ self.repo_2 = dataset_repo_2.strip() if dataset_repo_2 else ""
48
  self._ready = bool(hf_token and dataset_repo)
49
+ self._dual = bool(self._ready and self.repo_2)
50
 
51
  if not self._ready:
52
  logger.warning(
53
  "DatasetStore: HF_TOKEN or HF_DATASET not set. "
54
  "Assets will not persist across controller restarts."
55
  )
56
+ elif self._dual:
57
+ logger.info(
58
+ f"DatasetStore: dual-dataset mode β€” "
59
+ f"{self.repo_1} + {self.repo_2}"
60
+ )
61
+ else:
62
+ logger.info(f"DatasetStore: single-dataset mode β€” {self.repo_1}")
63
+
64
+ # ── Dataset picker ────────────────────────────────────────────────────────
65
+
66
+ def _repo_for(self, pipeline_id: str) -> str:
67
+ """
68
+ Deterministically pick a repo for this pipeline.
69
+ Uses the first hex char of the UUID β€” even = repo_1, odd = repo_2.
70
+ Same pipeline always maps to the same repo so all its files stay together.
71
+ """
72
+ if not self._dual:
73
+ return self.repo_1
74
+ return self.repo_2 if int(pipeline_id[0], 16) % 2 == 1 else self.repo_1
75
+
76
+ def _other_repo(self, repo: str) -> Optional[str]:
77
+ """Return the other repo (for fallback reads)."""
78
+ if not self._dual:
79
+ return None
80
+ return self.repo_2 if repo == self.repo_1 else self.repo_1
81
 
82
  # ── Public API ────────────────────────────────────────────────────────────
83
 
 
88
  data: bytes,
89
  content_type: str = "application/octet-stream",
90
  ) -> str:
 
91
  if not self._ready:
92
  logger.warning(f"DatasetStore not configured β€” {filename} not persisted.")
93
  return f"memory://{pipeline_id}/{filename}"
94
 
95
+ repo = self._repo_for(pipeline_id)
96
  path_in_repo = f"{pipeline_id}/{filename}"
97
+ loop = asyncio.get_running_loop()
98
+
99
  await loop.run_in_executor(
100
+ None, self._upload_with_retry, repo, path_in_repo, data, content_type
101
  )
102
+ return HF_RAW_URL.format(repo=repo, path=path_in_repo)
103
 
104
  async def load(self, pipeline_id: str, filename: str) -> bytes:
 
105
  if not self._ready:
106
  raise RuntimeError("DatasetStore not configured.")
107
+
108
+ repo = self._repo_for(pipeline_id)
109
  path_in_repo = f"{pipeline_id}/{filename}"
110
+ url = HF_RAW_URL.format(repo=repo, path=path_in_repo)
111
+ loop = asyncio.get_running_loop()
112
+
113
+ try:
114
+ return await loop.run_in_executor(None, self._download_sync, url)
115
+ except Exception as primary_err:
116
+ other = self._other_repo(repo)
117
+ if not other:
118
+ raise
119
+ logger.warning(
120
+ f"DatasetStore: load failed from {repo} for {path_in_repo}, "
121
+ f"trying {other}: {primary_err}"
122
+ )
123
+ fallback_url = HF_RAW_URL.format(repo=other, path=path_in_repo)
124
+ return await loop.run_in_executor(None, self._download_sync, fallback_url)
125
 
126
  async def delete_intermediates(self, pipeline_id: str) -> None:
 
 
 
 
127
  if not self._ready:
128
  logger.warning(
129
  f"DatasetStore not configured β€” cannot delete intermediates "
 
131
  )
132
  return
133
 
134
+ repo = self._repo_for(pipeline_id)
135
  loop = asyncio.get_running_loop()
136
  await loop.run_in_executor(
137
+ None, self._delete_intermediates_sync, repo, pipeline_id
138
  )
139
 
140
  async def delete_pipeline(self, pipeline_id: str) -> None:
 
 
 
 
141
  if not self._ready:
142
  logger.warning(
143
  f"DatasetStore not configured β€” cannot delete {pipeline_id}."
144
  )
145
  return
146
 
147
+ repo = self._repo_for(pipeline_id)
148
  loop = asyncio.get_running_loop()
149
+ await loop.run_in_executor(None, self._delete_sync, repo, pipeline_id)
150
 
151
  # ── Upload with retry ─────────────────────────────────────────────────────
152
 
153
  def _upload_with_retry(
154
+ self, repo: str, path_in_repo: str, data: bytes, content_type: str
155
  ) -> None:
 
 
 
 
 
 
 
 
 
 
156
  last_exc: Optional[Exception] = None
157
  delay = RETRY_BASE_DELAY
158
 
159
+ for attempt in range(1, MAX_UPLOAD_RETRIES + 2):
160
  try:
161
+ self._upload_sync(repo, path_in_repo, data, content_type)
162
  if attempt > 1:
163
  logger.info(
164
  f"DatasetStore: upload succeeded on attempt {attempt} "
165
+ f"for {path_in_repo} β†’ {repo}"
166
  )
167
+ return
168
 
169
  except Exception as exc:
170
  last_exc = exc
171
+ status = self._extract_status(exc)
172
 
173
  if status not in RETRYABLE_STATUSES:
 
174
  logger.error(
175
  f"DatasetStore: non-retryable error uploading "
176
+ f"{path_in_repo} to {repo} (HTTP {status}): {exc}"
177
  )
178
  raise
179
 
180
  if attempt <= MAX_UPLOAD_RETRIES:
181
  logger.warning(
182
  f"DatasetStore: upload attempt {attempt} failed with "
183
+ f"HTTP {status} for {path_in_repo} β†’ {repo} β€” "
184
  f"retrying in {delay:.1f}s …"
185
  )
186
  time.sleep(delay)
 
188
  else:
189
  logger.error(
190
  f"DatasetStore: all {MAX_UPLOAD_RETRIES + 1} upload "
191
+ f"attempts failed for {path_in_repo} β†’ {repo}: {exc}"
192
  )
193
 
194
+ raise last_exc
195
 
196
  @staticmethod
197
  def _extract_status(exc: Exception) -> int:
 
 
 
 
 
198
  response = getattr(exc, "response", None)
199
  if response is not None:
200
  return getattr(response, "status_code", 0)
 
201
  return getattr(exc, "status_code", 0)
202
 
203
  # ── Sync internals ────────────────────────────────────────────────────────
204
 
205
  def _upload_sync(
206
+ self, repo: str, path_in_repo: str, data: bytes, content_type: str
207
  ) -> None:
208
  from huggingface_hub import HfApi
209
  import io
 
212
  api.upload_file(
213
  path_or_fileobj=io.BytesIO(data),
214
  path_in_repo=path_in_repo,
215
+ repo_id=repo,
216
  repo_type="dataset",
217
  commit_message=f"Pipeline asset: {path_in_repo}",
218
  )
219
  logger.info(
220
+ f"DatasetStore: uploaded {path_in_repo} β†’ {repo} ({len(data):,} bytes)"
221
  )
222
 
223
  def _download_sync(self, url: str) -> bytes:
 
227
  r.raise_for_status()
228
  return r.content
229
 
230
+ def _delete_intermediates_sync(self, repo: str, pipeline_id: str) -> None:
 
231
  from huggingface_hub import HfApi
232
 
233
+ api = HfApi(token=self.token)
234
  deleted = []
235
  skipped = []
236
 
 
239
  try:
240
  api.delete_file(
241
  path_in_repo=path_in_repo,
242
+ repo_id=repo,
243
  repo_type="dataset",
244
  commit_message=(
245
  f"Pipeline {pipeline_id}: cleanup intermediate {filename}"
 
248
  deleted.append(filename)
249
  except Exception as e:
250
  skipped.append(filename)
251
+ logger.debug(f"DatasetStore: skip delete {path_in_repo}: {e}")
 
 
252
 
253
  logger.info(
254
+ f"DatasetStore: intermediates for {pipeline_id} β†’ {repo} β€” "
255
  f"deleted={deleted}, skipped={skipped}"
256
  )
257
 
258
+ def _delete_sync(self, repo: str, pipeline_id: str) -> None:
 
259
  from huggingface_hub import HfApi
260
 
261
  api = HfApi(token=self.token)
262
  try:
263
  api.delete_folder(
264
  path_in_repo=pipeline_id,
265
+ repo_id=repo,
266
  repo_type="dataset",
267
  commit_message=(
268
  f"Pipeline {pipeline_id} abandoned: deleted all assets"
269
  ),
270
  )
271
+ logger.info(f"DatasetStore: deleted folder {pipeline_id} from {repo}")
272
  except Exception as e:
273
  logger.warning(
274
+ f"DatasetStore: failed to delete {pipeline_id} from {repo}: {e}"
275
  )