models.py 13 KB

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