| 1 | import logging |
| 2 | import requests |
| 3 | import base64 |
| 4 | import mimetypes |
| 5 | from io import BytesIO |
| 6 | import cv2 |
| 7 | |
| 8 | from utils.retry import download_retry |
| 9 | |
| 10 | |
| 11 | @download_retry |
| 12 | def download_image(url, save_path): |
| 13 | try: |
| 14 | logging.info(f"Downloading image from {url} to {save_path}") |
| 15 | |
| 16 | response = requests.get(url, stream=True, timeout=(10, 300)) |
| 17 | response.raise_for_status() # Check for HTTP errors |
| 18 | |
| 19 | with open(save_path, 'wb') as file: |
| 20 | for chunk in response.iter_content(chunk_size=1024): |
| 21 | file.write(chunk) |
| 22 | logging.info(f"Image downloaded successfully to {save_path}") |
| 23 | |
| 24 | except Exception as e: |
| 25 | logging.error(f"Error downloading image: {e}") |
| 26 | raise e |
| 27 | |
| 28 | |
| 29 | def image_path_to_b64(image_path, mime: bool = True) -> str: |
| 30 | with open(image_path, 'rb') as image_file: |
| 31 | b64 = base64.b64encode(image_file.read()).decode('utf-8') |
| 32 | |
| 33 | if mime: |
| 34 | mime_type, _ = mimetypes.guess_type(image_path) |
| 35 | if mime_type is None: |
| 36 | mime_type = 'application/octet-stream' |
| 37 | return f"data:{mime_type};base64,{b64}" |
| 38 | |
| 39 | return b64 |
| 40 | |
| 41 | |
| 42 | def pil_to_b64(image, mime: bool = True) -> str: |
| 43 | buffered = BytesIO() |
| 44 | image.save(buffered, format="PNG") |
| 45 | b64 = base64.b64encode(buffered.getvalue()).decode('utf-8') |
| 46 | |
| 47 | if mime: |
| 48 | return f"data:image/png;base64,{b64}" |
| 49 | |
| 50 | return b64 |
| 51 | |
| 52 | |
| 53 | def save_base64_image(b64_string, save_path): |
| 54 | # If the base64 string has a data URL prefix, remove it |
| 55 | if ',' in b64_string: |
| 56 | b64_string = b64_string.split(',')[1] |
| 57 | |
| 58 | with open(save_path, 'wb') as image_file: |
| 59 | image_file.write(base64.b64decode(b64_string)) |
| 60 | |
| 61 |