Create a program, using the "moondream" model, that reads all the images in a pdf and exports the text to a json file. The json has a list, each containing the number of the page and the text content.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
ollama: For interacting with the "moondream" model.
pdf2image: To convert PDF pages to images.
pytesseract: For OCR (in case PDF has embedded text in images).
pillow: For image processing.
PyPDF2: For handling PDF metadata.
Ensure the moondream model is downloaded:
bash
ollama pull moondream
Verify that Ollama is running locally.
Code Implementation
Below is the Python program:
python
import json
import os
from pdf2image import convert_from_path
from pytesseract import image_to_string
from PyPDF2 import PdfReader
from ollama import chat
def process_pdf(pdf_path, output_json, model="moondream", dpi=300):
"""
Extracts text from all pages of a PDF that contain images and exports it to a JSON file.
Args:
pdf_path (str): Path to the input PDF file.
output_json (str): Path to the output JSON file.
model (str): Name of the Ollama model to use for processing.
dpi (int): DPI for converting PDF pages to images.
"""
# Ensure the PDF file exists
if not os.path.exists(pdf_path):
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
# Read the PDF to get the number of pages
pdf_reader = PdfReader(pdf_path)
num_pages = len(pdf_reader.pages)
# Prepare JSON output structure
output_data = {"pages": []}
# Convert PDF pages to images
print(f"Processing {num_pages} pages from {pdf_path}...")
images = convert_from_path(pdf_path, dpi=dpi)
# Process each page
for page_number, image in enumerate(images, start=1):
print(f"Processing page {page_number}...")
# Extract text from the image using OCR
ocr_text = image_to_string(image)
# Use the model to refine the text (if necessary)
response = chat(
model=model,
messages=[
{
"role": "user",
"content": f"Refine the following OCR text extracted from page {page_number}:\n\n{ocr_text}",
}
]
)
# Use the model's text or fallback to OCR text
refined_text = response.message.content if response.message.content else ocr_text
# Append to JSON output
output_data["pages"].append({
"page_number": page_number,
"text": refined_text.strip()
})
# Write output to JSON file
with open(output_json, "w", encoding="utf-8") as f:
json.dump(output_data, f, ensure_ascii=False, indent=4)
print(f"Text extracted and saved to {output_json}")
if __name__ == "__main__":
# Example usage
input_pdf = "input.pdf" # Path to your PDF
output_json = "output.json" # Path to save the extracted text
process_pdf(input_pdf, output_json)
How It Works:
PDF to Image Conversion:
The pdf2image.convert_from_path function converts each page of the PDF into an image.
OCR Text Extraction:
pytesseract.image_to_string is used to extract text from the images.
Text Refinement with "moondream":
The ollama.chat function sends the text extracted via OCR to the "moondream" model for refinement.
JSON Output:
The program organizes the text into a JSON structure with page_number and text fields for each page.
Example Input and Output
Input: input.pdf
A multi-page PDF with embedded images.
Output: output.json
json
{
"pages": [
{
"page_number": 1,
"text": "Extracted and refined text from page 1."
},
{
"page_number": 2,
"text": "Extracted and refined text from page 2."
}
]
}
Notes:
Tesseract Installation:
Ensure Tesseract OCR is installed on your system. For example: