Spaces:
Sleeping
Sleeping
Download app/utils/reach_upload.py from utkarsh134/LogoGeneration: direct link, hf CLI and curl.
- Browser
- Download file 4.27 kB
-
https://huggingface.co/spaces/utkarsh134/LogoGeneration/resolve/main/app/utils/reach_upload.py
- Command line
-
hf download hf://spaces/utkarsh134/LogoGeneration/app/utils/reach_upload.py
-
curl -L -o reach_upload.py https://huggingface.co/spaces/utkarsh134/LogoGeneration/resolve/main/app/utils/reach_upload.py
4.27 kB
| import os | |
| import time | |
| from typing import Dict | |
| import requests | |
| from io import BytesIO | |
| import logging | |
| from urllib.parse import urlparse, parse_qs, urlencode, urlunparse | |
| logger = logging.getLogger(__name__) | |
| logger.setLevel(logging.DEBUG) | |
| # Add a stream handler if not already added | |
| if not logger.handlers: | |
| handler = logging.StreamHandler() | |
| handler.setLevel(logging.DEBUG) | |
| formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
| handler.setFormatter(formatter) | |
| logger.addHandler(handler) | |
| def upload_to_reach( | |
| image_data: bytes, | |
| brand_name: str, | |
| image_format: str, | |
| index: int, | |
| file_type: str, # Required parameter | |
| max_retries: int = 3, | |
| retry_delay: float = 2.0 | |
| ) -> Dict[str, str]: | |
| """ | |
| Upload image to Reach Mobile Platform storage with retry logic. | |
| Args: | |
| image_data (bytes): Raw image bytes | |
| brand_name (str): Brand name for reference | |
| image_format (str): Image format/extension | |
| index (int): Index to differentiate multiple uploads | |
| file_type (str): Type of file to upload (e.g., LOGO, FAV_ICON, etc.) | |
| max_retries (int): Maximum number of retry attempts | |
| retry_delay (float): Delay between retries in seconds | |
| Returns: | |
| Dict[str, str]: Metadata dictionary containing URL from Reach API | |
| Raises: | |
| requests.RequestException: If upload fails after all retries | |
| EnvironmentError: If required environment variables are missing | |
| """ | |
| url = os.getenv('REACH_UPLOAD_ENDPOINT') | |
| auth_key = os.getenv('REACH_AUTH_KEY') | |
| if not url: | |
| raise EnvironmentError("REACH_UPLOAD_ENDPOINT is not defined in environment variables.") | |
| if not auth_key: | |
| raise EnvironmentError("REACH_AUTH_KEY is not defined in environment variables.") | |
| last_exception = None | |
| for attempt in range(max_retries): | |
| try: | |
| file_obj = BytesIO(image_data) | |
| filename = f"{brand_name.replace(' ', '')}_{index}.{image_format.lower()}" | |
| files = { | |
| 'file': (filename, file_obj, f'image/{image_format.lower()}') | |
| } | |
| headers = { | |
| 'accept': 'application/json', | |
| 'accept-language': 'en-US,en;q=0.9', | |
| 'authorization': auth_key | |
| } | |
| logger.info(f"Attempting upload of {filename} as {file_type} (attempt {attempt + 1}/{max_retries})") | |
| # Ensure fileType is only added once and URL is valid | |
| parsed_url = urlparse(url) | |
| query = parse_qs(parsed_url.query) | |
| if 'fileType' not in query: | |
| query['fileType'] = [file_type] | |
| else: | |
| query['fileType'] = [file_type] # Overwrite if present | |
| new_query = urlencode(query, doseq=True) | |
| upload_url = urlunparse(parsed_url._replace(query=new_query)) | |
| logger.debug(f"Uploading to endpoint: {upload_url}") | |
| response = requests.post( | |
| upload_url, | |
| files=files, | |
| headers=headers, | |
| timeout=30 | |
| ) | |
| if response.status_code != 200: | |
| raise requests.HTTPError(f"Upload failed: {response.status_code} {response.text}") | |
| response_data = response.json() | |
| if response_data.get('status') != 'SUCCESS': | |
| raise requests.HTTPError(f"Upload failed: {response_data}") | |
| logger.info(f"Successfully uploaded {filename}") | |
| return { | |
| "url": response_data.get('data') | |
| } | |
| except (requests.RequestException, requests.Timeout) as e: | |
| last_exception = e | |
| logger.warning(f"Upload attempt {attempt + 1} failed: {str(e)}") | |
| if attempt < max_retries - 1: | |
| time.sleep(retry_delay * (attempt + 1)) # Exponential backoff | |
| continue | |
| break | |
| error_msg = f"❌ Error uploading to Reach platform after {max_retries} attempts: {str(last_exception)}" | |
| logger.error(error_msg) | |
| raise requests.RequestException(error_msg) | |