chore: Clean up and refactor codebase for improved maintainability
- Removed obsolete command-line test parameters from `run_cli.py` to streamline functionality. - Introduced a new `ocr_preprocess.py` module for unified OCR image preprocessing, enhancing recognition stability. - Updated various components to utilize the new preprocessing function, improving code organization and readability. - Adjusted configuration values in `config.json` for better performance and consistency. - Added comprehensive technical documentation for the Douyin project, detailing code modification standards and operational guidelines. - Cleaned up excessive blank lines across multiple files to enhance overall readability.
This commit is contained in:
1 parent
efe6e2252f
commit
223c127e11
70 files changed
+17121
-1752
No files matched your search
@@ -270,19 +270,8 @@ class underlying_operations:
|
||||
), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||||
# 使用 PaddleOCR(强制 CPU 模式)
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
|
||||
if (
|
||||
paddle.device.is_compiled_with_cuda()
|
||||
and paddle.device.get_device()
|
||||
):
|
||||
use_gpu = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
@@ -293,8 +282,7 @@ class underlying_operations:
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||||
print(f"[OCR] EasyOCR不可用,使用 PaddleOCR({gpu_status})")
|
||||
print(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)")
|
||||
print(
|
||||
f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr"
|
||||
)
|
||||
@@ -373,19 +361,8 @@ class underlying_operations:
|
||||
):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||||
# 使用 PaddleOCR(强制 CPU 模式)
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
|
||||
if (
|
||||
paddle.device.is_compiled_with_cuda()
|
||||
and paddle.device.get_device()
|
||||
):
|
||||
use_gpu = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
@@ -396,8 +373,7 @@ class underlying_operations:
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:使用 PaddleOCR({gpu_status})")
|
||||
print(f"[OCR] 延迟初始化:使用 PaddleOCR(CPU模式)")
|
||||
except Exception:
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
|
||||
+2
-1
@@ -25,6 +25,7 @@
|
||||
"high_value_room_revisit_only_current_run": true,
|
||||
"reservation_back_verify_enabled": true,
|
||||
"reservation_back_swipe_delay": 0.5,
|
||||
"record_room_title_mapping_enabled": true,
|
||||
"reservation_preempt_min_value": 0.0,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
@@ -84,4 +85,4 @@
|
||||
"yanghao_comment_texts": [],
|
||||
"yanghao_like_keywords": [],
|
||||
"yanghao_fav_keywords": []
|
||||
}
|
||||
}
|
||||
+8
-8
@@ -7,7 +7,7 @@
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 120,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 50,
|
||||
"reset_after_swipes": 10,
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"high_value_fudai_enabled": true,
|
||||
@@ -29,7 +29,7 @@
|
||||
"yanghao_fallback_enter_live_y": 1200,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
"fudai_icon_max_wait_seconds": 8.5,
|
||||
"fudai_icon_max_wait_seconds": 8.0,
|
||||
"fudai_click_wait_seconds": 1.7,
|
||||
"fudai_detail_initial_wait_seconds": 0.8,
|
||||
"fudai_detail_verified_wait_seconds": 0.2,
|
||||
@@ -76,9 +76,9 @@
|
||||
"yanghao_comment_texts": [],
|
||||
"yanghao_like_keywords": [],
|
||||
"yanghao_fav_keywords": [],
|
||||
"stage_diag_max_time": 5.0,
|
||||
"stage_diag_max_time": 6.0,
|
||||
"stage_diag_max_step_time": 2.0,
|
||||
"live_room_match_threshold": 0.6,
|
||||
"live_room_match_threshold": 0.8,
|
||||
"enable_ocr_mode1": false,
|
||||
"fudai_template_match_enabled": false,
|
||||
"fudai_template_match_threshold": 0.7,
|
||||
@@ -101,9 +101,9 @@
|
||||
"beautify_output": true,
|
||||
"show_timestamps": true,
|
||||
"show_execution_times": true,
|
||||
"debug_detail_level": "normal",
|
||||
"debug_detail_level": "detailed",
|
||||
"error_detail_level": "full",
|
||||
"action_log_format": "concise",
|
||||
"action_log_format": "detailed",
|
||||
"color_output": true,
|
||||
"max_log_lines_display": 1000,
|
||||
"auto_scroll_logs": true,
|
||||
@@ -129,7 +129,7 @@
|
||||
"debug_captures": {
|
||||
"enabled": true,
|
||||
"keep_days": 3,
|
||||
"max_files": 2000,
|
||||
"max_files": 1900,
|
||||
"auto_cleanup": true
|
||||
},
|
||||
"fudai_detail_template_threshold": 0.54,
|
||||
@@ -138,7 +138,7 @@
|
||||
"attend_button_red_ratio_threshold": 0.25,
|
||||
"fansclub_join_red_ratio_threshold": 0.25,
|
||||
"reservation_test_mode": false,
|
||||
"swipe_duration_ms": 600,
|
||||
"swipe_duration_ms": 300,
|
||||
"gui": {
|
||||
"theme": "litera"
|
||||
}
|
||||
|
||||
+6811
File diff suppressed because it is too large.
Load diff
+176
-168
@@ -22,7 +22,6 @@ from douyin.detection import douyin_detection
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
from douyin.core import douyin_flow_control
|
||||
from douyin.logging.action_tracker import track_action
|
||||
from douyin.other import douyin_live_room
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
from douyin.utils import douyin_config
|
||||
@@ -34,24 +33,8 @@ from douyin.handlers import douyin_swipe_handler
|
||||
from douyin.reservation import douyin_reservation_handler
|
||||
from douyin.stage import douyin_stage_handler
|
||||
|
||||
from .fudai_modules import (
|
||||
NavigationMixin,
|
||||
StageDetectionMixin,
|
||||
PopupHandlerMixin,
|
||||
LotteryResultMixin,
|
||||
RoomUtilsMixin,
|
||||
MainLogicMixin,
|
||||
)
|
||||
|
||||
|
||||
class fudai_analyse(
|
||||
NavigationMixin,
|
||||
StageDetectionMixin,
|
||||
PopupHandlerMixin,
|
||||
LotteryResultMixin,
|
||||
RoomUtilsMixin,
|
||||
MainLogicMixin,
|
||||
):
|
||||
class fudai_analyse:
|
||||
"""福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。"""
|
||||
|
||||
# 类常量:魔法数字提取
|
||||
@@ -74,12 +57,7 @@ class fudai_analyse(
|
||||
|
||||
# 运行配置(只保留与你当前需求直接相关的主流程字段,细节统一放在各子模块内部)
|
||||
self.operation = underlying_operations()
|
||||
try:
|
||||
import path_config
|
||||
self.config_path = path_config.get_config_path()
|
||||
except Exception:
|
||||
import path_config
|
||||
self.config_path = path_config.get_config_path()
|
||||
self.config_path = "config/config.json"
|
||||
|
||||
# 日志相关字段:完全独立的日志系统(不依赖原始代码)
|
||||
try:
|
||||
@@ -98,31 +76,6 @@ class fudai_analyse(
|
||||
self._last_log_tag = None
|
||||
# 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告
|
||||
self._std_logger = None # type: ignore[assignment]
|
||||
# 后台 tick:供等待循环期间执行轻量后台任务(可被覆盖)
|
||||
# 示例用途:在等待直播间标题出现时处理弹窗、更新小状态等
|
||||
def _default_background_tick():
|
||||
try:
|
||||
# 处理优惠券弹窗(如果存在)
|
||||
if hasattr(self, "_check_coupon_popup") and callable(getattr(self, "_check_coupon_popup")):
|
||||
try:
|
||||
self._check_coupon_popup()
|
||||
except Exception:
|
||||
pass
|
||||
# 处理购物红包弹窗(如果存在)
|
||||
if hasattr(self, "_check_shopping_redpacket_popup") and callable(getattr(self, "_check_shopping_redpacket_popup")):
|
||||
try:
|
||||
self._check_shopping_redpacket_popup()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 绑定为实例方法
|
||||
try:
|
||||
self.background_tick = _default_background_tick # type: ignore[assignment]
|
||||
except Exception:
|
||||
# 若绑定失败,保证属性存在
|
||||
self.background_tick = lambda: None # type: ignore[assignment]
|
||||
|
||||
# 初始化统一日志系统和traceId
|
||||
# 确保日志系统已配置(在实例化之前)
|
||||
@@ -278,14 +231,9 @@ class fudai_analyse(
|
||||
self.queue_full_waiting_at_earliest: bool = False
|
||||
|
||||
# 预约队列状态文件(供 WebGUI / 其他进程查看)
|
||||
try:
|
||||
import path_config
|
||||
self._reservations_state_path: str = path_config.get_reservations_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
self._reservations_state_path: str = os.path.join(
|
||||
os.path.dirname(__file__), "state", "reservations.json"
|
||||
)
|
||||
self._reservations_state_path: str = os.path.join(
|
||||
os.path.dirname(__file__), "state", "reservations.json"
|
||||
)
|
||||
|
||||
# 运行时直播间标题和位置映射表(用于回退校验)
|
||||
# 格式:{room_pos: (room_title, room_title_raw)}
|
||||
@@ -313,9 +261,32 @@ class fudai_analyse(
|
||||
self.load_config()
|
||||
|
||||
# ===== 兼容原始脚本的一些简单封装方法 =====
|
||||
# RoomUtilsMixin 已提供 _find_room_pos_by_title 和 _record_room_title_and_pos 方法
|
||||
def _find_room_pos_by_title(
|
||||
self, target_title: str, target_title_raw: str = ""
|
||||
) -> int | None:
|
||||
"""根据直播间标题在运行时映射表中查找对应的位置。
|
||||
|
||||
# NavigationMixin 已提供 click 和 load_config 方法
|
||||
返回:
|
||||
如果找到匹配的位置,返回位置值;否则返回 None
|
||||
"""
|
||||
return douyin_reservation_handler.ReservationHandler.find_room_pos_by_title(
|
||||
self, target_title, target_title_raw
|
||||
)
|
||||
|
||||
def _record_room_title_and_pos(self) -> None:
|
||||
"""记录当前直播间的标题和位置到运行时映射表。
|
||||
|
||||
用于预约回退校验时验证位置信息。
|
||||
"""
|
||||
douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self)
|
||||
|
||||
def click(self, x: int, y: int) -> None:
|
||||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
|
||||
douyin_helpers.HelperFunctions.click(self, x, y)
|
||||
|
||||
def load_config(self) -> None:
|
||||
"""从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。"""
|
||||
douyin_config.ConfigManager.load_config_from_file(self) # type: ignore[attr-defined]
|
||||
|
||||
# ========== 兼容旧入口:主循环 ==========
|
||||
def fudai_choujiang(
|
||||
@@ -347,21 +318,10 @@ class fudai_analyse(
|
||||
|
||||
start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
try:
|
||||
try:
|
||||
import path_config
|
||||
actions_log_path = path_config.get_actions_log_path()
|
||||
log_dir = path_config.get_logs_dir()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
try:
|
||||
import path_config
|
||||
actions_log_path = path_config.get_actions_log_path()
|
||||
log_dir = path_config.get_logs_dir()
|
||||
except Exception:
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
with open(
|
||||
@@ -418,16 +378,10 @@ class fudai_analyse(
|
||||
|
||||
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
|
||||
try:
|
||||
import path_config
|
||||
actions_log_path = path_config.get_actions_log_path()
|
||||
log_dir = path_config.get_logs_dir()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
with open(
|
||||
@@ -498,10 +452,56 @@ class fudai_analyse(
|
||||
time.sleep(1.0)
|
||||
|
||||
# ========== 阶段诊断 ==========
|
||||
# StageDetectionMixin 已提供 _diagnose_stage_from_current_screen 方法
|
||||
def _diagnose_stage_from_current_screen(self) -> Tuple[str, str]:
|
||||
"""封装到子模块的阶段诊断入口。"""
|
||||
return douyin_stage_handler.StageHandler.diagnose_stage_from_current_screen(
|
||||
self
|
||||
)
|
||||
|
||||
# ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ==========
|
||||
# NavigationMixin 和 StageDetectionMixin 已提供截图和坐标转换相关方法
|
||||
def cut_pic(
|
||||
self,
|
||||
x_top: int = 1,
|
||||
y_top: int = 1,
|
||||
x_bottom: int = 2,
|
||||
y_bottom: int = 2,
|
||||
target: str = "",
|
||||
cut_pic_name: str = "",
|
||||
y_pianyi: int = 0,
|
||||
) -> None:
|
||||
"""裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。"""
|
||||
douyin_screenshot_handler.ScreenshotHandler.cut_pic(
|
||||
self, x_top, y_top, x_bottom, y_bottom, target, cut_pic_name, y_pianyi
|
||||
)
|
||||
|
||||
def _read_pixel_stage_state(
|
||||
self, return_details: bool = False
|
||||
) -> dict | tuple[dict, dict]:
|
||||
"""读取像素阶段状态(用于阶段诊断)。
|
||||
|
||||
参数:
|
||||
return_details: 是否返回每个检测步骤的详细信息(包括分数)
|
||||
|
||||
返回:
|
||||
dict: 检测结果(return_details=False时)
|
||||
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
|
||||
"""
|
||||
return douyin_helpers.HelperFunctions.read_pixel_stage_state(
|
||||
self, return_details
|
||||
)
|
||||
|
||||
def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]:
|
||||
"""将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。
|
||||
|
||||
返回 (scaled_x, scaled_y)
|
||||
"""
|
||||
return douyin_screenshot_handler.ScreenshotHandler.scale_from_base(
|
||||
self, base_x, base_y
|
||||
)
|
||||
|
||||
def _save_step_screenshot(self, label: str) -> None:
|
||||
"""保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。"""
|
||||
douyin_screenshot_handler.ScreenshotHandler.save_step_screenshot(self, label)
|
||||
|
||||
def _check_in_live_room_by_icon(
|
||||
self,
|
||||
@@ -538,38 +538,24 @@ class fudai_analyse(
|
||||
)
|
||||
|
||||
# ========== 弹窗 / 人机校验 ==========
|
||||
# PopupHandlerMixin 已提供 _check_coupon_popup 和 _check_shopping_redpacket_popup 方法
|
||||
def _check_coupon_popup(self) -> bool:
|
||||
"""购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的"看门狗"中使用)。"""
|
||||
return douyin_popup_handler.PopupHandler.check_coupon_popup(self)
|
||||
|
||||
def _check_shopping_redpacket_popup(self) -> bool:
|
||||
"""购物红包中央弹窗。"""
|
||||
return douyin_popup_handler.PopupHandler.check_shopping_redpacket_popup(self)
|
||||
|
||||
# ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ==========
|
||||
@track_action("run_once_basic")
|
||||
def run_once_basic(self, recursion_depth: int = 0) -> None: # type: ignore[complexity]
|
||||
def run_once_basic(self) -> None: # type: ignore[complexity]
|
||||
"""单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。
|
||||
|
||||
参数:
|
||||
recursion_depth: 递归深度,用于防止栈溢出(默认 0)
|
||||
|
||||
注意:此方法复杂度较高,已通过模块化重构将部分逻辑拆分到子模块。
|
||||
"""
|
||||
from douyin.reservation import douyin_reservation_logic # 确保在函数作用域内可用
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# 0.1. 优先检查预约回退直接参与标志(避免陷入循环)
|
||||
reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False)
|
||||
if reservation_direct_attend:
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 检测到预约回退直接参与标志,立即执行参与逻辑",
|
||||
reservation_direct_attend=reservation_direct_attend,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 执行直接参与逻辑(跳过其他检查)
|
||||
self._handle_reservation_direct_attend()
|
||||
return
|
||||
|
||||
# 0.2. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果
|
||||
# 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果
|
||||
if getattr(self, "_waiting_for_lottery_result", False):
|
||||
try:
|
||||
# 检查是否有高价值预约需要处理(除非遇到高价值预约,否则应该等待福袋开奖)
|
||||
@@ -852,24 +838,31 @@ class fudai_analyse(
|
||||
|
||||
# 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间"
|
||||
try:
|
||||
# 从状态文件加载预约队列,保持预约记录的持久化
|
||||
# 每次开始运行时丢弃旧的预约队列,不加载状态文件
|
||||
try:
|
||||
# 检查是否已经初始化预约队列
|
||||
if not hasattr(self, "reservations") or self.reservations is None:
|
||||
self.reservations = []
|
||||
|
||||
# 如果是第一次运行,从状态文件加载预约队列
|
||||
# 如果是第一次运行,清空预约队列,不加载状态文件
|
||||
is_first_run = getattr(self, "_first_run_once_basic", True)
|
||||
# 记录清空前的队列状态(用于调试)
|
||||
old_reservations_count = 0
|
||||
try:
|
||||
old_reservations_count = (
|
||||
len(self.reservations)
|
||||
if hasattr(self, "reservations") and self.reservations
|
||||
else 0
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if is_first_run:
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 第一次运行:清空预约队列,确保每次启动都是干净状态",
|
||||
"[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件",
|
||||
old_reservations_count=old_reservations_count,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 清空预约队列(强制清空,确保每次启动时队列为空)
|
||||
try:
|
||||
# 先记录清空前的状态
|
||||
@@ -887,6 +880,7 @@ class fudai_analyse(
|
||||
|
||||
# 同时清空状态文件,确保外部查看时也是空的
|
||||
try:
|
||||
|
||||
state_path = getattr(self, "_reservations_state_path", None)
|
||||
if state_path:
|
||||
# 写入空队列到状态文件
|
||||
@@ -932,14 +926,13 @@ class fudai_analyse(
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 标记已运行过
|
||||
try:
|
||||
self._first_run_once_basic = False
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 如果不是第一次运行,保持当前内存中的预约队列
|
||||
# 如果不是第一次运行,也记录日志(用于调试)
|
||||
try:
|
||||
current_count = (
|
||||
len(self.reservations)
|
||||
@@ -954,6 +947,9 @@ class fudai_analyse(
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 不再从状态文件加载预约数据,每次启动时都从空队列开始
|
||||
# 已移除从状态文件加载预约数据的逻辑,每次启动时预约队列为空
|
||||
except Exception as exc:
|
||||
try:
|
||||
self._log_kv(
|
||||
@@ -1626,23 +1622,11 @@ class fudai_analyse(
|
||||
pass
|
||||
# 为避免递归过深,仅在当前检测到不在抖音前台的场景下递归一次;
|
||||
# 自救完成后前台包名应为抖音,下一次 run_once_basic 将不会再次进入自救分支。
|
||||
MAX_RECURSION_DEPTH = 3
|
||||
if recursion_depth >= MAX_RECURSION_DEPTH:
|
||||
try:
|
||||
self._log_kv(
|
||||
"流程",
|
||||
"run_once_basic:达到最大递归深度,停止递归",
|
||||
recursion_depth=recursion_depth,
|
||||
max_depth=MAX_RECURSION_DEPTH,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
try:
|
||||
self.operation.delay(0.5)
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
self.run_once_basic(recursion_depth + 1)
|
||||
self.run_once_basic()
|
||||
return
|
||||
except Exception as e:
|
||||
try:
|
||||
@@ -2204,11 +2188,6 @@ class fudai_analyse(
|
||||
次数=2,
|
||||
)
|
||||
self.operation.delay(self.ENTER_LIVE_FINAL_DELAY)
|
||||
# 标记刚刚切换直播间,后续读取标题时会等待标题出现
|
||||
try:
|
||||
self._just_switched_room = True
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
self._log_kv("流程", "处理推荐页面时出错", error=str(e))
|
||||
# 如果出错,尝试回退
|
||||
@@ -2265,26 +2244,79 @@ class fudai_analyse(
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
|
||||
# LotteryResultMixin 已提供 _check_lottery_result_by_ocr 和 _handle_lottery_result_by_ocr 方法
|
||||
def _check_lottery_result_by_ocr(self) -> Optional[str]:
|
||||
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。"""
|
||||
return douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(self)
|
||||
|
||||
def _shot_and_diagnose(self, tag: str, msg: str, device_id: str, diagnose: bool = True) -> None:
|
||||
"""截图并执行阶段诊断(兼容旧版调用方式)。"""
|
||||
douyin_helpers.HelperFunctions.shot_and_diagnose(self, tag, msg, device_id, diagnose)
|
||||
def _handle_lottery_result_by_ocr(self, result_type: str) -> None:
|
||||
"""根据OCR识别结果处理开奖结果。
|
||||
|
||||
参数:
|
||||
result_type: "我知道了" 或 "立即领取奖品"
|
||||
"""
|
||||
douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(self, result_type)
|
||||
|
||||
def _shot_and_diagnose(
|
||||
self, tag: str, msg: str, device_id: str, diagnose: bool = True
|
||||
) -> None:
|
||||
"""截图并执行阶段诊断(兼容旧版调用方式)。
|
||||
|
||||
Args:
|
||||
tag: 日志标签
|
||||
msg: 日志消息
|
||||
device_id: 设备ID
|
||||
diagnose: 是否执行阶段诊断(默认True)
|
||||
"""
|
||||
douyin_helpers.HelperFunctions.shot_and_diagnose(
|
||||
self, tag, msg, device_id, diagnose
|
||||
)
|
||||
|
||||
# ========== 基础动作封装 ==========
|
||||
# NavigationMixin 已提供导航相关方法
|
||||
def swipe_up_to_next_live(self) -> None:
|
||||
"""上滑切换直播间(简单版封装)。
|
||||
|
||||
# RoomUtilsMixin 已提供 _seek_reservation_room 方法
|
||||
注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间),
|
||||
则不允许上划离开预约直播间,直接返回。
|
||||
"""
|
||||
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(self)
|
||||
|
||||
def _return_to_recommend_and_reenter_live(self) -> None:
|
||||
"""返回推荐页面并重新进入直播间。
|
||||
|
||||
通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。
|
||||
"""
|
||||
douyin_swipe_handler.SwipeHandler.return_to_recommend_and_reenter_live(self)
|
||||
|
||||
def swipe_down_back_from_live(self) -> None:
|
||||
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。"""
|
||||
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(self)
|
||||
|
||||
def _maybe_reset_after_swipes(self) -> int:
|
||||
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
|
||||
|
||||
返回:
|
||||
重置后的滑动次数(通常为0)
|
||||
"""
|
||||
return douyin_swipe_handler.SwipeHandler.maybe_reset_after_swipes(self)
|
||||
|
||||
def _seek_reservation_room(self, item: dict[str, Any]) -> bool:
|
||||
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
|
||||
|
||||
说明:
|
||||
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
|
||||
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
|
||||
"""
|
||||
return douyin_reservation_handler.ReservationHandler.seek_reservation_room(
|
||||
self, item
|
||||
)
|
||||
|
||||
# ========== 福袋相关 ==========
|
||||
@track_action("handle_reservation_direct_attend")
|
||||
def _handle_reservation_direct_attend(self) -> None:
|
||||
"""预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。"""
|
||||
douyin_reservation_handler.ReservationHandler.handle_reservation_direct_attend(
|
||||
self
|
||||
)
|
||||
|
||||
@track_action("handle_in_fudai_detail")
|
||||
def _handle_in_fudai_detail(self) -> None:
|
||||
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
|
||||
start_time = time.time()
|
||||
@@ -3014,23 +3046,6 @@ def _shot_and_diagnose(self, tag: str, msg: str, device_id: str, diagnose: bool
|
||||
remain_seconds=remain_seconds,
|
||||
future_ts=int(future_timestamp),
|
||||
)
|
||||
# 参与成功,重置兜底重试计数,避免后续兜底逻辑误触
|
||||
try:
|
||||
self._fudai_detail_retry_count = 0
|
||||
except Exception:
|
||||
pass
|
||||
# 增加额外诊断日志,便于排查进入等待开奖阶段的时序问题
|
||||
try:
|
||||
self._log_kv(
|
||||
"参与",
|
||||
"进入等待开奖阶段",
|
||||
remain_seconds=remain_seconds,
|
||||
future_ts=int(future_timestamp),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查是否是预约福袋,如果是,清除锁定期并从预约队列中移除已完成的预约
|
||||
try:
|
||||
@@ -3229,13 +3244,6 @@ def _shot_and_diagnose(self, tag: str, msg: str, device_id: str, diagnose: bool
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 重置详情页验证标志,开始新一轮福袋查找
|
||||
try:
|
||||
self._fudai_detail_verified = False
|
||||
self._fudai_detail_verified_retry = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
room_pos_ref: List[int] = [0]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
|
||||
if not opened:
|
||||
|
||||
@@ -86,3 +86,25 @@ class BaseFudaiMixin:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -41,3 +41,5 @@ class LotteryResultMixin:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -70,9 +70,39 @@ class MainLogicMixin(BaseFudaiMixin):
|
||||
self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400
|
||||
|
||||
# 加载配置
|
||||
# #region agent log
|
||||
import json
|
||||
import time as time_module
|
||||
from path_config import get_debug_log_path
|
||||
current_ts = int(time_module.time() * 1000)
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{current_ts}_load_config_call",
|
||||
"timestamp": current_ts,
|
||||
"location": "fudai_main_logic.py:73",
|
||||
"message": "调用 load_config 方法",
|
||||
"data": {"method": "load_config", "action": "call"},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "call_check_run1",
|
||||
"hypothesisId": "call_check_hyp2"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
self._safe_operation_call("load_config")
|
||||
|
||||
# 主循环
|
||||
# #region agent log
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{current_ts}_run_once_basic_call",
|
||||
"timestamp": current_ts,
|
||||
"location": "fudai_main_logic.py:76",
|
||||
"message": "调用 run_once_basic 方法",
|
||||
"data": {"method": "run_once_basic", "action": "call"},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "call_check_run1",
|
||||
"hypothesisId": "call_check_hyp2"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
self._safe_operation_call("run_once_basic")
|
||||
|
||||
def _handle_reservation_direct_attend(self) -> None:
|
||||
@@ -83,45 +113,157 @@ class MainLogicMixin(BaseFudaiMixin):
|
||||
)
|
||||
|
||||
def _handle_in_fudai_detail(self) -> None:
|
||||
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
|
||||
"""已经在福袋详情页:执行点击参与福袋的核心逻辑。"""
|
||||
start_time = time.time()
|
||||
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
|
||||
|
||||
# 这里应该包含主要的福袋处理逻辑
|
||||
# 由于代码太长,这里暂时保留调用原有handler的逻辑
|
||||
# #region agent log
|
||||
import json
|
||||
from path_config import get_debug_log_path
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{int(start_time * 1000)}_call_check",
|
||||
"timestamp": int(start_time * 1000),
|
||||
"location": "fudai_main_logic.py:85",
|
||||
"message": "开始检查 _handle_in_fudai_detail 方法调用",
|
||||
"data": {"method": "_handle_in_fudai_detail", "action": "start"},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "call_check_run1",
|
||||
"hypothesisId": "call_check_hyp1"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_flow
|
||||
# 动态检查FudaiFlow是否存在
|
||||
if hasattr(douyin_fudai_flow, 'FudaiFlow'):
|
||||
flow_class = getattr(douyin_fudai_flow, 'FudaiFlow')
|
||||
if hasattr(flow_class, 'handle_in_fudai_detail'):
|
||||
flow_class.handle_in_fudai_detail(self)
|
||||
else:
|
||||
self._safe_log("警告", "FudaiFlow.handle_in_fudai_detail 方法不可用")
|
||||
# 直接调用福袋参与功能
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
|
||||
# #region agent log
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{int(start_time * 1000)}_import_check",
|
||||
"timestamp": int(start_time * 1000),
|
||||
"location": "fudai_main_logic.py:91",
|
||||
"message": "导入 douyin_fudai_core 模块成功",
|
||||
"data": {"module": "douyin.fudai.douyin_fudai_core", "status": "imported"},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "call_check_run1",
|
||||
"hypothesisId": "call_check_hyp1"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
|
||||
# 检查方法是否存在
|
||||
# #region agent log
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{int(start_time * 1000)}_method_check",
|
||||
"timestamp": int(start_time * 1000),
|
||||
"location": "fudai_main_logic.py:93",
|
||||
"message": "检查 attend_choujiang 方法存在性",
|
||||
"data": {
|
||||
"method_exists": hasattr(douyin_fudai_core, 'attend_choujiang'),
|
||||
"module_attrs": [attr for attr in dir(douyin_fudai_core) if 'attend' in attr.lower()]
|
||||
},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "call_check_run1",
|
||||
"hypothesisId": "call_check_hyp1"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
|
||||
attend_result = douyin_fudai_core.attend_choujiang(self)
|
||||
|
||||
# #region agent log
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{int(start_time * 1000)}_method_call",
|
||||
"timestamp": int(start_time * 1000),
|
||||
"location": "fudai_main_logic.py:93",
|
||||
"message": "调用 attend_choujiang 方法完成",
|
||||
"data": {"method": "attend_choujiang", "result": attend_result},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "call_check_run1",
|
||||
"hypothesisId": "call_check_hyp1"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
|
||||
if attend_result:
|
||||
self._safe_log("参与", "福袋参与成功")
|
||||
else:
|
||||
self._safe_log("警告", "FudaiFlow 类不可用")
|
||||
self._safe_log("参与", "福袋参与失败")
|
||||
|
||||
except Exception as e:
|
||||
self._safe_log("错误", "_handle_in_fudai_detail 调用失败", error=str(e))
|
||||
# #region agent log
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{int(start_time * 1000)}_error",
|
||||
"timestamp": int(start_time * 1000),
|
||||
"location": "fudai_main_logic.py:100",
|
||||
"message": "_handle_in_fudai_detail 执行异常",
|
||||
"data": {"error": str(e), "error_type": type(e).__name__},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "call_check_run1",
|
||||
"hypothesisId": "call_check_hyp1"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
|
||||
self._safe_log("错误", "_handle_in_fudai_detail 执行失败", error=str(e))
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
self._safe_log(
|
||||
"性能",
|
||||
"_handle_in_fudai_detail 耗时",
|
||||
elapsed_seconds=round(elapsed, 2)
|
||||
)
|
||||
# 限制性能日志输出频率,避免过多输出
|
||||
current_time = time.time()
|
||||
last_perf_log_time = getattr(self, "_last_perf_log_time", 0)
|
||||
if current_time - last_perf_log_time >= 5.0: # 至少间隔5秒才输出性能日志
|
||||
self._safe_log(
|
||||
"性能",
|
||||
"_handle_in_fudai_detail 耗时",
|
||||
elapsed_seconds=round(elapsed, 2)
|
||||
)
|
||||
self._last_perf_log_time = current_time
|
||||
|
||||
def _handle_live_room_has_or_not_fudai(self) -> None:
|
||||
"""直播间有无福袋的处理逻辑。"""
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_flow
|
||||
# 动态检查FudaiFlow是否存在
|
||||
if hasattr(douyin_fudai_flow, 'FudaiFlow'):
|
||||
flow_class = getattr(douyin_fudai_flow, 'FudaiFlow')
|
||||
if hasattr(flow_class, 'handle_live_room_has_or_not_fudai'):
|
||||
flow_class.handle_live_room_has_or_not_fudai(self)
|
||||
else:
|
||||
self._safe_log("警告", "FudaiFlow.handle_live_room_has_or_not_fudai 方法不可用")
|
||||
# 使用 flow_control 来查找和打开福袋
|
||||
from douyin.core import douyin_flow_control
|
||||
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
|
||||
|
||||
if opened:
|
||||
# 成功打开福袋详情,调用参与逻辑
|
||||
self._handle_in_fudai_detail()
|
||||
self._safe_log("流程", "_handle_live_room_has_or_not_fudai:成功处理福袋")
|
||||
else:
|
||||
self._safe_log("警告", "FudaiFlow 类不可用")
|
||||
# 无福袋,交给 flow_control 的"无福袋处理"逻辑
|
||||
# 根据配置决定是否允许切换直播间(needswitch=False 时只等待不切房)
|
||||
try:
|
||||
needswitch_cfg = bool(getattr(self, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch_cfg = True
|
||||
|
||||
wait_times_ref = [0]
|
||||
swipe_times_ref = [0]
|
||||
reservation_focus_until_ts_ref = [0.0]
|
||||
reset_to_list_after_reservations_ref = [False]
|
||||
douyin_flow_control.handle_no_fudai_situation(
|
||||
self,
|
||||
x=0,
|
||||
swipe_times=0,
|
||||
wait_times_ref=wait_times_ref,
|
||||
needswitch=needswitch_cfg,
|
||||
reservation_focus_until_ts=0.0,
|
||||
reservations=[],
|
||||
room_pos=room_pos_ref[0],
|
||||
post_switch_delay_s=1.5,
|
||||
swipe_up_switch_callback=self.swipe_up_to_next_live, # type: ignore[attr-defined]
|
||||
swipe_down_back_callback=lambda: None,
|
||||
sort_reservations_callback=lambda: None,
|
||||
clear_reservations_callback=lambda: None,
|
||||
write_state_callback=lambda: None,
|
||||
back_to_list_callback=lambda: None,
|
||||
into_list_callback=lambda: None,
|
||||
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
|
||||
reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref,
|
||||
swipe_times_ref=swipe_times_ref,
|
||||
)
|
||||
self._safe_log("流程", "_handle_live_room_has_or_not_fudai:未找到福袋,已处理切换逻辑")
|
||||
|
||||
except Exception as e:
|
||||
self._safe_log("错误", "_handle_live_room_has_or_not_fudai 调用失败", error=str(e))
|
||||
self._safe_log("错误", "_handle_live_room_has_or_not_fudai 执行失败", error=str(e))
|
||||
@@ -60,3 +60,25 @@ class RoomUtilsMixin:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"updated_ts": 1767009711.8732166,
|
||||
"updated_ts": 1767105402.1814883,
|
||||
"reason": "startup_clear",
|
||||
"room_pos": 0,
|
||||
"current_room_title": "",
|
||||
|
||||
@@ -32,3 +32,25 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -644,84 +644,84 @@ def detect_fansclub_join_red_area(
|
||||
|
||||
|
||||
def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
|
||||
"""通过像素检测右上角x和xin图标区域,判断是否在直播间。
|
||||
"""通过像素检测多边形区域内的白色像素,判断是否在直播间。
|
||||
|
||||
检测右上角区域(60%-100%宽度,0%-40%高度)的像素特征:
|
||||
- x图标:通常是白色或浅色的X形状
|
||||
- xin图标:通常是粉色/红色的心形图标
|
||||
检测指定多边形区域内的白色像素比例,基于1080x2400分辨率:
|
||||
- 多边形顶点坐标(12个点):
|
||||
(1002,172), (999,174), (1011,186), (999,199), (1002,202), (1013,190),
|
||||
(1025,201), (1028,198), (1017,187), (1028,174), (1025,172), (1014,184)
|
||||
- 白色像素比例 >= 0.8 则认为在直播间内
|
||||
|
||||
返回:
|
||||
(detected, confidence) 其中 confidence 为置信度(0.0~1.0)
|
||||
(detected, confidence) 其中 confidence 为白色像素比例(0.0~1.0)
|
||||
"""
|
||||
try:
|
||||
from PIL import ImageDraw
|
||||
import numpy as np
|
||||
|
||||
width, height = pic_rgb.size
|
||||
# 缩放坐标到实际尺寸(基于1080x2400)
|
||||
scale_x = width / 1080.0
|
||||
scale_y = height / 2400.0
|
||||
|
||||
# 检测区域:右上角(60%-100%宽度,0%-40%高度)
|
||||
x1 = int(648 * scale_x) # 60%宽度 = 648
|
||||
y1 = 0
|
||||
x2 = width # 100%宽度
|
||||
y2 = int(960 * scale_y) # 40%高度 = 960
|
||||
# 多边形顶点坐标(基于1080x2400基准分辨率)
|
||||
polygon_base_points = [
|
||||
(1002, 172), (999, 174), (1011, 186), (999, 199), (1002, 202), (1013, 190),
|
||||
(1025, 201), (1028, 198), (1017, 187), (1028, 174), (1025, 172), (1014, 184)
|
||||
]
|
||||
|
||||
# 缩放多边形坐标到实际截图尺寸
|
||||
polygon_points = [
|
||||
(int(x * scale_x), int(y * scale_y))
|
||||
for x, y in polygon_base_points
|
||||
]
|
||||
|
||||
# 确保坐标在范围内
|
||||
x1 = max(0, min(x1, width))
|
||||
y1 = max(0, min(y1, height))
|
||||
x2 = max(0, min(x2, width))
|
||||
y2 = max(0, min(y2, height))
|
||||
# 创建多边形mask
|
||||
mask = Image.new('L', (width, height), 0)
|
||||
draw = ImageDraw.Draw(mask)
|
||||
|
||||
# 绘制多边形(填充为白色)
|
||||
draw.polygon(polygon_points, fill=255)
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
# 将mask转换为numpy数组
|
||||
mask_array = np.array(mask)
|
||||
|
||||
# 获取原始图像的像素数据
|
||||
img_array = np.array(pic_rgb)
|
||||
|
||||
# 计算多边形内部的总像素数
|
||||
total_pixels = np.sum(mask_array > 0)
|
||||
|
||||
if total_pixels == 0:
|
||||
return False, 0.0
|
||||
|
||||
# 采样检测点
|
||||
step_x = max(1, (x2 - x1) // 20)
|
||||
step_y = max(1, (y2 - y1) // 20)
|
||||
|
||||
# 检测特征:
|
||||
# 1. 白色/浅色像素(x图标)
|
||||
# 2. 粉色/红色像素(xin图标)
|
||||
# 计算多边形内部的白色像素(RGB值都>=240)
|
||||
white_count = 0
|
||||
pink_red_count = 0
|
||||
total_samples = 0
|
||||
|
||||
for y in range(y1, y2, step_y):
|
||||
for x in range(x1, x2, step_x):
|
||||
try:
|
||||
r, g, b = pic_rgb.getpixel((x, y))
|
||||
total_samples += 1
|
||||
|
||||
# 检测白色/浅色(x图标):RGB值都较高且接近
|
||||
if (
|
||||
r > 200
|
||||
and g > 200
|
||||
and b > 200
|
||||
and abs(r - g) < 30
|
||||
and abs(g - b) < 30
|
||||
):
|
||||
for y in range(height):
|
||||
for x in range(width):
|
||||
if mask_array[y, x] > 0: # 在多边形内部
|
||||
r, g, b = img_array[y, x]
|
||||
if r >= 240 and g >= 240 and b >= 240: # 白色阈值
|
||||
white_count += 1
|
||||
|
||||
# 检测粉色/红色(xin图标):R值高,G和B相对较低
|
||||
if r > 200 and (r - g) > 50 and (r - b) > 50:
|
||||
pink_red_count += 1
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
continue
|
||||
white_ratio = white_count / total_pixels if total_pixels > 0 else 0.0
|
||||
|
||||
if total_samples == 0:
|
||||
return False, 0.0
|
||||
# 白色像素比例 >= 0.8 则认为在直播间内
|
||||
detected = white_ratio >= 0.8
|
||||
confidence = white_ratio # 置信度就是白色比例
|
||||
|
||||
# 计算置信度
|
||||
white_ratio = white_count / total_samples if total_samples > 0 else 0
|
||||
pink_red_ratio = pink_red_count / total_samples if total_samples > 0 else 0
|
||||
# 计算多边形边界框(用于调试图像)
|
||||
if polygon_points:
|
||||
x_coords = [p[0] for p in polygon_points]
|
||||
y_coords = [p[1] for p in polygon_points]
|
||||
x1 = max(0, min(x_coords))
|
||||
y1 = max(0, min(y_coords))
|
||||
x2 = min(width, max(x_coords))
|
||||
y2 = min(height, max(y_coords))
|
||||
else:
|
||||
x1, y1, x2, y2 = 0, 0, 0, 0
|
||||
|
||||
# 如果白色或粉色/红色像素占比足够高,认为检测到图标
|
||||
# 阈值:白色>=5% 或 粉色/红色>=3%
|
||||
detected = white_ratio >= 0.05 or pink_red_ratio >= 0.03
|
||||
|
||||
# 计算置信度(基于检测到的像素比例)
|
||||
confidence = min(1.0, max(white_ratio * 10, pink_red_ratio * 15))
|
||||
|
||||
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
|
||||
# 保存调试图像(检测结果)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
@@ -730,15 +730,15 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
|
||||
operation_type="pixel_detect",
|
||||
picname="live_room_icons",
|
||||
step="detected" if detected else "not_detected",
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域边界框
|
||||
extra_info={
|
||||
"white_ratio": round(white_ratio, 4),
|
||||
"pink_red_ratio": round(pink_red_ratio, 4),
|
||||
"white_count": white_count,
|
||||
"pink_red_count": pink_red_count,
|
||||
"total_samples": total_samples,
|
||||
"total_pixels": total_pixels,
|
||||
"confidence": round(confidence, 4),
|
||||
"threshold": 0.8,
|
||||
"result": "success" if detected else "failed",
|
||||
"polygon_points": len(polygon_points),
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
@@ -746,10 +746,11 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
"[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, pink_red_ratio=%.4f, confidence=%.4f, result=%s",
|
||||
"[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s",
|
||||
debug_path,
|
||||
white_ratio,
|
||||
pink_red_ratio,
|
||||
white_count,
|
||||
total_pixels,
|
||||
confidence,
|
||||
"success" if detected else "failed",
|
||||
)
|
||||
@@ -758,7 +759,7 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
return detected, confidence
|
||||
return bool(detected), float(confidence)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return False, 0.0
|
||||
|
||||
@@ -868,6 +869,7 @@ def read_pixel_stage_state_from_screenshot(
|
||||
"has_attend_button_red": False,
|
||||
"has_fansclub_join_red": False,
|
||||
"has_fudai_detail": False,
|
||||
"has_live_room_pixel": False, # 直播间图标像素检测(多边形区域白色像素检测)
|
||||
}
|
||||
details: dict[str, dict] = {}
|
||||
|
||||
@@ -884,6 +886,7 @@ def read_pixel_stage_state_from_screenshot(
|
||||
coupon_threshold = None
|
||||
attend_button_threshold = None
|
||||
fansclub_threshold = None
|
||||
live_room_pixel_threshold = None
|
||||
if analyser is not None:
|
||||
try:
|
||||
coupon_threshold = float(
|
||||
@@ -903,7 +906,30 @@ def read_pixel_stage_state_from_screenshot(
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
live_room_pixel_threshold = float(
|
||||
getattr(analyser, "live_room_match_threshold", None) or 0.8
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
# 定义直播间图标像素检测包装函数
|
||||
def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]:
|
||||
"""直播间图标像素检测包装函数,返回 (bool, dict) 格式"""
|
||||
try:
|
||||
detected, confidence = detect_live_room_icons_by_pixel(pic)
|
||||
threshold = live_room_pixel_threshold or 0.8
|
||||
is_detected = detected and confidence >= threshold
|
||||
return is_detected, {
|
||||
"method": "pixel_detection",
|
||||
"confidence": confidence,
|
||||
"effective_threshold": threshold,
|
||||
}
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return False, {"method": "pixel_detection", "error": str(e)}
|
||||
|
||||
# 模板匹配已删除,只使用像素检测
|
||||
|
||||
detection_tasks = {
|
||||
"has_coupon_bg": lambda pic: detect_coupon_popup_background(
|
||||
pic,
|
||||
@@ -936,10 +962,11 @@ def read_pixel_stage_state_from_screenshot(
|
||||
return_info=True,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测(多边形区域白色像素检测)
|
||||
}
|
||||
|
||||
# 使用线程池并行执行检测
|
||||
with ThreadPoolExecutor(max_workers=6) as executor:
|
||||
# 使用线程池并行执行检测(增加线程数以支持直播间图标检测)
|
||||
with ThreadPoolExecutor(max_workers=8) as executor:
|
||||
# 提交所有任务
|
||||
future_to_key = {
|
||||
executor.submit(detect_func, pic_rgb): key
|
||||
@@ -962,6 +989,7 @@ def read_pixel_stage_state_from_screenshot(
|
||||
"detected": bool(is_detected),
|
||||
"method": info.get("method", "unknown"),
|
||||
"template_score": info.get("template_score"),
|
||||
"confidence": info.get("confidence"), # 添加confidence支持(用于像素检测)
|
||||
"task_count": info.get("task_count"), # 添加task_count支持
|
||||
"red_ratio": info.get("red_ratio"), # 添加red_ratio支持
|
||||
"effective_threshold": info.get("effective_threshold"),
|
||||
@@ -987,3 +1015,91 @@ def read_pixel_stage_state_from_screenshot(
|
||||
if return_details:
|
||||
return state, details
|
||||
return state
|
||||
|
||||
# 模板匹配已删除,只使用像素检测
|
||||
|
||||
detection_tasks = {
|
||||
"has_coupon_bg": lambda pic: detect_coupon_popup_background(
|
||||
pic,
|
||||
return_info=True,
|
||||
template_threshold=coupon_threshold,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_redpacket_bg": detect_redpacket_popup_background,
|
||||
"has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(
|
||||
pic, lucky_draw_red_ratio_threshold, return_info=True
|
||||
),
|
||||
"has_attend_button_red": lambda pic: detect_attend_button_red_area(
|
||||
pic,
|
||||
return_info=True,
|
||||
red_ratio_threshold=attend_button_threshold,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area(
|
||||
pic,
|
||||
return_info=True,
|
||||
red_ratio_threshold=fansclub_threshold,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_fudai_detail": lambda pic: detect_fudai_detail_page(
|
||||
pic,
|
||||
resolution_ratio_x,
|
||||
resolution_ratio_y,
|
||||
y_pianyi,
|
||||
fudai_template_threshold,
|
||||
return_info=True,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测(多边形区域白色像素检测)
|
||||
}
|
||||
|
||||
# 使用线程池并行执行检测(增加线程数以支持直播间图标检测)
|
||||
with ThreadPoolExecutor(max_workers=8) as executor:
|
||||
# 提交所有任务
|
||||
future_to_key = {
|
||||
executor.submit(detect_func, pic_rgb): key
|
||||
for key, detect_func in detection_tasks.items()
|
||||
}
|
||||
|
||||
# 收集结果
|
||||
for future in as_completed(future_to_key):
|
||||
key = future_to_key[future]
|
||||
try:
|
||||
result = future.result()
|
||||
|
||||
# 处理结果
|
||||
if isinstance(result, tuple):
|
||||
# 检测函数返回 (bool, dict) 格式
|
||||
is_detected, info = result
|
||||
state[key] = bool(is_detected)
|
||||
if return_details:
|
||||
details[key] = {
|
||||
"detected": bool(is_detected),
|
||||
"method": info.get("method", "unknown"),
|
||||
"template_score": info.get("template_score"),
|
||||
"confidence": info.get("confidence"), # 添加confidence支持(用于像素检测)
|
||||
"task_count": info.get("task_count"), # 添加task_count支持
|
||||
"red_ratio": info.get("red_ratio"), # 添加red_ratio支持
|
||||
"effective_threshold": info.get("effective_threshold"),
|
||||
"reason": info.get("reason"),
|
||||
}
|
||||
else:
|
||||
# 其他检测返回 bool(不应该发生,因为所有检测都支持return_info)
|
||||
state[key] = bool(result)
|
||||
if return_details:
|
||||
details[key] = {
|
||||
"detected": bool(result),
|
||||
"method": "unknown",
|
||||
}
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
# 如果某个检测失败,保持默认值 False
|
||||
state[key] = False
|
||||
if return_details:
|
||||
details[key] = {
|
||||
"detected": False,
|
||||
"error": str(e),
|
||||
}
|
||||
|
||||
if return_details:
|
||||
return state, details
|
||||
return state
|
||||
File diff suppressed because it is too large.
Load diff
@@ -73,3 +73,25 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
"""福袋核心模块
|
||||
|
||||
本目录包含从 douyin_fudai_core.py 模块化后的功能模块。
|
||||
|
||||
向后兼容:所有函数都从原文件重新导出,确保现有代码继续工作。
|
||||
"""
|
||||
|
||||
# 优先从子模块导入(如果已迁移)
|
||||
try:
|
||||
from .fudai_debug_utils import _save_full_screenshot_with_ocr_region
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import _save_full_screenshot_with_ocr_region
|
||||
|
||||
# 优先从子模块导入 get_fudai_contain
|
||||
try:
|
||||
from .fudai_detail_reader import get_fudai_contain
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import get_fudai_contain
|
||||
|
||||
# 优先从子模块导入 attend_choujiang
|
||||
try:
|
||||
from .fudai_attend import attend_choujiang
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import attend_choujiang
|
||||
|
||||
# 优先从子模块导入结果检查函数
|
||||
try:
|
||||
from .fudai_result_checker import (
|
||||
check_lucky_draw_result,
|
||||
check_have_reward_notice_confirm,
|
||||
check_in_order_confirm_page,
|
||||
get_reward,
|
||||
)
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import (
|
||||
check_lucky_draw_result,
|
||||
check_have_reward_notice_confirm,
|
||||
check_in_order_confirm_page,
|
||||
get_reward,
|
||||
)
|
||||
|
||||
# 优先从子模块导入过滤函数
|
||||
try:
|
||||
from .fudai_filter import (
|
||||
check_contain,
|
||||
is_watch_task_fudai,
|
||||
should_skip_fudai_by_config,
|
||||
basic_join_decision,
|
||||
)
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import (
|
||||
check_contain,
|
||||
is_watch_task_fudai,
|
||||
should_skip_fudai_by_config,
|
||||
basic_join_decision,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_save_full_screenshot_with_ocr_region",
|
||||
"get_fudai_contain",
|
||||
"attend_choujiang",
|
||||
"check_lucky_draw_result",
|
||||
"check_have_reward_notice_confirm",
|
||||
"check_in_order_confirm_page",
|
||||
"get_reward",
|
||||
"check_contain",
|
||||
"is_watch_task_fudai",
|
||||
"should_skip_fudai_by_config",
|
||||
"basic_join_decision",
|
||||
]
|
||||
|
||||
@@ -17,28 +17,58 @@ def attend_choujiang(analyser) -> bool:
|
||||
analyser.last_attend_fail_reason = ""
|
||||
click_times = 0
|
||||
while click_times < 2:
|
||||
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字
|
||||
# 优化:尝试多种OCR模式提高精准度(优先保证精准)
|
||||
attend_button_text = str(
|
||||
analyser.operation.analyse_pic_word("参与按钮", 0) or ""
|
||||
)
|
||||
if not attend_button_text or not any(
|
||||
k in attend_button_text
|
||||
for k in (
|
||||
"参与成功",
|
||||
"还需看播",
|
||||
"评论",
|
||||
"参与抽奖",
|
||||
"开始观看",
|
||||
"参与",
|
||||
"加入粉丝团",
|
||||
"粉丝团",
|
||||
)
|
||||
):
|
||||
attend_button_text = str(
|
||||
analyser.operation.analyse_pic_word("参与按钮", 1) or ""
|
||||
)
|
||||
analyser._log_kv("参与", "识别参与按钮", text=attend_button_text)
|
||||
# 优化:优先使用并行OCR中已识别的按钮状态(避免重复识别)
|
||||
attend_button_text = None
|
||||
button_status = getattr(analyser, "_fudai_button_status", None)
|
||||
button_text = getattr(analyser, "_fudai_button_text", "")
|
||||
|
||||
# 如果并行OCR已经识别了按钮,且识别时间较近(5秒内),直接使用
|
||||
if button_text and button_status:
|
||||
try:
|
||||
button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0)
|
||||
current_time = time.time()
|
||||
# 如果并行OCR结果在5秒内,且状态有效,直接使用
|
||||
if current_time - button_ocr_time < 5.0:
|
||||
attend_button_text = button_text
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"使用并行OCR识别的按钮状态",
|
||||
button_text=attend_button_text[:100] if attend_button_text else "",
|
||||
button_status=button_status,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果并行OCR结果不可用,则重新识别
|
||||
if not attend_button_text:
|
||||
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字
|
||||
|
||||
# 统一使用预处理工具生成可供 OCR 使用的图片名(若失败则回退到原名)
|
||||
try:
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr
|
||||
|
||||
use_name = preprocess_for_ocr(analyser, "参与按钮")
|
||||
except Exception:
|
||||
use_name = "参与按钮"
|
||||
|
||||
# 优化:尝试多种OCR模式提高精准度(优先保证精准)
|
||||
attend_button_text = str(analyser.operation.analyse_pic_word(use_name, 0) or "")
|
||||
if not attend_button_text or not any(
|
||||
k in attend_button_text
|
||||
for k in (
|
||||
"参与成功",
|
||||
"还需看播",
|
||||
"评论",
|
||||
"参与抽奖",
|
||||
"开始观看",
|
||||
"参与",
|
||||
"加入粉丝团",
|
||||
"粉丝团",
|
||||
)
|
||||
):
|
||||
# 切换到模式1识别,优先使用预处理图(若存在)
|
||||
attend_button_text = str(analyser.operation.analyse_pic_word(use_name, 1) or "")
|
||||
analyser._log_kv("参与", "识别参与按钮", text=attend_button_text)
|
||||
if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖
|
||||
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
|
||||
# 记录最后一次成功参与的时间
|
||||
@@ -52,6 +82,24 @@ def attend_choujiang(analyser) -> bool:
|
||||
try:
|
||||
# 从 detail 中获取 future_ts(如果可用)
|
||||
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
|
||||
# 如果没有从 detail 中获取到 future_ts,尝试直接解析当前详情页的倒计时文本
|
||||
if not future_ts:
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
|
||||
content, time_text, participants, copies, prize_value_yuan = douyin_fudai_core.get_fudai_contain(
|
||||
analyser, renwu=1
|
||||
)
|
||||
# 尝试用 operation.check_countdown 解析 time_text
|
||||
try:
|
||||
res = analyser.operation.check_countdown(time_text)
|
||||
if isinstance(res, tuple) and len(res) == 2:
|
||||
_, parsed_future = res
|
||||
future_ts = float(parsed_future or 0.0)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
if future_ts > 0:
|
||||
participated_fudai_ts = getattr(
|
||||
analyser, "_participated_fudai_future_ts", set()
|
||||
@@ -183,6 +231,23 @@ def attend_choujiang(analyser) -> bool:
|
||||
pass
|
||||
|
||||
# 设置等待开奖标志,避免参与后立即切换直播间
|
||||
# #region agent log - set countdown
|
||||
import json
|
||||
from path_config import get_debug_log_path
|
||||
current_ts_debug = int(time.time() * 1000)
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{current_ts_debug}_set_countdown_start",
|
||||
"timestamp": current_ts_debug,
|
||||
"location": "fudai_attend.py:186",
|
||||
"message": "开始设置等待开奖标志",
|
||||
"data": {"future_ts": getattr(analyser, "_current_fudai_future_ts", 0.0)},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "countdown_debug_run1",
|
||||
"hypothesisId": "countdown_hyp2"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
|
||||
try:
|
||||
# 从 detail 中获取 future_ts(如果可用)
|
||||
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
|
||||
@@ -194,6 +259,26 @@ def attend_choujiang(analyser) -> bool:
|
||||
# 提前13秒,修正倒计时误差
|
||||
analyser._waiting_for_lottery_result = True
|
||||
analyser._lottery_result_expected_ts = future_ts - 13.0
|
||||
|
||||
# #region agent log - countdown set
|
||||
with open(get_debug_log_path(), 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps({
|
||||
"id": f"log_{current_ts_debug}_countdown_set",
|
||||
"timestamp": current_ts_debug,
|
||||
"location": "fudai_attend.py:195",
|
||||
"message": "成功设置等待开奖标志",
|
||||
"data": {
|
||||
"waiting_for_lottery_result": analyser._waiting_for_lottery_result,
|
||||
"lottery_result_expected_ts": analyser._lottery_result_expected_ts,
|
||||
"future_ts": future_ts,
|
||||
"current_time": current_time,
|
||||
"remain_seconds": remain_seconds
|
||||
},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "countdown_debug_run1",
|
||||
"hypothesisId": "countdown_hyp2"
|
||||
}) + '\n')
|
||||
# #endregion
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖后,设置等待开奖标志",
|
||||
|
||||
@@ -107,23 +107,41 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
analyser.y_pianyi,
|
||||
)
|
||||
|
||||
# 并行执行两个OCR识别(使用轻量数字OCR)
|
||||
# 并行执行两个OCR识别(使用轻量数字OCR),优先对裁剪图做预处理以提升识别率
|
||||
try:
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr
|
||||
|
||||
mm_name = preprocess_for_ocr(analyser, "福袋倒计时_分钟")
|
||||
ss_name = preprocess_for_ocr(analyser, "福袋倒计时_秒")
|
||||
except Exception:
|
||||
mm_name = "福袋倒计时_分钟"
|
||||
ss_name = "福袋倒计时_秒"
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mm = executor.submit(
|
||||
analyser.operation.analyse_pic_digits, "福袋倒计时_分钟", 1
|
||||
analyser.operation.analyse_pic_digits, mm_name, 1
|
||||
)
|
||||
future_ss = executor.submit(
|
||||
analyser.operation.analyse_pic_digits, "福袋倒计时_秒", 1
|
||||
analyser.operation.analyse_pic_digits, ss_name, 1
|
||||
)
|
||||
mm_raw = future_mm.result()
|
||||
ss_raw = future_ss.result()
|
||||
|
||||
# 提取数字:分钟和秒都应该是1-2位数字
|
||||
def _extract_digits(text: str, max_digits: int = 2) -> str:
|
||||
"""提取数字,最多max_digits位"""
|
||||
"""提取数字,最多max_digits位,智能处理前导零"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
if len(digits) > max_digits:
|
||||
return digits[:max_digits]
|
||||
# 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况)
|
||||
# 例如"002" -> "02" 而不是 "00"
|
||||
candidate = digits[-max_digits:]
|
||||
# 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数
|
||||
if candidate.startswith('0') and not digits.startswith('0' * len(digits)):
|
||||
# 移除前导零后的长度
|
||||
actual_digits = digits.lstrip('0') or '0'
|
||||
if len(actual_digits) <= max_digits:
|
||||
return actual_digits.zfill(max_digits)
|
||||
return candidate
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
return digits
|
||||
@@ -264,7 +282,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi
|
||||
) # 福袋内容详情(包含任务描述)
|
||||
# 优化:稍微扩大高度,确保完整
|
||||
countdown_box = (390, 1180, 690, 1300)
|
||||
# 优化:向上扩大区域,确保完整识别倒计时数字
|
||||
countdown_box = (390, 1140, 690, 1290)
|
||||
# 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域
|
||||
x1, y1, x2, y2 = countdown_box
|
||||
w = max(1, int(x2 - x1))
|
||||
@@ -398,7 +417,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
def ocr_task_list():
|
||||
"""OCR识别任务列表(用于检测观看任务)"""
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋任务列表", 0)
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr
|
||||
name_tl = preprocess_for_ocr(analyser, "福袋任务列表")
|
||||
return analyser.operation.analyse_pic_word(name_tl, 0)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -415,7 +436,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
def ocr_content():
|
||||
"""OCR识别福袋内容"""
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋内容", 0)
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr
|
||||
name_fc = preprocess_for_ocr(analyser, "福袋内容")
|
||||
return analyser.operation.analyse_pic_word(name_fc, 0)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -466,7 +489,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
def ocr_value():
|
||||
"""OCR识别福袋价值(使用普通OCR)"""
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋价值", 0)
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr
|
||||
name_val = preprocess_for_ocr(analyser, "福袋价值")
|
||||
return analyser.operation.analyse_pic_word(name_val, 0)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -912,10 +937,19 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
try:
|
||||
# 提取数字:分钟和秒都应该是1-2位数字
|
||||
def _extract_digits(text: str, max_digits: int = 2) -> str:
|
||||
"""提取数字,最多max_digits位"""
|
||||
"""提取数字,最多max_digits位,智能处理前导零"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
if len(digits) > max_digits:
|
||||
return digits[:max_digits]
|
||||
# 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况)
|
||||
# 例如"002" -> "02" 而不是 "00"
|
||||
candidate = digits[-max_digits:]
|
||||
# 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数
|
||||
if candidate.startswith('0') and not digits.startswith('0' * len(digits)):
|
||||
# 移除前导零后的长度
|
||||
actual_digits = digits.lstrip('0') or '0'
|
||||
if len(actual_digits) <= max_digits:
|
||||
return actual_digits.zfill(max_digits)
|
||||
return candidate
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
return digits
|
||||
|
||||
@@ -520,47 +520,44 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查是否是预约回退后强制参与(跳过验证)
|
||||
# 注意:必须在检查 _last_fudai_detail_status 之前检查,否则强制参与标志会被忽略
|
||||
force_attend = getattr(analyser, "_force_attend_after_reservation_back", False)
|
||||
|
||||
# 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理
|
||||
# 但如果设置了强制参与标志,则跳过状态检查(预约回退时使用预约记录,可能不满足验证条件)
|
||||
try:
|
||||
last_status = getattr(analyser, "_last_fudai_detail_status", "")
|
||||
if not force_attend: # 只有在非强制参与模式下才检查状态
|
||||
if last_status == "coupon_popup":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
if last_status == "coupon_popup":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(优惠券弹窗)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
"basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理",
|
||||
)
|
||||
return False
|
||||
elif last_status == "validation_failed":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(优惠券弹窗)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
elif last_status == "validation_failed":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(验证失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理",
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(验证失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查是否是预约回退后强制参与(跳过验证)
|
||||
force_attend = getattr(analyser, "_force_attend_after_reservation_back", False)
|
||||
if force_attend:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
|
||||
@@ -7,7 +7,7 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
def check_lucky_draw_result(analyser) -> int | bool:
|
||||
"""判定福袋抽奖的结果。"""
|
||||
@@ -42,26 +42,30 @@ def check_lucky_draw_result(analyser) -> int | bool:
|
||||
if (now - cached_ts) < analyser._ocr_cache_ttl:
|
||||
lucky_draw_result = cached_result
|
||||
else:
|
||||
name_lr0 = preprocess_for_ocr(analyser, "抽奖结果")
|
||||
lucky_draw_result = str(
|
||||
analyser.operation.analyse_pic_word("抽奖结果", 0) or ""
|
||||
analyser.operation.analyse_pic_word(name_lr0, 0) or ""
|
||||
)
|
||||
if not lucky_draw_result or (
|
||||
"没有抽中" not in lucky_draw_result
|
||||
and "抽中福袋" not in lucky_draw_result
|
||||
):
|
||||
name_lr1 = preprocess_for_ocr(analyser, "抽奖结果")
|
||||
lucky_draw_result = str(
|
||||
analyser.operation.analyse_pic_word("抽奖结果", 1) or ""
|
||||
analyser.operation.analyse_pic_word(name_lr1, 1) or ""
|
||||
)
|
||||
analyser._ocr_cache[cache_key] = (now, lucky_draw_result)
|
||||
else:
|
||||
name_lr0b = preprocess_for_ocr(analyser, "抽奖结果")
|
||||
lucky_draw_result = str(
|
||||
analyser.operation.analyse_pic_word("抽奖结果", 0) or ""
|
||||
analyser.operation.analyse_pic_word(name_lr0b, 0) or ""
|
||||
)
|
||||
if not lucky_draw_result or (
|
||||
"没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result
|
||||
):
|
||||
name_lr1b = preprocess_for_ocr(analyser, "抽奖结果")
|
||||
lucky_draw_result = str(
|
||||
analyser.operation.analyse_pic_word("抽奖结果", 1) or ""
|
||||
analyser.operation.analyse_pic_word(name_lr1b, 1) or ""
|
||||
)
|
||||
analyser._ocr_cache[cache_key] = (now, lucky_draw_result)
|
||||
|
||||
@@ -84,17 +88,30 @@ def check_lucky_draw_result(analyser) -> int | bool:
|
||||
# 速度优化:使用缓存避免重复OCR
|
||||
cache_key2 = ("no_award_confirm", 0)
|
||||
dur2 = 0.0 # Initialize dur2 to avoid unbound variable
|
||||
if cache_key2 in analyser._ocr_cache:
|
||||
cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2]
|
||||
if (now - cached_ts2) < analyser._ocr_cache_ttl:
|
||||
no_award_confirm = cached_result2
|
||||
# 使用统一的"我知道了"识别方法(与倒计时/开奖结果处理一致)
|
||||
try:
|
||||
from douyin.utils.douyin_helpers import HelperFunctions
|
||||
|
||||
# 优先使用 HelperFunctions 中封装的按钮OCR方法(ROI 和多模式识别更鲁棒)
|
||||
t1 = time.time()
|
||||
detected = HelperFunctions.check_lottery_result_by_ocr(analyser)
|
||||
dur2 = time.time() - t1
|
||||
# 将检测结果映射为之前的 no_award_confirm 表示(保留原接口)
|
||||
if detected == "我知道了":
|
||||
no_award_confirm = "我知道了"
|
||||
elif detected == "立即领取奖品":
|
||||
no_award_confirm = "立即领取奖品"
|
||||
else:
|
||||
t1 = time.time()
|
||||
# 回退到原始更大区域OCR(兼容)
|
||||
t1b = time.time()
|
||||
analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
|
||||
no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认")
|
||||
analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
|
||||
dur2 = time.time() - t1
|
||||
else:
|
||||
name_na = preprocess_for_ocr(analyser, "无奖励确认")
|
||||
no_award_confirm = analyser.operation.analyse_pic_word(name_na)
|
||||
dur2 = time.time() - t1b
|
||||
|
||||
analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
|
||||
except Exception:
|
||||
# 回退到原实现:直接OCR
|
||||
t1 = time.time()
|
||||
analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
|
||||
no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认")
|
||||
@@ -138,8 +155,9 @@ def check_lucky_draw_result(analyser) -> int | bool:
|
||||
if not have_read_user_agreement:
|
||||
t2 = time.time()
|
||||
analyser.cut_pic(280, y - 35, 670, y + 35, "", f"已阅读用户协议_{y}")
|
||||
name_agree = preprocess_for_ocr(analyser, f"已阅读用户协议_{y}")
|
||||
have_read_user_agreement = analyser.operation.analyse_pic_word(
|
||||
f"已阅读用户协议_{y}"
|
||||
name_agree
|
||||
)
|
||||
analyser._ocr_cache[cache_key3] = (
|
||||
time.time(),
|
||||
@@ -170,7 +188,8 @@ def check_have_reward_notice_confirm(analyser) -> bool:
|
||||
"""判断是否有领奖的二次确认提醒。"""
|
||||
analyser._shot_and_diagnose("领奖确认", "识别是否有我知道了", analyser.device_id)
|
||||
analyser.cut_pic(370, 1350, 680, 1440, "", "奖励通知确认")
|
||||
reward_notice_confirm = analyser.operation.analyse_pic_word("奖励通知确认", 1)
|
||||
name_reward = preprocess_for_ocr(analyser, "奖励通知确认")
|
||||
reward_notice_confirm = analyser.operation.analyse_pic_word(name_reward, 1)
|
||||
if "我知道了" in (reward_notice_confirm or ""):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -188,7 +207,8 @@ def check_in_order_confirm_page(analyser) -> bool:
|
||||
"""判断是否在中奖下单后的购买成功的页面。"""
|
||||
analyser._shot_and_diagnose("下单结果", "识别是否购买成功页", analyser.device_id)
|
||||
analyser.cut_pic(370, 120, 700, 220, "", "订单确认")
|
||||
order_confirm = analyser.operation.analyse_pic_word("订单确认")
|
||||
name_order = preprocess_for_ocr(analyser, "订单确认")
|
||||
order_confirm = analyser.operation.analyse_pic_word(name_order)
|
||||
if "购买成功" in (order_confirm or ""):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
|
||||
@@ -17,6 +17,7 @@ import path_config
|
||||
from douyin.fudai.core.fudai_debug_utils import (
|
||||
_save_full_screenshot_with_ocr_region,
|
||||
)
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
|
||||
def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]:
|
||||
@@ -114,23 +115,39 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
analyser.y_pianyi,
|
||||
)
|
||||
|
||||
# 并行执行两个OCR识别(使用轻量数字OCR)
|
||||
# 并行执行两个OCR识别(使用轻量数字OCR),优先预处理以提高识别率
|
||||
try:
|
||||
mm_name = preprocess_for_ocr(analyser, "福袋倒计时_分钟")
|
||||
ss_name = preprocess_for_ocr(analyser, "福袋倒计时_秒")
|
||||
except Exception:
|
||||
mm_name = "福袋倒计时_分钟"
|
||||
ss_name = "福袋倒计时_秒"
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mm = executor.submit(
|
||||
analyser.operation.analyse_pic_digits, "福袋倒计时_分钟", 1
|
||||
analyser.operation.analyse_pic_digits, mm_name, 1
|
||||
)
|
||||
future_ss = executor.submit(
|
||||
analyser.operation.analyse_pic_digits, "福袋倒计时_秒", 1
|
||||
analyser.operation.analyse_pic_digits, ss_name, 1
|
||||
)
|
||||
mm_raw = future_mm.result()
|
||||
ss_raw = future_ss.result()
|
||||
|
||||
# 提取数字:分钟和秒都应该是1-2位数字
|
||||
def _extract_digits(text: str, max_digits: int = 2) -> str:
|
||||
"""提取数字,最多max_digits位"""
|
||||
"""提取数字,最多max_digits位,智能处理前导零"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
if len(digits) > max_digits:
|
||||
return digits[:max_digits]
|
||||
# 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况)
|
||||
# 例如"002" -> "02" 而不是 "00"
|
||||
candidate = digits[-max_digits:]
|
||||
# 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数
|
||||
if candidate.startswith('0') and not digits.startswith('0' * len(digits)):
|
||||
# 移除前导零后的长度
|
||||
actual_digits = digits.lstrip('0') or '0'
|
||||
if len(actual_digits) <= max_digits:
|
||||
return actual_digits.zfill(max_digits)
|
||||
return candidate
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
return digits
|
||||
@@ -275,8 +292,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
analyser.cut_pic(
|
||||
389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi
|
||||
) # 福袋内容详情(包含任务描述)
|
||||
# 优化:稍微扩大高度,确保完整
|
||||
countdown_box = (390, 1180, 690, 1300)
|
||||
# 优化:向上扩大区域,确保完整识别倒计时数字
|
||||
countdown_box = (390, 1140, 690, 1290)
|
||||
# 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域
|
||||
x1, y1, x2, y2 = countdown_box
|
||||
w = max(1, int(x2 - x1))
|
||||
@@ -410,7 +427,26 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 并行执行五个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值
|
||||
# 准备参与按钮区域的截图(用于并行OCR识别按钮状态)
|
||||
try:
|
||||
# 保存参与按钮区域的调试截图(仅在配置启用时)
|
||||
if save_debug_images:
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser, "参与按钮", (306, 2030, 780, 2110), analyser.y_pianyi
|
||||
)
|
||||
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮", analyser.y_pianyi)
|
||||
except Exception as e:
|
||||
# 按钮截图失败不影响后续流程,记录日志即可
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋",
|
||||
"参与按钮截图失败,继续后续流程",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 并行执行六个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值/参与按钮
|
||||
# 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数
|
||||
ocr_start_time = time.time()
|
||||
task_list_raw = None
|
||||
@@ -418,11 +454,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
countdown_mm_raw = None
|
||||
countdown_ss_raw = None
|
||||
value_raw = None
|
||||
button_text_raw = None
|
||||
|
||||
def ocr_task_list():
|
||||
"""OCR识别任务列表(用于检测观看任务)"""
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋任务列表", 0)
|
||||
name_tl = preprocess_for_ocr(analyser, "福袋任务列表")
|
||||
return analyser.operation.analyse_pic_word(name_tl, 0)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -439,7 +477,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
def ocr_content():
|
||||
"""OCR识别福袋内容"""
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋内容", 0)
|
||||
name_fc = preprocess_for_ocr(analyser, "福袋内容")
|
||||
return analyser.operation.analyse_pic_word(name_fc, 0)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -490,7 +529,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
def ocr_value():
|
||||
"""OCR识别福袋价值(使用普通OCR)"""
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋价值", 0)
|
||||
name_val = preprocess_for_ocr(analyser, "福袋价值")
|
||||
return analyser.operation.analyse_pic_word(name_val, 0)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -504,15 +544,53 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
pass
|
||||
return None
|
||||
|
||||
def ocr_button():
|
||||
"""OCR识别参与按钮(用于检测参与状态)"""
|
||||
try:
|
||||
name_btn = preprocess_for_ocr(analyser, "参与按钮")
|
||||
# 尝试模式0和模式1,优先使用模式0
|
||||
button_text = str(analyser.operation.analyse_pic_word(name_btn, 0) or "")
|
||||
# 如果模式0没有识别到关键信息,尝试模式1
|
||||
if not button_text or not any(
|
||||
k in button_text
|
||||
for k in (
|
||||
"参与成功",
|
||||
"还需看播",
|
||||
"评论",
|
||||
"参与抽奖",
|
||||
"开始观看",
|
||||
"参与",
|
||||
"加入粉丝团",
|
||||
"粉丝团",
|
||||
"等待开奖",
|
||||
"未达成",
|
||||
)
|
||||
):
|
||||
button_text = str(analyser.operation.analyse_pic_word(name_btn, 1) or "")
|
||||
return button_text
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"OCR识别参与按钮失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
# 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行)
|
||||
# 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=5) as executor:
|
||||
with ThreadPoolExecutor(max_workers=6) as executor:
|
||||
future_task_list = executor.submit(ocr_task_list)
|
||||
future_content = executor.submit(ocr_content)
|
||||
future_countdown_mm = executor.submit(ocr_countdown_mm)
|
||||
future_countdown_ss = executor.submit(ocr_countdown_ss)
|
||||
future_value = executor.submit(ocr_value)
|
||||
future_button = executor.submit(ocr_button)
|
||||
|
||||
# 等待所有操作完成
|
||||
task_list_raw = future_task_list.result()
|
||||
@@ -520,6 +598,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
countdown_mm_raw = future_countdown_mm.result()
|
||||
countdown_ss_raw = future_countdown_ss.result()
|
||||
value_raw = future_value.result()
|
||||
button_text_raw = future_button.result()
|
||||
|
||||
# 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查)
|
||||
if task_list_raw:
|
||||
@@ -577,6 +656,58 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
# 直接返回空内容,后续流程会跳过
|
||||
return "", "", 0, 0, 0.0
|
||||
|
||||
# 处理按钮识别结果,判断参与状态并做决策
|
||||
button_status = None
|
||||
if button_text_raw:
|
||||
button_text = str(button_text_raw).strip()
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"并行OCR识别参与按钮",
|
||||
button_text=button_text[:100] if button_text else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 判断按钮状态
|
||||
if "参与成功" in button_text or "等待开奖" in button_text:
|
||||
button_status = "已参与"
|
||||
elif "加入粉丝团" in button_text or "粉丝团" in button_text:
|
||||
button_status = "需要加入粉丝团"
|
||||
elif "评论" in button_text or "发表评论" in button_text or "一键发表评论" in button_text:
|
||||
button_status = "需要评论"
|
||||
elif "还需看播" in button_text or "开始观看" in button_text:
|
||||
button_status = "需要观看"
|
||||
elif "未达成" in button_text:
|
||||
button_status = "未达成要求"
|
||||
elif "参与抽奖" in button_text or "参与" in button_text:
|
||||
button_status = "可以参与"
|
||||
else:
|
||||
button_status = "未知状态"
|
||||
|
||||
# 将按钮状态存储到 analyser 对象中,供后续决策使用
|
||||
try:
|
||||
analyser._fudai_button_status = button_status
|
||||
analyser._fudai_button_text = button_text
|
||||
analyser._fudai_button_ocr_time = time.time() # 记录识别时间
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"按钮状态判断",
|
||||
status=button_status,
|
||||
button_text=button_text[:100] if button_text else "",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"保存按钮状态失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ocr_elapsed = time.time() - ocr_start_time
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -584,6 +715,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
"并行OCR识别完成(任务数量已在前置检测中获取)",
|
||||
elapsed_seconds=round(ocr_elapsed, 3),
|
||||
task_count=renwu,
|
||||
button_status=button_status or "未识别",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
@@ -613,7 +745,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
|
||||
def ocr_task_list_fallback():
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋任务列表", 0)
|
||||
name_tl2 = preprocess_for_ocr(analyser, "福袋任务列表")
|
||||
return analyser.operation.analyse_pic_word(name_tl2, 0)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -691,12 +824,47 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
pass
|
||||
return None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=5) as executor:
|
||||
def ocr_button_fallback():
|
||||
try:
|
||||
name_btn = preprocess_for_ocr(analyser, "参与按钮")
|
||||
button_text = str(analyser.operation.analyse_pic_word(name_btn, 0) or "")
|
||||
if not button_text or not any(
|
||||
k in button_text
|
||||
for k in (
|
||||
"参与成功",
|
||||
"还需看播",
|
||||
"评论",
|
||||
"参与抽奖",
|
||||
"开始观看",
|
||||
"参与",
|
||||
"加入粉丝团",
|
||||
"粉丝团",
|
||||
"等待开奖",
|
||||
"未达成",
|
||||
)
|
||||
):
|
||||
button_text = str(analyser.operation.analyse_pic_word(name_btn, 1) or "")
|
||||
return button_text
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"备用OCR识别参与按钮失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=6) as executor:
|
||||
future_task_list = executor.submit(ocr_task_list_fallback)
|
||||
future_content = executor.submit(ocr_content_fallback)
|
||||
future_countdown_mm = executor.submit(ocr_countdown_mm_fallback)
|
||||
future_countdown_ss = executor.submit(ocr_countdown_ss_fallback)
|
||||
future_value = executor.submit(ocr_value_fallback)
|
||||
future_button = executor.submit(ocr_button_fallback)
|
||||
|
||||
# 等待所有操作完成
|
||||
task_list_raw = future_task_list.result()
|
||||
@@ -704,6 +872,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
countdown_mm_raw = future_countdown_mm.result()
|
||||
countdown_ss_raw = future_countdown_ss.result()
|
||||
value_raw = future_value.result()
|
||||
button_text_raw = future_button.result()
|
||||
|
||||
# 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查)
|
||||
if task_list_raw:
|
||||
@@ -760,6 +929,49 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
pass
|
||||
# 直接返回空内容,后续流程会跳过
|
||||
return "", "", 0, 0, 0.0
|
||||
|
||||
# 处理备用并行执行的按钮识别结果
|
||||
button_status = None
|
||||
if button_text_raw:
|
||||
button_text = str(button_text_raw).strip()
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"备用并行OCR识别参与按钮",
|
||||
button_text=button_text[:100] if button_text else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 判断按钮状态
|
||||
if "参与成功" in button_text or "等待开奖" in button_text:
|
||||
button_status = "已参与"
|
||||
elif "加入粉丝团" in button_text or "粉丝团" in button_text:
|
||||
button_status = "需要加入粉丝团"
|
||||
elif "评论" in button_text or "发表评论" in button_text or "一键发表评论" in button_text:
|
||||
button_status = "需要评论"
|
||||
elif "还需看播" in button_text or "开始观看" in button_text:
|
||||
button_status = "需要观看"
|
||||
elif "未达成" in button_text:
|
||||
button_status = "未达成要求"
|
||||
elif "参与抽奖" in button_text or "参与" in button_text:
|
||||
button_status = "可以参与"
|
||||
else:
|
||||
button_status = "未知状态"
|
||||
|
||||
# 将按钮状态存储到 analyser 对象中
|
||||
try:
|
||||
analyser._fudai_button_status = button_status
|
||||
analyser._fudai_button_text = button_text
|
||||
analyser._fudai_button_ocr_time = time.time() # 记录识别时间
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"备用按钮状态判断",
|
||||
status=button_status,
|
||||
button_text=button_text[:100] if button_text else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as fallback_error:
|
||||
# 如果备用并行执行也失败,使用串行执行作为最后兜底
|
||||
try:
|
||||
@@ -774,7 +986,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
pass
|
||||
# 串行执行所有OCR(包括任务列表OCR)
|
||||
try:
|
||||
task_list_raw = analyser.operation.analyse_pic_word("福袋任务列表", 0)
|
||||
name_tl3 = preprocess_for_ocr(analyser, "福袋任务列表")
|
||||
task_list_raw = analyser.operation.analyse_pic_word(name_tl3, 0)
|
||||
# 检查任务列表中是否包含"观看X分钟"任务
|
||||
if task_list_raw:
|
||||
is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw))
|
||||
@@ -810,6 +1023,71 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
)
|
||||
countdown_ss_raw = analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1)
|
||||
value_raw = analyser.operation.analyse_pic_word("福袋价值", 0)
|
||||
# 串行执行按钮OCR
|
||||
try:
|
||||
name_btn3 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
button_text_raw = str(analyser.operation.analyse_pic_word(name_btn3, 0) or "")
|
||||
if not button_text_raw or not any(
|
||||
k in button_text_raw
|
||||
for k in (
|
||||
"参与成功",
|
||||
"还需看播",
|
||||
"评论",
|
||||
"参与抽奖",
|
||||
"开始观看",
|
||||
"参与",
|
||||
"加入粉丝团",
|
||||
"粉丝团",
|
||||
"等待开奖",
|
||||
"未达成",
|
||||
)
|
||||
):
|
||||
button_text_raw = str(analyser.operation.analyse_pic_word(name_btn3, 1) or "")
|
||||
|
||||
# 处理串行执行的按钮识别结果
|
||||
button_status = None
|
||||
if button_text_raw:
|
||||
button_text = str(button_text_raw).strip()
|
||||
# 判断按钮状态
|
||||
if "参与成功" in button_text or "等待开奖" in button_text:
|
||||
button_status = "已参与"
|
||||
elif "加入粉丝团" in button_text or "粉丝团" in button_text:
|
||||
button_status = "需要加入粉丝团"
|
||||
elif "评论" in button_text or "发表评论" in button_text or "一键发表评论" in button_text:
|
||||
button_status = "需要评论"
|
||||
elif "还需看播" in button_text or "开始观看" in button_text:
|
||||
button_status = "需要观看"
|
||||
elif "未达成" in button_text:
|
||||
button_status = "未达成要求"
|
||||
elif "参与抽奖" in button_text or "参与" in button_text:
|
||||
button_status = "可以参与"
|
||||
else:
|
||||
button_status = "未知状态"
|
||||
|
||||
# 将按钮状态存储到 analyser 对象中
|
||||
try:
|
||||
analyser._fudai_button_status = button_status
|
||||
analyser._fudai_button_text = button_text
|
||||
analyser._fudai_button_ocr_time = time.time() # 记录识别时间
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"串行按钮状态判断",
|
||||
status=button_status,
|
||||
button_text=button_text[:100] if button_text else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"串行OCR识别参与按钮失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 先检查原始OCR内容是否是"观看X分钟"任务(在清理之前检查,避免丢失关键信息)
|
||||
is_watch_task = False
|
||||
@@ -936,10 +1214,19 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
try:
|
||||
# 提取数字:分钟和秒都应该是1-2位数字
|
||||
def _extract_digits(text: str, max_digits: int = 2) -> str:
|
||||
"""提取数字,最多max_digits位"""
|
||||
"""提取数字,最多max_digits位,智能处理前导零"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
if len(digits) > max_digits:
|
||||
return digits[:max_digits]
|
||||
# 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况)
|
||||
# 例如"002" -> "02" 而不是 "00"
|
||||
candidate = digits[-max_digits:]
|
||||
# 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数
|
||||
if candidate.startswith('0') and not digits.startswith('0' * len(digits)):
|
||||
# 移除前导零后的长度
|
||||
actual_digits = digits.lstrip('0') or '0'
|
||||
if len(actual_digits) <= max_digits:
|
||||
return actual_digits.zfill(max_digits)
|
||||
return candidate
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
return digits
|
||||
@@ -1201,13 +1488,24 @@ def check_contain(analyser, contains: str = "") -> bool:
|
||||
|
||||
def attend_choujiang(analyser) -> bool:
|
||||
"""点击参与抽奖。"""
|
||||
# 优先委派到 core/fudai_attend.py 中的实现(该实现包含预处理与增强OCR)
|
||||
try:
|
||||
from douyin.fudai.core.fudai_attend import attend_choujiang as external_attend # type: ignore
|
||||
|
||||
# 如果外部实现存在,直接调用并返回结果
|
||||
return external_attend(analyser)
|
||||
except Exception:
|
||||
# 无法委派时回退到本地实现(保持向后兼容)
|
||||
pass
|
||||
|
||||
analyser.last_attend_fail_reason = ""
|
||||
click_times = 0
|
||||
while click_times < 2:
|
||||
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字
|
||||
# 优化:尝试多种OCR模式提高精准度(优先保证精准)
|
||||
name_part0b = preprocess_for_ocr(analyser, "参与按钮")
|
||||
attend_button_text = str(
|
||||
analyser.operation.analyse_pic_word("参与按钮", 0) or ""
|
||||
analyser.operation.analyse_pic_word(name_part0b, 0) or ""
|
||||
)
|
||||
if not attend_button_text or not any(
|
||||
k in attend_button_text
|
||||
@@ -1222,8 +1520,9 @@ def attend_choujiang(analyser) -> bool:
|
||||
"粉丝团",
|
||||
)
|
||||
):
|
||||
name_part1b = preprocess_for_ocr(analyser, "参与按钮")
|
||||
attend_button_text = str(
|
||||
analyser.operation.analyse_pic_word("参与按钮", 1) or ""
|
||||
analyser.operation.analyse_pic_word(name_part1b, 1) or ""
|
||||
)
|
||||
analyser._log_kv("参与", "识别参与按钮", text=attend_button_text)
|
||||
if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖
|
||||
|
||||
@@ -18,6 +18,9 @@ from typing import Any, Optional, Tuple, Dict
|
||||
from PIL import Image
|
||||
import path_config
|
||||
|
||||
# OCR 预处理接口(直接导入)
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
|
||||
class FudaiImageAcquirer:
|
||||
"""图像获取器:负责截图和图像预处理"""
|
||||
@@ -456,14 +459,14 @@ class FudaiDetector:
|
||||
threshold = 0.6 # 降低默认阈值,因为添加了多种匹配方法
|
||||
|
||||
# 读取模板(彩色和灰度)
|
||||
template_color = cv2.imread(template_path, cv2.IMREAD_COLOR) # type: ignore[attr-defined]
|
||||
template_gray = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) # type: ignore[attr-defined]
|
||||
template_color = cv2.imread(template_path, cv2.IMREAD_COLOR) # type: ignore[attr-defined, misc]
|
||||
template_gray = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) # type: ignore[attr-defined, misc]
|
||||
if template_color is None or template_gray is None:
|
||||
return None
|
||||
|
||||
width, height = pic.size
|
||||
pic_rgb = pic.convert("RGB")
|
||||
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
|
||||
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) # type: ignore[attr-defined, misc]
|
||||
|
||||
# 提取搜索区域(扩大Y范围用于模板匹配,提高成功率)
|
||||
if "y_top" in region:
|
||||
@@ -491,13 +494,13 @@ class FudaiDetector:
|
||||
return None
|
||||
|
||||
# 转换为灰度图(用于灰度匹配)
|
||||
search_roi_gray = cv2.cvtColor(search_roi_bgr, cv2.COLOR_BGR2GRAY)
|
||||
search_roi_gray = cv2.cvtColor(search_roi_bgr, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined, misc]
|
||||
|
||||
# 图像预处理:增强对比度和去噪
|
||||
try:
|
||||
# 直方图均衡化(增强对比度)
|
||||
search_roi_gray_enhanced = cv2.equalizeHist(search_roi_gray)
|
||||
template_gray_enhanced = cv2.equalizeHist(template_gray)
|
||||
search_roi_gray_enhanced = cv2.equalizeHist(search_roi_gray) # type: ignore[attr-defined, misc]
|
||||
template_gray_enhanced = cv2.equalizeHist(template_gray) # type: ignore[attr-defined, misc]
|
||||
except Exception:
|
||||
search_roi_gray_enhanced = search_roi_gray
|
||||
template_gray_enhanced = template_gray
|
||||
@@ -516,9 +519,9 @@ class FudaiDetector:
|
||||
|
||||
# 多种匹配方法(按优先级排序)
|
||||
match_methods = [
|
||||
(cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # 归一化相关系数(最常用)
|
||||
(cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # 归一化相关匹配
|
||||
(cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # 归一化平方差(值越小越好)
|
||||
(cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关系数(最常用)
|
||||
(cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关匹配
|
||||
(cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化平方差(值越小越好)
|
||||
]
|
||||
|
||||
for scale in scales:
|
||||
@@ -530,24 +533,22 @@ class FudaiDetector:
|
||||
continue
|
||||
|
||||
# 缩放模板(彩色和灰度)
|
||||
scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th))
|
||||
scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th))
|
||||
scaled_template_gray_enhanced = cv2.resize(
|
||||
template_gray_enhanced, (scaled_tw, scaled_th)
|
||||
)
|
||||
scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
|
||||
scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
|
||||
scaled_template_gray_enhanced = cv2.resize(template_gray_enhanced, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
|
||||
|
||||
# 尝试多种匹配方法
|
||||
for method, method_name in match_methods:
|
||||
try:
|
||||
# 方法1:彩色匹配
|
||||
res_color = cv2.matchTemplate(
|
||||
res_color = cv2.matchTemplate( # type: ignore[attr-defined, misc]
|
||||
search_roi_bgr, scaled_template_color, method
|
||||
)
|
||||
if method == cv2.TM_SQDIFF_NORMED:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc]
|
||||
score = 1.0 - max_val # SQDIFF值越小越好,转换为越大越好
|
||||
else:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc]
|
||||
score = max_val
|
||||
|
||||
if score > best_score:
|
||||
@@ -557,14 +558,14 @@ class FudaiDetector:
|
||||
best_method = f"{method_name}_color"
|
||||
|
||||
# 方法2:灰度匹配(更稳定,不受光照影响)
|
||||
res_gray = cv2.matchTemplate(
|
||||
res_gray = cv2.matchTemplate( # type: ignore[attr-defined, misc]
|
||||
search_roi_gray, scaled_template_gray, method
|
||||
)
|
||||
if method == cv2.TM_SQDIFF_NORMED:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc]
|
||||
score = 1.0 - max_val
|
||||
else:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc]
|
||||
score = max_val
|
||||
|
||||
if score > best_score:
|
||||
@@ -574,16 +575,16 @@ class FudaiDetector:
|
||||
best_method = f"{method_name}_gray"
|
||||
|
||||
# 方法3:增强对比度后的灰度匹配
|
||||
res_gray_enhanced = cv2.matchTemplate(
|
||||
res_gray_enhanced = cv2.matchTemplate( # type: ignore[attr-defined, misc]
|
||||
search_roi_gray_enhanced, scaled_template_gray_enhanced, method
|
||||
)
|
||||
if method == cv2.TM_SQDIFF_NORMED:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc]
|
||||
res_gray_enhanced
|
||||
)
|
||||
score = 1.0 - max_val
|
||||
else:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc]
|
||||
res_gray_enhanced
|
||||
)
|
||||
score = max_val
|
||||
@@ -603,11 +604,11 @@ class FudaiDetector:
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale > 0:
|
||||
template_color = cv2.resize(
|
||||
template_color = cv2.resize( # type: ignore[attr-defined, misc]
|
||||
template_color,
|
||||
(max(1, int(tw * scale)), max(1, int(th * scale))),
|
||||
)
|
||||
template_gray = cv2.resize(
|
||||
template_gray = cv2.resize( # type: ignore[attr-defined, misc]
|
||||
template_gray,
|
||||
(max(1, int(tw * scale)), max(1, int(th * scale))),
|
||||
)
|
||||
@@ -615,10 +616,10 @@ class FudaiDetector:
|
||||
|
||||
if th <= rh and tw <= rw:
|
||||
try:
|
||||
res = cv2.matchTemplate(
|
||||
res = cv2.matchTemplate( # type: ignore[attr-defined, misc]
|
||||
search_roi_bgr, template_color, cv2.TM_CCOEFF_NORMED
|
||||
)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined, misc]
|
||||
best_score = max_val
|
||||
best_x = max_loc[0]
|
||||
best_scale = 1.0
|
||||
@@ -1003,8 +1004,9 @@ class FudaiClickExecutor:
|
||||
)
|
||||
|
||||
# OCR识别
|
||||
name_chk = preprocess_for_ocr(self.analyser, "檢查紅包特徵")
|
||||
check_text = str(
|
||||
self.analyser.operation.analyse_pic_word("檢查紅包特徵", 0) or ""
|
||||
self.analyser.operation.analyse_pic_word(name_chk, 0) or ""
|
||||
).strip()
|
||||
|
||||
# 检查是否包含红包关键词
|
||||
@@ -1214,9 +1216,10 @@ class FudaiDetailVerifier:
|
||||
self.analyser.cut_pic(
|
||||
238, 454, 847, 545, "", "验证邀你抢红包区域", y_pianyi
|
||||
)
|
||||
name_invite = preprocess_for_ocr(self.analyser, "验证邀你抢红包区域")
|
||||
ocr_text = str(
|
||||
self.analyser.operation.analyse_pic_word(
|
||||
"验证邀你抢红包区域", 0
|
||||
name_invite, 0
|
||||
)
|
||||
or ""
|
||||
)
|
||||
@@ -1231,9 +1234,10 @@ class FudaiDetailVerifier:
|
||||
kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气")
|
||||
)
|
||||
):
|
||||
name_invite1 = preprocess_for_ocr(self.analyser, "验证邀你抢红包区域")
|
||||
ocr_text = str(
|
||||
self.analyser.operation.analyse_pic_word(
|
||||
"验证邀你抢红包区域", 1
|
||||
name_invite1, 1
|
||||
)
|
||||
or ""
|
||||
)
|
||||
|
||||
@@ -37,3 +37,25 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -555,6 +555,70 @@ def init_debug_captures_cleanup() -> None:
|
||||
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": "位置",
|
||||
}
|
||||
|
||||
|
||||
def _sanitize_filename_part(text: str) -> str:
|
||||
"""清理文件名部分,移除Windows不允许的字符
|
||||
|
||||
@@ -594,7 +658,7 @@ def _sanitize_filename_part(text: str) -> str:
|
||||
return sanitized
|
||||
|
||||
|
||||
def save_debug_image(
|
||||
def save_debug_image( # type: ignore
|
||||
image: Image.Image,
|
||||
operation_type: str = "",
|
||||
picname: str = "",
|
||||
@@ -745,18 +809,30 @@ def save_debug_image(
|
||||
|
||||
parts = []
|
||||
if operation_type:
|
||||
parts.append(_sanitize_filename_part(operation_type))
|
||||
# 转换为中文
|
||||
operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type)
|
||||
parts.append(_sanitize_filename_part(operation_type_cn))
|
||||
if picname:
|
||||
parts.append(_sanitize_filename_part(picname))
|
||||
# 转换为中文
|
||||
picname_cn = _PICNAME_CN.get(picname, picname)
|
||||
parts.append(_sanitize_filename_part(picname_cn))
|
||||
if step:
|
||||
parts.append(_sanitize_filename_part(step))
|
||||
# 转换为中文
|
||||
step_cn = _STEP_CN.get(step, step)
|
||||
parts.append(_sanitize_filename_part(step_cn))
|
||||
if coords:
|
||||
parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})")
|
||||
if extra_info:
|
||||
for key, value in extra_info.items():
|
||||
# 将键名转换为中文
|
||||
key_cn = _EXTRA_INFO_KEY_CN.get(key, key)
|
||||
# 清理键名和值
|
||||
clean_key = _sanitize_filename_part(str(key))
|
||||
clean_value = _sanitize_filename_part(str(value))
|
||||
clean_key = _sanitize_filename_part(str(key_cn))
|
||||
# 处理值的转换(布尔值转为中文)
|
||||
if isinstance(value, bool):
|
||||
clean_value = "是" if value else "否"
|
||||
else:
|
||||
clean_value = _sanitize_filename_part(str(value))
|
||||
# 限制值的长度,避免文件名过长
|
||||
# 对于 text_preview 等长文本,限制更短(20字符)
|
||||
if key == "text_preview" or key == "content":
|
||||
@@ -778,11 +854,17 @@ def save_debug_image(
|
||||
# 优先保留:时间戳、操作类型、图片名、步骤
|
||||
base_parts = [timestamp]
|
||||
if operation_type:
|
||||
base_parts.append(_sanitize_filename_part(operation_type))
|
||||
# 转换为中文
|
||||
operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type)
|
||||
base_parts.append(_sanitize_filename_part(operation_type_cn))
|
||||
if picname:
|
||||
base_parts.append(_sanitize_filename_part(picname))
|
||||
# 转换为中文
|
||||
picname_cn = _PICNAME_CN.get(picname, picname)
|
||||
base_parts.append(_sanitize_filename_part(picname_cn))
|
||||
if step:
|
||||
base_parts.append(_sanitize_filename_part(step))
|
||||
# 转换为中文
|
||||
step_cn = _STEP_CN.get(step, step)
|
||||
base_parts.append(_sanitize_filename_part(step_cn))
|
||||
|
||||
base = "_".join(base_parts)
|
||||
|
||||
@@ -792,8 +874,15 @@ def save_debug_image(
|
||||
important_keys = ["mode", "size", "used_img2", "avg_confidence"]
|
||||
for key in important_keys:
|
||||
if key in extra_info and remaining > 0:
|
||||
clean_key = _sanitize_filename_part(str(key))
|
||||
clean_value = _sanitize_filename_part(str(extra_info[key]))
|
||||
# 将键名转换为中文
|
||||
key_cn = _EXTRA_INFO_KEY_CN.get(key, key)
|
||||
clean_key = _sanitize_filename_part(str(key_cn))
|
||||
# 处理值的转换(布尔值转为中文)
|
||||
value = extra_info[key]
|
||||
if isinstance(value, bool):
|
||||
clean_value = "是" if value else "否"
|
||||
else:
|
||||
clean_value = _sanitize_filename_part(str(value))
|
||||
if len(clean_value) > 15:
|
||||
clean_value = clean_value[:15]
|
||||
part = f"{clean_key}_{clean_value}"
|
||||
@@ -963,3 +1052,162 @@ def save_debug_image(
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
# 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在)
|
||||
try:
|
||||
ensure_debug_captures_dir()
|
||||
except Exception:
|
||||
pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理
|
||||
|
||||
# 保存图像的辅助函数,带重试机制
|
||||
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 as dir_error:
|
||||
# 记录目录创建失败
|
||||
try:
|
||||
print(f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 最后一次尝试失败,抛出异常
|
||||
raise
|
||||
except PermissionError as e:
|
||||
# 权限错误,不重试
|
||||
try:
|
||||
print(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except OSError as e:
|
||||
# 系统级错误(磁盘空间不足等),不重试
|
||||
try:
|
||||
print(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except Exception as e:
|
||||
# 其他异常直接抛出
|
||||
last_error = e
|
||||
raise
|
||||
# 所有重试都失败
|
||||
if last_error:
|
||||
raise last_error
|
||||
return False
|
||||
|
||||
# 如果需要标注,在图像上添加信息
|
||||
if annotate and (coords or extra_info):
|
||||
try:
|
||||
from PIL import ImageDraw, ImageFont
|
||||
|
||||
annotated_image = image.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:
|
||||
# 使用元组格式 (x1, y1, x2, y2)
|
||||
rect_coords: Tuple[float, float, float, float] = (
|
||||
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
|
||||
|
||||
save_image_with_retry(annotated_image, file_path)
|
||||
except (PermissionError, OSError) as e:
|
||||
# 权限或系统错误,尝试保存原图
|
||||
try:
|
||||
try:
|
||||
print(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
save_image_with_retry(image, file_path)
|
||||
except Exception:
|
||||
# 如果保存原图也失败,抛出异常让外层处理
|
||||
raise
|
||||
except Exception as e:
|
||||
# 其他标注错误,尝试保存原图
|
||||
try:
|
||||
try:
|
||||
print(f"[截图管理] 图像标注失败,尝试保存原图: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
save_image_with_retry(image, file_path)
|
||||
except Exception:
|
||||
# 如果保存原图也失败,抛出异常让外层处理
|
||||
raise
|
||||
else:
|
||||
save_image_with_retry(image, file_path)
|
||||
|
||||
return file_path
|
||||
except FileNotFoundError as e:
|
||||
# 文件或目录不存在
|
||||
try:
|
||||
print(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
except PermissionError as e:
|
||||
# 权限错误
|
||||
try:
|
||||
print(f"[截图管理] 保存调试图像失败(权限错误): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
except OSError as e:
|
||||
# 系统级错误(磁盘空间不足、路径过长等)
|
||||
try:
|
||||
print(f"[截图管理] 保存调试图像失败(系统错误): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
except Exception as e:
|
||||
# 其他未知错误
|
||||
try:
|
||||
error_type = type(e).__name__
|
||||
print(f"[截图管理] 保存调试图像失败({error_type}): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
@@ -28,3 +28,25 @@ def track_action(name: str = ""):
|
||||
__all__ = ["track_action"]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ class DebugLogger:
|
||||
if not self.enabled:
|
||||
return
|
||||
tb = traceback.format_exc()
|
||||
line = format_debug_log("Exception", level="ERROR", exception=type(exc).__name__, message=str(exc), traceback=tb, context=context or {})
|
||||
line = format_debug_log("Exception", level="ERROR", exception=type(exc).__name__, traceback=tb, context=context or {})
|
||||
_debug_logger.error(line)
|
||||
_err.log_exception(exc, context=context)
|
||||
|
||||
|
||||
@@ -30,6 +30,10 @@ class ErrorLogger:
|
||||
def log_exception(self, exc: BaseException, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None:
|
||||
if not logger:
|
||||
_init_logger()
|
||||
if logger is None:
|
||||
# 如果仍然无法初始化 logger,则退回到标准输出,避免抛出异常
|
||||
print(f"[ErrorLogger] {type(exc).__name__}: {exc}")
|
||||
return
|
||||
tb = traceback.format_exc()
|
||||
ctx = ", ".join(f"{k}={v}" for k, v in (context or {}).items()) if context else ""
|
||||
msg = f"Exception: {type(exc).__name__}: {exc}"
|
||||
@@ -41,6 +45,9 @@ class ErrorLogger:
|
||||
def log_error(self, msg: str, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None:
|
||||
if not logger:
|
||||
_init_logger()
|
||||
if logger is None:
|
||||
print(f"[ErrorLogger] {msg}")
|
||||
return
|
||||
full = msg
|
||||
if context:
|
||||
full += " | " + ", ".join(f"{k}={v}" for k, v in context.items())
|
||||
@@ -54,4 +61,23 @@ class ErrorLogger:
|
||||
|
||||
__all__ = ["ErrorLogger"]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ from PIL import Image
|
||||
|
||||
from douyin.detection import douyin_pixel
|
||||
|
||||
# OCR 预处理接口(直接导入)
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
|
||||
def check_coupon_popup(analyser) -> bool:
|
||||
"""优惠券弹窗检测(模板匹配 + OCR兜底确认)。
|
||||
@@ -76,7 +79,8 @@ def check_coupon_popup(analyser) -> bool:
|
||||
# OCR模式0
|
||||
ocr_mode0_start = time.time()
|
||||
try:
|
||||
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
pname0 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
coupon_text = str(analyser.operation.analyse_pic_word(pname0, 0) or "")
|
||||
ocr_mode0_elapsed = time.time() - ocr_mode0_start
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
@@ -111,7 +115,8 @@ def check_coupon_popup(analyser) -> bool:
|
||||
if enable_ocr_mode1 and not ocr_confirmed:
|
||||
ocr_mode1_start = time.time()
|
||||
try:
|
||||
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "")
|
||||
pname1 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
coupon_text = str(analyser.operation.analyse_pic_word(pname1, 1) or "")
|
||||
ocr_mode1_elapsed = time.time() - ocr_mode1_start
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
@@ -228,7 +233,8 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
# OCR 模式0
|
||||
ocr_mode0_start = time.time()
|
||||
try:
|
||||
t = str(analyser.operation.analyse_pic_word("診斷購物紅包", 0) or "")
|
||||
name_r = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
t = str(analyser.operation.analyse_pic_word(name_r, 0) or "")
|
||||
hay = t.strip() if t else ""
|
||||
ocr_mode0_elapsed = time.time() - ocr_mode0_start
|
||||
except Exception as e:
|
||||
@@ -255,8 +261,9 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
# 嘗試按鈕區域快速 OCR(兜底)
|
||||
try:
|
||||
analyser.cut_pic(400, 1200, 680, 1400, "", "診斷購物紅包按鈕")
|
||||
name_btn = preprocess_for_ocr(analyser, "診斷購物紅包按鈕")
|
||||
btn_text = str(
|
||||
analyser.operation.analyse_pic_word("診斷購物紅包按鈕", 0) or ""
|
||||
analyser.operation.analyse_pic_word(name_btn, 0) or ""
|
||||
).strip()
|
||||
if "搶" in btn_text:
|
||||
total_elapsed = time.time() - check_start
|
||||
@@ -292,7 +299,8 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
# 模式1
|
||||
ocr_mode1_start = time.time()
|
||||
try:
|
||||
t1 = str(analyser.operation.analyse_pic_word("診斷購物紅包", 1) or "")
|
||||
name_r1 = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
t1 = str(analyser.operation.analyse_pic_word(name_r1, 1) or "")
|
||||
hay1 = t1.strip() if t1 else ""
|
||||
ocr_mode1_elapsed = time.time() - ocr_mode1_start
|
||||
if hay1:
|
||||
@@ -320,7 +328,8 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
# 模式2
|
||||
ocr_mode2_start = time.time()
|
||||
try:
|
||||
t2 = str(analyser.operation.analyse_pic_word("診斷購物紅包", 2) or "")
|
||||
name_r2 = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
t2 = str(analyser.operation.analyse_pic_word(name_r2, 2) or "")
|
||||
hay2 = t2.strip() if t2 else ""
|
||||
ocr_mode2_elapsed = time.time() - ocr_mode2_start
|
||||
if hay2:
|
||||
@@ -374,39 +383,25 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
|
||||
|
||||
def handle_lottery_result_popup(analyser) -> None:
|
||||
"""处理抽奖结果弹窗:点击"我知道了"或"领取并使用"按钮。
|
||||
"""处理抽奖结果弹窗:通过OCR识别并点击"我知道了"或"领取并使用"按钮。
|
||||
|
||||
根据阶段诊断,已经确认是 FUDai_RESULT 阶段,这里只需要点击按钮关闭弹窗。
|
||||
按钮位置通常在屏幕中下部,坐标约 (540, 1400) 基于1080x2400。
|
||||
根据阶段诊断,已经确认是 FUDai_RESULT 阶段,这里使用OCR识别按钮文本后点击。
|
||||
"""
|
||||
try:
|
||||
analyser._log_kv("开奖结果", "开始处理抽奖结果弹窗")
|
||||
|
||||
# 点击"我知道了"或"领取并使用"按钮(坐标基于1080x2400:540, 1400)
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
btn_x = int(540 * rx // 1080)
|
||||
btn_y = int(1400 * ry // 2400)
|
||||
# 使用OCR识别开奖结果按钮
|
||||
from douyin.utils import douyin_helpers
|
||||
result_type = douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(analyser)
|
||||
|
||||
analyser.operation.click(analyser.device_id, btn_x, btn_y)
|
||||
analyser._log_kv("开奖结果", "已点击结果按钮", x=btn_x, y=btn_y)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 如果还有弹窗,尝试再次点击或按返回键
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
from douyin.stage import douyin_stage
|
||||
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
|
||||
if result is None:
|
||||
stage = "UNKNOWN"
|
||||
else:
|
||||
stage, _ = result
|
||||
if stage == "FUDai_RESULT":
|
||||
# 仍在结果页,尝试按返回键
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
if result_type:
|
||||
# 根据OCR识别结果处理
|
||||
douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(analyser, result_type)
|
||||
else:
|
||||
# OCR未识别到,尝试按返回键
|
||||
analyser._log_kv("开奖结果", "OCR未识别到按钮,使用返回键关闭")
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
|
||||
analyser._log_kv("开奖结果", "处理完成")
|
||||
except Exception as e:
|
||||
|
||||
@@ -5,6 +5,8 @@ from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
# OCR 预处理接口(直接导入)
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
def check_have_robot_analyse(analyser) -> int | bool:
|
||||
"""检查是否存在人机校验。
|
||||
@@ -16,17 +18,19 @@ def check_have_robot_analyse(analyser) -> int | bool:
|
||||
- False: 未检测到人机验证
|
||||
"""
|
||||
analyser.cut_pic(130, 790, 680, 870, "", "直播验证")
|
||||
result = analyser.operation.analyse_pic_word("直播验证", 1)
|
||||
name_live = preprocess_for_ocr(analyser, "直播验证")
|
||||
result = analyser.operation.analyse_pic_word(name_live, 0)
|
||||
if "验证" in result:
|
||||
print("存在滑动图片人机校验,需要等待完成验证.")
|
||||
print("存在滑动图片人机校验,需要等待完成验证。")
|
||||
return 1
|
||||
elif "形状相同" in result:
|
||||
print("存在点击图片人机校验,需要等待完成验证.")
|
||||
print("存在点击图片人机校验,需要等待完成验证。")
|
||||
return 2
|
||||
analyser.cut_pic(340, 1415, 700, 1518, "", "直播验证")
|
||||
result = analyser.operation.analyse_pic_word("直播验证")
|
||||
name_live2 = preprocess_for_ocr(analyser, "直播验证")
|
||||
result = analyser.operation.analyse_pic_word(name_live2)
|
||||
if "开始检测" in result:
|
||||
print("存在人脸识别人机校验,需要等待完成验证.")
|
||||
print("存在人脸识别人机校验,需要等待完成验证。")
|
||||
return 3
|
||||
return False
|
||||
|
||||
@@ -142,4 +146,3 @@ def check_robot_pic_distance(analyser) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -47,3 +47,25 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -166,6 +166,14 @@ class ReservationHandler:
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
# 检查配置项,只有在启用时才记录映射表
|
||||
try:
|
||||
mapping_enabled = bool(getattr(analyser, "record_room_title_mapping_enabled", True))
|
||||
if not mapping_enabled:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
|
||||
@@ -350,20 +358,20 @@ class ReservationHandler:
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
delay_s = float(
|
||||
getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6
|
||||
)
|
||||
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
|
||||
try:
|
||||
analyser._skip_record_title_during_seek = True
|
||||
except Exception:
|
||||
pass
|
||||
for _ in range(back_times):
|
||||
# 执行连续滑动,不在每次滑动后添加延迟(ADB滑动命令本身会等待完成)
|
||||
for i in range(back_times):
|
||||
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(analyser)
|
||||
try:
|
||||
analyser.operation.delay(delay_s)
|
||||
except Exception:
|
||||
time.sleep(delay_s)
|
||||
# 只在最后一次滑动后添加短暂延迟,确保页面稳定
|
||||
if i == back_times - 1 and back_times > 0:
|
||||
try:
|
||||
analyser.operation.delay(0.1) # 最后一次滑动后短暂等待
|
||||
except Exception:
|
||||
time.sleep(0.1)
|
||||
# 清除标志
|
||||
try:
|
||||
analyser._skip_record_title_during_seek = False
|
||||
@@ -385,20 +393,20 @@ class ReservationHandler:
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
delay_s = float(
|
||||
getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6
|
||||
)
|
||||
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
|
||||
try:
|
||||
analyser._skip_record_title_during_seek = True
|
||||
except Exception:
|
||||
pass
|
||||
for _ in range(forward_times):
|
||||
# 执行连续滑动,不在每次滑动后添加延迟(ADB滑动命令本身会等待完成)
|
||||
for i in range(forward_times):
|
||||
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(analyser)
|
||||
try:
|
||||
analyser.operation.delay(delay_s)
|
||||
except Exception:
|
||||
time.sleep(delay_s)
|
||||
# 只在最后一次滑动后添加短暂延迟,确保页面稳定
|
||||
if i == forward_times - 1 and forward_times > 0:
|
||||
try:
|
||||
analyser.operation.delay(0.1) # 最后一次滑动后短暂等待
|
||||
except Exception:
|
||||
time.sleep(0.1)
|
||||
# 清除标志
|
||||
try:
|
||||
analyser._skip_record_title_during_seek = False
|
||||
@@ -411,7 +419,13 @@ class ReservationHandler:
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
"""预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。
|
||||
"""预约回退后直接参与:直接查找福袋并点击,使用按钮检测进行决策,跳过OCR识别。
|
||||
|
||||
新流程:
|
||||
1. 直接查找福袋图标并点击
|
||||
2. 点击后调用阶段检测中的按钮检测进行决策
|
||||
3. 完成决策后,再点击福袋图标验证参与状态
|
||||
4. 参与成功后进入开奖倒计时
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
@@ -420,7 +434,7 @@ class ReservationHandler:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后直接参与:使用预约记录中的详情,跳过OCR识别",
|
||||
"[预约] 预约回退后直接参与:直接查找福袋,使用按钮检测进行决策,跳过OCR识别",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -441,14 +455,10 @@ class ReservationHandler:
|
||||
first_reservation = analyser.reservations[0]
|
||||
try:
|
||||
# 从预约记录中获取信息
|
||||
content = str(first_reservation.get("content", "") or "")
|
||||
future_ts = float(first_reservation.get("future_ts", 0.0) or 0.0)
|
||||
prize_value_yuan = float(
|
||||
first_reservation.get("prize_value_yuan", 0.0) or 0.0
|
||||
)
|
||||
future_ts = float(first_reservation.get("future_ts", 0.0) or 0.0)
|
||||
time_text = str(first_reservation.get("time_text", "") or "")
|
||||
participants = int(first_reservation.get("participants", 0) or 0)
|
||||
copies = int(first_reservation.get("copies", 0) or 0)
|
||||
|
||||
# 检查福袋是否已过期
|
||||
now_ts = time.time()
|
||||
@@ -481,7 +491,6 @@ class ReservationHandler:
|
||||
pass
|
||||
|
||||
# 清除相关标志
|
||||
analyser._reservation_back_direct_attend = False
|
||||
analyser._force_attend_after_reservation_back = False
|
||||
analyser.queue_full_waiting_at_earliest = False
|
||||
|
||||
@@ -497,45 +506,196 @@ class ReservationHandler:
|
||||
|
||||
return
|
||||
|
||||
# 构造倒计时元组
|
||||
countdown_start = now_ts
|
||||
countdown_end = future_ts if future_ts > 0 else (now_ts + 60.0)
|
||||
|
||||
# 构造 detail tuple(格式与 read_fudai_detail_once 返回的格式一致)
|
||||
detail = (
|
||||
content, # 0: 内容
|
||||
time_text, # 1: 倒计时文本
|
||||
participants, # 2: 参与人数
|
||||
copies, # 3: 份数
|
||||
prize_value_yuan, # 4: 价值
|
||||
(countdown_start, countdown_end), # 5: 倒计时元组
|
||||
)
|
||||
# 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除)
|
||||
analyser._current_fudai_future_ts = future_ts
|
||||
|
||||
# 步骤1:直接查找福袋图标并点击
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后直接参与:从预约记录构造详情",
|
||||
content=content[:50] if content else "",
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
future_ts=int(future_ts) if future_ts > 0 else 0,
|
||||
time_text=time_text,
|
||||
participants=participants,
|
||||
copies=copies,
|
||||
"[预约] 步骤1:直接查找福袋图标并点击",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 保存详情数据,标记为已读取(用于后续可能的第二次打开)
|
||||
analyser._last_fudai_detail_tuple = detail
|
||||
analyser._fudai_detail_first_read = True
|
||||
from douyin.core import douyin_flow_control
|
||||
|
||||
# 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除)
|
||||
analyser._current_fudai_future_ts = future_ts
|
||||
room_pos_ref = [int(getattr(analyser, "room_pos", 0) or 0)]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(
|
||||
analyser, room_pos_ref
|
||||
)
|
||||
|
||||
# 直接调用参与决策,跳过详情识别
|
||||
join_result = douyin_fudai_core.basic_join_decision(analyser, detail)
|
||||
if not opened:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 未找到福袋图标,回退到正常流程",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
return
|
||||
|
||||
# 如果参与成功,设置开奖等待状态并从预约队列中移除
|
||||
# 等待页面加载
|
||||
try:
|
||||
analyser.operation.delay(0.5) # 等待详情页加载(减少延迟)
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
|
||||
# 步骤2:调用阶段检测中的按钮检测进行决策
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 步骤2:调用按钮检测进行决策",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 获取截图
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检测参与按钮
|
||||
from PIL import Image
|
||||
import path_config
|
||||
|
||||
try:
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
pic_rgb = Image.open(screenshot_path) # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 无法读取截图,回退到正常流程",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
return
|
||||
|
||||
from douyin.detection import douyin_pixel
|
||||
|
||||
button_result = douyin_pixel.detect_attend_button_red_area(
|
||||
pic_rgb, return_info=True, analyser=analyser
|
||||
)
|
||||
if isinstance(button_result, tuple):
|
||||
has_button, button_info = button_result
|
||||
else:
|
||||
has_button = button_result
|
||||
button_info = {}
|
||||
|
||||
if not has_button:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 未检测到参与按钮,回退到正常流程",
|
||||
button_info=button_info,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
return
|
||||
|
||||
# 步骤3:点击参与按钮
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 步骤3:点击参与按钮",
|
||||
button_info=button_info,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
|
||||
attend_x = int(543 * rx / 1080)
|
||||
attend_y = int(2070 * ry / 2400)
|
||||
analyser.operation.click(analyser.device_id, attend_x, attend_y)
|
||||
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 已点击参与按钮",
|
||||
click_x=attend_x,
|
||||
click_y=attend_y,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 等待点击后的响应
|
||||
try:
|
||||
analyser.operation.delay(0.8) # 等待参与响应(减少延迟)
|
||||
except Exception:
|
||||
time.sleep(0.8)
|
||||
|
||||
# 步骤4:点击福袋图标验证参与状态
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 步骤4:点击福袋图标验证参与状态",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 再次查找并点击福袋图标
|
||||
room_pos_ref2 = [int(getattr(analyser, "room_pos", 0) or 0)]
|
||||
opened2 = douyin_flow_control.find_and_open_fudai_detail(
|
||||
analyser, room_pos_ref2
|
||||
)
|
||||
|
||||
if not opened2:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 验证时未找到福袋图标,可能已参与成功",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 等待详情页加载
|
||||
try:
|
||||
analyser.operation.delay(0.5) # 减少延迟
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
|
||||
# 再次检测按钮状态,验证是否参与成功
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
screenshot_path2 = path_config.get_screenshot_path()
|
||||
pic_rgb2 = Image.open(screenshot_path2) # type: ignore[attr-defined]
|
||||
button_result2 = douyin_pixel.detect_attend_button_red_area(
|
||||
pic_rgb2, return_info=True, analyser=analyser
|
||||
)
|
||||
if isinstance(button_result2, tuple):
|
||||
has_button2, button_info2 = button_result2
|
||||
else:
|
||||
has_button2 = button_result2
|
||||
button_info2 = {}
|
||||
|
||||
if has_button2:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 验证时仍检测到参与按钮,可能参与失败",
|
||||
button_info=button_info2,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 如果还有按钮,回退到正常流程
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 步骤5:参与成功,设置开奖等待状态并从预约队列中移除
|
||||
join_result = True # 假设参与成功
|
||||
if join_result and future_ts > 0:
|
||||
try:
|
||||
# 设置开奖等待状态
|
||||
@@ -597,8 +757,6 @@ class ReservationHandler:
|
||||
if len(remaining_reservations) < len(analyser.reservations):
|
||||
analyser.reservations = remaining_reservations
|
||||
|
||||
# 清除预约回退直接参与标志
|
||||
analyser._reservation_back_direct_attend = False
|
||||
analyser.reservation_after_action_pending = False
|
||||
except Exception as e:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -629,4 +787,3 @@ class ReservationHandler:
|
||||
pass
|
||||
# 如果出错,回退到正常流程
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
|
||||
@@ -744,13 +744,11 @@ def handle_queue_full_wait_at_earliest(
|
||||
except Exception:
|
||||
time.sleep(1.5)
|
||||
|
||||
# 队列满后回退到最早直播间,直接设置参与标志,不管时间窗口是否到达
|
||||
# 立即参与,不等待开奖窗口
|
||||
# 队列满后回退到最早直播间,继续执行后续流程
|
||||
try:
|
||||
analyser._reservation_back_direct_attend = True
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 队列满回退后,直接设置参与标志(立即参与,不等待开奖窗口)",
|
||||
"[预约] 队列满回退后,继续执行后续流程",
|
||||
earliest_future_ts=int(ft),
|
||||
now_ts=int(now_ts),
|
||||
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
|
||||
@@ -1064,8 +1062,7 @@ def process_reservation_attend_window(
|
||||
is_queue_full_immediate_attend_check = False
|
||||
try:
|
||||
queue_full_waiting_check = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False)
|
||||
reservation_direct_attend_check = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False)
|
||||
if queue_full_waiting_check and reservation_direct_attend_check:
|
||||
if queue_full_waiting_check:
|
||||
is_queue_full_immediate_attend_check = True
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1110,8 +1107,7 @@ def process_reservation_attend_window(
|
||||
is_queue_full_immediate_attend_pos = False
|
||||
try:
|
||||
queue_full_waiting_pos = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False)
|
||||
reservation_direct_attend_pos = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False)
|
||||
if queue_full_waiting_pos and reservation_direct_attend_pos:
|
||||
if queue_full_waiting_pos:
|
||||
is_queue_full_immediate_attend_pos = True
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1193,17 +1189,15 @@ def process_reservation_attend_window(
|
||||
# 检查是否是队列满后立即参与的情况(使用标志判断,而不是锁定期)
|
||||
is_queue_full_immediate_attend = False
|
||||
try:
|
||||
# 检查队列满等待标志和直接参与标志
|
||||
# 检查队列满等待标志
|
||||
queue_full_waiting = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False)
|
||||
reservation_direct_attend = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False)
|
||||
if queue_full_waiting and reservation_direct_attend:
|
||||
if queue_full_waiting:
|
||||
is_queue_full_immediate_attend = True
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 检测到队列满后立即参与模式(通过标志判断),跳过时间窗口检查,直接参与",
|
||||
queue_full_waiting=queue_full_waiting,
|
||||
reservation_direct_attend=reservation_direct_attend,
|
||||
target_future_ts=int(ft),
|
||||
)
|
||||
except Exception:
|
||||
@@ -2012,4 +2006,4 @@ def record_high_value_reservation(
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
return False
|
||||
+237
-239
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
from douyin.detection import douyin_pixel
|
||||
|
||||
|
||||
def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C901
|
||||
def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: C901
|
||||
"""完整抽離自 `douyin_fudai.fudai_analyse._diagnose_stage_from_current_screen`。
|
||||
|
||||
日志輸出已從 print 改為 _log_kv,方便結構化查看。
|
||||
@@ -17,7 +17,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
# 是否输出详细阶段诊断日志:
|
||||
# - False:只保留最终结果等精简日志
|
||||
# - True:输出完整步骤级诊断日志(便于排查问题)
|
||||
verbose: bool = bool(getattr(self, "stage_diag_verbose", False))
|
||||
verbose: bool = bool(getattr(analyser, "stage_diag_verbose", False))
|
||||
|
||||
def _log(msg: str, **fields): # type: ignore[misc]
|
||||
"""阶段诊断详细日志入口:始终记录到行为日志,仅在 verbose=True 时输出到 stdout。"""
|
||||
@@ -26,7 +26,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
# _log_kv 会同时写入 actions.log 和输出到 stdout
|
||||
# 如果 verbose=False,我们需要控制 stdout 输出,但行为日志应该始终记录
|
||||
# 由于 _log_kv 的设计,我们暂时让它始终调用,确保行为日志有完整记录
|
||||
self._log_kv("阶段诊断", msg, **fields) # type: ignore[attr-defined]
|
||||
analyser._log_kv("阶段诊断", msg, **fields) # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
# 兜底:避免任何日志异常影响主流程
|
||||
pass
|
||||
@@ -34,7 +34,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
def _log_summary(msg: str, **fields):
|
||||
"""阶段诊断精简日志入口:始终输出,用于记录最终结果等关键信息。"""
|
||||
try:
|
||||
self._log_kv("阶段诊断", msg, **fields)
|
||||
analyser._log_kv("阶段诊断", msg, **fields)
|
||||
except Exception:
|
||||
# 兜底:避免任何日志异常影响主流程
|
||||
pass
|
||||
@@ -48,94 +48,190 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
msg = f"\n{char * 3} {title} {char * 3}\n"
|
||||
else:
|
||||
msg = f"\n{char * 10}\n"
|
||||
self._log_kv("阶段诊断", msg)
|
||||
analyser._log_kv("阶段诊断", msg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
diag_start = time.time()
|
||||
max_diag_time = getattr(self, "stage_diag_max_time", 10.0) # 最大诊断时间(可配置,默认10秒)
|
||||
max_step_time = getattr(self, "stage_diag_max_step_time", 2.0) # 每个步骤最大耗时(可配置,默认2秒)
|
||||
enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False)) # OCR模式1开关(二值化)
|
||||
max_diag_time = getattr(analyser, "stage_diag_max_time", 10.0) # 最大诊断时间(可配置,默认10秒)
|
||||
max_step_time = getattr(analyser, "stage_diag_max_step_time", 2.0) # 每个步骤最大耗时(可配置,默认2秒)
|
||||
enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False)) # OCR模式1开关(二值化)
|
||||
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
# 仅在详细模式下输出开始分隔符与起始信息
|
||||
_log_separator("开始阶段诊断")
|
||||
_log("开始阶段诊断", 最大诊断时间秒=max_diag_time, 单步最大耗时秒=max_step_time)
|
||||
|
||||
# ========== 步骤0:首先检测是否在直播间(最优先)==========
|
||||
# ========== 步骤0:首先执行并行检测(包括直播间图标检测)==========
|
||||
step_start = time.time()
|
||||
_log("步骤0[检测直播间]-开始", 说明="优先像素检测,然后模板匹配,最后OCR回退")
|
||||
_log("步骤0[并行检测]-开始", 说明="并行检测:直播间图标(像素检测-多边形区域白色像素)、优惠券、红包、抽奖结果、参与按钮、粉丝团、福袋详情")
|
||||
in_live_room = False
|
||||
live_room_score = 0.0
|
||||
detection_method = ""
|
||||
|
||||
# 第一步:优先使用像素检测
|
||||
# 获取像素检测阈值(用于判断置信度是否达到要求)
|
||||
pixel_threshold = float(getattr(self, "live_room_match_threshold", 0.8) or 0.8)
|
||||
pixel_threshold = float(getattr(analyser, "live_room_match_threshold", 0.8) or 0.8)
|
||||
if pixel_threshold < 0.0:
|
||||
pixel_threshold = 0.0
|
||||
if pixel_threshold > 1.0:
|
||||
pixel_threshold = 1.0
|
||||
|
||||
# ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)==========
|
||||
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
|
||||
# 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测
|
||||
pixel_state = {}
|
||||
pixel_details = {}
|
||||
pixel_detection_start = time.time()
|
||||
try:
|
||||
pixel_start = time.time()
|
||||
import os
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic_rgb = douyin_pixel._safe_open_screenshot_rgb(pic_path)
|
||||
if pic_rgb is not None:
|
||||
detected, confidence = douyin_pixel.detect_live_room_icons_by_pixel(pic_rgb)
|
||||
pixel_elapsed = (time.time() - pixel_start) * 1000
|
||||
# 使用 live_room_match_threshold 判断像素检测的置信度是否达到阈值
|
||||
if detected and confidence >= pixel_threshold:
|
||||
in_live_room = True
|
||||
live_room_score = float(confidence or 0.0)
|
||||
detection_method = "像素检测"
|
||||
_log(
|
||||
"步骤0[检测直播间]-命中(像素检测)",
|
||||
置信度=round(confidence, 3),
|
||||
阈值=pixel_threshold,
|
||||
耗时毫秒=pixel_elapsed,
|
||||
)
|
||||
result = analyser._read_pixel_stage_state(return_details=True)
|
||||
if isinstance(result, tuple):
|
||||
pixel_state, pixel_details = result
|
||||
else:
|
||||
pixel_state = result
|
||||
pixel_details = {}
|
||||
|
||||
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
|
||||
|
||||
# 从并行检测结果中获取直播间图标检测结果
|
||||
# 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间
|
||||
live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False))
|
||||
|
||||
# 获取检测分数(白色像素比例)
|
||||
pixel_confidence = 0.0
|
||||
if "has_live_room_pixel" in pixel_details:
|
||||
pixel_confidence = float(pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0)
|
||||
|
||||
# 如果像素检测通过(白色比例 >= 阈值),判定为在直播间
|
||||
if live_room_pixel_detected:
|
||||
in_live_room = True
|
||||
detection_method = "像素检测(多边形区域白色像素)"
|
||||
live_room_score = pixel_confidence # 白色像素比例即为置信度
|
||||
_log(
|
||||
"步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)",
|
||||
白色像素比例=round(pixel_confidence, 3),
|
||||
阈值=pixel_threshold,
|
||||
)
|
||||
else:
|
||||
# 像素检测未通过
|
||||
in_live_room = False
|
||||
detection_method = "像素检测未命中"
|
||||
_log(
|
||||
"步骤0[检测直播间]-像素检测未命中",
|
||||
白色像素比例=round(pixel_confidence, 3),
|
||||
阈值=pixel_threshold,
|
||||
)
|
||||
|
||||
if in_live_room:
|
||||
total_elapsed = (time.time() - step_start) * 1000
|
||||
_log("步骤0[检测直播间]-最终结果:在直播间", 检测方法=detection_method, 分数=live_room_score, 总耗时毫秒=total_elapsed)
|
||||
|
||||
# 记录每个检测步骤的详细信息
|
||||
for key, detail in pixel_details.items():
|
||||
step_name_map = {
|
||||
"has_coupon_bg": "优惠券背景",
|
||||
"has_redpacket_bg": "购物红包背景",
|
||||
"has_lucky_draw_result": "抽奖结果弹窗",
|
||||
"has_attend_button_red": "参与按钮红色区域",
|
||||
"has_fansclub_join_red": "粉丝团加入红色区域",
|
||||
"has_fudai_detail": "福袋详情页",
|
||||
"has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)",
|
||||
}
|
||||
step_name = step_name_map.get(key, key)
|
||||
detected = detail.get("detected", False)
|
||||
method = detail.get("method", "unknown")
|
||||
|
||||
log_fields = {
|
||||
"步骤": step_name,
|
||||
"检测结果": "命中" if detected else "未命中",
|
||||
"检测方法": method,
|
||||
}
|
||||
|
||||
# 添加分数信息
|
||||
if "template_score" in detail and detail["template_score"] is not None:
|
||||
log_fields["分数"] = round(detail["template_score"], 4)
|
||||
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
|
||||
# 对于像素检测,添加置信度信息
|
||||
if "confidence" in detail and detail["confidence"] is not None:
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["confidence"], 4)
|
||||
log_fields["置信度"] = round(detail["confidence"], 4)
|
||||
# 如果是三部分识别,显示平均分和区域结果
|
||||
if "avg_score" in detail and detail["avg_score"] is not None:
|
||||
log_fields["平均分"] = round(detail["avg_score"], 4)
|
||||
if "detected_parts" in detail and detail["detected_parts"]:
|
||||
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
|
||||
if "best_region" in detail and detail["best_region"]:
|
||||
log_fields["最佳区域"] = detail["best_region"]
|
||||
if "region_results" in detail and detail["region_results"]:
|
||||
region_scores = detail["region_results"]
|
||||
if isinstance(region_scores, dict):
|
||||
log_fields["区域分数"] = f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
|
||||
# 对于像素检测,red_ratio也作为分数显示
|
||||
if "red_ratio" in detail and detail["red_ratio"] is not None:
|
||||
log_fields["红色比例"] = round(detail["red_ratio"], 4)
|
||||
# 如果还没有分数,将red_ratio作为分数显示
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["red_ratio"], 4)
|
||||
# 显示阈值(无论是否为None都显示,方便调试)
|
||||
if "effective_threshold" in detail:
|
||||
threshold_val = detail["effective_threshold"]
|
||||
if threshold_val is not None:
|
||||
log_fields["阈值"] = round(threshold_val, 4)
|
||||
else:
|
||||
_log(
|
||||
"步骤0[检测直播间]-像素检测未命中",
|
||||
置信度=round(confidence, 3),
|
||||
阈值=pixel_threshold,
|
||||
耗时毫秒=pixel_elapsed,
|
||||
log_fields["阈值"] = "未设置"
|
||||
# 对于福袋详情页,额外显示配置的阈值(用于调试)
|
||||
if key == "has_fudai_detail":
|
||||
# 显示任务数量信息(无论是否为None都显示,便于调试)
|
||||
if "task_count" in detail:
|
||||
task_count_val = detail["task_count"]
|
||||
log_fields["任务数量"] = task_count_val
|
||||
# 如果任务数量存在但检测结果为False,记录警告
|
||||
if task_count_val is not None and task_count_val > 0 and not detected:
|
||||
try:
|
||||
_log( # type: ignore[misc]
|
||||
"警告:检测到任务数量但 has_fudai_detail 为 False",
|
||||
任务数量=task_count_val,
|
||||
detected=detected,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
log_fields["任务数量"] = "未获取"
|
||||
try:
|
||||
configured_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None) or
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
|
||||
)
|
||||
log_fields["配置阈值"] = round(configured_threshold, 4)
|
||||
except Exception:
|
||||
pass
|
||||
if "reason" in detail:
|
||||
log_fields["原因"] = detail["reason"]
|
||||
if "error" in detail:
|
||||
log_fields["错误"] = detail["error"]
|
||||
|
||||
_log(f"并行检测-{step_name}", **log_fields)
|
||||
|
||||
_log(
|
||||
"像素状态(并行检测完成)",
|
||||
耗时毫秒=pixel_detection_elapsed,
|
||||
直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)),
|
||||
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
|
||||
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
|
||||
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
|
||||
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
|
||||
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
|
||||
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
|
||||
)
|
||||
except Exception as e:
|
||||
pixel_elapsed = (time.time() - step_start) * 1000
|
||||
_log("步骤0[检测直播间]-像素检测异常", 耗时毫秒=pixel_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
|
||||
import traceback
|
||||
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
|
||||
_log("并行检测异常", 耗时毫秒=pixel_detection_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
|
||||
pixel_state = {}
|
||||
pixel_details = {}
|
||||
|
||||
# 第二步:如果像素检测失败,使用模板匹配
|
||||
if not in_live_room:
|
||||
try:
|
||||
template_start = time.time()
|
||||
detected, score = self._check_in_live_room_by_icon()
|
||||
template_elapsed = (time.time() - template_start) * 1000
|
||||
if detected:
|
||||
in_live_room = True
|
||||
live_room_score = float(score or 0.0)
|
||||
detection_method = "模板匹配"
|
||||
_log("步骤0[检测直播间]-命中(模板匹配)", 分数=live_room_score, 耗时毫秒=template_elapsed)
|
||||
else:
|
||||
_log("步骤0[检测直播间]-模板匹配未命中", 分数=live_room_score, 耗时毫秒=template_elapsed)
|
||||
except Exception as e:
|
||||
template_elapsed = (time.time() - step_start) * 1000
|
||||
_log("步骤0[检测直播间]-模板匹配异常", 耗时毫秒=template_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
|
||||
|
||||
if in_live_room:
|
||||
total_elapsed = (time.time() - step_start) * 1000
|
||||
_log("步骤0[检测直播间]-最终结果:在直播间", 检测方法=detection_method, 分数=live_room_score, 总耗时毫秒=total_elapsed)
|
||||
|
||||
# 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)
|
||||
# ========== 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)==========
|
||||
if not in_live_room:
|
||||
_log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
|
||||
|
||||
@@ -151,13 +247,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
_log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
self.cut_pic(400, 140, 900, 200, "", "推荐页标签栏")
|
||||
analyser.cut_pic(400, 140, 900, 200, "", "推荐页标签栏")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
t_recommend = str(self.operation.analyse_pic_word("推荐页标签栏", 0) or "")
|
||||
name0 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(analyser.operation.analyse_pic_word(name0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式0",
|
||||
@@ -170,7 +267,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
not t_recommend or ("推荐" not in t_recommend and "关注" not in t_recommend and "直播" not in t_recommend)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
t_recommend = str(self.operation.analyse_pic_word("推荐页标签栏", 1) or "")
|
||||
name1 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(analyser.operation.analyse_pic_word(name1, 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式1",
|
||||
@@ -206,13 +304,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
try:
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
self.cut_pic(658, 147, 765, 194, "", "关注列表标签")
|
||||
analyser.cut_pic(658, 147, 765, 194, "", "关注列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
t_follow = str(self.operation.analyse_pic_word("关注列表标签", 0) or "")
|
||||
namef0 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(analyser.operation.analyse_pic_word(namef0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-OCR模式0",
|
||||
@@ -223,7 +322,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
|
||||
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("关注" not in t_follow):
|
||||
ocr_start_1 = time.time()
|
||||
t_follow = str(self.operation.analyse_pic_word("关注列表标签", 1) or "")
|
||||
namef1 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(analyser.operation.analyse_pic_word(namef1, 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-OCR模式1",
|
||||
@@ -246,9 +346,9 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
识别文本=follow_text,
|
||||
)
|
||||
try:
|
||||
self._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
self._last_follow_list_title_text = ""
|
||||
analyser._last_follow_list_title_text = ""
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="FOLLOW_LIST",
|
||||
@@ -265,31 +365,33 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
try:
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
self.cut_pic(650, 145, 800, 195, "", "直播列表标签")
|
||||
analyser.cut_pic(650, 145, 800, 195, "", "直播列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
t_list = str(self.operation.analyse_pic_word("直播列表标签", 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
namel0 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(analyser.operation.analyse_pic_word(namel0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
|
||||
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("正在直播" not in t_list):
|
||||
ocr_start_1 = time.time()
|
||||
t_list = str(self.operation.analyse_pic_word("直播列表标签", 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("正在直播" not in t_list):
|
||||
ocr_start_1 = time.time()
|
||||
namel1 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(analyser.operation.analyse_pic_word(namel1, 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
_log("步骤3[OCR直播列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
|
||||
@@ -315,9 +417,9 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
|
||||
# 记录诊断时看到的"关注页标题"
|
||||
try:
|
||||
self._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
self._last_follow_list_title_text = ""
|
||||
analyser._last_follow_list_title_text = ""
|
||||
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
if elapsed_total > max_step_time * 1000:
|
||||
@@ -350,122 +452,9 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
|
||||
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
|
||||
|
||||
# ========== 在直播间:继续执行像素检测 ==========
|
||||
_log_separator("在直播间,继续执行像素检测")
|
||||
_log("在直播间,继续执行像素检测")
|
||||
|
||||
# ========== 第一步:基于同一张截图并行采集所有像素特征 ==========
|
||||
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
|
||||
pixel_state = {}
|
||||
pixel_details = {}
|
||||
pixel_detection_start = time.time()
|
||||
try:
|
||||
result = self._read_pixel_stage_state(return_details=True)
|
||||
if isinstance(result, tuple):
|
||||
pixel_state, pixel_details = result
|
||||
else:
|
||||
pixel_state = result
|
||||
pixel_details = {}
|
||||
|
||||
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
|
||||
|
||||
# 记录每个检测步骤的详细信息
|
||||
for key, detail in pixel_details.items():
|
||||
step_name_map = {
|
||||
"has_coupon_bg": "优惠券背景",
|
||||
"has_redpacket_bg": "购物红包背景",
|
||||
"has_lucky_draw_result": "抽奖结果弹窗",
|
||||
"has_attend_button_red": "参与按钮红色区域",
|
||||
"has_fansclub_join_red": "粉丝团加入红色区域",
|
||||
"has_fudai_detail": "福袋详情页",
|
||||
}
|
||||
step_name = step_name_map.get(key, key)
|
||||
detected = detail.get("detected", False)
|
||||
method = detail.get("method", "unknown")
|
||||
|
||||
log_fields = {
|
||||
"步骤": step_name,
|
||||
"检测结果": "命中" if detected else "未命中",
|
||||
"检测方法": method,
|
||||
}
|
||||
|
||||
# 添加分数信息
|
||||
if "template_score" in detail and detail["template_score"] is not None:
|
||||
log_fields["分数"] = round(detail["template_score"], 4)
|
||||
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
|
||||
# 如果是三部分识别,显示平均分和区域结果
|
||||
if "avg_score" in detail and detail["avg_score"] is not None:
|
||||
log_fields["平均分"] = round(detail["avg_score"], 4)
|
||||
if "detected_parts" in detail and detail["detected_parts"]:
|
||||
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
|
||||
if "best_region" in detail and detail["best_region"]:
|
||||
log_fields["最佳区域"] = detail["best_region"]
|
||||
if "region_results" in detail and detail["region_results"]:
|
||||
region_scores = detail["region_results"]
|
||||
if isinstance(region_scores, dict):
|
||||
log_fields["区域分数"] = f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
|
||||
# 对于像素检测,red_ratio也作为分数显示
|
||||
if "red_ratio" in detail and detail["red_ratio"] is not None:
|
||||
log_fields["红色比例"] = round(detail["red_ratio"], 4)
|
||||
# 如果还没有分数,将red_ratio作为分数显示
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["red_ratio"], 4)
|
||||
# 显示阈值(无论是否为None都显示,方便调试)
|
||||
if "effective_threshold" in detail:
|
||||
threshold_val = detail["effective_threshold"]
|
||||
if threshold_val is not None:
|
||||
log_fields["阈值"] = round(threshold_val, 4)
|
||||
else:
|
||||
log_fields["阈值"] = "未设置"
|
||||
# 对于福袋详情页,额外显示配置的阈值(用于调试)
|
||||
if key == "has_fudai_detail":
|
||||
# 显示任务数量信息(无论是否为None都显示,便于调试)
|
||||
if "task_count" in detail:
|
||||
task_count_val = detail["task_count"]
|
||||
log_fields["任务数量"] = task_count_val
|
||||
# 如果任务数量存在但检测结果为False,记录警告
|
||||
if task_count_val is not None and task_count_val > 0 and not detected:
|
||||
try:
|
||||
_log( # type: ignore[misc]
|
||||
"警告:检测到任务数量但 has_fudai_detail 为 False",
|
||||
任务数量=task_count_val,
|
||||
detected=detected,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
log_fields["任务数量"] = "未获取"
|
||||
try:
|
||||
configured_threshold = float(
|
||||
getattr(self, "fudai_detail_template_threshold", None) or
|
||||
getattr(self, "fudai_template_match_threshold", 0.7) or 0.7
|
||||
)
|
||||
log_fields["配置阈值"] = round(configured_threshold, 4)
|
||||
except Exception:
|
||||
pass
|
||||
if "reason" in detail:
|
||||
log_fields["原因"] = detail["reason"]
|
||||
if "error" in detail:
|
||||
log_fields["错误"] = detail["error"]
|
||||
|
||||
_log(f"并行检测-{step_name}", **log_fields)
|
||||
|
||||
_log(
|
||||
"像素状态(并行检测完成)",
|
||||
耗时毫秒=pixel_detection_elapsed,
|
||||
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
|
||||
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
|
||||
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
|
||||
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
|
||||
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
|
||||
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
|
||||
_log("像素状态读取异常", 耗时毫秒=pixel_detection_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
|
||||
pixel_state = {}
|
||||
pixel_details = {}
|
||||
# ========== 在直播间:继续执行像素检测结果处理 ==========
|
||||
_log_separator("在直播间,继续执行像素检测结果处理")
|
||||
_log("在直播间,继续执行像素检测结果处理")
|
||||
|
||||
# ========== 优先使用像素检测结果判断阶段(按优先级顺序)==========
|
||||
# 根据像素检测结果,按优先级返回阶段
|
||||
@@ -483,13 +472,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
# 检测抽奖结果文字区域 (300, 600)-(800, 800) - 扩大区域以覆盖"没有抽中福袋"文字
|
||||
if time.time() - step_result_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
self.cut_pic(300, 600, 800, 800, "", "抽奖结果")
|
||||
analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤1[检测抽奖结果弹窗]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_result_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
result_text = str(self.operation.analyse_pic_word("抽奖结果", 0) or "")
|
||||
name_res0 = preprocess_for_ocr(analyser, "抽奖结果")
|
||||
result_text = str(analyser.operation.analyse_pic_word(name_res0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤1[检测抽奖结果弹窗]-OCR模式0",
|
||||
@@ -500,7 +490,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
|
||||
if enable_ocr_mode1 and (time.time() - step_result_start < max_step_time) and (not result_text or ("没有抽中" not in result_text and "抽中福袋" not in result_text)):
|
||||
ocr_start_1 = time.time()
|
||||
result_text = str(self.operation.analyse_pic_word("抽奖结果", 1) or "")
|
||||
name_res1 = preprocess_for_ocr(analyser, "抽奖结果")
|
||||
result_text = str(analyser.operation.analyse_pic_word(name_res1, 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤1[检测抽奖结果弹窗]-OCR模式1",
|
||||
@@ -513,13 +504,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if result_text and ("没有抽中" in result_text or "抽中福袋" in result_text):
|
||||
if time.time() - step_result_start < max_step_time:
|
||||
cut_confirm_start = time.time()
|
||||
self.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
|
||||
analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
|
||||
cut_confirm_elapsed = (time.time() - cut_confirm_start) * 1000
|
||||
_log("步骤1[检测抽奖结果弹窗]-确认按钮截图完成", 耗时毫秒=cut_confirm_elapsed)
|
||||
|
||||
if time.time() - step_result_start < max_step_time:
|
||||
ocr_confirm_start = time.time()
|
||||
confirm_text = str(self.operation.analyse_pic_word("无奖励确认", 0) or "")
|
||||
name_confirm0 = preprocess_for_ocr(analyser, "无奖励确认")
|
||||
confirm_text = str(analyser.operation.analyse_pic_word(name_confirm0, 0) or "")
|
||||
ocr_confirm_elapsed = (time.time() - ocr_confirm_start) * 1000
|
||||
_log(
|
||||
"步骤1[检测抽奖结果弹窗]-确认按钮OCR模式0",
|
||||
@@ -566,13 +558,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
try:
|
||||
if time.time() - step_redpacket_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
self.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
|
||||
analyser.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_redpacket_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
redpacket_text = str(self.operation.analyse_pic_word("診斷購物紅包", 0) or "")
|
||||
name_rp = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(analyser.operation.analyse_pic_word(name_rp, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR模式0",
|
||||
@@ -630,7 +623,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
# 确保 detail_task_count 不是 None 时才保存
|
||||
if detail_task_count is not None:
|
||||
try:
|
||||
self._fudai_detail_task_count_from_stage = detail_task_count
|
||||
analyser._fudai_detail_task_count_from_stage = detail_task_count
|
||||
try:
|
||||
_log( # type: ignore[misc]
|
||||
"保存任务数量到 analyser 对象",
|
||||
@@ -678,10 +671,10 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
|
||||
# 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间
|
||||
# 暂时禁用:将默认值改为 False
|
||||
enable_invite_redpacket_ocr = bool(getattr(self, "enable_invite_redpacket_ocr", False))
|
||||
template_match_score_threshold = float(getattr(self, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4)
|
||||
enable_invite_redpacket_ocr = bool(getattr(analyser, "enable_invite_redpacket_ocr", False))
|
||||
template_match_score_threshold = float(getattr(analyser, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4)
|
||||
# 获取模板匹配分数(如果存在),用于判断是否跳过OCR
|
||||
template_match_score = float(getattr(self, "_last_template_match_score", 0.0) or 0.0)
|
||||
template_match_score = float(getattr(analyser, "_last_template_match_score", 0.0) or 0.0)
|
||||
should_skip_redpacket_ocr = (not detail_detected and template_match_score > 0 and template_match_score < template_match_score_threshold)
|
||||
|
||||
if should_skip_redpacket_ocr:
|
||||
@@ -696,14 +689,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
step_ocr_redpacket_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
# 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待
|
||||
ocr_max_step_time = float(getattr(self, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0)
|
||||
ocr_max_step_time = float(getattr(analyser, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0)
|
||||
if remaining_time_before > ocr_max_step_time:
|
||||
try:
|
||||
_log("步骤1.5[OCR检测邀你抢红包]-开始", 剩余时间秒=remaining_time_before, 说明="在指定区域检测邀你抢红包文字")
|
||||
|
||||
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
|
||||
cut_start = time.time()
|
||||
y_pianyi = int(getattr(self, "y_pianyi", 0) or 0)
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
# 保存完整截图并标注OCR区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
@@ -718,8 +711,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
pic_rgb = pic.convert("RGB")
|
||||
|
||||
width, height = pic_rgb.size
|
||||
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
|
||||
x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545
|
||||
x1 = int(x1_base * width / rx)
|
||||
@@ -753,13 +746,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.cut_pic(238, 454, 847, 545, "", "阶段诊断邀你抢红包区域", y_pianyi)
|
||||
analyser.cut_pic(238, 454, 847, 545, "", "阶段诊断邀你抢红包区域", y_pianyi)
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
|
||||
ocr_start = time.time()
|
||||
ocr_text = str(self.operation.analyse_pic_word("阶段诊断邀你抢红包区域", 0) or "")
|
||||
name_red0 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域")
|
||||
ocr_text = str(analyser.operation.analyse_pic_word(name_red0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤1.5[OCR检测邀你抢红包]-OCR模式0",
|
||||
@@ -769,10 +763,11 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
)
|
||||
|
||||
# 如果模式0未识别到,尝试模式1
|
||||
enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False))
|
||||
enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False))
|
||||
if enable_ocr_mode1 and (not ocr_text or not any(kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气"))):
|
||||
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
|
||||
ocr_text = str(self.operation.analyse_pic_word("阶段诊断邀你抢红包区域", 1) or "")
|
||||
name_red1 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域")
|
||||
ocr_text = str(analyser.operation.analyse_pic_word(name_red1, 1) or "")
|
||||
_log(
|
||||
"步骤1.5[OCR检测邀你抢红包]-OCR模式1",
|
||||
文本长度=len(ocr_text),
|
||||
@@ -824,7 +819,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
self.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
|
||||
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
@@ -834,8 +829,10 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if enable_ocr_mode1:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mode0 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 0)
|
||||
future_mode1 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 1)
|
||||
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode0 = executor.submit(analyser.operation.analyse_pic_word, name_part0, 0)
|
||||
name_part1 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode1 = executor.submit(analyser.operation.analyse_pic_word, name_part1, 1)
|
||||
text_mode0 = str(future_mode0.result() or "")
|
||||
text_mode1 = str(future_mode1.result() or "")
|
||||
# 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1
|
||||
@@ -855,7 +852,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
else:
|
||||
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
pname = preprocess_for_ocr(analyser, "参与按钮")
|
||||
coupon_text = str(analyser.operation.analyse_pic_word(pname, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
|
||||
@@ -888,13 +886,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
self.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
|
||||
analyser.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
redpacket_text = str(self.operation.analyse_pic_word("診斷購物紅包", 0) or "")
|
||||
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(analyser.operation.analyse_pic_word(name_rp2, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
|
||||
@@ -951,5 +950,4 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
原因="像素检测未命中,默认直播间",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
|
||||
return "IN_LIVE_ROOM", "像素检测未命中,默认直播间"
|
||||
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
|
||||
@@ -141,10 +141,14 @@ class StageHandler:
|
||||
return False, 0.0
|
||||
|
||||
try:
|
||||
# 同时读取灰度图和彩色图,灰度图用于模板匹配,彩色图用于颜色特征过滤
|
||||
img = cv2.imread( # type: ignore[attr-defined]
|
||||
screenshot_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined]
|
||||
)
|
||||
if img is None:
|
||||
img_color = cv2.imread( # type: ignore[attr-defined]
|
||||
screenshot_path, cv2.IMREAD_COLOR # type: ignore[attr-defined]
|
||||
)
|
||||
if img is None or img_color is None:
|
||||
raise RuntimeError("cv2.imread 返回 None")
|
||||
except Exception as e:
|
||||
try:
|
||||
@@ -163,14 +167,51 @@ class StageHandler:
|
||||
threshold = max(0.0, min(1.0, threshold))
|
||||
template_threshold = max(0.0, min(1.0, template_threshold))
|
||||
|
||||
# 第一步:裁剪右上角图标区域
|
||||
# 第一步:裁剪右上角图标区域(使用固定坐标,基于1080x2400基准分辨率)
|
||||
# 直播间图标区域:(972, 147) 到 (1047, 216) - 与像素检测区域一致
|
||||
ih, iw = img.shape[:2]
|
||||
roi_x1 = max(0, int(iw * 0.60))
|
||||
roi_y1 = 0
|
||||
roi_x2 = iw
|
||||
roi_y2 = min(ih, int(ih * 0.40))
|
||||
|
||||
# 基准分辨率
|
||||
base_width = 1080
|
||||
base_height = 2400
|
||||
|
||||
# 固定坐标(基于1080x2400)
|
||||
base_x1 = 972
|
||||
base_y1 = 147
|
||||
base_x2 = 1047
|
||||
base_y2 = 216
|
||||
|
||||
# 缩放坐标到实际分辨率
|
||||
scale_x = iw / base_width
|
||||
scale_y = ih / base_height
|
||||
|
||||
roi_x1 = max(0, int(base_x1 * scale_x))
|
||||
roi_y1 = max(0, int(base_y1 * scale_y))
|
||||
roi_x2 = min(iw, int(base_x2 * scale_x))
|
||||
roi_y2 = min(ih, int(base_y2 * scale_y))
|
||||
|
||||
# 确保区域有效
|
||||
if roi_x1 >= roi_x2 or roi_y1 >= roi_y2:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", "_check_in_live_room_by_icon ROI区域无效",
|
||||
roi_x1=roi_x1, roi_y1=roi_y1, roi_x2=roi_x2, roi_y2=roi_y2,
|
||||
img_width=iw, img_height=ih
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
roi = img[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index]
|
||||
|
||||
# 同步裁剪彩色 ROI,用于后续颜色特征检测(白色比例等)
|
||||
roi_color = None
|
||||
try:
|
||||
if img_color is not None:
|
||||
roi_color = img_color[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index]
|
||||
except Exception:
|
||||
roi_color = None
|
||||
|
||||
if roi.size == 0:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -214,6 +255,22 @@ class StageHandler:
|
||||
best_name = ""
|
||||
detected = False
|
||||
|
||||
# 预计算颜色特征:白色像素比例(仅对 x 图标有效,用于过滤推荐页等误判)
|
||||
# 直播间关闭 x 一般是“白色 x + 略暗背景”,因此需要一定的白色比例
|
||||
x_white_ratio = None
|
||||
if roi_color is not None:
|
||||
try:
|
||||
roi_gray_for_white = cv2.cvtColor(roi_color, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined]
|
||||
# 阈值 210:偏亮即视为白色像素
|
||||
_, white_bin = cv2.threshold( # type: ignore[attr-defined]
|
||||
roi_gray_for_white, 210, 255, cv2.THRESH_BINARY # type: ignore[attr-defined]
|
||||
)
|
||||
white_pixels = float((white_bin == 255).sum())
|
||||
total_pixels = float(white_bin.size or 1.0)
|
||||
x_white_ratio = max(0.0, min(1.0, white_pixels / total_pixels))
|
||||
except Exception:
|
||||
x_white_ratio = None
|
||||
|
||||
for template_path, roi_path, icon_name in template_roi_pairs:
|
||||
try:
|
||||
# 调试日志:检查文件存在性
|
||||
@@ -281,35 +338,301 @@ class StageHandler:
|
||||
if tpl is None or roi_img is None:
|
||||
continue
|
||||
|
||||
th, tw = tpl.shape[:2]
|
||||
rh, rw = roi_img.shape[:2]
|
||||
# 图像预处理:根据图标类型选择不同的预处理方法
|
||||
# x图标:使用二值化+边缘检测(提高匹配准确性)
|
||||
# xin图标:使用直方图均衡化(保持原有方法)
|
||||
if icon_name == "x":
|
||||
try:
|
||||
# x图标特点:白色x在深灰色背景上,对比度明显
|
||||
# 方法1:固定阈值二值化(针对白色x和深灰背景,阈值约160-180)
|
||||
# 先尝试多个阈值,选择最佳
|
||||
best_binary_score = 0.0
|
||||
best_binary_thresh = 160
|
||||
roi_binary_fixed = None
|
||||
tpl_binary_fixed = None
|
||||
|
||||
for thresh_val in [140, 160, 180, 200]:
|
||||
try:
|
||||
_, roi_bin = cv2.threshold(roi_img, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined]
|
||||
_, tpl_bin = cv2.threshold(tpl, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined]
|
||||
# 快速测试分数
|
||||
res_test = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED) # type: ignore[attr-defined]
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res_test) # type: ignore[attr-defined]
|
||||
if max_val > best_binary_score:
|
||||
best_binary_score = max_val
|
||||
best_binary_thresh = thresh_val
|
||||
roi_binary_fixed = roi_bin
|
||||
tpl_binary_fixed = tpl_bin
|
||||
except:
|
||||
continue
|
||||
|
||||
# 方法2:自适应二值化(调整参数,blockSize使用较小值以提高精度)
|
||||
roi_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined]
|
||||
roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined]
|
||||
)
|
||||
tpl_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined]
|
||||
tpl, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined]
|
||||
)
|
||||
|
||||
# 方法3:Otsu二值化(全局阈值)
|
||||
_, roi_binary_otsu = cv2.threshold(roi_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined]
|
||||
_, tpl_binary_otsu = cv2.threshold(tpl, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined]
|
||||
|
||||
# 方法4:边缘检测(Canny,针对白色x和深灰背景,调整参数)
|
||||
roi_edges = cv2.Canny(roi_img, 50, 150) # type: ignore[attr-defined]
|
||||
tpl_edges = cv2.Canny(tpl, 50, 150) # type: ignore[attr-defined]
|
||||
|
||||
# 方法5:边缘检测(更激进的参数,检测更多边缘)
|
||||
roi_edges_aggressive = cv2.Canny(roi_img, 30, 80) # type: ignore[attr-defined]
|
||||
tpl_edges_aggressive = cv2.Canny(tpl, 30, 80) # type: ignore[attr-defined]
|
||||
|
||||
# 方法6:形态学处理(去除噪声,增强边缘)
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # type: ignore[attr-defined]
|
||||
roi_edges_morph = cv2.morphologyEx(roi_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined]
|
||||
tpl_edges_morph = cv2.morphologyEx(tpl_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined]
|
||||
|
||||
# 使用固定阈值二值化图像作为主要匹配图像(针对白色x和深灰背景优化)
|
||||
if roi_binary_fixed is not None and tpl_binary_fixed is not None:
|
||||
roi_img_enhanced = roi_binary_fixed
|
||||
tpl_enhanced = tpl_binary_fixed
|
||||
else:
|
||||
# 回退到自适应二值化
|
||||
roi_img_enhanced = roi_binary_adaptive
|
||||
tpl_enhanced = tpl_binary_adaptive
|
||||
|
||||
# 保存所有预处理图像用于多方法匹配
|
||||
roi_binary_adaptive_backup = roi_binary_adaptive
|
||||
tpl_binary_adaptive_backup = tpl_binary_adaptive
|
||||
roi_binary_otsu_backup = roi_binary_otsu
|
||||
tpl_binary_otsu_backup = tpl_binary_otsu
|
||||
roi_edges_backup = roi_edges
|
||||
tpl_edges_backup = tpl_edges
|
||||
roi_edges_aggressive_backup = roi_edges_aggressive
|
||||
tpl_edges_aggressive_backup = tpl_edges_aggressive
|
||||
roi_edges_morph_backup = roi_edges_morph
|
||||
tpl_edges_morph_backup = tpl_edges_morph
|
||||
|
||||
# 方法7:强对比度增强(针对实际测试中表现较好的配置)
|
||||
roi_contrast = cv2.convertScaleAbs(roi_img_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined]
|
||||
tpl_contrast = cv2.convertScaleAbs(tpl_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined]
|
||||
roi_contrast_backup = roi_contrast
|
||||
tpl_contrast_backup = tpl_contrast
|
||||
roi_edges_morph_backup = roi_edges_morph
|
||||
tpl_edges_morph_backup = tpl_edges_morph
|
||||
|
||||
use_edges = True
|
||||
except Exception:
|
||||
roi_img_enhanced = roi_img
|
||||
tpl_enhanced = tpl
|
||||
use_edges = False
|
||||
else:
|
||||
try:
|
||||
roi_img_enhanced = cv2.equalizeHist(roi_img) # type: ignore[attr-defined]
|
||||
tpl_enhanced = cv2.equalizeHist(tpl) # type: ignore[attr-defined]
|
||||
use_edges = False
|
||||
except Exception:
|
||||
roi_img_enhanced = roi_img
|
||||
tpl_enhanced = tpl
|
||||
use_edges = False
|
||||
|
||||
th, tw = tpl_enhanced.shape[:2]
|
||||
rh, rw = roi_img_enhanced.shape[:2]
|
||||
|
||||
# 模板必须小于或等于ROI
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale <= 0:
|
||||
continue
|
||||
tpl = cv2.resize( # type: ignore[attr-defined]
|
||||
tpl, (max(1, int(tw * scale)), max(1, int(th * scale)))
|
||||
tpl_enhanced = cv2.resize(
|
||||
tpl_enhanced, (max(1, int(tw * scale)), max(1, int(th * scale)))
|
||||
)
|
||||
th, tw = tpl.shape[:2]
|
||||
th, tw = tpl_enhanced.shape[:2]
|
||||
|
||||
# 在ROI中匹配模板
|
||||
res = cv2.matchTemplate( # type: ignore[attr-defined]
|
||||
roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined]
|
||||
)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc( # type: ignore[attr-defined]
|
||||
res
|
||||
)
|
||||
if icon_name == "x" and use_edges:
|
||||
try:
|
||||
tpl_binary_adaptive_backup = cv2.resize(tpl_binary_adaptive_backup, (max(1, int(tw)), max(1, int(th))))
|
||||
tpl_binary_otsu_backup = cv2.resize(tpl_binary_otsu_backup, (max(1, int(tw)), max(1, int(th))))
|
||||
tpl_edges_backup = cv2.resize(tpl_edges_backup, (max(1, int(tw)), max(1, int(th))))
|
||||
tpl_edges_aggressive_backup = cv2.resize(tpl_edges_aggressive_backup, (max(1, int(tw)), max(1, int(th))))
|
||||
tpl_edges_morph_backup = cv2.resize(tpl_edges_morph_backup, (max(1, int(tw)), max(1, int(th))))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if max_val > best_score:
|
||||
# 多方法模板匹配,取最高分(提高稳定性)
|
||||
scores = []
|
||||
|
||||
if icon_name == "x" and use_edges:
|
||||
try:
|
||||
res1_fixed = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1_fixed)
|
||||
scores.append(("TM_CCOEFF_NORMED_固定阈值二值化", float(max_val1 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res2_adaptive = cv2.matchTemplate(roi_binary_adaptive_backup, tpl_binary_adaptive_backup, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2_adaptive)
|
||||
scores.append(("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res3_otsu = cv2.matchTemplate(roi_binary_otsu_backup, tpl_binary_otsu_backup, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3_otsu)
|
||||
scores.append(("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res4_edges = cv2.matchTemplate(roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc(res4_edges)
|
||||
scores.append(("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res5_edges_agg = cv2.matchTemplate(roi_edges_aggressive_backup, tpl_edges_aggressive_backup, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc(res5_edges_agg)
|
||||
scores.append(("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res6_morph = cv2.matchTemplate(roi_edges_morph_backup, tpl_edges_morph_backup, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc(res6_morph)
|
||||
scores.append(("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res7_contrast = cv2.matchTemplate(roi_contrast_backup, tpl_contrast_backup, cv2.TM_CCORR_NORMED)
|
||||
_min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc(res7_contrast)
|
||||
scores.append(("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res8_original = cv2.matchTemplate(roi_img, tpl, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc(res8_original)
|
||||
scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
res1 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1)
|
||||
scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res2 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED)
|
||||
_min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2)
|
||||
scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
res3 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED)
|
||||
min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3)
|
||||
score3 = 1.0 - float(min_val3 or 0.0)
|
||||
scores.append(("TM_SQDIFF_NORMED", score3))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 选择最高分(如果多个方法都可用,使用加权平均)
|
||||
if scores:
|
||||
if icon_name == "x" and use_edges:
|
||||
max_val = 0.0
|
||||
best_method = ""
|
||||
ccoeff_scores = [(m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m]
|
||||
ccoeff_max = max(ccoeff_scores, key=lambda x: x[1]) if ccoeff_scores else None
|
||||
ccorr_scores = [(m, s) for m, s in scores if "TM_CCORR_NORMED" in m]
|
||||
ccorr_max = max(ccorr_scores, key=lambda x: x[1]) if ccorr_scores else None
|
||||
if ccoeff_max and ccoeff_max[1] >= 0.50:
|
||||
best_method, max_val = ccoeff_max
|
||||
elif ccorr_max and ccorr_max[1] >= 0.75:
|
||||
best_method, max_val = ccorr_max
|
||||
elif ccoeff_max:
|
||||
best_method, max_val = ccoeff_max
|
||||
elif ccorr_max:
|
||||
best_method, max_val = ccorr_max
|
||||
else:
|
||||
best_method, max_val = max(scores, key=lambda x: x[1])
|
||||
|
||||
if len(scores) >= 2:
|
||||
sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True)
|
||||
top_score = sorted_scores[0][1]
|
||||
second_score = sorted_scores[1][1]
|
||||
if top_score - second_score > 0.15:
|
||||
max_val = top_score
|
||||
best_method = sorted_scores[0][0]
|
||||
else:
|
||||
ccoeff_scores = [s for s in sorted_scores if "TM_CCOEFF_NORMED" in s[0]]
|
||||
if len(ccoeff_scores) >= 2:
|
||||
max_val = ccoeff_scores[0][1] * 0.7 + ccoeff_scores[1][1] * 0.3
|
||||
best_method = f"{ccoeff_scores[0][0]}+{ccoeff_scores[1][0]}_加权"
|
||||
elif len(ccoeff_scores) >= 1:
|
||||
max_val = ccoeff_scores[0][1] * 0.7 + second_score * 0.3
|
||||
best_method = f"{ccoeff_scores[0][0]}+{sorted_scores[1][0]}_加权"
|
||||
else:
|
||||
binary_scores = [s for s in sorted_scores if "二值化" in s[0]]
|
||||
if len(binary_scores) >= 2:
|
||||
max_val = binary_scores[0][1] * 0.7 + binary_scores[1][1] * 0.3
|
||||
best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权"
|
||||
else:
|
||||
max_val = top_score * 0.7 + second_score * 0.3
|
||||
best_method = f"{sorted_scores[0][0]}+{sorted_scores[1][0]}_加权"
|
||||
elif len(scores) == 1:
|
||||
best_method, max_val = scores[0]
|
||||
else:
|
||||
max_val = 0.0
|
||||
best_method = ""
|
||||
for method, score in scores:
|
||||
if method == "TM_CCOEFF_NORMED":
|
||||
max_val = score
|
||||
best_method = method
|
||||
break
|
||||
elif score > max_val:
|
||||
max_val = score
|
||||
best_method = method
|
||||
if best_method == "" and scores:
|
||||
best_method, max_val = max(scores, key=lambda x: x[1])
|
||||
if len(scores) > 1:
|
||||
weighted_sum = 0.0
|
||||
total_weight = 0.0
|
||||
for method, score in scores:
|
||||
if method == "TM_CCOEFF_NORMED":
|
||||
weight = 0.5
|
||||
else:
|
||||
weight = 0.25
|
||||
weighted_sum += score * weight
|
||||
total_weight += weight
|
||||
if total_weight > 0:
|
||||
max_val = weighted_sum / total_weight
|
||||
else:
|
||||
res = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
max_val = float(max_val or 0.0)
|
||||
best_method = "TM_CCOEFF_NORMED"
|
||||
|
||||
passed_color_filter = True
|
||||
if icon_name == "x" and x_white_ratio is not None:
|
||||
if x_white_ratio < 0.05 or x_white_ratio > 0.25:
|
||||
passed_color_filter = False
|
||||
elif 0.10 <= x_white_ratio <= 0.15:
|
||||
if "TM_CCORR_NORMED" in best_method:
|
||||
if max_val < 0.82:
|
||||
passed_color_filter = False
|
||||
else:
|
||||
if max_val < 0.50:
|
||||
passed_color_filter = False
|
||||
|
||||
if max_val > best_score and passed_color_filter:
|
||||
best_score = float(max_val or 0.0)
|
||||
best_name = (
|
||||
f"assets/{icon_name}.png -> "
|
||||
f"ocr/{'xx' if icon_name == 'x' else 'xxin'}.png"
|
||||
)
|
||||
best_name = f"assets/{icon_name}.png -> ocr/{'xx' if icon_name == 'x' else 'xxin'}.png (方法:{best_method})"
|
||||
|
||||
if max_val >= template_threshold:
|
||||
if max_val >= template_threshold and passed_color_filter:
|
||||
detected = True
|
||||
except Exception:
|
||||
continue
|
||||
@@ -327,8 +650,11 @@ class StageHandler:
|
||||
"阶段诊断",
|
||||
"_check_in_live_room_by_icon 结果",
|
||||
detected=int(bool(detected)),
|
||||
score=round(best_score, 3),
|
||||
score=round(best_score, 4),
|
||||
template=best_name or "-",
|
||||
threshold=round(template_threshold, 4),
|
||||
白色比例=x_white_ratio if x_white_ratio is not None else -1.0,
|
||||
说明="已优化:使用直方图均衡化+多方法匹配+固定ROI区域+颜色过滤",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -343,8 +669,6 @@ class StageHandler:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
# 这个方法非常长,直接调用原方法,保持兼容性
|
||||
# 注意:由于方法过于复杂(900+行),暂时保持原实现
|
||||
# 后续可以进一步拆分
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
@@ -355,11 +679,8 @@ class StageHandler:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
start_time = time.time()
|
||||
# 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别)
|
||||
try:
|
||||
already_verified = bool(
|
||||
getattr(analyser, "_fudai_detail_verified", False) or False
|
||||
)
|
||||
already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False)
|
||||
if already_verified:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -368,7 +689,6 @@ class StageHandler:
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 直接调用详情处理逻辑,不查找福袋
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -383,12 +703,8 @@ class StageHandler:
|
||||
# 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情
|
||||
try:
|
||||
now_ts = time.time()
|
||||
focus_until = float(
|
||||
getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0
|
||||
)
|
||||
queue_full_waiting = bool(
|
||||
getattr(analyser, "queue_full_waiting_at_earliest", False) or False
|
||||
)
|
||||
focus_until = float(getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0)
|
||||
queue_full_waiting = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False)
|
||||
|
||||
if focus_until > 0 and now_ts < focus_until and queue_full_waiting:
|
||||
if analyser.reservations and len(analyser.reservations) > 0:
|
||||
@@ -396,19 +712,10 @@ class StageHandler:
|
||||
try:
|
||||
ft = float(earliest.get("future_ts") or 0.0)
|
||||
if ft > 0:
|
||||
join_ahead = float(
|
||||
getattr(
|
||||
analyser, "high_value_fudai_join_ahead_seconds", 120
|
||||
)
|
||||
or 120
|
||||
)
|
||||
poll_before = float(
|
||||
getattr(analyser, "poll_before_open_seconds", 10.0)
|
||||
or 10.0
|
||||
)
|
||||
join_ahead = float(getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120)
|
||||
poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0)
|
||||
time_window_start_ts = ft - join_ahead
|
||||
time_window_end_ts = ft + max(0.0, poll_before)
|
||||
|
||||
if now_ts < time_window_start_ts:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -417,9 +724,7 @@ class StageHandler:
|
||||
focus_until=int(focus_until),
|
||||
now_ts=int(now_ts),
|
||||
time_window_start=int(time_window_start_ts),
|
||||
remain_seconds=int(
|
||||
time_window_start_ts - now_ts
|
||||
),
|
||||
remain_seconds=int(time_window_start_ts - now_ts),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -438,12 +743,10 @@ class StageHandler:
|
||||
room_pos_ref: List[int] = [0]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref)
|
||||
if not opened:
|
||||
# 无福袋,交给 flow_control 的"无福袋处理"逻辑
|
||||
try:
|
||||
needswitch_cfg = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch_cfg = True
|
||||
|
||||
wait_times_ref = [0]
|
||||
swipe_times_ref = [0]
|
||||
reservation_focus_until_ts_ref = [0.0]
|
||||
@@ -477,7 +780,6 @@ class StageHandler:
|
||||
)
|
||||
return
|
||||
|
||||
# 成功打开详情:调用同一套详情处理逻辑
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -485,4 +787,3 @@ class StageHandler:
|
||||
"_handle_live_room_has_or_not_fudai完成(成功打开详情)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -170,6 +170,11 @@ class ConfigManager:
|
||||
config["reservation_back_verify_enabled"]
|
||||
)
|
||||
|
||||
if "record_room_title_mapping_enabled" in config:
|
||||
analyser.record_room_title_mapping_enabled = bool(
|
||||
config["record_room_title_mapping_enabled"]
|
||||
)
|
||||
|
||||
if "reservation_back_swipe_delay" in config:
|
||||
analyser.reservation_back_swipe_delay = float(
|
||||
config["reservation_back_swipe_delay"] or 0.6
|
||||
|
||||
@@ -15,6 +15,7 @@ from __future__ import annotations
|
||||
import os
|
||||
import time
|
||||
import shutil
|
||||
import json
|
||||
from typing import Any, Optional, Tuple, Dict, Union
|
||||
from datetime import datetime
|
||||
|
||||
@@ -25,7 +26,7 @@ from douyin.handlers import douyin_screenshot_handler
|
||||
class HelperFunctions:
|
||||
"""工具函数集合:通用工具方法"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
@staticmethod
|
||||
def click(analyser: Any, x: int, y: int) -> None:
|
||||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。
|
||||
|
||||
@@ -39,7 +40,7 @@ class HelperFunctions:
|
||||
analyser.operation.click(analyser.device_id, int(x), int(y))
|
||||
elapsed = time.time() - start_time
|
||||
if elapsed > 0.1: # 只记录耗时较长的点击操作
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
analyser._log_kv(
|
||||
"操作",
|
||||
"点击操作",
|
||||
x=int(x),
|
||||
@@ -113,14 +114,16 @@ class HelperFunctions:
|
||||
None - 未识别到相关文本
|
||||
"""
|
||||
try:
|
||||
# OCR区域:(175, 1267) 到 (890, 1377)
|
||||
# OCR区域:(175, 1200) 到 (890, 1377) - 向上扩展了识别区域
|
||||
# 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures)
|
||||
douyin_screenshot_handler.ScreenshotHandler.cut_pic(
|
||||
analyser, 175, 1267, 890, 1377, "", "开奖结果按钮", 0
|
||||
analyser, 175, 1200, 890, 1377, "", "开奖结果按钮", 0
|
||||
)
|
||||
|
||||
# OCR识别
|
||||
ocr_text = str(analyser.operation.analyse_pic_word("开奖结果按钮", 0) or "")
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
name_res = preprocess_for_ocr(analyser, "开奖结果按钮")
|
||||
ocr_text = str(analyser.operation.analyse_pic_word(name_res, 0) or "")
|
||||
|
||||
analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text) # type: ignore[attr-defined]
|
||||
|
||||
@@ -132,6 +135,18 @@ class HelperFunctions:
|
||||
or "领取奖品" in ocr_text
|
||||
or "立即领取" in ocr_text
|
||||
):
|
||||
# 检查是否为误识别(检查相似字记录)
|
||||
if HelperFunctions._is_false_positive_prize_text(ocr_text):
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "识别到相似字,判定为误识别", text=ocr_text
|
||||
)
|
||||
return None
|
||||
# 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查
|
||||
if ocr_text.strip() != "立即领取奖品":
|
||||
HelperFunctions._save_false_positive(ocr_text)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "记录相似字文本", text=ocr_text
|
||||
)
|
||||
return "立即领取奖品"
|
||||
else:
|
||||
# 尝试模式1识别
|
||||
@@ -145,6 +160,18 @@ class HelperFunctions:
|
||||
or "领取奖品" in ocr_text_1
|
||||
or "立即领取" in ocr_text_1
|
||||
):
|
||||
# 检查是否为误识别(检查相似字记录)
|
||||
if HelperFunctions._is_false_positive_prize_text(ocr_text_1):
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "识别到相似字,判定为误识别", text=ocr_text_1
|
||||
)
|
||||
return None
|
||||
# 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查
|
||||
if ocr_text_1.strip() != "立即领取奖品":
|
||||
HelperFunctions._save_false_positive(ocr_text_1)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "记录相似字文本", text=ocr_text_1
|
||||
)
|
||||
return "立即领取奖品"
|
||||
|
||||
return None
|
||||
@@ -152,6 +179,60 @@ class HelperFunctions:
|
||||
analyser._log_kv("开奖结果", "OCR识别异常", error=str(e)) # type: ignore[attr-defined]
|
||||
return None
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _get_false_positive_file_path() -> str:
|
||||
"""获取误识别记录文件路径"""
|
||||
try:
|
||||
import path_config
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
except Exception:
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_dir = os.path.join(base_dir, "pic")
|
||||
false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json")
|
||||
return false_positive_file
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _load_false_positives() -> set[str]:
|
||||
"""加载误识别文本记录"""
|
||||
false_positive_file = HelperFunctions._get_false_positive_file_path()
|
||||
if not os.path.exists(false_positive_file):
|
||||
return set()
|
||||
try:
|
||||
with open(false_positive_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return set(data.get("false_positives", []))
|
||||
except Exception:
|
||||
return set()
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _save_false_positive(text: str) -> None:
|
||||
"""保存误识别文本到记录文件"""
|
||||
false_positive_file = HelperFunctions._get_false_positive_file_path()
|
||||
os.makedirs(os.path.dirname(false_positive_file), exist_ok=True)
|
||||
|
||||
false_positives = HelperFunctions._load_false_positives()
|
||||
false_positives.add(text.strip())
|
||||
|
||||
try:
|
||||
with open(false_positive_file, "w", encoding="utf-8") as f:
|
||||
json.dump({"false_positives": list(false_positives)}, f, ensure_ascii=False, indent=2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _is_false_positive_prize_text(text: str) -> bool:
|
||||
"""检查文本是否为误识别的"立即领取奖品"相似字"""
|
||||
false_positives = HelperFunctions._load_false_positives()
|
||||
text_clean = text.strip()
|
||||
# 检查是否在误识别列表中
|
||||
if text_clean in false_positives:
|
||||
return True
|
||||
# 检查是否包含误识别文本
|
||||
for fp_text in false_positives:
|
||||
if fp_text in text_clean or text_clean in fp_text:
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def handle_lottery_result_by_ocr(analyser: Any, result_type: str) -> None:
|
||||
"""根据OCR识别结果处理开奖结果。
|
||||
@@ -166,9 +247,9 @@ class HelperFunctions:
|
||||
# 识别到"我知道了",点击按钮,切换下一个直播间
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
# 按钮位置在OCR区域中心附近 (175+890)/2=532, (1267+1377)/2=1322
|
||||
# 按钮位置在OCR区域中心附近 (175+890)/2=532, (1200+1377)/2=1288.5≈1289
|
||||
btn_x = int(532 * rx // 1080)
|
||||
btn_y = int(1322 * ry // 2400)
|
||||
btn_y = int(1289 * ry // 2400)
|
||||
|
||||
analyser.operation.click(analyser.device_id, btn_x, btn_y)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -311,4 +392,4 @@ class HelperFunctions:
|
||||
tag, f"{msg} - 异常: {type(e).__name__}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
pass
|
||||
@@ -0,0 +1,70 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
OCR 预处理工具
|
||||
提供统一的图像预处理流水线:灰度、放大、自动对比、锐化等,以提高 OCR 识别稳定性。
|
||||
接口尽量简单:preprocess_for_ocr(analyser, cut_pic_name) -> 返回用于 OCR 的图片名称(不含扩展名)。
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
import os
|
||||
|
||||
def preprocess_for_ocr(analyser: Any, cut_pic_name: str) -> str:
|
||||
"""对已由 ScreenshotHandler.cut_pic 生成的裁剪图做预处理,返回可传入 analyse_pic_* 的图片名。
|
||||
|
||||
参数:
|
||||
analyser: fudai_analyse 实例
|
||||
cut_pic_name: cut_pic 时使用的名称(不含扩展名)
|
||||
返回:
|
||||
返回预处理后图片的名称(不含扩展名),调用者应把它传给 analyse_pic_word/analyse_pic_digits
|
||||
"""
|
||||
try:
|
||||
from PIL import Image, ImageOps, ImageFilter
|
||||
from path_config import get_cut_pic_path
|
||||
except Exception:
|
||||
# 如果 PIL 或 path_config 不可用,回退到原名
|
||||
return cut_pic_name
|
||||
|
||||
src = get_cut_pic_path(cut_pic_name)
|
||||
pre_name = f"{cut_pic_name}_preprocessed"
|
||||
dst = get_cut_pic_path(pre_name)
|
||||
|
||||
try:
|
||||
if not os.path.exists(src):
|
||||
return cut_pic_name
|
||||
img = Image.open(src)
|
||||
img.load()
|
||||
# 转灰度
|
||||
img = img.convert("L")
|
||||
# 放大两倍(Lanczos)
|
||||
img = img.resize((img.width * 2, img.height * 2), Image.LANCZOS)
|
||||
# 自动对比并锐化
|
||||
img = ImageOps.autocontrast(img)
|
||||
img = img.filter(ImageFilter.SHARPEN)
|
||||
# 保存为目标路径(覆盖或新文件)
|
||||
img.save(dst)
|
||||
return pre_name
|
||||
except Exception:
|
||||
# 任何异常回退到原名,保证不抛出
|
||||
try:
|
||||
return cut_pic_name
|
||||
except Exception:
|
||||
return cut_pic_name
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -50,3 +50,25 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
@@ -1,15 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
优惠券弹窗检测模块
|
||||
==================
|
||||
|
||||
检测当前弹窗是否为优惠券弹窗,而非真正的福袋详情页。
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
import os
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
@@ -37,274 +31,240 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
pass
|
||||
return False
|
||||
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
import path_config
|
||||
path = path_config.get_screenshot_path()
|
||||
try:
|
||||
pic = Image.open(path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
import path_config
|
||||
path = path_config.get_screenshot_path()
|
||||
|
||||
pic = pic.convert("RGBA")
|
||||
pix = pic.load()
|
||||
w, h = pic.size
|
||||
try:
|
||||
pic = Image.open(path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 扫描区域:153,351 到 266,451(基于1080x2400基准坐标)
|
||||
# 根据实际分辨率缩放坐标
|
||||
scale_x = w / 1080.0
|
||||
scale_y = h / 2400.0
|
||||
x1 = int(153 * scale_x)
|
||||
y1 = int(351 * scale_y)
|
||||
x2 = int(266 * scale_x)
|
||||
y2 = int(451 * scale_y)
|
||||
|
||||
# 边界检查
|
||||
x1 = max(0, min(x1, w))
|
||||
y1 = max(0, min(y1, h))
|
||||
x2 = max(0, min(x2, w))
|
||||
y2 = max(0, min(y2, h))
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
return False
|
||||
pic = pic.convert("RGBA")
|
||||
pix = pic.load()
|
||||
w, h = pic.size
|
||||
|
||||
fudai_like = 0
|
||||
coupon_like = 0
|
||||
step_x = max(1, (x2 - x1) // 40)
|
||||
step_y = max(1, (y2 - y1) // 40)
|
||||
# 扫描区域:153,351 到 266,451(基于1080x2400基准坐标)
|
||||
# 根据实际分辨率缩放坐标
|
||||
scale_x = w / 1080.0
|
||||
scale_y = h / 2400.0
|
||||
x1 = int(153 * scale_x)
|
||||
y1 = int(351 * scale_y)
|
||||
x2 = int(266 * scale_x)
|
||||
y2 = int(451 * scale_y)
|
||||
|
||||
for yy in range(y1, y2, step_y):
|
||||
for xx in range(x1, x2, step_x):
|
||||
try:
|
||||
p = pix[xx, yy]
|
||||
except Exception as e:
|
||||
# 像素访问失败,跳过该像素(可能是坐标越界)
|
||||
continue
|
||||
if not (isinstance(p, tuple) and len(p) >= 3):
|
||||
continue
|
||||
r, g, b = int(p[0]), int(p[1]), int(p[2])
|
||||
# 福袋:粉/紫/粉蓝
|
||||
if r >= 200 and b >= 210 and 80 <= g <= 230:
|
||||
fudai_like += 1
|
||||
# 券:偏橙色
|
||||
if r >= 200 and 120 <= g <= 230 and b <= 180:
|
||||
coupon_like += 1
|
||||
# 边界检查
|
||||
x1 = max(0, min(x1, w))
|
||||
y1 = max(0, min(y1, h))
|
||||
x2 = max(0, min(x2, w))
|
||||
y2 = max(0, min(y2, h))
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
return False
|
||||
|
||||
fudai_like = 0
|
||||
coupon_like = 0
|
||||
step_x = max(1, (x2 - x1) // 40)
|
||||
step_y = max(1, (y2 - y1) // 40)
|
||||
|
||||
for yy in range(y1, y2, step_y):
|
||||
for xx in range(x1, x2, step_x):
|
||||
try:
|
||||
p = pix[xx, yy]
|
||||
except Exception as e:
|
||||
# 像素访问失败,跳过该像素(可能是坐标越界)
|
||||
continue
|
||||
if not (isinstance(p, tuple) and len(p) >= 3):
|
||||
continue
|
||||
r, g, b = int(p[0]), int(p[1]), int(p[2])
|
||||
# 福袋:粉/紫/粉蓝
|
||||
if r >= 200 and b >= 210 and 80 <= g <= 230:
|
||||
fudai_like += 1
|
||||
# 券:偏橙色
|
||||
if r >= 200 and 120 <= g <= 230 and b <= 180:
|
||||
coupon_like += 1
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"弹窗",
|
||||
"弹窗颜色统计",
|
||||
fudai_like=fudai_like,
|
||||
coupon_like=coupon_like,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录弹窗颜色统计日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
"弹窗",
|
||||
"弹窗颜色统计",
|
||||
fudai_like=fudai_like,
|
||||
coupon_like=coupon_like,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果券像素明显多于粉袋像素,可能需要OCR确认
|
||||
is_coupon_like_by_color = coupon_like > fudai_like * 1.2
|
||||
|
||||
# 检测是否同时有福袋详情特征(通过像素检测)
|
||||
has_fudai_detail = False
|
||||
try:
|
||||
from douyin.detection import douyin_pixel
|
||||
resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
pic_rgb = pic.convert("RGB")
|
||||
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None) or
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
|
||||
)
|
||||
result = douyin_pixel.detect_fudai_detail_page(
|
||||
pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi,
|
||||
template_threshold, return_info=True, analyser=analyser
|
||||
)
|
||||
if isinstance(result, tuple):
|
||||
has_fudai_detail, detect_info = result
|
||||
# 记录检测信息到日志
|
||||
except Exception as e:
|
||||
try:
|
||||
task_count = detect_info.get("task_count", 0)
|
||||
detection_method = detect_info.get("method", "unknown")
|
||||
method_name = "任务数量检测" if detection_method == "task_count" else "未知"
|
||||
analyser._log_kv(
|
||||
"弹窗",
|
||||
f"检测福袋详情页({method_name})",
|
||||
task_count=task_count,
|
||||
method=detection_method,
|
||||
"错误",
|
||||
"记录弹窗颜色统计日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录福袋详情检测日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
has_fudai_detail = result
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果券像素明显多于粉袋像素,可能需要OCR确认
|
||||
is_coupon_like_by_color = coupon_like > fudai_like * 1.2
|
||||
|
||||
# 检测是否同时有福袋详情特征(通过像素检测)
|
||||
has_fudai_detail = False
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"检测福袋详情页失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
from douyin.detection import douyin_pixel
|
||||
resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
pic_rgb = pic.convert("RGB")
|
||||
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None) or
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果颜色统计显示可能是优惠券,需要严格确认:
|
||||
# 1. 先进行模板匹配确认(使用 detect_coupon_popup_background)
|
||||
# 2. 如果模板匹配成功,再进行OCR确认"开心收下"按钮
|
||||
# 3. 只有模板匹配和OCR都确认时,才判定为优惠券弹窗
|
||||
# 这样可以避免因识别福袋位置失败而误判为优惠券弹窗
|
||||
if is_coupon_like_by_color:
|
||||
try:
|
||||
# 步骤1:模板匹配确认
|
||||
template_matched = False
|
||||
try:
|
||||
from douyin.detection import douyin_pixel
|
||||
pic_rgb = pic.convert("RGB")
|
||||
template_matched = douyin_pixel.detect_coupon_popup_background(pic_rgb)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"模板匹配确认异常",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not template_matched:
|
||||
# 模板匹配失败,即使颜色统计偏向优惠券,也不判定为优惠券弹窗
|
||||
# 可能是识别福袋位置失败,导致点击了错误位置
|
||||
result = douyin_pixel.detect_fudai_detail_page(
|
||||
pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi,
|
||||
template_threshold, return_info=True, analyser=analyser
|
||||
)
|
||||
if isinstance(result, tuple):
|
||||
has_fudai_detail, detect_info = result
|
||||
# 记录检测信息到日志
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"弹窗",
|
||||
"颜色统计偏向优惠券,但模板匹配未命中,不判定为优惠券弹窗",
|
||||
说明="可能是识别福袋位置失败,点击了错误位置",
|
||||
"福袋详情检测结果",
|
||||
has_fudai_detail=has_fudai_detail,
|
||||
detect_info=detect_info if detect_info else {},
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录模板匹配失败日志失败",
|
||||
"记录福袋详情检测日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
# 步骤2:OCR确认"开心收下"按钮(模板匹配成功后)
|
||||
if has_fudai_detail:
|
||||
analyser._log_kv("弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认")
|
||||
else:
|
||||
analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认")
|
||||
|
||||
# 使用参与按钮区域检测"开心收下"(与"粉丝团加入"相同的区域)
|
||||
# 保存完整截图并标注OCR区域
|
||||
has_fudai_detail = bool(result)
|
||||
except Exception as e:
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic_check = Image.open(pic_path)
|
||||
pic_check.load()
|
||||
pic_rgb_check = pic_check.convert("RGB")
|
||||
|
||||
width, height = pic_rgb_check.size
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
|
||||
x1_base, y1_base, x2_base, y2_base = 200, 1940, 880, 2140
|
||||
x1 = int(x1_base * width / rx)
|
||||
y1 = int(y1_base * height / ry)
|
||||
x2 = int(x2_base * width / rx)
|
||||
y2 = int(y2_base * height / ry)
|
||||
|
||||
x1 = max(0, min(x1, width - 1))
|
||||
y1 = max(0, min(y1, height - 1))
|
||||
x2 = max(0, min(x2, width - 1))
|
||||
y2 = max(0, min(y2, height - 1))
|
||||
|
||||
if x1 < x2 and y1 < y2:
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_check,
|
||||
operation_type="ocr",
|
||||
picname="参与按钮",
|
||||
step="before_ocr",
|
||||
coords=(x1, y1, x2, y2),
|
||||
extra_info={
|
||||
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
|
||||
"purpose": "检测开心收下",
|
||||
}
|
||||
)
|
||||
if debug_path:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"福袋详情检测异常",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果颜色不像优惠券,且没有福袋详情特征,直接判定为福袋详情页
|
||||
if not is_coupon_like_by_color:
|
||||
if not has_fudai_detail:
|
||||
analyser._log_kv("弹窗", "颜色统计不像优惠券,且未检测到福袋详情,判定为福袋详情页")
|
||||
else:
|
||||
analyser._log_kv("弹窗", "颜色统计不像优惠券,但检测到福袋详情,判定为福袋详情页")
|
||||
return False
|
||||
|
||||
# 如果颜色像优惠券,但没有福袋详情特征,可能只是误判
|
||||
if not has_fudai_detail:
|
||||
analyser._log_kv("弹窗", "颜色统计像优惠券,但未检测到福袋详情,判定为福袋详情页(可能是误判)")
|
||||
return False
|
||||
|
||||
# 步骤2:OCR确认"开心收下"按钮(模板匹配成功后)
|
||||
if has_fudai_detail:
|
||||
analyser._log_kv("弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认")
|
||||
else:
|
||||
analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认")
|
||||
|
||||
# 使用参与按钮区域检测"开心收下"(与"粉丝团加入"相同的区域)
|
||||
# 保存完整截图并标注OCR区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic_check = Image.open(pic_path)
|
||||
pic_check.load()
|
||||
pic_rgb_check = pic_check.convert("RGB")
|
||||
|
||||
width, height = pic_rgb_check.size
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
|
||||
x1_base, y1_base, x2_base, y2_base = 200, 1940, 880, 2140
|
||||
x1 = int(x1_base * width / rx)
|
||||
y1 = int(y1_base * height / ry)
|
||||
x2 = int(x2_base * width / rx)
|
||||
y2 = int(y2_base * height / ry)
|
||||
|
||||
x1 = max(0, min(x1, width - 1))
|
||||
y1 = max(0, min(y1, height - 1))
|
||||
x2 = max(0, min(x2, width - 1))
|
||||
y2 = max(0, min(y2, height - 1))
|
||||
|
||||
if x1 < x2 and y1 < y2:
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_check,
|
||||
operation_type="ocr",
|
||||
picname="参与按钮",
|
||||
step="before_ocr",
|
||||
coords=(x1, y1, x2, y2),
|
||||
extra_info={
|
||||
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
|
||||
"purpose": "检测开心收下",
|
||||
}
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"OCR识别前保存完整截图(参与按钮-检测开心收下)",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"OCR识别前保存完整截图(参与按钮-检测开心收下)",
|
||||
path=debug_path,
|
||||
"错误",
|
||||
"记录调试图像日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录调试图像日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"保存参与按钮调试截图失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"保存参与按钮调试截图失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
|
||||
|
||||
|
||||
# 并行执行模式0和模式1的OCR(如果启用模式1)
|
||||
enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False))
|
||||
coupon_text = ""
|
||||
@@ -328,7 +288,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
else:
|
||||
# 只使用模式0
|
||||
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
# 模板匹配 + OCR 都确认,判定为优惠券弹窗
|
||||
analyser._log_kv("弹窗", "模板匹配+OCR确认:检测到'开心收下',判定为优惠券弹窗", OCR文本=coupon_text[:50])
|
||||
@@ -362,7 +322,19 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
# 否则判定为福袋详情页
|
||||
return False
|
||||
|
||||
# 否则判定为福袋详情页
|
||||
return False
|
||||
except Exception as e:
|
||||
# 整个函数异常处理
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"优惠券弹窗检测过程异常",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
@@ -156,7 +156,7 @@ def read_live_room_title_core(
|
||||
) -> Tuple[str, str]:
|
||||
"""读取当前直播间顶部区域的"主播名/直播间名"(OCR,尽量轻量)。
|
||||
|
||||
使用多个 ROI 区域和不同的 OCR 模式进行识别,选择最佳结果。
|
||||
只使用指定区域 (144,144) 到 (329,185) 进行识别,避免多次截图。
|
||||
"""
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
@@ -171,79 +171,26 @@ def read_live_room_title_core(
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 如果是切换直播间后立即调用,等待标题区域出现(避免识别到空白或旧截图)
|
||||
try:
|
||||
if getattr(analyser, "_just_switched_room", False):
|
||||
wait_seconds = float(getattr(analyser, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
|
||||
poll_interval = 0.5
|
||||
start_ts = time.time()
|
||||
while time.time() - start_ts < wait_seconds:
|
||||
try:
|
||||
# 先截图并切割 mid 区域做快速检测(使用临时名字,不覆盖正式裁剪)
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
analyser.cut_pic(80, 128, 560, 230, "", "live_room_title_mid_tmp", y_pianyi)
|
||||
txt = analyser.operation.analyse_pic_word("live_room_title_mid_tmp", 0)
|
||||
if txt and str(txt).strip():
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
# 在等待期间执行可选的后台任务(例如处理弹窗等),以提高并发性
|
||||
try:
|
||||
if hasattr(analyser, "background_tick") and callable(getattr(analyser, "background_tick")):
|
||||
analyser.background_tick()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(poll_interval)
|
||||
try:
|
||||
analyser._just_switched_room = False
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
cands: List[Tuple[str, str, str]] = []
|
||||
|
||||
# mid ROI:优先使用更大区域,减少"只截到尾巴1个字"
|
||||
# 只使用指定区域 (144,144) 到 (329,185),只尝试一次OCR(mode 0)
|
||||
try:
|
||||
analyser.cut_pic(80, 128, 560, 230, '', 'live_room_title_mid', y_pianyi)
|
||||
analyser.cut_pic(144, 144, 329, 185, '', 'live_room_title_mid', y_pianyi)
|
||||
t, r = _ocr_try_room_title(analyser, 'live_room_title_mid', 0)
|
||||
cands.append((t, r, 'mid_cc0'))
|
||||
if len(t or "") < min_len:
|
||||
t1, r1 = _ocr_try_room_title(analyser, 'live_room_title_mid', 1)
|
||||
cands.append((t1, r1, 'mid_cc1'))
|
||||
title = t
|
||||
raw_text = r
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"OCR识别直播间标题(mid区域)失败",
|
||||
"OCR识别直播间标题失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# large ROI:进一步扩大,兼容机型/系统字体/刘海偏移
|
||||
if not cands or max(len(x[0] or "") for x in cands) < min_len:
|
||||
try:
|
||||
analyser.cut_pic(40, 110, 660, 260, '', 'live_room_title_large', y_pianyi)
|
||||
t2, r2 = _ocr_try_room_title(analyser, 'live_room_title_large', 0)
|
||||
cands.append((t2, r2, 'large_cc0'))
|
||||
if len(t2 or "") < min_len:
|
||||
t3, r3 = _ocr_try_room_title(analyser, 'live_room_title_large', 1)
|
||||
cands.append((t3, r3, 'large_cc1'))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# small ROI:最后兜底(历史区域),使用优化后的坐标
|
||||
if not cands or max(len(x[0] or "") for x in cands) <= 1:
|
||||
try:
|
||||
analyser.cut_pic(147, 160, 301, 191, '', 'live_room_title_small', y_pianyi)
|
||||
t4, r4 = _ocr_try_room_title(analyser, 'live_room_title_small', 0)
|
||||
cands.append((t4, r4, 'small_cc0'))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
title, raw_text = _pick_best_room_title(cands, min_len)
|
||||
title = ""
|
||||
raw_text = ""
|
||||
|
||||
# 更新 analyser 的属性
|
||||
try:
|
||||
|
||||
@@ -17,3 +17,25 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -57,3 +57,25 @@ def save_ui_to_config(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -67,3 +67,25 @@ def create_device_selector(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -53,3 +53,25 @@ def create_image_viewer(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
"""
|
||||
日志颜色配置模块
|
||||
================
|
||||
|
||||
为不同的操作类型定义颜色标签,支持明亮和暗色主题。
|
||||
"""
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
|
||||
# 操作类型关键词映射(用于识别日志中的操作类型)
|
||||
OPERATION_KEYWORDS: Dict[str, list] = {
|
||||
"ocr": [
|
||||
"OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败",
|
||||
"直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果"
|
||||
],
|
||||
"click": [
|
||||
"点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标",
|
||||
"返回", "确认", "关闭", "发送", "加入"
|
||||
],
|
||||
"swipe": [
|
||||
"滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动",
|
||||
"回退", "切换直播间", "切换房间"
|
||||
],
|
||||
"screenshot": [
|
||||
"截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败"
|
||||
],
|
||||
"detection": [
|
||||
"检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配",
|
||||
"检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到"
|
||||
],
|
||||
"decision": [
|
||||
"决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选",
|
||||
"价值过低", "人数过少", "人数过多", "倒计时", "内容不符合"
|
||||
],
|
||||
"reservation": [
|
||||
"预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列",
|
||||
"高价值预约", "预约回退", "预约校验"
|
||||
],
|
||||
"fansclub": [
|
||||
"粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功"
|
||||
],
|
||||
"lottery": [
|
||||
"开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间"
|
||||
],
|
||||
"stage": [
|
||||
"阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE",
|
||||
"LIVE_OR_UNKNOWN", "阶段变化", "阶段流转"
|
||||
],
|
||||
"performance": [
|
||||
"耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率"
|
||||
],
|
||||
"error": [
|
||||
"错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout"
|
||||
],
|
||||
"success": [
|
||||
"成功", "SUCCESS", "完成", "完成", "已", "完成"
|
||||
],
|
||||
"info": [
|
||||
"信息", "INFO", "提示", "注意", "开始", "启动", "停止"
|
||||
],
|
||||
"flow": [
|
||||
"流程", "flow", "处理", "执行", "运行", "完成"
|
||||
],
|
||||
"operation": [
|
||||
"操作", "operation", "动作", "行为"
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
|
||||
# 操作类型关键词映射(用于识别日志中的操作类型)
|
||||
OPERATION_KEYWORDS: Dict[str, list] = {
|
||||
"ocr": [
|
||||
"OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败",
|
||||
"直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果"
|
||||
],
|
||||
"click": [
|
||||
"点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标",
|
||||
"返回", "确认", "关闭", "发送", "加入"
|
||||
],
|
||||
"swipe": [
|
||||
"滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动",
|
||||
"回退", "切换直播间", "切换房间"
|
||||
],
|
||||
"screenshot": [
|
||||
"截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败"
|
||||
],
|
||||
"detection": [
|
||||
"检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配",
|
||||
"检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到"
|
||||
],
|
||||
"decision": [
|
||||
"决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选",
|
||||
"价值过低", "人数过少", "人数过多", "倒计时", "内容不符合"
|
||||
],
|
||||
"reservation": [
|
||||
"预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列",
|
||||
"高价值预约", "预约回退", "预约校验"
|
||||
],
|
||||
"fansclub": [
|
||||
"粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功"
|
||||
],
|
||||
"lottery": [
|
||||
"开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间"
|
||||
],
|
||||
"stage": [
|
||||
"阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE",
|
||||
"LIVE_OR_UNKNOWN", "阶段变化", "阶段流转"
|
||||
],
|
||||
"performance": [
|
||||
"耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率"
|
||||
],
|
||||
"error": [
|
||||
"错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout"
|
||||
],
|
||||
"success": [
|
||||
"成功", "SUCCESS", "完成", "完成", "已", "完成"
|
||||
],
|
||||
"info": [
|
||||
"信息", "INFO", "提示", "注意", "开始", "启动", "停止"
|
||||
],
|
||||
"flow": [
|
||||
"流程", "flow", "处理", "执行", "运行", "完成"
|
||||
],
|
||||
"operation": [
|
||||
"操作", "operation", "动作", "行为"
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def get_operation_type(line: str) -> Optional[str]:
|
||||
"""
|
||||
根据日志行内容识别操作类型
|
||||
|
||||
日志格式通常是: [时间] [GUI] - 操作类型 内容
|
||||
优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等)
|
||||
|
||||
Args:
|
||||
line: 日志行内容
|
||||
|
||||
Returns:
|
||||
操作类型名称,如果无法识别则返回None
|
||||
"""
|
||||
line_lower = line.lower()
|
||||
|
||||
# 优先级1: 识别日志内容开头的操作类型(最精确)
|
||||
# 日志格式: [时间] [GUI] - 操作类型 内容
|
||||
# 例如: [GUI] - 流程 find_and_open_fudai_detail完成
|
||||
# [GUI] - 滑动上滑切换直播间
|
||||
# [GUI] - 阶段诊断开始阶段诊断
|
||||
# [GUI] - 预约[预约]记录直播间标题
|
||||
|
||||
import re
|
||||
# 提取日志内容部分(去掉时间戳和标签)
|
||||
# 匹配格式: [时间] [标签] - 内容
|
||||
content_match = re.search(r'\]\s*-\s*(.+)$', line)
|
||||
if content_match:
|
||||
content = content_match.group(1).strip()
|
||||
content_lower = content.lower()
|
||||
|
||||
# 操作类型关键词映射(按优先级排序,更具体的在前)
|
||||
operation_type_map = [
|
||||
# 检测相关(最具体)
|
||||
("阶段诊断", "detection"),
|
||||
("阶段检测", "detection"),
|
||||
("并行检测", "detection"),
|
||||
("像素检测", "detection"),
|
||||
("模板匹配", "detection"),
|
||||
("检测", "detection"),
|
||||
# 滑动相关
|
||||
("滑动", "swipe"),
|
||||
("上滑", "swipe"),
|
||||
("下滑", "swipe"),
|
||||
("切换直播间", "swipe"),
|
||||
# 预约相关
|
||||
("预约", "reservation"),
|
||||
# OCR相关
|
||||
("OCR", "ocr"),
|
||||
("ocr识别", "ocr"),
|
||||
("识别", "ocr"),
|
||||
# 点击相关
|
||||
("点击", "click"),
|
||||
# 截图相关
|
||||
("截图", "screenshot"),
|
||||
# 流程相关
|
||||
("流程", "flow"),
|
||||
# 决策相关
|
||||
("决策", "decision"),
|
||||
("行为识别", "decision"),
|
||||
# 开奖相关
|
||||
("开奖", "lottery"),
|
||||
("抽奖结果", "lottery"),
|
||||
# 粉丝团相关
|
||||
("粉丝团", "fansclub"),
|
||||
# 操作相关(通用,放后面)
|
||||
("操作", "operation"),
|
||||
# 自救相关
|
||||
("自救", "info"),
|
||||
# 错误相关
|
||||
("错误", "error"),
|
||||
("异常", "error"),
|
||||
# 成功相关
|
||||
("成功", "success"),
|
||||
# 信息相关(最通用,放最后)
|
||||
("信息", "info"),
|
||||
]
|
||||
|
||||
# 检查内容开头是否匹配操作类型
|
||||
for keyword, op_type in operation_type_map:
|
||||
# 检查是否在内容开头(更精确)
|
||||
if content_lower.startswith(keyword.lower()):
|
||||
return op_type
|
||||
# 或者检查是否紧跟在 " - " 后面
|
||||
if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower:
|
||||
return op_type
|
||||
|
||||
# 优先级2: 使用日志标签识别(如果内容中没有匹配到)
|
||||
tag_match = re.search(r'\[([^\]]+)\]', line)
|
||||
if tag_match:
|
||||
tag = tag_match.group(1).lower()
|
||||
|
||||
# 标签到操作类型的映射(精确匹配)
|
||||
tag_to_op_type = {
|
||||
"阶段诊断": "detection",
|
||||
"阶段检测": "detection",
|
||||
"截图": "screenshot",
|
||||
"ocr": "ocr",
|
||||
"ocr识别": "ocr",
|
||||
"点击": "click",
|
||||
"滑动": "swipe",
|
||||
"预约": "reservation",
|
||||
"找福袋图标": "detection",
|
||||
"福袋查找": "detection",
|
||||
"自救": "info",
|
||||
"流程": "flow",
|
||||
"行为识别": "decision",
|
||||
"决策": "decision",
|
||||
"错误": "error",
|
||||
"异常": "error",
|
||||
"成功": "success",
|
||||
"信息": "info",
|
||||
"提示": "info",
|
||||
}
|
||||
|
||||
# 精确匹配标签
|
||||
if tag in tag_to_op_type:
|
||||
return tag_to_op_type[tag]
|
||||
|
||||
# 部分匹配标签(用于更灵活的匹配)
|
||||
for tag_key, op_type in tag_to_op_type.items():
|
||||
if tag_key in tag or tag in tag_key:
|
||||
return op_type
|
||||
|
||||
# 优先级2: 使用关键词匹配(更具体的短语优先)
|
||||
# 定义更具体的关键词短语(按优先级排序)
|
||||
specific_patterns = [
|
||||
# 检测相关(更具体的短语优先)
|
||||
("阶段诊断", "detection"),
|
||||
("阶段检测", "detection"),
|
||||
("像素检测", "detection"),
|
||||
("模板匹配", "detection"),
|
||||
("并行检测", "detection"),
|
||||
# OCR相关
|
||||
("OCR识别", "ocr"),
|
||||
("OCR模式", "ocr"),
|
||||
("识别成功", "ocr"),
|
||||
("识别失败", "ocr"),
|
||||
# 点击相关
|
||||
("点击成功", "click"),
|
||||
("点击失败", "click"),
|
||||
("参与按钮", "click"),
|
||||
# 滑动相关
|
||||
("向上滑动", "swipe"),
|
||||
("向下滑动", "swipe"),
|
||||
("切换直播间", "swipe"),
|
||||
# 预约相关
|
||||
("记录预约", "reservation"),
|
||||
("预约窗口", "reservation"),
|
||||
("预约队列", "reservation"),
|
||||
# 开奖相关
|
||||
("抽奖结果", "lottery"),
|
||||
("等待开奖", "lottery"),
|
||||
("开奖时间", "lottery"),
|
||||
# 粉丝团相关
|
||||
("加入粉丝团", "fansclub"),
|
||||
("粉丝团失败", "fansclub"),
|
||||
("粉丝团成功", "fansclub"),
|
||||
]
|
||||
|
||||
# 先检查更具体的短语
|
||||
for pattern, op_type in specific_patterns:
|
||||
if pattern.lower() in line_lower:
|
||||
return op_type
|
||||
|
||||
# 优先级3: 使用通用关键词匹配(按操作类型优先级)
|
||||
# 调整顺序,让更具体的操作类型优先
|
||||
priority_order = [
|
||||
"lottery", # 开奖相关(更具体)
|
||||
"fansclub", # 粉丝团(更具体)
|
||||
"reservation", # 预约(更具体)
|
||||
"decision", # 决策(更具体)
|
||||
"detection", # 检测(较具体)
|
||||
"ocr", # OCR(较具体)
|
||||
"click", # 点击(较具体)
|
||||
"swipe", # 滑动(较具体)
|
||||
"flow", # 流程(较具体)
|
||||
"operation", # 操作(较具体)
|
||||
"screenshot", # 截图(较通用,放后面)
|
||||
"stage", # 阶段(较通用)
|
||||
"performance", # 性能(较通用)
|
||||
"error", # 错误(较通用)
|
||||
"success", # 成功(较通用)
|
||||
"info", # 信息(最通用,放最后)
|
||||
]
|
||||
|
||||
# 按优先级顺序检查
|
||||
for op_type in priority_order:
|
||||
if op_type in OPERATION_KEYWORDS:
|
||||
for keyword in OPERATION_KEYWORDS[op_type]:
|
||||
# 避免过于宽泛的关键词误匹配
|
||||
if keyword.lower() in ["截图", "检测", "识别", "成功", "完成", "失败", "错误"]:
|
||||
# 这些关键词太宽泛,只在特定上下文中使用
|
||||
# 检查是否在更具体的上下文中
|
||||
if keyword.lower() == "截图" and ("截图成功" in line_lower or "截图失败" in line_lower or "[截图]" in line):
|
||||
return op_type
|
||||
elif keyword.lower() == "检测" and ("阶段检测" in line_lower or "像素检测" in line_lower or "并行检测" in line_lower):
|
||||
return op_type
|
||||
elif keyword.lower() == "识别" and ("OCR识别" in line_lower or "识别成功" in line_lower or "识别失败" in line_lower):
|
||||
return op_type
|
||||
# 其他宽泛关键词跳过,避免误匹配
|
||||
continue
|
||||
|
||||
if keyword.lower() in line_lower:
|
||||
return op_type
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
获取颜色配置(根据主题)
|
||||
|
||||
Args:
|
||||
theme: 主题名称("litera", "darkly" 等)
|
||||
|
||||
Returns:
|
||||
颜色配置字典,包含每种操作类型的颜色设置
|
||||
"""
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
is_light = theme.lower() in light_themes
|
||||
|
||||
if is_light:
|
||||
# 明亮主题颜色配置(深色文字,与白色背景对比,高区分度)
|
||||
return {
|
||||
"ocr": {
|
||||
"foreground": "#0052CC", # 鲜明蓝色 - OCR识别
|
||||
"background": "#D6E8FF", # 浅蓝色背景
|
||||
},
|
||||
"click": {
|
||||
"foreground": "#D32F2F", # 鲜明红色 - 点击操作
|
||||
"background": "#FFE0E0", # 浅红色背景
|
||||
},
|
||||
"swipe": {
|
||||
"foreground": "#2E7D32", # 鲜明绿色 - 滑动操作
|
||||
"background": "#E0F2E8", # 浅绿色背景
|
||||
},
|
||||
"screenshot": {
|
||||
"foreground": "#7B1FA2", # 鲜明紫色 - 截图操作
|
||||
"background": "#F3E5F5", # 浅紫色背景
|
||||
},
|
||||
"detection": {
|
||||
"foreground": "#F57C00", # 鲜明橙色 - 检测操作
|
||||
"background": "#FFF3E0", # 浅橙色背景
|
||||
},
|
||||
"decision": {
|
||||
"foreground": "#C2185B", # 鲜明品红色 - 决策操作
|
||||
"background": "#FCE4EC", # 浅品红色背景
|
||||
},
|
||||
"reservation": {
|
||||
"foreground": "#00897B", # 鲜明青色 - 预约操作(区别于OCR蓝色)
|
||||
"background": "#E0F2F1", # 浅青色背景
|
||||
},
|
||||
"fansclub": {
|
||||
"foreground": "#8E24AA", # 鲜明紫红色 - 粉丝团操作(区别于截图紫色)
|
||||
"background": "#F3E5F5", # 浅紫红色背景
|
||||
},
|
||||
"lottery": {
|
||||
"foreground": "#E64A19", # 鲜明橙红色 - 开奖相关(区别于点击红色)
|
||||
"background": "#FFEBEE", # 浅橙红色背景
|
||||
},
|
||||
"stage": {
|
||||
"foreground": "#616161", # 深灰色 - 阶段信息
|
||||
"background": "#F5F5F5", # 浅灰色背景
|
||||
},
|
||||
"performance": {
|
||||
"foreground": "#00796B", # 鲜明青绿色 - 性能信息
|
||||
"background": "#E0F2F1", # 浅青绿色背景
|
||||
},
|
||||
"error": {
|
||||
"foreground": "#C62828", # 鲜明深红色 - 错误
|
||||
"background": "#FFCDD2", # 浅红色背景
|
||||
},
|
||||
"success": {
|
||||
"foreground": "#2E7D32", # 鲜明深绿色 - 成功
|
||||
"background": "#C8E6C9", # 浅绿色背景
|
||||
},
|
||||
"info": {
|
||||
"foreground": "#0277BD", # 鲜明天蓝色 - 信息(区别于OCR深蓝色)
|
||||
"background": "#BBDEFB", # 浅天蓝色背景
|
||||
},
|
||||
"flow": {
|
||||
"foreground": "#5D4037", # 深棕色 - 流程操作
|
||||
"background": "#EFEBE9", # 浅棕色背景
|
||||
},
|
||||
"operation": {
|
||||
"foreground": "#455A64", # 深蓝灰色 - 操作动作
|
||||
"background": "#ECEFF1", # 浅蓝灰色背景
|
||||
},
|
||||
}
|
||||
else:
|
||||
# 暗色主题颜色配置(亮色文字,与深色背景对比,高区分度)
|
||||
return {
|
||||
"ocr": {
|
||||
"foreground": "#42A5F5", # 鲜明亮蓝色 - OCR识别
|
||||
"background": "#0D47A1", # 深蓝色背景
|
||||
},
|
||||
"click": {
|
||||
"foreground": "#EF5350", # 鲜明亮红色 - 点击操作
|
||||
"background": "#B71C1C", # 深红色背景
|
||||
},
|
||||
"swipe": {
|
||||
"foreground": "#66BB6A", # 鲜明亮绿色 - 滑动操作
|
||||
"background": "#1B5E20", # 深绿色背景
|
||||
},
|
||||
"screenshot": {
|
||||
"foreground": "#AB47BC", # 鲜明亮紫色 - 截图操作
|
||||
"background": "#4A148C", # 深紫色背景
|
||||
},
|
||||
"detection": {
|
||||
"foreground": "#FFA726", # 鲜明亮橙色 - 检测操作
|
||||
"background": "#E65100", # 深橙色背景
|
||||
},
|
||||
"decision": {
|
||||
"foreground": "#EC407A", # 鲜明亮品红色 - 决策操作
|
||||
"background": "#880E4F", # 深品红色背景
|
||||
},
|
||||
"reservation": {
|
||||
"foreground": "#26A69A", # 鲜明亮青色 - 预约操作(区别于OCR蓝色)
|
||||
"background": "#004D40", # 深青色背景
|
||||
},
|
||||
"fansclub": {
|
||||
"foreground": "#BA68C8", # 鲜明亮紫红色 - 粉丝团操作(区别于截图紫色)
|
||||
"background": "#4A148C", # 深紫红色背景
|
||||
},
|
||||
"lottery": {
|
||||
"foreground": "#FF7043", # 鲜明亮橙红色 - 开奖相关(区别于点击红色)
|
||||
"background": "#BF360C", # 深橙红色背景
|
||||
},
|
||||
"stage": {
|
||||
"foreground": "#90A4AE", # 亮灰色 - 阶段信息
|
||||
"background": "#263238", # 深灰色背景
|
||||
},
|
||||
"performance": {
|
||||
"foreground": "#26A69A", # 鲜明亮青绿色 - 性能信息
|
||||
"background": "#004D40", # 深青绿色背景
|
||||
},
|
||||
"error": {
|
||||
"foreground": "#F44336", # 鲜明亮红色 - 错误
|
||||
"background": "#B71C1C", # 深红色背景
|
||||
},
|
||||
"success": {
|
||||
"foreground": "#66BB6A", # 鲜明亮绿色 - 成功
|
||||
"background": "#1B5E20", # 深绿色背景
|
||||
},
|
||||
"info": {
|
||||
"foreground": "#29B6F6", # 鲜明亮天蓝色 - 信息(区别于OCR深蓝色)
|
||||
"background": "#01579B", # 深天蓝色背景
|
||||
},
|
||||
"flow": {
|
||||
"foreground": "#A1887F", # 亮棕色 - 流程操作
|
||||
"background": "#3E2723", # 深棕色背景
|
||||
},
|
||||
"operation": {
|
||||
"foreground": "#78909C", # 亮蓝灰色 - 操作动作
|
||||
"background": "#263238", # 深蓝灰色背景
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def apply_operation_color(
|
||||
text_widget,
|
||||
start_pos: str,
|
||||
end_pos: str,
|
||||
line: str,
|
||||
theme: str = "litera"
|
||||
) -> None:
|
||||
"""
|
||||
为日志行应用操作类型颜色
|
||||
|
||||
Args:
|
||||
text_widget: tkinter Text 组件
|
||||
start_pos: 起始位置
|
||||
end_pos: 结束位置
|
||||
line: 日志行内容
|
||||
theme: 主题名称
|
||||
"""
|
||||
try:
|
||||
# 识别操作类型
|
||||
op_type = get_operation_type(line)
|
||||
if not op_type:
|
||||
return
|
||||
|
||||
# 获取颜色配置
|
||||
color_config = get_color_config(theme)
|
||||
if op_type not in color_config:
|
||||
return
|
||||
|
||||
colors = color_config[op_type]
|
||||
tag_name = f"op_{op_type}"
|
||||
|
||||
# 配置标签(总是重新配置,确保主题改变时颜色也会更新)
|
||||
text_widget.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
|
||||
# 应用标签
|
||||
text_widget.tag_add(tag_name, start_pos, end_pos)
|
||||
except Exception:
|
||||
# 忽略颜色应用失败,不影响日志显示
|
||||
pass
|
||||
@@ -0,0 +1,943 @@
|
||||
"""
|
||||
日志颜色配置模块
|
||||
================
|
||||
|
||||
为不同的操作类型定义颜色标签,支持明亮和暗色主题。
|
||||
"""
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
|
||||
# 操作类型关键词映射(用于识别日志中的操作类型)
|
||||
OPERATION_KEYWORDS: Dict[str, list] = {
|
||||
"ocr": [
|
||||
"OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败",
|
||||
"直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果"
|
||||
],
|
||||
"click": [
|
||||
"点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标",
|
||||
"返回", "确认", "关闭", "发送", "加入"
|
||||
],
|
||||
"swipe": [
|
||||
"滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动",
|
||||
"回退", "切换直播间", "切换房间"
|
||||
],
|
||||
"screenshot": [
|
||||
"截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败"
|
||||
],
|
||||
"detection": [
|
||||
"检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配",
|
||||
"检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到"
|
||||
],
|
||||
"decision": [
|
||||
"决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选",
|
||||
"价值过低", "人数过少", "人数过多", "倒计时", "内容不符合"
|
||||
],
|
||||
"reservation": [
|
||||
"预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列",
|
||||
"高价值预约", "预约回退", "预约校验"
|
||||
],
|
||||
"fansclub": [
|
||||
"粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功"
|
||||
],
|
||||
"lottery": [
|
||||
"开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间"
|
||||
],
|
||||
"stage": [
|
||||
"阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE",
|
||||
"LIVE_OR_UNKNOWN", "阶段变化", "阶段流转"
|
||||
],
|
||||
"performance": [
|
||||
"耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率"
|
||||
],
|
||||
"error": [
|
||||
"错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout"
|
||||
],
|
||||
"success": [
|
||||
"成功", "SUCCESS", "完成", "完成", "已", "完成"
|
||||
],
|
||||
"info": [
|
||||
"信息", "INFO", "提示", "注意", "开始", "启动", "停止"
|
||||
],
|
||||
"flow": [
|
||||
"流程", "flow", "处理", "执行", "运行", "完成"
|
||||
],
|
||||
"operation": [
|
||||
"操作", "operation", "动作", "行为"
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def get_operation_type(line: str) -> Optional[str]:
|
||||
"""
|
||||
根据日志行内容识别操作类型
|
||||
|
||||
日志格式通常是: [时间] [GUI] - 操作类型 内容
|
||||
优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等)
|
||||
|
||||
Args:
|
||||
line: 日志行内容
|
||||
|
||||
Returns:
|
||||
操作类型名称,如果无法识别则返回None
|
||||
"""
|
||||
line_lower = line.lower()
|
||||
|
||||
# 优先级1: 识别日志内容开头的操作类型(最精确)
|
||||
# 日志格式: [时间] [GUI] - 操作类型 内容
|
||||
# 例如: [GUI] - 流程 find_and_open_fudai_detail完成
|
||||
# [GUI] - 滑动上滑切换直播间
|
||||
# [GUI] - 阶段诊断开始阶段诊断
|
||||
# [GUI] - 预约[预约]记录直播间标题
|
||||
|
||||
import re
|
||||
# 提取日志内容部分(去掉时间戳和标签)
|
||||
# 匹配格式: [时间] [标签] - 内容
|
||||
content_match = re.search(r'\]\s*-\s*(.+)$', line)
|
||||
if content_match:
|
||||
content = content_match.group(1).strip()
|
||||
content_lower = content.lower()
|
||||
|
||||
# 操作类型关键词映射(按优先级排序,更具体的在前)
|
||||
operation_type_map = [
|
||||
# 检测相关(最具体)
|
||||
("阶段诊断", "detection"),
|
||||
("阶段检测", "detection"),
|
||||
("并行检测", "detection"),
|
||||
("像素检测", "detection"),
|
||||
("模板匹配", "detection"),
|
||||
("检测", "detection"),
|
||||
# 滑动相关
|
||||
("滑动", "swipe"),
|
||||
("上滑", "swipe"),
|
||||
("下滑", "swipe"),
|
||||
("切换直播间", "swipe"),
|
||||
# 预约相关
|
||||
("预约", "reservation"),
|
||||
# OCR相关
|
||||
("OCR", "ocr"),
|
||||
("ocr识别", "ocr"),
|
||||
("识别", "ocr"),
|
||||
# 点击相关
|
||||
("点击", "click"),
|
||||
# 截图相关
|
||||
("截图", "screenshot"),
|
||||
# 流程相关
|
||||
("流程", "flow"),
|
||||
# 决策相关
|
||||
("决策", "decision"),
|
||||
("行为识别", "decision"),
|
||||
# 开奖相关
|
||||
("开奖", "lottery"),
|
||||
("抽奖结果", "lottery"),
|
||||
# 粉丝团相关
|
||||
("粉丝团", "fansclub"),
|
||||
# 操作相关(通用,放后面)
|
||||
("操作", "operation"),
|
||||
# 自救相关
|
||||
("自救", "info"),
|
||||
# 错误相关
|
||||
("错误", "error"),
|
||||
("异常", "error"),
|
||||
# 成功相关
|
||||
("成功", "success"),
|
||||
# 信息相关(最通用,放最后)
|
||||
("信息", "info"),
|
||||
]
|
||||
|
||||
# 检查内容开头是否匹配操作类型
|
||||
for keyword, op_type in operation_type_map:
|
||||
# 检查是否在内容开头(更精确)
|
||||
if content_lower.startswith(keyword.lower()):
|
||||
return op_type
|
||||
# 或者检查是否紧跟在 " - " 后面
|
||||
if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower:
|
||||
return op_type
|
||||
|
||||
# 优先级2: 使用日志标签识别(如果内容中没有匹配到)
|
||||
tag_match = re.search(r'\[([^\]]+)\]', line)
|
||||
if tag_match:
|
||||
tag = tag_match.group(1).lower()
|
||||
|
||||
# 标签到操作类型的映射(精确匹配)
|
||||
tag_to_op_type = {
|
||||
"阶段诊断": "detection",
|
||||
"阶段检测": "detection",
|
||||
"截图": "screenshot",
|
||||
"ocr": "ocr",
|
||||
"ocr识别": "ocr",
|
||||
"点击": "click",
|
||||
"滑动": "swipe",
|
||||
"预约": "reservation",
|
||||
"找福袋图标": "detection",
|
||||
"福袋查找": "detection",
|
||||
"自救": "info",
|
||||
"流程": "flow",
|
||||
"行为识别": "decision",
|
||||
"决策": "decision",
|
||||
"错误": "error",
|
||||
"异常": "error",
|
||||
"成功": "success",
|
||||
"信息": "info",
|
||||
"提示": "info",
|
||||
}
|
||||
|
||||
# 精确匹配标签
|
||||
if tag in tag_to_op_type:
|
||||
return tag_to_op_type[tag]
|
||||
|
||||
# 部分匹配标签(用于更灵活的匹配)
|
||||
for tag_key, op_type in tag_to_op_type.items():
|
||||
if tag_key in tag or tag in tag_key:
|
||||
return op_type
|
||||
|
||||
# 优先级2: 使用关键词匹配(更具体的短语优先)
|
||||
# 定义更具体的关键词短语(按优先级排序)
|
||||
specific_patterns = [
|
||||
# 检测相关(更具体的短语优先)
|
||||
("阶段诊断", "detection"),
|
||||
("阶段检测", "detection"),
|
||||
("像素检测", "detection"),
|
||||
("模板匹配", "detection"),
|
||||
("并行检测", "detection"),
|
||||
# OCR相关
|
||||
("OCR识别", "ocr"),
|
||||
("OCR模式", "ocr"),
|
||||
("识别成功", "ocr"),
|
||||
("识别失败", "ocr"),
|
||||
# 点击相关
|
||||
("点击成功", "click"),
|
||||
("点击失败", "click"),
|
||||
("参与按钮", "click"),
|
||||
# 滑动相关
|
||||
("向上滑动", "swipe"),
|
||||
("向下滑动", "swipe"),
|
||||
("切换直播间", "swipe"),
|
||||
# 预约相关
|
||||
("记录预约", "reservation"),
|
||||
("预约窗口", "reservation"),
|
||||
("预约队列", "reservation"),
|
||||
# 开奖相关
|
||||
("抽奖结果", "lottery"),
|
||||
("等待开奖", "lottery"),
|
||||
("开奖时间", "lottery"),
|
||||
# 粉丝团相关
|
||||
("加入粉丝团", "fansclub"),
|
||||
("粉丝团失败", "fansclub"),
|
||||
("粉丝团成功", "fansclub"),
|
||||
]
|
||||
|
||||
# 先检查更具体的短语
|
||||
for pattern, op_type in specific_patterns:
|
||||
if pattern.lower() in line_lower:
|
||||
return op_type
|
||||
|
||||
# 优先级3: 使用通用关键词匹配(按操作类型优先级)
|
||||
# 调整顺序,让更具体的操作类型优先
|
||||
priority_order = [
|
||||
"lottery", # 开奖相关(更具体)
|
||||
"fansclub", # 粉丝团(更具体)
|
||||
"reservation", # 预约(更具体)
|
||||
"decision", # 决策(更具体)
|
||||
"detection", # 检测(较具体)
|
||||
"ocr", # OCR(较具体)
|
||||
"click", # 点击(较具体)
|
||||
"swipe", # 滑动(较具体)
|
||||
"flow", # 流程(较具体)
|
||||
"operation", # 操作(较具体)
|
||||
"screenshot", # 截图(较通用,放后面)
|
||||
"stage", # 阶段(较通用)
|
||||
"performance", # 性能(较通用)
|
||||
"error", # 错误(较通用)
|
||||
"success", # 成功(较通用)
|
||||
"info", # 信息(最通用,放最后)
|
||||
]
|
||||
|
||||
# 按优先级顺序检查
|
||||
for op_type in priority_order:
|
||||
if op_type in OPERATION_KEYWORDS:
|
||||
for keyword in OPERATION_KEYWORDS[op_type]:
|
||||
# 避免过于宽泛的关键词误匹配
|
||||
if keyword.lower() in ["截图", "检测", "识别", "成功", "完成", "失败", "错误"]:
|
||||
# 这些关键词太宽泛,只在特定上下文中使用
|
||||
# 检查是否在更具体的上下文中
|
||||
if keyword.lower() == "截图" and ("截图成功" in line_lower or "截图失败" in line_lower or "[截图]" in line):
|
||||
return op_type
|
||||
elif keyword.lower() == "检测" and ("阶段检测" in line_lower or "像素检测" in line_lower or "并行检测" in line_lower):
|
||||
return op_type
|
||||
elif keyword.lower() == "识别" and ("OCR识别" in line_lower or "识别成功" in line_lower or "识别失败" in line_lower):
|
||||
return op_type
|
||||
# 其他宽泛关键词跳过,避免误匹配
|
||||
continue
|
||||
|
||||
if keyword.lower() in line_lower:
|
||||
return op_type
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
获取颜色配置(根据主题)
|
||||
|
||||
Args:
|
||||
theme: 主题名称("litera", "darkly" 等)
|
||||
|
||||
Returns:
|
||||
颜色配置字典,包含每种操作类型的颜色设置
|
||||
"""
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
is_light = theme.lower() in light_themes
|
||||
|
||||
if is_light:
|
||||
# 明亮主题颜色配置(深色文字,与白色背景对比,高区分度)
|
||||
return {
|
||||
"ocr": {
|
||||
"foreground": "#0052CC", # 鲜明蓝色 - OCR识别
|
||||
"background": "#D6E8FF", # 浅蓝色背景
|
||||
},
|
||||
"click": {
|
||||
"foreground": "#D32F2F", # 鲜明红色 - 点击操作
|
||||
"background": "#FFE0E0", # 浅红色背景
|
||||
},
|
||||
"swipe": {
|
||||
"foreground": "#2E7D32", # 鲜明绿色 - 滑动操作
|
||||
"background": "#E0F2E8", # 浅绿色背景
|
||||
},
|
||||
"screenshot": {
|
||||
"foreground": "#7B1FA2", # 鲜明紫色 - 截图操作
|
||||
"background": "#F3E5F5", # 浅紫色背景
|
||||
},
|
||||
"detection": {
|
||||
"foreground": "#F57C00", # 鲜明橙色 - 检测操作
|
||||
"background": "#FFF3E0", # 浅橙色背景
|
||||
},
|
||||
"decision": {
|
||||
"foreground": "#C2185B", # 鲜明品红色 - 决策操作
|
||||
"background": "#FCE4EC", # 浅品红色背景
|
||||
},
|
||||
"reservation": {
|
||||
"foreground": "#00897B", # 鲜明青色 - 预约操作(区别于OCR蓝色)
|
||||
"background": "#E0F2F1", # 浅青色背景
|
||||
},
|
||||
"fansclub": {
|
||||
"foreground": "#8E24AA", # 鲜明紫红色 - 粉丝团操作(区别于截图紫色)
|
||||
"background": "#F3E5F5", # 浅紫红色背景
|
||||
},
|
||||
"lottery": {
|
||||
"foreground": "#E64A19", # 鲜明橙红色 - 开奖相关(区别于点击红色)
|
||||
"background": "#FFEBEE", # 浅橙红色背景
|
||||
},
|
||||
"stage": {
|
||||
"foreground": "#616161", # 深灰色 - 阶段信息
|
||||
"background": "#F5F5F5", # 浅灰色背景
|
||||
},
|
||||
"performance": {
|
||||
"foreground": "#00796B", # 鲜明青绿色 - 性能信息
|
||||
"background": "#E0F2F1", # 浅青绿色背景
|
||||
},
|
||||
"error": {
|
||||
"foreground": "#C62828", # 鲜明深红色 - 错误
|
||||
"background": "#FFCDD2", # 浅红色背景
|
||||
},
|
||||
"success": {
|
||||
"foreground": "#2E7D32", # 鲜明深绿色 - 成功
|
||||
"background": "#C8E6C9", # 浅绿色背景
|
||||
},
|
||||
"info": {
|
||||
"foreground": "#0277BD", # 鲜明天蓝色 - 信息(区别于OCR深蓝色)
|
||||
"background": "#BBDEFB", # 浅天蓝色背景
|
||||
},
|
||||
"flow": {
|
||||
"foreground": "#5D4037", # 深棕色 - 流程操作
|
||||
"background": "#EFEBE9", # 浅棕色背景
|
||||
},
|
||||
"operation": {
|
||||
"foreground": "#455A64", # 深蓝灰色 - 操作动作
|
||||
"background": "#ECEFF1", # 浅蓝灰色背景
|
||||
},
|
||||
}
|
||||
else:
|
||||
# 暗色主题颜色配置(亮色文字,与深色背景对比,高区分度)
|
||||
return {
|
||||
"ocr": {
|
||||
"foreground": "#42A5F5", # 鲜明亮蓝色 - OCR识别
|
||||
"background": "#0D47A1", # 深蓝色背景
|
||||
},
|
||||
"click": {
|
||||
"foreground": "#EF5350", # 鲜明亮红色 - 点击操作
|
||||
"background": "#B71C1C", # 深红色背景
|
||||
},
|
||||
"swipe": {
|
||||
"foreground": "#66BB6A", # 鲜明亮绿色 - 滑动操作
|
||||
"background": "#1B5E20", # 深绿色背景
|
||||
},
|
||||
"screenshot": {
|
||||
"foreground": "#AB47BC", # 鲜明亮紫色 - 截图操作
|
||||
"background": "#4A148C", # 深紫色背景
|
||||
},
|
||||
"detection": {
|
||||
"foreground": "#FFA726", # 鲜明亮橙色 - 检测操作
|
||||
"background": "#E65100", # 深橙色背景
|
||||
},
|
||||
"decision": {
|
||||
"foreground": "#EC407A", # 鲜明亮品红色 - 决策操作
|
||||
"background": "#880E4F", # 深品红色背景
|
||||
},
|
||||
"reservation": {
|
||||
"foreground": "#26A69A", # 鲜明亮青色 - 预约操作(区别于OCR蓝色)
|
||||
"background": "#004D40", # 深青色背景
|
||||
},
|
||||
"fansclub": {
|
||||
"foreground": "#BA68C8", # 鲜明亮紫红色 - 粉丝团操作(区别于截图紫色)
|
||||
"background": "#4A148C", # 深紫红色背景
|
||||
},
|
||||
"lottery": {
|
||||
"foreground": "#FF7043", # 鲜明亮橙红色 - 开奖相关(区别于点击红色)
|
||||
"background": "#BF360C", # 深橙红色背景
|
||||
},
|
||||
"stage": {
|
||||
"foreground": "#90A4AE", # 亮灰色 - 阶段信息
|
||||
"background": "#263238", # 深灰色背景
|
||||
},
|
||||
"performance": {
|
||||
"foreground": "#26A69A", # 鲜明亮青绿色 - 性能信息
|
||||
"background": "#004D40", # 深青绿色背景
|
||||
},
|
||||
"error": {
|
||||
"foreground": "#F44336", # 鲜明亮红色 - 错误
|
||||
"background": "#B71C1C", # 深红色背景
|
||||
},
|
||||
"success": {
|
||||
"foreground": "#66BB6A", # 鲜明亮绿色 - 成功
|
||||
"background": "#1B5E20", # 深绿色背景
|
||||
},
|
||||
"info": {
|
||||
"foreground": "#29B6F6", # 鲜明亮天蓝色 - 信息(区别于OCR深蓝色)
|
||||
"background": "#01579B", # 深天蓝色背景
|
||||
},
|
||||
"flow": {
|
||||
"foreground": "#A1887F", # 亮棕色 - 流程操作
|
||||
"background": "#3E2723", # 深棕色背景
|
||||
},
|
||||
"operation": {
|
||||
"foreground": "#78909C", # 亮蓝灰色 - 操作动作
|
||||
"background": "#263238", # 深蓝灰色背景
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def apply_operation_color(
|
||||
text_widget,
|
||||
start_pos: str,
|
||||
end_pos: str,
|
||||
line: str,
|
||||
theme: str = "litera"
|
||||
) -> None:
|
||||
"""
|
||||
为日志行应用操作类型颜色
|
||||
|
||||
Args:
|
||||
text_widget: tkinter Text 组件
|
||||
start_pos: 起始位置
|
||||
end_pos: 结束位置
|
||||
line: 日志行内容
|
||||
theme: 主题名称
|
||||
"""
|
||||
try:
|
||||
# 识别操作类型
|
||||
op_type = get_operation_type(line)
|
||||
if not op_type:
|
||||
return
|
||||
|
||||
# 获取颜色配置
|
||||
color_config = get_color_config(theme)
|
||||
if op_type not in color_config:
|
||||
return
|
||||
|
||||
colors = color_config[op_type]
|
||||
tag_name = f"op_{op_type}"
|
||||
|
||||
# 配置标签(总是重新配置,确保主题改变时颜色也会更新)
|
||||
text_widget.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
|
||||
# 应用标签
|
||||
text_widget.tag_add(tag_name, start_pos, end_pos)
|
||||
except Exception:
|
||||
# 忽略颜色应用失败,不影响日志显示
|
||||
pass
|
||||
|
||||
|
||||
"""
|
||||
为不同的操作类型定义颜色标签,支持明亮和暗色主题。
|
||||
"""
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
|
||||
# 操作类型关键词映射(用于识别日志中的操作类型)
|
||||
OPERATION_KEYWORDS: Dict[str, list] = {
|
||||
"ocr": [
|
||||
"OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败",
|
||||
"直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果"
|
||||
],
|
||||
"click": [
|
||||
"点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标",
|
||||
"返回", "确认", "关闭", "发送", "加入"
|
||||
],
|
||||
"swipe": [
|
||||
"滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动",
|
||||
"回退", "切换直播间", "切换房间"
|
||||
],
|
||||
"screenshot": [
|
||||
"截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败"
|
||||
],
|
||||
"detection": [
|
||||
"检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配",
|
||||
"检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到"
|
||||
],
|
||||
"decision": [
|
||||
"决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选",
|
||||
"价值过低", "人数过少", "人数过多", "倒计时", "内容不符合"
|
||||
],
|
||||
"reservation": [
|
||||
"预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列",
|
||||
"高价值预约", "预约回退", "预约校验"
|
||||
],
|
||||
"fansclub": [
|
||||
"粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功"
|
||||
],
|
||||
"lottery": [
|
||||
"开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间"
|
||||
],
|
||||
"stage": [
|
||||
"阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE",
|
||||
"LIVE_OR_UNKNOWN", "阶段变化", "阶段流转"
|
||||
],
|
||||
"performance": [
|
||||
"耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率"
|
||||
],
|
||||
"error": [
|
||||
"错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout"
|
||||
],
|
||||
"success": [
|
||||
"成功", "SUCCESS", "完成", "完成", "已", "完成"
|
||||
],
|
||||
"info": [
|
||||
"信息", "INFO", "提示", "注意", "开始", "启动", "停止"
|
||||
],
|
||||
"flow": [
|
||||
"流程", "flow", "处理", "执行", "运行", "完成"
|
||||
],
|
||||
"operation": [
|
||||
"操作", "operation", "动作", "行为"
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def get_operation_type(line: str) -> Optional[str]:
|
||||
"""
|
||||
根据日志行内容识别操作类型
|
||||
|
||||
日志格式通常是: [时间] [GUI] - 操作类型 内容
|
||||
优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等)
|
||||
|
||||
Args:
|
||||
line: 日志行内容
|
||||
|
||||
Returns:
|
||||
操作类型名称,如果无法识别则返回None
|
||||
"""
|
||||
line_lower = line.lower()
|
||||
|
||||
# 优先级1: 识别日志内容开头的操作类型(最精确)
|
||||
# 日志格式: [时间] [GUI] - 操作类型 内容
|
||||
# 例如: [GUI] - 流程 find_and_open_fudai_detail完成
|
||||
# [GUI] - 滑动上滑切换直播间
|
||||
# [GUI] - 阶段诊断开始阶段诊断
|
||||
# [GUI] - 预约[预约]记录直播间标题
|
||||
|
||||
import re
|
||||
# 提取日志内容部分(去掉时间戳和标签)
|
||||
# 匹配格式: [时间] [标签] - 内容
|
||||
content_match = re.search(r'\]\s*-\s*(.+)$', line)
|
||||
if content_match:
|
||||
content = content_match.group(1).strip()
|
||||
content_lower = content.lower()
|
||||
|
||||
# 操作类型关键词映射(按优先级排序,更具体的在前)
|
||||
operation_type_map = [
|
||||
# 检测相关(最具体)
|
||||
("阶段诊断", "detection"),
|
||||
("阶段检测", "detection"),
|
||||
("并行检测", "detection"),
|
||||
("像素检测", "detection"),
|
||||
("模板匹配", "detection"),
|
||||
("检测", "detection"),
|
||||
# 滑动相关
|
||||
("滑动", "swipe"),
|
||||
("上滑", "swipe"),
|
||||
("下滑", "swipe"),
|
||||
("切换直播间", "swipe"),
|
||||
# 预约相关
|
||||
("预约", "reservation"),
|
||||
# OCR相关
|
||||
("OCR", "ocr"),
|
||||
("ocr识别", "ocr"),
|
||||
("识别", "ocr"),
|
||||
# 点击相关
|
||||
("点击", "click"),
|
||||
# 截图相关
|
||||
("截图", "screenshot"),
|
||||
# 流程相关
|
||||
("流程", "flow"),
|
||||
# 决策相关
|
||||
("决策", "decision"),
|
||||
("行为识别", "decision"),
|
||||
# 开奖相关
|
||||
("开奖", "lottery"),
|
||||
("抽奖结果", "lottery"),
|
||||
# 粉丝团相关
|
||||
("粉丝团", "fansclub"),
|
||||
# 操作相关(通用,放后面)
|
||||
("操作", "operation"),
|
||||
# 自救相关
|
||||
("自救", "info"),
|
||||
# 错误相关
|
||||
("错误", "error"),
|
||||
("异常", "error"),
|
||||
# 成功相关
|
||||
("成功", "success"),
|
||||
# 信息相关(最通用,放最后)
|
||||
("信息", "info"),
|
||||
]
|
||||
|
||||
# 检查内容开头是否匹配操作类型
|
||||
for keyword, op_type in operation_type_map:
|
||||
# 检查是否在内容开头(更精确)
|
||||
if content_lower.startswith(keyword.lower()):
|
||||
return op_type
|
||||
# 或者检查是否紧跟在 " - " 后面
|
||||
if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower:
|
||||
return op_type
|
||||
|
||||
# 优先级2: 使用日志标签识别(如果内容中没有匹配到)
|
||||
tag_match = re.search(r'\[([^\]]+)\]', line)
|
||||
if tag_match:
|
||||
tag = tag_match.group(1).lower()
|
||||
|
||||
# 标签到操作类型的映射(精确匹配)
|
||||
tag_to_op_type = {
|
||||
"阶段诊断": "detection",
|
||||
"阶段检测": "detection",
|
||||
"截图": "screenshot",
|
||||
"ocr": "ocr",
|
||||
"ocr识别": "ocr",
|
||||
"点击": "click",
|
||||
"滑动": "swipe",
|
||||
"预约": "reservation",
|
||||
"找福袋图标": "detection",
|
||||
"福袋查找": "detection",
|
||||
"自救": "info",
|
||||
"流程": "flow",
|
||||
"行为识别": "decision",
|
||||
"决策": "decision",
|
||||
"错误": "error",
|
||||
"异常": "error",
|
||||
"成功": "success",
|
||||
"信息": "info",
|
||||
"提示": "info",
|
||||
}
|
||||
|
||||
# 精确匹配标签
|
||||
if tag in tag_to_op_type:
|
||||
return tag_to_op_type[tag]
|
||||
|
||||
# 部分匹配标签(用于更灵活的匹配)
|
||||
for tag_key, op_type in tag_to_op_type.items():
|
||||
if tag_key in tag or tag in tag_key:
|
||||
return op_type
|
||||
|
||||
# 优先级2: 使用关键词匹配(更具体的短语优先)
|
||||
# 定义更具体的关键词短语(按优先级排序)
|
||||
specific_patterns = [
|
||||
# 检测相关(更具体的短语优先)
|
||||
("阶段诊断", "detection"),
|
||||
("阶段检测", "detection"),
|
||||
("像素检测", "detection"),
|
||||
("模板匹配", "detection"),
|
||||
("并行检测", "detection"),
|
||||
# OCR相关
|
||||
("OCR识别", "ocr"),
|
||||
("OCR模式", "ocr"),
|
||||
("识别成功", "ocr"),
|
||||
("识别失败", "ocr"),
|
||||
# 点击相关
|
||||
("点击成功", "click"),
|
||||
("点击失败", "click"),
|
||||
("参与按钮", "click"),
|
||||
# 滑动相关
|
||||
("向上滑动", "swipe"),
|
||||
("向下滑动", "swipe"),
|
||||
("切换直播间", "swipe"),
|
||||
# 预约相关
|
||||
("记录预约", "reservation"),
|
||||
("预约窗口", "reservation"),
|
||||
("预约队列", "reservation"),
|
||||
# 开奖相关
|
||||
("抽奖结果", "lottery"),
|
||||
("等待开奖", "lottery"),
|
||||
("开奖时间", "lottery"),
|
||||
# 粉丝团相关
|
||||
("加入粉丝团", "fansclub"),
|
||||
("粉丝团失败", "fansclub"),
|
||||
("粉丝团成功", "fansclub"),
|
||||
]
|
||||
|
||||
# 先检查更具体的短语
|
||||
for pattern, op_type in specific_patterns:
|
||||
if pattern.lower() in line_lower:
|
||||
return op_type
|
||||
|
||||
# 优先级3: 使用通用关键词匹配(按操作类型优先级)
|
||||
# 调整顺序,让更具体的操作类型优先
|
||||
priority_order = [
|
||||
"lottery", # 开奖相关(更具体)
|
||||
"fansclub", # 粉丝团(更具体)
|
||||
"reservation", # 预约(更具体)
|
||||
"decision", # 决策(更具体)
|
||||
"detection", # 检测(较具体)
|
||||
"ocr", # OCR(较具体)
|
||||
"click", # 点击(较具体)
|
||||
"swipe", # 滑动(较具体)
|
||||
"flow", # 流程(较具体)
|
||||
"operation", # 操作(较具体)
|
||||
"screenshot", # 截图(较通用,放后面)
|
||||
"stage", # 阶段(较通用)
|
||||
"performance", # 性能(较通用)
|
||||
"error", # 错误(较通用)
|
||||
"success", # 成功(较通用)
|
||||
"info", # 信息(最通用,放最后)
|
||||
]
|
||||
|
||||
# 按优先级顺序检查
|
||||
for op_type in priority_order:
|
||||
if op_type in OPERATION_KEYWORDS:
|
||||
for keyword in OPERATION_KEYWORDS[op_type]:
|
||||
# 避免过于宽泛的关键词误匹配
|
||||
if keyword.lower() in ["截图", "检测", "识别", "成功", "完成", "失败", "错误"]:
|
||||
# 这些关键词太宽泛,只在特定上下文中使用
|
||||
# 检查是否在更具体的上下文中
|
||||
if keyword.lower() == "截图" and ("截图成功" in line_lower or "截图失败" in line_lower or "[截图]" in line):
|
||||
return op_type
|
||||
elif keyword.lower() == "检测" and ("阶段检测" in line_lower or "像素检测" in line_lower or "并行检测" in line_lower):
|
||||
return op_type
|
||||
elif keyword.lower() == "识别" and ("OCR识别" in line_lower or "识别成功" in line_lower or "识别失败" in line_lower):
|
||||
return op_type
|
||||
# 其他宽泛关键词跳过,避免误匹配
|
||||
continue
|
||||
|
||||
if keyword.lower() in line_lower:
|
||||
return op_type
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
获取颜色配置(根据主题)
|
||||
|
||||
Args:
|
||||
theme: 主题名称("litera", "darkly" 等)
|
||||
|
||||
Returns:
|
||||
颜色配置字典,包含每种操作类型的颜色设置
|
||||
"""
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
is_light = theme.lower() in light_themes
|
||||
|
||||
if is_light:
|
||||
# 明亮主题颜色配置(深色文字,与白色背景对比,高区分度)
|
||||
return {
|
||||
"ocr": {
|
||||
"foreground": "#0052CC", # 鲜明蓝色 - OCR识别
|
||||
"background": "#D6E8FF", # 浅蓝色背景
|
||||
},
|
||||
"click": {
|
||||
"foreground": "#D32F2F", # 鲜明红色 - 点击操作
|
||||
"background": "#FFE0E0", # 浅红色背景
|
||||
},
|
||||
"swipe": {
|
||||
"foreground": "#2E7D32", # 鲜明绿色 - 滑动操作
|
||||
"background": "#E0F2E8", # 浅绿色背景
|
||||
},
|
||||
"screenshot": {
|
||||
"foreground": "#7B1FA2", # 鲜明紫色 - 截图操作
|
||||
"background": "#F3E5F5", # 浅紫色背景
|
||||
},
|
||||
"detection": {
|
||||
"foreground": "#F57C00", # 鲜明橙色 - 检测操作
|
||||
"background": "#FFF3E0", # 浅橙色背景
|
||||
},
|
||||
"decision": {
|
||||
"foreground": "#C2185B", # 鲜明品红色 - 决策操作
|
||||
"background": "#FCE4EC", # 浅品红色背景
|
||||
},
|
||||
"reservation": {
|
||||
"foreground": "#00897B", # 鲜明青色 - 预约操作(区别于OCR蓝色)
|
||||
"background": "#E0F2F1", # 浅青色背景
|
||||
},
|
||||
"fansclub": {
|
||||
"foreground": "#8E24AA", # 鲜明紫红色 - 粉丝团操作(区别于截图紫色)
|
||||
"background": "#F3E5F5", # 浅紫红色背景
|
||||
},
|
||||
"lottery": {
|
||||
"foreground": "#E64A19", # 鲜明橙红色 - 开奖相关(区别于点击红色)
|
||||
"background": "#FFEBEE", # 浅橙红色背景
|
||||
},
|
||||
"stage": {
|
||||
"foreground": "#616161", # 深灰色 - 阶段信息
|
||||
"background": "#F5F5F5", # 浅灰色背景
|
||||
},
|
||||
"performance": {
|
||||
"foreground": "#00796B", # 鲜明青绿色 - 性能信息
|
||||
"background": "#E0F2F1", # 浅青绿色背景
|
||||
},
|
||||
"error": {
|
||||
"foreground": "#C62828", # 鲜明深红色 - 错误
|
||||
"background": "#FFCDD2", # 浅红色背景
|
||||
},
|
||||
"success": {
|
||||
"foreground": "#2E7D32", # 鲜明深绿色 - 成功
|
||||
"background": "#C8E6C9", # 浅绿色背景
|
||||
},
|
||||
"info": {
|
||||
"foreground": "#0277BD", # 鲜明天蓝色 - 信息(区别于OCR深蓝色)
|
||||
"background": "#BBDEFB", # 浅天蓝色背景
|
||||
},
|
||||
"flow": {
|
||||
"foreground": "#5D4037", # 深棕色 - 流程操作
|
||||
"background": "#EFEBE9", # 浅棕色背景
|
||||
},
|
||||
"operation": {
|
||||
"foreground": "#455A64", # 深蓝灰色 - 操作动作
|
||||
"background": "#ECEFF1", # 浅蓝灰色背景
|
||||
},
|
||||
}
|
||||
else:
|
||||
# 暗色主题颜色配置(亮色文字,与深色背景对比,高区分度)
|
||||
return {
|
||||
"ocr": {
|
||||
"foreground": "#42A5F5", # 鲜明亮蓝色 - OCR识别
|
||||
"background": "#0D47A1", # 深蓝色背景
|
||||
},
|
||||
"click": {
|
||||
"foreground": "#EF5350", # 鲜明亮红色 - 点击操作
|
||||
"background": "#B71C1C", # 深红色背景
|
||||
},
|
||||
"swipe": {
|
||||
"foreground": "#66BB6A", # 鲜明亮绿色 - 滑动操作
|
||||
"background": "#1B5E20", # 深绿色背景
|
||||
},
|
||||
"screenshot": {
|
||||
"foreground": "#AB47BC", # 鲜明亮紫色 - 截图操作
|
||||
"background": "#4A148C", # 深紫色背景
|
||||
},
|
||||
"detection": {
|
||||
"foreground": "#FFA726", # 鲜明亮橙色 - 检测操作
|
||||
"background": "#E65100", # 深橙色背景
|
||||
},
|
||||
"decision": {
|
||||
"foreground": "#EC407A", # 鲜明亮品红色 - 决策操作
|
||||
"background": "#880E4F", # 深品红色背景
|
||||
},
|
||||
"reservation": {
|
||||
"foreground": "#26A69A", # 鲜明亮青色 - 预约操作(区别于OCR蓝色)
|
||||
"background": "#004D40", # 深青色背景
|
||||
},
|
||||
"fansclub": {
|
||||
"foreground": "#BA68C8", # 鲜明亮紫红色 - 粉丝团操作(区别于截图紫色)
|
||||
"background": "#4A148C", # 深紫红色背景
|
||||
},
|
||||
"lottery": {
|
||||
"foreground": "#FF7043", # 鲜明亮橙红色 - 开奖相关(区别于点击红色)
|
||||
"background": "#BF360C", # 深橙红色背景
|
||||
},
|
||||
"stage": {
|
||||
"foreground": "#90A4AE", # 亮灰色 - 阶段信息
|
||||
"background": "#263238", # 深灰色背景
|
||||
},
|
||||
"performance": {
|
||||
"foreground": "#26A69A", # 鲜明亮青绿色 - 性能信息
|
||||
"background": "#004D40", # 深青绿色背景
|
||||
},
|
||||
"error": {
|
||||
"foreground": "#F44336", # 鲜明亮红色 - 错误
|
||||
"background": "#B71C1C", # 深红色背景
|
||||
},
|
||||
"success": {
|
||||
"foreground": "#66BB6A", # 鲜明亮绿色 - 成功
|
||||
"background": "#1B5E20", # 深绿色背景
|
||||
},
|
||||
"info": {
|
||||
"foreground": "#29B6F6", # 鲜明亮天蓝色 - 信息(区别于OCR深蓝色)
|
||||
"background": "#01579B", # 深天蓝色背景
|
||||
},
|
||||
"flow": {
|
||||
"foreground": "#A1887F", # 亮棕色 - 流程操作
|
||||
"background": "#3E2723", # 深棕色背景
|
||||
},
|
||||
"operation": {
|
||||
"foreground": "#78909C", # 亮蓝灰色 - 操作动作
|
||||
"background": "#263238", # 深蓝灰色背景
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def apply_operation_color(
|
||||
text_widget,
|
||||
start_pos: str,
|
||||
end_pos: str,
|
||||
line: str,
|
||||
theme: str = "litera"
|
||||
) -> None:
|
||||
"""
|
||||
为日志行应用操作类型颜色
|
||||
|
||||
Args:
|
||||
text_widget: tkinter Text 组件
|
||||
start_pos: 起始位置
|
||||
end_pos: 结束位置
|
||||
line: 日志行内容
|
||||
theme: 主题名称
|
||||
"""
|
||||
try:
|
||||
# 识别操作类型
|
||||
op_type = get_operation_type(line)
|
||||
if not op_type:
|
||||
return
|
||||
|
||||
# 获取颜色配置
|
||||
color_config = get_color_config(theme)
|
||||
if op_type not in color_config:
|
||||
return
|
||||
|
||||
colors = color_config[op_type]
|
||||
tag_name = f"op_{op_type}"
|
||||
|
||||
# 配置标签(总是重新配置,确保主题改变时颜色也会更新)
|
||||
text_widget.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
|
||||
# 应用标签
|
||||
text_widget.tag_add(tag_name, start_pos, end_pos)
|
||||
except Exception:
|
||||
# 忽略颜色应用失败,不影响日志显示
|
||||
pass
|
||||
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
日志颜色配置模块
|
||||
================
|
||||
|
||||
为不同的操作类型定义颜色标签,支持明亮和暗色主题。
|
||||
"""
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
|
||||
# 操作类型关键词映射(用于识别日志中的操作类型)
|
||||
OPERATION_KEYWORDS: Dict[str, list] = {
|
||||
"ocr": [
|
||||
"OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败",
|
||||
"直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果"
|
||||
],
|
||||
"click": [
|
||||
"点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标",
|
||||
"返回", "确认", "关闭", "发送", "加入"
|
||||
],
|
||||
"swipe": [
|
||||
"滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动",
|
||||
"回退", "切换直播间", "切换房间"
|
||||
],
|
||||
"screenshot": [
|
||||
"截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败"
|
||||
],
|
||||
"detection": [
|
||||
"检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配",
|
||||
"检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到"
|
||||
],
|
||||
"decision": [
|
||||
"决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选",
|
||||
"价值过低", "人数过少", "人数过多", "倒计时", "内容不符合"
|
||||
],
|
||||
"reservation": [
|
||||
"预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列",
|
||||
"高价值预约", "预约回退", "预约校验"
|
||||
],
|
||||
"fansclub": [
|
||||
"粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功"
|
||||
],
|
||||
"lottery": [
|
||||
"开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间"
|
||||
],
|
||||
"stage": [
|
||||
"阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE",
|
||||
"LIVE_OR_UNKNOWN", "阶段变化", "阶段流转"
|
||||
],
|
||||
"performance": [
|
||||
"性能", "耗时", "time", "duration", "elapsed", "ms", "毫秒", "秒",
|
||||
"执行时间", "处理时间", "检测时间"
|
||||
],
|
||||
"error": [
|
||||
"错误", "error", "exception", "失败", "fail", "timeout", "超时",
|
||||
"异常", "崩溃", "中断", "连接失败"
|
||||
],
|
||||
"info": [
|
||||
"信息", "info", "开始", "完成", "初始化", "启动", "停止",
|
||||
"日志", "debug", "调试"
|
||||
],
|
||||
"network": [
|
||||
"网络", "network", "连接", "请求", "响应", "http", "api",
|
||||
"服务器", "接口", "上传", "下载"
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def get_operation_type(line: str) -> Optional[str]:
|
||||
"""
|
||||
根据日志行内容识别操作类型
|
||||
|
||||
日志格式通常是: [时间] [GUI] - 操作类型 内容
|
||||
优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等)
|
||||
|
||||
Args:
|
||||
line: 日志行内容
|
||||
|
||||
Returns:
|
||||
操作类型名称,如果无法识别则返回None
|
||||
"""
|
||||
line_lower = line.lower()
|
||||
|
||||
# 优先级1: 识别日志内容开头的操作类型(最精确)
|
||||
# 日志格式: [时间] [GUI] - 操作类型 内容
|
||||
# 例如: [GUI] - 流程 find_and_open_fudai_detail完成
|
||||
if "[gui] -" in line_lower:
|
||||
parts = line_lower.split("[gui] -")
|
||||
if len(parts) > 1:
|
||||
content = parts[1].strip()
|
||||
# 提取操作类型(第一个词)
|
||||
first_word = content.split()[0] if content.split() else ""
|
||||
if first_word in ["流程", "滑动", "阶段诊断", "预约", "截图", "点击", "识别", "检测"]:
|
||||
return first_word
|
||||
|
||||
# 优先级2: 关键词匹配(更全面的识别)
|
||||
for operation_type, keywords in OPERATION_KEYWORDS.items():
|
||||
for keyword in keywords:
|
||||
if keyword.lower() in line_lower:
|
||||
return operation_type
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
根据主题获取颜色配置
|
||||
|
||||
Args:
|
||||
theme: 主题名称,如 'litera'(明亮), 'darkly'(暗色), 'cyborg'(深色)
|
||||
|
||||
Returns:
|
||||
颜色配置字典,包含各操作类型的颜色设置
|
||||
"""
|
||||
# 基础颜色配置
|
||||
if theme in ["litera", "minty", "pulse", "solar", "united", "yeti"]:
|
||||
# 明亮主题
|
||||
base_config = {
|
||||
"ocr": {"foreground": "#2E8B57", "background": "#F0FFF0"}, # 绿色
|
||||
"click": {"foreground": "#4169E1", "background": "#F0F8FF"}, # 蓝色
|
||||
"swipe": {"foreground": "#FF6347", "background": "#FFF5EE"}, # 红色
|
||||
"screenshot": {"foreground": "#8B4513", "background": "#FFF8DC"}, # 棕色
|
||||
"detection": {"foreground": "#9932CC", "background": "#F8F8FF"}, # 紫色
|
||||
"decision": {"foreground": "#FF8C00", "background": "#FFFACD"}, # 橙色
|
||||
"reservation": {"foreground": "#20B2AA", "background": "#F0FFFF"}, # 青色
|
||||
"fansclub": {"foreground": "#DC143C", "background": "#FFE4E1"}, # 粉红
|
||||
"lottery": {"foreground": "#FFD700", "background": "#FFFFE0"}, # 金色
|
||||
"stage": {"foreground": "#8B008B", "background": "#F0F0F0"}, # 深紫
|
||||
"performance": {"foreground": "#696969", "background": "#F5F5F5"}, # 灰色
|
||||
"error": {"foreground": "#B22222", "background": "#FFE4E1"}, # 深红
|
||||
"info": {"foreground": "#000000", "background": "#FFFFFF"}, # 黑色
|
||||
"network": {"foreground": "#4682B4", "background": "#F0F8FF"} # 钢蓝
|
||||
}
|
||||
else:
|
||||
# 暗色主题
|
||||
base_config = {
|
||||
"ocr": {"foreground": "#98FB98", "background": "#2F4F2F"}, # 亮绿
|
||||
"click": {"foreground": "#87CEEB", "background": "#191970"}, # 亮蓝
|
||||
"swipe": {"foreground": "#FFA07A", "background": "#8B0000"}, # 亮红
|
||||
"screenshot": {"foreground": "#F4A460", "background": "#8B4513"}, # 沙色
|
||||
"detection": {"foreground": "#DDA0DD", "background": "#4B0082"}, # 梅红
|
||||
"decision": {"foreground": "#FFDAB9", "background": "#FF8C00"}, # 桃色
|
||||
"reservation": {"foreground": "#AFEEEE", "background": "#008B8B"}, # 淡青
|
||||
"fansclub": {"foreground": "#FFB6C1", "background": "#8B0000"}, # 浅粉
|
||||
"lottery": {"foreground": "#FFFF00", "background": "#FFD700"}, # 亮黄
|
||||
"stage": {"foreground": "#DDA0DD", "background": "#2F2F2F"}, # 梅红
|
||||
"performance": {"foreground": "#D3D3D3", "background": "#696969"}, # 浅灰
|
||||
"error": {"foreground": "#FFA07A", "background": "#B22222"}, # 亮红
|
||||
"info": {"foreground": "#FFFFFF", "background": "#000000"}, # 白色
|
||||
"network": {"foreground": "#87CEEB", "background": "#4682B4"} # 亮蓝
|
||||
}
|
||||
|
||||
return base_config
|
||||
|
||||
|
||||
def apply_operation_color(
|
||||
text_widget,
|
||||
start_pos: str,
|
||||
end_pos: str,
|
||||
operation_type: Optional[str],
|
||||
theme: str = "litera"
|
||||
) -> None:
|
||||
"""
|
||||
为日志文本中的指定范围应用操作类型颜色标签
|
||||
|
||||
Args:
|
||||
text_widget: Tkinter文本控件
|
||||
start_pos: 开始位置(如 "1.0")
|
||||
end_pos: 结束位置(如 "1.end")
|
||||
operation_type: 操作类型(None表示不应用颜色)
|
||||
theme: 主题名称
|
||||
"""
|
||||
try:
|
||||
if operation_type is None:
|
||||
return
|
||||
|
||||
# 获取颜色配置
|
||||
color_config = get_color_config(theme)
|
||||
colors = color_config.get(operation_type)
|
||||
|
||||
if colors is None:
|
||||
return
|
||||
|
||||
# 创建唯一标签名
|
||||
tag_name = f"operation_{operation_type}"
|
||||
|
||||
# 配置标签(总是重新配置,确保主题改变时颜色也会更新)
|
||||
text_widget.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
|
||||
# 应用标签
|
||||
text_widget.tag_add(tag_name, start_pos, end_pos)
|
||||
except Exception:
|
||||
# 忽略颜色应用失败,不影响日志显示
|
||||
pass
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Optional, List, Dict
|
||||
from typing import Any, Callable, Optional, List, Dict, Tuple
|
||||
import queue
|
||||
import re
|
||||
import threading
|
||||
@@ -44,7 +44,7 @@ except ImportError:
|
||||
class EnhancedLogViewer(ttk.Frame):
|
||||
"""增强的日志查看器组件"""
|
||||
|
||||
def __init__(self, parent: Any, log_queue: "queue.Queue[str]" = None):
|
||||
def __init__(self, parent: Any, log_queue: Optional[queue.Queue] = None):
|
||||
super().__init__(parent)
|
||||
|
||||
# 初始化数据
|
||||
@@ -372,9 +372,9 @@ def format_gui_log_line(line: str) -> str:
|
||||
|
||||
def create_log_viewer(
|
||||
parent: Any,
|
||||
log_queue: "queue.Queue[str]",
|
||||
log_queue: Optional[queue.Queue],
|
||||
on_line: Callable[[str], None]
|
||||
) -> tuple[ScrolledText, Callable[[], None]]:
|
||||
) -> Any:
|
||||
"""创建日志查看器组件(兼容旧接口)。
|
||||
|
||||
参数:
|
||||
|
||||
@@ -49,3 +49,25 @@ def create_main_window(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -50,3 +50,25 @@ def create_ocr_panel(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+370
-144
@@ -27,6 +27,22 @@ from gui.gui_core import (
|
||||
)
|
||||
from path_config import get_logs_dir
|
||||
|
||||
# 导入日志颜色配置模块
|
||||
try:
|
||||
from gui.components.log_color_config import (
|
||||
get_color_config,
|
||||
apply_operation_color,
|
||||
get_operation_type,
|
||||
)
|
||||
except ImportError:
|
||||
# 如果模块不存在,使用空函数作为回退
|
||||
def get_color_config(theme: str = "litera"):
|
||||
return {}
|
||||
def apply_operation_color(*args, **kwargs):
|
||||
pass
|
||||
def get_operation_type(line: str) -> str | None:
|
||||
return None
|
||||
|
||||
# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告)
|
||||
warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning)
|
||||
warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning)
|
||||
@@ -1087,7 +1103,7 @@ def main():
|
||||
|
||||
row4c = ttk.Frame(fudai_find_box)
|
||||
row4c.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(row4c, text="直播间检测阈值:").pack(side=LEFT)
|
||||
ttk.Label(row4c, text="直播间检测阈值(白色像素比例):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4c,
|
||||
from_=0.0,
|
||||
@@ -1096,7 +1112,7 @@ def main():
|
||||
textvariable=live_room_match_threshold_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4c, text="(0.0~1.0,默认0.7,值越高越严格)").pack(
|
||||
ttk.Label(row4c, text="(0.0~1.0,默认0.8,多边形区域白色像素比例>=此值判定为在直播间)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
@@ -1623,7 +1639,7 @@ def main():
|
||||
cfg2["stage_diag_max_step_time"] = float(
|
||||
stage_diag_max_step_time_var.get() or 2.0
|
||||
)
|
||||
cfg2["enable_ocr_mode1"] = bool(enable_ocr_mode1_var.get())
|
||||
cfg2["enable_ocr_mode1"] = bool(cfg.get("enable_ocr_mode1", False))
|
||||
cfg2["fudai_template_match_enabled"] = bool(
|
||||
fudai_template_match_enabled_var.get()
|
||||
)
|
||||
@@ -1941,6 +1957,7 @@ def main():
|
||||
high_value_tab = ttk.Frame(notebook)
|
||||
actions_log_tab = ttk.Frame(notebook)
|
||||
ocr_results_tab = ttk.Frame(notebook)
|
||||
win_record_tab = ttk.Frame(notebook)
|
||||
notebook.add(log_tab, text="运行日志")
|
||||
notebook.add(preview_tab, text="截图预览")
|
||||
notebook.add(stats_tab, text="统计信息")
|
||||
@@ -1948,6 +1965,7 @@ def main():
|
||||
notebook.add(high_value_tab, text="高价值房间")
|
||||
notebook.add(actions_log_tab, text="行为日志")
|
||||
notebook.add(ocr_results_tab, text="OCR结果")
|
||||
notebook.add(win_record_tab, text="中奖记录")
|
||||
|
||||
# 日志区
|
||||
log_box = ttk.Frame(log_tab)
|
||||
@@ -2100,6 +2118,19 @@ def main():
|
||||
log_text.tag_configure("log_critical", foreground="#F44336", font=("Consolas", 10, "bold")) # 加粗亮红色
|
||||
log_text.tag_configure("log_performance", foreground="#81C784") # 亮绿色,性能数据
|
||||
log_text.tag_configure("log_module", foreground="#BA68C8") # 亮紫色,模块标识
|
||||
|
||||
# 配置操作类型颜色标签(使用模块化配置)
|
||||
try:
|
||||
color_config = get_color_config(current_theme)
|
||||
for op_type, colors in color_config.items():
|
||||
tag_name = f"op_{op_type}"
|
||||
log_text.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略操作类型颜色配置失败
|
||||
except Exception:
|
||||
pass # 忽略标签配置失败
|
||||
|
||||
@@ -2273,7 +2304,6 @@ def main():
|
||||
0 if infinite_loop_var.get() else int(wait_minutes_var.get() or 5)
|
||||
)
|
||||
return RunParams(
|
||||
enable_ocr_mode1=bool(enable_ocr_mode1_var.get()),
|
||||
device_id=device_var.get().strip(),
|
||||
y_pianyi=int(y_var.get()),
|
||||
needswitch=bool(needswitch_var.get()),
|
||||
@@ -2287,26 +2317,15 @@ def main():
|
||||
auto_join_fansclub=bool(auto_join_var.get()),
|
||||
fansclub_fail_action=str(fansclub_action_var.get() or "stay").lower(),
|
||||
# Web端新增参数
|
||||
high_value_room_revisit_enabled=bool(
|
||||
high_value_room_revisit_enabled_var.get()
|
||||
),
|
||||
high_value_room_revisit_only_current_run=bool(
|
||||
high_value_room_revisit_only_current_run_var.get()
|
||||
),
|
||||
reservation_back_verify_enabled=bool(
|
||||
reservation_back_verify_enabled_var.get()
|
||||
),
|
||||
reservation_back_swipe_delay=float(
|
||||
reservation_back_swipe_delay_var.get() or 0
|
||||
),
|
||||
reservation_preempt_min_value=float(
|
||||
reservation_preempt_min_value_var.get() or 0
|
||||
),
|
||||
fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 0),
|
||||
high_value_room_revisit_enabled=bool(high_value_room_revisit_enabled_var.get()),
|
||||
high_value_room_revisit_only_current_run=bool(high_value_room_revisit_only_current_run_var.get()),
|
||||
reservation_back_verify_enabled=bool(reservation_back_verify_enabled_var.get()),
|
||||
reservation_back_swipe_delay=float(reservation_back_swipe_delay_var.get() or 1.0),
|
||||
reservation_preempt_min_value=float(reservation_preempt_min_value_var.get() or 1000),
|
||||
fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 5),
|
||||
enable_ocr_mode1=bool(enable_ocr_mode1_var.get()),
|
||||
fudai_template_match_enabled=bool(fudai_template_match_enabled_var.get()),
|
||||
fudai_template_match_threshold=float(
|
||||
fudai_template_match_threshold_var.get() or 0.7
|
||||
),
|
||||
fudai_template_match_threshold=float(fudai_template_match_threshold_var.get() or 0.7),
|
||||
)
|
||||
|
||||
def start_run():
|
||||
@@ -2354,57 +2373,7 @@ def main():
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3)
|
||||
test_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
|
||||
)
|
||||
ttk.Label(actions, text="测试养号(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
actions, from_=10, to=3600, increment=10, textvariable=test_seconds_var, width=8
|
||||
).pack(side=LEFT, padx=(0, 8))
|
||||
|
||||
def start_test_yanghao():
|
||||
if runner.is_running():
|
||||
on_line("[运行] 已在运行中")
|
||||
return
|
||||
save_ui_to_config()
|
||||
secs = int(test_seconds_var.get() or 90)
|
||||
dev = device_var.get().strip()
|
||||
on_line(f"[测试] 启动养号流程:device={dev or '(auto)'} seconds={secs}")
|
||||
status_var.set("运行中")
|
||||
try:
|
||||
runner.start_test_yanghao_flow(dev, secs)
|
||||
except Exception as e:
|
||||
status_var.set("启动失败")
|
||||
on_line(f"[错误] {e}")
|
||||
|
||||
ttk.Button(actions, text="测试养号流程", command=start_test_yanghao).pack(side=LEFT)
|
||||
|
||||
ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3)
|
||||
test_comment_var = tk.StringVar(value="测试评论")
|
||||
ttk.Label(actions, text="测试评论:").pack(side=LEFT)
|
||||
ttk.Entry(actions, textvariable=test_comment_var, width=12).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
def start_test_comment():
|
||||
if runner.is_running():
|
||||
on_line("[运行] 已在运行中")
|
||||
return
|
||||
save_ui_to_config()
|
||||
text = test_comment_var.get().strip()
|
||||
dev = device_var.get().strip()
|
||||
on_line(f"[测试] 启动评论测试:device={dev or '(auto)'} text={text}")
|
||||
status_var.set("运行中")
|
||||
try:
|
||||
runner.start_test_comment(dev, text)
|
||||
except Exception as e:
|
||||
status_var.set("启动失败")
|
||||
on_line(f"[错误] {e}")
|
||||
|
||||
ttk.Button(actions, text="测试评论", command=start_test_comment).pack(side=LEFT)
|
||||
|
||||
ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3)
|
||||
# (已移除:测试养号/测试评论 按钮与相关UI)
|
||||
|
||||
def send_back_key():
|
||||
dev = device_var.get().strip()
|
||||
@@ -2422,37 +2391,56 @@ def main():
|
||||
def pump_logs():
|
||||
changed = False
|
||||
try:
|
||||
# 获取当前主题(用于颜色配置)
|
||||
try:
|
||||
current_theme = str(gui_theme_var.get() or "litera")
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
while True:
|
||||
line = q.get_nowait()
|
||||
try:
|
||||
# 插入日志行并应用颜色标签
|
||||
start_pos = log_text.index("end-1c")
|
||||
|
||||
# 检查是否需要应用颜色标签
|
||||
tag = None
|
||||
if "[INFO]" in line:
|
||||
tag = "log_info"
|
||||
elif "[WARNING]" in line:
|
||||
tag = "log_warning"
|
||||
elif "[ERROR]" in line:
|
||||
tag = "log_error"
|
||||
elif "[CRITICAL]" in line:
|
||||
tag = "log_critical"
|
||||
elif "elapsed_seconds=" in line or "耗时" in line:
|
||||
tag = "log_performance"
|
||||
elif re.search(r'\[[\w\.]+\]', line):
|
||||
tag = "log_module"
|
||||
|
||||
# 插入文本
|
||||
log_text.insert("end", line + "\n")
|
||||
end_pos = log_text.index("end-1c")
|
||||
|
||||
# 如果有标签,应用到这一行
|
||||
if tag:
|
||||
end_pos = log_text.index("end-1c")
|
||||
# 优先级1: 先检查操作类型颜色(更具体)
|
||||
op_type_applied = False
|
||||
try:
|
||||
op_type = get_operation_type(line)
|
||||
if op_type:
|
||||
apply_operation_color(
|
||||
log_text, start_pos, end_pos, line, current_theme
|
||||
)
|
||||
op_type_applied = True
|
||||
except Exception:
|
||||
pass # 忽略操作类型颜色应用失败
|
||||
|
||||
# 优先级2: 再检查日志级别标签(作为补充,如果操作类型未匹配)
|
||||
# 只有在没有操作类型颜色时才应用级别标签
|
||||
if not op_type_applied:
|
||||
try:
|
||||
log_text.tag_add(tag, start_pos, end_pos)
|
||||
tag = None
|
||||
if "[INFO]" in line:
|
||||
tag = "log_info"
|
||||
elif "[WARNING]" in line:
|
||||
tag = "log_warning"
|
||||
elif "[ERROR]" in line:
|
||||
tag = "log_error"
|
||||
elif "[CRITICAL]" in line:
|
||||
tag = "log_critical"
|
||||
elif "elapsed_seconds=" in line or "耗时" in line:
|
||||
tag = "log_performance"
|
||||
elif re.search(r'\[[\w\.]+\]', line):
|
||||
tag = "log_module"
|
||||
|
||||
if tag:
|
||||
log_text.tag_add(tag, start_pos, end_pos)
|
||||
except Exception:
|
||||
pass # 忽略标签应用失败
|
||||
pass # 忽略级别标签应用失败
|
||||
|
||||
# 不再自动滚动到底部,让用户自由控制滚动位置
|
||||
changed = True
|
||||
@@ -3430,35 +3418,43 @@ def main():
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 配置行为日志颜色标签(与主日志保持一致)
|
||||
try:
|
||||
# 根据主题调整行为日志颜色
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
# 配置行为日志颜色标签(使用统一的颜色配置模块)
|
||||
def configure_actions_log_colors():
|
||||
"""根据当前主题配置行为日志的颜色标签"""
|
||||
try:
|
||||
current_theme = str(gui_theme_var.get() or "litera")
|
||||
# 获取当前主题
|
||||
try:
|
||||
current_theme = str(gui_theme_var.get() or "litera")
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
# 获取颜色配置
|
||||
color_config = get_color_config(current_theme)
|
||||
|
||||
# 根据主题设置背景和前景色
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
is_light = current_theme.lower() in light_themes
|
||||
if is_light:
|
||||
actions_log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C")
|
||||
else:
|
||||
actions_log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF")
|
||||
|
||||
# 为所有操作类型配置标签
|
||||
for op_type, colors in color_config.items():
|
||||
tag_name = f"op_{op_type}"
|
||||
try:
|
||||
actions_log_text.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略标签配置失败
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
if current_theme in light_themes:
|
||||
# 明亮主题
|
||||
actions_log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C")
|
||||
actions_log_text.tag_configure("action_timestamp", foreground="#8B8B8B")
|
||||
actions_log_text.tag_configure("action_operation", foreground="#1E88E5") # 蓝色操作
|
||||
actions_log_text.tag_configure("action_ocr", foreground="#388E3C") # 绿色OCR
|
||||
actions_log_text.tag_configure("action_decision", foreground="#F57C00") # 橙色决策
|
||||
actions_log_text.tag_configure("action_state", foreground="#7B1FA2") # 紫色状态
|
||||
actions_log_text.tag_configure("action_performance", foreground="#D32F2F") # 红色性能
|
||||
else:
|
||||
# 暗色主题
|
||||
actions_log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF")
|
||||
actions_log_text.tag_configure("action_timestamp", foreground="#A0A0A0")
|
||||
actions_log_text.tag_configure("action_operation", foreground="#64B5F6") # 亮蓝色操作
|
||||
actions_log_text.tag_configure("action_ocr", foreground="#81C784") # 亮绿色OCR
|
||||
actions_log_text.tag_configure("action_decision", foreground="#FFB74D") # 金色决策
|
||||
actions_log_text.tag_configure("action_state", foreground="#BA68C8") # 亮紫色状态
|
||||
actions_log_text.tag_configure("action_performance", foreground="#EF5350") # 亮红色性能
|
||||
except Exception:
|
||||
pass # 忽略颜色配置失败
|
||||
pass # 忽略颜色配置失败
|
||||
|
||||
# 初始配置
|
||||
configure_actions_log_colors()
|
||||
|
||||
actions_filter_var = tk.StringVar(value="")
|
||||
|
||||
@@ -3515,6 +3511,12 @@ def main():
|
||||
|
||||
actions_log_text.delete("1.0", "end")
|
||||
if tail:
|
||||
# 获取当前主题(用于颜色配置)
|
||||
try:
|
||||
current_theme = str(gui_theme_var.get() or "litera")
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
# 逐行插入并应用颜色标签
|
||||
for i, line in enumerate(tail):
|
||||
start_pos = actions_log_text.index("end-1c")
|
||||
@@ -3524,29 +3526,18 @@ def main():
|
||||
actions_log_text.insert("end", "\n")
|
||||
actions_log_text.insert("end", line)
|
||||
|
||||
# 根据内容类型应用颜色标签
|
||||
# 使用统一的颜色配置模块应用颜色
|
||||
end_pos = actions_log_text.index("end")
|
||||
tag = None
|
||||
|
||||
if "操作:" in line or "执行" in line:
|
||||
tag = "action_operation"
|
||||
elif "OCR" in line or "识别" in line:
|
||||
tag = "action_ocr"
|
||||
elif "决策" in line or "判断" in line:
|
||||
tag = "action_decision"
|
||||
elif "状态" in line or "阶段" in line:
|
||||
tag = "action_state"
|
||||
elif "耗时" in line or "时间" in line or "性能" in line:
|
||||
tag = "action_performance"
|
||||
elif re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', line):
|
||||
tag = "action_timestamp"
|
||||
|
||||
# 应用标签
|
||||
if tag:
|
||||
try:
|
||||
actions_log_text.tag_add(tag, start_pos, end_pos)
|
||||
except Exception:
|
||||
pass # 忽略标签应用失败
|
||||
try:
|
||||
apply_operation_color(
|
||||
actions_log_text,
|
||||
start_pos,
|
||||
end_pos,
|
||||
line,
|
||||
current_theme
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略颜色应用失败
|
||||
else:
|
||||
actions_log_text.insert("1.0", "暂无匹配的行为日志")
|
||||
|
||||
@@ -3719,6 +3710,240 @@ def main():
|
||||
side=LEFT, padx=(10, 0)
|
||||
)
|
||||
|
||||
# 中奖记录显示
|
||||
win_record_top = ttk.Frame(win_record_tab)
|
||||
win_record_top.pack(fill=X, padx=10, pady=(10, 0))
|
||||
|
||||
win_record_left = ttk.Frame(win_record_tab)
|
||||
win_record_left.pack(side=LEFT, fill=BOTH, expand=True, padx=(10, 5), pady=10)
|
||||
|
||||
win_record_right = ttk.Frame(win_record_tab)
|
||||
win_record_right.pack(side=RIGHT, fill=BOTH, expand=False, padx=(5, 10), pady=10, ipadx=10)
|
||||
|
||||
# 左侧:中奖截图列表
|
||||
win_list_label = ttk.Label(win_record_left, text="中奖截图列表:")
|
||||
win_list_label.pack(anchor="w", padx=(0, 10), pady=(0, 5))
|
||||
|
||||
win_list_frame = ttk.Frame(win_record_left)
|
||||
win_list_frame.pack(fill=BOTH, expand=True)
|
||||
|
||||
win_list_scrollbar = ttk.Scrollbar(win_list_frame)
|
||||
win_list_scrollbar.pack(side=RIGHT, fill=Y)
|
||||
|
||||
win_listbox = tk.Listbox(win_list_frame, yscrollcommand=win_list_scrollbar.set, font=("Consolas", 9))
|
||||
win_listbox.pack(side=LEFT, fill=BOTH, expand=True)
|
||||
win_list_scrollbar.config(command=win_listbox.yview)
|
||||
|
||||
# 存储文件路径映射(索引 -> 文件路径)
|
||||
_win_file_paths: dict[int, str] = {}
|
||||
|
||||
# 右侧:截图预览
|
||||
win_preview_label = ttk.Label(win_record_right, text="截图预览:")
|
||||
win_preview_label.pack(anchor="w", pady=(0, 5))
|
||||
|
||||
win_preview_frame = ttk.Frame(win_record_right)
|
||||
win_preview_frame.pack(fill=BOTH, expand=True)
|
||||
|
||||
win_image_label = ttk.Label(win_preview_frame)
|
||||
win_image_label.pack(fill=BOTH, expand=True)
|
||||
_win_img_ref: dict[str, Any] = {"photo": None}
|
||||
|
||||
def scan_win_images():
|
||||
"""扫描中奖截图目录"""
|
||||
try:
|
||||
from path_config import get_pic_dir
|
||||
pic_dir = get_pic_dir()
|
||||
except Exception:
|
||||
import path_config
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
|
||||
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
||||
win_images = []
|
||||
|
||||
if os.path.exists(prize_dir):
|
||||
for file in os.listdir(prize_dir):
|
||||
if file.lower().endswith((".png", ".jpg", ".jpeg")):
|
||||
file_path = os.path.join(prize_dir, file)
|
||||
# 获取文件修改时间
|
||||
try:
|
||||
mtime = os.path.getmtime(file_path)
|
||||
win_images.append((file, file_path, mtime))
|
||||
except Exception:
|
||||
win_images.append((file, file_path, 0))
|
||||
|
||||
# 按时间倒序排序(最新的在前)
|
||||
win_images.sort(key=lambda x: x[2], reverse=True)
|
||||
return win_images
|
||||
|
||||
def refresh_win_record():
|
||||
"""刷新中奖记录列表"""
|
||||
try:
|
||||
win_images = scan_win_images()
|
||||
win_listbox.delete(0, tk.END)
|
||||
_win_file_paths.clear()
|
||||
|
||||
for idx, (file, file_path, mtime) in enumerate(win_images):
|
||||
# 格式化显示:文件名 + 时间
|
||||
try:
|
||||
from datetime import datetime
|
||||
dt = datetime.fromtimestamp(mtime)
|
||||
time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
display_text = f"{file} ({time_str})"
|
||||
except Exception:
|
||||
display_text = file
|
||||
|
||||
win_listbox.insert(tk.END, display_text)
|
||||
# 存储文件路径映射
|
||||
_win_file_paths[idx] = file_path
|
||||
|
||||
if win_images:
|
||||
on_line(f"[中奖记录] 扫描到 {len(win_images)} 张中奖截图")
|
||||
else:
|
||||
on_line("[中奖记录] 暂无中奖截图")
|
||||
except Exception as e:
|
||||
on_line(f"[中奖记录] 刷新失败:{e}")
|
||||
|
||||
def on_win_list_select(event):
|
||||
"""当选择中奖截图时,显示预览"""
|
||||
try:
|
||||
selection = win_listbox.curselection()
|
||||
if not selection:
|
||||
return
|
||||
|
||||
index = selection[0]
|
||||
# 从映射中获取文件路径
|
||||
if index in _win_file_paths:
|
||||
file_path = _win_file_paths[index]
|
||||
_load_win_image(file_path)
|
||||
except Exception as e:
|
||||
on_line(f"[中奖记录] 预览失败:{e}")
|
||||
|
||||
def _load_win_image(img_path: str):
|
||||
"""加载并显示中奖截图"""
|
||||
if not os.path.exists(img_path):
|
||||
win_image_label.configure(image="")
|
||||
_win_img_ref["photo"] = None
|
||||
return
|
||||
|
||||
try:
|
||||
img = Image.open(img_path)
|
||||
img.load()
|
||||
img = img.convert("RGB")
|
||||
except Exception as e:
|
||||
on_line(f"[中奖记录] 图片加载失败:{e}")
|
||||
return
|
||||
|
||||
# 获取预览区域尺寸
|
||||
try:
|
||||
win_preview_frame.update_idletasks()
|
||||
w = win_preview_frame.winfo_width()
|
||||
h = win_preview_frame.winfo_height()
|
||||
if w <= 1 or h <= 1:
|
||||
w, h = 400, 600
|
||||
except Exception:
|
||||
w, h = 400, 600
|
||||
|
||||
max_w = max(200, w - 20)
|
||||
max_h = max(300, h - 20)
|
||||
|
||||
try:
|
||||
resample = Image.Resampling.LANCZOS
|
||||
except AttributeError:
|
||||
resample = 1
|
||||
|
||||
img.thumbnail((max_w, max_h), resample)
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
_win_img_ref["photo"] = photo
|
||||
win_image_label.configure(image=photo)
|
||||
|
||||
win_listbox.bind("<<ListboxSelect>>", on_win_list_select)
|
||||
|
||||
ttk.Button(win_record_top, text="刷新列表", command=refresh_win_record).pack(side=LEFT, padx=(0, 10))
|
||||
|
||||
def open_win_folder():
|
||||
"""打开中奖截图目录"""
|
||||
try:
|
||||
from path_config import get_pic_dir
|
||||
pic_dir = get_pic_dir()
|
||||
except Exception:
|
||||
import path_config
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
|
||||
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
||||
os.makedirs(prize_dir, exist_ok=True)
|
||||
try:
|
||||
os.startfile(prize_dir) # type: ignore[attr-defined]
|
||||
except Exception as e:
|
||||
on_line(f"[中奖记录] 打开目录失败:{e}")
|
||||
|
||||
ttk.Button(win_record_top, text="打开目录", command=open_win_folder).pack(side=LEFT)
|
||||
|
||||
# 误识别记录管理
|
||||
false_positive_frame = ttk.LabelFrame(win_record_right, text="误识别记录管理")
|
||||
false_positive_frame.pack(fill=X, pady=(10, 0))
|
||||
|
||||
false_positive_text = ScrolledText(false_positive_frame, height=6)
|
||||
false_positive_text.pack(fill=X, padx=10, pady=10)
|
||||
|
||||
def load_false_positives():
|
||||
"""加载误识别记录"""
|
||||
try:
|
||||
from path_config import get_pic_dir
|
||||
pic_dir = get_pic_dir()
|
||||
except Exception:
|
||||
import path_config
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
|
||||
false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json")
|
||||
if not os.path.exists(false_positive_file):
|
||||
false_positive_text.delete("1.0", "end")
|
||||
false_positive_text.insert("1.0", "暂无误识别记录")
|
||||
return
|
||||
|
||||
try:
|
||||
import json
|
||||
with open(false_positive_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
false_positives = data.get("false_positives", [])
|
||||
false_positive_text.delete("1.0", "end")
|
||||
if false_positives:
|
||||
false_positive_text.insert("1.0", "\n".join(false_positives))
|
||||
else:
|
||||
false_positive_text.insert("1.0", "暂无误识别记录")
|
||||
except Exception as e:
|
||||
false_positive_text.delete("1.0", "end")
|
||||
false_positive_text.insert("1.0", f"加载失败:{e}")
|
||||
|
||||
def save_false_positives():
|
||||
"""保存误识别记录"""
|
||||
try:
|
||||
from path_config import get_pic_dir
|
||||
pic_dir = get_pic_dir()
|
||||
except Exception:
|
||||
import path_config
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
|
||||
false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json")
|
||||
os.makedirs(os.path.dirname(false_positive_file), exist_ok=True)
|
||||
|
||||
content = false_positive_text.get("1.0", "end-1c")
|
||||
lines = [line.strip() for line in content.splitlines() if line.strip()]
|
||||
|
||||
try:
|
||||
import json
|
||||
with open(false_positive_file, "w", encoding="utf-8") as f:
|
||||
json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2)
|
||||
on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录")
|
||||
except Exception as e:
|
||||
on_line(f"[中奖记录] 保存失败:{e}")
|
||||
|
||||
false_positive_btn_frame = ttk.Frame(false_positive_frame)
|
||||
false_positive_btn_frame.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Button(false_positive_btn_frame, text="刷新", command=load_false_positives).pack(side=LEFT, padx=(0, 5))
|
||||
ttk.Button(false_positive_btn_frame, text="保存", command=save_false_positives).pack(side=LEFT)
|
||||
|
||||
load_false_positives()
|
||||
|
||||
pump_logs()
|
||||
|
||||
def delayed_refresh_preview() -> None:
|
||||
@@ -3730,6 +3955,7 @@ def main():
|
||||
root.after(500, refresh_reservations) # type: ignore[arg-type]
|
||||
root.after(500, refresh_high_value_rooms) # type: ignore[arg-type]
|
||||
root.after(500, refresh_actions_log) # type: ignore[arg-type]
|
||||
root.after(500, refresh_win_record) # type: ignore[arg-type]
|
||||
|
||||
# 定期刷新行为日志(每2秒)
|
||||
def auto_refresh_actions_log() -> None:
|
||||
@@ -3771,4 +3997,4 @@ if __name__ == "__main__":
|
||||
print_version_banner("gui_app")
|
||||
except Exception:
|
||||
pass
|
||||
main()
|
||||
main()
|
||||
+7
-166
@@ -894,172 +894,9 @@ class Runner:
|
||||
self._reader_thread = threading.Thread(target=_reader, daemon=True)
|
||||
self._reader_thread.start()
|
||||
|
||||
def start_test_yanghao_flow(self, device_id: str, seconds: int) -> None:
|
||||
if self.is_running():
|
||||
raise RuntimeError("已经在运行")
|
||||
# (已移除) 测试养号启动器
|
||||
|
||||
seconds = int(seconds or 0)
|
||||
if seconds <= 0:
|
||||
seconds = 90
|
||||
|
||||
run_cli_path = path_config.get_run_cli_path()
|
||||
if not os.path.exists(run_cli_path):
|
||||
raise FileNotFoundError(
|
||||
f"未找到 run_cli.py 文件。\n"
|
||||
f"预期路径: {run_cli_path}\n"
|
||||
f"请确保 run_cli.py 位于项目根目录。"
|
||||
)
|
||||
cmd = [
|
||||
sys.executable,
|
||||
run_cli_path,
|
||||
"--test-yanghao-flow",
|
||||
"--test-yanghao-flow-seconds",
|
||||
str(seconds),
|
||||
]
|
||||
if device_id:
|
||||
cmd += ["--device-id", device_id]
|
||||
|
||||
env = os.environ.copy()
|
||||
env.setdefault("PYTHONIOENCODING", "utf-8")
|
||||
|
||||
adb_exe = find_adb_executable()
|
||||
if adb_exe:
|
||||
adb_dir = os.path.dirname(adb_exe)
|
||||
env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "")
|
||||
env["ADB_EXECUTABLE"] = adb_exe
|
||||
else:
|
||||
self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH")
|
||||
|
||||
p = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
env=env,
|
||||
cwd=path_config.PROJECT_ROOT,
|
||||
)
|
||||
|
||||
with self._lock:
|
||||
self._proc = p
|
||||
self._pid = p.pid
|
||||
self._start_ts = time.time()
|
||||
self._exit_code = None
|
||||
self._last_log_ts = time.time()
|
||||
self._counters = {}
|
||||
self._fudai_last = {
|
||||
"content": "",
|
||||
"countdown": "",
|
||||
"participants": None,
|
||||
"copies": None,
|
||||
"prize_value_yuan": None,
|
||||
"updated_ts": None,
|
||||
}
|
||||
self._events = []
|
||||
self._wins = []
|
||||
|
||||
def _reader():
|
||||
assert self._proc is not None
|
||||
out = self._proc.stdout
|
||||
if out is None:
|
||||
return
|
||||
for line in out:
|
||||
cleaned_line = line.rstrip("\n")
|
||||
self._on_line(cleaned_line)
|
||||
try:
|
||||
self._update_stats_from_line(cleaned_line)
|
||||
except Exception:
|
||||
pass
|
||||
rc = self._proc.wait()
|
||||
with self._lock:
|
||||
self._exit_code = rc
|
||||
self._on_line(f"[进程结束] exit_code={rc}")
|
||||
|
||||
self._reader_thread = threading.Thread(target=_reader, daemon=True)
|
||||
self._reader_thread.start()
|
||||
|
||||
def start_test_comment(self, device_id: str, text: str) -> None:
|
||||
if self.is_running():
|
||||
raise RuntimeError("已经在运行")
|
||||
|
||||
text = str(text or "").strip()
|
||||
run_cli_path = path_config.get_run_cli_path()
|
||||
if not os.path.exists(run_cli_path):
|
||||
raise FileNotFoundError(
|
||||
f"未找到 run_cli.py 文件。\n"
|
||||
f"预期路径: {run_cli_path}\n"
|
||||
f"请确保 run_cli.py 位于项目根目录。"
|
||||
)
|
||||
cmd = [
|
||||
sys.executable,
|
||||
run_cli_path,
|
||||
"--test-comment",
|
||||
]
|
||||
if text:
|
||||
cmd += ["--test-comment-text", text]
|
||||
if device_id:
|
||||
cmd += ["--device-id", device_id]
|
||||
|
||||
env = os.environ.copy()
|
||||
env.setdefault("PYTHONIOENCODING", "utf-8")
|
||||
|
||||
adb_exe = find_adb_executable()
|
||||
if adb_exe:
|
||||
adb_dir = os.path.dirname(adb_exe)
|
||||
env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "")
|
||||
env["ADB_EXECUTABLE"] = adb_exe
|
||||
else:
|
||||
self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH")
|
||||
|
||||
p = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
env=env,
|
||||
cwd=path_config.PROJECT_ROOT,
|
||||
)
|
||||
|
||||
with self._lock:
|
||||
self._proc = p
|
||||
self._pid = p.pid
|
||||
self._start_ts = time.time()
|
||||
self._exit_code = None
|
||||
self._last_log_ts = time.time()
|
||||
self._counters = {}
|
||||
self._fudai_last = {
|
||||
"content": "",
|
||||
"countdown": "",
|
||||
"participants": None,
|
||||
"copies": None,
|
||||
"prize_value_yuan": None,
|
||||
"updated_ts": None,
|
||||
}
|
||||
self._events = []
|
||||
self._wins = []
|
||||
|
||||
def _reader():
|
||||
assert self._proc is not None
|
||||
out = self._proc.stdout
|
||||
if out is None:
|
||||
return
|
||||
for line in out:
|
||||
cleaned_line = line.rstrip("\n")
|
||||
self._on_line(cleaned_line)
|
||||
try:
|
||||
self._update_stats_from_line(cleaned_line)
|
||||
except Exception:
|
||||
pass
|
||||
rc = self._proc.wait()
|
||||
with self._lock:
|
||||
self._exit_code = rc
|
||||
self._on_line(f"[进程结束] exit_code={rc}")
|
||||
|
||||
self._reader_thread = threading.Thread(target=_reader, daemon=True)
|
||||
self._reader_thread.start()
|
||||
# (已移除) 测试评论启动器
|
||||
|
||||
def send_back_key(self, device_id: str) -> bool:
|
||||
"""手动发送返回键到指定设备。
|
||||
@@ -1153,7 +990,11 @@ class Runner:
|
||||
# 类 Unix:尝试向进程组发送 SIGKILL
|
||||
import signal
|
||||
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except AttributeError:
|
||||
# 如果SIGKILL不存在,使用SIGTERM
|
||||
os.kill(pid, signal.SIGTERM)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -17,3 +17,25 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -25,3 +25,25 @@ __all__ = ["ProcRunner"]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+16
-37
@@ -825,12 +825,13 @@ class ProcRunner:
|
||||
|
||||
def get_reservations(self) -> dict:
|
||||
"""获取当前预约队列信息(来自子进程写入的 douyin/core/state/reservations.json)。"""
|
||||
try:
|
||||
import path_config
|
||||
path = path_config.get_reservations_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
path = path_config.get_reservations_path()
|
||||
if hasattr(path_config, "get_reservations_path"):
|
||||
try:
|
||||
path = path_config.get_reservations_path()
|
||||
except Exception:
|
||||
path = os.path.join(path_config.PROJECT_ROOT if hasattr(path_config, "PROJECT_ROOT") else os.getcwd(), "douyin", "state", "reservations.json")
|
||||
else:
|
||||
path = os.path.join(os.getcwd(), "douyin", "state", "reservations.json")
|
||||
try:
|
||||
if os.path.exists(path):
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
@@ -1577,13 +1578,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
n = int((qs.get("lines") or [200])[0])
|
||||
except Exception:
|
||||
n = 200
|
||||
# 使用统一的路径配置
|
||||
try:
|
||||
import path_config
|
||||
path = path_config.get_actions_log_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
path = path_config.get_actions_log_path()
|
||||
# 使用统一的路径配置(优先使用 path_config 中的配置,失败时回退到项目内置路径)
|
||||
if hasattr(path_config, "get_actions_log_path"):
|
||||
try:
|
||||
path = path_config.get_actions_log_path()
|
||||
except Exception:
|
||||
path = os.path.join(path_config.PROJECT_ROOT if hasattr(path_config, "PROJECT_ROOT") else os.getcwd(), "logs", "actions.log")
|
||||
else:
|
||||
path = os.path.join(os.getcwd(), "logs", "actions.log")
|
||||
out_lines: list[str] = []
|
||||
try:
|
||||
if os.path.exists(path):
|
||||
@@ -1779,29 +1781,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self._send_json({"ok": False, "error": str(e)}, status=500)
|
||||
return self._send_json({"ok": True})
|
||||
|
||||
if u.path == "/api/test-yanghao":
|
||||
if RUNNER.is_running():
|
||||
return self._send_json({"ok": False, "error": "running"}, status=409)
|
||||
body = self._read_json()
|
||||
device_id = str(body.get("device_id") or "").strip()
|
||||
seconds = int(body.get("seconds") or 60)
|
||||
try:
|
||||
RUNNER.start_test_yanghao(device_id, seconds)
|
||||
except Exception as e:
|
||||
return self._send_json({"ok": False, "error": str(e)}, status=500)
|
||||
return self._send_json({"ok": True})
|
||||
|
||||
if u.path == "/api/test-comment":
|
||||
if RUNNER.is_running():
|
||||
return self._send_json({"ok": False, "error": "running"}, status=409)
|
||||
body = self._read_json()
|
||||
device_id = str(body.get("device_id") or "").strip()
|
||||
text = str(body.get("text") or "").strip()
|
||||
try:
|
||||
RUNNER.start_test_comment(device_id, text)
|
||||
except Exception as e:
|
||||
return self._send_json({"ok": False, "error": str(e)}, status=500)
|
||||
return self._send_json({"ok": True})
|
||||
# (已移除) /api/test-yanghao 与 /api/test-comment 接口已删除
|
||||
|
||||
if u.path == "/api/stop":
|
||||
RUNNER.stop()
|
||||
@@ -1854,7 +1834,6 @@ def main() -> int:
|
||||
raise
|
||||
print(f"Web GUI: http://{host}:{port}")
|
||||
print("- 可在页面里设置养号时长/间隔并保存到 config.json")
|
||||
print("- 可一键运行‘测试养号流程’,日志会在页面里滚动显示")
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
|
||||
@@ -38,7 +38,7 @@ class OCRProcessor:
|
||||
# 首先尝试EasyOCR
|
||||
try:
|
||||
# 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题
|
||||
import easyocr # type: ignore[import-untyped] # pyright: ignore[reportMissingImports]
|
||||
import easyocr # type: ignore[import-untyped, import] # pyright: ignore[reportMissingImports, reportMissingModuleSource]
|
||||
|
||||
# 只加载中文和英文,加快初始化速度
|
||||
# 自动检测GPU可用性,如果可用则启用GPU加速
|
||||
@@ -67,19 +67,8 @@ class OCRProcessor:
|
||||
), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||||
# 使用 PaddleOCR(强制 CPU 模式,不进行 GPU 检测)
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
|
||||
if (
|
||||
paddle.device.is_compiled_with_cuda()
|
||||
and paddle.device.get_device()
|
||||
):
|
||||
use_gpu = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
@@ -90,8 +79,7 @@ class OCRProcessor:
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||||
print(f"[OCR] EasyOCR不可用,使用 PaddleOCR({gpu_status})")
|
||||
print(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)")
|
||||
print(
|
||||
f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr"
|
||||
)
|
||||
@@ -146,19 +134,8 @@ class OCRProcessor:
|
||||
):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||||
# 使用 PaddleOCR(强制 CPU 模式)
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
|
||||
if (
|
||||
paddle.device.is_compiled_with_cuda()
|
||||
and paddle.device.get_device()
|
||||
):
|
||||
use_gpu = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
@@ -169,8 +146,7 @@ class OCRProcessor:
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR({gpu_status})")
|
||||
print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR(CPU模式)")
|
||||
except Exception as e:
|
||||
print(f"[OCR] OCR引擎初始化失败: {e}")
|
||||
self.ocr = None
|
||||
@@ -228,4 +204,4 @@ __all__ = [
|
||||
"extract_ocr_content",
|
||||
"_ensure_ocr",
|
||||
]
|
||||
|
||||
|
||||
+1
-18
@@ -108,24 +108,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
default=0,
|
||||
help="运行时长(分钟),0或负数表示无限运行,默认0(无限运行)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--test-yanghao-flow",
|
||||
action="store_true",
|
||||
help="测试:只执行一次推荐页养号流程并退出",
|
||||
)
|
||||
p.add_argument(
|
||||
"--test-yanghao-flow-seconds",
|
||||
type=int,
|
||||
default=10,
|
||||
help="测试:推荐页养号停留秒数",
|
||||
)
|
||||
|
||||
p.add_argument(
|
||||
"--test-comment",
|
||||
action="store_true",
|
||||
help="测试:按配置坐标执行一次评论输入+键盘确认发送并退出",
|
||||
)
|
||||
p.add_argument("--test-comment-text", default="测试评论123", help="测试评论内容")
|
||||
# (已移除) 测试相关的命令行参数(测试养号、测试评论)
|
||||
|
||||
# 允许从 GUI 覆盖关键配置(不改动 config.json 也能生效)
|
||||
p.add_argument(
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# 区域选择器 - 白色像素统计工具
|
||||
|
||||
## 功能说明
|
||||
|
||||
这个工具用于在图片上选择区域,圈出边框,并统计该区域内的白色像素数量。主要用于识别直播间图标等需要根据白色像素比例来判断的场景。
|
||||
|
||||
## 主要功能
|
||||
|
||||
1. **图片查看和导航**
|
||||
- 支持多种图片格式:PNG, JPG, JPEG, BMP, WebP
|
||||
- 上一张/下一张图片切换
|
||||
- 拖放图片文件到窗口直接打开
|
||||
|
||||
2. **图片缩放和平移**
|
||||
- 鼠标滚轮缩放
|
||||
- Ctrl+滚轮快速缩放
|
||||
- 右键拖拽平移图片
|
||||
- 适应窗口大小
|
||||
- 重置缩放
|
||||
|
||||
3. **区域选择**
|
||||
- 左键拖拽选择矩形区域
|
||||
- 红色虚线显示选择区域
|
||||
- 实时显示选择区域坐标和尺寸
|
||||
|
||||
4. **白色像素分析**
|
||||
- 统计选中区域内的白色像素数量
|
||||
- 计算白色像素比例
|
||||
- 计算置信度(基于白色比例与0.5的距离)
|
||||
- 自动保存分析结果
|
||||
|
||||
5. **数据管理**
|
||||
- 保存/加载区域数据到JSON文件
|
||||
- 显示所有保存的区域
|
||||
- 清除选择或清除所有区域
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 启动工具
|
||||
|
||||
```bash
|
||||
# 从tools目录运行
|
||||
python region_selector.py
|
||||
|
||||
# 或者直接指定图片路径
|
||||
python region_selector.py path/to/image.png
|
||||
```
|
||||
|
||||
### 基本操作
|
||||
|
||||
1. **打开图片**
|
||||
- 点击"文件" -> "打开" 或按 Ctrl+O
|
||||
- 或者直接拖放图片文件到窗口
|
||||
|
||||
2. **选择区域**
|
||||
- 按住鼠标左键拖拽选择矩形区域
|
||||
- 红色虚线会显示选择的区域
|
||||
|
||||
3. **缩放和平移**
|
||||
- 鼠标滚轮:缩放
|
||||
- Ctrl+滚轮:快速缩放
|
||||
- 右键拖拽:平移图片
|
||||
- 视图菜单:放大/缩小/重置/适应窗口
|
||||
|
||||
4. **分析区域**
|
||||
- 选择区域后,按 Enter 键或点击"分析区域"按钮
|
||||
- 结果会显示在右侧面板和控制台
|
||||
|
||||
5. **管理数据**
|
||||
- Ctrl+S:保存区域数据到JSON文件
|
||||
- Ctrl+L:加载区域数据
|
||||
- "显示所有":查看所有保存的区域数据
|
||||
|
||||
## 快捷键
|
||||
|
||||
| 快捷键 | 功能 |
|
||||
|--------|------|
|
||||
| Ctrl+O | 打开图片 |
|
||||
| ← / → | 上一张/下一张图片 |
|
||||
| + / - | 放大/缩小 |
|
||||
| Ctrl+0 | 重置缩放 |
|
||||
| Ctrl+F | 适应窗口 |
|
||||
| Delete | 清除选择 |
|
||||
| Enter | 分析区域 |
|
||||
| Ctrl+S | 保存区域数据 |
|
||||
| Ctrl+A | 显示所有区域 |
|
||||
|
||||
## 输出格式
|
||||
|
||||
分析结果包括:
|
||||
- 区域坐标:(x1, y1) - (x2, y2)
|
||||
- 区域尺寸:宽度x高度
|
||||
- 总像素数
|
||||
- 白色像素数
|
||||
- 白色像素比例
|
||||
- 置信度
|
||||
|
||||
## 数据文件格式
|
||||
|
||||
保存的JSON文件包含每个区域的完整信息:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"coordinates": [x1, y1, x2, y2],
|
||||
"size": [width, height],
|
||||
"total_pixels": 1234,
|
||||
"white_pixels": 567,
|
||||
"white_ratio": 0.459,
|
||||
"image_path": "path/to/image.png"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## 应用场景
|
||||
|
||||
- 直播间图标识别:通过白色像素比例判断是否为直播状态
|
||||
- UI元素检测:识别界面上的特定图标或按钮
|
||||
- 图像分析:统计图像中特定区域的颜色分布
|
||||
|
||||
## 技术说明
|
||||
|
||||
- 使用PIL (Pillow) 进行图像处理
|
||||
- 使用tkinter创建GUI界面
|
||||
- 支持numpy进行高效的像素统计
|
||||
- 白色像素阈值:RGB值都≥240的像素被认为是白色
|
||||
|
||||
|
||||
+300
-30
@@ -30,14 +30,23 @@ class CoordPicker:
|
||||
self.w = 0
|
||||
self.h = 0
|
||||
self.scale = 1.0
|
||||
self.min_scale = 0.1 # 最小缩放比例
|
||||
self.max_scale = 10.0 # 最大缩放比例
|
||||
self.disp_w = 0
|
||||
self.disp_h = 0
|
||||
self.tk_img = None
|
||||
self.file_list: list[Path] = []
|
||||
self.file_idx: int = -1
|
||||
self.zoom_center_x = 0 # 缩放中心点
|
||||
self.zoom_center_y = 0
|
||||
self.scroll_offset_x = 0 # 滚动偏移
|
||||
self.scroll_offset_y = 0
|
||||
self.magnifier_window = None # 放大镜窗口
|
||||
self.magnifier_size = 200 # 放大镜窗口大小
|
||||
self.magnifier_zoom = 8 # 放大倍数
|
||||
|
||||
# 使用 TkinterDnD 支持拖放(如果可用)
|
||||
if HAS_DND:
|
||||
if HAS_DND and TkinterDnD is not None:
|
||||
self.root = TkinterDnD.Tk()
|
||||
else:
|
||||
self.root = tk.Tk()
|
||||
@@ -51,27 +60,59 @@ class CoordPicker:
|
||||
file_menu.add_separator()
|
||||
file_menu.add_command(label="退出", command=self.root.destroy)
|
||||
menubar.add_cascade(label="文件", menu=file_menu)
|
||||
|
||||
view_menu = tk.Menu(menubar, tearoff=0)
|
||||
view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+ / Ctrl+滚轮上")
|
||||
view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="- / Ctrl+滚轮下")
|
||||
view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0")
|
||||
view_menu.add_separator()
|
||||
view_menu.add_command(label="显示/隐藏放大镜", command=self.toggle_magnifier, accelerator="M")
|
||||
menubar.add_cascade(label="视图", menu=view_menu)
|
||||
|
||||
self.root.config(menu=menubar)
|
||||
self.root.bind_all("<Control-o>", lambda e: self.open_dialog())
|
||||
self.root.bind("<Left>", lambda e: self.prev_image())
|
||||
self.root.bind("<Right>", lambda e: self.next_image())
|
||||
self.root.bind("<Prior>", lambda e: self.prev_image()) # PageUp
|
||||
self.root.bind("<Next>", lambda e: self.next_image()) # PageDown
|
||||
self.root.bind("<plus>", lambda e: self.zoom_in())
|
||||
self.root.bind("<equal>", lambda e: self.zoom_in()) # 无Shift的+键
|
||||
self.root.bind("<minus>", lambda e: self.zoom_out())
|
||||
self.root.bind("<Control-0>", lambda e: self.reset_zoom())
|
||||
self.root.bind("<Key-m>", lambda e: self.toggle_magnifier())
|
||||
self.root.bind("<Key-M>", lambda e: self.toggle_magnifier())
|
||||
|
||||
self.canvas = tk.Canvas(self.root, width=800, height=600)
|
||||
self.canvas.pack(fill=tk.BOTH, expand=False)
|
||||
self.canvas.pack(fill=tk.BOTH, expand=True)
|
||||
self._canvas_image_id = self.canvas.create_image(0, 0, anchor=tk.NW)
|
||||
|
||||
self.status = tk.StringVar()
|
||||
if HAS_DND:
|
||||
self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片;或直接拖放图片到窗口")
|
||||
self.status.set("移动鼠标查看坐标;单击复制坐标;滚轮缩放;右键显示放大镜;Ctrl+O 打开图片;或直接拖放图片到窗口")
|
||||
else:
|
||||
self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片(提示:安装 tkinterdnd2 可支持拖放)")
|
||||
self.status.set("移动鼠标查看坐标;单击复制坐标;滚轮缩放;右键显示放大镜;Ctrl+O 打开图片(提示:安装 tkinterdnd2 可支持拖放)")
|
||||
self.label = tk.Label(self.root, textvariable=self.status, anchor="w")
|
||||
self.label.pack(fill=tk.X)
|
||||
|
||||
# 像素信息显示
|
||||
self.pixel_info = tk.StringVar()
|
||||
self.pixel_info.set("")
|
||||
self.pixel_label = tk.Label(self.root, textvariable=self.pixel_info, anchor="w", font=("Courier", 10))
|
||||
self.pixel_label.pack(fill=tk.X)
|
||||
|
||||
self.canvas.bind("<Motion>", self.on_move)
|
||||
self.canvas.bind("<Button-1>", self.on_click)
|
||||
self.canvas.bind("<Button-3>", self.on_right_click) # 右键显示放大镜
|
||||
self.canvas.bind("<MouseWheel>", self.on_mousewheel) # Windows/Linux
|
||||
self.canvas.bind("<Button-4>", self.on_mousewheel) # Linux
|
||||
self.canvas.bind("<Button-5>", self.on_mousewheel) # Linux
|
||||
self.canvas.bind("<Control-MouseWheel>", self.on_mousewheel_ctrl) # Ctrl+滚轮
|
||||
self.canvas.bind("<B1-Motion>", self.on_drag) # 拖拽平移
|
||||
self.canvas.bind("<ButtonPress-1>", self.on_drag_start)
|
||||
self.canvas.bind("<ButtonRelease-1>", self.on_drag_end)
|
||||
self.drag_start_x = 0
|
||||
self.drag_start_y = 0
|
||||
self.is_dragging = False
|
||||
|
||||
# 添加拖放支持
|
||||
if HAS_DND:
|
||||
@@ -113,28 +154,8 @@ class CoordPicker:
|
||||
self._refresh_file_list(image_path)
|
||||
|
||||
# 显示用缩放(不改变输出坐标)
|
||||
screen_w = self.root.winfo_screenwidth()
|
||||
screen_h = self.root.winfo_screenheight()
|
||||
max_w = int(screen_w * 0.9)
|
||||
max_h = int(screen_h * 0.85)
|
||||
scale_w = max_w / max(1, self.w)
|
||||
scale_h = max_h / max(1, self.h)
|
||||
self.scale = min(1.0, scale_w, scale_h)
|
||||
self.disp_w = int(self.w * self.scale)
|
||||
self.disp_h = int(self.h * self.scale)
|
||||
|
||||
disp_img = self.img
|
||||
if self.scale < 1.0:
|
||||
try:
|
||||
resample = Image.Resampling.BICUBIC # Pillow>=9
|
||||
except Exception:
|
||||
resample = Image.BICUBIC # older Pillow
|
||||
disp_img = self.img.resize((self.disp_w, self.disp_h), resample)
|
||||
|
||||
self.tk_img = ImageTk.PhotoImage(disp_img)
|
||||
self.canvas.config(width=self.disp_w, height=self.disp_h)
|
||||
self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img)
|
||||
self.root.title(f"取坐标: {image_path} ({self.w}x{self.h})")
|
||||
self._update_display()
|
||||
self.root.title(f"取坐标: {image_path} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x")
|
||||
|
||||
def open_dialog(self) -> bool:
|
||||
initial_dir = None
|
||||
@@ -164,24 +185,273 @@ class CoordPicker:
|
||||
def _to_image_xy(self, event) -> tuple[int, int]:
|
||||
if not self.img or self.w <= 0 or self.h <= 0:
|
||||
return 0, 0
|
||||
x = int(clamp(event.x / self.scale, 0, self.w - 1))
|
||||
y = int(clamp(event.y / self.scale, 0, self.h - 1))
|
||||
# 把canvas坐标转换为图像坐标(考虑缩放和滚动偏移)
|
||||
canvas_x = event.x + self.scroll_offset_x
|
||||
canvas_y = event.y + self.scroll_offset_y
|
||||
x = int(clamp(canvas_x / self.scale, 0, self.w - 1))
|
||||
y = int(clamp(canvas_y / self.scale, 0, self.h - 1))
|
||||
return x, y
|
||||
|
||||
def _update_display(self):
|
||||
"""更新显示"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
# 获取canvas实际大小
|
||||
self.root.update_idletasks()
|
||||
canvas_w = max(1, self.canvas.winfo_width())
|
||||
canvas_h = max(1, self.canvas.winfo_height())
|
||||
|
||||
# 计算显示尺寸
|
||||
self.disp_w = int(self.w * self.scale)
|
||||
self.disp_h = int(self.h * self.scale)
|
||||
|
||||
# 限制滚动偏移
|
||||
max_offset_x = max(0, self.disp_w - canvas_w)
|
||||
max_offset_y = max(0, self.disp_h - canvas_h)
|
||||
self.scroll_offset_x = max(0, min(self.scroll_offset_x, max_offset_x))
|
||||
self.scroll_offset_y = max(0, min(self.scroll_offset_y, max_offset_y))
|
||||
|
||||
# 生成显示图像
|
||||
try:
|
||||
resample = Image.Resampling.BICUBIC if hasattr(Image, 'Resampling') else Image.BICUBIC
|
||||
except Exception:
|
||||
resample = Image.BICUBIC
|
||||
|
||||
if self.scale != 1.0:
|
||||
# 如果放大,只显示可见区域以提高性能
|
||||
if self.scale > 1.0 and canvas_w < self.disp_w and canvas_h < self.disp_h:
|
||||
# 计算原图中要显示的区域
|
||||
src_x1 = max(0, int(self.scroll_offset_x / self.scale))
|
||||
src_y1 = max(0, int(self.scroll_offset_y / self.scale))
|
||||
src_x2 = min(self.w, src_x1 + int(canvas_w / self.scale) + 2)
|
||||
src_y2 = min(self.h, src_y1 + int(canvas_h / self.scale) + 2)
|
||||
|
||||
# 裁剪并放大
|
||||
crop_img = self.img.crop((src_x1, src_y1, src_x2, src_y2))
|
||||
crop_w, crop_h = crop_img.size
|
||||
disp_img = crop_img.resize((int(crop_w * self.scale), int(crop_h * self.scale)), resample)
|
||||
else:
|
||||
# 缩小或完全显示
|
||||
disp_img = self.img.resize((self.disp_w, self.disp_h), resample)
|
||||
else:
|
||||
disp_img = self.img
|
||||
|
||||
self.tk_img = ImageTk.PhotoImage(disp_img)
|
||||
|
||||
# 更新canvas滚动区域
|
||||
self.canvas.config(scrollregion=(0, 0, self.disp_w, self.disp_h))
|
||||
|
||||
# 更新图像位置
|
||||
self.canvas.coords(self._canvas_image_id, -self.scroll_offset_x, -self.scroll_offset_y)
|
||||
self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img)
|
||||
|
||||
# 更新标题
|
||||
if self.image_path:
|
||||
self.root.title(f"取坐标: {self.image_path.name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x")
|
||||
|
||||
def on_move(self, event):
|
||||
"""移动鼠标:显示坐标和像素信息(保留你原来的坐标逻辑)"""
|
||||
x, y = self._to_image_xy(event)
|
||||
self.status.set(f"x={x}, y={y}")
|
||||
rgb_info = ""
|
||||
if self.img and 0 <= x < self.w and 0 <= y < self.h:
|
||||
try:
|
||||
pixel = self.img.getpixel((x, y))
|
||||
if isinstance(pixel, tuple) and len(pixel) >= 3:
|
||||
rgb_info = f" | RGB({pixel[0]}, {pixel[1]}, {pixel[2]})"
|
||||
elif isinstance(pixel, int):
|
||||
rgb_info = f" | Gray({pixel})"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.status.set(f"x={x}, y={y}{rgb_info}")
|
||||
self.pixel_info.set(f"像素位置: ({x}, {y}){rgb_info}")
|
||||
|
||||
# 更新放大镜
|
||||
if self.magnifier_window and self.magnifier_window.winfo_exists():
|
||||
self._update_magnifier(x, y)
|
||||
|
||||
def on_click(self, event):
|
||||
"""左键点击:输出到终端 + 复制到剪贴板(恢复你之前的简单行为)"""
|
||||
x, y = self._to_image_xy(event)
|
||||
text = f"{x},{y}"
|
||||
print(text)
|
||||
try:
|
||||
self.root.clipboard_clear()
|
||||
self.root.clipboard_append(text)
|
||||
self.root.update_idletasks()
|
||||
self.status.set(f"已复制: {text}")
|
||||
except Exception:
|
||||
self.status.set(f"坐标: {text} (复制失败)")
|
||||
|
||||
def on_right_click(self, event):
|
||||
"""右键显示/隐藏放大镜"""
|
||||
self.toggle_magnifier()
|
||||
|
||||
def on_drag_start(self, event):
|
||||
"""开始拖拽"""
|
||||
self.drag_start_x = event.x
|
||||
self.drag_start_y = event.y
|
||||
self.is_dragging = False
|
||||
|
||||
def on_drag(self, event):
|
||||
"""拖拽平移"""
|
||||
if not self.img:
|
||||
return
|
||||
dx = event.x - self.drag_start_x
|
||||
dy = event.y - self.drag_start_y
|
||||
if abs(dx) > 5 or abs(dy) > 5: # 避免误触
|
||||
self.is_dragging = True
|
||||
self.scroll_offset_x -= dx
|
||||
self.scroll_offset_y -= dy
|
||||
self.drag_start_x = event.x
|
||||
self.drag_start_y = event.y
|
||||
self._update_display()
|
||||
|
||||
def on_drag_end(self, event):
|
||||
"""结束拖拽"""
|
||||
self.is_dragging = False
|
||||
|
||||
def on_mousewheel(self, event):
|
||||
"""鼠标滚轮缩放(无Ctrl)"""
|
||||
if event.state & 0x4: # Ctrl键按下
|
||||
return # 交给on_mousewheel_ctrl处理
|
||||
|
||||
delta = 0
|
||||
if event.num == 4 or event.delta > 0: # 向上滚动
|
||||
delta = 1
|
||||
elif event.num == 5 or event.delta < 0: # 向下滚动
|
||||
delta = -1
|
||||
|
||||
if delta != 0:
|
||||
x, y = self._to_image_xy(event)
|
||||
self._zoom_at_point(x, y, delta * 0.1)
|
||||
|
||||
def on_mousewheel_ctrl(self, event):
|
||||
"""Ctrl+滚轮缩放"""
|
||||
delta = 0
|
||||
if event.num == 4 or event.delta > 0: # 向上滚动
|
||||
delta = 1
|
||||
elif event.num == 5 or event.delta < 0: # 向下滚动
|
||||
delta = -1
|
||||
|
||||
if delta != 0:
|
||||
x, y = self._to_image_xy(event)
|
||||
self._zoom_at_point(x, y, delta * 0.1)
|
||||
|
||||
def _zoom_at_point(self, img_x: int, img_y: int, delta: float):
|
||||
"""在指定点缩放"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
old_scale = self.scale
|
||||
new_scale = clamp(old_scale + delta, self.min_scale, self.max_scale)
|
||||
|
||||
if abs(new_scale - old_scale) < 0.01:
|
||||
return
|
||||
|
||||
# 计算缩放中心点在图像中的位置
|
||||
# 调整滚动偏移,使缩放点保持在屏幕上的同一位置
|
||||
scale_ratio = new_scale / old_scale
|
||||
self.scroll_offset_x = img_x * new_scale - (img_x * old_scale - self.scroll_offset_x) * scale_ratio
|
||||
self.scroll_offset_y = img_y * new_scale - (img_y * old_scale - self.scroll_offset_y) * scale_ratio
|
||||
|
||||
self.scale = new_scale
|
||||
self._update_display()
|
||||
|
||||
def zoom_in(self):
|
||||
"""放大"""
|
||||
if not self.img:
|
||||
return
|
||||
center_x = self.w // 2
|
||||
center_y = self.h // 2
|
||||
self._zoom_at_point(center_x, center_y, 0.2)
|
||||
|
||||
def zoom_out(self):
|
||||
"""缩小"""
|
||||
if not self.img:
|
||||
return
|
||||
center_x = self.w // 2
|
||||
center_y = self.h // 2
|
||||
self._zoom_at_point(center_x, center_y, -0.2)
|
||||
|
||||
def reset_zoom(self):
|
||||
"""重置缩放"""
|
||||
if not self.img:
|
||||
return
|
||||
self.scale = 1.0
|
||||
self.scroll_offset_x = 0
|
||||
self.scroll_offset_y = 0
|
||||
self._update_display()
|
||||
|
||||
def toggle_magnifier(self):
|
||||
"""切换放大镜显示"""
|
||||
if self.magnifier_window and self.magnifier_window.winfo_exists():
|
||||
self.magnifier_window.destroy()
|
||||
self.magnifier_window = None
|
||||
else:
|
||||
self._create_magnifier()
|
||||
|
||||
def _create_magnifier(self):
|
||||
"""创建放大镜窗口"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
self.magnifier_window = tk.Toplevel(self.root)
|
||||
self.magnifier_window.title("放大镜")
|
||||
self.magnifier_window.geometry(f"{self.magnifier_size}x{self.magnifier_size}")
|
||||
self.magnifier_window.resizable(False, False)
|
||||
|
||||
self.magnifier_canvas = tk.Canvas(
|
||||
self.magnifier_window,
|
||||
width=self.magnifier_size,
|
||||
height=self.magnifier_size,
|
||||
highlightthickness=1,
|
||||
highlightbackground="black"
|
||||
)
|
||||
self.magnifier_canvas.pack()
|
||||
|
||||
# 绑定鼠标移动
|
||||
self.root.bind("<Motion>", self._on_magnifier_move)
|
||||
|
||||
def _on_magnifier_move(self, event):
|
||||
"""鼠标移动时更新放大镜"""
|
||||
if not self.magnifier_window or not self.magnifier_window.winfo_exists():
|
||||
return
|
||||
|
||||
x, y = self._to_image_xy(event)
|
||||
self._update_magnifier(x, y)
|
||||
|
||||
def _update_magnifier(self, img_x: int, img_y: int):
|
||||
"""更新放大镜显示"""
|
||||
if not self.magnifier_window or not self.magnifier_window.winfo_exists() or not self.img:
|
||||
return
|
||||
|
||||
# 计算放大区域
|
||||
half_size = self.magnifier_size // (2 * self.magnifier_zoom)
|
||||
x1 = max(0, img_x - half_size)
|
||||
y1 = max(0, img_y - half_size)
|
||||
x2 = min(self.w, img_x + half_size)
|
||||
y2 = min(self.h, img_y + half_size)
|
||||
|
||||
# 裁剪并放大
|
||||
crop_img = self.img.crop((x1, y1, x2, y2))
|
||||
try:
|
||||
resample = Image.Resampling.NEAREST if hasattr(Image, 'Resampling') else Image.NEAREST
|
||||
except Exception:
|
||||
resample = Image.NEAREST
|
||||
magnified = crop_img.resize((self.magnifier_size, self.magnifier_size), resample)
|
||||
|
||||
# 显示
|
||||
tk_mag_img = ImageTk.PhotoImage(magnified)
|
||||
self.magnifier_canvas.delete("all")
|
||||
self.magnifier_canvas.create_image(self.magnifier_size // 2, self.magnifier_size // 2, image=tk_mag_img)
|
||||
self.magnifier_canvas.image = tk_mag_img # 保持引用
|
||||
|
||||
# 绘制十字线
|
||||
center = self.magnifier_size // 2
|
||||
self.magnifier_canvas.create_line(center, 0, center, self.magnifier_size, fill="red", width=1)
|
||||
self.magnifier_canvas.create_line(0, center, self.magnifier_size, center, fill="red", width=1)
|
||||
|
||||
def _load_by_index(self, idx: int) -> bool:
|
||||
if not self.file_list:
|
||||
@@ -260,4 +530,4 @@ def main(argv: list[str]) -> int:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv))
|
||||
raise SystemExit(main(sys.argv))
|
||||
@@ -0,0 +1,764 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
区域选择和白色像素统计工具
|
||||
用于选择图片区域,圈出边框,并统计区域内白色像素数量
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional, Tuple, Any
|
||||
import json
|
||||
|
||||
from PIL import Image, ImageTk, ImageDraw
|
||||
|
||||
try:
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog, messagebox
|
||||
except Exception as e:
|
||||
raise SystemExit(f"tkinter 不可用:{e}\n请安装带 tkinter 的 Python。")
|
||||
|
||||
# 尝试导入拖放支持库
|
||||
try:
|
||||
from tkinterdnd2 import DND_FILES, TkinterDnD # type: ignore[import]
|
||||
HAS_DND = True
|
||||
except ImportError:
|
||||
HAS_DND = False
|
||||
DND_FILES: Any = None
|
||||
TkinterDnD: Any = None
|
||||
|
||||
|
||||
def clamp(v: float, lo: float, hi: float) -> float:
|
||||
return lo if v < lo else hi if v > hi else v
|
||||
|
||||
|
||||
class RegionSelector:
|
||||
def __init__(self, image_path: Optional[Path]):
|
||||
self.image_path: Optional[Path] = None
|
||||
self.img: Optional[Image.Image] = None
|
||||
self.w = 0
|
||||
self.h = 0
|
||||
self.scale = 1.0
|
||||
self.min_scale = 0.1 # 最小缩放比例
|
||||
self.max_scale = 10.0 # 最大缩放比例
|
||||
self.disp_w = 0
|
||||
self.disp_h = 0
|
||||
self.tk_img = None
|
||||
self.file_list: list[Path] = []
|
||||
self.file_idx: int = -1
|
||||
self.zoom_center_x = 0 # 缩放中心点
|
||||
self.zoom_center_y = 0
|
||||
self.scroll_offset_x = 0 # 滚动偏移
|
||||
self.scroll_offset_y = 0
|
||||
|
||||
# 区域选择相关
|
||||
self.selection_rect = None # 当前选择的矩形 (x1, y1, x2, y2)
|
||||
self.selection_canvas_id = None # Canvas中的矩形ID
|
||||
self.is_selecting = False
|
||||
self.select_start_x = 0
|
||||
self.select_start_y = 0
|
||||
self.select_end_x = 0
|
||||
self.select_end_y = 0
|
||||
|
||||
# 拖拽相关
|
||||
self.is_dragging = False
|
||||
self.drag_start_x = 0
|
||||
self.drag_start_y = 0
|
||||
|
||||
# 结果存储
|
||||
self.white_pixel_regions = [] # 存储区域和白色像素统计结果
|
||||
|
||||
# 使用 TkinterDnD 支持拖放(如果可用)
|
||||
if HAS_DND:
|
||||
self.root = TkinterDnD.Tk()
|
||||
else:
|
||||
self.root = tk.Tk()
|
||||
|
||||
self.root.title("区域选择器 - 白色像素统计工具")
|
||||
self.root.geometry("1200x800")
|
||||
|
||||
# 创建菜单
|
||||
self._create_menu()
|
||||
|
||||
# 创建主界面
|
||||
self._create_ui()
|
||||
|
||||
if image_path is None:
|
||||
if not self.open_dialog():
|
||||
raise SystemExit(2)
|
||||
else:
|
||||
self.set_image(image_path, update_list=True)
|
||||
|
||||
def _create_menu(self):
|
||||
"""创建菜单栏"""
|
||||
menubar = tk.Menu(self.root)
|
||||
file_menu = tk.Menu(menubar, tearoff=0)
|
||||
file_menu.add_command(label="打开...", command=self.open_dialog, accelerator="Ctrl+O")
|
||||
file_menu.add_command(label="上一张", command=self.prev_image, accelerator="← / PageUp")
|
||||
file_menu.add_command(label="下一张", command=self.next_image, accelerator="→ / PageDown")
|
||||
file_menu.add_separator()
|
||||
file_menu.add_command(label="保存区域数据", command=self.save_regions, accelerator="Ctrl+S")
|
||||
file_menu.add_command(label="加载区域数据", command=self.load_regions, accelerator="Ctrl+L")
|
||||
file_menu.add_separator()
|
||||
file_menu.add_command(label="退出", command=self.root.destroy)
|
||||
menubar.add_cascade(label="文件", menu=file_menu)
|
||||
|
||||
view_menu = tk.Menu(menubar, tearoff=0)
|
||||
view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+ / Ctrl+滚轮上")
|
||||
view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="- / Ctrl+滚轮下")
|
||||
view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0")
|
||||
view_menu.add_command(label="适应窗口", command=self.fit_to_window, accelerator="Ctrl+F")
|
||||
menubar.add_cascade(label="视图", menu=view_menu)
|
||||
|
||||
region_menu = tk.Menu(menubar, tearoff=0)
|
||||
region_menu.add_command(label="清除选择", command=self.clear_selection, accelerator="Delete")
|
||||
region_menu.add_command(label="分析区域", command=self.analyze_region, accelerator="Enter")
|
||||
region_menu.add_separator()
|
||||
region_menu.add_command(label="显示所有区域", command=self.show_all_regions, accelerator="Ctrl+A")
|
||||
region_menu.add_command(label="清除所有区域", command=self.clear_all_regions)
|
||||
menubar.add_cascade(label="区域", menu=region_menu)
|
||||
|
||||
self.root.config(menu=menubar)
|
||||
|
||||
# 绑定快捷键
|
||||
self.root.bind_all("<Control-o>", lambda e: self.open_dialog())
|
||||
self.root.bind("<Left>", lambda e: self.prev_image())
|
||||
self.root.bind("<Right>", lambda e: self.next_image())
|
||||
self.root.bind("<Prior>", lambda e: self.prev_image()) # PageUp
|
||||
self.root.bind("<Next>", lambda e: self.next_image()) # PageDown
|
||||
self.root.bind("<plus>", lambda e: self.zoom_in())
|
||||
self.root.bind("<equal>", lambda e: self.zoom_in()) # 无Shift的+键
|
||||
self.root.bind("<minus>", lambda e: self.zoom_out())
|
||||
self.root.bind("<Control-0>", lambda e: self.reset_zoom())
|
||||
self.root.bind("<Control-f>", lambda e: self.fit_to_window())
|
||||
self.root.bind("<Delete>", lambda e: self.clear_selection())
|
||||
self.root.bind("<Return>", lambda e: self.analyze_region())
|
||||
self.root.bind("<Control-s>", lambda e: self.save_regions())
|
||||
self.root.bind("<Control-l>", lambda e: self.load_regions())
|
||||
self.root.bind("<Control-a>", lambda e: self.show_all_regions())
|
||||
|
||||
def _create_ui(self):
|
||||
"""创建用户界面"""
|
||||
# 主框架
|
||||
main_frame = tk.Frame(self.root)
|
||||
main_frame.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
# 左侧控制面板
|
||||
left_panel = tk.Frame(main_frame, width=300, bg='#f0f0f0')
|
||||
left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)
|
||||
|
||||
# 右侧画布区域
|
||||
right_panel = tk.Frame(main_frame)
|
||||
right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
|
||||
|
||||
# 控制面板内容
|
||||
self._create_control_panel(left_panel)
|
||||
|
||||
# 画布
|
||||
self.canvas = tk.Canvas(right_panel, bg='#404040')
|
||||
self.canvas.pack(fill=tk.BOTH, expand=True)
|
||||
self._canvas_image_id = self.canvas.create_image(0, 0, anchor=tk.NW)
|
||||
|
||||
# 状态栏
|
||||
self.status = tk.StringVar()
|
||||
if HAS_DND:
|
||||
self.status.set("拖拽选择区域;滚轮缩放;右键拖拽平移;Enter分析区域;Ctrl+O打开图片;或直接拖放图片")
|
||||
else:
|
||||
self.status.set("拖拽选择区域;滚轮缩放;右键拖拽平移;Enter分析区域;Ctrl+O打开图片")
|
||||
|
||||
status_label = tk.Label(right_panel, textvariable=self.status, anchor="w", bg='#e0e0e0')
|
||||
status_label.pack(fill=tk.X, side=tk.BOTTOM)
|
||||
|
||||
# 绑定事件
|
||||
self.canvas.bind("<Motion>", self.on_move)
|
||||
self.canvas.bind("<Button-1>", self.on_left_click)
|
||||
self.canvas.bind("<B1-Motion>", self.on_left_drag)
|
||||
self.canvas.bind("<ButtonRelease-1>", self.on_left_release)
|
||||
self.canvas.bind("<Button-3>", self.on_right_click) # 右键开始拖拽
|
||||
self.canvas.bind("<B3-Motion>", self.on_right_drag) # 右键拖拽
|
||||
self.canvas.bind("<ButtonRelease-3>", self.on_right_release)
|
||||
self.canvas.bind("<MouseWheel>", self.on_mousewheel) # Windows/Linux
|
||||
self.canvas.bind("<Button-4>", self.on_mousewheel) # Linux
|
||||
self.canvas.bind("<Button-5>", self.on_mousewheel) # Linux
|
||||
self.canvas.bind("<Control-MouseWheel>", self.on_mousewheel_ctrl) # Ctrl+滚轮
|
||||
|
||||
# 添加拖放支持
|
||||
if HAS_DND:
|
||||
self.root.drop_target_register(DND_FILES)
|
||||
self.root.dnd_bind('<<Drop>>', self.on_drop)
|
||||
self.canvas.drop_target_register(DND_FILES)
|
||||
self.canvas.dnd_bind('<<Drop>>', self.on_drop)
|
||||
|
||||
def _create_control_panel(self, parent):
|
||||
"""创建控制面板"""
|
||||
# 标题
|
||||
title_label = tk.Label(parent, text="区域选择器", font=("Arial", 14, "bold"), bg='#f0f0f0')
|
||||
title_label.pack(pady=10)
|
||||
|
||||
# 当前选择信息
|
||||
selection_frame = tk.LabelFrame(parent, text="当前选择", bg='#f0f0f0')
|
||||
selection_frame.pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
self.selection_info = tk.StringVar()
|
||||
self.selection_info.set("未选择区域")
|
||||
selection_label = tk.Label(selection_frame, textvariable=self.selection_info,
|
||||
anchor="w", bg='#f0f0f0', justify=tk.LEFT)
|
||||
selection_label.pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
# 分析结果
|
||||
result_frame = tk.LabelFrame(parent, text="分析结果", bg='#f0f0f0')
|
||||
result_frame.pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
self.result_info = tk.Text(result_frame, height=8, width=35, font=("Courier", 9))
|
||||
scrollbar = tk.Scrollbar(result_frame, command=self.result_info.yview)
|
||||
self.result_info.config(yscrollcommand=scrollbar.set)
|
||||
self.result_info.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)
|
||||
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
|
||||
|
||||
# 按钮区域
|
||||
button_frame = tk.Frame(parent, bg='#f0f0f0')
|
||||
button_frame.pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
tk.Button(button_frame, text="分析区域", command=self.analyze_region,
|
||||
bg='#4CAF50', fg='white').pack(fill=tk.X, pady=2)
|
||||
tk.Button(button_frame, text="清除选择", command=self.clear_selection,
|
||||
bg='#f44336', fg='white').pack(fill=tk.X, pady=2)
|
||||
tk.Button(button_frame, text="显示所有", command=self.show_all_regions,
|
||||
bg='#2196F3', fg='white').pack(fill=tk.X, pady=2)
|
||||
tk.Button(button_frame, text="清除所有", command=self.clear_all_regions,
|
||||
bg='#FF9800', fg='white').pack(fill=tk.X, pady=2)
|
||||
|
||||
def _refresh_file_list(self, current: Path) -> None:
|
||||
"""刷新当前目录下的图片列表"""
|
||||
exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}
|
||||
try:
|
||||
files = [p for p in current.parent.iterdir() if p.suffix.lower() in exts and p.is_file()]
|
||||
files.sort()
|
||||
self.file_list = files
|
||||
try:
|
||||
self.file_idx = self.file_list.index(current)
|
||||
except ValueError:
|
||||
self.file_idx = -1
|
||||
except Exception:
|
||||
self.file_list = []
|
||||
self.file_idx = -1
|
||||
|
||||
def set_image(self, image_path: Path, update_list: bool = False) -> None:
|
||||
"""设置当前图片"""
|
||||
image_path = Path(image_path)
|
||||
self.image_path = image_path
|
||||
self.img = Image.open(image_path).convert("RGB")
|
||||
self.w, self.h = self.img.size
|
||||
|
||||
if update_list:
|
||||
self._refresh_file_list(image_path)
|
||||
|
||||
# 清除之前的选择
|
||||
self.clear_selection()
|
||||
self.clear_all_regions()
|
||||
|
||||
# 显示用缩放
|
||||
self._update_display()
|
||||
self.root.title(f"区域选择器: {image_path.name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x")
|
||||
|
||||
def open_dialog(self) -> bool:
|
||||
"""打开文件选择对话框"""
|
||||
initial_dir = None
|
||||
try:
|
||||
if self.image_path and self.image_path.parent.exists():
|
||||
initial_dir = str(self.image_path.parent)
|
||||
except Exception:
|
||||
initial_dir = None
|
||||
|
||||
filename = filedialog.askopenfilename(
|
||||
title="选择图片",
|
||||
initialdir=initial_dir,
|
||||
filetypes=[
|
||||
("Images", "*.png;*.jpg;*.jpeg;*.bmp;*.webp"),
|
||||
("All files", "*.*"),
|
||||
],
|
||||
)
|
||||
if not filename:
|
||||
return False
|
||||
try:
|
||||
self.set_image(Path(filename), update_list=True)
|
||||
return True
|
||||
except Exception as e:
|
||||
messagebox.showerror("错误", f"打开图片失败: {e}")
|
||||
return False
|
||||
|
||||
def _to_image_xy(self, event) -> tuple[int, int]:
|
||||
"""将canvas坐标转换为图像坐标"""
|
||||
if not self.img or self.w <= 0 or self.h <= 0:
|
||||
return 0, 0
|
||||
# 考虑缩放和滚动偏移
|
||||
canvas_x = event.x + self.scroll_offset_x
|
||||
canvas_y = event.y + self.scroll_offset_y
|
||||
x = int(clamp(canvas_x / self.scale, 0, self.w - 1))
|
||||
y = int(clamp(canvas_y / self.scale, 0, self.h - 1))
|
||||
return x, y
|
||||
|
||||
def _to_canvas_xy(self, img_x: int, img_y: int) -> tuple[int, int]:
|
||||
"""将图像坐标转换为canvas坐标"""
|
||||
canvas_x = img_x * self.scale - self.scroll_offset_x
|
||||
canvas_y = img_y * self.scale - self.scroll_offset_y
|
||||
return int(canvas_x), int(canvas_y)
|
||||
|
||||
def _update_display(self):
|
||||
"""更新显示"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
# 获取canvas实际大小
|
||||
self.root.update_idletasks()
|
||||
canvas_w = max(1, self.canvas.winfo_width())
|
||||
canvas_h = max(1, self.canvas.winfo_height())
|
||||
|
||||
# 计算显示尺寸
|
||||
self.disp_w = int(self.w * self.scale)
|
||||
self.disp_h = int(self.h * self.scale)
|
||||
|
||||
# 限制滚动偏移
|
||||
max_offset_x = max(0, self.disp_w - canvas_w)
|
||||
max_offset_y = max(0, self.disp_h - canvas_h)
|
||||
self.scroll_offset_x = max(0, min(self.scroll_offset_x, max_offset_x))
|
||||
self.scroll_offset_y = max(0, min(self.scroll_offset_y, max_offset_y))
|
||||
|
||||
# 生成显示图像
|
||||
try:
|
||||
resample = Image.Resampling.BICUBIC if hasattr(Image, 'Resampling') else Image.BICUBIC
|
||||
except Exception:
|
||||
resample = Image.BICUBIC
|
||||
|
||||
if self.scale != 1.0:
|
||||
# 如果放大,只显示可见区域以提高性能
|
||||
if self.scale > 1.0 and canvas_w < self.disp_w and canvas_h < self.disp_h:
|
||||
# 计算原图中要显示的区域
|
||||
src_x1 = max(0, int(self.scroll_offset_x / self.scale))
|
||||
src_y1 = max(0, int(self.scroll_offset_y / self.scale))
|
||||
src_x2 = min(self.w, src_x1 + int(canvas_w / self.scale) + 2)
|
||||
src_y2 = min(self.h, src_y1 + int(canvas_h / self.scale) + 2)
|
||||
|
||||
# 裁剪并放大
|
||||
crop_img = self.img.crop((src_x1, src_y1, src_x2, src_y2))
|
||||
crop_w, crop_h = crop_img.size
|
||||
disp_img = crop_img.resize((int(crop_w * self.scale), int(crop_h * self.scale)), resample)
|
||||
else:
|
||||
# 缩小或完全显示
|
||||
disp_img = self.img.resize((self.disp_w, self.disp_h), resample)
|
||||
else:
|
||||
disp_img = self.img
|
||||
|
||||
self.tk_img = ImageTk.PhotoImage(disp_img)
|
||||
|
||||
# 更新canvas滚动区域
|
||||
self.canvas.config(scrollregion=(0, 0, self.disp_w, self.disp_h))
|
||||
|
||||
# 更新图像位置
|
||||
self.canvas.coords(self._canvas_image_id, -self.scroll_offset_x, -self.scroll_offset_y)
|
||||
self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img)
|
||||
|
||||
# 重新绘制选择矩形
|
||||
self._redraw_selection_rect()
|
||||
|
||||
# 更新标题
|
||||
if self.image_path:
|
||||
self.root.title(f"区域选择器: {self.image_path.name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x")
|
||||
|
||||
def _redraw_selection_rect(self):
|
||||
"""重新绘制选择矩形"""
|
||||
# 删除旧的矩形
|
||||
if self.selection_canvas_id:
|
||||
self.canvas.delete(self.selection_canvas_id)
|
||||
self.selection_canvas_id = None
|
||||
|
||||
# 绘制新的矩形
|
||||
if self.selection_rect:
|
||||
x1, y1, x2, y2 = self.selection_rect
|
||||
canvas_x1, canvas_y1 = self._to_canvas_xy(x1, y1)
|
||||
canvas_x2, canvas_y2 = self._to_canvas_xy(x2, y2)
|
||||
|
||||
self.selection_canvas_id = self.canvas.create_rectangle(
|
||||
canvas_x1, canvas_y1, canvas_x2, canvas_y2,
|
||||
outline='red', width=2, dash=(5, 5)
|
||||
)
|
||||
|
||||
def on_move(self, event):
|
||||
"""鼠标移动事件"""
|
||||
if self.is_selecting:
|
||||
# 更新选择矩形
|
||||
self.select_end_x, self.select_end_y = self._to_image_xy(event)
|
||||
self._update_selection_rect()
|
||||
elif self.is_dragging:
|
||||
# 拖拽平移
|
||||
dx = event.x - self.drag_start_x
|
||||
dy = event.y - self.drag_start_y
|
||||
self.scroll_offset_x -= dx
|
||||
self.scroll_offset_y -= dy
|
||||
self.drag_start_x = event.x
|
||||
self.drag_start_y = event.y
|
||||
self._update_display()
|
||||
|
||||
def on_left_click(self, event):
|
||||
"""左键点击"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
img_x, img_y = self._to_image_xy(event)
|
||||
self.select_start_x = img_x
|
||||
self.select_start_y = img_y
|
||||
self.select_end_x = img_x
|
||||
self.select_end_y = img_y
|
||||
self.is_selecting = True
|
||||
self._update_selection_rect()
|
||||
|
||||
def on_left_drag(self, event):
|
||||
"""左键拖拽"""
|
||||
if self.is_selecting:
|
||||
self.select_end_x, self.select_end_y = self._to_image_xy(event)
|
||||
self._update_selection_rect()
|
||||
|
||||
def on_left_release(self, event):
|
||||
"""左键释放"""
|
||||
if self.is_selecting:
|
||||
self.select_end_x, self.select_end_y = self._to_image_xy(event)
|
||||
self._update_selection_rect()
|
||||
self.is_selecting = False
|
||||
|
||||
# 更新选择信息
|
||||
self._update_selection_info()
|
||||
|
||||
def on_right_click(self, event):
|
||||
"""右键点击开始拖拽"""
|
||||
self.drag_start_x = event.x
|
||||
self.drag_start_y = event.y
|
||||
self.is_dragging = True
|
||||
|
||||
def on_right_drag(self, event):
|
||||
"""右键拖拽"""
|
||||
if self.is_dragging:
|
||||
dx = event.x - self.drag_start_x
|
||||
dy = event.y - self.drag_start_y
|
||||
self.scroll_offset_x -= dx
|
||||
self.scroll_offset_y -= dy
|
||||
self.drag_start_x = event.x
|
||||
self.drag_start_y = event.y
|
||||
self._update_display()
|
||||
|
||||
def on_right_release(self, event):
|
||||
"""右键释放"""
|
||||
self.is_dragging = False
|
||||
|
||||
def _update_selection_rect(self):
|
||||
"""更新选择矩形"""
|
||||
x1 = min(self.select_start_x, self.select_end_x)
|
||||
y1 = min(self.select_start_y, self.select_end_y)
|
||||
x2 = max(self.select_start_x, self.select_end_x)
|
||||
y2 = max(self.select_start_y, self.select_end_y)
|
||||
|
||||
self.selection_rect = (x1, y1, x2, y2)
|
||||
self._redraw_selection_rect()
|
||||
|
||||
def _update_selection_info(self):
|
||||
"""更新选择信息显示"""
|
||||
if self.selection_rect:
|
||||
x1, y1, x2, y2 = self.selection_rect
|
||||
width = x2 - x1 + 1
|
||||
height = y2 - y1 + 1
|
||||
self.selection_info.set(f"区域: ({x1}, {y1}) - ({x2}, {y2})\n尺寸: {width}x{height}")
|
||||
else:
|
||||
self.selection_info.set("未选择区域")
|
||||
|
||||
def analyze_region(self):
|
||||
"""分析当前选择的区域"""
|
||||
if not self.img or not self.selection_rect:
|
||||
messagebox.showwarning("警告", "请先选择一个区域")
|
||||
return
|
||||
|
||||
x1, y1, x2, y2 = self.selection_rect
|
||||
|
||||
# 统计白色像素
|
||||
white_count = 0
|
||||
total_pixels = 0
|
||||
region_img = self.img.crop((x1, y1, x2+1, y2+1))
|
||||
|
||||
# 将图像转换为numpy数组进行分析
|
||||
import numpy as np
|
||||
region_array = np.array(region_img)
|
||||
|
||||
# 计算白色像素(RGB值都接近255的像素)
|
||||
white_threshold = 240 # 白色阈值
|
||||
white_pixels = np.all(region_array >= white_threshold, axis=2)
|
||||
white_count = np.sum(white_pixels)
|
||||
total_pixels = region_array.shape[0] * region_array.shape[1]
|
||||
|
||||
white_ratio = white_count / total_pixels if total_pixels > 0 else 0
|
||||
|
||||
# 生成结果文本
|
||||
result_text = f"区域分析结果:\n"
|
||||
result_text += f"坐标: ({x1}, {y1}) - ({x2}, {y2})\n"
|
||||
result_text += f"尺寸: {(x2-x1+1)}x{(y2-y1+1)}\n"
|
||||
result_text += f"总像素: {total_pixels}\n"
|
||||
result_text += f"白色像素: {white_count}\n"
|
||||
result_text += f"白色比例: {white_ratio:.3f}\n"
|
||||
result_text += f"置信度: {(1 - abs(white_ratio - 0.5) * 2):.3f}"
|
||||
# 保存到结果列表
|
||||
region_data = {
|
||||
'coordinates': (x1, y1, x2, y2),
|
||||
'size': (x2-x1+1, y2-y1+1),
|
||||
'total_pixels': total_pixels,
|
||||
'white_pixels': white_count,
|
||||
'white_ratio': white_ratio,
|
||||
'image_path': str(self.image_path) if self.image_path else None
|
||||
}
|
||||
|
||||
self.white_pixel_regions.append(region_data)
|
||||
|
||||
# 显示结果
|
||||
self.result_info.delete(1.0, tk.END)
|
||||
self.result_info.insert(tk.END, result_text)
|
||||
|
||||
# 打印到控制台
|
||||
print(f"\n=== 区域分析结果 ===")
|
||||
print(result_text)
|
||||
print(f"结果已保存到内存中 (共{len(self.white_pixel_regions)}个区域)")
|
||||
|
||||
def clear_selection(self):
|
||||
"""清除当前选择"""
|
||||
self.selection_rect = None
|
||||
if self.selection_canvas_id:
|
||||
self.canvas.delete(self.selection_canvas_id)
|
||||
self.selection_canvas_id = None
|
||||
self._update_selection_info()
|
||||
|
||||
def clear_all_regions(self):
|
||||
"""清除所有保存的区域"""
|
||||
self.white_pixel_regions.clear()
|
||||
self.result_info.delete(1.0, tk.END)
|
||||
self.result_info.insert(tk.END, "已清除所有区域数据")
|
||||
|
||||
def show_all_regions(self):
|
||||
"""显示所有保存的区域"""
|
||||
if not self.white_pixel_regions:
|
||||
messagebox.showinfo("信息", "没有保存的区域数据")
|
||||
return
|
||||
|
||||
result_text = f"所有区域数据 (共{len(self.white_pixel_regions)}个):\n\n"
|
||||
for i, region in enumerate(self.white_pixel_regions, 1):
|
||||
x1, y1, x2, y2 = region['coordinates']
|
||||
result_text += f"区域 {i}:\n"
|
||||
result_text += f" 坐标: ({x1}, {y1}) - ({x2}, {y2})\n"
|
||||
result_text += f" 尺寸: {region['size'][0]}x{region['size'][1]}\n"
|
||||
result_text += f" 白色像素: {region['white_pixels']}/{region['total_pixels']} "
|
||||
result_text += f"({region['white_ratio']:.3f})\n\n"
|
||||
|
||||
self.result_info.delete(1.0, tk.END)
|
||||
self.result_info.insert(tk.END, result_text)
|
||||
|
||||
def save_regions(self):
|
||||
"""保存区域数据到文件"""
|
||||
if not self.white_pixel_regions:
|
||||
messagebox.showwarning("警告", "没有区域数据可以保存")
|
||||
return
|
||||
|
||||
filename = filedialog.asksaveasfilename(
|
||||
title="保存区域数据",
|
||||
defaultextension=".json",
|
||||
filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")]
|
||||
)
|
||||
|
||||
if filename:
|
||||
try:
|
||||
with open(filename, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.white_pixel_regions, f, indent=2, ensure_ascii=False)
|
||||
messagebox.showinfo("成功", f"区域数据已保存到: {filename}")
|
||||
except Exception as e:
|
||||
messagebox.showerror("错误", f"保存失败: {e}")
|
||||
|
||||
def load_regions(self):
|
||||
"""从文件加载区域数据"""
|
||||
filename = filedialog.askopenfilename(
|
||||
title="加载区域数据",
|
||||
filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")]
|
||||
)
|
||||
|
||||
if filename:
|
||||
try:
|
||||
with open(filename, 'r', encoding='utf-8') as f:
|
||||
self.white_pixel_regions = json.load(f)
|
||||
messagebox.showinfo("成功", f"已加载 {len(self.white_pixel_regions)} 个区域数据")
|
||||
self.show_all_regions()
|
||||
except Exception as e:
|
||||
messagebox.showerror("错误", f"加载失败: {e}")
|
||||
|
||||
def on_mousewheel(self, event):
|
||||
"""鼠标滚轮缩放"""
|
||||
if event.state & 0x4: # Ctrl键按下
|
||||
return # 交给on_mousewheel_ctrl处理
|
||||
|
||||
delta = 0
|
||||
if event.num == 4 or event.delta > 0: # 向上滚动
|
||||
delta = 1
|
||||
elif event.num == 5 or event.delta < 0: # 向下滚动
|
||||
delta = -1
|
||||
|
||||
if delta != 0:
|
||||
img_x, img_y = self._to_image_xy(event)
|
||||
self._zoom_at_point(img_x, img_y, delta * 0.1)
|
||||
|
||||
def on_mousewheel_ctrl(self, event):
|
||||
"""Ctrl+滚轮缩放"""
|
||||
delta = 0
|
||||
if event.num == 4 or event.delta > 0: # 向上滚动
|
||||
delta = 1
|
||||
elif event.num == 5 or event.delta < 0: # 向下滚动
|
||||
delta = -1
|
||||
|
||||
if delta != 0:
|
||||
img_x, img_y = self._to_image_xy(event)
|
||||
self._zoom_at_point(img_x, img_y, delta * 0.1)
|
||||
|
||||
def _zoom_at_point(self, img_x: int, img_y: int, delta: float):
|
||||
"""在指定点缩放"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
old_scale = self.scale
|
||||
new_scale = clamp(old_scale + delta, self.min_scale, self.max_scale)
|
||||
|
||||
if abs(new_scale - old_scale) < 0.01:
|
||||
return
|
||||
|
||||
# 计算缩放中心点在图像中的位置
|
||||
# 调整滚动偏移,使缩放点保持在屏幕上的同一位置
|
||||
scale_ratio = new_scale / old_scale
|
||||
self.scroll_offset_x = img_x * new_scale - (img_x * old_scale - self.scroll_offset_x) * scale_ratio
|
||||
self.scroll_offset_y = img_y * new_scale - (img_y * old_scale - self.scroll_offset_y) * scale_ratio
|
||||
|
||||
self.scale = new_scale
|
||||
self._update_display()
|
||||
|
||||
def zoom_in(self):
|
||||
"""放大"""
|
||||
if not self.img:
|
||||
return
|
||||
center_x = self.w // 2
|
||||
center_y = self.h // 2
|
||||
self._zoom_at_point(center_x, center_y, 0.2)
|
||||
|
||||
def zoom_out(self):
|
||||
"""缩小"""
|
||||
if not self.img:
|
||||
return
|
||||
center_x = self.w // 2
|
||||
center_y = self.h // 2
|
||||
self._zoom_at_point(center_x, center_y, -0.2)
|
||||
|
||||
def reset_zoom(self):
|
||||
"""重置缩放"""
|
||||
if not self.img:
|
||||
return
|
||||
self.scale = 1.0
|
||||
self.scroll_offset_x = 0
|
||||
self.scroll_offset_y = 0
|
||||
self._update_display()
|
||||
|
||||
def fit_to_window(self):
|
||||
"""适应窗口大小"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
self.root.update_idletasks()
|
||||
canvas_w = self.canvas.winfo_width()
|
||||
canvas_h = self.canvas.winfo_height()
|
||||
|
||||
if canvas_w > 0 and canvas_h > 0:
|
||||
scale_x = canvas_w / self.w
|
||||
scale_y = canvas_h / self.h
|
||||
self.scale = min(scale_x, scale_y) * 0.9 # 留一点边距
|
||||
self.scroll_offset_x = 0
|
||||
self.scroll_offset_y = 0
|
||||
self._update_display()
|
||||
|
||||
def _load_by_index(self, idx: int) -> bool:
|
||||
"""按索引加载图片"""
|
||||
if not self.file_list:
|
||||
return False
|
||||
idx = idx % len(self.file_list)
|
||||
try:
|
||||
self.set_image(self.file_list[idx], update_list=False)
|
||||
self.file_idx = idx
|
||||
return True
|
||||
except Exception as e:
|
||||
messagebox.showerror("错误", f"切换图片失败: {e}")
|
||||
return False
|
||||
|
||||
def next_image(self) -> None:
|
||||
"""下一张图片"""
|
||||
if self.file_list:
|
||||
if self._load_by_index(self.file_idx + 1):
|
||||
self.status.set(f"下一张: {self.image_path.name if self.image_path else ''}")
|
||||
|
||||
def prev_image(self) -> None:
|
||||
"""上一张图片"""
|
||||
if self.file_list:
|
||||
if self._load_by_index(self.file_idx - 1):
|
||||
self.status.set(f"上一张: {self.image_path.name if self.image_path else ''}")
|
||||
|
||||
def on_drop(self, event) -> None:
|
||||
"""处理拖放事件"""
|
||||
if not HAS_DND:
|
||||
return
|
||||
|
||||
try:
|
||||
# 获取拖放的文件路径
|
||||
files = self.root.tk.splitlist(event.data)
|
||||
if not files:
|
||||
return
|
||||
|
||||
# 取第一个文件
|
||||
file_path = files[0]
|
||||
# 移除可能的花括号(Windows 拖放可能包含)
|
||||
file_path = file_path.strip('{}')
|
||||
|
||||
path = Path(file_path)
|
||||
if not path.exists():
|
||||
self.status.set(f"文件不存在: {path}")
|
||||
return
|
||||
|
||||
# 检查是否为图片文件
|
||||
exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}
|
||||
if path.suffix.lower() not in exts:
|
||||
self.status.set(f"不是支持的图片格式: {path.suffix}")
|
||||
return
|
||||
|
||||
# 加载图片
|
||||
self.set_image(path, update_list=True)
|
||||
self.status.set(f"已加载: {path.name}")
|
||||
except Exception as e:
|
||||
self.status.set(f"拖放失败: {e}")
|
||||
|
||||
def run(self):
|
||||
"""运行主循环"""
|
||||
self.root.mainloop()
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
"""主函数"""
|
||||
p: Optional[Path] = None
|
||||
if len(argv) >= 2:
|
||||
p = Path(argv[1]).expanduser()
|
||||
if p and not p.is_absolute():
|
||||
p = (Path(__file__).resolve().parent.parent / p).resolve()
|
||||
if p and not p.exists():
|
||||
print(f"找不到图片: {p}")
|
||||
print("将弹出文件选择框,请手动选择图片。")
|
||||
p = None
|
||||
else:
|
||||
print("未传入图片路径,将弹出文件选择框。")
|
||||
|
||||
RegionSelector(p).run()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv))
|
||||
@@ -0,0 +1,699 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
简化版区域选择器 - 专门用于抖音挂机项目
|
||||
用于选择直播间图标区域并统计白色像素
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
import json
|
||||
|
||||
try:
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog, messagebox
|
||||
except ImportError:
|
||||
print("错误: tkinter不可用。请确保Python安装时包含了tkinter。")
|
||||
print("在Windows上,请重新安装Python并勾选'tcl/tk and IDLE'选项。")
|
||||
sys.exit(1)
|
||||
|
||||
from PIL import Image, ImageTk, ImageDraw
|
||||
import numpy as np
|
||||
|
||||
|
||||
class SimpleRegionSelector:
|
||||
def __init__(self, image_path=None):
|
||||
self.image_path = image_path
|
||||
self.img = None
|
||||
self.photo = None
|
||||
self.scale = 1.0
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
|
||||
# 选择相关
|
||||
self.polygon_points = [] # 多边形顶点列表
|
||||
self.polygon_id = None # 画布上的多边形ID
|
||||
|
||||
# 缩放和平移相关
|
||||
self.scale = 1.0
|
||||
self.min_scale = 0.1
|
||||
self.max_scale = 10.0
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
self.is_dragging = False
|
||||
self.drag_start_x = 0
|
||||
self.drag_start_y = 0
|
||||
|
||||
# 结果存储
|
||||
self.regions = []
|
||||
|
||||
self.setup_ui()
|
||||
|
||||
if image_path:
|
||||
self.load_image(image_path)
|
||||
else:
|
||||
self.ask_for_image()
|
||||
|
||||
def setup_ui(self):
|
||||
"""设置用户界面"""
|
||||
self.root = tk.Tk()
|
||||
self.root.title("抖音区域选择器 - 白色像素统计")
|
||||
self.root.geometry("1000x700")
|
||||
|
||||
# 菜单栏
|
||||
menubar = tk.Menu(self.root)
|
||||
file_menu = tk.Menu(menubar, tearoff=0)
|
||||
file_menu.add_command(label="打开图片", command=self.ask_for_image, accelerator="Ctrl+O")
|
||||
file_menu.add_command(label="保存区域", command=self.save_regions, accelerator="Ctrl+S")
|
||||
file_menu.add_command(label="加载区域", command=self.load_regions, accelerator="Ctrl+L")
|
||||
file_menu.add_separator()
|
||||
file_menu.add_command(label="退出", command=self.root.quit)
|
||||
menubar.add_cascade(label="文件", menu=file_menu)
|
||||
|
||||
edit_menu = tk.Menu(menubar, tearoff=0)
|
||||
edit_menu.add_command(label="清除选择", command=self.clear_selection, accelerator="Del")
|
||||
edit_menu.add_command(label="分析区域", command=self.analyze_region, accelerator="Enter")
|
||||
edit_menu.add_command(label="显示所有", command=self.show_all_regions)
|
||||
edit_menu.add_command(label="清除所有", command=self.clear_all_regions)
|
||||
menubar.add_cascade(label="编辑", menu=edit_menu)
|
||||
|
||||
# 移除视图菜单,不需要放大缩小功能
|
||||
|
||||
# 视图菜单
|
||||
view_menu = tk.Menu(menubar, tearoff=0)
|
||||
view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+")
|
||||
view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="-")
|
||||
view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0")
|
||||
view_menu.add_command(label="适应窗口", command=self.fit_to_window, accelerator="Ctrl+F")
|
||||
menubar.add_cascade(label="视图", menu=view_menu)
|
||||
|
||||
self.root.config(menu=menubar)
|
||||
|
||||
# 绑定快捷键
|
||||
self.root.bind("<Control-o>", lambda e: self.ask_for_image())
|
||||
self.root.bind("<Control-s>", lambda e: self.save_regions())
|
||||
self.root.bind("<Control-l>", lambda e: self.load_regions())
|
||||
self.root.bind("<Delete>", lambda e: self.clear_selection())
|
||||
self.root.bind("<Return>", lambda e: self.analyze_region())
|
||||
# 视图相关快捷键
|
||||
self.root.bind("<plus>", lambda e: self.zoom_in())
|
||||
self.root.bind("<equal>", lambda e: self.zoom_in())
|
||||
self.root.bind("<minus>", lambda e: self.zoom_out())
|
||||
self.root.bind("<Control-0>", lambda e: self.reset_zoom())
|
||||
self.root.bind("<Control-f>", lambda e: self.fit_to_window())
|
||||
|
||||
# 主框架
|
||||
main_frame = tk.Frame(self.root)
|
||||
main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
|
||||
|
||||
# 左侧控制面板
|
||||
left_panel = tk.Frame(main_frame, width=250, bg='#f0f0f0')
|
||||
left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=(0,5))
|
||||
|
||||
# 右侧画布区域
|
||||
right_panel = tk.Frame(main_frame)
|
||||
right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
|
||||
|
||||
# 控制面板内容
|
||||
self.setup_control_panel(left_panel)
|
||||
|
||||
# 画布
|
||||
self.canvas = tk.Canvas(right_panel, bg='#404040')
|
||||
self.canvas.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
# 状态栏
|
||||
self.status_var = tk.StringVar()
|
||||
self.status_var.set("请打开图片,然后用滚轮缩放、右键拖拽调整视图,依次点击多个点围成x图标区域")
|
||||
status_bar = tk.Label(right_panel, textvariable=self.status_var,
|
||||
anchor="w", bg='#e0e0e0', relief=tk.SUNKEN)
|
||||
status_bar.pack(fill=tk.X, side=tk.BOTTOM)
|
||||
|
||||
# 绑定画布事件
|
||||
self.canvas.bind("<Button-1>", self.on_canvas_click) # 左键添加点
|
||||
self.canvas.bind("<Button-3>", self.on_canvas_right_click) # 右键完成多边形
|
||||
self.canvas.bind("<B3-Motion>", self.on_canvas_drag) # 右键拖拽
|
||||
self.canvas.bind("<MouseWheel>", self.on_mousewheel) # 滚轮缩放
|
||||
self.root.bind("<space>", self.finish_polygon) # 空格键完成多边形
|
||||
self.root.bind("<BackSpace>", self.remove_last_point) # 退格键删除最后一个点
|
||||
|
||||
def setup_control_panel(self, parent):
|
||||
"""设置控制面板"""
|
||||
# 标题
|
||||
title = tk.Label(parent, text="区域选择器", font=("Arial", 12, "bold"), bg='#f0f0f0')
|
||||
title.pack(pady=10)
|
||||
|
||||
# 当前选择信息
|
||||
select_frame = tk.LabelFrame(parent, text="当前选择", bg='#f0f0f0')
|
||||
select_frame.pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
self.select_info = tk.StringVar()
|
||||
self.select_info.set("未选择区域")
|
||||
tk.Label(select_frame, textvariable=self.select_info, anchor="w", bg='#f0f0f0',
|
||||
justify=tk.LEFT, wraplength=220).pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
# 分析结果
|
||||
result_frame = tk.LabelFrame(parent, text="分析结果", bg='#f0f0f0')
|
||||
result_frame.pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
self.result_text = tk.Text(result_frame, height=10, width=25, font=("Courier", 9))
|
||||
scrollbar = tk.Scrollbar(result_frame, command=self.result_text.yview)
|
||||
self.result_text.config(yscrollcommand=scrollbar.set)
|
||||
self.result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)
|
||||
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
|
||||
|
||||
# 按钮区域
|
||||
btn_frame = tk.Frame(parent, bg='#f0f0f0')
|
||||
btn_frame.pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
tk.Button(btn_frame, text="分析区域", command=self.analyze_region,
|
||||
bg='#4CAF50', fg='white').pack(fill=tk.X, pady=2)
|
||||
tk.Button(btn_frame, text="清除选择", command=self.clear_selection,
|
||||
bg='#f44336', fg='white').pack(fill=tk.X, pady=2)
|
||||
tk.Button(btn_frame, text="显示所有", command=self.show_all_regions,
|
||||
bg='#2196F3', fg='white').pack(fill=tk.X, pady=2)
|
||||
tk.Button(btn_frame, text="清除所有", command=self.clear_all_regions,
|
||||
bg='#FF9800', fg='white').pack(fill=tk.X, pady=2)
|
||||
|
||||
# 添加使用说明
|
||||
help_frame = tk.LabelFrame(parent, text="多边形选择说明", bg='#f0f0f0')
|
||||
help_frame.pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
help_text = """操作步骤:
|
||||
1. 打开图片
|
||||
2. 滚轮缩放,右键拖拽调整视图
|
||||
3. 依次点击多个点围成x图标
|
||||
4. 右键或按Space完成选择
|
||||
5. 按Enter分析区域
|
||||
|
||||
快捷键:
|
||||
Space: 完成多边形
|
||||
BackSpace: 删除最后一个点
|
||||
+/-: 放大缩小
|
||||
Ctrl+0: 重置缩放
|
||||
Ctrl+F: 适应窗口"""
|
||||
tk.Label(help_frame, text=help_text, anchor="w", bg='#f0f0f0',
|
||||
justify=tk.LEFT, font=("Arial", 9)).pack(fill=tk.X, padx=5, pady=5)
|
||||
|
||||
def ask_for_image(self):
|
||||
"""选择图片文件"""
|
||||
filetypes = [("图片文件", "*.png *.jpg *.jpeg *.bmp *.webp"), ("所有文件", "*.*")]
|
||||
filename = filedialog.askopenfilename(title="选择图片", filetypes=filetypes)
|
||||
|
||||
if filename:
|
||||
self.load_image(filename)
|
||||
|
||||
def load_image(self, path):
|
||||
"""加载图片"""
|
||||
try:
|
||||
self.image_path = path
|
||||
self.img = Image.open(path).convert("RGB")
|
||||
self.w, self.h = self.img.size
|
||||
self.scale = 1.0
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
self.clear_selection()
|
||||
self.clear_all_regions()
|
||||
self.update_display()
|
||||
self.root.title(f"多边形区域选择器 - {Path(path).name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x")
|
||||
self.status_var.set("图片已加载,请依次点击多个点围成x图标区域")
|
||||
except Exception as e:
|
||||
messagebox.showerror("错误", f"加载图片失败: {e}")
|
||||
|
||||
def update_display(self):
|
||||
"""更新显示"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
# 获取canvas尺寸
|
||||
canvas_w = self.canvas.winfo_width()
|
||||
canvas_h = self.canvas.winfo_height()
|
||||
|
||||
if canvas_w <= 1 or canvas_h <= 1:
|
||||
return
|
||||
|
||||
# 计算显示尺寸
|
||||
disp_w = int(self.w * self.scale)
|
||||
disp_h = int(self.h * self.scale)
|
||||
|
||||
# 缩放图片
|
||||
if self.scale != 1.0:
|
||||
try:
|
||||
resample = Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS
|
||||
except:
|
||||
resample = Image.BICUBIC
|
||||
resized = self.img.resize((disp_w, disp_h), resample)
|
||||
else:
|
||||
resized = self.img
|
||||
|
||||
self.photo = ImageTk.PhotoImage(resized)
|
||||
self.canvas.config(scrollregion=(0, 0, disp_w, disp_h))
|
||||
self.canvas.delete("image")
|
||||
self.canvas.create_image(-self.offset_x, -self.offset_y, anchor=tk.NW,
|
||||
image=self.photo, tags="image")
|
||||
|
||||
# 重新绘制多边形
|
||||
self.redraw_polygon()
|
||||
|
||||
# 更新标题
|
||||
if self.image_path:
|
||||
self.root.title(f"多边形区域选择器 - {Path(self.image_path).name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x")
|
||||
|
||||
def redraw_polygon(self):
|
||||
"""重新绘制多边形"""
|
||||
self.canvas.delete("polygon")
|
||||
|
||||
if not self.polygon_points:
|
||||
return
|
||||
|
||||
# 绘制多边形边线
|
||||
if len(self.polygon_points) >= 2:
|
||||
canvas_points = []
|
||||
for img_x, img_y in self.polygon_points:
|
||||
canvas_x = img_x * self.scale - self.offset_x
|
||||
canvas_y = img_y * self.scale - self.offset_y
|
||||
canvas_points.extend([canvas_x, canvas_y])
|
||||
|
||||
# 如果多边形已完成,绘制闭合多边形
|
||||
if len(self.polygon_points) >= 3:
|
||||
# 连接最后一个点到第一个点
|
||||
first_x = self.polygon_points[0][0] * self.scale - self.offset_x
|
||||
first_y = self.polygon_points[0][1] * self.scale - self.offset_y
|
||||
canvas_points.extend([first_x, first_y])
|
||||
|
||||
# 绘制填充的多边形
|
||||
self.polygon_id = self.canvas.create_polygon(
|
||||
canvas_points,
|
||||
outline='red', fill='red', stipple='gray50',
|
||||
width=2, tags="polygon"
|
||||
)
|
||||
else:
|
||||
# 绘制开放的多边形线条
|
||||
self.polygon_id = self.canvas.create_line(
|
||||
canvas_points,
|
||||
fill='red', width=2, tags="polygon"
|
||||
)
|
||||
|
||||
# 绘制顶点
|
||||
for i, (img_x, img_y) in enumerate(self.polygon_points):
|
||||
canvas_x = img_x * self.scale - self.offset_x
|
||||
canvas_y = img_y * self.scale - self.offset_y
|
||||
|
||||
# 绘制点(根据缩放调整大小)
|
||||
radius = max(3, int(3 / self.scale)) if self.scale > 0 else 3
|
||||
self.canvas.create_oval(
|
||||
canvas_x - radius, canvas_y - radius,
|
||||
canvas_x + radius, canvas_y + radius,
|
||||
fill='blue', outline='white', width=1, tags="polygon"
|
||||
)
|
||||
|
||||
# 绘制点编号(根据缩放调整字体大小)
|
||||
font_size = max(8, int(10 / self.scale)) if self.scale > 0 else 8
|
||||
self.canvas.create_text(
|
||||
canvas_x, canvas_y - radius - 5,
|
||||
text=str(i+1), fill='white', font=('Arial', font_size, 'bold'),
|
||||
tags="polygon"
|
||||
)
|
||||
|
||||
def canvas_to_image_coords(self, canvas_x, canvas_y):
|
||||
"""画布坐标转图片坐标"""
|
||||
if self.scale == 0:
|
||||
return 0, 0
|
||||
img_x = int((canvas_x + self.offset_x) / self.scale)
|
||||
img_y = int((canvas_y + self.offset_y) / self.scale)
|
||||
return max(0, min(img_x, self.w-1)), max(0, min(img_y, self.h-1))
|
||||
|
||||
def on_canvas_click(self, event):
|
||||
"""画布点击 - 添加多边形顶点"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
img_x, img_y = self.canvas_to_image_coords(event.x, event.y)
|
||||
|
||||
# 添加新点到多边形
|
||||
self.polygon_points.append((img_x, img_y))
|
||||
self.redraw_polygon()
|
||||
|
||||
point_num = len(self.polygon_points)
|
||||
self.status_var.set(f"已添加第{point_num}个点: ({img_x}, {img_y}) | 右键或按空格完成多边形")
|
||||
print(f"点 {point_num}: ({img_x}, {img_y})")
|
||||
|
||||
def on_canvas_right_click(self, event):
|
||||
"""右键点击 - 完成多边形"""
|
||||
self.finish_polygon()
|
||||
|
||||
def finish_polygon(self, event=None):
|
||||
"""完成多边形选择"""
|
||||
if len(self.polygon_points) < 3:
|
||||
messagebox.showwarning("警告", "需要至少3个点才能构成多边形")
|
||||
return
|
||||
|
||||
# 关闭多边形(连接最后一个点到第一个点)
|
||||
self.redraw_polygon()
|
||||
self.update_selection_info()
|
||||
|
||||
point_count = len(self.polygon_points)
|
||||
self.status_var.set(f"多边形已完成 ({point_count}个顶点),按Enter分析区域")
|
||||
print(f"多边形完成,共{point_count}个顶点")
|
||||
|
||||
def remove_last_point(self, event=None):
|
||||
"""删除最后一个点"""
|
||||
if self.polygon_points:
|
||||
removed_point = self.polygon_points.pop()
|
||||
self.redraw_polygon()
|
||||
point_count = len(self.polygon_points)
|
||||
if point_count > 0:
|
||||
self.status_var.set(f"已删除最后一个点,还剩{point_count}个点")
|
||||
print(f"删除点: {removed_point},还剩{point_count}个点")
|
||||
else:
|
||||
self.status_var.set("已清除所有点,请重新选择")
|
||||
print("已清除所有点")
|
||||
else:
|
||||
self.status_var.set("没有点可以删除")
|
||||
|
||||
def on_mousewheel(self, event):
|
||||
"""鼠标滚轮缩放"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
# Windows用event.delta,Linux用event.num
|
||||
if event.delta > 0 or event.num == 4: # 放大
|
||||
self.zoom_at_point(event.x, event.y, 1.2)
|
||||
elif event.delta < 0 or event.num == 5: # 缩小
|
||||
self.zoom_at_point(event.x, event.y, 0.8)
|
||||
|
||||
def on_canvas_drag(self, event):
|
||||
"""右键拖拽图片"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
if not self.is_dragging:
|
||||
self.is_dragging = True
|
||||
self.drag_start_x = event.x
|
||||
self.drag_start_y = event.y
|
||||
return
|
||||
|
||||
# 计算拖拽距离
|
||||
dx = event.x - self.drag_start_x
|
||||
dy = event.y - self.drag_start_y
|
||||
|
||||
# 更新偏移
|
||||
self.offset_x += dx
|
||||
self.offset_y += dy
|
||||
|
||||
# 限制拖拽范围
|
||||
self.limit_offsets()
|
||||
|
||||
# 更新拖拽起始点
|
||||
self.drag_start_x = event.x
|
||||
self.drag_start_y = event.y
|
||||
|
||||
# 重新显示
|
||||
self.update_display()
|
||||
self.status_var.set(f"拖拽中... 偏移: ({self.offset_x:.0f}, {self.offset_y:.0f})")
|
||||
|
||||
def zoom_at_point(self, canvas_x, canvas_y, factor):
|
||||
"""在指定点缩放"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
old_scale = self.scale
|
||||
new_scale = max(self.min_scale, min(self.max_scale, old_scale * factor))
|
||||
|
||||
if abs(new_scale - old_scale) < 0.01:
|
||||
return
|
||||
|
||||
# 计算缩放中心点在图像中的位置
|
||||
img_x = (canvas_x + self.offset_x) / old_scale
|
||||
img_y = (canvas_y + self.offset_y) / old_scale
|
||||
|
||||
# 更新缩放
|
||||
self.scale = new_scale
|
||||
|
||||
# 调整偏移使缩放点保持在原位
|
||||
self.offset_x = img_x * new_scale - canvas_x
|
||||
self.offset_y = img_y * new_scale - canvas_y
|
||||
|
||||
# 限制偏移范围
|
||||
self.limit_offsets()
|
||||
|
||||
# 重新显示
|
||||
self.update_display()
|
||||
self.status_var.set(f"缩放: {self.scale:.2f}x")
|
||||
|
||||
def limit_offsets(self):
|
||||
"""限制偏移范围,防止图片拖拽出视野"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
canvas_w = self.canvas.winfo_width()
|
||||
canvas_h = self.canvas.winfo_height()
|
||||
|
||||
if canvas_w <= 1 or canvas_h <= 1:
|
||||
return
|
||||
|
||||
disp_w = self.w * self.scale
|
||||
disp_h = self.h * self.scale
|
||||
|
||||
# 计算最大偏移
|
||||
max_offset_x = max(0, disp_w - canvas_w)
|
||||
max_offset_y = max(0, disp_h - canvas_h)
|
||||
|
||||
# 限制偏移
|
||||
self.offset_x = max(-canvas_w // 2, min(self.offset_x, max_offset_x + canvas_w // 2))
|
||||
self.offset_y = max(-canvas_h // 2, min(self.offset_y, max_offset_y + canvas_h // 2))
|
||||
|
||||
def zoom_in(self):
|
||||
"""放大"""
|
||||
if self.img:
|
||||
canvas_w = self.canvas.winfo_width()
|
||||
canvas_h = self.canvas.winfo_height()
|
||||
center_x = canvas_w // 2
|
||||
center_y = canvas_h // 2
|
||||
self.zoom_at_point(center_x, center_y, 1.5)
|
||||
|
||||
def zoom_out(self):
|
||||
"""缩小"""
|
||||
if self.img:
|
||||
canvas_w = self.canvas.winfo_width()
|
||||
canvas_h = self.canvas.h // 2
|
||||
center_x = canvas_w // 2
|
||||
center_y = canvas_h // 2
|
||||
self.zoom_at_point(center_x, center_y, 0.67)
|
||||
|
||||
def reset_zoom(self):
|
||||
"""重置缩放"""
|
||||
if self.img:
|
||||
self.scale = 1.0
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
self.update_display()
|
||||
self.status_var.set("已重置缩放")
|
||||
|
||||
def fit_to_window(self):
|
||||
"""适应窗口"""
|
||||
if not self.img:
|
||||
return
|
||||
|
||||
self.canvas.update()
|
||||
canvas_w = self.canvas.winfo_width()
|
||||
canvas_h = self.canvas.winfo_height()
|
||||
|
||||
if canvas_w > 0 and canvas_h > 0:
|
||||
scale_x = canvas_w / self.w
|
||||
scale_y = canvas_h / self.h
|
||||
self.scale = min(scale_x, scale_y) * 0.9
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
self.update_display()
|
||||
self.status_var.set(f"适应窗口,缩放: {self.scale:.2f}x")
|
||||
|
||||
def update_selection_info(self):
|
||||
"""更新选择信息"""
|
||||
if self.polygon_points:
|
||||
point_count = len(self.polygon_points)
|
||||
if point_count >= 3:
|
||||
self.select_info.set(f"多边形: {point_count}个顶点\n状态: 已完成")
|
||||
else:
|
||||
self.select_info.set(f"多边形: {point_count}个顶点\n状态: 未完成(需要至少3个点)")
|
||||
else:
|
||||
self.select_info.set("未选择区域")
|
||||
|
||||
|
||||
def clear_selection(self):
|
||||
"""清除选择"""
|
||||
self.polygon_points = []
|
||||
self.canvas.delete("polygon")
|
||||
self.update_selection_info()
|
||||
if self.img:
|
||||
self.status_var.set("已清除多边形,请重新依次点击多个点围成区域")
|
||||
else:
|
||||
self.status_var.set("请先打开图片")
|
||||
|
||||
def analyze_region(self):
|
||||
"""分析多边形区域"""
|
||||
if not self.img or len(self.polygon_points) < 3:
|
||||
messagebox.showwarning("警告", "请先选择一个完整的多边形区域(至少3个点)")
|
||||
return
|
||||
|
||||
# 创建多边形mask
|
||||
mask = Image.new('L', (self.w, self.h), 0)
|
||||
draw = ImageDraw.Draw(mask)
|
||||
|
||||
# 将多边形点转换为整数坐标
|
||||
polygon_coords = [(int(x), int(y)) for x, y in self.polygon_points]
|
||||
|
||||
# 绘制多边形(填充为白色)
|
||||
draw.polygon(polygon_coords, fill=255)
|
||||
|
||||
# 将mask转换为numpy数组
|
||||
mask_array = np.array(mask)
|
||||
|
||||
# 获取原始图像的像素数据
|
||||
img_array = np.array(self.img)
|
||||
|
||||
# 计算多边形内部的总像素数
|
||||
total_pixels = np.sum(mask_array > 0)
|
||||
|
||||
if total_pixels == 0:
|
||||
messagebox.showwarning("警告", "多边形区域为空,请重新选择")
|
||||
return
|
||||
|
||||
# 计算多边形内部的白色像素
|
||||
white_count = 0
|
||||
for y in range(self.h):
|
||||
for x in range(self.w):
|
||||
if mask_array[y, x] > 0: # 在多边形内部
|
||||
r, g, b = img_array[y, x]
|
||||
if r >= 240 and g >= 240 and b >= 240: # 白色阈值
|
||||
white_count += 1
|
||||
|
||||
white_ratio = white_count / total_pixels if total_pixels > 0 else 0
|
||||
|
||||
# 计算置信度(基于与0.5的距离)
|
||||
confidence = 1 - abs(white_ratio - 0.5) * 2
|
||||
|
||||
# 保存结果
|
||||
region_data = {
|
||||
'polygon_points': self.polygon_points.copy(),
|
||||
'total_pixels': total_pixels,
|
||||
'white_pixels': white_count,
|
||||
'white_ratio': white_ratio,
|
||||
'confidence': confidence,
|
||||
'image_path': str(self.image_path) if self.image_path else None
|
||||
}
|
||||
|
||||
self.regions.append(region_data)
|
||||
|
||||
# 显示结果
|
||||
result_text = f"多边形区域分析结果:\n"
|
||||
result_text += f"顶点数量: {len(self.polygon_points)}\n"
|
||||
result_text += f"顶点坐标:\n"
|
||||
for i, (x, y) in enumerate(self.polygon_points):
|
||||
result_text += f" {i+1}: ({x:.0f}, {y:.0f})\n"
|
||||
result_text += f"总像素: {total_pixels}\n"
|
||||
result_text += f"白色像素: {white_count}\n"
|
||||
result_text += f"白色比例: {white_ratio:.3f}\n"
|
||||
result_text += f"置信度: {confidence:.3f}\n"
|
||||
# 判断是否可能是直播图标
|
||||
if white_ratio < 0.3:
|
||||
result_text += f"判断: 可能是直播图标 (白色像素较少)\n"
|
||||
elif white_ratio > 0.7:
|
||||
result_text += f"判断: 可能不是直播图标 (白色像素较多)\n"
|
||||
else:
|
||||
result_text += f"判断: 不确定 (白色比例适中)\n"
|
||||
|
||||
self.result_text.delete(1.0, tk.END)
|
||||
self.result_text.insert(tk.END, result_text)
|
||||
|
||||
print(f"\n=== 多边形区域分析结果 ===")
|
||||
print(f"顶点: {self.polygon_points}")
|
||||
print(result_text)
|
||||
print(f"结果已保存 (共{len(self.regions)}个区域)")
|
||||
|
||||
def show_all_regions(self):
|
||||
"""显示所有区域"""
|
||||
if not self.regions:
|
||||
messagebox.showinfo("信息", "没有保存的区域数据")
|
||||
return
|
||||
|
||||
result_text = f"所有多边形区域数据 (共{len(self.regions)}个):\n\n"
|
||||
for i, region in enumerate(self.regions, 1):
|
||||
result_text += f"区域 {i}:\n"
|
||||
result_text += f" 顶点数: {len(region['polygon_points'])}\n"
|
||||
result_text += f" 顶点坐标:\n"
|
||||
for j, (x, y) in enumerate(region['polygon_points']):
|
||||
result_text += f" {j+1}: ({x:.0f}, {y:.0f})\n"
|
||||
result_text += f" 白色像素: {region['white_pixels']}/{region['total_pixels']}\n"
|
||||
result_text += f" 比例: {region['white_ratio']:.3f}, 置信度: {region['confidence']:.3f}\n\n"
|
||||
|
||||
self.result_text.delete(1.0, tk.END)
|
||||
self.result_text.insert(tk.END, result_text)
|
||||
|
||||
def clear_all_regions(self):
|
||||
"""清除所有区域"""
|
||||
self.regions.clear()
|
||||
self.result_text.delete(1.0, tk.END)
|
||||
self.result_text.insert(tk.END, "已清除所有区域数据")
|
||||
|
||||
def save_regions(self):
|
||||
"""保存区域数据"""
|
||||
if not self.regions:
|
||||
messagebox.showwarning("警告", "没有区域数据可以保存")
|
||||
return
|
||||
|
||||
filename = filedialog.asksaveasfilename(
|
||||
title="保存区域数据",
|
||||
defaultextension=".json",
|
||||
filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")]
|
||||
)
|
||||
|
||||
if filename:
|
||||
try:
|
||||
with open(filename, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.regions, f, indent=2, ensure_ascii=False)
|
||||
messagebox.showinfo("成功", f"区域数据已保存到: {filename}")
|
||||
except Exception as e:
|
||||
messagebox.showerror("错误", f"保存失败: {e}")
|
||||
|
||||
def load_regions(self):
|
||||
"""加载区域数据"""
|
||||
filename = filedialog.askopenfilename(
|
||||
title="加载区域数据",
|
||||
filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")]
|
||||
)
|
||||
|
||||
if filename:
|
||||
try:
|
||||
with open(filename, 'r', encoding='utf-8') as f:
|
||||
self.regions = json.load(f)
|
||||
messagebox.showinfo("成功", f"已加载 {len(self.regions)} 个区域数据")
|
||||
self.show_all_regions()
|
||||
except Exception as e:
|
||||
messagebox.showerror("错误", f"加载失败: {e}")
|
||||
|
||||
def run(self):
|
||||
"""运行主循环"""
|
||||
self.root.mainloop()
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
# 如果有命令行参数,使用它作为图片路径
|
||||
image_path = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
|
||||
if image_path and not os.path.exists(image_path):
|
||||
print(f"错误: 找不到图片文件 {image_path}")
|
||||
image_path = None
|
||||
|
||||
try:
|
||||
app = SimpleRegionSelector(image_path)
|
||||
app.run()
|
||||
except Exception as e:
|
||||
print(f"启动失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
在两个指定小区域内统计白色像素比例,用于辅助判断右上角是否有关闭 X 图标。
|
||||
|
||||
用法示例:
|
||||
python tools/test_white_regions_x.py pic/screenshot_recommend.png pic/screenshot_live.png
|
||||
|
||||
思路:
|
||||
- 假设原始截图分辨率约为 1080x2400(宽x高),并使用与代码中像素检测相同的坐标系。
|
||||
- X 图标所在的大 ROI 为 (972,147)-(1047,216)
|
||||
- 你在 pick_coords 中点出的两个白色点大致为:
|
||||
P1 = (999,174)
|
||||
P2 = (1025,201)
|
||||
- 本脚本在这两个点附近取一个小方框(默认 7x7),统计白色像素比例。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from typing import Tuple, List
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# 修正 Windows 控制台编码问题
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def load_image(path: str) -> np.ndarray:
|
||||
"""加载图片(支持中文路径),返回 BGR 图像。"""
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(path)
|
||||
data = np.fromfile(path, dtype=np.uint8)
|
||||
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
||||
if img is None:
|
||||
raise RuntimeError(f"无法读取图片: {path}")
|
||||
return img
|
||||
|
||||
|
||||
def crop_region(
|
||||
img: np.ndarray, x1: int, y1: int, x2: int, y2: int
|
||||
) -> np.ndarray:
|
||||
h, w = img.shape[:2]
|
||||
x1 = max(0, min(w - 1, x1))
|
||||
x2 = max(0, min(w, x2))
|
||||
y1 = max(0, min(h - 1, y1))
|
||||
y2 = max(0, min(h, y2))
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
return img[0:0, 0:0]
|
||||
return img[y1:y2, x1:x2]
|
||||
|
||||
|
||||
def count_white_pixels(region: np.ndarray, gray_threshold: int = 245, diff_threshold: int = 10) -> Tuple[int, int, float]:
|
||||
"""
|
||||
统计区域内“白色像素”数量。
|
||||
|
||||
- gray_threshold: 灰度阈值(越大越严格,默认 245)
|
||||
- diff_threshold: RGB 分量差异阈值(越小越接近纯白,默认 10)
|
||||
"""
|
||||
if region.size == 0:
|
||||
return 0, 0, 0.0
|
||||
|
||||
b, g, r = cv2.split(region)
|
||||
gray = cv2.cvtColor(region, cv2.COLOR_BGR2GRAY)
|
||||
|
||||
# 灰度足够亮
|
||||
bright = gray >= gray_threshold
|
||||
# RGB 三通道差异不大(接近无色)
|
||||
diff_rg = np.abs(r.astype(np.int16) - g.astype(np.int16)) <= diff_threshold
|
||||
diff_rb = np.abs(r.astype(np.int16) - b.astype(np.int16)) <= diff_threshold
|
||||
diff_gb = np.abs(g.astype(np.int16) - b.astype(np.int16)) <= diff_threshold
|
||||
|
||||
white_mask = bright & diff_rg & diff_rb & diff_gb
|
||||
white_count = int(white_mask.sum())
|
||||
total = int(region.shape[0] * region.shape[1])
|
||||
ratio = white_count / total if total > 0 else 0.0
|
||||
return white_count, total, ratio
|
||||
|
||||
|
||||
def analyse_image(
|
||||
path: str,
|
||||
p1: Tuple[int, int],
|
||||
p2: Tuple[int, int],
|
||||
) -> None:
|
||||
"""对单张截图进行分析并打印结果(使用两点组成的对角矩形区域)。"""
|
||||
img = load_image(path)
|
||||
h, w = img.shape[:2]
|
||||
print("=" * 80)
|
||||
print(f"图片: {path}")
|
||||
print(f"尺寸: {w}x{h}")
|
||||
|
||||
# 如果不是接近 1080x2400,可以按宽高比例缩放坐标
|
||||
base_w, base_h = 1080, 2400
|
||||
scale_x = w / base_w
|
||||
scale_y = h / base_h
|
||||
|
||||
def scaled_point(p: Tuple[int, int]) -> Tuple[int, int]:
|
||||
return int(round(p[0] * scale_x)), int(round(p[1] * scale_y))
|
||||
|
||||
sp1 = scaled_point(p1)
|
||||
sp2 = scaled_point(p2)
|
||||
|
||||
# 使用两点组成对角矩形区域
|
||||
x1, y1 = sp1
|
||||
x2, y2 = sp2
|
||||
rx1, ry1 = min(x1, x2), min(y1, y2)
|
||||
rx2, ry2 = max(x1, x2), max(y1, y2)
|
||||
|
||||
region = crop_region(img, rx1, ry1, rx2, ry2)
|
||||
|
||||
# 为了更接近“纯白”,在这个测试里稍微提高阈值要求
|
||||
white_count, total, ratio = count_white_pixels(region, gray_threshold=250, diff_threshold=5)
|
||||
|
||||
print(f"矩形区域(基于原坐标): {p1} - {p2}")
|
||||
print(f"实际像素区域: ({rx1},{ry1})-({rx2},{ry2}), 尺寸={region.shape[1]}x{region.shape[0]}")
|
||||
print(f"纯白像素: {white_count}/{total}, 比例={ratio:.4f}")
|
||||
|
||||
|
||||
def main(argv: List[str]) -> int:
|
||||
if len(argv) < 2:
|
||||
print(
|
||||
"用法: python tools/test_white_regions_x.py <图片1> [图片2 ...]\n"
|
||||
"建议:分别传入推荐页截图和直播间截图,对比输出的白色像素比例。"
|
||||
)
|
||||
return 1
|
||||
|
||||
# 你在 pick_coords 中点出的两个点
|
||||
p1 = (999, 174)
|
||||
p2 = (1025, 201)
|
||||
|
||||
for path in argv[1:]:
|
||||
try:
|
||||
analyse_image(path, p1, p2)
|
||||
except Exception as e:
|
||||
print(f"分析失败: {path} -> {e}")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv))
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
抖音区域选择器使用说明
|
||||
==========================
|
||||
|
||||
工具位置:
|
||||
- 主程序:tools/simple_region_selector.py
|
||||
- 启动脚本:tools/启动区域选择器.bat
|
||||
|
||||
功能说明:
|
||||
这个工具专门用于抖音挂机项目,帮助你:
|
||||
1. 可视化选择直播间图标(x)的区域
|
||||
2. 统计区域内的白色像素数量
|
||||
3. 通过白色像素比例判断是否为直播状态
|
||||
4. 保存区域坐标和分析结果
|
||||
|
||||
快速开始:
|
||||
1. 双击运行 "启动区域选择器.bat"
|
||||
2. 在弹出的窗口中点击"文件" -> "打开图片"
|
||||
3. 选择一张抖音截图(比如pic/screenshot.png)
|
||||
4. 依次点击多个点围成x图标的形状
|
||||
5. 右键或按空格键完成多边形选择
|
||||
6. 按Enter键分析白色像素统计
|
||||
7. 按Ctrl+S保存区域坐标数据
|
||||
|
||||
操作说明:
|
||||
- 依次点击:沿着x图标的边缘点击多个点
|
||||
- 完成选择:右键点击或按空格键闭合多边形
|
||||
- 删除点:按Backspace键删除最后一个点
|
||||
- 系统会自动绘制红色多边形和半透明填充显示选择的区域
|
||||
- 不支持拖拽图片或放大缩小,图片按原始大小显示
|
||||
|
||||
使用技巧:
|
||||
- 多边形可以精确围住不规则形状的x图标
|
||||
- 至少需要3个点才能构成有效多边形
|
||||
- 白色像素比例<0.3:可能是直播图标
|
||||
- 白色像素比例>0.7:可能不是直播图标
|
||||
- 置信度接近1.0:判断更可靠
|
||||
|
||||
图片操作:
|
||||
- 鼠标滚轮:放大缩小
|
||||
- 右键拖拽:移动图片
|
||||
- 适应窗口:自动调整缩放比例
|
||||
- 重置缩放:恢复原始大小
|
||||
|
||||
快捷键:
|
||||
Ctrl+O 打开图片
|
||||
Enter 分析区域
|
||||
Delete 清除选择
|
||||
Space 完成多边形
|
||||
Backspace 删除最后一个点
|
||||
Ctrl+S 保存数据
|
||||
Ctrl+L 加载数据
|
||||
+/- 放大缩小
|
||||
Ctrl+0 重置缩放
|
||||
Ctrl+F 适应窗口
|
||||
|
||||
输出格式:
|
||||
保存的JSON文件包含:
|
||||
- 坐标范围 (x1,y1)-(x2,y2)
|
||||
- 区域尺寸
|
||||
- 白色像素统计
|
||||
- 置信度分析
|
||||
|
||||
注意事项:
|
||||
- 确保Python和PIL库已安装
|
||||
- 建议使用高分辨率截图
|
||||
- 区域选择要精确圈住图标
|
||||
@@ -0,0 +1,35 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
title 抖音区域选择器 - 白色像素统计工具
|
||||
|
||||
echo ========================================
|
||||
echo 抖音区域选择器 - 白色像素统计工具
|
||||
echo ========================================
|
||||
echo.
|
||||
echo 这个工具可以帮助你:
|
||||
echo - 可视化选择图片区域(圈出x图标位置)
|
||||
echo - 统计区域内白色像素数量
|
||||
echo - 保存区域坐标和分析结果
|
||||
echo.
|
||||
echo 使用方法:
|
||||
echo 1. 点击"文件" -> "打开图片" 选择截图
|
||||
echo 2. 滚轮缩放,右键拖拽调整视图
|
||||
echo 3. 依次点击多个点围成x图标形状
|
||||
echo 4. 右键或按空格键完成多边形选择
|
||||
echo 5. 按Enter键分析白色像素统计
|
||||
echo 6. Ctrl+S保存区域数据
|
||||
echo.
|
||||
echo 快捷键:
|
||||
echo Ctrl+O: 打开图片
|
||||
echo Ctrl+S: 保存区域数据
|
||||
echo Enter: 分析区域
|
||||
echo Delete: 清除选择
|
||||
echo +/-: 放大缩小
|
||||
echo Ctrl+0: 重置缩放
|
||||
echo.
|
||||
echo ========================================
|
||||
|
||||
cd /d "%~dp0"
|
||||
python simple_region_selector.py
|
||||
|
||||
pause
|
||||
Whitespace-only changes.
@@ -26,5 +26,4 @@ def setLogLevel(level: int) -> None: ...
|
||||
class utils:
|
||||
class logging:
|
||||
LOG_LEVEL_SILENT: int
|
||||
def setLogLevel(level: int) -> None: ...
|
||||
def equalizeHist(src: Any, dst: Any = ...) -> Any: ...
|
||||
+2
-4
@@ -677,15 +677,13 @@ async function startRun() {
|
||||
async function testYanghao() {
|
||||
const deviceId = $("device").value || "";
|
||||
const seconds = parseInt($("yanghao_recommend_duration_seconds").value || "60", 10);
|
||||
await apiPost("/api/test-yanghao", { device_id: deviceId, seconds });
|
||||
appendLog([`[WEB] 已启动测试养号:device=${deviceId || '(auto)'} seconds=${seconds}`]);
|
||||
// 已移除测试养号功能
|
||||
}
|
||||
|
||||
async function testComment() {
|
||||
const deviceId = $("device").value || "";
|
||||
const text = "";
|
||||
await apiPost("/api/test-comment", { device_id: deviceId, text });
|
||||
appendLog([`[WEB] 已启动测试评论:device=${deviceId || '(auto)'}${text ? ' text=自定义' : ''}`]);
|
||||
// 已移除测试评论功能
|
||||
}
|
||||
|
||||
async function stopRun() {
|
||||
|
||||
+81
-84
@@ -10,7 +10,7 @@
|
||||
<div class="app">
|
||||
<header class="header">
|
||||
<div>
|
||||
<div class="title">抖音挂机控制台</div>
|
||||
<div class="title">�㚚𨺗��㦤�批��?/div>
|
||||
<div class="subtitle">配置与运行(纯坐标点击)</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
@@ -18,8 +18,7 @@
|
||||
<span class="btnIcon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4v16l13-8z"/></svg>
|
||||
</span>
|
||||
开始运行
|
||||
</button>
|
||||
撘�憪贝�銵? </button>
|
||||
<button id="btnRefresh" class="btn">
|
||||
<span class="btnIcon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>
|
||||
@@ -74,7 +73,7 @@
|
||||
</button>
|
||||
<button class="tabBtn" type="button" data-target="filter" role="tab" aria-selected="false">
|
||||
<span class="tabIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 3H2l8 9v7l4 2v-9z"/></svg></span>
|
||||
<span class="tabText">筛选</span>
|
||||
<span class="tabText">蝑偦�?/span>
|
||||
</button>
|
||||
<button class="tabBtn" type="button" data-target="stats" role="tab" aria-selected="false">
|
||||
<span class="tabIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19V5"/><path d="M20 19V5"/><path d="M8 17v-6"/><path d="M12 17V9"/><path d="M16 17V7"/></svg></span>
|
||||
@@ -86,7 +85,7 @@
|
||||
</button>
|
||||
<button class="tabBtn" type="button" data-target="keywords" role="tab" aria-selected="false">
|
||||
<span class="tabIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10a7 7 0 1 1-14 0 7 7 0 0 1 14 0z"/><path d="M21 21l-6-6"/></svg></span>
|
||||
<span class="tabText">关键词</span>
|
||||
<span class="tabText">�喲睸霂?/span>
|
||||
</button>
|
||||
<button class="tabBtn" type="button" data-target="debug" role="tab" aria-selected="false">
|
||||
<span class="tabIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></span>
|
||||
@@ -118,12 +117,12 @@
|
||||
<input id="y_pianyi" class="input" type="number" min="-200" max="200" step="1" value="0" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">倒计时阈值(分钟)</label>
|
||||
<label class="label">�坿恣�園��?���)</label>
|
||||
<input id="wait_minutes" class="input" type="number" min="1" max="60" step="1" value="5" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">允许切换直播间(needswitch)</label>
|
||||
<label class="label">��捂��揢�湔偘�湛�needswitch嚗?/label>
|
||||
<label class="check">
|
||||
<input id="needswitch" type="checkbox" checked />
|
||||
<span>启用</span>
|
||||
@@ -137,79 +136,78 @@
|
||||
</label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">切换 N 次后回到第一个(次数)</label>
|
||||
<label class="label">��揢 N 甈∪��𧼮�蝚砌�銝迎�甈⊥㺭嚗?/label>
|
||||
<input id="reset_after_swipes" class="input" data-key="reset_after_swipes" data-type="int" type="number" min="1" step="1" />
|
||||
<div class="hint">用于需要循环切换时的回退阈值;配合上方开关启用</div>
|
||||
<div class="hint">�其���閬�儐�臬��X𧒄��������潘��滚�銝𦠜䲮撘��喳鍳�?/div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">找福袋最大尝试次数</label>
|
||||
<label class="label">�曄�鋡𧢲�憭批�霂閙活�?/label>
|
||||
<input id="fudai_find_max_attempts" class="input" data-key="fudai_find_max_attempts" data-type="int" type="number" min="1" max="50" step="1" />
|
||||
<div class="hint">找小福袋图标时的最大重试次数,默认 5</div>
|
||||
</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">找福袋重试间隔(秒)</label>
|
||||
<label class="label">�曄�鋡钅�霂閖𡢿�?蝘?</label>
|
||||
<input id="fudai_icon_retry_delay_seconds" class="input" data-key="fudai_icon_retry_delay_seconds" data-type="float" type="number" min="0.1" max="3.0" step="0.1" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">找福袋最大等待时间(秒)</label>
|
||||
<label class="label">�曄�鋡𧢲�憭抒�敺�𧒄�?蝘?</label>
|
||||
<input id="fudai_icon_max_wait_seconds" class="input" data-key="fudai_icon_max_wait_seconds" data-type="float" type="number" min="0" max="30" step="0.5" />
|
||||
<div class="hint">识别到福袋一般 4–6 秒,可按设备/网络情况微调</div>
|
||||
<div class="hint">霂���啁�鋡衤��?4�? 蝘𡜐��舀�霈曉�/蝵𤑳����敺株�</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">直播间检测阈值</label>
|
||||
<label class="label">�湔偘�湔�瘚钅��?/label>
|
||||
<input id="live_room_match_threshold" class="input" data-key="live_room_match_threshold" data-type="float" type="number" min="0.0" max="1.0" step="0.01" />
|
||||
<div class="hint">模板匹配阈值(0.0~1.0),默认0.8,值越高越严格,建议≥0.8</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">预约抢占最小价值(元)</label>
|
||||
<label class="label">憸�漲�W���撠譍遠�?�?</label>
|
||||
<input id="reservation_preempt_min_value" class="input" data-key="reservation_preempt_min_value" data-type="float" type="number" min="0" step="1" />
|
||||
<div class="hint">低于该价值的预约不会抢占当前任务;0 表示任何预约可抢占</div>
|
||||
<div class="hint">雿𦒘�霂乩遠�潛�憸�漲銝滢��W�敶枏�隞餃𦛚嚗? 銵函內隞颱�憸�漲�舀𦜖�?/div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel" data-panel="filter" role="tabpanel" hidden>
|
||||
<div class="sectionTitle">
|
||||
<span class="sectionIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 3H2l8 9v7l4 2v-9z"/></svg></span>
|
||||
筛选设置
|
||||
</div>
|
||||
蝑偦�㕑挽蝵? </div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">最低价值(元)</label>
|
||||
<label class="label">��雿𦒘遠�?�?</label>
|
||||
<input id="min_prize_value_yuan" class="input" data-key="min_prize_value_yuan" data-type="float" type="number" min="0" step="0.1" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">倒计时小于(秒)时不参与(高价值可预约)</label>
|
||||
<label class="label">�坿恣�嗅�鈭?蝘?�嗡����嚗��隞瑕�澆虾憸�漲嚗?/label>
|
||||
<input id="skip_if_countdown_lt_seconds" class="input" data-key="skip_if_countdown_lt_seconds" data-type="int" type="number" min="0" max="120" step="1" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">参与人数最小</label>
|
||||
<label class="label">���鈭箸㺭��撠?/label>
|
||||
<input id="min_participants" class="input" data-key="min_participants" data-type="int" type="number" min="0" step="1" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">参与人数最大</label>
|
||||
<label class="label">���鈭箸㺭��憭?/label>
|
||||
<input id="max_participants" class="input" data-key="max_participants" data-type="int" type="number" min="0" step="1" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">自动加入粉丝团(谨慎)</label>
|
||||
<label class="label">�芸𢆡�惩�蝎劐��g�靚冽�嚗?/label>
|
||||
<label class="check">
|
||||
<input id="auto_join_fansclub" type="checkbox" data-key="auto_join_fansclub" data-type="bool" />
|
||||
<span>启用</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">粉丝团失败策略</label>
|
||||
<label class="label">蝎劐��W仃韐亦��?/label>
|
||||
<select id="fansclub_fail_action" class="input" data-key="fansclub_fail_action" data-type="str">
|
||||
<option value="stay">stay</option>
|
||||
<option value="switch">switch</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">高价值福袋预约参与</div>
|
||||
<div class="sectionTitle">擃䀝遠�潛�鋡钅�蝥血�銝?/div>
|
||||
<div class="row">
|
||||
<label class="label">启用预约(价值≥阈值)</label>
|
||||
<label class="check">
|
||||
@@ -219,28 +217,28 @@
|
||||
</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">价值阈值(元)</label>
|
||||
<label class="label">隞瑕�潮��?�?</label>
|
||||
<input id="high_value_fudai_threshold_yuan" class="input" data-key="high_value_fudai_threshold_yuan" data-type="float" type="number" min="0" step="1" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">提前参与(秒)</label>
|
||||
<label class="label">�𣂼����(蝘?</label>
|
||||
<input id="high_value_fudai_join_ahead_seconds" class="input" data-key="high_value_fudai_join_ahead_seconds" data-type="int" type="number" min="5" max="900" step="1" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">最多回退直播间次数</label>
|
||||
<label class="label">��憭𡁜����湔偘�湔活�?/label>
|
||||
<input id="high_value_fudai_max_swipe_back" class="input" data-key="high_value_fudai_max_swipe_back" data-type="int" type="number" min="0" max="300" step="1" />
|
||||
<div class="hint">防止预约期间切换太远导致回退过慢/异常;0 表示不限制</div>
|
||||
<div class="hint">�脫迫憸�漲�罸𡢿��揢憭芾�撖潸稲�鮋��餈��/撘�虜嚗? 銵函內銝漤��?/div>
|
||||
</div>
|
||||
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">最多记录数量</label>
|
||||
<label class="label">��憭朞扇敶閙㺭�?/label>
|
||||
<input id="high_value_fudai_max_reservations" class="input" data-key="high_value_fudai_max_reservations" data-type="int" type="number" min="1" max="50" step="1" />
|
||||
<div class="hint">超过后丢弃最晚开奖的预约</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">完成后策略</label>
|
||||
<label class="label">摰峕��𡒊��?/label>
|
||||
<select id="high_value_fudai_after_action" class="input" data-key="high_value_fudai_after_action" data-type="str">
|
||||
<option value="continue">continue</option>
|
||||
<option value="stay">stay</option>
|
||||
@@ -256,10 +254,10 @@
|
||||
</label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">仅回访本次运行记录的直播间</label>
|
||||
<label class="label">隞��霈踵𧋦甈∟�銵諹扇敶閧��湔偘�?/label>
|
||||
<label class="check">
|
||||
<input id="high_value_room_revisit_only_current_run" type="checkbox" data-key="high_value_room_revisit_only_current_run" data-type="bool" />
|
||||
<span>仅本次运行</span>
|
||||
<span>隞�𧋦甈∟�銵?/span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="row">
|
||||
@@ -272,10 +270,10 @@
|
||||
<div class="row">
|
||||
<label class="label">回退回滑快速延迟(秒,未启用回退校验时生效)</label>
|
||||
<input id="reservation_back_swipe_delay" class="input" data-key="reservation_back_swipe_delay" data-type="float" type="number" min="0.2" step="0.1" />
|
||||
<div class="hint">较小值能加快回退速度;当启用回退校验时仍使用兼容的较慢延迟。</div>
|
||||
<div class="hint">颲���潸��惩翰�鮋���笔漲嚗𥕦��舐鍂�鮋���⊿��嗡�雿輻鍂�澆捆����W辣餈麄�?/div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">定时禁抢(仅养号)</div>
|
||||
<div class="sectionTitle">摰𡁏𧒄蝳�𦜖嚗���餃噡嚗?/div>
|
||||
<div class="row">
|
||||
<label class="label">启用定时禁抢</label>
|
||||
<label class="check">
|
||||
@@ -285,13 +283,13 @@
|
||||
</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">开始小时</label>
|
||||
<label class="label">撘�憪见��?/label>
|
||||
<input id="fudai_quiet_start_hour" class="input" data-key="fudai_quiet_start_hour" data-type="int" type="number" min="0" max="23" step="1" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">结束小时</label>
|
||||
<input id="fudai_quiet_end_hour" class="input" data-key="fudai_quiet_end_hour" data-type="int" type="number" min="0" max="23" step="1" />
|
||||
<div class="hint">区间为 [开始, 结束),例如 2-7 表示 2:00~6:59</div>
|
||||
<div class="hint">�粹𡢿銝?[撘�憪? 蝏𤘪�)嚗䔶�憒?2-7 銵函內 2:00~6:59</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -302,12 +300,12 @@
|
||||
运行统计
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">福袋中奖内容(最近20条)</div>
|
||||
<div class="sectionTitle">蝳讛�銝剖���捆嚗��餈?0�∴�</div>
|
||||
<div class="table" id="tableWins"></div>
|
||||
|
||||
<div class="statsGrid">
|
||||
<div class="stat">
|
||||
<div class="statLabel">运行状态</div>
|
||||
<div class="statLabel">餈鞱��嗆�?/div>
|
||||
<div id="statRunning" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
@@ -324,7 +322,7 @@
|
||||
<div class="statHint" id="statLogCap">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="statLabel">最近日志时间</div>
|
||||
<div class="statLabel">��餈烐𠯫敹埈𧒄�?/div>
|
||||
<div id="statLastLog" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
@@ -338,7 +336,7 @@
|
||||
</div>
|
||||
|
||||
<div class="stat">
|
||||
<div class="statLabel">福袋:识别次数</div>
|
||||
<div class="statLabel">蝳讛�嚗朞��急活�?/div>
|
||||
<div id="statFudaiSeen" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
@@ -346,11 +344,11 @@
|
||||
<div id="statFudaiOpen" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="statLabel">福袋:参与成功/已参与</div>
|
||||
<div class="statLabel">蝳讛�嚗𡁜�銝擧��?撌脣�銝?/div>
|
||||
<div id="statFudaiAttendOk" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="statLabel">福袋:参与失败</div>
|
||||
<div class="statLabel">蝳讛�嚗𡁜�銝𤾸仃韐?/div>
|
||||
<div id="statFudaiAttendFail" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
@@ -358,16 +356,16 @@
|
||||
<div id="statFudaiNoWin" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="statLabel">福袋:中奖次数</div>
|
||||
<div class="statLabel">蝳讛�嚗帋葉憟𡝗活�?/div>
|
||||
<div id="statFudaiWin" class="statValue">-</div>
|
||||
</div>
|
||||
|
||||
<div class="stat">
|
||||
<div class="statLabel">福袋:跳过(价值低)</div>
|
||||
<div class="statLabel">蝳讛�嚗朞歲餈��隞瑕�潔�嚗?/div>
|
||||
<div id="statSkipValueLow" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="statLabel">福袋:跳过(人数低/高)</div>
|
||||
<div class="statLabel">蝳讛�嚗朞歲餈��鈭箸㺭雿?擃矋�</div>
|
||||
<div id="statSkipParticipants" class="statValue">-</div>
|
||||
<div class="statHint" id="statSkipParticipantsHint">-</div>
|
||||
</div>
|
||||
@@ -382,25 +380,25 @@
|
||||
</div>
|
||||
|
||||
<div class="stat">
|
||||
<div class="statLabel">粉丝团门槛</div>
|
||||
<div class="statLabel">蝎劐��a秄瑽?/div>
|
||||
<div id="statFansclub" class="statValue">-</div>
|
||||
<div class="statHint" id="statFansclubHint">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="statLabel">切换直播间次数</div>
|
||||
<div class="statLabel">��揢�湔偘�湔活�?/div>
|
||||
<div id="statSwitchRoom" class="statValue">-</div>
|
||||
<div class="statHint" id="statSwitchRoomHint">-</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">最近识别到的福袋</div>
|
||||
<div class="sectionTitle">��餈𤏸��怠����鋡?/div>
|
||||
<div class="statsGrid">
|
||||
<div class="stat">
|
||||
<div class="statLabel">内容</div>
|
||||
<div id="statLastContent" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="statLabel">倒计时</div>
|
||||
<div class="statLabel">�坿恣�?/div>
|
||||
<div id="statLastCountdown" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
@@ -408,17 +406,17 @@
|
||||
<div id="statLastPeople" class="statValue">-</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="statLabel">奖品价值(元)</div>
|
||||
<div class="statLabel">憟硋�隞瑕�?�?</div>
|
||||
<div id="statLastValue" class="statValue">-</div>
|
||||
<div class="statHint" id="statLastUpdated">-</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">趋势(最近2小时,5分钟粒度)</div>
|
||||
<div class="sectionTitle">頞见飵嚗��餈?撠𤩺𧒄嚗?���蝎鍦漲嚗?/div>
|
||||
<div class="chartBlock">
|
||||
<div class="chartTitle">福袋关键动作趋势</div>
|
||||
<div id="chartTimeline" class="chart"></div>
|
||||
<div class="hint">展示:打开详情 / 参与成功 / 参与失败 / 中奖 / 未中奖 / 跳过 / 切换直播间</div>
|
||||
<div class="hint">撅閧內嚗𡁏�撘�霂行� / ����𣂼� / ���憭梯揖 / 銝剖� / �芯葉憟?/ 頝唾� / ��揢�湔偘�?/div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">分布</div>
|
||||
@@ -428,11 +426,11 @@
|
||||
<div id="chartSkipReason" class="chart"></div>
|
||||
</div>
|
||||
<div class="chartBlock">
|
||||
<div class="chartTitle">切换直播间原因</div>
|
||||
<div class="chartTitle">��揢�湔偘�游��?/div>
|
||||
<div id="chartSwitchReason" class="chart"></div>
|
||||
</div>
|
||||
<div class="chartBlock">
|
||||
<div class="chartTitle">奖品价值区间(元)</div>
|
||||
<div class="chartTitle">憟硋�隞瑕�澆躹�?�?</div>
|
||||
<div id="chartValueBuckets" class="chart"></div>
|
||||
</div>
|
||||
<div class="chartBlock">
|
||||
@@ -440,7 +438,7 @@
|
||||
<div id="chartParticipantsBuckets" class="chart"></div>
|
||||
</div>
|
||||
<div class="chartBlock">
|
||||
<div class="chartTitle">倒计时区间(秒)</div>
|
||||
<div class="chartTitle">�坿恣�嗅躹�?蝘?</div>
|
||||
<div id="chartCountdownBuckets" class="chart"></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -452,8 +450,7 @@
|
||||
<div class="panel" data-panel="yanghao" role="tabpanel" hidden>
|
||||
<div class="sectionTitle">
|
||||
<span class="sectionIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.8 4.6c-1.4-1.4-3.7-1.4-5.1 0L12 8.3 8.3 4.6c-1.4-1.4-3.7-1.4-5.1 0s-1.4 3.7 0 5.1L12 18.5l8.8-8.8c1.4-1.4 1.4-3.7 0-5.1z"/></svg></span>
|
||||
推荐页养号(爱心/收藏/评论)
|
||||
</div>
|
||||
�刻�憿萄��瘀��勗�/�嗉�/霂�捏嚗? </div>
|
||||
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
@@ -464,7 +461,7 @@
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">养号动作开关(爱心/收藏/评论)</label>
|
||||
<label class="label">�餃噡�其�撘��喉��勗�/�嗉�/霂�捏嚗?/label>
|
||||
<label class="check">
|
||||
<input id="yanghao_enable_actions" type="checkbox" data-key="yanghao_enable_actions" data-type="bool" checked />
|
||||
<span>启用</span>
|
||||
@@ -472,7 +469,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">逐步截图(调试用)</label>
|
||||
<label class="label">�鞉郊�芸㦛嚗��霂閧鍂嚗?/label>
|
||||
<label class="check">
|
||||
<input id="yanghao_step_screenshot" type="checkbox" data-key="yanghao_step_screenshot" data-type="bool" />
|
||||
<span>启用</span>
|
||||
@@ -480,13 +477,13 @@
|
||||
</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">养号时长(秒)</label>
|
||||
<label class="label">�餃噡�園鵭(蝘?</label>
|
||||
<input id="yanghao_recommend_duration_seconds" class="input" data-key="yanghao_recommend_duration_seconds" data-type="int" type="number" min="1" max="3600" step="5" value="60" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">养号间隔(秒)</label>
|
||||
<label class="label">�餃噡�湧�(蝘?</label>
|
||||
<input id="yanghao_recommend_interval_seconds" class="input" data-key="yanghao_recommend_interval_seconds" data-type="int" type="number" min="0" max="3600" step="10" value="0" />
|
||||
<div class="hint">0 表示每次触发都执行</div>
|
||||
<div class="hint">0 銵函內瘥𤩺活閫血��賣�銵?/div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row grid3">
|
||||
@@ -510,7 +507,7 @@
|
||||
<input id="yanghao_icon_roi_size" class="input" data-key="yanghao_icon_roi_size" data-type="int" type="number" min="80" max="600" step="10" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">匹配阈值</label>
|
||||
<label class="label">�寥����?/label>
|
||||
<input id="yanghao_icon_match_threshold" class="input" data-key="yanghao_icon_match_threshold" data-type="float" type="number" min="0" max="1" step="0.01" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -569,7 +566,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">评论输入框坐标(x,y)</label>
|
||||
<label class="label">霂�捏颲枏�獢���?x,y)</label>
|
||||
<div class="inline2">
|
||||
<input id="yanghao_comment_input_x" class="input" data-key="yanghao_comment_input_x" data-type="int" type="number" />
|
||||
<input id="yanghao_comment_input_y" class="input" data-key="yanghao_comment_input_y" data-type="int" type="number" />
|
||||
@@ -578,7 +575,7 @@
|
||||
</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">评论发送坐标(x,y)</label>
|
||||
<label class="label">霂�捏�煾����?x,y)</label>
|
||||
<div class="inline2">
|
||||
<input id="yanghao_comment_send_x" class="input" data-key="yanghao_comment_send_x" data-type="int" type="number" />
|
||||
<input id="yanghao_comment_send_y" class="input" data-key="yanghao_comment_send_y" data-type="int" type="number" />
|
||||
@@ -595,14 +592,14 @@
|
||||
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">停留后滑动方向</label>
|
||||
<label class="label">�𦦵��擧��冽䲮�?/label>
|
||||
<select id="yanghao_after_dwell_swipe_direction" class="input" data-key="yanghao_after_dwell_swipe_direction" data-type="str">
|
||||
<option value="up">up</option>
|
||||
<option value="down">down</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">停留后滑动距离(px)</label>
|
||||
<label class="label">�𦦵��擧��刻�蝳?px)</label>
|
||||
<input id="yanghao_after_dwell_swipe_distance_px" class="input" data-key="yanghao_after_dwell_swipe_distance_px" data-type="int" type="number" min="100" max="2000" step="10" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -633,7 +630,7 @@
|
||||
<textarea id="contains_want" class="input textarea" data-key="contains_want" data-type="list_lines" rows="5"></textarea>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">不想要 contains_not_want</label>
|
||||
<label class="label">銝齿�閬?contains_not_want</label>
|
||||
<textarea id="contains_not_want" class="input textarea" data-key="contains_not_want" data-type="list_lines" rows="5"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
@@ -661,7 +658,7 @@
|
||||
<input id="debug_captures_auto_cleanup" type="checkbox" data-key="debug_captures.auto_cleanup" data-type="bool" checked />
|
||||
<span>启用</span>
|
||||
</label>
|
||||
<div class="hint">每天第一次保存调试图像时自动清理旧目录</div>
|
||||
<div class="hint">瘥誩予蝚砌�甈∩�摮䁅�霂訫㦛�𤩺𧒄�芸𢆡皜���抒𤌍敶?/div>
|
||||
</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
@@ -670,9 +667,9 @@
|
||||
<div class="hint">超过此天数的调试图像目录将被自动删除</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">最大文件数量</label>
|
||||
<label class="label">��憭扳�隞嗆㺭�?/label>
|
||||
<input id="debug_captures_max_files" class="input" data-key="debug_captures.max_files" data-type="int" type="number" min="100" max="10000" step="100" value="2000" />
|
||||
<div class="hint">超过此数量的调试图像将被自动清理(优先删除最旧的)</div>
|
||||
<div class="hint">頞��甇斗㺭�讐�靚���曉�撠�◤�芸𢆡皜��嚗������斗��抒�嚗?/div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -683,7 +680,7 @@
|
||||
<input id="enable_ocr_mode1" type="checkbox" data-key="enable_ocr_mode1" data-type="bool" />
|
||||
<span>启用</span>
|
||||
</label>
|
||||
<div class="hint">当模式0识别失败时,自动尝试模式1</div>
|
||||
<div class="hint">敶𤘪芋撘?霂��憭梯揖�塚��芸𢆡撠肽�璅∪�1</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">模板匹配</div>
|
||||
@@ -696,31 +693,31 @@
|
||||
<div class="hint">使用模板匹配辅助查找福袋图标</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">模板匹配阈值</label>
|
||||
<label class="label">璅⊥踎�寥����?/label>
|
||||
<input id="fudai_template_match_threshold" class="input" data-key="fudai_template_match_threshold" data-type="float" type="number" min="0" max="1" step="0.01" value="0.7" />
|
||||
<div class="hint">匹配分数阈值,范围 0-1,默认 0.7</div>
|
||||
<div class="hint">�寥���㺭���潘���凒 0-1嚗屸�霈?0.7</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">像素检测</div>
|
||||
<div class="sectionTitle">�讐�璉�瘚?/div>
|
||||
<div class="row">
|
||||
<label class="label">抽奖结果红色比例阈值</label>
|
||||
<label class="label">�賢�蝏𤘪�蝥Z𠧧瘥𥪯����?/label>
|
||||
<input id="lucky_draw_red_ratio_threshold" class="input" data-key="lucky_draw_red_ratio_threshold" data-type="float" type="number" min="0" max="1" step="0.01" value="0.8" />
|
||||
<div class="hint">用于检测抽奖结果弹窗,范围 0-1,默认 0.8</div>
|
||||
<div class="hint">�其�璉�瘚𧢲𡂝憟𣇉��𨅯撕蝒梹���凒 0-1嚗屸�霈?0.8</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">直播间匹配阈值</label>
|
||||
<label class="label">�湔偘�游龪�漤��?/label>
|
||||
<input id="live_room_match_threshold" class="input" data-key="live_room_match_threshold" data-type="float" type="number" min="0" max="1" step="0.01" value="0.7" />
|
||||
<div class="hint">用于判断是否在直播间,范围 0-1,默认 0.7</div>
|
||||
<div class="hint">�其��斗鱏�臬炏�函凒�剝𡢿嚗諹��?0-1嚗屸�霈?0.7</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">阶段诊断</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">最大诊断时间(秒)</label>
|
||||
<label class="label">��憭扯��剜𧒄�?蝘?</label>
|
||||
<input id="stage_diag_max_time" class="input" data-key="stage_diag_max_time" data-type="float" type="number" min="1" max="60" step="1" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">单步最大时间(秒)</label>
|
||||
<label class="label">�閙郊��憭扳𧒄�?蝘?</label>
|
||||
<input id="stage_diag_max_step_time" class="input" data-key="stage_diag_max_step_time" data-type="float" type="number" min="0.5" max="10" step="0.5" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -740,7 +737,7 @@
|
||||
<div class="preview">
|
||||
<img id="liveShot" alt="实时截图预览" src="/pic/screenshot.png" />
|
||||
</div>
|
||||
<div class="hint" id="liveShotStatus">等待截图…</div>
|
||||
<div class="hint" id="liveShotStatus">蝑匧��芸㦛�?/div>
|
||||
</section>
|
||||
|
||||
<section class="card cardReservations">
|
||||
@@ -782,4 +779,4 @@
|
||||
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
@@ -0,0 +1,550 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
x图标模板匹配阈值优化测试脚本
|
||||
测试不同阈值参数对模板匹配结果的影响
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import cv2
|
||||
import numpy as np
|
||||
from pathlib import Path
|
||||
import glob
|
||||
from collections import defaultdict
|
||||
|
||||
# 设置UTF-8编码
|
||||
if sys.platform == 'win32':
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
|
||||
# 测试图片路径(自动扫描debug_captures文件夹)
|
||||
DEBUG_CAPTURES_DIR = r"pic/debug_captures"
|
||||
TEMPLATE_PATH = r"assets/x.png"
|
||||
|
||||
# ROI坐标(基于1080x2400分辨率)
|
||||
ROI_X1, ROI_Y1 = 972, 147
|
||||
ROI_X2, ROI_Y2 = 1047, 216
|
||||
|
||||
def load_image(image_path):
|
||||
"""加载图片(支持中文路径)"""
|
||||
if not os.path.exists(image_path):
|
||||
raise FileNotFoundError(f"图片不存在: {image_path}")
|
||||
|
||||
# 使用numpy读取,支持中文路径
|
||||
img_array = np.fromfile(image_path, dtype=np.uint8)
|
||||
img = cv2.imdecode(img_array, cv2.IMREAD_GRAYSCALE)
|
||||
if img is None:
|
||||
raise ValueError(f"无法读取图片: {image_path}")
|
||||
return img
|
||||
|
||||
def crop_roi(img, x1, y1, x2, y2):
|
||||
"""裁剪ROI区域"""
|
||||
h, w = img.shape[:2]
|
||||
# 如果图片尺寸不是1080x2400,需要缩放坐标
|
||||
if w != 1080 or h != 2400:
|
||||
scale_x = w / 1080.0
|
||||
scale_y = h / 2400.0
|
||||
x1 = int(x1 * scale_x)
|
||||
y1 = int(y1 * scale_y)
|
||||
x2 = int(x2 * scale_x)
|
||||
y2 = int(y2 * scale_y)
|
||||
|
||||
roi = img[y1:y2, x1:x2]
|
||||
return roi
|
||||
|
||||
def test_fixed_threshold_binary(roi_img, template, threshold_values):
|
||||
"""测试固定阈值二值化的不同阈值"""
|
||||
results = []
|
||||
for thresh in threshold_values:
|
||||
try:
|
||||
_, roi_bin = cv2.threshold(roi_img, thresh, 255, cv2.THRESH_BINARY)
|
||||
_, tpl_bin = cv2.threshold(template, thresh, 255, cv2.THRESH_BINARY)
|
||||
|
||||
# 确保模板尺寸匹配
|
||||
th, tw = tpl_bin.shape[:2]
|
||||
rh, rw = roi_bin.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("固定阈值二值化", thresh, float(max_val or 0.0)))
|
||||
except Exception as e:
|
||||
results.append(("固定阈值二值化", thresh, 0.0))
|
||||
return results
|
||||
|
||||
def test_adaptive_threshold(roi_img, template, block_sizes, c_values):
|
||||
"""测试自适应二值化的不同参数"""
|
||||
results = []
|
||||
for block_size in block_sizes:
|
||||
for c in c_values:
|
||||
try:
|
||||
roi_bin = cv2.adaptiveThreshold(
|
||||
roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY, block_size, c
|
||||
)
|
||||
tpl_bin = cv2.adaptiveThreshold(
|
||||
template, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY, block_size, c
|
||||
)
|
||||
|
||||
# 确保模板尺寸匹配
|
||||
th, tw = tpl_bin.shape[:2]
|
||||
rh, rw = roi_bin.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("自适应二值化", f"blockSize={block_size}, C={c}", float(max_val or 0.0)))
|
||||
except Exception as e:
|
||||
results.append(("自适应二值化", f"blockSize={block_size}, C={c}", 0.0))
|
||||
return results
|
||||
|
||||
def test_canny_edges(roi_img, template, low_thresholds, high_thresholds):
|
||||
"""测试Canny边缘检测的不同阈值组合"""
|
||||
results = []
|
||||
for low in low_thresholds:
|
||||
for high in high_thresholds:
|
||||
if high <= low:
|
||||
continue
|
||||
try:
|
||||
roi_edges = cv2.Canny(roi_img, low, high)
|
||||
tpl_edges = cv2.Canny(template, low, high)
|
||||
|
||||
# 确保模板尺寸匹配
|
||||
th, tw = tpl_edges.shape[:2]
|
||||
rh, rw = roi_edges.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_edges = cv2.resize(tpl_edges, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_edges, tpl_edges, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("Canny边缘检测", f"low={low}, high={high}", float(max_val or 0.0)))
|
||||
except Exception as e:
|
||||
results.append(("Canny边缘检测", f"low={low}, high={high}", 0.0))
|
||||
return results
|
||||
|
||||
def test_template_methods(roi_img, template, method_name="固定阈值二值化", thresh=180):
|
||||
"""测试不同的模板匹配方法"""
|
||||
# 预处理
|
||||
_, roi_bin = cv2.threshold(roi_img, thresh, 255, cv2.THRESH_BINARY)
|
||||
_, tpl_bin = cv2.threshold(template, thresh, 255, cv2.THRESH_BINARY)
|
||||
|
||||
# 确保模板尺寸匹配
|
||||
th, tw = tpl_bin.shape[:2]
|
||||
rh, rw = roi_bin.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
methods = [
|
||||
("TM_CCOEFF_NORMED", cv2.TM_CCOEFF_NORMED),
|
||||
("TM_CCORR_NORMED", cv2.TM_CCORR_NORMED),
|
||||
("TM_SQDIFF_NORMED", cv2.TM_SQDIFF_NORMED),
|
||||
]
|
||||
|
||||
results = []
|
||||
for name, method in methods:
|
||||
try:
|
||||
res = cv2.matchTemplate(roi_bin, tpl_bin, method)
|
||||
if method == cv2.TM_SQDIFF_NORMED:
|
||||
_min_val, _max_val, min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
score = 1.0 - float(_min_val or 0.0) # SQDIFF越小越好,转换为越大越好
|
||||
else:
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
score = float(max_val or 0.0)
|
||||
results.append((name, score))
|
||||
except Exception as e:
|
||||
results.append((name, 0.0))
|
||||
return results
|
||||
|
||||
def test_advanced_preprocessing(roi_img, template):
|
||||
"""测试高级预处理方法"""
|
||||
results = []
|
||||
|
||||
# 1. 反转图像 + 二值化
|
||||
try:
|
||||
roi_inv = 255 - roi_img
|
||||
tpl_inv = 255 - template
|
||||
_, roi_bin_inv = cv2.threshold(roi_inv, 180, 255, cv2.THRESH_BINARY)
|
||||
_, tpl_bin_inv = cv2.threshold(tpl_inv, 180, 255, cv2.THRESH_BINARY)
|
||||
|
||||
th, tw = tpl_bin_inv.shape[:2]
|
||||
rh, rw = roi_bin_inv.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_bin_inv = cv2.resize(tpl_bin_inv, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_bin_inv, tpl_bin_inv, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("反转+二值化", "thresh=180", float(max_val or 0.0)))
|
||||
except Exception:
|
||||
results.append(("反转+二值化", "thresh=180", 0.0))
|
||||
|
||||
# 2. 直方图均衡化
|
||||
try:
|
||||
roi_eq = cv2.equalizeHist(roi_img)
|
||||
tpl_eq = cv2.equalizeHist(template)
|
||||
|
||||
th, tw = tpl_eq.shape[:2]
|
||||
rh, rw = roi_eq.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_eq = cv2.resize(tpl_eq, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_eq, tpl_eq, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("直方图均衡化", "", float(max_val or 0.0)))
|
||||
except Exception:
|
||||
results.append(("直方图均衡化", "", 0.0))
|
||||
|
||||
# 3. 对比度增强(CLAHE)
|
||||
try:
|
||||
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
||||
roi_clahe = clahe.apply(roi_img)
|
||||
tpl_clahe = clahe.apply(template)
|
||||
|
||||
th, tw = tpl_clahe.shape[:2]
|
||||
rh, rw = roi_clahe.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_clahe = cv2.resize(tpl_clahe, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_clahe, tpl_clahe, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("CLAHE对比度增强", "clipLimit=2.0", float(max_val or 0.0)))
|
||||
except Exception:
|
||||
results.append(("CLAHE对比度增强", "clipLimit=2.0", 0.0))
|
||||
|
||||
# 4. 高斯模糊 + 边缘检测
|
||||
try:
|
||||
roi_blur = cv2.GaussianBlur(roi_img, (3, 3), 0)
|
||||
tpl_blur = cv2.GaussianBlur(template, (3, 3), 0)
|
||||
roi_edges = cv2.Canny(roi_blur, 50, 150)
|
||||
tpl_edges = cv2.Canny(tpl_blur, 50, 150)
|
||||
|
||||
th, tw = tpl_edges.shape[:2]
|
||||
rh, rw = roi_edges.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_edges = cv2.resize(tpl_edges, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_edges, tpl_edges, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("高斯模糊+边缘检测", "blur(3,3), canny(50,150)", float(max_val or 0.0)))
|
||||
except Exception:
|
||||
results.append(("高斯模糊+边缘检测", "blur(3,3), canny(50,150)", 0.0))
|
||||
|
||||
# 5. 形态学操作(开运算)
|
||||
try:
|
||||
_, roi_bin = cv2.threshold(roi_img, 180, 255, cv2.THRESH_BINARY)
|
||||
_, tpl_bin = cv2.threshold(template, 180, 255, cv2.THRESH_BINARY)
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
|
||||
roi_morph = cv2.morphologyEx(roi_bin, cv2.MORPH_OPEN, kernel)
|
||||
tpl_morph = cv2.morphologyEx(tpl_bin, cv2.MORPH_OPEN, kernel)
|
||||
|
||||
th, tw = tpl_morph.shape[:2]
|
||||
rh, rw = roi_morph.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_morph = cv2.resize(tpl_morph, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_morph, tpl_morph, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("形态学开运算", "kernel(3,3)", float(max_val or 0.0)))
|
||||
except Exception:
|
||||
results.append(("形态学开运算", "kernel(3,3)", 0.0))
|
||||
|
||||
# 6. 形态学操作(闭运算)
|
||||
try:
|
||||
_, roi_bin = cv2.threshold(roi_img, 180, 255, cv2.THRESH_BINARY)
|
||||
_, tpl_bin = cv2.threshold(template, 180, 255, cv2.THRESH_BINARY)
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
|
||||
roi_morph = cv2.morphologyEx(roi_bin, cv2.MORPH_CLOSE, kernel)
|
||||
tpl_morph = cv2.morphologyEx(tpl_bin, cv2.MORPH_CLOSE, kernel)
|
||||
|
||||
th, tw = tpl_morph.shape[:2]
|
||||
rh, rw = roi_morph.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
tpl_morph = cv2.resize(tpl_morph, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_morph, tpl_morph, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("形态学闭运算", "kernel(3,3)", float(max_val or 0.0)))
|
||||
except Exception:
|
||||
results.append(("形态学闭运算", "kernel(3,3)", 0.0))
|
||||
|
||||
# 7. 原始图像(作为基准)
|
||||
try:
|
||||
th, tw = template.shape[:2]
|
||||
rh, rw = roi_img.shape[:2]
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
template_scaled = cv2.resize(template, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
else:
|
||||
template_scaled = template
|
||||
|
||||
res = cv2.matchTemplate(roi_img, template_scaled, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results.append(("原始图像", "", float(max_val or 0.0)))
|
||||
except Exception:
|
||||
results.append(("原始图像", "", 0.0))
|
||||
|
||||
return results
|
||||
|
||||
def find_test_images():
|
||||
"""查找所有直播间图标测试图片"""
|
||||
pattern = os.path.join(DEBUG_CAPTURES_DIR, "**", "*直播间图标*.png")
|
||||
images = glob.glob(pattern, recursive=True)
|
||||
return images
|
||||
|
||||
def test_single_image(image_path, template):
|
||||
"""测试单张图片的所有方法,返回结果字典"""
|
||||
results = {}
|
||||
|
||||
try:
|
||||
# 加载图片
|
||||
test_img = load_image(image_path)
|
||||
|
||||
# 裁剪ROI
|
||||
roi_img = crop_roi(test_img, ROI_X1, ROI_Y1, ROI_X2, ROI_Y2)
|
||||
|
||||
# 确保模板尺寸匹配
|
||||
th, tw = template.shape[:2]
|
||||
rh, rw = roi_img.shape[:2]
|
||||
template_scaled = template.copy()
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
template_scaled = cv2.resize(template_scaled, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
|
||||
# 1. 测试固定阈值二值化
|
||||
threshold_values = list(range(100, 250, 10))
|
||||
for thresh in threshold_values:
|
||||
try:
|
||||
_, roi_bin = cv2.threshold(roi_img, thresh, 255, cv2.THRESH_BINARY)
|
||||
_, tpl_bin = cv2.threshold(template_scaled, thresh, 255, cv2.THRESH_BINARY)
|
||||
|
||||
th_t, tw_t = tpl_bin.shape[:2]
|
||||
rh_t, rw_t = roi_bin.shape[:2]
|
||||
if th_t > rh_t or tw_t > rw_t:
|
||||
scale = min(rh_t / max(th_t, 1), rw_t / max(tw_t, 1))
|
||||
tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw_t * scale)), max(1, int(th_t * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
key = f"固定阈值二值化_{thresh}"
|
||||
results[key] = float(max_val or 0.0)
|
||||
except:
|
||||
results[f"固定阈值二值化_{thresh}"] = 0.0
|
||||
|
||||
# 2. 测试自适应二值化
|
||||
block_sizes = [3, 5, 7, 9, 11, 15]
|
||||
c_values = [0, 1, 2, 3, 5]
|
||||
for block_size in block_sizes:
|
||||
for c in c_values:
|
||||
try:
|
||||
roi_bin = cv2.adaptiveThreshold(
|
||||
roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY, block_size, c
|
||||
)
|
||||
tpl_bin = cv2.adaptiveThreshold(
|
||||
template_scaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY, block_size, c
|
||||
)
|
||||
|
||||
th_t, tw_t = tpl_bin.shape[:2]
|
||||
rh_t, rw_t = roi_bin.shape[:2]
|
||||
if th_t > rh_t or tw_t > rw_t:
|
||||
scale = min(rh_t / max(th_t, 1), rw_t / max(tw_t, 1))
|
||||
tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw_t * scale)), max(1, int(th_t * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
key = f"自适应二值化_bs{block_size}_c{c}"
|
||||
results[key] = float(max_val or 0.0)
|
||||
except:
|
||||
results[f"自适应二值化_bs{block_size}_c{c}"] = 0.0
|
||||
|
||||
# 3. 测试Canny边缘检测
|
||||
low_thresholds = [20, 30, 40, 50, 60]
|
||||
high_thresholds = [60, 80, 100, 120, 150, 180]
|
||||
for low in low_thresholds:
|
||||
for high in high_thresholds:
|
||||
if high <= low:
|
||||
continue
|
||||
try:
|
||||
roi_edges = cv2.Canny(roi_img, low, high)
|
||||
tpl_edges = cv2.Canny(template_scaled, low, high)
|
||||
|
||||
th_t, tw_t = tpl_edges.shape[:2]
|
||||
rh_t, rw_t = roi_edges.shape[:2]
|
||||
if th_t > rh_t or tw_t > rw_t:
|
||||
scale = min(rh_t / max(th_t, 1), rw_t / max(tw_t, 1))
|
||||
tpl_edges = cv2.resize(tpl_edges, (max(1, int(tw_t * scale)), max(1, int(th_t * scale))))
|
||||
|
||||
res = cv2.matchTemplate(roi_edges, tpl_edges, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
key = f"Canny边缘检测_low{low}_high{high}"
|
||||
results[key] = float(max_val or 0.0)
|
||||
except:
|
||||
results[f"Canny边缘检测_low{low}_high{high}"] = 0.0
|
||||
|
||||
# 4. 测试高级预处理方法
|
||||
advanced_results = test_advanced_preprocessing(roi_img, template_scaled)
|
||||
for method, params, score in advanced_results:
|
||||
key = f"{method}_{params}" if params else method
|
||||
results[key] = score
|
||||
|
||||
# 5. 测试原始图像
|
||||
try:
|
||||
res = cv2.matchTemplate(roi_img, template_scaled, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
|
||||
results["原始图像"] = float(max_val or 0.0)
|
||||
except:
|
||||
results["原始图像"] = 0.0
|
||||
|
||||
except Exception as e:
|
||||
print(f" 处理图片失败: {os.path.basename(image_path)} - {e}")
|
||||
return {}
|
||||
|
||||
return results
|
||||
|
||||
def main():
|
||||
print("=" * 80)
|
||||
print("x图标模板匹配阈值优化测试(多图片批量测试)")
|
||||
print("=" * 80)
|
||||
print()
|
||||
|
||||
# 查找所有测试图片
|
||||
print(f"扫描测试图片目录: {DEBUG_CAPTURES_DIR}")
|
||||
test_images = find_test_images()
|
||||
print(f"找到 {len(test_images)} 张直播间图标图片")
|
||||
|
||||
if len(test_images) == 0:
|
||||
print("未找到测试图片!")
|
||||
return
|
||||
|
||||
# 加载模板
|
||||
print(f"\n加载模板: {TEMPLATE_PATH}")
|
||||
try:
|
||||
template = load_image(TEMPLATE_PATH)
|
||||
print(f" 模板尺寸: {template.shape[1]}x{template.shape[0]}")
|
||||
except Exception as e:
|
||||
print(f" 错误: {e}")
|
||||
return
|
||||
|
||||
print("\n" + "=" * 80)
|
||||
print("开始批量测试...")
|
||||
print("=" * 80)
|
||||
|
||||
# 统计所有方法在所有图片上的分数
|
||||
method_scores = defaultdict(list) # {method_name: [score1, score2, ...]}
|
||||
|
||||
# 测试每张图片
|
||||
for i, image_path in enumerate(test_images, 1):
|
||||
print(f"\n[{i}/{len(test_images)}] 测试: {os.path.basename(image_path)}")
|
||||
results = test_single_image(image_path, template)
|
||||
|
||||
# 收集分数
|
||||
for method, score in results.items():
|
||||
method_scores[method].append(score)
|
||||
|
||||
# 计算平均分数
|
||||
print("\n" + "=" * 80)
|
||||
print("【统计结果】所有方法的平均分数")
|
||||
print("=" * 80)
|
||||
|
||||
avg_scores = []
|
||||
for method, scores in method_scores.items():
|
||||
avg_score = sum(scores) / len(scores) if scores else 0.0
|
||||
max_score = max(scores) if scores else 0.0
|
||||
min_score = min(scores) if scores else 0.0
|
||||
avg_scores.append((method, avg_score, max_score, min_score, len(scores)))
|
||||
|
||||
# 按平均分数排序
|
||||
avg_scores.sort(key=lambda x: x[1], reverse=True)
|
||||
|
||||
print(f"{'排名':<6} {'方法':<35} {'平均分':<10} {'最高分':<10} {'最低分':<10} {'图片数':<8} {'状态':<10}")
|
||||
print("-" * 100)
|
||||
|
||||
for i, (method, avg_score, max_score, min_score, count) in enumerate(avg_scores[:30], 1): # 显示前30名
|
||||
status = "✓ 通过" if avg_score >= 0.72 else "✗ 未通过"
|
||||
print(f"{i:<6} {method:<35} {avg_score:<10.4f} {max_score:<10.4f} {min_score:<10.4f} {count:<8} {status:<10}")
|
||||
|
||||
# 推荐配置
|
||||
print("\n" + "=" * 80)
|
||||
print("【推荐配置】")
|
||||
print("=" * 80)
|
||||
if avg_scores:
|
||||
best_method, best_avg, best_max, best_min, best_count = avg_scores[0]
|
||||
print(f"最佳方法: {best_method}")
|
||||
print(f"平均分数: {best_avg:.4f}")
|
||||
print(f"最高分数: {best_max:.4f}")
|
||||
print(f"最低分数: {best_min:.4f}")
|
||||
print(f"测试图片数: {best_count}")
|
||||
print(f"是否通过阈值(0.72): {'是' if best_avg >= 0.72 else '否'}")
|
||||
|
||||
# 解析最佳方法参数
|
||||
if "固定阈值二值化" in best_method:
|
||||
thresh = best_method.split("_")[-1]
|
||||
print(f"\n推荐配置:")
|
||||
print(f" 方法: 固定阈值二值化")
|
||||
print(f" 阈值: {thresh}")
|
||||
print(f" 模板匹配方法: TM_CCOEFF_NORMED")
|
||||
elif "自适应二值化" in best_method:
|
||||
parts = best_method.split("_")
|
||||
bs = parts[1].replace("bs", "")
|
||||
c = parts[2].replace("c", "")
|
||||
print(f"\n推荐配置:")
|
||||
print(f" 方法: 自适应二值化")
|
||||
print(f" blockSize: {bs}")
|
||||
print(f" C: {c}")
|
||||
print(f" 模板匹配方法: TM_CCOEFF_NORMED")
|
||||
elif "Canny边缘检测" in best_method:
|
||||
parts = best_method.split("_")
|
||||
low = parts[1].replace("low", "")
|
||||
high = parts[2].replace("high", "")
|
||||
print(f"\n推荐配置:")
|
||||
print(f" 方法: Canny边缘检测")
|
||||
print(f" low: {low}")
|
||||
print(f" high: {high}")
|
||||
print(f" 模板匹配方法: TM_CCOEFF_NORMED")
|
||||
else:
|
||||
print(f"\n推荐配置:")
|
||||
print(f" 方法: {best_method}")
|
||||
print(f" 模板匹配方法: TM_CCOEFF_NORMED")
|
||||
|
||||
print("\n测试完成!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
"""
|
||||
x图标模板匹配阈值优化测试脚本
|
||||
测试不同阈值参数对模板匹配结果的影响
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import cv2
|
||||
import numpy as np
|
||||
from pathlib import Path
|
||||
import glob
|
||||
from collections import defaultdict
|
||||
|
||||
# 设置UTF-8编码
|
||||
if sys.platform == 'win32':
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
|
||||
# 测试图片路径(自动扫描debug_captures文件夹)
|
||||
DEBUG_CAPTURES_DIR = r"pic/debug_captures"
|
||||
TEMPLATE_PATH = r"assets/x.png"
|
||||
|
||||
# ROI坐标(基于1080x2400分辨率)
|
||||
ROI_X1, ROI_Y1 = 972, 147
|
||||
ROI_X2, ROI_Y2 = 1047, 216
|
||||
|
||||
Reference in new issue
Block a user