Files
douyin_guaji-main/douyin/utils/douyin_helpers.py
T
Your Name bdf9312bc9 chore: Remove obsolete scripts and enhance path configuration
- Deleted `check_md_files.py` and `fix_cursor_md_issue.py` as they are no longer needed.
- Added new functions in `path_config.py` for better path management, including actions log and run_cli paths.
- Updated various modules to utilize the new path configuration, ensuring consistency and maintainability across the project.
2025-12-28 20:55:34 +08:00

315 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
"""
工具方法模块
============
职责:通用工具方法
- 点击操作封装
- OCR检查开奖结果
- 处理开奖结果
- 截图并诊断
- 读取像素阶段状态
"""
import os
import time
import shutil
from typing import Any, Optional, Tuple, Dict, Union
from datetime import datetime
from douyin.detection.douyin_pixel import read_pixel_stage_state_from_screenshot
from douyin.handlers import douyin_screenshot_handler
class HelperFunctions:
"""工具函数集合:通用工具方法"""
@staticmethod # type: ignore[misc]
def click(analyser: Any, x: int, y: int) -> None:
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。
参数:
analyser: 分析器对象
x: X坐标
y: Y坐标
"""
start_time = time.time()
try:
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]
"操作",
"点击操作",
x=int(x),
y=int(y),
elapsed_seconds=round(elapsed, 2),
)
except Exception:
pass
@staticmethod # type: ignore[misc]
def read_pixel_stage_state(
analyser: Any, return_details: bool = False
) -> Union[Dict[str, Any], Tuple[Dict[str, Any], Dict[str, Any]]]:
"""读取像素阶段状态(用于阶段诊断)。
参数:
analyser: 分析器对象
return_details: 是否返回每个检测步骤的详细信息(包括分数)
返回:
dict: 检测结果(return_details=False时)
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
"""
# 使用统一的截图路径配置
try:
import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
pic_path = path_config.get_screenshot_path()
# 获取分辨率比例和y偏移参数
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)
lucky_threshold = float(
getattr(analyser, "lucky_draw_red_ratio_threshold", 0.9) or 0.9
)
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
fudai_template_threshold = float(
getattr(analyser, "fudai_detail_template_threshold", None)
or getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
if fudai_template_threshold < 0.0:
fudai_template_threshold = 0.0
if fudai_template_threshold > 1.0:
fudai_template_threshold = 1.0
return read_pixel_stage_state_from_screenshot(
pic_path,
resolution_ratio_x,
resolution_ratio_y,
y_pianyi,
lucky_threshold,
fudai_template_threshold,
return_details=return_details,
analyser=analyser,
)
@staticmethod # type: ignore[misc]
def check_lottery_result_by_ocr(analyser: Any) -> Optional[str]:
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。
参数:
analyser: 分析器对象
返回:
"我知道了" - 识别到"我知道了"按钮
"立即领取奖品" - 识别到"立即领取奖品"按钮
None - 未识别到相关文本
"""
try:
# OCR区域:(175, 1267) 到 (890, 1377)
# 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures)
douyin_screenshot_handler.ScreenshotHandler.cut_pic(
analyser, 175, 1267, 890, 1377, "", "开奖结果按钮", 0
)
# OCR识别
ocr_text = str(analyser.operation.analyse_pic_word("开奖结果按钮", 0) or "")
analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text) # type: ignore[attr-defined]
# 检查识别到的文本
if "我知道了" in ocr_text:
return "我知道了"
elif (
"立即领取奖品" in ocr_text
or "领取奖品" in ocr_text
or "立即领取" in ocr_text
):
return "立即领取奖品"
else:
# 尝试模式1识别
ocr_text_1 = str(
analyser.operation.analyse_pic_word("开奖结果按钮", 1) or ""
)
if "我知道了" in ocr_text_1:
return "我知道了"
elif (
"立即领取奖品" in ocr_text_1
or "领取奖品" in ocr_text_1
or "立即领取" in ocr_text_1
):
return "立即领取奖品"
return None
except Exception as e:
analyser._log_kv("开奖结果", "OCR识别异常", error=str(e)) # type: ignore[attr-defined]
return None
@staticmethod # type: ignore[misc]
def handle_lottery_result_by_ocr(analyser: Any, result_type: str) -> None:
"""根据OCR识别结果处理开奖结果。
参数:
analyser: 分析器对象
result_type: "我知道了" 或 "立即领取奖品"
"""
start_time = time.time()
try:
if result_type == "我知道了":
# 识别到"我知道了",点击按钮,切换下一个直播间
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
btn_x = int(532 * rx // 1080)
btn_y = int(1322 * ry // 2400)
analyser.operation.click(analyser.device_id, btn_x, btn_y)
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果", "点击我知道了按钮", x=btn_x, y=btn_y
)
analyser.operation.delay(0.5)
# 切换下一个直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果", "处理完开奖结果,切换直播间找新福袋"
)
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
else:
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果",
"处理完开奖结果,未启用切换,继续在当前直播间",
)
elif result_type == "立即领取奖品":
# 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间
try:
# 确保有最新截图
analyser.operation.get_screenshot(analyser.device_id)
# 使用统一的截图路径配置
try:
import path_config
src = path_config.get_screenshot_path()
pic_dir = path_config.get_pic_dir()
except Exception:
# 回退到旧路径(向后兼容)
base_dir = os.path.dirname(__file__)
pic_dir = os.path.join(base_dir, "pic")
src = os.path.join(pic_dir, "screenshot.png")
if os.path.exists(src):
# 创建单独的文件夹保存"立即领取奖品"的截图
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
os.makedirs(prize_dir, exist_ok=True)
# 保存截图,文件名包含时间戳
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
dst = os.path.join(prize_dir, f"prize_{timestamp}.png")
shutil.copy(src, dst)
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果", "已保存立即领取奖品截图", path=dst
)
except Exception as e:
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果", "保存截图失败", error=str(e)
)
# 点击返回键
analyser.operation.click_back(analyser.device_id)
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果", "点击返回键关闭开奖结果"
)
analyser.operation.delay(0.5)
# 切换下一个直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果", "处理完开奖结果,切换直播间找新福袋"
)
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
else:
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果",
"处理完开奖结果,未启用切换,继续在当前直播间",
)
except Exception as e:
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果",
"处理开奖结果失败",
error=str(e),
result_type=result_type,
)
# 失败时尝试按返回键并切换
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.5)
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
except Exception:
pass
finally:
elapsed = time.time() - start_time
analyser._log_kv( # type: ignore[attr-defined]
"流程",
"_handle_lottery_result_by_ocr完成",
elapsed_seconds=round(elapsed, 2),
result_type=result_type,
)
@staticmethod # type: ignore[misc]
def shot_and_diagnose(
analyser: Any, tag: str, msg: str, device_id: str, diagnose: bool = True
) -> None:
"""截图并执行阶段诊断(兼容旧版调用方式)。
参数:
analyser: 分析器对象
tag: 日志标签
msg: 日志消息
device_id: 设备ID
diagnose: 是否执行阶段诊断(默认True)
"""
try:
# 截图
ok = analyser.operation.get_screenshot(device_id)
if not ok:
analyser._log_kv(tag, f"{msg} - 获取截图失败", ok=0) # type: ignore[attr-defined]
return
# 如果启用诊断,执行阶段诊断
if diagnose:
stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined]
analyser._last_diag_stage = stage # type: ignore[attr-defined]
analyser._last_diag_seen = seen # type: ignore[attr-defined]
analyser._last_diag_ts = time.time() # type: ignore[attr-defined]
# 使用位置参数调用,避免与关键字参数冲突
analyser._log_kv(tag, msg, **{"stage": stage, "seen": seen}) # type: ignore[attr-defined]
else:
analyser._log_kv(tag, msg) # type: ignore[attr-defined]
except Exception as e:
# 避免异常影响主流程
try:
analyser._log_kv( # type: ignore[attr-defined]
tag, f"{msg} - 异常: {type(e).__name__}"
)
except Exception:
pass