Spaces:
Sleeping
Sleeping
Download utils.py from Gangadhar123/pdf_ocr_extractor: direct link, hf CLI and curl.
- Browser
- Download file 833 Bytes
-
https://huggingface.co/spaces/Gangadhar123/pdf_ocr_extractor/resolve/main/utils.py
- Command line
-
hf download hf://spaces/Gangadhar123/pdf_ocr_extractor/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/Gangadhar123/pdf_ocr_extractor/resolve/main/utils.py
833 Bytes
| import pytesseract | |
| from pdf2image import convert_from_bytes | |
| from PIL import Image | |
| from typing import Union | |
| import io | |
| def extract_text_from_pdf(pdf_file: Union[io.BytesIO, any]) -> str: | |
| """ | |
| Converts PDF file to images and extracts text using OCR. | |
| Args: | |
| pdf_file: A file-like object of the uploaded PDF. | |
| Returns: | |
| Extracted text as a string. | |
| """ | |
| try: | |
| images = convert_from_bytes(pdf_file.read(), dpi=300) | |
| extracted_text = [] | |
| for index, image in enumerate(images): | |
| text = pytesseract.image_to_string(image) | |
| page_header = f"\n\n--- Page {index + 1} ---\n" | |
| extracted_text.append(page_header + text) | |
| return "".join(extracted_text) | |
| except Exception as e: | |
| return f"Error occurred while processing the PDF: {str(e)}" | |