File size: 3,850 Bytes
b373569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""
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)