File size: 1,672 Bytes
f434b4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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}")