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.
To create a program that uses the "moondream" model to read all JPEG images from a specified folder (./images) and exports the extracted text to a JSON file, we can utilize the ollama library. This program will involve loading the images, sending them to the model for processing, and saving the results in a structured JSON format.
Here’s a step-by-step guide along with the complete code:
Step-by-Step Guide:
Import Required Libraries: We'll need os for file operations, json for exporting data, and ollama for interacting with the model.
List All JPEG Images: Read all files in the specified folder and filter out the JPEG images.
Extract Text from Images: For each image, use the ollama.embed method to extract text. (Assuming that the model can extract text from images).
Structure the Data: Organize the results into a list of dictionaries, each containing the file name, extracted content, and any additional parameters like language.
Save to JSON: Write the structured data to a JSON file.
Complete Code:
python
import os
import json
from ollama import AsyncClient # Use AsyncClient for asynchronous operation
async def extract_text_from_images(image_folder: str, model: str, output_file: str):
# Initialize the Ollama asynchronous client
client = AsyncClient()
results = []
# List all JPEG files in the specified folder
for filename in os.listdir(image_folder):
if filename.lower().endswith('.jpeg') or filename.lower().endswith('.jpg'):
file_path = os.path.join(image_folder, filename)
print(f"Processing image: {file_path}")
try:
# Read the image content
with open(file_path, 'rb') as img_file:
image_data = img_file.read()
# Send the image to the model for text extraction
response = await client.embed(model=model, input=image_data)
# Assuming the model returns a text response, extract the text
extracted_text = response.embeddings # Adapt this based on the actual response structure
# Create a result dictionary
result = {
'file_name': filename,
'text_content': extracted_text,
'language': 'unknown' # Placeholder for language; adjust as needed
}
results.append(result)
except Exception as e:
print(f"Failed to process {filename}: {e}")
# Export the results to a JSON file
with open(output_file, 'w') as json_file:
json.dump(results, json_file, indent=4)
print(f"Exported data to {output_file}")
# Main function to run the script
if __name__ == '__main__':
import asyncio
image_folder = './images' # Directory containing JPEG images
model = 'moondream' # The model to be used
output_file = 'extracted_text.json' # Output JSON file
# Run the async extraction function
asyncio.run(extract_text_from_images(image_folder, model, output_file))
Explanation of the Code:
Imports: We import the necessary libraries to handle file operations and asynchronous requests.
Async Function: The extract_text_from_images function is defined to handle the image processing asynchronously.
Image Processing: The function lists all JPEG files in the specified directory, reads each file, and sends it to the moondream model for processing.
Error Handling: Basic error handling is included to print messages if an image fails to process.
JSON Export: Finally, it saves the results in a JSON file with an appropriate structure.
Notes:
Model Limitations: Ensure that the "moondream" model is capable of processing images and extracting text.
Language Detection: The language detection feature is currently a placeholder. You might want to integrate a language detection library (like langdetect) if necessary.
Asynchronous Operations: This code uses AsyncClient to handle requests asynchronously, which is beneficial for performance when dealing with multiple images.
Make sure to run the program in an environment where the ollama library is installed and the necessary model is available. Adjust the model name and parameters as needed based on your specific requirements.