## Minor changes & fixes in 2.4.3
- [x]  Fix for SD Next compatibility Version: 3bcca6f9 3bcca6f9 06/07/2023.
- [x]  Add proper warning to SD Next users if they are using incompatible style parameters.
- [x]  Fix CozyNest=No which was not properly disabling Cozy Nest.
- [x]  Various fix and optimizations.
pull/178/head 2.4.3
Nevysha 2023-07-07 19:36:15 +02:00 committed by GitHub
parent a9bae13427
commit 68660059cc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 494 additions and 458 deletions

View File

@ -1,7 +1,13 @@
## Compatibility
- Automatic1111's webui 1.3.2 release.
- SD Next (Vlad's fork) Version: 4867dafa Fri Jun 23. (Not compatible with latest!)
- SD Next (Vlad's fork) Version: 3bcca6f9 06/07/2023
## Minor changes & fixes in 2.4.3
- [x] Fix for SD Next compatibility Version: 3bcca6f9 3bcca6f9 06/07/2023.
- [x] Add proper warning to SD Next users if they are using incompatible style parameters.
- [x] Fix CozyNest=No which was not properly disabling Cozy Nest.
- [x] Various fix and optimizations.
## Minor changes & fixes in 2.4.2
- [x] Sort folder tree by name

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,27 @@
//post build script run by Nodejs
//copy cozy-nest-style.css and cozy-nest-style-sdnext.css to cozy-nest-client/assets
import {copyFile } from 'fs/promises';
import {join} from 'path';
import { fileURLToPath } from 'url';
import * as path from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const cozyNestStyleCss = join(__dirname, 'main/cozy-nest-style.css');
const cozyNestStyleSdnextCss = join(__dirname, 'main/cozy-nest-style-sdnext.css');
const cozyNestStyleCssDest = join(__dirname, '../client/assets/cozy-nest-style.css');
const cozyNestStyleSdnextCssDest = join(__dirname, '../client/assets/cozy-nest-style-sdnext.css');
async function copyCss() {
await copyFile(cozyNestStyleCss, cozyNestStyleCssDest);
await copyFile(cozyNestStyleSdnextCss, cozyNestStyleSdnextCssDest);
}
(async () => {
await copyCss();
})();

View File

@ -8,17 +8,15 @@ import {CozyLogger} from "./main/CozyLogger.js";
import {startCozyNestImageBrowser} from "@image-browser/main.jsx";
import startCozyNestSettings from "@settings/main.jsx";
import {
dummyLoraCard, dummyControlNetBloc, dummySubdirs, getTheme, hasCozyNestNo
hasCozyNestNo, checkClientEnv
} from './main/cozy-utils.js';
import startCozyPrompt from "./cozy-prompt/main.jsx";
import {startExtraNetwork} from "./extra-network/main.jsx";
import {OverrideUiJs} from "./main/override_ui.js";
import CozyNestEventBus from "./CozyNestEventBus.js";
import {startCozyExtraNetwork} from "./cozy_extra_network/main.jsx";
import CozyModal from './main/modal/Module.jsx';
window.CozyTools = {
dummyLoraCard,
dummyControlNetBloc,
dummySubdirs,
stop:() => setTimeout(function(){debugger;}, 5000),
}
@ -27,6 +25,17 @@ window.CozyTools = {
export default async function cozyNestLoader() {
await fetchCozyNestConfig();
if (COZY_NEST_CONFIG.webui === WEBUI_SDNEXT) {
//add sdnext css
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = import.meta.env.VITE_CONTEXT === 'DEV' ?
'/cozy-nest-client/main/cozy-nest-style-sdnext.css'
:'/cozy-nest-client/assets/cozy-nest-style-sdnext.css';
document.head.appendChild(link);
}
await cozyNestModuleLoader(async () => {
startCozyNestSettings();
@ -46,9 +55,13 @@ export default async function cozyNestLoader() {
startCozyNestImageBrowser();
CozyNestEventBus.emit('cozy-nest-loaded');
// load modal module
await CozyModal.prepareReactHost();
CozyNestEventBus.emit('cozy-nest-loaded');
});
setTimeout(checkClientEnv, 1000); // small timer just for UX purposes
}
window.cozyNestLoader = cozyNestLoader;
@ -71,9 +84,6 @@ window.cozyNestLoader = cozyNestLoader;
cozyNestLoader();
})
}
else {
CozyLogger.init(false);
}
})();

View File

@ -0,0 +1,11 @@
body {
overflow: hidden !important;
}
.nevysha.skip-interrupt-wrapper {
justify-content: space-between;
}
.nevysha.skip-interrupt-wrapper button {
width: 50%;
}

View File

@ -1,5 +1,6 @@
import {CozyLogger} from "./CozyLogger.js";
import DOM_IDS from "./dom_ids.js";
import CozyModal from "./modal/Module.jsx";
export const getTheme = (modeFromConfig) => {
modeFromConfig = modeFromConfig || COZY_NEST_CONFIG.color_mode
@ -104,34 +105,25 @@ export function hideNativeUiExtraNetworkElement(prefix) {
tabs.style.display = 'none';
}
//dummy method
export const dummyLoraCard = () => {
const container = document.querySelector("#txt2img_lora_cards");
// Get the first child element of the container
const firstChild = container.firstChild;
// Duplicate the first child element 100 times and append them to the fragment
for (let i = 0; i < 100; i++) {
const clone = container.querySelector('.card').cloneNode(true);
container.insertBefore(clone, firstChild);
export function checkClientEnv() {
//legacy : check if url contains __theme which is deprecated
if (window.location.href.includes('__theme')) {
CozyModal.showToast(
'warning',
"Warning",
"The __theme parameter is deprecated for CozyNest. Please remove it from URL and use Cozy Nest settings instead.",
)
}
};
export const dummyControlNetBloc = () => {
const container = document.querySelector("#txt2img_controlnet");
// Get the parent element of the container
const parent = container.parentElement;
// Duplicate the first child element 100 times and append them to the fragment
for (let i = 0; i < 100; i++) {
const clone = parent.cloneNode(true);
parent.parentElement.insertBefore(clone, parent);
// check for gradio theme (vlad's fork)
if (document.querySelector('#setting_gradio_theme input')) {
const gradioTheme = document.querySelector('#setting_gradio_theme input').value
if (gradioTheme !== 'gradio/default' && gradioTheme !== '' && gradioTheme !== 'Default') {
CozyModal.showToast(
'error',
'Incompatible theme',
'Cozy Nest may not be compatible with this theme. Please switch to the default theme. You can do this by going to the settings tab and selecting "gradio/default" or "Default" from the dropdown menu under "User interface > UI theme".',
90000
)
}
}
export const dummySubdirs = () => {
const $subdirs = $('#txt2img_lora_subdirs');
$subdirs.append($subdirs.html());
}

View File

@ -12,92 +12,26 @@ import {
useDisclosure, useToast
} from "@chakra-ui/react";
export function CozyModalSimple() {
const listen = 'CozyModalSimple'
const { isOpen, onOpen, onClose } = useDisclosure()
const [text, setText] = React.useState('')
useEffect(() => {
// listen to events on listen
const _eventFn = ({msg}) => {
setText(msg)
onOpen()
}
EventBus.on(listen, _eventFn)
return () => {
// unlisten to events on listen
EventBus.off(listen, _eventFn)
}
}, [])
return (
<>
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Modal Title</ModalHeader>
<ModalCloseButton />
<ModalBody>
<p>{text}</p>
</ModalBody>
<ModalFooter>
<Button colorScheme='blue' mr={3} onClick={onClose}>
Close
</Button>
<Button variant='ghost'>Secondary Action</Button>
</ModalFooter>
</ModalContent>
</Modal>
</>
)
}
export function CozyModalRich() {
const listen = 'CozyModalRich'
useEffect(() => {
// listen to events on listen
const _eventFn = (args) => {
CozyLogger.debug("CozyModalRoot event", listen, args);
}
EventBus.on(listen, _eventFn)
return () => {
// unlisten to events on listen
EventBus.off(listen, _eventFn)
}
}, [])
return (
<div className="CozyModalRich">
</div>
)
}
export function CozyToast() {
export function CozyToast({registerReady}) {
const listen = 'CozyToast'
const toast = useToast()
useEffect(() => {
// listen to events on listen
const _eventFn = ({title, msg, status}) => {
const _eventFn = ({title, msg, status, duration}) => {
duration = duration || 9000
toast({
title: title,
description: msg,
status: status,
duration: 9000,
duration: duration,
isClosable: true,
})
}
EventBus.on(listen, _eventFn)
registerReady()
return () => {
// unlisten to events on listen
EventBus.off(listen, _eventFn)

View File

@ -2,7 +2,7 @@ import React from "react";
import ReactDOM from "react-dom/client";
import {ChakraProvider} from "@chakra-ui/react";
import {theme} from "../../chakra/chakra-theme.ts";
import {CozyModalRich, CozyModalSimple, CozyToast} from "./Modal.jsx";
import {CozyToast} from "./Modal.jsx";
import EventEmitter from 'eventemitter3';
class EventBusClass extends EventEmitter{
@ -18,51 +18,44 @@ export const EventBus = new EventBusClass();
let _ready = false;
function prepareReactHost() {
async function prepareReactHost() {
return new Promise((resolve, reject) => {
_prepareReactHost(resolve);
})
}
function _prepareReactHost(resolve) {
// insert a div at the end of the body
const _hostCozyModalSimple =
`<div id="CozyModalSimple"/>`;
const _hostCozyModalRich =
`<div id="CozyModalRich"/>`;
const _hostCozyToast =
`<div id="CozyToast"/>`;
document.body.insertAdjacentHTML("beforeend", _hostCozyModalSimple);
document.body.insertAdjacentHTML("beforeend", _hostCozyModalRich);
document.body.insertAdjacentHTML("beforeend", _hostCozyToast);
ReactDOM.createRoot(document.getElementById(`CozyModalSimple`)).render(
<React.StrictMode>
<ChakraProvider theme={theme} >
<CozyModalSimple />
</ChakraProvider>
</React.StrictMode>,
)
ReactDOM.createRoot(document.getElementById(`CozyModalRich`)).render(
<React.StrictMode>
<ChakraProvider theme={theme} >
<CozyModalRich />
</ChakraProvider>
</React.StrictMode>,
)
let _isReady = 0;
let _readyNeed = 0;
const registerReady = () => {
_readyNeed++;
return () => {
_isReady++;
if (_isReady === _readyNeed) {
_ready = true;
resolve();
}
}
}
ReactDOM.createRoot(document.getElementById(`CozyToast`)).render(
<React.StrictMode>
<ChakraProvider theme={theme} >
<CozyToast />
<CozyToast registerReady={registerReady()}/>
</ChakraProvider>
</React.StrictMode>,
)
_ready = true;
}
let CozyModal = {
prepareReactHost,
showModalSimple: (msg) => EventBus.emit('CozyModalSimple', {msg}),
showModalRich: () => EventBus.emit('CozyModalRich'),
showToast: (status, title, msg) => EventBus.emit('CozyToast', {status, title, msg}),
showToast: (status, title, msg, duration) => EventBus.emit('CozyToast', {status, title, msg, duration}),
};
//hook on modal event
window.ModalEventBus = EventBus;

View File

@ -30,7 +30,6 @@ import clearGeneratedImage from './tweaks/clear-generated-image.js'
import {createAlertDiv, showAlert} from "./tweaks/cozy-alert.js";
import DOM_IDS from "./dom_ids.js";
import CozyNestEventBus from "../CozyNestEventBus.js";
import Modal from './modal/Module.jsx'
const addDraggable = ({prefix}) => {
@ -1007,17 +1006,6 @@ const onLoad = (done, error) => {
// log time for onLoad execution after gradio has loaded
SimpleTimer.time(COZY_NEST_DOM_TWEAK_LOAD_DURATION);
// load modal module
Modal.prepareReactHost();
// check for gradio theme (vlad's fork)
if (document.querySelector('#setting_gradio_theme input')) {
const gradioTheme = document.querySelector('#setting_gradio_theme input').value
if (gradioTheme !== 'gradio/default' && gradioTheme !== '' && gradioTheme !== 'Default') {
showAlert('Warning','Cozy Nest may not be compatible with this theme. Please switch to the default theme. You can do this by going to the settings tab and selecting "gradio/default" or "Default" from the dropdown menu under "User interface > UI theme".')
}
}
//add quicksettings_gap after checkpoint reload button
// Select the target element
const refresh_sd_model_checkpoint = document.querySelector('#refresh_sd_model_checkpoint');
@ -1148,14 +1136,6 @@ const onLoad = (done, error) => {
//add observer for .options resize
addOptionsObserver();
//legacy : check if url contains __theme which is deprecated
if (window.location.href.includes('__theme')) {
showAlert(
"Warning",
"The __theme parameter is deprecated for CozyNest. Please remove it from URL and use Cozy Nest settings instead.",
)
}
/* --------------- TWEAK SOME EXTENSION --------------- */
//if AWQ-container is present in COZY_NEST_CONFIG.extensions array from localStorage, tweak AWQ
if (COZY_NEST_CONFIG.extensions

View File

@ -6,6 +6,7 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"build-cozy": "vite build && node cozy.build.js",
"preview": "vite preview"
},
"dependencies": {

View File

@ -30,6 +30,20 @@
});
}
document.addEventListener("DOMContentLoaded", async function() {
try {
//check if the param CozyNest=No is present in the url
const urlParams = new URLSearchParams(window.location.search);
const cozyNestParam = urlParams.get('CozyNest');
//if the param is present and set to No,
// or if url contains #CozyNest=No
// disable Cozy Nest
if (cozyNestParam === "No" || window.location.hash.includes("CozyNest=No")) {
console.log("CozyNest: disabled by url param")
return;
}
// Create a new link element and set its attributes
const cozyNestCss = document.createElement('link');
cozyNestCss.rel = 'stylesheet';
@ -39,8 +53,6 @@
// Append the link element to the document head
document.head.appendChild(cozyNestCss);
document.addEventListener("DOMContentLoaded", async function() {
try {
await jsDynamicLoad(`/cozy-nest-client/assets/index.js?t=${Date.now()}`);
cozyNestLoader();
}

View File

@ -1,7 +1,3 @@
import json
import os
from pathlib import Path
from modules import shared
@ -18,22 +14,65 @@ class CozyLoggerClass:
def __init__(self, name: str):
self.name = name
self.tag = f"[{self.name}]"
self.log_enabled = CozyLoggerClass.LOG_ENABLED
from scripts.cozy_lib.CozyNestConfig import CozyNestConfig
self.config = CozyNestConfig.instance()
if self.config.is_sdnext():
import logging
if CozyLoggerClass.LOG_ENABLED:
logging.getLogger(name).setLevel(logging.DEBUG)
else:
logging.getLogger(name).setLevel(logging.INFO)
base_log = logging.getLogger("sd")
logging.getLogger(name).handlers = base_log.handlers
def format_message(self, message: str):
if self.config.is_sdnext():
return f"{self.tag} {message}"
else:
return message
def debug(self, message: str):
message = self.format_message(message)
if self.config.is_sdnext():
import logging
logging.getLogger(self.name).debug(message)
else:
if self.log_enabled:
print(f"[{self.name}:DEBUG] {message}")
def warning(self, message: str):
message = self.format_message(message)
if self.config.is_sdnext():
import logging
logging.getLogger(self.name).warning(message)
else:
print(f"[{self.name}:WARNING] {message}")
def info(self, message: str):
message = self.format_message(message)
if self.config.is_sdnext():
import logging
logging.getLogger(self.name).info(message)
else:
print(f"[{self.name}:INFO] {message}")
def error(self, message: str, exception: Exception = None):
message = self.format_message(message)
if self.config.is_sdnext():
import logging
logging.getLogger(self.name).error(message, exc_info=exception)
else:
print(f"[{self.name}:ERROR] {message}")
if exception is not None:
print(exception)
CozyLogger = CozyLoggerClass("Cozy")
CozyLogger = CozyLoggerClass("CozyNest")
if CozyLoggerClass.LOG_ENABLED:
CozyLogger.warning("Logger enabled")
CozyLogger.debug("Logger enabled")
CozyLoggerExtNe = CozyLoggerClass("Cozy:ExtNe")
CozyLoggerConfig = CozyLoggerClass("Cozy:Config")

View File

@ -3,27 +3,31 @@ import os
from modules import shared
from scripts.cozy_lib import Static
from scripts.cozy_lib.tools import output_folder_array
from scripts.cozy_lib.CozyLogger import CozyLoggerConfig
class CozyNestConfig:
WEBUI_AUTO = 'auto1111'
WEBUI_SD_NEXT = 'sd.next'
WEBUI_UNKNOWN = 'unknown'
_instance = None
def __init__(self):
config = self.get_dict_from_config()
self.config = {**CozyNestConfig.get_default_settings(), **config}
def init(self):
if self.config['webui'] == 'unknown' and hasattr(shared, 'get_version'):
if self.config['webui'] == CozyNestConfig.WEBUI_UNKNOWN and hasattr(shared, 'get_version'):
version = shared.get_version()
# check if the 'app' is 'sd.next'
if version['app'] == 'sd.next':
self.config['webui'] = 'sd.next'
if version['app'] == CozyNestConfig.WEBUI_SD_NEXT:
self.config['webui'] = CozyNestConfig.WEBUI_SD_NEXT
self.config['fetch_output_folder_from_a1111_settings'] = False
else:
self.config['webui'] = 'auto1111'
self.config['webui'] = CozyNestConfig.WEBUI_AUTO
self.save_settings(self.config)
if self.config['webui'] == 'sd.next':
if self.config['webui'] == CozyNestConfig.WEBUI_SD_NEXT:
self.config['fetch_output_folder_from_a1111_settings'] = False
# check if cnib_output_folder is empty and/or need to be fetched from a1111 settings
@ -34,6 +38,7 @@ class CozyNestConfig:
if self.config.get('fetch_output_folder_from_a1111_settings'):
# merge cnib_output_folder output_folder_array()
from scripts.cozy_lib.Static import output_folder_array
cnib_output_folder = cnib_output_folder + list(set(output_folder_array()) - set(cnib_output_folder))
self.config['cnib_output_folder'] = cnib_output_folder
@ -41,6 +46,12 @@ class CozyNestConfig:
# save the merged settings
self.save_settings(self.config)
def is_sdnext(self):
return self.config['webui'] == CozyNestConfig.WEBUI_SD_NEXT
def is_auto1111(self):
return self.config['webui'] == CozyNestConfig.WEBUI_AUTO
def migrate(self):
current_version = CozyNestConfig.get_version()
current_version_code = CozyNestConfig.normalize_version(current_version)
@ -51,8 +62,6 @@ class CozyNestConfig:
local_version_code = CozyNestConfig.normalize_version(local_version)
if local_version_code < current_version_code:
CozyLoggerConfig.debug(f"current_version: {current_version} current_version_code: {current_version_code}")
CozyLoggerConfig.debug(f"local_version: {local_version} local_version_code: {local_version_code}")
if local_version_code < CozyNestConfig.normalize_version('2.4.0'):
self.config['enable_extra_network_tweaks'] = False
self.config['enable_cozy_extra_networks'] = True
@ -61,6 +70,14 @@ class CozyNestConfig:
self.simple_save_settings()
@staticmethod
def instance():
if CozyNestConfig._instance is None:
CozyNestConfig._instance = CozyNestConfig()
CozyNestConfig._instance.init()
CozyNestConfig._instance.migrate()
return CozyNestConfig._instance
@staticmethod
def get_version():
with open(Static.VERSION_FILENAME, 'r') as f:

View File

@ -1,6 +1,29 @@
import os
from pathlib import Path
from modules import shared, scripts
EXTENSION_FOLDER = Path(__file__).parent.parent.parent
CONFIG_FILENAME = Path(EXTENSION_FOLDER, "nevyui_settings.json")
VERSION_FILENAME = Path(EXTENSION_FOLDER, "version_data.json")
CACHE_FILENAME = Path(EXTENSION_FOLDER, "data", "images.cache")
def output_folder_array():
outdir_txt2img_samples = shared.opts.data['outdir_txt2img_samples']
outdir_img2img_samples = shared.opts.data['outdir_img2img_samples']
outdir_extras_samples = shared.opts.data['outdir_extras_samples']
base_dir = scripts.basedir()
# check if outdir_txt2img_samples is a relative path
if not os.path.isabs(outdir_txt2img_samples):
outdir_txt2img_samples = os.path.normpath(os.path.join(base_dir, outdir_txt2img_samples))
if not os.path.isabs(outdir_img2img_samples):
outdir_img2img_samples = os.path.normpath(os.path.join(base_dir, outdir_img2img_samples))
if not os.path.isabs(outdir_extras_samples):
outdir_extras_samples = os.path.normpath(os.path.join(base_dir, outdir_extras_samples))
images_folders = [
outdir_txt2img_samples,
outdir_img2img_samples,
outdir_extras_samples,
]
return images_folders

View File

@ -8,6 +8,7 @@ from fastapi import Response, Request
from modules import sd_hijack, shared, sd_models
from scripts.cozy_lib.CozyLogger import CozyLoggerExtNe
from scripts.cozy_lib.CozyNestConfig import CozyNestConfig
def format_path_array(paths, _type, validator):
@ -36,6 +37,11 @@ def format_path_array(paths, _type, validator):
# credit to https://github.com/DominikDoom/a1111-sd-webui-tagcomplete
class CozyExtraNetworksClass:
def __init__(self):
self.MODEL_PATH = None
self.LYCO_PATH = None
self.LORA_PATH = None
self.HYP_PATH = None
self.EMB_PATH = None
try:
from modules.paths import extensions_dir, script_path
except ImportError:
@ -54,24 +60,11 @@ class CozyExtraNetworksClass:
# The extension base path
self.EXT_PATH = self.FILE_DIR.joinpath('extensions')
self.EMB_PATH = Path(shared.cmd_opts.embeddings_dir)
self.HYP_PATH = Path(shared.cmd_opts.hypernetwork_dir)
try:
self.LORA_PATH = Path(shared.cmd_opts.lora_dir)
except AttributeError:
self.LORA_PATH = None
try:
self.LYCO_PATH = Path(shared.cmd_opts.lyco_dir)
except AttributeError:
self.LYCO_PATH = None
try:
ckpt_dir = shared.cmd_opts.ckpt_dir or sd_models.model_path
self.MODEL_PATH = Path(ckpt_dir)
except AttributeError or TypeError:
self.MODEL_PATH = None
config = CozyNestConfig.instance()
if config.is_auto1111():
self.init_for_a1111()
else:
self.init_for_sdnext()
# print all paths
CozyLoggerExtNe.debug(f"FILE_DIR: {self.FILE_DIR}")
@ -82,6 +75,27 @@ class CozyExtraNetworksClass:
CozyLoggerExtNe.debug(f"LYCO_PATH: {self.LYCO_PATH}")
CozyLoggerExtNe.debug(f"MODEL_PATH: {self.MODEL_PATH}")
def init_for_a1111(self):
self.EMB_PATH = Path(shared.cmd_opts.embeddings_dir)
self.HYP_PATH = Path(shared.cmd_opts.hypernetwork_dir)
try:
self.LORA_PATH = Path(shared.cmd_opts.lora_dir)
except AttributeError:
self.LORA_PATH = None
try:
self.LYCO_PATH = Path(shared.cmd_opts.lyco_dir)
except AttributeError:
self.LYCO_PATH = None
try:
ckpt_dir = shared.cmd_opts.ckpt_dir or sd_models.model_path
self.MODEL_PATH = Path(ckpt_dir)
except AttributeError or TypeError:
self.MODEL_PATH = None
def init_for_sdnext(self):
# TODO NEVYSHA implement sd next compliant
self.init_for_a1111()
def get_hypernetworks(self):
"""Write a list of all hypernetworks"""
@ -171,7 +185,7 @@ class CozyExtraNetworksClass:
results = sorted(results, key=lambda x: x["name"].lower())
except AttributeError:
print(
CozyLoggerExtNe.warning(
"tag_autocomplete_helper: Old webui version or unrecognized model shape, using fallback for embedding completion.")
# Get a list of all embeddings in the folder
all_embeds = [str(e.relative_to(self.EMB_PATH)) for e in self.EMB_PATH.rglob("*") if

View File

@ -5,10 +5,11 @@ import websockets
from websockets.server import serve
from scripts.cozy_lib import tools
from scripts.cozy_lib.CozyLogger import CozyLoggerImageBrowser as CozyLogger
async def start_server(images_folders, server_port, stopper):
print(f"CozyNestSocket: Starting socket server on localhost:{server_port}...")
CozyLogger.info(f"CozyNestSocket: Starting socket server on localhost:{server_port}...")
CLIENTS = set()
@ -17,7 +18,7 @@ async def start_server(images_folders, server_port, stopper):
CLIENTS.add(websocket)
while True:
if stopper.is_set():
print(f"CozyNestSocket: Stopping socket server on localhost:{server_port}...")
CozyLogger.info(f"CozyNestSocket: Stopping socket server on localhost:{server_port}...")
break
# Receive data from the client
@ -28,8 +29,7 @@ async def start_server(images_folders, server_port, stopper):
try:
res = await process(data)
except Exception as e:
print(f"CozyNestSocket: Error while processing data: {data}")
print(e)
CozyLogger.error(f"CozyNestSocket: Error while processing data: {data}", e)
res = json.dumps({
'what': 'error',
'data': 'None',
@ -64,7 +64,7 @@ async def start_server(images_folders, server_port, stopper):
})
else:
print(f"CozyNestSocket: Unknown data: {data}")
CozyLogger.info(f"CozyNestSocket: Unknown data: {data}")
return json.dumps({
'what': 'error',
'data': 'None',
@ -103,6 +103,6 @@ async def start_server(images_folders, server_port, stopper):
while True:
await asyncio.sleep(1)
if stopper.is_set():
print(f"CozyNestSocket: Stopping socket server on localhost:{server_port}...")
CozyLogger.info(f"CozyNestSocket: Stopping socket server on localhost:{server_port}...")
stop.set_result(True)
break

View File

@ -12,26 +12,6 @@ from scripts.cozy_lib import Static
from scripts.cozy_lib.CozyLogger import CozyLoggerImageBrowser as Logger
def output_folder_array():
outdir_txt2img_samples = shared.opts.data['outdir_txt2img_samples']
outdir_img2img_samples = shared.opts.data['outdir_img2img_samples']
outdir_extras_samples = shared.opts.data['outdir_extras_samples']
base_dir = scripts.basedir()
# check if outdir_txt2img_samples is a relative path
if not os.path.isabs(outdir_txt2img_samples):
outdir_txt2img_samples = os.path.normpath(os.path.join(base_dir, outdir_txt2img_samples))
if not os.path.isabs(outdir_img2img_samples):
outdir_img2img_samples = os.path.normpath(os.path.join(base_dir, outdir_img2img_samples))
if not os.path.isabs(outdir_extras_samples):
outdir_extras_samples = os.path.normpath(os.path.join(base_dir, outdir_extras_samples))
images_folders = [
outdir_txt2img_samples,
outdir_img2img_samples,
outdir_extras_samples,
]
return images_folders
def get_image_exif(path: str):
try:
image = Image.open(path)

View File

@ -21,7 +21,7 @@ from scripts.cozy_lib import tools
from scripts.cozy_lib.CozyLogger import CozyLogger
from scripts.cozy_lib.CozyNestConfig import CozyNestConfig
from scripts.cozy_lib.cozynest_image_browser import start_server
from scripts.cozy_lib.tools import output_folder_array
from scripts.cozy_lib.Static import output_folder_array
def request_restart():
@ -43,7 +43,7 @@ def update():
# perform git pull in the extension folder
output = subprocess.check_output([git, '-C', subdir, 'pull', '--autostash'])
print(output.decode('utf-8'))
CozyLogger.info(output.decode('utf-8'))
def is_port_free(port):
@ -62,13 +62,13 @@ def is_port_free(port):
def serv_img_browser_socket(server_port=3333, auto_search_port=True, cnib_output_folder=None):
if cnib_output_folder is None or cnib_output_folder == []:
print("CozyNest: No output folder specified for image browser. Aborting.")
CozyLogger.error("CozyNest: No output folder specified for image browser. Aborting.")
return
# check if port is free
if auto_search_port:
while not is_port_free(server_port) and server_port < 64000:
print(f"CozyNest: Port {server_port} is already in use. Searching for a free port.")
CozyLogger.info(f"CozyNest: Port {server_port} is already in use. Searching for a free port.")
server_port += 1
try:
@ -79,8 +79,7 @@ def serv_img_browser_socket(server_port=3333, auto_search_port=True, cnib_output
start_server_in_dedicated_process(cnib_output_folder, server_port)
return server_port
except Exception as e:
print("CozyNest: Error while starting socket server")
print(e)
CozyLogger.error("CozyNest: Error while starting socket server", e)
def start_server_in_dedicated_process(_images_folders, server_port):
@ -132,11 +131,9 @@ _server_port = None
def on_ui_tabs():
global _server_port
config = CozyNestConfig()
config.init()
config.migrate()
config = CozyNestConfig.instance()
CozyLogger.info(f"version: {config.get('version')}")
CozyLogger.info(f"version: {config.get('version')} on {config.get('webui')}")
# check if the user has disabled the image browser
disable_image_browser_value = config.get('disable_image_browser')
@ -152,7 +149,7 @@ def on_ui_tabs():
)
_server_port = server_port
else:
print("CozyNest: Image browser is disabled. To enable it, go to the CozyNest settings.")
CozyLogger.info("CozyNest: Image browser is disabled. To enable it, go to the CozyNest settings.")
def on_image_saved(gen_params: script_callbacks.ImageSaveParams):
base_dir = scripts.basedir()
@ -226,7 +223,7 @@ def cozy_nest_api(_: Any, app: FastAPI, **kwargs):
# Access POST parameters
data = await request.json()
config = CozyNestConfig()
config = CozyNestConfig.instance()
config.save_settings(data)
@ -234,7 +231,7 @@ def cozy_nest_api(_: Any, app: FastAPI, **kwargs):
@app.delete("/cozy-nest/config")
async def delete_config():
config = CozyNestConfig()
config = CozyNestConfig.instance()
config.reset_settings()
return {"message": "Config deleted successfully"}
@ -275,7 +272,7 @@ def cozy_nest_api(_: Any, app: FastAPI, **kwargs):
async def delete_index():
global _server_port
config = CozyNestConfig()
config = CozyNestConfig.instance()
cnib_output_folder = config.get('cnib_output_folder')
if cnib_output_folder and cnib_output_folder != "":
tools.delete_index()
@ -305,7 +302,7 @@ def cozy_nest_api(_: Any, app: FastAPI, **kwargs):
# do nothing for now
return Response(status_code=501, content="unimplemented")
config = CozyNestConfig()
config = CozyNestConfig.instance()
archive_path = config.get('archive_path')
if not archive_path or archive_path == "":
# return {"message": "archive path not set"}

View File

@ -1,3 +1,3 @@
{
"version": "2.4.2"
"version": "2.4.3"
}