"doc/vscode:/vscode.git/clone" did not exist on "4a4f537e6e10ac4ab1906d63fe1a193021aea855"
main.py 13 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
import re
Timothy J. Baek's avatar
Timothy J. Baek committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import requests
from fastapi import (
    FastAPI,
    Request,
    Depends,
    HTTPException,
    status,
    UploadFile,
    File,
    Form,
)
from fastapi.middleware.cors import CORSMiddleware
from faster_whisper import WhisperModel

from constants import ERROR_MESSAGES
from utils.utils import (
    get_current_user,
    get_admin_user,
)
Timothy J. Baek's avatar
Timothy J. Baek committed
21
22

from apps.images.utils.comfyui import ImageGenerationPayload, comfyui_generate_image
Timothy J. Baek's avatar
Timothy J. Baek committed
23
24
25
from utils.misc import calculate_sha256
from typing import Optional
from pydantic import BaseModel
Timothy J. Baek's avatar
Timothy J. Baek committed
26
27
28
29
from pathlib import Path
import uuid
import base64
import json
30
import logging
Timothy J. Baek's avatar
Timothy J. Baek committed
31

Self Denial's avatar
Self Denial committed
32
33
34
from config import (
    SRC_LOG_LEVELS,
    CACHE_DIR,
Self Denial's avatar
Self Denial committed
35
    ENABLE_IMAGE_GENERATION,
Self Denial's avatar
Self Denial committed
36
37
    AUTOMATIC1111_BASE_URL,
    COMFYUI_BASE_URL,
38
39
    IMAGES_OPENAI_API_BASE_URL,
    IMAGES_OPENAI_API_KEY,
Self Denial's avatar
Self Denial committed
40
)
Timothy J. Baek's avatar
Timothy J. Baek committed
41
42


43
44
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["IMAGES"])
Timothy J. Baek's avatar
Timothy J. Baek committed
45
46
47

IMAGE_CACHE_DIR = Path(CACHE_DIR).joinpath("./image/generations/")
IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
Timothy J. Baek's avatar
Timothy J. Baek committed
48
49
50
51
52
53
54
55
56
57

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

Timothy J. Baek's avatar
Timothy J. Baek committed
58
app.state.ENGINE = ""
Self Denial's avatar
Self Denial committed
59
app.state.ENABLED = ENABLE_IMAGE_GENERATION
Timothy J. Baek's avatar
Timothy J. Baek committed
60

61
62
app.state.OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
app.state.OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
Timothy J. Baek's avatar
Timothy J. Baek committed
63

Timothy J. Baek's avatar
Timothy J. Baek committed
64
65
66
app.state.MODEL = ""


Timothy J. Baek's avatar
Timothy J. Baek committed
67
app.state.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
Timothy J. Baek's avatar
Timothy J. Baek committed
68
69
app.state.COMFYUI_BASE_URL = COMFYUI_BASE_URL

Timothy J. Baek's avatar
Timothy J. Baek committed
70

Timothy J. Baek's avatar
Timothy J. Baek committed
71
app.state.IMAGE_SIZE = "512x512"
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
72
app.state.IMAGE_STEPS = 50
Timothy J. Baek's avatar
Timothy J. Baek committed
73
74


Timothy J. Baek's avatar
Timothy J. Baek committed
75
76
77
@app.get("/config")
async def get_config(request: Request, user=Depends(get_admin_user)):
    return {"engine": app.state.ENGINE, "enabled": app.state.ENABLED}
Timothy J. Baek's avatar
Timothy J. Baek committed
78
79


Timothy J. Baek's avatar
Timothy J. Baek committed
80
81
82
83
84
85
86
87
88
89
class ConfigUpdateForm(BaseModel):
    engine: str
    enabled: bool


@app.post("/config/update")
async def update_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
    app.state.ENGINE = form_data.engine
    app.state.ENABLED = form_data.enabled
    return {"engine": app.state.ENGINE, "enabled": app.state.ENABLED}
Timothy J. Baek's avatar
Timothy J. Baek committed
90
91


Timothy J. Baek's avatar
Timothy J. Baek committed
92
93
94
class EngineUrlUpdateForm(BaseModel):
    AUTOMATIC1111_BASE_URL: Optional[str] = None
    COMFYUI_BASE_URL: Optional[str] = None
Timothy J. Baek's avatar
Timothy J. Baek committed
95
96
97


@app.get("/url")
Timothy J. Baek's avatar
Timothy J. Baek committed
98
99
100
101
102
async def get_engine_url(user=Depends(get_admin_user)):
    return {
        "AUTOMATIC1111_BASE_URL": app.state.AUTOMATIC1111_BASE_URL,
        "COMFYUI_BASE_URL": app.state.COMFYUI_BASE_URL,
    }
Timothy J. Baek's avatar
Timothy J. Baek committed
103
104
105


@app.post("/url/update")
Timothy J. Baek's avatar
Timothy J. Baek committed
106
107
async def update_engine_url(
    form_data: EngineUrlUpdateForm, user=Depends(get_admin_user)
Timothy J. Baek's avatar
Timothy J. Baek committed
108
):
Timothy J. Baek's avatar
Timothy J. Baek committed
109

Timothy J. Baek's avatar
Timothy J. Baek committed
110
    if form_data.AUTOMATIC1111_BASE_URL == None:
Timothy J. Baek's avatar
Timothy J. Baek committed
111
112
        app.state.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
    else:
Timothy J. Baek's avatar
Timothy J. Baek committed
113
        url = form_data.AUTOMATIC1111_BASE_URL.strip("/")
Timothy J. Baek's avatar
Timothy J. Baek committed
114
115
116
117
118
        try:
            r = requests.head(url)
            app.state.AUTOMATIC1111_BASE_URL = url
        except Exception as e:
            raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
Timothy J. Baek's avatar
Timothy J. Baek committed
119

Timothy J. Baek's avatar
Timothy J. Baek committed
120
121
122
123
    if form_data.COMFYUI_BASE_URL == None:
        app.state.COMFYUI_BASE_URL = COMFYUI_BASE_URL
    else:
        url = form_data.COMFYUI_BASE_URL.strip("/")
Timothy J. Baek's avatar
Timothy J. Baek committed
124
125
126
127
128
129

        try:
            r = requests.head(url)
            app.state.COMFYUI_BASE_URL = url
        except Exception as e:
            raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
Timothy J. Baek's avatar
Timothy J. Baek committed
130

Timothy J. Baek's avatar
Timothy J. Baek committed
131
132
    return {
        "AUTOMATIC1111_BASE_URL": app.state.AUTOMATIC1111_BASE_URL,
Timothy J. Baek's avatar
Timothy J. Baek committed
133
        "COMFYUI_BASE_URL": app.state.COMFYUI_BASE_URL,
Timothy J. Baek's avatar
Timothy J. Baek committed
134
135
        "status": True,
    }
Timothy J. Baek's avatar
Timothy J. Baek committed
136
137


138
139
class OpenAIConfigUpdateForm(BaseModel):
    url: str
Timothy J. Baek's avatar
Timothy J. Baek committed
140
141
142
    key: str


143
144
145
146
147
148
@app.get("/openai/config")
async def get_openai_config(user=Depends(get_admin_user)):
    return {
        "OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL,
        "OPENAI_API_KEY": app.state.OPENAI_API_KEY,
    }
Timothy J. Baek's avatar
Timothy J. Baek committed
149
150


151
152
153
@app.post("/openai/config/update")
async def update_openai_config(
    form_data: OpenAIConfigUpdateForm, user=Depends(get_admin_user)
Timothy J. Baek's avatar
Timothy J. Baek committed
154
155
156
157
):
    if form_data.key == "":
        raise HTTPException(status_code=400, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)

158
    app.state.OPENAI_API_BASE_URL = form_data.url
Timothy J. Baek's avatar
Timothy J. Baek committed
159
    app.state.OPENAI_API_KEY = form_data.key
160

Timothy J. Baek's avatar
Timothy J. Baek committed
161
162
    return {
        "status": True,
163
164
        "OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL,
        "OPENAI_API_KEY": app.state.OPENAI_API_KEY,
Timothy J. Baek's avatar
Timothy J. Baek committed
165
166
167
    }


Timothy J. Baek's avatar
Timothy J. Baek committed
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
class ImageSizeUpdateForm(BaseModel):
    size: str


@app.get("/size")
async def get_image_size(user=Depends(get_admin_user)):
    return {"IMAGE_SIZE": app.state.IMAGE_SIZE}


@app.post("/size/update")
async def update_image_size(
    form_data: ImageSizeUpdateForm, user=Depends(get_admin_user)
):
    pattern = r"^\d+x\d+$"  # Regular expression pattern
    if re.match(pattern, form_data.size):
        app.state.IMAGE_SIZE = form_data.size
        return {
            "IMAGE_SIZE": app.state.IMAGE_SIZE,
            "status": True,
        }
    else:
        raise HTTPException(
            status_code=400,
            detail=ERROR_MESSAGES.INCORRECT_FORMAT("  (e.g., 512x512)."),
        )
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
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

class ImageStepsUpdateForm(BaseModel):
    steps: int


@app.get("/steps")
async def get_image_size(user=Depends(get_admin_user)):
    return {"IMAGE_STEPS": app.state.IMAGE_STEPS}


@app.post("/steps/update")
async def update_image_size(
    form_data: ImageStepsUpdateForm, user=Depends(get_admin_user)
):
    if form_data.steps >= 0:
        app.state.IMAGE_STEPS = form_data.steps
        return {
            "IMAGE_STEPS": app.state.IMAGE_STEPS,
            "status": True,
        }
    else:
        raise HTTPException(
            status_code=400,
            detail=ERROR_MESSAGES.INCORRECT_FORMAT("  (e.g., 50)."),
        )
Timothy J. Baek's avatar
Timothy J. Baek committed
219
220


Timothy J. Baek's avatar
Timothy J. Baek committed
221
222
223
@app.get("/models")
def get_models(user=Depends(get_current_user)):
    try:
Timothy J. Baek's avatar
Timothy J. Baek committed
224
225
226
227
228
        if app.state.ENGINE == "openai":
            return [
                {"id": "dall-e-2", "name": "DALL·E 2"},
                {"id": "dall-e-3", "name": "DALL·E 3"},
            ]
Timothy J. Baek's avatar
Timothy J. Baek committed
229
230
231
232
233
234
235
236
237
238
239
240
        elif app.state.ENGINE == "comfyui":

            r = requests.get(url=f"{app.state.COMFYUI_BASE_URL}/object_info")
            info = r.json()

            return list(
                map(
                    lambda model: {"id": model, "name": model},
                    info["CheckpointLoaderSimple"]["input"]["required"]["ckpt_name"][0],
                )
            )

Timothy J. Baek's avatar
Timothy J. Baek committed
241
242
243
244
245
246
247
248
249
250
251
        else:
            r = requests.get(
                url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/sd-models"
            )
            models = r.json()
            return list(
                map(
                    lambda model: {"id": model["title"], "name": model["model_name"]},
                    models,
                )
            )
Timothy J. Baek's avatar
Timothy J. Baek committed
252
    except Exception as e:
253
        app.state.ENABLED = False
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
254
        raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
Timothy J. Baek's avatar
Timothy J. Baek committed
255
256
257
258
259


@app.get("/models/default")
async def get_default_model(user=Depends(get_admin_user)):
    try:
Timothy J. Baek's avatar
Timothy J. Baek committed
260
261
        if app.state.ENGINE == "openai":
            return {"model": app.state.MODEL if app.state.MODEL else "dall-e-2"}
Timothy J. Baek's avatar
Timothy J. Baek committed
262
263
        elif app.state.ENGINE == "comfyui":
            return {"model": app.state.MODEL if app.state.MODEL else ""}
Timothy J. Baek's avatar
Timothy J. Baek committed
264
265
266
267
        else:
            r = requests.get(url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options")
            options = r.json()
            return {"model": options["sd_model_checkpoint"]}
Timothy J. Baek's avatar
Timothy J. Baek committed
268
    except Exception as e:
269
        app.state.ENABLED = False
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
270
        raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
Timothy J. Baek's avatar
Timothy J. Baek committed
271
272
273
274
275
276
277


class UpdateModelForm(BaseModel):
    model: str


def set_model_handler(model: str):
Timothy J. Baek's avatar
Timothy J. Baek committed
278
279
280
    if app.state.ENGINE == "openai":
        app.state.MODEL = model
        return app.state.MODEL
Timothy J. Baek's avatar
Timothy J. Baek committed
281
282
283
    if app.state.ENGINE == "comfyui":
        app.state.MODEL = model
        return app.state.MODEL
Timothy J. Baek's avatar
Timothy J. Baek committed
284
285
286
287
288
289
290
291
292
    else:
        r = requests.get(url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options")
        options = r.json()

        if model != options["sd_model_checkpoint"]:
            options["sd_model_checkpoint"] = model
            r = requests.post(
                url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options", json=options
            )
Timothy J. Baek's avatar
Timothy J. Baek committed
293

Timothy J. Baek's avatar
Timothy J. Baek committed
294
        return options
Timothy J. Baek's avatar
Timothy J. Baek committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308


@app.post("/models/default/update")
def update_default_model(
    form_data: UpdateModelForm,
    user=Depends(get_current_user),
):
    return set_model_handler(form_data.model)


class GenerateImageForm(BaseModel):
    model: Optional[str] = None
    prompt: str
    n: int = 1
Timothy J. Baek's avatar
Timothy J. Baek committed
309
    size: Optional[str] = None
Timothy J. Baek's avatar
Timothy J. Baek committed
310
311
312
    negative_prompt: Optional[str] = None


Timothy J. Baek's avatar
Timothy J. Baek committed
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def save_b64_image(b64_str):
    image_id = str(uuid.uuid4())
    file_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.png")

    try:
        # Split the base64 string to get the actual image data
        img_data = base64.b64decode(b64_str)

        # Write the image data to a file
        with open(file_path, "wb") as f:
            f.write(img_data)

        return image_id
    except Exception as e:
327
        log.error(f"Error saving image: {e}")
Timothy J. Baek's avatar
Timothy J. Baek committed
328
329
330
        return None


Timothy J. Baek's avatar
Timothy J. Baek committed
331
332
333
334
335
336
337
338
339
340
341
342
343
def save_url_image(url):
    image_id = str(uuid.uuid4())
    file_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.png")

    try:
        r = requests.get(url)
        r.raise_for_status()

        with open(file_path, "wb") as image_file:
            image_file.write(r.content)

        return image_id
    except Exception as e:
344
        log.exception(f"Error saving image: {e}")
Timothy J. Baek's avatar
Timothy J. Baek committed
345
346
347
        return None


Timothy J. Baek's avatar
Timothy J. Baek committed
348
349
350
351
352
353
@app.post("/generations")
def generate_image(
    form_data: GenerateImageForm,
    user=Depends(get_current_user),
):

Timothy J. Baek's avatar
Timothy J. Baek committed
354
355
    width, height = tuple(map(int, app.state.IMAGE_SIZE.split("x")))

Timothy J. Baek's avatar
Timothy J. Baek committed
356
    r = None
357
    try:
Timothy J. Baek's avatar
Timothy J. Baek committed
358
        if app.state.ENGINE == "openai":
359

Timothy J. Baek's avatar
Timothy J. Baek committed
360
361
362
            headers = {}
            headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEY}"
            headers["Content-Type"] = "application/json"
363

Timothy J. Baek's avatar
Timothy J. Baek committed
364
365
366
367
            data = {
                "model": app.state.MODEL if app.state.MODEL != "" else "dall-e-2",
                "prompt": form_data.prompt,
                "n": form_data.n,
Timothy J. Baek's avatar
Timothy J. Baek committed
368
                "size": form_data.size if form_data.size else app.state.IMAGE_SIZE,
Timothy J. Baek's avatar
Timothy J. Baek committed
369
370
                "response_format": "b64_json",
            }
371

Timothy J. Baek's avatar
Timothy J. Baek committed
372
            r = requests.post(
Timothy J. Baek's avatar
Timothy J. Baek committed
373
                url=f"{app.state.OPENAI_API_BASE_URL}/images/generations",
Timothy J. Baek's avatar
Timothy J. Baek committed
374
375
376
                json=data,
                headers=headers,
            )
377

Timothy J. Baek's avatar
Timothy J. Baek committed
378
379
            r.raise_for_status()
            res = r.json()
Timothy J. Baek's avatar
Timothy J. Baek committed
380

Timothy J. Baek's avatar
Timothy J. Baek committed
381
382
383
384
385
386
387
388
389
390
391
392
            images = []

            for image in res["data"]:
                image_id = save_b64_image(image["b64_json"])
                images.append({"url": f"/cache/image/generations/{image_id}.png"})
                file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.json")

                with open(file_body_path, "w") as f:
                    json.dump(data, f)

            return images

Timothy J. Baek's avatar
Timothy J. Baek committed
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
        elif app.state.ENGINE == "comfyui":

            data = {
                "prompt": form_data.prompt,
                "width": width,
                "height": height,
                "n": form_data.n,
            }

            if app.state.IMAGE_STEPS != None:
                data["steps"] = app.state.IMAGE_STEPS

            if form_data.negative_prompt != None:
                data["negative_prompt"] = form_data.negative_prompt

            data = ImageGenerationPayload(**data)

            res = comfyui_generate_image(
                app.state.MODEL,
                data,
                user.id,
                app.state.COMFYUI_BASE_URL,
            )
416
            log.debug(f"res: {res}")
Timothy J. Baek's avatar
Timothy J. Baek committed
417
418
419
420
421
422
423
424
425
426
427

            images = []

            for image in res["data"]:
                image_id = save_url_image(image["url"])
                images.append({"url": f"/cache/image/generations/{image_id}.png"})
                file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.json")

                with open(file_body_path, "w") as f:
                    json.dump(data.model_dump(exclude_none=True), f)

428
            log.debug(f"images: {images}")
Timothy J. Baek's avatar
Timothy J. Baek committed
429
            return images
Timothy J. Baek's avatar
Timothy J. Baek committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
        else:
            if form_data.model:
                set_model_handler(form_data.model)

            data = {
                "prompt": form_data.prompt,
                "batch_size": form_data.n,
                "width": width,
                "height": height,
            }

            if app.state.IMAGE_STEPS != None:
                data["steps"] = app.state.IMAGE_STEPS

            if form_data.negative_prompt != None:
                data["negative_prompt"] = form_data.negative_prompt

            r = requests.post(
                url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/txt2img",
                json=data,
            )

            res = r.json()

454
            log.debug(f"res: {res}")
Timothy J. Baek's avatar
Timothy J. Baek committed
455
456
457
458
459
460
461
462
463
464
465
466

            images = []

            for image in res["images"]:
                image_id = save_b64_image(image)
                images.append({"url": f"/cache/image/generations/{image_id}.png"})
                file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.json")

                with open(file_body_path, "w") as f:
                    json.dump({**data, "info": res["info"]}, f)

            return images
467
468

    except Exception as e:
469
470
471
472
473
474
475
        error = e

        if r != None:
            data = r.json()
            if "error" in data:
                error = data["error"]["message"]
        raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error))