把巨型文件 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>
294 lines
9.7 KiB
Python
294 lines
9.7 KiB
Python
from __future__ import annotations
|
||
|
||
"""screenshot_manager.cleanup - 调试图像存档目录的轮转 / 清理。"""
|
||
|
||
import os
|
||
import shutil
|
||
import time
|
||
from datetime import datetime
|
||
|
||
from douyin.core import path_config
|
||
|
||
from ._common import _mgr_log
|
||
from .paths import get_debug_captures_base_dir
|
||
|
||
|
||
def count_debug_captures_files() -> int:
|
||
"""统计所有调试图像文件的总数量
|
||
|
||
返回:
|
||
文件总数
|
||
"""
|
||
try:
|
||
debug_base_dir = get_debug_captures_base_dir()
|
||
if not os.path.exists(debug_base_dir):
|
||
return 0
|
||
|
||
total_count = 0
|
||
# 遍历所有日期目录
|
||
for item in os.listdir(debug_base_dir):
|
||
# 跳过隐藏文件和标记文件
|
||
if item.startswith("."):
|
||
continue
|
||
|
||
item_path = os.path.join(debug_base_dir, item)
|
||
if not os.path.isdir(item_path):
|
||
continue
|
||
|
||
# 统计该目录下的所有PNG文件
|
||
try:
|
||
for _root, _dirs, files in os.walk(item_path):
|
||
for f in files:
|
||
if f.lower().endswith(".png"):
|
||
total_count += 1
|
||
except Exception:
|
||
pass
|
||
|
||
return total_count
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
|
||
|
||
def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:
|
||
"""清理旧的调试图像存档目录
|
||
|
||
参数:
|
||
keep_days: 保留天数,默认7天,超过此天数的目录将被删除
|
||
max_files: 最大文件数量,默认2000,超过此数量时删除最旧的目录
|
||
|
||
返回:
|
||
清理的目录数量
|
||
"""
|
||
try:
|
||
debug_base_dir = get_debug_captures_base_dir()
|
||
if not os.path.exists(debug_base_dir):
|
||
return 0
|
||
|
||
from datetime import datetime, timedelta
|
||
|
||
# 计算截止日期
|
||
cutoff_date = datetime.now() - timedelta(days=keep_days)
|
||
|
||
deleted_count = 0
|
||
deleted_dirs = []
|
||
total_size_freed = 0
|
||
|
||
# 收集所有日期目录及其信息
|
||
dirs_info = []
|
||
for item in os.listdir(debug_base_dir):
|
||
# 跳过隐藏文件和标记文件
|
||
if item.startswith("."):
|
||
continue
|
||
|
||
item_path = os.path.join(debug_base_dir, item)
|
||
if not os.path.isdir(item_path):
|
||
continue
|
||
|
||
# 尝试解析目录名为日期(格式:YYYY-MM-DD)
|
||
try:
|
||
dir_date = datetime.strptime(item, "%Y-%m-%d")
|
||
|
||
# 统计该目录下的文件数量和大小
|
||
file_count = 0
|
||
dir_size = 0
|
||
try:
|
||
for root, _dirs, files in os.walk(item_path):
|
||
for f in files:
|
||
if f.lower().endswith(".png"):
|
||
file_count += 1
|
||
file_path = os.path.join(root, f)
|
||
try:
|
||
dir_size += os.path.getsize(file_path)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
dirs_info.append(
|
||
{
|
||
"name": item,
|
||
"path": item_path,
|
||
"date": dir_date,
|
||
"file_count": file_count,
|
||
"size": dir_size,
|
||
}
|
||
)
|
||
except ValueError:
|
||
# 如果目录名不是日期格式,跳过
|
||
continue
|
||
|
||
# 按日期排序(最旧的在前)
|
||
dirs_info.sort(key=lambda x: x["date"])
|
||
|
||
# 先按天数清理:删除超过保留天数的目录
|
||
for dir_info in dirs_info[:]:
|
||
if dir_info["date"] < cutoff_date:
|
||
try:
|
||
shutil.rmtree(dir_info["path"])
|
||
deleted_count += 1
|
||
deleted_dirs.append(dir_info["name"])
|
||
total_size_freed += dir_info["size"]
|
||
dirs_info.remove(dir_info)
|
||
except Exception as e:
|
||
try:
|
||
_mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}")
|
||
except Exception:
|
||
pass
|
||
|
||
# 再按文件数量清理:如果文件总数超过max_files,删除最旧的目录
|
||
total_files = sum(d["file_count"] for d in dirs_info)
|
||
if total_files > max_files:
|
||
# 计算需要删除的文件数量
|
||
need_delete_count = total_files - max_files
|
||
|
||
# 从最旧的目录开始删除,直到文件数量降到max_files以下
|
||
deleted_files_count = 0
|
||
for dir_info in dirs_info[:]:
|
||
if deleted_files_count >= need_delete_count:
|
||
break
|
||
|
||
try:
|
||
shutil.rmtree(dir_info["path"])
|
||
deleted_count += 1
|
||
deleted_dirs.append(dir_info["name"])
|
||
total_size_freed += dir_info["size"]
|
||
deleted_files_count += dir_info["file_count"]
|
||
dirs_info.remove(dir_info)
|
||
except Exception as e:
|
||
try:
|
||
_mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}")
|
||
except Exception:
|
||
pass
|
||
|
||
if deleted_count > 0:
|
||
try:
|
||
size_mb = total_size_freed / (1024 * 1024)
|
||
reason_parts = []
|
||
if total_files > max_files:
|
||
reason_parts.append(f"文件数量超过{max_files}")
|
||
if any(
|
||
d["date"] < cutoff_date
|
||
for d in dirs_info
|
||
if d not in [{"name": name} for name in deleted_dirs]
|
||
):
|
||
reason_parts.append(f"超过{keep_days}天")
|
||
reason = ",".join(reason_parts) if reason_parts else "自动清理"
|
||
|
||
_mgr_log(
|
||
f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}"
|
||
)
|
||
_mgr_log(f"[调试图像清理] 清理原因: {reason}")
|
||
if size_mb > 0.1: # 只显示大于0.1MB的清理
|
||
_mgr_log(f"[调试图像清理] 释放空间: {size_mb:.2f} MB")
|
||
except Exception:
|
||
pass
|
||
|
||
return deleted_count
|
||
except Exception as e:
|
||
# 清理失败不应影响程序运行
|
||
try:
|
||
_mgr_log(f"[调试图像清理] 清理旧调试图像时出错: {e}")
|
||
except Exception:
|
||
pass
|
||
return 0
|
||
|
||
|
||
|
||
|
||
def init_debug_captures_cleanup() -> None:
|
||
"""初始化调试图像清理(在程序启动时调用)
|
||
|
||
从 config.json 读取配置并执行清理
|
||
"""
|
||
try:
|
||
import json
|
||
|
||
config_path = path_config.get_config_path()
|
||
if not os.path.exists(config_path):
|
||
return
|
||
|
||
with open(config_path, "r", encoding="utf-8") as f:
|
||
config = json.load(f)
|
||
|
||
# 检查是否启用自动清理
|
||
auto_cleanup = True
|
||
keep_days = 7
|
||
max_files = 2000
|
||
|
||
if "debug_captures" in config and isinstance(config["debug_captures"], dict):
|
||
auto_cleanup = config["debug_captures"].get("auto_cleanup", True)
|
||
keep_days = int(config["debug_captures"].get("keep_days", 7))
|
||
max_files = int(config["debug_captures"].get("max_files", 2000))
|
||
|
||
if auto_cleanup:
|
||
cleanup_debug_captures(keep_days=keep_days, max_files=max_files)
|
||
except Exception:
|
||
# 初始化失败不影响程序运行
|
||
pass
|
||
|
||
|
||
# 操作类型和步骤的中文映射
|
||
_OPERATION_TYPE_CN = {
|
||
"cut_pic": "裁剪图片",
|
||
"ocr": "ocr", # 保持ocr不变
|
||
"pixel_detect": "像素检测",
|
||
"template_match": "模板匹配",
|
||
}
|
||
|
||
_STEP_CN = {
|
||
"before_ocr": "识别前",
|
||
"preprocessed": "预处理后",
|
||
"after_ocr": "识别后",
|
||
"before_detect": "检测前",
|
||
"detected": "检测成功",
|
||
"not_detected": "未检测到",
|
||
"matched": "匹配成功",
|
||
"failed": "匹配失败",
|
||
}
|
||
|
||
# picname 的中文映射
|
||
_PICNAME_CN = {
|
||
"live_room_title_mid": "直播间标题", # 现在只使用一个区域,简化为"直播间标题"
|
||
"live_room_title_large": "直播间标题_大", # 保留以兼容旧代码
|
||
"live_room_title_small": "直播间标题_小", # 保留以兼容旧代码
|
||
"live_room_title_mid_tmp": "直播间标题_临时", # 保留以兼容旧代码
|
||
"live_room_title_large_tmp": "直播间标题_大_临时", # 保留以兼容旧代码
|
||
"fudai_icon": "福袋图标",
|
||
"lucky_draw_result": "抽奖结果",
|
||
"attend_button": "参与按钮",
|
||
"live_room_icons": "直播间图标",
|
||
"fudai_content": "福袋内容",
|
||
"fudai_countdown": "福袋倒计时",
|
||
"fudai_value": "福袋价值",
|
||
"fudai_task_list": "福袋任务列表",
|
||
"fudai_coupon": "优惠券",
|
||
"shopping_redpacket": "购物红包",
|
||
}
|
||
|
||
# extra_info 键名的中文映射
|
||
_EXTRA_INFO_KEY_CN = {
|
||
"mode": "模式",
|
||
"size": "尺寸",
|
||
"used_img2": "使用图片2",
|
||
"avg_confidence": "平均置信度",
|
||
"min_confidence": "最小置信度",
|
||
"max_confidence": "最大置信度",
|
||
"confidence_items": "置信度项数",
|
||
"text_preview": "文本预览",
|
||
"text_len": "文本长度",
|
||
"source": "来源",
|
||
"has_full_screenshot": "有完整截图",
|
||
"has_coords": "有坐标",
|
||
"digits": "数字",
|
||
"type": "类型",
|
||
"region": "区域",
|
||
"y_offset": "Y偏移",
|
||
"region_size": "区域尺寸",
|
||
"content": "内容",
|
||
"threshold": "阈值",
|
||
"score": "分数",
|
||
"loc": "位置",
|
||
}
|