Create a program, using the "moondream" model, that reads all the images (assume jpeg) from the folder "./images" and exports the text to a json file with a list of dictionaries, each containing the name of the file, the text content, and any other parameters that may be interesting (for example, language of the text?)
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 images and export the results to JSON. Here's a complete solution:
python
import os
import json
from pathlib import Path
from typing import List, Dict
import ollama
from ollama import Message
def process_images_folder(folder_path: str = "./images") -> List[Dict]:
"""
Process all JPEG images in the specified folder using moondream model.
Args:
folder_path: Path to the folder containing images
Returns:
List of dictionaries containing analysis results
"""
# Initialize Ollama client
client = ollama.Client()
results = []
# Get all jpeg/jpg files from the folder
image_files = [
f for f in os.listdir(folder_path)
if [Redacted Person]().endswith(('.jpg', '.jpeg'))
]
# Process each image
for image_file in image_files:
image_path = Path(folder_path) / image_file
try:
# Create message with the image
message = Message(
role="user",
content="What do you see in this image? Please be detailed.",
images=[str(image_path)]
)
# Get response from [Redacted Person]
response = client.chat(
model='moondream',
messages=[message]
)
# Create result dictionary
result = {
"filename": image_file,
"description": response.message.content,
"path": str(image_path),
"size_bytes": image_path.stat().st_size,
"timestamp": image_path.stat().st_mtime
}
results.append(result)
print(f"Processed: {image_file}")
except Exception as e:
print(f"Error processing {image_file}: {str(e)}")
continue
return results
def save_to_json(results: List[Dict], output_file: str = "image_analysis.json"):
"""
Save results to a JSON file.
Args:
results: List of analysis results
output_file: Output JSON filename
"""
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(results, indent=2, ensure_ascii=False, default=str)
def main():
print("Starting image analysis...")
# Make sure the images folder exists
if not os.path.exists("./images"):
print("Error: './images' folder not found!")
return
# Process images
results = process_images_folder()
# Save results
if results:
save_to_json(results)
print(f"\nAnalysis complete! Results saved to 'image_analysis.json'")
print(f"Processed {len(results)} images")
else:
print("\nNo images were processed!")
if __name__ == "__main__":
main()
This program:
Scans the "./images" folder for JPEG files
Uses the moondream model through Ollama to analyze each image
Creates a dictionary for each image containing:
filename
description (from moondream)
full path
file size
timestamp
Saves all results to a JSON file named 'image_analysis.json'
To use this program:
Make sure you have Ollama installed and running
Pull the moondream model:
bash
ollama pull moondream
Create a folder named "images" in the same directory as the script
The program includes error handling and progress feedback. If any image fails to process, the program will continue with the remaining images and report the error.
Note that the actual response content from the moondream model will depend on its capabilities and the specific version you're using. The model might provide different levels of detail or focus on different aspects of the images.