| |
| """ |
| 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 |
|
|
| |
| 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 |
| """ |
| |
| if not Path(image_path).exists(): |
| raise FileNotFoundError(f"Image not found: {image_path}") |
| |
| |
| 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() |
| } |
| |
| |
| print(f"Processing image: {image_path}") |
| response = self.session.post(url, files=files, data=data) |
| |
| |
| 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) |
| |
| |
| result = client.remove_background( |
| image_path="sample_images/portrait.jpg", |
| quality="high" |
| ) |
| |
| |
| 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) |
| |
| |
| result = client.remove_background( |
| image_path="sample_images/product.jpg", |
| quality="ultra", |
| model="u2net", |
| return_mask=True |
| ) |
| |
| |
| 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) |
| |
| |
| result = client.remove_background( |
| image_path="sample_images/person.jpg", |
| quality="high" |
| ) |
| |
| image_id = result['id'] |
| |
| |
| color_result = client.replace_background( |
| image_id=image_id, |
| background="#3498db" |
| ) |
| client.download_result(color_result['image'], "output/person_blue_bg.png") |
| |
| |
| 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) |
| |
| |
| 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" |
| ) |
| results.append(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 |
| |
| |
| client.download_result( |
| result['image'], |
| f"output/comparison/detailed_{quality}.png" |
| ) |
| |
| |
| 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_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) |
| |
| |
| 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) |
| |
| |
| 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) |
| |
| |
| 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() |