Files
douyi_guaji_main/douyin/handlers/screenshot_manager/async_save.py
T
2026-06-03 10:47:39 +08:00

195 lines
6.2 KiB
Python

from __future__ import annotations
"""screenshot_manager.async_save - 异步调试图像保存工作线程。
定义:
- _debug_save_loop:消费 _debug_save_queue 的后台线程入口
- shutdown_debug_save_worker:优雅关闭(atexit 注册一次)
- _ensure_debug_save_worker_started:启动 worker(双检查锁)
"""
import json
import os
import threading
import traceback
from datetime import datetime
from queue import Empty
from typing import Optional, Tuple
import logging
from PIL import Image
from douyin.core import path_config
from ._common import (
_async_save_counters_lock,
_debug_save_queue,
_debug_save_shutdown_event,
_debug_save_worker_lock,
)
from . import _common as _state
from .paths import ensure_debug_captures_dir
from .save_image_helpers import annotate_debug_image
def _debug_log_on_complete(file_path: str) -> None:
try:
cfg_path = path_config.get_config_path()
log_on_complete = False
if os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as _f:
cfg = json.load(_f)
dbg_cfg = (
cfg.get("debug_captures", {})
if isinstance(cfg.get("debug_captures"), dict)
else {}
)
log_on_complete = bool(dbg_cfg.get("log_on_complete", False))
if log_on_complete:
logging.debug("[调试图像] 异步保存完成: %s", file_path)
except Exception:
pass
def _record_async_success(file_path: str) -> None:
try:
with _async_save_counters_lock:
_state._async_save_success_count += 1
except Exception:
pass
_debug_log_on_complete(file_path)
def _record_async_failure(file_path: str) -> None:
try:
logs_dir = path_config.get_logs_dir()
os.makedirs(logs_dir, exist_ok=True)
err_path = os.path.join(logs_dir, "async_debug_save_errors.log")
with open(err_path, "a", encoding="utf-8") as ef:
ef.write(f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n")
ef.write(traceback.format_exc())
ef.write("\n\n")
except Exception:
pass
try:
with _async_save_counters_lock:
_state._async_save_failure_count += 1
except Exception:
pass
try:
logging.getLogger("action_logger").info("[调试图像] 异步保存失败: %s", file_path)
except Exception:
pass
def _debug_save_loop() -> None:
"""后台线程循环,消费调试图像保存任务并执行同步保存。"""
while not _debug_save_shutdown_event.is_set():
try:
task = _debug_save_queue.get(timeout=1.0)
if task is None:
_debug_save_queue.task_done()
break
(
img,
file_path,
annotate,
coords,
extra_info,
operation_type,
picname,
step,
) = task
# 在函数中修改全局计数器时需要声明 global,避免静态分析/运行时错误
try:
# 执行同步保存(重复之前 save_debug_image 中的标注与保存逻辑)
def _save_image_with_retry(
img_to_save: Image.Image, path: str, max_retries: int = 2
) -> bool:
last_error = None
for attempt in range(max_retries):
try:
img_to_save.save(path, "PNG")
return True
except FileNotFoundError as e:
last_error = e
if attempt < max_retries - 1:
try:
ensure_debug_captures_dir()
except Exception:
pass
else:
raise
except PermissionError:
raise
except OSError:
raise
if last_error:
raise last_error
return False
try:
img_to_save = img
if annotate and (coords or extra_info):
try:
img_to_save = annotate_debug_image(
image=img,
picname=picname,
step=step,
coords=coords,
extra_info=extra_info,
)
except Exception:
img_to_save = img
_save_image_with_retry(img_to_save, file_path)
_record_async_success(file_path)
except Exception:
_record_async_failure(file_path)
except Exception:
pass
finally:
_debug_save_queue.task_done()
except Empty:
continue
except Exception:
# 防止线程因异常退出
try:
import time
time.sleep(0.1)
except Exception:
pass
def shutdown_debug_save_worker(timeout: float = 5.0) -> None:
"""优雅关闭调试保存工作线程"""
if not _state._debug_save_worker_started:
return
_debug_save_shutdown_event.set()
_debug_save_queue.put(None) # 毒丸信号
try:
_debug_save_queue.join()
except Exception:
pass
_state._debug_save_worker_started = False
# 注册 atexit 清理函数
import atexit
atexit.register(shutdown_debug_save_worker)
def _ensure_debug_save_worker_started() -> None:
if _state._debug_save_worker_started:
return
with _debug_save_worker_lock:
if _state._debug_save_worker_started:
return
t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True)
t.start()
_state._debug_save_worker_started = True