File size: 2,749 Bytes
2c1318d | 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | """
PDF Text/Image Classifier
--------------------------
Separates PDFs into:
text_pdfs/
PDFs with extractable text
image_pdfs/
Scanned/image-only PDFs requiring OCR
Usage:
python split_pdf_types.py
"""
from pathlib import Path
import shutil
import fitz
from tqdm import tqdm
# -----------------------------
# CONFIG
# -----------------------------
INPUT_FOLDER = Path("./pdfs")
OUTPUT_FOLDER = Path("./classified_pdfs")
TEXT_FOLDER = OUTPUT_FOLDER / "text_pdfs"
IMAGE_FOLDER = OUTPUT_FOLDER / "image_pdfs"
# Minimum characters per page
# below this -> considered scanned
MIN_CHARS_PER_PAGE = 30
# -----------------------------
# CLASSIFICATION
# -----------------------------
def classify_pdf(pdf_path):
"""
Returns:
TEXT
IMAGE
"""
try:
doc = fitz.open(pdf_path)
total_chars = 0
total_pages = len(doc)
image_pages = 0
for page in doc:
text = page.get_text().strip()
total_chars += len(text)
# Count pages containing images
if len(page.get_images(full=True)) > 0:
image_pages += 1
avg_chars = total_chars / max(total_pages,1)
#
# Rules
#
# No text layer
if avg_chars < MIN_CHARS_PER_PAGE:
return "IMAGE"
# Mostly image pages + little text
if image_pages / total_pages > 0.7 and avg_chars < 100:
return "IMAGE"
return "TEXT"
except Exception as e:
print(
f"Error reading {pdf_path.name}: {e}"
)
return "IMAGE"
# -----------------------------
# MAIN
# -----------------------------
def main():
TEXT_FOLDER.mkdir(
parents=True,
exist_ok=True
)
IMAGE_FOLDER.mkdir(
parents=True,
exist_ok=True
)
pdfs=list(
INPUT_FOLDER.glob("*.pdf")
)
print(
f"Found {len(pdfs)} PDFs"
)
stats={
"TEXT":0,
"IMAGE":0
}
for pdf in tqdm(pdfs):
category = classify_pdf(pdf)
if category=="TEXT":
destination = (
TEXT_FOLDER /
pdf.name
)
else:
destination = (
IMAGE_FOLDER /
pdf.name
)
shutil.copy2(
pdf,
destination
)
stats[category]+=1
print("\nCompleted")
print(
f"Text PDFs : {stats['TEXT']}"
)
print(
f"Image PDFs : {stats['IMAGE']}"
)
print("\nOutput:")
print(
TEXT_FOLDER
)
print(
IMAGE_FOLDER
)
if __name__=="__main__":
main() |