Florent Gbelidji commited on
Commit
1c2734a
·
verified ·
1 Parent(s): a42b77c

Sync DeepSeek OCR HF job code

Browse files
ds-batch-ocr.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Thin entrypoint that delegates to the package implementation."""
2
+
3
+ from ds_batch_ocr.cli import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ main()
8
+
ds_batch_ocr/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """DeepSeek OCR pipeline package."""
2
+
3
+ from .cli import main
4
+
5
+ __all__ = ["main"]
6
+
ds_batch_ocr/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (231 Bytes). View file
 
ds_batch_ocr/__pycache__/cli.cpython-312.pyc ADDED
Binary file (11.5 kB). View file
 
ds_batch_ocr/__pycache__/config.cpython-312.pyc ADDED
Binary file (3.3 kB). View file
 
ds_batch_ocr/__pycache__/dependencies.cpython-312.pyc ADDED
Binary file (2.3 kB). View file
 
ds_batch_ocr/__pycache__/document.cpython-312.pyc ADDED
Binary file (12.4 kB). View file
 
ds_batch_ocr/__pycache__/hf_io.cpython-312.pyc ADDED
Binary file (4.5 kB). View file
 
ds_batch_ocr/__pycache__/logging_utils.cpython-312.pyc ADDED
Binary file (686 Bytes). View file
 
ds_batch_ocr/__pycache__/server.cpython-312.pyc ADDED
Binary file (7.83 kB). View file
 
ds_batch_ocr/__pycache__/stages.cpython-312.pyc ADDED
Binary file (13.3 kB). View file
 
ds_batch_ocr/cli.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Optional, Sequence
9
+
10
+ from .config import ArtifactLocator, AssembleSettings, DescribeSettings, ExtractSettings, InferenceSettings
11
+ from .dependencies import bootstrap
12
+ from .logging_utils import configure_logging
13
+ from .server import (
14
+ DeepSeekClient,
15
+ base_url_from_env,
16
+ launch_vllm,
17
+ should_launch_server,
18
+ shutdown_server,
19
+ wait_for_server,
20
+ )
21
+ from .stages import (
22
+ run_stage_assemble,
23
+ run_stage_describe,
24
+ run_stage_extract,
25
+ )
26
+
27
+ LOGGER = logging.getLogger(__name__)
28
+
29
+
30
+ def parse_arguments(argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
31
+ parser = argparse.ArgumentParser(description="DeepSeek OCR HF Jobs pipeline")
32
+ parser.add_argument("--stage", choices=["extract", "describe", "assemble"], help="Pipeline stage to run")
33
+ parser.add_argument("--output-dir", help="Output directory for the current stage")
34
+ parser.add_argument("--stage1-dir", help="Path to stage1 outputs (for describe/assemble)")
35
+ parser.add_argument("--stage2-dir", help="Path to stage2 outputs (for assemble)")
36
+ parser.add_argument("--dataset-name", help="Dataset name for extract stage")
37
+ parser.add_argument("--dataset-config", help="Dataset config for extract stage")
38
+ parser.add_argument("--dataset-split", help="Dataset split for extract stage")
39
+ parser.add_argument("--max-samples", type=int, help="Max samples to process in extract stage")
40
+ parser.add_argument("--doc-prompt", help="Prompt for document extraction stage")
41
+ parser.add_argument("--figure-prompt", help="Prompt for figure description stage")
42
+ parser.add_argument("--doc-max-tokens", type=int, help="Max tokens for extraction stage")
43
+ parser.add_argument("--figure-max-tokens", type=int, help="Max tokens for description stage")
44
+ parser.add_argument("--doc-temperature", type=float, help="Sampling temperature for extraction stage")
45
+ parser.add_argument("--figure-temperature", type=float, help="Sampling temperature for description stage")
46
+ parser.add_argument(
47
+ "--no-streaming",
48
+ action="store_true",
49
+ help="Disable dataset streaming in extract stage",
50
+ )
51
+ parser.add_argument("--dataset-repo-id", help="Hugging Face dataset repo to upload assembled outputs")
52
+ parser.add_argument("--dataset-path-in-repo", help="Target path inside the dataset repo")
53
+ parser.add_argument("--dataset-branch", help="Dataset repo branch or revision to push to")
54
+ parser.add_argument("--dataset-commit-message", help="Commit message for dataset upload")
55
+ parser.add_argument("--dataset-repo-type", help="Repository type (defaults to 'dataset')")
56
+ return parser.parse_args(argv)
57
+
58
+
59
+ def getenv_float(name: str, default: float) -> float:
60
+ value = os.environ.get(name)
61
+ if value is None:
62
+ return default
63
+ try:
64
+ return float(value)
65
+ except ValueError:
66
+ LOGGER.warning("Invalid float for %s=%s. Using default=%s", name, value, default)
67
+ return default
68
+
69
+
70
+ def getenv_int(name: str, default: int) -> int:
71
+ value = os.environ.get(name)
72
+ if value is None:
73
+ return default
74
+ try:
75
+ return int(value)
76
+ except ValueError:
77
+ LOGGER.warning("Invalid int for %s=%s. Using default=%s", name, value, default)
78
+ return default
79
+
80
+
81
+ def main(argv: Optional[Sequence[str]] = None) -> None:
82
+ configure_logging()
83
+ bootstrap() # Ensure dependencies are installed and available.
84
+ args = parse_arguments(argv)
85
+
86
+ stage = (args.stage or os.environ.get("PIPELINE_STAGE", "extract")).lower()
87
+ if stage not in {"extract", "describe", "assemble"}:
88
+ raise ValueError(f"Unsupported stage: {stage}")
89
+
90
+ served_model_name = os.environ.get("SERVED_MODEL_NAME", "deepseek-ocr")
91
+ base_url = base_url_from_env()
92
+
93
+ launch_server = should_launch_server() and stage in {"extract", "describe"}
94
+ server_process: Optional[subprocess.Popen] = None
95
+
96
+ try:
97
+ if launch_server:
98
+ server_process = launch_vllm()
99
+
100
+ if stage in {"extract", "describe"}:
101
+ health_url = os.environ.get("HEALTH_URL", f"{base_url}/health")
102
+ LOGGER.info("Waiting for server at %s", health_url)
103
+ if not wait_for_server(health_url):
104
+ raise RuntimeError("vLLM server did not become ready in time")
105
+
106
+ if stage == "extract":
107
+ dataset_name = args.dataset_name or os.environ.get(
108
+ "DATASET_NAME", "HuggingFaceM4/FineVision"
109
+ )
110
+ dataset_config = args.dataset_config or os.environ.get(
111
+ "DATASET_CONFIG", "olmOCR-mix-0225-documents"
112
+ )
113
+ dataset_split = args.dataset_split or os.environ.get(
114
+ "DATASET_SPLIT", "train"
115
+ )
116
+ max_samples = args.max_samples
117
+ if max_samples is None:
118
+ max_samples = getenv_int("MAX_SAMPLES", 3)
119
+
120
+ doc_prompt = args.doc_prompt or os.environ.get(
121
+ "DOC_PROMPT",
122
+ "<image>\n<|grounding|>Convert this document to Markdown.",
123
+ )
124
+ output_dir = Path(
125
+ args.output_dir
126
+ or os.environ.get("STAGE1_OUTPUT_DIR")
127
+ or os.environ.get("OUTPUT_DIR", "./outputs/stage1")
128
+ )
129
+ doc_max_tokens = args.doc_max_tokens or getenv_int("DOC_MAX_TOKENS", 2048)
130
+ doc_temperature = (
131
+ args.doc_temperature
132
+ if args.doc_temperature is not None
133
+ else getenv_float("DOC_TEMPERATURE", 0.0)
134
+ )
135
+
136
+ extract_inference = InferenceSettings.from_env("extract")
137
+
138
+ client = DeepSeekClient(
139
+ base_url=base_url,
140
+ model_name=served_model_name,
141
+ max_tokens=doc_max_tokens,
142
+ temperature=doc_temperature,
143
+ request_timeout=extract_inference.request_timeout,
144
+ max_retries=extract_inference.max_retries,
145
+ retry_backoff_seconds=extract_inference.retry_backoff_seconds,
146
+ max_retry_wait_seconds=extract_inference.max_retry_wait_seconds,
147
+ )
148
+
149
+ settings = ExtractSettings(
150
+ dataset_name=dataset_name,
151
+ dataset_config=dataset_config,
152
+ dataset_split=dataset_split,
153
+ max_samples=max_samples,
154
+ prompt=doc_prompt,
155
+ max_tokens=doc_max_tokens,
156
+ temperature=doc_temperature,
157
+ output_dir=output_dir,
158
+ stream_dataset=not args.no_streaming,
159
+ served_model_name=served_model_name,
160
+ inference=extract_inference,
161
+ client=client,
162
+ )
163
+ run_stage_extract(settings)
164
+
165
+ elif stage == "describe":
166
+ stage1_dir = Path(
167
+ args.stage1_dir
168
+ or os.environ.get("STAGE1_DIR")
169
+ or os.environ.get("STAGE1_OUTPUT_DIR", "./outputs/stage1")
170
+ )
171
+ output_dir = Path(
172
+ args.output_dir
173
+ or os.environ.get("STAGE2_OUTPUT_DIR")
174
+ or os.environ.get("OUTPUT_DIR", "./outputs/stage2")
175
+ )
176
+ figure_prompt = args.figure_prompt or os.environ.get(
177
+ "FIGURE_PROMPT",
178
+ "<image>\nDescribe this image in detail",
179
+ )
180
+ figure_max_tokens = (
181
+ args.figure_max_tokens or getenv_int("FIGURE_MAX_TOKENS", 512)
182
+ )
183
+ figure_temperature = (
184
+ args.figure_temperature
185
+ if args.figure_temperature is not None
186
+ else getenv_float("FIGURE_TEMPERATURE", 0.0)
187
+ )
188
+
189
+ describe_inference = InferenceSettings.from_env("describe")
190
+
191
+ client = DeepSeekClient(
192
+ base_url=base_url,
193
+ model_name=served_model_name,
194
+ max_tokens=figure_max_tokens,
195
+ temperature=figure_temperature,
196
+ request_timeout=describe_inference.request_timeout,
197
+ max_retries=describe_inference.max_retries,
198
+ retry_backoff_seconds=describe_inference.retry_backoff_seconds,
199
+ max_retry_wait_seconds=describe_inference.max_retry_wait_seconds,
200
+ )
201
+
202
+ stage1_locator = ArtifactLocator.from_env("stage1", manifest_name="manifest.json")
203
+
204
+ settings = DescribeSettings(
205
+ stage1_dir=stage1_dir,
206
+ output_dir=output_dir,
207
+ prompt=figure_prompt,
208
+ max_tokens=figure_max_tokens,
209
+ temperature=figure_temperature,
210
+ client=client,
211
+ inference=describe_inference,
212
+ source_locator=stage1_locator,
213
+ )
214
+ run_stage_describe(settings)
215
+
216
+ elif stage == "assemble":
217
+ stage1_dir = Path(
218
+ args.stage1_dir
219
+ or os.environ.get("STAGE1_DIR")
220
+ or os.environ.get("STAGE1_OUTPUT_DIR", "./outputs/stage1")
221
+ )
222
+ stage2_dir = Path(
223
+ args.stage2_dir
224
+ or os.environ.get("STAGE2_DIR")
225
+ or os.environ.get("STAGE2_OUTPUT_DIR", "./outputs/stage2")
226
+ )
227
+ output_dir = Path(
228
+ args.output_dir
229
+ or os.environ.get("STAGE3_OUTPUT_DIR")
230
+ or os.environ.get("OUTPUT_DIR", "./outputs/stage3")
231
+ )
232
+
233
+ dataset_repo_id = args.dataset_repo_id or os.environ.get("ASSEMBLED_DATASET_REPO")
234
+ if dataset_repo_id:
235
+ dataset_repo_id = dataset_repo_id.strip() or None
236
+
237
+ dataset_path_in_repo = (
238
+ args.dataset_path_in_repo
239
+ or os.environ.get("ASSEMBLED_DATASET_PATH_IN_REPO")
240
+ or "data"
241
+ )
242
+ dataset_commit_message = (
243
+ args.dataset_commit_message
244
+ or os.environ.get("ASSEMBLED_DATASET_COMMIT_MESSAGE")
245
+ )
246
+ dataset_branch = args.dataset_branch or os.environ.get("ASSEMBLED_DATASET_BRANCH")
247
+ dataset_repo_type = (
248
+ args.dataset_repo_type
249
+ or os.environ.get("ASSEMBLED_DATASET_REPO_TYPE")
250
+ or "dataset"
251
+ )
252
+
253
+ stage1_locator = ArtifactLocator.from_env("stage1", manifest_name="manifest.json")
254
+ stage2_locator = ArtifactLocator.from_env(
255
+ "stage2", manifest_name="figure_descriptions.json"
256
+ )
257
+
258
+ settings = AssembleSettings(
259
+ stage1_dir=stage1_dir,
260
+ stage2_dir=stage2_dir,
261
+ output_dir=output_dir,
262
+ dataset_repo_id=dataset_repo_id,
263
+ dataset_path_in_repo=dataset_path_in_repo,
264
+ dataset_commit_message=dataset_commit_message,
265
+ dataset_branch=dataset_branch,
266
+ dataset_repo_type=dataset_repo_type,
267
+ stage1_locator=stage1_locator,
268
+ stage2_locator=stage2_locator,
269
+ )
270
+ run_stage_assemble(settings)
271
+
272
+ finally:
273
+ if server_process is not None:
274
+ shutdown_server(server_process)
275
+
276
+
277
+ import subprocess # noqa: E402
278
+
279
+ __all__ = ["main", "parse_arguments", "getenv_float", "getenv_int"]
280
+
ds_batch_ocr/config.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Dict, List, Optional
8
+
9
+ LOGGER = logging.getLogger(__name__)
10
+
11
+
12
+ @dataclass
13
+ class FigureMetadata:
14
+ figure_id: str
15
+ label: str
16
+ image_path: str
17
+ document_relative_path: str
18
+ bounding_box_norm: Dict[str, float]
19
+ bounding_box_norm_list: List[List[float]]
20
+ bounding_box_pixels: Dict[str, int]
21
+ description: Optional[str] = None
22
+
23
+
24
+ @dataclass
25
+ class DocumentMetadata:
26
+ sample_id: str
27
+ dataset_index: int
28
+ document_path: str
29
+ raw_response_path: str
30
+ source_image_path: str
31
+ figures: List[FigureMetadata] = field(default_factory=list)
32
+
33
+
34
+ @dataclass
35
+ class InferenceSettings:
36
+ max_batch_size: int = 4
37
+ max_concurrency: int = 4
38
+ request_timeout: int = 120
39
+ max_retries: int = 3
40
+ retry_backoff_seconds: float = 2.0
41
+ max_retry_wait_seconds: float = 60.0
42
+
43
+ @classmethod
44
+ def from_env(cls, stage: str) -> "InferenceSettings":
45
+ stage = stage.upper()
46
+ default = cls()
47
+
48
+ def read_int(*keys: str, default_value: int) -> int:
49
+ return _read_env(*keys, default=default_value, cast=int)
50
+
51
+ def read_float(*keys: str, default_value: float) -> float:
52
+ return _read_env(*keys, default=default_value, cast=float)
53
+
54
+ return cls(
55
+ max_batch_size=max(
56
+ 1,
57
+ read_int(f"{stage}_BATCH_SIZE", "PIPELINE_BATCH_SIZE", default_value=default.max_batch_size),
58
+ ),
59
+ max_concurrency=max(
60
+ 1,
61
+ read_int(
62
+ f"{stage}_MAX_CONCURRENCY",
63
+ "PIPELINE_MAX_CONCURRENCY",
64
+ default_value=default.max_concurrency,
65
+ ),
66
+ ),
67
+ request_timeout=max(
68
+ 1,
69
+ read_int(
70
+ f"{stage}_REQUEST_TIMEOUT",
71
+ "PIPELINE_REQUEST_TIMEOUT",
72
+ default_value=default.request_timeout,
73
+ ),
74
+ ),
75
+ max_retries=max(
76
+ 0,
77
+ read_int(
78
+ f"{stage}_MAX_RETRIES",
79
+ "PIPELINE_MAX_RETRIES",
80
+ default_value=default.max_retries,
81
+ ),
82
+ ),
83
+ retry_backoff_seconds=max(
84
+ 0.0,
85
+ read_float(
86
+ f"{stage}_RETRY_BACKOFF_SECONDS",
87
+ "PIPELINE_RETRY_BACKOFF_SECONDS",
88
+ default_value=default.retry_backoff_seconds,
89
+ ),
90
+ ),
91
+ max_retry_wait_seconds=max(
92
+ 1.0,
93
+ read_float(
94
+ f"{stage}_MAX_RETRY_WAIT_SECONDS",
95
+ "PIPELINE_MAX_RETRY_WAIT_SECONDS",
96
+ default_value=default.max_retry_wait_seconds,
97
+ ),
98
+ ),
99
+ )
100
+
101
+
102
+ @dataclass
103
+ class ArtifactLocator:
104
+ strategy: str = "local"
105
+ repo_id: Optional[str] = None
106
+ job_id: Optional[str] = None
107
+ job_owner: Optional[str] = None
108
+ uri: Optional[str] = None
109
+ manifest_name: str = "manifest.json"
110
+
111
+ @classmethod
112
+ def from_env(cls, stage: str, *, manifest_name: str) -> "ArtifactLocator":
113
+ stage = stage.upper()
114
+
115
+ def read_str(*keys: str) -> Optional[str]:
116
+ for key in keys:
117
+ value = os.environ.get(key)
118
+ if value:
119
+ value = value.strip()
120
+ if value:
121
+ return value
122
+ return None
123
+
124
+ repo_id = read_str(f"{stage}_JOB_REPO", f"{stage}_REPO_ID")
125
+ job_id = read_str(f"{stage}_JOB_ID")
126
+ job_owner = read_str(f"{stage}_JOB_OWNER")
127
+ uri = read_str(f"{stage}_ARTIFACT_URI", f"{stage}_S3_URI")
128
+ manifest_override = read_str(f"{stage}_MANIFEST_NAME")
129
+ explicit_strategy = read_str(f"{stage}_ARTIFACT_STRATEGY")
130
+ pipeline_strategy = read_str("PIPELINE_ARTIFACT_STRATEGY")
131
+
132
+ strategy = (explicit_strategy or pipeline_strategy or "").lower()
133
+ if not strategy:
134
+ if uri and uri.startswith("s3://"):
135
+ strategy = "s3"
136
+ elif repo_id or (job_id and job_owner):
137
+ strategy = "hf-hub"
138
+ else:
139
+ strategy = "local"
140
+
141
+ locator = cls(
142
+ strategy=strategy,
143
+ repo_id=repo_id,
144
+ job_id=job_id,
145
+ job_owner=job_owner,
146
+ uri=uri,
147
+ manifest_name=manifest_override or manifest_name,
148
+ )
149
+
150
+ LOGGER.debug(
151
+ "Artifact locator for %s: %s",
152
+ stage,
153
+ {
154
+ "strategy": locator.strategy,
155
+ "repo_id": locator.repo_id,
156
+ "job_id": locator.job_id,
157
+ "job_owner": locator.job_owner,
158
+ "uri": locator.uri,
159
+ "manifest": locator.manifest_name,
160
+ },
161
+ )
162
+ return locator
163
+
164
+
165
+ @dataclass
166
+ class ExtractSettings:
167
+ dataset_name: str
168
+ dataset_config: str
169
+ dataset_split: str
170
+ max_samples: Optional[int]
171
+ prompt: str
172
+ max_tokens: int
173
+ temperature: float
174
+ output_dir: Path
175
+ stream_dataset: bool
176
+ served_model_name: str
177
+ inference: InferenceSettings = field(default_factory=InferenceSettings)
178
+ client: "DeepSeekClient"
179
+
180
+
181
+ @dataclass
182
+ class DescribeSettings:
183
+ stage1_dir: Path
184
+ output_dir: Path
185
+ prompt: str
186
+ max_tokens: int
187
+ temperature: float
188
+ client: "DeepSeekClient"
189
+ inference: InferenceSettings = field(default_factory=InferenceSettings)
190
+ source_locator: ArtifactLocator = field(default_factory=ArtifactLocator)
191
+
192
+
193
+ @dataclass
194
+ class AssembleSettings:
195
+ stage1_dir: Path
196
+ stage2_dir: Path
197
+ output_dir: Path
198
+ dataset_repo_id: Optional[str]
199
+ dataset_path_in_repo: str
200
+ dataset_commit_message: Optional[str]
201
+ dataset_branch: Optional[str]
202
+ dataset_repo_type: str
203
+ stage1_locator: ArtifactLocator = field(default_factory=ArtifactLocator)
204
+ stage2_locator: ArtifactLocator = field(default_factory=ArtifactLocator)
205
+
206
+
207
+ __all__ = [
208
+ "FigureMetadata",
209
+ "DocumentMetadata",
210
+ "InferenceSettings",
211
+ "ArtifactLocator",
212
+ "ExtractSettings",
213
+ "DescribeSettings",
214
+ "AssembleSettings",
215
+ ]
216
+
217
+
218
+ def _read_env(*keys: str, default, cast):
219
+ for key in keys:
220
+ raw = os.environ.get(key)
221
+ if raw is None:
222
+ continue
223
+ try:
224
+ return cast(raw)
225
+ except (TypeError, ValueError):
226
+ LOGGER.warning("Invalid value for %s=%s; using default=%s", key, raw, default)
227
+ return default
228
+
ds_batch_ocr/dependencies.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import subprocess
5
+ import sys
6
+ from typing import Any, Dict, Sequence
7
+
8
+ LOGGER = logging.getLogger(__name__)
9
+
10
+ DEFAULT_DEPENDENCIES: Sequence[str] = (
11
+ "datasets",
12
+ "huggingface_hub",
13
+ "pillow",
14
+ "requests",
15
+ )
16
+
17
+ _CACHE: Dict[str, Any] | None = None
18
+
19
+
20
+ def ensure_packages(packages: Sequence[str]) -> None:
21
+ missing: list[str] = []
22
+ for package in packages:
23
+ module_name = "PIL" if package == "pillow" else package
24
+ try:
25
+ __import__(module_name)
26
+ except ModuleNotFoundError:
27
+ missing.append(package)
28
+
29
+ if not missing:
30
+ return
31
+
32
+ LOGGER.info("Installing missing packages: %s", ", ".join(missing))
33
+ subprocess.run([sys.executable, "-m", "pip", "install", *missing], check=True)
34
+
35
+
36
+ def bootstrap() -> Dict[str, Any]:
37
+ global _CACHE
38
+ if _CACHE is None:
39
+ ensure_packages(DEFAULT_DEPENDENCIES)
40
+
41
+ from datasets import load_dataset as _load_dataset # type: ignore
42
+ import requests as _requests # type: ignore
43
+ from huggingface_hub import ( # type: ignore
44
+ HfApi as _HfApi,
45
+ create_repo as _create_repo,
46
+ snapshot_download as _snapshot_download,
47
+ )
48
+ from PIL import Image as _Image # type: ignore
49
+
50
+ _CACHE = {
51
+ "load_dataset": _load_dataset,
52
+ "requests": _requests,
53
+ "HfApi": _HfApi,
54
+ "create_repo": _create_repo,
55
+ "snapshot_download": _snapshot_download,
56
+ "Image": _Image,
57
+ }
58
+ return _CACHE.copy()
59
+
60
+
61
+ def get_dependency(name: str) -> Any:
62
+ cache = bootstrap()
63
+ if name not in cache:
64
+ raise KeyError(f"Unknown dependency requested: {name}")
65
+ return cache[name]
66
+
67
+
68
+ __all__ = [
69
+ "DEFAULT_DEPENDENCIES",
70
+ "ensure_packages",
71
+ "bootstrap",
72
+ "get_dependency",
73
+ ]
74
+
ds_batch_ocr/document.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import base64
5
+ import json
6
+ import re
7
+ from io import BytesIO
8
+ from pathlib import Path
9
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
10
+
11
+ from .config import FigureMetadata
12
+ from .dependencies import bootstrap
13
+
14
+ deps = bootstrap()
15
+ Image = deps["Image"]
16
+
17
+ GROUNDING_PATTERN = re.compile(
18
+ r"<\|ref\|>(.*?)<\|/ref\|><\|det\|>(.*?)<\|/det\|>",
19
+ re.DOTALL,
20
+ )
21
+
22
+ FIGURE_MARKDOWN_PATTERN = re.compile(
23
+ r"!\[Figure (?P<figure_id>[^\]]+)\]\((?P<path>[^)]+)\)"
24
+ )
25
+
26
+
27
+ def encode_image(image: "Image.Image") -> str:
28
+ buffer = BytesIO()
29
+ image.save(buffer, format="PNG")
30
+ return base64.b64encode(buffer.getvalue()).decode("utf-8")
31
+
32
+
33
+ def extract_grounding_blocks(text: str) -> List[Dict[str, Any]]:
34
+ matches: List[Dict[str, Any]] = []
35
+ for match in GROUNDING_PATTERN.finditer(text):
36
+ label = match.group(1).strip()
37
+ details = match.group(2).strip()
38
+ try:
39
+ coordinates = ast.literal_eval(details)
40
+ except Exception:
41
+ coordinates = None
42
+ matches.append(
43
+ {
44
+ "label": label,
45
+ "coordinates": coordinates,
46
+ "raw": match.group(0),
47
+ "span": match.span(),
48
+ }
49
+ )
50
+ return matches
51
+
52
+
53
+ def flatten_boxes(coordinates: Any) -> List[List[float]]:
54
+ boxes: List[List[float]] = []
55
+ if coordinates is None:
56
+ return boxes
57
+ if isinstance(coordinates, (list, tuple)):
58
+ for item in coordinates:
59
+ if isinstance(item, (list, tuple)) and len(item) == 4:
60
+ boxes.append([float(value) for value in item])
61
+ elif isinstance(item, dict):
62
+ boxes.extend(flatten_boxes(item.get("bbox")))
63
+ elif isinstance(coordinates, dict):
64
+ boxes.extend(flatten_boxes(coordinates.get("bbox")))
65
+ return boxes
66
+
67
+
68
+ def merge_boxes(boxes: List[List[float]]) -> Optional[List[float]]:
69
+ if not boxes:
70
+ return None
71
+ x1 = min(box[0] for box in boxes)
72
+ y1 = min(box[1] for box in boxes)
73
+ x2 = max(box[2] for box in boxes)
74
+ y2 = max(box[3] for box in boxes)
75
+ return [x1, y1, x2, y2]
76
+
77
+
78
+ def clamp(value: int, lower: int, upper: int) -> int:
79
+ return max(lower, min(upper, value))
80
+
81
+
82
+ def normalized_to_pixels(box: List[float], width: int, height: int) -> Optional[List[int]]:
83
+ if len(box) != 4 or width <= 0 or height <= 0:
84
+ return None
85
+ x1 = clamp(int(round(box[0] / 999.0 * width)), 0, width)
86
+ y1 = clamp(int(round(box[1] / 999.0 * height)), 0, height)
87
+ x2 = clamp(int(round(box[2] / 999.0 * width)), 0, width)
88
+ y2 = clamp(int(round(box[3] / 999.0 * height)), 0, height)
89
+ if x2 <= x1 or y2 <= y1:
90
+ return None
91
+ return [x1, y1, x2, y2]
92
+
93
+
94
+ def postprocess_markdown(text: str) -> str:
95
+ cleaned = (
96
+ text.replace("\\coloneqq", ":=")
97
+ .replace("\\eqqcolon", "=:")
98
+ .replace("<|image_pad|>", "")
99
+ )
100
+ cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
101
+ return cleaned.strip()
102
+
103
+
104
+ def apply_replacements(text: str, replacements: List[Tuple[int, int, str]]) -> str:
105
+ if not replacements:
106
+ return postprocess_markdown(text)
107
+ sorted_replacements = sorted(replacements, key=lambda item: item[0])
108
+ segments: List[str] = []
109
+ cursor = 0
110
+ for start, end, replacement in sorted_replacements:
111
+ segments.append(text[cursor:start])
112
+ segments.append(replacement)
113
+ cursor = end
114
+ segments.append(text[cursor:])
115
+ return postprocess_markdown("".join(segments))
116
+
117
+
118
+ def save_figure(
119
+ image: "Image.Image",
120
+ sample_dir: Path,
121
+ sample_id: str,
122
+ figure_index: int,
123
+ boxes: List[List[float]],
124
+ label: str,
125
+ ) -> Optional[FigureMetadata]:
126
+ merged_box = merge_boxes(boxes)
127
+ if not merged_box:
128
+ return None
129
+ width, height = image.size
130
+ pixel_box = normalized_to_pixels(merged_box, width, height)
131
+ if not pixel_box:
132
+ return None
133
+ x1, y1, x2, y2 = pixel_box
134
+ crop = image.crop((x1, y1, x2, y2))
135
+
136
+ figures_dir = sample_dir / "figures"
137
+ figures_dir.mkdir(parents=True, exist_ok=True)
138
+
139
+ figure_id = f"{sample_id}_fig{figure_index:02d}"
140
+ figure_filename = f"{figure_id}.png"
141
+ figure_relative_doc_path = Path("figures") / figure_filename
142
+ full_path = figures_dir / figure_filename
143
+ crop.save(full_path)
144
+
145
+ norm_box = [value / 999.0 for value in merged_box]
146
+ bounding_box_norm = {
147
+ "x1": norm_box[0],
148
+ "y1": norm_box[1],
149
+ "x2": norm_box[2],
150
+ "y2": norm_box[3],
151
+ }
152
+ bounding_box_pixels = {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
153
+
154
+ return FigureMetadata(
155
+ figure_id=figure_id,
156
+ label=label,
157
+ image_path=(Path(sample_id) / figure_relative_doc_path).as_posix(),
158
+ document_relative_path=figure_relative_doc_path.as_posix(),
159
+ bounding_box_norm=bounding_box_norm,
160
+ bounding_box_norm_list=[[float(v) for v in box] for box in boxes],
161
+ bounding_box_pixels=bounding_box_pixels,
162
+ )
163
+
164
+
165
+ def write_text(path: Path, content: str) -> None:
166
+ path.parent.mkdir(parents=True, exist_ok=True)
167
+ path.write_text(content, encoding="utf-8")
168
+
169
+
170
+ def write_json(path: Path, payload: Dict[str, Any]) -> None:
171
+ path.parent.mkdir(parents=True, exist_ok=True)
172
+ with path.open("w", encoding="utf-8") as handle:
173
+ json.dump(payload, handle, indent=2, ensure_ascii=False)
174
+
175
+
176
+ def write_jsonl(path: Path, rows: Iterable[Dict[str, Any]]) -> None:
177
+ path.parent.mkdir(parents=True, exist_ok=True)
178
+ with path.open("w", encoding="utf-8") as handle:
179
+ for row in rows:
180
+ handle.write(json.dumps(row, ensure_ascii=False))
181
+ handle.write("\n")
182
+
183
+
184
+ def build_document_markdown(
185
+ image: "Image.Image",
186
+ response_text: str,
187
+ sample_dir: Path,
188
+ sample_id: str,
189
+ ) -> Tuple[str, List[FigureMetadata]]:
190
+ blocks = extract_grounding_blocks(response_text)
191
+ replacements: List[Tuple[int, int, str]] = []
192
+ figures: List[FigureMetadata] = []
193
+ figure_index = 1
194
+
195
+ for block in blocks:
196
+ label = block["label"].lower()
197
+ start, end = block["span"]
198
+ if label == "image":
199
+ boxes = flatten_boxes(block["coordinates"])
200
+ figure_metadata = save_figure(
201
+ image=image,
202
+ sample_dir=sample_dir,
203
+ sample_id=sample_id,
204
+ figure_index=figure_index,
205
+ boxes=boxes,
206
+ label=block["label"],
207
+ )
208
+ if figure_metadata:
209
+ figures.append(figure_metadata)
210
+ replacements.append(
211
+ (
212
+ start,
213
+ end,
214
+ f"![Figure {figure_metadata.figure_id}]({figure_metadata.document_relative_path})",
215
+ )
216
+ )
217
+ figure_index += 1
218
+ else:
219
+ replacements.append((start, end, ""))
220
+ else:
221
+ replacements.append((start, end, ""))
222
+
223
+ markdown = apply_replacements(response_text, replacements)
224
+ return markdown, figures
225
+
226
+
227
+ def enrich_markdown_with_captions(
228
+ markdown: str,
229
+ description_map: Dict[str, Dict[str, Any]],
230
+ ) -> str:
231
+ used: set[str] = set()
232
+
233
+ def replace(match: re.Match[str]) -> str:
234
+ figure_id = match.group("figure_id").strip()
235
+ path = match.group("path").strip()
236
+ entry = description_map.get(figure_id)
237
+ if not entry:
238
+ return match.group(0)
239
+
240
+ description = entry.get("description", "").strip()
241
+ if not description:
242
+ return match.group(0)
243
+
244
+ alt_text = f"Figure {figure_id}: {description}"
245
+ rendered = f"![{alt_text}]({path})"
246
+ if figure_id not in used:
247
+ rendered += f"\n\n*Figure {figure_id}: {description}*\n"
248
+ used.add(figure_id)
249
+ return rendered
250
+
251
+ return FIGURE_MARKDOWN_PATTERN.sub(replace, markdown)
252
+
253
+
254
+ __all__ = [
255
+ "encode_image",
256
+ "extract_grounding_blocks",
257
+ "flatten_boxes",
258
+ "merge_boxes",
259
+ "normalized_to_pixels",
260
+ "postprocess_markdown",
261
+ "apply_replacements",
262
+ "save_figure",
263
+ "write_text",
264
+ "write_json",
265
+ "write_jsonl",
266
+ "build_document_markdown",
267
+ "enrich_markdown_with_captions",
268
+ "FigureMetadata",
269
+ "GROUNDING_PATTERN",
270
+ "FIGURE_MARKDOWN_PATTERN",
271
+ ]
272
+
ds_batch_ocr/hf_io.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Dict, Optional
8
+
9
+ from .config import ArtifactLocator
10
+ from .dependencies import bootstrap
11
+
12
+ deps = bootstrap()
13
+ snapshot_download = deps["snapshot_download"]
14
+ create_repo = deps["create_repo"]
15
+ 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")):
22
+ LOGGER.info("Extracting archive %s", archive)
23
+ with tarfile.open(archive, "r:gz") as tar:
24
+ tar.extractall(archive.parent)
25
+ archive.unlink()
26
+
27
+
28
+ def download_job_artifact(repo_id: str, target_dir: Path) -> None:
29
+ LOGGER.info("Downloading job artifact %s -> %s", repo_id, target_dir)
30
+ snapshot_download(
31
+ repo_id=repo_id,
32
+ local_dir=target_dir,
33
+ local_dir_use_symlinks=False,
34
+ ignore_patterns=("logs/**",),
35
+ )
36
+ unpack_archives(target_dir)
37
+
38
+
39
+ def resolve_stage_dir(base_dir: Path, locator: ArtifactLocator) -> Path:
40
+ base_dir.mkdir(parents=True, exist_ok=True)
41
+
42
+ def locate_manifest(candidate: Path) -> Optional[Path]:
43
+ manifest_name = locator.manifest_name or "manifest.json"
44
+ manifest_path = candidate / manifest_name
45
+ return manifest_path if manifest_path.exists() else None
46
+
47
+ manifest_path = locate_manifest(base_dir)
48
+ if manifest_path:
49
+ return base_dir
50
+
51
+ strategy = (locator.strategy or "local").lower()
52
+ if strategy == "local":
53
+ LOGGER.debug("Using local artifact locator for %s", base_dir)
54
+ elif strategy in {"hf-hub", "huggingface", "hub"}:
55
+ repo_id = locator.repo_id
56
+ if locator.uri:
57
+ repo_id = locator.uri
58
+ if repo_id:
59
+ download_job_artifact(repo_id, base_dir)
60
+ elif locator.job_id and locator.job_owner:
61
+ download_job_artifact(f"jobs/{locator.job_owner}/{locator.job_id}", base_dir)
62
+ else:
63
+ LOGGER.debug("HF locator missing repo or job identifiers; skipping download.")
64
+ elif strategy == "s3":
65
+ if locator.uri:
66
+ LOGGER.warning(
67
+ "S3 artifact download is not yet implemented. uri=%s", locator.uri
68
+ )
69
+ else:
70
+ LOGGER.warning("S3 artifact locator missing uri; nothing to download.")
71
+ else:
72
+ LOGGER.warning(
73
+ "Unknown artifact locator strategy '%s'; falling back to local files.",
74
+ locator.strategy,
75
+ )
76
+
77
+ manifest_path = locate_manifest(base_dir)
78
+ if manifest_path:
79
+ return base_dir
80
+
81
+ outputs_dir = base_dir / "outputs"
82
+ if locate_manifest(outputs_dir):
83
+ return outputs_dir
84
+
85
+ return base_dir
86
+
87
+
88
+ def maybe_upload_dataset(
89
+ *,
90
+ output_dir: Path,
91
+ repo_id: Optional[str],
92
+ repo_type: str,
93
+ path_in_repo: str,
94
+ commit_message: Optional[str],
95
+ revision: Optional[str],
96
+ ) -> None:
97
+ if not repo_id:
98
+ LOGGER.info("No dataset repo provided; skipping upload.")
99
+ return
100
+
101
+ commit_message = commit_message or (
102
+ "Add assembled DeepSeek OCR dataset " + datetime.utcnow().isoformat() + "Z"
103
+ )
104
+
105
+ token = env_or_none("HF_TOKEN")
106
+ LOGGER.info("Ensuring %s repo exists: repo_id=%s", repo_type, repo_id)
107
+ create_repo(
108
+ repo_id=repo_id,
109
+ repo_type=repo_type,
110
+ exist_ok=True,
111
+ token=token,
112
+ )
113
+
114
+ LOGGER.info(
115
+ "Uploading assembled outputs to %s (path_in_repo=%s, revision=%s)",
116
+ repo_id,
117
+ path_in_repo,
118
+ revision,
119
+ )
120
+ HfApi().upload_folder(
121
+ folder_path=str(output_dir),
122
+ repo_id=repo_id,
123
+ repo_type=repo_type,
124
+ path_in_repo=path_in_repo or "",
125
+ commit_message=commit_message,
126
+ revision=revision,
127
+ token=token,
128
+ )
129
+
130
+
131
+ def env_or_none(name: str) -> Optional[str]:
132
+ value = os.environ.get(name)
133
+ if value:
134
+ value = value.strip()
135
+ return value or None
136
+
137
+
138
+ import os
139
+
140
+ __all__ = [
141
+ "unpack_archives",
142
+ "download_job_artifact",
143
+ "resolve_stage_dir",
144
+ "maybe_upload_dataset",
145
+ ]
146
+
ds_batch_ocr/logging_utils.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+
6
+
7
+ def configure_logging() -> None:
8
+ level = os.environ.get("LOG_LEVEL", "INFO").upper()
9
+ logging.basicConfig(
10
+ level=level,
11
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
12
+ )
13
+
14
+
15
+ __all__ = ["configure_logging"]
16
+
ds_batch_ocr/server.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ import signal
6
+ import subprocess
7
+ import threading
8
+ import time
9
+ from typing import Any, Dict, List, Optional, Sequence
10
+
11
+ from .dependencies import bootstrap
12
+ from .document import encode_image
13
+
14
+ deps = bootstrap()
15
+ requests = deps["requests"]
16
+
17
+ LOGGER = logging.getLogger(__name__)
18
+
19
+
20
+ def _stream_output(pipe, prefix: str) -> None:
21
+ try:
22
+ for line in iter(pipe.readline, ""):
23
+ print(f"[{prefix}] {line.rstrip()}", flush=True)
24
+ finally:
25
+ pipe.close()
26
+
27
+
28
+ def launch_vllm() -> subprocess.Popen:
29
+ model_id = os.environ.get("MODEL_ID", "deepseek-ai/DeepSeek-OCR")
30
+ served_name = os.environ.get("SERVED_MODEL_NAME", "deepseek-ocr")
31
+ port = os.environ.get("PORT", "8080")
32
+ host = os.environ.get("HOST", "0.0.0.0")
33
+
34
+ cmd: List[str] = [
35
+ "vllm",
36
+ "serve",
37
+ "--model",
38
+ model_id,
39
+ "--served-model-name",
40
+ served_name,
41
+ "--tensor-parallel-size",
42
+ os.environ.get("TENSOR_PARALLEL_SIZE", "1"),
43
+ "--max-model-len",
44
+ os.environ.get("MAX_MODEL_LEN", "4096"),
45
+ "--gpu-memory-utilization",
46
+ os.environ.get("GPU_MEMORY_UTILIZATION", "0.85"),
47
+ "--port",
48
+ port,
49
+ "--host",
50
+ host,
51
+ "--trust-remote-code",
52
+ "--enable-chunked-prefill",
53
+ ]
54
+
55
+ extra_server_args = os.environ.get("EXTRA_VLLM_ARGS")
56
+ if extra_server_args:
57
+ cmd.extend(extra_server_args.split())
58
+
59
+ LOGGER.info("Launching vLLM server with command: %s", " ".join(cmd))
60
+ process = subprocess.Popen(
61
+ cmd,
62
+ stdout=subprocess.PIPE,
63
+ stderr=subprocess.PIPE,
64
+ text=True,
65
+ bufsize=1,
66
+ )
67
+
68
+ threads = []
69
+ for name, pipe in (("STDOUT", process.stdout), ("STDERR", process.stderr)):
70
+ if pipe is not None:
71
+ thread = threading.Thread(
72
+ target=_stream_output,
73
+ args=(pipe, f"vLLM {name}"),
74
+ daemon=True,
75
+ )
76
+ thread.start()
77
+ threads.append(thread)
78
+
79
+ process._log_threads = threads # type: ignore[attr-defined]
80
+ return process
81
+
82
+
83
+ def shutdown_server(server_process: subprocess.Popen) -> None:
84
+ LOGGER.info("Shutting down vLLM server")
85
+ server_process.send_signal(signal.SIGTERM)
86
+ try:
87
+ server_process.wait(timeout=30)
88
+ except subprocess.TimeoutExpired:
89
+ LOGGER.warning("Server did not exit in time, sending SIGKILL")
90
+ server_process.kill()
91
+
92
+ log_threads = getattr(server_process, "_log_threads", [])
93
+ for thread in log_threads:
94
+ thread.join(timeout=1)
95
+
96
+
97
+ def wait_for_server(url: str, timeout_s: int = 300, interval_s: int = 5) -> bool:
98
+ deadline = time.time() + timeout_s
99
+ while time.time() < deadline:
100
+ try:
101
+ response = requests.get(url, timeout=5)
102
+ if response.ok:
103
+ return True
104
+ except Exception:
105
+ pass
106
+ time.sleep(interval_s)
107
+ return False
108
+
109
+
110
+ def should_launch_server() -> bool:
111
+ return os.environ.get("SKIP_SERVER_LAUNCH", "").lower() not in {"1", "true", "yes"}
112
+
113
+
114
+ def base_url_from_env() -> str:
115
+ port = os.environ.get("PORT", "8080")
116
+ default_url = f"http://127.0.0.1:{port}"
117
+ return os.environ.get("BASE_URL", default_url)
118
+
119
+
120
+ def prepare_payload(
121
+ image: "Image.Image",
122
+ served_name: str,
123
+ prompt: str,
124
+ max_tokens: int,
125
+ temperature: float,
126
+ ) -> Dict[str, Any]:
127
+ return {
128
+ "model": served_name,
129
+ "messages": [
130
+ {
131
+ "role": "user",
132
+ "content": [
133
+ {"type": "text", "text": prompt},
134
+ {
135
+ "type": "image_url",
136
+ "image_url": {"url": f"data:image/png;base64,{encode_image(image)}"},
137
+ },
138
+ ],
139
+ }
140
+ ],
141
+ "max_tokens": max_tokens,
142
+ "temperature": temperature,
143
+ }
144
+
145
+
146
+ class DeepSeekClient:
147
+ def __init__(
148
+ self,
149
+ base_url: str,
150
+ model_name: str,
151
+ max_tokens: int,
152
+ temperature: float,
153
+ *,
154
+ request_timeout: int = 120,
155
+ max_retries: int = 3,
156
+ retry_backoff_seconds: float = 2.0,
157
+ max_retry_wait_seconds: float = 60.0,
158
+ backend: Optional[str] = None,
159
+ ) -> None:
160
+ self.base_url = base_url.rstrip("/")
161
+ self.model_name = model_name
162
+ self.default_max_tokens = max_tokens
163
+ self.default_temperature = temperature
164
+ self.default_request_timeout = request_timeout
165
+ self.max_retries = max(0, max_retries)
166
+ self.retry_backoff_seconds = max(0.0, retry_backoff_seconds)
167
+ self.max_retry_wait_seconds = max_retry_wait_seconds
168
+ self._thread_local = threading.local()
169
+ self.backend = (backend or os.environ.get("DEEPSEEK_INFERENCE_MODE", "http")).lower()
170
+ self._llm = None
171
+ self._sampling_params_cls = None
172
+ if self.backend == "vllm":
173
+ try:
174
+ from vllm import LLM, SamplingParams # type: ignore
175
+ except ImportError as exc: # pragma: no cover - runtime safeguard
176
+ raise RuntimeError(
177
+ "DEEPSEEK_INFERENCE_MODE=vllm requires the vllm package to be installed."
178
+ ) from exc
179
+
180
+ model_id = os.environ.get("MODEL_ID", model_name)
181
+ tensor_parallel = int(os.environ.get("TENSOR_PARALLEL_SIZE", "1"))
182
+ trust_remote_code = os.environ.get("VLLM_TRUST_REMOTE_CODE", "1").lower() in {
183
+ "1",
184
+ "true",
185
+ "yes",
186
+ }
187
+ llm_kwargs: Dict[str, Any] = {
188
+ "model": model_id,
189
+ "tensor_parallel_size": tensor_parallel,
190
+ "trust_remote_code": trust_remote_code,
191
+ }
192
+ mm_cache_gb = os.environ.get("VLLM_MM_CACHE_GB")
193
+ if mm_cache_gb:
194
+ try:
195
+ llm_kwargs["mm_processor_cache_gb"] = float(mm_cache_gb)
196
+ except ValueError:
197
+ LOGGER.warning("Invalid VLLM_MM_CACHE_GB=%s; ignoring.", mm_cache_gb)
198
+ self._llm = LLM(**llm_kwargs)
199
+ self._sampling_params_cls = SamplingParams
200
+
201
+ def _get_session(self) -> Any:
202
+ session = getattr(self._thread_local, "session", None)
203
+ if session is None:
204
+ session = requests.Session()
205
+ self._thread_local.session = session
206
+ return session
207
+
208
+ def _perform_request(
209
+ self,
210
+ payload: Dict[str, Any],
211
+ request_timeout: int,
212
+ ) -> Dict[str, Any]:
213
+ attempts = self.max_retries + 1
214
+ for attempt in range(1, attempts + 1):
215
+ try:
216
+ session = self._get_session()
217
+ response = session.post(
218
+ f"{self.base_url}/v1/chat/completions",
219
+ json=payload,
220
+ timeout=request_timeout,
221
+ )
222
+ response.raise_for_status()
223
+ return response.json()
224
+ except Exception as exc: # pragma: no cover - defensive logging
225
+ if attempt >= attempts:
226
+ LOGGER.error("DeepSeek request exhausted retries: %s", exc)
227
+ raise
228
+ backoff = min(
229
+ self.retry_backoff_seconds * (2 ** (attempt - 1)),
230
+ self.max_retry_wait_seconds,
231
+ )
232
+ LOGGER.warning(
233
+ "DeepSeek request failed (attempt %s/%s): %s. Retrying in %.2fs",
234
+ attempt,
235
+ attempts,
236
+ exc,
237
+ backoff,
238
+ )
239
+ time.sleep(backoff)
240
+ raise RuntimeError("Unreachable") # pragma: no cover
241
+
242
+ def infer(
243
+ self,
244
+ image: "Image.Image",
245
+ prompt: str,
246
+ max_tokens: Optional[int] = None,
247
+ temperature: Optional[float] = None,
248
+ request_timeout: Optional[int] = None,
249
+ ) -> str:
250
+ payload = prepare_payload(
251
+ image=image,
252
+ served_name=self.model_name,
253
+ prompt=prompt,
254
+ max_tokens=max_tokens or self.default_max_tokens,
255
+ temperature=(
256
+ temperature if temperature is not None else self.default_temperature
257
+ ),
258
+ )
259
+ if self.backend == "vllm":
260
+ responses = self.infer_batch(
261
+ [
262
+ {
263
+ "image": image,
264
+ "prompt": prompt,
265
+ "max_tokens": max_tokens or self.default_max_tokens,
266
+ "temperature": (
267
+ temperature if temperature is not None else self.default_temperature
268
+ ),
269
+ }
270
+ ]
271
+ )
272
+ return responses[0]
273
+
274
+ effective_timeout = request_timeout or self.default_request_timeout
275
+ result = self._perform_request(payload, effective_timeout)
276
+ return result["choices"][0]["message"]["content"]
277
+
278
+ def infer_batch(self, requests_data: Sequence[Dict[str, Any]]) -> List[str]:
279
+ if not requests_data:
280
+ return []
281
+
282
+ if self.backend == "vllm":
283
+ assert self._llm is not None and self._sampling_params_cls is not None # for mypy
284
+ base_req = requests_data[0]
285
+ sampling = self._sampling_params_cls(
286
+ temperature=base_req.get("temperature", self.default_temperature),
287
+ max_tokens=base_req.get("max_tokens", self.default_max_tokens),
288
+ top_p=base_req.get("top_p", 1.0),
289
+ )
290
+ llm_inputs = []
291
+ for req in requests_data:
292
+ if req.get("max_tokens") != base_req.get("max_tokens"):
293
+ LOGGER.debug(
294
+ "Mixed max_tokens in batch; using first value %s",
295
+ base_req.get("max_tokens"),
296
+ )
297
+ if req.get("temperature") != base_req.get("temperature"):
298
+ LOGGER.debug(
299
+ "Mixed temperature in batch; using first value %s",
300
+ base_req.get("temperature"),
301
+ )
302
+ llm_inputs.append(
303
+ {
304
+ "prompt": req.get("prompt", ""),
305
+ "multi_modal_data": {"image": req["image"]},
306
+ }
307
+ )
308
+ outputs = self._llm.generate(llm_inputs, sampling)
309
+ results: List[str] = []
310
+ for output in outputs:
311
+ if not output.outputs:
312
+ results.append("")
313
+ else:
314
+ results.append(output.outputs[0].text)
315
+ return results
316
+
317
+ responses: List[str] = []
318
+ for req in requests_data:
319
+ responses.append(
320
+ self.infer(
321
+ image=req["image"],
322
+ prompt=req.get("prompt", ""),
323
+ max_tokens=req.get("max_tokens"),
324
+ temperature=req.get("temperature"),
325
+ request_timeout=req.get("request_timeout"),
326
+ )
327
+ )
328
+ return responses
329
+
330
+ def close(self) -> None:
331
+ session = getattr(self._thread_local, "session", None)
332
+ if session is not None:
333
+ try:
334
+ session.close()
335
+ finally:
336
+ delattr(self._thread_local, "session")
337
+ if self._llm is not None:
338
+ try:
339
+ shutdown = getattr(self._llm, "shutdown", None)
340
+ if callable(shutdown):
341
+ shutdown()
342
+ finally:
343
+ self._llm = None
344
+
345
+
346
+ __all__ = [
347
+ "launch_vllm",
348
+ "shutdown_server",
349
+ "wait_for_server",
350
+ "should_launch_server",
351
+ "base_url_from_env",
352
+ "DeepSeekClient",
353
+ ]
354
+
ds_batch_ocr/stages.py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ import shutil
9
+
10
+ from .config import (
11
+ AssembleSettings,
12
+ DescribeSettings,
13
+ DocumentMetadata,
14
+ ExtractSettings,
15
+ FigureMetadata,
16
+ )
17
+ from .dependencies import bootstrap
18
+ from .document import (
19
+ build_document_markdown,
20
+ enrich_markdown_with_captions,
21
+ write_json,
22
+ write_jsonl,
23
+ write_text,
24
+ )
25
+ from .hf_io import maybe_upload_dataset, resolve_stage_dir
26
+
27
+ deps = bootstrap()
28
+ load_dataset = deps["load_dataset"]
29
+ Image = deps["Image"]
30
+
31
+ LOGGER = logging.getLogger(__name__)
32
+
33
+
34
+ def run_stage_extract(settings: ExtractSettings) -> None:
35
+ dataset = load_dataset(
36
+ settings.dataset_name,
37
+ settings.dataset_config,
38
+ split=settings.dataset_split,
39
+ streaming=settings.stream_dataset,
40
+ )
41
+
42
+ settings.output_dir.mkdir(parents=True, exist_ok=True)
43
+
44
+ documents: List[DocumentMetadata] = []
45
+ failures: List[Dict[str, Any]] = []
46
+
47
+ chunk_size = max(settings.inference.max_batch_size, 1)
48
+
49
+ LOGGER.info(
50
+ "Extract stage | dataset=%s/%s/%s | max_samples=%s | chunk=%s",
51
+ settings.dataset_name,
52
+ settings.dataset_config,
53
+ settings.dataset_split,
54
+ settings.max_samples,
55
+ chunk_size,
56
+ )
57
+
58
+ batch_contexts: List[Dict[str, Any]] = []
59
+ batch_requests: List[Dict[str, Any]] = []
60
+
61
+ def flush_batch() -> None:
62
+ nonlocal batch_contexts, batch_requests
63
+ if not batch_contexts:
64
+ return
65
+
66
+ try:
67
+ responses = list(settings.client.infer_batch(batch_requests))
68
+ except Exception as exc: # pragma: no cover - defensive logging
69
+ LOGGER.exception("Batch inference failed for %s samples", len(batch_contexts))
70
+ for ctx in batch_contexts:
71
+ failures.append(
72
+ {
73
+ "sample_id": ctx["sample_id"],
74
+ "dataset_index": ctx["dataset_index"],
75
+ "error": str(exc),
76
+ "exception_type": exc.__class__.__name__,
77
+ }
78
+ )
79
+ image_obj = ctx.get("image")
80
+ if hasattr(image_obj, "close"):
81
+ image_obj.close()
82
+ batch_contexts = []
83
+ batch_requests = []
84
+ return
85
+
86
+ if len(responses) != len(batch_contexts):
87
+ LOGGER.warning(
88
+ "Mismatch between responses (%s) and requests (%s) in extract batch",
89
+ len(responses),
90
+ len(batch_contexts),
91
+ )
92
+
93
+ for idx, ctx in enumerate(batch_contexts):
94
+ image_obj = ctx.get("image")
95
+ try:
96
+ response_text = responses[idx].strip() if idx < len(responses) else ""
97
+ if not response_text:
98
+ raise RuntimeError("Empty response from DeepSeek inference")
99
+
100
+ raw_response_path = ctx["sample_dir"] / "raw_response.md"
101
+ write_text(raw_response_path, response_text)
102
+
103
+ markdown, figures = build_document_markdown(
104
+ image=image_obj,
105
+ response_text=response_text,
106
+ sample_dir=ctx["sample_dir"],
107
+ sample_id=ctx["sample_id"],
108
+ )
109
+
110
+ document_path = ctx["sample_dir"] / "document.md"
111
+ write_text(document_path, markdown)
112
+
113
+ documents.append(
114
+ DocumentMetadata(
115
+ sample_id=ctx["sample_id"],
116
+ dataset_index=ctx["dataset_index"],
117
+ document_path=(Path(ctx["sample_id"]) / "document.md").as_posix(),
118
+ raw_response_path=(Path(ctx["sample_id"]) / "raw_response.md").as_posix(),
119
+ source_image_path=(Path(ctx["sample_id"]) / "source.png").as_posix(),
120
+ figures=figures,
121
+ )
122
+ )
123
+
124
+ LOGGER.debug(
125
+ "Processed sample %s | figures=%s | markdown_chars=%s",
126
+ ctx["sample_id"],
127
+ len(figures),
128
+ len(markdown),
129
+ )
130
+ except Exception as exc: # pragma: no cover - defensive logging
131
+ LOGGER.exception("Failed to finalize sample %s", ctx["sample_id"])
132
+ failures.append(
133
+ {
134
+ "sample_id": ctx["sample_id"],
135
+ "dataset_index": ctx["dataset_index"],
136
+ "error": str(exc),
137
+ "exception_type": exc.__class__.__name__,
138
+ }
139
+ )
140
+ finally:
141
+ if hasattr(image_obj, "close"):
142
+ image_obj.close()
143
+
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
+
151
+ sample_id = f"sample_{idx:05d}"
152
+ sample_dir = settings.output_dir / sample_id
153
+ sample_dir.mkdir(parents=True, exist_ok=True)
154
+
155
+ image = sample["images"][0]
156
+ if not isinstance(image, Image.Image):
157
+ image = Image.fromarray(image)
158
+ image = image.convert("RGB")
159
+
160
+ source_image_path = sample_dir / "source.png"
161
+ image.save(source_image_path)
162
+
163
+ batch_contexts.append(
164
+ {
165
+ "sample_id": sample_id,
166
+ "dataset_index": idx,
167
+ "sample_dir": sample_dir,
168
+ "image": image,
169
+ }
170
+ )
171
+ batch_requests.append(
172
+ {
173
+ "image": image,
174
+ "prompt": settings.prompt,
175
+ "max_tokens": settings.max_tokens,
176
+ "temperature": settings.temperature,
177
+ "request_timeout": settings.inference.request_timeout,
178
+ }
179
+ )
180
+
181
+ if len(batch_requests) >= chunk_size:
182
+ flush_batch()
183
+
184
+ flush_batch()
185
+
186
+ manifest = {
187
+ "generated_at": __now_iso(),
188
+ "stage": "extract",
189
+ "dataset": {
190
+ "name": settings.dataset_name,
191
+ "config": settings.dataset_config,
192
+ "split": settings.dataset_split,
193
+ },
194
+ "model": {
195
+ "served_model_name": settings.served_model_name,
196
+ "prompt": settings.prompt,
197
+ "max_tokens": settings.max_tokens,
198
+ "temperature": settings.temperature,
199
+ },
200
+ "inference": {
201
+ "max_batch_size": settings.inference.max_batch_size,
202
+ "max_concurrency": settings.inference.max_concurrency,
203
+ "request_timeout": settings.inference.request_timeout,
204
+ "max_retries": settings.inference.max_retries,
205
+ "retry_backoff_seconds": settings.inference.retry_backoff_seconds,
206
+ "max_retry_wait_seconds": settings.inference.max_retry_wait_seconds,
207
+ },
208
+ "documents": [dataclass_to_dict(document) for document in documents],
209
+ "failures": failures,
210
+ }
211
+
212
+ write_json(settings.output_dir / "manifest.json", manifest)
213
+ LOGGER.info(
214
+ "Extract stage complete | documents=%s | failures=%s",
215
+ len(documents),
216
+ len(failures),
217
+ )
218
+
219
+
220
+ def run_stage_describe(settings: DescribeSettings) -> None:
221
+ stage1_dir = resolve_stage_dir(settings.stage1_dir, settings.source_locator)
222
+
223
+ manifest_name = settings.source_locator.manifest_name or "manifest.json"
224
+ manifest_path = stage1_dir / manifest_name
225
+ if not manifest_path.exists():
226
+ raise FileNotFoundError(f"Stage 1 manifest not found at {manifest_path}")
227
+
228
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
229
+ documents = manifest.get("documents", [])
230
+
231
+ settings.output_dir.mkdir(parents=True, exist_ok=True)
232
+
233
+ sample_to_figures: Dict[str, List[Dict[str, Any]]] = {}
234
+ all_figures: List[Dict[str, Any]] = []
235
+ failures: List[Dict[str, Any]] = []
236
+
237
+ chunk_size = max(settings.inference.max_batch_size, 1)
238
+ total_figures = sum(len(doc.get("figures", [])) for doc in documents)
239
+
240
+ LOGGER.info(
241
+ "Describe stage | documents=%s | figures=%s | chunk=%s",
242
+ len(documents),
243
+ total_figures,
244
+ chunk_size,
245
+ )
246
+
247
+ batch_contexts: List[Dict[str, Any]] = []
248
+ batch_requests: List[Dict[str, Any]] = []
249
+
250
+ def flush_batch() -> None:
251
+ nonlocal batch_contexts, batch_requests
252
+ if not batch_contexts:
253
+ return
254
+
255
+ try:
256
+ responses = list(settings.client.infer_batch(batch_requests))
257
+ except Exception as exc: # pragma: no cover - defensive logging
258
+ LOGGER.exception("Describe batch inference failed for %s figures", len(batch_contexts))
259
+ for ctx in batch_contexts:
260
+ failures.append(
261
+ {
262
+ "sample_id": ctx["sample_id"],
263
+ "dataset_index": ctx["dataset_index"],
264
+ "figure_id": ctx["figure_id"],
265
+ "image_path": ctx["image_rel_path"],
266
+ "error": str(exc),
267
+ "exception_type": exc.__class__.__name__,
268
+ }
269
+ )
270
+ image_obj = ctx.get("image")
271
+ if hasattr(image_obj, "close"):
272
+ image_obj.close()
273
+ batch_contexts = []
274
+ batch_requests = []
275
+ return
276
+
277
+ if len(responses) != len(batch_contexts):
278
+ LOGGER.warning(
279
+ "Mismatch between responses (%s) and requests (%s) in describe batch",
280
+ len(responses),
281
+ len(batch_contexts),
282
+ )
283
+
284
+ for idx, ctx in enumerate(batch_contexts):
285
+ image_obj = ctx.get("image")
286
+ try:
287
+ description = responses[idx].strip() if idx < len(responses) else ""
288
+ if not description:
289
+ raise RuntimeError("Empty description generated for figure")
290
+
291
+ record = {
292
+ "figure_id": ctx["figure_id"],
293
+ "sample_id": ctx["sample_id"],
294
+ "dataset_index": ctx["dataset_index"],
295
+ "image_path": ctx["image_rel_path"],
296
+ "document_relative_path": ctx["document_relative_path"],
297
+ "description": description,
298
+ }
299
+ sample_to_figures.setdefault(ctx["sample_id"], []).append(record)
300
+ all_figures.append(record)
301
+
302
+ LOGGER.debug(
303
+ "Described figure %s | description_chars=%s",
304
+ ctx["figure_id"],
305
+ len(description),
306
+ )
307
+ except Exception as exc: # pragma: no cover - defensive logging
308
+ LOGGER.exception("Failed to finalize description for figure %s", ctx["figure_id"])
309
+ failures.append(
310
+ {
311
+ "sample_id": ctx["sample_id"],
312
+ "dataset_index": ctx["dataset_index"],
313
+ "figure_id": ctx["figure_id"],
314
+ "image_path": ctx["image_rel_path"],
315
+ "error": str(exc),
316
+ "exception_type": exc.__class__.__name__,
317
+ }
318
+ )
319
+ finally:
320
+ if hasattr(image_obj, "close"):
321
+ image_obj.close()
322
+
323
+ batch_contexts = []
324
+ batch_requests = []
325
+
326
+ for document in documents:
327
+ sample_id = document["sample_id"]
328
+ dataset_index = document.get("dataset_index")
329
+ for figure in document.get("figures", []):
330
+ image_rel_path = figure["image_path"]
331
+ image_path = stage1_dir / image_rel_path
332
+ if not image_path.exists():
333
+ LOGGER.warning("Figure image missing: %s", image_path)
334
+ failures.append(
335
+ {
336
+ "sample_id": sample_id,
337
+ "dataset_index": dataset_index,
338
+ "figure_id": figure["figure_id"],
339
+ "image_path": image_rel_path,
340
+ "reason": "missing_image",
341
+ }
342
+ )
343
+ continue
344
+
345
+ try:
346
+ figure_image = Image.open(image_path).convert("RGB")
347
+ except Exception as exc: # pragma: no cover - defensive logging
348
+ LOGGER.exception("Failed to load figure image %s", image_path)
349
+ failures.append(
350
+ {
351
+ "sample_id": sample_id,
352
+ "dataset_index": dataset_index,
353
+ "figure_id": figure["figure_id"],
354
+ "image_path": image_rel_path,
355
+ "error": str(exc),
356
+ "exception_type": exc.__class__.__name__,
357
+ }
358
+ )
359
+ continue
360
+
361
+ batch_contexts.append(
362
+ {
363
+ "sample_id": sample_id,
364
+ "dataset_index": dataset_index,
365
+ "figure_id": figure["figure_id"],
366
+ "image_rel_path": image_rel_path,
367
+ "document_relative_path": figure.get("document_relative_path"),
368
+ "image": figure_image,
369
+ }
370
+ )
371
+ batch_requests.append(
372
+ {
373
+ "image": figure_image,
374
+ "prompt": settings.prompt,
375
+ "max_tokens": settings.max_tokens,
376
+ "temperature": settings.temperature,
377
+ "request_timeout": settings.inference.request_timeout,
378
+ }
379
+ )
380
+
381
+ if len(batch_requests) >= chunk_size:
382
+ flush_batch()
383
+
384
+ flush_batch()
385
+
386
+ for sample_id, records in sample_to_figures.items():
387
+ records.sort(key=lambda entry: entry["figure_id"])
388
+ write_json(
389
+ settings.output_dir / f"{sample_id}.json",
390
+ {"sample_id": sample_id, "figures": records},
391
+ )
392
+
393
+ aggregate = {
394
+ "generated_at": __now_iso(),
395
+ "stage": "describe",
396
+ "prompt": settings.prompt,
397
+ "max_tokens": settings.max_tokens,
398
+ "temperature": settings.temperature,
399
+ "inference": {
400
+ "max_batch_size": settings.inference.max_batch_size,
401
+ "max_concurrency": settings.inference.max_concurrency,
402
+ "request_timeout": settings.inference.request_timeout,
403
+ "max_retries": settings.inference.max_retries,
404
+ "retry_backoff_seconds": settings.inference.retry_backoff_seconds,
405
+ "max_retry_wait_seconds": settings.inference.max_retry_wait_seconds,
406
+ },
407
+ "figures": all_figures,
408
+ "failures": failures,
409
+ }
410
+ write_json(settings.output_dir / "figure_descriptions.json", aggregate)
411
+ LOGGER.info(
412
+ "Describe stage complete | figures=%s | failures=%s",
413
+ len(all_figures),
414
+ len(failures),
415
+ )
416
+
417
+
418
+ def run_stage_assemble(settings: AssembleSettings) -> None:
419
+ stage1_dir = resolve_stage_dir(settings.stage1_dir, settings.stage1_locator)
420
+ stage2_dir = resolve_stage_dir(settings.stage2_dir, settings.stage2_locator)
421
+
422
+ manifest_name = settings.stage1_locator.manifest_name or "manifest.json"
423
+ manifest_path = stage1_dir / manifest_name
424
+ if not manifest_path.exists():
425
+ raise FileNotFoundError(f"Stage 1 manifest not found at {manifest_path}")
426
+
427
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
428
+ documents = manifest.get("documents", [])
429
+
430
+ description_map = _load_figure_descriptions(stage2_dir)
431
+ settings.output_dir.mkdir(parents=True, exist_ok=True)
432
+
433
+ final_documents: List[Dict[str, Any]] = []
434
+ dataset_records: List[Dict[str, Any]] = []
435
+ failures: List[Dict[str, Any]] = []
436
+
437
+ LOGGER.info(
438
+ "Starting assemble stage | documents=%s | figures_with_descriptions=%s",
439
+ len(documents),
440
+ len(description_map),
441
+ )
442
+
443
+ for document in documents:
444
+ sample_id = document["sample_id"]
445
+ sample_output_dir = settings.output_dir / sample_id
446
+ sample_output_dir.mkdir(parents=True, exist_ok=True)
447
+
448
+ doc_rel_path = Path(document["document_path"])
449
+ stage1_doc_path = stage1_dir / doc_rel_path
450
+ if not stage1_doc_path.exists():
451
+ LOGGER.warning("Document markdown missing: %s", stage1_doc_path)
452
+ failures.append(
453
+ {
454
+ "sample_id": sample_id,
455
+ "dataset_index": document.get("dataset_index"),
456
+ "missing_path": stage1_doc_path.as_posix(),
457
+ "reason": "document_missing",
458
+ }
459
+ )
460
+ continue
461
+
462
+ markdown = stage1_doc_path.read_text(encoding="utf-8")
463
+ enriched_markdown = enrich_markdown_with_captions(markdown, description_map)
464
+
465
+ final_doc_path = sample_output_dir / "document_final.md"
466
+ write_text(final_doc_path, enriched_markdown)
467
+
468
+ copied_figures: List[Dict[str, Any]] = []
469
+ for figure in document.get("figures", []):
470
+ figure_id = figure["figure_id"]
471
+ source_fig_path = stage1_dir / figure["image_path"]
472
+ if not source_fig_path.exists():
473
+ LOGGER.warning("Figure image missing: %s", source_fig_path)
474
+ failures.append(
475
+ {
476
+ "sample_id": sample_id,
477
+ "figure_id": figure_id,
478
+ "missing_path": source_fig_path.as_posix(),
479
+ "reason": "figure_missing",
480
+ }
481
+ )
482
+ continue
483
+
484
+ target_fig_dir = sample_output_dir / "figures"
485
+ target_fig_dir.mkdir(parents=True, exist_ok=True)
486
+ target_fig_path = target_fig_dir / Path(figure["document_relative_path"]).name
487
+ shutil.copy2(source_fig_path, target_fig_path)
488
+
489
+ description_entry = description_map.get(figure_id, {})
490
+ if not description_entry:
491
+ failures.append(
492
+ {
493
+ "sample_id": sample_id,
494
+ "figure_id": figure_id,
495
+ "reason": "description_missing",
496
+ }
497
+ )
498
+ copied_figures.append(
499
+ {
500
+ "figure_id": figure_id,
501
+ "image_path": (
502
+ Path(sample_id) / "figures" / target_fig_path.name
503
+ ).as_posix(),
504
+ "description": description_entry.get("description"),
505
+ }
506
+ )
507
+
508
+ final_doc_rel_path = (Path(sample_id) / "document_final.md").as_posix()
509
+ final_documents.append(
510
+ {
511
+ "sample_id": sample_id,
512
+ "dataset_index": document.get("dataset_index"),
513
+ "final_document_path": final_doc_rel_path,
514
+ "figures": copied_figures,
515
+ }
516
+ )
517
+
518
+ dataset_records.append(
519
+ {
520
+ "sample_id": sample_id,
521
+ "dataset_index": document.get("dataset_index"),
522
+ "document_markdown": final_doc_rel_path,
523
+ "figures": copied_figures,
524
+ }
525
+ )
526
+
527
+ aggregate = {
528
+ "generated_at": __now_iso(),
529
+ "stage": "assemble",
530
+ "documents": final_documents,
531
+ "source_manifest": manifest_path.relative_to(stage1_dir).as_posix(),
532
+ "failures": failures,
533
+ }
534
+ write_json(settings.output_dir / "manifest.json", aggregate)
535
+ write_jsonl(settings.output_dir / "dataset.jsonl", dataset_records)
536
+
537
+ maybe_upload_dataset(
538
+ output_dir=settings.output_dir,
539
+ repo_id=settings.dataset_repo_id,
540
+ repo_type=settings.dataset_repo_type,
541
+ path_in_repo=settings.dataset_path_in_repo,
542
+ commit_message=settings.dataset_commit_message,
543
+ revision=settings.dataset_branch,
544
+ )
545
+ LOGGER.info(
546
+ "Assemble stage complete | documents=%s | failures=%s",
547
+ len(final_documents),
548
+ len(failures),
549
+ )
550
+
551
+
552
+ def _load_figure_descriptions(stage2_dir: Path) -> Dict[str, Dict[str, Any]]:
553
+ aggregate_path = stage2_dir / "figure_descriptions.json"
554
+ descriptions: Dict[str, Dict[str, Any]] = {}
555
+ if aggregate_path.exists():
556
+ data = json.loads(aggregate_path.read_text(encoding="utf-8"))
557
+ for entry in data.get("figures", []):
558
+ descriptions[entry["figure_id"]] = entry
559
+ return descriptions
560
+
561
+ for json_file in stage2_dir.glob("*.json"):
562
+ data = json.loads(json_file.read_text(encoding="utf-8"))
563
+ for entry in data.get("figures", []):
564
+ descriptions[entry["figure_id"]] = entry
565
+ return descriptions
566
+
567
+
568
+ def dataclass_to_dict(document: DocumentMetadata) -> Dict[str, Any]:
569
+ result = {
570
+ "sample_id": document.sample_id,
571
+ "dataset_index": document.dataset_index,
572
+ "document_path": document.document_path,
573
+ "raw_response_path": document.raw_response_path,
574
+ "source_image_path": document.source_image_path,
575
+ "figures": [
576
+ {
577
+ "figure_id": figure.figure_id,
578
+ "label": figure.label,
579
+ "image_path": figure.image_path,
580
+ "document_relative_path": figure.document_relative_path,
581
+ "bounding_box_norm": figure.bounding_box_norm,
582
+ "bounding_box_norm_list": figure.bounding_box_norm_list,
583
+ "bounding_box_pixels": figure.bounding_box_pixels,
584
+ "description": figure.description,
585
+ }
586
+ for figure in document.figures
587
+ ],
588
+ }
589
+ return result
590
+
591
+
592
+ def __now_iso() -> str:
593
+ from datetime import datetime
594
+
595
+ return datetime.utcnow().isoformat() + "Z"
596
+
597
+ __all__ = [
598
+ "run_stage_extract",
599
+ "run_stage_describe",
600
+ "run_stage_assemble",
601
+ ]
602
+
hf_job_runner.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Minimal entrypoint for Hugging Face Jobs.
3
+
4
+ It downloads the job code repository (containing the `ds_batch_ocr` package)
5
+ using `huggingface_hub.snapshot_download` and then delegates to
6
+ `ds_batch_ocr.cli.main`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import subprocess
13
+ import sys
14
+ from pathlib import Path
15
+
16
+
17
+ def ensure_code_checkout() -> Path:
18
+ repo_id = os.environ.get("JOB_CODE_REPO")
19
+ if not repo_id:
20
+ raise RuntimeError("JOB_CODE_REPO environment variable must be set.")
21
+
22
+ repo_type = os.environ.get("JOB_CODE_REPO_TYPE", "dataset")
23
+ revision = os.environ.get("JOB_CODE_REVISION")
24
+ local_dir = Path(os.environ.get("JOB_CODE_LOCAL_DIR", "/tmp/deepseek-ocr-job-code"))
25
+ local_dir.mkdir(parents=True, exist_ok=True)
26
+
27
+ try:
28
+ from huggingface_hub import snapshot_download
29
+ except ModuleNotFoundError:
30
+ subprocess.run(
31
+ [sys.executable, "-m", "pip", "install", "huggingface_hub"],
32
+ check=True,
33
+ )
34
+ from huggingface_hub import snapshot_download
35
+
36
+ snapshot_download(
37
+ repo_id=repo_id,
38
+ repo_type=repo_type,
39
+ revision=revision,
40
+ local_dir=str(local_dir),
41
+ local_dir_use_symlinks=False,
42
+ )
43
+ return local_dir
44
+
45
+
46
+ def main() -> None:
47
+ code_dir = ensure_code_checkout()
48
+ sys.path.insert(0, str(code_dir))
49
+
50
+ from ds_batch_ocr.cli import main as pipeline_main
51
+
52
+ pipeline_main()
53
+
54
+
55
+ if __name__ == "__main__":
56
+ main()
57
+