Florent Gbelidji commited on
Commit
16b916e
·
verified ·
1 Parent(s): ccf3e02

Sync DeepSeek OCR HF job code

Browse files
ds_batch_ocr/cli.py CHANGED
@@ -8,7 +8,6 @@ from pathlib import Path
8
  from typing import Optional, Sequence
9
 
10
  from .config import ArtifactLocator, AssembleSettings, DescribeSettings, ExtractSettings, InferenceSettings
11
- from .logging_utils import configure_logging
12
  from .server import (
13
  DeepSeekClient,
14
  base_url_from_env,
@@ -115,7 +114,10 @@ def safe_max_tokens(desired: int, stage: str) -> int:
115
 
116
 
117
  def main(argv: Optional[Sequence[str]] = None) -> None:
118
- configure_logging()
 
 
 
119
  args = parse_arguments(argv)
120
 
121
  stage = (args.stage or os.environ.get("PIPELINE_STAGE", "extract")).lower()
@@ -126,7 +128,7 @@ def main(argv: Optional[Sequence[str]] = None) -> None:
126
  base_url = base_url_from_env()
127
 
128
  launch_server = should_launch_server() and stage in {"extract", "describe"}
129
- server_process: Optional[subprocess.Popen] = None
130
 
131
  try:
132
  if launch_server:
@@ -357,8 +359,6 @@ def main(argv: Optional[Sequence[str]] = None) -> None:
357
  shutdown_server(server_process)
358
 
359
 
360
- import subprocess # noqa: E402
361
-
362
  __all__ = ["main", "parse_arguments", "getenv_float", "getenv_int"]
363
 
364
 
 
8
  from typing import Optional, Sequence
9
 
10
  from .config import ArtifactLocator, AssembleSettings, DescribeSettings, ExtractSettings, InferenceSettings
 
11
  from .server import (
12
  DeepSeekClient,
13
  base_url_from_env,
 
114
 
115
 
116
  def main(argv: Optional[Sequence[str]] = None) -> None:
117
+ logging.basicConfig(
118
+ level=os.environ.get("LOG_LEVEL", "INFO").upper(),
119
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
120
+ )
121
  args = parse_arguments(argv)
122
 
123
  stage = (args.stage or os.environ.get("PIPELINE_STAGE", "extract")).lower()
 
128
  base_url = base_url_from_env()
129
 
130
  launch_server = should_launch_server() and stage in {"extract", "describe"}
131
+ server_process: Optional["subprocess.Popen"] = None
132
 
133
  try:
134
  if launch_server:
 
359
  shutdown_server(server_process)
360
 
361
 
 
 
362
  __all__ = ["main", "parse_arguments", "getenv_float", "getenv_int"]
363
 
364
 
ds_batch_ocr/config.py CHANGED
@@ -104,7 +104,6 @@ class InferenceSettings:
104
  class ArtifactLocator:
105
  strategy: str = "local"
106
  repo_id: Optional[str] = None
107
- repo_type: Optional[str] = None
108
  job_id: Optional[str] = None
109
  job_owner: Optional[str] = None
110
  uri: Optional[str] = None
 
104
  class ArtifactLocator:
105
  strategy: str = "local"
106
  repo_id: Optional[str] = None
 
107
  job_id: Optional[str] = None
108
  job_owner: Optional[str] = None
109
  uri: Optional[str] = None
ds_batch_ocr/hf_io.py CHANGED
@@ -16,19 +16,6 @@ DEFAULT_CHUNK_MAX_FILES = 200
16
  DEFAULT_CHUNK_MAX_BYTES = 512 * 1024 * 1024
17
 
18
 
19
- def _read_positive_int_env(name: str, default: int) -> int:
20
- raw = os.environ.get(name)
21
- if not raw:
22
- return default
23
- try:
24
- value = int(raw)
25
- if value > 0:
26
- return value
27
- except ValueError:
28
- pass
29
- return default
30
-
31
-
32
  def _gather_files(output_dir: Path, path_in_repo: str) -> List[Tuple[Path, str, int]]:
33
  base = output_dir.resolve()
34
  entries: List[Tuple[Path, str, int]] = []
@@ -181,7 +168,6 @@ def maybe_upload_dataset(
181
  *,
182
  output_dir: Path,
183
  repo_id: Optional[str],
184
- repo_type: str,
185
  path_in_repo: str,
186
  commit_message: Optional[str],
187
  revision: Optional[str],
@@ -197,8 +183,8 @@ def maybe_upload_dataset(
197
  token = env_or_none("HF_TOKEN")
198
  api = HfApi(token=token)
199
 
200
- max_files = _read_positive_int_env("HF_UPLOAD_CHUNK_MAX_FILES", DEFAULT_CHUNK_MAX_FILES)
201
- max_bytes = _read_positive_int_env("HF_UPLOAD_CHUNK_MAX_BYTES", DEFAULT_CHUNK_MAX_BYTES)
202
 
203
  files = _gather_files(output_dir, path_in_repo or "")
204
  if not files:
@@ -214,10 +200,10 @@ def maybe_upload_dataset(
214
  total_batches,
215
  )
216
 
217
- LOGGER.info("Ensuring %s repo exists: repo_id=%s", repo_type, repo_id)
218
  create_repo(
219
  repo_id=repo_id,
220
- repo_type=repo_type,
221
  exist_ok=True,
222
  token=token,
223
  )
@@ -240,7 +226,7 @@ def maybe_upload_dataset(
240
  )
241
  api.create_commit(
242
  repo_id=repo_id,
243
- repo_type=repo_type,
244
  revision=revision,
245
  operations=operations,
246
  commit_message=message,
 
16
  DEFAULT_CHUNK_MAX_BYTES = 512 * 1024 * 1024
17
 
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def _gather_files(output_dir: Path, path_in_repo: str) -> List[Tuple[Path, str, int]]:
20
  base = output_dir.resolve()
21
  entries: List[Tuple[Path, str, int]] = []
 
168
  *,
169
  output_dir: Path,
170
  repo_id: Optional[str],
 
171
  path_in_repo: str,
172
  commit_message: Optional[str],
173
  revision: Optional[str],
 
183
  token = env_or_none("HF_TOKEN")
184
  api = HfApi(token=token)
185
 
186
+ max_files = int(os.environ.get("HF_UPLOAD_CHUNK_MAX_FILES", DEFAULT_CHUNK_MAX_FILES))
187
+ max_bytes = int(os.environ.get("HF_UPLOAD_CHUNK_MAX_BYTES", DEFAULT_CHUNK_MAX_BYTES))
188
 
189
  files = _gather_files(output_dir, path_in_repo or "")
190
  if not files:
 
200
  total_batches,
201
  )
202
 
203
+ LOGGER.info("Ensuring dataset repo exists: repo_id=%s", repo_id)
204
  create_repo(
205
  repo_id=repo_id,
206
+ repo_type="dataset",
207
  exist_ok=True,
208
  token=token,
209
  )
 
226
  )
227
  api.create_commit(
228
  repo_id=repo_id,
229
+ repo_type="dataset",
230
  revision=revision,
231
  operations=operations,
232
  commit_message=message,
ds_batch_ocr/stages.py CHANGED
@@ -8,6 +8,7 @@ from typing import Any, Dict, List, Optional
8
  import shutil
9
  from datasets import load_dataset
10
  from PIL import Image, ImageOps
 
11
 
12
  from .config import (
13
  AssembleSettings,
@@ -28,6 +29,10 @@ from .hf_io import maybe_upload_dataset, resolve_stage_dir, env_or_none
28
  LOGGER = logging.getLogger(__name__)
29
 
30
 
 
 
 
 
31
  def run_stage_extract(settings: ExtractSettings) -> None:
32
  dataset = load_dataset(
33
  settings.dataset_name,
@@ -36,6 +41,20 @@ def run_stage_extract(settings: ExtractSettings) -> None:
36
  streaming=settings.stream_dataset,
37
  )
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  settings.output_dir.mkdir(parents=True, exist_ok=True)
40
 
41
  documents: List[DocumentMetadata] = []
@@ -144,7 +163,7 @@ def run_stage_extract(settings: ExtractSettings) -> None:
144
  batch_contexts = []
145
  batch_requests = []
146
 
147
- for idx, sample in enumerate(dataset):
148
  if settings.max_samples is not None and idx >= settings.max_samples:
149
  break
150
 
@@ -234,7 +253,6 @@ def run_stage_extract(settings: ExtractSettings) -> None:
234
  maybe_upload_dataset(
235
  output_dir=settings.output_dir,
236
  repo_id=settings.upload_repo_id,
237
- repo_type=settings.upload_repo_type,
238
  path_in_repo=settings.upload_path_in_repo,
239
  commit_message=extract_commit,
240
  revision=settings.upload_revision,
@@ -443,7 +461,6 @@ def run_stage_describe(settings: DescribeSettings) -> None:
443
  maybe_upload_dataset(
444
  output_dir=settings.output_dir,
445
  repo_id=settings.upload_repo_id,
446
- repo_type=settings.upload_repo_type,
447
  path_in_repo=settings.upload_path_in_repo,
448
  commit_message=describe_commit,
449
  revision=settings.upload_revision,
@@ -502,6 +519,27 @@ def run_stage_assemble(settings: AssembleSettings) -> None:
502
  markdown = stage1_doc_path.read_text(encoding="utf-8")
503
  enriched_markdown = enrich_markdown_with_captions(markdown, description_map)
504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  final_doc_path = sample_output_dir / "document_final.md"
506
  write_text(final_doc_path, enriched_markdown)
507
 
@@ -551,6 +589,7 @@ def run_stage_assemble(settings: AssembleSettings) -> None:
551
  "sample_id": sample_id,
552
  "dataset_index": document.get("dataset_index"),
553
  "final_document_path": final_doc_rel_path,
 
554
  "figures": copied_figures,
555
  }
556
  )
@@ -561,6 +600,7 @@ def run_stage_assemble(settings: AssembleSettings) -> None:
561
  "dataset_index": document.get("dataset_index"),
562
  "document_markdown_path": final_doc_rel_path,
563
  "document_markdown_text": enriched_markdown,
 
564
  "figures": copied_figures,
565
  }
566
  )
@@ -581,7 +621,6 @@ def run_stage_assemble(settings: AssembleSettings) -> None:
581
  maybe_upload_dataset(
582
  output_dir=settings.output_dir,
583
  repo_id=settings.dataset_repo_id,
584
- repo_type=settings.dataset_repo_type,
585
  path_in_repo=settings.dataset_path_in_repo,
586
  commit_message=assemble_commit,
587
  revision=settings.dataset_branch,
@@ -589,7 +628,6 @@ def run_stage_assemble(settings: AssembleSettings) -> None:
589
  publish_dataset_viewer_assets(
590
  dataset_records=dataset_records,
591
  repo_id=settings.dataset_repo_id,
592
- repo_type=settings.dataset_repo_type,
593
  revision=settings.dataset_branch,
594
  commit_message=f"{assemble_commit} [dataset viewer]",
595
  )
@@ -648,18 +686,17 @@ def publish_dataset_viewer_assets(
648
  *,
649
  dataset_records: List[Dict[str, Any]],
650
  repo_id: Optional[str],
651
- repo_type: str,
652
  revision: Optional[str],
653
  commit_message: str,
654
  ) -> None:
655
- if not repo_id or repo_type.lower() != "dataset":
656
  return
657
  if not dataset_records:
658
  LOGGER.debug("No dataset records to publish for %s", repo_id)
659
  return
660
 
661
  try:
662
- from datasets import Dataset, Features, Sequence, Value # type: ignore
663
  except Exception as exc: # pragma: no cover - defensive logging
664
  LOGGER.warning("Datasets library unavailable; skipping viewer dataset publish: %s", exc)
665
  return
@@ -673,6 +710,7 @@ def publish_dataset_viewer_assets(
673
  "dataset_index": int(record.get("dataset_index") or 0),
674
  "document_markdown_path": str(record.get("document_markdown_path", "")),
675
  "document_markdown_text": record.get("document_markdown_text", ""),
 
676
  "figures": [
677
  {
678
  "figure_id": str(fig.get("figure_id", "")),
@@ -685,6 +723,12 @@ def publish_dataset_viewer_assets(
685
  )
686
 
687
  dataset = Dataset.from_list(normalized)
 
 
 
 
 
 
688
  token = env_or_none("HF_TOKEN")
689
  try:
690
  dataset.push_to_hub(
 
8
  import shutil
9
  from datasets import load_dataset
10
  from PIL import Image, ImageOps
11
+ from torch.utils.data import DataLoader
12
 
13
  from .config import (
14
  AssembleSettings,
 
29
  LOGGER = logging.getLogger(__name__)
30
 
31
 
32
+ def _collate_single_item(batch: List[Any]) -> Any:
33
+ return batch[0]
34
+
35
+
36
  def run_stage_extract(settings: ExtractSettings) -> None:
37
  dataset = load_dataset(
38
  settings.dataset_name,
 
41
  streaming=settings.stream_dataset,
42
  )
43
 
44
+ if settings.stream_dataset:
45
+ num_workers = max(0, getenv_int("EXTRACT_DATALOADER_WORKERS", 2))
46
+ prefetch_factor = max(1, getenv_int("EXTRACT_DATALOADER_PREFETCH", 2))
47
+ dataloader_kwargs: Dict[str, Any] = {
48
+ "batch_size": 1,
49
+ "num_workers": num_workers,
50
+ "collate_fn": _collate_single_item,
51
+ }
52
+ if num_workers > 0:
53
+ dataloader_kwargs["prefetch_factor"] = prefetch_factor
54
+ sample_iterator = iter(DataLoader(dataset, **dataloader_kwargs))
55
+ else:
56
+ sample_iterator = iter(dataset)
57
+
58
  settings.output_dir.mkdir(parents=True, exist_ok=True)
59
 
60
  documents: List[DocumentMetadata] = []
 
163
  batch_contexts = []
164
  batch_requests = []
165
 
166
+ for idx, sample in enumerate(sample_iterator):
167
  if settings.max_samples is not None and idx >= settings.max_samples:
168
  break
169
 
 
253
  maybe_upload_dataset(
254
  output_dir=settings.output_dir,
255
  repo_id=settings.upload_repo_id,
 
256
  path_in_repo=settings.upload_path_in_repo,
257
  commit_message=extract_commit,
258
  revision=settings.upload_revision,
 
461
  maybe_upload_dataset(
462
  output_dir=settings.output_dir,
463
  repo_id=settings.upload_repo_id,
 
464
  path_in_repo=settings.upload_path_in_repo,
465
  commit_message=describe_commit,
466
  revision=settings.upload_revision,
 
519
  markdown = stage1_doc_path.read_text(encoding="utf-8")
520
  enriched_markdown = enrich_markdown_with_captions(markdown, description_map)
521
 
522
+ document_with_boxes_relpath: Optional[str] = None
523
+ document_boxes_rel = document.get("document_with_boxes_path")
524
+ if document_boxes_rel:
525
+ source_boxes_path = stage1_dir / document_boxes_rel
526
+ if source_boxes_path.exists():
527
+ target_boxes_path = sample_output_dir / Path(document_boxes_rel).name
528
+ shutil.copy2(source_boxes_path, target_boxes_path)
529
+ document_with_boxes_relpath = (
530
+ Path(sample_id) / target_boxes_path.name
531
+ ).as_posix()
532
+ else:
533
+ LOGGER.warning("Document image with boxes missing: %s", source_boxes_path)
534
+ failures.append(
535
+ {
536
+ "sample_id": sample_id,
537
+ "dataset_index": document.get("dataset_index"),
538
+ "missing_path": source_boxes_path.as_posix(),
539
+ "reason": "document_with_boxes_missing",
540
+ }
541
+ )
542
+
543
  final_doc_path = sample_output_dir / "document_final.md"
544
  write_text(final_doc_path, enriched_markdown)
545
 
 
589
  "sample_id": sample_id,
590
  "dataset_index": document.get("dataset_index"),
591
  "final_document_path": final_doc_rel_path,
592
+ "document_with_boxes_image_path": document_with_boxes_relpath,
593
  "figures": copied_figures,
594
  }
595
  )
 
600
  "dataset_index": document.get("dataset_index"),
601
  "document_markdown_path": final_doc_rel_path,
602
  "document_markdown_text": enriched_markdown,
603
+ "document_with_boxes_image_path": document_with_boxes_relpath,
604
  "figures": copied_figures,
605
  }
606
  )
 
621
  maybe_upload_dataset(
622
  output_dir=settings.output_dir,
623
  repo_id=settings.dataset_repo_id,
 
624
  path_in_repo=settings.dataset_path_in_repo,
625
  commit_message=assemble_commit,
626
  revision=settings.dataset_branch,
 
628
  publish_dataset_viewer_assets(
629
  dataset_records=dataset_records,
630
  repo_id=settings.dataset_repo_id,
 
631
  revision=settings.dataset_branch,
632
  commit_message=f"{assemble_commit} [dataset viewer]",
633
  )
 
686
  *,
687
  dataset_records: List[Dict[str, Any]],
688
  repo_id: Optional[str],
 
689
  revision: Optional[str],
690
  commit_message: str,
691
  ) -> None:
692
+ if not repo_id:
693
  return
694
  if not dataset_records:
695
  LOGGER.debug("No dataset records to publish for %s", repo_id)
696
  return
697
 
698
  try:
699
+ from datasets import Dataset, Features, Sequence, Value, Image # type: ignore
700
  except Exception as exc: # pragma: no cover - defensive logging
701
  LOGGER.warning("Datasets library unavailable; skipping viewer dataset publish: %s", exc)
702
  return
 
710
  "dataset_index": int(record.get("dataset_index") or 0),
711
  "document_markdown_path": str(record.get("document_markdown_path", "")),
712
  "document_markdown_text": record.get("document_markdown_text", ""),
713
+ "document_with_boxes_image": record.get("document_with_boxes_image_path"),
714
  "figures": [
715
  {
716
  "figure_id": str(fig.get("figure_id", "")),
 
723
  )
724
 
725
  dataset = Dataset.from_list(normalized)
726
+ if "document_with_boxes_image" in dataset.column_names:
727
+ try:
728
+ dataset = dataset.cast_column("document_with_boxes_image", Image())
729
+ except Exception as exc: # pragma: no cover - defensive logging
730
+ LOGGER.warning("Failed to cast document_with_boxes_image column to Image: %s", exc)
731
+
732
  token = env_or_none("HF_TOKEN")
733
  try:
734
  dataset.push_to_hub(