1
1
import base64
2
2
import io
3
3
import json
4
+ import sys
4
5
5
6
from PIL import Image
6
7
@@ -151,7 +152,7 @@ def convert_to_openai_messages(
151
152
# Shrink to less than 5mb
152
153
153
154
# Calculate size
154
- content_size_bytes = len ( content ) * 3 / 4
155
+ content_size_bytes = sys . getsizeof ( str ( content ))
155
156
156
157
# Convert the size to MB
157
158
content_size_mb = content_size_bytes / (1024 * 1024 )
@@ -162,12 +163,6 @@ def convert_to_openai_messages(
162
163
img_data = base64 .b64decode (encoded_string )
163
164
img = Image .open (io .BytesIO (img_data ))
164
165
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
-
171
166
# Run in a loop to make SURE it's less than 5mb
172
167
for _ in range (10 ):
173
168
# Calculate the scale factor needed to reduce the image size to 4.9 MB
@@ -191,10 +186,13 @@ def convert_to_openai_messages(
191
186
content = f"data:image/{ extension } ;base64,{ encoded_string } "
192
187
193
188
# Recalculate the size of the content in bytes
194
- content_size_bytes = len ( content ) * 3 / 4
189
+ content_size_bytes = sys . getsizeof ( str ( content ))
195
190
196
191
# Convert the size to MB
197
192
content_size_mb = content_size_bytes / (1024 * 1024 )
193
+
194
+ if content_size_mb < 5 :
195
+ break
198
196
else :
199
197
print (
200
198
"Attempted to shrink the image but failed. Sending to the LLM anyway."
0 commit comments