Meismaxandmaxisme commited on
Commit
d6beae9
·
verified ·
1 Parent(s): 506dcf4

Upload 8 files

Browse files
Files changed (8) hide show
  1. __init__.py +0 -0
  2. app_settings.py +124 -0
  3. constants.py +26 -0
  4. context.py +109 -0
  5. image_ops.py +15 -0
  6. paths.py +110 -0
  7. state.py +42 -0
  8. utils.py +38 -0
__init__.py ADDED
File without changes
app_settings.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+ from os import makedirs, path
3
+
4
+ import yaml
5
+ from constants import (
6
+ LCM_LORA_MODELS_FILE,
7
+ LCM_MODELS_FILE,
8
+ OPENVINO_LCM_MODELS_FILE,
9
+ SD_MODELS_FILE,
10
+ )
11
+ from paths import FastStableDiffusionPaths, join_paths
12
+ from utils import get_files_in_dir, get_models_from_text_file
13
+
14
+ from models.settings import Settings
15
+
16
+
17
+ class AppSettings:
18
+ def __init__(self):
19
+ self.config_path = FastStableDiffusionPaths().get_app_settings_path()
20
+ self._stable_diffsuion_models = get_models_from_text_file(
21
+ FastStableDiffusionPaths().get_models_config_path(SD_MODELS_FILE)
22
+ )
23
+ self._lcm_lora_models = get_models_from_text_file(
24
+ FastStableDiffusionPaths().get_models_config_path(LCM_LORA_MODELS_FILE)
25
+ )
26
+ self._openvino_lcm_models = get_models_from_text_file(
27
+ FastStableDiffusionPaths().get_models_config_path(OPENVINO_LCM_MODELS_FILE)
28
+ )
29
+ self._lcm_models = get_models_from_text_file(
30
+ FastStableDiffusionPaths().get_models_config_path(LCM_MODELS_FILE)
31
+ )
32
+ self._gguf_diffusion_models = get_files_in_dir(
33
+ join_paths(FastStableDiffusionPaths().get_gguf_models_path(), "diffusion")
34
+ )
35
+ self._gguf_clip_models = get_files_in_dir(
36
+ join_paths(FastStableDiffusionPaths().get_gguf_models_path(), "clip")
37
+ )
38
+ self._gguf_vae_models = get_files_in_dir(
39
+ join_paths(FastStableDiffusionPaths().get_gguf_models_path(), "vae")
40
+ )
41
+ self._gguf_t5xxl_models = get_files_in_dir(
42
+ join_paths(FastStableDiffusionPaths().get_gguf_models_path(), "t5xxl")
43
+ )
44
+ self._config = None
45
+
46
+ @property
47
+ def settings(self):
48
+ return self._config
49
+
50
+ @property
51
+ def stable_diffsuion_models(self):
52
+ return self._stable_diffsuion_models
53
+
54
+ @property
55
+ def openvino_lcm_models(self):
56
+ return self._openvino_lcm_models
57
+
58
+ @property
59
+ def lcm_models(self):
60
+ return self._lcm_models
61
+
62
+ @property
63
+ def lcm_lora_models(self):
64
+ return self._lcm_lora_models
65
+
66
+ @property
67
+ def gguf_diffusion_models(self):
68
+ return self._gguf_diffusion_models
69
+
70
+ @property
71
+ def gguf_clip_models(self):
72
+ return self._gguf_clip_models
73
+
74
+ @property
75
+ def gguf_vae_models(self):
76
+ return self._gguf_vae_models
77
+
78
+ @property
79
+ def gguf_t5xxl_models(self):
80
+ return self._gguf_t5xxl_models
81
+
82
+ def load(self, skip_file=False):
83
+ if skip_file:
84
+ print("Skipping config file")
85
+ settings_dict = self._load_default()
86
+ self._config = Settings.model_validate(settings_dict)
87
+ else:
88
+ if not path.exists(self.config_path):
89
+ base_dir = path.dirname(self.config_path)
90
+ if not path.exists(base_dir):
91
+ makedirs(base_dir)
92
+ try:
93
+ print("Settings not found creating default settings")
94
+ with open(self.config_path, "w") as file:
95
+ yaml.dump(
96
+ self._load_default(),
97
+ file,
98
+ )
99
+ except Exception as ex:
100
+ print(f"Error in creating settings : {ex}")
101
+ exit()
102
+ try:
103
+ with open(self.config_path) as file:
104
+ settings_dict = yaml.safe_load(file)
105
+ self._config = Settings.model_validate(settings_dict)
106
+ except Exception as ex:
107
+ print(f"Error in loading settings : {ex}")
108
+
109
+ def save(self):
110
+ try:
111
+ with open(self.config_path, "w") as file:
112
+ tmp_cfg = deepcopy(self._config)
113
+ tmp_cfg.lcm_diffusion_setting.init_image = None
114
+ configurations = tmp_cfg.model_dump(
115
+ exclude=["init_image"],
116
+ )
117
+ if configurations:
118
+ yaml.dump(configurations, file)
119
+ except Exception as ex:
120
+ print(f"Error in saving settings : {ex}")
121
+
122
+ def _load_default(self) -> dict:
123
+ default_config = Settings()
124
+ return default_config.model_dump()
constants.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os import environ, cpu_count
2
+
3
+ cpu_cores = cpu_count()
4
+ cpus = cpu_cores // 2 if cpu_cores else 0
5
+ APP_VERSION = "v1.0.0 beta 252"
6
+ LCM_DEFAULT_MODEL = "stabilityai/sd-turbo"
7
+ LCM_DEFAULT_MODEL_OPENVINO = "rupeshs/sd-turbo-openvino"
8
+ APP_NAME = "FastSD CPU"
9
+ APP_SETTINGS_FILE = "settings.yaml"
10
+ RESULTS_DIRECTORY = "results"
11
+ CONFIG_DIRECTORY = "configs"
12
+ DEVICE = environ.get("DEVICE", "cpu")
13
+ SD_MODELS_FILE = "stable-diffusion-models.txt"
14
+ LCM_LORA_MODELS_FILE = "lcm-lora-models.txt"
15
+ OPENVINO_LCM_MODELS_FILE = "openvino-lcm-models.txt"
16
+ TAESD_MODEL = "madebyollin/taesd"
17
+ TAESDXL_MODEL = "madebyollin/taesdxl"
18
+ TAESD_MODEL_OPENVINO = "rupeshs/taesd-ov"
19
+ LCM_MODELS_FILE = "lcm-models.txt"
20
+ TAESDXL_MODEL_OPENVINO = "rupeshs/taesdxl-openvino"
21
+ LORA_DIRECTORY = "lora_models"
22
+ CONTROLNET_DIRECTORY = "controlnet_models"
23
+ MODELS_DIRECTORY = "models"
24
+ GGUF_THREADS = environ.get("GGUF_THREADS", cpus)
25
+ TAEF1_MODEL_OPENVINO = "rupeshs/taef1-openvino"
26
+ SAFETY_CHECKER_MODEL = "Falconsai/nsfw_image_detection"
context.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pprint import pprint
2
+ from time import perf_counter
3
+ from traceback import print_exc
4
+ from typing import Any
5
+
6
+ from app_settings import Settings
7
+ from backend.image_saver import ImageSaver
8
+ from backend.lcm_text_to_image import LCMTextToImage
9
+ from backend.models.lcmdiffusion_setting import DiffusionTask
10
+ from backend.utils import get_blank_image
11
+ from models.interface_types import InterfaceType
12
+
13
+
14
+ class Context:
15
+ def __init__(
16
+ self,
17
+ interface_type: InterfaceType,
18
+ device="cpu",
19
+ ):
20
+ self.interface_type = interface_type.value
21
+ self.lcm_text_to_image = LCMTextToImage(device)
22
+ self._latency = 0
23
+ self._error = ""
24
+
25
+ @property
26
+ def latency(self):
27
+ return self._latency
28
+
29
+ @property
30
+ def error(self):
31
+ return self._error
32
+
33
+ def generate_text_to_image(
34
+ self,
35
+ settings: Settings,
36
+ reshape: bool = False,
37
+ device: str = "cpu",
38
+ save_config=True,
39
+ ) -> Any:
40
+ try:
41
+ self._error = ""
42
+ tick = perf_counter()
43
+ from state import get_settings
44
+
45
+ if (
46
+ settings.lcm_diffusion_setting.diffusion_task
47
+ == DiffusionTask.text_to_image.value
48
+ ):
49
+ settings.lcm_diffusion_setting.init_image = None
50
+
51
+ if save_config:
52
+ get_settings().save()
53
+
54
+ pprint(settings.lcm_diffusion_setting.model_dump())
55
+ if not settings.lcm_diffusion_setting.lcm_lora:
56
+ return None
57
+ self.lcm_text_to_image.init(
58
+ device,
59
+ settings.lcm_diffusion_setting,
60
+ )
61
+
62
+ images = self.lcm_text_to_image.generate(
63
+ settings.lcm_diffusion_setting,
64
+ reshape,
65
+ )
66
+
67
+ elapsed = perf_counter() - tick
68
+ self._latency = elapsed
69
+ print(f"Latency : {elapsed:.2f} seconds")
70
+ if settings.lcm_diffusion_setting.controlnet:
71
+ if settings.lcm_diffusion_setting.controlnet.enabled:
72
+ images.append(
73
+ settings.lcm_diffusion_setting.controlnet._control_image
74
+ )
75
+
76
+ if settings.lcm_diffusion_setting.use_safety_checker:
77
+ print("Safety Checker is enabled")
78
+ from state import get_safety_checker
79
+
80
+ safety_checker = get_safety_checker()
81
+ blank_image = get_blank_image(
82
+ settings.lcm_diffusion_setting.image_width,
83
+ settings.lcm_diffusion_setting.image_height,
84
+ )
85
+ for idx, image in enumerate(images):
86
+ if not safety_checker.is_safe(image):
87
+ images[idx] = blank_image
88
+ except Exception as exception:
89
+ print(f"Error in generating images: {exception}")
90
+ self._error = str(exception)
91
+ print_exc()
92
+ return None
93
+ return images
94
+
95
+ def save_images(
96
+ self,
97
+ images: Any,
98
+ settings: Settings,
99
+ ) -> list[str]:
100
+ saved_images = []
101
+ if images and settings.generated_images.save_image:
102
+ saved_images = ImageSaver.save_images(
103
+ settings.generated_images.path,
104
+ images=images,
105
+ lcm_diffusion_setting=settings.lcm_diffusion_setting,
106
+ format=settings.generated_images.format,
107
+ jpeg_quality=settings.generated_images.save_image_quality,
108
+ )
109
+ return saved_images
image_ops.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+
3
+
4
+ def resize_pil_image(
5
+ pil_image: Image,
6
+ image_width,
7
+ image_height,
8
+ ):
9
+ return pil_image.convert("RGB").resize(
10
+ (
11
+ image_width,
12
+ image_height,
13
+ ),
14
+ Image.Resampling.LANCZOS,
15
+ )
paths.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import constants
3
+ from pathlib import Path
4
+ from time import time
5
+ from utils import get_image_file_extension
6
+
7
+
8
+ def join_paths(
9
+ first_path: str,
10
+ second_path: str,
11
+ ) -> str:
12
+ return os.path.join(first_path, second_path)
13
+
14
+
15
+ def get_file_name(file_path: str) -> str:
16
+ return Path(file_path).stem
17
+
18
+
19
+ def get_app_path() -> str:
20
+ app_dir = os.path.dirname(__file__)
21
+ work_dir = os.path.dirname(app_dir)
22
+ return work_dir
23
+
24
+
25
+ def get_configs_path() -> str:
26
+ config_path = join_paths(get_app_path(), constants.CONFIG_DIRECTORY)
27
+ return config_path
28
+
29
+
30
+ class FastStableDiffusionPaths:
31
+ @staticmethod
32
+ def get_app_settings_path() -> str:
33
+ configs_path = get_configs_path()
34
+ settings_path = join_paths(
35
+ configs_path,
36
+ constants.APP_SETTINGS_FILE,
37
+ )
38
+ return settings_path
39
+
40
+ @staticmethod
41
+ def get_results_path() -> str:
42
+ results_path = join_paths(get_app_path(), constants.RESULTS_DIRECTORY)
43
+ return results_path
44
+
45
+ @staticmethod
46
+ def get_css_path() -> str:
47
+ app_dir = os.path.dirname(__file__)
48
+ css_path = os.path.join(
49
+ app_dir,
50
+ "frontend",
51
+ "webui",
52
+ "css",
53
+ "style.css",
54
+ )
55
+ return css_path
56
+
57
+ @staticmethod
58
+ def get_models_config_path(model_config_file: str) -> str:
59
+ configs_path = get_configs_path()
60
+ models_path = join_paths(
61
+ configs_path,
62
+ model_config_file,
63
+ )
64
+ return models_path
65
+
66
+ @staticmethod
67
+ def get_upscale_filepath(
68
+ file_path_src: str,
69
+ scale_factor: int,
70
+ format: str,
71
+ ) -> str:
72
+ if file_path_src:
73
+ file_name_src = get_file_name(file_path_src)
74
+ else:
75
+ file_name_src = "fastsdcpu"
76
+
77
+ extension = get_image_file_extension(format)
78
+ upscaled_filepath = join_paths(
79
+ FastStableDiffusionPaths.get_results_path(),
80
+ f"{file_name_src}_{int(scale_factor)}x_upscale_{int(time())}{extension}",
81
+ )
82
+ return upscaled_filepath
83
+
84
+ @staticmethod
85
+ def get_lora_models_path() -> str:
86
+ lora_models_path = join_paths(get_app_path(), constants.LORA_DIRECTORY)
87
+ return lora_models_path
88
+
89
+ @staticmethod
90
+ def get_controlnet_models_path() -> str:
91
+ controlnet_models_path = join_paths(
92
+ get_app_path(), constants.CONTROLNET_DIRECTORY
93
+ )
94
+ return controlnet_models_path
95
+
96
+ @staticmethod
97
+ def get_gguf_models_path() -> str:
98
+ models_path = join_paths(get_app_path(), constants.MODELS_DIRECTORY)
99
+ guuf_models_path = join_paths(models_path, "gguf")
100
+ return guuf_models_path
101
+
102
+
103
+ def get_base_folder_name(path: str) -> str:
104
+ return os.path.basename(path)
105
+
106
+
107
+ def ensure_path(path: str) -> None:
108
+ """Ensure that the directory exists."""
109
+ if not os.path.exists(path):
110
+ os.makedirs(path, exist_ok=True)
state.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app_settings import AppSettings
2
+ from typing import Optional
3
+
4
+ from context import Context
5
+ from models.interface_types import InterfaceType
6
+ from backend.safety_checker import SafetyChecker
7
+
8
+
9
+ class _AppState:
10
+ _instance: Optional["_AppState"] = None
11
+ settings: Optional[AppSettings] = None
12
+ context: Optional[Context] = None
13
+ safety_checker: Optional[SafetyChecker] = None
14
+
15
+
16
+ def get_state() -> _AppState:
17
+ if _AppState._instance is None:
18
+ _AppState._instance = _AppState()
19
+ return _AppState._instance
20
+
21
+
22
+ def get_settings(skip_file: bool = False) -> AppSettings:
23
+ state = get_state()
24
+ if state.settings is None:
25
+ state.settings = AppSettings()
26
+ state.settings.load(skip_file)
27
+ return state.settings
28
+
29
+
30
+ def get_context(interface_type: InterfaceType) -> Context:
31
+ state = get_state()
32
+ if state.context is None:
33
+ state.context = Context(interface_type)
34
+ return state.context
35
+
36
+
37
+ def get_safety_checker() -> SafetyChecker:
38
+ state = get_state()
39
+ if state.safety_checker is None:
40
+ print("Initializing safety checker")
41
+ state.safety_checker = SafetyChecker()
42
+ return state.safety_checker
utils.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os import path, listdir
2
+ import platform
3
+ from typing import List
4
+
5
+
6
+ def show_system_info():
7
+ try:
8
+ print(f"Running on {platform.system()} platform")
9
+ print(f"OS: {platform.platform()}")
10
+ print(f"Processor: {platform.processor()}")
11
+ except Exception as ex:
12
+ print(f"Error occurred while getting system information {ex}")
13
+
14
+
15
+ def get_models_from_text_file(file_path: str) -> List:
16
+ models = []
17
+ with open(file_path, "r") as file:
18
+ lines = file.readlines()
19
+ for repo_id in lines:
20
+ if repo_id.strip() != "":
21
+ models.append(repo_id.strip())
22
+ return models
23
+
24
+
25
+ def get_image_file_extension(image_format: str) -> str:
26
+ if image_format == "JPEG":
27
+ return ".jpg"
28
+ elif image_format == "PNG":
29
+ return ".png"
30
+
31
+
32
+ def get_files_in_dir(root_dir: str) -> List:
33
+ models = []
34
+ models.append("None")
35
+ for file in listdir(root_dir):
36
+ if file.endswith((".gguf", ".safetensors")):
37
+ models.append(path.join(root_dir, file))
38
+ return models