add stop
Browse files- owl/webapp_zh.py +117 -7
owl/webapp_zh.py
CHANGED
@@ -12,6 +12,10 @@ from dotenv import load_dotenv, set_key, find_dotenv, unset_key
|
|
12 |
import threading
|
13 |
import queue
|
14 |
import time
|
|
|
|
|
|
|
|
|
15 |
|
16 |
os.environ['PYTHONIOENCODING'] = 'utf-8'
|
17 |
|
@@ -55,6 +59,8 @@ def setup_logging():
|
|
55 |
LOG_FILE = None
|
56 |
LOG_QUEUE = queue.Queue()
|
57 |
STOP_LOG_THREAD = threading.Event()
|
|
|
|
|
58 |
|
59 |
# 日志读取和更新函数
|
60 |
def log_reader_thread(log_file):
|
@@ -239,6 +245,59 @@ def validate_input(question: str) -> bool:
|
|
239 |
return False
|
240 |
return True
|
241 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
242 |
def run_owl(question: str, example_module: str) -> Tuple[str, List[List[str]], str, str]:
|
243 |
"""运行OWL系统并返回结果
|
244 |
|
@@ -249,6 +308,11 @@ def run_owl(question: str, example_module: str) -> Tuple[str, List[List[str]], s
|
|
249 |
Returns:
|
250 |
Tuple[...]: 回答、聊天历史、令牌计数、状态
|
251 |
"""
|
|
|
|
|
|
|
|
|
|
|
252 |
# 验证输入
|
253 |
if not validate_input(question):
|
254 |
logging.warning("用户提交了无效的输入")
|
@@ -488,34 +552,65 @@ def create_ui():
|
|
488 |
# 创建一个实时日志更新函数
|
489 |
def process_with_live_logs(question, module_name):
|
490 |
"""处理问题并实时更新日志"""
|
|
|
|
|
491 |
# 创建一个后台线程来处理问题
|
492 |
result_queue = queue.Queue()
|
493 |
|
494 |
def process_in_background():
|
495 |
try:
|
|
|
|
|
|
|
|
|
|
|
496 |
result = run_owl(question, module_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
497 |
result_queue.put(result)
|
498 |
except Exception as e:
|
499 |
result_queue.put((f"发生错误: {str(e)}", [], "0", f"❌ 错误: {str(e)}"))
|
500 |
|
501 |
# 启动后台处理线程
|
502 |
bg_thread = threading.Thread(target=process_in_background)
|
|
|
503 |
bg_thread.start()
|
504 |
|
505 |
# 在等待处理完成的同时,每秒更新一次日志
|
506 |
while bg_thread.is_alive():
|
|
|
|
|
|
|
|
|
|
|
|
|
507 |
# 更新日志显示
|
508 |
logs = get_latest_logs(100)
|
509 |
yield None, None, None, "⏳ 处理中...", logs
|
510 |
time.sleep(1)
|
511 |
|
512 |
-
#
|
513 |
-
|
514 |
-
|
|
|
|
|
|
|
515 |
|
516 |
-
#
|
517 |
-
|
518 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
519 |
|
520 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as app:
|
521 |
gr.Markdown(
|
@@ -553,7 +648,9 @@ def create_ui():
|
|
553 |
elem_classes="module-info"
|
554 |
)
|
555 |
|
556 |
-
|
|
|
|
|
557 |
|
558 |
status_output = gr.Textbox(label="状态", interactive=False)
|
559 |
token_count_output = gr.Textbox(
|
@@ -729,6 +826,12 @@ def create_ui():
|
|
729 |
outputs=[answer_output, chat_output, token_count_output, status_output, log_display]
|
730 |
)
|
731 |
|
|
|
|
|
|
|
|
|
|
|
|
|
732 |
# 模块选择更新描述
|
733 |
module_dropdown.change(
|
734 |
fn=update_module_description,
|
@@ -789,7 +892,11 @@ def main():
|
|
789 |
|
790 |
# 注册应用关闭时的清理函数
|
791 |
def cleanup():
|
|
|
792 |
STOP_LOG_THREAD.set()
|
|
|
|
|
|
|
793 |
logging.info("应用程序关闭,停止日志线程")
|
794 |
|
795 |
app.launch(share=False,enable_queue=True,server_name="127.0.0.1",server_port=7860)
|
@@ -802,6 +909,9 @@ def main():
|
|
802 |
finally:
|
803 |
# 确保日志线程停止
|
804 |
STOP_LOG_THREAD.set()
|
|
|
|
|
|
|
805 |
logging.info("应用程序关闭")
|
806 |
|
807 |
if __name__ == "__main__":
|
|
|
12 |
import threading
|
13 |
import queue
|
14 |
import time
|
15 |
+
import signal
|
16 |
+
import sys
|
17 |
+
import subprocess
|
18 |
+
import platform
|
19 |
|
20 |
os.environ['PYTHONIOENCODING'] = 'utf-8'
|
21 |
|
|
|
59 |
LOG_FILE = None
|
60 |
LOG_QUEUE = queue.Queue()
|
61 |
STOP_LOG_THREAD = threading.Event()
|
62 |
+
CURRENT_PROCESS = None # 用于跟踪当前运行的进程
|
63 |
+
STOP_REQUESTED = threading.Event() # 用于标记是否请求停止
|
64 |
|
65 |
# 日志读取和更新函数
|
66 |
def log_reader_thread(log_file):
|
|
|
245 |
return False
|
246 |
return True
|
247 |
|
248 |
+
# 终止运行进程的函数
|
249 |
+
def terminate_process():
|
250 |
+
"""终止当前运行的进程,适配不同操作系统平台"""
|
251 |
+
global CURRENT_PROCESS, STOP_REQUESTED
|
252 |
+
|
253 |
+
if CURRENT_PROCESS is None:
|
254 |
+
logging.info("没有正在运行的进程")
|
255 |
+
return "没有正在运行的进程", "✅ 已就绪"
|
256 |
+
|
257 |
+
try:
|
258 |
+
STOP_REQUESTED.set() # 设置停止标志
|
259 |
+
logging.info("正在尝试终止进程...")
|
260 |
+
|
261 |
+
# 获取当前操作系统
|
262 |
+
current_os = platform.system()
|
263 |
+
|
264 |
+
if current_os == "Windows":
|
265 |
+
# Windows平台使用taskkill强制终止进程树
|
266 |
+
if hasattr(CURRENT_PROCESS, 'pid'):
|
267 |
+
subprocess.run(f"taskkill /F /T /PID {CURRENT_PROCESS.pid}", shell=True)
|
268 |
+
logging.info(f"已发送Windows终止命令到进程 {CURRENT_PROCESS.pid}")
|
269 |
+
else:
|
270 |
+
# Unix-like系统 (Linux, macOS)
|
271 |
+
if hasattr(CURRENT_PROCESS, 'pid'):
|
272 |
+
# 发送SIGTERM信号
|
273 |
+
os.killpg(os.getpgid(CURRENT_PROCESS.pid), signal.SIGTERM)
|
274 |
+
logging.info(f"已发送SIGTERM信号到进程组 {CURRENT_PROCESS.pid}")
|
275 |
+
|
276 |
+
# 给进程一些时间来清理
|
277 |
+
time.sleep(0.5)
|
278 |
+
|
279 |
+
# 如果进程仍在运行,发送SIGKILL
|
280 |
+
try:
|
281 |
+
if CURRENT_PROCESS.poll() is None:
|
282 |
+
os.killpg(os.getpgid(CURRENT_PROCESS.pid), signal.SIGKILL)
|
283 |
+
logging.info(f"已发送SIGKILL信号到进程组 {CURRENT_PROCESS.pid}")
|
284 |
+
except (ProcessLookupError, OSError):
|
285 |
+
pass # 进程可能已经终止
|
286 |
+
|
287 |
+
# 如果是线程,尝试终止线程
|
288 |
+
if isinstance(CURRENT_PROCESS, threading.Thread) and CURRENT_PROCESS.is_alive():
|
289 |
+
# 线程无法强制终止,但可以设置标志让线程自行退出
|
290 |
+
logging.info("等待线程终止...")
|
291 |
+
CURRENT_PROCESS.join(timeout=2)
|
292 |
+
|
293 |
+
CURRENT_PROCESS = None
|
294 |
+
logging.info("进程已终止")
|
295 |
+
return "进程已终止", "✅ 已就绪"
|
296 |
+
|
297 |
+
except Exception as e:
|
298 |
+
logging.error(f"终止进程时出错: {str(e)}")
|
299 |
+
return f"终止进程时出错: {str(e)}", f"❌ 错误: {str(e)}"
|
300 |
+
|
301 |
def run_owl(question: str, example_module: str) -> Tuple[str, List[List[str]], str, str]:
|
302 |
"""运行OWL系统并返回结果
|
303 |
|
|
|
308 |
Returns:
|
309 |
Tuple[...]: 回答、聊天历史、令牌计数、状态
|
310 |
"""
|
311 |
+
global CURRENT_PROCESS, STOP_REQUESTED
|
312 |
+
|
313 |
+
# 重置停止标志
|
314 |
+
STOP_REQUESTED.clear()
|
315 |
+
|
316 |
# 验证输入
|
317 |
if not validate_input(question):
|
318 |
logging.warning("用户提交了无效的输入")
|
|
|
552 |
# 创建一个实时日志更新函数
|
553 |
def process_with_live_logs(question, module_name):
|
554 |
"""处理问题并实时更新日志"""
|
555 |
+
global CURRENT_PROCESS, STOP_REQUESTED
|
556 |
+
|
557 |
# 创建一个后台线程来处理问题
|
558 |
result_queue = queue.Queue()
|
559 |
|
560 |
def process_in_background():
|
561 |
try:
|
562 |
+
# 检查是否已请求停止
|
563 |
+
if STOP_REQUESTED.is_set():
|
564 |
+
result_queue.put((f"操作已取消", [], "0", f"❌ 操作已取消"))
|
565 |
+
return
|
566 |
+
|
567 |
result = run_owl(question, module_name)
|
568 |
+
|
569 |
+
# 再次检查是否已请求停止
|
570 |
+
if STOP_REQUESTED.is_set():
|
571 |
+
result_queue.put((f"操作已取消", [], "0", f"❌ 操作已取消"))
|
572 |
+
return
|
573 |
+
|
574 |
result_queue.put(result)
|
575 |
except Exception as e:
|
576 |
result_queue.put((f"发生错误: {str(e)}", [], "0", f"❌ 错误: {str(e)}"))
|
577 |
|
578 |
# 启动后台处理线程
|
579 |
bg_thread = threading.Thread(target=process_in_background)
|
580 |
+
CURRENT_PROCESS = bg_thread # 记录当前进程
|
581 |
bg_thread.start()
|
582 |
|
583 |
# 在等待处理完成的同时,每秒更新一次日志
|
584 |
while bg_thread.is_alive():
|
585 |
+
# 检查是否已请求停止
|
586 |
+
if STOP_REQUESTED.is_set():
|
587 |
+
logs = get_latest_logs(100)
|
588 |
+
yield None, None, None, "⏹️ 正在终止...", logs
|
589 |
+
break
|
590 |
+
|
591 |
# 更新日志显示
|
592 |
logs = get_latest_logs(100)
|
593 |
yield None, None, None, "⏳ 处理中...", logs
|
594 |
time.sleep(1)
|
595 |
|
596 |
+
# 如果已请求停止但线程仍在运行
|
597 |
+
if STOP_REQUESTED.is_set() and bg_thread.is_alive():
|
598 |
+
bg_thread.join(timeout=2) # 等待线程最多2秒
|
599 |
+
logs = get_latest_logs(100)
|
600 |
+
yield "操作已取消", [], "0", "⏹️ 已终止", logs
|
601 |
+
return
|
602 |
|
603 |
+
# 处理完成,获取结果
|
604 |
+
if not result_queue.empty():
|
605 |
+
result = result_queue.get()
|
606 |
+
answer, chat_history, token_count, status = result
|
607 |
+
|
608 |
+
# 最后一次更新日志
|
609 |
+
logs = get_latest_logs(100)
|
610 |
+
yield answer, chat_history, token_count, status, logs
|
611 |
+
else:
|
612 |
+
logs = get_latest_logs(100)
|
613 |
+
yield "操作已取消或未完成", [], "0", "⏹️ 已终止", logs
|
614 |
|
615 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as app:
|
616 |
gr.Markdown(
|
|
|
648 |
elem_classes="module-info"
|
649 |
)
|
650 |
|
651 |
+
with gr.Row():
|
652 |
+
run_button = gr.Button("运行", variant="primary", elem_classes="primary")
|
653 |
+
stop_button = gr.Button("停止", variant="stop", elem_classes="stop")
|
654 |
|
655 |
status_output = gr.Textbox(label="状态", interactive=False)
|
656 |
token_count_output = gr.Textbox(
|
|
|
826 |
outputs=[answer_output, chat_output, token_count_output, status_output, log_display]
|
827 |
)
|
828 |
|
829 |
+
# 添加停止按钮事件处理
|
830 |
+
stop_button.click(
|
831 |
+
fn=terminate_process,
|
832 |
+
outputs=[answer_output, status_output]
|
833 |
+
)
|
834 |
+
|
835 |
# 模块选择更新描述
|
836 |
module_dropdown.change(
|
837 |
fn=update_module_description,
|
|
|
892 |
|
893 |
# 注册应用关闭时的清理函数
|
894 |
def cleanup():
|
895 |
+
global STOP_LOG_THREAD, STOP_REQUESTED
|
896 |
STOP_LOG_THREAD.set()
|
897 |
+
STOP_REQUESTED.set()
|
898 |
+
# 尝试终止当前进程
|
899 |
+
terminate_process()
|
900 |
logging.info("应用程序关闭,停止日志线程")
|
901 |
|
902 |
app.launch(share=False,enable_queue=True,server_name="127.0.0.1",server_port=7860)
|
|
|
909 |
finally:
|
910 |
# 确保日志线程停止
|
911 |
STOP_LOG_THREAD.set()
|
912 |
+
STOP_REQUESTED.set()
|
913 |
+
# 尝试终止当前进程
|
914 |
+
terminate_process()
|
915 |
logging.info("应用程序关闭")
|
916 |
|
917 |
if __name__ == "__main__":
|