Florent Gbelidji commited on
Commit
bc40e88
·
verified ·
1 Parent(s): 731e848

Sync DeepSeek OCR HF job code

Browse files
Files changed (1) hide show
  1. ds_batch_ocr/stages.py +188 -432
ds_batch_ocr/stages.py CHANGED
@@ -4,7 +4,7 @@ import json
4
  import logging
5
  import os
6
  from pathlib import Path
7
- from typing import Any, Dict, List, Optional
8
 
9
  import shutil
10
  from datasets import Dataset, Features, Sequence, Value, load_dataset, Image as HfImage
@@ -40,29 +40,77 @@ def write_jsonl(path: Path, rows: List[Dict[str, Any]]) -> None:
40
  handle.write("\n")
41
 
42
 
43
- def _coerce_to_str(value: Any) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  if value is None:
45
  return ""
46
- if isinstance(value, bytes):
47
- try:
48
- return value.decode("utf-8")
49
- except Exception:
50
- return value.decode("utf-8", errors="ignore")
51
- if isinstance(value, Path):
52
- return value.as_posix()
53
- if isinstance(value, str):
54
- return value
55
  if isinstance(value, (list, tuple, set)):
 
56
  for item in value:
57
- coerced = _coerce_to_str(item)
58
- if coerced:
59
- return coerced
60
- return ""
61
- return str(value)
62
 
 
 
 
 
 
 
 
 
 
63
 
64
- def _resolve_image_path(base_dir: Path, value: Any) -> str:
65
- path_str = _coerce_to_str(value)
66
  if not path_str:
67
  return ""
68
 
@@ -82,120 +130,6 @@ def _resolve_image_path(base_dir: Path, value: Any) -> str:
82
  return path.as_posix()
83
 
84
 
85
- def _normalize_figures(figures: Any) -> List[Dict[str, str]]:
86
- if not figures:
87
- return []
88
-
89
- def _looks_columnar(obj: Any) -> bool:
90
- if not isinstance(obj, dict) or not obj:
91
- return False
92
- has_sequence = False
93
- for value in obj.values():
94
- if value is None:
95
- continue
96
- if isinstance(value, (list, tuple)):
97
- has_sequence = True
98
- continue
99
- return False
100
- return has_sequence
101
-
102
- def _expand_entries(source: Any) -> List[Any]:
103
- if _looks_columnar(source):
104
- lengths = [
105
- len(column)
106
- for column in source.values()
107
- if isinstance(column, (list, tuple))
108
- ]
109
- max_len = max(lengths) if lengths else 0
110
- expanded: List[Dict[str, Any]] = []
111
- for idx in range(max_len):
112
- entry: Dict[str, Any] = {}
113
- for key, value in source.items():
114
- if isinstance(value, (list, tuple)):
115
- entry[key] = value[idx] if idx < len(value) else None
116
- else:
117
- entry[key] = value
118
- expanded.append(entry)
119
- return expanded
120
- if isinstance(source, dict):
121
- return [source]
122
- if isinstance(source, (list, tuple, set)):
123
- return list(source)
124
- return [source]
125
-
126
- def _unwrap(entry: Any) -> Any:
127
- current = entry
128
- # peel off single-item wrappers (e.g. [[{...}]]) common in some datasets
129
- while isinstance(current, (list, tuple)) and len(current) == 1:
130
- nested = current[0]
131
- if isinstance(nested, (dict, list, tuple)) or hasattr(nested, "figure_id"):
132
- current = nested
133
- else:
134
- break
135
- return current
136
-
137
- def _figure_from_entry(entry: Any) -> Dict[str, Any]:
138
- normalized_entry = _unwrap(entry)
139
-
140
- if isinstance(normalized_entry, dict):
141
- return normalized_entry
142
-
143
- if hasattr(normalized_entry, "figure_id"):
144
- return {
145
- "figure_id": getattr(normalized_entry, "figure_id", ""),
146
- "image_path": getattr(normalized_entry, "image_path", "")
147
- or getattr(normalized_entry, "document_relative_path", "")
148
- or "",
149
- "description": getattr(normalized_entry, "description", "") or "",
150
- }
151
-
152
- if isinstance(normalized_entry, (list, tuple)):
153
- return {
154
- "figure_id": normalized_entry[0] if len(normalized_entry) > 0 else "",
155
- "image_path": normalized_entry[1] if len(normalized_entry) > 1 else "",
156
- "description": normalized_entry[2] if len(normalized_entry) > 2 else "",
157
- }
158
-
159
- return {"figure_id": normalized_entry}
160
-
161
- normalized: List[Dict[str, str]] = []
162
- for raw_entry in _expand_entries(figures):
163
- try:
164
- figure_dict = _figure_from_entry(raw_entry)
165
- except Exception: # pragma: no cover - defensive guard
166
- LOGGER.warning("Unable to normalize figure entry; skipping: %s", raw_entry, exc_info=True)
167
- continue
168
-
169
- figure_id = _coerce_to_str(
170
- figure_dict.get("figure_id")
171
- or figure_dict.get("id")
172
- or figure_dict.get("label")
173
- )
174
- image_path = _coerce_to_str(
175
- figure_dict.get("image_path")
176
- or figure_dict.get("document_relative_path")
177
- or figure_dict.get("path")
178
- or figure_dict.get("document_path")
179
- or figure_dict.get("image")
180
- )
181
- description = _coerce_to_str(
182
- figure_dict.get("description")
183
- or figure_dict.get("caption")
184
- or figure_dict.get("text")
185
- )
186
-
187
- normalized.append(
188
- {
189
- "figure_id": figure_id,
190
- "image_path": image_path,
191
- "image": image_path,
192
- "description": description,
193
- }
194
- )
195
-
196
- return normalized
197
-
198
-
199
  def _dataset_features() -> Features:
200
  return Features(
201
  {
@@ -204,8 +138,14 @@ def _dataset_features() -> Features:
204
  "source_image_path": HfImage(),
205
  "document_with_boxes_image_path": HfImage(),
206
  "document_markdown_text": Value("string"),
207
- "figures": Sequence(HfImage()),
208
- "figures_metadata": Sequence(Value("string")),
 
 
 
 
 
 
209
  "document_markdown_path": Value("string"),
210
  "document_final_markdown_path": Value("string"),
211
  "document_final_markdown_text": Value("string"),
@@ -218,59 +158,52 @@ def _dataset_path(base_dir: Path) -> Path:
218
  return base_dir / DATASET_FILENAME
219
 
220
 
221
- def _build_dataset_records(documents: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
222
- records: List[Dict[str, Any]] = []
223
  for doc in documents:
224
- figures = _normalize_figures(doc.get("figures", []))
225
-
226
- document_with_boxes_relpath = _coerce_to_str(doc.get("document_with_boxes_path"))
227
- if document_with_boxes_relpath:
228
- relpath_obj = Path(document_with_boxes_relpath)
229
- if relpath_obj.suffix.lower() != ".png":
230
- document_with_boxes_relpath = relpath_obj.with_suffix(".png").as_posix()
231
 
 
232
  figure_entries: List[Dict[str, Any]] = []
233
- figure_metadata_json: List[str] = []
234
- for figure in figures:
235
- figure_image_relpath = _coerce_to_str(
236
- figure.get("image")
237
- or figure.get("image_path")
238
- or figure.get("document_relative_path")
239
- or figure.get("path")
 
 
 
 
 
 
 
 
240
  )
241
- if figure_image_relpath:
242
- figure_relpath_obj = Path(figure_image_relpath)
243
- if figure_relpath_obj.suffix.lower() != ".png":
244
- figure_image_relpath = figure_relpath_obj.with_suffix(".png").as_posix()
245
- metadata_entry = {
246
- "figure_id": _coerce_to_str(figure.get("figure_id")),
247
- "image_path": figure_image_relpath,
248
- "description": _coerce_to_str(figure.get("description")),
249
- }
250
- figure_entries.append({**metadata_entry, "image": figure_image_relpath})
251
- figure_metadata_json.append(json.dumps(metadata_entry, ensure_ascii=False))
 
 
252
 
253
- records.append(
254
- {
255
- "sample_id": doc.get("sample_id", ""),
256
- "dataset_index": int(doc.get("dataset_index") or 0),
257
- "source_image_path": doc.get("source_image_path", ""),
258
- "document_with_boxes_image_path": document_with_boxes_relpath,
259
- "document_markdown_text": doc.get("document_markdown_text") or "",
260
- "figures": figure_entries,
261
- "figures_metadata": figure_metadata_json,
262
- "document_markdown_path": doc.get("document_path", ""),
263
- "document_final_markdown_path": doc.get("document_final_markdown_path") or "",
264
- "document_final_markdown_text": doc.get("document_final_markdown_text") or "",
265
- "raw_response_path": doc.get("raw_response_path", ""),
266
- }
267
- )
268
- return records
269
 
270
 
271
  def _push_dataset_records(
272
  *,
273
- records: List[Dict[str, Any]],
 
274
  output_dir: Path,
275
  repo_id: Optional[str],
276
  commit_message: Optional[str],
@@ -280,133 +213,39 @@ def _push_dataset_records(
280
  return
281
 
282
  dataset_path = _dataset_path(output_dir)
283
- write_jsonl(dataset_path, records)
284
-
285
- normalized_records: List[Dict[str, Any]] = []
286
- for record in records:
287
- if not isinstance(record, dict):
288
- LOGGER.warning(
289
- "Skipping dataset record during normalization | type=%s | value=%r",
290
- type(record),
291
- record,
292
- )
293
- continue
294
-
295
- print(record)
296
 
297
- sample_id = _coerce_to_str(record.get("sample_id", ""))
298
- try:
299
- dataset_index = int(record.get("dataset_index") or 0)
300
- except Exception:
301
- LOGGER.warning(
302
- "Unable to coerce dataset_index for sample %s; defaulting to 0 | value=%r",
303
- sample_id or "<unknown>",
304
- record.get("dataset_index"),
305
- )
306
- dataset_index = 0
307
-
308
- document_with_boxes_image_path = _resolve_image_path(
309
- output_dir,
310
- record.get("document_with_boxes_image_path")
311
- or record.get("document_with_boxes_path")
312
- )
313
- source_image_path = _resolve_image_path(
314
- output_dir,
315
- record.get("source_image_path")
316
- )
317
-
318
- figure_images: List[str] = []
319
- figure_metadata_json: List[str] = []
320
-
321
- raw_figures = record.get("figures", []) or []
322
- if isinstance(raw_figures, dict):
323
- raw_figures = [raw_figures]
324
-
325
- for figure in raw_figures:
326
- raw_figure_path = _coerce_to_str(
327
- (figure or {}).get("image")
328
- or (figure or {}).get("image_path")
329
- or (figure or {}).get("document_relative_path")
330
- or (figure or {}).get("path")
331
- )
332
- if not raw_figure_path:
333
- LOGGER.warning(
334
- "Skipping figure with missing image reference | sample=%s | figure=%s",
335
- sample_id or "<unknown>",
336
- (figure or {}).get("figure_id"),
337
- )
338
- continue
339
-
340
- resolved_path = _resolve_image_path(output_dir, raw_figure_path)
341
- figure_images.append(resolved_path)
342
 
343
- metadata_entry = {
344
- "figure_id": _coerce_to_str((figure or {}).get("figure_id")),
345
- "image_path": _coerce_to_str((figure or {}).get("image_path") or raw_figure_path),
346
- "description": _coerce_to_str((figure or {}).get("description")),
347
- }
348
- figure_metadata_json.append(json.dumps(metadata_entry, ensure_ascii=False))
349
-
350
- if not figure_images and record.get("figures_metadata"):
351
- for metadata in record.get("figures_metadata", []):
352
- parsed: Dict[str, Any]
353
- if isinstance(metadata, str):
354
- try:
355
- parsed = json.loads(metadata)
356
- except Exception:
357
- LOGGER.warning(
358
- "Unable to parse figure metadata JSON | sample=%s | value=%r",
359
- sample_id or "<unknown>",
360
- metadata,
361
- )
362
- continue
363
- elif isinstance(metadata, dict):
364
- parsed = metadata
365
  else:
366
- continue
367
 
368
- raw_figure_path = _coerce_to_str(
369
- parsed.get("image_path")
370
- or parsed.get("image")
371
- or ""
372
- )
373
- if not raw_figure_path:
374
- continue
375
- resolved_path = _resolve_image_path(output_dir, raw_figure_path)
376
- figure_images.append(resolved_path)
377
 
378
- normalized_metadata = {
379
- "figure_id": _coerce_to_str(parsed.get("figure_id")),
380
- "image_path": _coerce_to_str(parsed.get("image_path") or raw_figure_path),
381
- "description": _coerce_to_str(parsed.get("description")),
382
- }
383
- figure_metadata_json.append(json.dumps(normalized_metadata, ensure_ascii=False))
384
 
385
- normalized_records.append(
386
- {
387
- "sample_id": sample_id,
388
- "dataset_index": dataset_index,
389
- "document_markdown_path": _coerce_to_str(
390
- record.get("document_markdown_path") or record.get("document_path")
391
- ),
392
- "document_markdown_text": _coerce_to_str(
393
- record.get("document_markdown_text")
394
- ),
395
- "document_final_markdown_path": _coerce_to_str(
396
- record.get("document_final_markdown_path")
397
- ),
398
- "document_final_markdown_text": _coerce_to_str(
399
- record.get("document_final_markdown_text")
400
- ),
401
- "document_with_boxes_image_path": document_with_boxes_image_path,
402
- "raw_response_path": _coerce_to_str(record.get("raw_response_path")),
403
- "source_image_path": source_image_path,
404
- "figures": figure_images,
405
- "figures_metadata": figure_metadata_json,
406
- }
407
- )
408
 
409
- dataset = Dataset.from_list(normalized_records, features=_dataset_features())
410
  token = env_or_none("HF_TOKEN")
411
  dataset.push_to_hub(
412
  repo_id=repo_id,
@@ -426,7 +265,10 @@ def _load_dataset_records(path: Path) -> List[Dict[str, Any]]:
426
  if not line:
427
  continue
428
  record = json.loads(line)
429
- record["figures"] = _normalize_figures(record.get("figures", []))
 
 
 
430
  records.append(record)
431
  return records
432
 
@@ -467,7 +309,11 @@ def run_stage_extract(settings: ExtractSettings) -> None:
467
 
468
  settings.output_dir.mkdir(parents=True, exist_ok=True)
469
 
470
- documents: List[DocumentMetadata] = []
 
 
 
 
471
  failures: List[Dict[str, Any]] = []
472
 
473
  chunk_size = max(settings.inference.max_batch_size, 1)
@@ -516,16 +362,20 @@ def run_stage_extract(settings: ExtractSettings) -> None:
516
  len(batch_contexts),
517
  )
518
 
 
 
519
  for idx, ctx in enumerate(batch_contexts):
520
  image_obj = ctx.get("image")
521
  try:
522
  response_text = responses[idx].strip() if idx < len(responses) else ""
523
  if not response_text:
524
  raise RuntimeError("Empty response from DeepSeek inference")
525
-
 
526
  raw_response_path = ctx["sample_dir"] / "raw_response.md"
527
  write_text(raw_response_path, response_text)
528
 
 
529
  markdown, figures, img_draw = build_document_markdown(
530
  image=image_obj,
531
  response_text=response_text,
@@ -533,25 +383,27 @@ def run_stage_extract(settings: ExtractSettings) -> None:
533
  sample_id=ctx["sample_id"],
534
  )
535
 
 
536
  document_path = ctx["sample_dir"] / "document.md"
537
  write_text(document_path, markdown)
538
 
 
539
  img_draw.save(ctx["sample_dir"] / "document_with_boxes.png")
540
 
541
- documents.append(
542
- DocumentMetadata(
543
- sample_id=ctx["sample_id"],
544
- dataset_index=ctx["dataset_index"],
545
- document_path=(Path(ctx["sample_id"]) / "document.md").as_posix(),
546
- raw_response_path=(Path(ctx["sample_id"]) / "raw_response.md").as_posix(),
547
- source_image_path=(Path(ctx["sample_id"]) / "source.png").as_posix(),
548
- document_with_boxes_path=(Path(ctx["sample_id"]) / "document_with_boxes.png").as_posix(),
549
- document_markdown_text=markdown,
550
- document_final_markdown_path="",
551
- document_final_markdown_text="",
552
- figures=figures,
553
- )
554
  )
 
555
 
556
  LOGGER.debug(
557
  "Processed sample %s | figures=%s | markdown_chars=%s",
@@ -573,6 +425,11 @@ def run_stage_extract(settings: ExtractSettings) -> None:
573
  if hasattr(image_obj, "close"):
574
  image_obj.close()
575
 
 
 
 
 
 
576
  batch_contexts = []
577
  batch_requests = []
578
 
@@ -586,29 +443,16 @@ def run_stage_extract(settings: ExtractSettings) -> None:
586
 
587
  raw_image = sample["images"][0]
588
  image = raw_image.copy()
589
- # if isinstance(raw_image, Image.Image):
590
- # image = raw_image.copy()
591
- # else:
592
- # image = Image.fromarray(raw_image)
593
-
594
- # if hasattr(raw_image, "close"):
595
- # try:
596
- # raw_image.close()
597
- # except Exception: # pragma: no cover - defensive cleanup
598
- # pass
599
-
600
  if image.mode != "RGB":
601
  image = image.convert("RGB")
602
 
 
603
  source_image_path = sample_dir / "source.png"
604
  image.save(source_image_path)
605
 
 
606
  processing_image = image.copy()
607
- if hasattr(image, "close"):
608
- try:
609
- image.close()
610
- except Exception: # pragma: no cover - defensive cleanup
611
- pass
612
 
613
  batch_contexts.append(
614
  {
@@ -631,6 +475,7 @@ def run_stage_extract(settings: ExtractSettings) -> None:
631
  if len(batch_requests) >= chunk_size:
632
  flush_batch()
633
 
 
634
  flush_batch()
635
 
636
  manifest = {
@@ -655,7 +500,9 @@ def run_stage_extract(settings: ExtractSettings) -> None:
655
  "retry_backoff_seconds": settings.inference.retry_backoff_seconds,
656
  "max_retry_wait_seconds": settings.inference.max_retry_wait_seconds,
657
  },
658
- "documents": [dataclass_to_dict(document) for document in documents],
 
 
659
  "failures": failures,
660
  }
661
 
@@ -663,9 +510,10 @@ def run_stage_extract(settings: ExtractSettings) -> None:
663
  extract_commit = settings.upload_commit_message
664
  if settings.upload_repo_id and not extract_commit:
665
  extract_commit = f"Upload extract stage outputs {__now_iso()}"
666
- dataset_records = _build_dataset_records(manifest["documents"])
 
667
  _push_dataset_records(
668
- records=dataset_records,
669
  output_dir=settings.output_dir,
670
  repo_id=settings.upload_repo_id,
671
  commit_message=extract_commit,
@@ -680,7 +528,7 @@ def run_stage_extract(settings: ExtractSettings) -> None:
680
  )
681
  LOGGER.info(
682
  "Extract stage complete | documents=%s | failures=%s",
683
- len(documents),
684
  len(failures),
685
  )
686
 
@@ -694,7 +542,12 @@ def run_stage_describe(settings: DescribeSettings) -> None:
694
  raise FileNotFoundError(f"Stage 1 manifest not found at {manifest_path}")
695
 
696
  manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
697
- documents = manifest.get("documents", [])
 
 
 
 
 
698
  doc_by_sample: Dict[str, Dict[str, Any]] = {doc.get("sample_id", ""): doc for doc in documents}
699
 
700
  dataset_path = _dataset_path(stage1_dir)
@@ -985,12 +838,6 @@ def run_stage_assemble(settings: AssembleSettings) -> None:
985
  commit_message=assemble_commit,
986
  revision=settings.dataset_branch,
987
  )
988
- publish_dataset_viewer_assets(
989
- dataset_records=dataset_records,
990
- repo_id=settings.dataset_repo_id,
991
- revision=settings.dataset_branch,
992
- commit_message=f"{assemble_commit} [dataset viewer]",
993
- )
994
  maybe_upload_dataset(
995
  output_dir=stage1_dir,
996
  repo_id=settings.dataset_repo_id,
@@ -1052,97 +899,6 @@ def __now_iso() -> str:
1052
 
1053
  return datetime.utcnow().isoformat() + "Z"
1054
 
1055
-
1056
- def publish_dataset_viewer_assets(
1057
- *,
1058
- dataset_records: List[Dict[str, Any]],
1059
- repo_id: Optional[str],
1060
- revision: Optional[str],
1061
- commit_message: str,
1062
- ) -> None:
1063
- if not repo_id:
1064
- return
1065
-
1066
- normalized: List[Dict[str, Any]] = []
1067
- for record in dataset_records:
1068
- figures = record.get("figures", []) or []
1069
- figures_metadata = record.get("figures_metadata", []) or []
1070
-
1071
- viewer_figures: List[Dict[str, Any]] = []
1072
-
1073
- if figures_metadata:
1074
- for metadata in figures_metadata:
1075
- if isinstance(metadata, str):
1076
- try:
1077
- parsed = json.loads(metadata)
1078
- except Exception:
1079
- LOGGER.warning(
1080
- "Failed to parse figures_metadata entry for viewer | sample=%s | value=%r",
1081
- record.get("sample_id"),
1082
- metadata,
1083
- )
1084
- continue
1085
- elif isinstance(metadata, dict):
1086
- parsed = metadata
1087
- else:
1088
- continue
1089
-
1090
- viewer_figures.append(
1091
- {
1092
- "figure_id": str(parsed.get("figure_id", "")),
1093
- "image_path": str(parsed.get("image_path", "")),
1094
- "image": str(parsed.get("image") or parsed.get("image_path") or ""),
1095
- "description": parsed.get("description", ""),
1096
- "metadata_json": json.dumps(parsed, ensure_ascii=False),
1097
- }
1098
- )
1099
- else:
1100
- for fig in figures:
1101
- metadata = {
1102
- "figure_id": _coerce_to_str(fig.get("figure_id")),
1103
- "image_path": _coerce_to_str(fig.get("image_path")),
1104
- "description": _coerce_to_str(fig.get("description")),
1105
- }
1106
- viewer_figures.append(
1107
- {
1108
- "figure_id": metadata["figure_id"],
1109
- "image_path": metadata["image_path"],
1110
- "image": _coerce_to_str(fig.get("image") or fig.get("image_path")),
1111
- "description": metadata["description"],
1112
- "metadata_json": json.dumps(metadata, ensure_ascii=False),
1113
- }
1114
- )
1115
-
1116
- normalized.append(
1117
- {
1118
- "sample_id": str(record.get("sample_id", "")),
1119
- "dataset_index": int(record.get("dataset_index") or 0),
1120
- "document_markdown_path": str(record.get("document_markdown_path", "")),
1121
- "document_markdown_text": record.get("document_markdown_text", ""),
1122
- "document_with_boxes_image": record.get("document_with_boxes_image_path"),
1123
- "figures": viewer_figures,
1124
- }
1125
- )
1126
-
1127
- dataset = Dataset.from_list(normalized)
1128
-
1129
- token = env_or_none("HF_TOKEN")
1130
- try:
1131
- dataset.push_to_hub(
1132
- repo_id=repo_id,
1133
- token=token,
1134
- split="train",
1135
- revision=revision,
1136
- commit_message=commit_message,
1137
- )
1138
- LOGGER.info(
1139
- "Published assembled dataset viewer table | repo=%s | records=%s",
1140
- repo_id,
1141
- len(normalized),
1142
- )
1143
- except Exception as exc: # pragma: no cover - defensive logging
1144
- LOGGER.exception("Failed to publish assembled dataset viewer assets: %s", exc)
1145
-
1146
  __all__ = [
1147
  "run_stage_extract",
1148
  "run_stage_describe",
 
4
  import logging
5
  import os
6
  from pathlib import Path
7
+ from typing import Any, Dict, Iterable, List, Optional
8
 
9
  import shutil
10
  from datasets import Dataset, Features, Sequence, Value, load_dataset, Image as HfImage
 
40
  handle.write("\n")
41
 
42
 
43
+ def append_jsonl(path: Path, rows: List[Dict[str, Any]]) -> None:
44
+ if not rows:
45
+ return
46
+ path.parent.mkdir(parents=True, exist_ok=True)
47
+ with path.open("a", encoding="utf-8") as handle:
48
+ for row in rows:
49
+ handle.write(json.dumps(row, ensure_ascii=False))
50
+ handle.write("\n")
51
+
52
+
53
+ def read_jsonl(path: Path) -> List[Dict[str, Any]]:
54
+ if not path.exists():
55
+ return []
56
+ data: List[Dict[str, Any]] = []
57
+ with path.open("r", encoding="utf-8") as handle:
58
+ for line in handle:
59
+ line = line.strip()
60
+ if not line:
61
+ continue
62
+ data.append(json.loads(line))
63
+ return data
64
+
65
+
66
+ def iter_jsonl(path: Path) -> Iterable[Dict[str, Any]]:
67
+ if not path.exists():
68
+ return []
69
+
70
+ def _generator() -> Iterable[Dict[str, Any]]:
71
+ with path.open("r", encoding="utf-8") as handle:
72
+ for line in handle:
73
+ line = line.strip()
74
+ if not line:
75
+ continue
76
+ yield json.loads(line)
77
+
78
+ return _generator()
79
+
80
+
81
+ def write_jsonl_iter(path: Path, rows: Iterable[Dict[str, Any]]) -> int:
82
+ path.parent.mkdir(parents=True, exist_ok=True)
83
+ count = 0
84
+ with path.open("w", encoding="utf-8") as handle:
85
+ for row in rows:
86
+ handle.write(json.dumps(row, ensure_ascii=False))
87
+ handle.write("\n")
88
+ count += 1
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
 
 
130
  return path.as_posix()
131
 
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  def _dataset_features() -> Features:
134
  return Features(
135
  {
 
138
  "source_image_path": HfImage(),
139
  "document_with_boxes_image_path": HfImage(),
140
  "document_markdown_text": Value("string"),
141
+ "figure_images": Sequence(HfImage()),
142
+ "figures": Sequence(
143
+ {
144
+ "figure_id": Value("string"),
145
+ "image_path": Value("string"),
146
+ "description": Value("string"),
147
+ }
148
+ ),
149
  "document_markdown_path": Value("string"),
150
  "document_final_markdown_path": Value("string"),
151
  "document_final_markdown_text": Value("string"),
 
158
  return base_dir / DATASET_FILENAME
159
 
160
 
161
+ def _build_dataset_records_iter(documents: Iterable[Dict[str, Any]]) -> Iterable[Dict[str, Any]]:
 
162
  for doc in documents:
163
+ document_with_boxes_path = doc.get("document_with_boxes_path")
164
+ document_with_boxes_relpath = str(document_with_boxes_path)
 
 
 
 
 
165
 
166
+ figure_images: List[str] = []
167
  figure_entries: List[Dict[str, Any]] = []
168
+ for figure in doc.get("figures") or []:
169
+ if not isinstance(figure, dict):
170
+ continue
171
+
172
+ raw_image_path = figure.get("image_path")
173
+ image_relpath = str(raw_image_path)
174
+
175
+ figure_images.append(image_relpath)
176
+ figure_entries.append(
177
+ {
178
+ "figure_id": str(figure.get("figure_id")),
179
+ "image_path": image_relpath,
180
+ "description": str(figure.get("description")),
181
+
182
+ }
183
  )
184
+ yield {
185
+ "sample_id": str(doc.get("sample_id")),
186
+ "dataset_index": int(doc.get("dataset_index")),
187
+ "source_image_path": str(doc.get("source_image_path")),
188
+ "document_with_boxes_image_path": document_with_boxes_relpath,
189
+ "document_markdown_text": doc.get("document_markdown_text"),
190
+ "figure_images": figure_images,
191
+ "figures": figure_entries,
192
+ "document_markdown_path": str(doc.get("document_path")),
193
+ "document_final_markdown_path": str(doc.get("document_final_markdown_path")),
194
+ "document_final_markdown_text": doc.get("document_final_markdown_text"),
195
+ "raw_response_path": str(doc.get("raw_response_path")),
196
+ }
197
 
198
+
199
+ def _build_dataset_records(documents: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]:
200
+ return list(_build_dataset_records_iter(documents))
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
 
203
  def _push_dataset_records(
204
  *,
205
+ records: Optional[Iterable[Dict[str, Any]]] = None,
206
+ records_path: Optional[Path] = None,
207
  output_dir: Path,
208
  repo_id: Optional[str],
209
  commit_message: Optional[str],
 
213
  return
214
 
215
  dataset_path = _dataset_path(output_dir)
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
+ if records_path:
218
+ if records is not None:
219
+ LOGGER.warning("Both records and records_path provided; ignoring in-memory records.")
220
+ if records_path != dataset_path:
221
+ dataset_path.parent.mkdir(parents=True, exist_ok=True)
222
+ shutil.copyfile(records_path, dataset_path)
223
+ else:
224
+ if records is None:
225
+ records = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
+ def _record_iterator() -> Iterable[Dict[str, Any]]:
228
+ for record in records:
229
+ if isinstance(record, dict):
230
+ data = dict(record)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  else:
232
+ data = dict(record)
233
 
234
+ if "figure_images" not in data or data["figure_images"] is None:
235
+ figure_images = []
236
+ for fig in data.get("figures", []) or []:
237
+ if isinstance(fig, dict):
238
+ image_path = fig.get("image_path")
239
+ if image_path:
240
+ figure_images.append(str(image_path))
241
+ data["figure_images"] = figure_images
 
242
 
243
+ yield data
 
 
 
 
 
244
 
245
+ write_jsonl_iter(dataset_path, _record_iterator())
246
+
247
+ dataset = Dataset.from_json(str(dataset_path), features=_dataset_features())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
 
249
  token = env_or_none("HF_TOKEN")
250
  dataset.push_to_hub(
251
  repo_id=repo_id,
 
265
  if not line:
266
  continue
267
  record = json.loads(line)
268
+ if record.get("figures") is None:
269
+ record["figures"] = []
270
+ if record.get("figure_images") is None:
271
+ record["figure_images"] = []
272
  records.append(record)
273
  return records
274
 
 
309
 
310
  settings.output_dir.mkdir(parents=True, exist_ok=True)
311
 
312
+ documents_jsonl_path = settings.output_dir / "documents.jsonl"
313
+ if documents_jsonl_path.exists():
314
+ documents_jsonl_path.unlink()
315
+
316
+ document_count = 0
317
  failures: List[Dict[str, Any]] = []
318
 
319
  chunk_size = max(settings.inference.max_batch_size, 1)
 
362
  len(batch_contexts),
363
  )
364
 
365
+ batch_document_dicts: List[Dict[str, Any]] = []
366
+
367
  for idx, ctx in enumerate(batch_contexts):
368
  image_obj = ctx.get("image")
369
  try:
370
  response_text = responses[idx].strip() if idx < len(responses) else ""
371
  if not response_text:
372
  raise RuntimeError("Empty response from DeepSeek inference")
373
+
374
+ #write raw response markdown to file
375
  raw_response_path = ctx["sample_dir"] / "raw_response.md"
376
  write_text(raw_response_path, response_text)
377
 
378
+ #build document markdown and extract figures
379
  markdown, figures, img_draw = build_document_markdown(
380
  image=image_obj,
381
  response_text=response_text,
 
383
  sample_id=ctx["sample_id"],
384
  )
385
 
386
+ #write document markdown to file
387
  document_path = ctx["sample_dir"] / "document.md"
388
  write_text(document_path, markdown)
389
 
390
+ #write document with boxes image to file
391
  img_draw.save(ctx["sample_dir"] / "document_with_boxes.png")
392
 
393
+ #build document metadata
394
+ doc_metadata = DocumentMetadata(
395
+ sample_id=ctx["sample_id"],
396
+ dataset_index=ctx["dataset_index"],
397
+ document_path=(Path(ctx["sample_id"]) / "document.md").as_posix(),
398
+ raw_response_path=(Path(ctx["sample_id"]) / "raw_response.md").as_posix(),
399
+ source_image_path=(Path(ctx["sample_id"]) / "source.png").as_posix(),
400
+ document_with_boxes_path=(Path(ctx["sample_id"]) / "document_with_boxes.png").as_posix(),
401
+ document_markdown_text=markdown,
402
+ document_final_markdown_path="",
403
+ document_final_markdown_text="",
404
+ figures=figures,
 
405
  )
406
+ batch_document_dicts.append(dataclass_to_dict(doc_metadata))
407
 
408
  LOGGER.debug(
409
  "Processed sample %s | figures=%s | markdown_chars=%s",
 
425
  if hasattr(image_obj, "close"):
426
  image_obj.close()
427
 
428
+ if batch_document_dicts:
429
+ append_jsonl(documents_jsonl_path, batch_document_dicts)
430
+ document_count += len(batch_document_dicts)
431
+
432
+ #reset batch contexts and requests
433
  batch_contexts = []
434
  batch_requests = []
435
 
 
443
 
444
  raw_image = sample["images"][0]
445
  image = raw_image.copy()
 
 
 
 
 
 
 
 
 
 
 
446
  if image.mode != "RGB":
447
  image = image.convert("RGB")
448
 
449
+ #write source image to file
450
  source_image_path = sample_dir / "source.png"
451
  image.save(source_image_path)
452
 
453
+ #copy image for processing
454
  processing_image = image.copy()
455
+ image.close()
 
 
 
 
456
 
457
  batch_contexts.append(
458
  {
 
475
  if len(batch_requests) >= chunk_size:
476
  flush_batch()
477
 
478
+ #process batch if not empty
479
  flush_batch()
480
 
481
  manifest = {
 
500
  "retry_backoff_seconds": settings.inference.retry_backoff_seconds,
501
  "max_retry_wait_seconds": settings.inference.max_retry_wait_seconds,
502
  },
503
+ "documents": [],
504
+ "documents_path": documents_jsonl_path.name,
505
+ "documents_count": document_count,
506
  "failures": failures,
507
  }
508
 
 
510
  extract_commit = settings.upload_commit_message
511
  if settings.upload_repo_id and not extract_commit:
512
  extract_commit = f"Upload extract stage outputs {__now_iso()}"
513
+ documents_iter_for_push = iter_jsonl(documents_jsonl_path)
514
+ dataset_records_iter = _build_dataset_records_iter(documents_iter_for_push)
515
  _push_dataset_records(
516
+ records=dataset_records_iter,
517
  output_dir=settings.output_dir,
518
  repo_id=settings.upload_repo_id,
519
  commit_message=extract_commit,
 
528
  )
529
  LOGGER.info(
530
  "Extract stage complete | documents=%s | failures=%s",
531
+ document_count,
532
  len(failures),
533
  )
534
 
 
542
  raise FileNotFoundError(f"Stage 1 manifest not found at {manifest_path}")
543
 
544
  manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
545
+ documents_path_str = manifest.get("documents_path")
546
+ if documents_path_str:
547
+ documents_path = stage1_dir / documents_path_str
548
+ documents = read_jsonl(documents_path)
549
+ else:
550
+ documents = manifest.get("documents", []) or []
551
  doc_by_sample: Dict[str, Dict[str, Any]] = {doc.get("sample_id", ""): doc for doc in documents}
552
 
553
  dataset_path = _dataset_path(stage1_dir)
 
838
  commit_message=assemble_commit,
839
  revision=settings.dataset_branch,
840
  )
 
 
 
 
 
 
841
  maybe_upload_dataset(
842
  output_dir=stage1_dir,
843
  repo_id=settings.dataset_repo_id,
 
899
 
900
  return datetime.utcnow().isoformat() + "Z"
901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902
  __all__ = [
903
  "run_stage_extract",
904
  "run_stage_describe",