Florent Gbelidji commited on
Commit
e51b44e
·
verified ·
1 Parent(s): b277483

Upload folder using huggingface_hub

Browse files
hf_job_runner.py CHANGED
@@ -3,7 +3,7 @@
3
  # dependencies = [
4
  # "huggingface-hub[hf_transfer,hf_xet]",
5
  # "torch",
6
- # "datasets>=2.0.0",
7
  # "pyarrow>=12.0.0",
8
  # "numpy",
9
  # "pillow",
 
3
  # dependencies = [
4
  # "huggingface-hub[hf_transfer,hf_xet]",
5
  # "torch",
6
+ # "datasets>=4.0.0",
7
  # "pyarrow>=12.0.0",
8
  # "numpy",
9
  # "pillow",
llm_ocr/config.py CHANGED
@@ -26,11 +26,9 @@ def env(key: str, default: T = None, cast: Type[T] = str) -> T:
26
 
27
  @dataclass
28
  class FigureMetadata:
29
- """Metadata for an extracted figure."""
30
  figure_id: str
31
  label: str
32
- image_path: str
33
- document_relative_path: str
34
  bounding_box_pixels: Dict[str, int]
35
  description: Optional[str] = None
36
 
 
26
 
27
  @dataclass
28
  class FigureMetadata:
29
+ """Metadata for an extracted figure (image stored in dataset, not as file)."""
30
  figure_id: str
31
  label: str
 
 
32
  bounding_box_pixels: Dict[str, int]
33
  description: Optional[str] = None
34
 
llm_ocr/document.py CHANGED
@@ -8,7 +8,7 @@ import logging
8
  import re
9
  from io import BytesIO
10
  from pathlib import Path
11
- from typing import Any, Dict, List, Optional, Tuple
12
 
13
  import numpy as np
14
  from PIL import Image, ImageDraw, ImageFont
@@ -22,8 +22,9 @@ GROUNDING_PATTERN = re.compile(
22
  re.DOTALL,
23
  )
24
 
 
25
  FIGURE_MARKDOWN_PATTERN = re.compile(
26
- r"!\[Figure (?P<figure_id>[^\]]+)\]\((?P<path>[^)]+)\)"
27
  )
28
 
29
 
@@ -81,40 +82,30 @@ def apply_replacements(text: str, replacements: List[Tuple[int, int, str]]) -> s
81
  return postprocess_markdown("".join(segments))
82
 
83
 
84
- def save_figure(
85
  image: Image.Image,
86
- sample_dir: Path,
87
  sample_id: str,
88
  figure_index: int,
89
  pixel_box: List[int],
90
  label: str,
91
- path_prefix: str = "",
92
- ) -> Optional[FigureMetadata]:
93
- """Crop and save a figure from the source image."""
 
 
 
94
  x1, y1, x2, y2 = pixel_box
95
  crop = image.crop((x1, y1, x2, y2)).copy()
96
 
97
- figures_dir = sample_dir / "figures"
98
- figures_dir.mkdir(parents=True, exist_ok=True)
99
-
100
  figure_id = f"{sample_id}_fig{figure_index:02d}"
101
- figure_filename = f"{figure_id}.png"
102
- full_path = figures_dir / figure_filename
103
- crop.save(full_path)
104
-
105
- # Path relative to dataset root (includes path_prefix like "outputs/extract")
106
- if path_prefix:
107
- document_relative_path = f"{path_prefix}/{sample_id}/figures/{figure_filename}"
108
- else:
109
- document_relative_path = f"{sample_id}/figures/{figure_filename}"
110
 
111
- return FigureMetadata(
112
  figure_id=figure_id,
113
  label=label,
114
- image_path=str(full_path),
115
- document_relative_path=document_relative_path,
116
  bounding_box_pixels={"x1": x1, "y1": y1, "x2": x2, "y2": y2},
117
  )
 
 
118
 
119
 
120
  def write_text(path: Path, content: str) -> None:
@@ -133,24 +124,21 @@ def write_json(path: Path, payload: Any) -> None:
133
  def build_document_markdown(
134
  image: Image.Image,
135
  response_text: str,
136
- sample_dir: Path,
137
  sample_id: str,
138
- path_prefix: str = "",
139
- ) -> Tuple[str, List[FigureMetadata], Image.Image]:
140
  """
141
  Process model response to extract markdown and figures.
142
 
143
- Args:
144
- path_prefix: Prefix for paths in markdown (e.g., "outputs/extract")
145
-
146
  Returns:
147
- - Cleaned markdown with figure references
148
- - List of extracted figure metadata
 
149
  - Annotated image with bounding boxes
150
  """
151
  blocks = extract_grounding_blocks(response_text)
152
  replacements: List[Tuple[int, int, str]] = []
153
  figures: List[FigureMetadata] = []
 
154
  figure_index = 1
155
 
156
  img_draw = image.copy()
@@ -179,24 +167,21 @@ def build_document_markdown(
179
 
180
  # Extract figures (images)
181
  if label == "image":
182
- figure_metadata = save_figure(
183
  image=image,
184
- sample_dir=sample_dir,
185
  sample_id=sample_id,
186
  figure_index=figure_index,
187
  pixel_box=pixel_box,
188
  label=block["label"],
189
- path_prefix=path_prefix,
190
  )
191
- if figure_metadata:
192
- figures.append(figure_metadata)
193
- replacements.append((
194
- start, end,
195
- f"![Figure {figure_metadata.figure_id}]({figure_metadata.document_relative_path})",
196
- ))
197
- figure_index += 1
198
- else:
199
- replacements.append((start, end, ""))
200
  else:
201
  replacements.append((start, end, ""))
202
 
@@ -214,19 +199,31 @@ def build_document_markdown(
214
 
215
  img_draw.paste(overlay, (0, 0), overlay)
216
  markdown = apply_replacements(response_text, replacements)
217
- return markdown, figures, img_draw
218
 
219
 
220
  def enrich_markdown_with_captions(
221
  markdown: str,
222
  description_map: Dict[str, Dict[str, Any]],
223
  ) -> str:
224
- """Add figure captions to markdown based on descriptions."""
 
 
 
 
225
  used: set[str] = set()
226
 
227
  def replace(match: re.Match[str]) -> str:
228
- figure_id = match.group("figure_id").strip()
229
  path = match.group("path").strip()
 
 
 
 
 
 
 
 
230
  entry = description_map.get(figure_id)
231
  if not entry:
232
  return match.group(0)
@@ -235,20 +232,102 @@ def enrich_markdown_with_captions(
235
  if not description:
236
  return match.group(0)
237
 
238
- alt_text = f"Figure {figure_id}: {description}"
239
- rendered = f"![{alt_text}]({path})"
 
240
  if figure_id not in used:
241
- rendered += f"\n\n*Figure {figure_id}: {description}*\n"
242
  used.add(figure_id)
243
  return rendered
244
 
245
  return FIGURE_MARKDOWN_PATTERN.sub(replace, markdown)
246
 
247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  __all__ = [
249
  "encode_image",
250
  "build_document_markdown",
251
  "enrich_markdown_with_captions",
 
 
252
  "write_text",
253
  "write_json",
254
  ]
 
8
  import re
9
  from io import BytesIO
10
  from pathlib import Path
11
+ from typing import Any, Dict, List, Tuple
12
 
13
  import numpy as np
14
  from PIL import Image, ImageDraw, ImageFont
 
22
  re.DOTALL,
23
  )
24
 
25
+ # Matches both old path format and new figure: URI format
26
  FIGURE_MARKDOWN_PATTERN = re.compile(
27
+ r"!\[(?:Figure )?(?P<figure_id>[^\]]+)\]\((?P<path>[^)]+)\)"
28
  )
29
 
30
 
 
82
  return postprocess_markdown("".join(segments))
83
 
84
 
85
+ def crop_figure(
86
  image: Image.Image,
 
87
  sample_id: str,
88
  figure_index: int,
89
  pixel_box: List[int],
90
  label: str,
91
+ ) -> Tuple[FigureMetadata, Image.Image]:
92
+ """Crop a figure from the source image.
93
+
94
+ Returns:
95
+ Tuple of (metadata, cropped_image) - image is for embedding in dataset
96
+ """
97
  x1, y1, x2, y2 = pixel_box
98
  crop = image.crop((x1, y1, x2, y2)).copy()
99
 
 
 
 
100
  figure_id = f"{sample_id}_fig{figure_index:02d}"
 
 
 
 
 
 
 
 
 
101
 
102
+ metadata = FigureMetadata(
103
  figure_id=figure_id,
104
  label=label,
 
 
105
  bounding_box_pixels={"x1": x1, "y1": y1, "x2": x2, "y2": y2},
106
  )
107
+
108
+ return metadata, crop
109
 
110
 
111
  def write_text(path: Path, content: str) -> None:
 
124
  def build_document_markdown(
125
  image: Image.Image,
126
  response_text: str,
 
127
  sample_id: str,
128
+ ) -> Tuple[str, List[FigureMetadata], List[Image.Image], Image.Image]:
 
129
  """
130
  Process model response to extract markdown and figures.
131
 
 
 
 
132
  Returns:
133
+ - Cleaned markdown with figure references (using figure:{id} URIs)
134
+ - List of figure metadata
135
+ - List of cropped figure images (for embedding in dataset)
136
  - Annotated image with bounding boxes
137
  """
138
  blocks = extract_grounding_blocks(response_text)
139
  replacements: List[Tuple[int, int, str]] = []
140
  figures: List[FigureMetadata] = []
141
+ figure_images: List[Image.Image] = []
142
  figure_index = 1
143
 
144
  img_draw = image.copy()
 
167
 
168
  # Extract figures (images)
169
  if label == "image":
170
+ metadata, crop = crop_figure(
171
  image=image,
 
172
  sample_id=sample_id,
173
  figure_index=figure_index,
174
  pixel_box=pixel_box,
175
  label=block["label"],
 
176
  )
177
+ figures.append(metadata)
178
+ figure_images.append(crop)
179
+ # Use figure:{id} URI format - clearly an identifier, not a file path
180
+ replacements.append((
181
+ start, end,
182
+ f"![{metadata.figure_id}](figure:{metadata.figure_id})",
183
+ ))
184
+ figure_index += 1
 
185
  else:
186
  replacements.append((start, end, ""))
187
 
 
199
 
200
  img_draw.paste(overlay, (0, 0), overlay)
201
  markdown = apply_replacements(response_text, replacements)
202
+ return markdown, figures, figure_images, img_draw
203
 
204
 
205
  def enrich_markdown_with_captions(
206
  markdown: str,
207
  description_map: Dict[str, Dict[str, Any]],
208
  ) -> str:
209
+ """Add figure captions to markdown based on descriptions.
210
+
211
+ Handles both new format ![figure_id](figure:figure_id) and
212
+ legacy format ![Figure figure_id](path).
213
+ """
214
  used: set[str] = set()
215
 
216
  def replace(match: re.Match[str]) -> str:
217
+ alt_text = match.group("figure_id").strip()
218
  path = match.group("path").strip()
219
+
220
+ # Extract figure_id from figure:{id} URI or from alt text
221
+ if path.startswith("figure:"):
222
+ figure_id = path[7:] # Remove "figure:" prefix
223
+ else:
224
+ # Legacy format - figure_id is in alt text after "Figure "
225
+ figure_id = alt_text.replace("Figure ", "").split(":")[0].strip()
226
+
227
  entry = description_map.get(figure_id)
228
  if not entry:
229
  return match.group(0)
 
232
  if not description:
233
  return match.group(0)
234
 
235
+ # Create enriched alt text with description
236
+ new_alt_text = f"{figure_id}: {description}"
237
+ rendered = f"![{new_alt_text}]({path})"
238
  if figure_id not in used:
239
+ rendered += f"\n\n*{figure_id}: {description}*\n"
240
  used.add(figure_id)
241
  return rendered
242
 
243
  return FIGURE_MARKDOWN_PATTERN.sub(replace, markdown)
244
 
245
 
246
+ def render_markdown_with_images(
247
+ markdown: str,
248
+ figure_images: List[Image.Image],
249
+ figure_metadata: List[Dict[str, Any]],
250
+ ) -> str:
251
+ """
252
+ Render markdown with embedded images as base64 data URIs.
253
+
254
+ The dataset stores images in `extracted_figures` (PIL images) and metadata
255
+ in `extracted_figures_metadata` (with figure_id). This function replaces
256
+ figure:{id} URIs in markdown with base64-encoded images.
257
+
258
+ Args:
259
+ markdown: Markdown text with ![figure_id](figure:figure_id) references
260
+ figure_images: List of PIL images from dataset's extracted_figures column
261
+ figure_metadata: List of metadata dicts (parsed from extracted_figures_metadata)
262
+
263
+ Returns:
264
+ Self-contained markdown with images embedded as data URIs
265
+ """
266
+ # Build figure_id -> image mapping
267
+ id_to_image: Dict[str, Image.Image] = {}
268
+ for i, meta in enumerate(figure_metadata):
269
+ fig_id = meta.get("figure_id", "")
270
+ if fig_id and i < len(figure_images) and figure_images[i] is not None:
271
+ id_to_image[fig_id] = figure_images[i]
272
+
273
+ def replace(match: re.Match[str]) -> str:
274
+ alt_text = match.group("figure_id").strip()
275
+ path = match.group("path").strip()
276
+
277
+ # Extract figure_id from figure:{id} URI or use alt_text as fallback
278
+ if path.startswith("figure:"):
279
+ figure_id = path[7:] # Remove "figure:" prefix
280
+ else:
281
+ # Legacy path format - extract figure_id from alt_text
282
+ figure_id = alt_text.replace("Figure ", "").split(":")[0].strip()
283
+
284
+ img = id_to_image.get(figure_id)
285
+ if img is None:
286
+ return match.group(0) # Keep original if image not found
287
+
288
+ # Embed as base64 data URI
289
+ data_uri = f"data:image/png;base64,{encode_image(img)}"
290
+ return f"![{alt_text}]({data_uri})"
291
+
292
+ return FIGURE_MARKDOWN_PATTERN.sub(replace, markdown)
293
+
294
+
295
+ def render_sample_markdown(sample: Dict[str, Any]) -> str:
296
+ """
297
+ Render a dataset sample's markdown with embedded images.
298
+
299
+ Args:
300
+ sample: A row from the dataset (dict with column values)
301
+
302
+ Returns:
303
+ Self-contained markdown string with images as data URIs
304
+ """
305
+ markdown = sample.get("document_final_markdown") or sample.get("document_markdown") or ""
306
+
307
+ # Parse metadata
308
+ raw_metadata = sample.get("extracted_figures_metadata") or []
309
+ metadata = []
310
+ for m in raw_metadata:
311
+ if isinstance(m, str):
312
+ metadata.append(json.loads(m))
313
+ else:
314
+ metadata.append(m)
315
+
316
+ images = sample.get("extracted_figures") or []
317
+
318
+ return render_markdown_with_images(
319
+ markdown=markdown,
320
+ figure_images=images,
321
+ figure_metadata=metadata,
322
+ )
323
+
324
+
325
  __all__ = [
326
  "encode_image",
327
  "build_document_markdown",
328
  "enrich_markdown_with_captions",
329
+ "render_markdown_with_images",
330
+ "render_sample_markdown",
331
  "write_text",
332
  "write_json",
333
  ]
llm_ocr/gcr_io.py CHANGED
@@ -122,8 +122,24 @@ def save_dataset_to_gcs(
122
  return result_uri
123
 
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  def load_dataset_from_gcs(gcs_uri: str, split: str = "train") -> "Dataset":
126
- """Load HF dataset from GCS (Arrow format).
127
 
128
  Args:
129
  gcs_uri: GCS URI to dataset directory (gs://bucket/path/to/dataset/)
@@ -131,41 +147,18 @@ def load_dataset_from_gcs(gcs_uri: str, split: str = "train") -> "Dataset":
131
 
132
  Returns:
133
  Loaded Dataset
 
 
 
134
  """
135
  from datasets import load_from_disk
136
 
137
- bucket_name, prefix = parse_gcs_uri(gcs_uri)
138
- prefix = prefix.rstrip("/")
139
 
140
- client = get_gcs_client()
141
- bucket = client.bucket(bucket_name)
142
 
143
- # Create temp directory for download
144
- local_dir = Path(f"/tmp/gcs_arrow_{prefix.replace('/', '_')}")
145
- if local_dir.exists():
146
- shutil.rmtree(local_dir)
147
- local_dir.mkdir(parents=True)
148
-
149
- # Download all files from GCS prefix
150
- blobs = list(bucket.list_blobs(prefix=prefix))
151
- file_count = 0
152
-
153
- for blob in blobs:
154
- # Get relative path from prefix
155
- rel_path = blob.name[len(prefix):].lstrip("/")
156
- if not rel_path:
157
- continue
158
- local_path = local_dir / rel_path
159
- local_path.parent.mkdir(parents=True, exist_ok=True)
160
- LOGGER.info("Downloading gs://%s/%s", bucket_name, blob.name)
161
- blob.download_to_filename(str(local_path))
162
- file_count += 1
163
-
164
- if file_count == 0:
165
- raise FileNotFoundError(f"No files found at {gcs_uri}")
166
-
167
- LOGGER.info("Loading dataset from %d files", file_count)
168
- return load_from_disk(str(local_dir))
169
 
170
 
171
  __all__ = [
 
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
  Args:
145
  gcs_uri: GCS URI to dataset directory (gs://bucket/path/to/dataset/)
 
147
 
148
  Returns:
149
  Loaded Dataset
150
+
151
+ Requires:
152
+ pip install datasets gcsfs
153
  """
154
  from datasets import load_from_disk
155
 
156
+ LOGGER.info("Loading dataset from %s", gcs_uri)
 
157
 
158
+ # load_from_disk supports GCS URIs directly with gcsfs
159
+ ds = load_from_disk(gcs_uri)
160
 
161
+ return ds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
 
164
  __all__ = [
llm_ocr/sm_io.py CHANGED
@@ -126,8 +126,24 @@ def save_dataset_to_s3(
126
  return result_uri
127
 
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  def load_dataset_from_s3(s3_uri: str, split: str = "train") -> "Dataset":
130
- """Load HF dataset from S3 (Arrow format).
131
 
132
  Args:
133
  s3_uri: S3 URI to dataset directory (s3://bucket/path/to/dataset/)
@@ -135,41 +151,18 @@ def load_dataset_from_s3(s3_uri: str, split: str = "train") -> "Dataset":
135
 
136
  Returns:
137
  Loaded Dataset
 
 
 
138
  """
139
  from datasets import load_from_disk
140
 
141
- bucket, prefix = parse_s3_uri(s3_uri)
142
- prefix = prefix.rstrip("/")
143
- s3 = get_s3_client()
144
 
145
- # Create temp directory for download
146
- local_dir = Path(f"/tmp/s3_arrow_{prefix.replace('/', '_')}")
147
- if local_dir.exists():
148
- shutil.rmtree(local_dir)
149
- local_dir.mkdir(parents=True)
150
-
151
- # Download all files from S3 prefix
152
- paginator = s3.get_paginator("list_objects_v2")
153
- file_count = 0
154
-
155
- for page in paginator.paginate(Bucket=bucket, Prefix=prefix):
156
- for obj in page.get("Contents", []):
157
- key = obj["Key"]
158
- # Get relative path from prefix
159
- rel_path = key[len(prefix):].lstrip("/")
160
- if not rel_path:
161
- continue
162
- local_path = local_dir / rel_path
163
- local_path.parent.mkdir(parents=True, exist_ok=True)
164
- LOGGER.info("Downloading s3://%s/%s", bucket, key)
165
- s3.download_file(bucket, key, str(local_path))
166
- file_count += 1
167
-
168
- if file_count == 0:
169
- raise FileNotFoundError(f"No files found at {s3_uri}")
170
-
171
- LOGGER.info("Loading dataset from %d files", file_count)
172
- return load_from_disk(str(local_dir))
173
 
174
 
175
  __all__ = [
 
126
  return result_uri
127
 
128
 
129
+ def get_dataset_features():
130
+ """Get the dataset feature schema."""
131
+ from datasets import Features, Sequence, Value, Image as HfImage
132
+
133
+ return Features({
134
+ "sample_id": Value("string"),
135
+ "dataset_index": Value("int64"),
136
+ "source_image": HfImage(),
137
+ "document_with_boxes_image": HfImage(),
138
+ "document_markdown": Value("string"),
139
+ "extracted_figures": Sequence(HfImage()),
140
+ "extracted_figures_metadata": Sequence(Value("string")),
141
+ "document_final_markdown": Value("string"),
142
+ })
143
+
144
+
145
  def load_dataset_from_s3(s3_uri: str, split: str = "train") -> "Dataset":
146
+ """Load HF dataset directly from S3 (saved with save_to_disk).
147
 
148
  Args:
149
  s3_uri: S3 URI to dataset directory (s3://bucket/path/to/dataset/)
 
151
 
152
  Returns:
153
  Loaded Dataset
154
+
155
+ Requires:
156
+ pip install datasets[s3] s3fs
157
  """
158
  from datasets import load_from_disk
159
 
160
+ LOGGER.info("Loading dataset from %s", s3_uri)
 
 
161
 
162
+ # load_from_disk supports S3 URIs directly with s3fs
163
+ ds = load_from_disk(s3_uri, storage_options={"anon": False})
164
+
165
+ return ds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
 
168
  __all__ = [
llm_ocr/stages.py CHANGED
@@ -14,7 +14,7 @@ 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, write_text
18
  from .storage import get_storage, get_source_storage
19
 
20
  LOGGER = logging.getLogger(__name__)
@@ -104,15 +104,23 @@ def run_stage_extract(settings: ExtractSettings) -> None:
104
  sample_dir = ctx["sample_dir"]
105
  sample_id = ctx["sample_id"]
106
 
107
- markdown, figures, img_draw = build_document_markdown(
108
- image=img, response_text=text, sample_dir=sample_dir,
109
- sample_id=sample_id, path_prefix=""
110
  )
111
 
112
- # Save images locally for dataset loading
113
  source_path = sample_dir / "source.png"
114
  boxes_path = sample_dir / "document_with_boxes.png"
115
  img_draw.save(boxes_path)
 
 
 
 
 
 
 
 
 
116
 
117
  docs.append({
118
  "sample_id": sample_id,
@@ -120,7 +128,7 @@ def run_stage_extract(settings: ExtractSettings) -> None:
120
  "source_image": str(source_path),
121
  "document_with_boxes_image": str(boxes_path),
122
  "document_markdown": markdown,
123
- "extracted_figures": [str(f.image_path) for f in figures],
124
  "extracted_figures_metadata": [json.dumps(asdict(f)) for f in figures],
125
  "document_final_markdown": "", # Filled in assemble stage
126
  })
@@ -290,6 +298,8 @@ def run_stage_describe(settings: DescribeSettings) -> None:
290
  LOGGER.info("No descriptions generated")
291
  return
292
 
 
 
293
  def apply(row):
294
  metas = row.get("extracted_figures_metadata") or []
295
  new_metas = []
@@ -298,12 +308,19 @@ def run_stage_describe(settings: DescribeSettings) -> None:
298
  if meta.get("figure_id") in lookup:
299
  meta["description"] = lookup[meta["figure_id"]]
300
  new_metas.append(json.dumps(meta))
301
- row["extracted_figures_metadata"] = new_metas
302
- return row
303
 
304
- updated = dataset.map(apply, features=dataset.features)
 
305
  shutil.rmtree(desc_dir)
306
 
 
 
 
 
 
 
 
307
  # Get output storage and save
308
  storage = get_storage(repo_id=settings.hub.repo_id)
309
  storage.save_dataset(updated, "dataset")
 
14
  from torch.utils.data import DataLoader
15
 
16
  from .config import AssembleSettings, DescribeSettings, ExtractSettings, env
17
+ from .document import build_document_markdown, enrich_markdown_with_captions, write_json
18
  from .storage import get_storage, get_source_storage
19
 
20
  LOGGER = logging.getLogger(__name__)
 
104
  sample_dir = ctx["sample_dir"]
105
  sample_id = ctx["sample_id"]
106
 
107
+ markdown, figures, figure_images, img_draw = build_document_markdown(
108
+ image=img, response_text=text, sample_id=sample_id,
 
109
  )
110
 
111
+ # Save images locally for dataset loading (HfImage needs file paths)
112
  source_path = sample_dir / "source.png"
113
  boxes_path = sample_dir / "document_with_boxes.png"
114
  img_draw.save(boxes_path)
115
+
116
+ # Save figure images for dataset loading
117
+ figures_dir = sample_dir / "figures"
118
+ figures_dir.mkdir(parents=True, exist_ok=True)
119
+ figure_paths = []
120
+ for fig_meta, fig_img in zip(figures, figure_images):
121
+ fig_path = figures_dir / f"{fig_meta.figure_id}.png"
122
+ fig_img.save(fig_path)
123
+ figure_paths.append(str(fig_path))
124
 
125
  docs.append({
126
  "sample_id": sample_id,
 
128
  "source_image": str(source_path),
129
  "document_with_boxes_image": str(boxes_path),
130
  "document_markdown": markdown,
131
+ "extracted_figures": figure_paths,
132
  "extracted_figures_metadata": [json.dumps(asdict(f)) for f in figures],
133
  "document_final_markdown": "", # Filled in assemble stage
134
  })
 
298
  LOGGER.info("No descriptions generated")
299
  return
300
 
301
+ LOGGER.info("Applying %d descriptions to dataset", len(lookup))
302
+
303
  def apply(row):
304
  metas = row.get("extracted_figures_metadata") or []
305
  new_metas = []
 
308
  if meta.get("figure_id") in lookup:
309
  meta["description"] = lookup[meta["figure_id"]]
310
  new_metas.append(json.dumps(meta))
311
+ return {"extracted_figures_metadata": new_metas}
 
312
 
313
+ # Disable caching for this map operation to ensure fresh results
314
+ updated = dataset.map(apply, load_from_cache_file=False)
315
  shutil.rmtree(desc_dir)
316
 
317
+ # Verify descriptions were applied
318
+ sample_meta = updated[0].get("extracted_figures_metadata", [])
319
+ if sample_meta:
320
+ first_meta = json.loads(sample_meta[0]) if isinstance(sample_meta[0], str) else sample_meta[0]
321
+ LOGGER.info("Sample metadata after update: figure_id=%s, has_description=%s",
322
+ first_meta.get("figure_id"), first_meta.get("description") is not None)
323
+
324
  # Get output storage and save
325
  storage = get_storage(repo_id=settings.hub.repo_id)
326
  storage.save_dataset(updated, "dataset")