File size: 14,057 Bytes
2ae242d |
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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
# API Usage Examples
## Python Examples
### Example 1: Colorize Image with Requests
```python
import requests
# Your Firebase App Check token
APP_CHECK_TOKEN = "your-app-check-token-here"
API_BASE_URL = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
# Colorize an image
def colorize_image(image_path):
url = f"{API_BASE_URL}/colorize"
headers = {
"X-Firebase-AppCheck": APP_CHECK_TOKEN
}
with open(image_path, "rb") as f:
files = {"file": f}
response = requests.post(url, headers=headers, files=files)
if response.status_code == 200:
result = response.json()
print(f"Success! Download URL: {result['download_url']}")
return result
else:
print(f"Error: {response.status_code} - {response.text}")
return None
# Usage
result = colorize_image("grayscale_image.jpg")
if result:
print(f"Colorized image available at: {result['download_url']}")
```
### Example 2: Upload and Colorize
```python
import requests
APP_CHECK_TOKEN = "your-app-check-token-here"
API_BASE_URL = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
def upload_and_colorize(image_path):
headers = {"X-Firebase-AppCheck": APP_CHECK_TOKEN}
# Step 1: Upload image
with open(image_path, "rb") as f:
files = {"file": f}
upload_response = requests.post(
f"{API_BASE_URL}/upload",
headers=headers,
files=files
)
if upload_response.status_code != 200:
print(f"Upload failed: {upload_response.text}")
return None
upload_result = upload_response.json()
print(f"Image uploaded: {upload_result['image_url']}")
# Step 2: Colorize the uploaded image
with open(image_path, "rb") as f:
files = {"file": f}
colorize_response = requests.post(
f"{API_BASE_URL}/colorize",
headers=headers,
files=files
)
if colorize_response.status_code == 200:
result = colorize_response.json()
print(f"Colorized image: {result['download_url']}")
return result
else:
print(f"Colorization failed: {colorize_response.text}")
return None
# Usage
result = upload_and_colorize("my_image.jpg")
```
### Example 3: Download Result
```python
import requests
APP_CHECK_TOKEN = "your-app-check-token-here"
API_BASE_URL = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
def download_colorized_image(result_id, output_path):
url = f"{API_BASE_URL}/download/{result_id}"
headers = {"X-Firebase-AppCheck": APP_CHECK_TOKEN}
response = requests.get(url, headers=headers)
if response.status_code == 200:
with open(output_path, "wb") as f:
f.write(response.content)
print(f"Image saved to: {output_path}")
return True
else:
print(f"Download failed: {response.status_code}")
return False
# Usage
result = colorize_image("input.jpg")
if result:
download_colorized_image(result["result_id"], "colorized_output.jpg")
```
---
## JavaScript/TypeScript Examples
### Example 1: Colorize Image with Fetch
```javascript
const API_BASE_URL = 'https://logicgoinfotechspaces-text-guided-image-colorization.hf.space';
async function colorizeImage(imageFile, appCheckToken) {
const formData = new FormData();
formData.append('file', imageFile);
try {
const response = await fetch(`${API_BASE_URL}/colorize`, {
method: 'POST',
headers: {
'X-Firebase-AppCheck': appCheckToken
},
body: formData
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Colorization failed');
}
const result = await response.json();
console.log('Colorized image URL:', result.download_url);
return result;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// Usage
const fileInput = document.getElementById('image-input');
const file = fileInput.files[0];
colorizeImage(file, appCheckToken)
.then(result => {
// Display the image
const img = document.createElement('img');
img.src = result.download_url;
document.body.appendChild(img);
})
.catch(error => {
console.error('Failed to colorize:', error);
});
```
### Example 2: Complete Workflow with Firebase App Check
```javascript
import { initializeApp } from "firebase/app";
import { initializeAppCheck, ReCaptchaEnterpriseProvider } from "firebase/app-check";
// Initialize Firebase
const firebaseConfig = {
apiKey: "AIzaSyBIB6rcfyyqy5niERTXWvVD714Ter4Vx68",
authDomain: "colorize-662df.firebaseapp.com",
projectId: "colorize-662df",
storageBucket: "colorize-662df.firebasestorage.app",
messagingSenderId: "69166278311",
appId: "1:69166278311:web:0e8c50b8dd8627aaeadd82",
measurementId: "G-58CC2J8XKX"
};
const app = initializeApp(firebaseConfig);
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaEnterpriseProvider('YOUR_RECAPTCHA_SITE_KEY'),
isTokenAutoRefreshEnabled: true
});
// Get App Check token
async function getAppCheckToken() {
const { getToken } = await import('firebase/app-check');
try {
const token = await getToken(appCheck);
return token.token;
} catch (error) {
console.error('Error getting App Check token:', error);
return null;
}
}
// Colorize image function
async function colorizeImageWithAppCheck(imageFile) {
const token = await getAppCheckToken();
if (!token) {
throw new Error('Failed to get App Check token');
}
const formData = new FormData();
formData.append('file', imageFile);
const response = await fetch(
'https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize',
{
method: 'POST',
headers: {
'X-Firebase-AppCheck': token
},
body: formData
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Colorization failed');
}
return await response.json();
}
// Usage in HTML form
document.getElementById('colorize-form').addEventListener('submit', async (e) => {
e.preventDefault();
const fileInput = document.getElementById('image-input');
const file = fileInput.files[0];
if (!file) {
alert('Please select an image');
return;
}
try {
const result = await colorizeImageWithAppCheck(file);
// Display result
const resultImg = document.getElementById('result-image');
resultImg.src = result.download_url;
resultImg.style.display = 'block';
console.log('Colorized image:', result.download_url);
} catch (error) {
console.error('Error:', error);
alert('Failed to colorize image: ' + error.message);
}
});
```
### Example 3: React Component
```jsx
import React, { useState } from 'react';
import { getToken } from 'firebase/app-check';
function ColorizeImage() {
const [file, setFile] = useState(null);
const [loading, setLoading] = useState(false);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
const handleFileChange = (e) => {
setFile(e.target.files[0]);
setResult(null);
setError(null);
};
const handleColorize = async () => {
if (!file) {
setError('Please select an image');
return;
}
setLoading(true);
setError(null);
try {
// Get App Check token
const token = await getToken(appCheck);
const formData = new FormData();
formData.append('file', file);
const response = await fetch(
'https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize',
{
method: 'POST',
headers: {
'X-Firebase-AppCheck': token.token
},
body: formData
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Colorization failed');
}
const data = await response.json();
setResult(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<div>
<input type="file" accept="image/*" onChange={handleFileChange} />
<button onClick={handleColorize} disabled={loading || !file}>
{loading ? 'Colorizing...' : 'Colorize Image'}
</button>
{error && <div className="error">{error}</div>}
{result && (
<div>
<h3>Colorized Image:</h3>
<img src={result.download_url} alt="Colorized" />
<a href={result.download_url} download>Download</a>
</div>
)}
</div>
);
}
export default ColorizeImage;
```
---
## cURL Examples
### Health Check
```bash
curl https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/health
```
### Upload Image
```bash
curl -X POST \
https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/upload \
-H "X-Firebase-AppCheck: YOUR_TOKEN" \
-F "file=@image.jpg"
```
### Colorize Image
```bash
curl -X POST \
https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize \
-H "X-Firebase-AppCheck: YOUR_TOKEN" \
-F "file=@grayscale_image.jpg" \
-o response.json
```
### Download Result
```bash
# Get result ID from colorize response first
RESULT_ID="550e8400-e29b-41d4-a716-446655440000"
curl -X GET \
https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/download/${RESULT_ID} \
-H "X-Firebase-AppCheck: YOUR_TOKEN" \
-o colorized_image.jpg
```
---
## Postman Collection
### Collection JSON
```json
{
"info": {
"name": "Colorize API",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Health Check",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/health",
"protocol": "https",
"host": ["logicgoinfotechspaces-text-guided-image-colorization", "hf", "space"],
"path": ["health"]
}
}
},
{
"name": "Colorize Image",
"request": {
"method": "POST",
"header": [
{
"key": "X-Firebase-AppCheck",
"value": "{{app_check_token}}",
"type": "text"
}
],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "file",
"type": "file",
"src": []
}
]
},
"url": {
"raw": "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize",
"protocol": "https",
"host": ["logicgoinfotechspaces-text-guided-image-colorization", "hf", "space"],
"path": ["colorize"]
}
}
}
],
"variable": [
{
"key": "app_check_token",
"value": "your-token-here"
}
]
}
```
---
## Error Handling Examples
### Python
```python
import requests
def colorize_with_error_handling(image_path, token):
url = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize"
headers = {"X-Firebase-AppCheck": token}
try:
with open(image_path, "rb") as f:
files = {"file": f}
response = requests.post(url, headers=headers, files=files, timeout=120)
if response.status_code == 200:
return response.json()
elif response.status_code == 401:
raise Exception("Invalid or missing App Check token")
elif response.status_code == 400:
raise Exception("Invalid file or request")
elif response.status_code == 503:
raise Exception("Model not loaded, please try again later")
else:
error = response.json()
raise Exception(f"Error {response.status_code}: {error.get('detail', 'Unknown error')}")
except requests.exceptions.Timeout:
raise Exception("Request timed out. Image processing may take 30-60 seconds.")
except requests.exceptions.RequestException as e:
raise Exception(f"Network error: {str(e)}")
```
### JavaScript
```javascript
async function colorizeWithErrorHandling(imageFile, token) {
try {
const formData = new FormData();
formData.append('file', imageFile);
const response = await fetch(
'https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize',
{
method: 'POST',
headers: {
'X-Firebase-AppCheck': token
},
body: formData,
signal: AbortSignal.timeout(120000) // 120 second timeout
}
);
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 401:
throw new Error('Invalid or missing App Check token');
case 400:
throw new Error('Invalid file or request');
case 503:
throw new Error('Model not loaded, please try again later');
default:
throw new Error(error.detail || `Error ${response.status}: ${response.statusText}`);
}
}
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
throw new Error('Request timed out. Image processing may take 30-60 seconds.');
}
throw error;
}
}
```
---
## Best Practices
1. **Always check health endpoint first** before making requests
2. **Handle timeouts** - Processing can take 30-60 seconds on CPU
3. **Cache App Check tokens** - They auto-refresh, but cache them to avoid unnecessary requests
4. **Use public URLs** for displaying images (no auth needed)
5. **Handle errors gracefully** - Show user-friendly error messages
6. **Validate file types** before uploading
7. **Show loading indicators** during processing
|