initialize_util.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import json
  2. import os
  3. import signal
  4. import sys
  5. import re
  6. from modules.timer import startup_timer
  7. def gradio_server_name():
  8. from modules.shared_cmd_options import cmd_opts
  9. if cmd_opts.server_name:
  10. return cmd_opts.server_name
  11. else:
  12. return "0.0.0.0" if cmd_opts.listen else None
  13. def fix_torch_version():
  14. import torch
  15. # Truncate version number of nightly/local build of PyTorch to not cause exceptions with CodeFormer or Safetensors
  16. if ".dev" in torch.__version__ or "+git" in torch.__version__:
  17. torch.__long_version__ = torch.__version__
  18. torch.__version__ = re.search(r'[\d.]+[\d]', torch.__version__).group(0)
  19. def fix_pytorch_lightning():
  20. # Checks if pytorch_lightning.utilities.distributed already exists in the sys.modules cache
  21. if 'pytorch_lightning.utilities.distributed' not in sys.modules:
  22. import pytorch_lightning
  23. # Lets the user know that the library was not found and then will set it to pytorch_lightning.utilities.rank_zero
  24. print(f"Pytorch_lightning.distributed not found, attempting pytorch_lightning.rank_zero")
  25. sys.modules["pytorch_lightning.utilities.distributed"] = pytorch_lightning.utilities.rank_zero
  26. def fix_asyncio_event_loop_policy():
  27. """
  28. The default `asyncio` event loop policy only automatically creates
  29. event loops in the main threads. Other threads must create event
  30. loops explicitly or `asyncio.get_event_loop` (and therefore
  31. `.IOLoop.current`) will fail. Installing this policy allows event
  32. loops to be created automatically on any thread, matching the
  33. behavior of Tornado versions prior to 5.0 (or 5.0 on Python 2).
  34. """
  35. import asyncio
  36. if sys.platform == "win32" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
  37. # "Any thread" and "selector" should be orthogonal, but there's not a clean
  38. # interface for composing policies so pick the right base.
  39. _BasePolicy = asyncio.WindowsSelectorEventLoopPolicy # type: ignore
  40. else:
  41. _BasePolicy = asyncio.DefaultEventLoopPolicy
  42. class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
  43. """Event loop policy that allows loop creation on any thread.
  44. Usage::
  45. asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
  46. """
  47. def get_event_loop(self) -> asyncio.AbstractEventLoop:
  48. try:
  49. return super().get_event_loop()
  50. except (RuntimeError, AssertionError):
  51. # This was an AssertionError in python 3.4.2 (which ships with debian jessie)
  52. # and changed to a RuntimeError in 3.4.3.
  53. # "There is no current event loop in thread %r"
  54. loop = self.new_event_loop()
  55. self.set_event_loop(loop)
  56. return loop
  57. asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
  58. def restore_config_state_file():
  59. from modules import shared, config_states
  60. config_state_file = shared.opts.restore_config_state_file
  61. if config_state_file == "":
  62. return
  63. shared.opts.restore_config_state_file = ""
  64. shared.opts.save(shared.config_filename)
  65. if os.path.isfile(config_state_file):
  66. print(f"*** About to restore extension state from file: {config_state_file}")
  67. with open(config_state_file, "r", encoding="utf-8") as f:
  68. config_state = json.load(f)
  69. config_states.restore_extension_config(config_state)
  70. startup_timer.record("restore extension config")
  71. elif config_state_file:
  72. print(f"!!! Config state backup not found: {config_state_file}")
  73. def validate_tls_options():
  74. from modules.shared_cmd_options import cmd_opts
  75. if not (cmd_opts.tls_keyfile and cmd_opts.tls_certfile):
  76. return
  77. try:
  78. if not os.path.exists(cmd_opts.tls_keyfile):
  79. print("Invalid path to TLS keyfile given")
  80. if not os.path.exists(cmd_opts.tls_certfile):
  81. print(f"Invalid path to TLS certfile: '{cmd_opts.tls_certfile}'")
  82. except TypeError:
  83. cmd_opts.tls_keyfile = cmd_opts.tls_certfile = None
  84. print("TLS setup invalid, running webui without TLS")
  85. else:
  86. print("Running with TLS")
  87. startup_timer.record("TLS")
  88. def get_gradio_auth_creds():
  89. """
  90. Convert the gradio_auth and gradio_auth_path commandline arguments into
  91. an iterable of (username, password) tuples.
  92. """
  93. from modules.shared_cmd_options import cmd_opts
  94. def process_credential_line(s):
  95. s = s.strip()
  96. if not s:
  97. return None
  98. return tuple(s.split(':', 1))
  99. if cmd_opts.gradio_auth:
  100. for cred in cmd_opts.gradio_auth.split(','):
  101. cred = process_credential_line(cred)
  102. if cred:
  103. yield cred
  104. if cmd_opts.gradio_auth_path:
  105. with open(cmd_opts.gradio_auth_path, 'r', encoding="utf8") as file:
  106. for line in file.readlines():
  107. for cred in line.strip().split(','):
  108. cred = process_credential_line(cred)
  109. if cred:
  110. yield cred
  111. def dumpstacks():
  112. import threading
  113. import traceback
  114. id2name = {th.ident: th.name for th in threading.enumerate()}
  115. code = []
  116. for threadId, stack in sys._current_frames().items():
  117. code.append(f"\n# Thread: {id2name.get(threadId, '')}({threadId})")
  118. for filename, lineno, name, line in traceback.extract_stack(stack):
  119. code.append(f"""File: "{filename}", line {lineno}, in {name}""")
  120. if line:
  121. code.append(" " + line.strip())
  122. print("\n".join(code))
  123. def configure_sigint_handler():
  124. # make the program just exit at ctrl+c without waiting for anything
  125. from modules import shared
  126. def sigint_handler(sig, frame):
  127. print(f'Interrupted with signal {sig} in {frame}')
  128. if shared.opts.dump_stacks_on_signal:
  129. dumpstacks()
  130. os._exit(0)
  131. if not os.environ.get("COVERAGE_RUN"):
  132. # Don't install the immediate-quit handler when running under coverage,
  133. # as then the coverage report won't be generated.
  134. signal.signal(signal.SIGINT, sigint_handler)
  135. def configure_opts_onchange():
  136. from modules import shared, sd_models, sd_vae, ui_tempdir, sd_hijack
  137. from modules.call_queue import wrap_queued_call
  138. shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: sd_models.reload_model_weights()), call=False)
  139. shared.opts.onchange("sd_vae", wrap_queued_call(lambda: sd_vae.reload_vae_weights()), call=False)
  140. shared.opts.onchange("sd_vae_overrides_per_model_preferences", wrap_queued_call(lambda: sd_vae.reload_vae_weights()), call=False)
  141. shared.opts.onchange("temp_dir", ui_tempdir.on_tmpdir_changed)
  142. shared.opts.onchange("gradio_theme", shared.reload_gradio_theme)
  143. shared.opts.onchange("cross_attention_optimization", wrap_queued_call(lambda: sd_hijack.model_hijack.redo_hijack(shared.sd_model)), call=False)
  144. shared.opts.onchange("fp8_storage", wrap_queued_call(lambda: sd_models.reload_model_weights()), call=False)
  145. shared.opts.onchange("cache_fp16_weight", wrap_queued_call(lambda: sd_models.reload_model_weights(forced_reload=True)), call=False)
  146. startup_timer.record("opts onchange")
  147. def setup_middleware(app):
  148. from starlette.middleware.gzip import GZipMiddleware
  149. app.middleware_stack = None # reset current middleware to allow modifying user provided list
  150. app.add_middleware(GZipMiddleware, minimum_size=1000)
  151. configure_cors_middleware(app)
  152. app.build_middleware_stack() # rebuild middleware stack on-the-fly
  153. def configure_cors_middleware(app):
  154. from starlette.middleware.cors import CORSMiddleware
  155. from modules.shared_cmd_options import cmd_opts
  156. cors_options = {
  157. "allow_methods": ["*"],
  158. "allow_headers": ["*"],
  159. "allow_credentials": True,
  160. }
  161. if cmd_opts.cors_allow_origins:
  162. cors_options["allow_origins"] = cmd_opts.cors_allow_origins.split(',')
  163. if cmd_opts.cors_allow_origins_regex:
  164. cors_options["allow_origin_regex"] = cmd_opts.cors_allow_origins_regex
  165. app.add_middleware(CORSMiddleware, **cors_options)