LogicGoInfotechSpaces commited on
Commit
adf77e7
·
verified ·
1 Parent(s): c335010

Delete API_EXAMPLES.md

Browse files
Files changed (1) hide show
  1. API_EXAMPLES.md +0 -541
API_EXAMPLES.md DELETED
@@ -1,541 +0,0 @@
1
- # API Usage Examples
2
-
3
- ## Python Examples
4
-
5
- ### Example 1: Colorize Image with Requests
6
-
7
- ```python
8
- import requests
9
-
10
- # Your Firebase App Check token
11
- APP_CHECK_TOKEN = "your-app-check-token-here"
12
- API_BASE_URL = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
13
-
14
- # Colorize an image
15
- def colorize_image(image_path):
16
- url = f"{API_BASE_URL}/colorize"
17
- headers = {
18
- "X-Firebase-AppCheck": APP_CHECK_TOKEN
19
- }
20
-
21
- with open(image_path, "rb") as f:
22
- files = {"file": f}
23
- response = requests.post(url, headers=headers, files=files)
24
-
25
- if response.status_code == 200:
26
- result = response.json()
27
- print(f"Success! Download URL: {result['download_url']}")
28
- return result
29
- else:
30
- print(f"Error: {response.status_code} - {response.text}")
31
- return None
32
-
33
- # Usage
34
- result = colorize_image("grayscale_image.jpg")
35
- if result:
36
- print(f"Colorized image available at: {result['download_url']}")
37
- ```
38
-
39
- ### Example 2: Upload and Colorize
40
-
41
- ```python
42
- import requests
43
-
44
- APP_CHECK_TOKEN = "your-app-check-token-here"
45
- API_BASE_URL = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
46
-
47
- def upload_and_colorize(image_path):
48
- headers = {"X-Firebase-AppCheck": APP_CHECK_TOKEN}
49
-
50
- # Step 1: Upload image
51
- with open(image_path, "rb") as f:
52
- files = {"file": f}
53
- upload_response = requests.post(
54
- f"{API_BASE_URL}/upload",
55
- headers=headers,
56
- files=files
57
- )
58
-
59
- if upload_response.status_code != 200:
60
- print(f"Upload failed: {upload_response.text}")
61
- return None
62
-
63
- upload_result = upload_response.json()
64
- print(f"Image uploaded: {upload_result['image_url']}")
65
-
66
- # Step 2: Colorize the uploaded image
67
- with open(image_path, "rb") as f:
68
- files = {"file": f}
69
- colorize_response = requests.post(
70
- f"{API_BASE_URL}/colorize",
71
- headers=headers,
72
- files=files
73
- )
74
-
75
- if colorize_response.status_code == 200:
76
- result = colorize_response.json()
77
- print(f"Colorized image: {result['download_url']}")
78
- return result
79
- else:
80
- print(f"Colorization failed: {colorize_response.text}")
81
- return None
82
-
83
- # Usage
84
- result = upload_and_colorize("my_image.jpg")
85
- ```
86
-
87
- ### Example 3: Download Result
88
-
89
- ```python
90
- import requests
91
-
92
- APP_CHECK_TOKEN = "your-app-check-token-here"
93
- API_BASE_URL = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
94
-
95
- def download_colorized_image(result_id, output_path):
96
- url = f"{API_BASE_URL}/download/{result_id}"
97
- headers = {"X-Firebase-AppCheck": APP_CHECK_TOKEN}
98
-
99
- response = requests.get(url, headers=headers)
100
-
101
- if response.status_code == 200:
102
- with open(output_path, "wb") as f:
103
- f.write(response.content)
104
- print(f"Image saved to: {output_path}")
105
- return True
106
- else:
107
- print(f"Download failed: {response.status_code}")
108
- return False
109
-
110
- # Usage
111
- result = colorize_image("input.jpg")
112
- if result:
113
- download_colorized_image(result["result_id"], "colorized_output.jpg")
114
- ```
115
-
116
- ---
117
-
118
- ## JavaScript/TypeScript Examples
119
-
120
- ### Example 1: Colorize Image with Fetch
121
-
122
- ```javascript
123
- const API_BASE_URL = 'https://logicgoinfotechspaces-text-guided-image-colorization.hf.space';
124
-
125
- async function colorizeImage(imageFile, appCheckToken) {
126
- const formData = new FormData();
127
- formData.append('file', imageFile);
128
-
129
- try {
130
- const response = await fetch(`${API_BASE_URL}/colorize`, {
131
- method: 'POST',
132
- headers: {
133
- 'X-Firebase-AppCheck': appCheckToken
134
- },
135
- body: formData
136
- });
137
-
138
- if (!response.ok) {
139
- const error = await response.json();
140
- throw new Error(error.detail || 'Colorization failed');
141
- }
142
-
143
- const result = await response.json();
144
- console.log('Colorized image URL:', result.download_url);
145
- return result;
146
- } catch (error) {
147
- console.error('Error:', error);
148
- throw error;
149
- }
150
- }
151
-
152
- // Usage
153
- const fileInput = document.getElementById('image-input');
154
- const file = fileInput.files[0];
155
-
156
- colorizeImage(file, appCheckToken)
157
- .then(result => {
158
- // Display the image
159
- const img = document.createElement('img');
160
- img.src = result.download_url;
161
- document.body.appendChild(img);
162
- })
163
- .catch(error => {
164
- console.error('Failed to colorize:', error);
165
- });
166
- ```
167
-
168
- ### Example 2: Complete Workflow with Firebase App Check
169
-
170
- ```javascript
171
- import { initializeApp } from "firebase/app";
172
- import { initializeAppCheck, ReCaptchaEnterpriseProvider } from "firebase/app-check";
173
-
174
- // Initialize Firebase
175
- const firebaseConfig = {
176
- apiKey: "AIzaSyBIB6rcfyyqy5niERTXWvVD714Ter4Vx68",
177
- authDomain: "colorize-662df.firebaseapp.com",
178
- projectId: "colorize-662df",
179
- storageBucket: "colorize-662df.firebasestorage.app",
180
- messagingSenderId: "69166278311",
181
- appId: "1:69166278311:web:0e8c50b8dd8627aaeadd82",
182
- measurementId: "G-58CC2J8XKX"
183
- };
184
-
185
- const app = initializeApp(firebaseConfig);
186
- const appCheck = initializeAppCheck(app, {
187
- provider: new ReCaptchaEnterpriseProvider('YOUR_RECAPTCHA_SITE_KEY'),
188
- isTokenAutoRefreshEnabled: true
189
- });
190
-
191
- // Get App Check token
192
- async function getAppCheckToken() {
193
- const { getToken } = await import('firebase/app-check');
194
- try {
195
- const token = await getToken(appCheck);
196
- return token.token;
197
- } catch (error) {
198
- console.error('Error getting App Check token:', error);
199
- return null;
200
- }
201
- }
202
-
203
- // Colorize image function
204
- async function colorizeImageWithAppCheck(imageFile) {
205
- const token = await getAppCheckToken();
206
-
207
- if (!token) {
208
- throw new Error('Failed to get App Check token');
209
- }
210
-
211
- const formData = new FormData();
212
- formData.append('file', imageFile);
213
-
214
- const response = await fetch(
215
- 'https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize',
216
- {
217
- method: 'POST',
218
- headers: {
219
- 'X-Firebase-AppCheck': token
220
- },
221
- body: formData
222
- }
223
- );
224
-
225
- if (!response.ok) {
226
- const error = await response.json();
227
- throw new Error(error.detail || 'Colorization failed');
228
- }
229
-
230
- return await response.json();
231
- }
232
-
233
- // Usage in HTML form
234
- document.getElementById('colorize-form').addEventListener('submit', async (e) => {
235
- e.preventDefault();
236
-
237
- const fileInput = document.getElementById('image-input');
238
- const file = fileInput.files[0];
239
-
240
- if (!file) {
241
- alert('Please select an image');
242
- return;
243
- }
244
-
245
- try {
246
- const result = await colorizeImageWithAppCheck(file);
247
-
248
- // Display result
249
- const resultImg = document.getElementById('result-image');
250
- resultImg.src = result.download_url;
251
- resultImg.style.display = 'block';
252
-
253
- console.log('Colorized image:', result.download_url);
254
- } catch (error) {
255
- console.error('Error:', error);
256
- alert('Failed to colorize image: ' + error.message);
257
- }
258
- });
259
- ```
260
-
261
- ### Example 3: React Component
262
-
263
- ```jsx
264
- import React, { useState } from 'react';
265
- import { getToken } from 'firebase/app-check';
266
-
267
- function ColorizeImage() {
268
- const [file, setFile] = useState(null);
269
- const [loading, setLoading] = useState(false);
270
- const [result, setResult] = useState(null);
271
- const [error, setError] = useState(null);
272
-
273
- const handleFileChange = (e) => {
274
- setFile(e.target.files[0]);
275
- setResult(null);
276
- setError(null);
277
- };
278
-
279
- const handleColorize = async () => {
280
- if (!file) {
281
- setError('Please select an image');
282
- return;
283
- }
284
-
285
- setLoading(true);
286
- setError(null);
287
-
288
- try {
289
- // Get App Check token
290
- const token = await getToken(appCheck);
291
-
292
- const formData = new FormData();
293
- formData.append('file', file);
294
-
295
- const response = await fetch(
296
- 'https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize',
297
- {
298
- method: 'POST',
299
- headers: {
300
- 'X-Firebase-AppCheck': token.token
301
- },
302
- body: formData
303
- }
304
- );
305
-
306
- if (!response.ok) {
307
- const errorData = await response.json();
308
- throw new Error(errorData.detail || 'Colorization failed');
309
- }
310
-
311
- const data = await response.json();
312
- setResult(data);
313
- } catch (err) {
314
- setError(err.message);
315
- } finally {
316
- setLoading(false);
317
- }
318
- };
319
-
320
- return (
321
- <div>
322
- <input type="file" accept="image/*" onChange={handleFileChange} />
323
- <button onClick={handleColorize} disabled={loading || !file}>
324
- {loading ? 'Colorizing...' : 'Colorize Image'}
325
- </button>
326
-
327
- {error && <div className="error">{error}</div>}
328
-
329
- {result && (
330
- <div>
331
- <h3>Colorized Image:</h3>
332
- <img src={result.download_url} alt="Colorized" />
333
- <a href={result.download_url} download>Download</a>
334
- </div>
335
- )}
336
- </div>
337
- );
338
- }
339
-
340
- export default ColorizeImage;
341
- ```
342
-
343
- ---
344
-
345
- ## cURL Examples
346
-
347
- ### Health Check
348
-
349
- ```bash
350
- curl https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/health
351
- ```
352
-
353
- ### Upload Image
354
-
355
- ```bash
356
- curl -X POST \
357
- https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/upload \
358
- -H "X-Firebase-AppCheck: YOUR_TOKEN" \
359
- -F "file=@image.jpg"
360
- ```
361
-
362
- ### Colorize Image
363
-
364
- ```bash
365
- curl -X POST \
366
- https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize \
367
- -H "X-Firebase-AppCheck: YOUR_TOKEN" \
368
- -F "file=@grayscale_image.jpg" \
369
- -o response.json
370
- ```
371
-
372
- ### Download Result
373
-
374
- ```bash
375
- # Get result ID from colorize response first
376
- RESULT_ID="550e8400-e29b-41d4-a716-446655440000"
377
-
378
- curl -X GET \
379
- https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/download/${RESULT_ID} \
380
- -H "X-Firebase-AppCheck: YOUR_TOKEN" \
381
- -o colorized_image.jpg
382
- ```
383
-
384
- ---
385
-
386
- ## Postman Collection
387
-
388
- ### Collection JSON
389
-
390
- ```json
391
- {
392
- "info": {
393
- "name": "Colorize API",
394
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
395
- },
396
- "item": [
397
- {
398
- "name": "Health Check",
399
- "request": {
400
- "method": "GET",
401
- "header": [],
402
- "url": {
403
- "raw": "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/health",
404
- "protocol": "https",
405
- "host": ["logicgoinfotechspaces-text-guided-image-colorization", "hf", "space"],
406
- "path": ["health"]
407
- }
408
- }
409
- },
410
- {
411
- "name": "Colorize Image",
412
- "request": {
413
- "method": "POST",
414
- "header": [
415
- {
416
- "key": "X-Firebase-AppCheck",
417
- "value": "{{app_check_token}}",
418
- "type": "text"
419
- }
420
- ],
421
- "body": {
422
- "mode": "formdata",
423
- "formdata": [
424
- {
425
- "key": "file",
426
- "type": "file",
427
- "src": []
428
- }
429
- ]
430
- },
431
- "url": {
432
- "raw": "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize",
433
- "protocol": "https",
434
- "host": ["logicgoinfotechspaces-text-guided-image-colorization", "hf", "space"],
435
- "path": ["colorize"]
436
- }
437
- }
438
- }
439
- ],
440
- "variable": [
441
- {
442
- "key": "app_check_token",
443
- "value": "your-token-here"
444
- }
445
- ]
446
- }
447
- ```
448
-
449
- ---
450
-
451
- ## Error Handling Examples
452
-
453
- ### Python
454
-
455
- ```python
456
- import requests
457
-
458
- def colorize_with_error_handling(image_path, token):
459
- url = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize"
460
- headers = {"X-Firebase-AppCheck": token}
461
-
462
- try:
463
- with open(image_path, "rb") as f:
464
- files = {"file": f}
465
- response = requests.post(url, headers=headers, files=files, timeout=120)
466
-
467
- if response.status_code == 200:
468
- return response.json()
469
- elif response.status_code == 401:
470
- raise Exception("Invalid or missing App Check token")
471
- elif response.status_code == 400:
472
- raise Exception("Invalid file or request")
473
- elif response.status_code == 503:
474
- raise Exception("Model not loaded, please try again later")
475
- else:
476
- error = response.json()
477
- raise Exception(f"Error {response.status_code}: {error.get('detail', 'Unknown error')}")
478
-
479
- except requests.exceptions.Timeout:
480
- raise Exception("Request timed out. Image processing may take 30-60 seconds.")
481
- except requests.exceptions.RequestException as e:
482
- raise Exception(f"Network error: {str(e)}")
483
- ```
484
-
485
- ### JavaScript
486
-
487
- ```javascript
488
- async function colorizeWithErrorHandling(imageFile, token) {
489
- try {
490
- const formData = new FormData();
491
- formData.append('file', imageFile);
492
-
493
- const response = await fetch(
494
- 'https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/colorize',
495
- {
496
- method: 'POST',
497
- headers: {
498
- 'X-Firebase-AppCheck': token
499
- },
500
- body: formData,
501
- signal: AbortSignal.timeout(120000) // 120 second timeout
502
- }
503
- );
504
-
505
- if (!response.ok) {
506
- const error = await response.json();
507
-
508
- switch (response.status) {
509
- case 401:
510
- throw new Error('Invalid or missing App Check token');
511
- case 400:
512
- throw new Error('Invalid file or request');
513
- case 503:
514
- throw new Error('Model not loaded, please try again later');
515
- default:
516
- throw new Error(error.detail || `Error ${response.status}: ${response.statusText}`);
517
- }
518
- }
519
-
520
- return await response.json();
521
- } catch (error) {
522
- if (error.name === 'AbortError') {
523
- throw new Error('Request timed out. Image processing may take 30-60 seconds.');
524
- }
525
- throw error;
526
- }
527
- }
528
- ```
529
-
530
- ---
531
-
532
- ## Best Practices
533
-
534
- 1. **Always check health endpoint first** before making requests
535
- 2. **Handle timeouts** - Processing can take 30-60 seconds on CPU
536
- 3. **Cache App Check tokens** - They auto-refresh, but cache them to avoid unnecessary requests
537
- 4. **Use public URLs** for displaying images (no auth needed)
538
- 5. **Handle errors gracefully** - Show user-friendly error messages
539
- 6. **Validate file types** before uploading
540
- 7. **Show loading indicators** during processing
541
-