Skip to main content

🖼️ Image Captioning API

A high-performance, production-ready REST API for ML-based image captioning — built with FastAPI, async concurrency, and GPU-optimized inference.


🚀 Features

  • Zero-Disk I/O — In-memory BytesIO buffers eliminate file system overhead (~200–500ms saved per request)
  • Singleton Model Loading — Model weights loaded once at startup via FastAPI lifespan events (sub-second latency vs. 8+ seconds with per-request loading)
  • Managed GPU Concurrency — asyncio.Semaphore prevents CUDA OOM crashes; asyncio.to_thread keeps the API responsive during heavy inference
  • FP16 + torch.compile — 50% VRAM reduction and ~25% faster execution via Tensor Core acceleration
  • Security Validation — python-magic binary header inspection + MAX_FILE_SIZE enforcement at the gate, before GPU resources are touched

📈 Performance

Metric Original Script Optimized API
Average Latency ~7.5s (model reloads) ~0.6s (warm model)
Concurrency Sequential (1 at a time) Concurrent (queue-based)
Disk Usage Temp file per request 0 bytes (in-memory)
VRAM Stability High OOM risk Safe (semaphore-limited)

🏗️ Architecture

Incoming Request
      │
      ▼
[Security Shield]  ← python-magic + MAX_FILE_SIZE check
      │
      ▼
[In-Memory Buffer] ← io.BytesIO (no disk I/O)
      │
      ▼
[Async Queue]      ← asyncio.Semaphore (concurrency gate)
      │
      ▼
[Background Thread] ← asyncio.to_thread (non-blocking)
      │
      ▼
[GPU Inference]    ← Singleton CaptioningModel (FP16 + torch.compile)
      │
      ▼
   Response

⚙️ Installation

# Clone the repository
git clone https://github.com/your-org/image-captioning-api.git
cd image-captioning-api

# Install dependencies
pip install -r requirements.txt

Requirements: Python 3.10+, CUDA-capable GPU, PyTorch with CUDA support.


🔧 Running the API

Development

uvicorn app:app --reload --host 0.0.0.0 --port 8000

Use Gunicorn with Uvicorn workers for maximum performance on multi-core systems:

gunicorn -w 4 -k uvicorn.workers.UvicornWorker app:app --bind 0.0.0.0:8000

Tip: Set -w (workers) to (2 × CPU cores) + 1 as a starting point.


📡 API Reference

POST /caption

Submit an image and receive a generated caption.

Request

Content-Type: multipart/form-data
Body: file=<image>

Response

{
  "caption": "A dog running through a field of sunflowers."
}

Error Responses

Code Reason
400 Invalid file type or binary header mismatch
413 File exceeds MAX_FILE_SIZE limit
503 GPU queue at capacity

GET /health

Returns 200 OK when the model is loaded and the API is ready.


🔐 Configuration

Set the following environment variables:

Variable Default Description
MAX_FILE_SIZE 10485760 Max upload size in bytes (default: 10MB)
GPU_CONCURRENCY 4 Max simultaneous GPU inference tasks
MODEL_PATH ./models/captioner Path to model weights

🛡️ Security

All uploads are validated before reaching GPU resources:

  1. Binary header inspection via python-magic — rejects files that aren't valid images regardless of extension
  2. Size enforcement — files exceeding MAX_FILE_SIZE are rejected at ingestion
  3. No disk writes — uploaded data never touches the filesystem

🧠 Key Implementation Details

Singleton Model (Lifespan)

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.model = CaptioningModel()   # loaded once at startup
    yield
    del app.state.model                   # cleanup on shutdown

Managed GPU Concurrency

semaphore = asyncio.Semaphore(GPU_CONCURRENCY)

async def caption_image(file_bytes: bytes) -> str:
    async with semaphore:
        return await asyncio.to_thread(_run_inference, file_bytes)

FP16 Inference

model = model.half()              # FP16: 50% VRAM reduction
model = torch.compile(model)     # JIT-optimized kernels

📄 License

MIT License — see LICENSE for details.

Metadata

Release files for image-captioning 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for image-captioning 1.0.0
File Size Uploaded Provenance Actions
image_captioning-1.0.0.tar.gz 11.2 kB Without provenance Details for image_captioning-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for image-captioning 1.0.0
File Interpreter ABI Platform Actions
image_captioning-1.0.0-py3-none-any.whl Python 3 none any Details for image_captioning-1.0.0-py3-none-any.whl

Total release size: 22.9 kB

Release files / image_captioning-1.0.0.tar.gz

Download URL image_captioning-1.0.0.tar.gz
Size 11.2 kB
Tags Source
SHA-256 checksum
How to use checksums
f779195193bb8c564075cb2f22cb34b4d19cb5df3f3224a5ae90b78920ac819b
BLAKE2b-256 checksum
How to use checksums
b702ce672f95404ab012296c49fb1cff54a8e9da35f24d64068b3866c97d62d4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.9

Release files / image_captioning-1.0.0-py3-none-any.whl

Download URL image_captioning-1.0.0-py3-none-any.whl
Size 11.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6f4699ed9f5d0cb840ae4e7a453b0d03bff337bf5f2ae4c2290d260e3bf49139
BLAKE2b-256 checksum
How to use checksums
e2c30ff94900a8161a0b9900722b8665a33b1321b5a563e8abb4a1bbdf250c63
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.9

Security for image-captioning 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page