scripts / batch_ocr.py
ElijahSturges's picture
Upload 3 files
f434b4c verified
Raw History Blame Contribute Delete
1.67 kB
from pathlib import Path
import subprocess
# Paths
input_dir = Path(
"/Users/productivity/Downloads/Approaching_Religion/PNGs"
)
output_dir = Path(
"/Users/productivity/Downloads/Approaching_Religion/OCR"
)
# OCR language
LANG = "eng"
output_dir.mkdir(parents=True, exist_ok=True)
# Find all PNG files in all subfolders
png_files = sorted(input_dir.rglob("*.png"))
total = len(png_files)
successful = 0
failed = []
print(f"Found {total} PNG files to OCR.\n")
for index, png_path in enumerate(png_files, start=1):
# Preserve the original subfolder structure
relative_path = png_path.relative_to(input_dir)
txt_path = (output_dir / relative_path).with_suffix(".txt")
# Create the corresponding output subfolder
txt_path.parent.mkdir(parents=True, exist_ok=True)
# Skip files already OCRed
if txt_path.exists():
print(f"[{index}/{total}] Skipping existing: {txt_path.name}")
continue
print(f"[{index}/{total}] OCR: {relative_path}")
try:
subprocess.run(
[
"tesseract",
str(png_path),
str(txt_path.with_suffix("")),
"-l", LANG
],
check=True,
capture_output=True,
text=True
)
successful += 1
except subprocess.CalledProcessError as exc:
print(f"ERROR: {relative_path}")
print(exc.stderr)
failed.append(str(relative_path))
print("\nOCR complete.")
print(f"Successfully OCRed: {successful}")
print(f"Failed: {len(failed)}")
if failed:
print("\nFiles that failed:")
for filename in failed:
print(f" - {filename}")