Files
douyin_guaji-main/douyin/fudai/core/fudai_attend.py
T
Your Name 25ed50cc3c 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.
2026-01-03 00:06:59 +08:00

1436 lines
77 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""福袋参与模块
包含参与抽奖、处理各种按钮状态的逻辑。
"""
from __future__ import annotations
import os
import time
from typing import Any
import path_config
def attend_choujiang(analyser) -> bool:
"""点击参与抽奖。"""
analyser.last_attend_fail_reason = ""
click_times = 0
while click_times < 2:
# 优化:优先使用并行OCR中已识别的按钮状态(避免重复识别)
attend_button_text = ""
button_status = getattr(analyser, "_fudai_button_status", None)
button_text = getattr(analyser, "_fudai_button_text", "")
# 如果并行OCR已经识别了按钮,且识别时间较近(5秒内),直接使用
if button_text and button_status:
try:
button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0)
current_time = time.time()
# 如果并行OCR结果在5秒内,且状态有效,直接使用
if current_time - button_ocr_time < 5.0:
attend_button_text = button_text
analyser._log_kv(
"参与",
"使用并行OCR识别的按钮状态",
button_text=(
attend_button_text[:100] if attend_button_text else ""
),
button_status=button_status,
)
except Exception:
pass
# 如果并行OCR结果不可用,则重新识别
if not attend_button_text:
from douyin.fudai.core.coords import PARTICIPATE_BUTTON
analyser.cut_pic(*PARTICIPATE_BUTTON, "", "参与按钮") # 参与福袋抽奖的文字
# 统一使用预处理工具生成可供 OCR 使用的图片名(若失败则回退到原名)
try:
from douyin.utils.ocr_preprocess import preprocess_for_ocr
use_name = preprocess_for_ocr(analyser, "参与按钮")
except Exception:
use_name = "参与按钮"
# 优化:尝试多种OCR模式提高精准度(优先保证精准)
attend_button_text = str(
analyser.operation.analyse_pic_word(use_name, 0) or ""
)
if not attend_button_text or not any(
k in attend_button_text
for k in (
"参与成功",
"还需看播",
"评论",
"参与抽奖",
"开始观看",
"参与",
"加入粉丝团",
"粉丝团",
)
):
# 切换到模式1识别,优先使用预处理图(若存在)
attend_button_text = str(
analyser.operation.analyse_pic_word(use_name, 1) or ""
)
analyser._log_kv("参与", "识别参与按钮", text=attend_button_text)
if (
attend_button_text and "参与成功" in attend_button_text
): # 如果识别到已经参与抽奖
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
# 记录最后一次成功参与的时间
try:
analyser._last_successful_attend_ts = time.time()
except Exception:
pass
# 记录已参与的福袋(通过 future_ts 标识),避免重复参与
future_ts = 0.0
try:
# 从 detail 中获取 future_ts(如果可用)
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
# 如果没有从 detail 中获取到 future_ts,尝试直接解析当前详情页的倒计时文本
if not future_ts:
try:
from douyin.fudai import douyin_fudai_core
content, time_text, participants, copies, prize_value_yuan = (
douyin_fudai_core.get_fudai_contain(analyser, renwu=1)
)
# 尝试用 operation.check_countdown 解析 time_text
try:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
_, parsed_future = res
future_ts = float(parsed_future or 0.0)
except Exception:
pass
except Exception:
pass
if future_ts > 0:
participated_fudai_ts = getattr(
analyser, "_participated_fudai_future_ts", set()
)
if not isinstance(participated_fudai_ts, set):
participated_fudai_ts = set()
participated_fudai_ts.add(future_ts)
analyser._participated_fudai_future_ts = participated_fudai_ts
analyser._log_kv(
"参与",
"记录已参与福袋",
future_ts=future_ts,
total_participated=len(participated_fudai_ts),
)
except Exception:
pass
# 设置开奖等待状态(如果 future_ts 可用)
if future_ts > 0:
try:
current_time = time.time()
remain_seconds = max(0, future_ts - current_time)
if remain_seconds > 0:
# 设置等待开奖标志和预期开奖时间(提前13秒,修正倒计时误差)
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts - 13.0
analyser._log_kv(
"参与",
"参与成功,设置等待开奖标志",
remain_seconds=int(remain_seconds),
future_ts=int(future_ts),
lottery_result_expected_ts=int(
analyser._lottery_result_expected_ts
),
)
else:
analyser._log_kv(
"参与",
"参与成功,但倒计时已过期,不设置等待标志",
future_ts=int(future_ts),
remain_seconds=int(remain_seconds),
)
except Exception as e:
analyser._log_kv(
"参与",
"设置开奖等待状态时出错",
error=str(e),
error_type=type(e).__name__,
)
# 设置标志:已经关闭了详情,避免后续再次点击返回键
try:
analyser._detail_closed_by_attend = True
except Exception:
pass
analyser.click(500, 470) # 点击刚才打开福袋的旁边位置
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
elif attend_button_text and (
("活动已结束" in attend_button_text) or ("活动己结束" in attend_button_text)
):
# 活动结束:按一次返回键退出详情
analyser.last_attend_fail_reason = "activity_ended"
try:
analyser._log_kv(
"参与", "活动已结束:按返回键退出详情", result="activity_ended"
)
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.5)
except Exception:
try:
analyser.click(500, 470)
except Exception:
pass
return False
elif (
attend_button_text and "还需看播" in attend_button_text
): # 如果识别到需要看播
analyser.last_attend_fail_reason = "watch_required"
analyser._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛")
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "无法参与" in attend_button_text:
analyser._log_kv("参与", "无法参与(条件不满足)", result="无法参与")
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "时长不足" in attend_button_text:
analyser._log_kv("参与", "无法参与(看播时长不足)", result="时长不足")
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "评论" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
action="点击参与",
mode="评论",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
return True
elif attend_button_text and "参与抽奖" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
action="点击参与",
mode="普通",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
# 设置标志:点击参与抽奖后直接查找福袋,跳过阶段检测
# 注意:点击参与按钮后会自动关闭详情页,返回直播间
try:
analyser._skip_stage_diagnosis_and_find_fudai = True
except Exception:
pass
# 设置等待开奖标志,避免参与后立即切换直播间
# #region agent log - set countdown
import json
from path_config import get_debug_log_path
current_ts_debug = int(time.time() * 1000)
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
json.dumps(
{
"id": f"log_{current_ts_debug}_set_countdown_start",
"timestamp": current_ts_debug,
"location": "fudai_attend.py:186",
"message": "开始设置等待开奖标志",
"data": {
"future_ts": getattr(
analyser, "_current_fudai_future_ts", 0.0
)
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
}
)
+ "\n"
)
# #endregion
try:
# 从 detail 中获取 future_ts(如果可用)
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
if future_ts > 0:
current_time = time.time()
remain_seconds = int(future_ts - current_time)
if remain_seconds > 0:
# 设置等待开奖标志和预期开奖时间
# 提前13秒,修正倒计时误差
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts - 13.0
# #region agent log - countdown set
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
json.dumps(
{
"id": f"log_{current_ts_debug}_countdown_set",
"timestamp": current_ts_debug,
"location": "fudai_attend.py:195",
"message": "成功设置等待开奖标志",
"data": {
"waiting_for_lottery_result": analyser._waiting_for_lottery_result,
"lottery_result_expected_ts": analyser._lottery_result_expected_ts,
"future_ts": future_ts,
"current_time": current_time,
"remain_seconds": remain_seconds,
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
}
)
+ "\n"
)
# #endregion
analyser._log_kv(
"参与",
"点击参与抽奖后,设置等待开奖标志",
future_ts=int(future_ts),
remain_seconds=remain_seconds,
expected_result_ts=int(
analyser._lottery_result_expected_ts
),
)
except Exception as e:
try:
analyser._log_kv(
"参与",
"点击参与抽奖后,设置等待开奖标志时出错",
error=str(e),
)
except Exception:
pass
analyser._log_kv(
"参与",
"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测",
)
return True
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"
)
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")
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)
# 缩放OCR区域坐标到实际分辨率
ocr_x1 = int(306 * width / rx)
ocr_y1 = int(2030 * height / ry)
ocr_x2 = int(780 * width / rx)
ocr_y2 = int(2110 * height / ry)
# 保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="参与按钮",
step="识别参与按钮",
coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2),
extra_info={
"ocr_text": attend_button_text[:50],
"region": "(306,2030)-(780,2110)",
"result": "需要粉丝团",
},
)
except Exception:
pass
# 第一步:先点击参与按钮(基于OCR区域中心:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"粉丝团门槛:先点击参与按钮",
result="需要粉丝团",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
analyser.operation.delay(1.0) # 等待参与按钮响应稍长一些,避免过快
# 第二步:使用OCR识别"加入粉丝团"按钮位置并点击(使用OCR识别的文字位置)
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
# OCR识别区域(扩大范围以便更容易识别)
ocr_region_x1, ocr_region_y1, ocr_region_x2, ocr_region_y2 = (
150,
1900,
950,
2200,
)
analyser.cut_pic(
ocr_region_x1,
ocr_region_y1,
ocr_region_x2,
ocr_region_y2,
"",
"加入粉丝团按钮",
)
# 获取OCR原始结果(包含bbox信息)
fansclub_text = ""
fansclub_bbox = None
# 尝试模式0
try:
# 获取裁剪后的图片路径
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获取原始结果
if getattr(analyser.operation, "ocr_type", None) == "easyocr":
ocr_result = analyser.operation.ocr.readtext(img_np)
else:
ocr_result = analyser.operation.ocr.ocr(img_np)
if ocr_result == [None]:
ocr_result = []
# 从OCR结果中查找"加入粉丝团"或"粉丝团"文字及其bbox
if isinstance(ocr_result, list) and ocr_result:
# PaddleOCR格式:[[[box], (text, score)], ...]
# EasyOCR格式:[(bbox, text, confidence), ...]
items = (
ocr_result[0]
if (
isinstance(ocr_result, list)
and len(ocr_result) == 1
and isinstance(ocr_result[0], list)
)
else ocr_result
)
for item in items:
text = ""
bbox = None
# 提取文本和bbox
if isinstance(item, (list, tuple)):
if len(item) >= 2:
# EasyOCR格式:[(bbox, text, confidence), ...]
if (
isinstance(item[0], (list, tuple))
and len(item[0]) >= 2
):
bbox = item[0] # bbox是第一个元素
if isinstance(item[1], str):
text = item[1]
# PaddleOCR格式:[box, (text, score)]
elif (
isinstance(item[1], (list, tuple))
and len(item[1]) >= 1
):
bbox = (
item[0]
if isinstance(item[0], (list, tuple))
else None
)
if isinstance(item[1][0], str):
text = item[1][0]
# 检查是否包含"加入粉丝团"或"粉丝团"
if (
text
and ("加入粉丝团" in text or "粉丝团" in text)
and bbox
):
fansclub_text = text
fansclub_bbox = bbox
break
except Exception as e:
analyser._log_kv(
"参与", "获取OCR原始结果失败", error=str(e), level="WARNING"
)
# 如果模式0没有找到,尝试模式1(使用analyse_pic_word)
if not fansclub_text:
fansclub_text = str(
analyser.operation.analyse_pic_word("加入粉丝团按钮", 1) or ""
)
# 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域)
try:
import importlib
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")
width, height = pic_rgb.size
# 缩放OCR区域坐标到实际分辨率
ocr_x1 = int(ocr_region_x1 * width / rx)
ocr_y1 = int(ocr_region_y1 * height / ry)
ocr_x2 = int(ocr_region_x2 * width / rx)
ocr_y2 = int(ocr_region_y2 * height / ry)
# 保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="加入粉丝团按钮",
step="识别加入粉丝团按钮",
coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2),
extra_info={
"ocr_text": fansclub_text[:50] if fansclub_text else "",
"region": f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})",
"result": (
"识别成功"
if fansclub_text
and (
"加入粉丝团" in fansclub_text
or "粉丝团" in fansclub_text
)
else "识别失败"
),
"has_bbox": fansclub_bbox is not None,
},
)
except Exception:
pass
# 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击
if fansclub_text and (
"加入粉丝团" in fansclub_text or "粉丝团" in fansclub_text
):
click_x = None
click_y = None
# 如果获取到了bbox,使用bbox的中心位置
if fansclub_bbox:
try:
# 提取bbox的坐标点
xs = []
ys = []
for p in fansclub_bbox:
if isinstance(p, (list, tuple)) and len(p) >= 2:
xs.append(float(p[0]))
ys.append(float(p[1]))
if xs and ys:
# 计算bbox中心(在裁剪图片中的坐标)
bbox_center_x = (min(xs) + max(xs)) / 2
bbox_center_y = (min(ys) + max(ys)) / 2
# 将裁剪图片坐标转换为全屏坐标
# 需要加上OCR区域的偏移
full_x = ocr_region_x1 + bbox_center_x
full_y = ocr_region_y1 + bbox_center_y
# 缩放到实际分辨率
click_x = int(full_x * rx // 1080)
click_y = int(full_y * ry // 2400)
except Exception as e:
analyser._log_kv(
"参与",
"计算bbox中心失败",
error=str(e),
level="WARNING",
)
# 如果bbox计算失败,使用OCR区域中心作为备选
if click_x is None or click_y is None:
click_x = int((ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080)
click_y = int((ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400)
analyser.operation.click(analyser.device_id, click_x, click_y)
analyser._log_kv(
"参与",
"粉丝团门槛:点击加入粉丝团按钮(OCR识别文字位置)",
ocr_text=fansclub_text[:50],
x=click_x,
y=click_y,
base_x=(
int((ocr_region_x1 + ocr_region_x2) / 2)
if click_x is None
else None
),
base_y=(
int((ocr_region_y1 + ocr_region_y2) / 2)
if click_y is None
else None
),
region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})",
used_bbox=fansclub_bbox is not None,
)
else:
# OCR未识别到"加入粉丝团",使用OCR区域中心作为备选
region_center_x = int(
(ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080
)
region_center_y = int(
(ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400
)
analyser.operation.click(
analyser.device_id, region_center_x, region_center_y
)
analyser._log_kv(
"参与",
"粉丝团门槛:点击加入粉丝团按钮(OCR未识别到文字,使用区域中心)",
ocr_text=fansclub_text[:50] if fansclub_text else "",
x=region_center_x,
y=region_center_y,
base_x=(ocr_region_x1 + ocr_region_x2) // 2,
base_y=(ocr_region_y1 + ocr_region_y2) // 2,
region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})",
)
# 等待点击完成(使用可配置延迟)
analyser.operation.delay(getattr(analyser, "fansclub_click_delay", 1.2))
except Exception as e:
analyser._log_kv("参与", "点击加入粉丝团按钮失败", error=str(e))
# 第三步:关闭详情页
analyser.click(500, 470) # 点击详情页旁边位置关闭详情页
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
if not analyser.auto_join_fansclub:
analyser._log_kv(
"参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15
)
analyser.operation.delay(15)
# 点击粉丝团按钮后,可能进入"加入粉丝团"独立页面:需要在该页再次点击"加入粉丝团"才能成功。
def _recover_to_fudai_detail_after_fansclub(max_steps: int = 4) -> bool:
for i in range(int(max_steps or 4)):
try:
analyser._shot_and_diagnose(
"粉丝团",
"粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps),
analyser.device_id,
)
except Exception:
pass
try:
st, seen = analyser._diagnose_stage_from_current_screen()
except Exception:
st, seen = "", ""
if st == "FUDai_DETAIL":
return True
if st == "FANSCLUB_JOIN":
# 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置)
analyser._log_kv(
"参与",
"粉丝团加入页:点击加入粉丝团",
stage=st,
seen=seen,
attempt=i + 1,
)
try:
# 点击加入粉丝团按钮
# 基于实际截图分析:OCR区域 (200, 1940, 880, 2140),尺寸680x200
# 按钮上部66%是红色区域(文字"加入粉丝团"所在),高度约132像素
# 红色区域Y范围:1940 到 2072,中心Y = 1940 + 132/2 = 2006
# 使用区域中心X = (200+880)/2 = 540,Y = 2006(红色区域中心)
rx = int(
getattr(analyser, "resolution_ratio_x", 1080) or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400) or 2400
)
# 点击红色文字区域的中心(基于截图分析优化)
click_x = int(540 * rx // 1080) # 区域中心X
click_y = int(
2006 * ry // 2400
) # 红色区域中心Y(基于截图:1940+132/2=2006)
# 第一次点击
analyser.operation.click(
analyser.device_id, click_x, click_y
)
analyser._log_kv(
"参与",
"恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)",
x=click_x,
y=click_y,
base_x=540,
base_y=2006,
region="(200,1940)-(880,2140)",
red_area_center_y=2006,
)
analyser.operation.delay(0.5) # 短暂等待后立即第二次点击
# 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击
# 扩大OCR识别区域以便更容易识别:使用常量 JOIN_FANSCLUB_REGION
from douyin.fudai.core.coords import JOIN_FANSCLUB_REGION
ocr_click_success = False
try:
(
ocr_region_x1,
ocr_region_y1,
ocr_region_x2,
ocr_region_y2,
) = JOIN_FANSCLUB_REGION
# 截图加入粉丝团按钮区域(扩大范围)
analyser.cut_pic(
ocr_region_x1,
ocr_region_y1,
ocr_region_x2,
ocr_region_y2,
"",
"加入粉丝团按钮",
)
# 获取OCR原始结果(包含bbox信息)
fansclub_text = ""
fansclub_bbox = None
try:
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)
if (
getattr(
analyser.operation, "ocr_type", None
)
== "easyocr"
):
ocr_result = (
analyser.operation.ocr.readtext(img_np)
)
else:
ocr_result = analyser.operation.ocr.ocr(
img_np
)
if ocr_result == [None]:
ocr_result = []
if isinstance(ocr_result, list) and ocr_result:
items = (
ocr_result[0]
if (
isinstance(ocr_result, list)
and len(ocr_result) == 1
and isinstance(ocr_result[0], list)
)
else ocr_result
)
for item in items:
text = ""
bbox = None
if isinstance(item, (list, tuple)):
if len(item) >= 2:
if (
isinstance(
item[0], (list, tuple)
)
and len(item[0]) >= 2
):
bbox = item[0]
if isinstance(item[1], str):
text = item[1]
elif (
isinstance(
item[1], (list, tuple)
)
and len(item[1]) >= 1
):
bbox = (
item[0]
if isinstance(
item[0],
(list, tuple),
)
else None
)
if isinstance(
item[1][0], str
):
text = item[1][0]
if (
text
and (
"加入粉丝团" in text
or "粉丝团" in text
)
and bbox
):
fansclub_text = text
fansclub_bbox = bbox
break
except Exception:
pass
# 如果模式0没有找到,尝试模式1
if not fansclub_text:
fansclub_text = str(
analyser.operation.analyse_pic_word(
"加入粉丝团按钮", 1
)
or ""
)
# 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击
if fansclub_text and (
"加入粉丝团" in fansclub_text
or "粉丝团" in fansclub_text
):
click_x = None
click_y = None
# 如果获取到了bbox,使用bbox的中心位置
if fansclub_bbox:
try:
xs = []
ys = []
for p in fansclub_bbox:
if (
isinstance(p, (list, tuple))
and len(p) >= 2
):
xs.append(float(p[0]))
ys.append(float(p[1]))
if xs and ys:
bbox_center_x = (min(xs) + max(xs)) / 2
bbox_center_y = (min(ys) + max(ys)) / 2
full_x = ocr_region_x1 + bbox_center_x
full_y = ocr_region_y1 + bbox_center_y
click_x = int(full_x * rx // 1080)
click_y = int(full_y * ry // 2400)
except Exception:
pass
# 如果bbox计算失败,使用OCR区域中心作为备选
if click_x is None or click_y is None:
click_x = int(
(ocr_region_x1 + ocr_region_x2)
/ 2
* rx
// 1080
)
click_y = int(
(ocr_region_y1 + ocr_region_y2)
/ 2
* ry
// 2400
)
analyser.operation.click(
analyser.device_id,
click_x,
click_y,
)
analyser._log_kv(
"参与",
"恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)",
ocr_text=fansclub_text[:50],
x=click_x,
y=click_y,
region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})",
used_bbox=fansclub_bbox is not None,
)
ocr_click_success = True
else:
# OCR未识别到"加入粉丝团",记录日志
analyser._log_kv(
"参与",
"恢复流程:OCR未识别到'加入粉丝团',使用坐标点击",
ocr_text=(
fansclub_text[:50]
if fansclub_text
else "空"
),
level="WARNING",
)
except Exception as e:
try:
analyser._log_kv(
"错误",
"OCR识别加入粉丝团按钮失败,使用坐标点击",
error=str(e),
error_type=type(e).__name__,
level="WARNING",
)
except Exception:
pass
# 如果OCR点击失败,回退到坐标点击
if not ocr_click_success:
analyser.operation.click(
analyser.device_id, click_x, click_y
)
analyser._log_kv(
"参与",
"恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)",
x=click_x,
y=click_y,
)
# 两次点击后,立即点击 (527, 567) 返回直播间
analyser.operation.delay(0.5) # 短暂等待
try:
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
)
return_x = int(527 * rx // 1080)
return_y = int(567 * ry // 2400)
analyser.operation.click(
analyser.device_id, return_x, return_y
)
analyser._log_kv(
"参与",
"恢复流程:两次点击后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
analyser.operation.delay(1.0) # 等待返回完成
except Exception as e:
analyser._log_kv(
"参与", "恢复流程:点击返回直播间失败", error=str(e)
)
except Exception:
# 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮)
try:
analyser.click(540, 2006) # 粉丝团加入按钮优化坐标
except Exception:
# 最后回退到旧坐标
try:
analyser.click(500, 2060)
except Exception:
pass
# 等待加入流程完成(根据是否启用自动加入决定等待时间)
auto_join_enabled = getattr(
analyser, "auto_join_fansclub", False
)
if auto_join_enabled:
# 启用自动加入:等待更长时间,让加入流程完成(可配置)
wait_s = getattr(
analyser, "fansclub_auto_join_wait_seconds", 5.0
)
analyser.operation.delay(wait_s)
analyser._log_kv(
"参与",
"已启用自动加入粉丝团,等待加入流程完成",
wait_seconds=wait_s,
)
else:
# 未启用自动加入:等待较短时间后返回(可配置)
wait_s = getattr(
analyser, "fansclub_manual_wait_seconds", 3.0
)
analyser.operation.delay(wait_s)
analyser._log_kv(
"参与",
"未启用自动加入粉丝团,等待后返回",
wait_seconds=wait_s,
)
# 加入粉丝团成功后,点击 (545, 1995) 然后关闭详情页
try:
rx = int(
getattr(analyser, "resolution_ratio_x", 1080) or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400) or 2400
)
return_x = int(545 * rx // 1080)
return_y = int(1995 * ry // 2400)
analyser.operation.click(
analyser.device_id, return_x, return_y
)
analyser._log_kv(
"参与",
"加入粉丝团成功后,点击指定位置",
x=return_x,
y=return_y,
base_x=545,
base_y=1995,
)
analyser.operation.delay(1.0) # 等待点击完成
# 关闭详情页
analyser.click(500, 470) # 点击详情页旁边位置关闭详情页
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
analyser.operation.delay(1.0) # 等待关闭完成
except Exception as e:
analyser._log_kv(
"参与", "点击指定位置或关闭详情页失败", error=str(e)
)
# 重新诊断阶段,确认是否还在粉丝团加入页
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
st_after, seen_after = (
analyser._diagnose_stage_from_current_screen()
)
analyser._log_kv(
"参与",
"点击加入粉丝团后重新诊断阶段",
stage_before=st,
stage_after=st_after,
seen_after=seen_after,
)
if st_after == "FANSCLUB_JOIN":
# 仍在粉丝团加入页,说明可能需要再次点击或等待更长时间
if auto_join_enabled:
# 如果启用了自动加入,尝试再次点击
analyser._log_kv(
"参与", "仍在粉丝团加入页,尝试再次点击"
)
try:
# 基于截图优化坐标:红色区域中心Y=2006
rx = int(
getattr(
analyser, "resolution_ratio_x", 1080
)
or 1080
)
ry = int(
getattr(
analyser, "resolution_ratio_y", 2400
)
or 2400
)
click_x = int(540 * rx // 1080)
click_y = int(
2006 * ry // 2400
) # 红色区域中心Y=2006
# 第一次点击
analyser.operation.click(
analyser.device_id, click_x, click_y
)
analyser._log_kv(
"参与",
"恢复流程:再次第一次点击加入粉丝团按钮(基于截图优化坐标)",
x=click_x,
y=click_y,
base_y=2006,
)
analyser.operation.delay(
0.5
) # 短暂等待后立即第二次点击
# 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击
# 扩大OCR识别区域以便更容易识别:(150, 1900, 950, 2200)
ocr_click_success_retry = False
try:
(
ocr_region_x1,
ocr_region_y1,
ocr_region_x2,
ocr_region_y2,
) = (150, 1900, 950, 2200)
# 截图加入粉丝团按钮区域(扩大范围)
analyser.cut_pic(
ocr_region_x1,
ocr_region_y1,
ocr_region_x2,
ocr_region_y2,
"",
"加入粉丝团按钮",
)
# 获取OCR原始结果(包含bbox信息)
fansclub_text_retry = ""
fansclub_bbox_retry = None
try:
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)
if (
getattr(
analyser.operation,
"ocr_type",
None,
)
== "easyocr"
):
ocr_result = analyser.operation.ocr.readtext(
img_np
)
else:
ocr_result = (
analyser.operation.ocr.ocr(
img_np
)
)
if ocr_result == [None]:
ocr_result = []
if (
isinstance(ocr_result, list)
and ocr_result
):
items = (
ocr_result[0]
if (
isinstance(
ocr_result, list
)
and len(ocr_result) == 1
and isinstance(
ocr_result[0], list
)
)
else ocr_result
)
for item in items:
text = ""
bbox = None
if isinstance(
item, (list, tuple)
):
if len(item) >= 2:
if (
isinstance(
item[0],
(
list,
tuple,
),
)
and len(item[0])
>= 2
):
bbox = item[0]
if isinstance(
item[1], str
):
text = item[
1
]
elif (
isinstance(
item[1],
(
list,
tuple,
),
)
and len(item[1])
>= 1
):
bbox = (
item[0]
if isinstance(
item[0],
(
list,
tuple,
),
)
else None
)
if isinstance(
item[1][0],
str,
):
text = item[
1
][0]
if (
text
and (
"加入粉丝团" in text
or "粉丝团" in text
)
and bbox
):
fansclub_text_retry = (
text
)
fansclub_bbox_retry = (
bbox
)
break
except Exception:
pass
# 如果模式0没有找到,尝试模式1
if not fansclub_text_retry:
fansclub_text_retry = str(
analyser.operation.analyse_pic_word(
"加入粉丝团按钮", 1
)
or ""
)
# 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击
if fansclub_text_retry and (
"加入粉丝团" in fansclub_text_retry
or "粉丝团" in fansclub_text_retry
):
click_x_retry = None
click_y_retry = None
# 如果获取到了bbox,使用bbox的中心位置
if fansclub_bbox_retry:
try:
xs = []
ys = []
for p in fansclub_bbox_retry:
if (
isinstance(
p, (list, tuple)
)
and len(p) >= 2
):
xs.append(float(p[0]))
ys.append(float(p[1]))
if xs and ys:
bbox_center_x = (
min(xs) + max(xs)
) / 2
bbox_center_y = (
min(ys) + max(ys)
) / 2
full_x = (
ocr_region_x1
+ bbox_center_x
)
full_y = (
ocr_region_y1
+ bbox_center_y
)
click_x_retry = int(
full_x * rx // 1080
)
click_y_retry = int(
full_y * ry // 2400
)
except Exception:
pass
# 如果bbox计算失败,使用OCR区域中心作为备选
if (
click_x_retry is None
or click_y_retry is None
):
click_x_retry = int(
(ocr_region_x1 + ocr_region_x2)
/ 2
* rx
// 1080
)
click_y_retry = int(
(ocr_region_y1 + ocr_region_y2)
/ 2
* ry
// 2400
)
analyser.operation.click(
analyser.device_id,
click_x_retry,
click_y_retry,
)
analyser._log_kv(
"参与",
"恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)",
ocr_text=fansclub_text_retry[:50],
x=click_x_retry,
y=click_y_retry,
region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})",
used_bbox=fansclub_bbox_retry
is not None,
)
ocr_click_success_retry = True
else:
# OCR未识别到"加入粉丝团",记录日志
analyser._log_kv(
"参与",
"恢复流程:OCR未识别到'加入粉丝团',使用坐标点击",
ocr_text=(
fansclub_text_retry[:50]
if fansclub_text_retry
else "空"
),
level="WARNING",
)
except Exception as e:
try:
analyser._log_kv(
"错误",
"OCR识别加入粉丝团按钮失败,使用坐标点击",
error=str(e),
error_type=type(e).__name__,
level="WARNING",
)
except Exception:
pass
# 如果OCR点击失败,回退到坐标点击
if not ocr_click_success_retry:
analyser.operation.click(
analyser.device_id, click_x, click_y
)
analyser._log_kv(
"参与",
"恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)",
x=click_x,
y=click_y,
)
# 两次点击后,立即点击 (527, 567) 返回直播间
analyser.operation.delay(0.5) # 短暂等待
try:
rx = int(
getattr(
analyser, "resolution_ratio_x", 1080
)
or 1080
)
ry = int(
getattr(
analyser, "resolution_ratio_y", 2400
)
or 2400
)
return_x = int(527 * rx // 1080)
return_y = int(567 * ry // 2400)
analyser.operation.click(
analyser.device_id, return_x, return_y
)
analyser._log_kv(
"参与",
"恢复流程:两次点击后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
analyser.operation.delay(
1.0
) # 等待返回完成
except Exception as e:
analyser._log_kv(
"参与",
"恢复流程:点击返回直播间失败",
error=str(e),
)
except Exception:
pass
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
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击开始观看(基于截图优化坐标)",
action="点击观看",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
return True
elif attend_button_text and "参与" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击参与(基于截图优化坐标)",
action="点击参与",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
return True
click_times += 1
analyser._log_kv(
"参与",
"参与抽奖失败:多次尝试均未识别到有效按钮",
click_times=click_times,
last_text=attend_button_text or "", # type: ignore[possibly-unbound]
result="参与失败",
)
return False