from __future__ import annotations import re import time import os import sys from typing import Tuple, Any from PIL import Image from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np from douyin_utils import normalize_countdown_text, extract_prize_value_yuan import douyin_reservation_logic import path_config def _save_full_screenshot_with_ocr_region( analyser: Any, picname: str, coords: Tuple[int, int, int, int], y_pianyi: int = 0 ) -> None: """保存完整截图并标注OCR区域(用于调试)。 参数: analyser: 分析器对象 picname: 图片名称(如"福袋内容") coords: OCR区域坐标 (x1, y1, x2, y2) - 基准坐标(1080x2400) y_pianyi: Y轴偏移 """ try: import douyin_screenshot_manager # 读取完整截图 pic_path = path_config.get_screenshot_path() if not os.path.exists(pic_path): return 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) x1_base, y1_base, x2_base, y2_base = coords x1 = int(x1_base * width / rx) y1 = int((y1_base + y_pianyi) * height / ry) x2 = int(x2_base * width / rx) y2 = int((y2_base + y_pianyi) * height / ry) # 边界检查和验证 x1_original = x1 y1_original = y1 x2_original = x2 y2_original = y2 x1 = max(0, min(x1, width - 1)) y1 = max(0, min(y1, height - 1)) x2 = max(0, min(x2, width - 1)) y2 = max(0, min(y2, height - 1)) # 记录坐标修正(如果坐标被修正) if ( x1_original != x1 or y1_original != y1 or x2_original != x2 or y2_original != y2 ): try: analyser._log_kv( "验证", "OCR区域坐标超出屏幕范围,已修正", original_coords=f"({x1_original},{y1_original})-({x2_original},{y2_original})", corrected_coords=f"({x1},{y1})-({x2},{y2})", screen_size=f"{width}x{height}", base_coords=coords, level="WARNING", ) except Exception: pass if x1 >= x2 or y1 >= y2: try: analyser._log_kv( "验证", "OCR区域坐标无效(x1>=x2或y1>=y2)", coords=f"({x1},{y1})-({x2},{y2})", base_coords=coords, level="WARNING", ) except Exception: pass return # 保存调试图片 debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, operation_type="ocr", picname=picname, step="before_ocr", coords=(x1, y1, x2, y2), extra_info={ "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", "size": f"{x2_base-x1_base}x{y2_base-y1_base}", "y_offset": y_pianyi, }, ) if debug_path: try: analyser._log_kv( "[调试图像]", f"OCR识别前保存完整截图({picname})", path=debug_path, region=f"({x1_base},{y1_base})-({x2_base},{y2_base})", ) except Exception as e: try: analyser._log_kv( "错误", "保存调试图像日志失败", error=str(e), error_type=type(e).__name__, picname=picname, level="WARNING", ) except Exception: pass except Exception as e: try: analyser._log_kv( "错误", "保存完整截图并标注OCR区域失败", error=str(e), error_type=type(e).__name__, picname=picname, coords=coords, level="WARNING", ) except Exception: pass def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: """获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。""" def _parse_mm_ss(text: str): m = re.search(r"(\d{1,2})[::](\d{2})", str(text or "")) if not m: return None try: return int(m.group(1)), int(m.group(2)) except Exception as e: try: analyser._log_kv( "验证", "解析倒计时格式失败", error=str(e), error_type=type(e).__name__, text=text[:50] if text else "", level="WARNING", ) except Exception: pass return None def _extract_2digits(text: str) -> str: digits = "".join(ch for ch in str(text or "") if ch.isdigit()) if len(digits) >= 2: return digits[:2] if len(digits) == 1: return "0" + digits return "" def _read_countdown_split(box: tuple[int, int, int, int]) -> str: """将倒计时区域分割成"分钟段"和"秒段",分别OCR识别,然后组合为 mm:ss。 优化:更精确的分割方式,避免识别顺序错误。 倒计时格式通常是:XX:XX后开奖,其中前两位是分钟,中间两位是秒。 """ try: x1, y1, x2, y2 = box w = max(1, int(x2 - x1)) # h 变量保留用于将来可能的垂直分割优化 # h = max(1, int(y2 - y1)) # 当前未使用,但保留以备将来使用 # 优化:根据实际布局,倒计时通常是:分钟(2位数字框) + 冒号 + 秒(2位数字框) + 后开奖 # 更精确的分割:前30%为分钟数字框,中间30%为秒数字框(剩余40%包含冒号和"后开奖") # 这样可以更精确地定位到数字区域,避免识别到冒号或"后开奖"文字 seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 # 保存调试截图 try: _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi, ) _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_秒", (x1 + seg1, y1, x1 + seg1 + seg2, y2), analyser.y_pianyi, ) except Exception as e: try: analyser._log_kv( "错误", "保存倒计时调试截图失败", error=str(e), error_type=type(e).__name__, box=box, level="WARNING", ) except Exception: pass # 切割分钟区域(左侧) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) # 切割秒区域(中间,跳过冒号) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi, ) # 并行执行两个OCR识别(使用轻量数字OCR) with ThreadPoolExecutor(max_workers=2) as executor: future_mm = executor.submit( analyser.operation.analyse_pic_digits, "福袋倒计时_分钟", 1 ) future_ss = executor.submit( analyser.operation.analyse_pic_digits, "福袋倒计时_秒", 1 ) mm_raw = future_mm.result() ss_raw = future_ss.result() # 提取数字:分钟和秒都应该是1-2位数字 def _extract_digits(text: str, max_digits: int = 2) -> str: """提取数字,最多max_digits位""" digits = "".join(ch for ch in str(text or "") if ch.isdigit()) if len(digits) > max_digits: return digits[:max_digits] if len(digits) == 1: return "0" + digits return digits mm = _extract_digits(mm_raw, max_digits=2) ss = _extract_digits(ss_raw, max_digits=2) # 分割识别已经分别识别了分钟和秒,顺序是正确的,不需要交换纠正 # 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果) try: mm_int = int(mm) if mm else 0 ss_int = int(ss) if ss else 0 if ss_int >= 60: try: analyser._log_kv( "验证", "分割识别:检测到秒数>=60(可能是识别错误)", mm=mm_int, ss=ss_int, mm_raw=mm_raw, ss_raw=ss_raw, level="WARNING", ) except Exception: pass except Exception as e: try: analyser._log_kv( "错误", "验证倒计时数值失败", error=str(e), error_type=type(e).__name__, mm=mm, ss=ss, level="WARNING", ) except Exception: pass if mm and ss: result = f"{mm}:{ss}" try: analyser._log_kv( "福袋倒计时", "分割识别成功", mm_raw=mm_raw, ss_raw=ss_raw, result=result, ) except Exception as e: try: analyser._log_kv( "错误", "记录倒计时识别成功日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return result except Exception as e: try: analyser._log_kv( "福袋倒计时", "分割识别失败", error=str(e), error_type=type(e).__name__, ) except Exception: pass return "" def _extract_participants_and_clean(text: str): if not text: return 0, 0, "" compact = re.sub(r"\s+", "", str(text)) # 例如:共1份1173人已参与 copies = 0 participants = 0 m = re.search(r"共(\d+)份", compact) if m: copies = int(m.group(1)) m = re.search(r"(\d+)人已参与", compact) if m: participants = int(m.group(1)) # 清理掉份数/参与人数等尾巴,避免干扰关键词匹配 cleaned = re.sub(r"共\d+份", "", compact) cleaned = re.sub(r"\d+人已参与", "", cleaned) return participants, copies, cleaned countdown_box = None if renwu == 2: # 如果是2个任务的 # 优化:扩大Y范围向上,确保包含任务描述(如"观看X分钟"等) # 从1240向上扩展到1100,确保包含任务描述区域 _save_full_screenshot_with_ocr_region( analyser, "福袋内容", (390, 1100, 980, 1470), analyser.y_pianyi ) analyser.cut_pic( 390, 1100, 980, 1470, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字 countdown_box = (390, 1110, 690, 1230) # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 x1, y1, x2, y2 = countdown_box w = max(1, int(x2 - x1)) seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi ) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_秒", (x1 + seg1, y1, x1 + seg1 + seg2, y2), analyser.y_pianyi, ) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) # 优化:增加高度(1560->1580),确保包含"元"等单位文字 _save_full_screenshot_with_ocr_region( analyser, "福袋价值", (390, 1460, 1000, 1580), analyser.y_pianyi ) analyser.cut_pic( 390, 1460, 1000, 1580, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 elif renwu == 1: # 如果是1个任务的 # 优化:扩大Y范围向上,确保包含任务描述 _save_full_screenshot_with_ocr_region( analyser, "福袋内容", (390, 1160, 980, 1530), analyser.y_pianyi ) analyser.cut_pic( 390, 1160, 980, 1530, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度,确保完整 countdown_box = (390, 1180, 690, 1300) # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 x1, y1, x2, y2 = countdown_box w = max(1, int(x2 - x1)) seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi ) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_秒", (x1 + seg1, y1, x1 + seg1 + seg2, y2), analyser.y_pianyi, ) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) # 优化:增加高度,包含单位 _save_full_screenshot_with_ocr_region( analyser, "福袋价值", (390, 1520, 1000, 1630), analyser.y_pianyi ) analyser.cut_pic( 390, 1520, 1000, 1630, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 elif renwu == 3: # 如果是3个任务的 # 优化:扩大Y范围向上,确保包含任务描述 _save_full_screenshot_with_ocr_region( analyser, "福袋内容", (390, 1020, 980, 1390), analyser.y_pianyi ) analyser.cut_pic( 390, 1020, 980, 1390, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度 countdown_box = (390, 1010, 690, 1130) # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 x1, y1, x2, y2 = countdown_box w = max(1, int(x2 - x1)) seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi ) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_秒", (x1 + seg1, y1, x1 + seg1 + seg2, y2), analyser.y_pianyi, ) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) # 优化:增加高度 _save_full_screenshot_with_ocr_region( analyser, "福袋价值", (390, 1380, 1000, 1490), analyser.y_pianyi ) analyser.cut_pic( 390, 1380, 1000, 1490, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 else: # 优化:稍微缩小宽度,增加高度 _save_full_screenshot_with_ocr_region( analyser, "福袋内容", (390, 1600, 980, 1830), analyser.y_pianyi ) analyser.cut_pic( 390, 1600, 980, 1830, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情 # 优化:稍微扩大高度 countdown_box = (390, 1460, 690, 1580) # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 x1, y1, x2, y2 = countdown_box w = max(1, int(x2 - x1)) seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi ) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_秒", (x1 + seg1, y1, x1 + seg1 + seg2, y2), analyser.y_pianyi, ) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) # 优化:增加高度 _save_full_screenshot_with_ocr_region( analyser, "福袋价值", (390, 1820, 1000, 1930), analyser.y_pianyi ) analyser.cut_pic( 390, 1820, 1000, 1930, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 # 准备任务列表区域的截图(用于并行OCR) # 任务列表区域(任务位置:50,1621到1032,1960),用于检测"观看X分钟"任务 try: # 保存任务列表区域的调试截图 _save_full_screenshot_with_ocr_region( analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi ) analyser.cut_pic(50, 1621, 1032, 1960, "", "福袋任务列表", analyser.y_pianyi) except Exception as e: # 任务列表截图失败不影响后续流程,记录日志即可 try: analyser._log_kv( "福袋", "任务列表截图失败,继续后续流程", error=str(e), ) except Exception: pass # 并行执行五个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值 # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 ocr_start_time = time.time() task_list_raw = None fudai_content_raw = None countdown_mm_raw = None countdown_ss_raw = None value_raw = None def ocr_task_list(): """OCR识别任务列表(用于检测观看任务)""" try: return analyser.operation.analyse_pic_word("福袋任务列表", 0) except Exception as e: try: analyser._log_kv( "错误", "OCR识别任务列表失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None def ocr_content(): """OCR识别福袋内容""" try: return analyser.operation.analyse_pic_word("福袋内容", 0) except Exception as e: try: analyser._log_kv( "错误", "OCR识别福袋内容失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None def ocr_countdown_mm(): """OCR识别福袋倒计时分钟(使用轻量数字OCR)""" try: return analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1) except Exception as e: try: analyser._log_kv( "错误", "OCR识别倒计时分钟失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None def ocr_countdown_ss(): """OCR识别福袋倒计时秒(使用轻量数字OCR)""" try: return analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) except Exception as e: try: analyser._log_kv( "错误", "OCR识别倒计时秒失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None def ocr_value(): """OCR识别福袋价值(使用普通OCR)""" try: return analyser.operation.analyse_pic_word("福袋价值", 0) except Exception as e: try: analyser._log_kv( "错误", "OCR识别福袋价值失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 try: with ThreadPoolExecutor(max_workers=5) as executor: future_task_list = executor.submit(ocr_task_list) future_content = executor.submit(ocr_content) future_countdown_mm = executor.submit(ocr_countdown_mm) future_countdown_ss = executor.submit(ocr_countdown_ss) future_value = executor.submit(ocr_value) # 等待所有操作完成 task_list_raw = future_task_list.result() fudai_content_raw = future_content.result() countdown_mm_raw = future_countdown_mm.result() countdown_ss_raw = future_countdown_ss.result() value_raw = future_value.result() # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) if task_list_raw: try: analyser._log_kv( "福袋", "OCR识别任务列表区域", task_list_text=task_list_raw[:200] if task_list_raw else "", ) except Exception as e: try: analyser._log_kv( "错误", "记录任务列表OCR结果日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 检查任务列表中是否包含"观看X分钟"任务 is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) if is_watch_task_in_list: try: analyser._log_kv( "福袋", "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", task_list_text=task_list_raw[:200] if task_list_raw else "", ) except Exception as e: try: analyser._log_kv( "错误", "记录观看任务检测日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 设置标志,让调用方知道这是观看任务 try: analyser._is_watch_task_detected = True except Exception as e: try: analyser._log_kv( "错误", "设置观看任务标志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 直接返回空内容,后续流程会跳过 return "", "", 0, 0, 0.0 ocr_elapsed = time.time() - ocr_start_time try: analyser._log_kv( "性能", "并行OCR识别完成(任务数量已在前置检测中获取)", elapsed_seconds=round(ocr_elapsed, 3), task_count=renwu, ) except Exception as e: try: analyser._log_kv( "错误", "记录OCR性能日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass except Exception as e: # 如果并行执行失败,回退到备用并行执行(使用新的线程池) try: analyser._log_kv( "错误", "并行OCR失败,使用备用并行执行", error=str(e), error_type=type(e).__name__, level="ERROR", ) except Exception: pass # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) try: def ocr_task_list_fallback(): try: return analyser.operation.analyse_pic_word("福袋任务列表", 0) except Exception as e: try: analyser._log_kv( "错误", "备用OCR识别任务列表失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None def ocr_content_fallback(): try: return analyser.operation.analyse_pic_word("福袋内容", 0) except Exception as e: try: analyser._log_kv( "错误", "备用OCR识别福袋内容失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None def ocr_countdown_mm_fallback(): try: return analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1) except Exception as e: try: analyser._log_kv( "错误", "备用OCR识别倒计时分钟失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None def ocr_countdown_ss_fallback(): try: return analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) except Exception as e: try: analyser._log_kv( "错误", "备用OCR识别倒计时秒失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None def ocr_value_fallback(): try: return analyser.operation.analyse_pic_word("福袋价值", 0) except Exception as e: try: analyser._log_kv( "错误", "备用OCR识别福袋价值失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return None with ThreadPoolExecutor(max_workers=5) as executor: future_task_list = executor.submit(ocr_task_list_fallback) future_content = executor.submit(ocr_content_fallback) future_countdown_mm = executor.submit(ocr_countdown_mm_fallback) future_countdown_ss = executor.submit(ocr_countdown_ss_fallback) future_value = executor.submit(ocr_value_fallback) # 等待所有操作完成 task_list_raw = future_task_list.result() fudai_content_raw = future_content.result() countdown_mm_raw = future_countdown_mm.result() countdown_ss_raw = future_countdown_ss.result() value_raw = future_value.result() # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) if task_list_raw: try: analyser._log_kv( "福袋", "OCR识别任务列表区域(备用并行)", task_list_text=task_list_raw[:200] if task_list_raw else "", ) except Exception as e: try: analyser._log_kv( "错误", "记录备用任务列表OCR结果日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 检查任务列表中是否包含"观看X分钟"任务 is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) if is_watch_task_in_list: try: analyser._log_kv( "福袋", "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", task_list_text=task_list_raw[:200] if task_list_raw else "", ) except Exception as e: try: analyser._log_kv( "错误", "记录备用观看任务检测日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 设置标志,让调用方知道这是观看任务 try: analyser._is_watch_task_detected = True except Exception as e: try: analyser._log_kv( "错误", "设置备用观看任务标志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 直接返回空内容,后续流程会跳过 return "", "", 0, 0, 0.0 except Exception as fallback_error: # 如果备用并行执行也失败,使用串行执行作为最后兜底 try: analyser._log_kv( "错误", "备用并行OCR也失败,使用串行执行作为最后兜底", error=str(fallback_error), error_type=type(fallback_error).__name__, level="ERROR", ) except Exception: pass # 串行执行所有OCR(包括任务列表OCR) try: task_list_raw = analyser.operation.analyse_pic_word("福袋任务列表", 0) # 检查任务列表中是否包含"观看X分钟"任务 if task_list_raw: is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) if is_watch_task_in_list: try: analyser._is_watch_task_detected = True except Exception as e: try: analyser._log_kv( "错误", "设置串行观看任务标志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return "", "", 0, 0, 0.0 except Exception as e: try: analyser._log_kv( "错误", "串行OCR识别任务列表失败", error=str(e), error_type=type(e).__name__, level="ERROR", ) except Exception: pass fudai_content_raw = analyser.operation.analyse_pic_word("福袋内容", 0) countdown_mm_raw = analyser.operation.analyse_pic_digits( "福袋倒计时_分钟", 1 ) countdown_ss_raw = analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) value_raw = analyser.operation.analyse_pic_word("福袋价值", 0) # 先检查原始OCR内容是否是"观看X分钟"任务(在清理之前检查,避免丢失关键信息) is_watch_task = False if fudai_content_raw: try: is_watch_task = is_watch_task_fudai(str(fudai_content_raw)) if is_watch_task: try: analyser._log_kv( "福袋", "OCR识别到'观看X分钟'类任务,直接跳过后续处理", raw_content=( fudai_content_raw[:100] if fudai_content_raw else "" ), ) except Exception as e: try: analyser._log_kv( "错误", "记录观看任务检测日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 设置标志,让调用方知道这是观看任务 try: analyser._is_watch_task_detected = True except Exception as e: try: analyser._log_kv( "错误", "设置观看任务标志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 直接返回空内容,后续流程会跳过 return "", "", 0, 0, 0.0 except Exception as e: try: analyser._log_kv( "错误", "检查观看任务失败", error=str(e), error_type=type(e).__name__, raw_content=fudai_content_raw[:100] if fudai_content_raw else "", level="WARNING", ) except Exception: pass participants, copies, fudai_content_text = _extract_participants_and_clean( fudai_content_raw ) # 如果清理后的内容中没有检测到,但原始内容中检测到了,使用原始内容再次确认 if not is_watch_task and fudai_content_text: try: is_watch_task = is_watch_task_fudai(fudai_content_text) if is_watch_task: try: analyser._log_kv( "福袋", "OCR识别到'观看X分钟'类任务(清理后检测),直接跳过后续处理", content=fudai_content_text[:100] if fudai_content_text else "", ) except Exception: pass # 设置标志 try: analyser._is_watch_task_detected = True except Exception: pass # 直接返回空内容,后续流程会跳过 return "", "", 0, 0, 0.0 except Exception: pass # 输出福袋内容(使用明确的格式,便于GUI解析) content_for_log = fudai_content_text if fudai_content_text else "未识别到" analyser._log_kv( "福袋", f"识别福袋内容:{content_for_log[:100]}", # 在消息中直接包含内容,确保可见 level="INFO", content=content_for_log, # 同时作为字段输出 ) # 记录进入直播间到识别到福袋的耗时(仅记录一次) try: if getattr(analyser, "_enter_live_ts", 0.0) and not getattr( analyser, "_enter_live_fudai_logged", False ): try: secs = float(time.time() - float(analyser._enter_live_ts or 0.0)) except Exception: secs = -1.0 reason = str(getattr(analyser, "_enter_live_reason", "") or "") analyser._log_kv( "性能", "进入直播间到识别福袋耗时", seconds=round(secs, 2), enter_reason=reason, ) try: analyser._enter_live_fudai_logged = True except Exception: pass if copies: analyser._log_kv( "福袋", "识别福袋信息", copies=copies, participants=participants if participants else 0, ) except Exception: pass # 倒计时:直接使用分割OCR结果(分钟+秒),不再使用完整OCR time_text = "" # 初始化为空字符串,确保类型为 str try: # 提取数字:分钟和秒都应该是1-2位数字 def _extract_digits(text: str, max_digits: int = 2) -> str: """提取数字,最多max_digits位""" digits = "".join(ch for ch in str(text or "") if ch.isdigit()) if len(digits) > max_digits: return digits[:max_digits] if len(digits) == 1: return "0" + digits return digits mm = _extract_digits(countdown_mm_raw, max_digits=2) if countdown_mm_raw else "" ss = _extract_digits(countdown_ss_raw, max_digits=2) if countdown_ss_raw else "" # OCR结果验证:检查倒计时识别结果是否为空 if not countdown_mm_raw and not countdown_ss_raw: try: analyser._log_kv( "验证", "倒计时OCR结果完全为空", level="WARNING", ) except Exception: pass elif not mm or not ss: try: analyser._log_kv( "验证", "倒计时OCR结果不完整", mm_raw=countdown_mm_raw, ss_raw=countdown_ss_raw, mm_extracted=mm, ss_extracted=ss, level="WARNING", ) except Exception: pass # 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果) try: mm_int = int(mm) if mm else 0 ss_int = int(ss) if ss else 0 # 数值范围验证 if mm_int < 0 or mm_int >= 60: try: analyser._log_kv( "验证", "倒计时分钟数值超出合理范围", mm=mm_int, mm_raw=countdown_mm_raw, level="WARNING", ) except Exception: pass if ss_int >= 60: try: analyser._log_kv( "验证", "倒计时秒数>=60(可能是识别错误)", mm=mm_int, ss=ss_int, mm_raw=countdown_mm_raw, ss_raw=countdown_ss_raw, level="WARNING", ) except Exception: pass elif ss_int < 0: try: analyser._log_kv( "验证", "倒计时秒数<0(可能是识别错误)", ss=ss_int, ss_raw=countdown_ss_raw, level="WARNING", ) except Exception: pass except Exception as e: try: analyser._log_kv( "错误", "验证倒计时数值失败", error=str(e), error_type=type(e).__name__, mm=mm, ss=ss, level="WARNING", ) except Exception: pass if mm and ss: time_text = f"{mm}:{ss}" try: analyser._log_kv( "福袋倒计时", "分割识别成功", mm_raw=countdown_mm_raw, ss_raw=countdown_ss_raw, result=time_text, ) except Exception: pass else: # 识别失败,time_text 保持为空字符串 try: analyser._log_kv( "福袋倒计时", "分割识别失败(分钟或秒为空)", mm_raw=countdown_mm_raw, ss_raw=countdown_ss_raw, ) except Exception: pass except Exception as e: # 异常时,time_text 保持为空字符串 try: analyser._log_kv( "福袋倒计时", "分割识别异常", error=str(e), error_type=type(e).__name__, ) except Exception: pass analyser._log_kv( "福袋", "识别倒计时", countdown=time_text if time_text else "未识别到" ) prize_value_yuan = extract_prize_value_yuan(value_raw) # OCR结果验证:检查价值识别结果 if not value_raw: try: analyser._log_kv( "验证", "价值OCR结果为空", level="WARNING", ) except Exception: pass elif prize_value_yuan: # 验证价值数值是否合理 try: value_float = float(prize_value_yuan) if value_float < 0: try: analyser._log_kv( "验证", "价值数值<0(可能是识别错误)", value_yuan=prize_value_yuan, value_raw=value_raw[:50] if value_raw else "", level="WARNING", ) except Exception: pass elif value_float > 100000: # 价值超过10万可能不合理 try: analyser._log_kv( "验证", "价值数值异常大(可能是识别错误)", value_yuan=prize_value_yuan, value_raw=value_raw[:50] if value_raw else "", level="WARNING", ) except Exception: pass except Exception as e: try: analyser._log_kv( "错误", "验证价值数值失败", error=str(e), error_type=type(e).__name__, value_raw=value_raw[:50] if value_raw else "", level="WARNING", ) except Exception: pass if float(prize_value_yuan).is_integer(): show_value = int(prize_value_yuan) else: show_value = prize_value_yuan analyser._log_kv("福袋", "识别奖品价值", value_yuan=show_value) else: # value_raw不为空但提取失败 try: analyser._log_kv( "验证", "价值OCR结果无法解析", value_raw=value_raw[:100] if value_raw else "", level="WARNING", ) except Exception: pass return fudai_content_text, time_text, participants, copies, prize_value_yuan def check_contain(analyser, contains: str = "") -> bool: """检查福袋内容是否命中“黑名单”关键词(只保留黑名单逻辑,不再使用白名单)。 返回值语义(调整后): - True : “建议丢弃”(内容命中黑名单 contains_not_want) - False : “可以保留”(未命中黑名单,或凌晨时段不做内容过滤) """ try: hour = int(analyser.operation.get_current_hour()) except Exception: hour = -1 # 凌晨:不对内容做要求(不过滤) if 0 < hour < 7: try: analyser._log_kv( "筛选", "凌晨不过滤福袋内容", hour=hour, contains=contains[:50] if contains else "", ) except Exception: pass return False try: for contain in getattr(analyser, "contains_not_want", []) or []: if contain and contain in (contains or ""): try: analyser._log_kv( "筛选", "福袋内容命中黑名单,将丢弃", keyword=contain, contains=contains[:80] if contains else "", ) except Exception: pass return True try: analyser._log_kv( "筛选", "福袋内容未命中黑名单,保留", contains=contains[:80] if contains else "", ) except Exception: pass return False except Exception: # 容错:异常时不过滤 try: analyser._log_kv( "筛选", "check_contain 异常,默认保留", contains=contains[:80] if contains else "", ) except Exception: pass return False def attend_choujiang(analyser) -> bool: """点击参与抽奖。""" analyser.last_attend_fail_reason = "" click_times = 0 while click_times < 2: analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字 # 优化:尝试多种OCR模式提高精准度(优先保证精准) attend_button_text = str( analyser.operation.analyse_pic_word("参与按钮", 0) or "" ) if not attend_button_text or not any( k in attend_button_text for k in ( "参与成功", "还需看播", "评论", "参与抽奖", "开始观看", "参与", "加入粉丝团", "粉丝团", ) ): attend_button_text = str( analyser.operation.analyse_pic_word("参与按钮", 1) or "" ) analyser._log_kv("参与", "识别参与按钮", text=attend_button_text) if "参与成功" 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 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 ("活动已结束" 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 "还需看播" 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 "无法参与" in attend_button_text: analyser._log_kv("参与", "无法参与(条件不满足)", result="无法参与") analyser.click(500, 470) analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") return False elif "时长不足" in attend_button_text: analyser._log_kv("参与", "无法参与(看播时长不足)", result="时长不足") analyser.click(500, 470) analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") return False elif "评论" 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 "参与抽奖" 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 # 设置等待开奖标志,避免参与后立即切换直播间 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 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 "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text: # 需要粉丝团门槛:先点击参与按钮,再使用OCR识别"加入粉丝团"按钮位置并点击,最后关闭详情页 analyser.last_attend_fail_reason = "fansclub_required" # 保存debug截图:标注OCR识别区域(参与按钮区域) try: import douyin_screenshot_manager pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): 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): img = Image.open(pic_path) img = img.convert("RGB") 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 douyin_screenshot_manager pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): 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(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识别区域以便更容易识别:(150, 1900, 950, 2200) ocr_click_success = 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 = "" fansclub_bbox = None try: pic_path = analyser.operation._find_pic_path("加入粉丝团按钮") if pic_path and os.path.exists(pic_path): img = Image.open(pic_path) img = img.convert("RGB") 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: # 启用自动加入:等待更长时间,让加入流程完成 analyser.operation.delay(5.0) analyser._log_kv( "参与", "已启用自动加入粉丝团,等待加入流程完成", wait_seconds=5.0, ) else: # 未启用自动加入:等待较短时间后返回 analyser.operation.delay(3.0) analyser._log_kv( "参与", "未启用自动加入粉丝团,等待后返回", wait_seconds=3.0, ) # 加入粉丝团成功后,点击 (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) 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): img = Image.open(pic_path) img = img.convert("RGB") 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: 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), ) analyser.operation.delay(3.0) except Exception: # 回退到优化后的坐标(粉丝团加入按钮) try: analyser.click(540, 2006) # 第一次点击 analyser.operation.delay(0.5) analyser.click( 540, 2006 ) # 第二次点击(连续点击两次确保成功) # 两次点击后,立即点击 (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), ) analyser.operation.delay(3.0) except Exception: # 最后回退到旧坐标 try: analyser.click(500, 2060) analyser.operation.delay(3.0) except Exception: pass else: # 未启用自动加入,直接返回 analyser._log_kv( "参与", "仍在粉丝团加入页,未启用自动加入,返回" ) try: analyser.operation.click_back( analyser.device_id ) analyser.operation.delay(1) except Exception: pass elif st_after == "FUDai_DETAIL": # 已经回到福袋详情页,说明加入成功 analyser._log_kv( "参与", "已回到福袋详情页,加入流程可能已完成" ) return True elif st_after in ( "IN_LIVE_ROOM", "FOLLOW_LIST", "LIVE_LIST", ): # 如果之前是在粉丝团加入页,现在显示在直播间,可能是误判 # 实际上可能还在加入成功的页面,需要点击返回键 analyser._log_kv( "参与", "点击加入粉丝团后显示在直播间(可能误判),尝试点击返回键", stage_before="FANSCLUB_JOIN", stage_after=st_after, ) try: analyser.operation.click_back(analyser.device_id) analyser.operation.delay(1.0) # 点击返回后再次诊断,看是否回到福袋详情页 try: analyser.operation.get_screenshot( analyser.device_id ) st_after_back, seen_after_back = ( analyser._diagnose_stage_from_current_screen() ) analyser._log_kv( "参与", "点击返回后重新诊断阶段", stage_after_back=st_after_back, seen_after_back=seen_after_back, ) if st_after_back == "FUDai_DETAIL": analyser._log_kv( "参与", "点击返回后已回到福袋详情页" ) return True elif st_after_back in ( "IN_LIVE_ROOM", "FOLLOW_LIST", "LIVE_LIST", ): analyser._log_kv( "参与", "点击返回后确实回到直播间,停止继续返回", stage=st_after_back, ) return False except Exception: pass except Exception: pass return False else: # 其他阶段,尝试返回 analyser._log_kv( "参与", "点击后进入其他阶段,尝试返回", stage=st_after, ) try: analyser.operation.click_back(analyser.device_id) analyser.operation.delay(1) except Exception: pass except Exception as e: # 诊断失败,保守处理:如果启用了自动加入,不返回;否则返回 analyser._log_kv("参与", "重新诊断阶段失败", error=str(e)) if not auto_join_enabled: try: analyser.operation.click_back(analyser.device_id) analyser.operation.delay(1) except Exception: pass continue # 已经回到直播间/列表时:尝试重新打开福袋详情页 if st in ("IN_LIVE_ROOM", "FOLLOW_LIST", "LIVE_LIST"): analyser._log_kv( "参与", "已离开福袋详情:尝试重新打开福袋详情页", stage=st, seen=seen, ) # 尝试重新打开福袋详情页 try: # 延迟导入避免循环导入 import douyin_flow_control room_pos_ref = [0] opened = douyin_flow_control.find_and_open_fudai_detail( analyser, room_pos_ref ) if opened: # 验证是否成功打开福袋详情页 analyser.operation.delay(0.5) try: analyser.operation.get_screenshot( analyser.device_id ) st_after, seen_after = ( analyser._diagnose_stage_from_current_screen() ) if st_after == "FUDai_DETAIL": analyser._log_kv( "参与", "重新打开福袋详情页成功", stage=st_after, ) return True else: analyser._log_kv( "参与", "重新打开福袋详情页后未在详情页", stage=st_after, seen=seen_after, ) except Exception as e: analyser._log_kv( "参与", "重新打开后验证阶段失败", error=str(e), ) except Exception as e: analyser._log_kv( "参与", "重新打开福袋详情页失败", error=str(e) ) # 如果重新打开失败,返回 False return False # 其它未知弹窗:尝试一次返回 analyser._log_kv( "参与", "粉丝团流程:尝试返回", stage=st, seen=seen ) try: analyser.operation.click_back(analyser.device_id) except Exception: pass analyser.operation.delay(1) return False ok = _recover_to_fudai_detail_after_fansclub() if ok: analyser._log_kv( "参与", "粉丝团流程结束:已回到福袋详情", result="回到详情" ) return attend_choujiang(analyser) analyser._log_kv( "参与", "粉丝团流程失败:未回到福袋详情", result="粉丝团门槛仍未解决" ) analyser.operation.delay(1.2) try: analyser.operation.get_screenshot(analyser.device_id) except Exception: pass if analyser.check_in_fudai_detail(): analyser._log_kv( "参与", "粉丝团流程失败:仍在详情页,执行关闭", stage="FUDai_DETAIL" ) try: analyser.click(500, 470) except Exception: pass analyser.operation.delay(0.8) else: analyser._log_kv( "参与", "粉丝团流程失败:已不在详情页,视为已退出", stage="UNKNOWN" ) try: analyser._log_kv( "参与", "粉丝团门槛仍未解决", result="粉丝团门槛仍未解决" ) except Exception: pass return False else: # 未识别到任何可用文案:再尝试一次 analyser._log_kv( "参与", "未识别到可用参与按钮文案", text=attend_button_text or "" ) click_times += 1 analyser.operation.delay(1) continue analyser._log_kv("参与", "参与抽奖多次点击失败", result="多次失败") return False def check_lucky_draw_result(analyser): """判定福袋抽奖的结果。""" # 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过) cache_key = ("lucky_draw_result", 0) now = time.time() need_screenshot = True # 检查缓存是否有效 if cache_key in analyser._ocr_cache: cached_ts, cached_result = analyser._ocr_cache[cache_key] if ( (now - cached_ts) < 0.5 and cached_result and ("没有抽中" in cached_result or "抽中福袋" in cached_result) ): need_screenshot = False if need_screenshot: analyser._shot_and_diagnose( "开奖结果", "识别是否中奖/未中奖", analyser.device_id ) # 优化:扩大区域(300-800, 600-800),确保包含完整的开奖结果文字"没有抽中福袋" analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果") # 没有抽中福袋位置 # 诊断开始时间 t0 = time.time() # 检查缓存 if cache_key in analyser._ocr_cache: cached_ts, cached_result = analyser._ocr_cache[cache_key] if (now - cached_ts) < analyser._ocr_cache_ttl: lucky_draw_result = cached_result else: lucky_draw_result = str( analyser.operation.analyse_pic_word("抽奖结果", 0) or "" ) if not lucky_draw_result or ( "没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result ): lucky_draw_result = str( analyser.operation.analyse_pic_word("抽奖结果", 1) or "" ) analyser._ocr_cache[cache_key] = (now, lucky_draw_result) else: lucky_draw_result = str( analyser.operation.analyse_pic_word("抽奖结果", 0) or "" ) if not lucky_draw_result or ( "没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result ): lucky_draw_result = str( analyser.operation.analyse_pic_word("抽奖结果", 1) or "" ) analyser._ocr_cache[cache_key] = (now, lucky_draw_result) dur = time.time() - t0 try: brief = (lucky_draw_result or "").replace("\n", " ")[:140] except Exception: brief = "" try: analyser._log_kv( "开奖诊断", "lucky_draw_result", brief=brief, ocr_dur=round(dur, 2), ) except Exception: pass if "没有抽中" in (lucky_draw_result or ""): # 速度优化:使用缓存避免重复OCR cache_key2 = ("no_award_confirm", 0) dur2 = 0.0 # Initialize dur2 to avoid unbound variable if cache_key2 in analyser._ocr_cache: cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2] if (now - cached_ts2) < analyser._ocr_cache_ttl: no_award_confirm = cached_result2 else: t1 = time.time() analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) dur2 = time.time() - t1 else: t1 = time.time() analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) dur2 = time.time() - t1 try: brief2 = (no_award_confirm or "").replace("\n", " ")[:140] except Exception: brief2 = "" try: analyser._log_kv( "开奖诊断", "no_award_confirm", brief=brief2, ocr_dur=round(dur2, 2), ) except Exception: pass if "我知道了" in (no_award_confirm or ""): return 1 elif "领取并使用" in (no_award_confirm or ""): return 2 return 3 elif "抽中福袋" in (lucky_draw_result or ""): try: analyser._log_kv("开奖诊断", "恭喜中奖了", result_text=brief) except Exception: pass # 速度优化:优先检测第一个常见位置,命中即返回 y_value = [1438, 1490] for y in y_value: cache_key3 = (f"have_read_user_agreement_{y}", 0) have_read_user_agreement = None dur3 = 0.0 if cache_key3 in analyser._ocr_cache: cached_ts3, cached_result3 = analyser._ocr_cache[cache_key3] if (now - cached_ts3) < analyser._ocr_cache_ttl: have_read_user_agreement = cached_result3 if not have_read_user_agreement: t2 = time.time() analyser.cut_pic(280, y - 35, 670, y + 35, "", f"已阅读用户协议_{y}") have_read_user_agreement = analyser.operation.analyse_pic_word( f"已阅读用户协议_{y}" ) analyser._ocr_cache[cache_key3] = ( time.time(), have_read_user_agreement, ) dur3 = time.time() - t2 try: brief3 = (have_read_user_agreement or "").replace("\n", " ")[:140] except Exception: brief3 = "" try: analyser._log_kv( "开奖诊断", "have_read_user_agreement", brief=brief3, ocr_dur=round(dur3, 2), y=y, ) except Exception: pass if "已阅读" in (have_read_user_agreement or ""): return y return False def check_have_reward_notice_confirm(analyser) -> bool: """判断是否有领奖的二次确认提醒。""" analyser._shot_and_diagnose("领奖确认", "识别是否有我知道了", analyser.device_id) analyser.cut_pic(370, 1350, 680, 1440, "", "奖励通知确认") reward_notice_confirm = analyser.operation.analyse_pic_word("奖励通知确认", 1) if "我知道了" in (reward_notice_confirm or ""): try: analyser._log_kv( "开奖诊断", "存在奖品领取提醒", text=(reward_notice_confirm or "")[:80], ) except Exception: pass return True return False def check_in_order_confirm_page(analyser) -> bool: """判断是否在中奖下单后的购买成功的页面。""" analyser._shot_and_diagnose("下单结果", "识别是否购买成功页", analyser.device_id) analyser.cut_pic(370, 120, 700, 220, "", "订单确认") order_confirm = analyser.operation.analyse_pic_word("订单确认") if "购买成功" in (order_confirm or ""): try: analyser._log_kv( "开奖诊断", "订单确认页面:购买成功", text=(order_confirm or "")[:80], ) except Exception: pass return True return False def get_reward(analyser, reward_y: int = 0) -> None: """中奖后领奖然后返回。""" analyser.operation.save_reward_pic(analyser.device_id) try: analyser._log_kv("领奖", "保存中奖截图", step="save_reward_pic") except Exception: pass analyser.click(243, reward_y) # 勾选协议 analyser.operation.delay(1) analyser.click(540, reward_y - 140) # 点击领取 try: analyser._log_kv("领奖", "勾选协议并点击领取", reward_y=reward_y) except Exception: pass analyser.operation.delay(5) analyser.click(886, 2170) # 点击下单 try: analyser._log_kv("领奖", "点击下单") except Exception: pass analyser.operation.delay(10) # 循环检查下单结果,增加保护避免极端死循环 max_checks = 5 checks = 0 while checks < max_checks and check_in_order_confirm_page(analyser): checks += 1 analyser.operation.click_back(analyser.device_id) try: analyser._log_kv("领奖", "点击回退按钮", check_round=checks) except Exception: pass analyser.operation.delay(4) try: analyser._log_kv("领奖", "下完单返回到直播间", checks=checks) except Exception: pass analyser.operation.delay(4) if check_lucky_draw_result(analyser): try: analyser._log_kv("领奖", "领奖弹窗未关闭,准备关闭") except Exception: pass analyser.click(540, reward_y + 180) try: analyser._log_kv( "领奖", "点击关闭领奖弹窗", x=540, y=(reward_y + 180) * analyser.resolution_ratio_y // 2400, ) except Exception: pass analyser.operation.delay(2) analyser.operation.save_reward_pic(analyser.device_id) try: analyser._log_kv("领奖", "保存关闭领奖弹窗后的截图") except Exception: pass analyser.operation.click_back(analyser.device_id) analyser.operation.delay(2) if check_have_reward_notice_confirm(analyser): try: analyser._log_kv("领奖", "提醒领奖弹窗未关闭,点击我知道了") except Exception: pass analyser.click(540, 1400) analyser.operation.delay(2) try: analyser._log_kv("领奖", "关闭中奖提醒后等待", wait_seconds=30) except Exception: pass analyser.operation.delay(30) def is_watch_task_fudai(content: str) -> bool: """检测是否为"观看X分钟"类任务福袋。 参数: content: 福袋内容文本 返回: True 表示是"观看X分钟"类任务,应放弃 False 表示不是此类任务 """ if not content: return False try: import re # 将内容转换为字符串并去除空白 content_str = re.sub(r"\s+", "", str(content)) # 中文数字字符 chinese_num_chars = "零一二三四五六七八九十百千两" # 匹配模式1:观看/看 + (可选"直播") + 数字或中文数字 + 分钟 patt1 = rf"(?:观看|看)(?:直播)?(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟" # 匹配模式2:需要观看/需要看 + 数字或中文数字 + 分钟 patt2 = rf"需要(?:观看|看)(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟" # 匹配模式3:观看时长 + 数字或中文数字 + 分钟 patt3 = rf"观看时长(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟" # 匹配模式4:看播 + 数字或中文数字 + 分钟 patt4 = rf"看播(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟" # 检查是否匹配任一模式 patterns = [patt1, patt2, patt3, patt4] for patt in patterns: if re.search(patt, content_str): return True return False except Exception: return False def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]: """根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。 返回: (skip, reason) 其中 reason 为简单文字原因,便于日志查看。 """ start_time = time.time() # 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if not needswitch: try: analyser._log_kv( "筛选", "单间模式:忽略所有福袋阈值配置,直接参与", needswitch=0, ) except Exception: pass return False, "single_room_mode" if not isinstance(detail, tuple) or len(detail) < 6: return False, "detail_tuple_invalid" content = str(detail[0] or "") # 优先检查是否为"观看X分钟"类任务:若是,直接放弃 if is_watch_task_fudai(content): try: analyser._log_kv( "筛选", "检测到'观看X分钟'类任务,自动放弃", content=content[:80] if content else "", reason="watch_task_detected", ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "筛选", "should_skip_fudai_by_config完成(观看任务)", elapsed_seconds=round(elapsed, 2), ) return True, "watch_task_detected" time_text = str(detail[1] or "") try: participants = int(detail[2] or 0) except Exception: participants = 0 try: copies = int(detail[3] or 0) except Exception: copies = 0 try: prize_value_yuan = float(detail[4] or 0.0) except Exception: prize_value_yuan = 0.0 cd_start, cd_end = None, None if isinstance(detail[5], (tuple, list)) and len(detail[5]) >= 2: cd_start, cd_end = detail[5][0], detail[5][1] now = time.time() remain_seconds = None try: if isinstance(cd_end, (int, float)) and cd_end > now: remain_seconds = float(cd_end - now) try: analyser._log_kv( "筛选", "倒计时计算成功", cd_end=cd_end, now=now, 剩余秒数=remain_seconds, ) except Exception: pass else: try: analyser._log_kv( "筛选", "倒计时计算失败或已过期", cd_end=cd_end, now=now, cd_end类型=type(cd_end).__name__, cd_end大于now=( bool(isinstance(cd_end, (int, float)) and cd_end > now) if isinstance(cd_end, (int, float)) else False ), ) except Exception: pass except Exception as e: remain_seconds = None try: analyser._log_kv( "筛选", "倒计时计算异常", 异常=str(e), 异常类型=type(e).__name__, ) except Exception: pass # 读取配置阈值 try: min_value = float(getattr(analyser, "min_prize_value_yuan", 0.0) or 0.0) except Exception: min_value = 0.0 try: min_participants = int(getattr(analyser, "min_participants", 0) or 0) except Exception: min_participants = 0 try: max_participants = int(getattr(analyser, "max_participants", 0) or 0) except Exception: max_participants = 0 skip_if_gt = 0 # Initialize before try block try: skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0) except Exception: skip_if_gt = 0 skip_if_lt = 0 # Initialize before try block try: skip_if_lt = int(getattr(analyser, "skip_if_countdown_lt_seconds", 0) or 0) except Exception: skip_if_lt = 0 # 记录所有配置值和实际值,便于调试 try: analyser._log_kv( "筛选", "should_skip_fudai_by_config 开始检查", 配置_最小价值=min_value, 配置_最小参与人数=min_participants, 配置_最大参与人数=max_participants, 配置_倒计时大于秒数=skip_if_gt, 配置_倒计时小于秒数=skip_if_lt, 实际_价值=prize_value_yuan, 实际_参与人数=participants, 实际_份数=copies, 实际_剩余秒数=int(remain_seconds) if remain_seconds is not None else None, 实际_内容=content[:60] if content else "", ) except Exception: pass # 1) 价值过滤 if min_value > 0: if prize_value_yuan > 0: if prize_value_yuan < min_value: try: analyser._log_kv( "筛选", "价值过滤:丢弃", 原因=f"value_lt_{min_value}", 实际价值=prize_value_yuan, 配置最小价值=min_value, ) except Exception: pass return True, f"value_lt_{min_value}" else: try: analyser._log_kv( "筛选", "价值过滤:通过", 实际价值=prize_value_yuan, 配置最小价值=min_value, ) except Exception: pass else: try: analyser._log_kv( "筛选", "价值过滤:跳过(未识别到价值)", 实际价值=prize_value_yuan, ) except Exception: pass # 2) 参与人数过滤 if min_participants > 0: if participants > 0: if participants < min_participants: try: analyser._log_kv( "筛选", "参与人数过滤:丢弃(小于最小值)", 原因=f"participants_lt_{min_participants}", 实际参与人数=participants, 配置最小参与人数=min_participants, ) except Exception: pass return True, f"participants_lt_{min_participants}" else: try: analyser._log_kv( "筛选", "参与人数过滤:通过(最小值检查)", 实际参与人数=participants, 配置最小参与人数=min_participants, ) except Exception: pass else: try: analyser._log_kv( "筛选", "参与人数过滤:跳过(未识别到参与人数)", 实际参与人数=participants, ) except Exception: pass if max_participants > 0: if participants > 0: if participants > max_participants: try: analyser._log_kv( "筛选", "参与人数过滤:丢弃(大于最大值)", 原因=f"participants_gt_{max_participants}", 实际参与人数=participants, 配置最大参与人数=max_participants, ) except Exception: pass return True, f"participants_gt_{max_participants}" else: try: analyser._log_kv( "筛选", "参与人数过滤:通过(最大值检查)", 实际参与人数=participants, 配置最大参与人数=max_participants, ) except Exception: pass # 3) 倒计时过滤 # 3.1) 倒计时小于阈值:直接丢弃(不参与) if skip_if_lt > 0: if remain_seconds is not None: if remain_seconds < skip_if_lt: try: analyser._log_kv( "筛选", "倒计时过滤:丢弃(剩余秒数小于阈值,不参与)", 原因=f"countdown_lt_{skip_if_lt}", 实际剩余秒数=int(remain_seconds), 配置阈值秒数=skip_if_lt, 判断条件=f"{remain_seconds} < {skip_if_lt} = True", ) except Exception: pass return True, f"countdown_lt_{skip_if_lt}" # 3.2) 倒计时大于阈值:不参与(但如果价值达到高价值阈值,可以预约) # 注意:这个过滤在 basic_join_decision 中会被特殊处理,如果价值达到高价值阈值,即使倒计时大于阈值也会记录预约 if skip_if_gt > 0: try: analyser._log_kv( "筛选", "倒计时过滤:开始检查", 配置阈值秒数=skip_if_gt, 实际剩余秒数=( int(remain_seconds) if remain_seconds is not None else None ), 是否有倒计时数据=remain_seconds is not None, 说明="如果剩余秒数大于阈值,则不参与(但高价值福袋可预约)", ) except Exception: pass if remain_seconds is not None: # 如果剩余秒数 > 阈值,就丢弃(不参与) if remain_seconds > skip_if_gt: try: analyser._log_kv( "筛选", "倒计时过滤:丢弃(剩余秒数大于阈值,不参与)", 原因=f"countdown_gt_{skip_if_gt}", 实际剩余秒数=int(remain_seconds), 配置阈值秒数=skip_if_gt, 判断条件=f"{remain_seconds} > {skip_if_gt} = True", 说明="如果价值达到高价值阈值,basic_join_decision 会记录预约", ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "筛选", "should_skip_fudai_by_config完成(倒计时大于阈值)", elapsed_seconds=round(elapsed, 2), ) return True, f"countdown_gt_{skip_if_gt}" else: try: analyser._log_kv( "筛选", "倒计时过滤:通过(剩余秒数小于等于阈值,可以参与)", 实际剩余秒数=int(remain_seconds), 配置阈值秒数=skip_if_gt, 判断条件=f"{remain_seconds} > {skip_if_gt} = False", ) except Exception: pass else: try: analyser._log_kv( "筛选", "倒计时过滤:跳过(未识别到倒计时或倒计时已过期)", 剩余秒数=remain_seconds, cd_start=cd_start, cd_end=cd_end, now=now, ) except Exception: pass else: try: analyser._log_kv( "筛选", "倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)", 配置阈值秒数=skip_if_gt, ) except Exception: pass # 4) 内容关键词过滤(复用 check_contain 逻辑) content_check_result = check_contain(analyser, content) if content_check_result: try: analyser._log_kv( "筛选", "内容关键词过滤:丢弃", 原因="content_not_wanted", 内容=content[:60] if content else "", ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "筛选", "should_skip_fudai_by_config完成(内容关键词过滤)", elapsed_seconds=round(elapsed, 2), ) return True, "content_not_wanted" else: try: analyser._log_kv( "筛选", "内容关键词过滤:通过", 内容=content[:60] if content else "", ) except Exception: pass try: analyser._log_kv( "筛选", "should_skip_fudai_by_config 通过(所有检查项均通过)", content=content[:60] if content else "", participants=participants, copies=copies, value_yuan=prize_value_yuan, remain_seconds=int(remain_seconds) if remain_seconds is not None else None, ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "筛选", "should_skip_fudai_by_config完成(通过)", elapsed_seconds=round(elapsed, 2), ) return False, "ok" def basic_join_decision(analyser: Any, detail: Tuple) -> bool: """基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。 返回: True 表示已经参与或已处理完成; False 表示未参与(例如被配置筛掉或参与失败)。 """ # time 模块在文件开头已导入 start_time = time.time() # 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值 content = "" prize_value_yuan = 0.0 countdown_tuple = None try: if isinstance(detail, tuple) and len(detail) >= 6: content = str(detail[0] or "") prize_value_yuan = float(detail[4] or 0.0) countdown_tuple = detail[5] except Exception: pass # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 try: last_status = getattr(analyser, "_last_fudai_detail_status", "") if last_status == "coupon_popup": try: analyser._log_kv( "参与", "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(优惠券弹窗)", elapsed_seconds=round(elapsed, 2), ) return False elif last_status == "validation_failed": try: analyser._log_kv( "参与", "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(验证失败)", elapsed_seconds=round(elapsed, 2), ) return False except Exception: pass # 检查是否是预约回退后强制参与(跳过验证) force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) if force_attend: try: analyser._log_kv( "参与", "basic_join_decision:检测到强制参与标志(预约回退),跳过验证,直接参与", ) except Exception: pass # 跳过验证,直接进入参与逻辑 else: # 额外验证:使用验证函数检查数据合理性 try: # 在函数开头导入,避免作用域问题 import douyin_fudai_detail as dfd_module is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser) if not is_valid: try: analyser._log_kv( "参与", "basic_join_decision:福袋详情数据验证失败,识别出错", validation_reason=reason, content=content[:50] if content else "", prize_value_yuan=prize_value_yuan, ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(验证失败)", elapsed_seconds=round(elapsed, 2), ) return False except Exception: pass # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误 if not content and prize_value_yuan == 0.0: try: analyser._log_kv( "参与", "basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理", content=content, prize_value_yuan=prize_value_yuan, ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(无效详情)", elapsed_seconds=round(elapsed, 2), ) return False # 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if not needswitch: try: analyser._log_kv( "参与", "basic_join_decision:单间模式,忽略阈值与预约逻辑,直接参与当前福袋", ) except Exception: pass result = attend_choujiang(analyser) elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(单间模式参与)", elapsed_seconds=round(elapsed, 2), result=result, ) return result # 检查是否启用高价值预约,以及价值是否达到阈值 try: high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False)) except Exception: high_value_enabled = False try: high_value_threshold = float( getattr(analyser, "high_value_fudai_threshold_yuan", 500.0) or 500.0 ) except Exception: high_value_threshold = 500.0 # 计算 future_timestamp(预计开奖时间戳) future_ts = 0.0 if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: try: future_ts = float(countdown_tuple[1] or 0.0) except Exception: future_ts = 0.0 # 检查是否已经参与过这个福袋(通过 future_ts 匹配,避免重复参与) if future_ts > 0: try: participated_fudai_ts = getattr( analyser, "_participated_fudai_future_ts", set() ) if not isinstance(participated_fudai_ts, set): participated_fudai_ts = set() # 检查是否已经参与过(允许5秒误差,因为倒计时可能略有变化) for participated_ts in participated_fudai_ts: if abs(future_ts - participated_ts) < 5.0: try: analyser._log_kv( "参与", "basic_join_decision:已参与过此福袋,跳过重复参与", future_ts=future_ts, participated_ts=participated_ts, ) except Exception: pass # 已参与过,直接返回 True(表示已处理完成) return True except Exception: pass # 检查价值是否达到高价值阈值 is_high_value = ( high_value_enabled and prize_value_yuan > 0 and prize_value_yuan >= high_value_threshold and future_ts > 0.0 ) # 执行筛选检查 skip, reason = should_skip_fudai_by_config(analyser, detail) # 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值 # 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约 # 注意:如果是观看任务,不应该进入这个特殊处理逻辑(should_skip_fudai_by_config 已经返回 watch_task_detected) if skip and reason.startswith("countdown_gt_") and is_high_value: # 再次检查是否是观看任务(双重保险) is_watch_task = False try: is_watch_task = is_watch_task_fudai(content) if is_watch_task: # 是观看任务,不记录预约,直接关闭详情页并返回 try: analyser._log_kv( "预约", "[预约] 特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃", content=content[:80] if content else "", value_yuan=prize_value_yuan, threshold=high_value_threshold, ) except Exception: pass # 关闭详情页 try: analyser.click(500, 470) except Exception: try: analyser.operation.click_back(analyser.device_id) except Exception: pass try: analyser._log_kv( "参与", "basic_join_decision:已关闭详情(观看任务)", action="close_detail", ) except Exception: pass # 如果允许切换直播间,切换直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: try: analyser._log_kv( "参与", "basic_join_decision:观看任务后切换直播间", reason="watch_task", ) except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(analyser, "swipe_up_to_next_live"): analyser.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int( getattr(analyser, "resolution_ratio_x", 1080) or 1080 ) ry = int( getattr(analyser, "resolution_ratio_y", 2400) or 2400 ) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 analyser.operation.swipe( analyser.device_id, start_x, start_y, end_x, end_y, 300, ) except Exception: # 切房失败不影响主流程,直接返回 pass # 直接返回 False,不参与抽奖 elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(观看任务,已丢弃)", elapsed_seconds=round(elapsed, 2), ) return False except Exception: # 如果检查观看任务时出错,记录日志但继续后续处理(容错处理) pass # 计算剩余秒数 remain_seconds = None if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: try: now = time.time() cd_start = float(countdown_tuple[0] or 0.0) cd_end = float(countdown_tuple[1] or 0.0) if cd_start > 0 and cd_end > cd_start: remain_seconds = float(cd_end - now) except Exception: pass # 获取"预约参与阈值"配置 try: join_ahead_seconds = int( getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120 ) except Exception: join_ahead_seconds = 120 # 检查是否是回退后强制参与 force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) # 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约 # 或者如果是回退后强制参与,也立即参与 if force_attend or ( remain_seconds is not None and remain_seconds <= join_ahead_seconds ): try: analyser._log_kv( "参与", "basic_join_decision:倒计时大于阈值,但剩余秒数在预约参与阈值内或回退后强制参与,立即参与", reason=reason, value_yuan=prize_value_yuan, threshold=high_value_threshold, remain_seconds=( int(remain_seconds) if remain_seconds is not None else None ), join_ahead_threshold=join_ahead_seconds, force_attend=force_attend, ) except Exception: pass # 不关闭详情,继续走立即参与逻辑 skip = False reason = ( "high_value_immediate_join" if not force_attend else "reservation_back_force_attend" ) # 如果是强制参与,设置 is_high_value = False,跳过后续的高价值处理逻辑(避免再次记录预约) # 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋 if force_attend: try: # 设置 is_high_value = False,跳过后续的高价值处理逻辑 is_high_value = False analyser._log_kv( "参与", "basic_join_decision:强制参与模式,跳过后续高价值处理逻辑,直接参与", force_attend=force_attend, ) except Exception: pass else: # 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务 is_watch_task_check = False try: is_watch_task_check = is_watch_task_fudai(content) if is_watch_task_check: # 是观看任务,不记录预约,直接关闭详情页并返回 try: analyser._log_kv( "预约", "[预约] 特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃", content=content[:80] if content else "", value_yuan=prize_value_yuan, threshold=high_value_threshold, ) except Exception: pass # 关闭详情页 try: analyser.click(500, 470) except Exception: try: analyser.operation.click_back(analyser.device_id) except Exception: pass try: analyser._log_kv( "参与", "basic_join_decision:已关闭详情(观看任务)", action="close_detail", ) except Exception: pass # 如果允许切换直播间,切换直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: try: analyser._log_kv( "参与", "basic_join_decision:观看任务后切换直播间", reason="watch_task", ) except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(analyser, "swipe_up_to_next_live"): analyser.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int( getattr(analyser, "resolution_ratio_x", 1080) or 1080 ) ry = int( getattr(analyser, "resolution_ratio_y", 2400) or 2400 ) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 analyser.operation.swipe( analyser.device_id, start_x, start_y, end_x, end_y, 300, ) except Exception: # 切房失败不影响主流程,直接返回 pass # 直接返回 False,不参与抽奖 elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(观看任务,已丢弃)", elapsed_seconds=round(elapsed, 2), ) return False except Exception: # 如果检查观看任务时出错,记录日志但继续后续处理(容错处理) pass # 剩余秒数大于"预约参与阈值",记录预约 try: analyser._log_kv( "参与", "basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约", reason=reason, value_yuan=prize_value_yuan, threshold=high_value_threshold, remain_seconds=( int(remain_seconds) if remain_seconds is not None else None ), join_ahead_threshold=join_ahead_seconds, ) except Exception: pass # 不关闭详情,继续走预约逻辑 skip = False reason = "high_value_reservation" if skip: try: analyser._log_kv( "参与", "basic_join_decision:按配置丢弃福袋", reason=reason, ) except Exception: pass # 丢弃时,尽量关闭详情,避免停留在详情页 try: analyser.click(500, 470) except Exception: try: analyser.operation.click_back(analyser.device_id) except Exception: pass try: analyser._log_kv( "参与", "basic_join_decision:已关闭详情", action="close_detail" ) except Exception: pass # 如果允许切换直播间,筛选不通过直接切换直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: try: analyser._log_kv( "参与", "basic_join_decision:丢弃后切换直播间", reason=reason ) except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(analyser, "swipe_up_to_next_live"): analyser.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 analyser.operation.swipe( analyser.device_id, start_x, start_y, end_x, end_y, 300 ) except Exception: # 切房失败不影响主流程,直接返回 pass return False # 未被筛掉:根据配置决定"直接参与"或"记录为高价值预约" # 注意:content, prize_value_yuan, countdown_tuple, future_ts, high_value_enabled, high_value_threshold, is_high_value 已在前面提取 # 仅当启用高价值预约、识别到价值且未来时间合理时,才考虑记入预约队列 if is_high_value: # 价值达到高价值阈值:检查剩余秒数,如果在"预约参与阈值"内则立即参与,否则记录预约 # 计算剩余秒数 remain_seconds = None if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: try: now = time.time() cd_start = float(countdown_tuple[0] or 0.0) cd_end = float(countdown_tuple[1] or 0.0) if cd_start > 0 and cd_end > cd_start: remain_seconds = float(cd_end - now) except Exception: pass # 获取"预约参与阈值"配置(high_value_fudai_join_ahead_seconds) # 如果剩余秒数 <= 这个阈值,立即参与;否则记录预约 try: join_ahead_seconds = int( getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120 ) except Exception: join_ahead_seconds = 120 # 检查是否是回退后强制参与(预约回退后必须立即参与,不记录预约) force_attend_check = getattr( analyser, "_force_attend_after_reservation_back", False ) # 如果剩余秒数在"预约参与阈值"内(<= 阈值),或者如果是回退后强制参与,立即参与而不是记录预约 if force_attend_check or ( remain_seconds is not None and remain_seconds <= join_ahead_seconds ): try: analyser._log_kv( "参与", "basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内或回退后强制参与,立即参与", value_yuan=prize_value_yuan, threshold=high_value_threshold, remain_seconds=( int(remain_seconds) if remain_seconds is not None else None ), join_ahead_threshold=join_ahead_seconds, force_attend=force_attend_check, ) except Exception: pass # 不记录预约,继续执行后续的立即参与逻辑 is_high_value = False # 如果是强制参与,清除标志(避免影响后续逻辑) if force_attend_check: try: analyser._force_attend_after_reservation_back = False except Exception: pass else: # 剩余秒数大于"预约参与阈值",记录预约 try: analyser._log_kv( "参与", "basic_join_decision:价值达到高价值阈值,但剩余秒数大于预约参与阈值,记录预约", value_yuan=prize_value_yuan, threshold=high_value_threshold, remain_seconds=( int(remain_seconds) if remain_seconds is not None else None ), join_ahead_threshold=join_ahead_seconds, ) except Exception: pass if is_high_value: # 价值达到高价值阈值且剩余秒数大于阈值:记录预约而不是立即参与 # 在记录预约之前,先检查是否是观看任务 is_watch_task = False try: is_watch_task = is_watch_task_fudai(content) if is_watch_task: # 是观看任务,不记录预约,直接关闭详情页并返回 try: analyser._log_kv( "预约", "[预约] 检测到'观看X分钟'类任务,不记录预约,直接丢弃", content=content[:80] if content else "", value_yuan=prize_value_yuan, threshold=high_value_threshold, ) except Exception: pass # 关闭详情页 try: analyser.click(500, 470) except Exception: try: analyser.operation.click_back(analyser.device_id) except Exception: pass try: analyser._log_kv( "参与", "basic_join_decision:已关闭详情(观看任务)", action="close_detail", ) except Exception: pass # 如果允许切换直播间,切换直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: try: analyser._log_kv( "参与", "basic_join_decision:观看任务后切换直播间", reason="watch_task", ) except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(analyser, "swipe_up_to_next_live"): analyser.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int( getattr(analyser, "resolution_ratio_x", 1080) or 1080 ) ry = int( getattr(analyser, "resolution_ratio_y", 2400) or 2400 ) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 analyser.operation.swipe( analyser.device_id, start_x, start_y, end_x, end_y, 300, ) except Exception: # 切房失败不影响主流程,直接返回 pass # 直接返回 False,不参与抽奖 elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(观看任务,已丢弃)", elapsed_seconds=round(elapsed, 2), ) return False except Exception as e: # 如果检查观看任务时出错,记录日志但继续后续检查(容错处理) try: analyser._log_kv( "预约", "[预约] 检查观看任务时出错,继续后续检查", error=str(e), error_type=type(e).__name__, ) except Exception: pass # 在记录预约之前,先检查福袋内容是否在黑名单中 try: # 检查内容是否命中黑名单 content_hit_blacklist = check_contain(analyser, content) if content_hit_blacklist: # 命中黑名单,不记录预约,直接关闭详情页并返回 try: analyser._log_kv( "预约", "[预约] 福袋内容命中黑名单,不记录预约,直接丢弃", content=content[:80] if content else "", value_yuan=prize_value_yuan, threshold=high_value_threshold, ) except Exception: pass # 关闭详情页 try: analyser.click(500, 470) except Exception: try: analyser.operation.click_back(analyser.device_id) except Exception: pass try: analyser._log_kv( "参与", "basic_join_decision:已关闭详情(命中黑名单)", action="close_detail", ) except Exception: pass # 如果允许切换直播间,切换直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: try: analyser._log_kv( "参与", "basic_join_decision:命中黑名单后切换直播间", reason="content_blacklist", ) except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(analyser, "swipe_up_to_next_live"): analyser.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int( getattr(analyser, "resolution_ratio_x", 1080) or 1080 ) ry = int( getattr(analyser, "resolution_ratio_y", 2400) or 2400 ) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 analyser.operation.swipe( analyser.device_id, start_x, start_y, end_x, end_y, 300, ) except Exception: # 切房失败不影响主流程,直接返回 pass # 直接返回 False,不参与抽奖 elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(命中黑名单,已丢弃)", elapsed_seconds=round(elapsed, 2), ) return False except Exception as e: # 如果检查黑名单时出错,记录日志但继续记录预约(容错处理) try: analyser._log_kv( "预约", "[预约] 检查黑名单时出错,继续记录预约", error=str(e), error_type=type(e).__name__, ) except Exception: pass if is_high_value: # 未命中黑名单,继续记录预约 try: # 预约抢占最小价值(若配置了,则低于该值的预约不会抢占当前任务) try: preempt_min = float( getattr(analyser, "reservation_preempt_min_value_yuan", 0.0) or 0.0 ) except Exception: preempt_min = 0.0 # 初始化预约队列容器 reservations = getattr(analyser, "reservations", None) if reservations is None: reservations = [] try: analyser.reservations = reservations # type: ignore[attr-defined] except Exception: pass else: # 在已有预约队列的情况下,先立即清理已过期的预约,保证队列始终是“未过期”的 try: import douyin_reservation_logic as rl_cleanup rl_cleanup.cleanup_expired_reservations( analyser, reservations, write_state_callback=None, ) except Exception: pass # room_pos:当前直播间位置计数 try: room_pos = int(getattr(analyser, "room_pos", 0) or 0) except Exception: room_pos = 0 # 获取当前直播间标题(如果可用) room_title = "" room_title_raw = "" try: # 每次记录预约时,都重新读取直播间标题,不使用缓存 # 这样可以确保每个预约记录的是当时的真实直播间标题 try: # 在函数开头导入,避免作用域问题 import douyin_fudai_detail as dfd_module y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) room_title, room_title_raw = ( dfd_module.read_live_room_title_core( analyser, y_pianyi_val ) ) # 更新 analyser 的属性,用于状态文件显示当前直播间 try: analyser.current_room_title = room_title analyser.current_room_title_raw = room_title_raw except Exception: pass except Exception as e: try: analyser._log_kv( "预约", "读取直播间标题失败,尝试使用缓存", error=str(e), error_type=type(e).__name__, ) except Exception: pass # 如果读取失败,尝试使用缓存(作为兜底) room_title = str( getattr(analyser, "current_room_title", "") or "" ) room_title_raw = str( getattr(analyser, "current_room_title_raw", "") or "" ) except Exception: pass # 记录高价值预约(仅负责入队和写状态,不立即改变当前直播间) # 使用全局导入的模块(已在文件顶部导入) # 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致) def _write_reservation_state() -> None: try: import os import json from datetime import datetime state_path = getattr( analyser, "_reservations_state_path", None ) if not state_path: # 使用与 douyin_fudai.py 相同的路径逻辑 state_path = os.path.join( os.path.dirname(__file__), "state", "reservations.json", ) # 确保目录存在 os.makedirs(os.path.dirname(state_path), exist_ok=True) # 格式化预约队列数据(与 douyin_reservation.py 格式一致) items = [] for r in reservations or []: try: ft = float(r.get("future_ts") or 0) except Exception: ft = 0.0 try: ft_str = ( datetime.fromtimestamp(ft).strftime( "%Y-%m-%d %H:%M:%S" ) if ft else "" ) except Exception: ft_str = str(r.get("future_str", "")) items.append( { "prize_value_yuan": float( r.get("prize_value_yuan") or 0 ), "content": str(r.get("content") or ""), "future_ts": ft, "future_str": ft_str, "pos_seen": int(r.get("pos_seen") or 0), "room_title": str(r.get("room_title") or ""), "room_title_raw": str( r.get("room_title_raw") or "" ), "created_ts": float(r.get("created_ts") or 0), "task_count": int(r.get("task_count") or 2), "time_text": str(r.get("time_text") or ""), "participants": int(r.get("participants") or 0), "copies": int(r.get("copies") or 0), } ) # 获取当前直播间标题(用于状态文件) current_title = str( getattr(analyser, "current_room_title", "") or room_title or "" ) current_title_raw = str( getattr(analyser, "current_room_title_raw", "") or room_title_raw or "" ) # 写入完整的状态数据 data = { "updated_ts": time.time(), "reason": "record_reservation", "room_pos": int(room_pos), "current_room_title": current_title, "current_room_title_raw": current_title_raw, "reservations": items, } with open(state_path, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) try: analyser._log_kv( "预约", "已写入预约队列状态文件", path=state_path, queue_len=len(reservations) if reservations is not None else 0, ) except Exception: pass except Exception as e: try: analyser._log_kv( "预约", "写入预约队列状态文件失败", error=str(e), error_type=type(e).__name__, ) except Exception: pass # 记录高价值直播间(在记录预约之前) try: import douyin_high_value_room if hasattr(douyin_high_value_room, "touch_high_value_room"): douyin_high_value_room.touch_high_value_room( # type: ignore[attr-defined] analyser=analyser, title_norm=room_title, title_raw=room_title_raw, prize_value_yuan=prize_value_yuan, reason="reservation", increment=True, content=content, pos_seen=room_pos, ) except Exception: pass # 确保位置信息已更新到运行时映射表 try: if hasattr(analyser, "_record_room_title_and_pos"): analyser._record_room_title_and_pos() else: # 如果没有这个方法,手动记录 try: room_pos_current = int(getattr(analyser, "room_pos", room_pos) or room_pos) room_pos_map = getattr(analyser, "_room_pos_to_title_map", {}) if room_pos_current not in room_pos_map: room_pos_map[room_pos_current] = (room_title, room_title_raw) analyser._room_pos_to_title_map = room_pos_map try: analyser._log_kv( "预约", "[预约] basic_join_decision:记录位置信息到运行时映射表", room_pos=room_pos_current, room_title=room_title[:50] if room_title else "", ) except Exception: pass except Exception as e: try: analyser._log_kv( "预约", "[预约] basic_join_decision:记录位置信息到运行时映射表失败", error=str(e), error_type=type(e).__name__, ) except Exception: pass except Exception: pass # 记录预约,并检查队列是否已满 queue_full_flag = [False] def _add_reservation_with_flag(q, item): queue_full_flag[0] = douyin_reservation_logic.add_reservation_core_logic( # type: ignore[attr-defined] q, item, max_reservations=int( getattr( analyser, "high_value_fudai_max_reservations", 3 ) or 3 ), analyser=analyser, write_state_callback=_write_reservation_state, ) # 获取任务数量和其他详情信息(从阶段检测结果获取) task_count = 2 # 默认2个任务 time_text = "" participants = 0 copies = 0 try: # 从 detail tuple 中获取信息 if isinstance(detail, tuple) and len(detail) >= 6: time_text = str(detail[1] or "") participants = int(detail[2] or 0) copies = int(detail[3] or 0) # 从阶段检测结果获取任务数量 task_count_from_stage = getattr( analyser, "_fudai_detail_task_count_from_stage", None ) if task_count_from_stage is not None: task_count = int(task_count_from_stage or 2) # 清除标志,避免影响后续调用 analyser._fudai_detail_task_count_from_stage = None else: # 如果阶段检测未保存任务数量,尝试通过阶段检测获取 try: import douyin_stage analyser.operation.get_screenshot(analyser.device_id) result = ( douyin_stage.diagnose_stage_from_current_screen( analyser ) ) if result: stage, _ = result if stage == "FUDai_DETAIL": # 尝试通过像素检测获取任务数量 try: import douyin_pixel import os pic_path = os.path.join( os.path.dirname(__file__), "pic", "screenshot.png", ) if os.path.exists(pic_path): from PIL import Image pic = Image.open(pic_path) pic_rgb = pic.convert("RGB") rx = int( getattr( analyser, "resolution_ratio_x", 1080, ) or 1080 ) ry = int( getattr( analyser, "resolution_ratio_y", 2400, ) or 2400 ) y_pianyi = int( getattr(analyser, "y_pianyi", 0) or 0 ) result = douyin_pixel.detect_fudai_detail_page( pic_rgb, rx, ry, y_pianyi, template_threshold=float( getattr( analyser, "fudai_detail_template_threshold", 0.7, ) or 0.7 ), return_info=True, analyser=analyser, ) if isinstance(result, tuple): _, detect_info = result detected_task_count = ( detect_info.get("task_count", 0) ) if detected_task_count in (1, 2, 3): task_count = detected_task_count except Exception: pass except Exception: pass # 限制任务数量在合理范围内 if task_count not in (1, 2, 3): task_count = 2 except Exception: task_count = 2 douyin_reservation_logic.record_high_value_reservation( # type: ignore[attr-defined] analyser=analyser, fudai_content_text=content, prize_value_yuan=prize_value_yuan, lastsecond=0, future_timestamp=future_ts, x=0, needswitch=True, wait_minutes=0, post_switch_delay_s=0.0, room_pos=room_pos, reservations=reservations, reservation_focus_until_ts_ref=[ float( getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0 ) ], close_detail_callback=lambda: None, swipe_up_switch_callback=lambda: None, swipe_down_back_callback=lambda: None, add_reservation_callback=_add_reservation_with_flag, sort_reservations_callback=lambda: ( douyin_reservation_logic._sort_reservations_inplace( # type: ignore[attr-defined] reservations if reservations is not None else [] # type: ignore[arg-type] ) ), write_state_callback=_write_reservation_state, room_title=room_title, room_title_raw=room_title_raw, task_count=task_count, time_text=time_text, participants=participants, copies=copies, ) # 如果队列已满,设置标志以便主循环处理 if queue_full_flag[0]: try: analyser.queue_full_waiting_at_earliest = ( False # 重置标志,让主循环处理 ) except Exception: pass try: analyser._log_kv( "预约", "basic_join_decision:命中高价值阈值,已记录为预约,不立即参与", value_yuan=prize_value_yuan, threshold=high_value_threshold, future_ts=int(future_ts), room_pos=room_pos, queue_len=len(reservations), preempt_min_value=preempt_min, ) except Exception: pass # 关闭当前详情,避免长时间停留 try: analyser.click(500, 470) except Exception: try: analyser.operation.click_back(analyser.device_id) except Exception: pass try: analyser._log_kv( "参与", "basic_join_decision:已关闭详情", action="close_detail", ) except Exception: pass # 记录预约后,切换直播间继续找别的福袋 # 注意:如果已经在锁定期内(已回退到预约直播间),不应该切换直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True # 检查是否在锁定期内 in_lock_period = False try: focus_until = float( getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0 ) now_ts = time.time() if focus_until > 0 and now_ts < focus_until: in_lock_period = True try: analyser._log_kv( "预约", "[预约] 记录预约后:在锁定期内,不切换直播间", focus_until=int(focus_until), remain_seconds=int(focus_until - now_ts), ) except Exception: pass except Exception: pass if needswitch and not in_lock_period: try: analyser._log_kv( "参与", "basic_join_decision:记录预约后切换直播间", reason="high_value_reservation", ) except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(analyser, "swipe_up_to_next_live"): analyser.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int( getattr(analyser, "resolution_ratio_x", 1080) or 1080 ) ry = int( getattr(analyser, "resolution_ratio_y", 2400) or 2400 ) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 analyser.operation.swipe( analyser.device_id, start_x, start_y, end_x, end_y, 300, ) except Exception: # 切房失败不影响主流程,直接返回 pass elif in_lock_period: # 在锁定期内,不切换直播间,但记录日志说明原因 try: analyser._log_kv( "参与", "basic_join_decision:记录预约后不切换直播间(锁定期内)", reason="lock_period_active", ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(记录预约)", elapsed_seconds=round(elapsed, 2), ) return True except Exception: # 若预约逻辑异常,退化为直接参与抽奖 try: analyser._log_kv( "预约", "basic_join_decision:记录预约时异常,退化为直接参与", ) except Exception: pass # 默认分支:未进入预约路径或预约失败,直接参与抽奖 try: analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖") except Exception: pass # 获取当前福袋的 future_ts(用于参与成功后从预约队列中移除) current_future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 result = attend_choujiang(analyser) # 如果参与成功,清除强制参与标志(避免影响后续福袋) if result: try: if getattr(analyser, "_force_attend_after_reservation_back", False): analyser._force_attend_after_reservation_back = False analyser._log_kv( "参与", "basic_join_decision:参与成功,清除强制参与标志", ) except Exception: pass # 如果参与成功,从预约队列中移除该预约(如果存在) if result and current_future_ts > 0: try: reservations = getattr(analyser, "reservations", None) if ( reservations and isinstance(reservations, list) and len(reservations) > 0 ): # 查找并移除匹配的预约(通过 future_ts 匹配,允许5秒误差) removed_count = 0 remaining_reservations = [] for res in reservations: try: res_future_ts = float(res.get("future_ts") or 0.0) if ( res_future_ts > 0 and abs(res_future_ts - current_future_ts) <= 5.0 ): # 匹配的预约,移除 removed_count += 1 analyser._log_kv( "预约", "[预约] 参与成功,从预约队列中移除该预约", future_ts=int(res_future_ts), value_yuan=res.get("prize_value_yuan", 0), content=( res.get("content", "")[:50] if res.get("content") else "" ), ) else: # 保留不匹配的预约 remaining_reservations.append(res) except Exception: # 如果解析预约项时出错,保留该项(容错处理) remaining_reservations.append(res) if removed_count > 0: analyser.reservations = remaining_reservations # 写入预约状态(供 GUI/Web 端查看) # 使用内联的写入逻辑(与 _write_reservation_state 类似,但需要适配当前作用域) try: import os import json from datetime import datetime state_path = getattr(analyser, "_reservations_state_path", None) if not state_path: state_path = os.path.join( os.path.dirname(__file__), "state", "reservations.json", ) os.makedirs(os.path.dirname(state_path), exist_ok=True) # 格式化预约队列数据 items = [] for r in remaining_reservations or []: try: ft = float(r.get("future_ts") or 0) except Exception: ft = 0.0 try: ft_str = ( datetime.fromtimestamp(ft).strftime( "%Y-%m-%d %H:%M:%S" ) if ft else "" ) except Exception: ft_str = str(r.get("future_str", "")) items.append( { "prize_value_yuan": float( r.get("prize_value_yuan") or 0 ), "content": str(r.get("content") or ""), "future_ts": ft, "future_str": ft_str, "pos_seen": int(r.get("pos_seen") or 0), "room_title": str(r.get("room_title") or ""), "room_title_raw": str( r.get("room_title_raw") or "" ), "created_ts": float(r.get("created_ts") or 0), "task_count": int(r.get("task_count") or 2), "time_text": str(r.get("time_text") or ""), "participants": int(r.get("participants") or 0), "copies": int(r.get("copies") or 0), } ) # 获取当前直播间标题 current_title = str( getattr(analyser, "current_room_title", "") or "" ) current_title_raw = str( getattr(analyser, "current_room_title_raw", "") or "" ) # 写入完整的状态数据 data = { "updated_ts": time.time(), "reason": "remove_reservation_after_attend", "room_pos": 0, "current_room_title": current_title, "current_room_title_raw": current_title_raw, "reservations": items, } with open(state_path, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) try: analyser._log_kv( "预约", "已写入预约队列状态文件(移除预约后)", path=state_path, queue_len=len(remaining_reservations), ) except Exception: pass except Exception as e: analyser._log_kv( "预约", "[预约] 写入预约状态失败", error=str(e), error_type=type(e).__name__, ) except Exception as e: analyser._log_kv( "预约", "[预约] 从预约队列中移除预约时出错", error=str(e), error_type=type(e).__name__, ) elapsed = time.time() - start_time analyser._log_kv( "参与", "basic_join_decision完成(参与抽奖)", elapsed_seconds=round(elapsed, 2), result=result, ) return result