initialize_util.py 7.7 KB

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