andersoncliffb commited on
Commit
2d62eb0
·
verified ·
1 Parent(s): 55ee624

Added UV script to move from single page OCR to consolidated OCR

Browse files
Files changed (1) hide show
  1. consolidate_ocr_dataset.py +320 -0
consolidate_ocr_dataset.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "datasets>=3.0.0",
5
+ # "huggingface_hub>=0.24.0",
6
+ # ]
7
+ # ///
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ from collections import OrderedDict
16
+ from typing import Any
17
+
18
+ from datasets import Dataset, DatasetDict, load_dataset
19
+
20
+
21
+ PAGE_RE = re.compile(r"_(\d{3,})-")
22
+
23
+
24
+ DEFAULT_KEEP_COLUMNS = [
25
+ "title",
26
+ "barcode",
27
+ "call_number",
28
+ "location",
29
+ "date_scanned",
30
+ "scanned_by",
31
+ "ld4p_id",
32
+ "original_zip",
33
+ ]
34
+
35
+
36
+ def normalize_value(value: Any) -> Any:
37
+ """Make values safe and stable for Dataset.from_list."""
38
+ if value is None:
39
+ return None
40
+
41
+ if isinstance(value, (str, int, float, bool)):
42
+ return value
43
+
44
+ try:
45
+ return json.dumps(value, ensure_ascii=False, sort_keys=True)
46
+ except TypeError:
47
+ return str(value)
48
+
49
+
50
+ def parse_page_number(source_path: str | None) -> int | None:
51
+ if not source_path:
52
+ return None
53
+
54
+ match = PAGE_RE.search(source_path)
55
+ if match:
56
+ return int(match.group(1))
57
+
58
+ return None
59
+
60
+
61
+ def make_document_id(row: dict[str, Any], group_by: list[str]) -> str:
62
+ values = [str(row.get(col, "")).strip() for col in group_by]
63
+ return "::".join(values)
64
+
65
+
66
+ def reduce_split(
67
+ ds: Dataset,
68
+ *,
69
+ group_by: list[str],
70
+ keep_columns: list[str],
71
+ markdown_column: str,
72
+ source_path_column: str,
73
+ inference_info_column: str,
74
+ add_page_markers: bool,
75
+ ) -> Dataset:
76
+ missing_group_cols = [col for col in group_by if col not in ds.column_names]
77
+ if missing_group_cols:
78
+ raise ValueError(f"Missing grouping columns: {missing_group_cols}")
79
+
80
+ if markdown_column not in ds.column_names:
81
+ raise ValueError(f"Missing markdown column: {markdown_column}")
82
+
83
+ if source_path_column not in ds.column_names:
84
+ raise ValueError(f"Missing source path column: {source_path_column}")
85
+
86
+ # Crucial: remove image/reference image columns before row iteration.
87
+ # This avoids decoding or carrying image payloads into the reduced dataset.
88
+ early_drop_columns = [col for col in ["image"] if col in ds.column_names]
89
+ if early_drop_columns:
90
+ ds = ds.remove_columns(early_drop_columns)
91
+
92
+ keep_columns = [col for col in keep_columns if col in ds.column_names]
93
+
94
+ documents: OrderedDict[tuple[Any, ...], dict[str, Any]] = OrderedDict()
95
+
96
+ for row_index, row in enumerate(ds):
97
+ key = tuple(normalize_value(row.get(col)) for col in group_by)
98
+
99
+ if key not in documents:
100
+ doc = {
101
+ col: normalize_value(row.get(col))
102
+ for col in keep_columns
103
+ }
104
+
105
+ doc["document_id"] = make_document_id(row, group_by)
106
+ doc["_pages"] = []
107
+ documents[key] = doc
108
+
109
+ source_path = row.get(source_path_column)
110
+ page_number = parse_page_number(source_path)
111
+
112
+ documents[key]["_pages"].append(
113
+ {
114
+ "row_index": row_index,
115
+ "page_number": page_number,
116
+ "source_path": normalize_value(source_path),
117
+ "markdown": row.get(markdown_column) or "",
118
+ "inference_info": normalize_value(row.get(inference_info_column))
119
+ if inference_info_column in ds.column_names
120
+ else None,
121
+ }
122
+ )
123
+
124
+ output_rows: list[dict[str, Any]] = []
125
+
126
+ for doc in documents.values():
127
+ pages = sorted(
128
+ doc["_pages"],
129
+ key=lambda p: (
130
+ p["page_number"] is None,
131
+ p["page_number"] if p["page_number"] is not None else 10**12,
132
+ p["row_index"],
133
+ ),
134
+ )
135
+
136
+ markdown_parts = []
137
+ for idx, page in enumerate(pages, start=1):
138
+ text = page["markdown"].strip()
139
+
140
+ if add_page_markers:
141
+ marker = f"<!-- page {idx}; source_path: {page['source_path']} -->"
142
+ markdown_parts.append(f"{marker}\n\n{text}".strip())
143
+ else:
144
+ markdown_parts.append(text)
145
+
146
+ source_paths = [p["source_path"] for p in pages]
147
+ page_numbers = [p["page_number"] for p in pages]
148
+
149
+ inference_infos = [
150
+ p["inference_info"]
151
+ for p in pages
152
+ if p.get("inference_info") not in (None, "")
153
+ ]
154
+
155
+ doc.pop("_pages", None)
156
+
157
+ doc[markdown_column] = "\n\n".join(part for part in markdown_parts if part)
158
+ doc["page_count"] = len(pages)
159
+ doc["source_paths"] = source_paths
160
+ doc["page_numbers"] = page_numbers
161
+
162
+ # Usually identical across pages; keep first value as document-level metadata.
163
+ doc[inference_info_column] = inference_infos[0] if inference_infos else None
164
+
165
+ output_rows.append(doc)
166
+
167
+ return Dataset.from_list(output_rows)
168
+
169
+
170
+ def parse_csv_arg(value: str) -> list[str]:
171
+ return [part.strip() for part in value.split(",") if part.strip()]
172
+
173
+
174
+ def main() -> None:
175
+ parser = argparse.ArgumentParser(
176
+ description="Consolidate page-level OCR rows into document-level OCR rows."
177
+ )
178
+
179
+ parser.add_argument(
180
+ "--input-dataset",
181
+ required=True,
182
+ help="Input Hugging Face dataset repo ID, e.g. username/page-level-ocr",
183
+ )
184
+
185
+ parser.add_argument(
186
+ "--output-dataset",
187
+ required=True,
188
+ help="Output Hugging Face dataset repo ID, e.g. username/document-level-ocr",
189
+ )
190
+
191
+ parser.add_argument(
192
+ "--config",
193
+ default=None,
194
+ help="Optional dataset config/subset name.",
195
+ )
196
+
197
+ parser.add_argument(
198
+ "--split",
199
+ default=None,
200
+ help="Optional split to process. If omitted, all splits are processed.",
201
+ )
202
+
203
+ parser.add_argument(
204
+ "--group-by",
205
+ default="barcode",
206
+ help="Comma-separated grouping columns. Default: barcode",
207
+ )
208
+
209
+ parser.add_argument(
210
+ "--keep-columns",
211
+ default=",".join(DEFAULT_KEEP_COLUMNS),
212
+ help="Comma-separated metadata columns to preserve.",
213
+ )
214
+
215
+ parser.add_argument(
216
+ "--markdown-column",
217
+ default="markdown",
218
+ help="OCR text column to concatenate. Default: markdown",
219
+ )
220
+
221
+ parser.add_argument(
222
+ "--source-path-column",
223
+ default="source_path",
224
+ help="Column used to infer page order. Default: source_path",
225
+ )
226
+
227
+ parser.add_argument(
228
+ "--inference-info-column",
229
+ default="inference_info",
230
+ help="Column containing OCR inference metadata. Default: inference_info",
231
+ )
232
+
233
+ parser.add_argument(
234
+ "--no-page-markers",
235
+ action="store_true",
236
+ help="Do not insert HTML page markers into the consolidated markdown.",
237
+ )
238
+
239
+ parser.add_argument(
240
+ "--private",
241
+ action="store_true",
242
+ help="Create the output dataset as private if it does not already exist.",
243
+ )
244
+
245
+ parser.add_argument(
246
+ "--token",
247
+ default=os.environ.get("HF_TOKEN"),
248
+ help="Hugging Face token. Defaults to HF_TOKEN environment variable.",
249
+ )
250
+
251
+ parser.add_argument(
252
+ "--dry-run",
253
+ action="store_true",
254
+ help="Print a summary instead of pushing to the Hub.",
255
+ )
256
+
257
+ args = parser.parse_args()
258
+
259
+ group_by = parse_csv_arg(args.group_by)
260
+ keep_columns = parse_csv_arg(args.keep_columns)
261
+
262
+ load_kwargs: dict[str, Any] = {
263
+ "path": args.input_dataset,
264
+ }
265
+
266
+ if args.config:
267
+ load_kwargs["name"] = args.config
268
+
269
+ if args.split:
270
+ load_kwargs["split"] = args.split
271
+
272
+ if args.token:
273
+ load_kwargs["token"] = args.token
274
+
275
+ loaded = load_dataset(**load_kwargs)
276
+
277
+ reduce_kwargs = {
278
+ "group_by": group_by,
279
+ "keep_columns": keep_columns,
280
+ "markdown_column": args.markdown_column,
281
+ "source_path_column": args.source_path_column,
282
+ "inference_info_column": args.inference_info_column,
283
+ "add_page_markers": not args.no_page_markers,
284
+ }
285
+
286
+ if isinstance(loaded, DatasetDict):
287
+ reduced = DatasetDict(
288
+ {
289
+ split_name: reduce_split(split_ds, **reduce_kwargs)
290
+ for split_name, split_ds in loaded.items()
291
+ }
292
+ )
293
+ else:
294
+ reduced = reduce_split(loaded, **reduce_kwargs)
295
+
296
+ if args.dry_run:
297
+ if isinstance(reduced, DatasetDict):
298
+ for split_name, split_ds in reduced.items():
299
+ print(f"{split_name}: {split_ds.num_rows} consolidated documents")
300
+ print(split_ds[0] if split_ds.num_rows else "No rows")
301
+ else:
302
+ print(f"{reduced.num_rows} consolidated documents")
303
+ print(reduced[0] if reduced.num_rows else "No rows")
304
+ return
305
+
306
+ push_kwargs: dict[str, Any] = {
307
+ "repo_id": args.output_dataset,
308
+ "private": args.private,
309
+ }
310
+
311
+ if args.token:
312
+ push_kwargs["token"] = args.token
313
+
314
+ reduced.push_to_hub(**push_kwargs)
315
+
316
+ print(f"Pushed consolidated dataset to: {args.output_dataset}")
317
+
318
+
319
+ if __name__ == "__main__":
320
+ main()