Skip to content

Latest commit

 

History

History
525 lines (400 loc) · 11 KB

File metadata and controls

525 lines (400 loc) · 11 KB

DEEPEDGE API Documentation

Overview

DEEPEDGE API is a RESTful service that provides text-to-image generation with semantic alignment scoring and instance segmentation. Built with FastAPI for high performance and automatic documentation.

Base URL: http://localhost:8000
API Version: 1.0.0
Format: JSON


Table of Contents

  1. Authentication
  2. Endpoints
  3. Request/Response Models
  4. Error Handling
  5. Rate Limiting
  6. Examples
  7. Interactive Documentation

Authentication

Currently, no authentication is required. Future versions will support API keys.


Endpoints

1. Health Check

Check API server status.

Endpoint: GET /

Description: Returns current server status and availability.

Parameters: None

Response:

{
  "status": "running"
}

Status Code: 200 OK

Example:

curl -X GET "http://localhost:8000/"

2. Generate Image

Main endpoint for generating images from text prompts.

Endpoint: POST /generate

Description:

  • Accepts a text prompt
  • Generates image using Stable Diffusion
  • Computes CLIP semantic alignment score
  • Optionally performs instance segmentation (SAM2)
  • Returns generated image path and analysis

Request Body:

Field Type Required Description
prompt string Yes Text description of image to generate (1-1000 chars)

Request Schema:

{
  "prompt": "A serene mountain landscape with a crystal clear lake reflecting the sky"
}

Response Body:

Field Type Description
image_path string Path to generated image (e.g., images/2026/01/uuid.png)
clip_analysis object Text-image alignment analysis
clip_analysis.concepts array List of key concepts extracted from prompt
clip_analysis.confidence number CLIP similarity score (0.0-1.0)
segmentation string Segmentation status ("completed", "failed", "skipped")

Response Schema:

{
  "image_path": "images/2026/01/550e8400-e29b-41d4-a716-446655440000.png",
  "clip_analysis": {
    "concepts": [
      "serene mountain landscape",
      "crystal clear lake"
    ],
    "confidence": 0.8632
  },
  "segmentation": "completed"
}

Status Codes:

  • 200 OK: Image generated successfully
  • 400 Bad Request: Invalid prompt (empty or malformed)
  • 422 Unprocessable Entity: Validation error in request
  • 500 Internal Server Error: Pipeline execution failed

Execution Time:

  • GPU (NVIDIA A100): ~5-10 seconds
  • GPU (NVIDIA V100): ~15-20 seconds
  • CPU (16 cores): ~120-180 seconds

Example:

curl -X POST "http://localhost:8000/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A futuristic cyberpunk city at night with neon lights and flying cars"
  }'

3. Analyze Image

Perform analysis on uploaded images.

Endpoint: POST /analyze

Description:

  • Analyzes uploaded image
  • Extracts features and segments objects
  • Returns detailed analysis results

Status: ⚠️ Currently under implementation

Planned Parameters:

  • Image file (multipart/form-data)
  • Analysis type (segmentation, feature extraction, etc.)
  • Confidence threshold

Planned Response:

{
  "image_id": "uuid",
  "upload_path": "uploaded_images/uuid.png",
  "segmentation": {
    "segments": 5,
    "masks": ["mask_0.png", "mask_1.png"],
    "confidence_scores": [0.95, 0.92, 0.88, 0.85, 0.79]
  },
  "features": {
    "dominant_colors": ["#FF0000", "#00FF00"],
    "objects_detected": ["person", "car", "tree"]
  }
}

Request/Response Models

GenerateRequest

class GenerateRequest(BaseModel):
    prompt: str  # 1-1000 characters
    
    class Config:
        example = {
            "prompt": "A beautiful sunset over the ocean"
        }

GenerateResponse

class ClipAnalysis(BaseModel):
    concepts: List[str]
    confidence: float  # 0.0 to 1.0

class GenerateResponse(BaseModel):
    image_path: str
    clip_analysis: ClipAnalysis
    segmentation: str  # "completed", "failed", or "skipped"
    
    class Config:
        example = {
            "image_path": "images/2026/01/uuid.png",
            "clip_analysis": {
                "concepts": ["beautiful sunset"],
                "confidence": 0.87
            },
            "segmentation": "completed"
        }

Error Handling

Standard Error Response

{
  "detail": "Error message describing what went wrong"
}

Common Error Scenarios

1. Empty Prompt

Request:

curl -X POST "http://localhost:8000/generate" \
  -H "Content-Type: application/json" \
  -d '{"prompt": ""}'

Response (400):

{
  "detail": "Prompt cannot be empty"
}

2. Invalid JSON

Request:

curl -X POST "http://localhost:8000/generate" \
  -H "Content-Type: application/json" \
  -d '{invalid json}'

Response (422):

{
  "detail": [
    {
      "loc": ["body", "prompt"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

3. Server Error

Response (500):

{
  "detail": "Pipeline execution failed: [detailed error message]"
}

Rate Limiting

Current Status: No rate limiting implemented

Future Plans:

  • Per-IP rate limiting (100 requests/hour)
  • Per-API-key rate limiting (1000 requests/hour for premium)
  • Token bucket algorithm for fair distribution

Examples

Python Client

import requests
import json
from pathlib import Path

class DEEPEDGEClient:
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url
    
    def health_check(self):
        """Check API server status"""
        response = requests.get(f"{self.base_url}/")
        return response.json()
    
    def generate_image(self, prompt):
        """Generate image from text prompt"""
        payload = {"prompt": prompt}
        response = requests.post(
            f"{self.base_url}/generate",
            json=payload
        )
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"API Error: {response.text}")

# Usage
client = DEEPEDGEClient()

# Check health
print(client.health_check())

# Generate image
result = client.generate_image(
    "A majestic eagle soaring over snow-capped mountains"
)

print(f"Image saved: {result['image_path']}")
print(f"CLIP Score: {result['clip_analysis']['confidence']}")

JavaScript/Node.js Client

const axios = require('axios');

class DEEPEDGEClient {
  constructor(baseURL = 'http://localhost:8000') {
    this.client = axios.create({ baseURL });
  }

  async healthCheck() {
    const response = await this.client.get('/');
    return response.data;
  }

  async generateImage(prompt) {
    const response = await this.client.post('/generate', { prompt });
    return response.data;
  }
}

// Usage
const client = new DEEPEDGEClient();

(async () => {
  const health = await client.healthCheck();
  console.log('Status:', health.status);

  const result = await client.generateImage(
    'A futuristic city with holographic billboards'
  );

  console.log('Image path:', result.image_path);
  console.log('CLIP Score:', result.clip_analysis.confidence);
})();

Bash/cURL Examples

#!/bin/bash

# Health check
echo "=== Health Check ==="
curl -X GET "http://localhost:8000/"
echo ""

# Generate image
echo "=== Generate Image ==="
curl -X POST "http://localhost:8000/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A serene forest with sunlight filtering through the trees"
  }' | jq '.'

# Save response to file
echo "=== Save to File ==="
curl -X POST "http://localhost:8000/generate" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Ocean waves during a storm"}' \
  --output response.json

echo "Response saved to response.json"

Batch Processing

import requests
import json
import time
from concurrent.futures import ThreadPoolExecutor

prompts = [
    "A serene mountain landscape",
    "A bustling city street at night",
    "A peaceful forest with a river",
    "A desert under starlight",
    "A tropical beach at sunset"
]

def generate_image(prompt):
    """Generate single image"""
    try:
        response = requests.post(
            "http://localhost:8000/generate",
            json={"prompt": prompt},
            timeout=300  # 5 minute timeout
        )
        return {
            "prompt": prompt,
            "status": "success",
            "data": response.json()
        }
    except Exception as e:
        return {
            "prompt": prompt,
            "status": "failed",
            "error": str(e)
        }

# Process in parallel (max 3 concurrent)
with ThreadPoolExecutor(max_workers=3) as executor:
    results = list(executor.map(generate_image, prompts))

# Save results
with open("batch_results.json", "w") as f:
    json.dump(results, f, indent=2)

# Print summary
successful = sum(1 for r in results if r["status"] == "success")
print(f"✓ {successful}/{len(prompts)} images generated successfully")

Interactive Documentation

Swagger UI

Access the interactive API documentation at:

http://localhost:8000/docs

Features:

  • ✓ Try out endpoints directly in browser
  • ✓ View request/response schemas
  • ✓ See all available endpoints
  • ✓ Test with different parameters

ReDoc

Alternative documentation view at:

http://localhost:8000/redoc

Performance Tips

  1. Batch Requests: Process multiple prompts concurrently

    from concurrent.futures import ThreadPoolExecutor
    with ThreadPoolExecutor(max_workers=3) as executor:
        results = executor.map(generate_image, prompts)
  2. Reduce Inference Steps: For faster (lower quality) generation

    • Default: 50 steps
    • Fast: 30 steps
    • Ultra-fast: 15 steps
  3. Use GPU: 15-20x faster than CPU

    • Check with: curl http://localhost:8000/health
  4. Cache Images: Store generated images to avoid regeneration

  5. Monitor Logs: Check logs/deepedge.log for performance metrics


Roadmap

Version 1.1 (Planned)

  • API key authentication
  • Rate limiting per IP/key
  • Image caching and deduplication
  • Batch endpoint for multiple prompts
  • WebSocket support for streaming

Version 1.2 (Planned)

  • Model selection endpoint
  • Custom generation parameters
  • Advanced segmentation analysis
  • Feature extraction API
  • Image similarity search

Version 2.0 (Planned)

  • Multi-model comparison
  • Prompt optimization
  • A/B testing framework
  • Real-time analytics dashboard
  • GraphQL API

Support


Last Updated: January 18, 2026
API Version: 1.0.0
Status: Production-Ready