api.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import numpy as np
  2. from fastapi import FastAPI, Body
  3. from fastapi.exceptions import HTTPException
  4. from PIL import Image
  5. import gradio as gr
  6. from modules.api.models import *
  7. from modules.api import api
  8. from scripts import external_code, global_state
  9. from scripts.processor import preprocessor_filters
  10. from scripts.logging import logger
  11. def encode_to_base64(image):
  12. if type(image) is str:
  13. return image
  14. elif type(image) is Image.Image:
  15. return api.encode_pil_to_base64(image)
  16. elif type(image) is np.ndarray:
  17. return encode_np_to_base64(image)
  18. else:
  19. return ""
  20. def encode_np_to_base64(image):
  21. pil = Image.fromarray(image)
  22. return api.encode_pil_to_base64(pil)
  23. def controlnet_api(_: gr.Blocks, app: FastAPI):
  24. @app.get("/controlnet/version")
  25. async def version():
  26. return {"version": external_code.get_api_version()}
  27. @app.get("/controlnet/model_list")
  28. async def model_list(update: bool = True):
  29. up_to_date_model_list = external_code.get_models(update=update)
  30. logger.debug(up_to_date_model_list)
  31. return {"model_list": up_to_date_model_list}
  32. @app.get("/controlnet/module_list")
  33. async def module_list(alias_names: bool = False):
  34. _module_list = external_code.get_modules(alias_names)
  35. logger.debug(_module_list)
  36. return {
  37. "module_list": _module_list,
  38. "module_detail": external_code.get_modules_detail(alias_names)
  39. }
  40. @app.get("/controlnet/control_types")
  41. async def control_types():
  42. def format_control_type(
  43. filtered_preprocessor_list,
  44. filtered_model_list,
  45. default_option,
  46. default_model,
  47. ):
  48. return {
  49. "module_list": filtered_preprocessor_list,
  50. "model_list": filtered_model_list,
  51. "default_option": default_option,
  52. "default_model": default_model,
  53. }
  54. return {
  55. 'control_types': {
  56. control_type: format_control_type(*global_state.select_control_type(control_type))
  57. for control_type in preprocessor_filters.keys()
  58. }
  59. }
  60. @app.get("/controlnet/settings")
  61. async def settings():
  62. max_models_num = external_code.get_max_models_num()
  63. return {"control_net_max_models_num":max_models_num}
  64. cached_cn_preprocessors = global_state.cache_preprocessors(global_state.cn_preprocessor_modules)
  65. @app.post("/controlnet/detect")
  66. async def detect(
  67. controlnet_module: str = Body("none", title='Controlnet Module'),
  68. controlnet_input_images: List[str] = Body([], title='Controlnet Input Images'),
  69. controlnet_processor_res: int = Body(512, title='Controlnet Processor Resolution'),
  70. controlnet_threshold_a: float = Body(64, title='Controlnet Threshold a'),
  71. controlnet_threshold_b: float = Body(64, title='Controlnet Threshold b')
  72. ):
  73. controlnet_module = global_state.reverse_preprocessor_aliases.get(controlnet_module, controlnet_module)
  74. if controlnet_module not in cached_cn_preprocessors:
  75. raise HTTPException(
  76. status_code=422, detail="Module not available")
  77. if len(controlnet_input_images) == 0:
  78. raise HTTPException(
  79. status_code=422, detail="No image selected")
  80. logger.info(f"Detecting {str(len(controlnet_input_images))} images with the {controlnet_module} module.")
  81. results = []
  82. processor_module = cached_cn_preprocessors[controlnet_module]
  83. for input_image in controlnet_input_images:
  84. img = external_code.to_base64_nparray(input_image)
  85. results.append(processor_module(img, res=controlnet_processor_res, thr_a=controlnet_threshold_a, thr_b=controlnet_threshold_b)[0])
  86. global_state.cn_preprocessor_unloadable.get(controlnet_module, lambda: None)()
  87. results64 = list(map(encode_to_base64, results))
  88. return {"images": results64, "info": "Success"}
  89. try:
  90. import modules.script_callbacks as script_callbacks
  91. script_callbacks.on_app_started(controlnet_api)
  92. except:
  93. pass