Florent Gbelidji commited on
Commit
c581249
·
verified ·
1 Parent(s): d45f06e

Upload folder using huggingface_hub

Browse files
hf_job_runner.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "huggingface-hub[hf_transfer,hf_xet]",
5
+ # "torch",
6
+ # "datasets>=4.0.0",
7
+ # "pyarrow>=12.0.0",
8
+ # "numpy",
9
+ # "pillow",
10
+ # "requests",
11
+ # "openai",
12
+ # "rich",
13
+ # ]
14
+ # ///
15
+
16
+ """
17
+ Minimal entrypoint for Hugging Face Jobs.
18
+
19
+ It downloads the job code repository (containing the `llm_ocr` package)
20
+ using `huggingface_hub.snapshot_download` and then delegates to
21
+ `llm_ocr.cli.main`.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import os
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ from huggingface_hub import snapshot_download
31
+
32
+
33
+ def ensure_code_checkout() -> Path:
34
+ repo_id = os.environ.get("JOB_CODE_REPO")
35
+ if not repo_id:
36
+ raise RuntimeError("JOB_CODE_REPO environment variable must be set.")
37
+
38
+ repo_type = os.environ.get("JOB_CODE_REPO_TYPE", "dataset")
39
+ revision = os.environ.get("JOB_CODE_REVISION")
40
+ local_dir = Path(os.environ.get("JOB_CODE_LOCAL_DIR", "/tmp/deepseek-ocr-job-code"))
41
+ local_dir.mkdir(parents=True, exist_ok=True)
42
+
43
+ snapshot_download(
44
+ repo_id=repo_id,
45
+ repo_type=repo_type,
46
+ revision=revision,
47
+ local_dir=str(local_dir),
48
+ local_dir_use_symlinks=False,
49
+ )
50
+ return local_dir
51
+
52
+
53
+ def main() -> None:
54
+ code_dir = ensure_code_checkout()
55
+ sys.path.insert(0, str(code_dir))
56
+
57
+ from llm_ocr.cli import main as pipeline_main
58
+
59
+ pipeline_main()
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main()
64
+
llm_ocr/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """DeepSeek OCR pipeline package."""
2
+
3
+ from .cli import main
4
+
5
+ __all__ = ["main"]
6
+
7
+
llm_ocr/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (258 Bytes). View file
 
llm_ocr/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (258 Bytes). View file
 
llm_ocr/__pycache__/cli.cpython-312.pyc ADDED
Binary file (4.54 kB). View file
 
llm_ocr/__pycache__/cli.cpython-313.pyc ADDED
Binary file (16.9 kB). View file
 
llm_ocr/__pycache__/config.cpython-312.pyc ADDED
Binary file (8.27 kB). View file
 
llm_ocr/__pycache__/config.cpython-313.pyc ADDED
Binary file (10.2 kB). View file
 
llm_ocr/__pycache__/dependencies.cpython-312.pyc ADDED
Binary file (2.34 kB). View file
 
llm_ocr/__pycache__/dependencies.cpython-313.pyc ADDED
Binary file (2.36 kB). View file
 
llm_ocr/__pycache__/document.cpython-312.pyc ADDED
Binary file (15.7 kB). View file
 
llm_ocr/__pycache__/document.cpython-313.pyc ADDED
Binary file (9.18 kB). View file
 
llm_ocr/__pycache__/gcr_io.cpython-312.pyc ADDED
Binary file (7.48 kB). View file
 
llm_ocr/__pycache__/hf_io.cpython-312.pyc ADDED
Binary file (9.22 kB). View file
 
llm_ocr/__pycache__/hf_io.cpython-313.pyc ADDED
Binary file (7.23 kB). View file
 
llm_ocr/__pycache__/logging_utils.cpython-312.pyc ADDED
Binary file (713 Bytes). View file
 
llm_ocr/__pycache__/logging_utils.cpython-313.pyc ADDED
Binary file (711 Bytes). View file
 
llm_ocr/__pycache__/server.cpython-312.pyc ADDED
Binary file (11.9 kB). View file
 
llm_ocr/__pycache__/server.cpython-313.pyc ADDED
Binary file (12 kB). View file
 
llm_ocr/__pycache__/stages.cpython-312.pyc ADDED
Binary file (17.1 kB). View file
 
llm_ocr/__pycache__/stages.cpython-313.pyc ADDED
Binary file (25.7 kB). View file
 
llm_ocr/__pycache__/storage.cpython-312.pyc ADDED
Binary file (11.4 kB). View file
 
llm_ocr/cli.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI entrypoint for the DeepSeek OCR pipeline."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import os
6
+
7
+ from .config import AssembleSettings, DescribeSettings, ExtractSettings, env
8
+ from .server import DeepSeekClient, base_url_from_env, launch_vllm, should_launch_server, shutdown_server, wait_for_server
9
+ from .stages import run_stage_assemble, run_stage_describe, run_stage_extract
10
+
11
+ LOGGER = logging.getLogger(__name__)
12
+
13
+
14
+ def _setup_logging() -> None:
15
+ """Configure logging with optional rich handler."""
16
+ level = env("LOG_LEVEL", "INFO").upper()
17
+ try:
18
+ from rich.console import Console
19
+ from rich.logging import RichHandler
20
+ console = Console(force_terminal=env("FORCE_COLOR", "").lower() in {"1", "true"})
21
+ handler = RichHandler(console=console, show_time=True, show_level=True, rich_tracebacks=True)
22
+ logging.basicConfig(level=level, format="%(message)s", handlers=[handler], force=True)
23
+ except ImportError:
24
+ logging.basicConfig(level=level, format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", force=True)
25
+
26
+
27
+ def _create_client(max_tokens: int, temperature: float, inference_settings) -> DeepSeekClient:
28
+ """Create DeepSeek client from environment."""
29
+ return DeepSeekClient(
30
+ base_url=base_url_from_env(),
31
+ model_name=env("SERVED_MODEL_NAME", "deepseek-ocr"),
32
+ max_tokens=max_tokens,
33
+ temperature=temperature,
34
+ request_timeout=inference_settings.request_timeout,
35
+ max_retries=inference_settings.max_retries,
36
+ retry_backoff_seconds=inference_settings.retry_backoff,
37
+ )
38
+
39
+
40
+ def main() -> None:
41
+ """Main entry point for the pipeline CLI."""
42
+ _setup_logging()
43
+
44
+ stage = env("PIPELINE_STAGE", "extract").lower()
45
+ if stage not in {"extract", "describe", "assemble"}:
46
+ raise ValueError(f"Unsupported stage: {stage}")
47
+
48
+ needs_server = stage in {"extract", "describe"}
49
+ launch_server = should_launch_server() and needs_server
50
+ server_process = None
51
+
52
+ try:
53
+ if launch_server:
54
+ server_process = launch_vllm()
55
+
56
+ if needs_server:
57
+ base_url = base_url_from_env()
58
+ health_url = env("HEALTH_URL", f"{base_url}/health")
59
+ LOGGER.info("Waiting for server at %s", health_url)
60
+ if not wait_for_server(health_url):
61
+ raise RuntimeError("vLLM server did not become ready in time")
62
+
63
+ if stage == "extract":
64
+ from .config import InferenceSettings
65
+ inference = InferenceSettings.from_env("EXTRACT")
66
+ max_tokens = env("DOC_MAX_TOKENS", 2048, int)
67
+ temperature = env("DOC_TEMPERATURE", 0.0, float)
68
+ client = _create_client(max_tokens, temperature, inference)
69
+ settings = ExtractSettings.from_env(client)
70
+ settings.inference = inference
71
+ run_stage_extract(settings)
72
+
73
+ elif stage == "describe":
74
+ from .config import InferenceSettings
75
+ inference = InferenceSettings.from_env("DESCRIBE")
76
+ max_tokens = env("FIGURE_MAX_TOKENS", 512, int)
77
+ temperature = env("FIGURE_TEMPERATURE", 0.0, float)
78
+ client = _create_client(max_tokens, temperature, inference)
79
+ settings = DescribeSettings.from_env(client)
80
+ settings.inference = inference
81
+ run_stage_describe(settings)
82
+
83
+ elif stage == "assemble":
84
+ settings = AssembleSettings.from_env()
85
+ run_stage_assemble(settings)
86
+
87
+ finally:
88
+ if server_process is not None:
89
+ shutdown_server(server_process)
90
+
91
+
92
+ __all__ = ["main"]
llm_ocr/config.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration dataclasses for pipeline stages."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import os
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any, Dict, Optional, Type, TypeVar
9
+
10
+ LOGGER = logging.getLogger(__name__)
11
+
12
+ T = TypeVar("T")
13
+
14
+
15
+ def env(key: str, default: T = None, cast: Type[T] = str) -> T:
16
+ """Read environment variable with type casting."""
17
+ raw = os.environ.get(key)
18
+ if raw is None:
19
+ return default
20
+ try:
21
+ return cast(raw)
22
+ except (TypeError, ValueError):
23
+ LOGGER.warning("Invalid %s=%s, using default=%s", key, raw, default)
24
+ return default
25
+
26
+
27
+ @dataclass
28
+ class FigureMetadata:
29
+ """Metadata for an extracted figure (image stored in dataset, not as file)."""
30
+ figure_id: str
31
+ label: str
32
+ bounding_box_pixels: Dict[str, int]
33
+ description: Optional[str] = None
34
+
35
+
36
+ @dataclass
37
+ class InferenceSettings:
38
+ """Settings for batch inference."""
39
+ batch_size: int = 4
40
+ max_concurrency: int = 4
41
+ request_timeout: int = 120
42
+ max_retries: int = 3
43
+ retry_backoff: float = 2.0
44
+
45
+ @classmethod
46
+ def from_env(cls, prefix: str = "") -> InferenceSettings:
47
+ """Load from environment with optional prefix (e.g., 'EXTRACT_')."""
48
+ p = f"{prefix}_" if prefix else ""
49
+ return cls(
50
+ batch_size=max(1, env(f"{p}BATCH_SIZE", 4, int)),
51
+ max_concurrency=max(1, env(f"{p}MAX_CONCURRENCY", 4, int)),
52
+ request_timeout=max(1, env(f"{p}REQUEST_TIMEOUT", 120, int)),
53
+ max_retries=max(0, env(f"{p}MAX_RETRIES", 3, int)),
54
+ retry_backoff=max(0.1, env(f"{p}RETRY_BACKOFF", 2.0, float)),
55
+ )
56
+
57
+
58
+ @dataclass
59
+ class HubSettings:
60
+ """Settings for HuggingFace Hub upload."""
61
+ repo_id: Optional[str] = None
62
+ path_in_repo: str = ""
63
+ branch: Optional[str] = None
64
+ commit_message: Optional[str] = None
65
+
66
+ @classmethod
67
+ def from_env(cls, prefix: str = "HF") -> HubSettings:
68
+ """Load from environment with prefix (e.g., 'HF_' -> HF_REPO_ID)."""
69
+ p = f"{prefix}_" if prefix else ""
70
+ return cls(
71
+ repo_id=env(f"{p}REPO_ID") or env(f"{p}REPO"),
72
+ path_in_repo=env(f"{p}PATH_IN_REPO", ""),
73
+ branch=env(f"{p}BRANCH"),
74
+ commit_message=env(f"{p}COMMIT_MESSAGE"),
75
+ )
76
+
77
+
78
+ @dataclass
79
+ class ExtractSettings:
80
+ """Settings for the extract stage."""
81
+ dataset_name: str
82
+ dataset_config: str
83
+ dataset_split: str
84
+ output_dir: Path
85
+ client: Any # DeepSeekClient
86
+ prompt: str = "<image>\n<|grounding|>Convert this document to Markdown."
87
+ max_tokens: int = 2048
88
+ temperature: float = 0.0
89
+ max_samples: Optional[int] = None
90
+ stream_dataset: bool = True
91
+ inference: InferenceSettings = field(default_factory=InferenceSettings)
92
+ hub: HubSettings = field(default_factory=HubSettings)
93
+
94
+ @classmethod
95
+ def from_env(cls, client: Any) -> ExtractSettings:
96
+ """Load settings from environment variables."""
97
+ return cls(
98
+ dataset_name=env("DATASET_NAME", "HuggingFaceM4/FineVision"),
99
+ dataset_config=env("DATASET_CONFIG", "olmOCR-mix-0225-documents"),
100
+ dataset_split=env("DATASET_SPLIT", "train"),
101
+ output_dir=Path(env("OUTPUT_DIR", "./outputs/extract")),
102
+ client=client,
103
+ prompt=env("DOC_PROMPT", "<image>\n<|grounding|>Convert this document to Markdown."),
104
+ max_tokens=env("DOC_MAX_TOKENS", 2048, int),
105
+ temperature=env("DOC_TEMPERATURE", 0.0, float),
106
+ max_samples=env("MAX_SAMPLES", None, int),
107
+ stream_dataset=env("STREAM_DATASET", "true").lower() == "true",
108
+ inference=InferenceSettings.from_env("EXTRACT"),
109
+ hub=HubSettings.from_env("HF"),
110
+ )
111
+
112
+
113
+ @dataclass
114
+ class DescribeSettings:
115
+ """Settings for the describe stage."""
116
+ output_dir: Path
117
+ client: Any # DeepSeekClient
118
+ source_repo_id: Optional[str] = None
119
+ prompt: str = "<image>\nDescribe this image in detail"
120
+ max_tokens: int = 512
121
+ temperature: float = 0.0
122
+ inference: InferenceSettings = field(default_factory=InferenceSettings)
123
+ hub: HubSettings = field(default_factory=HubSettings)
124
+
125
+ @classmethod
126
+ def from_env(cls, client: Any) -> DescribeSettings:
127
+ """Load settings from environment variables."""
128
+ return cls(
129
+ output_dir=Path(env("OUTPUT_DIR", "./outputs/describe")),
130
+ client=client,
131
+ source_repo_id=env("SOURCE_REPO_ID") or env("HF_REPO_ID"),
132
+ prompt=env("FIGURE_PROMPT", "<image>\nDescribe this image in detail"),
133
+ max_tokens=env("FIGURE_MAX_TOKENS", 512, int),
134
+ temperature=env("FIGURE_TEMPERATURE", 0.0, float),
135
+ inference=InferenceSettings.from_env("DESCRIBE"),
136
+ hub=HubSettings.from_env("HF"),
137
+ )
138
+
139
+
140
+ @dataclass
141
+ class AssembleSettings:
142
+ """Settings for the assemble stage."""
143
+ source_repo_id: Optional[str] = None
144
+ hub: HubSettings = field(default_factory=HubSettings)
145
+
146
+ @classmethod
147
+ def from_env(cls) -> AssembleSettings:
148
+ """Load settings from environment variables."""
149
+ return cls(
150
+ source_repo_id=env("SOURCE_REPO_ID") or env("HF_REPO_ID"),
151
+ hub=HubSettings.from_env("HF"),
152
+ )
153
+
154
+
155
+ __all__ = [
156
+ "env",
157
+ "FigureMetadata",
158
+ "InferenceSettings",
159
+ "HubSettings",
160
+ "ExtractSettings",
161
+ "DescribeSettings",
162
+ "AssembleSettings",
163
+ ]
llm_ocr/document.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Document processing: markdown extraction, figure handling, and caption enrichment."""
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ import base64
6
+ import json
7
+ import logging
8
+ import re
9
+ from io import BytesIO
10
+ from pathlib import Path
11
+ from typing import Any, Dict, List, Tuple
12
+
13
+ import numpy as np
14
+ from PIL import Image, ImageDraw, ImageFont
15
+
16
+ from .config import FigureMetadata
17
+
18
+ LOGGER = logging.getLogger(__name__)
19
+
20
+ GROUNDING_PATTERN = re.compile(
21
+ r"<\|ref\|>(.*?)<\|/ref\|><\|det\|>(.*?)<\|/det\|>",
22
+ re.DOTALL,
23
+ )
24
+
25
+ # Matches both old path format and new figure: URI format
26
+ FIGURE_MARKDOWN_PATTERN = re.compile(
27
+ r"!\[(?:Figure )?(?P<figure_id>[^\]]+)\]\((?P<path>[^)]+)\)"
28
+ )
29
+
30
+
31
+ def encode_image(image: Image.Image) -> str:
32
+ """Encode a PIL Image to base64 PNG string."""
33
+ buffer = BytesIO()
34
+ image.save(buffer, format="PNG")
35
+ return base64.b64encode(buffer.getvalue()).decode("utf-8")
36
+
37
+
38
+ def extract_grounding_blocks(text: str) -> List[Dict[str, Any]]:
39
+ """Extract grounding blocks (ref/det tags) from model response."""
40
+ matches: List[Dict[str, Any]] = []
41
+ for match in GROUNDING_PATTERN.finditer(text):
42
+ label = match.group(1).strip()
43
+ coords_text = match.group(2).strip()
44
+ coordinates = None
45
+ if coords_text:
46
+ try:
47
+ coordinates = ast.literal_eval(coords_text)
48
+ except Exception:
49
+ coordinates = None
50
+ matches.append({
51
+ "label": label,
52
+ "coordinates": coordinates,
53
+ "raw": match.group(0),
54
+ "span": match.span(),
55
+ })
56
+ return matches
57
+
58
+
59
+ def postprocess_markdown(text: str) -> str:
60
+ """Clean up markdown text from model output."""
61
+ cleaned = (
62
+ text.replace("\\coloneqq", ":=")
63
+ .replace("\\eqqcolon", "=:")
64
+ .replace("<|image_pad|>", "")
65
+ )
66
+ cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
67
+ return cleaned.strip()
68
+
69
+
70
+ def apply_replacements(text: str, replacements: List[Tuple[int, int, str]]) -> str:
71
+ """Apply text replacements at specified spans."""
72
+ if not replacements:
73
+ return postprocess_markdown(text)
74
+ sorted_replacements = sorted(replacements, key=lambda item: item[0])
75
+ segments: List[str] = []
76
+ cursor = 0
77
+ for start, end, replacement in sorted_replacements:
78
+ segments.append(text[cursor:start])
79
+ segments.append(replacement)
80
+ cursor = end
81
+ segments.append(text[cursor:])
82
+ return postprocess_markdown("".join(segments))
83
+
84
+
85
+ def crop_figure(
86
+ image: Image.Image,
87
+ sample_id: str,
88
+ figure_index: int,
89
+ pixel_box: List[int],
90
+ label: str,
91
+ ) -> Tuple[FigureMetadata, Image.Image]:
92
+ """Crop a figure from the source image.
93
+
94
+ Returns:
95
+ Tuple of (metadata, cropped_image) - image is for embedding in dataset
96
+ """
97
+ x1, y1, x2, y2 = pixel_box
98
+ crop = image.crop((x1, y1, x2, y2)).copy()
99
+
100
+ figure_id = f"{sample_id}_fig{figure_index:02d}"
101
+
102
+ metadata = FigureMetadata(
103
+ figure_id=figure_id,
104
+ label=label,
105
+ bounding_box_pixels={"x1": x1, "y1": y1, "x2": x2, "y2": y2},
106
+ )
107
+
108
+ return metadata, crop
109
+
110
+
111
+ def write_text(path: Path, content: str) -> None:
112
+ """Write text content to a file."""
113
+ path.parent.mkdir(parents=True, exist_ok=True)
114
+ path.write_text(content, encoding="utf-8")
115
+
116
+
117
+ def write_json(path: Path, payload: Any) -> None:
118
+ """Write JSON content to a file."""
119
+ path.parent.mkdir(parents=True, exist_ok=True)
120
+ with path.open("w", encoding="utf-8") as handle:
121
+ json.dump(payload, handle, indent=2, ensure_ascii=False)
122
+
123
+
124
+ def build_document_markdown(
125
+ image: Image.Image,
126
+ response_text: str,
127
+ sample_id: str,
128
+ ) -> Tuple[str, List[FigureMetadata], List[Image.Image], Image.Image]:
129
+ """
130
+ Process model response to extract markdown and figures.
131
+
132
+ Returns:
133
+ - Cleaned markdown with figure references (using figure:{id} URIs)
134
+ - List of figure metadata
135
+ - List of cropped figure images (for embedding in dataset)
136
+ - Annotated image with bounding boxes
137
+ """
138
+ blocks = extract_grounding_blocks(response_text)
139
+ replacements: List[Tuple[int, int, str]] = []
140
+ figures: List[FigureMetadata] = []
141
+ figure_images: List[Image.Image] = []
142
+ figure_index = 1
143
+
144
+ img_draw = image.copy()
145
+ draw = ImageDraw.Draw(img_draw)
146
+ overlay = Image.new("RGBA", img_draw.size, (0, 0, 0, 0))
147
+ draw_overlay = ImageDraw.Draw(overlay)
148
+ font = ImageFont.load_default()
149
+
150
+ width, height = image.size
151
+
152
+ for block in blocks:
153
+ label = block["label"].lower()
154
+ start, end = block["span"]
155
+
156
+ # Random color for this block
157
+ color = (np.random.randint(0, 200), np.random.randint(0, 200), np.random.randint(0, 255))
158
+ color_alpha = color + (20,)
159
+
160
+ # Convert normalized coords to pixels
161
+ raw_box = block["coordinates"][0]
162
+ x1 = int(raw_box[0] / 999 * width)
163
+ y1 = int(raw_box[1] / 999 * height)
164
+ x2 = int(raw_box[2] / 999 * width)
165
+ y2 = int(raw_box[3] / 999 * height)
166
+ pixel_box = (x1, y1, x2, y2)
167
+
168
+ # Extract figures (images)
169
+ if label == "image":
170
+ metadata, crop = crop_figure(
171
+ image=image,
172
+ sample_id=sample_id,
173
+ figure_index=figure_index,
174
+ pixel_box=pixel_box,
175
+ label=block["label"],
176
+ )
177
+ figures.append(metadata)
178
+ figure_images.append(crop)
179
+ # Use figure:{id} URI format - clearly an identifier, not a file path
180
+ replacements.append((
181
+ start, end,
182
+ f"![{metadata.figure_id}](figure:{metadata.figure_id})",
183
+ ))
184
+ figure_index += 1
185
+ else:
186
+ replacements.append((start, end, ""))
187
+
188
+ # Draw bounding box
189
+ box_width = 4 if label == "title" else 2
190
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=box_width)
191
+ draw_overlay.rectangle([x1, y1, x2, y2], fill=color_alpha)
192
+
193
+ # Draw label
194
+ text_x, text_y = x1, max(0, y1 - 15)
195
+ text_bbox = draw.textbbox((0, 0), label, font=font)
196
+ text_w, text_h = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
197
+ draw.rectangle([text_x, text_y, text_x + text_w, text_y + text_h], fill=(255, 255, 255, 30))
198
+ draw.text((text_x, text_y), label, font=font, fill=color)
199
+
200
+ img_draw.paste(overlay, (0, 0), overlay)
201
+ markdown = apply_replacements(response_text, replacements)
202
+ return markdown, figures, figure_images, img_draw
203
+
204
+
205
+ def _truncate_for_alt(description: str, max_length: int = 120) -> str:
206
+ """Create a short alt text from a description (first sentence, truncated)."""
207
+ # Take first sentence
208
+ first_sentence = description.split(". ")[0].split(".\n")[0]
209
+ if len(first_sentence) <= max_length:
210
+ return first_sentence.strip()
211
+ # Truncate at word boundary
212
+ truncated = first_sentence[:max_length].rsplit(" ", 1)[0]
213
+ return truncated.strip() + "..."
214
+
215
+
216
+ def enrich_markdown_with_captions(
217
+ markdown: str,
218
+ description_map: Dict[str, Dict[str, Any]],
219
+ ) -> str:
220
+ """Add figure captions to markdown based on descriptions.
221
+
222
+ Handles both new format ![figure_id](figure:figure_id) and
223
+ legacy format ![Figure figure_id](path).
224
+
225
+ The alt text is kept short (first sentence/~120 chars) for accessibility.
226
+ The full description appears as an italicized caption below the image.
227
+ """
228
+ used: set[str] = set()
229
+
230
+ def replace(match: re.Match[str]) -> str:
231
+ alt_text = match.group("figure_id").strip()
232
+ path = match.group("path").strip()
233
+
234
+ # Extract figure_id from figure:{id} URI or from alt text
235
+ if path.startswith("figure:"):
236
+ figure_id = path[7:] # Remove "figure:" prefix
237
+ else:
238
+ # Legacy format - figure_id is in alt text after "Figure "
239
+ figure_id = alt_text.replace("Figure ", "").split(":")[0].strip()
240
+
241
+ entry = description_map.get(figure_id)
242
+ if not entry:
243
+ return match.group(0)
244
+
245
+ description = (entry.get("description") or "").strip()
246
+ if not description:
247
+ return match.group(0)
248
+
249
+ # Alt text: short summary (first sentence, max 120 chars)
250
+ short_alt = _truncate_for_alt(description)
251
+
252
+ # Image tag with short alt text
253
+ rendered = f"![{figure_id}: {short_alt}]({path})"
254
+
255
+ # Add full caption below (only once per figure)
256
+ if figure_id not in used:
257
+ rendered += f"\n\n*Figure {figure_id}: {description}*\n"
258
+ used.add(figure_id)
259
+ return rendered
260
+
261
+ return FIGURE_MARKDOWN_PATTERN.sub(replace, markdown)
262
+
263
+
264
+ def render_markdown_with_images(
265
+ markdown: str,
266
+ figure_images: List[Image.Image],
267
+ figure_metadata: List[Dict[str, Any]],
268
+ ) -> str:
269
+ """
270
+ Render markdown with embedded images as base64 data URIs.
271
+
272
+ The dataset stores images in `extracted_figures` (PIL images) and metadata
273
+ in `extracted_figures_metadata` (with figure_id). This function replaces
274
+ figure:{id} URIs in markdown with base64-encoded images.
275
+
276
+ Args:
277
+ markdown: Markdown text with ![figure_id](figure:figure_id) references
278
+ figure_images: List of PIL images from dataset's extracted_figures column
279
+ figure_metadata: List of metadata dicts (parsed from extracted_figures_metadata)
280
+
281
+ Returns:
282
+ Self-contained markdown with images embedded as data URIs
283
+ """
284
+ # Build figure_id -> image mapping
285
+ id_to_image: Dict[str, Image.Image] = {}
286
+ for i, meta in enumerate(figure_metadata):
287
+ fig_id = meta.get("figure_id", "")
288
+ if fig_id and i < len(figure_images) and figure_images[i] is not None:
289
+ id_to_image[fig_id] = figure_images[i]
290
+
291
+ def replace(match: re.Match[str]) -> str:
292
+ alt_text = match.group("figure_id").strip()
293
+ path = match.group("path").strip()
294
+
295
+ # Extract figure_id from figure:{id} URI or use alt_text as fallback
296
+ if path.startswith("figure:"):
297
+ figure_id = path[7:] # Remove "figure:" prefix
298
+ else:
299
+ # Legacy path format - extract figure_id from alt_text
300
+ figure_id = alt_text.replace("Figure ", "").split(":")[0].strip()
301
+
302
+ img = id_to_image.get(figure_id)
303
+ if img is None:
304
+ return match.group(0) # Keep original if image not found
305
+
306
+ # Embed as base64 data URI
307
+ data_uri = f"data:image/png;base64,{encode_image(img)}"
308
+ return f"![{alt_text}]({data_uri})"
309
+
310
+ return FIGURE_MARKDOWN_PATTERN.sub(replace, markdown)
311
+
312
+
313
+ def render_sample_markdown(sample: Dict[str, Any]) -> str:
314
+ """
315
+ Render a dataset sample's markdown with embedded images.
316
+
317
+ Args:
318
+ sample: A row from the dataset (dict with column values)
319
+
320
+ Returns:
321
+ Self-contained markdown string with images as data URIs
322
+ """
323
+ markdown = sample.get("document_final_markdown") or sample.get("document_markdown") or ""
324
+
325
+ # Parse metadata
326
+ raw_metadata = sample.get("extracted_figures_metadata") or []
327
+ metadata = []
328
+ for m in raw_metadata:
329
+ if isinstance(m, str):
330
+ metadata.append(json.loads(m))
331
+ else:
332
+ metadata.append(m)
333
+
334
+ images = sample.get("extracted_figures") or []
335
+
336
+ return render_markdown_with_images(
337
+ markdown=markdown,
338
+ figure_images=images,
339
+ figure_metadata=metadata,
340
+ )
341
+
342
+
343
+ def display_markdown(sample: Dict[str, Any]) -> None:
344
+ """
345
+ Display a dataset sample's markdown with images rendered in Jupyter.
346
+
347
+ This function takes a dataset row, renders the figure: URIs as actual
348
+ images (from the extracted_figures column), and displays the result
349
+ as formatted markdown in the notebook.
350
+
351
+ Args:
352
+ sample: A row from the dataset (dict with column values)
353
+ """
354
+ from IPython.display import display, Markdown
355
+
356
+ rendered = render_sample_markdown(sample)
357
+ display(Markdown(rendered))
358
+
359
+
360
+ __all__ = [
361
+ "encode_image",
362
+ "build_document_markdown",
363
+ "enrich_markdown_with_captions",
364
+ "render_markdown_with_images",
365
+ "render_sample_markdown",
366
+ "display_markdown",
367
+ "write_text",
368
+ "write_json",
369
+ ]
llm_ocr/gcr_io.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Google Cloud Storage utilities for Cloud Run jobs."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import shutil
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING
8
+
9
+ if TYPE_CHECKING:
10
+ from datasets import Dataset
11
+
12
+ LOGGER = logging.getLogger(__name__)
13
+
14
+
15
+ def get_gcs_client():
16
+ """Get GCS client."""
17
+ from google.cloud import storage
18
+ return storage.Client()
19
+
20
+
21
+ def parse_gcs_uri(uri: str) -> tuple[str, str]:
22
+ """Parse gs://bucket/key into (bucket, key)."""
23
+ if not uri.startswith("gs://"):
24
+ raise ValueError(f"Invalid GCS URI: {uri}")
25
+ parts = uri[5:].split("/", 1)
26
+ bucket = parts[0]
27
+ key = parts[1] if len(parts) > 1 else ""
28
+ return bucket, key
29
+
30
+
31
+ def upload_files_to_gcs(
32
+ *,
33
+ output_dir: Path,
34
+ gcs_uri: str,
35
+ path_prefix: str = "",
36
+ ) -> None:
37
+ """Upload local files to GCS.
38
+
39
+ Args:
40
+ output_dir: Local directory containing files to upload
41
+ gcs_uri: GCS URI (gs://bucket/prefix)
42
+ path_prefix: Additional prefix to add to GCS keys
43
+ """
44
+ if not gcs_uri:
45
+ LOGGER.info("No GCS URI provided; skipping upload.")
46
+ return
47
+
48
+ bucket_name, base_prefix = parse_gcs_uri(gcs_uri)
49
+
50
+ full_prefix = base_prefix.rstrip("/")
51
+ if path_prefix:
52
+ full_prefix = f"{full_prefix}/{path_prefix.strip('/')}" if full_prefix else path_prefix.strip("/")
53
+
54
+ client = get_gcs_client()
55
+ bucket = client.bucket(bucket_name)
56
+ base = output_dir.resolve()
57
+
58
+ files = sorted(p for p in base.rglob("*") if p.is_file())
59
+ if not files:
60
+ LOGGER.info("Nothing to upload from %s", output_dir)
61
+ return
62
+
63
+ LOGGER.info("Uploading %d files to gs://%s/%s", len(files), bucket_name, full_prefix)
64
+
65
+ for local_path in files:
66
+ rel = local_path.relative_to(base).as_posix()
67
+ gcs_key = f"{full_prefix}/{rel}" if full_prefix else rel
68
+ try:
69
+ blob = bucket.blob(gcs_key)
70
+ blob.upload_from_filename(str(local_path))
71
+ except Exception as exc:
72
+ LOGGER.error("Failed to upload %s to gs://%s/%s: %s", local_path, bucket_name, gcs_key, exc)
73
+ raise
74
+
75
+
76
+ def save_dataset_to_gcs(
77
+ dataset,
78
+ gcs_uri: str,
79
+ name: str = "dataset",
80
+ ) -> str:
81
+ """Save HF dataset to GCS using Arrow format (preserves Image columns).
82
+
83
+ Args:
84
+ dataset: HuggingFace Dataset or DatasetDict to save
85
+ gcs_uri: Base GCS URI (gs://bucket/prefix)
86
+ name: Name for the dataset folder
87
+
88
+ Returns:
89
+ GCS URI of the saved dataset
90
+ """
91
+ from datasets import DatasetDict
92
+
93
+ # Handle DatasetDict by extracting the first split
94
+ if isinstance(dataset, DatasetDict):
95
+ if "train" in dataset:
96
+ dataset = dataset["train"]
97
+ else:
98
+ split_name = list(dataset.keys())[0]
99
+ dataset = dataset[split_name]
100
+ LOGGER.info("Using split '%s' from DatasetDict", split_name)
101
+
102
+ bucket_name, prefix = parse_gcs_uri(gcs_uri)
103
+ full_prefix = prefix.rstrip("/")
104
+
105
+ # Save to local temp directory using Arrow format
106
+ local_dir = Path(f"/tmp/{name}_arrow_temp")
107
+ if local_dir.exists():
108
+ shutil.rmtree(local_dir)
109
+
110
+ LOGGER.info("Saving dataset to Arrow format...")
111
+ dataset.save_to_disk(str(local_dir))
112
+
113
+ # Upload entire directory to GCS
114
+ gcs_prefix = f"{full_prefix}/{name}" if full_prefix else name
115
+ upload_files_to_gcs(output_dir=local_dir, gcs_uri=f"gs://{bucket_name}/{gcs_prefix}")
116
+
117
+ # Cleanup
118
+ shutil.rmtree(local_dir)
119
+
120
+ result_uri = f"gs://{bucket_name}/{gcs_prefix}"
121
+ LOGGER.info("Saved dataset to %s", result_uri)
122
+ return result_uri
123
+
124
+
125
+ def get_dataset_features():
126
+ """Get the dataset feature schema."""
127
+ from datasets import Features, Sequence, Value, Image as HfImage
128
+
129
+ return Features({
130
+ "sample_id": Value("string"),
131
+ "dataset_index": Value("int64"),
132
+ "source_image": HfImage(),
133
+ "document_with_boxes_image": HfImage(),
134
+ "document_markdown": Value("string"),
135
+ "extracted_figures": Sequence(HfImage()),
136
+ "extracted_figures_metadata": Sequence(Value("string")),
137
+ "document_final_markdown": Value("string"),
138
+ })
139
+
140
+
141
+ def load_dataset_from_gcs(gcs_uri: str, split: str = "train") -> "Dataset":
142
+ """Load HF dataset directly from GCS (saved with save_to_disk).
143
+
144
+ Downloads files locally first to avoid gcsfs caching issues.
145
+
146
+ Args:
147
+ gcs_uri: GCS URI to dataset directory (gs://bucket/path/to/dataset/)
148
+ split: Unused, kept for API compatibility
149
+
150
+ Returns:
151
+ Loaded Dataset
152
+
153
+ Requires:
154
+ pip install datasets google-cloud-storage
155
+ """
156
+ from datasets import load_from_disk
157
+ import tempfile
158
+
159
+ LOGGER.info("Loading dataset from %s", gcs_uri)
160
+
161
+ # Parse GCS URI
162
+ bucket_name, prefix = parse_gcs_uri(gcs_uri)
163
+
164
+ # Download to local temp directory (bypasses gcsfs cache)
165
+ client = get_gcs_client()
166
+ bucket = client.bucket(bucket_name)
167
+ local_dir = tempfile.mkdtemp(prefix="gcs_dataset_")
168
+
169
+ blobs = list(bucket.list_blobs(prefix=f"{prefix}/"))
170
+ for blob in blobs:
171
+ filename = blob.name.split('/')[-1]
172
+ if filename: # Skip directory markers
173
+ local_path = f"{local_dir}/{filename}"
174
+ blob.download_to_filename(local_path)
175
+
176
+ LOGGER.info("Downloaded %d files to %s", len(blobs), local_dir)
177
+
178
+ # Load from local
179
+ ds = load_from_disk(local_dir)
180
+
181
+ return ds
182
+
183
+
184
+ __all__ = [
185
+ "save_dataset_to_gcs",
186
+ "load_dataset_from_gcs",
187
+ "parse_gcs_uri",
188
+ "get_gcs_client",
189
+ ]
190
+
191
+
llm_ocr/server.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """vLLM server management and async inference client."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import logging
6
+ import os
7
+ import signal
8
+ import subprocess
9
+ import threading
10
+ import time
11
+ from typing import Any, Awaitable, Dict, List, Sequence
12
+
13
+ import requests
14
+ from openai import AsyncOpenAI
15
+
16
+ from .document import encode_image
17
+
18
+ LOGGER = logging.getLogger(__name__)
19
+
20
+
21
+ def _stream_output(pipe, prefix: str) -> None:
22
+ """Stream subprocess output to stdout with prefix."""
23
+ try:
24
+ for line in iter(pipe.readline, ""):
25
+ print(f"[{prefix}] {line.rstrip()}", flush=True)
26
+ finally:
27
+ pipe.close()
28
+
29
+
30
+ def launch_vllm() -> subprocess.Popen:
31
+ """Launch vLLM server as subprocess."""
32
+ model_id = os.environ.get("MODEL_ID", "deepseek-ai/DeepSeek-OCR")
33
+ served_name = os.environ.get("SERVED_MODEL_NAME", "deepseek-ocr")
34
+ port = os.environ.get("PORT", "8080")
35
+ host = os.environ.get("HOST", "0.0.0.0")
36
+
37
+ cmd: List[str] = [
38
+ "vllm", "serve", "--model", model_id,
39
+ "--served-model-name", served_name,
40
+ "--tensor-parallel-size", os.environ.get("TENSOR_PARALLEL_SIZE", "1"),
41
+ "--max-model-len", os.environ.get("MAX_MODEL_LEN", "4096"),
42
+ "--gpu-memory-utilization", os.environ.get("GPU_MEMORY_UTILIZATION", "0.90"),
43
+ "--port", port,
44
+ "--host", host,
45
+ "--trust-remote-code",
46
+ "--enable-chunked-prefill",
47
+ "--no-enable-prefix-caching",
48
+ "--mm-processor-cache-gb", os.environ.get("MM_PROCESSOR_CACHE_GB", "0"),
49
+ "--logits-processors", os.environ.get(
50
+ "LOGITS_PROCESSORS",
51
+ "vllm.model_executor.models.deepseek_ocr:NGramPerReqLogitsProcessor"
52
+ ),
53
+ ]
54
+
55
+ extra_args = os.environ.get("EXTRA_VLLM_ARGS")
56
+ if extra_args:
57
+ cmd.extend(extra_args.split())
58
+
59
+ LOGGER.info("Launching vLLM server: %s", " ".join(cmd))
60
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
61
+
62
+ # Start output streaming threads
63
+ threads = []
64
+ for name, pipe in [("STDOUT", process.stdout), ("STDERR", process.stderr)]:
65
+ if pipe:
66
+ t = threading.Thread(target=_stream_output, args=(pipe, f"vLLM {name}"), daemon=True)
67
+ t.start()
68
+ threads.append(t)
69
+
70
+ process._log_threads = threads # type: ignore
71
+ return process
72
+
73
+
74
+ def shutdown_server(server_process: subprocess.Popen) -> None:
75
+ """Gracefully shutdown vLLM server."""
76
+ LOGGER.info("Shutting down vLLM server")
77
+ server_process.send_signal(signal.SIGTERM)
78
+ try:
79
+ server_process.wait(timeout=30)
80
+ except subprocess.TimeoutExpired:
81
+ LOGGER.warning("Server did not exit in time, sending SIGKILL")
82
+ server_process.kill()
83
+
84
+ for thread in getattr(server_process, "_log_threads", []):
85
+ thread.join(timeout=1)
86
+
87
+
88
+ def wait_for_server(url: str, timeout_s: int = None, interval_s: int = 5) -> bool:
89
+ if timeout_s is None:
90
+ timeout_s = int(os.environ.get("VLLM_STARTUP_TIMEOUT", "600")) # 10 min default
91
+ """Wait for server health endpoint to respond."""
92
+ deadline = time.time() + timeout_s
93
+ while time.time() < deadline:
94
+ try:
95
+ if requests.get(url, timeout=5).ok:
96
+ return True
97
+ except Exception:
98
+ pass
99
+ time.sleep(interval_s)
100
+ return False
101
+
102
+
103
+ def should_launch_server() -> bool:
104
+ """Check if server should be auto-launched."""
105
+ return os.environ.get("SKIP_SERVER_LAUNCH", "").lower() not in {"1", "true", "yes"}
106
+
107
+
108
+ def base_url_from_env() -> str:
109
+ """Get vLLM base URL from environment."""
110
+ port = os.environ.get("PORT", "8080")
111
+ return os.environ.get("BASE_URL", f"http://127.0.0.1:{port}")
112
+
113
+
114
+ def _prepare_payload(
115
+ image: "Image.Image",
116
+ model_name: str,
117
+ prompt: str,
118
+ max_tokens: int,
119
+ temperature: float,
120
+ ) -> Dict[str, Any]:
121
+ """Prepare OpenAI-compatible chat completion payload."""
122
+ return {
123
+ "model": model_name,
124
+ "messages": [{
125
+ "role": "user",
126
+ "content": [
127
+ {"type": "text", "text": prompt},
128
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{encode_image(image)}"}},
129
+ ],
130
+ }],
131
+ "max_tokens": max_tokens,
132
+ "temperature": temperature,
133
+ "extra_body": {
134
+ "skip_special_tokens": False,
135
+ "vllm_xargs": {"ngram_size": 30, "window_size": 90, "whitelist_token_ids": "[128821,128822]"},
136
+ },
137
+ }
138
+
139
+
140
+ class DeepSeekClient:
141
+ """Async batch inference client for DeepSeek OCR via vLLM."""
142
+
143
+ def __init__(
144
+ self,
145
+ base_url: str,
146
+ model_name: str,
147
+ max_tokens: int,
148
+ temperature: float,
149
+ *,
150
+ request_timeout: int = 120,
151
+ max_retries: int = 3,
152
+ retry_backoff_seconds: float = 2.0,
153
+ max_retry_wait_seconds: float = 60.0,
154
+ ) -> None:
155
+ self.base_url = base_url.rstrip("/")
156
+ self.model_name = model_name
157
+ self.default_max_tokens = max_tokens
158
+ self.default_temperature = temperature
159
+ self.default_request_timeout = request_timeout
160
+ self.max_retries = max(0, max_retries)
161
+ self.retry_backoff_seconds = max(0.0, retry_backoff_seconds)
162
+ self.max_retry_wait_seconds = max_retry_wait_seconds
163
+ self._client = AsyncOpenAI(api_key="vllm", base_url=f"{self.base_url}/v1")
164
+
165
+ async def _async_completion(self, payload: Dict[str, Any], timeout: int) -> str:
166
+ """Execute single async completion request."""
167
+ try:
168
+ response = await self._client.chat.completions.create(
169
+ model=payload["model"],
170
+ messages=payload["messages"],
171
+ max_tokens=payload["max_tokens"],
172
+ temperature=payload["temperature"],
173
+ timeout=timeout,
174
+ extra_body=payload.get("extra_body"),
175
+ )
176
+ except Exception as exc:
177
+ LOGGER.error("DeepSeek request failed: %s", exc)
178
+ raise
179
+
180
+ if not response.choices:
181
+ return ""
182
+ return getattr(response.choices[0].message, "content", "") or ""
183
+
184
+ def infer(self, requests_data: Sequence[Dict[str, Any]]) -> List[str]:
185
+ """Run batch inference synchronously."""
186
+ if not requests_data:
187
+ return []
188
+
189
+ payloads = []
190
+ timeouts = []
191
+ for req in requests_data:
192
+ payloads.append(_prepare_payload(
193
+ image=req["image"],
194
+ model_name=self.model_name,
195
+ prompt=req.get("prompt", ""),
196
+ max_tokens=req.get("max_tokens", self.default_max_tokens),
197
+ temperature=req.get("temperature", self.default_temperature),
198
+ ))
199
+ timeouts.append(req.get("request_timeout") or self.default_request_timeout)
200
+
201
+ return self._run_async(self._async_infer_batch(payloads, timeouts))
202
+
203
+ async def _async_infer_batch(self, payloads: Sequence[Dict[str, Any]], timeouts: Sequence[int]) -> List[str]:
204
+ """Run batch of async completions concurrently."""
205
+ tasks = [asyncio.create_task(self._async_completion(p, t)) for p, t in zip(payloads, timeouts)]
206
+ return await asyncio.gather(*tasks)
207
+
208
+ @staticmethod
209
+ def _run_async(coro: Awaitable[Any]) -> Any:
210
+ """Run async coroutine in new event loop."""
211
+ loop = asyncio.new_event_loop()
212
+ try:
213
+ asyncio.set_event_loop(loop)
214
+ result = loop.run_until_complete(coro)
215
+ loop.run_until_complete(loop.shutdown_asyncgens())
216
+ return result
217
+ finally:
218
+ asyncio.set_event_loop(None)
219
+ loop.close()
220
+
221
+
222
+ __all__ = [
223
+ "launch_vllm",
224
+ "shutdown_server",
225
+ "wait_for_server",
226
+ "should_launch_server",
227
+ "base_url_from_env",
228
+ "DeepSeekClient",
229
+ ]
llm_ocr/sm_io.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Amazon S3 utilities for SageMaker jobs."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import shutil
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Tuple
8
+
9
+ import boto3
10
+ from botocore.config import Config
11
+
12
+ if TYPE_CHECKING:
13
+ from datasets import Dataset
14
+
15
+ LOGGER = logging.getLogger(__name__)
16
+
17
+
18
+ def get_s3_client():
19
+ """Get S3 client with retry configuration."""
20
+ config = Config(
21
+ retries={"max_attempts": 3, "mode": "standard"},
22
+ max_pool_connections=50,
23
+ )
24
+ return boto3.client("s3", config=config)
25
+
26
+
27
+ def parse_s3_uri(uri: str) -> Tuple[str, str]:
28
+ """Parse s3://bucket/key into (bucket, key)."""
29
+ if not uri.startswith("s3://"):
30
+ raise ValueError(f"Invalid S3 URI: {uri}")
31
+ parts = uri[5:].split("/", 1)
32
+ bucket = parts[0]
33
+ key = parts[1] if len(parts) > 1 else ""
34
+ return bucket, key
35
+
36
+
37
+ def upload_files_to_s3(
38
+ *,
39
+ output_dir: Path,
40
+ s3_uri: str,
41
+ path_prefix: str = "",
42
+ ) -> None:
43
+ """Upload local files to S3.
44
+
45
+ Args:
46
+ output_dir: Local directory containing files to upload
47
+ s3_uri: S3 URI (s3://bucket/prefix)
48
+ path_prefix: Additional prefix to add to S3 keys
49
+ """
50
+ if not s3_uri:
51
+ LOGGER.info("No S3 URI provided; skipping upload.")
52
+ return
53
+
54
+ bucket, base_prefix = parse_s3_uri(s3_uri)
55
+
56
+ full_prefix = base_prefix.rstrip("/")
57
+ if path_prefix:
58
+ full_prefix = f"{full_prefix}/{path_prefix.strip('/')}" if full_prefix else path_prefix.strip("/")
59
+
60
+ s3 = get_s3_client()
61
+ base = output_dir.resolve()
62
+
63
+ files = sorted(p for p in base.rglob("*") if p.is_file())
64
+ if not files:
65
+ LOGGER.info("Nothing to upload from %s", output_dir)
66
+ return
67
+
68
+ LOGGER.info("Uploading %d files to s3://%s/%s", len(files), bucket, full_prefix)
69
+
70
+ for local_path in files:
71
+ rel = local_path.relative_to(base).as_posix()
72
+ s3_key = f"{full_prefix}/{rel}" if full_prefix else rel
73
+ try:
74
+ s3.upload_file(str(local_path), bucket, s3_key)
75
+ except Exception as exc:
76
+ LOGGER.error("Failed to upload %s to s3://%s/%s: %s", local_path, bucket, s3_key, exc)
77
+ raise
78
+
79
+
80
+ def save_dataset_to_s3(
81
+ dataset,
82
+ s3_uri: str,
83
+ name: str = "dataset",
84
+ ) -> str:
85
+ """Save HF dataset to S3 using Arrow format (preserves Image columns).
86
+
87
+ Args:
88
+ dataset: HuggingFace Dataset or DatasetDict to save
89
+ s3_uri: Base S3 URI (s3://bucket/prefix)
90
+ name: Name for the dataset folder
91
+
92
+ Returns:
93
+ S3 URI of the saved dataset
94
+ """
95
+ from datasets import DatasetDict
96
+
97
+ # Handle DatasetDict by extracting the first split
98
+ if isinstance(dataset, DatasetDict):
99
+ if "train" in dataset:
100
+ dataset = dataset["train"]
101
+ else:
102
+ split_name = list(dataset.keys())[0]
103
+ dataset = dataset[split_name]
104
+ LOGGER.info("Using split '%s' from DatasetDict", split_name)
105
+
106
+ bucket, prefix = parse_s3_uri(s3_uri)
107
+ full_prefix = prefix.rstrip("/")
108
+
109
+ # Save to local temp directory using Arrow format
110
+ local_dir = Path(f"/tmp/{name}_arrow_temp")
111
+ if local_dir.exists():
112
+ shutil.rmtree(local_dir)
113
+
114
+ LOGGER.info("Saving dataset to Arrow format...")
115
+ dataset.save_to_disk(str(local_dir))
116
+
117
+ # Upload entire directory to S3
118
+ s3_prefix = f"{full_prefix}/{name}" if full_prefix else name
119
+ upload_files_to_s3(output_dir=local_dir, s3_uri=f"s3://{bucket}/{s3_prefix}")
120
+
121
+ # Cleanup
122
+ shutil.rmtree(local_dir)
123
+
124
+ result_uri = f"s3://{bucket}/{s3_prefix}"
125
+ LOGGER.info("Saved dataset to %s", result_uri)
126
+ return result_uri
127
+
128
+
129
+ def get_dataset_features():
130
+ """Get the dataset feature schema."""
131
+ from datasets import Features, Sequence, Value, Image as HfImage
132
+
133
+ return Features({
134
+ "sample_id": Value("string"),
135
+ "dataset_index": Value("int64"),
136
+ "source_image": HfImage(),
137
+ "document_with_boxes_image": HfImage(),
138
+ "document_markdown": Value("string"),
139
+ "extracted_figures": Sequence(HfImage()),
140
+ "extracted_figures_metadata": Sequence(Value("string")),
141
+ "document_final_markdown": Value("string"),
142
+ })
143
+
144
+
145
+ def load_dataset_from_s3(s3_uri: str, split: str = "train") -> "Dataset":
146
+ """Load HF dataset directly from S3 (saved with save_to_disk).
147
+
148
+ Downloads files locally first to avoid s3fs caching issues.
149
+
150
+ Args:
151
+ s3_uri: S3 URI to dataset directory (s3://bucket/path/to/dataset/)
152
+ split: Unused, kept for API compatibility
153
+
154
+ Returns:
155
+ Loaded Dataset
156
+
157
+ Requires:
158
+ pip install datasets boto3
159
+ """
160
+ from datasets import load_from_disk
161
+ import tempfile
162
+
163
+ LOGGER.info("Loading dataset from %s", s3_uri)
164
+
165
+ # Parse S3 URI
166
+ bucket_name, prefix = parse_s3_uri(s3_uri)
167
+
168
+ # Download to local temp directory (bypasses s3fs cache)
169
+ s3 = get_s3_client()
170
+ local_dir = tempfile.mkdtemp(prefix="s3_dataset_")
171
+
172
+ # List and download all objects
173
+ paginator = s3.get_paginator('list_objects_v2')
174
+ download_count = 0
175
+ for page in paginator.paginate(Bucket=bucket_name, Prefix=f"{prefix}/"):
176
+ for obj in page.get('Contents', []):
177
+ key = obj['Key']
178
+ filename = key.split('/')[-1]
179
+ if filename: # Skip directory markers
180
+ local_path = f"{local_dir}/{filename}"
181
+ s3.download_file(bucket_name, key, local_path)
182
+ download_count += 1
183
+
184
+ LOGGER.info("Downloaded %d files to %s", download_count, local_dir)
185
+
186
+ # Load from local
187
+ ds = load_from_disk(local_dir)
188
+
189
+ return ds
190
+
191
+
192
+ __all__ = [
193
+ "save_dataset_to_s3",
194
+ "load_dataset_from_s3",
195
+ "parse_s3_uri",
196
+ "get_s3_client",
197
+ ]
llm_ocr/stages.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pipeline stages: extract, describe, assemble."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import logging
6
+ import shutil
7
+ from dataclasses import asdict
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List
11
+
12
+ from datasets import Features, Sequence, Value, load_dataset, Image as HfImage
13
+ from PIL import Image
14
+ from torch.utils.data import DataLoader
15
+
16
+ from .config import AssembleSettings, DescribeSettings, ExtractSettings, env
17
+ from .document import build_document_markdown, enrich_markdown_with_captions, write_json
18
+ from .storage import get_storage, get_source_storage
19
+
20
+ LOGGER = logging.getLogger(__name__)
21
+
22
+
23
+ def _now_iso() -> str:
24
+ return datetime.utcnow().isoformat() + "Z"
25
+
26
+
27
+ def _dataset_features() -> Features:
28
+ """Dataset schema - all data is embedded, no external file paths."""
29
+ return Features({
30
+ "sample_id": Value("string"),
31
+ "dataset_index": Value("int64"),
32
+ "source_image": HfImage(),
33
+ "document_with_boxes_image": HfImage(),
34
+ "document_markdown": Value("string"),
35
+ "extracted_figures": Sequence(HfImage()),
36
+ "extracted_figures_metadata": Sequence(Value("string")),
37
+ "document_final_markdown": Value("string"),
38
+ })
39
+
40
+
41
+ def run_stage_extract(settings: ExtractSettings) -> None:
42
+ """Run OCR extraction on dataset samples."""
43
+ dataset = load_dataset(
44
+ settings.dataset_name,
45
+ settings.dataset_config,
46
+ split=settings.dataset_split,
47
+ streaming=settings.stream_dataset,
48
+ )
49
+
50
+ # Setup iterator with optional DataLoader for streaming
51
+ if settings.stream_dataset:
52
+ num_workers = env("DATALOADER_WORKERS", 2, int)
53
+ prefetch = env("DATALOADER_PREFETCH", 2, int)
54
+ kwargs = {"batch_size": 1, "num_workers": num_workers, "collate_fn": lambda b: b[0]}
55
+ if num_workers > 0:
56
+ kwargs["prefetch_factor"] = prefetch
57
+ sample_iter = iter(DataLoader(dataset, **kwargs))
58
+ else:
59
+ sample_iter = iter(dataset)
60
+
61
+ settings.output_dir.mkdir(parents=True, exist_ok=True)
62
+ batches_dir = settings.output_dir / "document_batches"
63
+ if batches_dir.exists():
64
+ shutil.rmtree(batches_dir)
65
+ batches_dir.mkdir(parents=True, exist_ok=True)
66
+
67
+ batch_files: List[str] = []
68
+ batch_idx = 0
69
+ doc_count = 0
70
+ failures: List[Dict[str, Any]] = []
71
+ chunk_size = settings.inference.batch_size
72
+
73
+ LOGGER.info("Extract | dataset=%s/%s/%s | max_samples=%s | batch=%s",
74
+ settings.dataset_name, settings.dataset_config, settings.dataset_split,
75
+ settings.max_samples, chunk_size)
76
+
77
+ contexts: List[Dict[str, Any]] = []
78
+ requests: List[Dict[str, Any]] = []
79
+
80
+ def flush():
81
+ nonlocal contexts, requests, doc_count, batch_idx
82
+ if not contexts:
83
+ return
84
+
85
+ try:
86
+ responses = settings.client.infer(requests)
87
+ except Exception as exc:
88
+ LOGGER.exception("Batch inference failed for %d samples", len(contexts))
89
+ for ctx in contexts:
90
+ failures.append({"sample_id": ctx["sample_id"], "error": str(exc)})
91
+ if hasattr(ctx.get("image"), "close"):
92
+ ctx["image"].close()
93
+ contexts, requests = [], []
94
+ return
95
+
96
+ docs: List[Dict[str, Any]] = []
97
+ for i, ctx in enumerate(contexts):
98
+ img = ctx.get("image")
99
+ try:
100
+ text = responses[i].strip() if i < len(responses) else ""
101
+ if not text:
102
+ raise RuntimeError("Empty response")
103
+
104
+ sample_dir = ctx["sample_dir"]
105
+ sample_id = ctx["sample_id"]
106
+
107
+ markdown, figures, figure_images, img_draw = build_document_markdown(
108
+ image=img, response_text=text, sample_id=sample_id,
109
+ )
110
+
111
+ # Save images locally for dataset loading (HfImage needs file paths)
112
+ source_path = sample_dir / "source.png"
113
+ boxes_path = sample_dir / "document_with_boxes.png"
114
+ img_draw.save(boxes_path)
115
+
116
+ # Save figure images for dataset loading
117
+ figures_dir = sample_dir / "figures"
118
+ figures_dir.mkdir(parents=True, exist_ok=True)
119
+ figure_paths = []
120
+ for fig_meta, fig_img in zip(figures, figure_images):
121
+ fig_path = figures_dir / f"{fig_meta.figure_id}.png"
122
+ fig_img.save(fig_path)
123
+ figure_paths.append(str(fig_path))
124
+
125
+ docs.append({
126
+ "sample_id": sample_id,
127
+ "dataset_index": ctx["dataset_index"],
128
+ "source_image": str(source_path),
129
+ "document_with_boxes_image": str(boxes_path),
130
+ "document_markdown": markdown,
131
+ "extracted_figures": figure_paths,
132
+ "extracted_figures_metadata": [json.dumps(asdict(f)) for f in figures],
133
+ "document_final_markdown": "", # Filled in assemble stage
134
+ })
135
+ except Exception as exc:
136
+ LOGGER.exception("Failed sample %s", ctx["sample_id"])
137
+ failures.append({"sample_id": ctx["sample_id"], "error": str(exc)})
138
+ finally:
139
+ if hasattr(img, "close"):
140
+ img.close()
141
+
142
+ if docs:
143
+ batch_file = batches_dir / f"batch_{batch_idx:05d}.json"
144
+ write_json(batch_file, docs)
145
+ batch_files.append(str(batch_file))
146
+ batch_idx += 1
147
+ doc_count += len(docs)
148
+
149
+ contexts, requests = [], []
150
+
151
+ for idx, sample in enumerate(sample_iter):
152
+ if settings.max_samples and idx >= settings.max_samples:
153
+ break
154
+
155
+ sample_id = f"sample_{idx:05d}"
156
+ sample_dir = settings.output_dir / sample_id
157
+ sample_dir.mkdir(parents=True, exist_ok=True)
158
+
159
+ img = sample["images"][0].copy()
160
+ if img.mode != "RGB":
161
+ img = img.convert("RGB")
162
+ img.save(sample_dir / "source.png")
163
+
164
+ contexts.append({"sample_id": sample_id, "dataset_index": idx, "sample_dir": sample_dir, "image": img.copy()})
165
+ requests.append({
166
+ "image": contexts[-1]["image"],
167
+ "prompt": settings.prompt,
168
+ "max_tokens": settings.max_tokens,
169
+ "temperature": settings.temperature,
170
+ "request_timeout": settings.inference.request_timeout,
171
+ })
172
+ img.close()
173
+
174
+ if len(requests) >= chunk_size:
175
+ flush()
176
+
177
+ flush()
178
+
179
+ # Save manifest
180
+ write_json(settings.output_dir / "manifest.json", {
181
+ "generated_at": _now_iso(),
182
+ "stage": "extract",
183
+ "documents_count": doc_count,
184
+ "failures": failures,
185
+ })
186
+
187
+ # Load as HF dataset
188
+ ds = load_dataset("json", data_files=batch_files, features=_dataset_features())
189
+ shutil.rmtree(batches_dir)
190
+
191
+ # Get storage backend and save
192
+ storage = get_storage(repo_id=settings.hub.repo_id)
193
+ storage.save_dataset(ds, "dataset")
194
+
195
+ LOGGER.info("Extract complete | docs=%d | failures=%d", doc_count, len(failures))
196
+
197
+
198
+ def run_stage_describe(settings: DescribeSettings) -> None:
199
+ """Describe figures in the dataset that lack descriptions."""
200
+ # Get source storage and load dataset
201
+ source_storage = get_source_storage(source_repo_id=settings.source_repo_id or settings.hub.repo_id)
202
+ if not source_storage.is_configured:
203
+ raise ValueError("No source configured for describe stage (set SOURCE_REPO_ID, HF_REPO_ID, or S3_INPUT_URI)")
204
+
205
+ dataset = source_storage.load_dataset()
206
+ if dataset is None:
207
+ raise RuntimeError("Failed to load source dataset for describe stage")
208
+
209
+ settings.output_dir.mkdir(parents=True, exist_ok=True)
210
+ desc_dir = settings.output_dir / "descriptions"
211
+ if desc_dir.exists():
212
+ shutil.rmtree(desc_dir)
213
+ desc_dir.mkdir(parents=True, exist_ok=True)
214
+
215
+ chunk_size = settings.inference.batch_size
216
+ failures: List[Dict[str, Any]] = []
217
+ contexts: List[Dict[str, Any]] = []
218
+ requests: List[Dict[str, Any]] = []
219
+ batch_idx = 0
220
+ described = 0
221
+
222
+ def flush():
223
+ nonlocal contexts, requests, batch_idx, described
224
+ if not contexts:
225
+ return
226
+
227
+ results = []
228
+ try:
229
+ responses = settings.client.infer(requests)
230
+ for i, ctx in enumerate(contexts):
231
+ desc = responses[i].strip() if i < len(responses) else ""
232
+ if desc:
233
+ results.append({"figure_id": ctx["figure_id"], "description": desc})
234
+ described += 1
235
+ except Exception as exc:
236
+ LOGGER.exception("Describe batch failed")
237
+ for ctx in contexts:
238
+ failures.append({"figure_id": ctx.get("figure_id"), "error": str(exc)})
239
+ finally:
240
+ for ctx in contexts:
241
+ if hasattr(ctx.get("image"), "close"):
242
+ ctx["image"].close()
243
+ contexts, requests = [], []
244
+
245
+ if results:
246
+ with (desc_dir / f"batch_{batch_idx:05d}.jsonl").open("w") as f:
247
+ for r in results:
248
+ f.write(json.dumps(r) + "\n")
249
+ batch_idx += 1
250
+
251
+ # Queue figures needing descriptions
252
+ pending = 0
253
+ for row in dataset:
254
+ sample_id = row["sample_id"]
255
+ metas = row.get("extracted_figures_metadata") or []
256
+ images = row.get("extracted_figures") or []
257
+
258
+ for i, meta_json in enumerate(metas):
259
+ meta = json.loads(meta_json) if isinstance(meta_json, str) else meta_json
260
+ if meta.get("description"):
261
+ continue
262
+
263
+ pending += 1
264
+ fig_id = meta.get("figure_id", "")
265
+
266
+ if i >= len(images) or images[i] is None:
267
+ failures.append({"sample_id": sample_id, "figure_id": fig_id, "reason": "missing_image"})
268
+ continue
269
+
270
+ fig_img = images[i]
271
+ contexts.append({"sample_id": sample_id, "figure_id": fig_id, "image": fig_img})
272
+ requests.append({
273
+ "image": fig_img,
274
+ "prompt": settings.prompt,
275
+ "max_tokens": settings.max_tokens,
276
+ "temperature": settings.temperature,
277
+ "request_timeout": settings.inference.request_timeout,
278
+ })
279
+
280
+ if len(requests) >= chunk_size:
281
+ flush()
282
+
283
+ flush()
284
+
285
+ if pending == 0:
286
+ LOGGER.info("No figures need descriptions")
287
+ return
288
+
289
+ # Load descriptions and apply to dataset
290
+ lookup = {}
291
+ for f in sorted(desc_dir.glob("batch_*.jsonl")):
292
+ for line in f.read_text().splitlines():
293
+ if line.strip():
294
+ r = json.loads(line)
295
+ lookup[r["figure_id"]] = r["description"]
296
+
297
+ if not lookup:
298
+ LOGGER.info("No descriptions generated")
299
+ return
300
+
301
+ LOGGER.info("Lookup has %d descriptions, first few: %s",
302
+ len(lookup), list(lookup.keys())[:3])
303
+
304
+ def apply(row):
305
+ metas = row.get("extracted_figures_metadata") or []
306
+ new_metas = []
307
+ for m in metas:
308
+ meta = json.loads(m) if isinstance(m, str) else m
309
+ if meta.get("figure_id") in lookup:
310
+ meta["description"] = lookup[meta["figure_id"]]
311
+ new_metas.append(json.dumps(meta))
312
+ return {"extracted_figures_metadata": new_metas}
313
+
314
+ # Don't pass features - let map infer them
315
+ updated = dataset.map(apply)
316
+ shutil.rmtree(desc_dir)
317
+
318
+ # Verify before saving
319
+ test_meta = updated[0]["extracted_figures_metadata"]
320
+ if test_meta:
321
+ test_parsed = json.loads(test_meta[0]) if isinstance(test_meta[0], str) else test_meta[0]
322
+ LOGGER.info("VERIFY before save - description present: %s",
323
+ test_parsed.get("description") is not None)
324
+
325
+ # Get output storage and save
326
+ storage = get_storage(repo_id=settings.hub.repo_id)
327
+ storage.save_dataset(updated, "dataset")
328
+
329
+ LOGGER.info("Describe complete | described=%d | failures=%d", described, len(failures))
330
+
331
+
332
+ def run_stage_assemble(settings: AssembleSettings) -> None:
333
+ """Enrich markdown with figure descriptions."""
334
+ # Get source storage and load dataset
335
+ source_storage = get_source_storage(source_repo_id=settings.source_repo_id or settings.hub.repo_id)
336
+ if not source_storage.is_configured:
337
+ raise ValueError("No source configured for assemble stage (set SOURCE_REPO_ID, HF_REPO_ID, or S3_INPUT_URI)")
338
+
339
+ dataset = source_storage.load_dataset()
340
+ if dataset is None:
341
+ raise RuntimeError("Failed to load source dataset for assemble stage")
342
+
343
+ assembled_count = 0
344
+
345
+ def assemble(row):
346
+ nonlocal assembled_count
347
+ markdown = row.get("document_markdown") or ""
348
+ if not markdown:
349
+ return row
350
+
351
+ # Parse figure metadata for description lookup
352
+ desc_map = {}
353
+ for m in row.get("extracted_figures_metadata") or []:
354
+ meta = json.loads(m) if isinstance(m, str) else m
355
+ if meta.get("figure_id"):
356
+ desc_map[meta["figure_id"]] = meta
357
+
358
+ # Enrich with captions (keeps figure: URIs, adds descriptions)
359
+ # Images are rendered on-demand using render_sample_markdown()
360
+ final_markdown = enrich_markdown_with_captions(markdown, desc_map)
361
+
362
+ row["document_final_markdown"] = final_markdown
363
+ assembled_count += 1
364
+ return row
365
+
366
+ dataset = dataset.map(assemble)
367
+
368
+ # Get output storage and save
369
+ storage = get_storage(repo_id=settings.hub.repo_id)
370
+ storage.save_dataset(dataset, "dataset")
371
+
372
+ LOGGER.info("Assemble complete | assembled=%d", assembled_count)
373
+
374
+
375
+ __all__ = ["run_stage_extract", "run_stage_describe", "run_stage_assemble"]
llm_ocr/storage.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unified storage abstraction for dataset I/O.
2
+
3
+ This module provides a common interface for saving/loading HuggingFace datasets,
4
+ abstracting away whether we're using HuggingFace Hub, S3, or GCS.
5
+
6
+ Usage:
7
+ from .storage import get_storage
8
+
9
+ storage = get_storage()
10
+ storage.save_dataset(dataset, "my_dataset")
11
+ dataset = storage.load_dataset()
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from abc import ABC, abstractmethod
17
+ from typing import TYPE_CHECKING, Optional
18
+
19
+ from .config import env
20
+
21
+ if TYPE_CHECKING:
22
+ from datasets import Dataset
23
+
24
+ LOGGER = logging.getLogger(__name__)
25
+
26
+
27
+ class DatasetStorage(ABC):
28
+ """Abstract base class for dataset storage backends."""
29
+
30
+ @abstractmethod
31
+ def save_dataset(self, dataset: "Dataset", name: str) -> bool:
32
+ """Save a HuggingFace dataset to storage.
33
+
34
+ Args:
35
+ dataset: HuggingFace Dataset to save
36
+ name: Name/identifier for the dataset
37
+
38
+ Returns:
39
+ True if save succeeded
40
+ """
41
+ pass
42
+
43
+ @abstractmethod
44
+ def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
45
+ """Load a HuggingFace dataset from storage.
46
+
47
+ Args:
48
+ split: Dataset split to load
49
+
50
+ Returns:
51
+ Loaded Dataset or None if not available
52
+ """
53
+ pass
54
+
55
+ @property
56
+ @abstractmethod
57
+ def is_configured(self) -> bool:
58
+ """Check if this storage backend is configured."""
59
+ pass
60
+
61
+
62
+ class HFHubStorage(DatasetStorage):
63
+ """HuggingFace Hub storage backend."""
64
+
65
+ def __init__(
66
+ self,
67
+ repo_id: Optional[str] = None,
68
+ branch: Optional[str] = None,
69
+ commit_message: Optional[str] = None,
70
+ ):
71
+ self.repo_id = repo_id or env("HF_REPO_ID")
72
+ self.branch = branch or env("HF_BRANCH")
73
+ self.commit_message = commit_message or env("HF_COMMIT_MESSAGE")
74
+ self._token = env("HF_TOKEN")
75
+
76
+ @property
77
+ def is_configured(self) -> bool:
78
+ return bool(self.repo_id)
79
+
80
+ def save_dataset(self, dataset: "Dataset", name: str) -> bool:
81
+ if not self.is_configured:
82
+ LOGGER.debug("HF Hub not configured, skipping dataset save")
83
+ return False
84
+
85
+ try:
86
+ dataset.push_to_hub(
87
+ self.repo_id,
88
+ token=self._token,
89
+ revision=self.branch,
90
+ commit_message=self.commit_message or f"Add {name}",
91
+ )
92
+ LOGGER.info("Pushed dataset to HF Hub: %s", self.repo_id)
93
+ return True
94
+ except Exception as exc:
95
+ LOGGER.exception("HF Hub dataset push failed: %s", exc)
96
+ return False
97
+
98
+ def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
99
+ if not self.is_configured:
100
+ LOGGER.debug("HF Hub not configured, cannot load dataset")
101
+ return None
102
+
103
+ try:
104
+ from datasets import load_dataset
105
+
106
+ LOGGER.info("Loading dataset from HF Hub: %s", self.repo_id)
107
+ return load_dataset(self.repo_id, split=split, token=self._token)
108
+ except Exception as exc:
109
+ LOGGER.exception("HF Hub dataset load failed: %s", exc)
110
+ return None
111
+
112
+
113
+ class S3Storage(DatasetStorage):
114
+ """Amazon S3 storage backend."""
115
+
116
+ def __init__(
117
+ self,
118
+ output_uri: Optional[str] = None,
119
+ input_uri: Optional[str] = None,
120
+ ):
121
+ self.output_uri = output_uri or env("S3_OUTPUT_URI")
122
+ self.input_uri = input_uri or env("S3_INPUT_URI")
123
+
124
+ @property
125
+ def is_configured(self) -> bool:
126
+ return bool(self.output_uri or self.input_uri)
127
+
128
+ def save_dataset(self, dataset: "Dataset", name: str) -> bool:
129
+ if not self.output_uri:
130
+ LOGGER.debug("S3 output URI not configured, skipping dataset save")
131
+ return False
132
+
133
+ try:
134
+ from .sm_io import save_dataset_to_s3
135
+
136
+ save_dataset_to_s3(dataset, self.output_uri, name)
137
+ return True
138
+ except ImportError as exc:
139
+ LOGGER.warning("S3 save failed (missing dependency): %s", exc)
140
+ return False
141
+ except Exception as exc:
142
+ LOGGER.exception("S3 dataset save failed: %s", exc)
143
+ return False
144
+
145
+ def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
146
+ if not self.input_uri:
147
+ LOGGER.debug("S3 input URI not configured, cannot load dataset")
148
+ return None
149
+
150
+ try:
151
+ from .sm_io import load_dataset_from_s3
152
+
153
+ return load_dataset_from_s3(self.input_uri, split=split)
154
+ except ImportError as exc:
155
+ LOGGER.warning("S3 load failed (missing dependency): %s", exc)
156
+ return None
157
+ except Exception as exc:
158
+ LOGGER.exception("S3 dataset load failed: %s", exc)
159
+ return None
160
+
161
+
162
+ class GCSStorage(DatasetStorage):
163
+ """Google Cloud Storage backend."""
164
+
165
+ def __init__(
166
+ self,
167
+ output_uri: Optional[str] = None,
168
+ input_uri: Optional[str] = None,
169
+ ):
170
+ self.output_uri = output_uri or env("GCS_OUTPUT_URI")
171
+ self.input_uri = input_uri or env("GCS_INPUT_URI")
172
+
173
+ @property
174
+ def is_configured(self) -> bool:
175
+ return bool(self.output_uri or self.input_uri)
176
+
177
+ def save_dataset(self, dataset: "Dataset", name: str) -> bool:
178
+ if not self.output_uri:
179
+ LOGGER.debug("GCS output URI not configured, skipping dataset save")
180
+ return False
181
+
182
+ try:
183
+ from .gcr_io import save_dataset_to_gcs
184
+
185
+ save_dataset_to_gcs(dataset, self.output_uri, name)
186
+ return True
187
+ except ImportError as exc:
188
+ LOGGER.warning("GCS save failed (missing dependency): %s", exc)
189
+ return False
190
+ except Exception as exc:
191
+ LOGGER.exception("GCS dataset save failed: %s", exc)
192
+ return False
193
+
194
+ def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
195
+ if not self.input_uri:
196
+ LOGGER.debug("GCS input URI not configured, cannot load dataset")
197
+ return None
198
+
199
+ try:
200
+ from .gcr_io import load_dataset_from_gcs
201
+
202
+ return load_dataset_from_gcs(self.input_uri, split=split)
203
+ except ImportError as exc:
204
+ LOGGER.warning("GCS load failed (missing dependency): %s", exc)
205
+ return None
206
+ except Exception as exc:
207
+ LOGGER.exception("GCS dataset load failed: %s", exc)
208
+ return None
209
+
210
+
211
+ def get_storage(
212
+ *,
213
+ repo_id: Optional[str] = None,
214
+ s3_output_uri: Optional[str] = None,
215
+ s3_input_uri: Optional[str] = None,
216
+ gcs_output_uri: Optional[str] = None,
217
+ gcs_input_uri: Optional[str] = None,
218
+ ) -> DatasetStorage:
219
+ """Get the appropriate storage backend based on configuration.
220
+
221
+ Priority: GCS > S3 > HF Hub.
222
+
223
+ Args:
224
+ repo_id: Override HF repo ID
225
+ s3_output_uri: Override S3 output URI
226
+ s3_input_uri: Override S3 input URI
227
+ gcs_output_uri: Override GCS output URI
228
+ gcs_input_uri: Override GCS input URI
229
+
230
+ Returns:
231
+ Configured DatasetStorage instance
232
+ """
233
+ gcs = GCSStorage(output_uri=gcs_output_uri, input_uri=gcs_input_uri)
234
+ s3 = S3Storage(output_uri=s3_output_uri, input_uri=s3_input_uri)
235
+ hf = HFHubStorage(repo_id=repo_id)
236
+
237
+ # Return first configured backend
238
+ if gcs.is_configured:
239
+ return gcs
240
+ if s3.is_configured:
241
+ return s3
242
+ return hf
243
+
244
+
245
+ def get_source_storage(
246
+ *,
247
+ source_repo_id: Optional[str] = None,
248
+ ) -> DatasetStorage:
249
+ """Get storage backend for loading source data.
250
+
251
+ Checks GCS_INPUT_URI first, then S3_INPUT_URI, then falls back to HF Hub.
252
+
253
+ Args:
254
+ source_repo_id: HF repo ID to load from (falls back to SOURCE_REPO_ID env var)
255
+
256
+ Returns:
257
+ Configured DatasetStorage instance for loading
258
+ """
259
+ gcs_input = env("GCS_INPUT_URI")
260
+ if gcs_input:
261
+ return GCSStorage(input_uri=gcs_input)
262
+
263
+ s3_input = env("S3_INPUT_URI")
264
+ if s3_input:
265
+ return S3Storage(input_uri=s3_input)
266
+
267
+ repo_id = source_repo_id or env("SOURCE_REPO_ID") or env("HF_REPO_ID")
268
+ return HFHubStorage(repo_id=repo_id)
269
+
270
+
271
+ __all__ = [
272
+ "DatasetStorage",
273
+ "HFHubStorage",
274
+ "S3Storage",
275
+ "GCSStorage",
276
+ "get_storage",
277
+ "get_source_storage",
278
+ ]