Spaces:
Sleeping
Sleeping
Upload 17 files
#8
by kajalan - opened
Files changed (4)
- .env.example+5
- Dockerfile+9-9
- README.md+39-332
- docker-compose.yml+3-3
6 unmodified lines7891011126 unmodified linesPORT=8000DEBUG=false# ── Model ─────────────────────────────────────────────────────────────────────# Recommended CPU models (smallest to largest):#6 unmodified lines78910111213141516176 unmodified linesPORT=8000DEBUG=false# ── Hugging Face ──────────────────────────────────────────────────────────────# Get your free token at https://huggingface.co/settings/tokens# Removes the rate-limit warning and speeds up model file resolutionHF_TOKEN=# ── Model ─────────────────────────────────────────────────────────────────────# Recommended CPU models (smallest to largest):#
38 unmodified lines39404142434445464748495051525354555657585910 unmodified lines7071727338 unmodified lines# Create runtime directoriesRUN mkdir -p outputs model_cache# Non-root user for securityRUN useradd -m -u 1000 appuser \&& chown -R appuser:appuser /appUSER appuser# Expose API portEXPOSE 8000# Health check — hits the /health endpoint every 30 sHEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \CMD curl -f http://localhost:8000/health || exit 1# Default env (override with docker run -e or docker-compose)ENV HOST=0.0.0.0 \PORT=8000 \MODEL_ID=nota-ai/bk-sdm-small \MODEL_CACHE_DIR=/app/model_cache \AUTO_LOAD_MODEL=true \10 unmodified linesJOB_TTL_SECONDS=0CMD ["python", "-m", "uvicorn", "main:app", \"--host", "0.0.0.0", "--port", "8000", "--workers", "1"]38 unmodified lines39404142434445464748495051525354555657585910 unmodified lines7071727338 unmodified lines# Create runtime directoriesRUN mkdir -p outputs model_cache# HF Spaces runs containers as UID 1000 — match itRUN useradd -m -u 1000 appuser \&& chown -R appuser:appuser /appUSER appuser# ── Port 7860 is REQUIRED by Hugging Face Spaces ──────────────────────────────EXPOSE 7860# Health check — longer start_period for model download on cold startHEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=5 \CMD curl -f http://localhost:7860/health || exit 1# Default env (override via HF Spaces Secrets or docker-compose)ENV HOST=0.0.0.0 \PORT=7860 \MODEL_ID=nota-ai/bk-sdm-small \MODEL_CACHE_DIR=/app/model_cache \AUTO_LOAD_MODEL=true \10 unmodified linesJOB_TTL_SECONDS=0CMD ["python", "-m", "uvicorn", "main:app", \"--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352---license: mittitle: hf-image-apisdk: dockeremoji: 💻colorFrom: purplecolorTo: yellowpinned: true---# HF CPU Image Generation APIA production-ready REST API for **Stable Diffusion image generation on CPU** using Hugging Face Diffusers. Built on top of the architecture patterns from [Local AI Image Generator](https://github.com/techjarves/Local-AI-Image-Generator) and redesigned as a stateless, job-queue-based HTTP API.---## Architecture Overview```Client││ POST /generate → { job_id, status: "queued" }││ GET /jobs/{id} → { status: "processing", progress: 45 }│ GET /jobs/{id} → { status: "completed", download_url: "..." }││ GET /jobs/{id}/download → image.png││ DELETE /jobs/{id} → { ok: true }│▼┌─────────────────────────────────────────────────────────────┐│ FastAPI (main.py) ││ ├── POST /generate → enqueue job, return job_id ││ ├── GET /jobs → list / filter jobs ││ ├── GET /jobs/{id} → status + progress ││ ├── GET /jobs/{id}/download → FileResponse (PNG) ││ ├── DELETE /jobs/{id} → delete job + image ││ ├── GET /health → pipeline & queue status ││ └── POST /models/load → hot-swap model ││ ││ job_store.py — thread-safe in-memory job registry ││ worker.py — background daemon thread + FIFO queue ││ pipeline_manager.py — HF Diffusers pipeline (CPU-tuned) │└─────────────────────────────────────────────────────────────┘│┌────────▼────────┐│ outputs/ ││ (PNG files) │└─────────────────┘```---## Quick Start### Prerequisites- Python 3.9 or higher- 4 GB+ RAM (8 GB recommended for SD v1.5)- Internet connection on first run (to download model weights)### 1. Install```bashgit clone <this-repo>cd hf-image-api# Linux / macOS — one command setup:bash start.sh# Windows:python -m venv .venv.venv\Scripts\activatepip install torch torchvision --index-url https://download.pytorch.org/whl/cpupip install -r requirements.txtcopy .env.example .envpython -m uvicorn main:app --host 0.0.0.0 --port 8000 --workers 1```### 2. Open the interactive docs```http://localhost:8000/docs```---## CPU Performance Guide| Model | Size | 512×512 @ 20 steps | Notes ||---|---|---|---|| `nota-ai/bk-sdm-small` | ~500 MB | **~60–120 s** | Best for CPU — default || `runwayml/stable-diffusion-v1-5` | ~4 GB | ~150–300 s | Standard quality || `stabilityai/stable-diffusion-2-1-base` | ~5 GB | ~200–400 s | Highest quality |### Optimisations applied automatically| Optimisation | Effect ||---|---|| `torch.float32` | Mandatory for CPU (float16 causes NaN) || `low_cpu_mem_usage=True` | Streams weights into RAM — avoids double-buffering || `enable_attention_slicing(1)` | Lowers peak RAM ~30 %, minimal speed cost || `DPMSolverMultistepScheduler` + Karras sigmas | Converges well at 15–20 steps || `safety_checker=None` | Skips NSFW classifier, saves ~300 MB RAM || `torch.set_num_threads(N)` | Saturates all logical CPU cores || `torch.inference_mode()` | Disables autograd, reduces overhead |### Tips to speed up CPU generation- Use **`nota-ai/bk-sdm-small`** — it is specifically distilled for speed- Keep images at **512×512** (larger = much slower on SD v1.x)- Use **20 steps with DPM++** (better than 50 steps with PNDM)- Set `CPU_THREADS=0` in `.env` to use all logical cores- Avoid running other CPU-heavy workloads during generation---## API Reference### Submit a generation job```POST /generate```**Request body:**```json{"prompt": "a photorealistic mountain landscape at golden hour","negative_prompt": "blurry, low quality, watermark","width": 512,"height": 512,"num_inference_steps": 20,"guidance_scale": 7.5,"seed": -1,"scheduler": "dpm++"}```**Schedulers:** `dpm++` (best), `euler_a`, `euler`, `pndm`**Response `202 Accepted`:**```json{"job_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6","status": "queued","created_at": "2024-06-01T12:00:00Z","queue_position": 1,"message": "Job is next in queue and will start immediately."}```---### Check job status```GET /jobs/{job_id}```**While processing:**```json{"job_id": "3fa85f64-...","status": "processing","progress": 45,"current_step": 9,"total_steps": 20,"started_at": "2024-06-01T12:00:01Z"}```**When completed:**```json{"job_id": "3fa85f64-...","status": "completed","progress": 100,"download_url": "/jobs/3fa85f64-.../download","image_filename": "20240601_120045_3fa85f64_42.png","duration_seconds": 87.3,"completed_at": "2024-06-01T12:01:28Z"}```---### Download the image```GET /jobs/{job_id}/download```Returns the PNG as a file attachment. Returns `202` if still processing.---### Delete a job and its image```DELETE /jobs/{job_id}```Removes the job record and deletes the PNG from disk.```json{"ok": true,"job_id": "3fa85f64-...","image_deleted": true,"message": "Job deleted. Image file removed from disk."}```---### List all jobs```GET /jobs?status=completed&limit=50&offset=0```Status filter options: `queued`, `processing`, `completed`, `failed`---### Health check```GET /health``````json{"status": "ok","model_id": "nota-ai/bk-sdm-small","pipeline_loaded": true,"loading": false,"queue_size": 2,"jobs_total": 15,"jobs_by_status": {"queued": 2,"processing": 1,"completed": 11,"failed": 1},"cpu_threads": 8}```---### Hot-swap model```POST /models/loadContent-Type: application/json{ "model_id": "runwayml/stable-diffusion-v1-5" }```Loads the new model in the background. Poll `GET /health` to confirm `pipeline_loaded: true`.---## Example: Full workflow with curl```bash# 1. Check service is readycurl http://localhost:8000/health | jq .pipeline_loaded# 2. Submit a generation jobJOB=$(curl -s -X POST http://localhost:8000/generate \-H "Content-Type: application/json" \-d '{"prompt": "a serene Japanese garden with koi pond, watercolor style","negative_prompt": "low quality, blurry, cartoon","width": 512,"height": 512,"num_inference_steps": 20,"guidance_scale": 7.5,"seed": 42,"scheduler": "dpm++"}')echo $JOB | jq .JOB_ID=$(echo $JOB | jq -r .job_id)# 3. Poll until completedwhile true; doSTATUS=$(curl -s http://localhost:8000/jobs/$JOB_ID | jq -r .status)PROGRESS=$(curl -s http://localhost:8000/jobs/$JOB_ID | jq -r .progress)echo "Status: $STATUS Progress: $PROGRESS%"[ "$STATUS" = "completed" ] || [ "$STATUS" = "failed" ] && breaksleep 5done# 4. Download the imagecurl -s http://localhost:8000/jobs/$JOB_ID/download -o output.pngecho "Saved to output.png"# 5. Delete the job + imagecurl -s -X DELETE http://localhost:8000/jobs/$JOB_ID | jq .```---## Configuration (`.env`)| Variable | Default | Description ||---|---|---|| `MODEL_ID` | `nota-ai/bk-sdm-small` | Hugging Face model repo ID || `MODEL_CACHE_DIR` | `./model_cache` | Where weights are cached || `AUTO_LOAD_MODEL` | `true` | Load model at startup || `CPU_THREADS` | `0` (all cores) | PyTorch thread count || `ENABLE_ATTENTION_SLICING` | `true` | Lower peak RAM usage || `DEFAULT_STEPS` | `20` | Default inference steps || `MAX_STEPS` | `50` | Request cap || `DEFAULT_WIDTH/HEIGHT` | `512` | Default image dimensions || `MAX_WIDTH/HEIGHT` | `768` | Request cap || `OUTPUTS_DIR` | `./outputs` | Where PNGs are saved || `PORT` | `8000` | HTTP port || `DEBUG` | `false` | Verbose logging + auto-reload |---## File Structure```hf-image-api/├── main.py # FastAPI app + lifespan (startup/shutdown)├── config.py # Settings from environment / .env├── schemas.py # All Pydantic request & response models├── job_store.py # Thread-safe in-memory job registry├── pipeline_manager.py # HuggingFace Diffusers pipeline (CPU-tuned)├── worker.py # Background worker thread + FIFO job queue├── routes/│ ├── generate.py # POST /generate│ ├── jobs.py # GET/DELETE /jobs and /jobs/{id}/download│ └── health.py # GET /health, GET /models, POST /models/load├── outputs/ # Generated PNG files (auto-created)├── model_cache/ # HuggingFace model weights cache (auto-created)├── requirements.txt├── .env.example├── start.sh└── README.md```---## LicenseMIT — free to use and modify.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859---title: HF Image APIemoji: 🖼️colorFrom: bluecolorTo: purplesdk: dockerpinned: falseapp_port: 7860---# HF CPU Image Generation APIA job-queue REST API for Stable Diffusion image generation on CPU using Hugging Face Diffusers.**Swagger UI:** `https://your-space-url.hf.space/docs`## Job flow```POST /generate → { job_id, status: "queued" }GET /jobs/{id} → { status: "processing", progress: 45 }GET /jobs/{id} → { status: "completed", download_url: "..." }GET /jobs/{id}/download → image.pngDELETE /jobs/{id} → removes job + image```## API endpoints| Method | Path | Description ||---|---|---|| `POST` | `/generate` | Submit a generation job || `GET` | `/jobs` | List all jobs || `GET` | `/jobs/{id}` | Poll job status & progress || `GET` | `/jobs/{id}/download` | Download the PNG || `DELETE` | `/jobs/{id}` | Delete job + image || `GET` | `/health` | Pipeline & queue status || `GET` | `/models` | List supported models || `POST` | `/models/load` | Hot-swap model |## CPU optimisations- `torch.float32` (mandatory for CPU)- `DPMSolverMultistepScheduler` — converges at 20 steps- `enable_attention_slicing` — lower peak RAM- `low_cpu_mem_usage=True` — no double-buffering- `safety_checker=None` — saves ~300 MB RAM## Default model`nota-ai/bk-sdm-small` (~500 MB) — fastest on CPU, ~60–120s per 512×512 image.## HF Spaces SecretsSet these under **Settings → Secrets** in your Space:| Secret | Description ||---|---|| `HF_TOKEN` | Your HuggingFace token (faster downloads) || `MODEL_ID` | Override model (e.g. `runwayml/stable-diffusion-v1-5`) |
8 unmodified lines910111213141534 unmodified lines505152535455562 unmodified lines596061628 unmodified linescontainer_name: hf-image-apiports:- "8000:8000"# ── Persistent volumes ─────────────────────────────────────────────────────volumes:34 unmodified linesrestart: unless-stoppedhealthcheck:test: ["CMD", "curl", "-f", "http://localhost:8000/health"]interval: 30stimeout: 10sretries: 32 unmodified lines# ── Named volumes ──────────────────────────────────────────────────────────────volumes:model_cache:driver: local8 unmodified lines910111213141534 unmodified lines505152535455562 unmodified lines596061628 unmodified linescontainer_name: hf-image-apiports:- "8000:7860"# ── Persistent volumes ─────────────────────────────────────────────────────volumes:34 unmodified linesrestart: unless-stoppedhealthcheck:test: ["CMD", "curl", "-f", "http://localhost:7860/health"]interval: 30stimeout: 10sretries: 32 unmodified lines# ── Named volumes ──────────────────────────────────────────────────────────────volumes:model_cache:driver: local
.env.example+5
Dockerfile+9-9
README.md+39-332
docker-compose.yml+3-3