from __future__ import annotations """ Fudai detail helpers shim (WebGUI version) ========================================== Exports: - close_fudai_detail - ensure_fudai_detail_open - read_live_room_title_core - read_fudai_detail_once - read_fudai_detail_with_retries - is_abnormal_time_value """ from typing import Any, Dict, Tuple, List, Optional import os import time import re import sys from PIL import Image from douyin_detection import check_detail_height from douyin_fudai_core import get_fudai_contain # ============================================================================ # 直播间标题处理辅助函数(模块化) # ============================================================================ def _room_title_has_ellipsis(s: str) -> bool: """检查是否包含省略号。""" if "…" in s: return True if re.search(r"\.{3,}", s): return True return False def _strip_room_noise_text(s: str) -> str: """移除直播间名 OCR 常见噪音(点赞/关注/粉丝等)。""" try: t = str(s or "") except Exception as e: # 字符串转换失败,返回空字符串 return "" t = t.replace("\r", "\n").replace("\t", " ") t = re.sub(r"[\s\u3000]+", " ", t).strip() # 计数噪音:例如 1.2万点赞 / 234点赞 / 3W点赞 t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞)", " ", t) t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*关注", " ", t) t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*粉丝", " ", t) t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*人(?:在线|在看)?", " ", t) t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t) t = re.sub(r"本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t) for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "人在线", "在线"): t = t.replace(w, " ") t = re.sub(r"\s+", " ", t).strip() return t def _extract_room_title_candidate(raw_text: str) -> str: """从 OCR 原文中提取更像"直播间名"的片段。""" t = _strip_room_noise_text(raw_text) if not t: return "" segs = [x.strip() for x in re.split(r"[\n ]+", t) if x.strip()] best = "" best_score = -999 for seg in segs: if not seg: continue seg2 = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞|关注|粉丝)$", "", seg).strip() if not seg2: continue seg = seg2 score = len(seg) if _room_title_has_ellipsis(seg): score += 30 if re.search(r"[\u4e00-\u9fffA-Za-z]", seg): score += 5 if score > best_score: best_score = score best = seg if best: m = re.search(r"(.*?)(…|\.{3,})", best) if m: cand = (m.group(1) + m.group(2)).strip() return cand if cand else best.strip() return best.strip() m2 = re.search(r"(.*?)(…|\.{3,})", t) if m2: cand2 = (m2.group(1) + m2.group(2)).strip() if cand2: return cand2 return t.strip() def _normalize_room_title(t: str) -> str: """规范化直播间标题。""" s = _extract_room_title_candidate(str(t or "")) s = s.replace("\r", " ").replace("\n", " ").strip() s = re.sub(r"\s+", "", s) for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"): s = s.replace(w, "") s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s) s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s) s = re.sub(r"本场(?:点赞|点赞|点贊|点)", "", s) s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", s) return s def _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tuple[str, str]: """尝试 OCR 识别直播间标题。""" try: raw0 = analyser.operation.analyse_pic_word(cut_name, change_color) except Exception as e: try: analyser._log_kv( "错误", "OCR识别直播间标题失败", error=str(e), error_type=type(e).__name__, cut_name=cut_name, level="WARNING", ) except Exception: pass raw0 = "" raw_text0 = str(raw0 or "").replace("\r", "\n").strip() cand_raw0 = _extract_room_title_candidate(raw_text0) title0 = _normalize_room_title(cand_raw0) return title0, cand_raw0 def _pick_best_room_title(cands: List[Tuple[str, str, str]], min_len: int = 3) -> Tuple[str, str]: """从多个候选结果中选择最佳的一个。""" best = ("", "") best_score = -1 for t_norm, t_raw, tag in cands: if not t_raw and not t_norm: continue ln = len(t_norm or "") score = ln if ln >= min_len: score += 10 if ln == 1: score -= 4 if ln == 2: score -= 1 if _room_title_has_ellipsis(t_raw or ""): score += 8 if tag.endswith("_cc0"): score += 2 if tag.startswith("large"): score += 2 if tag.startswith("mid"): score += 1 if score > best_score: best_score = score best = (t_norm, t_raw) return best def close_fudai_detail(analyser: Any) -> None: """关闭福袋详情:使用点击关闭详情页的坐标,而不是返回键。""" try: # 获取分辨率比例(基准分辨率 1080x2400) rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) # 计算关闭详情页的坐标(基准坐标 500, 470) close_x = int(500 * rx // 1080) close_y = int(470 * ry // 2400) # 坐标验证:检查坐标是否在合理范围内 # 获取屏幕尺寸(如果可用) screen_width = rx screen_height = ry try: if hasattr(analyser, 'operation') and hasattr(analyser.operation, 'get_screen_size'): try: screen_size = analyser.operation.get_screen_size(analyser.device_id) if screen_size: screen_width, screen_height = screen_size except Exception: pass except Exception: pass # 验证坐标边界 if close_x < 0 or close_x >= screen_width or close_y < 0 or close_y >= screen_height: try: analyser._log_kv( "验证", "关闭详情页坐标超出屏幕范围", x=close_x, y=close_y, screen_width=screen_width, screen_height=screen_height, base_x=500, base_y=470, level="WARNING", ) except Exception: pass # 修正坐标到屏幕范围内 close_x = max(0, min(close_x, screen_width - 1)) close_y = max(0, min(close_y, screen_height - 1)) analyser._log_kv( "详情", "close_fudai_detail:点击关闭详情页坐标", x=close_x, y=close_y, base_x=500, base_y=470, ) except Exception as e: # 如果获取分辨率失败,使用默认坐标 try: analyser._log_kv( "错误", "获取分辨率失败,使用默认坐标", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass close_x, close_y = 500, 470 try: analyser._log_kv("详情", "close_fudai_detail:使用默认坐标关闭详情页") except Exception: pass try: analyser.operation.click(analyser.device_id, close_x, close_y) except Exception as e1: # 兜底:尝试使用 analyser.click try: analyser._log_kv( "错误", "使用operation.click关闭详情页失败,尝试备用方法", error=str(e1), error_type=type(e1).__name__, level="WARNING", ) except Exception: pass try: analyser.click(close_x, close_y) except Exception as e2: # 最后兜底:使用返回键 try: analyser._log_kv( "错误", "使用analyser.click关闭详情页失败,使用返回键", error=str(e2), error_type=type(e2).__name__, level="WARNING", ) except Exception: pass try: analyser.operation.click_back(analyser.device_id) except Exception as e3: try: analyser._log_kv( "错误", "所有关闭详情页方法都失败", error=str(e3), error_type=type(e3).__name__, level="ERROR", ) except Exception: pass try: analyser.operation.delay(0.5) except Exception as e: try: analyser._log_kv( "错误", "operation.delay失败,使用time.sleep", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass time.sleep(0.5) def ensure_fudai_detail_open(analyser: Any, fudai_x: int = 0) -> bool: """确保福袋详情已打开:当前实现只记录日志并假定已打开。 Args: analyser: 分析器实例 fudai_x: 福袋的x坐标(可选,当前实现未使用) """ try: analyser._log_kv("详情", "ensure_fudai_detail_open:假定已打开", fudai_x=fudai_x) except Exception as e: try: analyser._log_kv( "错误", "记录ensure_fudai_detail_open日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return True def _is_wrong_coupon_popup(analyser: Any) -> bool: """在已点击疑似福袋后,判断当前弹窗是否为优惠券类,而非真正福袋详情。 只在"点击详情后"调用,不在平时循环中使用,避免额外开销。 逻辑: 1. 对屏幕中部区域做颜色统计 2. 如果同时检测到福袋详情和优惠券特征,需要OCR确认"开心收下"字样 3. 只有OCR确认是"开心收下"时,才判定为优惠券弹窗 """ try: analyser.operation.get_screenshot(analyser.device_id) except Exception as e: try: analyser._log_kv( "错误", "获取截图失败(判断优惠券弹窗)", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return False path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") try: pic = Image.open(path) pic.load() # Force load to catch truncated files early except (OSError, IOError, SyntaxError): # Handle truncated image files return False except Exception: return False pic = pic.convert("RGBA") pix = pic.load() w, h = pic.size # 扫描区域:153,351 到 266,451(基于1080x2400基准坐标) # 根据实际分辨率缩放坐标 scale_x = w / 1080.0 scale_y = h / 2400.0 x1 = int(153 * scale_x) y1 = int(351 * scale_y) x2 = int(266 * scale_x) y2 = int(451 * scale_y) # 边界检查 x1 = max(0, min(x1, w)) y1 = max(0, min(y1, h)) x2 = max(0, min(x2, w)) y2 = max(0, min(y2, h)) if x1 >= x2 or y1 >= y2: return False fudai_like = 0 coupon_like = 0 step_x = max(1, (x2 - x1) // 40) step_y = max(1, (y2 - y1) // 40) for yy in range(y1, y2, step_y): for xx in range(x1, x2, step_x): try: p = pix[xx, yy] except Exception as e: # 像素访问失败,跳过该像素(可能是坐标越界) continue if not (isinstance(p, tuple) and len(p) >= 3): continue r, g, b = int(p[0]), int(p[1]), int(p[2]) # 福袋:粉/紫/粉蓝 if r >= 200 and b >= 210 and 80 <= g <= 230: fudai_like += 1 # 券:偏橙色 if r >= 200 and 120 <= g <= 230 and b <= 180: coupon_like += 1 try: analyser._log_kv( "弹窗", "弹窗颜色统计", fudai_like=fudai_like, coupon_like=coupon_like, ) except Exception as e: try: analyser._log_kv( "错误", "记录弹窗颜色统计日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 如果券像素明显多于粉袋像素,可能需要OCR确认 is_coupon_like_by_color = coupon_like > fudai_like * 1.2 # 检测是否同时有福袋详情特征(通过像素检测) has_fudai_detail = False try: import douyin_pixel resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) pic_rgb = pic.convert("RGB") # 获取模板匹配阈值(优先使用福袋详情页专用阈值) template_threshold = float( getattr(analyser, "fudai_detail_template_threshold", None) or getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 ) result = douyin_pixel.detect_fudai_detail_page( pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi, template_threshold=template_threshold, return_info=True, analyser=analyser ) if isinstance(result, tuple): has_fudai_detail, detect_info = result # 记录检测信息到日志 try: task_count = detect_info.get("task_count", 0) detection_method = detect_info.get("method", "unknown") method_name = "任务数量检测" if detection_method == "task_count" else "未知" analyser._log_kv( "弹窗", f"检测福袋详情页({method_name})", task_count=task_count, method=detection_method, ) except Exception as e: try: analyser._log_kv( "错误", "记录福袋详情检测日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass else: has_fudai_detail = result except Exception as e: try: analyser._log_kv( "错误", "检测福袋详情页失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # 如果颜色统计显示可能是优惠券,需要严格确认: # 1. 先进行模板匹配确认(使用 detect_coupon_popup_background) # 2. 如果模板匹配成功,再进行OCR确认"开心收下"按钮 # 3. 只有模板匹配和OCR都确认时,才判定为优惠券弹窗 # 这样可以避免因识别福袋位置失败而误判为优惠券弹窗 if is_coupon_like_by_color: try: # 步骤1:模板匹配确认 template_matched = False try: import douyin_pixel pic_rgb = pic.convert("RGB") template_matched = douyin_pixel.detect_coupon_popup_background(pic_rgb) except Exception as e: try: analyser._log_kv( "错误", "模板匹配确认异常", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass if not template_matched: # 模板匹配失败,即使颜色统计偏向优惠券,也不判定为优惠券弹窗 # 可能是识别福袋位置失败,导致点击了错误位置 try: analyser._log_kv( "弹窗", "颜色统计偏向优惠券,但模板匹配未命中,不判定为优惠券弹窗", 说明="可能是识别福袋位置失败,点击了错误位置", ) except Exception as e: try: analyser._log_kv( "错误", "记录模板匹配失败日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return False # 步骤2:OCR确认"开心收下"按钮(模板匹配成功后) if has_fudai_detail: analyser._log_kv("弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认") else: analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认") # 使用参与按钮区域检测"开心收下"(与"粉丝团加入"相同的区域) # 保存完整截图并标注OCR区域 try: import douyin_screenshot_manager pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") if os.path.exists(pic_path): pic_check = Image.open(pic_path) pic_check.load() pic_rgb_check = pic_check.convert("RGB") width, height = pic_rgb_check.size rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) x1_base, y1_base, x2_base, y2_base = 200, 1940, 880, 2140 x1 = int(x1_base * width / rx) y1 = int(y1_base * height / ry) x2 = int(x2_base * width / rx) y2 = int(y2_base * height / ry) x1 = max(0, min(x1, width - 1)) y1 = max(0, min(y1, height - 1)) x2 = max(0, min(x2, width - 1)) y2 = max(0, min(y2, height - 1)) if x1 < x2 and y1 < y2: debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb_check, operation_type="ocr", picname="参与按钮", step="before_ocr", coords=(x1, y1, x2, y2), extra_info={ "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", "size": f"{x2_base-x1_base}x{y2_base-y1_base}", "purpose": "检测开心收下", } ) if debug_path: try: analyser._log_kv( "[调试图像]", "OCR识别前保存完整截图(参与按钮-检测开心收下)", path=debug_path, ) except Exception as e: try: analyser._log_kv( "错误", "记录调试图像日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass except Exception as e: try: analyser._log_kv( "错误", "保存参与按钮调试截图失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮") # 并行执行模式0和模式1的OCR(如果启用模式1) enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False)) coupon_text = "" if enable_ocr_mode1: # 并行执行两个OCR模式 from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=2) as executor: future_mode0 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 0) future_mode1 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 1) text_mode0 = str(future_mode0.result() or "") text_mode1 = str(future_mode1.result() or "") # 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1 if text_mode0 and "开心收下" in text_mode0: coupon_text = text_mode0 elif text_mode1 and "开心收下" in text_mode1: coupon_text = text_mode1 elif text_mode0: coupon_text = text_mode0 else: coupon_text = text_mode1 else: # 只使用模式0 coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "") if coupon_text and "开心收下" in coupon_text: # 模板匹配 + OCR 都确认,判定为优惠券弹窗 analyser._log_kv("弹窗", "模板匹配+OCR确认:检测到'开心收下',判定为优惠券弹窗", OCR文本=coupon_text[:50]) return True else: # 模板匹配成功,但OCR未确认"开心收下" # 如果同时检测到福袋详情,优先信任福袋详情 if has_fudai_detail: analyser._log_kv("弹窗", "模板匹配成功但OCR未确认'开心收下',且检测到福袋详情,判定为福袋详情页", OCR文本=coupon_text[:50] if coupon_text else "空") return False else: # 模板匹配成功但OCR未确认,可能是识别福袋位置失败 # 不判定为优惠券弹窗,避免误点返回 analyser._log_kv( "弹窗", "模板匹配成功但OCR未确认'开心收下',不判定为优惠券弹窗", OCR文本=coupon_text[:50] if coupon_text else "空", 说明="可能是识别福袋位置失败,点击了错误位置", ) return False except Exception as e: # 确认过程异常,不判定为优惠券弹窗,避免误判 try: analyser._log_kv( "错误", "优惠券确认过程异常,不判定为优惠券弹窗", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass return False # 否则判定为福袋详情页 return False def read_live_room_title_core( analyser: Any, y_pianyi: int, min_len: int = 3, ) -> Tuple[str, str]: """读取当前直播间顶部区域的"主播名/直播间名"(OCR,尽量轻量)。 使用多个 ROI 区域和不同的 OCR 模式进行识别,选择最佳结果。 """ try: analyser.operation.get_screenshot(analyser.device_id) except Exception as e: try: analyser._log_kv( "错误", "获取截图失败(读取直播间标题)", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass cands: List[Tuple[str, str, str]] = [] # mid ROI:优先使用更大区域,减少"只截到尾巴1个字" try: analyser.cut_pic(80, 128, 560, 230, '', 'live_room_title_mid', y_pianyi) t, r = _ocr_try_room_title(analyser, 'live_room_title_mid', 0) cands.append((t, r, 'mid_cc0')) if len(t or "") < min_len: t1, r1 = _ocr_try_room_title(analyser, 'live_room_title_mid', 1) cands.append((t1, r1, 'mid_cc1')) except Exception as e: try: analyser._log_kv( "错误", "OCR识别直播间标题(mid区域)失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass # large ROI:进一步扩大,兼容机型/系统字体/刘海偏移 if not cands or max(len(x[0] or "") for x in cands) < min_len: try: analyser.cut_pic(40, 110, 660, 260, '', 'live_room_title_large', y_pianyi) t2, r2 = _ocr_try_room_title(analyser, 'live_room_title_large', 0) cands.append((t2, r2, 'large_cc0')) if len(t2 or "") < min_len: t3, r3 = _ocr_try_room_title(analyser, 'live_room_title_large', 1) cands.append((t3, r3, 'large_cc1')) except Exception: pass # small ROI:最后兜底(历史区域),使用优化后的坐标 if not cands or max(len(x[0] or "") for x in cands) <= 1: try: analyser.cut_pic(147, 147, 320, 188, '', 'live_room_title_small', y_pianyi) t4, r4 = _ocr_try_room_title(analyser, 'live_room_title_small', 0) cands.append((t4, r4, 'small_cc0')) except Exception: pass title, raw_text = _pick_best_room_title(cands, min_len) # 更新 analyser 的属性 try: analyser.current_room_title_raw = raw_text if title: analyser.current_room_title = title except Exception: pass return title, raw_text def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: """执行一次福袋详情识别(本地完整版实现)。 流程: 1. 获取截图(任务数量检测和弹窗检测已在阶段检测中完成,不再重复检测); 2. 从阶段检测结果中获取任务数量(_fudai_detail_task_count_from_stage); 3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值; 4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。 """ start_time = time.time() # 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取) # 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage task_count = 0 try: 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 0) try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:从阶段检测获取任务数量(无需截图)", task_count=task_count, ) except Exception: pass else: # 如果阶段检测未保存任务数量,记录警告日志 try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:警告:阶段检测未保存任务数量(可能为None)", task_count_from_stage=task_count_from_stage, ) except Exception: pass # 使用默认值 task_count = 2 # 清除标志,避免影响后续调用 try: analyser._fudai_detail_task_count_from_stage = None except Exception: pass # 如果任务数量为0,说明不在福袋详情页(阶段检测应该已经过滤掉了,这里作为兜底) # 在获取截图之前就返回错误,避免不必要的截图 if task_count <= 0: try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:任务数量为0,不在福袋详情页,跳过截图和OCR", task_count=task_count, ) except Exception: pass now = time.time() tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_once完成(任务数量为0)", elapsed_seconds=round(elapsed, 2)) return "error", tup_err, {"reason": "not_in_fudai_detail", "task_count": task_count} # 如果任务数不在(1,2,3)范围内,默认按2个任务处理 if task_count not in (1, 2, 3): task_count = 2 except Exception as e: try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:获取任务数量异常,使用默认值", error=str(e), ) except Exception: pass # 异常时使用默认值 task_count = 2 # 步骤2:获取截图(仅用于后续OCR识别内容/倒计时/价值,不是为了获取任务数量) try: analyser.operation.get_screenshot(analyser.device_id) except Exception: pass pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") pic_rgb = None try: if os.path.exists(pic_path): pic = Image.open(pic_path) pic.load() pic_rgb = pic.convert("RGB") except Exception: pass if pic_rgb is None: try: analyser._log_kv("福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别") except Exception: pass now = time.time() tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_once完成(截图失败)", elapsed_seconds=round(elapsed, 2)) return "error", tup_err, {"reason": "screenshot_failed"} # 如果任务数不在(1,2,3)范围内,默认按2个任务处理 if task_count not in (1, 2, 3): task_count = 2 # 识别福袋内容 / 倒计时 / 价值 try: content, time_text, participants, copies, prize_value_yuan = get_fudai_contain( analyser, renwu=task_count ) except Exception as e: # 出现异常时,记录错误并返回占位结果 try: analyser._log_kv( "福袋详情", "read_fudai_detail_once 异常", error=str(e), ) except Exception: pass now = time.time() tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2)) return "error", tup_err, {} # 检查是否检测到观看任务(通过 _is_watch_task_detected 标志) is_watch_task = False try: is_watch_task = bool(getattr(analyser, "_is_watch_task_detected", False)) # 清除标志,避免影响后续调用 if is_watch_task: try: analyser._is_watch_task_detected = False except Exception: pass except Exception: pass # 如果检测到观看任务,返回 watch_task 状态 if is_watch_task: try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过", ) except Exception: pass now = time.time() tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_once完成(观看任务)", elapsed_seconds=round(elapsed, 2)) return "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count} # 解析倒计时 -> (剩余秒数, 未来时间戳) countdown_start = time.time() countdown_end = countdown_start + 60.0 try: if time_text: res = analyser.operation.check_countdown(time_text) if isinstance(res, tuple) and len(res) == 2: total_seconds, future_ts = res try: total_seconds = int(total_seconds) except Exception: total_seconds = int(float(total_seconds or 0)) if total_seconds > 0 and isinstance(future_ts, (int, float)): countdown_start = float(countdown_start) countdown_end = float(future_ts) except Exception: pass detail_tuple = ( content or "", time_text or "", int(participants or 0), int(copies or 0), float(prize_value_yuan or 0.0), (countdown_start, countdown_end), ) extra: Dict[str, Any] = { "task_count": task_count, } # 获取直播间名字 room_title = "" room_title_raw = "" try: room_title = str(getattr(analyser, "current_room_title", "") or "").strip() room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip() except Exception: pass # 输出所有识别到的内容到运行日志和行为日志 try: from datetime import datetime # 格式化时间戳为可读格式 countdown_start_str = "" countdown_end_str = "" if countdown_start and countdown_end: try: if countdown_start > 0: countdown_start_str = datetime.fromtimestamp(countdown_start).strftime("%Y-%m-%d %H:%M:%S") if countdown_end > 0: countdown_end_str = datetime.fromtimestamp(countdown_end).strftime("%Y-%m-%d %H:%M:%S") except Exception: pass # 计算剩余秒数 remain_seconds = 0 if countdown_end > countdown_start: remain_seconds = int(countdown_end - time.time()) # 输出完整的识别结果到运行日志 content_preview = (content or "")[:60] if content else "未识别到" content_full = content or "" # 添加明确的"福袋内容:"格式输出,确保GUI能正确解析(即使内容为空也输出) analyser._log_kv( "福袋", f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析 level="INFO", ) analyser._log_kv( "福袋详情", f"read_fudai_detail_once 完整识别结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", status="ok", room_title=room_title, room_title_raw=room_title_raw, task_count=task_count, content=content_full, content_length=len(content_full), time_text=time_text or "", participants=int(participants or 0), copies=int(copies or 0), prize_value_yuan=float(prize_value_yuan or 0.0), countdown_start=countdown_start, countdown_start_str=countdown_start_str, countdown_end=countdown_end, countdown_end_str=countdown_end_str, remain_seconds=remain_seconds, elapsed_seconds=round(time.time() - start_time, 2), ) # 输出到行为日志(使用更详细的格式) content_preview = (content or "")[:60] if content else "未识别到" analyser._log_kv( "行为", f"识别福袋详情完成:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", action="识别福袋详情", result="成功", detail={ "直播间": room_title if room_title else room_title_raw, "直播间原始": room_title_raw, "任务数量": task_count, "福袋内容": content or "", "倒计时文本": time_text or "", "参与人数": int(participants or 0), "福袋份数": int(copies or 0), "奖品价值": float(prize_value_yuan or 0.0), "倒计时开始时间": countdown_start_str if countdown_start_str else f"{countdown_start}", "倒计时结束时间": countdown_end_str if countdown_end_str else f"{countdown_end}", "剩余秒数": remain_seconds, }, ) # 输出简化的运行日志(兼容原有格式) analyser._log_kv( "福袋详情", "read_fudai_detail_once 结果", status="ok", content=detail_tuple[0], time_text=detail_tuple[1], participants=detail_tuple[2], copies=detail_tuple[3], prize_value_yuan=detail_tuple[4], countdown_start=countdown_start, countdown_end=countdown_end, task_count=task_count, ) except Exception as e: # 如果详细日志输出失败,至少输出基本信息 try: analyser._log_kv( "福袋详情", "read_fudai_detail_once 结果(简化)", status="ok", content=content or "", time_text=time_text or "", participants=int(participants or 0), copies=int(copies or 0), prize_value_yuan=float(prize_value_yuan or 0.0), error=str(e), ) except Exception: pass elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_once完成(成功)", elapsed_seconds=round(elapsed, 2)) return "ok", detail_tuple, extra def read_fudai_detail_with_retries( analyser: Any, fudai_x: int, read_once_callback, close_detail_callback, ensure_open_callback, ) -> Tuple: """多次重试读取福袋详情,返回 6 字段 detail tuple。 与原版保持兼容:总是返回 (content, time_text, participants, copies, prize_value_yuan, countdown_tuple) """ start_time = time.time() # 首次识别前等待,确保详情页完全加载 # 如果优化查找器已经验证过详情页,可以减少等待时间 already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False) if already_verified: # 已经验证过,只需要短暂等待确保界面稳定 initial_wait = 0.3 try: analyser._log_kv( "福袋详情", "read_fudai_detail_with_retries:优化查找器已验证详情页,缩短等待时间", initial_wait=initial_wait, ) except Exception: pass # 清除标志,避免影响后续调用 try: analyser._fudai_detail_verified = False except Exception: pass else: initial_wait = float( getattr(analyser, "fudai_detail_initial_wait_seconds", 1.2) or 1.2 ) if initial_wait < 0.8: initial_wait = 0.8 # 最小0.8秒 try: analyser.operation.delay(initial_wait) except Exception: time.sleep(initial_wait) max_attempts = 2 try: max_attempts = int(getattr(analyser, "fudai_detail_max_attempts", 2) or 2) except Exception: max_attempts = 2 if max_attempts < 1: max_attempts = 1 retry_delay = 0.8 try: retry_delay = float(getattr(analyser, "fudai_detail_retry_delay_seconds", 0.8) or 0.8) except Exception: retry_delay = 0.8 last_tuple: Optional[Tuple] = None last_status: str = "error" first_countdown_seconds: Optional[float] = None first_tuple: Optional[Tuple] = None first_attempt_time: float = 0.0 for attempt in range(max_attempts): attempt_start_time = time.time() status, tup, extra = read_fudai_detail_once(analyser) last_status = status if isinstance(tup, tuple) and len(tup) >= 6: current_tuple = tup[:6] # 计算当前倒计时秒数 current_countdown_seconds = None try: cd = current_tuple[5] if isinstance(cd, (tuple, list)) and len(cd) >= 2: cd_start = float(cd[0] or 0.0) cd_end = float(cd[1] or 0.0) if cd_start > 0 and cd_end > cd_start: current_countdown_seconds = cd_end - cd_start except Exception: pass # 记录第一次成功读取的结果(作为基准) if first_countdown_seconds is None and current_countdown_seconds is not None and status == "ok": first_countdown_seconds = current_countdown_seconds first_tuple = current_tuple first_attempt_time = attempt_start_time last_tuple = current_tuple # 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误 elif first_countdown_seconds is not None and current_countdown_seconds is not None: # 计算时间流逝(从第一次读取到现在的时间差) time_elapsed = attempt_start_time - first_attempt_time if time_elapsed < 0: time_elapsed = 0.5 # 默认假设间隔0.5秒 # 预期倒计时 = 第一次倒计时 - 时间流逝(允许一定误差) expected_countdown = first_countdown_seconds - time_elapsed # 计算实际差异(与第一次相比) diff_ratio = abs(current_countdown_seconds - first_countdown_seconds) / max(first_countdown_seconds, 1.0) # 计算与预期的差异(考虑时间流逝) expected_diff_ratio = abs(current_countdown_seconds - expected_countdown) / max(expected_countdown, 1.0) if expected_countdown > 0 else 1.0 # 如果差异过大(超过30%)或与预期差异过大(超过20%),判定为识别错误 # 注意:如果当前倒计时明显大于第一次(时间应该减少),肯定是识别错误 is_inconsistent = ( diff_ratio > 0.3 or expected_diff_ratio > 0.2 or current_countdown_seconds > first_countdown_seconds + 10 # 倒计时不应该增加 ) if is_inconsistent: try: analyser._log_kv( "福袋详情", "倒计时识别不一致,判定为识别错误(拒绝本次结果,保留第一次结果)", attempt=attempt + 1, first_countdown_seconds=int(first_countdown_seconds), current_countdown_seconds=int(current_countdown_seconds), expected_countdown=int(expected_countdown), time_elapsed=round(time_elapsed, 2), diff_ratio=round(diff_ratio, 3), expected_diff_ratio=round(expected_diff_ratio, 3), ) except Exception: pass # 拒绝本次结果,继续使用第一次的结果 current_tuple = first_tuple # 如果还有重试机会,继续重试 if attempt < max_attempts - 1: try: analyser.operation.delay(retry_delay) except Exception: time.sleep(retry_delay) continue else: # 倒计时合理,更新为当前结果 last_tuple = current_tuple # 如果没有第一次结果,直接使用当前结果 elif first_countdown_seconds is None: last_tuple = current_tuple # 如果成功读取,或者检测到优惠券弹窗(已处理完毕),或者检测到观看任务,都停止重试 if status == "ok" or status == "coupon_popup" or status == "watch_task": break # 如果任务数量为0,说明没有正确打开福袋详情页,尝试重新打开 if status == "error" and isinstance(extra, dict) and extra.get("reason") == "task_count_zero": if attempt < max_attempts - 1: try: analyser._log_kv( "福袋详情", "read_fudai_detail_with_retries:任务数量为0,尝试重新打开福袋详情页", attempt=attempt + 1, max_attempts=max_attempts, ) except Exception: pass # 调用回调函数重新打开福袋详情页 try: if ensure_open_callback: ensure_open_callback(analyser, fudai_x) # 重新打开后等待一段时间,确保页面加载完成 try: analyser.operation.delay(retry_delay + 0.5) except Exception: time.sleep(retry_delay + 0.5) except Exception as e: try: analyser._log_kv( "福袋详情", "read_fudai_detail_with_retries:重新打开福袋详情页失败", error=str(e), ) except Exception: pass if attempt < max_attempts - 1: try: analyser.operation.delay(retry_delay) except Exception: time.sleep(retry_delay) if last_tuple is None: now = time.time() last_tuple = ("", "", 0, 0, 0.0, (now, now + 60.0)) content, time_text, participants, copies, prize_value_yuan, cd = last_tuple cd_start, cd_end = None, None if isinstance(cd, (tuple, list)) and len(cd) >= 2: cd_start, cd_end = cd[0], cd[1] # 如果是优惠券弹窗,记录日志并明确标记 is_coupon_popup = (last_status == "coupon_popup") is_watch_task = (last_status == "watch_task") # 获取直播间名字(所有情况都需要,用于日志输出) room_title = "" room_title_raw = "" try: room_title = str(getattr(analyser, "current_room_title", "") or "").strip() room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip() except Exception: pass # 格式化时间信息(所有情况都需要,用于日志输出) cd_end_str = "" remain_seconds = 0 try: from datetime import datetime if cd_end and isinstance(cd_end, (int, float)) and cd_end > 0: cd_end_str = datetime.fromtimestamp(cd_end).strftime("%Y-%m-%d %H:%M:%S") remain_seconds = int(cd_end - time.time()) if cd_end > time.time() else 0 except Exception: pass if is_coupon_popup: try: analyser._log_kv( "福袋详情", "read_fudai_detail_with_retries 最终结果:优惠券弹窗,已关闭,跳过后续处理", status=last_status, fudai_x=fudai_x, ) except Exception: pass # 输出到行为日志 try: analyser._log_kv( "行为", "识别福袋详情完成(最终结果)", action="识别福袋详情", result="优惠券弹窗", detail={ "直播间": room_title if room_title else room_title_raw, "直播间原始": room_title_raw, "福袋内容": content or "", "倒计时文本": time_text or "", "参与人数": int(participants or 0), "福袋份数": int(copies or 0), "奖品价值": float(prize_value_yuan or 0.0), "倒计时开始时间": str(cd_start) if cd_start else "", "倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "", "剩余秒数": remain_seconds, "状态": last_status, }, ) except Exception: pass elif is_watch_task: try: analyser._log_kv( "福袋详情", "read_fudai_detail_with_retries 最终结果:观看X分钟任务,已跳过,关闭详情", status=last_status, fudai_x=fudai_x, ) except Exception: pass # 输出到行为日志 try: analyser._log_kv( "行为", "识别福袋详情完成(最终结果)", action="识别福袋详情", result="观看任务", detail={ "直播间": room_title if room_title else room_title_raw, "直播间原始": room_title_raw, "福袋内容": content or "", "倒计时文本": time_text or "", "参与人数": int(participants or 0), "福袋份数": int(copies or 0), "奖品价值": float(prize_value_yuan or 0.0), "倒计时开始时间": str(cd_start) if cd_start else "", "倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "", "剩余秒数": remain_seconds, "状态": last_status, }, ) except Exception: pass # 关闭详情页 try: close_detail_callback(analyser) analyser.operation.delay(0.5) except Exception: pass # 切换直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: try: analyser._log_kv( "福袋详情", "检测到观看任务后切换直播间", ) # 优先使用封装好的上滑切房方法 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 ) analyser.operation.delay(0.5) except Exception: pass else: # 正常情况(成功或错误):输出到运行日志和行为日志 try: # 运行日志:完整的福袋详情 content_preview = (content or "")[:60] if content else "未识别到" content_full = content or "" # 添加明确的"福袋内容:"格式输出,确保GUI能正确解析(即使内容为空也输出) if last_status == "ok": analyser._log_kv( "福袋", f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析 level="INFO", ) analyser._log_kv( "福袋详情", f"read_fudai_detail_with_retries 最终结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", status=last_status, room_title=room_title, room_title_raw=room_title_raw, content=content_full, time_text=time_text, participants=participants, copies=copies, prize_value_yuan=prize_value_yuan, countdown_start=cd_start, countdown_end=cd_end, countdown_end_str=cd_end_str if cd_end_str else "", remain_seconds=remain_seconds, fudai_x=fudai_x, ) # 行为日志:完整的福袋详情 analyser._log_kv( "行为", f"识别福袋详情完成(最终结果):内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", action="识别福袋详情", result="成功" if last_status == "ok" else last_status, detail={ "直播间": room_title if room_title else room_title_raw, "直播间原始": room_title_raw, "福袋内容": content or "", "倒计时文本": time_text or "", "参与人数": int(participants or 0), "福袋份数": int(copies or 0), "奖品价值": float(prize_value_yuan or 0.0), "倒计时开始时间": str(cd_start) if cd_start else "", "倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "", "剩余秒数": remain_seconds, "状态": last_status, }, ) except Exception as e: # 如果日志输出失败,至少尝试输出简化版本 try: analyser._log_kv( "福袋详情", "read_fudai_detail_with_retries 最终结果(简化)", status=last_status, content=content or "", error=str(e), ) except Exception: pass # 将状态信息存储在 analyser 中,供调用方检查 try: analyser._last_fudai_detail_status = last_status # type: ignore[attr-defined] # 同时保存 extra 信息,用于检查错误原因 if isinstance(extra, dict): analyser._last_fudai_detail_extra = extra # type: ignore[attr-defined] else: analyser._last_fudai_detail_extra = {} # type: ignore[attr-defined] except Exception: pass # 验证福袋详情数据的合理性(仅在成功读取时验证) if last_status == "ok": is_valid, reason = validate_fudai_detail(last_tuple, analyser) if not is_valid: try: analyser._log_kv( "福袋详情", "read_fudai_detail_with_retries:数据验证失败,识别可能出错", validation_reason=reason, content=content[:50] if content else "", prize_value_yuan=prize_value_yuan, participants=participants, copies=copies, time_text=time_text[:30] if time_text else "", ) # 标记为识别错误 analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined] except Exception: pass elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_with_retries完成", elapsed_seconds=round(elapsed, 2), status=last_status, attempts=max_attempts) return last_tuple def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, str]: """验证福袋详情数据的合理性。 返回: (is_valid, reason) - is_valid=True 表示数据合理,False 表示识别出错 reason 为失败原因描述 """ if not isinstance(detail, tuple) or len(detail) < 6: return False, "detail_tuple_invalid" content = str(detail[0] or "").strip() time_text = str(detail[1] or "").strip() 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 countdown_tuple = detail[5] countdown_start, countdown_end = None, None if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: try: countdown_start = float(countdown_tuple[0] or 0.0) countdown_end = float(countdown_tuple[1] or 0.0) except Exception: pass # 检查1:内容不能为空(至少要有一些文字) if not content or len(content.strip()) < 2: return False, "content_empty_or_too_short" # 检查2:价值应该大于0(福袋至少应该有价值) if prize_value_yuan <= 0: return False, "prize_value_zero_or_negative" # 检查3:价值应该合理(不能太大,比如超过100万) if prize_value_yuan > 1000000: return False, "prize_value_too_large" # 检查4:倒计时应该合理 if countdown_end is not None and countdown_start is not None: remain_seconds = countdown_end - countdown_start # 倒计时不能是负数 if remain_seconds < 0: return False, "countdown_negative" # 倒计时不能太长(超过24小时) if remain_seconds > 24 * 3600: return False, "countdown_too_long" # 倒计时不能为0(至少应该有几秒) if remain_seconds == 0 and not time_text: return False, "countdown_zero_and_no_time_text" # 倒计时合理性检查:如果 time_text 存在,验证倒计时与 time_text 是否一致 if time_text: try: # 解析 time_text 为秒数 import re m = re.search(r"(\d{1,2})[::](\d{1,2})", time_text) if m: mm = int(m.group(1)) ss = int(m.group(2)) # 如果秒数>=60,尝试交换分秒 if ss >= 60 and mm < 60: mm, ss = ss, mm # 如果秒数仍然>=60,进行进位 if ss >= 60: mm += ss // 60 ss = ss % 60 text_seconds = mm * 60 + ss # 允许一定误差(±10%),但差异过大则判定为识别错误 if text_seconds > 0: diff_ratio = abs(remain_seconds - text_seconds) / max(text_seconds, 1.0) if diff_ratio > 0.15: # 差异超过15%视为不一致 return False, f"countdown_mismatch_time_text (remain={int(remain_seconds)}, text={text_seconds}, diff={round(diff_ratio*100, 1)}%)" except Exception: pass # 检查5:参与人数应该合理(不能是负数) if participants < 0: return False, "participants_negative" # 检查6:份数应该合理(不能是负数,至少应该是1) if copies < 0: return False, "copies_negative" # 检查7:如果份数为0,但参与人数大于0,可能识别错误 if copies == 0 and participants > 0: return False, "copies_zero_but_participants_positive" # 检查8:时间文本应该存在(至少应该有倒计时信息) if not time_text and (countdown_end is None or countdown_end <= 0): return False, "no_time_text_and_no_countdown" # 所有检查通过 return True, "ok" def is_abnormal_time_value(v: float) -> bool: """Shim: treat clearly invalid time values as abnormal.""" if v <= 0: return True if v > 24 * 3600 * 7: return True return False