|
import fitz |
|
import os |
|
import pytesseract |
|
from PIL import Image |
|
from tqdm import tqdm |
|
|
|
|
|
input_dir = "pdfs" |
|
|
|
output_dir = "text3" |
|
|
|
|
|
os.makedirs(output_dir, exist_ok=True) |
|
|
|
def extract_text_from_image(page): |
|
|
|
pix = page.get_pixmap() |
|
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) |
|
|
|
text = pytesseract.image_to_string(img) |
|
return text |
|
|
|
|
|
for pdf_file in tqdm(os.listdir(input_dir)): |
|
if pdf_file.endswith(".pdf"): |
|
|
|
pdf_path = os.path.join(input_dir, pdf_file) |
|
doc = fitz.open(pdf_path) |
|
|
|
|
|
text = "" |
|
for page_num in range(len(doc)): |
|
page = doc.load_page(page_num) |
|
page_text = page.get_text() |
|
if not page_text.strip(): |
|
|
|
page_text = extract_text_from_image(page) |
|
text += page_text |
|
|
|
|
|
base_name = os.path.splitext(pdf_file)[0] |
|
txt_path = os.path.join(output_dir, f"{base_name}.txt") |
|
with open(txt_path, "w", encoding="utf-8") as txt_file: |
|
txt_file.write(text) |
|
|
|
print("Conversion complete!") |