Spaces:
Build error
Build error
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,41 +1,35 @@
|
|
| 1 |
-
import base64
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
raise FileNotFoundError(f"Image file not found at: {image_path}")
|
| 37 |
-
except Exception as e:
|
| 38 |
-
raise Exception(f"Error encoding image: {str(e)}")
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
# print(encode_image_to_base64("backiee-81547.jpg"))
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
|
| 3 |
+
def encode_image_to_base64(uploaded_file):
|
| 4 |
+
"""
|
| 5 |
+
Convert a Streamlit uploaded file to a base64 string.
|
| 6 |
+
|
| 7 |
+
Args:
|
| 8 |
+
uploaded_file (UploadedFile): File object from st.file_uploader()
|
| 9 |
+
|
| 10 |
+
Returns:
|
| 11 |
+
tuple: (base64_string, mime_type)
|
| 12 |
+
"""
|
| 13 |
+
try:
|
| 14 |
+
# Get the file extension
|
| 15 |
+
file_type = uploaded_file.type
|
| 16 |
+
|
| 17 |
+
# Determine MIME type
|
| 18 |
+
mime_types = {
|
| 19 |
+
'image/png': 'image/png',
|
| 20 |
+
'image/jpeg': 'image/jpeg'
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
mime_type = mime_types.get(file_type, 'image/png')
|
| 24 |
+
|
| 25 |
+
# Read the binary data directly from the uploaded file
|
| 26 |
+
binary_data = uploaded_file.getvalue()
|
| 27 |
+
|
| 28 |
+
# Encode to base64
|
| 29 |
+
base64_encoded = base64.b64encode(binary_data)
|
| 30 |
+
|
| 31 |
+
# Convert to string and remove b'' prefix
|
| 32 |
+
return base64_encoded.decode('utf-8'), mime_type
|
| 33 |
+
|
| 34 |
+
except Exception as e:
|
| 35 |
+
raise Exception(f"Error encoding image: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|