memoryai's picture
Upload folder using huggingface_hub
b373569 verified
"""
FastAPI server for 4K image generation.
"""
import asyncio
import uuid
import time
from pathlib import Path
import torch
from fastapi import FastAPI, BackgroundTasks
from fastapi.responses import FileResponse
from pydantic import BaseModel
import sys
sys.path.insert(0, str(Path(__file__).parent))
from inference import load_flux_pipeline, load_sr_model, generate_4k
app = FastAPI(title="4K Image Generation API")
# Global models (loaded on startup)
flux_pipe = None
sr_stage2 = None
sr_stage3 = None
jobs = {}
OUTPUT_DIR = Path("/home/adminuser/chungcat/outputs/api")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
class GenerateRequest(BaseModel):
prompt: str
resolution: str = "4k" # "1k", "2k", "4k"
steps: int = 28
guidance_scale: float = 3.5
class JobStatus(BaseModel):
job_id: str
status: str # "pending", "processing", "completed", "failed"
resolution: str
elapsed_seconds: float = 0
result_url: str = None
error: str = None
@app.on_event("startup")
async def startup():
global flux_pipe, sr_stage2, sr_stage3
flux_pipe = load_flux_pipeline(
"black-forest-labs/FLUX.1-schnell",
lora_path=Path("/home/adminuser/chungcat/checkpoints/flux_lora/final"),
device="cuda:0",
)
sr_stage2 = load_sr_model(
"/home/adminuser/chungcat/checkpoints/sr_stage2/final/model.pt",
device="cuda:1",
)
sr_stage3 = load_sr_model(
"/home/adminuser/chungcat/checkpoints/sr_stage3/final/model.pt",
device="cuda:1",
)
print("All models loaded!")
def process_job(job_id: str, request: GenerateRequest):
jobs[job_id]["status"] = "processing"
t0 = time.time()
try:
image = generate_4k(
prompt=request.prompt,
flux_pipe=flux_pipe,
sr_stage2=sr_stage2,
sr_stage3=sr_stage3,
output_path=OUTPUT_DIR / job_id,
num_inference_steps=request.steps,
guidance_scale=request.guidance_scale,
)
jobs[job_id]["status"] = "completed"
jobs[job_id]["elapsed_seconds"] = time.time() - t0
stem = request.prompt[:50].replace(" ", "_").replace("/", "_")
res_suffix = request.resolution
jobs[job_id]["result_url"] = f"/result/{job_id}/{stem}_{res_suffix}.png"
except Exception as e:
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
jobs[job_id]["elapsed_seconds"] = time.time() - t0
@app.post("/generate", response_model=JobStatus)
async def generate(request: GenerateRequest, background_tasks: BackgroundTasks):
job_id = str(uuid.uuid4())[:8]
jobs[job_id] = {
"job_id": job_id,
"status": "pending",
"resolution": request.resolution,
"elapsed_seconds": 0,
}
background_tasks.add_task(process_job, job_id, request)
return JobStatus(**jobs[job_id])
@app.get("/status/{job_id}", response_model=JobStatus)
async def get_status(job_id: str):
if job_id not in jobs:
return JobStatus(job_id=job_id, status="not_found", resolution="")
return JobStatus(**jobs[job_id])
@app.get("/result/{job_id}/{filename}")
async def get_result(job_id: str, filename: str):
file_path = OUTPUT_DIR / job_id / filename
if not file_path.exists():
return {"error": "File not found"}
return FileResponse(file_path, media_type="image/png")
@app.get("/health")
async def health():
return {
"status": "ok",
"gpu_0": torch.cuda.get_device_name(0),
"gpu_1": torch.cuda.get_device_name(1),
"gpu_0_memory_used": f"{torch.cuda.memory_allocated(0) / 1024**3:.1f} GB",
"gpu_1_memory_used": f"{torch.cuda.memory_allocated(1) / 1024**3:.1f} GB",
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)