# 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 (
{error &&
{error}
} {result && (

Colorized Image:

Colorized Download
)}
); } 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