selenium/thesis-file
0
1import pytesseract2from PIL import Image3from pdf2image import convert_from_path4 5MAX_WIDTH = 1200 # reduce image width to save memory6 7 8def preprocess_image(img: Image.Image) -> Image.Image:9 """Resize image while maintaining aspect ratio to reduce memory usage."""10 if img.width > MAX_WIDTH:11 ratio = MAX_WIDTH / img.width12 new_height = int(img.height * ratio)13 img = img.resize((MAX_WIDTH, new_height))14 return img15 16 17def extract_text_from_image(path: str) -> str:18 """Extract text from a single image safely with timeout."""19 try:20 img = Image.open(path)21 img = preprocess_image(img)22 text = pytesseract.image_to_string(23 img, timeout=60) # 60s max per image24 return text25 except pytesseract.TesseractError as e:26 return f'OCR error: {str(e)}'27 except Exception as e:28 return f'OCR error: {str(e)}'29 30 31def extract_text_from_pdf(path: str) -> str:32 """Extract text from a PDF safely, processing pages one by one."""33 try:34 pages = convert_from_path(path)35 text = ''36 for page in pages:37 page = preprocess_image(page)38 text += pytesseract.image_to_string(page, timeout=60)39 return text40 except pytesseract.TesseractError as e:41 return f'OCR error: {str(e)}'42 except Exception as e:43 return f'OCR error: {str(e)}'44 