diff --git a/douyin/fudai/douyin_fudai_contain_impl.py b/douyin/fudai/douyin_fudai_contain_impl.py new file mode 100644 index 0000000..941af61 --- /dev/null +++ b/douyin/fudai/douyin_fudai_contain_impl.py @@ -0,0 +1,1009 @@ +from __future__ import annotations + +import os +import time +import threading +from typing import Tuple, Any, Optional, Dict, List + +from douyin.utils.douyin_utils import extract_prize_value_yuan +from douyin.core import path_config +from douyin.fudai.core.fudai_filter import ( + is_watch_task_fudai, + _is_short_countdown_text, +) + +# 从新模块导入调试工具函数 +from douyin.fudai.core.fudai_debug_utils import ( + _save_full_screenshot_with_ocr_region, +) + + +# 从子包 re-export(保持兼容):薄壳 forwarding +from douyin.fudai.douyin_fudai_core_pkg import ( + attend_choujiang, + basic_join_decision, + check_have_reward_notice_confirm, + check_in_order_confirm_page, + check_lucky_draw_result, + get_reward, + _get_fudai_ocr_executor, + is_watch_task_fudai, + should_skip_fudai_by_config, + _is_short_countdown_text, +) +from douyin.fudai.douyin_fudai_core_pkg.contain_helpers import ( + extract_participants_and_clean, + is_blank_text, + run_heavy_ocr, + should_use_heavy, +) +from douyin.fudai.douyin_fudai_core_pkg.button_state import ( + apply_button_ocr_result, + decide_button_status, +) +from douyin.fudai.douyin_fudai_core_pkg.parallel_exec import run_parallel_tasks +from douyin.fudai.douyin_fudai_core_pkg.watch_task import ( + handle_content_watch_task, + handle_task_list_watch_task, +) +from douyin.fudai.douyin_fudai_core_pkg.countdown_parse import ( + extract_countdown_digits, + parse_countdown_time_text, +) +from douyin.fudai.douyin_fudai_core_pkg.contain_postprocess import ( + log_enter_live_latency, + persist_room_detail_map, + update_live_room_title, + validate_value_ocr, +) + +try: + from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore +except Exception: # pyright: ignore + # 在运行环境中可能缺少 OCR 预处理依赖,提供回退实现以避免导入失败导致程序中断。 + def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore # pyright: ignore + """回退的 preprocess_for_ocr:直接返回 picname(不做预处理)。""" + try: + return str(picname) + except TypeError: # pyright: ignore + return picname + + +# 模块级线程池状态,用于复用 OCR 并行执行,避免频繁创建/销毁 + + +def _emit_flow_flag(analyser: Any, flag: str, status: str, **extra) -> None: + try: + payload = { + "flag": str(flag or ""), + "status": str(status or ""), + "run_id": str(getattr(analyser, "_run_id", "") or ""), + } + payload.update(extra or {}) + analyser._log_kv("流程标志", f"[FLOW_FLAG] {flag}:{status}", **payload) + except Exception: + pass + + +def _extract_two_digits(text: Any) -> str: + """提取最多两位数字;与倒计时最终解析保持同一策略。""" + return extract_countdown_digits(str(text or ""), max_digits=2) + + +def _build_countdown_candidate_boxes(renwu: int) -> List[Tuple[int, int, int, int]]: + """构建倒计时候选框列表:主候选优先,其余候选按稳定顺序补充。""" + from douyin.fudai.core.coords import ( + COUNTDOWN_1010_1130, + COUNTDOWN_1110_1230, + COUNTDOWN_1140_1290, + COUNTDOWN_1460_1580, + ) + + if renwu == 1: + primary = COUNTDOWN_1140_1290 + elif renwu == 2: + primary = COUNTDOWN_1110_1230 + elif renwu == 3: + primary = COUNTDOWN_1010_1130 + else: + primary = COUNTDOWN_1460_1580 + + ordered: List[Tuple[int, int, int, int]] = [] + for box in ( + primary, + COUNTDOWN_1140_1290, + COUNTDOWN_1110_1230, + COUNTDOWN_1010_1130, + COUNTDOWN_1460_1580, + ): + if box not in ordered: + ordered.append(box) + return ordered + + +def _cut_countdown_candidate_regions( + analyser: Any, + box: Tuple[int, int, int, int], + mm_name: str, + ss_name: str, + *, + save_debug_images: bool = False, +) -> None: + """按稳定分割比例切分钟/秒候选区域,降低混入“后开奖”等文本的概率。""" + x1, y1, x2, y2 = box + w = max(1, int(x2 - x1)) + + # 经验分割:分钟在左 0~26%,秒在中部 38%~64%,避开中间冒号与右侧“后开奖”文本。 + mm_x1 = x1 + mm_x2 = min(x2, x1 + max(1, int(w * 0.26))) + ss_x1 = min(x2 - 1, x1 + max(1, int(w * 0.38))) + ss_x2 = min(x2, max(ss_x1 + 1, x1 + max(2, int(w * 0.64)))) + + if save_debug_images: + try: + _save_full_screenshot_with_ocr_region( + analyser, mm_name, (mm_x1, y1, mm_x2, y2), analyser.y_pianyi + ) + _save_full_screenshot_with_ocr_region( + analyser, ss_name, (ss_x1, y1, ss_x2, y2), analyser.y_pianyi + ) + except Exception: + pass + + analyser.cut_pic(mm_x1, y1, mm_x2, y2, "", mm_name, analyser.y_pianyi) + analyser.cut_pic(ss_x1, y1, ss_x2, y2, "", ss_name, analyser.y_pianyi) + + +def _pick_best_countdown_candidate( + analyser: Any, + candidates: List[Dict[str, Any]], + *, + room_title_hint: str = "", +) -> Optional[Dict[str, Any]]: + """从多个倒计时候选中挑选最可信的一个(数值合法 + 时间连续性)。""" + room_title_now = str( + room_title_hint or getattr(analyser, "current_room_title_raw", "") or "" + ) + prev_room_title = str(getattr(analyser, "_countdown_last_room_title", "") or "") + same_room = bool(room_title_now and room_title_now == prev_room_title) + + prev_total: Optional[int] = None + if same_room: + try: + prev_total_val = getattr(analyser, "_last_countdown_total_seconds", None) + if prev_total_val is not None: + prev_total = int(prev_total_val) + except Exception: + prev_total = None + + best: Optional[Dict[str, Any]] = None + best_score = -10**9 + + for cand in candidates: + mm = _extract_two_digits(cand.get("mm_raw")) + ss = _extract_two_digits(cand.get("ss_raw")) + cand["mm"] = mm + cand["ss"] = ss + cand["valid"] = False + cand["total_seconds"] = None + + score = 0 + if cand.get("is_primary"): + score += 8 + + if mm and ss: + try: + mm_i = int(mm) + ss_i = int(ss) + if 0 <= mm_i <= 59 and 0 <= ss_i <= 59: + cand["valid"] = True + total = mm_i * 60 + ss_i + cand["total_seconds"] = total + score += 100 + # 更偏好两段都完整为两位数字的候选。 + if len(str(cand.get("mm_raw") or "")) >= 2: + score += 3 + if len(str(cand.get("ss_raw") or "")) >= 2: + score += 3 + + # 同直播间内优先选择“倒计时递减”的候选,避免错行跳数。 + if prev_total is not None: + if total <= prev_total + 3: + score += 24 + else: + score -= 16 + if abs(total - prev_total) <= 120: + score += 8 + else: + score -= 12 + except Exception: + score -= 12 + else: + score -= 20 + + cand["score"] = score + if score > best_score: + best = cand + best_score = score + + return best + + +def _select_countdown_from_candidates( + analyser: Any, + candidate_meta: List[Dict[str, Any]], + primary_mm_raw: Any, + primary_ss_raw: Any, + extra_results: Dict[str, Any], + *, + room_title_hint: str = "", +) -> Tuple[Any, Any, Optional[Dict[str, Any]]]: + """根据候选 OCR 结果选择最可信倒计时,返回 (mm_raw, ss_raw, best_candidate)。""" + candidates: List[Dict[str, Any]] = [] + for meta in candidate_meta: + is_primary = bool(meta.get("is_primary")) + if is_primary: + mm_raw = primary_mm_raw + ss_raw = primary_ss_raw + else: + mm_raw = extra_results.get(str(meta.get("mm_result_key") or ""), None) + ss_raw = extra_results.get(str(meta.get("ss_result_key") or ""), None) + + candidates.append( + { + "idx": int(meta.get("idx", -1)), + "box": tuple(meta.get("box") or ()), + "is_primary": is_primary, + "mm_raw": mm_raw, + "ss_raw": ss_raw, + } + ) + + best = _pick_best_countdown_candidate( + analyser, + candidates, + room_title_hint=room_title_hint, + ) + try: + snapshot = [] + for cand in candidates: + box = cand.get("box") or () + snapshot.append( + { + "idx": int(cand.get("idx", -1) or -1), + "primary": bool(cand.get("is_primary")), + "mm_raw": str(cand.get("mm_raw") or ""), + "ss_raw": str(cand.get("ss_raw") or ""), + "mm": str(cand.get("mm") or ""), + "ss": str(cand.get("ss") or ""), + "valid": bool(cand.get("valid")), + "score": int(cand.get("score", 0) or 0), + "box": tuple(box)[:4], + } + ) + analyser._log_kv( + "倒计时", + "倒计时候选评分", + room_title_hint=str(room_title_hint or "")[:40], + candidate_count=len(snapshot), + candidates=snapshot, + ) + except Exception: + pass + if best and bool(best.get("valid")): + mm_sel = str(best.get("mm") or "") + ss_sel = str(best.get("ss") or "") + if mm_sel and ss_sel: + return mm_sel, ss_sel, best + return primary_mm_raw, primary_ss_raw, best + + +def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: + """获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。""" + _emit_flow_flag(analyser, "fudai_contain", "start", renwu=int(renwu or 0)) + + # 检查是否启用调试截图保存(默认False,正常运行时跳过以提升性能) + try: + save_debug_images = bool( + getattr(analyser, "fudai_detail_save_debug_images", False) + ) + except Exception: + save_debug_images = False + # 如果analyser未提供配置,回退到全局配置文件 + if not save_debug_images: + try: + import json + + cfg_path = path_config.get_config_path() + if os.path.exists(cfg_path): + with open(cfg_path, "r", encoding="utf-8") as f: + cfg = json.load(f) + save_debug_images = bool( + cfg.get("fudai_detail_save_debug_images", False) + ) + except Exception: # pyright: ignore[reportTooBroadExceptionType] + pass + + # 轻重分流模式:auto(缺失字段才跑重)、light(只跑轻)、heavy(轻后必跑重) + try: + ocr_mode = str( + getattr(analyser, "fudai_detail_ocr_mode", "light") or "light" + ).lower() # 优化:默认使用light模式,提升性能 + except Exception: + ocr_mode = "light" + force_light = ocr_mode == "light" + force_heavy = ocr_mode == "heavy" + + # 切割直播间标题图片(用于并行 OCR) + from douyin.fudai.core.coords import LIVE_ROOM_TITLE, PARTICIPATE_BUTTON, TASK_LIST + analyser.cut_pic(*LIVE_ROOM_TITLE, "", "live_room_title_mid", analyser.y_pianyi) + + # 切割内容/倒计时/价值(按 renwu 选 countdown_box) + from douyin.fudai.douyin_fudai_core_pkg.cut_regions import cut_detail_regions + countdown_box = cut_detail_regions( + analyser, renwu, save_debug_images=save_debug_images + ) + # 额外切割倒计时候选区域(用于并行多候选OCR,根治分钟框偏移) + countdown_candidate_meta: List[Dict[str, Any]] = [] + try: + candidate_boxes = _build_countdown_candidate_boxes(renwu) + for idx, box in enumerate(candidate_boxes): + is_primary = (tuple(box) == tuple(countdown_box)) + if is_primary: + # 主候选沿用原始“福袋倒计时_分钟/秒”命名,兼容现有OCR与调试图像链路 + mm_name = "福袋倒计时_分钟" + ss_name = "福袋倒计时_秒" + mm_key = "countdown_mm" + ss_key = "countdown_ss" + else: + mm_name = f"福袋倒计时_候选{idx}_分钟" + ss_name = f"福袋倒计时_候选{idx}_秒" + mm_key = f"countdown_mm_c{idx}" + ss_key = f"countdown_ss_c{idx}" + _cut_countdown_candidate_regions( + analyser, + tuple(box), + mm_name, + ss_name, + save_debug_images=save_debug_images, + ) + + countdown_candidate_meta.append( + { + "idx": idx, + "box": tuple(box), + "is_primary": is_primary, + "mm_name": mm_name, + "ss_name": ss_name, + "mm_result_key": mm_key, + "ss_result_key": ss_key, + } + ) + except Exception: + countdown_candidate_meta = [ + { + "idx": 0, + "box": tuple(countdown_box), + "is_primary": True, + "mm_name": "福袋倒计时_分钟", + "ss_name": "福袋倒计时_秒", + "mm_result_key": "countdown_mm", + "ss_result_key": "countdown_ss", + } + ] + + # 准备任务列表区域的截图(用于并行OCR) + # 任务列表区域(任务位置:50,1621到1032,1960),用于检测"观看X分钟"任务 + try: + # 保存任务列表区域的调试截图(仅在配置启用时) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi + ) + analyser.cut_pic(*TASK_LIST, "", "福袋任务列表", analyser.y_pianyi) + except Exception as e_inner: # pyright: ignore[reportTooBroadExceptionType] + # 任务列表截图失败不影响后续流程,记录日志即可 + try: + analyser._log_kv( # pyright: ignore[reportPrivateUsage] + "福袋", + "任务列表截图失败,继续后续流程", + error=str(e_inner), + ) + except Exception: # pyright: ignore[reportTooBroadExceptionType] + pass + + # 准备参与按钮区域的截图(用于并行OCR识别按钮状态) + try: + # 保存参与按钮区域的调试截图(仅在配置启用时) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "参与按钮", PARTICIPATE_BUTTON, analyser.y_pianyi + ) + analyser.cut_pic(*PARTICIPATE_BUTTON, "", "参与按钮", analyser.y_pianyi) + except Exception as e_inner: # pyright: ignore[reportTooBroadExceptionType] + # 按钮截图失败不影响后续流程,记录日志即可 + try: + analyser._log_kv( # pyright: ignore[reportPrivateUsage] + "福袋", + "参与按钮截图失败,继续后续流程", + error=str(e_inner), + ) + 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 + button_text_raw = None + # 并行子任务耗时收集(ms),由各子任务在 finally 中写入 + perf_task_durations: Dict[str, float] = {} + perf_task_lock = threading.Lock() + + # 读取内容 OCR 配置开关(其它开关在 OcrTaskRunner 内部按需读取) + from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import _read_disable_flag + disable_content_recognition = _read_disable_flag( + analyser, + "fudai_disable_content_recognition", + "fudai_disable_content_recognition", + ) + + # 7 个并行 OCR 子任务封装到 OcrTaskRunner + from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import OcrTaskRunner + _ocr_runner = OcrTaskRunner( + analyser, + perf_task_durations, + perf_task_lock, + disable_content_recognition=disable_content_recognition, + ) + ocr_task_list = _ocr_runner.ocr_task_list + ocr_content = _ocr_runner.ocr_content + ocr_countdown_mm = _ocr_runner.ocr_countdown_mm + ocr_countdown_ss = _ocr_runner.ocr_countdown_ss + ocr_value = _ocr_runner.ocr_value + ocr_button = _ocr_runner.ocr_button + ocr_live_room_title = _ocr_runner.ocr_live_room_title + + # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) + # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 + try: + _emit_flow_flag(analyser, "fudai_contain_ocr", "parallel_start") + # 使用动态线程池大小,根据CPU核心数优化,并复用线程池 + from operations.screenshot_service import get_optimal_workers + + optimal_workers = get_optimal_workers() + executor = _get_fudai_ocr_executor(optimal_workers) + + task_funcs = { + "task_list": ocr_task_list, + "countdown_mm": ocr_countdown_mm, + "countdown_ss": ocr_countdown_ss, + "value": ocr_value, + "button": ocr_button, + "live_room_title": ocr_live_room_title, + } + # 并行补充倒计时额外候选(保持并行,不降级) + for meta in countdown_candidate_meta: + if meta.get("is_primary"): + continue + mm_name = str(meta.get("mm_name") or "") + ss_name = str(meta.get("ss_name") or "") + mm_key = str(meta.get("mm_result_key") or "") + ss_key = str(meta.get("ss_result_key") or "") + if not mm_name or not ss_name or not mm_key or not ss_key: + continue + task_funcs[mm_key] = ( + lambda name=mm_name: "".join( + ch + for ch in str( + analyser.operation.analyse_pic_digits(name, 0) or "" + ) + if ch.isdigit() + ) + ) + task_funcs[ss_key] = ( + lambda name=ss_name: "".join( + ch + for ch in str( + analyser.operation.analyse_pic_digits(name, 0) or "" + ) + if ch.isdigit() + ) + ) + # 如果配置启用,避免把 content 任务加入并行队列,彻底不调度该OCR + if not disable_content_recognition: + task_funcs["content"] = ocr_content + task_list_raw = fudai_content_raw = countdown_mm_raw = None + countdown_ss_raw = value_raw = None + live_room_title_raw = live_room_title_text_raw = None + + # 收集结果并记录耗时 + results, durations = run_parallel_tasks(task_funcs, executor) + extra_countdown_results: Dict[str, Any] = {} + for name, res in results.items(): + if name == "task_list": + task_list_raw = res + elif name == "content": + fudai_content_raw = res + elif name == "countdown_mm": + countdown_mm_raw = res + elif name == "countdown_ss": + countdown_ss_raw = res + elif name == "value": + value_raw = res + elif name == "button": + button_text_raw = res + elif name == "live_room_title": + live_room_title_raw, live_room_title_text_raw = res + elif name.startswith("countdown_mm_c") or name.startswith("countdown_ss_c"): + extra_countdown_results[name] = res + + try: + countdown_mm_raw, countdown_ss_raw, picked = _select_countdown_from_candidates( + analyser, + countdown_candidate_meta, + countdown_mm_raw, + countdown_ss_raw, + extra_countdown_results, + room_title_hint=str(live_room_title_text_raw or live_room_title_raw or ""), + ) + if picked: + analyser._log_kv( + "倒计时", + "倒计时候选选择结果", + chosen_idx=int(picked.get("idx", -1) or -1), + chosen_is_primary=bool(picked.get("is_primary")), + chosen_mm=str(picked.get("mm") or ""), + chosen_ss=str(picked.get("ss") or ""), + chosen_score=int(picked.get("score", 0) or 0), + chosen_valid=bool(picked.get("valid")), + candidates=len(countdown_candidate_meta), + ) + except Exception as e_pick: + try: + analyser._log_kv( + "倒计时", + "倒计时候选选择异常,回退主候选", + error=str(e_pick), + error_type=type(e_pick).__name__, + level="WARNING", + ) + except Exception: + pass + + try: + analyser._log_kv( + "性能", + "并行OCR子任务耗时(ms)", + **{f"ocr_{k}": v for k, v in durations.items()}, + ) + except Exception: + pass + _emit_flow_flag( + analyser, + "fudai_contain_ocr", + "parallel_done", + has_content=bool(fudai_content_raw), + has_button=bool(button_text_raw), + has_countdown_mm=bool(countdown_mm_raw), + has_countdown_ss=bool(countdown_ss_raw), + ) + + # 输出一行紧凑的并行 OCR 汇总,便于日志聚合分析 + try: + total_ocr_ms = round((time.time() - ocr_start_time) * 1000, 1) + durations_str = ",".join(f"{k}={v}" for k, v in durations.items()) + import logging + + logging.info( + "[OCR汇总] total_ms=%.1f %s", + total_ocr_ms, + durations_str, + ) + except Exception: + pass + + # 轻重分流:轻量OCR跑完后,仅在缺字段或强制时补充重OCR + try: + heavy_fields = should_use_heavy( + force_light, + force_heavy, + fudai_content_raw, + countdown_mm_raw, + countdown_ss_raw, + value_raw, + task_list_raw, + button_text_raw, + ) + except Exception: + heavy_fields = set() + + if heavy_fields: + heavy_res = run_heavy_ocr(analyser, heavy_fields) + + def _prefer(new_val: Any, old_val: Any): + return new_val if not is_blank_text(new_val) else old_val + + task_list_raw = _prefer(heavy_res.get("task_list"), task_list_raw) + fudai_content_raw = _prefer(heavy_res.get("content"), fudai_content_raw) + countdown_mm_raw = _prefer(heavy_res.get("countdown_mm"), countdown_mm_raw) + countdown_ss_raw = _prefer(heavy_res.get("countdown_ss"), countdown_ss_raw) + value_raw = _prefer(heavy_res.get("value"), value_raw) + button_text_raw = _prefer(heavy_res.get("button"), button_text_raw) + + try: + if ("countdown_mm" in heavy_fields) or ("countdown_ss" in heavy_fields): + countdown_mm_raw, countdown_ss_raw, picked_heavy = _select_countdown_from_candidates( + analyser, + countdown_candidate_meta, + countdown_mm_raw, + countdown_ss_raw, + extra_countdown_results, + room_title_hint=str(live_room_title_text_raw or live_room_title_raw or ""), + ) + if picked_heavy: + analyser._log_kv( + "倒计时", + "重OCR后倒计时候选复选结果", + chosen_idx=int(picked_heavy.get("idx", -1) or -1), + chosen_is_primary=bool(picked_heavy.get("is_primary")), + chosen_mm=str(picked_heavy.get("mm") or ""), + chosen_ss=str(picked_heavy.get("ss") or ""), + chosen_score=int(picked_heavy.get("score", 0) or 0), + chosen_valid=bool(picked_heavy.get("valid")), + candidates=len(countdown_candidate_meta), + ) + except Exception: + pass + + try: + analyser._log_kv( + "性能", + "福袋详情OCR轻重分流:触发重OCR补齐", + mode=ocr_mode, + heavy_fields=sorted(list(heavy_fields)), + heavy_duration_ms=heavy_res.get("_duration_ms"), + ) + except Exception: + pass + + # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) + if handle_task_list_watch_task(analyser, task_list_raw, fallback=False): + return "", "", 0, 0, 0.0 + + # 处理按钮识别结果,判断参与状态并做决策 + button_status = None + if button_text_raw: + button_text = str(button_text_raw).strip() + try: + analyser._log_kv( + "参与", + "主并行OCR识别参与按钮", + button_text=button_text if button_text else "", + ) + except Exception: + pass + + button_status = decide_button_status(button_text) + + # 将按钮状态存储到 analyser 对象中 + try: + apply_button_ocr_result( + analyser, + button_text_raw=button_text_raw, + button_status=button_status, + fudai_content_raw=fudai_content_raw, + task_list_raw=task_list_raw, + countdown_mm_raw=countdown_mm_raw, + countdown_ss_raw=countdown_ss_raw, + value_raw=value_raw, + live_room_title_raw=live_room_title_raw, + log_prefix="主", + record_room_pos=True, + ) + except Exception: + pass + + ocr_elapsed = time.time() - ocr_start_time + try: + analyser._log_kv( + "性能", + "并行OCR识别完成(任务数量已在前置检测中获取)", + elapsed_seconds=round(ocr_elapsed, 3), + task_count=renwu, + button_status=button_status or "未识别", + ) + # 输出所有OCR识别结果详情 + ocr_results = { + "福袋内容": fudai_content_raw[:100] if fudai_content_raw else "未识别", + "任务列表": task_list_raw[:100] if task_list_raw else "未识别", + "倒计时分钟": countdown_mm_raw if countdown_mm_raw else "未识别", + "倒计时秒": countdown_ss_raw if countdown_ss_raw else "未识别", + "奖品价值": value_raw[:50] if value_raw else "未识别", + "按钮文本": button_text_raw if button_text_raw else "未识别", + "直播间标题": ( + live_room_title_raw[:100] if live_room_title_raw else "未识别" + ), + } + analyser._log_kv("详情", "并行OCR识别结果详情", **ocr_results) + except Exception as e_inner: + try: + analyser._log_kv( + "错误", + "记录OCR性能日志失败", + error=str(e_inner), + error_type=type(e_inner).__name__, + level="WARNING", + ) + except Exception: + pass + except Exception as e_inner: + # 如果并行执行失败,按需决定是否走备用并行(可跳过以节省时间) + _emit_flow_flag( + analyser, + "fudai_contain_ocr", + "parallel_exception", + error_type=type(e_inner).__name__, + error=str(e_inner), + ) + try: + analyser._log_kv( + "错误", + "并行OCR失败", + error=str(e_inner), + error_type=type(e_inner).__name__, + level="ERROR", + ) + except Exception: + pass + + # 可选跳过备用并行,加快失败路径(默认启用备用;可通过 analyser.enable_fudai_ocr_fallback 控制) + try: + enable_fallback_parallel = bool( + getattr(analyser, "enable_fudai_ocr_fallback", True) + ) + except Exception: + enable_fallback_parallel = True + + if not enable_fallback_parallel: + try: + analyser._log_kv( + "性能", + "跳过备用并行OCR以节省时间", + reason="fallback_disabled", + level="WARNING", + ) + except Exception: + pass + return "", "", 0, 0, 0.0 + + # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) + try: + + # 6 个备用并行 OCR 子任务封装到 OcrTaskRunnerFallback + from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import ( + OcrTaskRunnerFallback, + ) + _fb_runner = OcrTaskRunnerFallback( + analyser, + disable_content_recognition=disable_content_recognition, + ) + ocr_task_list_fallback = _fb_runner.ocr_task_list + ocr_content_fallback = _fb_runner.ocr_content + ocr_countdown_mm_fallback = _fb_runner.ocr_countdown_mm + ocr_countdown_ss_fallback = _fb_runner.ocr_countdown_ss + ocr_value_fallback = _fb_runner.ocr_value + ocr_button_fallback = _fb_runner.ocr_button + + # 使用动态线程池大小,并复用线程池 + from operations.screenshot_service import get_optimal_workers + + optimal_workers = get_optimal_workers() + executor = _get_fudai_ocr_executor(optimal_workers) + + task_funcs = { + "task_list": ocr_task_list_fallback, + "countdown_mm": ocr_countdown_mm_fallback, + "countdown_ss": ocr_countdown_ss_fallback, + "value": ocr_value_fallback, + "button": ocr_button_fallback, + } + # 备用并行中也加入倒计时额外候选 + for meta in countdown_candidate_meta: + if meta.get("is_primary"): + continue + mm_name = str(meta.get("mm_name") or "") + ss_name = str(meta.get("ss_name") or "") + mm_key = str(meta.get("mm_result_key") or "") + ss_key = str(meta.get("ss_result_key") or "") + if not mm_name or not ss_name or not mm_key or not ss_key: + continue + task_funcs[mm_key] = ( + lambda name=mm_name: "".join( + ch + for ch in str( + analyser.operation.analyse_pic_digits(name, 0) or "" + ) + if ch.isdigit() + ) + ) + task_funcs[ss_key] = ( + lambda name=ss_name: "".join( + ch + for ch in str( + analyser.operation.analyse_pic_digits(name, 0) or "" + ) + if ch.isdigit() + ) + ) + # 如果配置允许,则加入备用 content OCR,否则不调度 + if not disable_content_recognition: + task_funcs["content"] = ocr_content_fallback + durations = {} + task_list_raw = fudai_content_raw = countdown_mm_raw = None + countdown_ss_raw = value_raw = button_text_raw = None + results, durations = run_parallel_tasks(task_funcs, executor) + extra_countdown_results_fb: Dict[str, Any] = {} + for name, res in results.items(): + if name == "task_list": + task_list_raw = res + elif name == "content": + fudai_content_raw = res + elif name == "countdown_mm": + countdown_mm_raw = res + elif name == "countdown_ss": + countdown_ss_raw = res + elif name == "value": + value_raw = res + elif name == "button": + button_text_raw = res + elif name.startswith("countdown_mm_c") or name.startswith("countdown_ss_c"): + extra_countdown_results_fb[name] = res + + try: + countdown_mm_raw, countdown_ss_raw, picked_fb = _select_countdown_from_candidates( + analyser, + countdown_candidate_meta, + countdown_mm_raw, + countdown_ss_raw, + extra_countdown_results_fb, + room_title_hint=str( + getattr(analyser, "current_room_title_raw", "") or "" + ), + ) + if picked_fb: + analyser._log_kv( + "倒计时", + "备用并行倒计时候选选择结果", + chosen_idx=int(picked_fb.get("idx", -1) or -1), + chosen_is_primary=bool(picked_fb.get("is_primary")), + chosen_mm=str(picked_fb.get("mm") or ""), + chosen_ss=str(picked_fb.get("ss") or ""), + chosen_score=int(picked_fb.get("score", 0) or 0), + chosen_valid=bool(picked_fb.get("valid")), + candidates=len(countdown_candidate_meta), + ) + except Exception: + pass + + try: + analyser._log_kv( + "性能", + "备用并行OCR子任务耗时(ms)", + **{f"ocr_{k}": v for k, v in durations.items()}, + ) + except Exception: + pass + + # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) + if handle_task_list_watch_task(analyser, task_list_raw, fallback=True): + return "", "", 0, 0, 0.0 + + # 处理备用并行执行的按钮识别结果 + button_status = None + if button_text_raw: + button_text = str(button_text_raw).strip() + try: + analyser._log_kv( + "参与", + "备用并行OCR识别参与按钮", + button_text=button_text if button_text else "", + ) + except Exception: + pass + + button_status = decide_button_status(button_text) + + # 将按钮状态存储到 analyser 对象中 + try: + apply_button_ocr_result( + analyser, + button_text_raw=button_text_raw, + button_status=button_status, + fudai_content_raw=fudai_content_raw, + task_list_raw=task_list_raw, + countdown_mm_raw=countdown_mm_raw, + countdown_ss_raw=countdown_ss_raw, + value_raw=value_raw, + live_room_title_raw=live_room_title_raw, + log_prefix="备用", + ) + except Exception: + pass + except Exception: + pass + + # 先检查原始OCR内容是否是"观看X分钟"任务(在清理之前检查,避免丢失关键信息) + if handle_content_watch_task(analyser, fudai_content_raw, cleaned=False): + return "", "", 0, 0, 0.0 + + participants, copies, fudai_content_text = extract_participants_and_clean( + fudai_content_raw if fudai_content_raw is not None else "" + ) + + # 清理后再次检查观看任务 + if handle_content_watch_task(analyser, fudai_content_text, cleaned=True): + return "", "", 0, 0, 0.0 + + # 输出福袋内容(使用明确的格式,便于GUI解析) + content_for_log = fudai_content_text if fudai_content_text else "未识别到" + # 移除重复输出,因为并行OCR详情中已经包含了此信息 + # analyser._log_kv( + # "福袋", + # f"识别福袋内容:{content_for_log[:100]}", # 在消息中直接包含内容,确保可见 + # level="DEBUG", + # content=content_for_log, # 同时作为字段输出 + # ) + + log_enter_live_latency(analyser, copies, participants) + + # 倒计时:直接使用分割OCR结果(分钟+秒),不再使用完整OCR + time_text = parse_countdown_time_text(analyser, countdown_mm_raw, countdown_ss_raw) + # 移除重复输出,因为并行OCR详情中已经包含了倒计时信息 + # analyser._log_kv( + # "福袋", "识别倒计时", countdown=time_text if time_text else "未识别到" + # ) + + prize_value_yuan = extract_prize_value_yuan( + value_raw if value_raw is not None else "" + ) + + validate_value_ocr(analyser, value_raw, prize_value_yuan) + + update_live_room_title(analyser, live_room_title_raw, live_room_title_text_raw) + + persist_room_detail_map( + analyser, + fudai_content_text, + task_list_raw, + countdown_mm_raw, + countdown_ss_raw, + time_text, + participants, + copies, + prize_value_yuan, + value_raw, + button_text_raw, + live_room_title_raw, + live_room_title_text_raw, + ) + _emit_flow_flag( + analyser, + "fudai_contain", + "return", + content_nonempty=bool(fudai_content_text), + time_text=str(time_text or ""), + prize_value_yuan=float(prize_value_yuan or 0.0), + ) + + return fudai_content_text, time_text, participants, copies, prize_value_yuan + + +# check_contain 已迁移到 douyin.fudai.core.fudai_filter(顶部导入)。 +# 此处保留模块级名称以兼容历史 from douyin_fudai_core import check_contain。 + + diff --git a/douyin/fudai/douyin_fudai_core_pkg/countdown_parse.py b/douyin/fudai/douyin_fudai_core_pkg/countdown_parse.py new file mode 100644 index 0000000..bcb45e4 --- /dev/null +++ b/douyin/fudai/douyin_fudai_core_pkg/countdown_parse.py @@ -0,0 +1,170 @@ +"""倒计时 OCR 结果解析与校验。""" + +from __future__ import annotations + + +def extract_countdown_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: + # 倒计时分钟/秒区域偶发会混入噪声数字(如 "601"、"0123")。 + # 对 2 位提取场景,优先尝试滑窗中第一个“合法”候选(00~59), + # 若都不合法再回退到原有左侧截取策略。 + if max_digits == 2: + windows = [digits[i : i + 2] for i in range(0, len(digits) - 1)] + for win in windows: + try: + v = int(win) + except Exception: + continue + if 0 <= v <= 59: + return win + candidate = digits[:max_digits] + if set(candidate) == {"0"} and digits.lstrip("0"): + actual = digits.lstrip("0")[:max_digits] + return actual.zfill(max_digits) + return candidate + if len(digits) == 1: + return "0" + digits + return digits + + +def _extract_digits(text: str, max_digits: int = 2) -> str: + """兼容旧调用名:转发到 extract_countdown_digits。""" + return extract_countdown_digits(text, max_digits=max_digits) + + +def parse_countdown_time_text(analyser, countdown_mm_raw, countdown_ss_raw) -> str: + """从 OCR 分钟/秒文本构建倒计时字符串,失败时返回空字符串。""" + time_text = "" + try: + mm = ( + extract_countdown_digits(countdown_mm_raw, max_digits=2) + if countdown_mm_raw + else "" + ) + ss = ( + extract_countdown_digits(countdown_ss_raw, max_digits=2) + if countdown_ss_raw + else "" + ) + + 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 + + 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_inner: + try: + analyser._log_kv( + "错误", + "验证倒计时数值失败", + error=str(e_inner), + error_type=type(e_inner).__name__, + mm=mm, + ss=ss, + level="WARNING", + ) + except Exception: + pass + + if mm and ss: + # 结构化校验:分钟/秒任一越界都视为本次倒计时无效,避免把 OCR 噪声带入参与决策。 + try: + mm_int = int(mm) + ss_int = int(ss) + except Exception: + mm_int = -1 + ss_int = -1 + + if 0 <= mm_int <= 59 and 0 <= ss_int <= 59: + time_text = f"{mm}:{ss}" + else: + try: + analyser._log_kv( + "福袋倒计时", + "分割识别结果越界,判定本次倒计时无效", + mm_raw=countdown_mm_raw, + ss_raw=countdown_ss_raw, + mm=mm, + ss=ss, + level="WARNING", + ) + except Exception: + pass + time_text = "" + else: + try: + analyser._log_kv( + "福袋倒计时", + "分割识别失败(分钟或秒为空)", + mm_raw=countdown_mm_raw, + ss_raw=countdown_ss_raw, + ) + except Exception: + pass + except Exception as e_inner: + try: + analyser._log_kv( + "福袋倒计时", + "分割识别异常", + error=str(e_inner), + error_type=type(e_inner).__name__, + ) + except Exception: + pass + return time_text diff --git a/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py b/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py index f9803ba..2209eb6 100644 --- a/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py +++ b/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py @@ -67,21 +67,26 @@ def cut_detail_regions( pass analyser.cut_pic(*CONTENT_BOX, "", "福袋内容", analyser.y_pianyi) - # 2. 倒计时区域分割(前 30% 分钟 + 中间 30% 秒) + # 2. 倒计时区域分割(与候选切图保持一致,避免分钟框吃到前缀噪声) 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%:秒数字框 + mm_x1 = x1 + mm_x2 = min(x2, x1 + max(1, int(w * 0.26))) + ss_x1 = min(x2 - 1, x1 + max(1, int(w * 0.38))) + ss_x2 = min(x2, max(ss_x1 + 1, x1 + max(2, int(w * 0.64)))) if save_debug_images and _save_full_screenshot_with_ocr_region is not None: try: _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi + analyser, + "福袋倒计时_分钟", + (mm_x1, y1, mm_x2, y2), + analyser.y_pianyi, ) except Exception: pass analyser.cut_pic( - x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi + mm_x1, y1, mm_x2, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) if save_debug_images and _save_full_screenshot_with_ocr_region is not None: @@ -89,13 +94,13 @@ def cut_detail_regions( _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), + (ss_x1, y1, ss_x2, y2), analyser.y_pianyi, ) except Exception: pass analyser.cut_pic( - x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi + ss_x1, y1, ss_x2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) # 3. 福袋价值 diff --git a/tests/test_countdown_candidate_selection.py b/tests/test_countdown_candidate_selection.py new file mode 100644 index 0000000..981a691 --- /dev/null +++ b/tests/test_countdown_candidate_selection.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +from unittest.mock import MagicMock + +from douyin.fudai.douyin_fudai_contain_impl import ( + _select_countdown_from_candidates, +) +from douyin.fudai.douyin_fudai_core_pkg.countdown_parse import ( + parse_countdown_time_text, +) + + +def _mk_analyser(): + a = MagicMock() + a._log_kv = MagicMock() + a.current_room_title_raw = "直播间A" + a._countdown_last_room_title = "直播间A" + a._last_countdown_total_seconds = 10 * 60 + return a + + +def test_select_countdown_prefers_valid_non_primary_when_primary_missing(): + analyser = _mk_analyser() + candidate_meta = [ + { + "idx": 0, + "box": (1, 2, 3, 4), + "is_primary": True, + "mm_result_key": "countdown_mm", + "ss_result_key": "countdown_ss", + }, + { + "idx": 1, + "box": (5, 6, 7, 8), + "is_primary": False, + "mm_result_key": "countdown_mm_c1", + "ss_result_key": "countdown_ss_c1", + }, + ] + + mm, ss, best = _select_countdown_from_candidates( + analyser, + candidate_meta, + primary_mm_raw="", + primary_ss_raw="", + extra_results={"countdown_mm_c1": "09", "countdown_ss_c1": "58"}, + room_title_hint="直播间A", + ) + + assert mm == "09" + assert ss == "58" + assert best is not None + assert best.get("idx") == 1 + assert bool(best.get("valid")) is True + + +def test_select_countdown_keeps_primary_when_extra_invalid(): + analyser = _mk_analyser() + candidate_meta = [ + { + "idx": 0, + "box": (1, 2, 3, 4), + "is_primary": True, + "mm_result_key": "countdown_mm", + "ss_result_key": "countdown_ss", + }, + { + "idx": 1, + "box": (5, 6, 7, 8), + "is_primary": False, + "mm_result_key": "countdown_mm_c1", + "ss_result_key": "countdown_ss_c1", + }, + ] + + mm, ss, best = _select_countdown_from_candidates( + analyser, + candidate_meta, + primary_mm_raw="12", + primary_ss_raw="26", + extra_results={"countdown_mm_c1": "99", "countdown_ss_c1": "88"}, + room_title_hint="直播间A", + ) + + assert mm == "12" + assert ss == "26" + assert best is not None + assert bool(best.get("valid")) is True + + +def test_parse_countdown_sliding_window_filters_noise_digits(): + analyser = _mk_analyser() + # 分钟 OCR 噪声 "601" 不应被解析成 "60",应优先取合法窗口 "01" + time_text = parse_countdown_time_text(analyser, "601", "53") + assert time_text == "01:53" + + +def test_select_countdown_uses_sliding_window_for_candidate_validity(): + analyser = _mk_analyser() + candidate_meta = [ + { + "idx": 0, + "box": (1, 2, 3, 4), + "is_primary": True, + "mm_result_key": "countdown_mm", + "ss_result_key": "countdown_ss", + } + ] + + mm, ss, best = _select_countdown_from_candidates( + analyser, + candidate_meta, + primary_mm_raw="601", + primary_ss_raw="53", + extra_results={}, + room_title_hint="直播间A", + ) + + assert mm == "01" + assert ss == "53" + assert best is not None + assert bool(best.get("valid")) is True + + +def test_parse_countdown_rejects_out_of_range_mm_ss(): + analyser = _mk_analyser() + # 分钟与秒都越界时,必须返回空字符串,避免误参与 + time_text = parse_countdown_time_text(analyser, "99", "88") + assert time_text == "" diff --git a/tests/test_cut_regions.py b/tests/test_cut_regions.py index 5f1636d..9fd6f0a 100644 --- a/tests/test_cut_regions.py +++ b/tests/test_cut_regions.py @@ -3,7 +3,7 @@ 覆盖: - _select_countdown_box 4 种 renwu 值返回正确常量 - cut_detail_regions 调用 cut_pic 4 次(内容 + 分钟 + 秒 + 价值) -- 倒计时分割比例(30% / 30%)正确 +- 倒计时分割坐标(分钟 0~26%,秒 38%~64%)正确 - save_debug_images 开关效果 """ from __future__ import annotations @@ -75,24 +75,26 @@ class TestCutDetailRegions: assert names == ["福袋内容", "福袋倒计时_分钟", "福袋倒计时_秒", "福袋价值"] def test_countdown_split_ratio(self): - """倒计时 box 应按 30% 分钟 + 30% 秒 切分。""" + """倒计时 box 应按分钟 0~26%,秒 38%~64% 切分。""" a = _mk_analyser() from douyin.fudai.core.coords import COUNTDOWN_1110_1230 x1, y1, x2, y2 = COUNTDOWN_1110_1230 w = x2 - x1 - seg = int(w * 0.3) + mm_x2 = x1 + int(w * 0.26) + ss_x1 = x1 + int(w * 0.38) + ss_x2 = x1 + int(w * 0.64) cut_detail_regions(a, renwu=2) # 倒计时分钟 = 第 2 次 cut_pic 调用 mm_call = a.cut_pic.call_args_list[1] assert mm_call.args[0] == x1 - assert mm_call.args[2] == x1 + seg + assert mm_call.args[2] == mm_x2 # 倒计时秒 = 第 3 次调用 ss_call = a.cut_pic.call_args_list[2] - assert ss_call.args[0] == x1 + seg - assert ss_call.args[2] == x1 + seg + seg + assert ss_call.args[0] == ss_x1 + assert ss_call.args[2] == ss_x2 def test_save_debug_images_disabled_default(self): a = _mk_analyser()