I’ve made a simple script for reading images.
You can check it here :
import base64
import requests
import os
import json
import time
# Colores ANSI
COLOR_RED = "\033[91m"
COLOR_YELLOW = "\033[93m"
COLOR_WHITE = "\033[97m"
COLOR_RESET = "\033[0m"
COLOR_BLUE = "\033[94m"
COLOR_GREEN = "\033[92m"
# OpenAI API Key
#api_key = (apikeytext)
api_key = (OTHERAPIKEY)
# Folder path
FOLDERPATH = "imgs"
SEARCHPROMPT = "Describe the scene in detail without using phrases like 'the image shows' or 'the image depicts'.It should be consise and focus on the visual elements. Format: Description: (detailed description). Tags: tag1, tag2, tag3."
MAXTOKENS = 300
GENERATEJSONPERFILE = True
GENERATEALLJSON = True
# Function to encode the image
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
# Print global variables
print(f"{COLOR_BLUE}Made by JPupper Aka Julian Puppo from Jeyder Multimedia, a GIFT for David Sheldrick{COLOR_RESET}")
print(f"{COLOR_RED}---------------------------------------------------")
print("Global variables:")
print(f"{COLOR_GREEN}FOLDERPATH{COLOR_WHITE}: {FOLDERPATH}")
print(f"{COLOR_GREEN}SEARCHPROMPT{COLOR_WHITE}: {SEARCHPROMPT}")
print(f"{COLOR_GREEN}MAXTOKENS{COLOR_WHITE}: {MAXTOKENS}")
print(f"{COLOR_GREEN}GENERATEJSONPERFILE{COLOR_WHITE}: {GENERATEJSONPERFILE}")
print(f"{COLOR_GREEN}GENERATEALLJSON{COLOR_WHITE}: {GENERATEALLJSON}")
print(f"{COLOR_RED}---------------------------------------------------{COLOR_RESET}")
# List all images in the folder
images = [f for f in os.listdir(FOLDERPATH) if os.path.isfile(os.path.join(FOLDERPATH, f))]
print(f"{COLOR_YELLOW}Imgs in the folder:{COLOR_RESET}")
print(images)
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
# Start timing
start_time = time.time()
# Informing the start of the process
print(f"{COLOR_RED}Connecting to ChatGPT API for generating images...{COLOR_RESET}")
# List to store all response data
all_responses = []
# Process each image in the folder
for idx, image_file_name in enumerate(images, start=1):
image_path = os.path.join(FOLDERPATH, image_file_name)
image_size = os.path.getsize(image_path)
# Getting the base64 string
base64_image = encode_image(image_path)
payload = {
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": SEARCHPROMPT
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
],
"max_tokens": MAXTOKENS
}
try:
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
response.raise_for_status()
response_data = response.json()
# Extract description and tags from content
content = response_data['choices'][0]['message']['content']
description = content.split("Description: ")[1].split("Tags:")[0].strip()
tags = content.split("Tags:")[1].strip().split(", ")
# Add description and tags to the response data
response_data['description'] = description
response_data['tags'] = tags
# Add image name and size to the response data
response_data['image_name'] = image_file_name
response_data['image_size'] = image_size
# Append response data to the list of all responses
all_responses.append(response_data)
if GENERATEJSONPERFILE:
# Save response data to a JSON file in the same folder as the images
json_filename = os.path.join(FOLDERPATH, f"response_{image_file_name}.json")
with open(json_filename, "w") as json_file:
json.dump(response_data, json_file, indent=4)
print(f"{COLOR_GREEN}JSON generated for {image_file_name}{COLOR_RESET}")
# Print the data in the desired format
print(f"{COLOR_RED}---------------------------------------------------------------")
print(f"{COLOR_GREEN}Image number{COLOR_WHITE}: {idx}")
print(f"{COLOR_GREEN}Image size{COLOR_WHITE}: {image_size} bytes")
print(f"{COLOR_GREEN}Image name{COLOR_WHITE}: {image_file_name}")
print(f"{COLOR_GREEN}id{COLOR_WHITE}: {response_data['id']}")
print(f"{COLOR_GREEN}Description{COLOR_WHITE}: {response_data['description']}")
print(f"{COLOR_GREEN}Tags{COLOR_WHITE}: {response_data['tags']}")
print(f"{COLOR_GREEN}Usage{COLOR_WHITE}: {response_data['usage']}")
print(f"{COLOR_GREEN}Completion tokens{COLOR_WHITE}: {response_data['usage']['completion_tokens']}")
print(f"{COLOR_GREEN}Total tokens{COLOR_WHITE}: {response_data['usage']['total_tokens']}")
print(f"{COLOR_RED}---------------------------------------------------------------{COLOR_RESET}")
except requests.exceptions.RequestException as e:
print(f"{COLOR_RED}Error processing image {image_file_name}:{COLOR_WHITE} {e}{COLOR_RESET}")
except KeyError as e:
print(f"{COLOR_RED}Error extracting data from response for image {image_file_name}:{COLOR_WHITE} {e}{COLOR_RESET}")
# Save all responses to a single JSON file if GENERATEALLJSON is True
if GENERATEALLJSON:
global_json_filename = os.path.join(FOLDERPATH, "all_responses.json")
with open(global_json_filename, "w") as global_json_file:
json.dump(all_responses, global_json_file, indent=4)
print(f"{COLOR_YELLOW}Global JSON generated.{COLOR_RESET}")
# End timing
end_time = time.time()
total_time = end_time - start_time
print(f"{COLOR_YELLOW}All images finished processing.{COLOR_RESET}")
print(f"{COLOR_YELLOW}Amount of images{COLOR_WHITE}: {len(images)}")
print(f"{COLOR_YELLOW}Amount of time taken{COLOR_WHITE}: {total_time} seconds{COLOR_RESET}")
When i use my Apikey is not working , i get this error printed out :
401 Client Error: Unauthorized for url: h ttps:/ /api.openai. com/v1/chat/completi ons
But when i try the Apikey for my friend it works perfectly.
Everything in my account seems to be the same as my friends account configuration, the apikey has all permissions available. My friend has no made no special configuration yet it works for him but not for me , what can it be ?