Upload folder using huggingface_hub
Browse files- llm_ocr/__init__.py +13 -13
- llm_ocr/__pycache__/__init__.cpython-312.pyc +0 -0
- llm_ocr/__pycache__/config.cpython-312.pyc +0 -0
- llm_ocr/__pycache__/document.cpython-312.pyc +0 -0
- llm_ocr/__pycache__/server.cpython-312.pyc +0 -0
- llm_ocr/__pycache__/stages.cpython-312.pyc +0 -0
- llm_ocr/__pycache__/storage.cpython-312.pyc +0 -0
- llm_ocr/cli.py +29 -7
- llm_ocr/cloudrun_io.py +41 -69
- llm_ocr/config.py +10 -1
- llm_ocr/document.py +77 -105
- llm_ocr/server.py +80 -35
- llm_ocr/sm_io.py +33 -70
- llm_ocr/stages.py +135 -71
- llm_ocr/storage.py +68 -76
llm_ocr/__init__.py
CHANGED
|
@@ -13,27 +13,27 @@ Example usage:
|
|
| 13 |
|
| 14 |
# Stage runners - main entry points for pipeline stages
|
| 15 |
from llm_ocr.stages import (
|
| 16 |
-
run_stage_assemble,
|
| 17 |
-
run_stage_describe,
|
| 18 |
-
run_stage_extract,
|
| 19 |
)
|
| 20 |
|
| 21 |
# Configuration classes
|
| 22 |
from llm_ocr.config import (
|
| 23 |
-
AssembleSettings,
|
| 24 |
-
DescribeSettings,
|
| 25 |
-
ExtractSettings,
|
| 26 |
-
InferenceSettings,
|
| 27 |
)
|
| 28 |
|
| 29 |
# Inference client
|
| 30 |
-
from llm_ocr.server import DeepSeekClient
|
| 31 |
|
| 32 |
# Storage backends
|
| 33 |
from llm_ocr.storage import (
|
| 34 |
-
DatasetStorage,
|
| 35 |
-
GCSStorage,
|
| 36 |
-
HFHubStorage,
|
| 37 |
-
S3Storage,
|
| 38 |
-
get_storage,
|
| 39 |
)
|
|
|
|
| 13 |
|
| 14 |
# Stage runners - main entry points for pipeline stages
|
| 15 |
from llm_ocr.stages import (
|
| 16 |
+
run_stage_assemble as run_stage_assemble,
|
| 17 |
+
run_stage_describe as run_stage_describe,
|
| 18 |
+
run_stage_extract as run_stage_extract,
|
| 19 |
)
|
| 20 |
|
| 21 |
# Configuration classes
|
| 22 |
from llm_ocr.config import (
|
| 23 |
+
AssembleSettings as AssembleSettings,
|
| 24 |
+
DescribeSettings as DescribeSettings,
|
| 25 |
+
ExtractSettings as ExtractSettings,
|
| 26 |
+
InferenceSettings as InferenceSettings,
|
| 27 |
)
|
| 28 |
|
| 29 |
# Inference client
|
| 30 |
+
from llm_ocr.server import DeepSeekClient as DeepSeekClient
|
| 31 |
|
| 32 |
# Storage backends
|
| 33 |
from llm_ocr.storage import (
|
| 34 |
+
DatasetStorage as DatasetStorage,
|
| 35 |
+
GCSStorage as GCSStorage,
|
| 36 |
+
HFHubStorage as HFHubStorage,
|
| 37 |
+
S3Storage as S3Storage,
|
| 38 |
+
get_storage as get_storage,
|
| 39 |
)
|
llm_ocr/__pycache__/__init__.cpython-312.pyc
CHANGED
|
Binary files a/llm_ocr/__pycache__/__init__.cpython-312.pyc and b/llm_ocr/__pycache__/__init__.cpython-312.pyc differ
|
|
|
llm_ocr/__pycache__/config.cpython-312.pyc
CHANGED
|
Binary files a/llm_ocr/__pycache__/config.cpython-312.pyc and b/llm_ocr/__pycache__/config.cpython-312.pyc differ
|
|
|
llm_ocr/__pycache__/document.cpython-312.pyc
CHANGED
|
Binary files a/llm_ocr/__pycache__/document.cpython-312.pyc and b/llm_ocr/__pycache__/document.cpython-312.pyc differ
|
|
|
llm_ocr/__pycache__/server.cpython-312.pyc
CHANGED
|
Binary files a/llm_ocr/__pycache__/server.cpython-312.pyc and b/llm_ocr/__pycache__/server.cpython-312.pyc differ
|
|
|
llm_ocr/__pycache__/stages.cpython-312.pyc
CHANGED
|
Binary files a/llm_ocr/__pycache__/stages.cpython-312.pyc and b/llm_ocr/__pycache__/stages.cpython-312.pyc differ
|
|
|
llm_ocr/__pycache__/storage.cpython-312.pyc
CHANGED
|
Binary files a/llm_ocr/__pycache__/storage.cpython-312.pyc and b/llm_ocr/__pycache__/storage.cpython-312.pyc differ
|
|
|
llm_ocr/cli.py
CHANGED
|
@@ -1,11 +1,18 @@
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from .stages import run_stage_assemble, run_stage_describe, run_stage_extract
|
| 10 |
|
| 11 |
LOGGER = logging.getLogger(__name__)
|
|
@@ -17,14 +24,27 @@ def _setup_logging() -> None:
|
|
| 17 |
try:
|
| 18 |
from rich.console import Console
|
| 19 |
from rich.logging import RichHandler
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
except ImportError:
|
| 24 |
-
logging.basicConfig(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
-
def _create_client(
|
|
|
|
|
|
|
| 28 |
"""Create DeepSeek client from environment."""
|
| 29 |
return DeepSeekClient(
|
| 30 |
base_url=base_url_from_env(),
|
|
@@ -62,6 +82,7 @@ def main() -> None:
|
|
| 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)
|
|
@@ -72,6 +93,7 @@ def main() -> None:
|
|
| 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)
|
|
|
|
| 1 |
"""CLI entrypoint for the DeepSeek OCR pipeline."""
|
| 2 |
+
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import logging
|
|
|
|
| 6 |
|
| 7 |
from .config import AssembleSettings, DescribeSettings, ExtractSettings, env
|
| 8 |
+
from .server import (
|
| 9 |
+
DeepSeekClient,
|
| 10 |
+
base_url_from_env,
|
| 11 |
+
launch_vllm,
|
| 12 |
+
should_launch_server,
|
| 13 |
+
shutdown_server,
|
| 14 |
+
wait_for_server,
|
| 15 |
+
)
|
| 16 |
from .stages import run_stage_assemble, run_stage_describe, run_stage_extract
|
| 17 |
|
| 18 |
LOGGER = logging.getLogger(__name__)
|
|
|
|
| 24 |
try:
|
| 25 |
from rich.console import Console
|
| 26 |
from rich.logging import RichHandler
|
| 27 |
+
|
| 28 |
+
console = Console(
|
| 29 |
+
force_terminal=env("FORCE_COLOR", "").lower() in {"1", "true"}
|
| 30 |
+
)
|
| 31 |
+
handler = RichHandler(
|
| 32 |
+
console=console, show_time=True, show_level=True, rich_tracebacks=True
|
| 33 |
+
)
|
| 34 |
+
logging.basicConfig(
|
| 35 |
+
level=level, format="%(message)s", handlers=[handler], force=True
|
| 36 |
+
)
|
| 37 |
except ImportError:
|
| 38 |
+
logging.basicConfig(
|
| 39 |
+
level=level,
|
| 40 |
+
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
| 41 |
+
force=True,
|
| 42 |
+
)
|
| 43 |
|
| 44 |
|
| 45 |
+
def _create_client(
|
| 46 |
+
max_tokens: int, temperature: float, inference_settings
|
| 47 |
+
) -> DeepSeekClient:
|
| 48 |
"""Create DeepSeek client from environment."""
|
| 49 |
return DeepSeekClient(
|
| 50 |
base_url=base_url_from_env(),
|
|
|
|
| 82 |
|
| 83 |
if stage == "extract":
|
| 84 |
from .config import InferenceSettings
|
| 85 |
+
|
| 86 |
inference = InferenceSettings.from_env("EXTRACT")
|
| 87 |
max_tokens = env("DOC_MAX_TOKENS", 2048, int)
|
| 88 |
temperature = env("DOC_TEMPERATURE", 0.0, float)
|
|
|
|
| 93 |
|
| 94 |
elif stage == "describe":
|
| 95 |
from .config import InferenceSettings
|
| 96 |
+
|
| 97 |
inference = InferenceSettings.from_env("DESCRIBE")
|
| 98 |
max_tokens = env("FIGURE_MAX_TOKENS", 512, int)
|
| 99 |
temperature = env("FIGURE_TEMPERATURE", 0.0, float)
|
llm_ocr/cloudrun_io.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Google Cloud Storage utilities for Cloud Run jobs."""
|
|
|
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import logging
|
|
@@ -15,6 +16,7 @@ LOGGER = logging.getLogger(__name__)
|
|
| 15 |
def get_gcs_client():
|
| 16 |
"""Get GCS client."""
|
| 17 |
from google.cloud import storage
|
|
|
|
| 18 |
return storage.Client()
|
| 19 |
|
| 20 |
|
|
@@ -34,34 +36,34 @@ def upload_files_to_gcs(
|
|
| 34 |
gcs_uri: str,
|
| 35 |
path_prefix: str = "",
|
| 36 |
) -> None:
|
| 37 |
-
"""Upload local
|
| 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 =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
| 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
|
|
@@ -69,7 +71,13 @@ def upload_files_to_gcs(
|
|
| 69 |
blob = bucket.blob(gcs_key)
|
| 70 |
blob.upload_from_filename(str(local_path))
|
| 71 |
except Exception as exc:
|
| 72 |
-
LOGGER.error(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
raise
|
| 74 |
|
| 75 |
|
|
@@ -78,18 +86,9 @@ def save_dataset_to_gcs(
|
|
| 78 |
gcs_uri: str,
|
| 79 |
name: str = "dataset",
|
| 80 |
) -> str:
|
| 81 |
-
"""Save HF dataset to GCS
|
| 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:
|
|
@@ -98,84 +97,57 @@ def save_dataset_to_gcs(
|
|
| 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(
|
| 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
|
| 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(
|
| 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
|
|
|
|
| 1 |
"""Google Cloud Storage utilities for Cloud Run jobs."""
|
| 2 |
+
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import logging
|
|
|
|
| 16 |
def get_gcs_client():
|
| 17 |
"""Get GCS client."""
|
| 18 |
from google.cloud import storage
|
| 19 |
+
|
| 20 |
return storage.Client()
|
| 21 |
|
| 22 |
|
|
|
|
| 36 |
gcs_uri: str,
|
| 37 |
path_prefix: str = "",
|
| 38 |
) -> None:
|
| 39 |
+
"""Upload local directory contents to GCS."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
if not gcs_uri:
|
| 41 |
LOGGER.info("No GCS URI provided; skipping upload.")
|
| 42 |
return
|
| 43 |
|
| 44 |
bucket_name, base_prefix = parse_gcs_uri(gcs_uri)
|
| 45 |
+
|
| 46 |
full_prefix = base_prefix.rstrip("/")
|
| 47 |
if path_prefix:
|
| 48 |
+
full_prefix = (
|
| 49 |
+
f"{full_prefix}/{path_prefix.strip('/')}"
|
| 50 |
+
if full_prefix
|
| 51 |
+
else path_prefix.strip("/")
|
| 52 |
+
)
|
| 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(
|
| 64 |
+
"Uploading %d files to gs://%s/%s", len(files), bucket_name, full_prefix
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
for local_path in files:
|
| 68 |
rel = local_path.relative_to(base).as_posix()
|
| 69 |
gcs_key = f"{full_prefix}/{rel}" if full_prefix else rel
|
|
|
|
| 71 |
blob = bucket.blob(gcs_key)
|
| 72 |
blob.upload_from_filename(str(local_path))
|
| 73 |
except Exception as exc:
|
| 74 |
+
LOGGER.error(
|
| 75 |
+
"Failed to upload %s to gs://%s/%s: %s",
|
| 76 |
+
local_path,
|
| 77 |
+
bucket_name,
|
| 78 |
+
gcs_key,
|
| 79 |
+
exc,
|
| 80 |
+
)
|
| 81 |
raise
|
| 82 |
|
| 83 |
|
|
|
|
| 86 |
gcs_uri: str,
|
| 87 |
name: str = "dataset",
|
| 88 |
) -> str:
|
| 89 |
+
"""Save HF dataset to GCS in Arrow format. Returns the GCS URI."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
from datasets import DatasetDict
|
| 91 |
+
|
| 92 |
# Handle DatasetDict by extracting the first split
|
| 93 |
if isinstance(dataset, DatasetDict):
|
| 94 |
if "train" in dataset:
|
|
|
|
| 97 |
split_name = list(dataset.keys())[0]
|
| 98 |
dataset = dataset[split_name]
|
| 99 |
LOGGER.info("Using split '%s' from DatasetDict", split_name)
|
| 100 |
+
|
| 101 |
bucket_name, prefix = parse_gcs_uri(gcs_uri)
|
| 102 |
full_prefix = prefix.rstrip("/")
|
| 103 |
+
|
| 104 |
# Save to local temp directory using Arrow format
|
| 105 |
local_dir = Path(f"/tmp/{name}_arrow_temp")
|
| 106 |
if local_dir.exists():
|
| 107 |
shutil.rmtree(local_dir)
|
| 108 |
+
|
| 109 |
LOGGER.info("Saving dataset to Arrow format...")
|
| 110 |
dataset.save_to_disk(str(local_dir))
|
| 111 |
+
|
| 112 |
# Upload entire directory to GCS
|
| 113 |
gcs_prefix = f"{full_prefix}/{name}" if full_prefix else name
|
| 114 |
+
upload_files_to_gcs(
|
| 115 |
+
output_dir=local_dir, gcs_uri=f"gs://{bucket_name}/{gcs_prefix}"
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
# Cleanup
|
| 119 |
shutil.rmtree(local_dir)
|
| 120 |
+
|
| 121 |
result_uri = f"gs://{bucket_name}/{gcs_prefix}"
|
| 122 |
LOGGER.info("Saved dataset to %s", result_uri)
|
| 123 |
return result_uri
|
| 124 |
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
def load_dataset_from_gcs(gcs_uri: str, split: str = "train") -> "Dataset":
|
| 127 |
+
"""Load HF dataset from GCS. Downloads locally to avoid gcsfs caching issues."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
from datasets import load_from_disk
|
| 129 |
import tempfile
|
| 130 |
+
|
| 131 |
LOGGER.info("Loading dataset from %s", gcs_uri)
|
| 132 |
+
|
| 133 |
# Parse GCS URI
|
| 134 |
bucket_name, prefix = parse_gcs_uri(gcs_uri)
|
| 135 |
+
|
| 136 |
# Download to local temp directory (bypasses gcsfs cache)
|
| 137 |
client = get_gcs_client()
|
| 138 |
bucket = client.bucket(bucket_name)
|
| 139 |
local_dir = tempfile.mkdtemp(prefix="gcs_dataset_")
|
| 140 |
+
|
| 141 |
blobs = list(bucket.list_blobs(prefix=f"{prefix}/"))
|
| 142 |
for blob in blobs:
|
| 143 |
+
filename = blob.name.split("/")[-1]
|
| 144 |
if filename: # Skip directory markers
|
| 145 |
local_path = f"{local_dir}/{filename}"
|
| 146 |
blob.download_to_filename(local_path)
|
| 147 |
+
|
| 148 |
LOGGER.info("Downloaded %d files to %s", len(blobs), local_dir)
|
| 149 |
+
|
| 150 |
# Load from local
|
| 151 |
ds = load_from_disk(local_dir)
|
| 152 |
+
|
| 153 |
return ds
|
llm_ocr/config.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Configuration dataclasses for pipeline stages."""
|
|
|
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import logging
|
|
@@ -27,6 +28,7 @@ def env(key: str, default: T = None, cast: Type[T] = str) -> T:
|
|
| 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]
|
|
@@ -36,6 +38,7 @@ class FigureMetadata:
|
|
| 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
|
|
@@ -58,6 +61,7 @@ class InferenceSettings:
|
|
| 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
|
|
@@ -78,6 +82,7 @@ class HubSettings:
|
|
| 78 |
@dataclass
|
| 79 |
class ExtractSettings:
|
| 80 |
"""Settings for the extract stage."""
|
|
|
|
| 81 |
dataset_name: str
|
| 82 |
dataset_config: str
|
| 83 |
dataset_split: str
|
|
@@ -100,7 +105,9 @@ class ExtractSettings:
|
|
| 100 |
dataset_split=env("DATASET_SPLIT", "train"),
|
| 101 |
output_dir=Path(env("OUTPUT_DIR", "./outputs/extract")),
|
| 102 |
client=client,
|
| 103 |
-
prompt=env(
|
|
|
|
|
|
|
| 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),
|
|
@@ -113,6 +120,7 @@ class ExtractSettings:
|
|
| 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
|
|
@@ -140,6 +148,7 @@ class DescribeSettings:
|
|
| 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 |
|
|
|
|
| 1 |
"""Configuration dataclasses for pipeline stages."""
|
| 2 |
+
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import logging
|
|
|
|
| 28 |
@dataclass
|
| 29 |
class FigureMetadata:
|
| 30 |
"""Metadata for an extracted figure (image stored in dataset, not as file)."""
|
| 31 |
+
|
| 32 |
figure_id: str
|
| 33 |
label: str
|
| 34 |
bounding_box_pixels: Dict[str, int]
|
|
|
|
| 38 |
@dataclass
|
| 39 |
class InferenceSettings:
|
| 40 |
"""Settings for batch inference."""
|
| 41 |
+
|
| 42 |
batch_size: int = 4
|
| 43 |
max_concurrency: int = 4
|
| 44 |
request_timeout: int = 120
|
|
|
|
| 61 |
@dataclass
|
| 62 |
class HubSettings:
|
| 63 |
"""Settings for HuggingFace Hub upload."""
|
| 64 |
+
|
| 65 |
repo_id: Optional[str] = None
|
| 66 |
path_in_repo: str = ""
|
| 67 |
branch: Optional[str] = None
|
|
|
|
| 82 |
@dataclass
|
| 83 |
class ExtractSettings:
|
| 84 |
"""Settings for the extract stage."""
|
| 85 |
+
|
| 86 |
dataset_name: str
|
| 87 |
dataset_config: str
|
| 88 |
dataset_split: str
|
|
|
|
| 105 |
dataset_split=env("DATASET_SPLIT", "train"),
|
| 106 |
output_dir=Path(env("OUTPUT_DIR", "./outputs/extract")),
|
| 107 |
client=client,
|
| 108 |
+
prompt=env(
|
| 109 |
+
"DOC_PROMPT", "<image>\n<|grounding|>Convert this document to Markdown."
|
| 110 |
+
),
|
| 111 |
max_tokens=env("DOC_MAX_TOKENS", 2048, int),
|
| 112 |
temperature=env("DOC_TEMPERATURE", 0.0, float),
|
| 113 |
max_samples=env("MAX_SAMPLES", None, int),
|
|
|
|
| 120 |
@dataclass
|
| 121 |
class DescribeSettings:
|
| 122 |
"""Settings for the describe stage."""
|
| 123 |
+
|
| 124 |
output_dir: Path
|
| 125 |
client: Any # DeepSeekClient
|
| 126 |
source_repo_id: Optional[str] = None
|
|
|
|
| 148 |
@dataclass
|
| 149 |
class AssembleSettings:
|
| 150 |
"""Settings for the assemble stage."""
|
| 151 |
+
|
| 152 |
source_repo_id: Optional[str] = None
|
| 153 |
hub: HubSettings = field(default_factory=HubSettings)
|
| 154 |
|
llm_ocr/document.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Document processing: markdown extraction, figure handling, and caption enrichment."""
|
|
|
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import ast
|
|
@@ -47,12 +48,14 @@ def extract_grounding_blocks(text: str) -> List[Dict[str, Any]]:
|
|
| 47 |
coordinates = ast.literal_eval(coords_text)
|
| 48 |
except Exception:
|
| 49 |
coordinates = None
|
| 50 |
-
matches.append(
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
| 56 |
return matches
|
| 57 |
|
| 58 |
|
|
@@ -89,10 +92,13 @@ def crop_figure(
|
|
| 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 |
-
|
| 96 |
"""
|
| 97 |
x1, y1, x2, y2 = pixel_box
|
| 98 |
crop = image.crop((x1, y1, x2, y2)).copy()
|
|
@@ -104,7 +110,7 @@ def crop_figure(
|
|
| 104 |
label=label,
|
| 105 |
bounding_box_pixels={"x1": x1, "y1": y1, "x2": x2, "y2": y2},
|
| 106 |
)
|
| 107 |
-
|
| 108 |
return metadata, crop
|
| 109 |
|
| 110 |
|
|
@@ -126,14 +132,10 @@ def build_document_markdown(
|
|
| 126 |
response_text: str,
|
| 127 |
sample_id: str,
|
| 128 |
) -> Tuple[str, List[FigureMetadata], List[Image.Image], Image.Image]:
|
| 129 |
-
"""
|
| 130 |
-
|
| 131 |
-
|
| 132 |
Returns:
|
| 133 |
-
|
| 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]] = []
|
|
@@ -154,7 +156,11 @@ def build_document_markdown(
|
|
| 154 |
start, end = block["span"]
|
| 155 |
|
| 156 |
# Random color for this block
|
| 157 |
-
color = (
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
color_alpha = color + (20,)
|
| 159 |
|
| 160 |
# Convert normalized coords to pixels
|
|
@@ -177,10 +183,13 @@ def build_document_markdown(
|
|
| 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 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
| 184 |
figure_index += 1
|
| 185 |
else:
|
| 186 |
replacements.append((start, end, ""))
|
|
@@ -194,7 +203,9 @@ def build_document_markdown(
|
|
| 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(
|
|
|
|
|
|
|
| 198 |
draw.text((text_x, text_y), label, font=font, fill=color)
|
| 199 |
|
| 200 |
img_draw.paste(overlay, (0, 0), overlay)
|
|
@@ -217,27 +228,20 @@ def enrich_markdown_with_captions(
|
|
| 217 |
markdown: str,
|
| 218 |
description_map: Dict[str, Dict[str, Any]],
|
| 219 |
) -> str:
|
| 220 |
-
"""Add figure captions to markdown
|
| 221 |
-
|
| 222 |
-
Handles both new format  and
|
| 223 |
-
legacy format .
|
| 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)
|
|
@@ -248,10 +252,10 @@ def enrich_markdown_with_captions(
|
|
| 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""
|
| 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"
|
|
@@ -266,62 +270,42 @@ def render_markdown_with_images(
|
|
| 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  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""
|
| 309 |
-
|
| 310 |
return FIGURE_MARKDOWN_PATTERN.sub(replace, markdown)
|
| 311 |
|
| 312 |
|
| 313 |
def render_sample_markdown(sample: Dict[str, Any]) -> str:
|
| 314 |
-
"""
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 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 = []
|
|
@@ -330,9 +314,9 @@ def render_sample_markdown(sample: Dict[str, Any]) -> 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,
|
|
@@ -341,65 +325,49 @@ def render_sample_markdown(sample: Dict[str, Any]) -> str:
|
|
| 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 |
def display_samples(dataset, num_samples: int = 2) -> None:
|
| 361 |
-
"""
|
| 362 |
-
Display a few samples from a dataset with images and figure descriptions.
|
| 363 |
-
|
| 364 |
-
Shows source images, markdown previews, extracted figures with their
|
| 365 |
-
descriptions from metadata.
|
| 366 |
-
|
| 367 |
-
Args:
|
| 368 |
-
dataset: A Hugging Face dataset or list of samples
|
| 369 |
-
num_samples: Number of samples to display (default 2)
|
| 370 |
-
"""
|
| 371 |
from IPython.display import display
|
| 372 |
-
|
| 373 |
print(f"Dataset: {len(dataset)} samples")
|
| 374 |
print(f"Columns: {list(dataset.column_names)}")
|
| 375 |
print()
|
| 376 |
-
|
| 377 |
for i in range(min(num_samples, len(dataset))):
|
| 378 |
sample = dataset[i]
|
| 379 |
print(f"=== Sample {i}: {sample.get('sample_id', i)} ===")
|
| 380 |
-
|
| 381 |
# Show source image
|
| 382 |
-
if sample.get(
|
| 383 |
print("Source image:")
|
| 384 |
-
img = sample[
|
| 385 |
img.thumbnail((500, 500)) # Resize to max 500px
|
| 386 |
display(img)
|
| 387 |
-
|
| 388 |
# Show markdown preview
|
| 389 |
-
md = sample.get(
|
| 390 |
if md:
|
| 391 |
print(f"\nMarkdown preview ({len(md)} chars):")
|
| 392 |
-
print(md[:500] +
|
| 393 |
-
|
| 394 |
# Show final markdown if available
|
| 395 |
-
final_md = sample.get(
|
|
|
|
|
|
|
| 396 |
if final_md:
|
| 397 |
print(f"\nFinal markdown preview ({len(final_md)} chars):")
|
| 398 |
-
print(final_md[:500] +
|
| 399 |
-
|
| 400 |
# Show figures and their descriptions
|
| 401 |
-
figures = sample.get(
|
| 402 |
-
metadata = sample.get(
|
| 403 |
if figures:
|
| 404 |
print(f"\nExtracted figures: {len(figures)}")
|
| 405 |
for j, fig in enumerate(figures[:2]): # Show max 2 figures
|
|
@@ -408,8 +376,12 @@ def display_samples(dataset, num_samples: int = 2) -> None:
|
|
| 408 |
# Show figure description if available
|
| 409 |
if j < len(metadata):
|
| 410 |
try:
|
| 411 |
-
meta =
|
| 412 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
print(f" 📝 Description: {meta['description'][:200]}...")
|
| 414 |
except Exception:
|
| 415 |
pass
|
|
|
|
| 1 |
"""Document processing: markdown extraction, figure handling, and caption enrichment."""
|
| 2 |
+
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import ast
|
|
|
|
| 48 |
coordinates = ast.literal_eval(coords_text)
|
| 49 |
except Exception:
|
| 50 |
coordinates = None
|
| 51 |
+
matches.append(
|
| 52 |
+
{
|
| 53 |
+
"label": label,
|
| 54 |
+
"coordinates": coordinates,
|
| 55 |
+
"raw": match.group(0),
|
| 56 |
+
"span": match.span(),
|
| 57 |
+
}
|
| 58 |
+
)
|
| 59 |
return matches
|
| 60 |
|
| 61 |
|
|
|
|
| 92 |
pixel_box: List[int],
|
| 93 |
label: str,
|
| 94 |
) -> Tuple[FigureMetadata, Image.Image]:
|
| 95 |
+
"""Crop a figure region from the source image.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
pixel_box: [x1, y1, x2, y2] bounding box in pixels
|
| 99 |
+
|
| 100 |
Returns:
|
| 101 |
+
(metadata, cropped_image) tuple for embedding in dataset
|
| 102 |
"""
|
| 103 |
x1, y1, x2, y2 = pixel_box
|
| 104 |
crop = image.crop((x1, y1, x2, y2)).copy()
|
|
|
|
| 110 |
label=label,
|
| 111 |
bounding_box_pixels={"x1": x1, "y1": y1, "x2": x2, "y2": y2},
|
| 112 |
)
|
| 113 |
+
|
| 114 |
return metadata, crop
|
| 115 |
|
| 116 |
|
|
|
|
| 132 |
response_text: str,
|
| 133 |
sample_id: str,
|
| 134 |
) -> Tuple[str, List[FigureMetadata], List[Image.Image], Image.Image]:
|
| 135 |
+
"""Process model response to extract markdown and figures.
|
| 136 |
+
|
|
|
|
| 137 |
Returns:
|
| 138 |
+
(markdown, figure_metadata, figure_images, annotated_image) tuple
|
|
|
|
|
|
|
|
|
|
| 139 |
"""
|
| 140 |
blocks = extract_grounding_blocks(response_text)
|
| 141 |
replacements: List[Tuple[int, int, str]] = []
|
|
|
|
| 156 |
start, end = block["span"]
|
| 157 |
|
| 158 |
# Random color for this block
|
| 159 |
+
color = (
|
| 160 |
+
np.random.randint(0, 200),
|
| 161 |
+
np.random.randint(0, 200),
|
| 162 |
+
np.random.randint(0, 255),
|
| 163 |
+
)
|
| 164 |
color_alpha = color + (20,)
|
| 165 |
|
| 166 |
# Convert normalized coords to pixels
|
|
|
|
| 183 |
figures.append(metadata)
|
| 184 |
figure_images.append(crop)
|
| 185 |
# Use figure:{id} URI format - clearly an identifier, not a file path
|
| 186 |
+
replacements.append(
|
| 187 |
+
(
|
| 188 |
+
start,
|
| 189 |
+
end,
|
| 190 |
+
f"",
|
| 191 |
+
)
|
| 192 |
+
)
|
| 193 |
figure_index += 1
|
| 194 |
else:
|
| 195 |
replacements.append((start, end, ""))
|
|
|
|
| 203 |
text_x, text_y = x1, max(0, y1 - 15)
|
| 204 |
text_bbox = draw.textbbox((0, 0), label, font=font)
|
| 205 |
text_w, text_h = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
|
| 206 |
+
draw.rectangle(
|
| 207 |
+
[text_x, text_y, text_x + text_w, text_y + text_h], fill=(255, 255, 255, 30)
|
| 208 |
+
)
|
| 209 |
draw.text((text_x, text_y), label, font=font, fill=color)
|
| 210 |
|
| 211 |
img_draw.paste(overlay, (0, 0), overlay)
|
|
|
|
| 228 |
markdown: str,
|
| 229 |
description_map: Dict[str, Dict[str, Any]],
|
| 230 |
) -> str:
|
| 231 |
+
"""Add figure captions to markdown. Alt text is truncated; full description below."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
used: set[str] = set()
|
| 233 |
|
| 234 |
def replace(match: re.Match[str]) -> str:
|
| 235 |
alt_text = match.group("figure_id").strip()
|
| 236 |
path = match.group("path").strip()
|
| 237 |
+
|
| 238 |
# Extract figure_id from figure:{id} URI or from alt text
|
| 239 |
if path.startswith("figure:"):
|
| 240 |
figure_id = path[7:] # Remove "figure:" prefix
|
| 241 |
else:
|
| 242 |
# Legacy format - figure_id is in alt text after "Figure "
|
| 243 |
figure_id = alt_text.replace("Figure ", "").split(":")[0].strip()
|
| 244 |
+
|
| 245 |
entry = description_map.get(figure_id)
|
| 246 |
if not entry:
|
| 247 |
return match.group(0)
|
|
|
|
| 252 |
|
| 253 |
# Alt text: short summary (first sentence, max 120 chars)
|
| 254 |
short_alt = _truncate_for_alt(description)
|
| 255 |
+
|
| 256 |
# Image tag with short alt text
|
| 257 |
rendered = f""
|
| 258 |
+
|
| 259 |
# Add full caption below (only once per figure)
|
| 260 |
if figure_id not in used:
|
| 261 |
rendered += f"\n\n*Figure {figure_id}: {description}*\n"
|
|
|
|
| 270 |
figure_images: List[Image.Image],
|
| 271 |
figure_metadata: List[Dict[str, Any]],
|
| 272 |
) -> str:
|
| 273 |
+
"""Replace figure:{id} URIs in markdown with base64-encoded images."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
# Build figure_id -> image mapping
|
| 275 |
id_to_image: Dict[str, Image.Image] = {}
|
| 276 |
for i, meta in enumerate(figure_metadata):
|
| 277 |
fig_id = meta.get("figure_id", "")
|
| 278 |
if fig_id and i < len(figure_images) and figure_images[i] is not None:
|
| 279 |
id_to_image[fig_id] = figure_images[i]
|
| 280 |
+
|
| 281 |
def replace(match: re.Match[str]) -> str:
|
| 282 |
alt_text = match.group("figure_id").strip()
|
| 283 |
path = match.group("path").strip()
|
| 284 |
+
|
| 285 |
# Extract figure_id from figure:{id} URI or use alt_text as fallback
|
| 286 |
if path.startswith("figure:"):
|
| 287 |
figure_id = path[7:] # Remove "figure:" prefix
|
| 288 |
else:
|
| 289 |
# Legacy path format - extract figure_id from alt_text
|
| 290 |
figure_id = alt_text.replace("Figure ", "").split(":")[0].strip()
|
| 291 |
+
|
| 292 |
img = id_to_image.get(figure_id)
|
| 293 |
if img is None:
|
| 294 |
return match.group(0) # Keep original if image not found
|
| 295 |
+
|
| 296 |
# Embed as base64 data URI
|
| 297 |
data_uri = f"data:image/png;base64,{encode_image(img)}"
|
| 298 |
return f""
|
| 299 |
+
|
| 300 |
return FIGURE_MARKDOWN_PATTERN.sub(replace, markdown)
|
| 301 |
|
| 302 |
|
| 303 |
def render_sample_markdown(sample: Dict[str, Any]) -> str:
|
| 304 |
+
"""Render dataset sample's markdown with embedded base64 images."""
|
| 305 |
+
markdown = (
|
| 306 |
+
sample.get("document_final_markdown") or sample.get("document_markdown") or ""
|
| 307 |
+
)
|
| 308 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
# Parse metadata
|
| 310 |
raw_metadata = sample.get("extracted_figures_metadata") or []
|
| 311 |
metadata = []
|
|
|
|
| 314 |
metadata.append(json.loads(m))
|
| 315 |
else:
|
| 316 |
metadata.append(m)
|
| 317 |
+
|
| 318 |
images = sample.get("extracted_figures") or []
|
| 319 |
+
|
| 320 |
return render_markdown_with_images(
|
| 321 |
markdown=markdown,
|
| 322 |
figure_images=images,
|
|
|
|
| 325 |
|
| 326 |
|
| 327 |
def display_markdown(sample: Dict[str, Any]) -> None:
|
| 328 |
+
"""Display sample's markdown with embedded images in Jupyter."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
from IPython.display import display, Markdown
|
| 330 |
+
|
| 331 |
rendered = render_sample_markdown(sample)
|
| 332 |
display(Markdown(rendered))
|
| 333 |
|
| 334 |
|
| 335 |
def display_samples(dataset, num_samples: int = 2) -> None:
|
| 336 |
+
"""Display samples with source images, markdown, and figure descriptions."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
from IPython.display import display
|
| 338 |
+
|
| 339 |
print(f"Dataset: {len(dataset)} samples")
|
| 340 |
print(f"Columns: {list(dataset.column_names)}")
|
| 341 |
print()
|
| 342 |
+
|
| 343 |
for i in range(min(num_samples, len(dataset))):
|
| 344 |
sample = dataset[i]
|
| 345 |
print(f"=== Sample {i}: {sample.get('sample_id', i)} ===")
|
| 346 |
+
|
| 347 |
# Show source image
|
| 348 |
+
if sample.get("source_image"):
|
| 349 |
print("Source image:")
|
| 350 |
+
img = sample["source_image"]
|
| 351 |
img.thumbnail((500, 500)) # Resize to max 500px
|
| 352 |
display(img)
|
| 353 |
+
|
| 354 |
# Show markdown preview
|
| 355 |
+
md = sample.get("document_markdown") or sample.get("document_markdown_text", "")
|
| 356 |
if md:
|
| 357 |
print(f"\nMarkdown preview ({len(md)} chars):")
|
| 358 |
+
print(md[:500] + "..." if len(md) > 500 else md)
|
| 359 |
+
|
| 360 |
# Show final markdown if available
|
| 361 |
+
final_md = sample.get("document_final_markdown") or sample.get(
|
| 362 |
+
"document_final_markdown_text", ""
|
| 363 |
+
)
|
| 364 |
if final_md:
|
| 365 |
print(f"\nFinal markdown preview ({len(final_md)} chars):")
|
| 366 |
+
print(final_md[:500] + "..." if len(final_md) > 500 else final_md)
|
| 367 |
+
|
| 368 |
# Show figures and their descriptions
|
| 369 |
+
figures = sample.get("extracted_figures", [])
|
| 370 |
+
metadata = sample.get("extracted_figures_metadata", [])
|
| 371 |
if figures:
|
| 372 |
print(f"\nExtracted figures: {len(figures)}")
|
| 373 |
for j, fig in enumerate(figures[:2]): # Show max 2 figures
|
|
|
|
| 376 |
# Show figure description if available
|
| 377 |
if j < len(metadata):
|
| 378 |
try:
|
| 379 |
+
meta = (
|
| 380 |
+
json.loads(metadata[j])
|
| 381 |
+
if isinstance(metadata[j], str)
|
| 382 |
+
else metadata[j]
|
| 383 |
+
)
|
| 384 |
+
if meta.get("description"):
|
| 385 |
print(f" 📝 Description: {meta['description'][:200]}...")
|
| 386 |
except Exception:
|
| 387 |
pass
|
llm_ocr/server.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""vLLM server management and async inference client."""
|
|
|
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import asyncio
|
|
@@ -8,13 +9,16 @@ 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 |
|
|
@@ -35,20 +39,31 @@ def launch_vllm() -> subprocess.Popen:
|
|
| 35 |
host = os.environ.get("HOST", "0.0.0.0")
|
| 36 |
|
| 37 |
cmd: List[str] = [
|
| 38 |
-
"vllm",
|
| 39 |
-
"
|
| 40 |
-
"--
|
| 41 |
-
|
| 42 |
-
"--
|
| 43 |
-
|
| 44 |
-
"--
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
"--trust-remote-code",
|
| 46 |
"--enable-chunked-prefill",
|
| 47 |
"--no-enable-prefix-caching",
|
| 48 |
-
"--mm-processor-cache-gb",
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
"LOGITS_PROCESSORS",
|
| 51 |
-
"vllm.model_executor.models.deepseek_ocr:NGramPerReqLogitsProcessor"
|
| 52 |
),
|
| 53 |
]
|
| 54 |
|
|
@@ -57,13 +72,17 @@ def launch_vllm() -> subprocess.Popen:
|
|
| 57 |
cmd.extend(extra_args.split())
|
| 58 |
|
| 59 |
LOGGER.info("Launching vLLM server: %s", " ".join(cmd))
|
| 60 |
-
process = subprocess.Popen(
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
| 67 |
t.start()
|
| 68 |
threads.append(t)
|
| 69 |
|
|
@@ -96,10 +115,10 @@ def wait_for_server(url: str, timeout_s: int = None, interval_s: int = 5) -> boo
|
|
| 96 |
"""Wait for server health endpoint to respond."""
|
| 97 |
if timeout_s is None:
|
| 98 |
timeout_s = int(os.environ.get("VLLM_STARTUP_TIMEOUT", "600")) # 10 min default
|
| 99 |
-
|
| 100 |
start_time = time.time()
|
| 101 |
LOGGER.info("⏳ Waiting for vLLM server to start...")
|
| 102 |
-
|
| 103 |
deadline = time.time() + timeout_s
|
| 104 |
while time.time() < deadline:
|
| 105 |
try:
|
|
@@ -110,7 +129,7 @@ def wait_for_server(url: str, timeout_s: int = None, interval_s: int = 5) -> boo
|
|
| 110 |
except Exception:
|
| 111 |
pass
|
| 112 |
time.sleep(interval_s)
|
| 113 |
-
|
| 114 |
elapsed = time.time() - start_time
|
| 115 |
LOGGER.error("❌ vLLM server failed to start after %s", _format_duration(elapsed))
|
| 116 |
return False
|
|
@@ -137,25 +156,36 @@ def _prepare_payload(
|
|
| 137 |
"""Prepare OpenAI-compatible chat completion payload."""
|
| 138 |
return {
|
| 139 |
"model": model_name,
|
| 140 |
-
"messages": [
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
"max_tokens": max_tokens,
|
| 148 |
"temperature": temperature,
|
| 149 |
"extra_body": {
|
| 150 |
"skip_special_tokens": False,
|
| 151 |
-
"vllm_xargs": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
},
|
| 153 |
}
|
| 154 |
|
| 155 |
|
| 156 |
class DeepSeekClient:
|
| 157 |
"""Async batch inference client for DeepSeek OCR via vLLM."""
|
| 158 |
-
|
| 159 |
def __init__(
|
| 160 |
self,
|
| 161 |
base_url: str,
|
|
@@ -198,27 +228,42 @@ class DeepSeekClient:
|
|
| 198 |
return getattr(response.choices[0].message, "content", "") or ""
|
| 199 |
|
| 200 |
def infer(self, requests_data: Sequence[Dict[str, Any]]) -> List[str]:
|
| 201 |
-
"""Run batch inference synchronously.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
if not requests_data:
|
| 203 |
return []
|
| 204 |
|
| 205 |
payloads = []
|
| 206 |
timeouts = []
|
| 207 |
for req in requests_data:
|
| 208 |
-
payloads.append(
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
| 215 |
timeouts.append(req.get("request_timeout") or self.default_request_timeout)
|
| 216 |
|
| 217 |
return self._run_async(self._async_infer_batch(payloads, timeouts))
|
| 218 |
|
| 219 |
-
async def _async_infer_batch(
|
|
|
|
|
|
|
| 220 |
"""Run batch of async completions concurrently."""
|
| 221 |
-
tasks = [
|
|
|
|
|
|
|
|
|
|
| 222 |
return await asyncio.gather(*tasks)
|
| 223 |
|
| 224 |
@staticmethod
|
|
|
|
| 1 |
"""vLLM server management and async inference client."""
|
| 2 |
+
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import asyncio
|
|
|
|
| 9 |
import subprocess
|
| 10 |
import threading
|
| 11 |
import time
|
| 12 |
+
from typing import TYPE_CHECKING, Any, Awaitable, Dict, List, Sequence
|
| 13 |
|
| 14 |
import requests
|
| 15 |
from openai import AsyncOpenAI
|
| 16 |
|
| 17 |
from .document import encode_image
|
| 18 |
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from PIL import Image
|
| 21 |
+
|
| 22 |
LOGGER = logging.getLogger(__name__)
|
| 23 |
|
| 24 |
|
|
|
|
| 39 |
host = os.environ.get("HOST", "0.0.0.0")
|
| 40 |
|
| 41 |
cmd: List[str] = [
|
| 42 |
+
"vllm",
|
| 43 |
+
"serve",
|
| 44 |
+
"--model",
|
| 45 |
+
model_id,
|
| 46 |
+
"--served-model-name",
|
| 47 |
+
served_name,
|
| 48 |
+
"--tensor-parallel-size",
|
| 49 |
+
os.environ.get("TENSOR_PARALLEL_SIZE", "1"),
|
| 50 |
+
"--max-model-len",
|
| 51 |
+
os.environ.get("MAX_MODEL_LEN", "4096"),
|
| 52 |
+
"--gpu-memory-utilization",
|
| 53 |
+
os.environ.get("GPU_MEMORY_UTILIZATION", "0.90"),
|
| 54 |
+
"--port",
|
| 55 |
+
port,
|
| 56 |
+
"--host",
|
| 57 |
+
host,
|
| 58 |
"--trust-remote-code",
|
| 59 |
"--enable-chunked-prefill",
|
| 60 |
"--no-enable-prefix-caching",
|
| 61 |
+
"--mm-processor-cache-gb",
|
| 62 |
+
os.environ.get("MM_PROCESSOR_CACHE_GB", "0"),
|
| 63 |
+
"--logits-processors",
|
| 64 |
+
os.environ.get(
|
| 65 |
"LOGITS_PROCESSORS",
|
| 66 |
+
"vllm.model_executor.models.deepseek_ocr:NGramPerReqLogitsProcessor",
|
| 67 |
),
|
| 68 |
]
|
| 69 |
|
|
|
|
| 72 |
cmd.extend(extra_args.split())
|
| 73 |
|
| 74 |
LOGGER.info("Launching vLLM server: %s", " ".join(cmd))
|
| 75 |
+
process = subprocess.Popen(
|
| 76 |
+
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1
|
| 77 |
+
)
|
| 78 |
|
| 79 |
# Start output streaming threads
|
| 80 |
threads = []
|
| 81 |
for name, pipe in [("STDOUT", process.stdout), ("STDERR", process.stderr)]:
|
| 82 |
if pipe:
|
| 83 |
+
t = threading.Thread(
|
| 84 |
+
target=_stream_output, args=(pipe, f"vLLM {name}"), daemon=True
|
| 85 |
+
)
|
| 86 |
t.start()
|
| 87 |
threads.append(t)
|
| 88 |
|
|
|
|
| 115 |
"""Wait for server health endpoint to respond."""
|
| 116 |
if timeout_s is None:
|
| 117 |
timeout_s = int(os.environ.get("VLLM_STARTUP_TIMEOUT", "600")) # 10 min default
|
| 118 |
+
|
| 119 |
start_time = time.time()
|
| 120 |
LOGGER.info("⏳ Waiting for vLLM server to start...")
|
| 121 |
+
|
| 122 |
deadline = time.time() + timeout_s
|
| 123 |
while time.time() < deadline:
|
| 124 |
try:
|
|
|
|
| 129 |
except Exception:
|
| 130 |
pass
|
| 131 |
time.sleep(interval_s)
|
| 132 |
+
|
| 133 |
elapsed = time.time() - start_time
|
| 134 |
LOGGER.error("❌ vLLM server failed to start after %s", _format_duration(elapsed))
|
| 135 |
return False
|
|
|
|
| 156 |
"""Prepare OpenAI-compatible chat completion payload."""
|
| 157 |
return {
|
| 158 |
"model": model_name,
|
| 159 |
+
"messages": [
|
| 160 |
+
{
|
| 161 |
+
"role": "user",
|
| 162 |
+
"content": [
|
| 163 |
+
{"type": "text", "text": prompt},
|
| 164 |
+
{
|
| 165 |
+
"type": "image_url",
|
| 166 |
+
"image_url": {
|
| 167 |
+
"url": f"data:image/png;base64,{encode_image(image)}"
|
| 168 |
+
},
|
| 169 |
+
},
|
| 170 |
+
],
|
| 171 |
+
}
|
| 172 |
+
],
|
| 173 |
"max_tokens": max_tokens,
|
| 174 |
"temperature": temperature,
|
| 175 |
"extra_body": {
|
| 176 |
"skip_special_tokens": False,
|
| 177 |
+
"vllm_xargs": {
|
| 178 |
+
"ngram_size": 30,
|
| 179 |
+
"window_size": 90,
|
| 180 |
+
"whitelist_token_ids": "[128821,128822]",
|
| 181 |
+
},
|
| 182 |
},
|
| 183 |
}
|
| 184 |
|
| 185 |
|
| 186 |
class DeepSeekClient:
|
| 187 |
"""Async batch inference client for DeepSeek OCR via vLLM."""
|
| 188 |
+
|
| 189 |
def __init__(
|
| 190 |
self,
|
| 191 |
base_url: str,
|
|
|
|
| 228 |
return getattr(response.choices[0].message, "content", "") or ""
|
| 229 |
|
| 230 |
def infer(self, requests_data: Sequence[Dict[str, Any]]) -> List[str]:
|
| 231 |
+
"""Run batch inference synchronously.
|
| 232 |
+
|
| 233 |
+
Args:
|
| 234 |
+
requests_data: List of dicts with keys: image (PIL.Image), prompt (str),
|
| 235 |
+
optional: max_tokens, temperature, request_timeout
|
| 236 |
+
|
| 237 |
+
Returns:
|
| 238 |
+
List of response strings, one per request
|
| 239 |
+
"""
|
| 240 |
if not requests_data:
|
| 241 |
return []
|
| 242 |
|
| 243 |
payloads = []
|
| 244 |
timeouts = []
|
| 245 |
for req in requests_data:
|
| 246 |
+
payloads.append(
|
| 247 |
+
_prepare_payload(
|
| 248 |
+
image=req["image"],
|
| 249 |
+
model_name=self.model_name,
|
| 250 |
+
prompt=req.get("prompt", ""),
|
| 251 |
+
max_tokens=req.get("max_tokens", self.default_max_tokens),
|
| 252 |
+
temperature=req.get("temperature", self.default_temperature),
|
| 253 |
+
)
|
| 254 |
+
)
|
| 255 |
timeouts.append(req.get("request_timeout") or self.default_request_timeout)
|
| 256 |
|
| 257 |
return self._run_async(self._async_infer_batch(payloads, timeouts))
|
| 258 |
|
| 259 |
+
async def _async_infer_batch(
|
| 260 |
+
self, payloads: Sequence[Dict[str, Any]], timeouts: Sequence[int]
|
| 261 |
+
) -> List[str]:
|
| 262 |
"""Run batch of async completions concurrently."""
|
| 263 |
+
tasks = [
|
| 264 |
+
asyncio.create_task(self._async_completion(p, t))
|
| 265 |
+
for p, t in zip(payloads, timeouts)
|
| 266 |
+
]
|
| 267 |
return await asyncio.gather(*tasks)
|
| 268 |
|
| 269 |
@staticmethod
|
llm_ocr/sm_io.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Amazon S3 utilities for SageMaker jobs."""
|
|
|
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import logging
|
|
@@ -40,40 +41,40 @@ def upload_files_to_s3(
|
|
| 40 |
s3_uri: str,
|
| 41 |
path_prefix: str = "",
|
| 42 |
) -> None:
|
| 43 |
-
"""Upload local
|
| 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 =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
| 77 |
raise
|
| 78 |
|
| 79 |
|
|
@@ -82,18 +83,9 @@ def save_dataset_to_s3(
|
|
| 82 |
s3_uri: str,
|
| 83 |
name: str = "dataset",
|
| 84 |
) -> str:
|
| 85 |
-
"""Save HF dataset to S3
|
| 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:
|
|
@@ -102,88 +94,59 @@ def save_dataset_to_s3(
|
|
| 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
|
| 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(
|
| 174 |
download_count = 0
|
| 175 |
for page in paginator.paginate(Bucket=bucket_name, Prefix=f"{prefix}/"):
|
| 176 |
-
for obj in page.get(
|
| 177 |
-
key = obj[
|
| 178 |
-
filename = key.split(
|
| 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
|
|
|
|
| 1 |
"""Amazon S3 utilities for SageMaker jobs."""
|
| 2 |
+
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import logging
|
|
|
|
| 41 |
s3_uri: str,
|
| 42 |
path_prefix: str = "",
|
| 43 |
) -> None:
|
| 44 |
+
"""Upload local directory contents to S3."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
if not s3_uri:
|
| 46 |
LOGGER.info("No S3 URI provided; skipping upload.")
|
| 47 |
return
|
| 48 |
|
| 49 |
bucket, base_prefix = parse_s3_uri(s3_uri)
|
| 50 |
+
|
| 51 |
full_prefix = base_prefix.rstrip("/")
|
| 52 |
if path_prefix:
|
| 53 |
+
full_prefix = (
|
| 54 |
+
f"{full_prefix}/{path_prefix.strip('/')}"
|
| 55 |
+
if full_prefix
|
| 56 |
+
else path_prefix.strip("/")
|
| 57 |
+
)
|
| 58 |
|
| 59 |
s3 = get_s3_client()
|
| 60 |
base = output_dir.resolve()
|
| 61 |
+
|
| 62 |
files = sorted(p for p in base.rglob("*") if p.is_file())
|
| 63 |
if not files:
|
| 64 |
LOGGER.info("Nothing to upload from %s", output_dir)
|
| 65 |
return
|
| 66 |
|
| 67 |
LOGGER.info("Uploading %d files to s3://%s/%s", len(files), bucket, full_prefix)
|
| 68 |
+
|
| 69 |
for local_path in files:
|
| 70 |
rel = local_path.relative_to(base).as_posix()
|
| 71 |
s3_key = f"{full_prefix}/{rel}" if full_prefix else rel
|
| 72 |
try:
|
| 73 |
s3.upload_file(str(local_path), bucket, s3_key)
|
| 74 |
except Exception as exc:
|
| 75 |
+
LOGGER.error(
|
| 76 |
+
"Failed to upload %s to s3://%s/%s: %s", local_path, bucket, s3_key, exc
|
| 77 |
+
)
|
| 78 |
raise
|
| 79 |
|
| 80 |
|
|
|
|
| 83 |
s3_uri: str,
|
| 84 |
name: str = "dataset",
|
| 85 |
) -> str:
|
| 86 |
+
"""Save HF dataset to S3 in Arrow format. Returns the S3 URI."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
from datasets import DatasetDict
|
| 88 |
+
|
| 89 |
# Handle DatasetDict by extracting the first split
|
| 90 |
if isinstance(dataset, DatasetDict):
|
| 91 |
if "train" in dataset:
|
|
|
|
| 94 |
split_name = list(dataset.keys())[0]
|
| 95 |
dataset = dataset[split_name]
|
| 96 |
LOGGER.info("Using split '%s' from DatasetDict", split_name)
|
| 97 |
+
|
| 98 |
bucket, prefix = parse_s3_uri(s3_uri)
|
| 99 |
full_prefix = prefix.rstrip("/")
|
| 100 |
+
|
| 101 |
# Save to local temp directory using Arrow format
|
| 102 |
local_dir = Path(f"/tmp/{name}_arrow_temp")
|
| 103 |
if local_dir.exists():
|
| 104 |
shutil.rmtree(local_dir)
|
| 105 |
+
|
| 106 |
LOGGER.info("Saving dataset to Arrow format...")
|
| 107 |
dataset.save_to_disk(str(local_dir))
|
| 108 |
+
|
| 109 |
# Upload entire directory to S3
|
| 110 |
s3_prefix = f"{full_prefix}/{name}" if full_prefix else name
|
| 111 |
upload_files_to_s3(output_dir=local_dir, s3_uri=f"s3://{bucket}/{s3_prefix}")
|
| 112 |
+
|
| 113 |
# Cleanup
|
| 114 |
shutil.rmtree(local_dir)
|
| 115 |
+
|
| 116 |
result_uri = f"s3://{bucket}/{s3_prefix}"
|
| 117 |
LOGGER.info("Saved dataset to %s", result_uri)
|
| 118 |
return result_uri
|
| 119 |
|
| 120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
def load_dataset_from_s3(s3_uri: str, split: str = "train") -> "Dataset":
|
| 122 |
+
"""Load HF dataset from S3. Downloads locally to avoid s3fs caching issues."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
from datasets import load_from_disk
|
| 124 |
import tempfile
|
| 125 |
+
|
| 126 |
LOGGER.info("Loading dataset from %s", s3_uri)
|
| 127 |
+
|
| 128 |
# Parse S3 URI
|
| 129 |
bucket_name, prefix = parse_s3_uri(s3_uri)
|
| 130 |
+
|
| 131 |
# Download to local temp directory (bypasses s3fs cache)
|
| 132 |
s3 = get_s3_client()
|
| 133 |
local_dir = tempfile.mkdtemp(prefix="s3_dataset_")
|
| 134 |
+
|
| 135 |
# List and download all objects
|
| 136 |
+
paginator = s3.get_paginator("list_objects_v2")
|
| 137 |
download_count = 0
|
| 138 |
for page in paginator.paginate(Bucket=bucket_name, Prefix=f"{prefix}/"):
|
| 139 |
+
for obj in page.get("Contents", []):
|
| 140 |
+
key = obj["Key"]
|
| 141 |
+
filename = key.split("/")[-1]
|
| 142 |
if filename: # Skip directory markers
|
| 143 |
local_path = f"{local_dir}/{filename}"
|
| 144 |
s3.download_file(bucket_name, key, local_path)
|
| 145 |
download_count += 1
|
| 146 |
+
|
| 147 |
LOGGER.info("Downloaded %d files to %s", download_count, local_dir)
|
| 148 |
+
|
| 149 |
# Load from local
|
| 150 |
ds = load_from_disk(local_dir)
|
| 151 |
+
|
| 152 |
return ds
|
llm_ocr/stages.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Pipeline stages: extract, describe, assemble."""
|
|
|
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import json
|
|
@@ -7,11 +8,9 @@ import shutil
|
|
| 7 |
import time
|
| 8 |
from dataclasses import asdict
|
| 9 |
from datetime import datetime
|
| 10 |
-
from pathlib import Path
|
| 11 |
from typing import Any, Dict, List
|
| 12 |
|
| 13 |
from datasets import Features, Sequence, Value, load_dataset, Image as HfImage
|
| 14 |
-
from PIL import Image
|
| 15 |
|
| 16 |
from .config import AssembleSettings, DescribeSettings, ExtractSettings, env
|
| 17 |
from .document import build_document_markdown, enrich_markdown_with_captions, write_json
|
|
@@ -33,26 +32,28 @@ def _now_iso() -> str:
|
|
| 33 |
|
| 34 |
def _dataset_features() -> Features:
|
| 35 |
"""Dataset schema - all data is embedded, no external file paths."""
|
| 36 |
-
return Features(
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
def run_stage_extract(settings: ExtractSettings) -> None:
|
| 49 |
"""Run OCR extraction on dataset samples."""
|
| 50 |
stage_start = time.time()
|
| 51 |
LOGGER.info("⏳ Starting EXTRACT stage...")
|
| 52 |
-
|
| 53 |
# Lazy import torch - only needed for extract stage
|
| 54 |
from torch.utils.data import DataLoader
|
| 55 |
-
|
| 56 |
dataset = load_dataset(
|
| 57 |
settings.dataset_name,
|
| 58 |
settings.dataset_config,
|
|
@@ -64,7 +65,11 @@ def run_stage_extract(settings: ExtractSettings) -> None:
|
|
| 64 |
if settings.stream_dataset:
|
| 65 |
num_workers = env("DATALOADER_WORKERS", 2, int)
|
| 66 |
prefetch = env("DATALOADER_PREFETCH", 2, int)
|
| 67 |
-
kwargs = {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
if num_workers > 0:
|
| 69 |
kwargs["prefetch_factor"] = prefetch
|
| 70 |
sample_iter = iter(DataLoader(dataset, **kwargs))
|
|
@@ -83,9 +88,14 @@ def run_stage_extract(settings: ExtractSettings) -> None:
|
|
| 83 |
failures: List[Dict[str, Any]] = []
|
| 84 |
chunk_size = settings.inference.batch_size
|
| 85 |
|
| 86 |
-
LOGGER.info(
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
contexts: List[Dict[str, Any]] = []
|
| 91 |
requests: List[Dict[str, Any]] = []
|
|
@@ -118,14 +128,16 @@ def run_stage_extract(settings: ExtractSettings) -> None:
|
|
| 118 |
sample_id = ctx["sample_id"]
|
| 119 |
|
| 120 |
markdown, figures, figure_images, img_draw = build_document_markdown(
|
| 121 |
-
image=img,
|
|
|
|
|
|
|
| 122 |
)
|
| 123 |
-
|
| 124 |
# Save images locally for dataset loading (HfImage needs file paths)
|
| 125 |
source_path = sample_dir / "source.png"
|
| 126 |
boxes_path = sample_dir / "document_with_boxes.png"
|
| 127 |
img_draw.save(boxes_path)
|
| 128 |
-
|
| 129 |
# Save figure images for dataset loading
|
| 130 |
figures_dir = sample_dir / "figures"
|
| 131 |
figures_dir.mkdir(parents=True, exist_ok=True)
|
|
@@ -135,16 +147,20 @@ def run_stage_extract(settings: ExtractSettings) -> None:
|
|
| 135 |
fig_img.save(fig_path)
|
| 136 |
figure_paths.append(str(fig_path))
|
| 137 |
|
| 138 |
-
docs.append(
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
except Exception as exc:
|
| 149 |
LOGGER.exception("Failed sample %s", ctx["sample_id"])
|
| 150 |
failures.append({"sample_id": ctx["sample_id"], "error": str(exc)})
|
|
@@ -174,14 +190,23 @@ def run_stage_extract(settings: ExtractSettings) -> None:
|
|
| 174 |
img = img.convert("RGB")
|
| 175 |
img.save(sample_dir / "source.png")
|
| 176 |
|
| 177 |
-
contexts.append(
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
img.close()
|
| 186 |
|
| 187 |
if len(requests) >= chunk_size:
|
|
@@ -190,12 +215,15 @@ def run_stage_extract(settings: ExtractSettings) -> None:
|
|
| 190 |
flush()
|
| 191 |
|
| 192 |
# Save manifest
|
| 193 |
-
write_json(
|
| 194 |
-
"
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
# Load as HF dataset
|
| 201 |
ds = load_dataset("json", data_files=batch_files, features=_dataset_features())
|
|
@@ -206,19 +234,27 @@ def run_stage_extract(settings: ExtractSettings) -> None:
|
|
| 206 |
storage.save_dataset(ds, "dataset")
|
| 207 |
|
| 208 |
elapsed = time.time() - stage_start
|
| 209 |
-
LOGGER.info(
|
| 210 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
|
| 213 |
def run_stage_describe(settings: DescribeSettings) -> None:
|
| 214 |
"""Describe figures in the dataset that lack descriptions."""
|
| 215 |
stage_start = time.time()
|
| 216 |
LOGGER.info("⏳ Starting DESCRIBE stage...")
|
| 217 |
-
|
| 218 |
# Get source storage and load dataset
|
| 219 |
-
source_storage = get_source_storage(
|
|
|
|
|
|
|
| 220 |
if not source_storage.is_configured:
|
| 221 |
-
raise ValueError(
|
|
|
|
|
|
|
| 222 |
|
| 223 |
dataset = source_storage.load_dataset()
|
| 224 |
if dataset is None:
|
|
@@ -282,18 +318,28 @@ def run_stage_describe(settings: DescribeSettings) -> None:
|
|
| 282 |
fig_id = meta.get("figure_id", "")
|
| 283 |
|
| 284 |
if i >= len(images) or images[i] is None:
|
| 285 |
-
failures.append(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
continue
|
| 287 |
|
| 288 |
fig_img = images[i]
|
| 289 |
-
contexts.append(
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
if len(requests) >= chunk_size:
|
| 299 |
flush()
|
|
@@ -316,8 +362,11 @@ def run_stage_describe(settings: DescribeSettings) -> None:
|
|
| 316 |
LOGGER.info("No descriptions generated")
|
| 317 |
return
|
| 318 |
|
| 319 |
-
LOGGER.info(
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
def apply(row):
|
| 323 |
metas = row.get("extracted_figures_metadata") or []
|
|
@@ -336,28 +385,40 @@ def run_stage_describe(settings: DescribeSettings) -> None:
|
|
| 336 |
# Verify before saving
|
| 337 |
test_meta = updated[0]["extracted_figures_metadata"]
|
| 338 |
if test_meta:
|
| 339 |
-
test_parsed =
|
| 340 |
-
|
| 341 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
# Get output storage and save
|
| 344 |
storage = get_storage(repo_id=settings.hub.repo_id)
|
| 345 |
storage.save_dataset(updated, "dataset")
|
| 346 |
|
| 347 |
elapsed = time.time() - stage_start
|
| 348 |
-
LOGGER.info(
|
| 349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
|
| 351 |
|
| 352 |
def run_stage_assemble(settings: AssembleSettings) -> None:
|
| 353 |
"""Enrich markdown with figure descriptions."""
|
| 354 |
stage_start = time.time()
|
| 355 |
LOGGER.info("⏳ Starting ASSEMBLE stage...")
|
| 356 |
-
|
| 357 |
# Get source storage and load dataset
|
| 358 |
-
source_storage = get_source_storage(
|
|
|
|
|
|
|
| 359 |
if not source_storage.is_configured:
|
| 360 |
-
raise ValueError(
|
|
|
|
|
|
|
| 361 |
|
| 362 |
dataset = source_storage.load_dataset()
|
| 363 |
if dataset is None:
|
|
@@ -393,5 +454,8 @@ def run_stage_assemble(settings: AssembleSettings) -> None:
|
|
| 393 |
storage.save_dataset(dataset, "dataset")
|
| 394 |
|
| 395 |
elapsed = time.time() - stage_start
|
| 396 |
-
LOGGER.info(
|
| 397 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""Pipeline stages: extract, describe, assemble."""
|
| 2 |
+
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import json
|
|
|
|
| 8 |
import time
|
| 9 |
from dataclasses import asdict
|
| 10 |
from datetime import datetime
|
|
|
|
| 11 |
from typing import Any, Dict, List
|
| 12 |
|
| 13 |
from datasets import Features, Sequence, Value, load_dataset, Image as HfImage
|
|
|
|
| 14 |
|
| 15 |
from .config import AssembleSettings, DescribeSettings, ExtractSettings, env
|
| 16 |
from .document import build_document_markdown, enrich_markdown_with_captions, write_json
|
|
|
|
| 32 |
|
| 33 |
def _dataset_features() -> Features:
|
| 34 |
"""Dataset schema - all data is embedded, no external file paths."""
|
| 35 |
+
return Features(
|
| 36 |
+
{
|
| 37 |
+
"sample_id": Value("string"),
|
| 38 |
+
"dataset_index": Value("int64"),
|
| 39 |
+
"source_image": HfImage(),
|
| 40 |
+
"document_with_boxes_image": HfImage(),
|
| 41 |
+
"document_markdown": Value("string"),
|
| 42 |
+
"extracted_figures": Sequence(HfImage()),
|
| 43 |
+
"extracted_figures_metadata": Sequence(Value("string")),
|
| 44 |
+
"document_final_markdown": Value("string"),
|
| 45 |
+
}
|
| 46 |
+
)
|
| 47 |
|
| 48 |
|
| 49 |
def run_stage_extract(settings: ExtractSettings) -> None:
|
| 50 |
"""Run OCR extraction on dataset samples."""
|
| 51 |
stage_start = time.time()
|
| 52 |
LOGGER.info("⏳ Starting EXTRACT stage...")
|
| 53 |
+
|
| 54 |
# Lazy import torch - only needed for extract stage
|
| 55 |
from torch.utils.data import DataLoader
|
| 56 |
+
|
| 57 |
dataset = load_dataset(
|
| 58 |
settings.dataset_name,
|
| 59 |
settings.dataset_config,
|
|
|
|
| 65 |
if settings.stream_dataset:
|
| 66 |
num_workers = env("DATALOADER_WORKERS", 2, int)
|
| 67 |
prefetch = env("DATALOADER_PREFETCH", 2, int)
|
| 68 |
+
kwargs = {
|
| 69 |
+
"batch_size": 1,
|
| 70 |
+
"num_workers": num_workers,
|
| 71 |
+
"collate_fn": lambda b: b[0],
|
| 72 |
+
}
|
| 73 |
if num_workers > 0:
|
| 74 |
kwargs["prefetch_factor"] = prefetch
|
| 75 |
sample_iter = iter(DataLoader(dataset, **kwargs))
|
|
|
|
| 88 |
failures: List[Dict[str, Any]] = []
|
| 89 |
chunk_size = settings.inference.batch_size
|
| 90 |
|
| 91 |
+
LOGGER.info(
|
| 92 |
+
"Extract | dataset=%s/%s/%s | max_samples=%s | batch=%s",
|
| 93 |
+
settings.dataset_name,
|
| 94 |
+
settings.dataset_config,
|
| 95 |
+
settings.dataset_split,
|
| 96 |
+
settings.max_samples,
|
| 97 |
+
chunk_size,
|
| 98 |
+
)
|
| 99 |
|
| 100 |
contexts: List[Dict[str, Any]] = []
|
| 101 |
requests: List[Dict[str, Any]] = []
|
|
|
|
| 128 |
sample_id = ctx["sample_id"]
|
| 129 |
|
| 130 |
markdown, figures, figure_images, img_draw = build_document_markdown(
|
| 131 |
+
image=img,
|
| 132 |
+
response_text=text,
|
| 133 |
+
sample_id=sample_id,
|
| 134 |
)
|
| 135 |
+
|
| 136 |
# Save images locally for dataset loading (HfImage needs file paths)
|
| 137 |
source_path = sample_dir / "source.png"
|
| 138 |
boxes_path = sample_dir / "document_with_boxes.png"
|
| 139 |
img_draw.save(boxes_path)
|
| 140 |
+
|
| 141 |
# Save figure images for dataset loading
|
| 142 |
figures_dir = sample_dir / "figures"
|
| 143 |
figures_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 147 |
fig_img.save(fig_path)
|
| 148 |
figure_paths.append(str(fig_path))
|
| 149 |
|
| 150 |
+
docs.append(
|
| 151 |
+
{
|
| 152 |
+
"sample_id": sample_id,
|
| 153 |
+
"dataset_index": ctx["dataset_index"],
|
| 154 |
+
"source_image": str(source_path),
|
| 155 |
+
"document_with_boxes_image": str(boxes_path),
|
| 156 |
+
"document_markdown": markdown,
|
| 157 |
+
"extracted_figures": figure_paths,
|
| 158 |
+
"extracted_figures_metadata": [
|
| 159 |
+
json.dumps(asdict(f)) for f in figures
|
| 160 |
+
],
|
| 161 |
+
"document_final_markdown": "", # Filled in assemble stage
|
| 162 |
+
}
|
| 163 |
+
)
|
| 164 |
except Exception as exc:
|
| 165 |
LOGGER.exception("Failed sample %s", ctx["sample_id"])
|
| 166 |
failures.append({"sample_id": ctx["sample_id"], "error": str(exc)})
|
|
|
|
| 190 |
img = img.convert("RGB")
|
| 191 |
img.save(sample_dir / "source.png")
|
| 192 |
|
| 193 |
+
contexts.append(
|
| 194 |
+
{
|
| 195 |
+
"sample_id": sample_id,
|
| 196 |
+
"dataset_index": idx,
|
| 197 |
+
"sample_dir": sample_dir,
|
| 198 |
+
"image": img.copy(),
|
| 199 |
+
}
|
| 200 |
+
)
|
| 201 |
+
requests.append(
|
| 202 |
+
{
|
| 203 |
+
"image": contexts[-1]["image"],
|
| 204 |
+
"prompt": settings.prompt,
|
| 205 |
+
"max_tokens": settings.max_tokens,
|
| 206 |
+
"temperature": settings.temperature,
|
| 207 |
+
"request_timeout": settings.inference.request_timeout,
|
| 208 |
+
}
|
| 209 |
+
)
|
| 210 |
img.close()
|
| 211 |
|
| 212 |
if len(requests) >= chunk_size:
|
|
|
|
| 215 |
flush()
|
| 216 |
|
| 217 |
# Save manifest
|
| 218 |
+
write_json(
|
| 219 |
+
settings.output_dir / "manifest.json",
|
| 220 |
+
{
|
| 221 |
+
"generated_at": _now_iso(),
|
| 222 |
+
"stage": "extract",
|
| 223 |
+
"documents_count": doc_count,
|
| 224 |
+
"failures": failures,
|
| 225 |
+
},
|
| 226 |
+
)
|
| 227 |
|
| 228 |
# Load as HF dataset
|
| 229 |
ds = load_dataset("json", data_files=batch_files, features=_dataset_features())
|
|
|
|
| 234 |
storage.save_dataset(ds, "dataset")
|
| 235 |
|
| 236 |
elapsed = time.time() - stage_start
|
| 237 |
+
LOGGER.info(
|
| 238 |
+
"✅ Extract complete | docs=%d | failures=%d | duration=%s",
|
| 239 |
+
doc_count,
|
| 240 |
+
len(failures),
|
| 241 |
+
_format_duration(elapsed),
|
| 242 |
+
)
|
| 243 |
|
| 244 |
|
| 245 |
def run_stage_describe(settings: DescribeSettings) -> None:
|
| 246 |
"""Describe figures in the dataset that lack descriptions."""
|
| 247 |
stage_start = time.time()
|
| 248 |
LOGGER.info("⏳ Starting DESCRIBE stage...")
|
| 249 |
+
|
| 250 |
# Get source storage and load dataset
|
| 251 |
+
source_storage = get_source_storage(
|
| 252 |
+
source_repo_id=settings.source_repo_id or settings.hub.repo_id
|
| 253 |
+
)
|
| 254 |
if not source_storage.is_configured:
|
| 255 |
+
raise ValueError(
|
| 256 |
+
"No source configured for describe stage (set SOURCE_REPO_ID, HF_REPO_ID, or S3_INPUT_URI)"
|
| 257 |
+
)
|
| 258 |
|
| 259 |
dataset = source_storage.load_dataset()
|
| 260 |
if dataset is None:
|
|
|
|
| 318 |
fig_id = meta.get("figure_id", "")
|
| 319 |
|
| 320 |
if i >= len(images) or images[i] is None:
|
| 321 |
+
failures.append(
|
| 322 |
+
{
|
| 323 |
+
"sample_id": sample_id,
|
| 324 |
+
"figure_id": fig_id,
|
| 325 |
+
"reason": "missing_image",
|
| 326 |
+
}
|
| 327 |
+
)
|
| 328 |
continue
|
| 329 |
|
| 330 |
fig_img = images[i]
|
| 331 |
+
contexts.append(
|
| 332 |
+
{"sample_id": sample_id, "figure_id": fig_id, "image": fig_img}
|
| 333 |
+
)
|
| 334 |
+
requests.append(
|
| 335 |
+
{
|
| 336 |
+
"image": fig_img,
|
| 337 |
+
"prompt": settings.prompt,
|
| 338 |
+
"max_tokens": settings.max_tokens,
|
| 339 |
+
"temperature": settings.temperature,
|
| 340 |
+
"request_timeout": settings.inference.request_timeout,
|
| 341 |
+
}
|
| 342 |
+
)
|
| 343 |
|
| 344 |
if len(requests) >= chunk_size:
|
| 345 |
flush()
|
|
|
|
| 362 |
LOGGER.info("No descriptions generated")
|
| 363 |
return
|
| 364 |
|
| 365 |
+
LOGGER.info(
|
| 366 |
+
"Lookup has %d descriptions, first few: %s",
|
| 367 |
+
len(lookup),
|
| 368 |
+
list(lookup.keys())[:3],
|
| 369 |
+
)
|
| 370 |
|
| 371 |
def apply(row):
|
| 372 |
metas = row.get("extracted_figures_metadata") or []
|
|
|
|
| 385 |
# Verify before saving
|
| 386 |
test_meta = updated[0]["extracted_figures_metadata"]
|
| 387 |
if test_meta:
|
| 388 |
+
test_parsed = (
|
| 389 |
+
json.loads(test_meta[0]) if isinstance(test_meta[0], str) else test_meta[0]
|
| 390 |
+
)
|
| 391 |
+
LOGGER.info(
|
| 392 |
+
"VERIFY before save - description present: %s",
|
| 393 |
+
test_parsed.get("description") is not None,
|
| 394 |
+
)
|
| 395 |
|
| 396 |
# Get output storage and save
|
| 397 |
storage = get_storage(repo_id=settings.hub.repo_id)
|
| 398 |
storage.save_dataset(updated, "dataset")
|
| 399 |
|
| 400 |
elapsed = time.time() - stage_start
|
| 401 |
+
LOGGER.info(
|
| 402 |
+
"✅ Describe complete | described=%d | failures=%d | duration=%s",
|
| 403 |
+
described,
|
| 404 |
+
len(failures),
|
| 405 |
+
_format_duration(elapsed),
|
| 406 |
+
)
|
| 407 |
|
| 408 |
|
| 409 |
def run_stage_assemble(settings: AssembleSettings) -> None:
|
| 410 |
"""Enrich markdown with figure descriptions."""
|
| 411 |
stage_start = time.time()
|
| 412 |
LOGGER.info("⏳ Starting ASSEMBLE stage...")
|
| 413 |
+
|
| 414 |
# Get source storage and load dataset
|
| 415 |
+
source_storage = get_source_storage(
|
| 416 |
+
source_repo_id=settings.source_repo_id or settings.hub.repo_id
|
| 417 |
+
)
|
| 418 |
if not source_storage.is_configured:
|
| 419 |
+
raise ValueError(
|
| 420 |
+
"No source configured for assemble stage (set SOURCE_REPO_ID, HF_REPO_ID, or S3_INPUT_URI)"
|
| 421 |
+
)
|
| 422 |
|
| 423 |
dataset = source_storage.load_dataset()
|
| 424 |
if dataset is None:
|
|
|
|
| 454 |
storage.save_dataset(dataset, "dataset")
|
| 455 |
|
| 456 |
elapsed = time.time() - stage_start
|
| 457 |
+
LOGGER.info(
|
| 458 |
+
"✅ Assemble complete | assembled=%d | duration=%s",
|
| 459 |
+
assembled_count,
|
| 460 |
+
_format_duration(elapsed),
|
| 461 |
+
)
|
llm_ocr/storage.py
CHANGED
|
@@ -5,11 +5,12 @@ 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
|
|
@@ -26,32 +27,17 @@ LOGGER = logging.getLogger(__name__)
|
|
| 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
|
| 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
|
| 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:
|
|
@@ -61,7 +47,7 @@ class DatasetStorage(ABC):
|
|
| 61 |
|
| 62 |
class HFHubStorage(DatasetStorage):
|
| 63 |
"""HuggingFace Hub storage backend."""
|
| 64 |
-
|
| 65 |
def __init__(
|
| 66 |
self,
|
| 67 |
repo_id: Optional[str] = None,
|
|
@@ -72,23 +58,23 @@ class HFHubStorage(DatasetStorage):
|
|
| 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 |
# Fail early if token is missing or empty
|
| 86 |
if not self._token:
|
| 87 |
raise ValueError(
|
| 88 |
"HF_TOKEN is required to push datasets to the Hub. "
|
| 89 |
"Set the HF_TOKEN environment variable with a token that has write permissions."
|
| 90 |
)
|
| 91 |
-
|
| 92 |
try:
|
| 93 |
dataset.push_to_hub(
|
| 94 |
self.repo_id,
|
|
@@ -101,15 +87,15 @@ class HFHubStorage(DatasetStorage):
|
|
| 101 |
except Exception as exc:
|
| 102 |
LOGGER.exception("HF Hub dataset push failed: %s", exc)
|
| 103 |
raise
|
| 104 |
-
|
| 105 |
def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
|
| 106 |
if not self.is_configured:
|
| 107 |
LOGGER.debug("HF Hub not configured, cannot load dataset")
|
| 108 |
return None
|
| 109 |
-
|
| 110 |
try:
|
| 111 |
from datasets import load_dataset
|
| 112 |
-
|
| 113 |
LOGGER.info("Loading dataset from HF Hub: %s", self.repo_id)
|
| 114 |
return load_dataset(self.repo_id, split=split, token=self._token)
|
| 115 |
except Exception as exc:
|
|
@@ -119,7 +105,7 @@ class HFHubStorage(DatasetStorage):
|
|
| 119 |
|
| 120 |
class S3Storage(DatasetStorage):
|
| 121 |
"""Amazon S3 storage backend."""
|
| 122 |
-
|
| 123 |
def __init__(
|
| 124 |
self,
|
| 125 |
output_uri: Optional[str] = None,
|
|
@@ -127,19 +113,19 @@ class S3Storage(DatasetStorage):
|
|
| 127 |
):
|
| 128 |
self.output_uri = output_uri or env("S3_OUTPUT_URI")
|
| 129 |
self.input_uri = input_uri or env("S3_INPUT_URI")
|
| 130 |
-
|
| 131 |
@property
|
| 132 |
def is_configured(self) -> bool:
|
| 133 |
return bool(self.output_uri or self.input_uri)
|
| 134 |
-
|
| 135 |
def save_dataset(self, dataset: "Dataset", name: str) -> bool:
|
| 136 |
if not self.output_uri:
|
| 137 |
LOGGER.debug("S3 output URI not configured, skipping dataset save")
|
| 138 |
return False
|
| 139 |
-
|
| 140 |
try:
|
| 141 |
from .sm_io import save_dataset_to_s3
|
| 142 |
-
|
| 143 |
save_dataset_to_s3(dataset, self.output_uri, name)
|
| 144 |
return True
|
| 145 |
except ImportError as exc:
|
|
@@ -148,15 +134,15 @@ class S3Storage(DatasetStorage):
|
|
| 148 |
except Exception as exc:
|
| 149 |
LOGGER.exception("S3 dataset save failed: %s", exc)
|
| 150 |
return False
|
| 151 |
-
|
| 152 |
def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
|
| 153 |
if not self.input_uri:
|
| 154 |
LOGGER.debug("S3 input URI not configured, cannot load dataset")
|
| 155 |
return None
|
| 156 |
-
|
| 157 |
try:
|
| 158 |
from .sm_io import load_dataset_from_s3
|
| 159 |
-
|
| 160 |
return load_dataset_from_s3(self.input_uri, split=split)
|
| 161 |
except ImportError as exc:
|
| 162 |
LOGGER.warning("S3 load failed (missing dependency): %s", exc)
|
|
@@ -168,7 +154,7 @@ class S3Storage(DatasetStorage):
|
|
| 168 |
|
| 169 |
class GCSStorage(DatasetStorage):
|
| 170 |
"""Google Cloud Storage backend."""
|
| 171 |
-
|
| 172 |
def __init__(
|
| 173 |
self,
|
| 174 |
output_uri: Optional[str] = None,
|
|
@@ -176,19 +162,19 @@ class GCSStorage(DatasetStorage):
|
|
| 176 |
):
|
| 177 |
self.output_uri = output_uri or env("GCS_OUTPUT_URI")
|
| 178 |
self.input_uri = input_uri or env("GCS_INPUT_URI")
|
| 179 |
-
|
| 180 |
@property
|
| 181 |
def is_configured(self) -> bool:
|
| 182 |
return bool(self.output_uri or self.input_uri)
|
| 183 |
-
|
| 184 |
def save_dataset(self, dataset: "Dataset", name: str) -> bool:
|
| 185 |
if not self.output_uri:
|
| 186 |
LOGGER.debug("GCS output URI not configured, skipping dataset save")
|
| 187 |
return False
|
| 188 |
-
|
| 189 |
try:
|
| 190 |
from .cloudrun_io import save_dataset_to_gcs
|
| 191 |
-
|
| 192 |
save_dataset_to_gcs(dataset, self.output_uri, name)
|
| 193 |
return True
|
| 194 |
except ImportError as exc:
|
|
@@ -197,15 +183,15 @@ class GCSStorage(DatasetStorage):
|
|
| 197 |
except Exception as exc:
|
| 198 |
LOGGER.exception("GCS dataset save failed: %s", exc)
|
| 199 |
return False
|
| 200 |
-
|
| 201 |
def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
|
| 202 |
if not self.input_uri:
|
| 203 |
LOGGER.debug("GCS input URI not configured, cannot load dataset")
|
| 204 |
return None
|
| 205 |
-
|
| 206 |
try:
|
| 207 |
from .cloudrun_io import load_dataset_from_gcs
|
| 208 |
-
|
| 209 |
return load_dataset_from_gcs(self.input_uri, split=split)
|
| 210 |
except ImportError as exc:
|
| 211 |
LOGGER.warning("GCS load failed (missing dependency): %s", exc)
|
|
@@ -223,25 +209,26 @@ def get_storage(
|
|
| 223 |
gcs_output_uri: Optional[str] = None,
|
| 224 |
gcs_input_uri: Optional[str] = None,
|
| 225 |
) -> DatasetStorage:
|
| 226 |
-
"""Get the
|
| 227 |
-
|
| 228 |
-
Priority: GCS > S3 > HF Hub.
|
| 229 |
-
|
| 230 |
-
Args:
|
| 231 |
-
repo_id: Override HF repo ID
|
| 232 |
-
s3_output_uri: Override S3 output URI
|
| 233 |
-
s3_input_uri: Override S3 input URI
|
| 234 |
-
gcs_output_uri: Override GCS output URI
|
| 235 |
-
gcs_input_uri: Override GCS input URI
|
| 236 |
-
|
| 237 |
-
Returns:
|
| 238 |
-
Configured DatasetStorage instance
|
| 239 |
-
"""
|
| 240 |
gcs = GCSStorage(output_uri=gcs_output_uri, input_uri=gcs_input_uri)
|
| 241 |
s3 = S3Storage(output_uri=s3_output_uri, input_uri=s3_input_uri)
|
| 242 |
hf = HFHubStorage(repo_id=repo_id)
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
if gcs.is_configured:
|
| 246 |
return gcs
|
| 247 |
if s3.is_configured:
|
|
@@ -253,23 +240,28 @@ def get_source_storage(
|
|
| 253 |
*,
|
| 254 |
source_repo_id: Optional[str] = None,
|
| 255 |
) -> DatasetStorage:
|
| 256 |
-
"""Get storage
|
| 257 |
-
|
| 258 |
-
Checks GCS_INPUT_URI first, then S3_INPUT_URI, then falls back to HF Hub.
|
| 259 |
-
|
| 260 |
-
Args:
|
| 261 |
-
source_repo_id: HF repo ID to load from (falls back to SOURCE_REPO_ID env var)
|
| 262 |
-
|
| 263 |
-
Returns:
|
| 264 |
-
Configured DatasetStorage instance for loading
|
| 265 |
-
"""
|
| 266 |
gcs_input = env("GCS_INPUT_URI")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
if gcs_input:
|
| 268 |
return GCSStorage(input_uri=gcs_input)
|
| 269 |
-
|
| 270 |
-
s3_input = env("S3_INPUT_URI")
|
| 271 |
if s3_input:
|
| 272 |
return S3Storage(input_uri=s3_input)
|
| 273 |
-
|
| 274 |
-
repo_id = source_repo_id or env("SOURCE_REPO_ID") or env("HF_REPO_ID")
|
| 275 |
-
return HFHubStorage(repo_id=repo_id)
|
|
|
|
| 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 |
+
|
| 14 |
from __future__ import annotations
|
| 15 |
|
| 16 |
import logging
|
|
|
|
| 27 |
|
| 28 |
class DatasetStorage(ABC):
|
| 29 |
"""Abstract base class for dataset storage backends."""
|
| 30 |
+
|
| 31 |
@abstractmethod
|
| 32 |
def save_dataset(self, dataset: "Dataset", name: str) -> bool:
|
| 33 |
+
"""Save dataset to storage. Returns True on success."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
pass
|
| 35 |
+
|
| 36 |
@abstractmethod
|
| 37 |
def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
|
| 38 |
+
"""Load dataset from storage. Returns None if unavailable."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
pass
|
| 40 |
+
|
| 41 |
@property
|
| 42 |
@abstractmethod
|
| 43 |
def is_configured(self) -> bool:
|
|
|
|
| 47 |
|
| 48 |
class HFHubStorage(DatasetStorage):
|
| 49 |
"""HuggingFace Hub storage backend."""
|
| 50 |
+
|
| 51 |
def __init__(
|
| 52 |
self,
|
| 53 |
repo_id: Optional[str] = None,
|
|
|
|
| 58 |
self.branch = branch or env("HF_BRANCH")
|
| 59 |
self.commit_message = commit_message or env("HF_COMMIT_MESSAGE")
|
| 60 |
self._token = env("HF_TOKEN")
|
| 61 |
+
|
| 62 |
@property
|
| 63 |
def is_configured(self) -> bool:
|
| 64 |
return bool(self.repo_id)
|
| 65 |
+
|
| 66 |
def save_dataset(self, dataset: "Dataset", name: str) -> bool:
|
| 67 |
if not self.is_configured:
|
| 68 |
LOGGER.debug("HF Hub not configured, skipping dataset save")
|
| 69 |
return False
|
| 70 |
+
|
| 71 |
# Fail early if token is missing or empty
|
| 72 |
if not self._token:
|
| 73 |
raise ValueError(
|
| 74 |
"HF_TOKEN is required to push datasets to the Hub. "
|
| 75 |
"Set the HF_TOKEN environment variable with a token that has write permissions."
|
| 76 |
)
|
| 77 |
+
|
| 78 |
try:
|
| 79 |
dataset.push_to_hub(
|
| 80 |
self.repo_id,
|
|
|
|
| 87 |
except Exception as exc:
|
| 88 |
LOGGER.exception("HF Hub dataset push failed: %s", exc)
|
| 89 |
raise
|
| 90 |
+
|
| 91 |
def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
|
| 92 |
if not self.is_configured:
|
| 93 |
LOGGER.debug("HF Hub not configured, cannot load dataset")
|
| 94 |
return None
|
| 95 |
+
|
| 96 |
try:
|
| 97 |
from datasets import load_dataset
|
| 98 |
+
|
| 99 |
LOGGER.info("Loading dataset from HF Hub: %s", self.repo_id)
|
| 100 |
return load_dataset(self.repo_id, split=split, token=self._token)
|
| 101 |
except Exception as exc:
|
|
|
|
| 105 |
|
| 106 |
class S3Storage(DatasetStorage):
|
| 107 |
"""Amazon S3 storage backend."""
|
| 108 |
+
|
| 109 |
def __init__(
|
| 110 |
self,
|
| 111 |
output_uri: Optional[str] = None,
|
|
|
|
| 113 |
):
|
| 114 |
self.output_uri = output_uri or env("S3_OUTPUT_URI")
|
| 115 |
self.input_uri = input_uri or env("S3_INPUT_URI")
|
| 116 |
+
|
| 117 |
@property
|
| 118 |
def is_configured(self) -> bool:
|
| 119 |
return bool(self.output_uri or self.input_uri)
|
| 120 |
+
|
| 121 |
def save_dataset(self, dataset: "Dataset", name: str) -> bool:
|
| 122 |
if not self.output_uri:
|
| 123 |
LOGGER.debug("S3 output URI not configured, skipping dataset save")
|
| 124 |
return False
|
| 125 |
+
|
| 126 |
try:
|
| 127 |
from .sm_io import save_dataset_to_s3
|
| 128 |
+
|
| 129 |
save_dataset_to_s3(dataset, self.output_uri, name)
|
| 130 |
return True
|
| 131 |
except ImportError as exc:
|
|
|
|
| 134 |
except Exception as exc:
|
| 135 |
LOGGER.exception("S3 dataset save failed: %s", exc)
|
| 136 |
return False
|
| 137 |
+
|
| 138 |
def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
|
| 139 |
if not self.input_uri:
|
| 140 |
LOGGER.debug("S3 input URI not configured, cannot load dataset")
|
| 141 |
return None
|
| 142 |
+
|
| 143 |
try:
|
| 144 |
from .sm_io import load_dataset_from_s3
|
| 145 |
+
|
| 146 |
return load_dataset_from_s3(self.input_uri, split=split)
|
| 147 |
except ImportError as exc:
|
| 148 |
LOGGER.warning("S3 load failed (missing dependency): %s", exc)
|
|
|
|
| 154 |
|
| 155 |
class GCSStorage(DatasetStorage):
|
| 156 |
"""Google Cloud Storage backend."""
|
| 157 |
+
|
| 158 |
def __init__(
|
| 159 |
self,
|
| 160 |
output_uri: Optional[str] = None,
|
|
|
|
| 162 |
):
|
| 163 |
self.output_uri = output_uri or env("GCS_OUTPUT_URI")
|
| 164 |
self.input_uri = input_uri or env("GCS_INPUT_URI")
|
| 165 |
+
|
| 166 |
@property
|
| 167 |
def is_configured(self) -> bool:
|
| 168 |
return bool(self.output_uri or self.input_uri)
|
| 169 |
+
|
| 170 |
def save_dataset(self, dataset: "Dataset", name: str) -> bool:
|
| 171 |
if not self.output_uri:
|
| 172 |
LOGGER.debug("GCS output URI not configured, skipping dataset save")
|
| 173 |
return False
|
| 174 |
+
|
| 175 |
try:
|
| 176 |
from .cloudrun_io import save_dataset_to_gcs
|
| 177 |
+
|
| 178 |
save_dataset_to_gcs(dataset, self.output_uri, name)
|
| 179 |
return True
|
| 180 |
except ImportError as exc:
|
|
|
|
| 183 |
except Exception as exc:
|
| 184 |
LOGGER.exception("GCS dataset save failed: %s", exc)
|
| 185 |
return False
|
| 186 |
+
|
| 187 |
def load_dataset(self, split: str = "train") -> Optional["Dataset"]:
|
| 188 |
if not self.input_uri:
|
| 189 |
LOGGER.debug("GCS input URI not configured, cannot load dataset")
|
| 190 |
return None
|
| 191 |
+
|
| 192 |
try:
|
| 193 |
from .cloudrun_io import load_dataset_from_gcs
|
| 194 |
+
|
| 195 |
return load_dataset_from_gcs(self.input_uri, split=split)
|
| 196 |
except ImportError as exc:
|
| 197 |
LOGGER.warning("GCS load failed (missing dependency): %s", exc)
|
|
|
|
| 209 |
gcs_output_uri: Optional[str] = None,
|
| 210 |
gcs_input_uri: Optional[str] = None,
|
| 211 |
) -> DatasetStorage:
|
| 212 |
+
"""Get the configured storage backend. Exactly one must be configured."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
gcs = GCSStorage(output_uri=gcs_output_uri, input_uri=gcs_input_uri)
|
| 214 |
s3 = S3Storage(output_uri=s3_output_uri, input_uri=s3_input_uri)
|
| 215 |
hf = HFHubStorage(repo_id=repo_id)
|
| 216 |
+
|
| 217 |
+
configured = [
|
| 218 |
+
name
|
| 219 |
+
for name, backend in [("GCS", gcs), ("S3", s3), ("HF Hub", hf)]
|
| 220 |
+
if backend.is_configured
|
| 221 |
+
]
|
| 222 |
+
|
| 223 |
+
if len(configured) > 1:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"Multiple storage backends configured: {configured}. Configure only one."
|
| 226 |
+
)
|
| 227 |
+
if len(configured) == 0:
|
| 228 |
+
raise ValueError(
|
| 229 |
+
"No storage backend configured. Set HF_REPO_ID, S3_OUTPUT_URI, or GCS_OUTPUT_URI."
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
if gcs.is_configured:
|
| 233 |
return gcs
|
| 234 |
if s3.is_configured:
|
|
|
|
| 240 |
*,
|
| 241 |
source_repo_id: Optional[str] = None,
|
| 242 |
) -> DatasetStorage:
|
| 243 |
+
"""Get storage for loading source data. Exactly one must be configured."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
gcs_input = env("GCS_INPUT_URI")
|
| 245 |
+
s3_input = env("S3_INPUT_URI")
|
| 246 |
+
hf_repo = source_repo_id or env("SOURCE_REPO_ID") or env("HF_REPO_ID")
|
| 247 |
+
|
| 248 |
+
configured = [
|
| 249 |
+
name
|
| 250 |
+
for name, val in [("GCS", gcs_input), ("S3", s3_input), ("HF Hub", hf_repo)]
|
| 251 |
+
if val
|
| 252 |
+
]
|
| 253 |
+
|
| 254 |
+
if len(configured) > 1:
|
| 255 |
+
raise ValueError(
|
| 256 |
+
f"Multiple source backends configured: {configured}. Configure only one."
|
| 257 |
+
)
|
| 258 |
+
if len(configured) == 0:
|
| 259 |
+
raise ValueError(
|
| 260 |
+
"No source storage configured. Set SOURCE_REPO_ID, S3_INPUT_URI, or GCS_INPUT_URI."
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
if gcs_input:
|
| 264 |
return GCSStorage(input_uri=gcs_input)
|
|
|
|
|
|
|
| 265 |
if s3_input:
|
| 266 |
return S3Storage(input_uri=s3_input)
|
| 267 |
+
return HFHubStorage(repo_id=hf_repo)
|
|
|
|
|
|