Spaces:
Sleeping
Sleeping
Upload 14 files
#1
by kajalan - opened
Files changed (14)
- .env.exampleAdded+48
- README.md+340-10
- config.pyAdded+64
- job_store.pyAdded+99
- main.pyAdded+131
- pipeline_manager.pyAdded+199
- requirements.txtAdded+20
- routes/__init__.pyAdded
- routes/generate.pyAdded+81
- routes/health.pyAdded+111
- routes/jobs.pyAdded+160
- schemas.pyAdded+132
- start.shAdded+44
- worker.pyAdded+179
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# ── HF CPU Image Generation API — environment configuration ──────────────────# Copy this file to .env and edit as needed.# All values shown here are the defaults.
# ── Server ────────────────────────────────────────────────────────────────────HOST=0.0.0.0PORT=8000DEBUG=false
# ── Model ─────────────────────────────────────────────────────────────────────# Recommended CPU models (smallest to largest):## nota-ai/bk-sdm-small ~500 MB — fastest on CPU (default)# runwayml/stable-diffusion-v1-5 ~4 GB — best quality/compat balance# stabilityai/stable-diffusion-2-1-base ~5 GB — highest quality#MODEL_ID=nota-ai/bk-sdm-smallMODEL_CACHE_DIR=./model_cache
# Load the model at startup so the first job doesn't pay cold-start cost.# Set to false if you want to control loading manually via POST /models/loadAUTO_LOAD_MODEL=true
# ── CPU Tuning ─────────────────────────────────────────────────────────────────# 0 = use all logical CPU cores (recommended)CPU_THREADS=0
# Slice attention into smaller chunks — lowers peak RAM, minimal speed costENABLE_ATTENTION_SLICING=true
# ── Generation defaults ────────────────────────────────────────────────────────# DPM++ scheduler converges well at 20 steps — good CPU/quality balanceDEFAULT_STEPS=20MAX_STEPS=50
# 512×512 is ideal for SD v1.x — larger sizes increase RAM and time significantlyDEFAULT_WIDTH=512DEFAULT_HEIGHT=512MAX_WIDTH=768MAX_HEIGHT=768
DEFAULT_GUIDANCE_SCALE=7.5
# ── Storage ────────────────────────────────────────────────────────────────────OUTPUTS_DIR=./outputs
# Auto-delete jobs after N seconds (0 = keep forever)JOB_TTL_SECONDS=012345678910111213---title: Hf Image Apiemoji: ⚡colorFrom: purplecolorTo: greensdk: gradiosdk_version: 6.19.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343# 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.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""config.py — All runtime settings loaded from environment / .env file."""from pydantic_settings import BaseSettingsfrom pydantic import Fieldimport os
class Settings(BaseSettings): # ── Server ──────────────────────────────────────────────────────────────── host: str = Field("0.0.0.0", env="HOST") port: int = Field(8000, env="PORT") debug: bool = Field(False, env="DEBUG")
# ── Model ───────────────────────────────────────────────────────────────── # Best CPU models (small → fast): # "nota-ai/bk-sdm-small" (~500 MB, very fast on CPU) # "runwayml/stable-diffusion-v1-5" (~4 GB, standard quality) # "stabilityai/stable-diffusion-2-1-base" (~5 GB, higher quality) model_id: str = Field( "nota-ai/bk-sdm-small", env="MODEL_ID", ) model_cache_dir: str = Field("./model_cache", env="MODEL_CACHE_DIR")
# Load the pipeline at startup (recommended — avoids cold-start on first job) auto_load_model: bool = Field(True, env="AUTO_LOAD_MODEL")
# ── CPU Optimisation ────────────────────────────────────────────────────── # Number of CPU threads for PyTorch inference (0 = use all logical cores) cpu_threads: int = Field(0, env="CPU_THREADS")
# Enable attention slicing (reduces peak RAM at slight speed cost) enable_attention_slicing: bool = Field(True, env="ENABLE_ATTENTION_SLICING")
# Default inference steps (DPM++ scheduler works well at 20 steps on CPU) default_steps: int = Field(20, env="DEFAULT_STEPS") max_steps: int = Field(50, env="MAX_STEPS")
# Default image dimensions (512×512 is ideal for SD v1.x on CPU) default_width: int = Field(512, env="DEFAULT_WIDTH") default_height: int = Field(512, env="DEFAULT_HEIGHT") max_width: int = Field(768, env="MAX_WIDTH") max_height: int = Field(768, env="MAX_HEIGHT")
# Default guidance scale default_guidance_scale: float = Field(7.5, env="DEFAULT_GUIDANCE_SCALE")
# ── Storage ─────────────────────────────────────────────────────────────── outputs_dir: str = Field("./outputs", env="OUTPUTS_DIR")
# Auto-delete completed jobs after N seconds (0 = never) job_ttl_seconds: int = Field(0, env="JOB_TTL_SECONDS")
class Config: env_file = ".env" env_file_encoding = "utf-8"
settings = Settings()
# Resolve absolute output pathos.makedirs(settings.outputs_dir, exist_ok=True)os.makedirs(settings.model_cache_dir, exist_ok=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""job_store.py — Thread-safe in-memory store for generation jobs.
Uses a plain threading.Lock so it is safe to call from both the FastAPIasync event-loop (via run_in_executor) and from the background worker thread."""from __future__ import annotations
import threadingimport uuidfrom datetime import datetime, timezonefrom typing import Dict, List, Optional
from schemas import Job, JobStatus
class JobStore: """Central store for all generation jobs."""
def __init__(self) -> None: self._jobs: Dict[str, Job] = {} self._lock = threading.Lock()
# ── Write operations ───────────────────────────────────────────────────────
def create( self, prompt: str, negative_prompt: str, params: dict, model_id: Optional[str] = None, ) -> Job: job_id = str(uuid.uuid4()) job = Job( job_id=job_id, status=JobStatus.QUEUED, prompt=prompt, negative_prompt=negative_prompt, params=params, created_at=datetime.now(timezone.utc), total_steps=params.get("num_inference_steps", 20), model_id=model_id, ) with self._lock: self._jobs[job_id] = job return job
def update(self, job_id: str, **kwargs) -> Optional[Job]: with self._lock: job = self._jobs.get(job_id) if not job: return None for key, val in kwargs.items(): if hasattr(job, key): setattr(job, key, val) return job
def delete(self, job_id: str) -> Optional[Job]: with self._lock: return self._jobs.pop(job_id, None)
# ── Read operations ────────────────────────────────────────────────────────
def get(self, job_id: str) -> Optional[Job]: with self._lock: return self._jobs.get(job_id)
def list_all( self, status_filter: Optional[JobStatus] = None, limit: int = 100, offset: int = 0, ) -> List[Job]: with self._lock: jobs = list(self._jobs.values())
# Apply optional status filter if status_filter is not None: jobs = [j for j in jobs if j.status == status_filter]
# Sort newest first jobs.sort(key=lambda j: j.created_at, reverse=True) return jobs[offset : offset + limit]
def counts_by_status(self) -> Dict[str, int]: with self._lock: result: Dict[str, int] = {s.value: 0 for s in JobStatus} for job in self._jobs.values(): result[job.status.value] += 1 return result
@property def total(self) -> int: with self._lock: return len(self._jobs)
# Singleton used throughout the applicationjob_store = JobStore()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""main.py — FastAPI application entry point.
Startup sequence────────────────1. Worker thread is started (daemon thread — auto-stops with the process).2. If AUTO_LOAD_MODEL=true, the HuggingFace pipeline is loaded in the background so the first job doesn't include cold-start download time.3. The HTTP server starts accepting requests.
Run with: uvicorn main:app --host 0.0.0.0 --port 8000 --reload"""from __future__ import annotations
import loggingimport osimport threadingfrom contextlib import asynccontextmanager
import uvicornfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse
from config import settingsfrom routes import generate, health, jobsfrom worker import start_worker
# ── Logging ───────────────────────────────────────────────────────────────────logging.basicConfig( level=logging.DEBUG if settings.debug else logging.INFO, format="%(asctime)s %(levelname)-8s %(name)s %(message)s", datefmt="%H:%M:%S",)logger = logging.getLogger("main")
# ── Lifespan (startup / shutdown) ─────────────────────────────────────────────
@asynccontextmanagerasync def lifespan(app: FastAPI): logger.info("═" * 60) logger.info(" HF Image Generation API — starting up") logger.info(" Model ID : %s", settings.model_id) logger.info(" Outputs dir: %s", settings.outputs_dir) logger.info(" CPU threads: %s", settings.cpu_threads or os.cpu_count()) logger.info("═" * 60)
# 1. Start background worker thread start_worker() logger.info("Background worker started.")
# 2. Optionally pre-load the pipeline if settings.auto_load_model: def _preload(): from pipeline_manager import pipeline_mgr try: pipeline_mgr.load() except Exception as exc: logger.exception("Pre-load failed: %s", exc)
t = threading.Thread(target=_preload, name="preload", daemon=True) t.start() logger.info("Pipeline pre-load started in background (AUTO_LOAD_MODEL=true).") else: logger.info("AUTO_LOAD_MODEL=false — pipeline will load on first job.")
yield # ← application runs here
logger.info("Shutting down.")
# ── App ───────────────────────────────────────────────────────────────────────
app = FastAPI( title="HF CPU Image Generation API", description=( "Job-based REST API for Stable Diffusion image generation on CPU " "using Hugging Face Diffusers. " "Submit a job → poll status → download image → optionally delete." ), version="1.0.0", lifespan=lifespan, docs_url="/docs", redoc_url="/redoc",)
# CORS — allow everything by default (restrict in production)app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# ── Global exception handler ───────────────────────────────────────────────────
@app.exception_handler(Exception)async def global_exception_handler(request: Request, exc: Exception): logger.exception("Unhandled error on %s %s: %s", request.method, request.url.path, exc) return JSONResponse( status_code=500, content={"detail": "An internal server error occurred.", "error": str(exc)}, )
# ── Root redirect to docs ──────────────────────────────────────────────────────
@app.get("/", include_in_schema=False)async def root(): from fastapi.responses import RedirectResponse return RedirectResponse(url="/docs")
# ── Mount routers ──────────────────────────────────────────────────────────────
app.include_router(health.router)app.include_router(generate.router)app.include_router(jobs.router)
# ── Dev entrypoint ─────────────────────────────────────────────────────────────
if __name__ == "__main__": uvicorn.run( "main:app", host=settings.host, port=settings.port, reload=settings.debug, log_level="debug" if settings.debug else "info", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199"""pipeline_manager.py — Singleton that owns the Diffusers pipeline.
CPU optimisations applied: • torch.float32 (float16 is GPU-only and causes NaN on CPU) • enable_attention_slicing() — lower peak RAM usage • DPMSolverMultistepScheduler — fast convergence in 15-20 steps • torch.set_num_threads() — saturate all logical cores • low_cpu_mem_usage=True — stream weights into RAM, don't double-buffer • safety_checker=None — skip the NSFW binary classifier (saves ~300 MB RAM)
Loading is thread-safe; only one thread can load at a time."""from __future__ import annotations
import loggingimport osimport threadingfrom typing import Callable, Optional, Tuple
logger = logging.getLogger("pipeline_manager")
class PipelineManager:
def __init__(self) -> None: self._pipe = None self._model_id: Optional[str] = None self._loading = False self._lock = threading.Lock()
# ── Public API ─────────────────────────────────────────────────────────────
@property def is_loaded(self) -> bool: return self._pipe is not None
@property def is_loading(self) -> bool: return self._loading
@property def current_model_id(self) -> Optional[str]: return self._model_id
def load(self, model_id: Optional[str] = None) -> None: """Load (or hot-swap) the pipeline. Blocks the calling thread until done.""" from config import settings import torch from diffusers import ( StableDiffusionPipeline, DPMSolverMultistepScheduler, )
target_model = model_id or settings.model_id
with self._lock: if self._loading: logger.warning("Pipeline is already loading — skipping duplicate load request.") return self._loading = True
try: logger.info("Loading pipeline: %s", target_model)
# ── CPU thread tuning ────────────────────────────────────────────── n_threads = settings.cpu_threads or os.cpu_count() or 4 torch.set_num_threads(n_threads) logger.info("PyTorch CPU threads set to %d", n_threads)
# ── Load the pipeline ────────────────────────────────────────────── pipe = StableDiffusionPipeline.from_pretrained( target_model, torch_dtype=torch.float32, # mandatory for CPU low_cpu_mem_usage=True, # stream tensors, avoid double RAM safety_checker=None, # skip NSFW checker (~300 MB RAM saved) requires_safety_checker=False, cache_dir=settings.model_cache_dir, )
# ── Move to CPU explicitly ───────────────────────────────────────── pipe = pipe.to("cpu")
# ── Swap scheduler: DPM++ 2M — best quality/speed on CPU ────────── pipe.scheduler = DPMSolverMultistepScheduler.from_config( pipe.scheduler.config, use_karras_sigmas=True, # smoother sampling curve )
# ── Memory optimisations ─────────────────────────────────────────── if settings.enable_attention_slicing: pipe.enable_attention_slicing(slice_size=1)
# ── Optional: torch.compile (PyTorch ≥ 2.0 only) ───────────────── # Disabled by default: first-run compilation takes minutes on CPU # and saves ~5-10 % on subsequent calls. Enable manually if needed: # pipe.unet = torch.compile(pipe.unet, backend="inductor")
with self._lock: self._pipe = pipe self._model_id = target_model self._loading = False
logger.info("Pipeline ready: %s", target_model)
except Exception as exc: with self._lock: self._loading = False logger.exception("Failed to load pipeline: %s", exc) raise
def generate( self, prompt: str, negative_prompt: str, width: int, height: int, num_inference_steps: int, guidance_scale: float, seed: int, scheduler_name: str, step_callback: Optional[Callable] = None, ) -> Tuple["PIL.Image.Image", int]: """ Run inference and return (PIL image, seed_used). Blocks the calling thread — always call from the worker thread. """ import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, PNDMScheduler, )
if not self._pipe: raise RuntimeError("Pipeline is not loaded. Call load() first.")
pipe = self._pipe
# ── Swap scheduler if requested ──────────────────────────────────────── scheduler_map = { "dpm++": DPMSolverMultistepScheduler, "euler_a": EulerAncestralDiscreteScheduler, "euler": EulerDiscreteScheduler, "pndm": PNDMScheduler, } SchedulerClass = scheduler_map.get(scheduler_name, DPMSolverMultistepScheduler) pipe.scheduler = SchedulerClass.from_config(pipe.scheduler.config)
# ── Seed handling ────────────────────────────────────────────────────── import random used_seed = seed if seed != -1 else random.randint(0, 2**32 - 1) generator = torch.Generator(device="cpu").manual_seed(used_seed)
# ── Step progress callback ───────────────────────────────────────────── # Build a callback compatible with both old and new diffusers APIs total_steps = num_inference_steps
def _legacy_callback(step: int, timestep, latents): if step_callback: step_callback(step + 1, total_steps)
def _new_callback(pipeline, step: int, timestep, callback_kwargs: dict): if step_callback: step_callback(step + 1, total_steps) return callback_kwargs
import diffusers diffusers_version = tuple(int(x) for x in diffusers.__version__.split(".")[:2])
call_kwargs = dict( prompt=prompt, negative_prompt=negative_prompt, width=width, height=height, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator, )
if diffusers_version >= (0, 25): # New API: callback_on_step_end call_kwargs["callback_on_step_end"] = _new_callback else: # Legacy API call_kwargs["callback"] = _legacy_callback call_kwargs["callback_steps"] = 1
# ── Run inference ────────────────────────────────────────────────────── with torch.inference_mode(): result = pipe(**call_kwargs)
image = result.images[0] return image, used_seed
# Singleton used throughout the applicationpipeline_mgr = PipelineManager()1234567891011121314151617181920# Core APIfastapi>=0.111.0uvicorn[standard]>=0.29.0python-multipart>=0.0.9
# Hugging Face / Diffusers (CPU-optimised)diffusers>=0.27.0transformers>=4.40.0accelerate>=0.30.0safetensors>=0.4.3
# PyTorch CPU-only (install via pip before running this file — see README)# pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
# UtilitiesPillow>=10.3.0python-dotenv>=1.0.1pydantic>=2.7.0pydantic-settings>=2.2.1aiofiles>=23.2.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""routes/generate.py — Image generation job submission.
POST /generate → Validates the request, creates a queued job, enqueues it for the background worker, and immediately returns the job_id. The caller then polls GET /jobs/{job_id} for progress/status."""from __future__ import annotations
import logging
from fastapi import APIRouter, HTTPException
from config import settingsfrom job_store import job_storefrom pipeline_manager import pipeline_mgrfrom schemas import GenerateRequest, JobSubmittedResponse, JobStatusfrom worker import enqueue, queue_position, queue_size
logger = logging.getLogger("routes.generate")router = APIRouter(tags=["Generation"])
@router.post( "/generate", response_model=JobSubmittedResponse, status_code=202, # 202 Accepted — work is deferred summary="Submit an image generation job", description=( "Validates the prompt and parameters, creates a queued job, " "and returns a `job_id` immediately. " "Poll `GET /jobs/{job_id}` to track progress. " "Download the result with `GET /jobs/{job_id}/download` once `status == 'completed'`." ),)async def submit_generate(body: GenerateRequest) -> JobSubmittedResponse: # Guard: pipeline must exist (or be auto-loaded at startup) if not pipeline_mgr.is_loaded and not pipeline_mgr.is_loading: # Try to trigger a load if the operator hasn't done so logger.warning( "Pipeline not loaded — prompting load of default model '%s'.", settings.model_id, ) # We don't block here; the worker will call load() itself before processing # But we warn the user so they know latency is higher for the first job.
params = { "width": body.width, "height": body.height, "num_inference_steps": body.num_inference_steps, "guidance_scale": body.guidance_scale, "seed": body.seed, "scheduler": body.scheduler.value, }
# Create and enqueue job = job_store.create( prompt=body.prompt, negative_prompt=body.negative_prompt, params=params, model_id=pipeline_mgr.current_model_id or settings.model_id, ) enqueue(job.job_id)
position = queue_position(job.job_id) msg = ( f"Job queued at position {position}." if position > 1 else "Job is next in queue and will start immediately." ) if not pipeline_mgr.is_loaded: msg += " Note: the model pipeline is not yet loaded — first job will include model load time."
return JobSubmittedResponse( job_id=job.job_id, status=JobStatus.QUEUED, created_at=job.created_at, queue_position=position, message=msg, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""routes/health.py — Health check and model management endpoints.
GET /health → system status and pipeline infoGET /models → list of well-known CPU-friendly model IDsPOST /models/load → hot-swap the loaded pipeline"""from __future__ import annotations
import loggingimport threading
from fastapi import APIRouter, BackgroundTasks, HTTPException
from config import settingsfrom job_store import job_storefrom pipeline_manager import pipeline_mgrfrom schemas import HealthResponse, LoadModelRequest, LoadModelResponsefrom worker import queue_size
logger = logging.getLogger("routes.health")router = APIRouter(tags=["System"])
# ── Health ────────────────────────────────────────────────────────────────────
@router.get( "/health", response_model=HealthResponse, summary="Service health and pipeline status",)async def health() -> HealthResponse: counts = job_store.counts_by_status() return HealthResponse( status="ok" if pipeline_mgr.is_loaded else ("loading" if pipeline_mgr.is_loading else "idle"), model_id=pipeline_mgr.current_model_id, pipeline_loaded=pipeline_mgr.is_loaded, loading=pipeline_mgr.is_loading, queue_size=queue_size(), jobs_total=job_store.total, jobs_by_status=counts, cpu_threads=settings.cpu_threads or (__import__("os").cpu_count() or 4), outputs_dir=settings.outputs_dir, )
# ── Model catalogue ────────────────────────────────────────────────────────────
_KNOWN_MODELS = [ { "model_id": "nota-ai/bk-sdm-small", "label": "BK-SDM Small (recommended for CPU)", "size_gb": 0.5, "notes": "Very fast on CPU. ~60-120s per 512×512 image at 20 steps.", }, { "model_id": "runwayml/stable-diffusion-v1-5", "label": "Stable Diffusion v1.5", "size_gb": 4.0, "notes": "Standard quality. ~150-300s per 512×512 on CPU.", }, { "model_id": "stabilityai/stable-diffusion-2-1-base", "label": "Stable Diffusion 2.1 Base", "size_gb": 5.2, "notes": "Higher quality. ~200-400s per 512×512 on CPU.", }, { "model_id": "CompVis/stable-diffusion-v1-4", "label": "Stable Diffusion v1.4 (original)", "size_gb": 4.0, "notes": "Historical baseline. SD v1.5 is preferred.", },]
@router.get( "/models", summary="List supported CPU-friendly model IDs",)async def list_models() -> dict: return { "current_model": pipeline_mgr.current_model_id, "models": _KNOWN_MODELS, }
# ── Hot-swap model ─────────────────────────────────────────────────────────────
@router.post( "/models/load", response_model=LoadModelResponse, summary="Load (or hot-swap) a Hugging Face model",)async def load_model(body: LoadModelRequest, background_tasks: BackgroundTasks) -> LoadModelResponse: if pipeline_mgr.is_loading: raise HTTPException(status_code=409, detail="A model is already loading. Try again shortly.")
def _load(): try: pipeline_mgr.load(body.model_id) except Exception as exc: logger.exception("Background model load failed: %s", exc)
background_tasks.add_task(_load)
return LoadModelResponse( ok=True, model_id=body.model_id, message=f"Loading '{body.model_id}' in the background. Poll GET /health to check status.", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""routes/jobs.py — Job lifecycle management.
GET /jobs → list all jobs (filterable)GET /jobs/{job_id} → single job status / progressGET /jobs/{job_id}/download → download the generated PNGDELETE /jobs/{job_id} → cancel or delete a job and its image"""from __future__ import annotations
import loggingimport mimetypesimport osfrom typing import Optional
from fastapi import APIRouter, HTTPException, Queryfrom fastapi.responses import FileResponse
from config import settingsfrom job_store import job_storefrom schemas import DeleteJobResponse, Job, JobListResponse, JobStatus
logger = logging.getLogger("routes.jobs")router = APIRouter(prefix="/jobs", tags=["Jobs"])
# ── List jobs ─────────────────────────────────────────────────────────────────
@router.get( "", response_model=JobListResponse, summary="List all jobs",)async def list_jobs( status: Optional[JobStatus] = Query(None, description="Filter by job status."), limit: int = Query(50, ge=1, le=200), offset: int = Query(0, ge=0),) -> JobListResponse: jobs = job_store.list_all(status_filter=status, limit=limit, offset=offset) counts = job_store.counts_by_status() return JobListResponse( jobs=jobs, total=job_store.total, queued=counts.get("queued", 0), processing=counts.get("processing", 0), completed=counts.get("completed", 0), failed=counts.get("failed", 0), )
# ── Single job status ─────────────────────────────────────────────────────────
@router.get( "/{job_id}", response_model=Job, summary="Get job status and progress", description=( "Poll this endpoint to track a generation job. " "When `status == 'completed'` the `download_url` field is populated." ),)async def get_job(job_id: str) -> Job: job = job_store.get(job_id) if not job: raise HTTPException(status_code=404, detail=f"Job '{job_id}' not found.") return job
# ── Download generated image ──────────────────────────────────────────────────
@router.get( "/{job_id}/download", summary="Download the generated image", description=( "Returns the PNG image as a file attachment. " "Only available when `status == 'completed'`." ), responses={ 200: {"content": {"image/png": {}}}, 202: {"description": "Job is still processing."}, 404: {"description": "Job not found or image missing."}, },)async def download_image(job_id: str): job = job_store.get(job_id) if not job: raise HTTPException(status_code=404, detail=f"Job '{job_id}' not found.")
if job.status == JobStatus.QUEUED: raise HTTPException(status_code=202, detail="Job is queued and has not started yet.")
if job.status == JobStatus.PROCESSING: raise HTTPException( status_code=202, detail=f"Job is still processing ({job.progress}% complete).", )
if job.status == JobStatus.FAILED: raise HTTPException(status_code=422, detail=f"Job failed: {job.error}")
if not job.image_filename: raise HTTPException(status_code=500, detail="Job completed but image filename is missing.")
image_path = os.path.join(settings.outputs_dir, job.image_filename) if not os.path.isfile(image_path): raise HTTPException( status_code=404, detail=f"Image file '{job.image_filename}' not found on disk. It may have been deleted.", )
return FileResponse( path=image_path, media_type="image/png", filename=job.image_filename, headers={"Content-Disposition": f'attachment; filename="{job.image_filename}"'}, )
# ── Delete job ─────────────────────────────────────────────────────────────────
@router.delete( "/{job_id}", response_model=DeleteJobResponse, summary="Delete a job and its generated image", description=( "Removes the job record from memory and deletes the PNG from disk " "(if it exists). Queued or processing jobs are also removed — " "the worker will skip orphaned job IDs gracefully." ),)async def delete_job(job_id: str) -> DeleteJobResponse: job = job_store.get(job_id) if not job: raise HTTPException(status_code=404, detail=f"Job '{job_id}' not found.")
# Delete image file from disk image_deleted = False if job.image_filename: image_path = os.path.join(settings.outputs_dir, job.image_filename) if os.path.isfile(image_path): try: os.remove(image_path) image_deleted = True logger.info("Deleted image: %s", image_path) except OSError as exc: logger.warning("Could not delete image %s: %s", image_path, exc)
# Remove job record job_store.delete(job_id) logger.info("Deleted job record: %s", job_id)
return DeleteJobResponse( ok=True, job_id=job_id, image_deleted=image_deleted, message=( f"Job {job_id} deleted." + (" Image file removed from disk." if image_deleted else "") ), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""schemas.py — All Pydantic models for request bodies and API responses."""from __future__ import annotationsfrom enum import Enumfrom typing import Any, Dict, Optionalfrom datetime import datetimefrom pydantic import BaseModel, Field, model_validator
# ── Enums ─────────────────────────────────────────────────────────────────────
class JobStatus(str, Enum): QUEUED = "queued" PROCESSING = "processing" COMPLETED = "completed" FAILED = "failed"
class Scheduler(str, Enum): DPM_PLUS_PLUS = "dpm++" # DPMSolverMultistepScheduler — best for CPU (fast convergence) EULER_A = "euler_a" # EulerAncestralDiscreteScheduler EULER = "euler" # EulerDiscreteScheduler PNDM = "pndm" # PNDMScheduler
# ── Request bodies ─────────────────────────────────────────────────────────────
class GenerateRequest(BaseModel): prompt: str = Field( ..., min_length=1, max_length=1500, description="Text prompt describing the image to generate.", examples=["a photorealistic cat sitting on a wooden table, soft light"], ) negative_prompt: str = Field( "blurry, ugly, low quality, distorted, watermark, text, nsfw", max_length=1000, description="Things to exclude from the image.", ) width: int = Field(512, ge=256, le=768, multiple_of=8, description="Image width (pixels, multiple of 8).") height: int = Field(512, ge=256, le=768, multiple_of=8, description="Image height (pixels, multiple of 8).") num_inference_steps: int = Field(20, ge=1, le=50, description="Denoising steps. 15–20 is optimal on CPU.") guidance_scale: float = Field(7.5, ge=1.0, le=20.0, description="Classifier-free guidance scale.") seed: int = Field(-1, ge=-1, description="RNG seed. -1 = random each time.") scheduler: Scheduler = Field(Scheduler.DPM_PLUS_PLUS, description="Noise scheduler algorithm.")
@model_validator(mode="after") def clamp_to_config(self) -> "GenerateRequest": from config import settings self.width = min(self.width, settings.max_width) self.height = min(self.height, settings.max_height) self.num_inference_steps = min(self.num_inference_steps, settings.max_steps) return self
class LoadModelRequest(BaseModel): model_id: str = Field( ..., description="Hugging Face model repo ID, e.g. 'runwayml/stable-diffusion-v1-5'.", )
# ── Job model ─────────────────────────────────────────────────────────────────
class Job(BaseModel): job_id: str status: JobStatus prompt: str negative_prompt: str params: Dict[str, Any]
created_at: datetime started_at: Optional[datetime] = None completed_at: Optional[datetime] = None
progress: int = 0 # 0–100 current_step: int = 0 total_steps: int = 0
image_filename: Optional[str] = None # filename inside outputs/ download_url: Optional[str] = None # relative URL duration_seconds: Optional[float] = None
error: Optional[str] = None
model_id: Optional[str] = None # model used for this job
# ── Response wrappers ─────────────────────────────────────────────────────────
class JobSubmittedResponse(BaseModel): job_id: str status: JobStatus created_at: datetime queue_position: int message: str
class JobListResponse(BaseModel): jobs: list[Job] total: int queued: int processing: int completed: int failed: int
class DeleteJobResponse(BaseModel): ok: bool job_id: str image_deleted: bool message: str
class HealthResponse(BaseModel): status: str model_id: Optional[str] pipeline_loaded: bool loading: bool queue_size: int jobs_total: int jobs_by_status: Dict[str, int] cpu_threads: int outputs_dir: str
class LoadModelResponse(BaseModel): ok: bool model_id: str message: str1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/usr/bin/env bash# start.sh — Quick-start script for the HF CPU Image Generation APIset -e
VENV_DIR=".venv"
echo ""echo "═══════════════════════════════════════════════════════════════"echo " HF CPU Image Generation API — Setup & Start"echo "═══════════════════════════════════════════════════════════════"echo ""
# ── 1. Create virtualenv if needed ────────────────────────────────────────────if [ ! -d "$VENV_DIR" ]; then echo "→ Creating Python virtualenv in $VENV_DIR ..." python3 -m venv "$VENV_DIR"fi
source "$VENV_DIR/bin/activate"
# ── 2. Install PyTorch (CPU-only wheel) ───────────────────────────────────────if ! python -c "import torch" 2>/dev/null; then echo "→ Installing PyTorch (CPU-only) ..." pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu -qfi
# ── 3. Install other dependencies ─────────────────────────────────────────────echo "→ Installing dependencies from requirements.txt ..."pip install -r requirements.txt -q
# ── 4. Copy .env if not present ───────────────────────────────────────────────if [ ! -f ".env" ]; then echo "→ Creating .env from .env.example ..." cp .env.example .envfi
# ── 5. Start the API ──────────────────────────────────────────────────────────echo ""echo "→ Starting API on http://0.0.0.0:8000"echo " Swagger UI: http://localhost:8000/docs"echo " API health: http://localhost:8000/health"echo ""
python -m uvicorn main:app --host 0.0.0.0 --port 8000 --workers 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""worker.py — Single background thread that processes generation jobs one at a time.
Architecture: ┌────────────────────┐ queue.put(job_id) ┌──────────────────────┐ │ FastAPI endpoint │ ────────────────────────────► │ _job_queue (Queue) │ │ POST /generate │ └──────────┬───────────┘ └────────────────────┘ │ .get() ▼ ┌──────────────────────┐ │ worker_loop() │ │ (daemon thread) │ │ runs _process_job() │ └──────────────────────┘
Only one job runs at a time — CPU inference is single-threaded anyway."""from __future__ import annotations
import loggingimport osimport queueimport threadingfrom datetime import datetime, timezonefrom typing import List
logger = logging.getLogger("worker")
# Internal FIFO queue — contains job_ids as strings_job_queue: queue.Queue[str] = queue.Queue()
# Lock used to inspect queue contents safely_queue_lock = threading.Lock()
# Ordered list of pending job IDs (mirrors the queue for position lookups)_pending: List[str] = []_pending_lock = threading.Lock()
# ── Public helpers (called from FastAPI routes) ────────────────────────────────
def enqueue(job_id: str) -> None: """Add a job to the processing queue.""" with _pending_lock: _pending.append(job_id) _job_queue.put(job_id) logger.info("Enqueued job %s (queue size: %d)", job_id, _job_queue.qsize())
def queue_position(job_id: str) -> int: """Return the 1-based position of job_id in the pending queue (0 if not found).""" with _pending_lock: try: return _pending.index(job_id) + 1 except ValueError: return 0
def queue_size() -> int: """Number of jobs still waiting (does not include the currently running job).""" return _job_queue.qsize()
# ── Core processing ────────────────────────────────────────────────────────────
def _process_job(job_id: str) -> None: """Generate an image for one job. All state mutations go through job_store.""" from config import settings from job_store import job_store from pipeline_manager import pipeline_mgr from schemas import JobStatus
job = job_store.get(job_id) if not job: logger.warning("Job %s not found in store — skipping.", job_id) return
# Mark as processing job_store.update( job_id, status=JobStatus.PROCESSING, started_at=datetime.now(timezone.utc), progress=0, ) logger.info("Processing job %s prompt=%r", job_id, job.prompt[:60])
try: # ── Ensure pipeline is loaded ────────────────────────────────────────── if not pipeline_mgr.is_loaded: logger.info("Pipeline not loaded — loading now (job %s will wait).", job_id) pipeline_mgr.load()
p = job.params
# ── Step-progress callback ───────────────────────────────────────────── def on_step(step: int, total: int) -> None: pct = int(step / total * 95) # reserve last 5 % for save job_store.update(job_id, progress=pct, current_step=step, total_steps=total)
# ── Inference ───────────────────────────────────────────────────────── image, used_seed = pipeline_mgr.generate( prompt=job.prompt, negative_prompt=job.negative_prompt, width=p.get("width", settings.default_width), height=p.get("height", settings.default_height), num_inference_steps=p.get("num_inference_steps", settings.default_steps), guidance_scale=p.get("guidance_scale", settings.default_guidance_scale), seed=p.get("seed", -1), scheduler_name=p.get("scheduler", "dpm++"), step_callback=on_step, )
# ── Save image ──────────────────────────────────────────────────────── job_store.update(job_id, progress=97)
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") filename = f"{timestamp}_{job_id[:8]}_{used_seed}.png" abs_path = os.path.join(settings.outputs_dir, filename) image.save(abs_path, format="PNG", optimize=False)
# ── Compute duration ─────────────────────────────────────────────────── now = datetime.now(timezone.utc) started = job_store.get(job_id).started_at duration = (now - started).total_seconds() if started else None
job_store.update( job_id, status=JobStatus.COMPLETED, completed_at=now, progress=100, image_filename=filename, download_url=f"/jobs/{job_id}/download", duration_seconds=round(duration, 2) if duration else None, )
logger.info( "Job %s completed in %.1f s → %s", job_id, duration or 0, filename, )
except Exception as exc: logger.exception("Job %s failed: %s", job_id, exc) job_store.update( job_id, status=JobStatus.FAILED, completed_at=datetime.now(timezone.utc), error=str(exc), progress=0, )
# ── Worker loop (runs in its own daemon thread) ────────────────────────────────
def worker_loop() -> None: """Infinite loop: pull job IDs from the queue and process them.""" logger.info("Worker thread started.") while True: job_id = _job_queue.get() # blocks until a job arrives with _pending_lock: try: _pending.remove(job_id) except ValueError: pass try: _process_job(job_id) except Exception as exc: # Catch-all safety net — the loop must never crash logger.exception("Unhandled error in worker for job %s: %s", job_id, exc) finally: _job_queue.task_done()
def start_worker() -> threading.Thread: """Spawn and return the daemon worker thread. Call once at application startup.""" t = threading.Thread(target=worker_loop, name="image-worker", daemon=True) t.start() return t.env.exampleAdded+48
README.md+340-10
config.pyAdded+64
job_store.pyAdded+99
main.pyAdded+131
pipeline_manager.pyAdded+199
requirements.txtAdded+20
routes/__init__.pyAdded
routes/generate.pyAdded+81
routes/health.pyAdded+111
routes/jobs.pyAdded+160
schemas.pyAdded+132
start.shAdded+44
worker.pyAdded+179