models.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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": "do_not_send", "type": bool, "default": False},
  94. {"key": "do_not_save", "type": bool, "default": True}
  95. ]
  96. ).generate_model()
  97. StableDiffusionImg2ImgProcessingAPI = PydanticModelGenerator(
  98. "StableDiffusionProcessingImg2Img",
  99. StableDiffusionProcessingImg2Img,
  100. [
  101. {"key": "sampler_index", "type": str, "default": "Euler"},
  102. {"key": "init_images", "type": list, "default": None},
  103. {"key": "denoising_strength", "type": float, "default": 0.75},
  104. {"key": "mask", "type": str, "default": None},
  105. {"key": "include_init_images", "type": bool, "default": False, "exclude" : True},
  106. {"key": "script_name", "type": str, "default": None},
  107. {"key": "script_args", "type": list, "default": []},
  108. {"key": "do_not_send", "type": bool, "default": False},
  109. {"key": "do_not_save", "type": bool, "default": True}
  110. ]
  111. ).generate_model()
  112. class TextToImageResponse(BaseModel):
  113. images: List[str] = Field(default=None, title="Image", description="The generated image in base64 format.")
  114. parameters: dict
  115. info: str
  116. class ImageToImageResponse(BaseModel):
  117. images: List[str] = Field(default=None, title="Image", description="The generated image in base64 format.")
  118. parameters: dict
  119. info: str
  120. class ExtrasBaseRequest(BaseModel):
  121. 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.")
  122. show_extras_results: bool = Field(default=True, title="Show results", description="Should the backend return the generated image?")
  123. 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.")
  124. 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.")
  125. 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.")
  126. 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.")
  127. 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.")
  128. 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.")
  129. upscaling_crop: bool = Field(default=True, title="Crop to fit", description="Should the upscaler crop the image to fit in the chosen size?")
  130. 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])}")
  131. 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])}")
  132. 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.")
  133. upscale_first: bool = Field(default=False, title="Upscale first", description="Should the upscaler run before restoring faces?")
  134. class ExtraBaseResponse(BaseModel):
  135. html_info: str = Field(title="HTML info", description="A series of HTML tags containing the process info.")
  136. class ExtrasSingleImageRequest(ExtrasBaseRequest):
  137. image: str = Field(default="", title="Image", description="Image to work on, must be a Base64 string containing the image's data.")
  138. class ExtrasSingleImageResponse(ExtraBaseResponse):
  139. image: str = Field(default=None, title="Image", description="The generated image in base64 format.")
  140. class FileData(BaseModel):
  141. data: str = Field(title="File data", description="Base64 representation of the file")
  142. name: str = Field(title="File name")
  143. class ExtrasBatchImagesRequest(ExtrasBaseRequest):
  144. imageList: List[FileData] = Field(title="Images", description="List of images to work on. Must be Base64 strings")
  145. class ExtrasBatchImagesResponse(ExtraBaseResponse):
  146. images: List[str] = Field(title="Images", description="The generated images in base64 format.")
  147. class PNGInfoRequest(BaseModel):
  148. image: str = Field(title="Image", description="The base64 encoded PNG image")
  149. class PNGInfoResponse(BaseModel):
  150. info: str = Field(title="Image info", description="A string with the parameters used to generate the image")
  151. items: dict = Field(title="Items", description="An object containing all the info the image had")
  152. class ProgressRequest(BaseModel):
  153. skip_current_image: bool = Field(default=False, title="Skip current image", description="Skip current image serialization")
  154. class ProgressResponse(BaseModel):
  155. progress: float = Field(title="Progress", description="The progress with a range of 0 to 1")
  156. eta_relative: float = Field(title="ETA in secs")
  157. state: dict = Field(title="State", description="The current state snapshot")
  158. 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.")
  159. textinfo: str = Field(default=None, title="Info text", description="Info text used by WebUI.")
  160. class InterrogateRequest(BaseModel):
  161. image: str = Field(default="", title="Image", description="Image to work on, must be a Base64 string containing the image's data.")
  162. model: str = Field(default="clip", title="Model", description="The interrogate model used.")
  163. class InterrogateResponse(BaseModel):
  164. caption: str = Field(default=None, title="Caption", description="The generated caption for the image.")
  165. class TrainResponse(BaseModel):
  166. info: str = Field(title="Train info", description="Response string from train embedding or hypernetwork task.")
  167. class CreateResponse(BaseModel):
  168. info: str = Field(title="Create info", description="Response string from create embedding or hypernetwork task.")
  169. class PreprocessResponse(BaseModel):
  170. info: str = Field(title="Preprocess info", description="Response string from preprocessing task.")
  171. fields = {}
  172. for key, metadata in opts.data_labels.items():
  173. value = opts.data.get(key)
  174. optType = opts.typemap.get(type(metadata.default), type(value))
  175. if (metadata is not None):
  176. fields.update({key: (Optional[optType], Field(
  177. default=metadata.default ,description=metadata.label))})
  178. else:
  179. fields.update({key: (Optional[optType], Field())})
  180. OptionsModel = create_model("Options", **fields)
  181. flags = {}
  182. _options = vars(parser)['_option_string_actions']
  183. for key in _options:
  184. if(_options[key].dest != 'help'):
  185. flag = _options[key]
  186. _type = str
  187. if _options[key].default is not None: _type = type(_options[key].default)
  188. flags.update({flag.dest: (_type,Field(default=flag.default, description=flag.help))})
  189. FlagsModel = create_model("Flags", **flags)
  190. class SamplerItem(BaseModel):
  191. name: str = Field(title="Name")
  192. aliases: List[str] = Field(title="Aliases")
  193. options: Dict[str, str] = Field(title="Options")
  194. class UpscalerItem(BaseModel):
  195. name: str = Field(title="Name")
  196. model_name: Optional[str] = Field(title="Model Name")
  197. model_path: Optional[str] = Field(title="Path")
  198. model_url: Optional[str] = Field(title="URL")
  199. scale: Optional[float] = Field(title="Scale")
  200. class SDModelItem(BaseModel):
  201. title: str = Field(title="Title")
  202. model_name: str = Field(title="Model Name")
  203. hash: Optional[str] = Field(title="Short hash")
  204. sha256: Optional[str] = Field(title="sha256 hash")
  205. filename: str = Field(title="Filename")
  206. config: Optional[str] = Field(title="Config file")
  207. class HypernetworkItem(BaseModel):
  208. name: str = Field(title="Name")
  209. path: Optional[str] = Field(title="Path")
  210. class FaceRestorerItem(BaseModel):
  211. name: str = Field(title="Name")
  212. cmd_dir: Optional[str] = Field(title="Path")
  213. class RealesrganItem(BaseModel):
  214. name: str = Field(title="Name")
  215. path: Optional[str] = Field(title="Path")
  216. scale: Optional[int] = Field(title="Scale")
  217. class PromptStyleItem(BaseModel):
  218. name: str = Field(title="Name")
  219. prompt: Optional[str] = Field(title="Prompt")
  220. negative_prompt: Optional[str] = Field(title="Negative Prompt")
  221. class ArtistItem(BaseModel):
  222. name: str = Field(title="Name")
  223. score: float = Field(title="Score")
  224. category: str = Field(title="Category")
  225. class EmbeddingItem(BaseModel):
  226. step: Optional[int] = Field(title="Step", description="The number of steps that were used to train this embedding, if available")
  227. sd_checkpoint: Optional[str] = Field(title="SD Checkpoint", description="The hash of the checkpoint this embedding was trained on, if available")
  228. 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")
  229. shape: int = Field(title="Shape", description="The length of each individual vector in the embedding")
  230. vectors: int = Field(title="Vectors", description="The number of vectors in the embedding")
  231. class EmbeddingsResponse(BaseModel):
  232. loaded: Dict[str, EmbeddingItem] = Field(title="Loaded", description="Embeddings loaded for the current model")
  233. skipped: Dict[str, EmbeddingItem] = Field(title="Skipped", description="Embeddings skipped for the current model (likely due to architecture incompatibility)")
  234. class MemoryResponse(BaseModel):
  235. ram: dict = Field(title="RAM", description="System memory stats")
  236. cuda: dict = Field(title="CUDA", description="nVidia CUDA memory stats")