screenplays-3k / convert_pdfs.py
aaronday3's picture
Upload 5 files
a04461a verified
raw
history blame
1.46 kB
import fitz # PyMuPDF
import os
import pytesseract
from PIL import Image
from tqdm import tqdm
# Directory containing PDFs
input_dir = "pdfs"
# Directory to save text files
output_dir = "text3"
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
def extract_text_from_image(page):
# Convert PDF page to an image
pix = page.get_pixmap()
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
# Use OCR to extract text from the image
text = pytesseract.image_to_string(img)
return text
# Loop through all PDF files in the input directory
for pdf_file in tqdm(os.listdir(input_dir)):
if pdf_file.endswith(".pdf"):
# Open the PDF file
pdf_path = os.path.join(input_dir, pdf_file)
doc = fitz.open(pdf_path)
# Extract text from each page
text = ""
for page_num in range(len(doc)):
page = doc.load_page(page_num)
page_text = page.get_text()
if not page_text.strip():
# If no text is found, try OCR
page_text = extract_text_from_image(page)
text += page_text
# Save the extracted text to a .txt file
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!")