2022-10-19 05:58:55 +02:00
|
|
|
"""server.py: FastAPI SD-UI Web Host.
|
|
|
|
Notes:
|
|
|
|
async endpoints always run on the main thread. Without they run on the thread pool.
|
|
|
|
"""
|
2022-09-09 17:04:32 +02:00
|
|
|
import json
|
2022-09-02 10:28:36 +02:00
|
|
|
import traceback
|
|
|
|
|
|
|
|
import sys
|
|
|
|
import os
|
2022-11-16 22:34:02 +01:00
|
|
|
import picklescan.scanner
|
|
|
|
import rich
|
2022-09-02 10:28:36 +02:00
|
|
|
|
2022-10-06 10:58:02 +02:00
|
|
|
SD_DIR = os.getcwd()
|
|
|
|
print('started in ', SD_DIR)
|
2022-09-02 10:28:36 +02:00
|
|
|
|
|
|
|
SD_UI_DIR = os.getenv('SD_UI_PATH', None)
|
|
|
|
sys.path.append(os.path.dirname(SD_UI_DIR))
|
|
|
|
|
2022-10-06 10:58:02 +02:00
|
|
|
CONFIG_DIR = os.path.abspath(os.path.join(SD_UI_DIR, '..', 'scripts'))
|
|
|
|
MODELS_DIR = os.path.abspath(os.path.join(SD_DIR, '..', 'models'))
|
2022-11-16 09:00:40 +01:00
|
|
|
|
|
|
|
USER_UI_PLUGINS_DIR = os.path.abspath(os.path.join(SD_DIR, '..', 'plugins', 'ui'))
|
|
|
|
CORE_UI_PLUGINS_DIR = os.path.abspath(os.path.join(SD_UI_DIR, 'plugins', 'ui'))
|
|
|
|
UI_PLUGINS_SOURCES = ((CORE_UI_PLUGINS_DIR, 'core'), (USER_UI_PLUGINS_DIR, 'user'))
|
2022-09-09 17:04:32 +02:00
|
|
|
|
2022-11-19 06:14:17 +01:00
|
|
|
STABLE_DIFFUSION_MODEL_EXTENSIONS = ['.ckpt']
|
|
|
|
VAE_MODEL_EXTENSIONS = ['.vae.pt', '.ckpt']
|
|
|
|
|
2022-09-02 10:28:36 +02:00
|
|
|
OUTPUT_DIRNAME = "Stable Diffusion UI" # in the user's home folder
|
2022-10-15 06:51:06 +02:00
|
|
|
TASK_TTL = 15 * 60 # Discard last session's task timeout
|
2022-10-17 03:41:39 +02:00
|
|
|
APP_CONFIG_DEFAULTS = {
|
|
|
|
# auto: selects the cuda device with the most free memory, cuda: use the currently active cuda device.
|
2022-11-16 07:46:46 +01:00
|
|
|
'render_devices': 'auto', # valid entries: 'auto', 'cpu' or 'cuda:N' (where N is a GPU index)
|
2022-10-17 03:41:39 +02:00
|
|
|
'update_branch': 'main',
|
2022-11-16 08:13:46 +01:00
|
|
|
'ui': {
|
|
|
|
'open_browser_on_start': True,
|
|
|
|
},
|
2022-10-17 03:41:39 +02:00
|
|
|
}
|
|
|
|
APP_CONFIG_DEFAULT_MODELS = [
|
|
|
|
# needed to support the legacy installations
|
|
|
|
'custom-model', # Check if user has a custom model, use it first.
|
|
|
|
'sd-v1-4', # Default fallback.
|
|
|
|
]
|
2022-09-02 10:28:36 +02:00
|
|
|
|
|
|
|
from fastapi import FastAPI, HTTPException
|
2022-09-22 17:01:30 +02:00
|
|
|
from fastapi.staticfiles import StaticFiles
|
2022-10-14 09:47:25 +02:00
|
|
|
from starlette.responses import FileResponse, JSONResponse, StreamingResponse
|
2022-09-02 10:28:36 +02:00
|
|
|
from pydantic import BaseModel
|
2022-09-09 17:35:24 +02:00
|
|
|
import logging
|
2022-10-17 03:41:39 +02:00
|
|
|
#import queue, threading, time
|
|
|
|
from typing import Any, Generator, Hashable, List, Optional, Union
|
2022-09-02 10:28:36 +02:00
|
|
|
|
2022-10-15 09:28:20 +02:00
|
|
|
from sd_internal import Request, Response, task_manager
|
2022-09-02 10:28:36 +02:00
|
|
|
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
|
|
modifiers_cache = None
|
|
|
|
outpath = os.path.join(os.path.expanduser("~"), OUTPUT_DIRNAME)
|
|
|
|
|
2022-11-16 09:00:40 +01:00
|
|
|
os.makedirs(USER_UI_PLUGINS_DIR, exist_ok=True)
|
2022-10-19 18:04:40 +02:00
|
|
|
|
2022-09-24 12:25:45 +02:00
|
|
|
# don't show access log entries for URLs that start with the given prefix
|
2022-10-14 09:47:25 +02:00
|
|
|
ACCESS_LOG_SUPPRESS_PATH_PREFIXES = ['/ping', '/image', '/modifier-thumbnails']
|
2022-09-24 12:25:45 +02:00
|
|
|
|
2022-10-14 09:47:25 +02:00
|
|
|
NOCACHE_HEADERS={"Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0"}
|
2022-10-19 18:04:40 +02:00
|
|
|
|
2022-11-18 13:01:20 +01:00
|
|
|
class NoCacheStaticFiles(StaticFiles):
|
|
|
|
def is_not_modified(self, response_headers, request_headers) -> bool:
|
|
|
|
if 'content-type' in response_headers and ('javascript' in response_headers['content-type'] or 'css' in response_headers['content-type']):
|
|
|
|
response_headers.update(NOCACHE_HEADERS)
|
|
|
|
return False
|
|
|
|
|
|
|
|
return super().is_not_modified(response_headers, request_headers)
|
|
|
|
|
|
|
|
app.mount('/media', NoCacheStaticFiles(directory=os.path.join(SD_UI_DIR, 'media')), name="media")
|
2022-11-16 09:00:40 +01:00
|
|
|
|
|
|
|
for plugins_dir, dir_prefix in UI_PLUGINS_SOURCES:
|
2022-11-18 13:01:20 +01:00
|
|
|
app.mount(f'/plugins/{dir_prefix}', NoCacheStaticFiles(directory=plugins_dir), name=f"plugins-{dir_prefix}")
|
2022-09-24 12:25:45 +02:00
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
def getConfig(default_val=APP_CONFIG_DEFAULTS):
|
|
|
|
try:
|
|
|
|
config_json_path = os.path.join(CONFIG_DIR, 'config.json')
|
|
|
|
if not os.path.exists(config_json_path):
|
|
|
|
return default_val
|
2022-10-18 05:15:36 +02:00
|
|
|
with open(config_json_path, 'r', encoding='utf-8') as f:
|
2022-11-19 17:10:45 +01:00
|
|
|
config = json.load(f)
|
|
|
|
if 'net' not in config:
|
|
|
|
config['net'] = {}
|
|
|
|
if os.getenv('SD_UI_BIND_PORT') is not None:
|
|
|
|
config['net']['listen_port'] = int(os.getenv('SD_UI_BIND_PORT'))
|
|
|
|
if os.getenv('SD_UI_BIND_IP') is not None:
|
|
|
|
config['net']['listen_to_network'] = ( os.getenv('SD_UI_BIND_IP') == '0.0.0.0' )
|
|
|
|
return config
|
2022-10-17 03:41:39 +02:00
|
|
|
except Exception as e:
|
|
|
|
print(str(e))
|
|
|
|
print(traceback.format_exc())
|
|
|
|
return default_val
|
|
|
|
|
|
|
|
def setConfig(config):
|
2022-11-19 17:10:45 +01:00
|
|
|
print( json.dumps(config) )
|
2022-10-17 03:41:39 +02:00
|
|
|
try: # config.json
|
|
|
|
config_json_path = os.path.join(CONFIG_DIR, 'config.json')
|
2022-10-18 05:15:36 +02:00
|
|
|
with open(config_json_path, 'w', encoding='utf-8') as f:
|
2022-10-28 17:30:25 +02:00
|
|
|
json.dump(config, f)
|
2022-10-17 03:41:39 +02:00
|
|
|
except:
|
|
|
|
print(traceback.format_exc())
|
|
|
|
|
|
|
|
try: # config.bat
|
|
|
|
config_bat_path = os.path.join(CONFIG_DIR, 'config.bat')
|
2022-11-16 07:10:51 +01:00
|
|
|
config_bat = []
|
2022-11-06 00:27:11 +01:00
|
|
|
|
2022-11-16 07:10:51 +01:00
|
|
|
if 'update_branch' in config:
|
|
|
|
config_bat.append(f"@set update_branch={config['update_branch']}")
|
2022-11-19 17:10:45 +01:00
|
|
|
|
|
|
|
config_bat.append(f"@set SD_UI_BIND_PORT={config['net']['listen_port']}")
|
|
|
|
bind_ip = '0.0.0.0' if config['net']['listen_to_network'] else '127.0.0.1'
|
|
|
|
config_bat.append(f"@set SD_UI_BIND_IP={bind_ip}")
|
2022-11-06 00:27:11 +01:00
|
|
|
|
2022-11-25 07:47:44 +01:00
|
|
|
config_bat.append(f"@set test_sd2={'Y' if config.get('test_sd2', False) else 'N'}")
|
|
|
|
|
2022-11-16 07:10:51 +01:00
|
|
|
if len(config_bat) > 0:
|
|
|
|
with open(config_bat_path, 'w', encoding='utf-8') as f:
|
|
|
|
f.write('\r\n'.join(config_bat))
|
|
|
|
except:
|
2022-10-17 03:41:39 +02:00
|
|
|
print(traceback.format_exc())
|
|
|
|
|
|
|
|
try: # config.sh
|
2022-11-10 15:33:11 +01:00
|
|
|
config_sh_path = os.path.join(CONFIG_DIR, 'config.sh')
|
2022-11-16 07:10:51 +01:00
|
|
|
config_sh = ['#!/bin/bash']
|
2022-11-06 00:27:11 +01:00
|
|
|
|
2022-11-16 07:10:51 +01:00
|
|
|
if 'update_branch' in config:
|
|
|
|
config_sh.append(f"export update_branch={config['update_branch']}")
|
2022-11-19 17:10:45 +01:00
|
|
|
|
|
|
|
config_sh.append(f"export SD_UI_BIND_PORT={config['net']['listen_port']}")
|
|
|
|
bind_ip = '0.0.0.0' if config['net']['listen_to_network'] else '127.0.0.1'
|
|
|
|
config_sh.append(f"export SD_UI_BIND_IP={bind_ip}")
|
2022-11-06 00:27:11 +01:00
|
|
|
|
2022-11-25 07:47:44 +01:00
|
|
|
config_sh.append(f"export test_sd2=\"{'Y' if config.get('test_sd2', False) else 'N'}\"")
|
|
|
|
|
2022-11-16 07:10:51 +01:00
|
|
|
if len(config_sh) > 1:
|
|
|
|
with open(config_sh_path, 'w', encoding='utf-8') as f:
|
|
|
|
f.write('\n'.join(config_sh))
|
|
|
|
except:
|
2022-10-17 03:41:39 +02:00
|
|
|
print(traceback.format_exc())
|
|
|
|
|
2022-11-08 12:24:15 +01:00
|
|
|
def resolve_model_to_use(model_name:str, model_type:str, model_dir:str, model_extensions:list, default_models=[]):
|
2022-11-29 08:44:58 +01:00
|
|
|
config = getConfig()
|
|
|
|
|
2022-10-28 16:36:44 +02:00
|
|
|
model_dirs = [os.path.join(MODELS_DIR, model_dir), SD_DIR]
|
2022-10-17 03:41:39 +02:00
|
|
|
if not model_name: # When None try user configured model.
|
2022-11-29 08:44:58 +01:00
|
|
|
# config = getConfig()
|
2022-10-28 16:36:44 +02:00
|
|
|
if 'model' in config and model_type in config['model']:
|
|
|
|
model_name = config['model'][model_type]
|
2022-10-17 03:41:39 +02:00
|
|
|
if model_name:
|
2022-11-29 08:44:58 +01:00
|
|
|
is_sd2 = config.get('test_sd2', False)
|
|
|
|
if model_name.startswith('sd2_') and not is_sd2: # temp hack, until SD2 is unified with 1.4
|
|
|
|
print('ERROR: Cannot use SD 2.0 models with SD 1.0 code. Using the sd-v1-4 model instead!')
|
|
|
|
model_name = 'sd-v1-4'
|
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
# Check models directory
|
2022-10-28 16:36:44 +02:00
|
|
|
models_dir_path = os.path.join(MODELS_DIR, model_dir, model_name)
|
2022-11-08 12:24:15 +01:00
|
|
|
for model_extension in model_extensions:
|
|
|
|
if os.path.exists(models_dir_path + model_extension):
|
|
|
|
return models_dir_path
|
|
|
|
if os.path.exists(model_name + model_extension):
|
|
|
|
# Direct Path to file
|
|
|
|
model_name = os.path.abspath(model_name)
|
|
|
|
return model_name
|
2022-10-17 03:41:39 +02:00
|
|
|
# Default locations
|
2022-10-28 16:36:44 +02:00
|
|
|
if model_name in default_models:
|
2022-10-17 03:41:39 +02:00
|
|
|
default_model_path = os.path.join(SD_DIR, model_name)
|
2022-11-08 12:24:15 +01:00
|
|
|
for model_extension in model_extensions:
|
|
|
|
if os.path.exists(default_model_path + model_extension):
|
|
|
|
return default_model_path
|
2022-10-17 03:41:39 +02:00
|
|
|
# Can't find requested model, check the default paths.
|
2022-10-28 16:36:44 +02:00
|
|
|
for default_model in default_models:
|
|
|
|
for model_dir in model_dirs:
|
|
|
|
default_model_path = os.path.join(model_dir, default_model)
|
2022-11-08 12:24:15 +01:00
|
|
|
for model_extension in model_extensions:
|
|
|
|
if os.path.exists(default_model_path + model_extension):
|
|
|
|
if model_name is not None:
|
|
|
|
print(f'Could not find the configured custom model {model_name}{model_extension}. Using the default one: {default_model_path}{model_extension}')
|
|
|
|
return default_model_path
|
2022-10-17 03:41:39 +02:00
|
|
|
raise Exception('No valid models found.')
|
|
|
|
|
2022-10-28 16:36:44 +02:00
|
|
|
def resolve_ckpt_to_use(model_name:str=None):
|
2022-11-19 06:14:17 +01:00
|
|
|
return resolve_model_to_use(model_name, model_type='stable-diffusion', model_dir='stable-diffusion', model_extensions=STABLE_DIFFUSION_MODEL_EXTENSIONS, default_models=APP_CONFIG_DEFAULT_MODELS)
|
2022-10-28 16:36:44 +02:00
|
|
|
|
2022-11-08 12:24:15 +01:00
|
|
|
def resolve_vae_to_use(model_name:str=None):
|
|
|
|
try:
|
2022-11-19 06:14:17 +01:00
|
|
|
return resolve_model_to_use(model_name, model_type='vae', model_dir='vae', model_extensions=VAE_MODEL_EXTENSIONS, default_models=[])
|
2022-11-08 12:24:15 +01:00
|
|
|
except:
|
|
|
|
return None
|
2022-10-28 16:36:44 +02:00
|
|
|
|
2022-09-09 17:04:32 +02:00
|
|
|
class SetAppConfigRequest(BaseModel):
|
2022-10-17 03:41:39 +02:00
|
|
|
update_branch: str = None
|
|
|
|
render_devices: Union[List[str], List[int], str, int] = None
|
2022-10-28 16:36:44 +02:00
|
|
|
model_vae: str = None
|
2022-11-16 08:13:46 +01:00
|
|
|
ui_open_browser_on_start: bool = None
|
2022-11-19 17:10:45 +01:00
|
|
|
listen_to_network: bool = None
|
|
|
|
listen_port: int = None
|
2022-11-25 09:27:15 +01:00
|
|
|
test_sd2: bool = None
|
2022-09-09 17:04:32 +02:00
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
@app.post('/app_config')
|
|
|
|
async def setAppConfig(req : SetAppConfigRequest):
|
|
|
|
config = getConfig()
|
2022-11-16 08:13:46 +01:00
|
|
|
if req.update_branch is not None:
|
2022-10-17 03:41:39 +02:00
|
|
|
config['update_branch'] = req.update_branch
|
2022-11-16 08:13:46 +01:00
|
|
|
if req.render_devices is not None:
|
2022-11-15 07:52:55 +01:00
|
|
|
update_render_devices_in_config(config, req.render_devices)
|
2022-11-16 08:13:46 +01:00
|
|
|
if req.ui_open_browser_on_start is not None:
|
|
|
|
if 'ui' not in config:
|
|
|
|
config['ui'] = {}
|
|
|
|
config['ui']['open_browser_on_start'] = req.ui_open_browser_on_start
|
2022-11-19 17:10:45 +01:00
|
|
|
if req.listen_to_network is not None:
|
|
|
|
if 'net' not in config:
|
|
|
|
config['net'] = {}
|
|
|
|
config['net']['listen_to_network'] = bool(req.listen_to_network)
|
|
|
|
if req.listen_port is not None:
|
|
|
|
if 'net' not in config:
|
|
|
|
config['net'] = {}
|
|
|
|
config['net']['listen_port'] = int(req.listen_port)
|
2022-11-25 09:27:15 +01:00
|
|
|
if req.test_sd2 is not None:
|
|
|
|
config['test_sd2'] = req.test_sd2
|
2022-10-17 03:41:39 +02:00
|
|
|
try:
|
|
|
|
setConfig(config)
|
2022-11-15 07:52:55 +01:00
|
|
|
|
|
|
|
if req.render_devices:
|
|
|
|
update_render_threads()
|
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
return JSONResponse({'status': 'OK'}, headers=NOCACHE_HEADERS)
|
|
|
|
except Exception as e:
|
|
|
|
print(traceback.format_exc())
|
2022-10-18 08:36:57 +02:00
|
|
|
raise HTTPException(status_code=500, detail=str(e))
|
2022-10-17 03:41:39 +02:00
|
|
|
|
2022-11-19 06:14:17 +01:00
|
|
|
def is_malicious_model(file_path):
|
|
|
|
try:
|
|
|
|
scan_result = picklescan.scanner.scan_file_path(file_path)
|
|
|
|
if scan_result.issues_count > 0 or scan_result.infected_files > 0:
|
|
|
|
rich.print(":warning: [bold red]Scan %s: %d scanned, %d issue, %d infected.[/bold red]" % (file_path, scan_result.scanned_files, scan_result.issues_count, scan_result.infected_files))
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
rich.print("Scan %s: [green]%d scanned, %d issue, %d infected.[/green]" % (file_path, scan_result.scanned_files, scan_result.issues_count, scan_result.infected_files))
|
|
|
|
return False
|
|
|
|
except Exception as e:
|
|
|
|
print('error while scanning', file_path, 'error:', e)
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
def getModels():
|
|
|
|
models = {
|
|
|
|
'active': {
|
|
|
|
'stable-diffusion': 'sd-v1-4',
|
2022-10-28 16:36:44 +02:00
|
|
|
'vae': '',
|
2022-10-17 03:41:39 +02:00
|
|
|
},
|
|
|
|
'options': {
|
|
|
|
'stable-diffusion': ['sd-v1-4'],
|
2022-10-28 16:36:44 +02:00
|
|
|
'vae': [],
|
2022-10-17 03:41:39 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2022-11-08 12:24:15 +01:00
|
|
|
def listModels(models_dirname, model_type, model_extensions):
|
|
|
|
models_dir = os.path.join(MODELS_DIR, models_dirname)
|
2022-11-09 11:58:58 +01:00
|
|
|
if not os.path.exists(models_dir):
|
|
|
|
os.makedirs(models_dir)
|
|
|
|
|
2022-11-08 12:24:15 +01:00
|
|
|
for file in os.listdir(models_dir):
|
2022-11-19 06:14:17 +01:00
|
|
|
for model_extension in model_extensions:
|
|
|
|
if not file.endswith(model_extension):
|
|
|
|
continue
|
|
|
|
|
|
|
|
if is_malicious_model(os.path.join(models_dir, file)):
|
2022-11-18 11:42:45 +01:00
|
|
|
models['scan-error'] = file
|
2022-11-19 06:14:17 +01:00
|
|
|
return
|
2022-11-18 11:42:45 +01:00
|
|
|
|
2022-11-19 06:14:17 +01:00
|
|
|
model_name = file[:-len(model_extension)]
|
|
|
|
models['options'][model_type].append(model_name)
|
2022-11-08 12:24:15 +01:00
|
|
|
|
|
|
|
models['options'][model_type] = [*set(models['options'][model_type])] # remove duplicates
|
2022-11-09 13:05:55 +01:00
|
|
|
models['options'][model_type].sort()
|
2022-11-08 12:24:15 +01:00
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
# custom models
|
2022-11-19 06:14:17 +01:00
|
|
|
listModels(models_dirname='stable-diffusion', model_type='stable-diffusion', model_extensions=STABLE_DIFFUSION_MODEL_EXTENSIONS)
|
|
|
|
listModels(models_dirname='vae', model_type='vae', model_extensions=VAE_MODEL_EXTENSIONS)
|
2022-10-06 10:58:02 +02:00
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
# legacy
|
|
|
|
custom_weight_path = os.path.join(SD_DIR, 'custom-model.ckpt')
|
|
|
|
if os.path.exists(custom_weight_path):
|
|
|
|
models['options']['stable-diffusion'].append('custom-model')
|
2022-10-06 10:58:02 +02:00
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
return models
|
2022-10-06 10:58:02 +02:00
|
|
|
|
2022-10-21 02:08:23 +02:00
|
|
|
def getUIPlugins():
|
|
|
|
plugins = []
|
|
|
|
|
2022-11-16 09:00:40 +01:00
|
|
|
for plugins_dir, dir_prefix in UI_PLUGINS_SOURCES:
|
|
|
|
for file in os.listdir(plugins_dir):
|
|
|
|
if file.endswith('.plugin.js'):
|
|
|
|
plugins.append(f'/plugins/{dir_prefix}/{file}')
|
2022-10-21 02:08:23 +02:00
|
|
|
|
|
|
|
return plugins
|
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
@app.get('/get/{key:path}')
|
|
|
|
def read_web_data(key:str=None):
|
|
|
|
if not key: # /get without parameters, stable-diffusion easter egg.
|
2022-10-18 08:36:57 +02:00
|
|
|
raise HTTPException(status_code=418, detail="StableDiffusion is drawing a teapot!") # HTTP418 I'm a teapot
|
2022-10-17 03:41:39 +02:00
|
|
|
elif key == 'app_config':
|
|
|
|
config = getConfig(default_val=None)
|
|
|
|
if config is None:
|
2022-11-16 07:50:25 +01:00
|
|
|
config = APP_CONFIG_DEFAULTS
|
2022-10-17 03:41:39 +02:00
|
|
|
return JSONResponse(config, headers=NOCACHE_HEADERS)
|
2022-10-29 23:33:44 +02:00
|
|
|
elif key == 'devices':
|
2022-11-14 06:53:22 +01:00
|
|
|
config = getConfig()
|
|
|
|
devices = task_manager.get_devices()
|
|
|
|
devices['config'] = config.get('render_devices', "auto")
|
|
|
|
return JSONResponse(devices, headers=NOCACHE_HEADERS)
|
2022-10-17 03:41:39 +02:00
|
|
|
elif key == 'models':
|
|
|
|
return JSONResponse(getModels(), headers=NOCACHE_HEADERS)
|
|
|
|
elif key == 'modifiers': return FileResponse(os.path.join(SD_UI_DIR, 'modifiers.json'), headers=NOCACHE_HEADERS)
|
|
|
|
elif key == 'output_dir': return JSONResponse({ 'output_dir': outpath }, headers=NOCACHE_HEADERS)
|
2022-10-21 02:08:23 +02:00
|
|
|
elif key == 'ui_plugins': return JSONResponse(getUIPlugins(), headers=NOCACHE_HEADERS)
|
2022-10-17 03:41:39 +02:00
|
|
|
else:
|
2022-10-18 08:36:57 +02:00
|
|
|
raise HTTPException(status_code=404, detail=f'Request for unknown {key}') # HTTP404 Not Found
|
2022-10-06 10:58:02 +02:00
|
|
|
|
2022-10-14 09:47:25 +02:00
|
|
|
@app.get('/ping') # Get server and optionally session status.
|
|
|
|
def ping(session_id:str=None):
|
2022-10-17 03:41:39 +02:00
|
|
|
if task_manager.is_alive() <= 0: # Check that render threads are alive.
|
2022-10-18 08:36:57 +02:00
|
|
|
if task_manager.current_state_error: raise HTTPException(status_code=500, detail=str(task_manager.current_state_error))
|
2022-10-18 08:30:30 +02:00
|
|
|
raise HTTPException(status_code=500, detail='Render thread is dead.')
|
2022-10-18 08:36:57 +02:00
|
|
|
if task_manager.current_state_error and not isinstance(task_manager.current_state_error, StopAsyncIteration): raise HTTPException(status_code=500, detail=str(task_manager.current_state_error))
|
2022-10-14 09:47:25 +02:00
|
|
|
# Alive
|
2022-10-15 09:28:20 +02:00
|
|
|
response = {'status': str(task_manager.current_state)}
|
2022-10-14 09:47:25 +02:00
|
|
|
if session_id:
|
2022-10-24 11:12:08 +02:00
|
|
|
task = task_manager.get_cached_task(session_id, update_ttl=True)
|
2022-10-14 09:47:25 +02:00
|
|
|
if task:
|
|
|
|
response['task'] = id(task)
|
|
|
|
if task.lock.locked():
|
|
|
|
response['session'] = 'running'
|
|
|
|
elif isinstance(task.error, StopAsyncIteration):
|
|
|
|
response['session'] = 'stopped'
|
|
|
|
elif task.error:
|
|
|
|
response['session'] = 'error'
|
|
|
|
elif not task.buffer_queue.empty():
|
|
|
|
response['session'] = 'buffer'
|
|
|
|
elif task.response:
|
|
|
|
response['session'] = 'completed'
|
|
|
|
else:
|
|
|
|
response['session'] = 'pending'
|
2022-11-14 15:23:40 +01:00
|
|
|
response['devices'] = task_manager.get_devices()
|
2022-10-14 09:47:25 +02:00
|
|
|
return JSONResponse(response, headers=NOCACHE_HEADERS)
|
|
|
|
|
2022-11-08 12:24:15 +01:00
|
|
|
def save_model_to_config(ckpt_model_name, vae_model_name):
|
2022-10-15 09:28:20 +02:00
|
|
|
config = getConfig()
|
|
|
|
if 'model' not in config:
|
|
|
|
config['model'] = {}
|
|
|
|
|
2022-11-08 12:24:15 +01:00
|
|
|
config['model']['stable-diffusion'] = ckpt_model_name
|
|
|
|
config['model']['vae'] = vae_model_name
|
|
|
|
|
|
|
|
if vae_model_name is None or vae_model_name == "":
|
|
|
|
del config['model']['vae']
|
|
|
|
|
2022-10-15 09:28:20 +02:00
|
|
|
setConfig(config)
|
|
|
|
|
2022-11-15 07:52:55 +01:00
|
|
|
def update_render_devices_in_config(config, render_devices):
|
|
|
|
if render_devices not in ('cpu', 'auto') and not render_devices.startswith('cuda:'):
|
|
|
|
raise HTTPException(status_code=400, detail=f'Invalid render device requested: {render_devices}')
|
2022-11-14 06:53:22 +01:00
|
|
|
|
2022-11-15 07:52:55 +01:00
|
|
|
if render_devices.startswith('cuda:'):
|
|
|
|
render_devices = render_devices.split(',')
|
2022-11-14 06:53:22 +01:00
|
|
|
|
2022-11-15 07:52:55 +01:00
|
|
|
config['render_devices'] = render_devices
|
2022-11-14 06:53:22 +01:00
|
|
|
|
|
|
|
@app.post('/render')
|
|
|
|
def render(req : task_manager.ImageRequest):
|
2022-10-15 09:28:20 +02:00
|
|
|
try:
|
2022-11-08 12:24:15 +01:00
|
|
|
save_model_to_config(req.use_stable_diffusion_model, req.use_vae_model)
|
2022-10-28 16:36:44 +02:00
|
|
|
req.use_stable_diffusion_model = resolve_ckpt_to_use(req.use_stable_diffusion_model)
|
2022-11-08 12:24:15 +01:00
|
|
|
req.use_vae_model = resolve_vae_to_use(req.use_vae_model)
|
2022-10-15 09:28:20 +02:00
|
|
|
new_task = task_manager.render(req)
|
|
|
|
response = {
|
|
|
|
'status': str(task_manager.current_state),
|
2022-10-17 03:41:39 +02:00
|
|
|
'queue': len(task_manager.tasks_queue),
|
2022-10-15 09:28:20 +02:00
|
|
|
'stream': f'/image/stream/{req.session_id}/{id(new_task)}',
|
|
|
|
'task': id(new_task)
|
|
|
|
}
|
|
|
|
return JSONResponse(response, headers=NOCACHE_HEADERS)
|
|
|
|
except ChildProcessError as e: # Render thread is dead
|
2022-10-18 08:30:30 +02:00
|
|
|
raise HTTPException(status_code=500, detail=f'Rendering thread has died.') # HTTP500 Internal Server Error
|
2022-10-15 09:28:20 +02:00
|
|
|
except ConnectionRefusedError as e: # Unstarted task pending, deny queueing more than one.
|
2022-10-18 08:30:30 +02:00
|
|
|
raise HTTPException(status_code=503, detail=f'Session {req.session_id} has an already pending task.') # HTTP503 Service Unavailable
|
2022-10-15 09:28:20 +02:00
|
|
|
except Exception as e:
|
2022-10-18 08:30:30 +02:00
|
|
|
raise HTTPException(status_code=500, detail=str(e))
|
2022-10-14 09:47:25 +02:00
|
|
|
|
|
|
|
@app.get('/image/stream/{session_id:str}/{task_id:int}')
|
|
|
|
def stream(session_id:str, task_id:int):
|
|
|
|
#TODO Move to WebSockets ??
|
2022-10-22 19:52:13 +02:00
|
|
|
task = task_manager.get_cached_task(session_id, update_ttl=True)
|
2022-10-18 08:30:30 +02:00
|
|
|
if not task: raise HTTPException(status_code=410, detail='No request received.') # HTTP410 Gone
|
|
|
|
if (id(task) != task_id): raise HTTPException(status_code=409, detail=f'Wrong task id received. Expected:{id(task)}, Received:{task_id}') # HTTP409 Conflict
|
2022-10-14 09:47:25 +02:00
|
|
|
if task.buffer_queue.empty() and not task.lock.locked():
|
|
|
|
if task.response:
|
|
|
|
#print(f'Session {session_id} sending cached response')
|
|
|
|
return JSONResponse(task.response, headers=NOCACHE_HEADERS)
|
2022-10-18 08:30:30 +02:00
|
|
|
raise HTTPException(status_code=425, detail='Too Early, task not started yet.') # HTTP425 Too Early
|
2022-10-14 09:47:25 +02:00
|
|
|
#print(f'Session {session_id} opened live render stream {id(task.buffer_queue)}')
|
2022-10-15 09:28:20 +02:00
|
|
|
return StreamingResponse(task.read_buffer_generator(), media_type='application/json')
|
2022-09-13 16:29:41 +02:00
|
|
|
|
2022-10-14 09:47:25 +02:00
|
|
|
@app.get('/image/stop')
|
|
|
|
def stop(session_id:str=None):
|
|
|
|
if not session_id:
|
2022-10-15 09:32:00 +02:00
|
|
|
if task_manager.current_state == task_manager.ServerStates.Online or task_manager.current_state == task_manager.ServerStates.Unavailable:
|
2022-10-18 08:30:30 +02:00
|
|
|
raise HTTPException(status_code=409, detail='Not currently running any tasks.') # HTTP409 Conflict
|
2022-10-15 09:28:20 +02:00
|
|
|
task_manager.current_state_error = StopAsyncIteration('')
|
2022-09-13 16:29:41 +02:00
|
|
|
return {'OK'}
|
2022-10-24 11:12:08 +02:00
|
|
|
task = task_manager.get_cached_task(session_id, update_ttl=False)
|
2022-10-18 08:30:30 +02:00
|
|
|
if not task: raise HTTPException(status_code=404, detail=f'Session {session_id} has no active task.') # HTTP404 Not Found
|
|
|
|
if isinstance(task.error, StopAsyncIteration): raise HTTPException(status_code=409, detail=f'Session {session_id} task is already stopped.') # HTTP409 Conflict
|
2022-10-14 09:47:25 +02:00
|
|
|
task.error = StopAsyncIteration('')
|
|
|
|
return {'OK'}
|
2022-09-13 16:29:41 +02:00
|
|
|
|
2022-10-14 09:47:25 +02:00
|
|
|
@app.get('/image/tmp/{session_id}/{img_id:int}')
|
2022-09-14 18:59:42 +02:00
|
|
|
def get_image(session_id, img_id):
|
2022-10-22 19:52:13 +02:00
|
|
|
task = task_manager.get_cached_task(session_id, update_ttl=True)
|
2022-10-18 08:30:30 +02:00
|
|
|
if not task: raise HTTPException(status_code=410, detail=f'Session {session_id} has not submitted a task.') # HTTP410 Gone
|
|
|
|
if not task.temp_images[img_id]: raise HTTPException(status_code=425, detail='Too Early, task data is not available yet.') # HTTP425 Too Early
|
2022-10-14 09:47:25 +02:00
|
|
|
try:
|
|
|
|
img_data = task.temp_images[img_id]
|
|
|
|
img_data.seek(0)
|
|
|
|
return StreamingResponse(img_data, media_type='image/jpeg')
|
|
|
|
except KeyError as e:
|
2022-10-18 08:30:30 +02:00
|
|
|
raise HTTPException(status_code=500, detail=str(e))
|
2022-09-14 18:59:42 +02:00
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
@app.get('/')
|
|
|
|
def read_root():
|
|
|
|
return FileResponse(os.path.join(SD_UI_DIR, 'index.html'), headers=NOCACHE_HEADERS)
|
2022-10-06 10:58:02 +02:00
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
@app.on_event("shutdown")
|
|
|
|
def shutdown_event(): # Signal render thread to close on shutdown
|
|
|
|
task_manager.current_state_error = SystemExit('Application shutting down.')
|
2022-09-02 10:28:36 +02:00
|
|
|
|
2022-09-24 12:25:45 +02:00
|
|
|
# don't log certain requests
|
|
|
|
class LogSuppressFilter(logging.Filter):
|
2022-09-09 17:35:24 +02:00
|
|
|
def filter(self, record: logging.LogRecord) -> bool:
|
2022-09-24 12:25:45 +02:00
|
|
|
path = record.getMessage()
|
|
|
|
for prefix in ACCESS_LOG_SUPPRESS_PATH_PREFIXES:
|
|
|
|
if path.find(prefix) != -1:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
logging.getLogger('uvicorn.access').addFilter(LogSuppressFilter())
|
2022-09-09 17:35:24 +02:00
|
|
|
|
2022-10-17 03:41:39 +02:00
|
|
|
# Start the task_manager
|
2022-10-28 16:36:44 +02:00
|
|
|
task_manager.default_model_to_load = resolve_ckpt_to_use()
|
2022-11-08 12:24:15 +01:00
|
|
|
task_manager.default_vae_to_load = resolve_vae_to_use()
|
2022-11-14 06:53:22 +01:00
|
|
|
|
|
|
|
def update_render_threads():
|
|
|
|
config = getConfig()
|
2022-11-16 07:50:25 +01:00
|
|
|
render_devices = config.get('render_devices', 'auto')
|
2022-11-14 06:53:22 +01:00
|
|
|
active_devices = task_manager.get_devices()['active'].keys()
|
|
|
|
|
|
|
|
print('requesting for render_devices', render_devices)
|
|
|
|
task_manager.update_render_threads(render_devices, active_devices)
|
|
|
|
|
|
|
|
update_render_threads()
|
2022-11-07 13:56:10 +01:00
|
|
|
|
2022-09-02 10:28:36 +02:00
|
|
|
# start the browser ui
|
2022-11-14 15:45:54 +01:00
|
|
|
def open_browser():
|
|
|
|
config = getConfig()
|
|
|
|
ui = config.get('ui', {})
|
2022-11-19 17:10:45 +01:00
|
|
|
net = config.get('net', {'listen_port':9000})
|
|
|
|
port = net.get('listen_port', 9000)
|
2022-11-14 15:45:54 +01:00
|
|
|
if ui.get('open_browser_on_start', True):
|
2022-11-19 17:10:45 +01:00
|
|
|
import webbrowser; webbrowser.open(f"http://localhost:{port}")
|
2022-11-14 15:45:54 +01:00
|
|
|
|
|
|
|
open_browser()
|