=============== LIBRARY RULES =============== From library maintainers: - Use multipart/form-data for image file uploads or base64 JSON endpoints - Authentication via Ocp-Apim-Subscription-Key header - Background removal returns transparent PNG - Upscale provides 4x resolution increase - Face restoration enhances facial details in photos ### Migration from remove.bg / Photoroom Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt Example demonstrating how to migrate from remove.bg to the Brainiall Image API for background removal. ```APIDOC ## POST /v1/image/remove-background (Migration Example) ### Description This example shows how to replace a `remove.bg` API call with a Brainiall Image API call for background removal. ### Method POST ### Endpoint /v1/image/remove-background ### Headers - **Authorization** (string) - Required - Bearer token for authentication (e.g., "Bearer YOUR_KEY"). ### Files - **file** (file) - Required - The image file to process (e.g., photo.jpg). ### Request Example ```python import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/remove-background", headers={"Authorization": "Bearer YOUR_KEY"}, files={"file": open("photo.jpg", "rb")}, ) response.raise_for_status() with open("result.png", "wb") as f: f.write(response.content) print("Background removed and saved to result.png") ``` ### Response #### Success Response (200) - **binary** - The processed PNG image content. ``` -------------------------------- ### Upscale Image with curl Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md This command-line example uses curl to upscale an image by 4x using multipart upload. The output is saved to 'upscaled_4x.png'. ```bash curl -X POST https://apim-ai-apis.azure-api.net/v1/image/upscale \ -H "Authorization: Bearer YOUR_KEY" \ -F "file=@small_image.jpg" \ -o upscaled_4x.png ``` -------------------------------- ### Python: Complete Image Processing Pipeline Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Demonstrates a sequential image processing pipeline: removing the background, upscaling the result, and restoring faces. Ensure you have the 'requests' library installed. ```python import requests import base64 from pathlib import Path BASE_URL = "https://apim-ai-apis.azure-api.net/v1/image" HEADERS = {"Authorization": "Bearer YOUR_KEY"} def remove_bg(input_path, output_path): """Remove background from image.""" with open(input_path, "rb") as f: resp = requests.post(f"{BASE_URL}/remove-background", headers=HEADERS, files={"file": f}) resp.raise_for_status() with open(output_path, "wb") as f: f.write(resp.content) print(f"Background removed: {output_path}") def upscale(input_path, output_path): """Upscale image 4x.""" with open(input_path, "rb") as f: resp = requests.post(f"{BASE_URL}/upscale", headers=HEADERS, files={"file": f}) resp.raise_for_status() with open(output_path, "wb") as f: f.write(resp.content) print(f"Upscaled 4x: {output_path}") def restore(input_path, output_path): """Restore faces in image.""" with open(input_path, "rb") as f: resp = requests.post(f"{BASE_URL}/restore-face", headers=HEADERS, files={"file": f}) resp.raise_for_status() with open(output_path, "wb") as f: f.write(resp.content) print(f"Face restored: {output_path}") # Full pipeline: remove bg -> upscale -> restore face remove_bg("portrait.jpg", "step1_nobg.png") upscale("step1_nobg.png", "step2_upscaled.png") restore("portrait.jpg", "step3_restored.png") ``` -------------------------------- ### Curl: Background Removal (Multipart and Base64) Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt Provides command-line examples using curl for background removal, demonstrating both multipart file upload and base64 JSON input methods. ```bash # curl — multipart curl -X POST https://apim-ai-apis.azure-api.net/v1/image/remove-background \ -H "Authorization: Bearer YOUR_KEY" \ -F "file=@photo.jpg" \ -o result_nobg.png ``` ```bash # curl — base64 B64=$(base64 -i photo.jpg) curl -s -X POST https://apim-ai-apis.azure-api.net/v1/image/remove-background/base64 \ -H "Authorization: Bearer YOUR_KEY" \ -H "Content-Type: application/json" \ -d "{\"image\": \"$B64\"}" | python3 -c " import json,sys,base64 d=json.load(sys.stdin) open('result_nobg.png','wb').write(base64.b64decode(d['image'])) print('Saved result_nobg.png') " ``` -------------------------------- ### Restore Face using curl Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md A command-line interface example using curl to restore faces via multipart upload. This is useful for quick testing or scripting. ```bash curl -X POST https://apim-ai-apis.azure-api.net/v1/image/restore-face \ -H "Authorization: Bearer YOUR_KEY" \ -F "file=@blurry_face.jpg" \ -o restored_face.png ``` -------------------------------- ### Python: 4x Image Upscaling (Multipart) Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt Shows how to upscale an image by 4x using the Real-ESRGAN model via multipart file upload in Python. Ensure the 'requests' library is installed. ```python import requests import base64 BASE_URL = "https://apim-ai-apis.azure-api.net/v1/image" HEADERS = {"Authorization": "Bearer YOUR_KEY"} # --- Multipart upload --- with open("small.jpg", "rb") as f: resp = requests.post(f"{BASE_URL}/upscale", headers=HEADERS, files={"file": f}, timeout=60) resp.raise_for_status() with open("upscaled_4x.png", "wb") as f: f.write(resp.content) print(f"Saved upscaled_4x.png ({len(resp.content)} bytes)") ``` -------------------------------- ### GET /health Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Checks the service health, including GPU status and loaded models. ```APIDOC ## GET /health ### Description Service health check with GPU status and model information. ### Method GET ### Endpoint https://apim-ai-apis.azure-api.net/v1/image/health ### Response #### Success Response (200) - **status** (string) - The health status of the service (e.g., "healthy"). - **gpu** (object) - Information about the GPU. - **name** (string) - The name of the GPU. - **vram_total_mb** (integer) - Total VRAM in MB. - **vram_used_mb** (integer) - Used VRAM in MB. - **vram_free_mb** (integer) - Free VRAM in MB. - **models** (object) - Status of loaded deep learning models. - **birefnet** (string) - Status of BiRefNet model (e.g., "loaded"). - **realesrgan** (string) - Status of Real-ESRGAN model (e.g., "loaded"). - **gfpgan** (string) - Status of GFPGAN model (e.g., "loaded"). ### Request Example ```bash curl -s https://apim-ai-apis.azure-api.net/v1/image/health \ -H "Authorization: Bearer YOUR_KEY" ``` ### Response Example ```json { "status": "healthy", "gpu": { "name": "NVIDIA A10", "vram_total_mb": 24576, "vram_used_mb": 1422, "vram_free_mb": 23154 }, "models": { "birefnet": "loaded", "realesrgan": "loaded", "gfpgan": "loaded" } } ``` ``` -------------------------------- ### Restore Face using Base64 Input (JavaScript) Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md This JavaScript example shows how to restore faces using Base64 encoded image data. It utilizes the 'fs' module for file operations and 'fetch' for API requests. ```javascript import fs from "fs"; const imageBuffer = fs.readFileSync("blurry_face.jpg"); const imageB64 = imageBuffer.toString("base64"); const response = await fetch( "https://apim-ai-apis.azure-api.net/v1/image/restore-face/base64", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer YOUR_KEY", }, body: JSON.stringify({ image: imageB64 }), } ); const result = await response.json(); const outputBuffer = Buffer.from(result.image, "base64"); fs.writeFileSync("restored_face.png", outputBuffer); console.log("Face restored!"); ``` -------------------------------- ### Python: Background Removal (Multipart and Base64) Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt Shows how to remove backgrounds from images using the BiRefNet model via both multipart file upload and base64 JSON encoding in Python. Ensure the 'requests' library is installed. ```python import requests import base64 BASE_URL = "https://apim-ai-apis.azure-api.net/v1/image" HEADERS = {"Authorization": "Bearer YOUR_KEY"} # --- Multipart upload --- with open("photo.jpg", "rb") as f: resp = requests.post(f"{BASE_URL}/remove-background", headers=HEADERS, files={"file": f}, timeout=30) resp.raise_for_status() with open("result_nobg.png", "wb") as f: f.write(resp.content) print(f"Saved result_nobg.png ({len(resp.content)} bytes)") # --- Base64 JSON --- with open("photo.jpg", "rb") as f: b64 = base64.b64encode(f.read()).decode() resp = requests.post( f"{BASE_URL}/remove-background/base64", headers={**HEADERS, "Content-Type": "application/json"}, json={"image": b64}, timeout=30, ) resp.raise_for_status() result = resp.json() with open("result_nobg_b64.png", "wb") as f: f.write(base64.b64decode(result["image"])) print("Saved result_nobg_b64.png") ``` -------------------------------- ### MCP Server Configuration for Brainiall Image API Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt Configuration for using the Brainiall Image API as an MCP server. This allows direct tool use from compatible AI clients. The first example shows a standard configuration, while the second provides an Apify-hosted variant. ```json { "mcpServers": { "brainiall-image": { "url": "https://apim-ai-apis.azure-api.net/mcp/image/mcp", "headers": { "Accept": "application/json, text/event-stream" } } } } ``` ```json { "mcpServers": { "brainiall-image-apify": { "url": "https://n3nr6htYhIkL7dOhK.apify.actor/mcp?token=YOUR_APIFY_TOKEN" } } } ``` -------------------------------- ### Remove Background with curl Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md This command-line example uses curl to remove an image background via multipart upload. The output is redirected to a file named 'result.png'. ```bash curl -X POST https://apim-ai-apis.azure-api.net/v1/image/remove-background \ -H "Authorization: Bearer YOUR_KEY" \ -F "file=@photo.jpg" \ -o result.png echo "Background removed! Saved to result.png" ``` -------------------------------- ### curl: Image Operations and Health Check Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Demonstrates various image operations using curl, including background removal (multipart and base64), upscaling, and face restoration. Also includes a health check example. Requires API key and image files for testing. ```bash BASE="https://apim-ai-apis.azure-api.net/v1/image" KEY="YOUR_KEY" # Remove background (multipart) curl -X POST "$BASE/remove-background" \ -H "Authorization: Bearer $KEY" \ -F "file=@photo.jpg" \ -o nobg.png # Remove background (base64) B64=$(base64 -i photo.jpg) curl -X POST "$BASE/remove-background/base64" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $KEY" \ -d "{\"image\": \"$B64\"}" | python3 -c " import json, sys, base64 data = json.load(sys.stdin) with open('nobg_b64.png', 'wb') as f: f.write(base64.b64decode(data['image'])) print('Saved nobg_b64.png') " # Upscale 4x curl -X POST "$BASE/upscale" \ -H "Authorization: Bearer $KEY" \ -F "file=@small.jpg" \ -o upscaled.png # Restore face curl -X POST "$BASE/restore-face" \ -H "Authorization: Bearer $KEY" \ -F "file=@blurry.jpg" \ -o restored.png # Health check curl -s "$BASE/health" \ -H "Authorization: Bearer $KEY" | python3 -m json.tool ``` -------------------------------- ### Remove Background with Multipart Upload (JavaScript) Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md A JavaScript example for removing image backgrounds using multipart form data. This requires Node.js environment with 'fs' module and 'fetch' API support. The processed image is saved to a file. ```javascript import fs from "fs"; const formData = new FormData(); formData.append("file", new Blob([fs.readFileSync("photo.jpg")])) const response = await fetch( "https://apim-ai-apis.azure-api.net/v1/image/remove-background", { method: "POST", headers: { Authorization: "Bearer YOUR_KEY" }, body: formData, } ); const buffer = await response.arrayBuffer(); fs.writeFileSync("result.png", Buffer.from(buffer)); console.log("Background removed!"); ``` -------------------------------- ### Python: Migrating from Photoroom to Brainll API Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Illustrates migrating from Photoroom to the Brainll API for background removal, emphasizing Brainll's lower cost and simpler REST API implementation compared to Photoroom's SDK. ```python # Before: Photoroom ($0.02/image) # Requires SDK installation and complex setup # After: Brainiall ($0.005/image — 4x cheaper) import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/remove-background", headers={"Authorization": "Bearer YOUR_KEY"}, files={"file": open("photo.jpg", "rb")} ) # Simple REST API, no SDK needed ``` -------------------------------- ### Python: LangChain Agent with Image Tools Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Demonstrates how to use LangChain with BrainiAll image tools for background removal, image upscaling, and face restoration. ```APIDOC ## Python: LangChain Agent with Image Tools This section provides Python code examples for integrating with the BrainiAll Image API using LangChain. ### Tools Available: - **remove_background(image_url: str) -> str**: Removes the background from an image at the given URL. Returns base64 PNG. - **upscale_image(image_url: str) -> str**: Upscales an image 4x from the given URL. Returns base64 PNG. - **restore_face(image_url: str) -> str**: Restores and enhances faces in an image from the given URL. ### Example Usage: ```python from langchain_core.tools import tool from langchain_brainiall import ChatBrainiall from langgraph.prebuilt import create_react_agent import requests import base64 IMAGE_API = "https://apim-ai-apis.azure-api.net/v1/image" API_KEY = "YOUR_KEY" @tool def remove_background(image_url: str) -> str: """Remove background from an image at the given URL. Returns base64 PNG.""" image_data = requests.get(image_url).content b64 = base64.b64encode(image_data).decode() resp = requests.post( f"{IMAGE_API}/remove-background/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) return f"Background removed. Result size: {len(resp.json()['image'])} chars base64" @tool def upscale_image(image_url: str) -> str: """Upscale an image 4x from the given URL. Returns base64 PNG.""" image_data = requests.get(image_url).content b64 = base64.b64encode(image_data).decode() resp = requests.post( f"{IMAGE_API}/upscale/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) return f"Image upscaled 4x. Result size: {len(resp.json()['image'])} chars base64" @tool def restore_face(image_url: str) -> str: """Restore and enhance faces in an image from the given URL.""" image_data = requests.get(image_url).content b64 = base64.b64encode(image_data).decode() resp = requests.post( f"{IMAGE_API}/restore-face/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) return f"Face restored. Result size: {len(resp.json()['image'])} chars base64" llm = ChatBrainiall(model="claude-sonnet-4-6") agent = create_react_agent(llm, [remove_background, upscale_image, restore_face]) result = agent.invoke({ "messages": [("human", "Remove the background from this product photo: https://example.com/product.jpg")] }) ``` ``` -------------------------------- ### Python: Async Processing with httpx Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Demonstrates how to use the httpx library for asynchronous image processing operations like removing backgrounds, upscaling, and restoring faces. ```APIDOC ## POST /v1/image/remove-background/base64 ### Description Removes the background from an image provided as base64 encoded string. ### Method POST ### Endpoint https://apim-ai-apis.azure-api.net/v1/image/remove-background/base64 ### Parameters #### Request Body - **image** (string) - Required - Base64 encoded image string. ### Request Example ```json { "image": "base64_encoded_image_string" } ``` ### Response #### Success Response (200) - **image** (string) - Base64 encoded image string with background removed. #### Response Example ```json { "image": "base64_encoded_result_image_string" } ``` ## POST /v1/image/upscale/base64 ### Description Upscales an image provided as a base64 encoded string by 4x. ### Method POST ### Endpoint https://apim-ai-apis.azure-net/v1/image/upscale/base64 ### Parameters #### Request Body - **image** (string) - Required - Base64 encoded image string. ### Request Example ```json { "image": "base64_encoded_image_string" } ``` ### Response #### Success Response (200) - **image** (string) - Base64 encoded upscaled image string. #### Response Example ```json { "image": "base64_encoded_upscaled_image_string" } ``` ## POST /v1/image/restore-face/base64 ### Description Restores faces in an image provided as a base64 encoded string. ### Method POST ### Endpoint https://apim-ai-apis.azure-net/v1/image/restore-face/base64 ### Parameters #### Request Body - **image** (string) - Required - Base64 encoded image string. ### Request Example ```json { "image": "base64_encoded_image_string" } ``` ### Response #### Success Response (200) - **image** (string) - Base64 encoded image string with faces restored. #### Response Example ```json { "image": "base64_encoded_restored_image_string" } ``` ``` -------------------------------- ### Python: Migrating from remove.bg to Brainll API Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Compares the API calls for background removal between remove.bg and the Brainll API. Highlights Brainll's cost savings and simpler REST API approach. ```python # Before: remove.bg ($0.195/image) import requests response = requests.post( "https://api.remove.bg/v1.0/removebg", files={"image_file": open("photo.jpg", "rb")}, data={"size": "auto"}, headers={"X-Api-Key": "REMOVEBG_KEY"}, ) # After: Brainiall ($0.005/image — 39x cheaper) response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/remove-background", headers={"Authorization": "Bearer YOUR_KEY"}, files={"file": open("photo.jpg", "rb")} ) ``` -------------------------------- ### Remove Background with Multipart Upload (Python) Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md Use this snippet to remove the background from an image using multipart upload. Ensure you have the 'requests' library installed. The processed image is saved as a PNG file. ```python import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/remove-background", headers={"Authorization": "Bearer YOUR_KEY"}, files={"file": open("photo.jpg", "rb")} ) with open("result.png", "wb") as f: f.write(response.content) print("Background removed! Saved to result.png") ``` -------------------------------- ### Authentication Methods for Brainiall Image API Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt Demonstrates the three supported methods for authenticating API requests: Bearer Token, API Key header, and Azure subscription key. ```bash # Bearer Token curl -H "Authorization: Bearer YOUR_KEY" ... ``` ```bash # API Key header curl -H "api-key: YOUR_KEY" ... ``` ```bash # Azure subscription key curl -H "Ocp-Apim-Subscription-Key: YOUR_KEY" ... ``` -------------------------------- ### Python: LangChain Agent with Image Tools Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Integrates image processing tools into a LangChain agent. Requires API key and specific libraries. Use for programmatic image manipulation within a LangChain workflow. ```python from langchain_core.tools import tool from langchain_brainiall import ChatBrainiall from langgraph.prebuilt import create_react_agent import requests import base64 IMAGE_API = "https://apim-ai-apis.azure-api.net/v1/image" API_KEY = "YOUR_KEY" @tool def remove_background(image_url: str) -> str: """Remove background from an image at the given URL. Returns base64 PNG.""" image_data = requests.get(image_url).content b64 = base64.b64encode(image_data).decode() resp = requests.post( f"{IMAGE_API}/remove-background/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) return f"Background removed. Result size: {len(resp.json()['image'])} chars base64" @tool def upscale_image(image_url: str) -> str: """Upscale an image 4x from the given URL. Returns base64 PNG.""" image_data = requests.get(image_url).content b64 = base64.b64encode(image_data).decode() resp = requests.post( f"{IMAGE_API}/upscale/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) return f"Image upscaled 4x. Result size: {len(resp.json()['image'])} chars base64" @tool def restore_face(image_url: str) -> str: """Restore and enhance faces in an image from the given URL.""" image_data = requests.get(image_url).content b64 = base64.b64encode(image_data).decode() resp = requests.post( f"{IMAGE_API}/restore-face/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) return f"Face restored. Result size: {len(resp.json()['image'])} chars base64" llm = ChatBrainiall(model="claude-sonnet-4-6") agent = create_react_agent(llm, [remove_background, upscale_image, restore_face]) result = agent.invoke({ "messages": [("human", "Remove the background from this product photo: https://example.com/product.jpg")] }) ``` -------------------------------- ### Migrate from remove.bg to Brainiall Image API Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt This Python snippet demonstrates migrating from the remove.bg API to the Brainiall Image API for background removal. It highlights the cost savings and changes in request structure and authentication. Requires the requests library. ```python import requests # BEFORE: remove.bg ($0.195/image) # response = requests.post( # "https://api.remove.bg/v1.0/removebg", # files={"image_file": open("photo.jpg", "rb")}, # data={"size": "auto"}, # headers={"X-Api-Key": "REMOVEBG_KEY"}, # ) # AFTER: Brainiall ($0.005/image — 39× cheaper) response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/remove-background", headers={"Authorization": "Bearer YOUR_KEY"}, files={"file": open("photo.jpg", "rb")}, ) response.raise_for_status() with open("result.png", "wb") as f: f.write(response.content) print("Background removed and saved to result.png") ``` -------------------------------- ### Restore Face using Base64 Input (Python) Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md This Python snippet demonstrates how to restore faces by sending the image as a Base64 encoded string. It requires the 'base64' library for encoding and decoding. ```python import requests import base64 with open("blurry_face.jpg", "rb") as f: image_b64 = base64.b64encode(f.read()).decode() response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/restore-face/base64", headers={ "Authorization": "Bearer YOUR_KEY", "Content-Type": "application/json" }, json={"image": image_b64} ) result = response.json() output_bytes = base64.b64decode(result["image"]) with open("restored_face.png", "wb") as f: f.write(output_bytes) print("Face restored!") ``` -------------------------------- ### MCP Server Configuration Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md Configuration for using Brainiall Image via MCP clients like Claude Desktop and Cursor. ```APIDOC ## MCP Server Configuration Use Brainiall Image via MCP (Model Context Protocol) in Claude Desktop, Cursor, or any MCP client. ### Claude Desktop / Cursor ```json { "mcpServers": { "brainiall-image": { "url": "https://apim-ai-apis.azure-api.net/mcp/image/mcp", "headers": { "Accept": "application/json, text/event-stream" } } } } ``` ### Available MCP Tools | Tool | Description | |------|-------------| | `remove_background` | Remove background from image (BiRefNet) | | `upscale_image` | Upscale image 4x (Real-ESRGAN) | | `restore_face` | Restore and enhance faces (GFPGAN) | | `check_image_service` | Health check with GPU status | ### Apify MCP ```json { "mcpServers": { "brainiall-image-apify": { "url": "https://n3nr6htYhIkL7dOhK.apify.actor/mcp?token=YOUR_APIFY_TOKEN" } } } ``` ``` -------------------------------- ### Full Image Processing Pipeline Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt Use this to chain multiple image operations sequentially, such as background removal, upscaling, and face restoration. It requires a single input image and an output directory. ```python import requests from pathlib import Path BASE_URL = "https://apim-ai-apis.azure-api.net/v1/image" HEADERS = {"Authorization": "Bearer YOUR_KEY"} def _post(endpoint: str, path: str) -> bytes: with open(path, "rb") as f: resp = requests.post(f"{BASE_URL}/{endpoint}", headers=HEADERS, files={"file": f}, timeout=60) resp.raise_for_status() return resp.content def full_pipeline(input_path: str, output_dir: str) -> dict: """Remove background → upscale 4× → restore faces.""" out = Path(output_dir) out.mkdir(exist_ok=True) stem = Path(input_path).stem nobg_path = out / f"{stem}_nobg.png" upscaled_path = out / f"{stem}_upscaled.png" restored_path = out / f"{stem}_restored.png" nobg_path.write_bytes(_post("remove-background", input_path)) print(f"Step 1: background removed → {nobg_path}") upscaled_path.write_bytes(_post("upscale", str(nobg_path))) print(f"Step 2: upscaled 4× → {upscaled_path}") restored_path.write_bytes(_post("restore-face", input_path)) print(f"Step 3: face restored → {restored_path}") return { "no_background": str(nobg_path), "high_resolution": str(upscaled_path), "face_restored": str(restored_path), } result = full_pipeline("portrait.jpg", "output/") print(result) # {'no_background': 'output/portrait_nobg.png', # 'high_resolution': 'output/portrait_upscaled.png', # 'face_restored': 'output/portrait_restored.png'} ``` -------------------------------- ### POST /upscale Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Upscales an image by 4x using the Real-ESRGAN x4plus model. Accepts multipart/form-data and returns a PNG image at 4x resolution. ```APIDOC ## POST /upscale ### Description Upscale an image by 4x using Real-ESRGAN x4plus. A 256x256 image becomes 1024x1024. ### Method POST ### Endpoint https://apim-ai-apis.azure-api.net/v1/image/upscale ### Parameters #### Request Body - **file** (multipart/form-data) - Required - The image file to upscale. ### Response #### Success Response (200) - **image** (PNG) - The upscaled image (4x resolution). ### Request Example ```python import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/upscale", headers={"Authorization": "Bearer YOUR_KEY"}, files={"file": open("small.jpg", "rb")} ) with open("upscaled.png", "wb") as f: f.write(response.content) ``` ``` -------------------------------- ### MCP Server Configuration Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt Configuration for using the Brainiall Image API as an MCP server, enabling direct tool use from AI clients. ```APIDOC ## MCP Server Configuration ### Description Configuration for the Brainiall Image API as an MCP server. ### Available MCP Tools - `remove_background` - `upscale_image` - `restore_face` - `check_image_service` ### Example Configuration (Standard) ```json { "mcpServers": { "brainiall-image": { "url": "https://apim-ai-apis.azure-api.net/mcp/image/mcp", "headers": { "Accept": "application/json, text/event-stream" } } } } ``` ### Example Configuration (Apify-hosted) ```json { "mcpServers": { "brainiall-image-apify": { "url": "https://n3nr6htYhIkL7dOhK.apify.actor/mcp?token=YOUR_APIFY_TOKEN" } } } ``` ``` -------------------------------- ### Python: Batch Image Processing with Progress Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Efficiently processes multiple images in a directory using multithreading and displays progress. Requires 'requests' and 'concurrent.futures'. Adjust 'workers' for optimal performance. ```python import requests from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path import time BASE_URL = "https://apim-ai-apis.azure-api.net/v1/image" HEADERS = {"Authorization": "Bearer YOUR_KEY"} def process_one(input_path, output_dir, operation="remove-background"): """Process a single image.""" name = Path(input_path).stem output_path = Path(output_dir) / f"{name}_{operation}.png" with open(input_path, "rb") as f: resp = requests.post( f"{BASE_URL}/{operation}", headers=HEADERS, files={"file": f}, timeout=30 ) if resp.status_code == 200: with open(output_path, "wb") as f: f.write(resp.content) return str(output_path), True return str(input_path), False def batch_process(input_dir, output_dir, operation="remove-background", workers=5): """Process all images in a directory.""" input_dir = Path(input_dir) output_dir = Path(output_dir) output_dir.mkdir(exist_ok=True) files = list(input_dir.glob("*.jpg")) + list(input_dir.glob("*.png")) print(f"Processing {len(files)} images with {workers} workers...") start = time.time() results = {"success": 0, "failed": 0} with ThreadPoolExecutor(max_workers=workers) as pool: futures = { pool.submit(process_one, str(f), str(output_dir), operation): f for f in files } for future in as_completed(futures): path, success = future.result() if success: results["success"] += 1 else: results["failed"] += 1 print(f" [{results['success'] + results['failed']}/{len(files)}] {Path(path).name}") elapsed = time.time() - start print(f"Done: {results['success']} success, {results['failed']} failed in {elapsed:.1f}s") print(f"Average: {elapsed / len(files):.2f}s per image") # Usage: batch_process("input_images/", "output_images/", "remove-background", workers=5) batch_process("input_images/", "output_images/", "upscale", workers=3) batch_process("input_images/", "output_images/", "restore-face", workers=5) ``` -------------------------------- ### MCP Server Configuration for Claude Desktop/Cursor Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md JSON configuration for integrating the BrainiAll Image API with MCP clients like Claude Desktop or Cursor. Specifies the API endpoint URL and necessary headers for communication. ```json { "mcpServers": { "brainiall-image": { "url": "https://apim-ai-apis.azure-api.net/mcp/image/mcp", "headers": { "Accept": "application/json, text/event-stream" } } } } ``` -------------------------------- ### Async Image Processing with httpx Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Perform image background removal, upscaling, and face restoration asynchronously using httpx. Handles base64 encoded images and includes batch processing capabilities. ```python import asyncio import httpx import base64 from pathlib import Path BASE_URL = "https://apim-ai-apis.azure-api.net/v1/image" API_KEY = "YOUR_KEY" async def remove_bg_async(image_bytes: bytes) -> bytes: """Remove background from image bytes asynchronously.""" b64 = base64.b64encode(image_bytes).decode() async with httpx.AsyncClient(timeout=30) as client: resp = await client.post( f"{BASE_URL}/remove-background/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) resp.raise_for_status() return base64.b64decode(resp.json()["image"]) async def upscale_async(image_bytes: bytes) -> bytes: """Upscale image 4x asynchronously.""" b64 = base64.b64encode(image_bytes).decode() async with httpx.AsyncClient(timeout=60) as client: resp = await client.post( f"{BASE_URL}/upscale/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) resp.raise_for_status() return base64.b64decode(resp.json()["image"]) async def restore_face_async(image_bytes: bytes) -> bytes: """Restore faces asynchronously.""" b64 = base64.b64encode(image_bytes).decode() async with httpx.AsyncClient(timeout=30) as client: resp = await client.post( f"{BASE_URL}/restore-face/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) resp.raise_for_status() return base64.b64decode(resp.json()["image"]) async def batch_remove_bg(input_dir: str, output_dir: str, concurrency: int = 5): """Process multiple images concurrently.""" input_path = Path(input_dir) output_path = Path(output_dir) output_path.mkdir(exist_ok=True) files = list(input_path.glob("*.jpg")) + list(input_path.glob("*.png")) semaphore = asyncio.Semaphore(concurrency) async def process_one(filepath): async with semaphore: image_bytes = filepath.read_bytes() result = await remove_bg_async(image_bytes) out = output_path / f"{filepath.stem}_nobg.png" out.write_bytes(result) print(f" Done: {filepath.name}") await asyncio.gather(*[process_one(f) for f in files]) print(f"Processed {len(files)} images") asyncio.run(batch_remove_bg("photos/", "output/", concurrency=5)) ``` -------------------------------- ### FastAPI Proxy Service for Image API Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt This Python code sets up a FastAPI application that acts as a proxy to the Brainiall Image API. It includes file size validation (max 10 MB) and streams PNG responses. Requires httpx for asynchronous HTTP requests. ```python from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.responses import StreamingResponse import httpx import io app = FastAPI() IMG_API = "https://apim-ai-apis.azure-api.net/v1/image" API_KEY = "YOUR_KEY" async def _proxy(file: UploadFile, operation: str) -> bytes: content = await file.read() if len(content) > 10 * 1024 * 1024: raise HTTPException(413, "File too large (max 10 MB)") async with httpx.AsyncClient(timeout=60) as client: resp = await client.post( f"{IMG_API}/{operation}", headers={"Authorization": f"Bearer {API_KEY}"}, files={"file": (file.filename, content, file.content_type)}, ) if resp.status_code != 200: raise HTTPException(resp.status_code, "Image processing failed") return resp.content @app.post("/api/remove-bg") async def remove_bg(file: UploadFile = File(...)): return StreamingResponse(io.BytesIO(await _proxy(file, "remove-background")), media_type="image/png") @app.post("/api/upscale") async def upscale(file: UploadFile = File(...)): return StreamingResponse(io.BytesIO(await _proxy(file, "upscale")), media_type="image/png") @app.post("/api/restore-face") async def restore_face(file: UploadFile = File(...)): return StreamingResponse(io.BytesIO(await _proxy(file, "restore-face")), media_type="image/png") # Run: uvicorn app:app --reload ``` -------------------------------- ### Upscale Image with Multipart Upload (Python) Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/README.md Use this Python snippet to upscale an image by 4x using multipart upload. The 'requests' library is required. The upscaled image is saved as a PNG file. ```python import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/upscale", headers={"Authorization": "Bearer YOUR_KEY"}, files={"file": open("small_image.jpg", "rb")} ) with open("upscaled_4x.png", "wb") as f: f.write(response.content) print("Image upscaled 4x! Saved to upscaled_4x.png") ``` -------------------------------- ### Upscale Image by 4x (File Upload) Source: https://github.com/fasuizu-br/brainiall-image-api/blob/main/llms-full.txt Upscale an image by 4x using the Real-ESRGAN model. This endpoint accepts a file upload and returns a PNG image at four times the original resolution. Authentication with a valid API key is required. ```python import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/image/upscale", headers={"Authorization": "Bearer YOUR_KEY"}, files={"file": open("small.jpg", "rb")} ) with open("upscaled.png", "wb") as f: f.write(response.content) ``` -------------------------------- ### Asynchronous Batch Image Processing with httpx (Python) Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt This asynchronous function processes images in batches using httpx and asyncio. It's designed for high concurrency and efficient handling of multiple requests without blocking the event loop. Ensure you have an `output` directory and images in the `photos` directory. ```python import asyncio import httpx import base64 from pathlib import Path BASE_URL = "https://apim-ai-apis.azure-api.net/v1/image" API_KEY = "YOUR_KEY" async def _b64_request(client: httpx.AsyncClient, endpoint: str, image_bytes: bytes) -> bytes: b64 = base64.b64encode(image_bytes).decode() resp = await client.post( f"{BASE_URL}/{endpoint}/base64", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"image": b64}, ) resp.raise_for_status() return base64.b64decode(resp.json()["image"]) async def batch_remove_bg(input_dir: str, output_dir: str, concurrency: int = 5): inp = Path(input_dir) out = Path(output_dir) out.mkdir(exist_ok=True) files = list(inp.glob("*.jpg")) + list(inp.glob("*.png")) sem = asyncio.Semaphore(concurrency) async def process(filepath: Path): async with sem: async with httpx.AsyncClient(timeout=30) as client: result = await _b64_request(client, "remove-background", filepath.read_bytes()) (out / f"{filepath.stem}_nobg.png").write_bytes(result) print(f" Done: {filepath.name}") await asyncio.gather(*[process(f) for f in files]) print(f"Finished {len(files)} images") asyncio.run(batch_remove_bg("photos/", "output/", concurrency=5)) ``` -------------------------------- ### BrainiallImage Class (Synchronous) Source: https://context7.com/fasuizu-br/brainiall-image-api/llms.txt A Python class for interacting with the Brainiall Image API synchronously. It includes methods for removing backgrounds, upscaling images, restoring faces, and checking API health, with built-in retry logic for common errors like rate limits and service unavailability. ```APIDOC ## BrainiallImage Class ### Description Provides a synchronous interface to the Brainiall Image API with built-in error handling and retry mechanisms. ### Methods #### `__init__(self, api_key: str, max_retries: int = 3, timeout: int = 30)` Initializes the BrainiallImage client. - **api_key** (str) - Required - Your API key for authentication. - **max_retries** (int) - Optional - Maximum number of retries for failed requests (default: 3). - **timeout** (int) - Optional - Request timeout in seconds (default: 30). #### `remove_background(self, src: str, dst: str) -> str` Removes the background from an image. - **src** (str) - Required - Path to the source image file. - **dst** (str) - Required - Path to save the output image file. Returns the path to the saved output image. #### `upscale(self, src: str, dst: str) -> str` Upscales an image. - **src** (str) - Required - Path to the source image file. - **dst** (str) - Required - Path to save the output image file. Returns the path to the saved output image. #### `restore_face(self, src: str, dst: str) -> str` Restores a face in an image. - **src** (str) - Required - Path to the source image file. - **dst** (str) - Required - Path to save the output image file. Returns the path to the saved output image. #### `health(self) -> dict` Checks the health status of the API. Returns a dictionary containing the API health status. ```