import os
import sys
from pdf2image import convert_from_path
import pytesseract
from langdetect import detect_langs
from collections import defaultdict
def ocr_pdf_filter_pages(pdf_path, poppler_path=None, tesseract_cmd=None, output_langs=['eng', 'guj'], debug=False):
"""
OCRs the PDF and returns a list of page numbers where the predominant language is English.
:param pdf_path: Path to the PDF file.
:param poppler_path: Path to the poppler bin directory (if needed).
:param tesseract_cmd: Path to the tesseract executable (if needed).
:param output_langs: List of language codes to use for OCR.
:param debug: If True, prints debug information.
:return: List of page numbers with predominantly English text.
"""
if not os.path.isfile(pdf_path):
print(f"Error: File '{pdf_path}' does not exist.")
sys.exit(1)
if tesseract_cmd:
pytesseract.pytesseract.tesseract_cmd = tesseract_cmd
# Convert PDF to images
try:
images = convert_from_path(pdf_path, poppler_path=poppler_path)
except Exception as e:
print(f"Error converting PDF to images: {e}")
sys.exit(1)
english_pages = []
for idx, image in enumerate(images):
page_number = idx + 1
if debug:
print(f"Processing page {page_number}...")
try:
# Perform OCR with specified languages
text = pytesseract.image_to_string(image, lang='+'.join(output_langs))
except Exception as e:
print(f"Error performing OCR on page {page_number}: {e}")
continue
if not text.strip():
if debug:
print(f"No text detected on page {page_number}. Skipping...")
continue
try:
# Detect languages with probabilities
lang_probs = detect_langs(text)
if debug:
print(f"Detected languages on page {page_number}: {lang_probs}")
# Compute a weighted score for English and Gujarati
scores = defaultdict(float)
for lang in lang_probs:
lang_code = lang.lang
prob = lang.prob
if lang_code in output_langs:
scores[lang_code] += prob
# Determine predominant language
if not scores:
if debug:
print(f"No relevant languages detected on page {page_number}. Skipping...")
continue
predominant_lang = max(scores, key=scores.get)
if debug:
print(f"Predominant language on page {page_number}: {predominant_lang} (score: {scores[predominant_lang]:.2f})")
if predominant_lang == 'en':
english_pages.append(page_number)
except Exception as e:
print(f"Error detecting language on page {page_number}: {e}")
continue
return english_pages
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="OCR a PDF and list pages predominantly in English.")
parser.add_argument("pdf_path", help="Path to the PDF file.")
parser.add_argument("--poppler_path", help="Path to the poppler bin directory.", default=None)
parser.add_argument("--tesseract_cmd", help="Path to the tesseract executable.", default=None)
parser.add_argument("--debug", action="store_true", help="Enable debug output.")
args = parser.parse_args()
english_pages = ocr_pdf_filter_pages(
pdf_path=args.pdf_path,
poppler_path=args.poppler_path,
tesseract_cmd=args.tesseract_cmd,
debug=args.debug
)
if english_pages:
print("Pages with predominantly English text:")
print(english_pages)
else:
print("No pages with predominantly English text were found.")