Files
douyi_guaji_main/douyin/handlers/screenshot_manager/async_save.py
T
CodexandClaude Opus 4.7 bf7f30996e 拆分 douyin_screenshot_manager (1705 → 6 个子模块 + 79 行 shim)
把巨型文件 douyin/handlers/douyin_screenshot_manager.py 按职责拆成
douyin/handlers/screenshot_manager/ 子包:

- _common (79)     共享 logger / 全局状态 / 异步计数器
- paths (205)      OCR 目录、调试存档目录、各类路径
- save_files (173) save_latest_attempt / save_last_success / save_*_from_file / cleanup_ocr_dir
- async_save (360) _debug_save_loop + 工作线程启停(global 状态走 _common._state.X)
- cleanup (293)    debug_captures 目录清理与轮转
- save_image (731) save_debug_image 主入口(最大头)

原文件改为 79 行 re-export shim,30 个公共符号全部保留。
外部 29 处 save_debug_image / 6 处 save_latest_attempt / 等
import 路径不变,零调用方修改。

回归:
- 子包 7 文件 + shim compileall 通过
- pytest 353 passed / 1 skipped(与拆分前完全一致)
- 旧 import 路径与新子包路径返回同一函数对象
- AST 验证 30 个期望符号全部正确暴露

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 16:25:59 +08:00

361 lines
16 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, ImageDraw, ImageFont
from douyin.core import path_config
from ._common import (
_async_save_counters_lock,
_debug_save_queue,
_debug_save_shutdown_event,
_debug_save_worker_lock,
_LOGGER,
_mgr_log,
)
from . import _common as _state
from .paths import ensure_debug_captures_dir
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
# 标注并保存
if annotate and (coords or extra_info):
try:
from PIL import ImageDraw, ImageFont
annotated_image = img.copy()
draw = ImageDraw.Draw(annotated_image)
try:
font = ImageFont.truetype("arial.ttf", 12)
except Exception:
try:
font = ImageFont.load_default()
except Exception:
font = None
if coords:
x1, y1, x2, y2 = coords
img_w, img_h = annotated_image.size
x1 = max(0, min(x1, img_w - 1))
y1 = max(0, min(y1, img_h - 1))
x2 = max(0, min(x2, img_w - 1))
y2 = max(0, min(y2, img_h - 1))
if x1 < x2 and y1 < y2:
rect_coords = (
float(x1),
float(y1),
float(x2),
float(y2),
)
draw.rectangle(rect_coords, outline="red", width=2)
if extra_info:
text_lines = [f"{k}: {v}" for k, v in extra_info.items()]
if text_lines:
text = "\n".join(text_lines)
try:
draw.text((5, 5), text, fill="yellow", font=font)
except Exception:
pass
try:
_save_image_with_retry(annotated_image, file_path)
# 计数并写入 actions.log
try:
with _async_save_counters_lock:
_state._async_save_success_count += 1
except Exception:
pass
try:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
# 保存完成时的可选日志(原有逻辑)
try:
import json, logging
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.info(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
except Exception:
try:
_save_image_with_retry(img, file_path)
try:
with _async_save_counters_lock:
_state._async_save_success_count += 1
except Exception:
pass
try:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
try:
import json, logging
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.info(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
except Exception:
# 保存失败:写入异步错误日志、计数并写入 actions.log
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:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存失败: %s", file_path
)
except Exception:
pass
# 捕获标注过程中的任何异常,避免线程退出
except Exception:
pass
# end if annotate block
else:
try:
_save_image_with_retry(img, file_path)
try:
with _async_save_counters_lock:
_state._async_save_success_count += 1
except Exception:
pass
try:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
try:
import json, logging
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.info("[调试图像] 异步保存完成: %s", file_path)
except Exception:
pass
except Exception:
# 保存失败:写入异步错误日志以便追踪,同时记录到 actions.log
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:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存失败: %s", file_path
)
except Exception:
pass
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
# 注册 atexit 清理函数(仅注册一次)
import atexit
atexit.register(shutdown_debug_save_worker)