BBrother commited on
Commit
29e62fe
1 Parent(s): bf9916a

Update SW_run.py

Browse files
Files changed (1) hide show
  1. SW_run.py +195 -72
SW_run.py CHANGED
@@ -1,11 +1,14 @@
1
- import subprocess
2
- import sys
3
- import logging
4
  import os
5
- import binascii # 用于将文本转换为十六进制
6
- import re # 用于正则表达式
 
 
 
 
7
 
8
- StartBL = ""
9
 
10
  # 打开并执行txt文件
11
  with open('/etc/main/StartBianLiang.txt', 'r') as file:
@@ -17,69 +20,189 @@ cleaned_code = '\n'.join(line.strip() for line in code.splitlines() if line.stri
17
  # 执行干净的代码
18
  exec(cleaned_code)
19
 
20
- # 获取元组中的字符串并去除括号
21
- StartBL = StartBL[0].strip('()')
22
-
23
- # 检查是否存在 logs_run.txt 文件,如果存在则删除它
24
- log_file = '/etc/main/logs_run.txt'
25
- if os.path.exists(log_file):
26
- os.remove(log_file)
27
-
28
- # 检查是否存在 url.txt 文件,如果存在则删除它
29
- url_file = '/etc/main/url.txt'
30
- if os.path.exists(url_file):
31
- os.remove(url_file)
32
-
33
- # 配置日志
34
- logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
35
-
36
- # 创建一个将输出同时发送到控制台和日志文件的处理程序
37
- console_handler = logging.StreamHandler(sys.stdout)
38
- console_handler.setLevel(logging.INFO)
39
- formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
40
- console_handler.setFormatter(formatter)
41
- logging.getLogger().addHandler(console_handler)
42
-
43
- # 重定向标准输出和标准错误到日志文件和控制台
44
- sys.stdout = logging.getLogger().handlers[0].stream
45
- sys.stderr = logging.getLogger().handlers[0].stream
46
-
47
- # 更改当前工作目录为 /etc/main
48
- os.chdir('/etc/main/')
49
-
50
- try:
51
- # 在 try 块中运行 /etc/main/webui.py,并将输出重定向到日志文件
52
- with open(log_file, 'a') as log_file_handle, open(url_file, 'a') as url_file_handle:
53
- process = subprocess.Popen(['python', '/etc/main/webui.py', StartBL ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
54
-
55
- url_pattern = re.compile(r'https?://\S+')
56
-
57
- for line in process.stdout:
58
- if "Public" in line or "Application" in line:
59
- # 将包含 "Public" 或 "Application" 的行转换为十六进制并写入 url.txt
60
- hex_line = binascii.hexlify(line.encode()).decode()
61
- url_file_handle.write(hex_line + '\n')
62
- else:
63
- # 查找行中的 URL 地址并将匹配的行转换为十六进制后写入 url.txt
64
- urls = url_pattern.findall(line)
65
- if urls:
66
- for url in urls:
67
- hex_url = binascii.hexlify(url.encode()).decode()
68
- url_file_handle.write(hex_url + '\n')
69
-
70
- # 将其他行写入日志文件
71
- log_file_handle.write(line)
72
- log_file_handle.flush()
73
-
74
- process.wait()
75
-
76
- except subprocess.CalledProcessError as e:
77
- # 捕获异常并记录到日志文件
78
- logging.exception(f"程序发生异常: {e}")
79
- except Exception as e:
80
- # 捕获其他异常并记录到日志文件
81
- logging.exception(f"程序发生异常: {e}")
82
- finally:
83
- # 最后,关闭日志处理程序,以确保所有日志都被写入到日志文件
84
- logging.getLogger().removeHandler(console_handler)
85
- console_handler.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
 
3
  import os
4
+ import time
5
+
6
+ from modules import timer
7
+ from modules import initialize_util
8
+ from modules import initialize
9
+ from pathlib import Path
10
 
11
+ ngrok_use = False
12
 
13
  # 打开并执行txt文件
14
  with open('/etc/main/StartBianLiang.txt', 'r') as file:
 
20
  # 执行干净的代码
21
  exec(cleaned_code)
22
 
23
+ #ngrok穿透
24
+ ngrokTokenFile='/etc/main/Authtoken.txt' # 非必填 存放ngrokToken的文件的路径
25
+
26
+ def ngrok_start(ngrokTokenFile: str, port: int, address_name: str, should_run: bool):
27
+ if not should_run:
28
+ print('Skipping ngrok start')
29
+ return
30
+ if Path(ngrokTokenFile).exists():
31
+ with open(ngrokTokenFile, encoding="utf-8") as nkfile:
32
+ ngrokToken = nkfile.readline()
33
+ print('use nrgok')
34
+ from pyngrok import conf, ngrok
35
+ conf.get_default().auth_token = ngrokToken
36
+ conf.get_default().monitor_thread = False
37
+ ssh_tunnels = ngrok.get_tunnels(conf.get_default())
38
+ if len(ssh_tunnels) == 0:
39
+ ssh_tunnel = ngrok.connect(port, bind_tls=True)
40
+ print(f'{address_name}:' + ssh_tunnel.public_url)
41
+ else:
42
+ print(f'{address_name}:' + ssh_tunnels[0].public_url)
43
+ else:
44
+ print('skip start ngrok')
45
+
46
+ if ngrok_use :
47
+ ngrok_start(ngrokTokenFile,7860,'ngrok_url:',ngrok_use)
48
+
49
+ startup_timer = timer.startup_timer
50
+ startup_timer.record("launcher")
51
+
52
+ initialize.imports()
53
+
54
+ initialize.check_versions()
55
+
56
+
57
+ def create_api(app):
58
+ from modules.api.api import Api
59
+ from modules.call_queue import queue_lock
60
+
61
+ api = Api(app, queue_lock)
62
+ return api
63
+
64
+
65
+ def api_only():
66
+ from fastapi import FastAPI
67
+ from modules.shared_cmd_options import cmd_opts
68
+
69
+ initialize.initialize()
70
+
71
+ app = FastAPI()
72
+ initialize_util.setup_middleware(app)
73
+ api = create_api(app)
74
+
75
+ from modules import script_callbacks
76
+ script_callbacks.before_ui_callback()
77
+ script_callbacks.app_started_callback(None, app)
78
+
79
+ print(f"Startup time: {startup_timer.summary()}.")
80
+ api.launch(
81
+ server_name="0.0.0.0" if cmd_opts.listen else "127.0.0.1",
82
+ port=cmd_opts.port if cmd_opts.port else 7861,
83
+ root_path=f"/{cmd_opts.subpath}" if cmd_opts.subpath else ""
84
+ )
85
+
86
+
87
+ def webui():
88
+ from modules.shared_cmd_options import cmd_opts
89
+
90
+ launch_api = cmd_opts.api
91
+ initialize.initialize()
92
+
93
+ from modules import shared, ui_tempdir, script_callbacks, ui, progress, ui_extra_networks
94
+
95
+ while 1:
96
+ if shared.opts.clean_temp_dir_at_start:
97
+ ui_tempdir.cleanup_tmpdr()
98
+ startup_timer.record("cleanup temp dir")
99
+
100
+ script_callbacks.before_ui_callback()
101
+ startup_timer.record("scripts before_ui_callback")
102
+
103
+ shared.demo = ui.create_ui()
104
+ startup_timer.record("create ui")
105
+
106
+ if not cmd_opts.no_gradio_queue:
107
+ shared.demo.queue(64)
108
+
109
+ gradio_auth_creds = list(initialize_util.get_gradio_auth_creds()) or None
110
+
111
+ auto_launch_browser = False
112
+ if os.getenv('SD_WEBUI_RESTARTING') != '1':
113
+ if shared.opts.auto_launch_browser == "Remote" or cmd_opts.autolaunch:
114
+ auto_launch_browser = True
115
+ elif shared.opts.auto_launch_browser == "Local":
116
+ auto_launch_browser = not any([cmd_opts.listen, cmd_opts.share, cmd_opts.ngrok, cmd_opts.server_name])
117
+
118
+ app, local_url, share_url = shared.demo.launch(
119
+ share=cmd_opts.share,
120
+ server_name=initialize_util.gradio_server_name(),
121
+ server_port=cmd_opts.port,
122
+ ssl_keyfile=cmd_opts.tls_keyfile,
123
+ ssl_certfile=cmd_opts.tls_certfile,
124
+ ssl_verify=cmd_opts.disable_tls_verify,
125
+ debug=cmd_opts.gradio_debug,
126
+ auth=gradio_auth_creds,
127
+ inbrowser=auto_launch_browser,
128
+ prevent_thread_lock=True,
129
+ allowed_paths=cmd_opts.gradio_allowed_path,
130
+ app_kwargs={
131
+ "docs_url": "/docs",
132
+ "redoc_url": "/redoc",
133
+ },
134
+ root_path=f"/{cmd_opts.subpath}" if cmd_opts.subpath else "",
135
+ )
136
+
137
+ startup_timer.record("gradio launch")
138
+
139
+ # gradio uses a very open CORS policy via app.user_middleware, which makes it possible for
140
+ # an attacker to trick the user into opening a malicious HTML page, which makes a request to the
141
+ # running web ui and do whatever the attacker wants, including installing an extension and
142
+ # running its code. We disable this here. Suggested by RyotaK.
143
+ app.user_middleware = [x for x in app.user_middleware if x.cls.__name__ != 'CORSMiddleware']
144
+
145
+ initialize_util.setup_middleware(app)
146
+
147
+ progress.setup_progress_api(app)
148
+ ui.setup_ui_api(app)
149
+
150
+ if launch_api:
151
+ create_api(app)
152
+
153
+ ui_extra_networks.add_pages_to_demo(app)
154
+
155
+ startup_timer.record("add APIs")
156
+
157
+ with startup_timer.subcategory("app_started_callback"):
158
+ script_callbacks.app_started_callback(shared.demo, app)
159
+
160
+ timer.startup_record = startup_timer.dump()
161
+ print(f"Startup time: {startup_timer.summary()}.")
162
+
163
+ try:
164
+ while True:
165
+ server_command = shared.state.wait_for_server_command(timeout=5)
166
+ if server_command:
167
+ if server_command in ("stop", "restart"):
168
+ break
169
+ else:
170
+ print(f"Unknown server command: {server_command}")
171
+ except KeyboardInterrupt:
172
+ print('Caught KeyboardInterrupt, stopping...')
173
+ server_command = "stop"
174
+
175
+ if server_command == "stop":
176
+ print("Stopping server...")
177
+ # If we catch a keyboard interrupt, we want to stop the server and exit.
178
+ shared.demo.close()
179
+ break
180
+
181
+ # disable auto launch webui in browser for subsequent UI Reload
182
+ os.environ.setdefault('SD_WEBUI_RESTARTING', '1')
183
+
184
+ print('Restarting UI...')
185
+ shared.demo.close()
186
+ time.sleep(0.5)
187
+ startup_timer.reset()
188
+ script_callbacks.app_reload_callback()
189
+ startup_timer.record("app reload callback")
190
+ script_callbacks.script_unloaded_callback()
191
+ startup_timer.record("scripts unloaded callback")
192
+ initialize.initialize_rest(reload_script_modules=True)
193
+
194
+
195
+ from modules.shared_cmd_options import cmd_opts
196
+
197
+ if cmd_opts.nowebui:
198
+ api_only()
199
+ else:
200
+ webui()
201
+
202
+ #if __name__ == "__main__":
203
+ # from modules.shared_cmd_options import cmd_opts#
204
+
205
+ # if cmd_opts.nowebui:
206
+ # api_only()
207
+ # else:
208
+ # webui()