interrogator.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import os
  2. import gc
  3. import pandas as pd
  4. import numpy as np
  5. from typing import Tuple, List, Dict
  6. from io import BytesIO
  7. from PIL import Image
  8. from pathlib import Path
  9. from huggingface_hub import hf_hub_download
  10. from modules import shared
  11. from modules.deepbooru import re_special as tag_escape_pattern
  12. # i'm not sure if it's okay to add this file to the repository
  13. from . import dbimutils
  14. # select a device to process
  15. use_cpu = ('all' in shared.cmd_opts.use_cpu) or (
  16. 'interrogate' in shared.cmd_opts.use_cpu)
  17. if use_cpu:
  18. tf_device_name = '/cpu:0'
  19. else:
  20. tf_device_name = '/gpu:0'
  21. if shared.cmd_opts.device_id is not None:
  22. try:
  23. tf_device_name = f'/gpu:{int(shared.cmd_opts.device_id)}'
  24. except ValueError:
  25. print('--device-id is not a integer')
  26. class Interrogator:
  27. @staticmethod
  28. def postprocess_tags(
  29. tags: Dict[str, float],
  30. threshold=0.35,
  31. additional_tags: List[str] = [],
  32. exclude_tags: List[str] = [],
  33. sort_by_alphabetical_order=False,
  34. add_confident_as_weight=False,
  35. replace_underscore=False,
  36. replace_underscore_excludes: List[str] = [],
  37. escape_tag=False
  38. ) -> Dict[str, float]:
  39. for t in additional_tags:
  40. tags[t] = 1.0
  41. # those lines are totally not "pythonic" but looks better to me
  42. tags = {
  43. t: c
  44. # sort by tag name or confident
  45. for t, c in sorted(
  46. tags.items(),
  47. key=lambda i: i[0 if sort_by_alphabetical_order else 1],
  48. reverse=not sort_by_alphabetical_order
  49. )
  50. # filter tags
  51. if (
  52. c >= threshold
  53. and t not in exclude_tags
  54. )
  55. }
  56. new_tags = []
  57. for tag in list(tags):
  58. new_tag = tag
  59. if replace_underscore and tag not in replace_underscore_excludes:
  60. new_tag = new_tag.replace('_', ' ')
  61. if escape_tag:
  62. new_tag = tag_escape_pattern.sub(r'\\\1', new_tag)
  63. if add_confident_as_weight:
  64. new_tag = f'({new_tag}:{tags[tag]})'
  65. new_tags.append((new_tag, tags[tag]))
  66. tags = dict(new_tags)
  67. return tags
  68. def __init__(self, name: str) -> None:
  69. self.name = name
  70. def load(self):
  71. raise NotImplementedError()
  72. def unload(self) -> bool:
  73. unloaded = False
  74. if hasattr(self, 'model') and self.model is not None:
  75. del self.model
  76. unloaded = True
  77. print(f'Unloaded {self.name}')
  78. if hasattr(self, 'tags'):
  79. del self.tags
  80. return unloaded
  81. def interrogate(
  82. self,
  83. image: Image
  84. ) -> Tuple[
  85. Dict[str, float], # rating confidents
  86. Dict[str, float] # tag confidents
  87. ]:
  88. raise NotImplementedError()
  89. class DeepDanbooruInterrogator(Interrogator):
  90. def __init__(self, name: str, project_path: os.PathLike) -> None:
  91. super().__init__(name)
  92. self.project_path = project_path
  93. def load(self) -> None:
  94. print(f'Loading {self.name} from {str(self.project_path)}')
  95. # deepdanbooru package is not include in web-sd anymore
  96. # https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/c81d440d876dfd2ab3560410f37442ef56fc663
  97. from launch import is_installed, run_pip
  98. if not is_installed('deepdanbooru'):
  99. package = os.environ.get(
  100. 'DEEPDANBOORU_PACKAGE',
  101. 'git+https://github.com/KichangKim/DeepDanbooru.git@d91a2963bf87c6a770d74894667e9ffa9f6de7ff'
  102. )
  103. run_pip(
  104. f'install {package} tensorflow tensorflow-io', 'deepdanbooru')
  105. import tensorflow as tf
  106. # tensorflow maps nearly all vram by default, so we limit this
  107. # https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth
  108. # TODO: only run on the first run
  109. for device in tf.config.experimental.list_physical_devices('GPU'):
  110. tf.config.experimental.set_memory_growth(device, True)
  111. with tf.device(tf_device_name):
  112. import deepdanbooru.project as ddp
  113. self.model = ddp.load_model_from_project(
  114. project_path=self.project_path,
  115. compile_model=False
  116. )
  117. print(f'Loaded {self.name} model from {str(self.project_path)}')
  118. self.tags = ddp.load_tags_from_project(
  119. project_path=self.project_path
  120. )
  121. def unload(self) -> bool:
  122. # unloaded = super().unload()
  123. # if unloaded:
  124. # # tensorflow suck
  125. # # https://github.com/keras-team/keras/issues/2102
  126. # import tensorflow as tf
  127. # tf.keras.backend.clear_session()
  128. # gc.collect()
  129. # return unloaded
  130. # There is a bug in Keras where it is not possible to release a model that has been loaded into memory.
  131. # Downgrading to keras==2.1.6 may solve the issue, but it may cause compatibility issues with other packages.
  132. # Using subprocess to create a new process may also solve the problem, but it can be too complex (like Automatic1111 did).
  133. # It seems that for now, the best option is to keep the model in memory, as most users use the Waifu Diffusion model with onnx.
  134. return False
  135. def interrogate(
  136. self,
  137. image: Image
  138. ) -> Tuple[
  139. Dict[str, float], # rating confidents
  140. Dict[str, float] # tag confidents
  141. ]:
  142. # init model
  143. if not hasattr(self, 'model') or self.model is None:
  144. self.load()
  145. import deepdanbooru.data as ddd
  146. # convert an image to fit the model
  147. image_bufs = BytesIO()
  148. image.save(image_bufs, format='PNG')
  149. image = ddd.load_image_for_evaluate(
  150. image_bufs,
  151. self.model.input_shape[2],
  152. self.model.input_shape[1]
  153. )
  154. image = image.reshape((1, *image.shape[0:3]))
  155. # evaluate model
  156. result = self.model.predict(image)
  157. confidents = result[0].tolist()
  158. ratings = {}
  159. tags = {}
  160. for i, tag in enumerate(self.tags):
  161. tags[tag] = confidents[i]
  162. return ratings, tags
  163. class WaifuDiffusionInterrogator(Interrogator):
  164. def __init__(
  165. self,
  166. name: str,
  167. model_path='model.onnx',
  168. tags_path='selected_tags.csv',
  169. **kwargs
  170. ) -> None:
  171. super().__init__(name)
  172. self.model_path = model_path
  173. self.tags_path = tags_path
  174. self.kwargs = kwargs
  175. def download(self) -> Tuple[os.PathLike, os.PathLike]:
  176. print(f"Loading {self.name} model file from {self.kwargs['repo_id']}")
  177. model_path = Path(hf_hub_download(
  178. **self.kwargs, filename=self.model_path))
  179. tags_path = Path(hf_hub_download(
  180. **self.kwargs, filename=self.tags_path))
  181. return model_path, tags_path
  182. def load(self) -> None:
  183. model_path, tags_path = self.download()
  184. # only one of these packages should be installed at a time in any one environment
  185. # https://onnxruntime.ai/docs/get-started/with-python.html#install-onnx-runtime
  186. # TODO: remove old package when the environment changes?
  187. from launch import is_installed, run_pip
  188. if not is_installed('onnxruntime'):
  189. package = os.environ.get(
  190. 'ONNXRUNTIME_PACKAGE',
  191. 'onnxruntime-gpu'
  192. )
  193. run_pip(f'install {package}', 'onnxruntime')
  194. from onnxruntime import InferenceSession
  195. # https://onnxruntime.ai/docs/execution-providers/
  196. # https://github.com/toriato/stable-diffusion-webui-wd14-tagger/commit/e4ec460122cf674bbf984df30cdb10b4370c1224#r92654958
  197. providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
  198. if use_cpu:
  199. providers.pop(0)
  200. self.model = InferenceSession(str(model_path), providers=providers)
  201. print(f'Loaded {self.name} model from {model_path}')
  202. self.tags = pd.read_csv(tags_path)
  203. def interrogate(
  204. self,
  205. image: Image
  206. ) -> Tuple[
  207. Dict[str, float], # rating confidents
  208. Dict[str, float] # tag confidents
  209. ]:
  210. # init model
  211. if not hasattr(self, 'model') or self.model is None:
  212. self.load()
  213. # code for converting the image and running the model is taken from the link below
  214. # thanks, SmilingWolf!
  215. # https://huggingface.co/spaces/SmilingWolf/wd-v1-4-tags/blob/main/app.py
  216. # convert an image to fit the model
  217. _, height, _, _ = self.model.get_inputs()[0].shape
  218. # alpha to white
  219. image = image.convert('RGBA')
  220. new_image = Image.new('RGBA', image.size, 'WHITE')
  221. new_image.paste(image, mask=image)
  222. image = new_image.convert('RGB')
  223. image = np.asarray(image)
  224. # PIL RGB to OpenCV BGR
  225. image = image[:, :, ::-1]
  226. image = dbimutils.make_square(image, height)
  227. image = dbimutils.smart_resize(image, height)
  228. image = image.astype(np.float32)
  229. image = np.expand_dims(image, 0)
  230. # evaluate model
  231. input_name = self.model.get_inputs()[0].name
  232. label_name = self.model.get_outputs()[0].name
  233. confidents = self.model.run([label_name], {input_name: image})[0]
  234. tags = self.tags[:][['name']]
  235. tags['confidents'] = confidents[0]
  236. # first 4 items are for rating (general, sensitive, questionable, explicit)
  237. ratings = dict(tags[:4].values)
  238. # rest are regular tags
  239. tags = dict(tags[4:].values)
  240. return ratings, tags