Created
October 30, 2023 19:12
-
-
Save BackgroundCut/aaf926c10e441c95ee4e28925a4c22b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from requests.exceptions import RequestException | |
# API configuration | |
API_ENDPOINT = "https://backgroundcut.co/api/v1/cut/" | |
API_KEY = 'YOUR-API-KEY' | |
REQUEST_PARAMETERS = { | |
'file_url': 'https://www.example.com/example.jpg', | |
'max_resolution': '12000000', # 12 MegaPixels (for example 4000 * 3000) | |
'quality': 'medium', | |
'return_format': 'webp', | |
} | |
TIMEOUT_DURATION = 20 # seconds | |
LOCAL_FILENAME = "/path/to/output.webp" | |
# Authorization header | |
auth_header = {'Authorization': f'Token {API_KEY}'} | |
try: | |
response = requests.post(API_ENDPOINT, | |
data=REQUEST_PARAMETERS, | |
headers=auth_header, | |
timeout=TIMEOUT_DURATION) | |
# Check response status code | |
if response.status_code == 200: | |
response_data = response.json() | |
output_image_url = response_data['output_image_url'] | |
# Download the output image | |
output_image_response = requests.get(output_image_url, stream=True) | |
output_image_response.raise_for_status() | |
# Save the image | |
with open(LOCAL_FILENAME, 'wb') as f: | |
for chunk in output_image_response.iter_content(chunk_size=8192): | |
f.write(chunk) | |
elif 400 <= response.status_code < 500: | |
try: | |
error_message = response.json().get('error', 'No error message provided') | |
except: | |
error_message = 'No error message provided' | |
raise Exception(f"Client error. Status Code: {response.status_code}. Error Message: {error_message}") | |
elif 500 <= response.status_code < 600: | |
raise Exception(f"Server error. Status Code: {response.status_code}") | |
else: | |
raise Exception(f"Unexpected response. Status Code: {response.status_code}") | |
except RequestException as req_err: | |
# Other errors (e.g., network issues, timeouts, etc.) | |
raise Exception(f"Request error occurred: {req_err}") | |
except Exception as e: | |
# Fallback for other unforeseen errors | |
raise Exception(f"An error occurred: {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment