""" API Client Examples for Binary Segmentation Service These examples show how to interact with the FastAPI service from Python, JavaScript, and curl. """ import requests import base64 import json from pathlib import Path # ============================================================================= # Python Client Examples # ============================================================================= class SegmentationClient: """Python client for segmentation API""" def __init__(self, base_url: str = "http://localhost:7860"): self.base_url = base_url.rstrip('/') def segment_image( self, image_path: str, output_path: str, model: str = "u2netp", threshold: float = 0.5 ): """ Segment image and save as PNG with transparency Args: image_path: Path to input image output_path: Path to save output PNG model: Model to use (u2netp, birefnet, rmbg) threshold: Segmentation threshold (0.0-1.0) """ with open(image_path, 'rb') as f: files = {'file': f} data = { 'model': model, 'threshold': threshold } response = requests.post( f"{self.base_url}/segment", files=files, data=data ) response.raise_for_status() with open(output_path, 'wb') as out: out.write(response.content) print(f"✓ Saved to: {output_path}") def get_mask( self, image_path: str, output_path: str, model: str = "u2netp", threshold: float = 0.5 ): """Get binary mask only""" with open(image_path, 'rb') as f: files = {'file': f} data = { 'model': model, 'threshold': threshold } response = requests.post( f"{self.base_url}/segment/mask", files=files, data=data ) response.raise_for_status() with open(output_path, 'wb') as out: out.write(response.content) print(f"✓ Mask saved to: {output_path}") def segment_base64( self, image_path: str, model: str = "u2netp", threshold: float = 0.5, return_type: str = "both" ): """ Get segmentation results as base64 Returns: dict with 'mask' and/or 'rgba' as base64 strings """ with open(image_path, 'rb') as f: files = {'file': f} data = { 'model': model, 'threshold': threshold, 'return_type': return_type } response = requests.post( f"{self.base_url}/segment/base64", files=files, data=data ) response.raise_for_status() return response.json() def batch_segment( self, image_paths: list[str], model: str = "u2netp", threshold: float = 0.5 ): """ Segment multiple images Args: image_paths: List of paths to images (max 10) Returns: dict with results for each image """ files = [ ('files', open(path, 'rb')) for path in image_paths ] data = { 'model': model, 'threshold': threshold } try: response = requests.post( f"{self.base_url}/segment/batch", files=files, data=data ) response.raise_for_status() return response.json() finally: # Close all file handles for _, f in files: f.close() def list_models(self): """List available models""" response = requests.get(f"{self.base_url}/models") response.raise_for_status() return response.json() def health_check(self): """Check service health""" response = requests.get(f"{self.base_url}/health") response.raise_for_status() return response.json() # ============================================================================= # Usage Examples # ============================================================================= def example_basic(): """Basic usage""" client = SegmentationClient("http://localhost:7860") # Segment image client.segment_image( image_path="input.jpg", output_path="output.png", model="u2netp", threshold=0.5 ) def example_mask(): """Get binary mask""" client = SegmentationClient("http://localhost:7860") client.get_mask( image_path="input.jpg", output_path="mask.png", model="u2netp", threshold=0.5 ) def example_base64(): """Get base64 results""" client = SegmentationClient("http://localhost:7860") result = client.segment_base64( image_path="input.jpg", return_type="both" ) # Save base64 images if 'rgba' in result: # Remove data URL prefix rgba_data = result['rgba'].split(',')[1] with open('output_rgba.png', 'wb') as f: f.write(base64.b64decode(rgba_data)) if 'mask' in result: mask_data = result['mask'].split(',')[1] with open('output_mask.png', 'wb') as f: f.write(base64.b64decode(mask_data)) def example_batch(): """Process multiple images""" client = SegmentationClient("http://localhost:7860") results = client.batch_segment( image_paths=["image1.jpg", "image2.jpg", "image3.jpg"], model="u2netp", threshold=0.5 ) # Save results for i, result in enumerate(results['results']): if result['success']: rgba_data = result['rgba'].split(',')[1] with open(f'output_{i}.png', 'wb') as f: f.write(base64.b64decode(rgba_data)) def example_models(): """List available models""" client = SegmentationClient("http://localhost:7860") models = client.list_models() print(json.dumps(models, indent=2)) # ============================================================================= # JavaScript Examples (for frontend) # ============================================================================= JAVASCRIPT_EXAMPLES = """ // Example 1: Basic fetch async function segmentImage(file) { const formData = new FormData(); formData.append('file', file); formData.append('model', 'u2netp'); formData.append('threshold', '0.5'); const response = await fetch('/segment', { method: 'POST', body: formData }); const blob = await response.blob(); return URL.createObjectURL(blob); } // Example 2: Get base64 async function segmentBase64(file) { const formData = new FormData(); formData.append('file', file); formData.append('model', 'u2netp'); formData.append('threshold', '0.5'); formData.append('return_type', 'rgba'); const response = await fetch('/segment/base64', { method: 'POST', body: formData }); const data = await response.json(); return data.rgba; // data:image/png;base64,... } // Example 3: Batch processing async function segmentBatch(files) { const formData = new FormData(); for (const file of files) { formData.append('files', file); } formData.append('model', 'u2netp'); formData.append('threshold', '0.5'); const response = await fetch('/segment/batch', { method: 'POST', body: formData }); return await response.json(); } // Example 4: With progress async function segmentWithProgress(file, onProgress) { const formData = new FormData(); formData.append('file', file); formData.append('model', 'u2netp'); formData.append('threshold', '0.5'); const xhr = new XMLHttpRequest(); return new Promise((resolve, reject) => { xhr.upload.addEventListener('progress', (e) => { if (e.lengthComputable) { onProgress(e.loaded / e.total); } }); xhr.addEventListener('load', () => { if (xhr.status === 200) { const blob = xhr.response; resolve(URL.createObjectURL(blob)); } else { reject(new Error('Upload failed')); } }); xhr.addEventListener('error', () => reject(new Error('Upload failed'))); xhr.open('POST', '/segment'); xhr.responseType = 'blob'; xhr.send(formData); }); } """ # ============================================================================= # cURL Examples # ============================================================================= CURL_EXAMPLES = """ # Example 1: Basic segmentation curl -X POST "http://localhost:7860/segment" \\ -F "file=@input.jpg" \\ -F "model=u2netp" \\ -F "threshold=0.5" \\ --output result.png # Example 2: Get mask curl -X POST "http://localhost:7860/segment/mask" \\ -F "file=@input.jpg" \\ -F "model=u2netp" \\ -F "threshold=0.5" \\ --output mask.png # Example 3: Get base64 JSON curl -X POST "http://localhost:7860/segment/base64" \\ -F "file=@input.jpg" \\ -F "model=u2netp" \\ -F "threshold=0.5" \\ -F "return_type=both" # Example 4: Batch processing curl -X POST "http://localhost:7860/segment/batch" \\ -F "files=@image1.jpg" \\ -F "files=@image2.jpg" \\ -F "files=@image3.jpg" \\ -F "model=u2netp" \\ -F "threshold=0.5" # Example 5: List models curl -X GET "http://localhost:7860/models" # Example 6: Health check curl -X GET "http://localhost:7860/health" """ if __name__ == "__main__": print("API Client Examples") print("=" * 50) print("\nPython Examples:") print(" example_basic() - Basic segmentation") print(" example_mask() - Get binary mask") print(" example_base64() - Get base64 results") print(" example_batch() - Batch processing") print(" example_models() - List models") print("\nUncomment the example you want to run!") # Uncomment to run: # example_basic() # example_mask() # example_base64() # example_batch() # example_models()