Upload folder using huggingface_hub
Browse files- llm_ocr/__init__.py +35 -3
- llm_ocr/__main__.py +6 -0
- llm_ocr/__pycache__/__init__.cpython-312.pyc +0 -0
- llm_ocr/__pycache__/__main__.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__/sm_io.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 +0 -3
- llm_ocr/cloudrun_io.py +181 -0
- llm_ocr/config.py +0 -11
- llm_ocr/document.py +0 -13
- llm_ocr/server.py +17 -11
- llm_ocr/sm_io.py +0 -8
- llm_ocr/stages.py +29 -7
- llm_ocr/storage.py +2 -12
llm_ocr/__init__.py
CHANGED
|
@@ -1,7 +1,39 @@
|
|
| 1 |
-
"""DeepSeek OCR pipeline package.
|
| 2 |
|
| 3 |
-
|
|
|
|
| 4 |
|
| 5 |
-
|
|
|
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DeepSeek OCR pipeline package.
|
| 2 |
|
| 3 |
+
This package provides tools for running batch OCR inference with DeepSeek-OCR
|
| 4 |
+
and similar vision-language models across different cloud platforms.
|
| 5 |
|
| 6 |
+
Example usage:
|
| 7 |
+
from llm_ocr import DeepSeekClient, ExtractSettings, run_stage_extract
|
| 8 |
|
| 9 |
+
client = DeepSeekClient(base_url="http://localhost:8000/v1")
|
| 10 |
+
settings = ExtractSettings.from_env(client)
|
| 11 |
+
run_stage_extract(settings)
|
| 12 |
+
"""
|
| 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 |
+
)
|
llm_ocr/__main__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Entry point for `python -m llm_ocr`."""
|
| 2 |
+
|
| 3 |
+
from llm_ocr.cli import main
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
main()
|
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__/__main__.cpython-312.pyc
ADDED
|
Binary file (324 Bytes). View file
|
|
|
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__/sm_io.cpython-312.pyc
ADDED
|
Binary file (7.67 kB). View file
|
|
|
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
|
@@ -87,6 +87,3 @@ def main() -> None:
|
|
| 87 |
finally:
|
| 88 |
if server_process is not None:
|
| 89 |
shutdown_server(server_process)
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
__all__ = ["main"]
|
|
|
|
| 87 |
finally:
|
| 88 |
if server_process is not None:
|
| 89 |
shutdown_server(server_process)
|
|
|
|
|
|
|
|
|
llm_ocr/cloudrun_io.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Google Cloud Storage utilities for Cloud Run jobs."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import shutil
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import TYPE_CHECKING
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from datasets import Dataset
|
| 11 |
+
|
| 12 |
+
LOGGER = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_gcs_client():
|
| 16 |
+
"""Get GCS client."""
|
| 17 |
+
from google.cloud import storage
|
| 18 |
+
return storage.Client()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def parse_gcs_uri(uri: str) -> tuple[str, str]:
|
| 22 |
+
"""Parse gs://bucket/key into (bucket, key)."""
|
| 23 |
+
if not uri.startswith("gs://"):
|
| 24 |
+
raise ValueError(f"Invalid GCS URI: {uri}")
|
| 25 |
+
parts = uri[5:].split("/", 1)
|
| 26 |
+
bucket = parts[0]
|
| 27 |
+
key = parts[1] if len(parts) > 1 else ""
|
| 28 |
+
return bucket, key
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def upload_files_to_gcs(
|
| 32 |
+
*,
|
| 33 |
+
output_dir: Path,
|
| 34 |
+
gcs_uri: str,
|
| 35 |
+
path_prefix: str = "",
|
| 36 |
+
) -> None:
|
| 37 |
+
"""Upload local files to GCS.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
output_dir: Local directory containing files to upload
|
| 41 |
+
gcs_uri: GCS URI (gs://bucket/prefix)
|
| 42 |
+
path_prefix: Additional prefix to add to GCS keys
|
| 43 |
+
"""
|
| 44 |
+
if not gcs_uri:
|
| 45 |
+
LOGGER.info("No GCS URI provided; skipping upload.")
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
bucket_name, base_prefix = parse_gcs_uri(gcs_uri)
|
| 49 |
+
|
| 50 |
+
full_prefix = base_prefix.rstrip("/")
|
| 51 |
+
if path_prefix:
|
| 52 |
+
full_prefix = f"{full_prefix}/{path_prefix.strip('/')}" if full_prefix else path_prefix.strip("/")
|
| 53 |
+
|
| 54 |
+
client = get_gcs_client()
|
| 55 |
+
bucket = client.bucket(bucket_name)
|
| 56 |
+
base = output_dir.resolve()
|
| 57 |
+
|
| 58 |
+
files = sorted(p for p in base.rglob("*") if p.is_file())
|
| 59 |
+
if not files:
|
| 60 |
+
LOGGER.info("Nothing to upload from %s", output_dir)
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
LOGGER.info("Uploading %d files to gs://%s/%s", len(files), bucket_name, full_prefix)
|
| 64 |
+
|
| 65 |
+
for local_path in files:
|
| 66 |
+
rel = local_path.relative_to(base).as_posix()
|
| 67 |
+
gcs_key = f"{full_prefix}/{rel}" if full_prefix else rel
|
| 68 |
+
try:
|
| 69 |
+
blob = bucket.blob(gcs_key)
|
| 70 |
+
blob.upload_from_filename(str(local_path))
|
| 71 |
+
except Exception as exc:
|
| 72 |
+
LOGGER.error("Failed to upload %s to gs://%s/%s: %s", local_path, bucket_name, gcs_key, exc)
|
| 73 |
+
raise
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def save_dataset_to_gcs(
|
| 77 |
+
dataset,
|
| 78 |
+
gcs_uri: str,
|
| 79 |
+
name: str = "dataset",
|
| 80 |
+
) -> str:
|
| 81 |
+
"""Save HF dataset to GCS using Arrow format (preserves Image columns).
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
dataset: HuggingFace Dataset or DatasetDict to save
|
| 85 |
+
gcs_uri: Base GCS URI (gs://bucket/prefix)
|
| 86 |
+
name: Name for the dataset folder
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
GCS URI of the saved dataset
|
| 90 |
+
"""
|
| 91 |
+
from datasets import DatasetDict
|
| 92 |
+
|
| 93 |
+
# Handle DatasetDict by extracting the first split
|
| 94 |
+
if isinstance(dataset, DatasetDict):
|
| 95 |
+
if "train" in dataset:
|
| 96 |
+
dataset = dataset["train"]
|
| 97 |
+
else:
|
| 98 |
+
split_name = list(dataset.keys())[0]
|
| 99 |
+
dataset = dataset[split_name]
|
| 100 |
+
LOGGER.info("Using split '%s' from DatasetDict", split_name)
|
| 101 |
+
|
| 102 |
+
bucket_name, prefix = parse_gcs_uri(gcs_uri)
|
| 103 |
+
full_prefix = prefix.rstrip("/")
|
| 104 |
+
|
| 105 |
+
# Save to local temp directory using Arrow format
|
| 106 |
+
local_dir = Path(f"/tmp/{name}_arrow_temp")
|
| 107 |
+
if local_dir.exists():
|
| 108 |
+
shutil.rmtree(local_dir)
|
| 109 |
+
|
| 110 |
+
LOGGER.info("Saving dataset to Arrow format...")
|
| 111 |
+
dataset.save_to_disk(str(local_dir))
|
| 112 |
+
|
| 113 |
+
# Upload entire directory to GCS
|
| 114 |
+
gcs_prefix = f"{full_prefix}/{name}" if full_prefix else name
|
| 115 |
+
upload_files_to_gcs(output_dir=local_dir, gcs_uri=f"gs://{bucket_name}/{gcs_prefix}")
|
| 116 |
+
|
| 117 |
+
# Cleanup
|
| 118 |
+
shutil.rmtree(local_dir)
|
| 119 |
+
|
| 120 |
+
result_uri = f"gs://{bucket_name}/{gcs_prefix}"
|
| 121 |
+
LOGGER.info("Saved dataset to %s", result_uri)
|
| 122 |
+
return result_uri
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_dataset_features():
|
| 126 |
+
"""Get the dataset feature schema."""
|
| 127 |
+
from datasets import Features, Sequence, Value, Image as HfImage
|
| 128 |
+
|
| 129 |
+
return Features({
|
| 130 |
+
"sample_id": Value("string"),
|
| 131 |
+
"dataset_index": Value("int64"),
|
| 132 |
+
"source_image": HfImage(),
|
| 133 |
+
"document_with_boxes_image": HfImage(),
|
| 134 |
+
"document_markdown": Value("string"),
|
| 135 |
+
"extracted_figures": Sequence(HfImage()),
|
| 136 |
+
"extracted_figures_metadata": Sequence(Value("string")),
|
| 137 |
+
"document_final_markdown": Value("string"),
|
| 138 |
+
})
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def load_dataset_from_gcs(gcs_uri: str, split: str = "train") -> "Dataset":
|
| 142 |
+
"""Load HF dataset directly from GCS (saved with save_to_disk).
|
| 143 |
+
|
| 144 |
+
Downloads files locally first to avoid gcsfs caching issues.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
gcs_uri: GCS URI to dataset directory (gs://bucket/path/to/dataset/)
|
| 148 |
+
split: Unused, kept for API compatibility
|
| 149 |
+
|
| 150 |
+
Returns:
|
| 151 |
+
Loaded Dataset
|
| 152 |
+
|
| 153 |
+
Requires:
|
| 154 |
+
pip install datasets google-cloud-storage
|
| 155 |
+
"""
|
| 156 |
+
from datasets import load_from_disk
|
| 157 |
+
import tempfile
|
| 158 |
+
|
| 159 |
+
LOGGER.info("Loading dataset from %s", gcs_uri)
|
| 160 |
+
|
| 161 |
+
# Parse GCS URI
|
| 162 |
+
bucket_name, prefix = parse_gcs_uri(gcs_uri)
|
| 163 |
+
|
| 164 |
+
# Download to local temp directory (bypasses gcsfs cache)
|
| 165 |
+
client = get_gcs_client()
|
| 166 |
+
bucket = client.bucket(bucket_name)
|
| 167 |
+
local_dir = tempfile.mkdtemp(prefix="gcs_dataset_")
|
| 168 |
+
|
| 169 |
+
blobs = list(bucket.list_blobs(prefix=f"{prefix}/"))
|
| 170 |
+
for blob in blobs:
|
| 171 |
+
filename = blob.name.split('/')[-1]
|
| 172 |
+
if filename: # Skip directory markers
|
| 173 |
+
local_path = f"{local_dir}/{filename}"
|
| 174 |
+
blob.download_to_filename(local_path)
|
| 175 |
+
|
| 176 |
+
LOGGER.info("Downloaded %d files to %s", len(blobs), local_dir)
|
| 177 |
+
|
| 178 |
+
# Load from local
|
| 179 |
+
ds = load_from_disk(local_dir)
|
| 180 |
+
|
| 181 |
+
return ds
|
llm_ocr/config.py
CHANGED
|
@@ -150,14 +150,3 @@ class AssembleSettings:
|
|
| 150 |
source_repo_id=env("SOURCE_REPO_ID") or env("HF_REPO_ID"),
|
| 151 |
hub=HubSettings.from_env("HF"),
|
| 152 |
)
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
__all__ = [
|
| 156 |
-
"env",
|
| 157 |
-
"FigureMetadata",
|
| 158 |
-
"InferenceSettings",
|
| 159 |
-
"HubSettings",
|
| 160 |
-
"ExtractSettings",
|
| 161 |
-
"DescribeSettings",
|
| 162 |
-
"AssembleSettings",
|
| 163 |
-
]
|
|
|
|
| 150 |
source_repo_id=env("SOURCE_REPO_ID") or env("HF_REPO_ID"),
|
| 151 |
hub=HubSettings.from_env("HF"),
|
| 152 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llm_ocr/document.py
CHANGED
|
@@ -414,16 +414,3 @@ def display_samples(dataset, num_samples: int = 2) -> None:
|
|
| 414 |
except Exception:
|
| 415 |
pass
|
| 416 |
print()
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
__all__ = [
|
| 420 |
-
"encode_image",
|
| 421 |
-
"build_document_markdown",
|
| 422 |
-
"enrich_markdown_with_captions",
|
| 423 |
-
"render_markdown_with_images",
|
| 424 |
-
"render_sample_markdown",
|
| 425 |
-
"display_markdown",
|
| 426 |
-
"display_samples",
|
| 427 |
-
"write_text",
|
| 428 |
-
"write_json",
|
| 429 |
-
]
|
|
|
|
| 414 |
except Exception:
|
| 415 |
pass
|
| 416 |
print()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llm_ocr/server.py
CHANGED
|
@@ -85,18 +85,34 @@ def shutdown_server(server_process: subprocess.Popen) -> None:
|
|
| 85 |
thread.join(timeout=1)
|
| 86 |
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
def wait_for_server(url: str, timeout_s: int = None, interval_s: int = 5) -> bool:
|
|
|
|
| 89 |
if timeout_s is None:
|
| 90 |
timeout_s = int(os.environ.get("VLLM_STARTUP_TIMEOUT", "600")) # 10 min default
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
| 92 |
deadline = time.time() + timeout_s
|
| 93 |
while time.time() < deadline:
|
| 94 |
try:
|
| 95 |
if requests.get(url, timeout=5).ok:
|
|
|
|
|
|
|
| 96 |
return True
|
| 97 |
except Exception:
|
| 98 |
pass
|
| 99 |
time.sleep(interval_s)
|
|
|
|
|
|
|
|
|
|
| 100 |
return False
|
| 101 |
|
| 102 |
|
|
@@ -217,13 +233,3 @@ class DeepSeekClient:
|
|
| 217 |
finally:
|
| 218 |
asyncio.set_event_loop(None)
|
| 219 |
loop.close()
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
__all__ = [
|
| 223 |
-
"launch_vllm",
|
| 224 |
-
"shutdown_server",
|
| 225 |
-
"wait_for_server",
|
| 226 |
-
"should_launch_server",
|
| 227 |
-
"base_url_from_env",
|
| 228 |
-
"DeepSeekClient",
|
| 229 |
-
]
|
|
|
|
| 85 |
thread.join(timeout=1)
|
| 86 |
|
| 87 |
|
| 88 |
+
def _format_duration(seconds: float) -> str:
|
| 89 |
+
"""Format duration as mm:ss."""
|
| 90 |
+
minutes = int(seconds // 60)
|
| 91 |
+
secs = int(seconds % 60)
|
| 92 |
+
return f"{minutes:02d}:{secs:02d}"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
def wait_for_server(url: str, timeout_s: int = None, interval_s: int = 5) -> bool:
|
| 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:
|
| 106 |
if requests.get(url, timeout=5).ok:
|
| 107 |
+
elapsed = time.time() - start_time
|
| 108 |
+
LOGGER.info("✅ vLLM server ready in %s", _format_duration(elapsed))
|
| 109 |
return True
|
| 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
|
| 117 |
|
| 118 |
|
|
|
|
| 233 |
finally:
|
| 234 |
asyncio.set_event_loop(None)
|
| 235 |
loop.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llm_ocr/sm_io.py
CHANGED
|
@@ -187,11 +187,3 @@ def load_dataset_from_s3(s3_uri: str, split: str = "train") -> "Dataset":
|
|
| 187 |
ds = load_from_disk(local_dir)
|
| 188 |
|
| 189 |
return ds
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
__all__ = [
|
| 193 |
-
"save_dataset_to_s3",
|
| 194 |
-
"load_dataset_from_s3",
|
| 195 |
-
"parse_s3_uri",
|
| 196 |
-
"get_s3_client",
|
| 197 |
-
]
|
|
|
|
| 187 |
ds = load_from_disk(local_dir)
|
| 188 |
|
| 189 |
return ds
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llm_ocr/stages.py
CHANGED
|
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|
| 4 |
import json
|
| 5 |
import logging
|
| 6 |
import shutil
|
|
|
|
| 7 |
from dataclasses import asdict
|
| 8 |
from datetime import datetime
|
| 9 |
from pathlib import Path
|
|
@@ -11,7 +12,6 @@ from typing import Any, Dict, List
|
|
| 11 |
|
| 12 |
from datasets import Features, Sequence, Value, load_dataset, Image as HfImage
|
| 13 |
from PIL import Image
|
| 14 |
-
from torch.utils.data import DataLoader
|
| 15 |
|
| 16 |
from .config import AssembleSettings, DescribeSettings, ExtractSettings, env
|
| 17 |
from .document import build_document_markdown, enrich_markdown_with_captions, write_json
|
|
@@ -20,6 +20,13 @@ from .storage import get_storage, get_source_storage
|
|
| 20 |
LOGGER = logging.getLogger(__name__)
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def _now_iso() -> str:
|
| 24 |
return datetime.utcnow().isoformat() + "Z"
|
| 25 |
|
|
@@ -40,6 +47,12 @@ def _dataset_features() -> Features:
|
|
| 40 |
|
| 41 |
def run_stage_extract(settings: ExtractSettings) -> None:
|
| 42 |
"""Run OCR extraction on dataset samples."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
dataset = load_dataset(
|
| 44 |
settings.dataset_name,
|
| 45 |
settings.dataset_config,
|
|
@@ -192,11 +205,16 @@ def run_stage_extract(settings: ExtractSettings) -> None:
|
|
| 192 |
storage = get_storage(repo_id=settings.hub.repo_id)
|
| 193 |
storage.save_dataset(ds, "dataset")
|
| 194 |
|
| 195 |
-
|
|
|
|
|
|
|
| 196 |
|
| 197 |
|
| 198 |
def run_stage_describe(settings: DescribeSettings) -> None:
|
| 199 |
"""Describe figures in the dataset that lack descriptions."""
|
|
|
|
|
|
|
|
|
|
| 200 |
# Get source storage and load dataset
|
| 201 |
source_storage = get_source_storage(source_repo_id=settings.source_repo_id or settings.hub.repo_id)
|
| 202 |
if not source_storage.is_configured:
|
|
@@ -326,11 +344,16 @@ def run_stage_describe(settings: DescribeSettings) -> None:
|
|
| 326 |
storage = get_storage(repo_id=settings.hub.repo_id)
|
| 327 |
storage.save_dataset(updated, "dataset")
|
| 328 |
|
| 329 |
-
|
|
|
|
|
|
|
| 330 |
|
| 331 |
|
| 332 |
def run_stage_assemble(settings: AssembleSettings) -> None:
|
| 333 |
"""Enrich markdown with figure descriptions."""
|
|
|
|
|
|
|
|
|
|
| 334 |
# Get source storage and load dataset
|
| 335 |
source_storage = get_source_storage(source_repo_id=settings.source_repo_id or settings.hub.repo_id)
|
| 336 |
if not source_storage.is_configured:
|
|
@@ -369,7 +392,6 @@ def run_stage_assemble(settings: AssembleSettings) -> None:
|
|
| 369 |
storage = get_storage(repo_id=settings.hub.repo_id)
|
| 370 |
storage.save_dataset(dataset, "dataset")
|
| 371 |
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
__all__ = ["run_stage_extract", "run_stage_describe", "run_stage_assemble"]
|
|
|
|
| 4 |
import json
|
| 5 |
import logging
|
| 6 |
import shutil
|
| 7 |
+
import time
|
| 8 |
from dataclasses import asdict
|
| 9 |
from datetime import datetime
|
| 10 |
from pathlib import Path
|
|
|
|
| 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
|
|
|
|
| 20 |
LOGGER = logging.getLogger(__name__)
|
| 21 |
|
| 22 |
|
| 23 |
+
def _format_duration(seconds: float) -> str:
|
| 24 |
+
"""Format duration as mm:ss."""
|
| 25 |
+
minutes = int(seconds // 60)
|
| 26 |
+
secs = int(seconds % 60)
|
| 27 |
+
return f"{minutes:02d}:{secs:02d}"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
def _now_iso() -> str:
|
| 31 |
return datetime.utcnow().isoformat() + "Z"
|
| 32 |
|
|
|
|
| 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,
|
|
|
|
| 205 |
storage = get_storage(repo_id=settings.hub.repo_id)
|
| 206 |
storage.save_dataset(ds, "dataset")
|
| 207 |
|
| 208 |
+
elapsed = time.time() - stage_start
|
| 209 |
+
LOGGER.info("✅ Extract complete | docs=%d | failures=%d | duration=%s",
|
| 210 |
+
doc_count, len(failures), _format_duration(elapsed))
|
| 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(source_repo_id=settings.source_repo_id or settings.hub.repo_id)
|
| 220 |
if not source_storage.is_configured:
|
|
|
|
| 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("✅ Describe complete | described=%d | failures=%d | duration=%s",
|
| 349 |
+
described, len(failures), _format_duration(elapsed))
|
| 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(source_repo_id=settings.source_repo_id or settings.hub.repo_id)
|
| 359 |
if not source_storage.is_configured:
|
|
|
|
| 392 |
storage = get_storage(repo_id=settings.hub.repo_id)
|
| 393 |
storage.save_dataset(dataset, "dataset")
|
| 394 |
|
| 395 |
+
elapsed = time.time() - stage_start
|
| 396 |
+
LOGGER.info("✅ Assemble complete | assembled=%d | duration=%s",
|
| 397 |
+
assembled_count, _format_duration(elapsed))
|
|
|
llm_ocr/storage.py
CHANGED
|
@@ -187,7 +187,7 @@ class GCSStorage(DatasetStorage):
|
|
| 187 |
return False
|
| 188 |
|
| 189 |
try:
|
| 190 |
-
from .
|
| 191 |
|
| 192 |
save_dataset_to_gcs(dataset, self.output_uri, name)
|
| 193 |
return True
|
|
@@ -204,7 +204,7 @@ class GCSStorage(DatasetStorage):
|
|
| 204 |
return None
|
| 205 |
|
| 206 |
try:
|
| 207 |
-
from .
|
| 208 |
|
| 209 |
return load_dataset_from_gcs(self.input_uri, split=split)
|
| 210 |
except ImportError as exc:
|
|
@@ -273,13 +273,3 @@ def get_source_storage(
|
|
| 273 |
|
| 274 |
repo_id = source_repo_id or env("SOURCE_REPO_ID") or env("HF_REPO_ID")
|
| 275 |
return HFHubStorage(repo_id=repo_id)
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
__all__ = [
|
| 279 |
-
"DatasetStorage",
|
| 280 |
-
"HFHubStorage",
|
| 281 |
-
"S3Storage",
|
| 282 |
-
"GCSStorage",
|
| 283 |
-
"get_storage",
|
| 284 |
-
"get_source_storage",
|
| 285 |
-
]
|
|
|
|
| 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
|
|
|
|
| 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:
|
|
|
|
| 273 |
|
| 274 |
repo_id = source_repo_id or env("SOURCE_REPO_ID") or env("HF_REPO_ID")
|
| 275 |
return HFHubStorage(repo_id=repo_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|