MogensR commited on
Commit
a545b7d
·
1 Parent(s): 3c486b8

Create examples/python/basic_usage.py

Browse files
Files changed (1) hide show
  1. examples/python/basic_usage.py +418 -0
examples/python/basic_usage.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ BackgroundFX Pro - Basic Python Usage Examples
4
+
5
+ This script demonstrates the fundamental operations of the BackgroundFX Pro API
6
+ including authentication, image processing, and result handling.
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Optional, Dict, Any
14
+
15
+ import requests
16
+ from PIL import Image
17
+ import json
18
+
19
+ # Configuration
20
+ API_BASE_URL = os.getenv("BACKGROUNDFX_API_URL", "https://api.backgroundfx.pro/v1")
21
+ API_KEY = os.getenv("BACKGROUNDFX_API_KEY", "your-api-key-here")
22
+
23
+
24
+ class BackgroundFXClient:
25
+ """Simple client for BackgroundFX Pro API."""
26
+
27
+ def __init__(self, api_key: str, base_url: str = API_BASE_URL):
28
+ """
29
+ Initialize the BackgroundFX client.
30
+
31
+ Args:
32
+ api_key: Your API key
33
+ base_url: API base URL
34
+ """
35
+ self.api_key = api_key
36
+ self.base_url = base_url.rstrip('/')
37
+ self.session = requests.Session()
38
+ self.session.headers.update({
39
+ 'Authorization': f'Bearer {api_key}',
40
+ 'User-Agent': 'BackgroundFX-Python-Client/1.0'
41
+ })
42
+
43
+ def remove_background(
44
+ self,
45
+ image_path: str,
46
+ quality: str = "high",
47
+ model: str = "auto",
48
+ return_mask: bool = False
49
+ ) -> Dict[str, Any]:
50
+ """
51
+ Remove background from an image.
52
+
53
+ Args:
54
+ image_path: Path to the image file
55
+ quality: Processing quality (low, medium, high, ultra)
56
+ model: Model to use (auto, rembg, u2net, sam2)
57
+ return_mask: Whether to return the mask image
58
+
59
+ Returns:
60
+ Dictionary with processed image URL and metadata
61
+ """
62
+ # Validate image exists
63
+ if not Path(image_path).exists():
64
+ raise FileNotFoundError(f"Image not found: {image_path}")
65
+
66
+ # Prepare the request
67
+ url = f"{self.base_url}/process/remove-background"
68
+
69
+ with open(image_path, 'rb') as f:
70
+ files = {'file': (Path(image_path).name, f, 'image/jpeg')}
71
+ data = {
72
+ 'quality': quality,
73
+ 'model': model,
74
+ 'return_mask': str(return_mask).lower()
75
+ }
76
+
77
+ # Make the request
78
+ print(f"Processing image: {image_path}")
79
+ response = self.session.post(url, files=files, data=data)
80
+
81
+ # Handle response
82
+ if response.status_code == 200:
83
+ result = response.json()
84
+ print(f"✓ Background removed successfully!")
85
+ print(f" Result URL: {result['image']}")
86
+ if return_mask and 'mask' in result:
87
+ print(f" Mask URL: {result['mask']}")
88
+ return result
89
+ else:
90
+ print(f"✗ Error: {response.status_code} - {response.text}")
91
+ response.raise_for_status()
92
+
93
+ def replace_background(
94
+ self,
95
+ image_id: str,
96
+ background: str,
97
+ blend_mode: str = "normal"
98
+ ) -> Dict[str, Any]:
99
+ """
100
+ Replace image background with a new one.
101
+
102
+ Args:
103
+ image_id: ID of the processed image
104
+ background: Background color (hex), gradient, or image URL
105
+ blend_mode: How to blend (normal, multiply, screen, overlay)
106
+
107
+ Returns:
108
+ Dictionary with result
109
+ """
110
+ url = f"{self.base_url}/process/replace-background"
111
+
112
+ payload = {
113
+ 'image_id': image_id,
114
+ 'background': background,
115
+ 'blend_mode': blend_mode
116
+ }
117
+
118
+ response = self.session.post(url, json=payload)
119
+
120
+ if response.status_code == 200:
121
+ result = response.json()
122
+ print(f"✓ Background replaced successfully!")
123
+ return result
124
+ else:
125
+ response.raise_for_status()
126
+
127
+ def download_result(self, url: str, output_path: str) -> str:
128
+ """
129
+ Download processed image to local file.
130
+
131
+ Args:
132
+ url: URL of the processed image
133
+ output_path: Where to save the image
134
+
135
+ Returns:
136
+ Path to saved file
137
+ """
138
+ response = requests.get(url, stream=True)
139
+ response.raise_for_status()
140
+
141
+ output_path = Path(output_path)
142
+ output_path.parent.mkdir(parents=True, exist_ok=True)
143
+
144
+ with open(output_path, 'wb') as f:
145
+ for chunk in response.iter_content(chunk_size=8192):
146
+ f.write(chunk)
147
+
148
+ print(f"✓ Downloaded to: {output_path}")
149
+ return str(output_path)
150
+
151
+ def get_usage_stats(self) -> Dict[str, Any]:
152
+ """
153
+ Get API usage statistics.
154
+
155
+ Returns:
156
+ Usage statistics dictionary
157
+ """
158
+ url = f"{self.base_url}/user/usage"
159
+ response = self.session.get(url)
160
+
161
+ if response.status_code == 200:
162
+ return response.json()
163
+ else:
164
+ response.raise_for_status()
165
+
166
+
167
+ def example_basic_processing():
168
+ """Example: Basic background removal."""
169
+ print("\n" + "="*60)
170
+ print("EXAMPLE 1: Basic Background Removal")
171
+ print("="*60)
172
+
173
+ client = BackgroundFXClient(API_KEY)
174
+
175
+ # Process an image
176
+ result = client.remove_background(
177
+ image_path="sample_images/portrait.jpg",
178
+ quality="high"
179
+ )
180
+
181
+ # Download the result
182
+ client.download_result(
183
+ result['image'],
184
+ "output/portrait_no_bg.png"
185
+ )
186
+
187
+ print("\n✓ Basic processing complete!")
188
+
189
+
190
+ def example_with_mask():
191
+ """Example: Get both processed image and mask."""
192
+ print("\n" + "="*60)
193
+ print("EXAMPLE 2: Background Removal with Mask")
194
+ print("="*60)
195
+
196
+ client = BackgroundFXClient(API_KEY)
197
+
198
+ # Process with mask
199
+ result = client.remove_background(
200
+ image_path="sample_images/product.jpg",
201
+ quality="ultra",
202
+ model="u2net",
203
+ return_mask=True
204
+ )
205
+
206
+ # Download both results
207
+ client.download_result(result['image'], "output/product_no_bg.png")
208
+ client.download_result(result['mask'], "output/product_mask.png")
209
+
210
+ print("\n✓ Processing with mask complete!")
211
+
212
+
213
+ def example_background_replacement():
214
+ """Example: Replace background with color/gradient."""
215
+ print("\n" + "="*60)
216
+ print("EXAMPLE 3: Background Replacement")
217
+ print("="*60)
218
+
219
+ client = BackgroundFXClient(API_KEY)
220
+
221
+ # First, remove background
222
+ result = client.remove_background(
223
+ image_path="sample_images/person.jpg",
224
+ quality="high"
225
+ )
226
+
227
+ image_id = result['id']
228
+
229
+ # Replace with solid color
230
+ color_result = client.replace_background(
231
+ image_id=image_id,
232
+ background="#3498db" # Blue background
233
+ )
234
+ client.download_result(color_result['image'], "output/person_blue_bg.png")
235
+
236
+ # Replace with gradient
237
+ gradient_result = client.replace_background(
238
+ image_id=image_id,
239
+ background="linear-gradient(45deg, #667eea, #764ba2)"
240
+ )
241
+ client.download_result(gradient_result['image'], "output/person_gradient_bg.png")
242
+
243
+ print("\n✓ Background replacement complete!")
244
+
245
+
246
+ def example_batch_processing():
247
+ """Example: Process multiple images."""
248
+ print("\n" + "="*60)
249
+ print("EXAMPLE 4: Batch Processing")
250
+ print("="*60)
251
+
252
+ client = BackgroundFXClient(API_KEY)
253
+
254
+ # List of images to process
255
+ images = [
256
+ "sample_images/product1.jpg",
257
+ "sample_images/product2.jpg",
258
+ "sample_images/product3.jpg"
259
+ ]
260
+
261
+ results = []
262
+ for image_path in images:
263
+ try:
264
+ print(f"\nProcessing: {image_path}")
265
+ result = client.remove_background(
266
+ image_path=image_path,
267
+ quality="medium" # Lower quality for batch
268
+ )
269
+ results.append(result)
270
+
271
+ # Download result
272
+ output_name = Path(image_path).stem + "_no_bg.png"
273
+ client.download_result(
274
+ result['image'],
275
+ f"output/batch/{output_name}"
276
+ )
277
+
278
+ except Exception as e:
279
+ print(f"✗ Failed to process {image_path}: {e}")
280
+
281
+ print(f"\n✓ Batch processing complete! Processed {len(results)}/{len(images)} images")
282
+
283
+
284
+ def example_quality_comparison():
285
+ """Example: Compare different quality settings."""
286
+ print("\n" + "="*60)
287
+ print("EXAMPLE 5: Quality Comparison")
288
+ print("="*60)
289
+
290
+ client = BackgroundFXClient(API_KEY)
291
+
292
+ image_path = "sample_images/detailed.jpg"
293
+ qualities = ["low", "medium", "high", "ultra"]
294
+
295
+ for quality in qualities:
296
+ print(f"\nProcessing with {quality} quality...")
297
+ start_time = time.time()
298
+
299
+ result = client.remove_background(
300
+ image_path=image_path,
301
+ quality=quality
302
+ )
303
+
304
+ processing_time = time.time() - start_time
305
+
306
+ # Download result
307
+ client.download_result(
308
+ result['image'],
309
+ f"output/comparison/detailed_{quality}.png"
310
+ )
311
+
312
+ # Print stats
313
+ print(f" Processing time: {processing_time:.2f}s")
314
+ print(f" File size: {result['metadata']['size'] / 1024:.1f} KB")
315
+ print(f" Resolution: {result['metadata']['width']}x{result['metadata']['height']}")
316
+
317
+ print("\n✓ Quality comparison complete!")
318
+
319
+
320
+ def example_error_handling():
321
+ """Example: Proper error handling."""
322
+ print("\n" + "="*60)
323
+ print("EXAMPLE 6: Error Handling")
324
+ print("="*60)
325
+
326
+ client = BackgroundFXClient(API_KEY)
327
+
328
+ # Test various error scenarios
329
+ test_cases = [
330
+ ("non_existent.jpg", "File not found"),
331
+ ("sample_images/corrupted.jpg", "Invalid image"),
332
+ ("sample_images/huge_file.jpg", "File too large")
333
+ ]
334
+
335
+ for image_path, expected_error in test_cases:
336
+ try:
337
+ print(f"\nTesting: {expected_error}")
338
+ result = client.remove_background(image_path)
339
+ print(f"✓ Unexpectedly succeeded")
340
+ except FileNotFoundError as e:
341
+ print(f"✓ Caught FileNotFoundError: {e}")
342
+ except requests.HTTPError as e:
343
+ print(f"✓ Caught HTTPError: {e.response.status_code}")
344
+ except Exception as e:
345
+ print(f"✓ Caught Exception: {type(e).__name__}: {e}")
346
+
347
+ print("\n✓ Error handling examples complete!")
348
+
349
+
350
+ def example_check_usage():
351
+ """Example: Check API usage and limits."""
352
+ print("\n" + "="*60)
353
+ print("EXAMPLE 7: Check API Usage")
354
+ print("="*60)
355
+
356
+ client = BackgroundFXClient(API_KEY)
357
+
358
+ try:
359
+ usage = client.get_usage_stats()
360
+
361
+ print("\nYour API Usage:")
362
+ print(f" Images processed: {usage['images_processed']}")
363
+ print(f" Videos processed: {usage['videos_processed']}")
364
+ print(f" Storage used: {usage['storage_used_mb']:.1f} MB")
365
+ print(f" API calls today: {usage['api_calls']}")
366
+
367
+ print(f"\nPlan Limits:")
368
+ limits = usage['plan_limits']
369
+ print(f" Images per month: {limits['images_per_month']}")
370
+ print(f" Storage: {limits['storage_gb']} GB")
371
+ print(f" API calls per hour: {limits['api_calls_per_hour']}")
372
+
373
+ except Exception as e:
374
+ print(f"✗ Failed to get usage stats: {e}")
375
+
376
+
377
+ def main():
378
+ """Run all examples."""
379
+ print("\n" + "#"*60)
380
+ print("# BackgroundFX Pro - Python Examples")
381
+ print("#"*60)
382
+
383
+ # Check API key
384
+ if API_KEY == "your-api-key-here":
385
+ print("\n⚠️ Please set your API key in the BACKGROUNDFX_API_KEY environment variable")
386
+ print(" or update the API_KEY variable in this script.")
387
+ sys.exit(1)
388
+
389
+ # Create output directories
390
+ Path("output/batch").mkdir(parents=True, exist_ok=True)
391
+ Path("output/comparison").mkdir(parents=True, exist_ok=True)
392
+ Path("sample_images").mkdir(parents=True, exist_ok=True)
393
+
394
+ # Run examples
395
+ examples = [
396
+ example_basic_processing,
397
+ example_with_mask,
398
+ example_background_replacement,
399
+ example_batch_processing,
400
+ example_quality_comparison,
401
+ example_error_handling,
402
+ example_check_usage
403
+ ]
404
+
405
+ for example in examples:
406
+ try:
407
+ example()
408
+ except Exception as e:
409
+ print(f"\n✗ Example failed: {e}")
410
+ print(" Continuing with next example...")
411
+
412
+ print("\n" + "#"*60)
413
+ print("# All examples complete!")
414
+ print("#"*60)
415
+
416
+
417
+ if __name__ == "__main__":
418
+ main()