Spaces:
Sleeping
Sleeping
import os | |
import uuid | |
import requests | |
import oss2 | |
from requests.cookies import RequestsCookieJar | |
def upload_image_to_cdn(base_url, auth_token, image_path): | |
""" | |
Uploads an image to the CDN using STS credentials. | |
Args: | |
base_url (str): The base URL of the API endpoint (e.g., "https://chat.qwen.ai"). | |
auth_token (str): The Bearer token for authentication. | |
image_path (str): The local path to the image file to upload. | |
Returns: | |
str: The CDN URL where the image is accessible. | |
Raises: | |
Exception: If the upload fails at any step. | |
""" | |
class ImageUploader: | |
def __init__(self, base_url, auth_token): | |
self.session = requests.Session() | |
self.base_url = base_url | |
self.auth_token = auth_token | |
self.headers = self._create_headers() | |
self.cookies = RequestsCookieJar() | |
def _create_headers(self): | |
return { | |
'x-request-id': str(uuid.uuid4()), | |
'Authorization': f'Bearer {self.auth_token}', | |
'Content-Type': 'application/json', | |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36' | |
} | |
def get_sts_token(self, filename, filesize, filetype): | |
endpoint = '/api/v1/files/getstsToken' | |
payload = { | |
'filename': filename, | |
'filesize': filesize, | |
'filetype': filetype | |
} | |
response = self.session.post( | |
f'{self.base_url}{endpoint}', | |
json=payload, | |
headers=self.headers, | |
cookies=self.cookies | |
) | |
response.raise_for_status() | |
return response.json() | |
def upload_to_oss(self, sts_data, image_path): | |
auth = oss2.StsAuth( | |
sts_data['access_key_id'], | |
sts_data['access_key_secret'], | |
sts_data['security_token'] | |
) | |
endpoint = f"https://{sts_data['region']}.aliyuncs.com" | |
bucket = oss2.Bucket(auth, endpoint, sts_data['bucketname']) | |
with open(image_path, 'rb') as file: | |
result = bucket.put_object(sts_data['file_path'], file) | |
return result.status == 200 | |
def upload_image(self, image_path): | |
filename = os.path.basename(image_path) | |
filesize = os.path.getsize(image_path) | |
filetype = 'image' # Modify if you need specific MIME type detection | |
# Step 1: Get STS token | |
sts_data = self.get_sts_token(filename, filesize, filetype) | |
# Step 2: Upload to OSS | |
upload_success = self.upload_to_oss(sts_data, image_path) | |
if upload_success: | |
return sts_data['file_url'] | |
else: | |
raise Exception("Upload failed") | |
# Initialize the uploader and perform the upload | |
uploader = ImageUploader(base_url, auth_token) | |
try: | |
file_url = uploader.upload_image(image_path) | |
return file_url | |
except Exception as e: | |
raise Exception(f"Image upload failed: {str(e)}") |