File size: 7,047 Bytes
2cc5994
7fb308a
2cc5994
 
7fb308a
 
 
322b854
1703ae8
7a45985
7fb308a
2cc5994
7fb308a
 
9811fff
ff1da03
7fb308a
f96382c
7fb308a
8ddc590
322b854
2cc5994
7fb308a
8ddc590
7fb308a
 
 
 
 
 
8ddc590
 
7fb308a
 
 
 
2578934
7fb308a
 
 
2cc5994
7fb308a
2cc5994
7fb308a
8ddc590
2cc5994
 
7fb308a
 
2cc5994
2578934
f96382c
2578934
 
 
f96382c
 
2578934
 
 
7fb308a
8ddc590
7fb308a
2578934
7fb308a
 
8ddc590
a30b23b
2578934
8ddc590
 
7fb308a
 
2cc5994
7fb308a
 
8ddc590
a45e639
2cc5994
7fb308a
 
 
 
 
2cc5994
 
2578934
c2b6ac4
a30b23b
2cc5994
 
7fb308a
2cc5994
7fb308a
 
 
 
 
2cc5994
1703ae8
2cc5994
7fb308a
 
 
8ddc590
2cc5994
1703ae8
 
a30b23b
1703ae8
 
 
 
c2b6ac4
2cc5994
7fb308a
f96382c
7fb308a
0b3edc8
 
3579187
2cc5994
7fb308a
2cc5994
8ddc590
f96382c
2cc5994
f96382c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cc5994
 
 
7fb308a
2578934
7fb308a
8ddc590
7fb308a
8ddc590
7fb308a
 
f96382c
 
 
 
 
7fb308a
 
8ddc590
 
7fb308a
 
f96382c
7fb308a
8ddc590
f96382c
 
7fb308a
 
 
8ddc590
2578934
7fb308a
 
8ddc590
7fb308a
8ddc590
 
7fb308a
 
 
8ddc590
f96382c
 
8ddc590
2cc5994
7fb308a
 
2cc5994
 
0b3edc8
 
2cc5994
7fb308a
f96382c
7fb308a
0b3edc8
322b854
 
8ddc590
 
 
4cb20ce
322b854
7fb308a
 
 
 
 
 
8ddc590
7fb308a
 
a902076
f96382c
9541138
7fb308a
 
8ddc590
 
 
 
 
 
 
 
 
2cc5994
7fb308a
 
2cc5994
3579187
7fb308a
 
 
83180c7
a45e639
7fb308a
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import io
import os
import base64
import asyncio
import random
from concurrent.futures import ThreadPoolExecutor

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse

from PIL import Image
import torch
from diffusers import DiffusionPipeline


# -------------------------------------------------------------
# HuggingFace Token
# -------------------------------------------------------------
HF_TOKEN = os.getenv("HF_TOKEN")


# -------------------------------------------------------------
# Model Settings
# -------------------------------------------------------------
MODEL_REPO = "stabilityai/sdxl-turbo"

device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if torch.cuda.is_available() else torch.float32

print(f"Loading {MODEL_REPO} on {device}...")

pipe = DiffusionPipeline.from_pretrained(
    MODEL_REPO,
    torch_dtype=dtype,
    use_safetensors=True,
    token=HF_TOKEN if HF_TOKEN else None,
)

pipe.to(device)

if device == "cpu":
    try:
        pipe.enable_model_cpu_offload()
    except:
        pass

print("Model ready.")


# -------------------------------------------------------------
# Automatic Negative Prompt (backend only)
# -------------------------------------------------------------
AUTO_NEGATIVE_PROMPT = (
    "low quality, worst quality, blurry, pixelated, jpeg artifacts, "
    "deformed, distorted, bad anatomy, extra fingers, extra limbs, "
    "missing fingers, watermark, text, logo"
)


# -------------------------------------------------------------
# Core Generation Function
# -------------------------------------------------------------
def generate_image(prompt, seed, width, height, steps, guidance):
    generator = torch.Generator(device=device).manual_seed(seed)

    result = pipe(
        prompt=prompt,
        negative_prompt=AUTO_NEGATIVE_PROMPT,
        guidance_scale=guidance,
        num_inference_steps=steps,
        width=width,
        height=height,
        generator=generator,
    )

    return result.images[0]


# -------------------------------------------------------------
# Async Queue
# -------------------------------------------------------------
executor = ThreadPoolExecutor(max_workers=2)
semaphore = asyncio.Semaphore(2)


async def run_generate(prompt, seed, width, height, steps, guidance):
    async with semaphore:
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            executor,
            generate_image,
            prompt,
            seed,
            width,
            height,
            steps,
            guidance,
        )


# -------------------------------------------------------------
# FastAPI App
# -------------------------------------------------------------
app = FastAPI(title="SDXL Turbo Generator", version="2.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# -------------------------------------------------------------
# UI
# -------------------------------------------------------------
@app.get("/", response_class=HTMLResponse)
def home():
    return """
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8"/>
      <title>SDXL Turbo</title>
      <style>
        body {
          font-family: Arial;
          max-width: 900px;
          margin: 30px auto;
        }
        textarea {
          width: 100%;
          padding: 12px;
          margin-bottom: 10px;
          font-size: 15px;
        }
        button {
          padding: 12px 18px;
          background: black;
          color: white;
          border: none;
          cursor: pointer;
          font-size: 15px;
        }
        #status {
          margin-top: 12px;
        }
        #output {
          margin-top: 20px;
          width: 100%;
          height: 432px;
          border: 1px solid #ddd;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #fafafa;
        }
        #output img {
          max-width: 100%;
          max-height: 100%;
          border-radius: 8px;
        }
      </style>
    </head>
    <body>

      <h1>SDXL Turbo</h1>

      <textarea id="prompt" placeholder="Enter prompt"></textarea>

      <button onclick="send()">Generate</button>

      <div id="status"></div>

      <div id="output">
        <span id="placeholder">Image will appear here</span>
        <img id="result" style="display:none;" />
      </div>

      <script>
        async function send() {
          const prompt = document.getElementById("prompt").value;
          const status = document.getElementById("status");
          const img = document.getElementById("result");
          const placeholder = document.getElementById("placeholder");

          status.innerText = "Generating...";
          img.style.display = "none";
          placeholder.style.display = "block";

          const res = await fetch("/api/generate", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({ prompt })
          });

          const data = await res.json();

          if (data.status !== "success") {
            status.innerText = "Error: " + data.message;
            return;
          }

          img.src = "data:image/png;base64," + data.image_base64;
          img.style.display = "block";
          placeholder.style.display = "none";
          status.innerText = "Done (seed " + data.seed + ")";
        }
      </script>

    </body>
    </html>
    """


# -------------------------------------------------------------
# API Endpoint
# -------------------------------------------------------------
@app.post("/api/generate")
async def api_generate(request: Request):
    try:
        body = await request.json()
        prompt = body.get("prompt", "").strip()
    except:
        return JSONResponse({"status": "error", "message": "Invalid JSON"}, 400)

    if not prompt:
        return JSONResponse({"status": "error", "message": "Prompt required"}, 400)

    width = 768
    height = 432
    steps = 2
    guidance = 0.0
    seed = random.randint(0, 2**31 - 1)

    try:
        img = await run_generate(prompt, seed, width, height, steps, guidance)

        buf = io.BytesIO()
        img.save(buf, format="PNG")
        b64 = base64.b64encode(buf.getvalue()).decode()

        return JSONResponse({
            "status": "success",
            "image_base64": b64,
            "seed": seed,
            "width": width,
            "height": height
        })

    except Exception as e:
        return JSONResponse({"status": "error", "message": str(e)}, 500)


# -------------------------------------------------------------
# Local run
# -------------------------------------------------------------
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)