Spaces:
Sleeping
Sleeping
File size: 7,254 Bytes
e6de3db eaf8840 e6de3db eaf8840 e6de3db 1481fe5 e6de3db 1481fe5 548bf91 e6de3db 1481fe5 e6de3db 1481fe5 e6de3db 548bf91 e6de3db 1481fe5 eaf8840 1481fe5 eaf8840 1481fe5 eaf8840 1481fe5 548bf91 1481fe5 eaf8840 1481fe5 548bf91 1481fe5 |
1 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
import os
import uuid
import requests
import oss2
from pydub import AudioSegment # For audio conversion
from requests.cookies import RequestsCookieJar
def convert_to_mp3(input_path, output_path):
"""
Converts an audio file to MP3 format using pydub.
Args:
input_path (str): Path to the input audio file.
output_path (str): Path where the converted MP3 file will be saved.
Returns:
None
"""
sound = AudioSegment.from_file(input_path)
sound.export(output_path, format="mp3")
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, file_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(file_path, 'rb') as file:
result = bucket.put_object(sts_data['file_path'], file)
return result.status == 200
def upload_file(self, file_path, filetype):
filename = os.path.basename(file_path)
filesize = os.path.getsize(file_path)
# 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, file_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_file(image_path, filetype='image')
return file_url
except Exception as e:
raise Exception(f"Image upload failed: {str(e)}")
def upload_audio_to_cdn(base_url, auth_token, audio_path):
"""
Uploads an audio file 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.
audio_path (str): The local path to the audio file to upload.
Returns:
str: The CDN URL where the audio is accessible.
Raises:
Exception: If the upload fails at any step.
"""
class AudioUploader:
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, file_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(file_path, 'rb') as file:
result = bucket.put_object(
sts_data['file_path'],
file,
headers={'Content-Type': 'audio/mpeg'} # Set correct MIME type
)
return result.status == 200
def upload_file(self, file_path, filetype):
# Convert the audio file to MP3 format
mp3_path = f"{os.path.splitext(file_path)[0]}.mp3"
convert_to_mp3(file_path, mp3_path)
# Use the converted MP3 file for upload
filename = os.path.basename(mp3_path)
filesize = os.path.getsize(mp3_path)
# 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, mp3_path)
if upload_success:
return sts_data['file_url']
else:
raise Exception("Upload failed")
# Initialize the uploader and perform the upload
uploader = AudioUploader(base_url, auth_token)
try:
file_url = uploader.upload_file(audio_path, filetype='audio')
return file_url
except Exception as e:
raise Exception(f"Audio upload failed: {str(e)}") |