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.
I'll help you create a program that uses the Ollama Python library with the moondream model to analyze PDF images and export the text to JSON. We'll need to use additional libraries to handle PDFs and convert them to images.
Here's the program:
python
import json
from pathlib import Path
from pdf2image import convert_from_path
import tempfile
from ollama import Client
import base64
from io import BytesIO
from PIL import Image
def pdf_to_json(pdf_path: str, output_path: str):
# Initialize Ollama client
client = Client()
# Convert PDF pages to images
pages = convert_from_path(pdf_path)
results = []
# Process each page
for i, page in enumerate(pages, start=1):
# Convert PIL Image to bytes
img_byte_arr = BytesIO()
page.save(img_byte_arr, format='PNG')
img_bytes = img_byte_arr.getvalue()
# Create message with the image
messages = [{
'role': 'user',
'content': 'What text do you see in this image?',
'images': [img_bytes]
}]
# Get response from moondream model
try:
response = client.chat('moondream', messages=messages)
# Add result to our list
results.append({
'page': i,
'text': response.message.content
})
print(f"Processed page {i}")
except Exception as e:
print(f"Error processing page {i}: {str(e)}")
results.append({
'page': i,
'text': f"Error: {str(e)}"
})
# Save results to JSON file
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"\nProcessing complete. Results saved to {output_path}")
if __name__ == "__main__":
# Example usage
pdf_path = "input.pdf" # Replace with your PDF path
output_path = "output.json" # Replace with desired output path
pdf_to_json(pdf_path, output_path)
To use this program, you'll need to install the required dependencies:
bash
pip install ollama pdf2image Pillow
You'll also need to have Ollama installed and running on your system, and the moondream model pulled:
bash
ollama pull moondream
Note that you'll also need to install poppler on your system for pdf2image to work:
On Ubuntu/Debian: sudo apt-get install poppler-utils
On macOS: brew install poppler
On Windows: Download and install poppler binaries
The program does the following:
Takes a PDF file path as input
Converts each page of the PDF to an image using pdf2image
For each page image:
Converts it to bytes
Sends it to the moondream model with a prompt asking for the text content
Stores the page number and extracted text
Saves all results to a JSON file
The output JSON will look something like this:
json
[
{
"page": 1,
"text": "Text content from page 1..."
},
{
"page": 2,
"text": "Text content from page 2..."
}
// ... more pages
]
To use the program, simply replace the pdf_path and output_path variables with your desired file paths and run the script.
The program includes error handling for individual pages, so if one page fails, it will continue processing the others. It also provides progress feedback by printing which page is being processed.
Remember that the quality of text extraction will depend on:
The quality of the PDF
How the text is represented in the PDF (actual text vs. images of text)
The capabilities of the moondream model
Also note that processing might take some time depending on the size of the PDF and the number of pages, as each page needs to be processed individually by the model.