feat: Add AI project summary and coordinate constants for Douyin Fudai

- Created AI_PROJECT_SUMMARY.md for quick understanding of project structure, data flow, key interfaces, and verification points.
- Added key modules and data flow overview for automated participation in Douyin Fudai lottery.
- Introduced a JSON schema example for configuration and provided quick validation steps.
- Updated coordinate constants in coords.py for various cropping areas related to Fudai details, ensuring centralized management of coordinates.
- Generated a new actions log file for tracking actions performed by the application.
This commit is contained in:
Your Name committed 2026-01-03 00:06:59 +08:00
1 parent 0b5f150691
commit 25ed50cc3c
19 files changed
+1829 -654

No files matched your search

+207 -73
View File
@@ -41,15 +41,11 @@ _EXTERNAL_AXF_SCREENSHOT = os.path.join(
os.environ.get(
"EXTERNAL_DOUYIN_FUDAI_DIR",
os.path.join(
os.path.expanduser("~"),
".cursor",
"worktrees",
"douyin_guaji-main",
"axf"
)
os.path.expanduser("~"), ".cursor", "worktrees", "douyin_guaji-main", "axf"
),
),
"pic",
"screenshot.png"
"screenshot.png",
)
@@ -151,7 +147,9 @@ def _mirror_screenshot_to_external(src_file: str) -> None:
# 检查是否是网络路径(UNC路径或网络驱动器)
if external_base.startswith("\\\\") or external_base.startswith("//"):
is_network_path = True
logging.warning("[截图] 检测到网络路径,镜像可能较慢: %s", external_base)
logging.warning(
"[截图] 检测到网络路径,镜像可能较慢: %s", external_base
)
# 检查是否是远程挂载点(简单启发式:包含常见网络挂载标识)
elif ":" in external_base and len(external_base) > 3:
# 可能是网络驱动器,但无法确定,记录路径供诊断
@@ -167,17 +165,32 @@ def _mirror_screenshot_to_external(src_file: str) -> None:
shutil.copyfile(src_file, tmp)
copy_dur = (time_module.time() - copy_start) * 1000.0
if copy_dur > 50.0 or is_network_path:
logging.info("[截图] 镜像复制耗时(ms)=%.1f src=%s dst=%s (网络路径=%s)", copy_dur, src_file, tmp, is_network_path)
logging.info(
"[截图] 镜像复制耗时(ms)=%.1f src=%s dst=%s (网络路径=%s)",
copy_dur,
src_file,
tmp,
is_network_path,
)
replace_start = time_module.time()
_safe_replace_file(tmp, external_path)
replace_dur = (time_module.time() - replace_start) * 1000.0
if replace_dur > 50.0 or is_network_path:
logging.info("[截图] 镜像文件替换耗时(ms)=%.1f (网络路径=%s)", replace_dur, is_network_path)
logging.info(
"[截图] 镜像文件替换耗时(ms)=%.1f (网络路径=%s)",
replace_dur,
is_network_path,
)
mirror_total_dur = (time_module.time() - mirror_start) * 1000.0
if mirror_total_dur > 100.0 or is_network_path:
logging.info("[截图] 镜像总耗时(ms)=%.1f path=%s (网络路径=%s)", mirror_total_dur, external_path, is_network_path)
logging.info(
"[截图] 镜像总耗时(ms)=%.1f path=%s (网络路径=%s)",
mirror_total_dur,
external_path,
is_network_path,
)
except Exception:
# 任何错误都不应该影响截图主流程
pass
@@ -206,6 +219,7 @@ class underlying_operations:
# 改为直接静默导入和初始化
# 尝试按需导入 easyocr,避免静态检查器在缺少依赖时报错
import importlib
try:
easyocr = importlib.import_module("easyocr")
except Exception:
@@ -244,7 +258,7 @@ class underlying_operations:
except Exception:
pass
try:
devnull = open(os.devnull, "w")
devnull = open(os.devnull, "w", encoding="utf-8")
with contextlib.redirect_stdout(
devnull
), contextlib.redirect_stderr(devnull):
@@ -262,9 +276,9 @@ class underlying_operations:
use_textline_orientation=False,
)
self.ocr_type = "paddleocr"
print(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)")
print("[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)")
print(
f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr"
"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr"
)
except Exception:
# 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。
@@ -304,7 +318,6 @@ class underlying_operations:
adb = adb[1:-1]
return adb
def _ensure_ocr(self):
if self.ocr is not None:
return
@@ -315,6 +328,7 @@ class underlying_operations:
try:
# 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题
import importlib
try:
easyocr = importlib.import_module("easyocr")
except Exception:
@@ -334,7 +348,7 @@ class underlying_operations:
)
self.ocr_type = "easyocr"
gpu_status = "GPU加速" if False else "CPU模式"
gpu_status = "CPU模式"
print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})")
else:
raise ImportError("easyocr not available")
@@ -343,7 +357,7 @@ class underlying_operations:
print(f"[OCR] 延迟初始化EasyOCR失败: {e},回退到PaddleOCR")
devnull = None
try:
devnull = open(os.devnull, "w")
devnull = open(os.devnull, "w", encoding="utf-8")
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
devnull
):
@@ -361,7 +375,7 @@ class underlying_operations:
use_textline_orientation=False,
)
self.ocr_type = "paddleocr"
print(f"[OCR] 延迟初始化:使用 PaddleOCR(CPU模式)")
print("[OCR] 延迟初始化:使用 PaddleOCR(CPU模式)")
except Exception:
self.ocr = None
self.ocr_type = None
@@ -425,9 +439,11 @@ class underlying_operations:
"""
try:
import path_config
pic_base = path_config.get_pic_dir()
except Exception:
import path_config
pic_base = path_config.get_pic_dir()
# 运行时必需文件始终在根目录(不需要移动)
@@ -439,7 +455,10 @@ class underlying_operations:
# OCR图片文件:按分类组织到子目录
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
category = douyin_screenshot_manager.get_category_for_picname(picname)
except Exception:
category = "others"
@@ -481,47 +500,69 @@ class underlying_operations:
if use_service:
try:
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
# 诊断:检查服务是否在运行
service_running = getattr(service, "_running", False)
if not service_running:
logging.debug("[截图] 后台服务未运行,尝试启动 device=%s", device_id)
logging.debug(
"[截图] 后台服务未运行,尝试启动 device=%s", device_id
)
try:
service.start(device_id, interval=1.5)
# 等待一小段时间让服务完成第一次截图
time_module.sleep(0.2)
except Exception as start_err:
logging.warning("[截图] 启动后台服务失败: %s,将使用直接截图", start_err)
logging.warning(
"[截图] 启动后台服务失败: %s,将使用直接截图", start_err
)
try:
service_result = service.get_screenshot(device_id, force=False)
if service_result:
dur = (time.time() - start_ts) * 1000.0
logging.info("[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id)
logging.info(
"[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id
)
return True
else:
from datetime import datetime
timetag = datetime.now().strftime("%H:%M:%S")
logging.info("[%s] [截图操作] 后台服务未提供有效截图,回退到直接截图", timetag)
logging.info(
"[%s] [截图操作] 后台服务未提供有效截图,回退到直接截图",
timetag,
)
# 不 return,这里继续走直接截图逻辑
except Exception as e:
from datetime import datetime
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning("[%s] [截图操作] 调用后台服务异常,回退到直接截图: %s", timetag, e)
logging.warning(
"[%s] [截图操作] 调用后台服务异常,回退到直接截图: %s",
timetag,
e,
)
except ImportError as e:
from datetime import datetime
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning("[%s] [截图操作] 无法导入截图服务模块,回退到直接截图: %s", timetag, e)
logging.warning(
"[%s] [截图操作] 无法导入截图服务模块,回退到直接截图: %s",
timetag,
e,
)
except Exception as e:
from datetime import datetime
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning("[%s] [截图操作] 服务模式不可用,回退到直接截图: %s", timetag, e)
logging.warning(
"[%s] [截图操作] 服务模式不可用,回退到直接截图: %s", timetag, e
)
# 原有的直接截图逻辑(保持向后兼容),测量其耗时
result = self._get_screenshot_direct(device_id, path)
dur = (time.time() - start_ts) * 1000.0
logging.info("[截图] 总耗时(ms)=%.1f device=%s use_service=%s result=%s", dur, device_id, bool(use_service), result)
logging.info(
"[截图] 总耗时(ms)=%.1f device=%s use_service=%s result=%s",
dur,
device_id,
bool(use_service),
result,
)
return result
def _get_screenshot_direct(self, device_id, path="pic"):
@@ -531,9 +572,11 @@ class underlying_operations:
if path == "pic":
try:
import path_config
out_dir = path_config.get_pic_dir()
except Exception:
import path_config
out_dir = path_config.get_pic_dir()
else:
out_dir = os.path.join(os.path.dirname(__file__), "target_pic")
@@ -586,7 +629,11 @@ class underlying_operations:
return False
header_check_dur = (time_module.time() - header_check_start) * 1000.0
if header_check_dur > 10.0: # 只记录超过10ms的
logging.debug("[截图] PNG头尾校验耗时(ms)=%.1f path=%s", header_check_dur, path0)
logging.debug(
"[截图] PNG头尾校验耗时(ms)=%.1f path=%s",
header_check_dur,
path0,
)
# 优化:只在必要时使用 PIL 验证(PIL verify 可能很慢)
# 对于临时文件,快速验证已足够;对于最终文件,可以跳过完整验证以提高速度
@@ -606,7 +653,11 @@ class underlying_operations:
verify_total_dur = (time_module.time() - verify_start) * 1000.0
if verify_total_dur > 100.0: # 只记录超过100ms的
logging.info("[截图] _valid_png总耗时(ms)=%.1f path=%s", verify_total_dur, path0)
logging.info(
"[截图] _valid_png总耗时(ms)=%.1f path=%s",
verify_total_dur,
path0,
)
return True
except Exception:
return False
@@ -649,10 +700,18 @@ class underlying_operations:
# 等待进程完成
return_code = process.wait(timeout=10)
if return_code != 0:
raise subprocess.CalledProcessError(return_code, [adb, "-s", device_id, "exec-out", "screencap", "-p"])
raise subprocess.CalledProcessError(
return_code,
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
)
adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0
logging.info("[截图] ADB exec-out subprocess耗时(ms)=%.1f device=%s attempt=%d", adb_subprocess_dur, device_id, attempt + 1)
logging.info(
"[截图] ADB exec-out subprocess耗时(ms)=%.1f device=%s attempt=%d",
adb_subprocess_dur,
device_id,
attempt + 1,
)
# 优化:移除 fsync(现代文件系统会自动同步,减少不必要的磁盘I/O)
# 文件写入已经完成,操作系统会在适当时机同步到磁盘
@@ -665,7 +724,11 @@ class underlying_operations:
is_valid = _valid_png(tmp_file)
validate_tmp_dur = (time_module.time() - validate_tmp_start) * 1000.0
if validate_tmp_dur > 50.0:
logging.info("[截图] 临时文件验证耗时(ms)=%.1f result=%s", validate_tmp_dur, is_valid)
logging.info(
"[截图] 临时文件验证耗时(ms)=%.1f result=%s",
validate_tmp_dur,
is_valid,
)
if is_valid:
# 使用安全的文件替换函数
@@ -673,14 +736,20 @@ class underlying_operations:
replace_success = _safe_replace_file(tmp_file, out_file)
replace_dur = (time_module.time() - replace_start) * 1000.0
if replace_dur > 50.0:
logging.info("[截图] 文件替换耗时(ms)=%.1f result=%s", replace_dur, replace_success)
logging.info(
"[截图] 文件替换耗时(ms)=%.1f result=%s",
replace_dur,
replace_success,
)
if replace_success:
mirror_start = time_module.time()
_mirror_screenshot_to_external(out_file)
mirror_dur = (time_module.time() - mirror_start) * 1000.0
if mirror_dur > 50.0:
logging.info("[截图] 镜像到外部路径耗时(ms)=%.1f", mirror_dur)
logging.info(
"[截图] 镜像到外部路径耗时(ms)=%.1f", mirror_dur
)
# 优化:快速验证目标文件(只检查存在和大小,不进行完整PNG验证)
# 完整验证可以在读取时进行,不阻塞截图流程
@@ -695,13 +764,27 @@ class underlying_operations:
with open(out_file, "rb") as f:
header = f.read(4)
if header == b"\x89PNG":
validate_out_dur = (time_module.time() - validate_out_start) * 1000.0
validate_out_dur = (
time_module.time()
- validate_out_start
) * 1000.0
if validate_out_dur > 50.0:
logging.info("[截图] 目标文件快速验证耗时(ms)=%.1f", validate_out_dur)
logging.info(
"[截图] 目标文件快速验证耗时(ms)=%.1f",
validate_out_dur,
)
overall_dur = (time_module.time() - overall_start) * 1000.0
logging.info("[截图] _get_screenshot_direct总耗时(ms)=%.1f device=%s (exec-out成功)", overall_dur, device_id)
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功")
overall_dur = (
time_module.time() - overall_start
) * 1000.0
logging.info(
"[截图] _get_screenshot_direct总耗时(ms)=%.1f device=%s (exec-out成功)",
overall_dur,
device_id,
)
print(
f"[{timetag}] [截图] ✓ 获取屏幕截图成功"
)
return True
except Exception:
pass
@@ -709,7 +792,9 @@ class underlying_operations:
# 如果快速验证失败,记录诊断信息
try:
st = os.stat(out_file)
print(f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}")
print(
f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}"
)
except Exception:
pass
except Exception:
@@ -719,7 +804,9 @@ class underlying_operations:
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
print(f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}")
print(
f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}"
)
except Exception:
pass
# 继续尝试回退方案
@@ -728,13 +815,15 @@ class underlying_operations:
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
print(f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}")
print(
f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}"
)
except Exception:
pass
# 继续尝试回退方案
except subprocess.TimeoutExpired:
# 超时异常,记录并继续重试
print(f"[截图] exec-out 超时,尝试重试或回退方案")
print("[截图] exec-out 超时,尝试重试或回退方案")
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
@@ -769,7 +858,11 @@ class underlying_operations:
timeout=10, # 添加超时
)
shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0
logging.info("[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s", shell_screencap_dur, device_id)
logging.info(
"[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s",
shell_screencap_dur,
device_id,
)
pull_start = time_module.time()
subprocess.run(
@@ -780,32 +873,55 @@ class underlying_operations:
timeout=10, # 添加超时
)
pull_dur = (time_module.time() - pull_start) * 1000.0
logging.info("[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id)
logging.info(
"[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id
)
fallback_validate_start = time_module.time()
if _valid_png(tmp_file):
fallback_validate_dur = (time_module.time() - fallback_validate_start) * 1000.0
fallback_validate_dur = (
time_module.time() - fallback_validate_start
) * 1000.0
if fallback_validate_dur > 50.0:
logging.info("[截图] 回退方案-临时文件验证耗时(ms)=%.1f", fallback_validate_dur)
logging.info(
"[截图] 回退方案-临时文件验证耗时(ms)=%.1f",
fallback_validate_dur,
)
# 使用安全的文件替换函数
fallback_replace_start = time_module.time()
if _safe_replace_file(tmp_file, out_file):
fallback_replace_dur = (time_module.time() - fallback_replace_start) * 1000.0
fallback_replace_dur = (
time_module.time() - fallback_replace_start
) * 1000.0
if fallback_replace_dur > 50.0:
logging.info("[截图] 回退方案-文件替换耗时(ms)=%.1f", fallback_replace_dur)
logging.info(
"[截图] 回退方案-文件替换耗时(ms)=%.1f",
fallback_replace_dur,
)
fallback_mirror_start = time_module.time()
_mirror_screenshot_to_external(out_file)
fallback_mirror_dur = (time_module.time() - fallback_mirror_start) * 1000.0
fallback_mirror_dur = (
time_module.time() - fallback_mirror_start
) * 1000.0
if fallback_mirror_dur > 50.0:
logging.info("[截图] 回退方案-镜像耗时(ms)=%.1f", fallback_mirror_dur)
logging.info(
"[截图] 回退方案-镜像耗时(ms)=%.1f", fallback_mirror_dur
)
try:
if _valid_png(out_file):
overall_dur = (time_module.time() - overall_start) * 1000.0
fallback_total_dur = (time_module.time() - fallback_start) * 1000.0
logging.info("[截图] _get_screenshot_direct总耗时(ms)=%.1f device=%s (回退方案成功, 回退部分耗时=%.1fms)", overall_dur, device_id, fallback_total_dur)
fallback_total_dur = (
time_module.time() - fallback_start
) * 1000.0
logging.info(
"[截图] _get_screenshot_direct总耗时(ms)=%.1f device=%s (回退方案成功, 回退部分耗时=%.1fms)",
overall_dur,
device_id,
fallback_total_dur,
)
print("{} 获取屏幕截图".format(timetag))
return True
except Exception:
@@ -819,12 +935,16 @@ class underlying_operations:
if os.path.exists(tmp_file):
# 尝试直接覆盖写入(如果文件被占用,这会失败,但至少尝试了)
try:
with open(tmp_file, "rb") as src, open(out_file, "wb") as dst:
with open(tmp_file, "rb") as src, open(
out_file, "wb"
) as dst:
dst.write(src.read())
_mirror_screenshot_to_external(out_file)
try:
if _valid_png(out_file):
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)")
print(
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)"
)
return True
except Exception:
pass
@@ -835,13 +955,17 @@ class underlying_operations:
_mirror_screenshot_to_external(out_file)
try:
if _valid_png(out_file):
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过优化替换)")
print(
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过优化替换)"
)
return True
except Exception:
pass
else:
# 最后兜底:返回True,让调用者知道临时文件存在
print(f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}")
print(
f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}"
)
return True
except Exception:
print(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
@@ -922,9 +1046,11 @@ class underlying_operations:
def save_reward_pic(self, device_id):
try:
import path_config
out_dir = path_config.get_pic_dir()
except Exception:
import path_config
out_dir = path_config.get_pic_dir()
if not os.path.exists(out_dir):
os.makedirs(out_dir)
@@ -1071,11 +1197,15 @@ class underlying_operations:
# 默认不保存,避免每次cut_pic都进行文件I/O操作(可节省50-200ms)
try:
# 检查是否启用调试图像保存
save_debug = os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1"
save_debug = (
os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1"
)
if not save_debug:
# 检查全局配置
try:
save_debug = os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1"
save_debug = (
os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1"
)
except Exception:
pass
@@ -1101,7 +1231,9 @@ class underlying_operations:
)
if debug_path:
try:
logging.info(f"[调试图像] cut_pic保存: {debug_path}")
logging.info(
"[调试图像] cut_pic保存: %s", debug_path
)
except Exception:
pass
except Exception:
@@ -1200,7 +1332,7 @@ class underlying_operations:
)
if debug_path:
try:
logging.info(f"[调试图像] cut_pic保存: {debug_path}")
logging.info("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
@@ -1342,7 +1474,7 @@ class underlying_operations:
)
if debug_path:
try:
logging.info(f"[调试图像] OCR预处理保存: {debug_path}")
logging.info("[调试图像] OCR预处理保存: %s", debug_path)
except Exception:
pass
except Exception:
@@ -1474,6 +1606,7 @@ class underlying_operations:
full_screenshot = None
try:
import path_config
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
full_screenshot = Image.open(screenshot_path)
@@ -1483,7 +1616,9 @@ class underlying_operations:
pass
# 如果成功加载完整截图,使用完整截图;否则使用预处理图像
debug_image = full_screenshot if full_screenshot is not None else img_for_attempt
debug_image = (
full_screenshot if full_screenshot is not None else img_for_attempt
)
extra_info_dict["has_full_screenshot"] = full_screenshot is not None
extra_info_dict["has_coords"] = ocr_coords is not None
@@ -1679,7 +1814,7 @@ class underlying_operations:
)
if debug_path:
try:
logging.info(f"[调试图像] OCR数字预处理保存: {debug_path}")
logging.info("[调试图像] OCR数字预处理保存: %s", debug_path)
except Exception:
pass
except Exception:
@@ -1803,7 +1938,6 @@ class underlying_operations:
# 对于倒计时:通常是1-2位数字
# 尝试提取最后几个数字(通常是实际值)
# 或者提取最短的连续数字段
import re
# 提取所有连续的数字段
digit_segments = re.findall(r"\d+", str(text))
@@ -2237,7 +2371,6 @@ class underlying_operations:
执行命令:adb shell input swipe <start_x> <start_y> <end_x> <end_y> <duration_ms>
"""
import subprocess
adb_cmd = self._adb()
# 注意:adb input swipe 的参数顺序是:start_x start_y end_x end_y duration_ms
@@ -2294,9 +2427,6 @@ class underlying_operations:
def _swipe_with_sendevent(self, device_id, x1, y1, x2, y2, steps):
"""使用 sendevent 方法滑动(需要 root 权限)"""
import subprocess
import time
# 获取触摸设备路径
result = subprocess.run(
f"{self._adb()} -s {device_id} shell getevent -p | grep -A 5 ABS_MT",
@@ -2812,9 +2942,11 @@ class underlying_operations:
try:
import path_config
local_path = path_config.get_window_dump_path()
except Exception:
import path_config
local_path = path_config.get_window_dump_path()
start = time.time()
while True:
@@ -2863,9 +2995,11 @@ class underlying_operations:
"""
try:
import path_config
local_path = path_config.get_window_dump_path()
except Exception:
import path_config
local_path = path_config.get_window_dump_path()
start = time.time()
+4 -4
View File
@@ -1,5 +1,5 @@
{
"needswitch": true,
"needswitch": false,
"infinite_loop_enabled": true,
"wait_minutes": 5,
"min_prize_value_yuan": 200.0,
@@ -127,12 +127,12 @@
}
},
"debug_captures": {
"enabled": false,
"enabled": true,
"keep_days": 3,
"max_files": 1900,
"auto_cleanup": true,
"async_save": false,
"log_on_complete": false
"async_save": true,
"log_on_complete": true
},
"fudai_detail_template_threshold": 0.53,
"switch_room_wait_after_stage_diag_seconds": 4.0,
+72
View File
@@ -0,0 +1,72 @@
# 项目(AI 友好)摘要 — 抖音福袋挂机
此文件为面向 AI 助手的精简技术摘要,便于快速理解项目结构、数据流、关键接口与运行验证要点。
## 一句概述
- 自动在抖音直播间检测并参与福袋抽奖;基于 ADB 截图、像素检测、模板匹配和 OCR(EasyOCR/PaddleOCR)实现决策与操作。
## 关键模块(短列表)
- `run_cli.py`:CLI 入口,解析参数并启动 `fudai_analyse.fudai_choujiang()`。
- `douyin/core/douyin_fudai.py`(`fudai_analyse`):主调度器(Mixin 组合)。
- `douyin/fudai/douyin_fudai_core.py`:福袋详情解析、并行 OCR、筛选与参与决策。
- `Underlying_Operations.py`:底层设备操作、截图、裁剪、OCR 封装与回退策略。
- `douyin/detection/`:像素检测与模板匹配(阶段诊断)。
- `douyin/reservation/`:高价值预约与回退处理。
- `path_config.py`:统一路径获取(避免硬编码)。
## 数据流(精简)
1. ADB截图 → 保存 `pic/screenshot.png`(原子替换)
2. 裁剪目标区域(`cut_pic`)→ 交给 OCR(`analyse_pic_word`/`analyse_pic_digits`)
3. OCR 文本 → 文本解析(倒计时/价值/人数)
4. 筛选决策(`basic_join_decision`)→ 点击操作(`operation.click`)或预约记录(`state/reservations.json`)
示意(ASCII):
SCREENSHOT -> CUT_PIC -> OCR -> PARSE -> DECIDE -> ACTION
↓ ↓
PIXEL_DETECT STATE
## AI 需要的简洁接口清单(签名 + 单行说明)
- `fudai_analyse.fudai_choujiang(device_id: str, y_pianyi: int, needswitch: bool, wait_minutes: int)` — 启动主循环。
- `fudai_analyse.run_once_basic()` — 单次循环(用于快速验证)。
- `get_fudai_contain(analyser) -> (content, countdown_text, participants, task_count, prize_value_yuan)` — 并行 OCR 获取福袋详情。
- `basic_join_decision(analyser, detail) -> bool` — 根据配置决策是否参与。
- `underlying_operations.get_screenshot(device_id) -> bool` — 获取并写入 `pic/screenshot.png`(原子替换)。
- `underlying_operations.cut_pic(left, top, right, bottom, name)` — 裁剪并保存子图用于 OCR。
- `underlying_operations.analyse_pic_word(picname) -> str` — 对裁剪图运行 OCR 并返回文本。
## 配置(快速 JSON schema 示例)
```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"needswitch": {"type":"boolean"},
"min_prize_value_yuan": {"type":"number","minimum":0},
"high_value_fudai_threshold_yuan": {"type":"number","minimum":0},
"debug_captures": {"type":"object"}
},
"required": ["needswitch"]
}
```
## 快速验证(AI 可执行的最小步骤)
1. 在连接设备的情况下,运行单次循环以生成截图并保存裁剪图:
```bash
python run_cli.py --device-id <DEVICE_ID> --wait-minutes 0
```
2. 检查 `pic/` 下的 `screenshot.png` 与裁剪图 (`pic/cut_*`),验证 `福袋价值` 裁剪区域是否为新坐标 (639,1466)-(769,1586)(已在代码中更新)。
## 变更与可检索点
- 已修改:`douyin/fudai/douyin_fudai_core.py` 中 `value_box` 裁剪坐标改为 `(639, 1466, 769, 1586)`。
- 文档新增:本 AI 摘要(此文件)与 `docs/完整技术文档.md` 的扩充。
## 推荐 AI 使用模式
- 若需解释函数,先调用 `semantic search` 在仓库内检索函数定义,然后读取对应文件段落(`path_config.py`、`Underlying_Operations.py`、`douyin/fudai/douyin_fudai_core.py`)。
- 对于 OCR/图像问题,优先让 AI 输出裁剪后的样例截图坐标与 OCR 文本样例,再定位 `analyse_pic_word` 的调用点。
---
文件生成于 2026-01-02,用于 AI 与开发者的快速对接;如需我将该内容合并回 `docs/完整技术文档.md` 的特定位置,我可以继续做这一步。
+190
View File
@@ -6,6 +6,42 @@
---
## 变更记录 (简要)
- 2025-12-30: 文档主版本 V3.0 完成;补充流程、OCR、预约细节。
- 2026-01-02: 补充快速开始、运行命令、重要环境变量与日志/调试图像说明。
- 2026-01-02: 补充快速开始、运行命令、重要环境变量与日志/调试图像说明。
- 统一整理关键裁剪区域坐标到 `douyin/fudai/core/coords.py` 并在 `douyin/stage/douyin_stage.py`、`douyin/fudai/douyin_fudai_core.py` 等模块引用常量,避免硬编码坐标。
## 快速开始(最小可运行示例)
1. 安装依赖(建议在虚拟环境中执行):
```bash
pip install -r requirements-minimal.txt
```
2. 连接设备并运行(示例):
```bash
# 指定设备并允许切换直播间
python run_cli.py --device_id <DEVICE_ID> --needswitch True
```
3. 仅测试一次循环(方便调试):
```bash
python run_cli.py --device_id <DEVICE_ID> --needswitch False --wait_minutes 0
```
## 重要路径与环境变量
- 配置文件优先使用: `config/config.json`(通过 `path_config.get_config_path()` 获取)。
- 路径工具: 统一使用 `path_config.py`,避免硬编码 `assets/`、`pic/`、`logs/`。
- OCR 初始化: 默认优先 `EasyOCR`,失败回退 `PaddleOCR`;可通过环境变量 `SKIP_OCR_INIT=1` 跳过OCR初始化用于快速启动/调试。
- 截图镜像: 为兼容性可能将截图镜像到外部目录,控制变量 `EXTERNAL_DOUYIN_FUDAI_DIR`;若不希望镜像,请设置 `DISABLE_SCREENSHOT_MIRROR=1`。
- 日志初始化函数: `douyin/logging/douyin_logging.py:configure_logging()`,业务日志请使用 `analyser._log_kv(...)`(封装在 `douyin/logging/douyin_logging_wrapper.py`)。
## 【代码修改规范】
### 1. 缩进要求
@@ -42,6 +78,48 @@
---
## 开发约束与提交流程
为保证代码质量与可维护性,请遵守以下约束与提交流程:
- **代码风格与缩进**: 严格使用4个空格缩进(不使用Tab),遵循项目现有风格。
- **异常处理**: `try` 必须配 `except` 或 `finally`,不要使用空的 `except:`,尽量捕获具体异常类型并记录或重抛。
- **最小变更原则**: 修改时仅变更为实现目标所需的最小代码。避免不相关文件的大量重格式化。
- **函数与方法接口**: 不随意修改公共函数签名,如确需变更应同步更新调用方与文档。
- **配置与路径**: 不要硬编码路径,使用 `path_config.py` 提供的路径函数。
- **测试与验证**:
- 修改后先在本地通过简单运行验证主流程:
```bash
python run_cli.py --device-id <DEVICE_ID> --wait-minutes 0
```
- 若修改涉及OCR/截图,可启用调试图像以验证裁剪区域:
```bash
SKIP_OCR_INIT=1 python run_cli.py --device-id <DEVICE_ID> --needswitch
```
- 建议在 Windows 下运行 `python -m py_compile <file>` 或直接运行脚本以捕获语法错误。
- **日志与调试**: 使用 `analyser._log_kv(...)` 记录业务日志,避免直接调用 `print()` 用于关键业务路径;调试时可保存截图并通过 `logs/actions.log` 追踪。
- **提交规范**:
- 分支命名: `feature/<短描述>`、`fix/<短描述>` 或 `docs/<短描述>`。
- 提交信息: 简洁说明修改目的、影响范围、验证步骤,例如:
```
feat: 优化福袋价值 OCR 区域 (修正坐标到 639,1466-769,1586)
说明: 调整裁剪框以改善 OCR 识别率。
验证: 本地运行 run_cli.py 并检查 pic/ 下裁剪图片与 logs/actions.log
```
- PR 描述: 包含变更摘要、影响文件列表、如何验证(步骤与期望结果)。
- 不强制要求代码风格工具,但请保持代码整洁;如仓库新增格式化检查,请遵循。
- **回滚与修复**: 如修改引入新问题,应先回滚到上一个稳定提交或提出快速修复 PR,并在 PR 中说明影响与回滚原因。
这些约束与流程用于日常开发与协作,保证代码可读性、可回溯性与稳定性。
## 文档目标
本文档旨在为AI助手提供项目的完整技术理解,包括:
@@ -248,6 +326,33 @@ fudai_analyse.fudai_choujiang(device_id, y_pianyi, needswitch, wait_minutes)
└─> fudai_analyse.run_once_basic() [循环调用]
```
#### 运行与常用命令
- 启动并允许自动切换直播间(常用):
```bash
python run_cli.py --device-id <DEVICE_ID> --needswitch
```
- 指定最小参与价值并限制运行时长(示例):
```bash
python run_cli.py --device-id <DEVICE_ID> --min-prize-value-yuan 300 --wait-minutes 60
```
- 常用命令行覆盖项(摘要):
- `--device-id`: ADB 设备 ID,空则自动选择。
- `--y-pianyi`: Y 轴偏移(整数,±数十范围)。
- `--needswitch`: 启用上划切换直播间(布尔开关,使用时传入即可)。
- `--wait-minutes`: 运行时长(分钟),0或负表示无限运行。
- `--min-prize-value-yuan`, `--min-participants`, `--max-participants`: 运行时覆盖筛选阈值。
- 预约/回退相关:`--reservation-back-verify-enabled/--disabled`, `--reservation-back-swipe-delay`。
- 高价值回访:`--high-value-room-revisit-enabled/--disabled`、`--high-value-room-revisit-only-current-run`。
- OCR/模板开关:`--enable-ocr-mode1` / `--disable-ocr-mode1`、`--fudai-template-enabled/--disabled`、`--fudai-template-threshold`。
请优先通过 `config/config.json` 配置常用选项,命令行参数仅用作临时覆盖或 GUI 启动时的快速覆盖(命令行优先级高于配置文件)。
**关键函数说明**:
- `run_cli.py::main()`: 命令行入口,解析参数并创建分析器对象
@@ -1889,6 +1994,14 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
- **镜像功能**: 自动镜像截图到外部工作树(如果配置了 `EXTERNAL_DOUYIN_FUDAI_DIR`)
- **文件验证**: 检查文件大小(至少1KB),避免0字节/损坏文件
**实现细节补充(重要)**:
- **临时文件 + 原子替换**: 截图先写入临时文件(例如 `screenshot.png.tmp`),完成后通过原子替换或安全复制覆盖目标 `screenshot.png`,以避免并发读取到半写入文件。
- **Windows 文件锁容错**: 使用 `_safe_replace_file()` 做两段回退(`os.replace` -> `shutil.copy2` -> 手动分块复制),确保在文件被占用时也能尽快恢复截图文件,避免阻塞主流程。
- **优先策略**: 优先使用 `adb exec-out screencap -p`(单次 adb 调用、速度最快)。若失败回退到 `adb shell screencap + adb pull` 或其它降级路径。
- **外部镜像**: 若设定 `EXTERNAL_DOUYIN_FUDAI_DIR`,会尝试把 `screenshot.png` 镜像一份到外部工作树,便于其它工具/工作树读取。为避免性能损耗,可通过 `DISABLE_SCREENSHOT_MIRROR=1` 禁用该镜像逻辑。
- **性能/可靠性权衡**: 镜像和原子替换会带来额外 IO,生产运行可选择禁用镜像且减少调试图像以提升稳定性。
**代码示例**:
```python
if operation.get_screenshot(device_id):
@@ -1970,6 +2083,20 @@ else:
- **坐标缓存**: 如果存在坐标缓存,传递给OCR引擎(提高识别精度)
- **错误处理**: 捕获所有异常,返回空字符串并记录错误
**OCR 初始化与回退策略(实现细节)**:
- **延迟初始化**: 类在构造时会根据 `SKIP_OCR_INIT` 环境变量决定是否立即初始化 OCR。若未设置 `SKIP_OCR_INIT`,构造函数会尝试优先初始化 EasyOCR;若失败回退到 PaddleOCR;两者都失败则保留 `ocr=None`,按需延迟初始化(通过 `_ensure_ocr()` 在首次 OCR 请求时再尝试加载)。
- **优先级**: EasyOCR 为首选(通常更快),PaddleOCR 为回退。若系统缺少依赖,会打印提示并继续运行(不会阻塞主流程)。
- **环境变量影响**:
- `SKIP_OCR_INIT=1`:跳过启动时 OCR 初始化(用于快速启动或仅需截图调试的场景)。
- `DISABLE_MODEL_SOURCE_CHECK=True`:在 PaddleOCR 导入时抑制模型源连通性检查(避免国内网络阻塞)。
- **输出与静默化**: 初始化过程会尽量静默(重定向 stdout/stderr),仅在需要时打印简短提示,减少启动噪音。
- **回退行为**: 当 `analyse_pic_word` 被调用且 `ocr is None`,会在内部调用 `_ensure_ocr()` 进行延迟初始化;初始化仍然可能失败,函数会捕获异常并返回空串,上层需要对空结果做容错处理。
**小结/建议**:
- 若频繁做大量 OCR 识别(生产运行),建议在环境中预装 `easyocr` 并允许启动时初始化以减少首次延迟;调试或仅需截图时可设置 `SKIP_OCR_INIT=1` 来缩短启动时间。
**代码示例**:
```python
# 识别福袋内容
@@ -2537,6 +2664,28 @@ UNKNOWN = "UNKNOWN" # 未知阶段
配置文件位于 `config/config.json`,路径通过 `path_config.get_config_path()` 获取。
### 7.1.1 `path_config.py` 用法
- 使用 `path_config.get_config_path()` 获取配置文件的绝对路径;
- 常用路径获取函数:
- `path_config.get_screenshot_path()`:当前截图 `pic/screenshot.png`;
- `path_config.get_reservations_path()`:预约状态文件路径;
- `path_config.get_logs_dir()` / `get_log_file_path()`:日志目录与统一日志文件;
- `path_config.get_cut_pic_path(name)`:获取裁剪图片用于 OCR 的路径。
- 在代码中不要硬编码 `pic/`、`logs/`、`state/` 等路径,统一通过 `path_config` 获取以保证兼容不同工作目录。
### 7.1.2 配置加载与覆盖优先级
配置项的生效顺序(从低到高优先级):
1. 代码中内置的默认值(类属性或常量);
2. `config/config.json`(通过 `path_config.get_config_path()` 指定的文件);
3. 环境变量(仅少数开关被代码显式读取,如 `SKIP_OCR_INIT`, `EXTERNAL_DOUYIN_FUDAI_DIR`, `DISABLE_MODEL_SOURCE_CHECK`, `DISABLE_SCREENSHOT_MIRROR` 等);
4. 命令行参数(`run_cli.py` 中解析的参数,会在创建 `fudai_analyse` 实例后覆盖运行时属性——命令行优先级最高)。
说明:实际运行时 `fudai_analyse.__init__()` 会加载 `config.json`(若存在),随后 `run_cli.py` 会将命令行参数按需覆盖分析器属性;因此临时调试请优先使用命令行参数,长期配置请写入 `config/config.json`。
### 7.2 配置项详解
#### 7.2.1 基础运行配置
@@ -6553,6 +6702,47 @@ debug_logger.log_exception(e, context={"step": "处理福袋"})
---
### 23.10 调试图像与截图说明
#### 23.10.1 存放位置与路径工具
- 所有截图与调试图像保存在项目 `pic/` 目录,使用 `path_config.get_pic_dir()` 与 `path_config.get_screenshot_path()` 获取路径;
- 裁剪供 OCR 使用的图片通过 `path_config.get_cut_pic_path(name)` 生成(即 `pic/<name>.png`);
- 调试图像也会在日志目录 `logs/` 下通过 `actions.log` 记录对应操作条目,便于追踪每张截图的来源。
#### 23.10.2 配置开关与保留策略
- 调试捕获配置位于 `config/config.json` 的 `debug_captures` 段(示例见 7.2.12);主要字段:
- `enabled`:是否启用调试捕获(布尔);
- `keep_days`:保留天数;
- `max_files`:最大文件数;
- `async_save`:是否异步保存以减少主流程阻塞;
- `log_on_complete`:保存完成后是否在 `actions.log` 写入记录;
#### 23.10.3 镜像与环境变量
- 若需要将截图镜像到外部目录以便实时查看,可设置环境变量 `EXTERNAL_DOUYIN_FUDAI_DIR` 指向目标目录(程序会尝试在该目录下复制调试图像);
- 若要禁用镜像或避免额外 IO,设置 `DISABLE_SCREENSHOT_MIRROR=1`;
- 在仅需调试截图但不希望初始化OCR模型时,可设置 `SKIP_OCR_INIT=1`(跳过OCR模型加载);
#### 23.10.4 性能注意事项与快速命令
- 保存大量调试图像会增加 IO 开销:生产运行建议关闭 `debug_captures` 或启用限制(`max_files`、`keep_days`);
- 推荐在开发/调试时使用异步保存(`async_save=true`)并启用 `log_on_complete`,方便排障而不阻塞主流程。
示例:快速启用截图镜像并保留调试图像(Linux/WSL 或 PowerShell 环境变量用法相似)
```bash
EXTERNAL_DOUYIN_FUDAI_DIR=/mnt/share/douyin_debug SKIP_OCR_INIT=1 python run_cli.py --device-id <DEVICE_ID> --needswitch
```
示例:禁用截图镜像以提高性能
```bash
DISABLE_SCREENSHOT_MIRROR=1 python run_cli.py --device-id <DEVICE_ID>
```
## 24. OCR预处理和优化详解
### 24.1 OCR预处理系统
+27 -18
View File
@@ -21,9 +21,11 @@ from douyin.stage import douyin_stage
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.core import douyin_flow_control # pylint: disable=redefined-outer-name
from douyin.other import douyin_live_room
from douyin.reservation import douyin_reservation_logic
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
from douyin.utils import douyin_config
from douyin.logging import douyin_logging_wrapper
from douyin.handlers import douyin_screenshot_handler
@@ -426,8 +428,6 @@ class fudai_analyse:
# 记录运行结束(定时模式)
try:
from datetime import datetime
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
actions_log_path = os.path.join(
@@ -456,8 +456,6 @@ class fudai_analyse:
self._log_kv("循环", "收到中断信号,退出循环")
# 记录运行结束
try:
from datetime import datetime
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
actions_log_path = os.path.join(
@@ -613,7 +611,7 @@ class fudai_analyse:
"""
from douyin.reservation import (
douyin_reservation_logic,
) # 确保在函数作用域内可用
) # pylint: disable=redefined-outer-name
start_time = time.time()
# 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果
@@ -628,8 +626,6 @@ class fudai_analyse:
reservations = self.reservations
if reservations and len(reservations) > 0:
# 检查是否有预约需要立即处理
from douyin.reservation import douyin_reservation_logic
reservation_focus_until_ts_ref = [0.0]
reservation_after_action_pending_ref = [False]
room_pos_ref = [getattr(self, "room_pos", 0) or 0]
@@ -1209,7 +1205,9 @@ class fudai_analyse:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
from douyin.stage import douyin_stage
from douyin.stage import (
douyin_stage,
) # pylint: disable=redefined-outer-name
result = douyin_stage.diagnose_stage_from_current_screen(self)
if result is None:
@@ -1246,7 +1244,9 @@ class fudai_analyse:
except Exception:
pass
# 查找福袋并打开详情页
from douyin.core import douyin_flow_control
from douyin.core import (
douyin_flow_control,
) # pylint: disable=redefined-outer-name
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
original_max_wait = getattr(
@@ -1502,7 +1502,9 @@ class fudai_analyse:
pass
try:
from douyin.reservation import douyin_reservation_logic
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
douyin_reservation_logic.cleanup_expired_reservations(
self, self.reservations, _write_state
@@ -1938,7 +1940,9 @@ class fudai_analyse:
self._force_attend_after_reservation_back = False
self.queue_full_waiting_at_earliest = False
# 清理过期预约
from douyin.reservation import douyin_reservation_logic
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
douyin_reservation_logic.cleanup_expired_reservations(
analyser=self,
@@ -2046,7 +2050,9 @@ class fudai_analyse:
self._force_attend_after_reservation_back = False
self.queue_full_waiting_at_earliest = False
# 清理过期预约
from douyin.reservation import douyin_reservation_logic
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
douyin_reservation_logic.cleanup_expired_reservations(
analyser=self,
@@ -2090,7 +2096,9 @@ class fudai_analyse:
pass
# 查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds 作为最大等待时间)
from douyin.core import douyin_flow_control
from douyin.core import (
douyin_flow_control,
) # pylint: disable=redefined-outer-name
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
# 临时设置 fudai_icon_max_wait_seconds 为 switch_room_wait_after_stage_diag_seconds
@@ -2404,8 +2412,7 @@ class fudai_analyse:
and len(detail) >= 6
):
# 类型检查:detail 已经通过 isinstance 检查,可以安全地索引
detail_values = detail
countdown_tuple: Any = detail_values[5] # type: ignore[index]
countdown_tuple: Any = detail[5]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
@@ -3103,7 +3110,9 @@ class fudai_analyse:
# 从预约队列中移除已完成的预约(匹配 future_ts,允许5秒误差)
if hasattr(self, "reservations") and self.reservations:
from douyin.reservation import douyin_reservation_logic
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
reservations_to_remove = []
for idx, r in enumerate(self.reservations):
+1 -1
View File
@@ -1,5 +1,5 @@
{
"updated_ts": 1767357328.7936106,
"updated_ts": 1767369418.118446,
"reason": "startup_clear",
"room_pos": 0,
"current_room_title": "",
+134 -57
View File
@@ -14,6 +14,8 @@ The logic is adapted from the original `axf/douyin_detection.py`, with extra
defensive checks to avoid crashes when certain analyser attributes are missing.
"""
# pylint: disable=no-member
from typing import Any
import os
import time
@@ -38,10 +40,12 @@ def check_detail_height(analyser: Any) -> int:
# 使用统一的截图路径配置
try:
import path_config
pic1_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
pic1_path = path_config.get_screenshot_path()
# 记录截图文件的时间戳(如果存在)
@@ -61,7 +65,9 @@ def check_detail_height(analyser: Any) -> int:
except Exception:
if attempt < 2:
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
analyser.operation.delay(0.2)
# 重新获取截图后,更新时间戳
try:
@@ -142,6 +148,7 @@ def check_detail_height(analyser: Any) -> int:
detected_y = y
try:
import time
current_time = time.time()
analyser._log_kv(
"检测",
@@ -150,7 +157,11 @@ def check_detail_height(analyser: Any) -> int:
detected_y=detected_y,
screenshot_timestamp=screenshot_timestamp,
current_time=current_time,
time_diff=round(current_time - screenshot_timestamp, 3) if screenshot_timestamp else None,
time_diff=(
round(current_time - screenshot_timestamp, 3)
if screenshot_timestamp
else None
),
)
except Exception:
pass
@@ -161,7 +172,10 @@ def check_detail_height(analyser: Any) -> int:
# 保存调试图片:标注检测区域和检测点
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
# 计算检测区域(参与按钮附近的区域)
check_region_x1 = max(0, x - 50)
@@ -175,12 +189,14 @@ def check_detail_height(analyser: Any) -> int:
check_y = base_y * ry // 2400 + dy
if 0 <= check_y < height:
# 标注检测点(小矩形区域)
coords_list.append((
max(0, x - 10),
max(0, check_y - 5),
min(width, x + 10),
min(height, check_y + 5)
))
coords_list.append(
(
max(0, x - 10),
max(0, check_y - 5),
min(width, x + 10),
min(height, check_y + 5),
)
)
# 保存调试图片
pic_rgb = pic.convert("RGB")
@@ -191,12 +207,14 @@ def check_detail_height(analyser: Any) -> int:
step="task_count_detection",
coords=(check_region_x1, check_region_y1, check_region_x2, check_region_y2),
extra_info={
"task_count": detected_task_count if detected_task_count is not None else 0,
"task_count": (
detected_task_count if detected_task_count is not None else 0
),
"detected_y": detected_y,
"check_x": x,
"check_points_count": len(check_points),
"region": f"({check_region_x1},{check_region_y1})-({check_region_x2},{check_region_y2})",
}
},
)
if debug_path:
try:
@@ -204,7 +222,9 @@ def check_detail_height(analyser: Any) -> int:
"[调试图像]",
"福袋任务数量检测",
path=debug_path,
task_count=detected_task_count if detected_task_count is not None else 0,
task_count=(
detected_task_count if detected_task_count is not None else 0
),
)
except Exception:
pass
@@ -225,6 +245,7 @@ def check_detail_height(analyser: Any) -> int:
pass
try:
import time
current_time = time.time()
analyser._log_kv(
"检测",
@@ -233,7 +254,9 @@ def check_detail_height(analyser: Any) -> int:
task_count=0,
screenshot_timestamp=screenshot_timestamp,
current_time=current_time,
time_diff=current_time - screenshot_timestamp if screenshot_timestamp else None,
time_diff=(
current_time - screenshot_timestamp if screenshot_timestamp else None
),
)
except Exception:
pass
@@ -250,15 +273,16 @@ def check_have_fudai_with_ready_screenshot(
"""
# 检查是否启用优化查找器
try:
use_optimized = bool(
getattr(analyser, "fudai_finder_optimized_enabled", False)
)
use_optimized = bool(getattr(analyser, "fudai_finder_optimized_enabled", False))
except Exception:
use_optimized = False
if use_optimized:
try:
from douyin.fudai.douyin_fudai_finder import check_have_fudai_with_ready_screenshot_optimized
from douyin.fudai.douyin_fudai_finder import (
check_have_fudai_with_ready_screenshot_optimized,
)
return check_have_fudai_with_ready_screenshot_optimized(
analyser, screenshot_ready
)
@@ -266,9 +290,7 @@ def check_have_fudai_with_ready_screenshot(
# 优化版不可用,回退到原版
try:
analyser._log_kv(
"[找福袋图标]",
"优化查找器不可用,使用原版",
error="ImportError"
"[找福袋图标]", "优化查找器不可用,使用原版", error="ImportError"
)
except Exception:
pass
@@ -279,7 +301,7 @@ def check_have_fudai_with_ready_screenshot(
"[找福袋图标]",
"优化查找器异常,使用原版",
error=str(e),
error_type=type(e).__name__
error_type=type(e).__name__,
)
except Exception:
pass
@@ -289,10 +311,12 @@ def check_have_fudai_with_ready_screenshot(
# 使用统一的截图路径配置
try:
import path_config
pic1_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
pic1_path = path_config.get_screenshot_path()
attempt_count = 0 # 仅用于日志记录,不影响循环控制
@@ -347,11 +371,16 @@ def check_have_fudai_with_ready_screenshot(
except Exception:
# 如果截图失败,尝试直接调用 get_screenshot 并验证文件可读性(避免半写入/截断图片导致后续 PIL 打开失败)
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
# 简单验证:文件存在、大小足够且能由 PIL 打开/加载
valid = False
try:
if os.path.exists(pic1_path) and os.path.getsize(pic1_path) >= 1024:
if (
os.path.exists(pic1_path)
and os.path.getsize(pic1_path) >= 1024
):
from PIL import Image as PILImage
with PILImage.open(pic1_path) as _im:
@@ -362,7 +391,9 @@ def check_have_fudai_with_ready_screenshot(
if not valid:
# 再尝试一次直接截图作为最后回退
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
except Exception:
pass
except Exception:
@@ -451,6 +482,7 @@ def check_have_fudai_with_ready_screenshot(
# 保存完整截图用于调试(检测前)
try:
from douyin.handlers import douyin_screenshot_manager
pic_rgb_full = pic_new.convert("RGB")
# 保存完整截图
@@ -459,20 +491,22 @@ def check_have_fudai_with_ready_screenshot(
operation_type="pixel_detect",
picname="fudai_icon",
step="before_detect",
coords=(scan_x_start, scan_y - 3, scan_x_end, scan_y + 4) if scan_y >= 3 else None,
coords=(
(scan_x_start, scan_y - 3, scan_x_end, scan_y + 4)
if scan_y >= 3
else None
),
extra_info={
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
"resolution": f"{rx}x{ry}",
"y_offset": y_pianyi_val,
"loop": loop
}
"loop": loop,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋图标检测前保存完整截图",
path=debug_path
"[调试图像]", "福袋图标检测前保存完整截图", path=debug_path
)
except Exception:
pass
@@ -498,7 +532,10 @@ def check_have_fudai_with_ready_screenshot(
# 双截图记录:保存实时操作截图(像素检测区域)
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
douyin_screenshot_manager.save_latest_attempt(
roi, operation_type="pixel_detect"
@@ -566,7 +603,10 @@ def check_have_fudai_with_ready_screenshot(
# 双截图记录:保存成功识别存档截图
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
douyin_screenshot_manager.save_last_success(
roi, operation_type="pixel_detect"
@@ -585,8 +625,8 @@ def check_have_fudai_with_ready_screenshot(
"detected_x_scaled": x1 + col_idx,
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
"resolution": f"{rx}x{ry}",
"result": "success"
}
"result": "success",
},
)
if debug_path:
try:
@@ -594,7 +634,7 @@ def check_have_fudai_with_ready_screenshot(
"[调试图像]",
"福袋图标检测成功保存完整截图",
path=debug_path,
detected_x=detected_x
detected_x=detected_x,
)
except Exception:
pass
@@ -623,7 +663,10 @@ def check_have_fudai_with_ready_screenshot(
try:
# 尝试获取上次找到的福袋位置(1080基准)
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
if last_fudai_x > 0 and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end:
if (
last_fudai_x > 0
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
):
optimal_x_scaled = last_fudai_x * rx // 1080
else:
# 使用默认最优位置:最热门区域中心(98-240的中心,约169)
@@ -633,7 +676,9 @@ def check_have_fudai_with_ready_screenshot(
optimal_x_scaled = 169 * rx // 1080
# 确保最优位置在搜索范围内
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
optimal_x_scaled = max(
scan_x_start, min(optimal_x_scaled, scan_x_end - 1)
)
# 确保y坐标在有效范围内
if 0 <= scan_y < pic_height:
@@ -645,7 +690,10 @@ def check_have_fudai_with_ready_screenshot(
# 优化:从最优位置开始向左右两侧搜索
found_x = None
search_range = max(optimal_x_scaled - scan_x_start, scan_x_end - optimal_x_scaled)
search_range = max(
optimal_x_scaled - scan_x_start,
scan_x_end - optimal_x_scaled,
)
# 先检查最优位置本身
try:
@@ -725,7 +773,10 @@ def check_have_fudai_with_ready_screenshot(
# 双截图记录:保存成功识别存档截图
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
detect_roi = pic_new.crop(
(
@@ -758,8 +809,8 @@ def check_have_fudai_with_ready_screenshot(
"detected_x_scaled": found_x,
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
"resolution": f"{rx}x{ry}",
"result": "success"
}
"result": "success",
},
)
if debug_path:
try:
@@ -767,7 +818,7 @@ def check_have_fudai_with_ready_screenshot(
"[调试图像]",
"福袋图标检测成功保存完整截图",
path=debug_path,
detected_x=detected_x
detected_x=detected_x,
)
except Exception:
pass
@@ -795,6 +846,7 @@ def check_have_fudai_with_ready_screenshot(
# 获取模板路径
try:
import path_config
template_path = path_config.get_assets_dir() + "/fudai.png"
except Exception:
# 回退到旧路径(向后兼容)
@@ -903,7 +955,10 @@ def check_have_fudai_with_ready_screenshot(
# 双截图记录:保存实时操作截图(搜索区域)
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
from PIL import Image as PILImage
search_roi_pil = PILImage.fromarray(
@@ -938,7 +993,10 @@ def check_have_fudai_with_ready_screenshot(
# 双截图记录:保存成功识别存档截图
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
from PIL import Image as PILImage
search_roi_pil = PILImage.fromarray(
@@ -1106,7 +1164,9 @@ def check_have_fudai_with_ready_screenshot(
scan_y=scan_y,
scan_x_start=scan_x_start,
scan_x_end=scan_x_end,
sample_color=str(sample_color) if sample_color is not None else "None",
sample_color=(
str(sample_color) if sample_color is not None else "None"
),
consecutive_failures=consecutive_failures,
)
except Exception:
@@ -1182,6 +1242,7 @@ def check_have_fudai_with_ready_screenshot(
# 获取模板路径
try:
import path_config
template_path = path_config.get_assets_dir() + "/fudai.png"
except Exception:
# 回退到旧路径(向后兼容)
@@ -1219,7 +1280,9 @@ def check_have_fudai_with_ready_screenshot(
screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR)
if screenshot_img is None:
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR)
except Exception:
pass
@@ -1365,7 +1428,10 @@ def check_have_fudai_with_ready_screenshot(
# 双截图记录:保存实时操作截图(搜索区域)
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
from PIL import Image as PILImage
search_roi_pil = PILImage.fromarray(
@@ -1386,11 +1452,13 @@ def check_have_fudai_with_ready_screenshot(
step="before_match",
coords=(search_x1, search_y1, search_x2, search_y2),
extra_info={
"template": os.path.basename(template_path) if template_path else "",
"template": (
os.path.basename(template_path) if template_path else ""
),
"template_size": f"{tw}x{th}",
"search_size": f"{search_x2-search_x1}x{search_y2-search_y1}",
"threshold": template_threshold
}
"threshold": template_threshold,
},
)
if debug_path:
try:
@@ -1398,7 +1466,7 @@ def check_have_fudai_with_ready_screenshot(
"[调试图像]",
"模板匹配前保存",
path=debug_path,
coords=f"({search_x1},{search_y1})-({search_x2},{search_y2})"
coords=f"({search_x1},{search_y1})-({search_x2},{search_y2})",
)
except Exception:
pass
@@ -1424,7 +1492,10 @@ def check_have_fudai_with_ready_screenshot(
# 双截图记录:保存成功识别存档截图
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
from PIL import Image as PILImage
search_roi_pil = PILImage.fromarray(
@@ -1452,7 +1523,12 @@ def check_have_fudai_with_ready_screenshot(
operation_type="template_match",
picname="fudai_icon",
step="matched",
coords=(search_x1, search_y1, search_x2, search_y2), # 搜索区域坐标
coords=(
search_x1,
search_y1,
search_x2,
search_y2,
), # 搜索区域坐标
extra_info={
"match_score": round(max_val, 4),
"match_location": f"({max_loc[0]},{max_loc[1]})",
@@ -1460,7 +1536,7 @@ def check_have_fudai_with_ready_screenshot(
"template_size": f"{tw}x{th}",
"threshold": template_threshold,
"passed": True,
}
},
)
if debug_path:
try:
@@ -1469,7 +1545,7 @@ def check_have_fudai_with_ready_screenshot(
"模板匹配成功保存",
path=debug_path,
score=round(max_val, 4),
location=f"({max_loc[0]},{max_loc[1]})"
location=f"({max_loc[0]},{max_loc[1]})",
)
except Exception:
pass
@@ -1677,8 +1753,9 @@ def check_in_fudai_detail(analyser: Any) -> bool:
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
template_threshold = float(
getattr(analyser, "fudai_detail_template_threshold", None) or
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
getattr(analyser, "fudai_detail_template_threshold", None)
or getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
if template_threshold < 0.0:
template_threshold = 0.0
+55 -15
View File
@@ -3,6 +3,7 @@
# pyright: reportMissingModuleSource=false
# pyright: reportUnknownMemberType=false
# pyright: reportUnknownVariableType=false
# pylint: disable=no-member
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional
@@ -99,6 +100,7 @@ def detect_coupon_popup_background(
# 使用统一的模板路径配置
try:
import path_config
template_path = path_config.get_assets_dir() + "/coupon.png"
except Exception:
# 回退到旧路径(向后兼容)
@@ -209,7 +211,10 @@ def detect_lucky_draw_result_popup(
detect_roi = None
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_latest_attempt(
@@ -268,7 +273,10 @@ def detect_lucky_draw_result_popup(
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
if result:
# 检测成功
@@ -364,7 +372,10 @@ def detect_attend_button_red_area(
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
@@ -439,7 +450,10 @@ def detect_attend_button_red_area(
# 无论成功失败都保存debug截图
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
@@ -523,7 +537,10 @@ def detect_fansclub_join_red_area(
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
@@ -592,7 +609,10 @@ def detect_fansclub_join_red_area(
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
@@ -672,18 +692,27 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
# 多边形顶点坐标(基于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)
(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
(int(x * scale_x), int(y * scale_y)) for x, y in polygon_base_points
]
# 创建多边形mask
mask = Image.new('L', (width, height), 0)
mask = Image.new("L", (width, height), 0)
draw = ImageDraw.Draw(mask)
# 绘制多边形(填充为白色)
@@ -710,7 +739,11 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
white_count = 0
else:
# 检查 RGB 三通道是否都 >= 240
white_flags = (masked_pixels[:, 0] >= 240) & (masked_pixels[:, 1] >= 240) & (masked_pixels[:, 2] >= 240)
white_flags = (
(masked_pixels[:, 0] >= 240)
& (masked_pixels[:, 1] >= 240)
& (masked_pixels[:, 2] >= 240)
)
white_count = int(np.count_nonzero(white_flags))
white_ratio = white_count / total_pixels if total_pixels > 0 else 0.0
@@ -733,7 +766,10 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
# 保存调试图像(检测结果)
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
@@ -999,7 +1035,9 @@ 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支持(用于像素检测)
"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"),
@@ -1087,7 +1125,9 @@ 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支持(用于像素检测)
"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"),
+69
View File
@@ -0,0 +1,69 @@
# 统一的坐标常量(基准分辨率 1080x2400)
# 仅包含常用的福袋详情相关裁剪框,后续可按需扩展。
# 福袋价值裁剪区域 (left, top, right, bottom)
"""
统一的坐标常量(基准分辨率 1080x2400)
集中维护常用裁剪框,避免代码中硬编码数字。
"""
# 福袋相关常用坐标
# 福袋价值裁剪区域 (left, top, right, bottom)
VALUE_BOX_TARGET = (656, 1466, 769, 1656)
# 福袋详情内容区域(任务/描述)
CONTENT_BOX = (389, 1273, 1000, 1534)
# 倒计时不同场景的裁剪区域(按出现情况命名)
COUNTDOWN_1110_1230 = (390, 1110, 690, 1230)
COUNTDOWN_1140_1290 = (390, 1140, 690, 1290)
COUNTDOWN_1010_1130 = (390, 1010, 690, 1130)
COUNTDOWN_1460_1580 = (390, 1460, 690, 1580)
# 任务列表区域(用于检测观看任务)
TASK_LIST = (50, 1621, 1032, 1960)
# 参与按钮区域
PARTICIPATE_BUTTON = (306, 2030, 780, 2110)
# 扩大识别区域(加入粉丝团 / OCR 扩大区域)
JOIN_FANSCLUB_REGION = (150, 1900, 950, 2200)
# 抽奖结果 / 弹窗确认
DRAW_RESULT = (380, 660, 720, 755)
NO_PRIZE_CONFIRM = (340, 1195, 740, 1355)
# 抽奖结果相关区域
LOTTERY_RESULT_AREA = (300, 600, 800, 800)
LOTTERY_RESULT_CONFIRM_BUTTON = (181, 1261, 890, 1389)
# 购物红包/弹窗诊断区域
SHOPPING_REDPACKET_AREA = (230, 450, 860, 550)
STAGE_RED_PACKET_OCR = (238, 454, 847, 545)
COUPON_PARTICIPATE_BUTTON_ALT = (200, 1940, 880, 2140)
# 常用标签栏(推荐/关注/直播)
RECOMMEND_TAB = (400, 140, 900, 200)
FOLLOW_TAB = (658, 147, 765, 194)
LIVE_LIST_TAB = (400, 140, 900, 200)
# 直播间标题中部(用于部分详情模块)
LIVE_ROOM_TITLE = (144, 144, 329, 185)
# 备用/替代参与按钮区域(弹窗/诊断模块使用)
PARTICIPATE_BUTTON_ALT = PARTICIPATE_BUTTON
# 直播/人机验证相关区域(占位值,可按实际截图微调)
LIVE_VERIFY1 = (200, 600, 880, 900)
LIVE_VERIFY2 = (200, 900, 880, 1200)
# 机器人验证图片裁剪区域(用于保存/处理验证图片)
ROBOT_VERIFY = (100, 1200, 980, 1780)
# 诊断购物红包(弹窗快速检测区域)
DIAG_SHOPPING_REDPACKET = (400, 1400, 900, 1600)
# 倒计时、任务、按钮等常用区域(保留占位,可根据需要填写)
# COUNTDOWN_BOX = (390, 1140, 570, 1290)
# BUTTON_BOX = (306, 2030, 780, 2110)
# CONTENT_BOX = (200, 600, 880, 900)
+102 -48
View File
@@ -33,7 +33,9 @@ def attend_choujiang(analyser) -> bool:
analyser._log_kv(
"参与",
"使用并行OCR识别的按钮状态",
button_text=attend_button_text[:100] if attend_button_text else "",
button_text=(
attend_button_text[:100] if attend_button_text else ""
),
button_status=button_status,
)
except Exception:
@@ -41,7 +43,9 @@ def attend_choujiang(analyser) -> bool:
# 如果并行OCR结果不可用,则重新识别
if not attend_button_text:
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字
from douyin.fudai.core.coords import PARTICIPATE_BUTTON
analyser.cut_pic(*PARTICIPATE_BUTTON, "", "参与按钮") # 参与福袋抽奖的文字
# 统一使用预处理工具生成可供 OCR 使用的图片名(若失败则回退到原名)
try:
@@ -52,7 +56,9 @@ def attend_choujiang(analyser) -> bool:
use_name = "参与按钮"
# 优化:尝试多种OCR模式提高精准度(优先保证精准)
attend_button_text = str(analyser.operation.analyse_pic_word(use_name, 0) or "")
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 (
@@ -67,9 +73,13 @@ def attend_choujiang(analyser) -> bool:
)
):
# 切换到模式1识别,优先使用预处理图(若存在)
attend_button_text = str(analyser.operation.analyse_pic_word(use_name, 1) or "")
attend_button_text = str(
analyser.operation.analyse_pic_word(use_name, 1) or ""
)
analyser._log_kv("参与", "识别参与按钮", text=attend_button_text)
if attend_button_text and "参与成功" in attend_button_text: # 如果识别到已经参与抽奖
if (
attend_button_text and "参与成功" in attend_button_text
): # 如果识别到已经参与抽奖
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
# 记录最后一次成功参与的时间
try:
@@ -87,8 +97,8 @@ def attend_choujiang(analyser) -> bool:
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
content, time_text, participants, copies, prize_value_yuan = (
douyin_fudai_core.get_fudai_contain(analyser, renwu=1)
)
# 尝试用 operation.check_countdown 解析 time_text
try:
@@ -159,9 +169,9 @@ def attend_choujiang(analyser) -> bool:
analyser.click(500, 470) # 点击刚才打开福袋的旁边位置
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
elif attend_button_text and (("活动已结束" in attend_button_text) or (
"活动己结束" in attend_button_text
)):
elif attend_button_text and (
("活动已结束" in attend_button_text) or ("活动己结束" in attend_button_text)
):
# 活动结束:按一次返回键退出详情
analyser.last_attend_fail_reason = "activity_ended"
try:
@@ -179,7 +189,9 @@ def attend_choujiang(analyser) -> bool:
except Exception:
pass
return False
elif attend_button_text and "还需看播" in attend_button_text: # 如果识别到需要看播
elif (
attend_button_text and "还需看播" in attend_button_text
): # 如果识别到需要看播
analyser.last_attend_fail_reason = "watch_required"
analyser._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛")
analyser.click(500, 470)
@@ -234,18 +246,28 @@ def attend_choujiang(analyser) -> bool:
# #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')
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:
@@ -261,23 +283,28 @@ def attend_choujiang(analyser) -> bool:
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')
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(
"参与",
@@ -303,18 +330,24 @@ def attend_choujiang(analyser) -> bool:
"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测",
)
return True
elif attend_button_text and ("加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text):
elif attend_button_text and (
"加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text
):
# 需要粉丝团门槛:先点击参与按钮,再使用OCR识别"加入粉丝团"按钮位置并点击,最后关闭详情页
analyser.last_attend_fail_reason = "fansclub_required"
# 保存debug截图:标注OCR识别区域(参与按钮区域)
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
from PIL import Image
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
@@ -385,9 +418,11 @@ def attend_choujiang(analyser) -> bool:
pic_path = analyser.operation._find_pic_path("加入粉丝团按钮")
if pic_path and os.path.exists(pic_path):
from PIL import Image
img = Image.open(pic_path)
img = img.convert("RGB")
import numpy as np
img_np = np.array(img)
# 调用OCR获取原始结果
@@ -463,11 +498,15 @@ def attend_choujiang(analyser) -> bool:
# 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域)
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
from PIL import Image
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
@@ -663,7 +702,9 @@ def attend_choujiang(analyser) -> bool:
)
analyser.operation.delay(0.5) # 短暂等待后立即第二次点击
# 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击
# 扩大OCR识别区域以便更容易识别:(150, 1900, 950, 2200)
# 扩大OCR识别区域以便更容易识别:使用常量 JOIN_FANSCLUB_REGION
from douyin.fudai.core.coords import JOIN_FANSCLUB_REGION
ocr_click_success = False
try:
(
@@ -671,7 +712,7 @@ def attend_choujiang(analyser) -> bool:
ocr_region_y1,
ocr_region_x2,
ocr_region_y2,
) = (150, 1900, 950, 2200)
) = JOIN_FANSCLUB_REGION
# 截图加入粉丝团按钮区域(扩大范围)
analyser.cut_pic(
ocr_region_x1,
@@ -692,9 +733,11 @@ def attend_choujiang(analyser) -> bool:
)
if pic_path and os.path.exists(pic_path):
from PIL import Image
img = Image.open(pic_path)
img = img.convert("RGB")
import numpy as np
img_np = np.array(img)
if (
@@ -923,7 +966,9 @@ def attend_choujiang(analyser) -> bool:
)
if auto_join_enabled:
# 启用自动加入:等待更长时间,让加入流程完成(可配置)
wait_s = getattr(analyser, "fansclub_auto_join_wait_seconds", 5.0)
wait_s = getattr(
analyser, "fansclub_auto_join_wait_seconds", 5.0
)
analyser.operation.delay(wait_s)
analyser._log_kv(
"参与",
@@ -932,7 +977,9 @@ def attend_choujiang(analyser) -> bool:
)
else:
# 未启用自动加入:等待较短时间后返回(可配置)
wait_s = getattr(analyser, "fansclub_manual_wait_seconds", 3.0)
wait_s = getattr(
analyser, "fansclub_manual_wait_seconds", 3.0
)
analyser.operation.delay(wait_s)
analyser._log_kv(
"参与",
@@ -974,7 +1021,9 @@ def attend_choujiang(analyser) -> bool:
# 重新诊断阶段,确认是否还在粉丝团加入页
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
st_after, seen_after = (
analyser._diagnose_stage_from_current_screen()
)
@@ -1059,9 +1108,11 @@ def attend_choujiang(analyser) -> bool:
pic_path
):
from PIL import Image
img = Image.open(pic_path)
img = img.convert("RGB")
import numpy as np
img_np = np.array(img)
if (
@@ -1329,7 +1380,9 @@ def attend_choujiang(analyser) -> bool:
base_x=527,
base_y=567,
)
analyser.operation.delay(1.0) # 等待返回完成
analyser.operation.delay(
1.0
) # 等待返回完成
except Exception as e:
analyser._log_kv(
"参与",
@@ -1341,6 +1394,7 @@ def attend_choujiang(analyser) -> bool:
except Exception:
pass
return _recover_to_fudai_detail_after_fansclub()
return True
elif attend_button_text and "开始观看" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
+86 -65
View File
@@ -16,6 +16,19 @@ from douyin.fudai.core.fudai_filter import is_watch_task_fudai
from douyin.utils.douyin_utils import extract_prize_value_yuan
# 更新:将福袋价值识别区域左下角调整为 (656, 1656)
# 格式: (left, top, right, bottom)
from douyin.fudai.core.coords import (
VALUE_BOX_TARGET,
CONTENT_BOX,
COUNTDOWN_1110_1230,
COUNTDOWN_1140_1290,
COUNTDOWN_1010_1130,
COUNTDOWN_1460_1580,
TASK_LIST,
)
def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]:
"""获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。"""
@@ -136,9 +149,11 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
# 例如"002" -> "02" 而不是 "00"
candidate = digits[-max_digits:]
# 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数
if candidate.startswith('0') and not digits.startswith('0' * len(digits)):
if candidate.startswith("0") and not digits.startswith(
"0" * len(digits)
):
# 移除前导零后的长度
actual_digits = digits.lstrip('0') or '0'
actual_digits = digits.lstrip("0") or "0"
if len(actual_digits) <= max_digits:
return actual_digits.zfill(max_digits)
return candidate
@@ -237,15 +252,15 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
countdown_box = None
if renwu == 2: # 如果是2个任务的
# 优化:扩大Y范围向上,确保包含任务描述(如"观看X分钟"等)
# 从1240向上扩展到1100,确保包含任务描述区域
# 从1240向上扩展到1100,确保包含任务描述区域
_save_full_screenshot_with_ocr_region(
analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi
analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi
)
analyser.cut_pic(
389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi
*CONTENT_BOX, "", "福袋内容", analyser.y_pianyi
) # 福袋内容详情(包含任务描述)
# 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字
countdown_box = (390, 1110, 690, 1230)
countdown_box = COUNTDOWN_1110_1230
# 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域
x1, y1, x2, y2 = countdown_box
w = max(1, int(x2 - x1))
@@ -267,23 +282,22 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi
)
# 优化:向上扩大范围(1460->1440),防止识别不完整
value_box = VALUE_BOX_TARGET
_save_full_screenshot_with_ocr_region(
analyser, "福袋价值", (390, 1440, 1000, 1580), analyser.y_pianyi
analyser, "福袋价值", value_box, analyser.y_pianyi
)
analyser.cut_pic(
390, 1440, 1000, 1580, "", "福袋价值", analyser.y_pianyi
) # 奖品价值/价格
analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi)
elif renwu == 1: # 如果是1个任务的
# 优化:扩大Y范围向上,确保包含任务描述
_save_full_screenshot_with_ocr_region(
analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi
analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi
)
analyser.cut_pic(
389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi
*CONTENT_BOX, "", "福袋内容", analyser.y_pianyi
) # 福袋内容详情(包含任务描述)
# 优化:稍微扩大高度,确保完整
# 优化:向上扩大区域,确保完整识别倒计时数字
countdown_box = (390, 1140, 690, 1290)
countdown_box = COUNTDOWN_1140_1290
# 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域
x1, y1, x2, y2 = countdown_box
w = max(1, int(x2 - x1))
@@ -305,22 +319,21 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi
)
# 优化:向上扩大范围(1520->1500),防止识别不完整
value_box = VALUE_BOX_TARGET
_save_full_screenshot_with_ocr_region(
analyser, "福袋价值", (390, 1500, 1000, 1630), analyser.y_pianyi
analyser, "福袋价值", value_box, analyser.y_pianyi
)
analyser.cut_pic(
390, 1500, 1000, 1630, "", "福袋价值", analyser.y_pianyi
) # 奖品价值/价格
analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi)
elif renwu == 3: # 如果是3个任务的
# 优化:扩大Y范围向上,确保包含任务描述
_save_full_screenshot_with_ocr_region(
analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi
analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi
)
analyser.cut_pic(
389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi
*CONTENT_BOX, "", "福袋内容", analyser.y_pianyi
) # 福袋内容详情(包含任务描述)
# 优化:稍微扩大高度
countdown_box = (390, 1010, 690, 1130)
countdown_box = COUNTDOWN_1010_1130
# 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域
x1, y1, x2, y2 = countdown_box
w = max(1, int(x2 - x1))
@@ -342,22 +355,21 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi
)
# 优化:向上扩大范围(1380->1360),防止识别不完整
value_box = VALUE_BOX_TARGET
_save_full_screenshot_with_ocr_region(
analyser, "福袋价值", (390, 1360, 1000, 1490), analyser.y_pianyi
analyser, "福袋价值", value_box, analyser.y_pianyi
)
analyser.cut_pic(
390, 1360, 1000, 1490, "", "福袋价值", analyser.y_pianyi
) # 奖品价值/价格
analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi)
else:
# 优化:稍微缩小宽度,增加高度
_save_full_screenshot_with_ocr_region(
analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi
analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi
)
analyser.cut_pic(
389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi
*CONTENT_BOX, "", "福袋内容", analyser.y_pianyi
) # 福袋内容详情
# 优化:稍微扩大高度
countdown_box = (390, 1460, 690, 1580)
countdown_box = COUNTDOWN_1460_1580
# 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域
x1, y1, x2, y2 = countdown_box
w = max(1, int(x2 - x1))
@@ -379,12 +391,11 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi
)
# 优化:向上扩大范围(1820->1800),防止识别不完整
value_box = VALUE_BOX_TARGET
_save_full_screenshot_with_ocr_region(
analyser, "福袋价值", (390, 1800, 1000, 1930), analyser.y_pianyi
analyser, "福袋价值", value_box, analyser.y_pianyi
)
analyser.cut_pic(
390, 1800, 1000, 1930, "", "福袋价值", analyser.y_pianyi
) # 奖品价值/价格
analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi)
# 准备任务列表区域的截图(用于并行OCR)
# 任务列表区域(任务位置:50,1621到1032,1960),用于检测"观看X分钟"任务
@@ -393,7 +404,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
_save_full_screenshot_with_ocr_region(
analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi
)
analyser.cut_pic(50, 1621, 1032, 1960, "", "福袋任务列表", analyser.y_pianyi)
analyser.cut_pic(*TASK_LIST, "", "福袋任务列表", analyser.y_pianyi)
except Exception as e:
# 任务列表截图失败不影响后续流程,记录日志即可
try:
@@ -418,6 +429,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
"""OCR识别任务列表(用于检测观看任务)"""
try:
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:
@@ -437,6 +449,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
"""OCR识别福袋内容"""
try:
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:
@@ -490,6 +503,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
"""OCR识别福袋价值(使用普通OCR)"""
try:
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:
@@ -510,6 +524,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
try:
# 使用动态线程池大小,根据CPU核心数优化
from operations.screenshot_service import get_optimal_workers
optimal_workers = get_optimal_workers()
with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
future_task_list = executor.submit(ocr_task_list)
@@ -614,16 +629,17 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
pass
# 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行)
try:
def ocr_task_list_fallback():
try:
return analyser.operation.analyse_pic_word("福袋任务列表", 0)
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"备用OCR识别任务列表失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
@@ -633,13 +649,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
def ocr_content_fallback():
try:
return analyser.operation.analyse_pic_word("福袋内容", 0)
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"备用OCR识别福袋内容失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
@@ -649,13 +665,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
def ocr_countdown_mm_fallback():
try:
return analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1)
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"备用OCR识别倒计时分钟失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
@@ -665,13 +681,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
def ocr_countdown_ss_fallback():
try:
return analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1)
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"备用OCR识别倒计时秒失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
@@ -681,13 +697,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
def ocr_value_fallback():
try:
return analyser.operation.analyse_pic_word("福袋价值", 0)
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"备用OCR识别福袋价值失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
@@ -696,6 +712,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
# 使用动态线程池大小,根据CPU核心数优化
from operations.screenshot_service import get_optimal_workers
optimal_workers = get_optimal_workers()
with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
future_task_list = executor.submit(ocr_task_list_fallback)
@@ -719,13 +736,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
"OCR识别任务列表区域(备用并行)",
task_list_text=task_list_raw[:200] if task_list_raw else "",
)
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"记录备用任务列表OCR结果日志失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
@@ -737,15 +754,17 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
analyser._log_kv(
"福袋",
"任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理",
task_list_text=task_list_raw[:200] if task_list_raw else "",
task_list_text=(
task_list_raw[:200] if task_list_raw else ""
),
)
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"记录备用观看任务检测日志失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
@@ -753,13 +772,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
# 设置标志,让调用方知道这是观看任务
try:
analyser._is_watch_task_detected = True
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"设置备用观看任务标志失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
@@ -787,25 +806,25 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
if is_watch_task_in_list:
try:
analyser._is_watch_task_detected = True
except Exception as e:
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"设置串行观看任务标志失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
pass
return "", "", 0, 0, 0.0
except Exception as e:
except Exception as e_serial:
try:
analyser._log_kv(
"错误",
"串行OCR识别任务列表失败",
error=str(e),
error_type=type(e).__name__,
error=str(e_serial),
error_type=type(e_serial).__name__,
level="ERROR",
)
except Exception:
@@ -949,9 +968,11 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
# 例如"002" -> "02" 而不是 "00"
candidate = digits[-max_digits:]
# 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数
if candidate.startswith('0') and not digits.startswith('0' * len(digits)):
if candidate.startswith("0") and not digits.startswith(
"0" * len(digits)
):
# 移除前导零后的长度
actual_digits = digits.lstrip('0') or '0'
actual_digits = digits.lstrip("0") or "0"
if len(actual_digits) <= max_digits:
return actual_digits.zfill(max_digits)
return candidate
+11 -6
View File
@@ -9,6 +9,7 @@ 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:
"""判定福袋抽奖的结果。"""
# 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过)
@@ -31,7 +32,9 @@ def check_lucky_draw_result(analyser) -> int | bool:
"开奖结果", "识别是否中奖/未中奖", analyser.device_id
)
# 优化:扩大区域(300-800, 600-800),确保包含完整的开奖结果文字"没有抽中福袋"
analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果") # 没有抽中福袋位置
from douyin.fudai.core.coords import DRAW_RESULT
analyser.cut_pic(*DRAW_RESULT, "", "抽奖结果") # 没有抽中福袋位置
# 诊断开始时间
t0 = time.time()
@@ -57,9 +60,7 @@ def check_lucky_draw_result(analyser) -> int | bool:
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(name_lr0b, 0) or ""
)
lucky_draw_result = str(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
):
@@ -104,7 +105,9 @@ def check_lucky_draw_result(analyser) -> int | bool:
else:
# 回退到原始更大区域OCR(兼容)
t1b = time.time()
analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
from douyin.fudai.core.coords import NO_PRIZE_CONFIRM
analyser.cut_pic(*NO_PRIZE_CONFIRM, "", "无奖励确认")
name_na = preprocess_for_ocr(analyser, "无奖励确认")
no_award_confirm = analyser.operation.analyse_pic_word(name_na)
dur2 = time.time() - t1b
@@ -113,7 +116,9 @@ def check_lucky_draw_result(analyser) -> int | bool:
except Exception:
# 回退到原实现:直接OCR
t1 = time.time()
analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
from douyin.fudai.core.coords import NO_PRIZE_CONFIRM
analyser.cut_pic(*NO_PRIZE_CONFIRM, "", "无奖励确认")
no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认")
analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
dur2 = time.time() - t1
File diff suppressed because it is too large. Load diff
+24 -5
View File
@@ -28,10 +28,12 @@ def check_coupon_popup(analyser) -> bool:
# 使用统一的截图路径配置
try:
import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
pic_path = path_config.get_screenshot_path()
pic = Image.open(pic_path)
pic.load() # Force load to catch truncated files early
@@ -73,7 +75,9 @@ def check_coupon_popup(analyser) -> bool:
try:
# 截图按钮区域
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
from douyin.fudai.core.coords import PARTICIPATE_BUTTON_ALT
analyser.cut_pic(*PARTICIPATE_BUTTON_ALT, "", "参与按钮")
cut_elapsed = time.time() - ocr_start
# OCR模式0
@@ -195,10 +199,12 @@ def check_shopping_redpacket_popup(analyser) -> bool:
# 使用统一的截图路径配置
try:
import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
pic_path = path_config.get_screenshot_path()
pic = Image.open(pic_path)
pic.load() # Force load to catch truncated files early
@@ -218,7 +224,11 @@ def check_shopping_redpacket_popup(analyser) -> bool:
# 步驟1:截圖檢測區域
cut_start = time.time()
try:
analyser.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
from douyin.fudai.core.coords import (
DIAG_SHOPPING_REDPACKET,
) # pylint: disable=no-name-in-module
analyser.cut_pic(*DIAG_SHOPPING_REDPACKET, "", "診斷購物紅包")
_ = time.time() - cut_start
except Exception as e:
cut_elapsed = time.time() - cut_start
@@ -260,7 +270,11 @@ def check_shopping_redpacket_popup(analyser) -> bool:
# 嘗試按鈕區域快速 OCR(兜底)
try:
analyser.cut_pic(400, 1200, 680, 1400, "", "診斷購物紅包按鈕")
from douyin.fudai.core.coords import (
DIAG_SHOPPING_REDPACKET,
) # pylint: disable=no-name-in-module
analyser.cut_pic(*DIAG_SHOPPING_REDPACKET, "", "診斷購物紅包按鈕")
name_btn = preprocess_for_ocr(analyser, "診斷購物紅包按鈕")
btn_text = str(
analyser.operation.analyse_pic_word(name_btn, 0) or ""
@@ -392,11 +406,16 @@ def handle_lottery_result_popup(analyser) -> None:
# 使用OCR识别开奖结果按钮
from douyin.utils import douyin_helpers
result_type = douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(analyser)
result_type = douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(
analyser
)
if result_type:
# 根据OCR识别结果处理
douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(analyser, result_type)
douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(
analyser, result_type
)
else:
# OCR未识别到,尝试按返回键
analyser._log_kv("开奖结果", "OCR未识别到按钮,使用返回键关闭")
+27 -7
View File
@@ -4,10 +4,16 @@ import os
from typing import Any
from PIL import Image
from douyin.fudai.core.coords import (
LIVE_VERIFY1,
LIVE_VERIFY2,
ROBOT_VERIFY,
) # pylint: disable=no-name-in-module
# OCR 预处理接口(直接导入)
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
def check_have_robot_analyse(analyser) -> int | bool:
"""检查是否存在人机校验。
@@ -17,7 +23,7 @@ def check_have_robot_analyse(analyser) -> int | bool:
- 3: 人脸识别验证
- False: 未检测到人机验证
"""
analyser.cut_pic(130, 790, 680, 870, "", "直播验证")
analyser.cut_pic(*LIVE_VERIFY1, "", "直播验证")
name_live = preprocess_for_ocr(analyser, "直播验证")
result = analyser.operation.analyse_pic_word(name_live, 0)
if "验证" in result:
@@ -26,7 +32,7 @@ def check_have_robot_analyse(analyser) -> int | bool:
elif "形状相同" in result:
print("存在点击图片人机校验,需要等待完成验证。")
return 2
analyser.cut_pic(340, 1415, 700, 1518, "", "直播验证")
analyser.cut_pic(*LIVE_VERIFY2, "", "直播验证")
name_live2 = preprocess_for_ocr(analyser, "直播验证")
result = analyser.operation.analyse_pic_word(name_live2)
if "开始检测" in result:
@@ -79,13 +85,15 @@ def deal_robot_analyse(analyser) -> None:
def deal_robot_pic_change_color(analyser) -> None:
"""处理人机验证的图片,转为黑白图。"""
analyser.cut_pic(143, 884, 936, 1380, "save", "机器人验证")
analyser.cut_pic(*ROBOT_VERIFY, "save", "机器人验证")
try:
import path_config
path = path_config.get_robot_verify_pic_path(save_subdir=True)
pic = path
except Exception:
import path_config
path = path_config.get_robot_verify_pic_path(save_subdir=True)
pic = path
img = Image.open(pic)
@@ -94,9 +102,17 @@ def deal_robot_pic_change_color(analyser) -> None:
for x in range(5, width - 40):
for y in range(20, height - 30):
current_color = img.getpixel((x, y))
if current_color[0] > 240 and current_color[1] > 240 and current_color[2] > 240:
if (
current_color[0] > 240
and current_color[1] > 240
and current_color[2] > 240
):
img.putpixel((x, y), (255, 255, 255)) # 白色
elif current_color[0] < 35 and current_color[1] < 20 and current_color[2] < 20:
elif (
current_color[0] < 35
and current_color[1] < 20
and current_color[2] < 20
):
img.putpixel((x, y), (0, 0, 0)) # 黑色
else:
img.putpixel((x, y), (128, 128, 128)) # 灰色
@@ -107,7 +123,7 @@ def deal_robot_pic_change_color(analyser) -> None:
def check_robot_pic_distance(analyser) -> int:
"""根据人机图片计算需要滑动的距离。"""
analyser.cut_pic(143, 884, 936, 1380, "", "机器人验证")
analyser.cut_pic(*ROBOT_VERIFY, "", "机器人验证")
# 使用新的路径查找方法(支持新旧位置)
pic_path = analyser.operation._find_pic_path("机器人验证", for_reading=True)
if not pic_path or not os.path.exists(pic_path):
@@ -122,7 +138,11 @@ def check_robot_pic_distance(analyser) -> int:
for y in range(20, height - 30):
for x in range(5, width - 40):
current_color = img.getpixel((x, y))
if current_color[0] > 240 and current_color[1] > 240 and current_color[2] > 240:
if (
current_color[0] > 240
and current_color[1] > 240
and current_color[2] > 240
):
if not printed_first_result: # 确保只输出一次第一个结果
print(x, y)
printed_first_result = True
+392 -109
View File
@@ -1,6 +1,17 @@
from __future__ import annotations
from douyin.detection import douyin_pixel
from douyin.fudai.core.coords import (
RECOMMEND_TAB,
FOLLOW_TAB,
LIVE_LIST_TAB,
DIAG_SHOPPING_REDPACKET,
LOTTERY_RESULT_AREA,
LOTTERY_RESULT_CONFIRM_BUTTON,
SHOPPING_REDPACKET_AREA,
STAGE_RED_PACKET_OCR,
COUPON_PARTICIPATE_BUTTON_ALT,
)
def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: C901
@@ -53,9 +64,15 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
pass
diag_start = time.time()
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开关(二值化)
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
@@ -65,7 +82,10 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# ========== 步骤0:首先执行并行检测(包括直播间图标检测)==========
step_start = time.time()
_log("步骤0[并行检测]-开始", 说明="并行检测:直播间图标(像素检测-多边形区域白色像素)、优惠券、红包、抽奖结果、参与按钮、粉丝团、福袋详情")
_log(
"步骤0[并行检测]-开始",
说明="并行检测:直播间图标(像素检测-多边形区域白色像素)、优惠券、红包、抽奖结果、参与按钮、粉丝团、福袋详情",
)
in_live_room = False
live_room_score = 0.0
detection_method = ""
@@ -100,7 +120,9 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# 获取检测分数(白色像素比例)
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)
pixel_confidence = float(
pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0
)
# 如果像素检测通过(白色比例 >= 阈值),判定为在直播间
if live_room_pixel_detected:
@@ -129,17 +151,30 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
detection_method = "抽奖结果弹窗(像素检测)"
# 尽量使用该项的置信度作为分数(回退为0.0)
try:
live_room_score = float(pixel_details.get("has_lucky_draw_result", {}).get("confidence", 0.0) or 0.0)
live_room_score = float(
pixel_details.get("has_lucky_draw_result", {}).get(
"confidence", 0.0
)
or 0.0
)
except Exception:
live_room_score = 0.0
_log("步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)", 抽奖弹窗置信度=round(live_room_score, 4))
_log(
"步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)",
抽奖弹窗置信度=round(live_room_score, 4),
)
except Exception:
# 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中
pass
if in_live_room:
total_elapsed = (time.time() - step_start) * 1000
_log("步骤0[检测直播间]-最终结果:在直播间", 检测方法=detection_method, 分数=live_room_score, 总耗时毫秒=total_elapsed)
_log(
"步骤0[检测直播间]-最终结果:在直播间",
检测方法=detection_method,
分数=live_room_score,
总耗时毫秒=total_elapsed,
)
# 记录每个检测步骤的详细信息
for key, detail in pixel_details.items():
@@ -181,7 +216,9 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
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}"
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)
@@ -202,7 +239,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
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:
if (
task_count_val is not None
and task_count_val > 0
and not detected
):
try:
_log( # type: ignore[misc]
"警告:检测到任务数量但 has_fudai_detail 为 False",
@@ -215,8 +256,9 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
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
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:
@@ -241,8 +283,14 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
except Exception as e:
import traceback
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
_log("并行检测异常", 耗时毫秒=pixel_detection_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
_log(
"并行检测异常",
耗时毫秒=pixel_detection_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
pixel_state = {}
pixel_details = {}
@@ -253,7 +301,9 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测)
step_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before)
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before
)
t_recommend = ""
t_follow = ""
t_list = ""
@@ -262,14 +312,16 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
_log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(400, 140, 900, 200, "", "推荐页标签栏")
analyser.cut_pic(*RECOMMEND_TAB, "", "推荐页标签栏")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
name0 = preprocess_for_ocr(analyser, "推荐页标签栏")
t_recommend = str(analyser.operation.analyse_pic_word(name0, 0) or "")
t_recommend = str(
analyser.operation.analyse_pic_word(name0, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR推荐页标签栏]-OCR模式0",
@@ -278,12 +330,23 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
文本预览=t_recommend[:50] if t_recommend else "",
)
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and (
not t_recommend or ("推荐" not in t_recommend and "关注" not in t_recommend and "直播" not in t_recommend)
if (
enable_ocr_mode1
and (time.time() - step_start < max_step_time)
and (
not t_recommend
or (
"推荐" not in t_recommend
and "关注" not in t_recommend
and "直播" not in t_recommend
)
)
):
ocr_start_1 = time.time()
name1 = preprocess_for_ocr(analyser, "推荐页标签栏")
t_recommend = str(analyser.operation.analyse_pic_word(name1, 1) or "")
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",
@@ -309,24 +372,29 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
原因=f"标题='{t_recommend}'",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:RECOMMEND_PAGE(推荐页)")
_log_separator("最终结果:RECOMMEND_PAGE(推荐页)")
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
# 如果识别到"关注"但没有"推荐",可能是关注列表
if "关注" in t_recommend and "推荐" not in t_recommend:
_log("步骤3[OCR关注列表]-检测到关注关键词,准备精确确认", 精确区域="(658,147)-(765,194)")
_log(
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
精确区域="(658,147)-(765,194)",
)
step_start_follow = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(658, 147, 765, 194, "", "关注列表标签")
analyser.cut_pic(*FOLLOW_TAB, "", "关注列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
namef0 = preprocess_for_ocr(analyser, "关注列表标签")
t_follow = str(analyser.operation.analyse_pic_word(namef0, 0) or "")
t_follow = str(
analyser.operation.analyse_pic_word(namef0, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR关注列表]-OCR模式0",
@@ -335,10 +403,16 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
文本预览=t_follow[:50] if t_follow else "",
)
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("关注" not in t_follow):
if (
enable_ocr_mode1
and (time.time() - step_start < max_step_time)
and ("关注" not in t_follow)
):
ocr_start_1 = time.time()
namef1 = preprocess_for_ocr(analyser, "关注列表标签")
t_follow = str(analyser.operation.analyse_pic_word(namef1, 1) or "")
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",
@@ -348,7 +422,13 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
except Exception as e:
import traceback
_log("步骤3[OCR关注列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
_log(
"步骤3[OCR关注列表]-异常",
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
elapsed_follow = (time.time() - step_start_follow) * 1000
if "关注" in t_follow:
@@ -361,7 +441,9 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
识别文本=follow_text,
)
try:
analyser._last_follow_list_title_text = str(t_follow or "").strip()
analyser._last_follow_list_title_text = str(
t_follow or ""
).strip()
except Exception:
analyser._last_follow_list_title_text = ""
_log_summary(
@@ -370,18 +452,25 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
原因=f"标题='{t_follow}'",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:FOLLOW_LIST(关注列表)")
_log_separator("最终结果:FOLLOW_LIST(关注列表)")
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
# 如果识别到"正在直播"标签,判定为直播列表
if "正在直播" in t_recommend or ("直播" in t_recommend and "推荐" not in t_recommend and "关注" not in t_recommend):
_log("步骤3[OCR直播列表]-检测到直播关键词,准备精确确认", 精确区域="(650,145)-(800,195)")
if "正在直播" in t_recommend or (
"直播" in t_recommend
and "推荐" not in t_recommend
and "关注" not in t_recommend
):
_log(
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
精确区域="(650,145)-(800,195)",
)
step_start_list = time.time()
try:
ocr_start = time.time() # 初始化ocr_start
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(650, 145, 800, 195, "", "直播列表标签")
analyser.cut_pic(*LIVE_LIST_TAB, "", "直播列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
@@ -398,10 +487,16 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
文本预览=t_list[:50] if t_list else "",
)
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("正在直播" not in t_list):
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 "")
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",
@@ -411,7 +506,13 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
except Exception as e:
import traceback
_log("步骤3[OCR直播列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
_log(
"步骤3[OCR直播列表]-异常",
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
elapsed_list = (time.time() - step_start_list) * 1000
if "正在直播" in t_list:
@@ -429,7 +530,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
原因=f"标题='{t_list}'",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:LIVE_LIST(直播列表)")
_log_separator("最终结果:LIVE_LIST(直播列表)")
return "LIVE_LIST", "标题='{}'".format(t_list)
# 记录诊断时看到的"关注页标题"
@@ -440,7 +541,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
elapsed_total = (time.time() - step_start) * 1000
if elapsed_total > max_step_time * 1000:
_log("步骤3[OCR推荐页/关注列表/直播列表]-步骤超时", 耗时毫秒=elapsed_total, 阈值毫秒=max_step_time * 1000)
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
耗时毫秒=elapsed_total,
阈值毫秒=max_step_time * 1000,
)
else:
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
@@ -450,6 +555,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
except Exception as e:
elapsed_total = (time.time() - step_start) * 1000
import traceback
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
耗时毫秒=elapsed_total,
@@ -466,7 +572,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
原因="不在直播间且未识别到特定页面,默认判定为在直播间",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
_log_separator("最终结果:IN_LIVE_ROOM(默认直播间)")
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
# ========== 在直播间:继续执行像素检测结果处理 ==========
@@ -482,21 +588,27 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# 像素检测到抽奖结果弹窗,使用OCR兜底确认
step_result_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤1[检测抽奖结果弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到抽奖结果弹窗,OCR兜底确认")
_log(
"步骤1[检测抽奖结果弹窗]-开始",
剩余时间秒=remaining_time_before,
说明="像素检测到抽奖结果弹窗,OCR兜底确认",
)
result_verified = False
try:
# 检测抽奖结果文字区域 (300, 600)-(800, 800) - 扩大区域以覆盖"没有抽中福袋"文字
if time.time() - step_result_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果")
analyser.cut_pic(*LOTTERY_RESULT_AREA, "", "抽奖结果")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_result_start < max_step_time:
ocr_start = time.time()
name_res0 = preprocess_for_ocr(analyser, "抽奖结果")
result_text = str(analyser.operation.analyse_pic_word(name_res0, 0) or "")
result_text = str(
analyser.operation.analyse_pic_word(name_res0, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1[检测抽奖结果弹窗]-OCR模式0",
@@ -505,10 +617,22 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
文本预览=result_text[:50] if result_text else "",
)
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)):
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()
name_res1 = preprocess_for_ocr(analyser, "抽奖结果")
result_text = str(analyser.operation.analyse_pic_word(name_res1, 1) or "")
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",
@@ -518,18 +642,36 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
# 检测"我知道了"按钮区域 (181, 1261)-(890, 1389) - 与像素检测区域一致
if result_text and ("没有抽中" in result_text or "抽中福袋" in result_text):
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()
analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
cut_confirm_elapsed = (time.time() - cut_confirm_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-确认按钮截图完成", 耗时毫秒=cut_confirm_elapsed)
analyser.cut_pic(
*LOTTERY_RESULT_CONFIRM_BUTTON, "", "无奖励确认"
)
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()
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
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",
耗时毫秒=ocr_confirm_elapsed,
@@ -537,19 +679,36 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
文本预览=confirm_text[:50] if confirm_text else "",
)
if confirm_text and ("我知道了" in confirm_text or "领取并使用" in confirm_text):
if confirm_text and (
"我知道了" in confirm_text
or "领取并使用" in confirm_text
):
result_verified = True
else:
# OCR未识别到确认按钮,即使像素检测到也不判定为抽奖结果弹窗
_log("步骤1[检测抽奖结果弹窗]-OCR未识别到确认按钮", 说明="OCR未匹配,不判定为抽奖结果弹窗")
_log(
"步骤1[检测抽奖结果弹窗]-OCR未识别到确认按钮",
说明="OCR未匹配,不判定为抽奖结果弹窗",
)
else:
# OCR未识别到结果文字("没有抽中"或"抽中福袋"),即使像素检测到也不判定为抽奖结果弹窗
_log("步骤1[检测抽奖结果弹窗]-OCR未识别到结果文字", 说明="OCR未匹配关键词,不判定为抽奖结果弹窗")
_log(
"步骤1[检测抽奖结果弹窗]-OCR未识别到结果文字",
说明="OCR未匹配关键词,不判定为抽奖结果弹窗",
)
except Exception as e:
result_elapsed = (time.time() - step_result_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-异常", 耗时毫秒=result_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
_log(
"步骤1[检测抽奖结果弹窗]-异常",
耗时毫秒=result_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
# OCR异常时,不判定为抽奖结果弹窗(需要OCR确认)
_log("步骤1[检测抽奖结果弹窗]-OCR异常,不判定为抽奖结果弹窗", 说明="需要OCR确认才能判定")
_log(
"步骤1[检测抽奖结果弹窗]-OCR异常,不判定为抽奖结果弹窗",
说明="需要OCR确认才能判定",
)
if result_verified:
total_elapsed = (time.time() - diag_start) * 1000
@@ -561,7 +720,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
总耗时毫秒=total_elapsed,
结果检测耗时毫秒=result_elapsed,
)
_log_separator(f"最终结果:FUDai_RESULT(抽奖结果弹窗)")
_log_separator("最终结果:FUDai_RESULT(抽奖结果弹窗)")
return "FUDai_RESULT", "像素检测+OCR确认(抽奖结果弹窗)"
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
@@ -569,20 +728,26 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
_log_separator("步骤1.5:检测购物红包弹窗")
step_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤1.5[检测购物红包弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到购物红包背景")
_log(
"步骤1.5[检测购物红包弹窗]-开始",
剩余时间秒=remaining_time_before,
说明="像素检测到购物红包背景",
)
redpacket_detected = False
try:
if time.time() - step_redpacket_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
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()
name_rp = preprocess_for_ocr(analyser, "診斷購物紅包")
redpacket_text = str(analyser.operation.analyse_pic_word(name_rp, 0) or "")
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1.5[检测购物红包弹窗]-OCR模式0",
@@ -593,16 +758,29 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# 检查是否包含购物红包关键词
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords):
if redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
):
redpacket_detected = True
else:
# OCR未识别到关键词,不判定为购物红包弹窗(以OCR为准)
_log("步骤1.5[检测购物红包弹窗]-OCR未识别到关键词", 说明="OCR未匹配,不判定为购物红包弹窗")
_log(
"步骤1.5[检测购物红包弹窗]-OCR未识别到关键词",
说明="OCR未匹配,不判定为购物红包弹窗",
)
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
_log("步骤1.5[检测购物红包弹窗]-异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
_log(
"步骤1.5[检测购物红包弹窗]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
# OCR异常时,不判定为购物红包弹窗(以OCR为准)
_log("步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗", 说明="需要OCR确认才能判定")
_log(
"步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗",
说明="需要OCR确认才能判定",
)
if redpacket_detected:
total_elapsed = (time.time() - diag_start) * 1000
@@ -622,9 +800,14 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# 注意:优惠券弹窗和按钮类型区分的OCR检测区域相同 (200, 1940)-(880, 2140)
# 为避免重复OCR,已暂时禁用这两个OCR检测步骤
# 阶段判断将依赖像素检测和任务数量检测等其他方式
has_red_button_area = pixel_state.get("has_attend_button_red", False) or pixel_state.get("has_fansclub_join_red", False)
has_red_button_area = pixel_state.get(
"has_attend_button_red", False
) or pixel_state.get("has_fansclub_join_red", False)
if has_red_button_area:
_log("步骤2[OCR检测]-已禁用", 说明="OCR检测已暂时禁用,跳过优惠券弹窗和按钮类型区分检测")
_log(
"步骤2[OCR检测]-已禁用",
说明="OCR检测已暂时禁用,跳过优惠券弹窗和按钮类型区分检测",
)
# OCR检测已禁用,继续后续检测
# ========== 步骤1:像素检测福袋详情页(从并行检测结果获取)==========
@@ -692,35 +875,55 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
任务数量=detail_task_count,
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:FUDai_DETAIL(福袋详情页)")
_log_separator("最终结果:FUDai_DETAIL(福袋详情页)")
return "FUDai_DETAIL", f"任务数量检测确认(任务数量={detail_task_count})"
# 额外检测:在指定区域检测"邀你抢红包"文字(用于检测红包/福袋详情页)
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
# 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间
# 暂时禁用:将默认值改为 False
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)
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(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)
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:
_log(
"步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)",
模板匹配分数=template_match_score,
阈值=template_match_score_threshold,
说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间"
说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间",
)
if not detail_detected and enable_invite_redpacket_ocr and not should_skip_redpacket_ocr:
if (
not detail_detected
and enable_invite_redpacket_ocr
and not should_skip_redpacket_ocr
):
step_ocr_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
# 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待
ocr_max_step_time = float(getattr(analyser, "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, 说明="在指定区域检测邀你抢红包文字")
_log(
"步骤1.5[OCR检测邀你抢红包]-开始",
剩余时间秒=remaining_time_before,
说明="在指定区域检测邀你抢红包文字",
)
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
cut_start = time.time()
@@ -728,7 +931,10 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# 保存完整截图并标注OCR区域
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
import path_config
import os
from PIL import Image
@@ -740,8 +946,12 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
pic_rgb = pic.convert("RGB")
width, height = pic_rgb.size
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "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)
@@ -765,24 +975,33 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
"y_offset": y_pianyi,
}
},
)
if debug_path:
try:
_log("OCR识别前保存完整截图(阶段诊断邀你抢红包区域)", path=debug_path)
_log(
"OCR识别前保存完整截图(阶段诊断邀你抢红包区域)",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
analyser.cut_pic(238, 454, 847, 545, "", "阶段诊断邀你抢红包区域", y_pianyi)
analyser.cut_pic(
*STAGE_RED_PACKET_OCR, "", "阶段诊断邀你抢红包区域", 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()
name_red0 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域")
ocr_text = str(analyser.operation.analyse_pic_word(name_red0, 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",
@@ -792,11 +1011,26 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
# 如果模式0未识别到,尝试模式1
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:
name_red1 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域")
ocr_text = str(analyser.operation.analyse_pic_word(name_red1, 1) or "")
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
):
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),
@@ -804,9 +1038,19 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
# 检测是否包含"邀你抢红包"相关关键词(支持变体)
redpacket_keywords = ("邀你抢红包", "邀你抢手气红包", "邀你抢", "抢红包", "抢手气")
if ocr_text and any(kw in ocr_text for kw in redpacket_keywords):
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
redpacket_keywords = (
"邀你抢红包",
"邀你抢手气红包",
"邀你抢",
"抢红包",
"抢手气",
)
if ocr_text and any(
kw in ocr_text for kw in redpacket_keywords
):
redpacket_elapsed = (
time.time() - step_ocr_redpacket_start
) * 1000
total_elapsed = (time.time() - diag_start) * 1000
_log(
"步骤1.5[OCR检测邀你抢红包]-命中",
@@ -823,24 +1067,38 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
return "FUDai_DETAIL", "OCR检测确认(邀你抢红包)"
else:
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
_log("步骤1.5[OCR检测邀你抢红包]-未命中", 耗时毫秒=redpacket_elapsed, OCR文本=ocr_text[:50] if ocr_text else "")
redpacket_elapsed = (
time.time() - step_ocr_redpacket_start
) * 1000
_log(
"步骤1.5[OCR检测邀你抢红包]-未命中",
耗时毫秒=redpacket_elapsed,
OCR文本=ocr_text[:50] if ocr_text else "",
)
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
_log("步骤1.5[OCR检测邀你抢红包]-异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
_log(
"步骤1.5[OCR检测邀你抢红包]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认
# 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判
has_suspicious_popup_pixel = (
pixel_state.get("has_coupon_bg", False) or
pixel_state.get("has_redpacket_bg", False)
)
has_suspicious_popup_pixel = pixel_state.get(
"has_coupon_bg", False
) or pixel_state.get("has_redpacket_bg", False)
if has_suspicious_popup_pixel:
step_ocr_verify_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤3[OCR确认弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认")
_log(
"步骤3[OCR确认弹窗]-开始",
剩余时间秒=remaining_time_before,
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
)
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
if pixel_state.get("has_coupon_bg", False):
@@ -848,7 +1106,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
analyser.cut_pic(*COUPON_PARTICIPATE_BUTTON_ALT, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
@@ -857,11 +1115,16 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# 如果启用模式1,并行执行两个OCR模式
if enable_ocr_mode1:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
future_mode0 = executor.submit(analyser.operation.analyse_pic_word, name_part0, 0)
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)
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
@@ -882,7 +1145,9 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
else:
pname = preprocess_for_ocr(analyser, "参与按钮")
coupon_text = str(analyser.operation.analyse_pic_word(pname, 0) or "")
coupon_text = str(
analyser.operation.analyse_pic_word(pname, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
@@ -895,7 +1160,12 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
coupon_verified = True
except Exception as e:
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-优惠券异常", 耗时毫秒=coupon_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
_log(
"步骤3[OCR确认弹窗]-优惠券异常",
耗时毫秒=coupon_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
if coupon_verified:
total_elapsed = (time.time() - diag_start) * 1000
@@ -915,14 +1185,16 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
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()
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
redpacket_text = str(analyser.operation.analyse_pic_word(name_rp2, 0) or "")
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp2, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
@@ -932,11 +1204,18 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords):
if redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
):
redpacket_verified = True
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-购物红包异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
_log(
"步骤3[OCR确认弹窗]-购物红包异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
if redpacket_verified:
total_elapsed = (time.time() - diag_start) * 1000
@@ -952,7 +1231,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-未匹配到弹窗", 耗时毫秒=ocr_verify_elapsed, 说明="OCR确认后未匹配,判定为直播间背景颜色")
_log(
"步骤3[OCR确认弹窗]-未匹配到弹窗",
耗时毫秒=ocr_verify_elapsed,
说明="OCR确认后未匹配,判定为直播间背景颜色",
)
# 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段
if in_live_room:
@@ -966,7 +1249,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
分数=live_room_score,
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:IN_LIVE_ROOM(在直播间)")
_log_separator("最终结果:IN_LIVE_ROOM(在直播间)")
return "IN_LIVE_ROOM", f"识别到在直播间({detection_method}),其他阶段未识别"
# 如果不在直播间,默认返回:在直播间内(IN_LIVE_ROOM)
@@ -979,4 +1262,4 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
原因="像素检测未命中,默认直播间",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
_log_separator("最终结果:IN_LIVE_ROOM(默认直播间)")
+11 -1
View File
@@ -179,4 +179,14 @@ def extract_prize_value_yuan(text: str) -> float:
except ValueError:
continue
return max(values) if values else 0.0
if values:
return max(values)
fallback_values: list[float] = []
for candidate in re.findall(r"\d+(?:,\d+)*(?:\.\d+)?", s):
normalized = candidate.replace(",", "")
try:
fallback_values.append(float(normalized))
except ValueError:
continue
return max(fallback_values) if fallback_values else 0.0
@@ -3,6 +3,7 @@
"""
from typing import Any
from douyin.fudai.core.coords import PARTICIPATE_BUTTON_ALT
import os
from PIL import Image
@@ -35,10 +36,12 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
# 使用统一的截图路径配置
try:
import path_config
path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
path = path_config.get_screenshot_path()
try:
@@ -120,18 +123,29 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
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)
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
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
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
@@ -171,14 +185,21 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
# 如果颜色不像优惠券,且没有福袋详情特征,直接判定为福袋详情页
if not is_coupon_like_by_color:
if not has_fudai_detail:
analyser._log_kv("弹窗", "颜色统计不像优惠券,且未检测到福袋详情,判定为福袋详情页")
analyser._log_kv(
"弹窗", "颜色统计不像优惠券,且未检测到福袋详情,判定为福袋详情页"
)
else:
analyser._log_kv("弹窗", "颜色统计不像优惠券,但检测到福袋详情,判定为福袋详情页")
analyser._log_kv(
"弹窗", "颜色统计不像优惠券,但检测到福袋详情,判定为福袋详情页"
)
return False
# 如果颜色像优惠券,但没有福袋详情特征,可能只是误判
if not has_fudai_detail:
analyser._log_kv("弹窗", "颜色统计像优惠券,但未检测到福袋详情,判定为福袋详情页(可能是误判)")
analyser._log_kv(
"弹窗",
"颜色统计像优惠券,但未检测到福袋详情,判定为福袋详情页(可能是误判)",
)
return False
# 步骤2:OCR确认"开心收下"按钮(模板匹配成功后)
@@ -191,13 +212,16 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
# 保存完整截图并标注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)
@@ -230,7 +254,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
"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:
@@ -263,7 +287,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
pass
try:
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
analyser.cut_pic(*PARTICIPATE_BUTTON_ALT, "", "参与按钮")
# 并行执行模式0和模式1的OCR(如果启用模式1)
enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False))
@@ -271,9 +295,14 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
if enable_ocr_mode1:
# 并行执行两个OCR模式
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
future_mode0 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 0)
future_mode1 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 1)
future_mode0 = executor.submit(
analyser.operation.analyse_pic_word, "参与按钮", 0
)
future_mode1 = executor.submit(
analyser.operation.analyse_pic_word, "参与按钮", 1
)
text_mode0 = str(future_mode0.result() or "")
text_mode1 = str(future_mode1.result() or "")
# 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1
@@ -287,17 +316,27 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
coupon_text = text_mode1
else:
# 只使用模式0
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
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])
analyser._log_kv(
"弹窗",
"模板匹配+OCR确认:检测到'开心收下',判定为优惠券弹窗",
OCR文本=coupon_text[:50],
)
return True
else:
# 模板匹配成功,但OCR未确认"开心收下"
# 如果同时检测到福袋详情,优先信任福袋详情
if has_fudai_detail:
analyser._log_kv("弹窗", "模板匹配成功但OCR未确认'开心收下',且检测到福袋详情,判定为福袋详情页", OCR文本=coupon_text[:50] if coupon_text else "空")
analyser._log_kv(
"弹窗",
"模板匹配成功但OCR未确认'开心收下',且检测到福袋详情,判定为福袋详情页",
OCR文本=coupon_text[:50] if coupon_text else "空",
)
return False
else:
# 模板匹配成功但OCR未确认,可能是识别福袋位置失败
@@ -8,6 +8,7 @@ from __future__ import annotations
"""
from typing import Any, Tuple, List
from douyin.fudai.core.coords import LIVE_ROOM_TITLE
import re
import time
@@ -37,7 +38,18 @@ def _strip_room_noise_text(s: str) -> str:
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*人(?:在线|在看)?", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
t = re.sub(r"本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "人在线", "在线"):
for w in (
"点赞",
"赞",
"关注",
"粉丝",
"直播中",
"正在直播",
"进入直播间",
"推荐",
"人在线",
"在线",
):
t = t.replace(w, " ")
t = re.sub(r"\s+", " ", t).strip()
return t
@@ -55,7 +67,9 @@ def _extract_room_title_candidate(raw_text: str) -> str:
for seg in segs:
if not seg:
continue
seg2 = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞|关注|粉丝)$", "", seg).strip()
seg2 = re.sub(
r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞|关注|粉丝)$", "", seg
).strip()
if not seg2:
continue
seg = seg2
@@ -88,7 +102,18 @@ def _normalize_room_title(t: str) -> str:
s = _extract_room_title_candidate(str(t or ""))
s = s.replace("\r", " ").replace("\n", " ").strip()
s = re.sub(r"\s+", "", s)
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"):
for w in (
"点赞",
"赞",
"关注",
"粉丝",
"直播中",
"正在直播",
"进入直播间",
"推荐",
"在线",
"人在线",
):
s = s.replace(w, "")
s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s)
s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s)
@@ -97,7 +122,9 @@ def _normalize_room_title(t: str) -> str:
return s
def _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tuple[str, str]:
def _ocr_try_room_title(
analyser: Any, cut_name: str, change_color: int
) -> Tuple[str, str]:
"""尝试 OCR 识别直播间标题。"""
try:
raw0 = analyser.operation.analyse_pic_word(cut_name, change_color)
@@ -120,7 +147,9 @@ def _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tupl
return title0, cand_raw0
def _pick_best_room_title(cands: List[Tuple[str, str, str]], min_len: int = 3) -> Tuple[str, str]:
def _pick_best_room_title(
cands: List[Tuple[str, str, str]], min_len: int = 3
) -> Tuple[str, str]:
"""从多个候选结果中选择最佳的一个。"""
best = ("", "")
best_score = -1
@@ -174,8 +203,8 @@ def read_live_room_title_core(
# 只使用指定区域 (144,144) 到 (329,185),只尝试一次OCR(mode 0)
try:
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)
analyser.cut_pic(*LIVE_ROOM_TITLE, "", "live_room_title_mid", y_pianyi)
t, r = _ocr_try_room_title(analyser, "live_room_title_mid", 0)
title = t
raw_text = r
except Exception as e: