| ================================================================================ | |
| QWEN IMAGE EDIT API DOCUMENTATION | |
| ================================================================================ | |
| API Name: Qwen Image Edit API (Hosted Inference) | |
| Description: FastAPI-based REST API for editing images using the Qwen/Qwen-Image-Edit model | |
| Version: 1.0 | |
| Base URL: https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space | |
| ================================================================================ | |
| OVERVIEW | |
| ================================================================================ | |
| This API allows you to upload images and edit them using text prompts. The API | |
| uses hosted inference via Hugging Face InferenceClient, which means the model | |
| runs on Hugging Face's infrastructure, not locally. | |
| Key Features: | |
| - Upload and edit images with text prompts | |
| - Supports multiple image formats (JPEG, PNG, WEBP, etc.) | |
| - Returns edited images in PNG format | |
| - Fast response times via hosted inference | |
| - No local GPU/memory requirements | |
| ================================================================================ | |
| AUTHENTICATION | |
| ================================================================================ | |
| This API uses two types of authentication: | |
| 1. Hugging Face Token (for private Spaces) | |
| 2. Firebase App Check (for API protection) | |
| -------------------------------------------------------------------------------- | |
| 1. HUGGING FACE TOKEN AUTHENTICATION | |
| -------------------------------------------------------------------------------- | |
| For private Spaces, you must include an Authorization header: | |
| Authorization: Bearer YOUR_HF_TOKEN | |
| If the Space is public, this header is optional. | |
| How to get your HF Token: | |
| 1. Go to https://huggingface.co/settings/tokens | |
| 2. Create a new token with "Read" permissions | |
| 3. Copy the token (starts with "hf_") | |
| Example: | |
| Authorization: Bearer hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | |
| -------------------------------------------------------------------------------- | |
| 2. FIREBASE APP CHECK AUTHENTICATION | |
| -------------------------------------------------------------------------------- | |
| Firebase App Check is enabled for this API to protect against abuse and ensure | |
| only authorized apps can access the endpoints. | |
| Required Header: | |
| X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN | |
| How to Get App Check Token: | |
| A. From Firebase Web App (JavaScript): | |
| import { initializeApp } from 'firebase/app'; | |
| import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check'; | |
| const app = initializeApp({ | |
| apiKey: "AIzaSyDXUV9lgYRZLN1lspwRDEWKfQHRwCn5JUE", | |
| authDomain: "nenobanana-77b32.firebaseapp.com", | |
| projectId: "nenobanana-77b32", | |
| // ... other config | |
| }); | |
| const appCheck = initializeAppCheck(app, { | |
| provider: new ReCaptchaV3Provider('YOUR_RECAPTCHA_SITE_KEY'), | |
| isTokenAutoRefreshEnabled: true | |
| }); | |
| // Get token | |
| const appCheckToken = await appCheck.getToken(true); | |
| console.log('Token:', appCheckToken.token); | |
| B. From Firebase Authentication (Email/Password): | |
| Use Firebase REST API to authenticate and get ID token: | |
| POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=YOUR_API_KEY | |
| Body: | |
| { | |
| "email": "[email protected]", | |
| "password": "password123", | |
| "returnSecureToken": true | |
| } | |
| Response includes: | |
| { | |
| "idToken": "...", // Use this as App Check token | |
| "refreshToken": "..." | |
| } | |
| Allowed Firebase App IDs: | |
| - 1:366958826869:web:22099143a1f24a9398af3c (Nano Banana Web App) | |
| If your App ID is not in the allowed list, contact the API administrator. | |
| Authentication Errors: | |
| - 401 Unauthorized: Missing or invalid App Check token | |
| - 403 Forbidden: App ID not in allowed list | |
| -------------------------------------------------------------------------------- | |
| COMPLETE AUTHENTICATION EXAMPLE | |
| -------------------------------------------------------------------------------- | |
| All API requests should include both headers: | |
| Authorization: Bearer YOUR_HF_TOKEN | |
| X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN | |
| Example (curl): | |
| curl -X GET "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/health" \ | |
| -H "Authorization: Bearer hf_xxxxxxxxxxxx" \ | |
| -H "X-Firebase-AppCheck: eyJhbGciOiJSUzI1NiIsImtpZCI6..." | |
| Example (Python): | |
| import requests | |
| headers = { | |
| "Authorization": "Bearer hf_xxxxxxxxxxxx", | |
| "X-Firebase-AppCheck": "eyJhbGciOiJSUzI1NiIsImtpZCI6..." | |
| } | |
| response = requests.get( | |
| "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/health", | |
| headers=headers | |
| ) | |
| print(response.json()) | |
| Example (JavaScript/Fetch): | |
| const response = await fetch( | |
| 'https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/health', | |
| { | |
| headers: { | |
| 'Authorization': `Bearer ${hfToken}`, | |
| 'X-Firebase-AppCheck': appCheckToken | |
| } | |
| } | |
| ); | |
| const data = await response.json(); | |
| ================================================================================ | |
| API ENDPOINTS | |
| ================================================================================ | |
| 1. ROOT ENDPOINT | |
| -------------------------------------------------------------------------------- | |
| GET / | |
| Description: Returns API status and welcome message | |
| Request: | |
| Method: GET | |
| URL: {base_url}/ | |
| Headers: None required | |
| Response: | |
| Status Code: 200 OK | |
| Content-Type: application/json | |
| Body: | |
| { | |
| "message": "Qwen Image Edit API (hosted inference) running." | |
| } | |
| Example (curl): | |
| curl -X GET "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/" | |
| Example (Python): | |
| import requests | |
| response = requests.get("https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/") | |
| print(response.json()) | |
| 2. HEALTH CHECK ENDPOINT | |
| -------------------------------------------------------------------------------- | |
| GET /health | |
| Description: Check API health and model availability status | |
| Request: | |
| Method: GET | |
| URL: {base_url}/health | |
| Headers: None required | |
| Response: | |
| Status Code: 200 OK | |
| Content-Type: application/json | |
| Body: | |
| { | |
| "status": "healthy", | |
| "proxy_mode": true, | |
| "model_loaded": true | |
| } | |
| Response Fields: | |
| - status: Always "healthy" if API is running | |
| - proxy_mode: Always true (indicates hosted inference mode) | |
| - model_loaded: true if InferenceClient is initialized, false otherwise | |
| Example (curl): | |
| curl -X GET "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/health" \ | |
| -H "Authorization: Bearer YOUR_HF_TOKEN" \ | |
| -H "X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN" | |
| Example (Python): | |
| import requests | |
| headers = { | |
| "Authorization": "Bearer YOUR_HF_TOKEN", | |
| "X-Firebase-AppCheck": "YOUR_APP_CHECK_TOKEN" | |
| } | |
| response = requests.get( | |
| "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/health", | |
| headers=headers | |
| ) | |
| print(response.json()) | |
| 3. EDIT IMAGE ENDPOINTS | |
| -------------------------------------------------------------------------------- | |
| The API provides three separate endpoints for different use cases: | |
| A. POST /edit/nanobanana - For nanobanana edits with default prompt | |
| B. POST /edit/descratch - For Descratch edits with default prompt | |
| C. POST /edit - For custom prompts (optional MongoDB logging) | |
| ================================================================================ | |
| A. POST /edit/nanobanana | |
| ================================================================================ | |
| Description: Edit an image using the default nanobanana prompt. Automatically | |
| saves to nanobanana MongoDB database. | |
| Request: | |
| Method: POST | |
| URL: {base_url}/edit/nanobanana | |
| Content-Type: multipart/form-data | |
| Headers: | |
| - Content-Type: multipart/form-data | |
| - Authorization: Bearer YOUR_HF_TOKEN (if Space is private) | |
| - X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN | |
| Body (form-data): | |
| - image: (file, required) Image file to edit | |
| (No prompt needed - uses default nanobanana prompt automatically) | |
| Default Prompt Used: | |
| "Using the provided photo of my parents, create a multi-stage creative setup. | |
| Show their grayscale 3D model displayed on a computer screen in the background. | |
| In the center, place a realistic 3D figurine of them in color, standing on a | |
| round base. To the side, include a colorful digital illustration of them printed | |
| on a poster or box. The scene should look like a modern studio environment, | |
| blending 3D modeling, realism, and stylized artwork in one frame" | |
| MongoDB: Automatically saves to "nanobanana" database | |
| ================================================================================ | |
| B. POST /edit/descratch | |
| ================================================================================ | |
| Description: Edit an image using the default Descratch prompt. Automatically | |
| saves to Descratch_logicgo MongoDB database. | |
| Request: | |
| Method: POST | |
| URL: {base_url}/edit/descratch | |
| Content-Type: multipart/form-data | |
| Headers: | |
| - Content-Type: multipart/form-data | |
| - Authorization: Bearer YOUR_HF_TOKEN (if Space is private) | |
| - X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN | |
| Body (form-data): | |
| - image: (file, required) Image file to edit | |
| (No prompt needed - uses default Descratch prompt automatically) | |
| Default Prompt Used: | |
| "Remove all scratches, dust, cracks, and surface imperfections from the image. | |
| Smoothly restore damaged areas with realistic texture and lighting while | |
| preserving original details, colors, and natural look" | |
| MongoDB: Automatically saves to "Descratch_logicgo" database | |
| ================================================================================ | |
| C. POST /edit | |
| ================================================================================ | |
| Description: Edit an image using a custom text prompt. Optionally saves to | |
| MongoDB if `db` parameter is provided. | |
| Request: | |
| Method: POST | |
| URL: {base_url}/edit | |
| Content-Type: multipart/form-data | |
| Headers: | |
| - Content-Type: multipart/form-data | |
| - Authorization: Bearer YOUR_HF_TOKEN (if Space is private) | |
| - X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN | |
| Body (form-data): | |
| - prompt: (string, required) Text description of the desired edit | |
| - image: (file, required) Image file to edit | |
| - db: (string, optional) Target database for logging: `"nanobanana"` or `"Descratch_logicgo"`. | |
| If not provided, request is not saved to MongoDB | |
| Supported Image Formats: | |
| - JPEG/JPG | |
| - PNG | |
| - WEBP | |
| - BMP | |
| - TIFF | |
| - Other formats supported by PIL/Pillow | |
| Response (Success): | |
| Status Code: 200 OK | |
| Content-Type: image/png | |
| Body: Binary image data (PNG format) | |
| Response (Error): | |
| Status Code: 400 Bad Request / 500 Internal Server Error | |
| Content-Type: application/json | |
| Body: | |
| { | |
| "error": "Error message description" | |
| } | |
| Error Codes: | |
| - 400: Bad Request (invalid image format, missing parameters) | |
| - 500: Internal Server Error (model not initialized, processing error) | |
| ================================================================================ | |
| EXAMPLES FOR ALL THREE ENDPOINTS | |
| ================================================================================ | |
| -------------------------------------------------------------------------------- | |
| A. Examples for /edit/nanobanana | |
| -------------------------------------------------------------------------------- | |
| Example (curl): | |
| curl -X POST "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/edit/nanobanana" \ | |
| -F "image=@/path/to/image.jpg" \ | |
| -H "Authorization: Bearer YOUR_HF_TOKEN" \ | |
| -H "X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN" \ | |
| -o edited_image.png | |
| Example (Python): | |
| import requests | |
| url = "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/edit/nanobanana" | |
| headers = { | |
| "Authorization": "Bearer YOUR_HF_TOKEN", | |
| "X-Firebase-AppCheck": "YOUR_APP_CHECK_TOKEN" | |
| } | |
| with open("image.jpg", "rb") as f: | |
| files = {"image": f} | |
| response = requests.post(url, files=files, headers=headers) | |
| if response.status_code == 200: | |
| with open("edited_image.png", "wb") as f: | |
| f.write(response.content) | |
| print("Image saved successfully!") | |
| else: | |
| print(f"Error: {response.json()}") | |
| -------------------------------------------------------------------------------- | |
| B. Examples for /edit/descratch | |
| -------------------------------------------------------------------------------- | |
| Example (curl): | |
| curl -X POST "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/edit/descratch" \ | |
| -F "image=@/path/to/image.jpg" \ | |
| -H "Authorization: Bearer YOUR_HF_TOKEN" \ | |
| -H "X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN" \ | |
| -o edited_image.png | |
| Example (Python): | |
| import requests | |
| url = "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/edit/descratch" | |
| headers = { | |
| "Authorization": "Bearer YOUR_HF_TOKEN", | |
| "X-Firebase-AppCheck": "YOUR_APP_CHECK_TOKEN" | |
| } | |
| with open("image.jpg", "rb") as f: | |
| files = {"image": f} | |
| response = requests.post(url, files=files, headers=headers) | |
| if response.status_code == 200: | |
| with open("edited_image.png", "wb") as f: | |
| f.write(response.content) | |
| print("Image saved successfully!") | |
| else: | |
| print(f"Error: {response.json()}") | |
| -------------------------------------------------------------------------------- | |
| C. Examples for /edit (custom prompt) | |
| -------------------------------------------------------------------------------- | |
| Example (curl): | |
| curl -X POST "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/edit" \ | |
| -F "prompt=make the background blue" \ | |
| -F "image=@/path/to/image.jpg" \ | |
| -F "db=nanobanana" \ | |
| -H "Authorization: Bearer YOUR_HF_TOKEN" \ | |
| -H "X-Firebase-AppCheck: YOUR_APP_CHECK_TOKEN" \ | |
| -o edited_image.png | |
| Example (Python): | |
| import requests | |
| url = "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/edit" | |
| headers = { | |
| "Authorization": "Bearer YOUR_HF_TOKEN", | |
| "X-Firebase-AppCheck": "YOUR_APP_CHECK_TOKEN" | |
| } | |
| with open("image.jpg", "rb") as f: | |
| files = {"image": f} | |
| data = { | |
| "prompt": "make the background blue", | |
| "db": "nanobanana" # Optional: "nanobanana" or "Descratch_logicgo" | |
| } | |
| response = requests.post(url, files=files, data=data, headers=headers) | |
| if response.status_code == 200: | |
| with open("edited_image.png", "wb") as f: | |
| f.write(response.content) | |
| print("Image saved successfully!") | |
| else: | |
| print(f"Error: {response.json()}") | |
| Example (JavaScript/Node.js): | |
| const FormData = require('form-data'); | |
| const fs = require('fs'); | |
| const axios = require('axios'); | |
| const form = new FormData(); | |
| form.append('prompt', 'make the background blue'); | |
| form.append('image', fs.createReadStream('image.jpg')); | |
| form.append('db', 'nanobanana'); // Optional | |
| axios.post('https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/edit', form, { | |
| headers: { | |
| ...form.getHeaders(), | |
| 'Authorization': 'Bearer YOUR_HF_TOKEN', | |
| 'X-Firebase-AppCheck': 'YOUR_APP_CHECK_TOKEN' | |
| }, | |
| responseType: 'arraybuffer' | |
| }) | |
| .then(response => { | |
| fs.writeFileSync('edited_image.png', response.data); | |
| console.log('Image saved successfully!'); | |
| }) | |
| .catch(error => { | |
| console.error('Error:', error.response?.data || error.message); | |
| }); | |
| 4. MONGODB DIAGNOSTIC ENDPOINT | |
| -------------------------------------------------------------------------------- | |
| POST /test-mongodb | |
| Description: Inserts a lightweight test document into the selected MongoDB database to verify connectivity. | |
| Request: | |
| Method: POST | |
| URL: {base_url}/test-mongodb | |
| Content-Type: multipart/form-data or application/x-www-form-urlencoded | |
| Headers: | |
| - Authorization: Bearer YOUR_HF_TOKEN (if Space is private) | |
| Body: | |
| - db: (string, required) `"nanobanana"` or `"Descratch_logicgo"` | |
| Response (Success): | |
| Status Code: 200 OK | |
| Content-Type: application/json | |
| Body: | |
| { | |
| "status": "success", | |
| "message": "Test document saved to nanobanana", | |
| "task_id": "uuid-string", | |
| "connection": "OK" | |
| } | |
| Response (Error): | |
| Status Code: 500 Internal Server Error | |
| Body includes `error` field with details. | |
| Example (curl): | |
| curl -X POST "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/test-mongodb" \ | |
| -F "db=nanobanana" \ | |
| -H "Authorization: Bearer YOUR_HF_TOKEN" | |
| ================================================================================ | |
| SUPPORTED IMAGE FORMATS | |
| ================================================================================ | |
| Input Formats (Accepted): | |
| - JPEG / JPG | |
| - PNG | |
| - WEBP | |
| - BMP | |
| - TIFF | |
| - GIF (static frames) | |
| - Other formats supported by PIL/Pillow library | |
| Output Format: | |
| - PNG (always returned as PNG regardless of input format) | |
| Image Validation: | |
| The API validates: | |
| 1. Content-Type header must start with "image/" | |
| 2. File must be a valid, readable image file | |
| 3. Image must pass PIL/Pillow verification | |
| Default Prompts by Database (`db` parameter): | |
| - nanobanana: | |
| "Using the provided photo of my parents, create a multi-stage creative setup. Show their grayscale 3D model displayed on a computer screen in the background. In the center, place a realistic 3D figurine of them in color, standing on a round base. To the side, include a colorful digital illustration of them printed on a poster or box. The scene should look like a modern studio environment, blending 3D modeling, realism, and stylized artwork in one frame" | |
| - Descratch_logicgo: | |
| "Remove all scratches, dust, cracks, and surface imperfections from the image. Smoothly restore damaged areas with realistic texture and lighting while preserving original details, colors, and natural look" | |
| ================================================================================ | |
| ERROR HANDLING | |
| ================================================================================ | |
| The API returns standard HTTP status codes: | |
| 200 OK | |
| - Request successful | |
| - Response contains the edited image (PNG format) | |
| 400 Bad Request | |
| - Invalid image format | |
| - Missing required parameters (prompt or image) | |
| - Image file cannot be opened/verified | |
| Example response: | |
| { | |
| "error": "Invalid image format. Supported: JPEG, PNG, WEBP, etc. Error: ..." | |
| } | |
| 500 Internal Server Error | |
| - InferenceClient not initialized | |
| - Model processing error | |
| - Unexpected provider response | |
| Example response: | |
| { | |
| "error": "Inference client not initialized" | |
| } | |
| ================================================================================ | |
| ENVIRONMENT VARIABLES | |
| ================================================================================ | |
| The API uses the following environment variables (configured in Hugging Face Space Secrets): | |
| HF_TOKEN | |
| - Your Hugging Face API token | |
| - Required for accessing gated models or private resources | |
| - Set in Space Settings > Secrets | |
| QWEN_MODEL_ID | |
| - Model identifier (default: "Qwen/Qwen-Image-Edit") | |
| - Can be overridden to use a different model | |
| QWEN_PROVIDER | |
| - Inference provider (default: "fal-ai") | |
| - Options: "fal-ai", "auto", or other supported providers | |
| - Determines which hosted inference service to use | |
| FIREBASE_APP_CHECK_ENABLED | |
| - Set to `1` to enforce Firebase App Check verification. | |
| FIREBASE_ALLOWED_APP_IDS | |
| - Comma-separated list of allowed Firebase App IDs (e.g. `1:12345:android:abcd,1:67890:web:efgh`). | |
| FIREBASE_SERVICE_ACCOUNT_JSON / FIREBASE_SERVICE_ACCOUNT_PATH | |
| - Service account credentials used to verify App Check tokens. | |
| - Provide either the raw JSON via `FIREBASE_SERVICE_ACCOUNT_JSON` (recommended for Spaces Secrets) | |
| or a path via `FIREBASE_SERVICE_ACCOUNT_PATH`. | |
| ================================================================================ | |
| RATE LIMITS | |
| ================================================================================ | |
| Rate limits depend on: | |
| - Your Hugging Face account tier | |
| - The inference provider being used | |
| - Space resource allocation | |
| For production use, consider: | |
| - Implementing request queuing | |
| - Adding retry logic with exponential backoff | |
| - Monitoring API response times | |
| ================================================================================ | |
| BEST PRACTICES | |
| ================================================================================ | |
| 1. Image Size: | |
| - Recommended: Images under 10MB for faster processing | |
| - Very large images may timeout or cause memory issues | |
| 2. Prompts: | |
| - Be specific and clear in your edit instructions | |
| - Example: "make the sky more blue" instead of "change sky" | |
| - Example: "remove the person in the background" instead of "edit image" | |
| 3. Error Handling: | |
| - Always check response status codes | |
| - Implement retry logic for transient failures | |
| - Handle timeout errors gracefully | |
| 4. Authentication: | |
| - Store HF_TOKEN securely (environment variables, secrets) | |
| - Never commit tokens to version control | |
| - Rotate tokens periodically | |
| 5. Performance: | |
| - Use appropriate timeout values (suggested: 120 seconds) | |
| - Implement caching for repeated requests | |
| - Consider async processing for batch operations | |
| ================================================================================ | |
| TESTING | |
| ================================================================================ | |
| Quick Test (curl): | |
| # Health check | |
| curl https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/health | |
| # Edit image | |
| curl -X POST "https://logicgoinfotechspaces-nano-banana-experimental-2.hf.space/edit" \ | |
| -F "prompt=make the background blue" \ | |
| -F "image=@test_image.jpg" \ | |
| -o result.png | |
| Python Test Script: | |
| See test.py in the repository for a complete testing example. | |
| ================================================================================ | |
| ADDITIONAL RESOURCES | |
| ================================================================================ | |
| - Hugging Face Spaces: https://huggingface.co/spaces | |
| - FastAPI Documentation: https://fastapi.tiangolo.com/ | |
| - Qwen Model Card: https://huggingface.co/Qwen/Qwen-Image-Edit | |
| - Hugging Face Inference API: https://huggingface.co/docs/api-inference | |
| ================================================================================ | |
| CHANGELOG | |
| ================================================================================ | |
| Version 1.0 (Current) | |
| - Initial release | |
| - Hosted inference via InferenceClient | |
| - Support for multiple image formats | |
| - Image format validation | |
| - Health check endpoint | |
| ================================================================================ | |
| SUPPORT | |
| ================================================================================ | |
| For issues or questions: | |
| - Check the Space logs on Hugging Face | |
| - Review error messages in API responses | |
| - Ensure HF_TOKEN is set correctly in Space Secrets | |
| - Verify image format is supported | |
| ================================================================================ | |
| END OF DOCUMENTATION | |
| ================================================================================ | |