""" 福袋详情读取模块 ================ 执行福袋详情的OCR识别和读取,包括单次读取和重试读取。 """ from __future__ import annotations from typing import Any, Dict, Tuple, Optional import os import time from PIL import Image from douyin.fudai.douyin_fudai_core import get_fudai_contain from .fudai_detail_validator import validate_fudai_detail 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() # 性能标记变量 screenshot_reused = False screenshot_start = None screenshot_end = None ocr_start = None ocr_end = None wait_file_ms: Optional[float] = None image_load_ms: Optional[float] = None service_stop_ms: Optional[float] = None countdown_parse_ms: Optional[float] = None def _log_perf(tag: str) -> None: try: total_ms = round((time.time() - start_time) * 1000, 1) screenshot_ms = None if screenshot_start is not None and screenshot_end is not None: screenshot_ms = round((screenshot_end - screenshot_start) * 1000, 1) ocr_ms = None if ocr_start is not None and ocr_end is not None: ocr_ms = round((ocr_end - ocr_start) * 1000, 1) analyser._log_kv( "性能", "福袋详情关键耗时(ms)", log_type="PERF", total_ms=total_ms, screenshot_ms=screenshot_ms, ocr_ms=ocr_ms, wait_file_ms=wait_file_ms, image_load_ms=image_load_ms, service_stop_ms=service_stop_ms, countdown_parse_ms=countdown_parse_ms, screenshot_reused=bool(screenshot_reused), tag=tag, ) except Exception: pass # 步骤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:从阶段检测获取任务数量(无需截图)", log_type="OP", task_count=task_count, ) except Exception: pass else: # 如果阶段检测未保存任务数量,记录警告日志 try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:警告:阶段检测未保存任务数量(可能为None)", log_type="DEBUG", task_count_from_stage=task_count_from_stage, ) except Exception: pass pass # 使用默认值 task_count = 2 # 清除任务数量标志,截图复用标志留给后续OCR阶段使用 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), log_type="OP", ) _log_perf("taskcount_zero") 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:获取任务数量异常,使用默认值", log_type="ERR", error=str(e), ) except Exception: pass # 异常时使用默认值 task_count = 2 # 步骤2:获取截图(仅用于后续OCR识别内容/倒计时/价值,不是为了获取任务数量) # 注意:此时后台截图服务已被停止,直接调用底层截图避免递归 # 检查是否可以复用阶段诊断时的截图 screenshot_reused = False try: if getattr(analyser, "_screenshot_ready_for_ocr", False): try: import path_config pic_path = path_config.get_screenshot_path() except Exception: pic_path = os.path.join( os.path.dirname(__file__), "pic", "screenshot.png" ) if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024: analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用 screenshot_reused = True try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:复用阶段诊断截图", log_type="SCREENSHOT", reason="stage_diagnosed_task_count_gt_zero", path=pic_path, ) except Exception: pass else: try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:无法复用阶段诊断截图(文件不可用)", log_type="SCREENSHOT", path=pic_path, size=( os.path.getsize(pic_path) if os.path.exists(pic_path) else 0 ), ) except Exception: pass except Exception: pass # 只有在不能复用截图时才进行新的截图 if not screenshot_reused: try: screenshot_start = time.time() analyser.operation.get_screenshot(analyser.device_id, use_service=False) # 等待截图文件确实存在(最多等待3秒) try: import path_config pic_path = path_config.get_screenshot_path() except Exception: pic_path = os.path.join( os.path.dirname(__file__), "pic", "screenshot.png" ) wait_start = time.time() while time.time() - wait_start < 3.0: if os.path.exists(pic_path): file_size = os.path.getsize(pic_path) if file_size >= 1024: # 至少1KB break time.sleep(0.1) screenshot_end = time.time() wait_file_ms = round((screenshot_end - wait_start) * 1000, 1) _log_perf("after_screenshot") except Exception: screenshot_end = time.time() if screenshot_start is not None else None pass # 使用统一的截图路径配置 try: import path_config pic_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) import path_config pic_path = path_config.get_screenshot_path() pic_rgb = None try: if os.path.exists(pic_path): _img0 = time.time() pic = Image.open(pic_path) pic.load() pic_rgb = pic.convert("RGB") image_load_ms = round((time.time() - _img0) * 1000, 1) _log_perf("after_image_load") 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), ) _log_perf("screenshot_failed") return "error", tup_err, {"reason": "screenshot_failed"} # 如果任务数不在(1,2,3)范围内,默认按2个任务处理 if task_count not in (1, 2, 3): task_count = 2 # 识别福袋内容 / 倒计时 / 价值 # 在OCR密集操作期间临时禁用截图服务,避免后台截图干扰 _ocr_screenshot_service_disabled = False try: from operations.screenshot_service import ScreenshotService service = ScreenshotService.get_instance() if service.is_running(): _svc0 = time.time() # 临时停止后台截图服务,避免在OCR过程中继续截图 service.stop() _ocr_screenshot_service_disabled = True service_stop_ms = round((time.time() - _svc0) * 1000, 1) try: analyser._log_kv( "截图服务", "OCR密集操作期间停止后台截图服务", reason="prevent_background_screenshots_during_ocr", ) except Exception: pass except Exception as e: try: analyser._log_kv( # pyright: ignore[reportPrivateUsage] "截图服务", "停止后台截图服务失败", error=str(e), level="WARNING" ) except Exception: # pyright: ignore[reportTooBroadExceptionType] pass try: ocr_start = time.time() content, time_text, participants, copies, prize_value_yuan = get_fudai_contain( analyser, renwu=task_count ) ocr_end = time.time() _log_perf("after_get_fudai_contain") except Exception as e: # pyright: ignore[reportTooBroadExceptionType] # 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查 try: import traceback tb = traceback.format_exc() # 先尝试通过 analyser._log_kv 输出完整 trace(如果可用) try: analyser._log_kv( # pyright: ignore[reportPrivateUsage] "福袋详情", "read_fudai_detail_once 异常", error=str(e), error_type=type(e).__name__, traceback=tb, ) except Exception: # pyright: ignore[reportTooBroadExceptionType] # fallback: 将 traceback 写入统一错误日志 try: import path_config err_log = path_config.get_error_log_path() with open(err_log, "a", encoding="utf-8") as ef: ef.write( f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] read_fudai_detail_once 异常: {e}\\n" ) ef.write(tb) ef.write("\\n") except Exception: pass except Exception: # pyright: ignore[reportTooBroadExceptionType] try: analyser._log_kv( "福袋详情", "read_fudai_detail_once 异常(无法格式化 traceback)", error=str(e), ) # pyright: ignore[reportPrivateUsage] except Exception: # pyright: ignore[reportTooBroadExceptionType] pass now = time.time() tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time try: analyser._log_kv( "福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2), ) # pyright: ignore[reportPrivateUsage] except Exception: # pyright: ignore[reportTooBroadExceptionType] pass _log_perf("exception_in_get_fudai_contain") 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 # pyright: ignore[reportPrivateUsage] ) except Exception: # pyright: ignore[reportTooBroadExceptionType] pass except Exception: pass # 如果检测到观看任务,返回 watch_task 状态 if is_watch_task: try: analyser._log_kv( # pyright: ignore[reportPrivateUsage] "福袋详情", "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), ) # pyright: ignore[reportPrivateUsage] return ( "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count}, ) # 解析倒计时 -> (剩余秒数, 未来时间戳) countdown_start = time.time() countdown_end = countdown_start + 60.0 try: _cd0 = time.time() 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) countdown_parse_ms = round((time.time() - _cd0) * 1000, 1) _log_perf("after_countdown_parse") 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="DEBUG", ) 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), level="DEBUG", ) # 输出到行为日志(使用更详细的格式) 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, }, level="DEBUG", ) # 输出简化的运行日志(兼容原有格式) 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, level="DEBUG", ) 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), level="DEBUG", ) _log_perf("success") 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) # 为了兼容之前对未使用参数的本地检测,我们在本地使用带下划线的别名 _read_once_callback = read_once_callback _close_detail_callback = close_detail_callback _ensure_open_callback = ensure_open_callback if already_verified: # 已经验证过,只需要短暂等待确保界面稳定 # 使用配置项,默认0.2秒(比之前的0.3秒更快) initial_wait = float( getattr(analyser, "fudai_detail_verified_wait_seconds", 0.2) or 0.2 ) if initial_wait < 0.1: initial_wait = 0.1 # 最小0.1秒 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: # 未验证情况,使用配置项,默认0.8秒(比之前的1.2秒更快) initial_wait = float( getattr(analyser, "fudai_detail_initial_wait_seconds", 0.8) or 0.8 ) if initial_wait < 0.5: initial_wait = 0.5 # 最小0.5秒 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 # 使用配置项,默认0.5秒(比之前的0.8秒更快) retry_delay = 0.5 try: retry_delay = float( getattr(analyser, "fudai_detail_retry_delay_seconds", 0.5) or 0.5 ) except Exception: retry_delay = 0.5 if retry_delay < 0.3: retry_delay = 0.3 # 最小0.3秒 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 extra: dict = {} # 初始化 extra,避免未绑定错误 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 # 优化:如果第一次识别成功且数据合理,直接返回,不进行第二次重试 # 检查数据是否合理(有内容、有价值、倒计时合理) content = current_tuple[0] if len(current_tuple) > 0 else "" prize_value = current_tuple[4] if len(current_tuple) > 4 else 0.0 time_text = current_tuple[1] if len(current_tuple) > 1 else "" # 如果数据看起来合理(有内容或价值>0,倒计时合理),直接返回 is_data_reasonable = ( (content and len(content.strip()) > 0) or (prize_value and float(prize_value) > 0) or (time_text and len(time_text.strip()) > 0) ) if is_data_reasonable and current_countdown_seconds > 0: try: analyser._log_kv( "福袋详情", "read_fudai_detail_with_retries:第一次识别成功且数据合理,跳过重试", attempt=attempt + 1, content_preview=content[:30] if content else "", prize_value=prize_value, countdown_seconds=int(current_countdown_seconds), ) except Exception: pass # 直接返回,不进行第二次重试 break # 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误 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