File size: 12,623 Bytes
a545b7d |
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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 |
#!/usr/bin/env python3
"""
BackgroundFX Pro - Basic Python Usage Examples
This script demonstrates the fundamental operations of the BackgroundFX Pro API
including authentication, image processing, and result handling.
"""
import os
import sys
import time
from pathlib import Path
from typing import Optional, Dict, Any
import requests
from PIL import Image
import json
# Configuration
API_BASE_URL = os.getenv("BACKGROUNDFX_API_URL", "https://api.backgroundfx.pro/v1")
API_KEY = os.getenv("BACKGROUNDFX_API_KEY", "your-api-key-here")
class BackgroundFXClient:
"""Simple client for BackgroundFX Pro API."""
def __init__(self, api_key: str, base_url: str = API_BASE_URL):
"""
Initialize the BackgroundFX client.
Args:
api_key: Your API key
base_url: API base URL
"""
self.api_key = api_key
self.base_url = base_url.rstrip('/')
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'User-Agent': 'BackgroundFX-Python-Client/1.0'
})
def remove_background(
self,
image_path: str,
quality: str = "high",
model: str = "auto",
return_mask: bool = False
) -> Dict[str, Any]:
"""
Remove background from an image.
Args:
image_path: Path to the image file
quality: Processing quality (low, medium, high, ultra)
model: Model to use (auto, rembg, u2net, sam2)
return_mask: Whether to return the mask image
Returns:
Dictionary with processed image URL and metadata
"""
# Validate image exists
if not Path(image_path).exists():
raise FileNotFoundError(f"Image not found: {image_path}")
# Prepare the request
url = f"{self.base_url}/process/remove-background"
with open(image_path, 'rb') as f:
files = {'file': (Path(image_path).name, f, 'image/jpeg')}
data = {
'quality': quality,
'model': model,
'return_mask': str(return_mask).lower()
}
# Make the request
print(f"Processing image: {image_path}")
response = self.session.post(url, files=files, data=data)
# Handle response
if response.status_code == 200:
result = response.json()
print(f"β Background removed successfully!")
print(f" Result URL: {result['image']}")
if return_mask and 'mask' in result:
print(f" Mask URL: {result['mask']}")
return result
else:
print(f"β Error: {response.status_code} - {response.text}")
response.raise_for_status()
def replace_background(
self,
image_id: str,
background: str,
blend_mode: str = "normal"
) -> Dict[str, Any]:
"""
Replace image background with a new one.
Args:
image_id: ID of the processed image
background: Background color (hex), gradient, or image URL
blend_mode: How to blend (normal, multiply, screen, overlay)
Returns:
Dictionary with result
"""
url = f"{self.base_url}/process/replace-background"
payload = {
'image_id': image_id,
'background': background,
'blend_mode': blend_mode
}
response = self.session.post(url, json=payload)
if response.status_code == 200:
result = response.json()
print(f"β Background replaced successfully!")
return result
else:
response.raise_for_status()
def download_result(self, url: str, output_path: str) -> str:
"""
Download processed image to local file.
Args:
url: URL of the processed image
output_path: Where to save the image
Returns:
Path to saved file
"""
response = requests.get(url, stream=True)
response.raise_for_status()
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"β Downloaded to: {output_path}")
return str(output_path)
def get_usage_stats(self) -> Dict[str, Any]:
"""
Get API usage statistics.
Returns:
Usage statistics dictionary
"""
url = f"{self.base_url}/user/usage"
response = self.session.get(url)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def example_basic_processing():
"""Example: Basic background removal."""
print("\n" + "="*60)
print("EXAMPLE 1: Basic Background Removal")
print("="*60)
client = BackgroundFXClient(API_KEY)
# Process an image
result = client.remove_background(
image_path="sample_images/portrait.jpg",
quality="high"
)
# Download the result
client.download_result(
result['image'],
"output/portrait_no_bg.png"
)
print("\nβ Basic processing complete!")
def example_with_mask():
"""Example: Get both processed image and mask."""
print("\n" + "="*60)
print("EXAMPLE 2: Background Removal with Mask")
print("="*60)
client = BackgroundFXClient(API_KEY)
# Process with mask
result = client.remove_background(
image_path="sample_images/product.jpg",
quality="ultra",
model="u2net",
return_mask=True
)
# Download both results
client.download_result(result['image'], "output/product_no_bg.png")
client.download_result(result['mask'], "output/product_mask.png")
print("\nβ Processing with mask complete!")
def example_background_replacement():
"""Example: Replace background with color/gradient."""
print("\n" + "="*60)
print("EXAMPLE 3: Background Replacement")
print("="*60)
client = BackgroundFXClient(API_KEY)
# First, remove background
result = client.remove_background(
image_path="sample_images/person.jpg",
quality="high"
)
image_id = result['id']
# Replace with solid color
color_result = client.replace_background(
image_id=image_id,
background="#3498db" # Blue background
)
client.download_result(color_result['image'], "output/person_blue_bg.png")
# Replace with gradient
gradient_result = client.replace_background(
image_id=image_id,
background="linear-gradient(45deg, #667eea, #764ba2)"
)
client.download_result(gradient_result['image'], "output/person_gradient_bg.png")
print("\nβ Background replacement complete!")
def example_batch_processing():
"""Example: Process multiple images."""
print("\n" + "="*60)
print("EXAMPLE 4: Batch Processing")
print("="*60)
client = BackgroundFXClient(API_KEY)
# List of images to process
images = [
"sample_images/product1.jpg",
"sample_images/product2.jpg",
"sample_images/product3.jpg"
]
results = []
for image_path in images:
try:
print(f"\nProcessing: {image_path}")
result = client.remove_background(
image_path=image_path,
quality="medium" # Lower quality for batch
)
results.append(result)
# Download result
output_name = Path(image_path).stem + "_no_bg.png"
client.download_result(
result['image'],
f"output/batch/{output_name}"
)
except Exception as e:
print(f"β Failed to process {image_path}: {e}")
print(f"\nβ Batch processing complete! Processed {len(results)}/{len(images)} images")
def example_quality_comparison():
"""Example: Compare different quality settings."""
print("\n" + "="*60)
print("EXAMPLE 5: Quality Comparison")
print("="*60)
client = BackgroundFXClient(API_KEY)
image_path = "sample_images/detailed.jpg"
qualities = ["low", "medium", "high", "ultra"]
for quality in qualities:
print(f"\nProcessing with {quality} quality...")
start_time = time.time()
result = client.remove_background(
image_path=image_path,
quality=quality
)
processing_time = time.time() - start_time
# Download result
client.download_result(
result['image'],
f"output/comparison/detailed_{quality}.png"
)
# Print stats
print(f" Processing time: {processing_time:.2f}s")
print(f" File size: {result['metadata']['size'] / 1024:.1f} KB")
print(f" Resolution: {result['metadata']['width']}x{result['metadata']['height']}")
print("\nβ Quality comparison complete!")
def example_error_handling():
"""Example: Proper error handling."""
print("\n" + "="*60)
print("EXAMPLE 6: Error Handling")
print("="*60)
client = BackgroundFXClient(API_KEY)
# Test various error scenarios
test_cases = [
("non_existent.jpg", "File not found"),
("sample_images/corrupted.jpg", "Invalid image"),
("sample_images/huge_file.jpg", "File too large")
]
for image_path, expected_error in test_cases:
try:
print(f"\nTesting: {expected_error}")
result = client.remove_background(image_path)
print(f"β Unexpectedly succeeded")
except FileNotFoundError as e:
print(f"β Caught FileNotFoundError: {e}")
except requests.HTTPError as e:
print(f"β Caught HTTPError: {e.response.status_code}")
except Exception as e:
print(f"β Caught Exception: {type(e).__name__}: {e}")
print("\nβ Error handling examples complete!")
def example_check_usage():
"""Example: Check API usage and limits."""
print("\n" + "="*60)
print("EXAMPLE 7: Check API Usage")
print("="*60)
client = BackgroundFXClient(API_KEY)
try:
usage = client.get_usage_stats()
print("\nYour API Usage:")
print(f" Images processed: {usage['images_processed']}")
print(f" Videos processed: {usage['videos_processed']}")
print(f" Storage used: {usage['storage_used_mb']:.1f} MB")
print(f" API calls today: {usage['api_calls']}")
print(f"\nPlan Limits:")
limits = usage['plan_limits']
print(f" Images per month: {limits['images_per_month']}")
print(f" Storage: {limits['storage_gb']} GB")
print(f" API calls per hour: {limits['api_calls_per_hour']}")
except Exception as e:
print(f"β Failed to get usage stats: {e}")
def main():
"""Run all examples."""
print("\n" + "#"*60)
print("# BackgroundFX Pro - Python Examples")
print("#"*60)
# Check API key
if API_KEY == "your-api-key-here":
print("\nβ οΈ Please set your API key in the BACKGROUNDFX_API_KEY environment variable")
print(" or update the API_KEY variable in this script.")
sys.exit(1)
# Create output directories
Path("output/batch").mkdir(parents=True, exist_ok=True)
Path("output/comparison").mkdir(parents=True, exist_ok=True)
Path("sample_images").mkdir(parents=True, exist_ok=True)
# Run examples
examples = [
example_basic_processing,
example_with_mask,
example_background_replacement,
example_batch_processing,
example_quality_comparison,
example_error_handling,
example_check_usage
]
for example in examples:
try:
example()
except Exception as e:
print(f"\nβ Example failed: {e}")
print(" Continuing with next example...")
print("\n" + "#"*60)
print("# All examples complete!")
print("#"*60)
if __name__ == "__main__":
main() |