11import base64
22import io
33import json
4+ import sys
45
56from 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