File size: 2,146 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
69
70
71
72
73
74
75
76
77
78
79
80
from pathlib import Path
import re

# Folder containing the OCR subfolders
input_dir = Path(
    "/Users/productivity/Downloads/Approaching_Religion/OCR"
)

# Folder where the master documents will be saved
output_dir = Path(
    "/Users/productivity/Downloads/Approaching_Religion/MasterDocuments"
)

output_dir.mkdir(parents=True, exist_ok=True)

# Find each subfolder corresponding to an original PDF
subfolders = sorted(
    folder for folder in input_dir.iterdir()
    if folder.is_dir()
)

successful = 0
failed = []

print(f"Found {len(subfolders)} OCR subfolders.\n")

for index, folder in enumerate(subfolders, start=1):
    # Find all page-level text files
    txt_files = list(folder.glob("*.txt"))

    # Sort by page number, rather than ordinary alphabetical order
    def page_number(path):
        match = re.search(r"_page_(\d+)$", path.stem)
        return int(match.group(1)) if match else float("inf")

    txt_files.sort(key=page_number)

    if not txt_files:
        print(f"WARNING: No TXT files found in {folder.name}")
        failed.append(folder.name)
        continue

    master_path = output_dir / f"{folder.name}.txt"

    try:
        with master_path.open("w", encoding="utf-8") as master:
            for txt_file in txt_files:
                master.write(
                    f"\n\n{'=' * 30}\n"
                    f"PAGE: {txt_file.stem}\n"
                    f"{'=' * 30}\n\n"
                )

                master.write(
                    txt_file.read_text(
                        encoding="utf-8",
                        errors="replace"
                    )
                )

        successful += 1
        print(
            f"[{index}/{len(subfolders)}] "
            f"Created {master_path.name} "
            f"from {len(txt_files)} pages"
        )

    except OSError as exc:
        print(f"ERROR: {folder.name}: {exc}")
        failed.append(folder.name)

print("\nMaster document creation complete.")
print(f"Created: {successful}")
print(f"Failed or empty: {len(failed)}")

if failed:
    print("\nFolders requiring attention:")
    for name in failed:
        print(f" - {name}")