Spaces:
Running
Running
File size: 10,775 Bytes
492772b |
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 |
"""
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()
|