models.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import inspect
  2. from pydantic import BaseModel, Field, create_model
  3. from typing import Any, Optional
  4. from typing_extensions import Literal
  5. from inflection import underscore
  6. from modules.processing import StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img
  7. from modules.shared import sd_upscalers, opts, parser
  8. from typing import Dict, List
  9. API_NOT_ALLOWED = [
  10. "self",
  11. "kwargs",
  12. "sd_model",
  13. "outpath_samples",
  14. "outpath_grids",
  15. "sampler_index",
  16. # "do_not_save_samples",
  17. # "do_not_save_grid",
  18. "extra_generation_params",
  19. "overlay_images",
  20. "do_not_reload_embeddings",
  21. "seed_enable_extras",
  22. "prompt_for_display",
  23. "sampler_noise_scheduler_override",
  24. "ddim_discretize"
  25. ]
  26. class ModelDef(BaseModel):
  27. """Assistance Class for Pydantic Dynamic Model Generation"""
  28. field: str
  29. field_alias: str
  30. field_type: Any
  31. field_value: Any
  32. field_exclude: bool = False
  33. class PydanticModelGenerator:
  34. """
  35. Takes in created classes and stubs them out in a way FastAPI/Pydantic is happy about:
  36. source_data is a snapshot of the default values produced by the class
  37. params are the names of the actual keys required by __init__
  38. """
  39. def __init__(
  40. self,
  41. model_name: str = None,
  42. class_instance = None,
  43. additional_fields = None,
  44. ):
  45. def field_type_generator(k, v):
  46. # field_type = str if not overrides.get(k) else overrides[k]["type"]
  47. # print(k, v.annotation, v.default)
  48. field_type = v.annotation
  49. return Optional[field_type]
  50. def merge_class_params(class_):
  51. all_classes = list(filter(lambda x: x is not object, inspect.getmro(class_)))
  52. parameters = {}
  53. for classes in all_classes:
  54. parameters = {**parameters, **inspect.signature(classes.__init__).parameters}
  55. return parameters
  56. self._model_name = model_name
  57. self._class_data = merge_class_params(class_instance)
  58. self._model_def = [
  59. ModelDef(
  60. field=underscore(k),
  61. field_alias=k,
  62. field_type=field_type_generator(k, v),
  63. field_value=v.default
  64. )
  65. for (k,v) in self._class_data.items() if k not in API_NOT_ALLOWED
  66. ]
  67. for fields in additional_fields:
  68. self._model_def.append(ModelDef(
  69. field=underscore(fields["key"]),
  70. field_alias=fields["key"],
  71. field_type=fields["type"],
  72. field_value=fields["default"],
  73. field_exclude=fields["exclude"] if "exclude" in fields else False))
  74. def generate_model(self):
  75. """
  76. Creates a pydantic BaseModel
  77. from the json and overrides provided at initialization
  78. """
  79. fields = {
  80. d.field: (d.field_type, Field(default=d.field_value, alias=d.field_alias, exclude=d.field_exclude)) for d in self._model_def
  81. }
  82. DynamicModel = create_model(self._model_name, **fields)
  83. DynamicModel.__config__.allow_population_by_field_name = True
  84. DynamicModel.__config__.allow_mutation = True
  85. return DynamicModel
  86. StableDiffusionTxt2ImgProcessingAPI = PydanticModelGenerator(
  87. "StableDiffusionProcessingTxt2Img",
  88. StableDiffusionProcessingTxt2Img,
  89. [
  90. {"key": "sampler_index", "type": str, "default": "Euler"},
  91. {"key": "script_name", "type": str, "default": None},
  92. {"key": "script_args", "type": list, "default": []},
  93. {"key": "send_images", "type": bool, "default": True},
  94. {"key": "save_images", "type": bool, "default": False},
  95. {"key": "alwayson_scripts", "type": dict, "default": {}},
  96. ]
  97. ).generate_model()
  98. StableDiffusionImg2ImgProcessingAPI = PydanticModelGenerator(
  99. "StableDiffusionProcessingImg2Img",
  100. StableDiffusionProcessingImg2Img,
  101. [
  102. {"key": "sampler_index", "type": str, "default": "Euler"},
  103. {"key": "init_images", "type": list, "default": None},
  104. {"key": "denoising_strength", "type": float, "default": 0.75},
  105. {"key": "mask", "type": str, "default": None},
  106. {"key": "include_init_images", "type": bool, "default": False, "exclude" : True},
  107. {"key": "script_name", "type": str, "default": None},
  108. {"key": "script_args", "type": list, "default": []},
  109. {"key": "send_images", "type": bool, "default": True},
  110. {"key": "save_images", "type": bool, "default": False},
  111. {"key": "alwayson_scripts", "type": dict, "default": {}},
  112. ]
  113. ).generate_model()
  114. class TextToImageResponse(BaseModel):
  115. images: List[str] = Field(default=None, title="Image", description="The generated image in base64 format.")
  116. parameters: dict
  117. info: str
  118. class ImageToImageResponse(BaseModel):
  119. images: List[str] = Field(default=None, title="Image", description="The generated image in base64 format.")
  120. parameters: dict
  121. info: str
  122. class ExtrasBaseRequest(BaseModel):
  123. resize_mode: Literal[0, 1] = Field(default=0, title="Resize Mode", description="Sets the resize mode: 0 to upscale by upscaling_resize amount, 1 to upscale up to upscaling_resize_h x upscaling_resize_w.")
  124. show_extras_results: bool = Field(default=True, title="Show results", description="Should the backend return the generated image?")
  125. gfpgan_visibility: float = Field(default=0, title="GFPGAN Visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of GFPGAN, values should be between 0 and 1.")
  126. codeformer_visibility: float = Field(default=0, title="CodeFormer Visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of CodeFormer, values should be between 0 and 1.")
  127. codeformer_weight: float = Field(default=0, title="CodeFormer Weight", ge=0, le=1, allow_inf_nan=False, description="Sets the weight of CodeFormer, values should be between 0 and 1.")
  128. upscaling_resize: float = Field(default=2, title="Upscaling Factor", ge=1, le=8, description="By how much to upscale the image, only used when resize_mode=0.")
  129. upscaling_resize_w: int = Field(default=512, title="Target Width", ge=1, description="Target width for the upscaler to hit. Only used when resize_mode=1.")
  130. upscaling_resize_h: int = Field(default=512, title="Target Height", ge=1, description="Target height for the upscaler to hit. Only used when resize_mode=1.")
  131. upscaling_crop: bool = Field(default=True, title="Crop to fit", description="Should the upscaler crop the image to fit in the chosen size?")
  132. upscaler_1: str = Field(default="None", title="Main upscaler", description=f"The name of the main upscaler to use, it has to be one of this list: {' , '.join([x.name for x in sd_upscalers])}")
  133. upscaler_2: str = Field(default="None", title="Secondary upscaler", description=f"The name of the secondary upscaler to use, it has to be one of this list: {' , '.join([x.name for x in sd_upscalers])}")
  134. extras_upscaler_2_visibility: float = Field(default=0, title="Secondary upscaler visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of secondary upscaler, values should be between 0 and 1.")
  135. upscale_first: bool = Field(default=False, title="Upscale first", description="Should the upscaler run before restoring faces?")
  136. class ExtraBaseResponse(BaseModel):
  137. html_info: str = Field(title="HTML info", description="A series of HTML tags containing the process info.")
  138. class ExtrasSingleImageRequest(ExtrasBaseRequest):
  139. image: str = Field(default="", title="Image", description="Image to work on, must be a Base64 string containing the image's data.")
  140. class ExtrasSingleImageResponse(ExtraBaseResponse):
  141. image: str = Field(default=None, title="Image", description="The generated image in base64 format.")
  142. class FileData(BaseModel):
  143. data: str = Field(title="File data", description="Base64 representation of the file")
  144. name: str = Field(title="File name")
  145. class ExtrasBatchImagesRequest(ExtrasBaseRequest):
  146. imageList: List[FileData] = Field(title="Images", description="List of images to work on. Must be Base64 strings")
  147. class ExtrasBatchImagesResponse(ExtraBaseResponse):
  148. images: List[str] = Field(title="Images", description="The generated images in base64 format.")
  149. class PNGInfoRequest(BaseModel):
  150. image: str = Field(title="Image", description="The base64 encoded PNG image")
  151. class PNGInfoResponse(BaseModel):
  152. info: str = Field(title="Image info", description="A string with the parameters used to generate the image")
  153. items: dict = Field(title="Items", description="An object containing all the info the image had")
  154. class ProgressRequest(BaseModel):
  155. skip_current_image: bool = Field(default=False, title="Skip current image", description="Skip current image serialization")
  156. class ProgressResponse(BaseModel):
  157. progress: float = Field(title="Progress", description="The progress with a range of 0 to 1")
  158. eta_relative: float = Field(title="ETA in secs")
  159. state: dict = Field(title="State", description="The current state snapshot")
  160. current_image: str = Field(default=None, title="Current image", description="The current image in base64 format. opts.show_progress_every_n_steps is required for this to work.")
  161. textinfo: str = Field(default=None, title="Info text", description="Info text used by WebUI.")
  162. class InterrogateRequest(BaseModel):
  163. image: str = Field(default="", title="Image", description="Image to work on, must be a Base64 string containing the image's data.")
  164. model: str = Field(default="clip", title="Model", description="The interrogate model used.")
  165. class InterrogateResponse(BaseModel):
  166. caption: str = Field(default=None, title="Caption", description="The generated caption for the image.")
  167. class TrainResponse(BaseModel):
  168. info: str = Field(title="Train info", description="Response string from train embedding or hypernetwork task.")
  169. class CreateResponse(BaseModel):
  170. info: str = Field(title="Create info", description="Response string from create embedding or hypernetwork task.")
  171. class PreprocessResponse(BaseModel):
  172. info: str = Field(title="Preprocess info", description="Response string from preprocessing task.")
  173. fields = {}
  174. for key, metadata in opts.data_labels.items():
  175. value = opts.data.get(key)
  176. optType = opts.typemap.get(type(metadata.default), type(metadata.default)) if metadata.default else Any
  177. if metadata is not None:
  178. fields.update({key: (Optional[optType], Field(default=metadata.default, description=metadata.label))})
  179. else:
  180. fields.update({key: (Optional[optType], Field())})
  181. OptionsModel = create_model("Options", **fields)
  182. flags = {}
  183. _options = vars(parser)['_option_string_actions']
  184. for key in _options:
  185. if(_options[key].dest != 'help'):
  186. flag = _options[key]
  187. _type = str
  188. if _options[key].default is not None:
  189. _type = type(_options[key].default)
  190. flags.update({flag.dest: (_type, Field(default=flag.default, description=flag.help))})
  191. FlagsModel = create_model("Flags", **flags)
  192. class SamplerItem(BaseModel):
  193. name: str = Field(title="Name")
  194. aliases: List[str] = Field(title="Aliases")
  195. options: Dict[str, str] = Field(title="Options")
  196. class UpscalerItem(BaseModel):
  197. name: str = Field(title="Name")
  198. model_name: Optional[str] = Field(title="Model Name")
  199. model_path: Optional[str] = Field(title="Path")
  200. model_url: Optional[str] = Field(title="URL")
  201. scale: Optional[float] = Field(title="Scale")
  202. class LatentUpscalerModeItem(BaseModel):
  203. name: str = Field(title="Name")
  204. class SDModelItem(BaseModel):
  205. title: str = Field(title="Title")
  206. model_name: str = Field(title="Model Name")
  207. hash: Optional[str] = Field(title="Short hash")
  208. sha256: Optional[str] = Field(title="sha256 hash")
  209. filename: str = Field(title="Filename")
  210. config: Optional[str] = Field(title="Config file")
  211. class SDVaeItem(BaseModel):
  212. model_name: str = Field(title="Model Name")
  213. filename: str = Field(title="Filename")
  214. class HypernetworkItem(BaseModel):
  215. name: str = Field(title="Name")
  216. path: Optional[str] = Field(title="Path")
  217. class FaceRestorerItem(BaseModel):
  218. name: str = Field(title="Name")
  219. cmd_dir: Optional[str] = Field(title="Path")
  220. class RealesrganItem(BaseModel):
  221. name: str = Field(title="Name")
  222. path: Optional[str] = Field(title="Path")
  223. scale: Optional[int] = Field(title="Scale")
  224. class PromptStyleItem(BaseModel):
  225. name: str = Field(title="Name")
  226. prompt: Optional[str] = Field(title="Prompt")
  227. negative_prompt: Optional[str] = Field(title="Negative Prompt")
  228. class EmbeddingItem(BaseModel):
  229. step: Optional[int] = Field(title="Step", description="The number of steps that were used to train this embedding, if available")
  230. sd_checkpoint: Optional[str] = Field(title="SD Checkpoint", description="The hash of the checkpoint this embedding was trained on, if available")
  231. sd_checkpoint_name: Optional[str] = Field(title="SD Checkpoint Name", description="The name of the checkpoint this embedding was trained on, if available. Note that this is the name that was used by the trainer; for a stable identifier, use `sd_checkpoint` instead")
  232. shape: int = Field(title="Shape", description="The length of each individual vector in the embedding")
  233. vectors: int = Field(title="Vectors", description="The number of vectors in the embedding")
  234. class EmbeddingsResponse(BaseModel):
  235. loaded: Dict[str, EmbeddingItem] = Field(title="Loaded", description="Embeddings loaded for the current model")
  236. skipped: Dict[str, EmbeddingItem] = Field(title="Skipped", description="Embeddings skipped for the current model (likely due to architecture incompatibility)")
  237. class MemoryResponse(BaseModel):
  238. ram: dict = Field(title="RAM", description="System memory stats")
  239. cuda: dict = Field(title="CUDA", description="nVidia CUDA memory stats")
  240. class ScriptsList(BaseModel):
  241. txt2img: list = Field(default=None, title="Txt2img", description="Titles of scripts (txt2img)")
  242. img2img: list = Field(default=None, title="Img2img", description="Titles of scripts (img2img)")
  243. class ScriptArg(BaseModel):
  244. label: str = Field(default=None, title="Label", description="Name of the argument in UI")
  245. value: Optional[Any] = Field(default=None, title="Value", description="Default value of the argument")
  246. minimum: Optional[Any] = Field(default=None, title="Minimum", description="Minimum allowed value for the argumentin UI")
  247. maximum: Optional[Any] = Field(default=None, title="Minimum", description="Maximum allowed value for the argumentin UI")
  248. step: Optional[Any] = Field(default=None, title="Minimum", description="Step for changing value of the argumentin UI")
  249. choices: Optional[List[str]] = Field(default=None, title="Choices", description="Possible values for the argument")
  250. class ScriptInfo(BaseModel):
  251. name: str = Field(default=None, title="Name", description="Script name")
  252. is_alwayson: bool = Field(default=None, title="IsAlwayson", description="Flag specifying whether this script is an alwayson script")
  253. is_img2img: bool = Field(default=None, title="IsImg2img", description="Flag specifying whether this script is an img2img script")
  254. args: List[ScriptArg] = Field(title="Arguments", description="List of script's arguments")