Download PDF2TXT_Take2.py from divinity-library/AR-test-01: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/datasets/divinity-library/AR-test-01/resolve/main/PDF2TXT_Take2.py
- Command line
-
hf download hf://datasets/divinity-library/AR-test-01/PDF2TXT_Take2.py
-
curl -L -o PDF2TXT_Take2.py https://huggingface.co/datasets/divinity-library/AR-test-01/resolve/main/PDF2TXT_Take2.py
13.9 kB
| 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}") | |