Spaces:
Sleeping
Sleeping
Upload reach_upload.py
Browse files- utils/reach_upload.py +110 -0
utils/reach_upload.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
logger.setLevel(logging.DEBUG)
|
| 10 |
+
|
| 11 |
+
# Add a stream handler if not already added
|
| 12 |
+
if not logger.handlers:
|
| 13 |
+
handler = logging.StreamHandler()
|
| 14 |
+
handler.setLevel(logging.DEBUG)
|
| 15 |
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 16 |
+
handler.setFormatter(formatter)
|
| 17 |
+
logger.addHandler(handler)
|
| 18 |
+
|
| 19 |
+
def upload_to_reach(
|
| 20 |
+
image_data: bytes,
|
| 21 |
+
brand_name: str,
|
| 22 |
+
image_format: str,
|
| 23 |
+
index: int,
|
| 24 |
+
file_type: str, # Required parameter
|
| 25 |
+
max_retries: int = 3,
|
| 26 |
+
retry_delay: float = 2.0
|
| 27 |
+
) -> Dict[str, str]:
|
| 28 |
+
"""
|
| 29 |
+
Upload image to Reach Mobile Platform storage with retry logic.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
image_data (bytes): Raw image bytes
|
| 33 |
+
brand_name (str): Brand name for reference
|
| 34 |
+
image_format (str): Image format/extension
|
| 35 |
+
index (int): Index to differentiate multiple uploads
|
| 36 |
+
file_type (str): Type of file to upload (e.g., LOGO, FAV_ICON, etc.)
|
| 37 |
+
max_retries (int): Maximum number of retry attempts
|
| 38 |
+
retry_delay (float): Delay between retries in seconds
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
Dict[str, str]: Metadata dictionary containing URL from Reach API
|
| 42 |
+
|
| 43 |
+
Raises:
|
| 44 |
+
requests.RequestException: If upload fails after all retries
|
| 45 |
+
EnvironmentError: If required environment variables are missing
|
| 46 |
+
"""
|
| 47 |
+
url = os.getenv('REACH_UPLOAD_ENDPOINT')
|
| 48 |
+
auth_key = os.getenv('REACH_AUTH_KEY')
|
| 49 |
+
|
| 50 |
+
if not url:
|
| 51 |
+
raise EnvironmentError("REACH_UPLOAD_ENDPOINT is not defined in environment variables.")
|
| 52 |
+
if not auth_key:
|
| 53 |
+
raise EnvironmentError("REACH_AUTH_KEY is not defined in environment variables.")
|
| 54 |
+
|
| 55 |
+
last_exception = None
|
| 56 |
+
|
| 57 |
+
for attempt in range(max_retries):
|
| 58 |
+
try:
|
| 59 |
+
file_obj = BytesIO(image_data)
|
| 60 |
+
filename = f"{brand_name.replace(' ', '')}_{index}.{image_format.lower()}"
|
| 61 |
+
|
| 62 |
+
files = {
|
| 63 |
+
'file': (filename, file_obj, f'image/{image_format.lower()}')
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
headers = {
|
| 67 |
+
'accept': 'application/json',
|
| 68 |
+
'accept-language': 'en-US,en;q=0.9',
|
| 69 |
+
'authorization': auth_key,
|
| 70 |
+
'sec-ch-ua-platform': 'Windows',
|
| 71 |
+
'x-partner-tenant-id': 'REACH@skyhawk'
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
logger.info(f"Attempting upload of {filename} as {file_type} (attempt {attempt + 1}/{max_retries})")
|
| 75 |
+
|
| 76 |
+
# Ensure file_type is present in the URL
|
| 77 |
+
upload_url = f"{url}?fileType={file_type}"
|
| 78 |
+
|
| 79 |
+
logger.debug(f"Uploading to endpoint: {upload_url}")
|
| 80 |
+
|
| 81 |
+
response = requests.post(
|
| 82 |
+
upload_url,
|
| 83 |
+
files=files,
|
| 84 |
+
headers=headers,
|
| 85 |
+
timeout=30
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
if response.status_code != 200:
|
| 89 |
+
raise requests.HTTPError(f"Upload failed: {response.status_code} {response.text}")
|
| 90 |
+
|
| 91 |
+
response_data = response.json()
|
| 92 |
+
if response_data.get('status') != 'SUCCESS':
|
| 93 |
+
raise requests.HTTPError(f"Upload failed: {response_data}")
|
| 94 |
+
|
| 95 |
+
logger.info(f"Successfully uploaded {filename}")
|
| 96 |
+
return {
|
| 97 |
+
"url": response_data.get('data')
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
except (requests.RequestException, requests.Timeout) as e:
|
| 101 |
+
last_exception = e
|
| 102 |
+
logger.warning(f"Upload attempt {attempt + 1} failed: {str(e)}")
|
| 103 |
+
if attempt < max_retries - 1:
|
| 104 |
+
time.sleep(retry_delay * (attempt + 1)) # Exponential backoff
|
| 105 |
+
continue
|
| 106 |
+
break
|
| 107 |
+
|
| 108 |
+
error_msg = f"❌ Error uploading to Reach platform after {max_retries} attempts: {str(last_exception)}"
|
| 109 |
+
logger.error(error_msg)
|
| 110 |
+
raise requests.RequestException(error_msg)
|