Upload a local file to a URL. output_url: The URL to upload the file to. data_or_file: Either the data to upload or the path to the file to upload. from_file: If True, data_or_file is the path to the file to upload.
(output_url: str, data_or_file: str, from_file: bool)
| 181 | |
| 182 | |
| 183 | async def upload_data(output_url: str, data_or_file: str, from_file: bool) -> None: |
| 184 | """ |
| 185 | Upload a local file to a URL. |
| 186 | output_url: The URL to upload the file to. |
| 187 | data_or_file: Either the data to upload or the path to the file to upload. |
| 188 | from_file: If True, data_or_file is the path to the file to upload. |
| 189 | """ |
| 190 | # Timeout is a common issue when uploading large files. |
| 191 | # We retry max_retries times before giving up. |
| 192 | max_retries = 5 |
| 193 | # Number of seconds to wait before retrying. |
| 194 | delay = 5 |
| 195 | |
| 196 | for attempt in range(1, max_retries + 1): |
| 197 | try: |
| 198 | # We increase the timeout to 1000 seconds to allow |
| 199 | # for large files (default is 300). |
| 200 | async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=1000)) as session: |
| 201 | if from_file: |
| 202 | with open(data_or_file, "rb") as file: |
| 203 | async with session.put(output_url, data=file) as response: |
| 204 | if response.status != 200: |
| 205 | raise Exception( |
| 206 | f"Failed to upload file.\n" |
| 207 | f"Status: {response.status}\n" |
| 208 | f"Response: {response.text()}" |
| 209 | ) |
| 210 | else: |
| 211 | async with session.put(output_url, data=data_or_file) as response: |
| 212 | if response.status != 200: |
| 213 | raise Exception( |
| 214 | f"Failed to upload data.\n" |
| 215 | f"Status: {response.status}\n" |
| 216 | f"Response: {response.text()}" |
| 217 | ) |
| 218 | |
| 219 | except Exception as e: |
| 220 | if attempt < max_retries: |
| 221 | console_logger.error( |
| 222 | "Failed to upload data (attempt %d). Error message: %s.\nRetrying in %d seconds...", # noqa: E501 |
| 223 | attempt, |
| 224 | e, |
| 225 | delay, |
| 226 | ) |
| 227 | await asyncio.sleep(delay) |
| 228 | else: |
| 229 | raise Exception( |
| 230 | f"Failed to upload data (attempt {attempt}). Error message: {str(e)}." # noqa: E501 |
| 231 | ) from e |
| 232 | |
| 233 | |
| 234 | async def write_file(path_or_url: str, batch_outputs: list[BatchRequestOutput], output_tmp_dir: str) -> None: |