models.py 16 KB

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