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