Florent Gbelidji commited on
Commit
b44418a
·
verified ·
1 Parent(s): a9e7119

Sync DeepSeek OCR HF job code

Browse files
Files changed (1) hide show
  1. ds_batch_ocr/hf_io.py +104 -19
ds_batch_ocr/hf_io.py CHANGED
@@ -1,11 +1,13 @@
1
  from __future__ import annotations
2
 
3
  import logging
 
4
  import tarfile
5
  from datetime import datetime
6
  from pathlib import Path
7
- from typing import Callable, Dict, Optional
8
 
 
9
  from .config import ArtifactLocator
10
  from .dependencies import bootstrap
11
 
@@ -16,6 +18,65 @@ HfApi = deps["HfApi"]
16
 
17
  LOGGER = logging.getLogger(__name__)
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  def unpack_archives(target_dir: Path) -> None:
21
  for archive in list(target_dir.glob("**/*.tar.gz")):
@@ -140,30 +201,57 @@ def maybe_upload_dataset(
140
  )
141
 
142
  token = env_or_none("HF_TOKEN")
143
- LOGGER.info("Ensuring %s repo exists: repo_id=%s", repo_type, repo_id)
144
- create_repo(
145
- repo_id=repo_id,
146
- repo_type=repo_type,
147
- exist_ok=True,
148
- token=token,
149
- )
 
 
150
 
 
 
151
  LOGGER.info(
152
- "Uploading assembled outputs to %s (path_in_repo=%s, revision=%s)",
 
153
  repo_id,
154
- path_in_repo,
155
- revision,
156
  )
157
- HfApi().upload_folder(
158
- folder_path=str(output_dir),
 
159
  repo_id=repo_id,
160
  repo_type=repo_type,
161
- path_in_repo=path_in_repo or "",
162
- commit_message=commit_message,
163
- revision=revision,
164
  token=token,
165
  )
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
  def env_or_none(name: str) -> Optional[str]:
169
  value = os.environ.get(name)
@@ -171,9 +259,6 @@ def env_or_none(name: str) -> Optional[str]:
171
  value = value.strip()
172
  return value or None
173
 
174
-
175
- import os
176
-
177
  __all__ = [
178
  "unpack_archives",
179
  "download_job_artifact",
 
1
  from __future__ import annotations
2
 
3
  import logging
4
+ import os
5
  import tarfile
6
  from datetime import datetime
7
  from pathlib import Path
8
+ from typing import Callable, Dict, List, Optional, Tuple
9
 
10
+ from huggingface_hub import CommitOperationAdd
11
  from .config import ArtifactLocator
12
  from .dependencies import bootstrap
13
 
 
18
 
19
  LOGGER = logging.getLogger(__name__)
20
 
21
+ DEFAULT_CHUNK_MAX_FILES = 200
22
+ DEFAULT_CHUNK_MAX_BYTES = 512 * 1024 * 1024
23
+
24
+
25
+ def _read_positive_int_env(name: str, default: int) -> int:
26
+ raw = os.environ.get(name)
27
+ if not raw:
28
+ return default
29
+ try:
30
+ value = int(raw)
31
+ if value > 0:
32
+ return value
33
+ except ValueError:
34
+ pass
35
+ return default
36
+
37
+
38
+ def _gather_files(output_dir: Path, path_in_repo: str) -> List[Tuple[Path, str, int]]:
39
+ base = output_dir.resolve()
40
+ entries: List[Tuple[Path, str, int]] = []
41
+ prefix = path_in_repo.strip("/")
42
+ for local_path in sorted(base.rglob("*")):
43
+ if not local_path.is_file():
44
+ continue
45
+ rel_path = local_path.relative_to(base).as_posix()
46
+ repo_path = f"{prefix}/{rel_path}" if prefix else rel_path
47
+ try:
48
+ size = local_path.stat().st_size
49
+ except OSError:
50
+ size = 0
51
+ entries.append((local_path, repo_path, size))
52
+ return entries
53
+
54
+
55
+ def _make_batches(
56
+ files: List[Tuple[Path, str, int]],
57
+ max_files: int,
58
+ max_bytes: int,
59
+ ) -> List[List[Tuple[Path, str, int]]]:
60
+ if not files:
61
+ return []
62
+
63
+ batches: List[List[Tuple[Path, str, int]]] = []
64
+ current: List[Tuple[Path, str, int]] = []
65
+ current_bytes = 0
66
+
67
+ for entry in files:
68
+ current.append(entry)
69
+ current_bytes += max(entry[2], 0)
70
+ if len(current) >= max_files or current_bytes >= max_bytes:
71
+ batches.append(current)
72
+ current = []
73
+ current_bytes = 0
74
+
75
+ if current:
76
+ batches.append(current)
77
+
78
+ return batches
79
+
80
 
81
  def unpack_archives(target_dir: Path) -> None:
82
  for archive in list(target_dir.glob("**/*.tar.gz")):
 
201
  )
202
 
203
  token = env_or_none("HF_TOKEN")
204
+ api = HfApi(token=token)
205
+
206
+ max_files = _read_positive_int_env("HF_UPLOAD_CHUNK_MAX_FILES", DEFAULT_CHUNK_MAX_FILES)
207
+ max_bytes = _read_positive_int_env("HF_UPLOAD_CHUNK_MAX_BYTES", DEFAULT_CHUNK_MAX_BYTES)
208
+
209
+ files = _gather_files(output_dir, path_in_repo or "")
210
+ if not files:
211
+ LOGGER.info("Nothing to upload from %s", output_dir)
212
+ return
213
 
214
+ batches = _make_batches(files, max_files=max_files, max_bytes=max_bytes)
215
+ total_batches = len(batches) or 1
216
  LOGGER.info(
217
+ "Uploading %s files to %s in %s commit(s)",
218
+ len(files),
219
  repo_id,
220
+ total_batches,
 
221
  )
222
+
223
+ LOGGER.info("Ensuring %s repo exists: repo_id=%s", repo_type, repo_id)
224
+ create_repo(
225
  repo_id=repo_id,
226
  repo_type=repo_type,
227
+ exist_ok=True,
 
 
228
  token=token,
229
  )
230
 
231
+ for index, batch in enumerate(batches, start=1):
232
+ operations = [
233
+ CommitOperationAdd(path_in_repo=repo_path, path_or_fileobj=local_path)
234
+ for local_path, repo_path, _ in batch
235
+ ]
236
+ message = commit_message
237
+ if total_batches > 1:
238
+ message = f"{commit_message} (batch {index}/{total_batches})"
239
+
240
+ LOGGER.info(
241
+ "Commit %s/%s | files=%s | path_in_repo=%s",
242
+ index,
243
+ total_batches,
244
+ len(batch),
245
+ path_in_repo or ".",
246
+ )
247
+ api.create_commit(
248
+ repo_id=repo_id,
249
+ repo_type=repo_type,
250
+ revision=revision,
251
+ operations=operations,
252
+ commit_message=message,
253
+ )
254
+
255
 
256
  def env_or_none(name: str) -> Optional[str]:
257
  value = os.environ.get(name)
 
259
  value = value.strip()
260
  return value or None
261
 
 
 
 
262
  __all__ = [
263
  "unpack_archives",
264
  "download_job_artifact",