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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import hashlib
4
+ import shutil
5
+ import tempfile
6
+ from pathlib import Path
7
+
8
+ import fitz
9
+ import pytesseract
10
+ from PIL import Image
11
+ from huggingface_hub import snapshot_download, HfApi
12
+
13
+
14
+ # ============================================================
15
+ # CONFIGURATION
16
+ # ============================================================
17
+
18
+ DPI = 300
19
+ OCR_LANGUAGE = "eng"
20
+
21
+
22
+ if os.environ.get("TESSERACT_CMD"):
23
+ pytesseract.pytesseract.tesseract_cmd = os.environ["TESSERACT_CMD"]
24
+
25
+
26
+ # ============================================================
27
+ # INGESTION
28
+ # ============================================================
29
+
30
+ def load_dataset():
31
+
32
+ print("\n" + "=" * 55)
33
+ print(" PDF OCR PROCESSING PIPELINE")
34
+ print("=" * 55)
35
+
36
+ source = input(
37
+ "\nEnter a Hugging Face dataset ID "
38
+ "or local directory path:\n> "
39
+ ).strip().strip('"').strip("'")
40
+
41
+ if not source:
42
+ raise ValueError("No dataset source was provided.")
43
+
44
+ source_path = Path(source).expanduser()
45
+
46
+ if source_path.is_dir():
47
+
48
+ print("\n[INGESTION] Using local dataset directory.")
49
+ dataset_path = source_path.resolve()
50
+
51
+ else:
52
+
53
+ print("\n[INGESTION] Downloading Hugging Face dataset...")
54
+
55
+ try:
56
+ dataset_path = Path(
57
+ snapshot_download(
58
+ repo_id=source,
59
+ repo_type="dataset",
60
+ allow_patterns=["*.pdf", "*.PDF"]
61
+ )
62
+ )
63
+
64
+ except Exception as error:
65
+ raise RuntimeError(
66
+ f"Could not retrieve dataset: {error}"
67
+ )
68
+
69
+ pdf_files = sorted(
70
+ [
71
+ file for file in dataset_path.rglob("*")
72
+ if file.is_file() and file.suffix.lower() == ".pdf"
73
+ ]
74
+ )
75
+
76
+ if not pdf_files:
77
+ raise FileNotFoundError(
78
+ "No PDF files were found in the supplied dataset."
79
+ )
80
+
81
+ print(f"\n[INGESTION] Found {len(pdf_files)} PDF files.")
82
+
83
+ return dataset_path, pdf_files
84
+
85
+
86
+ # ============================================================
87
+ # DOCUMENT DIRECTORY CREATION
88
+ # ============================================================
89
+
90
+ def create_document_folder(
91
+ pdf_path,
92
+ dataset_path,
93
+ output_path,
94
+ pdf_files
95
+ ):
96
+
97
+ relative_path = pdf_path.relative_to(dataset_path)
98
+
99
+ document_name = pdf_path.stem
100
+
101
+ safe_name = re.sub(
102
+ r'[<>:"/\\|?*]',
103
+ "_",
104
+ document_name
105
+ )
106
+
107
+ matching_files = [
108
+ p for p in pdf_files
109
+ if p.stem.casefold() == document_name.casefold()
110
+ ]
111
+
112
+ # Disambiguate PDFs with identical filenames.
113
+ if len(matching_files) > 1:
114
+
115
+ suffix = hashlib.sha1(
116
+ str(relative_path).encode("utf-8")
117
+ ).hexdigest()[:8]
118
+
119
+ safe_name = f"{safe_name}_{suffix}"
120
+
121
+ document_folder = output_path / safe_name
122
+
123
+ png_folder = document_folder / "png"
124
+ txt_folder = document_folder / "txt"
125
+
126
+ png_folder.mkdir(parents=True, exist_ok=True)
127
+ txt_folder.mkdir(parents=True, exist_ok=True)
128
+
129
+ return document_folder, png_folder, txt_folder, safe_name
130
+
131
+
132
+ # ============================================================
133
+ # PDF TO PNG CONVERSION
134
+ # ============================================================
135
+
136
+ def convert_pdf_to_png(
137
+ pdf_path,
138
+ png_folder,
139
+ document_name
140
+ ):
141
+
142
+ print(f"\n[CONVERSION] Processing: {pdf_path.name}")
143
+
144
+ pdf = fitz.open(pdf_path)
145
+
146
+ try:
147
+
148
+ page_count = len(pdf)
149
+
150
+ for page_number, page in enumerate(pdf, start=1):
151
+
152
+ filename = (
153
+ f"{document_name}_page_{page_number:04d}.png"
154
+ )
155
+
156
+ image_path = png_folder / filename
157
+
158
+ # Skip existing images.
159
+ if image_path.exists():
160
+ continue
161
+
162
+ matrix = fitz.Matrix(
163
+ DPI / 72,
164
+ DPI / 72
165
+ )
166
+
167
+ pixmap = page.get_pixmap(
168
+ matrix=matrix,
169
+ alpha=False
170
+ )
171
+
172
+ pixmap.save(str(image_path))
173
+
174
+ print(
175
+ f"[CONVERSION] Generated/verified "
176
+ f"{page_count} page images."
177
+ )
178
+
179
+ return page_count
180
+
181
+ finally:
182
+ pdf.close()
183
+
184
+
185
+ # ============================================================
186
+ # OCR PROCESSING
187
+ # ============================================================
188
+
189
+ def ocr_images(
190
+ png_folder,
191
+ txt_folder,
192
+ document_name
193
+ ):
194
+
195
+ print(f"\n[OCR] Processing: {document_name}")
196
+
197
+ image_files = sorted(
198
+ png_folder.glob(f"{document_name}_page_*.png")
199
+ )
200
+
201
+ for image_path in image_files:
202
+
203
+ text_filename = image_path.stem + ".txt"
204
+
205
+ text_path = txt_folder / text_filename
206
+
207
+ # Skip existing OCR outputs.
208
+ if text_path.exists():
209
+ continue
210
+
211
+ with Image.open(image_path) as image:
212
+
213
+ extracted_text = pytesseract.image_to_string(
214
+ image,
215
+ lang=OCR_LANGUAGE
216
+ )
217
+
218
+ with open(
219
+ text_path,
220
+ "w",
221
+ encoding="utf-8"
222
+ ) as text_file:
223
+
224
+ text_file.write(extracted_text)
225
+
226
+ print(
227
+ f"[OCR] Generated/verified "
228
+ f"{len(image_files)} page-level TXT files."
229
+ )
230
+
231
+
232
+ # ============================================================
233
+ # MASTER DOCUMENT CREATION
234
+ # ============================================================
235
+
236
+ def create_master_document(
237
+ txt_folder,
238
+ document_folder,
239
+ document_name,
240
+ page_count
241
+ ):
242
+
243
+ print(f"\n[STITCHING] Reconstructing: {document_name}")
244
+
245
+ master_path = document_folder / f"{document_name}.txt"
246
+
247
+ with open(
248
+ master_path,
249
+ "w",
250
+ encoding="utf-8"
251
+ ) as master_file:
252
+
253
+ for page_number in range(1, page_count + 1):
254
+
255
+ filename = (
256
+ f"{document_name}_page_{page_number:04d}.txt"
257
+ )
258
+
259
+ text_path = txt_folder / filename
260
+
261
+ if not text_path.exists():
262
+ raise FileNotFoundError(
263
+ f"Missing OCR output: {text_path}"
264
+ )
265
+
266
+ with open(
267
+ text_path,
268
+ "r",
269
+ encoding="utf-8"
270
+ ) as page_file:
271
+
272
+ page_text = page_file.read()
273
+
274
+ master_file.write(
275
+ f"\n\n========== PAGE {page_number} ==========\n\n"
276
+ )
277
+
278
+ master_file.write(page_text)
279
+
280
+ print("[STITCHING] Master document created.")
281
+
282
+ return master_path
283
+
284
+
285
+ # ============================================================
286
+ # DOCUMENT VALIDATION
287
+ # ============================================================
288
+
289
+ def validate_document(
290
+ png_folder,
291
+ txt_folder,
292
+ master_path,
293
+ page_count,
294
+ document_name
295
+ ):
296
+
297
+ png_count = len(
298
+ list(png_folder.glob(f"{document_name}_page_*.png"))
299
+ )
300
+
301
+ txt_count = len(
302
+ list(txt_folder.glob(f"{document_name}_page_*.txt"))
303
+ )
304
+
305
+ master_exists = master_path.exists()
306
+
307
+ valid = (
308
+ png_count == page_count
309
+ and txt_count == page_count
310
+ and master_exists
311
+ )
312
+
313
+ print("\n[VALIDATION]")
314
+
315
+ print(f"Expected pages: {page_count}")
316
+ print(f"PNG files: {png_count}")
317
+ print(f"TXT files: {txt_count}")
318
+ print(f"Master TXT: {master_exists}")
319
+
320
+ if valid:
321
+ print("[VALIDATION] SUCCESS")
322
+ else:
323
+ print("[VALIDATION] FAILED")
324
+
325
+ return valid
326
+
327
+
328
+ # ============================================================
329
+ # HUGGING FACE UPLOAD AND PULL REQUEST
330
+ # ============================================================
331
+
332
+ def upload_results(
333
+ successful_folders
334
+ ):
335
+
336
+ print("\n" + "=" * 55)
337
+ print(" HUGGING FACE UPLOAD")
338
+ print("=" * 55)
339
+
340
+ if not successful_folders:
341
+
342
+ print(
343
+ "\n[UPLOAD] No successfully validated documents. "
344
+ "Skipping upload."
345
+ )
346
+
347
+ return
348
+
349
+ repo_id = input(
350
+ "\nEnter destination Hugging Face dataset ID "
351
+ "(e.g. sample-organization/sample-dataset):\n> "
352
+ ).strip()
353
+
354
+ if not repo_id:
355
+
356
+ print("\n[UPLOAD] No repository specified. Skipping upload.")
357
+
358
+ return
359
+
360
+ try:
361
+
362
+ api = HfApi()
363
+
364
+ print(f"\n[UPLOAD] Destination: {repo_id}")
365
+ print(
366
+ f"[UPLOAD] Documents to upload: "
367
+ f"{len(successful_folders)}"
368
+ )
369
+
370
+ # Create a temporary staging directory containing
371
+ # only successfully validated documents.
372
+ with tempfile.TemporaryDirectory(
373
+ prefix="pdf_ocr_upload_"
374
+ ) as temporary_directory:
375
+
376
+ staging_path = Path(temporary_directory)
377
+
378
+ for document_folder in successful_folders:
379
+
380
+ destination = staging_path / document_folder.name
381
+
382
+ shutil.copytree(
383
+ document_folder,
384
+ destination
385
+ )
386
+
387
+ print("\n[UPLOAD] Uploading OCR corpus...")
388
+
389
+ result = api.upload_folder(
390
+
391
+ folder_path=str(staging_path),
392
+
393
+ repo_id=repo_id,
394
+
395
+ repo_type="dataset",
396
+
397
+ path_in_repo="ocr-output",
398
+
399
+ commit_message="Add OCR processing results",
400
+
401
+ commit_description=(
402
+ "Automatically generated OCR corpus "
403
+ "containing page images, page-level text "
404
+ "files, and consolidated master documents."
405
+ ),
406
+
407
+ create_pr=True
408
+ )
409
+
410
+ print("\n[SUCCESS] Upload completed!")
411
+
412
+ print(f"Pull Request URL: {result}")
413
+
414
+ except Exception as error:
415
+
416
+ print(f"\n[UPLOAD ERROR] {error}")
417
+
418
+ print(
419
+ "[UPLOAD] Local OCR results have been preserved."
420
+ )
421
+
422
+ print(
423
+ "[UPLOAD] Check your Hugging Face authentication "
424
+ "and repository write permissions."
425
+ )
426
+
427
+
428
+ # ============================================================
429
+ # MAIN PIPELINE
430
+ # ============================================================
431
+
432
+ def run_pipeline():
433
+
434
+ try:
435
+
436
+ pytesseract.get_tesseract_version()
437
+
438
+ except Exception as error:
439
+
440
+ raise RuntimeError(
441
+ "Tesseract OCR is not installed or is not accessible. "
442
+ "Check your installation and PATH."
443
+ ) from error
444
+
445
+ dataset_path, pdf_files = load_dataset()
446
+
447
+ output_input = input(
448
+ "\nEnter output directory "
449
+ "(press Enter for ./PDF_OCR_CORPUS):\n> "
450
+ ).strip().strip('"').strip("'")
451
+
452
+ if output_input:
453
+
454
+ output_path = Path(
455
+ output_input
456
+ ).expanduser().resolve()
457
+
458
+ else:
459
+
460
+ output_path = Path.cwd() / "PDF_OCR_CORPUS"
461
+
462
+ output_path.mkdir(
463
+ parents=True,
464
+ exist_ok=True
465
+ )
466
+
467
+ print("\n" + "=" * 55)
468
+
469
+ print(f"PDF FILES: {len(pdf_files)}")
470
+ print(f"OUTPUT: {output_path}")
471
+
472
+ print("=" * 55)
473
+
474
+ successful = 0
475
+ failed = 0
476
+
477
+ successful_folders = []
478
+
479
+ for index, pdf_path in enumerate(pdf_files, start=1):
480
+
481
+ print("\n" + "-" * 55)
482
+
483
+ print(
484
+ f"DOCUMENT {index}/{len(pdf_files)}: "
485
+ f"{pdf_path.name}"
486
+ )
487
+
488
+ print("-" * 55)
489
+
490
+ try:
491
+
492
+ (
493
+ document_folder,
494
+ png_folder,
495
+ txt_folder,
496
+ document_name
497
+ ) = create_document_folder(
498
+ pdf_path,
499
+ dataset_path,
500
+ output_path,
501
+ pdf_files
502
+ )
503
+
504
+ page_count = convert_pdf_to_png(
505
+ pdf_path,
506
+ png_folder,
507
+ document_name
508
+ )
509
+
510
+ ocr_images(
511
+ png_folder,
512
+ txt_folder,
513
+ document_name
514
+ )
515
+
516
+ master_path = create_master_document(
517
+ txt_folder,
518
+ document_folder,
519
+ document_name,
520
+ page_count
521
+ )
522
+
523
+ valid = validate_document(
524
+ png_folder,
525
+ txt_folder,
526
+ master_path,
527
+ page_count,
528
+ document_name
529
+ )
530
+
531
+ if valid:
532
+
533
+ successful += 1
534
+
535
+ successful_folders.append(
536
+ document_folder
537
+ )
538
+
539
+ else:
540
+
541
+ failed += 1
542
+
543
+ except Exception as error:
544
+
545
+ failed += 1
546
+
547
+ print(
548
+ f"\n[ERROR] Could not process "
549
+ f"{pdf_path.name}: {error}"
550
+ )
551
+
552
+ continue
553
+
554
+ # ========================================================
555
+ # PROCESSING SUMMARY
556
+ # ========================================================
557
+
558
+ print("\n" + "=" * 55)
559
+ print(" PIPELINE COMPLETE")
560
+ print("=" * 55)
561
+
562
+ print(f"Total PDFs: {len(pdf_files)}")
563
+ print(f"Successful: {successful}")
564
+ print(f"Failed: {failed}")
565
+ print(f"Output directory: {output_path}")
566
+
567
+ print("=" * 55)
568
+
569
+ # ========================================================
570
+ # OPTIONAL HUGGING FACE UPLOAD
571
+ # ========================================================
572
+
573
+ if successful > 0:
574
+
575
+ upload_choice = input(
576
+ "\nWould you like to upload the results "
577
+ "to Hugging Face and create a Pull Request? "
578
+ "(y/n):\n> "
579
+ ).strip().lower()
580
+
581
+ if upload_choice in ("y", "yes"):
582
+
583
+ upload_results(successful_folders)
584
+
585
+ else:
586
+
587
+ print("\n[UPLOAD] Skipped by user.")
588
+
589
+ else:
590
+
591
+ print(
592
+ "\n[UPLOAD] No successful documents to upload."
593
+ )
594
+
595
+
596
+ # ============================================================
597
+ # EXECUTION
598
+ # ============================================================
599
+
600
+ if __name__ == "__main__":
601
+
602
+ try:
603
+
604
+ run_pipeline()
605
+
606
+ except KeyboardInterrupt:
607
+
608
+ print("\n[INTERRUPTED] Pipeline stopped by user.")
609
+
610
+ except Exception as error:
611
+
612
+ print(f"\n[FATAL ERROR] {error}")