open-webui/backend/apps/images/main.py

564 lines
18 KiB
Python
Raw Normal View History

2024-02-22 02:12:01 +00:00
from fastapi import (
FastAPI,
Request,
Depends,
HTTPException,
)
from fastapi.middleware.cors import CORSMiddleware
from typing import Optional
from pydantic import BaseModel
2024-03-09 01:38:10 +00:00
from pathlib import Path
import mimetypes
2024-03-09 01:38:10 +00:00
import uuid
import base64
import json
import logging
2024-08-20 22:35:42 +00:00
import re
import requests
from utils.utils import (
get_verified_user,
get_admin_user,
)
from apps.images.utils.comfyui import (
ComfyUIWorkflow,
ComfyUIGenerateImageForm,
comfyui_generate_image,
)
2024-03-09 01:38:10 +00:00
2024-08-20 22:35:42 +00:00
from constants import ERROR_MESSAGES
2024-04-11 05:39:11 +00:00
from config import (
SRC_LOG_LEVELS,
CACHE_DIR,
IMAGE_GENERATION_ENGINE,
ENABLE_IMAGE_GENERATION,
2024-04-11 05:39:11 +00:00
AUTOMATIC1111_BASE_URL,
2024-06-20 06:15:49 +00:00
AUTOMATIC1111_API_AUTH,
2024-04-11 05:39:11 +00:00
COMFYUI_BASE_URL,
COMFYUI_WORKFLOW,
2024-08-20 23:21:03 +00:00
COMFYUI_WORKFLOW_NODES,
2024-04-23 11:14:31 +00:00
IMAGES_OPENAI_API_BASE_URL,
IMAGES_OPENAI_API_KEY,
IMAGE_GENERATION_MODEL,
IMAGE_SIZE,
IMAGE_STEPS,
2024-08-18 21:17:26 +00:00
CORS_ALLOW_ORIGIN,
AppConfig,
2024-04-11 05:39:11 +00:00
)
2024-03-09 01:38:10 +00:00
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["IMAGES"])
2024-03-09 01:38:10 +00:00
IMAGE_CACHE_DIR = Path(CACHE_DIR).joinpath("./image/generations/")
IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
2024-02-22 02:12:01 +00:00
app = FastAPI()
app.add_middleware(
CORSMiddleware,
2024-08-18 21:17:26 +00:00
allow_origins=CORS_ALLOW_ORIGIN,
2024-02-22 02:12:01 +00:00
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.state.config = AppConfig()
2024-03-09 01:38:10 +00:00
app.state.config.ENGINE = IMAGE_GENERATION_ENGINE
app.state.config.ENABLED = ENABLE_IMAGE_GENERATION
2024-04-20 20:15:59 +00:00
app.state.config.OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
app.state.config.OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
2024-03-09 01:38:10 +00:00
app.state.config.MODEL = IMAGE_GENERATION_MODEL
2024-03-09 01:38:10 +00:00
app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
2024-06-20 06:15:49 +00:00
app.state.config.AUTOMATIC1111_API_AUTH = AUTOMATIC1111_API_AUTH
app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
app.state.config.COMFYUI_WORKFLOW = COMFYUI_WORKFLOW
2024-08-20 23:21:03 +00:00
app.state.config.COMFYUI_WORKFLOW_NODES = COMFYUI_WORKFLOW_NODES
2024-03-09 01:38:10 +00:00
app.state.config.IMAGE_SIZE = IMAGE_SIZE
app.state.config.IMAGE_STEPS = IMAGE_STEPS
2024-02-22 02:12:01 +00:00
2024-08-02 20:35:02 +00:00
2024-03-09 01:38:10 +00:00
@app.get("/config")
async def get_config(request: Request, user=Depends(get_admin_user)):
return {
"enabled": app.state.config.ENABLED,
2024-08-20 22:35:42 +00:00
"engine": app.state.config.ENGINE,
"openai": {
"OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
},
"automatic1111": {
"AUTOMATIC1111_BASE_URL": app.state.config.AUTOMATIC1111_BASE_URL,
"AUTOMATIC1111_API_AUTH": app.state.config.AUTOMATIC1111_API_AUTH,
},
"comfyui": {
"COMFYUI_BASE_URL": app.state.config.COMFYUI_BASE_URL,
"COMFYUI_WORKFLOW": app.state.config.COMFYUI_WORKFLOW,
"COMFYUI_WORKFLOW_NODES": app.state.config.COMFYUI_WORKFLOW_NODES,
},
}
2024-02-22 02:12:01 +00:00
2024-08-20 22:35:42 +00:00
class OpenAIConfigForm(BaseModel):
OPENAI_API_BASE_URL: str
OPENAI_API_KEY: str
class Automatic1111ConfigForm(BaseModel):
AUTOMATIC1111_BASE_URL: str
AUTOMATIC1111_API_AUTH: str
class ComfyUIConfigForm(BaseModel):
COMFYUI_BASE_URL: str
COMFYUI_WORKFLOW: str
COMFYUI_WORKFLOW_NODES: list[dict]
class ConfigForm(BaseModel):
2024-03-09 01:38:10 +00:00
enabled: bool
2024-08-20 22:35:42 +00:00
engine: str
openai: OpenAIConfigForm
automatic1111: Automatic1111ConfigForm
comfyui: ComfyUIConfigForm
2024-03-09 01:38:10 +00:00
@app.post("/config/update")
2024-08-20 22:35:42 +00:00
async def update_config(form_data: ConfigForm, user=Depends(get_admin_user)):
app.state.config.ENGINE = form_data.engine
app.state.config.ENABLED = form_data.enabled
2024-02-22 02:12:01 +00:00
2024-08-20 22:35:42 +00:00
app.state.config.OPENAI_API_BASE_URL = form_data.openai.OPENAI_API_BASE_URL
app.state.config.OPENAI_API_KEY = form_data.openai.OPENAI_API_KEY
2024-02-22 02:12:01 +00:00
2024-08-20 22:35:42 +00:00
app.state.config.AUTOMATIC1111_BASE_URL = (
form_data.automatic1111.AUTOMATIC1111_BASE_URL
)
app.state.config.AUTOMATIC1111_API_AUTH = (
form_data.automatic1111.AUTOMATIC1111_API_AUTH
)
2024-02-22 02:12:01 +00:00
2024-08-20 22:35:42 +00:00
app.state.config.COMFYUI_BASE_URL = form_data.comfyui.COMFYUI_BASE_URL
app.state.config.COMFYUI_WORKFLOW = form_data.comfyui.COMFYUI_WORKFLOW
app.state.config.COMFYUI_WORKFLOW_NODES = form_data.comfyui.COMFYUI_WORKFLOW_NODES
2024-02-22 02:12:01 +00:00
2024-03-23 22:38:59 +00:00
return {
2024-08-20 22:35:42 +00:00
"enabled": app.state.config.ENABLED,
"engine": app.state.config.ENGINE,
"openai": {
"OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
},
"automatic1111": {
"AUTOMATIC1111_BASE_URL": app.state.config.AUTOMATIC1111_BASE_URL,
"AUTOMATIC1111_API_AUTH": app.state.config.AUTOMATIC1111_API_AUTH,
},
"comfyui": {
"COMFYUI_BASE_URL": app.state.config.COMFYUI_BASE_URL,
"COMFYUI_WORKFLOW": app.state.config.COMFYUI_WORKFLOW,
"COMFYUI_WORKFLOW_NODES": app.state.config.COMFYUI_WORKFLOW_NODES,
},
2024-03-23 22:38:59 +00:00
}
2024-02-22 02:12:01 +00:00
2024-08-20 22:35:42 +00:00
def get_automatic1111_api_auth():
if app.state.config.AUTOMATIC1111_API_AUTH is None:
return ""
2024-06-20 06:15:49 +00:00
else:
2024-08-20 22:35:42 +00:00
auth1111_byte_string = app.state.config.AUTOMATIC1111_API_AUTH.encode("utf-8")
auth1111_base64_encoded_bytes = base64.b64encode(auth1111_byte_string)
auth1111_base64_encoded_string = auth1111_base64_encoded_bytes.decode("utf-8")
return f"Basic {auth1111_base64_encoded_string}"
2024-02-22 02:12:01 +00:00
2024-08-21 15:27:39 +00:00
@app.get("/config/url/verify")
async def verify_url(user=Depends(get_admin_user)):
if app.state.config.ENGINE == "automatic1111":
try:
r = requests.get(
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
headers={"authorization": get_automatic1111_api_auth()},
)
r.raise_for_status()
return True
except Exception as e:
app.state.config.ENABLED = False
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.INVALID_URL)
elif app.state.config.ENGINE == "comfyui":
try:
r = requests.get(url=f"{app.state.config.COMFYUI_BASE_URL}/object_info")
r.raise_for_status()
return True
except Exception as e:
app.state.config.ENABLED = False
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.INVALID_URL)
else:
return True
2024-08-20 22:35:42 +00:00
def set_image_model(model: str):
app.state.config.MODEL = model
if app.state.config.ENGINE in ["", "automatic1111"]:
api_auth = get_automatic1111_api_auth()
r = requests.get(
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
headers={"authorization": api_auth},
)
options = r.json()
if model != options["sd_model_checkpoint"]:
options["sd_model_checkpoint"] = model
r = requests.post(
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
json=options,
headers={"authorization": api_auth},
)
return app.state.config.MODEL
2024-03-09 01:38:10 +00:00
2024-08-20 22:35:42 +00:00
def get_image_model():
if app.state.config.ENGINE == "openai":
return app.state.config.MODEL if app.state.config.MODEL else "dall-e-2"
elif app.state.config.ENGINE == "comfyui":
return app.state.config.MODEL if app.state.config.MODEL else ""
elif app.state.config.ENGINE == "automatic1111" or app.state.config.ENGINE == "":
try:
r = requests.get(
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
headers={"authorization": get_automatic1111_api_auth()},
)
options = r.json()
return options["sd_model_checkpoint"]
except Exception as e:
app.state.config.ENABLED = False
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
2024-03-09 01:38:10 +00:00
2024-08-20 22:35:42 +00:00
class ImageConfigForm(BaseModel):
2024-08-20 23:21:03 +00:00
MODEL: str
IMAGE_SIZE: str
IMAGE_STEPS: int
2024-03-09 01:38:10 +00:00
2024-04-23 11:14:31 +00:00
2024-08-20 22:35:42 +00:00
@app.get("/image/config")
async def get_image_config(user=Depends(get_admin_user)):
2024-03-09 01:38:10 +00:00
return {
2024-08-20 22:35:42 +00:00
"MODEL": app.state.config.MODEL,
"IMAGE_SIZE": app.state.config.IMAGE_SIZE,
"IMAGE_STEPS": app.state.config.IMAGE_STEPS,
2024-03-09 01:38:10 +00:00
}
2024-08-20 22:35:42 +00:00
@app.post("/image/config/update")
async def update_image_config(form_data: ImageConfigForm, user=Depends(get_admin_user)):
2024-08-20 23:21:03 +00:00
app.state.config.MODEL = form_data.MODEL
2024-02-23 03:32:36 +00:00
2024-08-20 22:35:42 +00:00
pattern = r"^\d+x\d+$"
2024-08-20 23:21:03 +00:00
if re.match(pattern, form_data.IMAGE_SIZE):
app.state.config.IMAGE_SIZE = form_data.IMAGE_SIZE
2024-02-23 03:32:36 +00:00
else:
raise HTTPException(
status_code=400,
detail=ERROR_MESSAGES.INCORRECT_FORMAT(" (e.g., 512x512)."),
)
2024-02-25 02:08:35 +00:00
2024-08-20 23:21:03 +00:00
if form_data.IMAGE_STEPS >= 0:
app.state.config.IMAGE_STEPS = form_data.IMAGE_STEPS
else:
raise HTTPException(
status_code=400,
detail=ERROR_MESSAGES.INCORRECT_FORMAT(" (e.g., 50)."),
)
2024-02-23 03:32:36 +00:00
2024-08-20 22:35:42 +00:00
return {
"MODEL": app.state.config.MODEL,
"IMAGE_SIZE": app.state.config.IMAGE_SIZE,
"IMAGE_STEPS": app.state.config.IMAGE_STEPS,
}
2024-02-23 03:32:36 +00:00
2024-02-22 02:12:01 +00:00
@app.get("/models")
2024-06-27 18:29:59 +00:00
def get_models(user=Depends(get_verified_user)):
2024-02-22 02:12:01 +00:00
try:
if app.state.config.ENGINE == "openai":
2024-03-09 01:38:10 +00:00
return [
{"id": "dall-e-2", "name": "DALL·E 2"},
{"id": "dall-e-3", "name": "DALL·E 3"},
]
elif app.state.config.ENGINE == "comfyui":
2024-08-20 22:35:42 +00:00
# TODO - get models from comfyui
r = requests.get(url=f"{app.state.config.COMFYUI_BASE_URL}/object_info")
2024-03-23 22:38:59 +00:00
info = r.json()
workflow = json.loads(app.state.config.COMFYUI_WORKFLOW)
model_node_id = None
for node in app.state.config.COMFYUI_WORKFLOW_NODES:
if node["type"] == "model":
2024-08-21 22:25:43 +00:00
if node["node_ids"]:
model_node_id = node["node_ids"][0]
break
if model_node_id:
model_list_key = None
print(workflow[model_node_id]["class_type"])
for key in info[workflow[model_node_id]["class_type"]]["input"][
"required"
]:
if "_name" in key:
model_list_key = key
break
if model_list_key:
return list(
map(
lambda model: {"id": model, "name": model},
info[workflow[model_node_id]["class_type"]]["input"][
"required"
][model_list_key][0],
)
)
else:
return list(
map(
lambda model: {"id": model, "name": model},
info["CheckpointLoaderSimple"]["input"]["required"][
"ckpt_name"
][0],
)
2024-03-23 22:38:59 +00:00
)
2024-08-20 22:35:42 +00:00
elif (
app.state.config.ENGINE == "automatic1111" or app.state.config.ENGINE == ""
):
2024-03-09 01:38:10 +00:00
r = requests.get(
2024-06-20 06:15:49 +00:00
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/sd-models",
2024-06-25 15:01:05 +00:00
headers={"authorization": get_automatic1111_api_auth()},
2024-03-09 01:38:10 +00:00
)
models = r.json()
return list(
map(
lambda model: {"id": model["title"], "name": model["model_name"]},
models,
)
)
2024-02-22 02:12:01 +00:00
except Exception as e:
app.state.config.ENABLED = False
2024-02-25 02:08:35 +00:00
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
2024-02-22 02:12:01 +00:00
class GenerateImageForm(BaseModel):
model: Optional[str] = None
prompt: str
2024-03-09 03:54:47 +00:00
size: Optional[str] = None
2024-08-20 22:35:42 +00:00
n: int = 1
2024-02-22 02:12:01 +00:00
negative_prompt: Optional[str] = None
2024-03-09 01:38:10 +00:00
def save_b64_image(b64_str):
try:
2024-05-02 22:59:45 +00:00
image_id = str(uuid.uuid4())
2024-03-09 01:38:10 +00:00
2024-05-02 22:59:45 +00:00
if "," in b64_str:
header, encoded = b64_str.split(",", 1)
mime_type = header.split(";")[0]
2024-04-30 18:52:08 +00:00
2024-05-02 22:59:45 +00:00
img_data = base64.b64decode(encoded)
image_format = mimetypes.guess_extension(mime_type)
image_filename = f"{image_id}{image_format}"
file_path = IMAGE_CACHE_DIR / f"{image_filename}"
with open(file_path, "wb") as f:
f.write(img_data)
return image_filename
else:
image_filename = f"{image_id}.png"
file_path = IMAGE_CACHE_DIR.joinpath(image_filename)
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_filename
2024-04-30 18:52:08 +00:00
2024-03-09 01:38:10 +00:00
except Exception as e:
log.exception(f"Error saving image: {e}")
2024-04-30 18:52:08 +00:00
return None
2024-03-09 01:38:10 +00:00
2024-03-24 00:01:13 +00:00
def save_url_image(url):
image_id = str(uuid.uuid4())
try:
r = requests.get(url)
r.raise_for_status()
if r.headers["content-type"].split("/")[0] == "image":
mime_type = r.headers["content-type"]
image_format = mimetypes.guess_extension(mime_type)
2024-03-24 00:01:13 +00:00
if not image_format:
raise ValueError("Could not determine image type from MIME type")
2024-05-02 22:54:31 +00:00
image_filename = f"{image_id}{image_format}"
file_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}")
with open(file_path, "wb") as image_file:
for chunk in r.iter_content(chunk_size=8192):
image_file.write(chunk)
2024-05-02 22:54:31 +00:00
return image_filename
else:
log.error(f"Url does not point to an image.")
2024-05-02 22:54:31 +00:00
return None
2024-03-24 00:01:13 +00:00
except Exception as e:
log.exception(f"Error saving image: {e}")
2024-05-02 22:54:31 +00:00
return None
2024-03-24 00:01:13 +00:00
2024-02-22 02:12:01 +00:00
@app.post("/generations")
2024-07-15 14:25:00 +00:00
async def image_generations(
2024-06-25 15:01:05 +00:00
form_data: GenerateImageForm,
2024-06-27 18:29:59 +00:00
user=Depends(get_verified_user),
2024-02-22 02:12:01 +00:00
):
width, height = tuple(map(int, app.state.config.IMAGE_SIZE.split("x")))
2024-03-24 00:01:13 +00:00
2024-03-09 03:54:47 +00:00
r = None
2024-02-22 02:36:40 +00:00
try:
if app.state.config.ENGINE == "openai":
2024-02-22 02:36:40 +00:00
2024-03-09 01:38:10 +00:00
headers = {}
headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEY}"
2024-03-09 01:38:10 +00:00
headers["Content-Type"] = "application/json"
2024-02-22 02:36:40 +00:00
2024-03-09 01:38:10 +00:00
data = {
"model": (
app.state.config.MODEL
if app.state.config.MODEL != ""
else "dall-e-2"
),
2024-03-09 01:38:10 +00:00
"prompt": form_data.prompt,
"n": form_data.n,
"size": (
form_data.size if form_data.size else app.state.config.IMAGE_SIZE
),
2024-03-09 01:38:10 +00:00
"response_format": "b64_json",
}
2024-03-12 20:35:30 +00:00
2024-03-09 01:38:10 +00:00
r = requests.post(
url=f"{app.state.config.OPENAI_API_BASE_URL}/images/generations",
2024-03-09 01:38:10 +00:00
json=data,
headers=headers,
)
2024-03-09 01:38:10 +00:00
r.raise_for_status()
res = r.json()
2024-02-22 02:12:01 +00:00
2024-03-09 01:38:10 +00:00
images = []
for image in res["data"]:
2024-04-30 18:52:08 +00:00
image_filename = save_b64_image(image["b64_json"])
images.append({"url": f"/cache/image/generations/{image_filename}"})
2024-05-02 22:55:42 +00:00
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
2024-03-09 01:38:10 +00:00
with open(file_body_path, "w") as f:
json.dump(data, f)
return images
elif app.state.config.ENGINE == "comfyui":
2024-03-24 00:01:13 +00:00
data = {
"prompt": form_data.prompt,
"width": width,
"height": height,
"n": form_data.n,
}
if app.state.config.IMAGE_STEPS is not None:
data["steps"] = app.state.config.IMAGE_STEPS
2024-03-24 00:01:13 +00:00
if form_data.negative_prompt is not None:
2024-03-24 00:01:13 +00:00
data["negative_prompt"] = form_data.negative_prompt
2024-08-21 12:49:17 +00:00
form_data = ComfyUIGenerateImageForm(
2024-08-21 12:49:54 +00:00
**{
2024-08-21 12:49:17 +00:00
"workflow": ComfyUIWorkflow(
2024-08-21 12:49:54 +00:00
**{
2024-08-21 12:49:17 +00:00
"workflow": app.state.config.COMFYUI_WORKFLOW,
"nodes": app.state.config.COMFYUI_WORKFLOW_NODES,
}
),
**data,
}
)
res = await comfyui_generate_image(
app.state.config.MODEL,
form_data,
2024-03-24 00:01:13 +00:00
user.id,
app.state.config.COMFYUI_BASE_URL,
2024-03-24 00:01:13 +00:00
)
log.debug(f"res: {res}")
2024-03-24 00:01:13 +00:00
images = []
for image in res["data"]:
2024-05-02 22:54:31 +00:00
image_filename = save_url_image(image["url"])
images.append({"url": f"/cache/image/generations/{image_filename}"})
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
2024-03-24 00:01:13 +00:00
with open(file_body_path, "w") as f:
2024-08-21 13:15:29 +00:00
json.dump(form_data.model_dump(exclude_none=True), f)
2024-03-24 00:01:13 +00:00
log.debug(f"images: {images}")
2024-03-24 00:01:13 +00:00
return images
2024-08-20 22:35:42 +00:00
elif (
app.state.config.ENGINE == "automatic1111" or app.state.config.ENGINE == ""
):
2024-03-09 01:38:10 +00:00
if form_data.model:
2024-08-20 22:35:42 +00:00
set_image_model(form_data.model)
2024-03-09 01:38:10 +00:00
data = {
"prompt": form_data.prompt,
"batch_size": form_data.n,
"width": width,
"height": height,
}
if app.state.config.IMAGE_STEPS is not None:
data["steps"] = app.state.config.IMAGE_STEPS
2024-03-09 01:38:10 +00:00
if form_data.negative_prompt is not None:
2024-03-09 01:38:10 +00:00
data["negative_prompt"] = form_data.negative_prompt
r = requests.post(
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/txt2img",
2024-03-09 01:38:10 +00:00
json=data,
2024-06-20 06:15:49 +00:00
headers={"authorization": get_automatic1111_api_auth()},
2024-03-09 01:38:10 +00:00
)
res = r.json()
log.debug(f"res: {res}")
2024-03-09 01:38:10 +00:00
images = []
for image in res["images"]:
2024-04-30 18:52:08 +00:00
image_filename = save_b64_image(image)
images.append({"url": f"/cache/image/generations/{image_filename}"})
2024-05-02 22:55:42 +00:00
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
2024-03-09 01:38:10 +00:00
with open(file_body_path, "w") as f:
json.dump({**data, "info": res["info"]}, f)
return images
2024-02-22 02:36:40 +00:00
except Exception as e:
2024-03-12 20:35:30 +00:00
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))