Skip to content

Commit e0d78fa

Browse files
committed
Image shrink fix
1 parent f1eb5f2 commit e0d78fa

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

interpreter/core/llm/utils/convert_to_openai_messages.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import base64
22
import io
33
import json
4+
import sys
45

56
from PIL import Image
67

@@ -151,7 +152,7 @@ def convert_to_openai_messages(
151152
# Shrink to less than 5mb
152153

153154
# Calculate size
154-
content_size_bytes = len(content) * 3 / 4
155+
content_size_bytes = sys.getsizeof(str(content))
155156

156157
# Convert the size to MB
157158
content_size_mb = content_size_bytes / (1024 * 1024)
@@ -162,12 +163,6 @@ def convert_to_openai_messages(
162163
img_data = base64.b64decode(encoded_string)
163164
img = Image.open(io.BytesIO(img_data))
164165

165-
# Calculate the size of the original binary data in bytes
166-
content_size_bytes = len(img_data)
167-
168-
# Convert the size to MB
169-
content_size_mb = content_size_bytes / (1024 * 1024)
170-
171166
# Run in a loop to make SURE it's less than 5mb
172167
for _ in range(10):
173168
# Calculate the scale factor needed to reduce the image size to 4.9 MB
@@ -191,10 +186,13 @@ def convert_to_openai_messages(
191186
content = f"data:image/{extension};base64,{encoded_string}"
192187

193188
# Recalculate the size of the content in bytes
194-
content_size_bytes = len(content) * 3 / 4
189+
content_size_bytes = sys.getsizeof(str(content))
195190

196191
# Convert the size to MB
197192
content_size_mb = content_size_bytes / (1024 * 1024)
193+
194+
if content_size_mb < 5:
195+
break
198196
else:
199197
print(
200198
"Attempted to shrink the image but failed. Sending to the LLM anyway."

0 commit comments

Comments
 (0)