Can someone help me? Every time I run it, I get this error:
Error analyzing image: 400 Request contains an invalid argument.
The code worked before, but now it doesn’t.
async def handle_image_attachment(attachments, channel, prompt=None, message=None):
"""Handles the image attachment processing and deletion for multiple images."""
add_to_history("System", "Processing image attachment(s)...")
image_files = [] # List to hold processed image paths
for i, attachment in enumerate(attachments):
file_extension = attachment.filename.split('.')[-1].lower()
if file_extension == 'jpg':
file_extension = 'jpeg' # Rename 'jpg' to 'jpeg'
# Generate a unique file name using a counter or timestamp
unique_filename = f'image_{i}_{int(time.time())}.{file_extension}'
file_path = os.path.join('system/RAM/read-img', unique_filename)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
try:
img_data = await attachment.read()
with open(file_path, 'wb') as file:
file.write(img_data)
if file_extension == 'jpeg':
img = Image.open(file_path).convert('RGB')
else:
img = Image.open(file_path)
# Add image to the list of processed images
image_files.append(img)
except Exception as e:
await channel.send(f"Error reading attachment {attachment.filename}: {str(e)}")
print(f"Error reading attachment: {e}")
return
if image_files:
# Prepare the images for the model and generate content
while True:
try:
async with message.channel.typing():
print("DEBUG: Starting image processing for model input.")
# Convert images to byte format for the model
image_file_objects = []
for img in image_files:
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_bytes = buffered.getvalue()
print(f"DEBUG: Processed image size in bytes: {len(img_bytes)}")
image_file_objects.append({
'mime_type': 'image/png', # or 'image/jpeg'
'data': img_bytes
})
print(f"DEBUG: Total number of images processed: {len(image_file_objects)}")
print("1")
# Retrieve the display name
display_name = member_custom_name.get(message.author.id, message.author.display_name)
member_name = display_name
print("2")
# Fetch conversation history
model_conversation_history = get_conversation_history(message)
# Prepare the prompt with conversation history
mprompt = f"Conversation History Memory: |{model_conversation_history}|\n{member_name}: {prompt}"
response_text = "" # Initialization
if not gemini_api_key_verified:
await message.channel.send("Please set up the API key at [Google AI Studio](https://aistudio.google.com/apikey)")
await message.add_reaction('🔑')
return
print("3")
try:
print(mprompt)
response = chat_session.send_message(image_file_objects + [mprompt])
user = message.author.name
user_settings = get_user_settings(user)
view_thoughts = user_settings.get('view_thoughts', False)
selected_model = user_settings['model']
if len(response.parts) >= 2 and selected_model in ["gemini-2.0-flash-thinking-exp", "gemini-2.0-flash-thinking-exp-1219"]:
if view_thoughts:
response_text = f"> ### Model's Thoughts:\n> {response.parts[0].text.replace('\n\n', '\n ** **\n').replace('\n', '\n> ')}\n\n{response.parts[1].text}"
else:
response_text = response.parts[1].text
add_to_history_bot("", f"{response.parts[1].text}")
else:
response_text = response.text.strip()
add_to_history_bot("", f"{response_text}")
if not any(keyword in response_text for keyword in ["/img", "/object", "`/object`"]):
pass
except Exception as e:
print(f"Error analyzing image: {e}")
await message.channel.send(f"Error analyzing image: {e}")
if response_text.startswith("/img"):
#~ ~ ~ Tell me if you want the rest of the code
i extremely simplified it and still no success:
if message.attachments:
for attachment in message.attachments:
valid_attachments = [
attachment for attachment in message.attachments
if attachment.filename.lower().endswith((‘png’, ‘jpg’, ‘jpeg’, ‘gif’))
]
if valid_attachments:
print(f"Image attachment found: {attachment.filename} | {attachment.filename.lower()} | From: {message.author.display_name} | ID: {message.author.id}“)
print(f"Processing image attachment: {attachment}”)
print(f"Processing image attachment2: {message.attachments}“)
try:
img_data = await attachment.read()
img = Image.open(io.BytesIO(img_data))
response = model.generate_content([img, “Analyze this”])
print(response)
except Exception as e:
print(f"Error occurred while processing image attachment: {e}”)
return
Image attachment found: 1105660156722819165.png | 1105660156722819165.png | From: Youssef | ID: 1096964888972230767
Processing image attachment: https://cdn.discordapp.com/attachments/1276768937287356500/1324384406193836033/1105660156722819165.png?ex=6777f498&is=6776a318&hm=5bfeee0c9e4abd567d76d733b3b28d93c2e650d83097c309867e0fe6f3e33a54&
Processing image attachment2: []
Error occurred while processing image attachment: 400 Request contains an invalid argument.