mirror of
https://github.com/nod-ai/AMD-SHARK-Studio.git
synced 2026-02-19 11:56:43 -05:00
* (WIP): Studio2 app infra and SD API UI/app structure and utility implementation. - Initializers for webui/API launch - Schedulers file for SD scheduling utilities - Additions to API-level utilities - Added embeddings module for LoRA, Lycoris, yada yada - Added image_processing module for resamplers, resize tools, transforms, and any image annotation (PNG metadata) - shared_cmd_opts module -- sorry, this is stable_args.py. It lives on. We still want to have some global control over the app exclusively from the command-line. At least we will be free from shark_args. - Moving around some utility pieces. - Try to make api+webui concurrency possible in index.py - SD UI -- this is just img2imgUI but hopefully a little better. - UI utilities for your nod logos and your gradio temps. Enable UI / bugfixes / tweaks * Studio2/SD: Use more correct LoRA alpha calculation (#2034) * Updates ProcessLoRA to use both embedded LoRA alpha, and lora_strength optional parameter (default 1.0) when applying LoRA weights. * Updates ProcessLoRA to cover more dim cases. * This bring ProcessLoRA into line with PR #2015 against Studio1 * Studio2: Remove duplications from api/utils.py (#2035) * Remove duplicate os import * Remove duplicate parse_seed_input function Migrating to JSON requests in SD UI More UI and app flow improvements, logging, shared device cache Model loading Complete SD pipeline. Tweaks to VAE, pipeline states Pipeline tweaks, add cmd_opts parsing to sd api * Add test for SD * Small cleanup * Shark2/SD/UI: Respect ckpt_dir, share and server_port args (#2070) * Takes whether to generate a gradio live link from the existing --share command line parameter, rather than hardcoding as True. * Takes server port from existing --server_port command line parameter, rather than hardcoding as 11911. * Default --ckpt_dir parameter to '../models' * Use --ckpt_dir rather than hardcoding ../models as the base directory for checkpoints, vae, and lora, etc * Add a 'checkpoints' directory below --ckpt_dir to match ComfyUI folder structure. Read custom_weights choices from there, and/or subfolders below there matching the selected base model. * Fix --ckpt_dir possibly not working correctly when an absolute rather than relative path is specified. * Relabel "Custom Weights" to "Custom Weights Checkpoint" in the UI * Add StreamingLLM support to studio2 chat (#2060) * Streaming LLM * Update precision and add gpu support * (studio2) Separate weights generation for quantization support * Adapt prompt changes to studio flow * Remove outdated flag from llm compile flags. * (studio2) use turbine vmfbRunner * tweaks to prompts * Update CPU path and llm api test. * Change device in test to cpu. * Fixes to runner, device names, vmfb mgmt * Use small test without external weights. * HF-Reference LLM mode + Update test result to match latest Turbine. (#2080) * HF-Reference LLM mode. * Fixup test to match current output from Turbine. * lint * Fix test error message + Only initialize HF torch model when used. * Remove redundant format_out change. * Add rest API endpoint from LanguageModel API * Add StreamingLLM support to studio2 chat (#2060) * Streaming LLM * Update precision and add gpu support * (studio2) Separate weights generation for quantization support * Adapt prompt changes to studio flow * Remove outdated flag from llm compile flags. * (studio2) use turbine vmfbRunner * tweaks to prompts * Update CPU path and llm api test. * Change device in test to cpu. * Fixes to runner, device names, vmfb mgmt * Use small test without external weights. * Formatting and init files. * Remove unused import. * Small fixes * Studio2/SD/UI: Improve various parts of the UI for Stable Diffusion (#2074) * Studio2/SD/UI: Improve various parts of the UI of Shark 2 * Update Gradio pin to 4.15.0. * Port workarounds for Gradio >4.8.0 main container sizing from Shark 1.0. * Move nod Logo out of the SD tab and onto the top right of the main tab bar. * Set nod logo icon as the favicon (as current Shark 1.0). * Create a tabbed right hand panel within the SD UI sized to the viewport height. * Make Input Image tab 1 in the right hand panel. * Make output images, generation log, and generation buttons, tab 2 in the right hand panel * Make config JSON display, with config load, save and clear, tab 3 in the right hand panel * Make gallery area of the Output tab take up all vertical space the other controls on the tab do not. * Tidy up the controls on the Config tab somewhat. * Studio2/SD/UI: Reorganise inputs on Left Panel of SD tab * Rename previously added Right Panel Output tab to 'Generate'. * Move Batch Count, Batch Size, and Repeatable Seeds, off of Left Panel and onto 'Generate' Tab. * On 'Generate' tab, rename 'Generate Image(s)' button to 'Start', and 'Stop Batch' button to 'Stop'. They are now below the Batch inputs on a Generate tab so don't need the specificity. * Move Device, Low VRAM, and Precision inputs into their own 'Device Settings' Accordion control. (starts closed) * Rename 'Custom Weights Checkpoint' to 'Checkpoint Weights' * Move Checkpoint Weights, VAE Model, Standalone Lora Weights, and Embeddings Options controls, into their own 'Model Weights' Accordion control. (starts closed) * Move Denoising Strength, and Resample Type controls into their own 'Input Image Processing' Accordion. (starts closed) * Move any remaining controls in the 'Advanced Options' Accorion directly onto the left panel, and remove then Accordion. * Enable the copy button for all text boxes on the SD tab. * Add emoji/unicode glphs to all top level controls and Accordions on the SD Left Panel. * Start with the 'Generate' as the initially selected tab in the SD Right Panel, working around Gradio issue #7805 * Tweaks to SD Right Tab Panel vertical height. * Studio2/SD/UI: Sizing tweaks for Right Panel, and >1920 width * Set height of right panel using vmin rather than vh, with explicit affordances for fixed areas above and below. * Port >1920 width Gradio >4.8 CSS workaround from Shark 1.0. * Studio2/SD: Fix sd pipeline up to "Windows not supported" (#2082) * Studio2/SD: Fix sd pipeline up to "Windows not supported" A number of fixes to the SD pipeline as run from the UI, up until the point that dynamo complains "Windows not yet supported for torch.compile". * Remove separate install of iree-runtime and iree-compile in setup_venv.ps1, and rely on the versions installed via the Turbine requirements.txt. Fixes #2063 for me. * Replace any "None" strings with python None when pulling the config in the UI. * Add 'hf_auth_token' param to api StableDiffusion class, defaulting to None, and then pass that in to the various Models where it is required and wasn't already being done before. * Fix clip custom_weight_params being passed to export_clip_model as "external_weight_file" rather than "external_weights" * Don't pass non-existing "custom_vae" parameter to the Turbine Vae Model, instead pass custom_vae as the "hf_model_id" if it is set. (this may be wrong in the custom vae cast, but stops the code *always* breaking). * Studio2/SD/UI: Improve UI config None handling * When populating the UI from a JSON Config set controls to "None" for null/None values. * When generating a JSON Config from the UI set props to null/None for controls set to "None". * Use null rather string 'None' in the default config --------- Co-authored-by: Ean Garvey <87458719+monorimet@users.noreply.github.com> * Studio2/SD/UI: Further sd ui pipeline fixes (#2091) On Windows, this gets us all the way failing in iree compile of the with SD 2.1 base. - Fix merge errors with sd right pane config UI tab. - Remove non-requirement.txt install/build of torch/mlir/iree/SRT in setup_venv.ps1, fixing "torch.compile not supported on Windows" error. - Fix gradio deprecation warning for `root=` FileExplorer kwarg. - Comment out `precision` and `max_length` kwargs being passed to unet, as not yet supported on main Turbine branch. Avoids keyword argument error. * Tweak compile-time flags for SD submodels. * Small fixes to sd, pin mpmath * Add pyinstaller spec and imports script. * Fix the .exe (#2101) * Fix _IREE_TARGET_MAP (#2103) (#2108) - Change target passed to iree for vulkan from 'vulkan' to 'vulkan-spriv', as 'vulkan' is not a valid value for --iree-hal-target-backends with the current iree compiler. Co-authored-by: Stefan Kapusniak <121311569+one-lithe-rune@users.noreply.github.com> * Cleanup sd model map. * Update dependencies. * Studio2/SD/UI: Update gradio to 4.19.2 (sd-studio2) (#2097) - Move pin for gradio from 4.15 -> 4.19.2 on the sd-studio2 branch * fix formatting and disable explicit vulkan env settings. --------- Co-authored-by: Stefan Kapusniak <121311569+one-lithe-rune@users.noreply.github.com> Co-authored-by: Stanley Winata <68087699+raikonenfnu@users.noreply.github.com> Co-authored-by: gpetters-amd <159576198+gpetters-amd@users.noreply.github.com> Co-authored-by: gpetters94 <gpetters@protonmail.com>
287 lines
12 KiB
Python
287 lines
12 KiB
Python
import base64
|
|
import io
|
|
import os
|
|
import time
|
|
import datetime
|
|
import uvicorn
|
|
import ipaddress
|
|
import requests
|
|
import threading
|
|
import collections
|
|
import gradio as gr
|
|
from PIL import Image, PngImagePlugin
|
|
from threading import Lock
|
|
from io import BytesIO
|
|
from fastapi import APIRouter, Depends, FastAPI, Request, Response
|
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
|
from fastapi.exceptions import HTTPException
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.encoders import jsonable_encoder
|
|
|
|
from apps.shark_studio.modules.shared_cmd_opts import cmd_opts
|
|
|
|
# from sdapi_v1 import shark_sd_api
|
|
from apps.shark_studio.api.llm import llm_chat_api
|
|
|
|
|
|
def decode_base64_to_image(encoding):
|
|
if encoding.startswith("http://") or encoding.startswith("https://"):
|
|
headers = {}
|
|
response = requests.get(encoding, timeout=30, headers=headers)
|
|
try:
|
|
image = Image.open(BytesIO(response.content))
|
|
return image
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail="Invalid image url") from e
|
|
|
|
if encoding.startswith("data:image/"):
|
|
encoding = encoding.split(";")[1].split(",")[1]
|
|
try:
|
|
image = Image.open(BytesIO(base64.b64decode(encoding)))
|
|
return image
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail="Invalid encoded image") from e
|
|
|
|
|
|
def encode_pil_to_base64(image):
|
|
with io.BytesIO() as output_bytes:
|
|
use_metadata = False
|
|
metadata = PngImagePlugin.PngInfo()
|
|
for key, value in image.info.items():
|
|
if isinstance(key, str) and isinstance(value, str):
|
|
metadata.add_text(key, value)
|
|
use_metadata = True
|
|
image.save(
|
|
output_bytes,
|
|
format="PNG",
|
|
pnginfo=(metadata if use_metadata else None),
|
|
)
|
|
|
|
bytes_data = output_bytes.getvalue()
|
|
|
|
return base64.b64encode(bytes_data)
|
|
|
|
|
|
# reference: https://gist.github.com/vitaliyp/6d54dd76ca2c3cdfc1149d33007dc34a
|
|
class FIFOLock(object):
|
|
def __init__(self):
|
|
self._lock = threading.Lock()
|
|
self._inner_lock = threading.Lock()
|
|
self._pending_threads = collections.deque()
|
|
|
|
def acquire(self, blocking=True):
|
|
with self._inner_lock:
|
|
lock_acquired = self._lock.acquire(False)
|
|
if lock_acquired:
|
|
return True
|
|
elif not blocking:
|
|
return False
|
|
|
|
release_event = threading.Event()
|
|
self._pending_threads.append(release_event)
|
|
|
|
release_event.wait()
|
|
return self._lock.acquire()
|
|
|
|
def release(self):
|
|
with self._inner_lock:
|
|
if self._pending_threads:
|
|
release_event = self._pending_threads.popleft()
|
|
release_event.set()
|
|
|
|
self._lock.release()
|
|
|
|
__enter__ = acquire
|
|
|
|
def __exit__(self, t, v, tb):
|
|
self.release()
|
|
|
|
|
|
def api_middleware(app: FastAPI):
|
|
rich_available = False
|
|
try:
|
|
if os.environ.get("WEBUI_RICH_EXCEPTIONS", None) is not None:
|
|
import anyio # importing just so it can be placed on silent list
|
|
import starlette # importing just so it can be placed on silent list
|
|
from rich.console import Console
|
|
|
|
console = Console()
|
|
rich_available = True
|
|
except Exception:
|
|
pass
|
|
|
|
@app.middleware("http")
|
|
async def log_and_time(req: Request, call_next):
|
|
ts = time.time()
|
|
res: Response = await call_next(req)
|
|
duration = str(round(time.time() - ts, 4))
|
|
res.headers["X-Process-Time"] = duration
|
|
endpoint = req.scope.get("path", "err")
|
|
if cmd_opts.api_log and endpoint.startswith("/sdapi"):
|
|
print(
|
|
"API {t} {code} {prot}/{ver} {method} {endpoint} {cli} {duration}".format(
|
|
t=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
|
|
code=res.status_code,
|
|
ver=req.scope.get("http_version", "0.0"),
|
|
cli=req.scope.get("client", ("0:0.0.0", 0))[0],
|
|
prot=req.scope.get("scheme", "err"),
|
|
method=req.scope.get("method", "err"),
|
|
endpoint=endpoint,
|
|
duration=duration,
|
|
)
|
|
)
|
|
return res
|
|
|
|
def handle_exception(request: Request, e: Exception):
|
|
err = {
|
|
"error": type(e).__name__,
|
|
"detail": vars(e).get("detail", ""),
|
|
"body": vars(e).get("body", ""),
|
|
"errors": str(e),
|
|
}
|
|
if not isinstance(
|
|
e, HTTPException
|
|
): # do not print backtrace on known httpexceptions
|
|
message = f"API error: {request.method}: {request.url} {err}"
|
|
if rich_available:
|
|
print(message)
|
|
console.print_exception(
|
|
show_locals=True,
|
|
max_frames=2,
|
|
extra_lines=1,
|
|
suppress=[anyio, starlette],
|
|
word_wrap=False,
|
|
width=min([console.width, 200]),
|
|
)
|
|
else:
|
|
print(message)
|
|
raise (e)
|
|
return JSONResponse(
|
|
status_code=vars(e).get("status_code", 500),
|
|
content=jsonable_encoder(err),
|
|
)
|
|
|
|
@app.middleware("http")
|
|
async def exception_handling(request: Request, call_next):
|
|
try:
|
|
return await call_next(request)
|
|
except Exception as e:
|
|
return handle_exception(request, e)
|
|
|
|
@app.exception_handler(Exception)
|
|
async def fastapi_exception_handler(request: Request, e: Exception):
|
|
return handle_exception(request, e)
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(request: Request, e: HTTPException):
|
|
return handle_exception(request, e)
|
|
|
|
|
|
class ApiCompat:
|
|
def __init__(self, app: FastAPI, queue_lock: Lock):
|
|
self.router = APIRouter()
|
|
self.app = app
|
|
self.queue_lock = queue_lock
|
|
api_middleware(self.app)
|
|
# self.add_api_route("/sdapi/v1/txt2img", shark_sd_api, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/img2img", shark_sd_api, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/upscaler", self.upscaler_api, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/extra-single-image", self.extras_single_image_api, methods=["POST"], response_model=models.ExtrasSingleImageResponse)
|
|
# self.add_api_route("/sdapi/v1/extra-batch-images", self.extras_batch_images_api, methods=["POST"], response_model=models.ExtrasBatchImagesResponse)
|
|
# self.add_api_route("/sdapi/v1/png-info", self.pnginfoapi, methods=["POST"], response_model=models.PNGInfoResponse)
|
|
# self.add_api_route("/sdapi/v1/progress", self.progressapi, methods=["GET"], response_model=models.ProgressResponse)
|
|
# self.add_api_route("/sdapi/v1/interrogate", self.interrogateapi, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/interrupt", self.interruptapi, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/skip", self.skip, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/options", self.get_config, methods=["GET"], response_model=models.OptionsModel)
|
|
# self.add_api_route("/sdapi/v1/options", self.set_config, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/cmd-flags", self.get_cmd_flags, methods=["GET"], response_model=models.FlagsModel)
|
|
# self.add_api_route("/sdapi/v1/samplers", self.get_samplers, methods=["GET"], response_model=List[models.SamplerItem])
|
|
# self.add_api_route("/sdapi/v1/upscalers", self.get_upscalers, methods=["GET"], response_model=List[models.UpscalerItem])
|
|
# self.add_api_route("/sdapi/v1/latent-upscale-modes", self.get_latent_upscale_modes, methods=["GET"], response_model=List[models.LatentUpscalerModeItem])
|
|
# self.add_api_route("/sdapi/v1/sd-models", self.get_sd_models, methods=["GET"], response_model=List[models.SDModelItem])
|
|
# self.add_api_route("/sdapi/v1/sd-vae", self.get_sd_vaes, methods=["GET"], response_model=List[models.SDVaeItem])
|
|
# self.add_api_route("/sdapi/v1/hypernetworks", self.get_hypernetworks, methods=["GET"], response_model=List[models.HypernetworkItem])
|
|
# self.add_api_route("/sdapi/v1/face-restorers", self.get_face_restorers, methods=["GET"], response_model=List[models.FaceRestorerItem])
|
|
# self.add_api_route("/sdapi/v1/realesrgan-models", self.get_realesrgan_models, methods=["GET"], response_model=List[models.RealesrganItem])
|
|
# self.add_api_route("/sdapi/v1/prompt-styles", self.get_prompt_styles, methods=["GET"], response_model=List[models.PromptStyleItem])
|
|
# self.add_api_route("/sdapi/v1/embeddings", self.get_embeddings, methods=["GET"], response_model=models.EmbeddingsResponse)
|
|
# self.add_api_route("/sdapi/v1/refresh-checkpoints", self.refresh_checkpoints, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/refresh-vae", self.refresh_vae, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/create/embedding", self.create_embedding, methods=["POST"], response_model=models.CreateResponse)
|
|
# self.add_api_route("/sdapi/v1/create/hypernetwork", self.create_hypernetwork, methods=["POST"], response_model=models.CreateResponse)
|
|
# self.add_api_route("/sdapi/v1/preprocess", self.preprocess, methods=["POST"], response_model=models.PreprocessResponse)
|
|
# self.add_api_route("/sdapi/v1/train/embedding", self.train_embedding, methods=["POST"], response_model=models.TrainResponse)
|
|
# self.add_api_route("/sdapi/v1/train/hypernetwork", self.train_hypernetwork, methods=["POST"], response_model=models.TrainResponse)
|
|
# self.add_api_route("/sdapi/v1/memory", self.get_memory, methods=["GET"], response_model=models.MemoryResponse)
|
|
# self.add_api_route("/sdapi/v1/unload-checkpoint", self.unloadapi, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/reload-checkpoint", self.reloadapi, methods=["POST"])
|
|
# self.add_api_route("/sdapi/v1/scripts", self.get_scripts_list, methods=["GET"], response_model=models.ScriptsList)
|
|
# self.add_api_route("/sdapi/v1/script-info", self.get_script_info, methods=["GET"], response_model=List[models.ScriptInfo])
|
|
|
|
# chat APIs needed for compatibility with multiple extensions using OpenAI API
|
|
self.add_api_route("/v1/chat/completions", llm_chat_api, methods=["POST"])
|
|
self.add_api_route("/v1/completions", llm_chat_api, methods=["POST"])
|
|
self.add_api_route("/chat/completions", llm_chat_api, methods=["POST"])
|
|
self.add_api_route("/completions", llm_chat_api, methods=["POST"])
|
|
self.add_api_route(
|
|
"/v1/engines/codegen/completions", llm_chat_api, methods=["POST"]
|
|
)
|
|
|
|
self.default_script_arg_txt2img = []
|
|
self.default_script_arg_img2img = []
|
|
|
|
def add_api_route(self, path: str, endpoint, **kwargs):
|
|
return self.app.add_api_route(path, endpoint, **kwargs)
|
|
|
|
# def refresh_checkpoints(self):
|
|
# with self.queue_lock:
|
|
# studio_data.refresh_checkpoints()
|
|
|
|
# def refresh_vae(self):
|
|
# with self.queue_lock:
|
|
# studio_data.refresh_vae_list()
|
|
|
|
# def unloadapi(self):
|
|
# unload_model_weights()
|
|
|
|
# return {}
|
|
|
|
# def reloadapi(self):
|
|
# reload_model_weights()
|
|
|
|
# return {}
|
|
|
|
# def skip(self):
|
|
# studio.state.skip()
|
|
|
|
def launch(self, server_name, port, root_path):
|
|
self.app.include_router(self.router)
|
|
uvicorn.run(
|
|
self.app,
|
|
host=server_name,
|
|
port=port,
|
|
root_path=root_path,
|
|
)
|
|
|
|
# def kill_studio(self):
|
|
# restart.stop_program()
|
|
|
|
# def restart_studio(self):
|
|
# if restart.is_restartable():
|
|
# restart.restart_program()
|
|
# return Response(status_code=501)
|
|
|
|
# def preprocess(self, args: dict):
|
|
# try:
|
|
# studio.state.begin(job="preprocess")
|
|
# preprocess(**args)
|
|
# studio.state.end()
|
|
# return models.PreprocessResponse(info="preprocess complete")
|
|
# except:
|
|
# studio.state.end()
|
|
|
|
# def stop_studio(request):
|
|
# studio.state.server_command = "stop"
|
|
# return Response("Stopping.")
|