Florent Gbelidji commited on
Commit
38b9700
·
verified ·
1 Parent(s): e58e01e

Sync DeepSeek OCR HF job code

Browse files
Files changed (2) hide show
  1. ds_batch_ocr/config.py +1 -1
  2. ds_batch_ocr/stages.py +59 -110
ds_batch_ocr/config.py CHANGED
@@ -32,7 +32,7 @@ class DocumentMetadata:
32
  document_markdown_text: str
33
  document_final_markdown_path: Optional[str] = None
34
  document_final_markdown_text: Optional[str] = None
35
- figures: List[FigureMetadata] = field(default_factory=list)
36
 
37
 
38
  @dataclass
 
32
  document_markdown_text: str
33
  document_final_markdown_path: Optional[str] = None
34
  document_final_markdown_text: Optional[str] = None
35
+ extracted_figures: List[FigureMetadata] = field(default_factory=list)
36
 
37
 
38
  @dataclass
ds_batch_ocr/stages.py CHANGED
@@ -89,47 +89,6 @@ def write_jsonl_iter(path: Path, rows: Iterable[Dict[str, Any]]) -> int:
89
  return count
90
 
91
 
92
- def _resolve_image_path(base_dir: Path, value: Any) -> str:
93
- if value is None:
94
- return ""
95
-
96
- if isinstance(value, (list, tuple, set)):
97
- candidate = ""
98
- for item in value:
99
- if item not in (None, ""):
100
- candidate = item
101
- break
102
- value = candidate or ""
103
-
104
- if isinstance(value, bytes):
105
- try:
106
- path_str = value.decode("utf-8")
107
- except Exception:
108
- path_str = value.decode("utf-8", errors="ignore")
109
- elif isinstance(value, Path):
110
- path_str = value.as_posix()
111
- else:
112
- path_str = str(value)
113
-
114
- if not path_str:
115
- return ""
116
-
117
- path = Path(path_str)
118
- if not path.is_absolute():
119
- path = base_dir / path
120
-
121
- if path.suffix.lower() != ".png":
122
- png_candidate = path.with_suffix(".png")
123
- if png_candidate.exists():
124
- path = png_candidate
125
-
126
- if not path.exists():
127
- LOGGER.warning("Image asset missing when preparing dataset | path=%s", path)
128
- return path.as_posix()
129
-
130
- return path.as_posix()
131
-
132
-
133
  def _dataset_features() -> Features:
134
  return Features(
135
  {
@@ -138,11 +97,8 @@ def _dataset_features() -> Features:
138
  "source_image_path": HfImage(),
139
  "document_with_boxes_image_path": HfImage(),
140
  "document_markdown_text": Value("string"),
141
- "figures": {
142
- "figure_id": Sequence(Value("string")),
143
- "image_path": Sequence(Value("string")),
144
- "description": Sequence(Value("string")),
145
- },
146
  "document_markdown_path": Value("string"),
147
  "document_final_markdown_path": Value("string"),
148
  "document_final_markdown_text": Value("string"),
@@ -155,61 +111,20 @@ def _dataset_path(base_dir: Path) -> Path:
155
  return base_dir / DATASET_FILENAME
156
 
157
 
158
- def _figures_to_columnar(figures: Optional[Iterable[Dict[str, Any]]]) -> Dict[str, List[str]]:
159
- ids: List[str] = []
160
- paths: List[str] = []
161
- descriptions: List[str] = []
162
-
163
- if figures:
164
- for figure in figures:
165
- if not isinstance(figure, dict):
166
- continue
167
-
168
- ids.append(str(figure.get("figure_id") or figure.get("id") or ""))
169
- paths.append(str(figure.get("image_path") or ""))
170
- descriptions.append(str(figure.get("description") or ""))
171
-
172
- return {
173
- "figure_id": ids,
174
- "image_path": paths,
175
- "description": descriptions,
176
- }
177
-
178
-
179
- def _figures_from_columnar(figures: Optional[Dict[str, Any]]) -> List[Dict[str, str]]:
180
- if not isinstance(figures, dict):
181
- return []
182
-
183
- ids = list(figures.get("figure_id") or [])
184
- paths = list(figures.get("image_path") or [])
185
- descriptions = list(figures.get("description") or [])
186
-
187
- length = max(len(ids), len(paths), len(descriptions))
188
- result: List[Dict[str, str]] = []
189
- for idx in range(length):
190
- result.append(
191
- {
192
- "figure_id": str(ids[idx]) if idx < len(ids) else "",
193
- "image_path": str(paths[idx]) if idx < len(paths) else "",
194
- "description": str(descriptions[idx]) if idx < len(descriptions) else "",
195
- }
196
- )
197
- return result
198
-
199
 
200
  def _build_dataset_records_iter(documents: Iterable[Dict[str, Any]]) -> Iterable[Dict[str, Any]]:
201
  for doc in documents:
202
  document_with_boxes_path = doc.get("document_with_boxes_path")
203
  document_with_boxes_relpath = str(document_with_boxes_path)
204
 
205
- figure_entries = _figures_to_columnar(doc.get("figures"))
206
  yield {
207
  "sample_id": str(doc.get("sample_id")),
208
  "dataset_index": int(doc.get("dataset_index") or 0),
209
  "source_image_path": str(doc.get("source_image_path") or ""),
210
  "document_with_boxes_image_path": document_with_boxes_relpath,
211
  "document_markdown_text": doc.get("document_markdown_text") or "",
212
- "figures": figure_entries,
 
213
  "document_markdown_path": str(doc.get("document_path") or ""),
214
  "document_final_markdown_path": str(doc.get("document_final_markdown_path") or ""),
215
  "document_final_markdown_text": doc.get("document_final_markdown_text") or "",
@@ -321,9 +236,13 @@ def run_stage_extract(settings: ExtractSettings) -> None:
321
 
322
  settings.output_dir.mkdir(parents=True, exist_ok=True)
323
 
324
- documents_jsonl_path = settings.output_dir / "documents.jsonl"
325
- if documents_jsonl_path.exists():
326
- documents_jsonl_path.unlink()
 
 
 
 
327
 
328
  document_count = 0
329
  failures: List[Dict[str, Any]] = []
@@ -343,7 +262,7 @@ def run_stage_extract(settings: ExtractSettings) -> None:
343
  batch_requests: List[Dict[str, Any]] = []
344
 
345
  def flush_batch() -> None:
346
- nonlocal batch_contexts, batch_requests, document_count
347
  if not batch_contexts:
348
  return
349
 
@@ -413,7 +332,7 @@ def run_stage_extract(settings: ExtractSettings) -> None:
413
  document_markdown_text=markdown,
414
  document_final_markdown_path="",
415
  document_final_markdown_text="",
416
- figures=figures,
417
  )
418
  batch_document_dicts.append(dataclass_to_dict(doc_metadata))
419
 
@@ -438,7 +357,10 @@ def run_stage_extract(settings: ExtractSettings) -> None:
438
  image_obj.close()
439
 
440
  if batch_document_dicts:
441
- append_jsonl(documents_jsonl_path, batch_document_dicts)
 
 
 
442
  document_count += len(batch_document_dicts)
443
 
444
  #reset batch contexts and requests
@@ -513,24 +435,34 @@ def run_stage_extract(settings: ExtractSettings) -> None:
513
  "max_retry_wait_seconds": settings.inference.max_retry_wait_seconds,
514
  },
515
  "documents": [],
516
- "documents_path": documents_jsonl_path.name,
 
 
 
517
  "documents_count": document_count,
518
  "failures": failures,
519
  }
520
 
521
  write_json(settings.output_dir / "manifest.json", manifest)
522
- maybe_upload_dataset(
523
- output_dir=settings.output_dir,
524
- repo_id=settings.upload_repo_id,
525
- path_in_repo=settings.upload_path_in_repo,
526
- commit_message=extract_commit,
527
- revision=settings.upload_revision,
528
- )
529
-
530
  extract_commit = settings.upload_commit_message
531
  if settings.upload_repo_id and not extract_commit:
532
  extract_commit = f"Upload extract stage outputs {__now_iso()}"
533
- documents_iter_for_push = iter_jsonl(documents_jsonl_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  dataset_records_iter = _build_dataset_records_iter(documents_iter_for_push)
535
  _push_dataset_records(
536
  records=dataset_records_iter,
@@ -562,12 +494,29 @@ def run_stage_describe(settings: DescribeSettings) -> None:
562
  raise FileNotFoundError(f"Stage 1 manifest not found at {manifest_path}")
563
 
564
  manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
565
- documents_path_str = manifest.get("documents_path")
566
- if documents_path_str:
567
- documents_path = stage1_dir / documents_path_str
568
- documents = read_jsonl(documents_path)
 
 
 
 
 
 
 
 
 
 
 
 
569
  else:
570
- documents = manifest.get("documents", []) or []
 
 
 
 
 
571
  doc_by_sample: Dict[str, Dict[str, Any]] = {doc.get("sample_id", ""): doc for doc in documents}
572
 
573
  dataset_path = _dataset_path(stage1_dir)
 
89
  return count
90
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  def _dataset_features() -> Features:
93
  return Features(
94
  {
 
97
  "source_image_path": HfImage(),
98
  "document_with_boxes_image_path": HfImage(),
99
  "document_markdown_text": Value("string"),
100
+ "extracted_figures": Sequence(HfImage()),
101
+ "extracted_figures_metadata": Sequence(Value("string")),
 
 
 
102
  "document_markdown_path": Value("string"),
103
  "document_final_markdown_path": Value("string"),
104
  "document_final_markdown_text": Value("string"),
 
111
  return base_dir / DATASET_FILENAME
112
 
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  def _build_dataset_records_iter(documents: Iterable[Dict[str, Any]]) -> Iterable[Dict[str, Any]]:
116
  for doc in documents:
117
  document_with_boxes_path = doc.get("document_with_boxes_path")
118
  document_with_boxes_relpath = str(document_with_boxes_path)
119
 
 
120
  yield {
121
  "sample_id": str(doc.get("sample_id")),
122
  "dataset_index": int(doc.get("dataset_index") or 0),
123
  "source_image_path": str(doc.get("source_image_path") or ""),
124
  "document_with_boxes_image_path": document_with_boxes_relpath,
125
  "document_markdown_text": doc.get("document_markdown_text") or "",
126
+ "extracted_figures": doc.get("extracted_figures") or [],
127
+ "extracted_figures_metadata": json.dumps(doc.get("extracted_figures_metadata") or []),
128
  "document_markdown_path": str(doc.get("document_path") or ""),
129
  "document_final_markdown_path": str(doc.get("document_final_markdown_path") or ""),
130
  "document_final_markdown_text": doc.get("document_final_markdown_text") or "",
 
236
 
237
  settings.output_dir.mkdir(parents=True, exist_ok=True)
238
 
239
+ documents_batches_dir = settings.output_dir / "document_batches"
240
+ if documents_batches_dir.exists():
241
+ shutil.rmtree(documents_batches_dir)
242
+ documents_batches_dir.mkdir(parents=True, exist_ok=True)
243
+
244
+ document_batch_files: List[Path] = []
245
+ batch_index = 0
246
 
247
  document_count = 0
248
  failures: List[Dict[str, Any]] = []
 
262
  batch_requests: List[Dict[str, Any]] = []
263
 
264
  def flush_batch() -> None:
265
+ nonlocal batch_contexts, batch_requests, document_count, batch_index
266
  if not batch_contexts:
267
  return
268
 
 
332
  document_markdown_text=markdown,
333
  document_final_markdown_path="",
334
  document_final_markdown_text="",
335
+ extracted_figures=figures,
336
  )
337
  batch_document_dicts.append(dataclass_to_dict(doc_metadata))
338
 
 
357
  image_obj.close()
358
 
359
  if batch_document_dicts:
360
+ batch_file = documents_batches_dir / f"batch_{batch_index:05d}.json"
361
+ write_json(batch_file, batch_document_dicts)
362
+ document_batch_files.append(batch_file)
363
+ batch_index += 1
364
  document_count += len(batch_document_dicts)
365
 
366
  #reset batch contexts and requests
 
435
  "max_retry_wait_seconds": settings.inference.max_retry_wait_seconds,
436
  },
437
  "documents": [],
438
+ "documents_path": documents_batches_dir.name,
439
+ "documents_batches": [
440
+ file.relative_to(settings.output_dir).as_posix() for file in document_batch_files
441
+ ],
442
  "documents_count": document_count,
443
  "failures": failures,
444
  }
445
 
446
  write_json(settings.output_dir / "manifest.json", manifest)
 
 
 
 
 
 
 
 
447
  extract_commit = settings.upload_commit_message
448
  if settings.upload_repo_id and not extract_commit:
449
  extract_commit = f"Upload extract stage outputs {__now_iso()}"
450
+ def iter_documents_from_batches(files: Iterable[Path]) -> Iterable[Dict[str, Any]]:
451
+ for file_path in files:
452
+ try:
453
+ batch_data = json.loads(file_path.read_text(encoding="utf-8"))
454
+ except Exception as exc: # pragma: no cover - defensive logging
455
+ LOGGER.warning("Failed to read documents batch %s: %s", file_path, exc)
456
+ continue
457
+
458
+ if not isinstance(batch_data, list):
459
+ LOGGER.warning("Unexpected batch content in %s; expected list", file_path)
460
+ continue
461
+
462
+ for entry in batch_data:
463
+ yield entry
464
+
465
+ documents_iter_for_push = iter_documents_from_batches(document_batch_files)
466
  dataset_records_iter = _build_dataset_records_iter(documents_iter_for_push)
467
  _push_dataset_records(
468
  records=dataset_records_iter,
 
494
  raise FileNotFoundError(f"Stage 1 manifest not found at {manifest_path}")
495
 
496
  manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
497
+
498
+ documents: List[Dict[str, Any]] = []
499
+ batch_rel_paths = manifest.get("documents_batches") or []
500
+ if batch_rel_paths:
501
+ for rel in batch_rel_paths:
502
+ batch_path = stage1_dir / rel
503
+ try:
504
+ batch_data = json.loads(batch_path.read_text(encoding="utf-8"))
505
+ except Exception as exc: # pragma: no cover
506
+ LOGGER.warning("Failed to load document batch %s: %s", batch_path, exc)
507
+ continue
508
+
509
+ if isinstance(batch_data, list):
510
+ documents.extend(batch_data)
511
+ else:
512
+ LOGGER.warning("Unexpected document batch format at %s", batch_path)
513
  else:
514
+ documents_path_str = manifest.get("documents_path")
515
+ if documents_path_str:
516
+ documents_path = stage1_dir / documents_path_str
517
+ documents = read_jsonl(documents_path)
518
+ else:
519
+ documents = manifest.get("documents", []) or []
520
  doc_by_sample: Dict[str, Dict[str, Any]] = {doc.get("sample_id", ""): doc for doc in documents}
521
 
522
  dataset_path = _dataset_path(stage1_dir)