ElijahSturges commited on
Commit
f434b4c
·
verified ·
1 Parent(s): f076fda

Upload 3 files

Browse files
Files changed (3) hide show
  1. batch_ocr.py +68 -0
  2. convert_pdfs.py +59 -0
  3. mergetxts.py +79 -0
batch_ocr.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import subprocess
3
+
4
+ # Paths
5
+ input_dir = Path(
6
+ "/Users/productivity/Downloads/Approaching_Religion/PNGs"
7
+ )
8
+ output_dir = Path(
9
+ "/Users/productivity/Downloads/Approaching_Religion/OCR"
10
+ )
11
+
12
+ # OCR language
13
+ LANG = "eng"
14
+
15
+ output_dir.mkdir(parents=True, exist_ok=True)
16
+
17
+ # Find all PNG files in all subfolders
18
+ png_files = sorted(input_dir.rglob("*.png"))
19
+
20
+ total = len(png_files)
21
+ successful = 0
22
+ failed = []
23
+
24
+ print(f"Found {total} PNG files to OCR.\n")
25
+
26
+ for index, png_path in enumerate(png_files, start=1):
27
+
28
+ # Preserve the original subfolder structure
29
+ relative_path = png_path.relative_to(input_dir)
30
+ txt_path = (output_dir / relative_path).with_suffix(".txt")
31
+
32
+ # Create the corresponding output subfolder
33
+ txt_path.parent.mkdir(parents=True, exist_ok=True)
34
+
35
+ # Skip files already OCRed
36
+ if txt_path.exists():
37
+ print(f"[{index}/{total}] Skipping existing: {txt_path.name}")
38
+ continue
39
+
40
+ print(f"[{index}/{total}] OCR: {relative_path}")
41
+
42
+ try:
43
+ subprocess.run(
44
+ [
45
+ "tesseract",
46
+ str(png_path),
47
+ str(txt_path.with_suffix("")),
48
+ "-l", LANG
49
+ ],
50
+ check=True,
51
+ capture_output=True,
52
+ text=True
53
+ )
54
+ successful += 1
55
+
56
+ except subprocess.CalledProcessError as exc:
57
+ print(f"ERROR: {relative_path}")
58
+ print(exc.stderr)
59
+ failed.append(str(relative_path))
60
+
61
+ print("\nOCR complete.")
62
+ print(f"Successfully OCRed: {successful}")
63
+ print(f"Failed: {len(failed)}")
64
+
65
+ if failed:
66
+ print("\nFiles that failed:")
67
+ for filename in failed:
68
+ print(f" - {filename}")
convert_pdfs.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import fitz
3
+
4
+ input_dir = Path("/Users/productivity/Downloads/Approaching_Religion/AllPDFS")
5
+ output_dir = Path("/Users/productivity/Downloads/Approaching_Religion/PNGs")
6
+
7
+ DPI = 300
8
+
9
+ output_dir.mkdir(parents=True, exist_ok=True)
10
+
11
+ pdf_files = sorted(
12
+ p for p in input_dir.glob("*.pdf")
13
+ if p.is_file()
14
+ )
15
+
16
+ total_pages = 0
17
+ failed_files = []
18
+
19
+ print(f"Found {len(pdf_files)} PDF files.")
20
+
21
+ for file_number, pdf_path in enumerate(pdf_files, start=1):
22
+ try:
23
+ with fitz.open(pdf_path) as pdf:
24
+ pdf_output = output_dir / pdf_path.stem
25
+ pdf_output.mkdir(parents=True, exist_ok=True)
26
+
27
+ page_count = len(pdf)
28
+ print(
29
+ f"[{file_number}/{len(pdf_files)}] "
30
+ f"{pdf_path.name}: {page_count} pages"
31
+ )
32
+
33
+ for page_number, page in enumerate(pdf, start=1):
34
+ pix = page.get_pixmap(
35
+ dpi=DPI,
36
+ colorspace=fitz.csRGB,
37
+ alpha=False
38
+ )
39
+
40
+ output_file = (
41
+ pdf_output /
42
+ f"{pdf_path.stem}_page_{page_number:04d}.png"
43
+ )
44
+ pix.save(output_file)
45
+
46
+ total_pages += page_count
47
+
48
+ except Exception as exc:
49
+ failed_files.append((pdf_path.name, str(exc)))
50
+ print(f"ERROR: {pdf_path.name}: {exc}")
51
+
52
+ print("\nConversion complete.")
53
+ print(f"Successfully converted pages: {total_pages}")
54
+ print(f"Failed PDFs: {len(failed_files)}")
55
+
56
+ if failed_files:
57
+ print("\nFiles requiring attention:")
58
+ for filename, error in failed_files:
59
+ print(f"- {filename}: {error}")
mergetxts.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import re
3
+
4
+ # Folder containing the OCR subfolders
5
+ input_dir = Path(
6
+ "/Users/productivity/Downloads/Approaching_Religion/OCR"
7
+ )
8
+
9
+ # Folder where the master documents will be saved
10
+ output_dir = Path(
11
+ "/Users/productivity/Downloads/Approaching_Religion/MasterDocuments"
12
+ )
13
+
14
+ output_dir.mkdir(parents=True, exist_ok=True)
15
+
16
+ # Find each subfolder corresponding to an original PDF
17
+ subfolders = sorted(
18
+ folder for folder in input_dir.iterdir()
19
+ if folder.is_dir()
20
+ )
21
+
22
+ successful = 0
23
+ failed = []
24
+
25
+ print(f"Found {len(subfolders)} OCR subfolders.\n")
26
+
27
+ for index, folder in enumerate(subfolders, start=1):
28
+ # Find all page-level text files
29
+ txt_files = list(folder.glob("*.txt"))
30
+
31
+ # Sort by page number, rather than ordinary alphabetical order
32
+ def page_number(path):
33
+ match = re.search(r"_page_(\d+)$", path.stem)
34
+ return int(match.group(1)) if match else float("inf")
35
+
36
+ txt_files.sort(key=page_number)
37
+
38
+ if not txt_files:
39
+ print(f"WARNING: No TXT files found in {folder.name}")
40
+ failed.append(folder.name)
41
+ continue
42
+
43
+ master_path = output_dir / f"{folder.name}.txt"
44
+
45
+ try:
46
+ with master_path.open("w", encoding="utf-8") as master:
47
+ for txt_file in txt_files:
48
+ master.write(
49
+ f"\n\n{'=' * 30}\n"
50
+ f"PAGE: {txt_file.stem}\n"
51
+ f"{'=' * 30}\n\n"
52
+ )
53
+
54
+ master.write(
55
+ txt_file.read_text(
56
+ encoding="utf-8",
57
+ errors="replace"
58
+ )
59
+ )
60
+
61
+ successful += 1
62
+ print(
63
+ f"[{index}/{len(subfolders)}] "
64
+ f"Created {master_path.name} "
65
+ f"from {len(txt_files)} pages"
66
+ )
67
+
68
+ except OSError as exc:
69
+ print(f"ERROR: {folder.name}: {exc}")
70
+ failed.append(folder.name)
71
+
72
+ print("\nMaster document creation complete.")
73
+ print(f"Created: {successful}")
74
+ print(f"Failed or empty: {len(failed)}")
75
+
76
+ if failed:
77
+ print("\nFolders requiring attention:")
78
+ for name in failed:
79
+ print(f" - {name}")