- douyin_fudai_core.py: 移除未使用的 ThreadPoolExecutor/check_contain 导入 和被覆盖的 fudai_result_checker 导入 - ocr_executor.py: 移除重复的 _fudai_ocr_executor_state 初始化 - flow_control_pkg: 移除 stage_handler/no_fudai/find_open 中未使用的导入 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
1191 lines
47 KiB
Python
1191 lines
47 KiB
Python
from __future__ import annotations
|
||
|
||
import os
|
||
import re
|
||
import time
|
||
import threading
|
||
from typing import Tuple, Any, Optional, Dict
|
||
|
||
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,
|
||
is_watch_task_fudai,
|
||
should_skip_fudai_by_config,
|
||
_is_short_countdown_text,
|
||
)
|
||
|
||
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 get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]:
|
||
"""获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。"""
|
||
|
||
# 检查是否启用调试截图保存(默认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"
|
||
|
||
def _read_countdown_split(box: tuple[int, int, int, int]) -> str:
|
||
"""委托给 douyin_fudai_core_pkg.countdown_split.read_countdown_split。
|
||
|
||
保留闭包形式,使 box 默认绑定到当前 analyser / save_debug_images 闭包变量。
|
||
"""
|
||
from douyin.fudai.douyin_fudai_core_pkg.countdown_split import (
|
||
read_countdown_split,
|
||
)
|
||
return read_countdown_split(
|
||
analyser, box, save_debug_images=save_debug_images
|
||
)
|
||
|
||
def _extract_participants_and_clean(text: str):
|
||
if not text:
|
||
return 0, 0, ""
|
||
compact = re.sub(r"\s+", "", str(text))
|
||
# 例如:共1份1173人已参与
|
||
copies = 0
|
||
participants = 0
|
||
m = re.search(r"共(\d+)份", compact)
|
||
if m:
|
||
copies = int(m.group(1))
|
||
m = re.search(r"(\d+)人已参与", compact)
|
||
if m:
|
||
participants = int(m.group(1))
|
||
|
||
# 清理掉份数/参与人数等尾巴,避免干扰关键词匹配
|
||
cleaned = re.sub(r"共\d+份", "", compact)
|
||
cleaned = re.sub(r"\d+人已参与", "", cleaned)
|
||
return participants, copies, cleaned
|
||
|
||
def _is_blank_text(text: Any) -> bool:
|
||
return len(str(text or "").strip()) == 0
|
||
|
||
def _should_use_heavy(
|
||
content_text: Any,
|
||
mm_raw: Any,
|
||
ss_raw: Any,
|
||
value_text: Any,
|
||
task_text: Any,
|
||
button_text: Any,
|
||
) -> set:
|
||
fields: set[str] = set()
|
||
if force_light:
|
||
return fields
|
||
if force_heavy or _is_blank_text(content_text):
|
||
fields.add("content")
|
||
if force_heavy or not (mm_raw and ss_raw):
|
||
fields.update({"countdown_mm", "countdown_ss"})
|
||
if force_heavy or _is_blank_text(value_text):
|
||
fields.add("value")
|
||
if force_heavy or _is_blank_text(task_text):
|
||
fields.add("task_list")
|
||
if force_heavy or _is_blank_text(button_text):
|
||
fields.add("button")
|
||
return fields
|
||
|
||
def _run_heavy_ocr(fields: set[str]) -> Dict[str, Any]:
|
||
"""委托给 douyin_fudai_core_pkg.heavy_ocr.run_heavy_ocr。"""
|
||
from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import run_heavy_ocr
|
||
return run_heavy_ocr(analyser, fields)
|
||
|
||
# 切割直播间标题图片(用于并行 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)
|
||
# 任务列表区域(任务位置: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:
|
||
# 使用动态线程池大小,根据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,
|
||
}
|
||
# 如果配置启用,避免把 content 任务加入并行队列,彻底不调度该OCR
|
||
if not disable_content_recognition:
|
||
task_funcs["content"] = ocr_content
|
||
futures: Dict[str, Any] = {}
|
||
start_ts: Dict[str, float] = {}
|
||
|
||
for name, func in task_funcs.items():
|
||
start_ts[name] = time.time()
|
||
futures[name] = executor.submit(func)
|
||
|
||
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
|
||
|
||
# 收集结果并记录耗时
|
||
durations = {}
|
||
for name, fut in futures.items():
|
||
try:
|
||
res = fut.result()
|
||
finally:
|
||
durations[name] = round(
|
||
(time.time() - start_ts.get(name, time.time())) * 1000, 1
|
||
)
|
||
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
|
||
|
||
try:
|
||
analyser._log_kv(
|
||
"性能",
|
||
"并行OCR子任务耗时(ms)",
|
||
**{f"ocr_{k}": v for k, v in durations.items()},
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 输出一行紧凑的并行 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(
|
||
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(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:
|
||
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 task_list_raw:
|
||
try:
|
||
analyser._log_kv(
|
||
"福袋",
|
||
"OCR识别任务列表区域",
|
||
task_list_text=task_list_raw[:200] if task_list_raw else "",
|
||
)
|
||
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
|
||
# 检查任务列表中是否包含"观看X分钟"任务
|
||
is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw))
|
||
if is_watch_task_in_list:
|
||
try:
|
||
analyser._log_kv(
|
||
"福袋",
|
||
"任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理",
|
||
task_list_text=task_list_raw[:200] if task_list_raw else "",
|
||
)
|
||
except Exception as e_inner:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"记录观看任务检测日志失败",
|
||
error=str(e_inner),
|
||
error_type=type(e_inner).__name__,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 设置标志,让调用方知道这是观看任务
|
||
try:
|
||
analyser._is_watch_task_detected = True
|
||
except Exception as e_inner:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"设置观看任务标志失败",
|
||
error=str(e_inner),
|
||
error_type=type(e_inner).__name__,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 直接返回空内容,后续流程会跳过
|
||
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
|
||
|
||
# 判断按钮状态
|
||
if "参与成功" in button_text or "等待开奖" in button_text:
|
||
button_status = "已参与"
|
||
elif "加入粉丝团" in button_text or "粉丝团" in button_text:
|
||
button_status = "需要加入粉丝团"
|
||
elif (
|
||
"评论" in button_text
|
||
or "发表评论" in button_text
|
||
or "一键发表评论" in button_text
|
||
):
|
||
button_status = "需要评论"
|
||
elif "还需看播" in button_text or "开始观看" in button_text:
|
||
button_status = "需要观看"
|
||
elif "未达成" in button_text:
|
||
button_status = "未达成要求"
|
||
elif "参与抽奖" in button_text or "参与" in button_text:
|
||
button_status = "可以参与"
|
||
else:
|
||
button_status = "未知状态"
|
||
|
||
# 将按钮状态存储到 analyser 对象中
|
||
try:
|
||
analyser._fudai_button_status = button_status
|
||
analyser._fudai_button_text = button_text
|
||
analyser.button_text_raw = (
|
||
button_text_raw # 设置按钮文本原始值供过滤使用
|
||
)
|
||
# 存储所有主并行OCR识别的原始字段供验证使用
|
||
analyser.fudai_content_raw = fudai_content_raw
|
||
analyser.task_list_raw = task_list_raw
|
||
analyser.countdown_mm_raw = countdown_mm_raw
|
||
analyser.countdown_ss_raw = countdown_ss_raw
|
||
analyser.value_raw = value_raw
|
||
analyser.live_room_title_raw = live_room_title_raw
|
||
analyser._fudai_button_ocr_time = time.time() # 记录识别时间
|
||
try:
|
||
analyser._fudai_button_room_pos = int(
|
||
getattr(analyser, "room_pos", 0) or 0
|
||
)
|
||
except Exception:
|
||
pass
|
||
analyser._log_kv(
|
||
"参与",
|
||
"主按钮状态判断",
|
||
status=button_status,
|
||
button_text=button_text if button_text else "",
|
||
)
|
||
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:
|
||
# 如果并行执行失败,按需决定是否走备用并行(可跳过以节省时间)
|
||
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,
|
||
}
|
||
# 如果配置允许,则加入备用 content OCR,否则不调度
|
||
if not disable_content_recognition:
|
||
task_funcs["content"] = ocr_content_fallback
|
||
futures: Dict[str, Any] = {}
|
||
start_ts: Dict[str, float] = {}
|
||
for name, func in task_funcs.items():
|
||
start_ts[name] = time.time()
|
||
futures[name] = executor.submit(func)
|
||
|
||
durations = {}
|
||
task_list_raw = fudai_content_raw = countdown_mm_raw = None
|
||
countdown_ss_raw = value_raw = button_text_raw = None
|
||
for name, fut in futures.items():
|
||
try:
|
||
res = fut.result()
|
||
finally:
|
||
durations[name] = round(
|
||
(time.time() - start_ts.get(name, time.time())) * 1000, 1
|
||
)
|
||
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
|
||
|
||
try:
|
||
analyser._log_kv(
|
||
"性能",
|
||
"备用并行OCR子任务耗时(ms)",
|
||
**{f"ocr_{k}": v for k, v in durations.items()},
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查)
|
||
if task_list_raw:
|
||
try:
|
||
analyser._log_kv(
|
||
"福袋",
|
||
"OCR识别任务列表区域(备用并行)",
|
||
task_list_text=task_list_raw[:200] if task_list_raw else "",
|
||
)
|
||
except Exception as e_inner2:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"记录备用任务列表OCR结果日志失败",
|
||
error=str(e_inner2),
|
||
error_type=type(e_inner2).__name__,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 检查任务列表中是否包含"观看X分钟"任务
|
||
is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw))
|
||
if is_watch_task_in_list:
|
||
try:
|
||
analyser._log_kv(
|
||
"福袋",
|
||
"任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理",
|
||
task_list_text=task_list_raw[:200] if task_list_raw else "",
|
||
)
|
||
except Exception as e_inner2:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"记录备用观看任务检测日志失败",
|
||
error=str(e_inner2),
|
||
error_type=type(e_inner2).__name__,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 设置标志,让调用方知道这是观看任务
|
||
try:
|
||
analyser._is_watch_task_detected = True
|
||
except Exception as e_inner2:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"设置备用观看任务标志失败",
|
||
error=str(e_inner2),
|
||
error_type=type(e_inner2).__name__,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 直接返回空内容,后续流程会跳过
|
||
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
|
||
|
||
# 判断按钮状态
|
||
if "参与成功" in button_text or "等待开奖" in button_text:
|
||
button_status = "已参与"
|
||
elif "加入粉丝团" in button_text or "粉丝团" in button_text:
|
||
button_status = "需要加入粉丝团"
|
||
elif (
|
||
"评论" in button_text
|
||
or "发表评论" in button_text
|
||
or "一键发表评论" in button_text
|
||
):
|
||
button_status = "需要评论"
|
||
elif "还需看播" in button_text or "开始观看" in button_text:
|
||
button_status = "需要观看"
|
||
elif "未达成" in button_text:
|
||
button_status = "未达成要求"
|
||
elif "参与抽奖" in button_text or "参与" in button_text:
|
||
button_status = "可以参与"
|
||
else:
|
||
button_status = "未知状态"
|
||
|
||
# 将按钮状态存储到 analyser 对象中
|
||
try:
|
||
analyser._fudai_button_status = button_status
|
||
analyser._fudai_button_text = button_text
|
||
analyser.button_text_raw = (
|
||
button_text_raw # 设置按钮文本原始值供过滤使用
|
||
)
|
||
# 存储所有备用并行OCR识别的原始字段供验证使用
|
||
analyser.fudai_content_raw = fudai_content_raw
|
||
analyser.task_list_raw = task_list_raw
|
||
analyser.countdown_mm_raw = countdown_mm_raw
|
||
analyser.countdown_ss_raw = countdown_ss_raw
|
||
analyser.value_raw = value_raw
|
||
analyser.live_room_title_raw = live_room_title_raw
|
||
analyser._fudai_button_ocr_time = time.time() # 记录识别时间
|
||
analyser._log_kv(
|
||
"参与",
|
||
"备用按钮状态判断",
|
||
status=button_status,
|
||
button_text=button_text if button_text else "",
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
# 先检查原始OCR内容是否是"观看X分钟"任务(在清理之前检查,避免丢失关键信息)
|
||
is_watch_task = False
|
||
if fudai_content_raw:
|
||
try:
|
||
is_watch_task = is_watch_task_fudai(str(fudai_content_raw))
|
||
if is_watch_task:
|
||
try:
|
||
analyser._log_kv(
|
||
"福袋",
|
||
"OCR识别到'观看X分钟'类任务,直接跳过后续处理",
|
||
raw_content=(
|
||
fudai_content_raw[:100] if fudai_content_raw else ""
|
||
),
|
||
)
|
||
except Exception as e_inner:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"记录观看任务检测日志失败",
|
||
error=str(e_inner),
|
||
error_type=type(e_inner).__name__,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 设置标志,让调用方知道这是观看任务
|
||
try:
|
||
analyser._is_watch_task_detected = True
|
||
except Exception as e_inner:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"设置观看任务标志失败",
|
||
error=str(e_inner),
|
||
error_type=type(e_inner).__name__,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 直接返回空内容,后续流程会跳过
|
||
return "", "", 0, 0, 0.0
|
||
except Exception as e_inner:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"检查观看任务失败",
|
||
error=str(e_inner),
|
||
error_type=type(e_inner).__name__,
|
||
raw_content=fudai_content_raw[:100] if fudai_content_raw else "",
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
participants, copies, fudai_content_text = _extract_participants_and_clean(
|
||
fudai_content_raw if fudai_content_raw is not None else ""
|
||
)
|
||
|
||
# 如果清理后的内容中没有检测到,但原始内容中检测到了,使用原始内容再次确认
|
||
if not is_watch_task and fudai_content_text:
|
||
try:
|
||
is_watch_task = is_watch_task_fudai(fudai_content_text)
|
||
if is_watch_task:
|
||
try:
|
||
analyser._log_kv(
|
||
"福袋",
|
||
"OCR识别到'观看X分钟'类任务(清理后检测),直接跳过后续处理",
|
||
content=fudai_content_text[:100] if fudai_content_text else "",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 设置标志
|
||
try:
|
||
analyser._is_watch_task_detected = True
|
||
except Exception:
|
||
pass
|
||
# 直接返回空内容,后续流程会跳过
|
||
return "", "", 0, 0, 0.0
|
||
except Exception:
|
||
pass
|
||
|
||
# 输出福袋内容(使用明确的格式,便于GUI解析)
|
||
content_for_log = fudai_content_text if fudai_content_text else "未识别到"
|
||
# 移除重复输出,因为并行OCR详情中已经包含了此信息
|
||
# analyser._log_kv(
|
||
# "福袋",
|
||
# f"识别福袋内容:{content_for_log[:100]}", # 在消息中直接包含内容,确保可见
|
||
# level="DEBUG",
|
||
# content=content_for_log, # 同时作为字段输出
|
||
# )
|
||
|
||
# 记录进入直播间到识别到福袋的耗时(仅记录一次)
|
||
try:
|
||
if getattr(analyser, "_enter_live_ts", 0.0) and not getattr(
|
||
analyser, "_enter_live_fudai_logged", False
|
||
):
|
||
try:
|
||
secs = float(time.time() - float(analyser._enter_live_ts or 0.0))
|
||
except Exception:
|
||
secs = -1.0
|
||
reason = str(getattr(analyser, "_enter_live_reason", "") or "")
|
||
analyser._log_kv(
|
||
"性能",
|
||
"进入直播间到识别福袋耗时",
|
||
seconds=round(secs, 2),
|
||
enter_reason=reason,
|
||
)
|
||
try:
|
||
analyser._enter_live_fudai_logged = True
|
||
except Exception:
|
||
pass
|
||
if copies:
|
||
analyser._log_kv(
|
||
"福袋",
|
||
"识别福袋信息",
|
||
copies=copies,
|
||
participants=participants if participants else 0,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 倒计时:直接使用分割OCR结果(分钟+秒),不再使用完整OCR
|
||
time_text = "" # 初始化为空字符串,确保类型为 str
|
||
try:
|
||
# 提取数字:分钟和秒都应该是1-2位数字
|
||
def _extract_digits(text: str, max_digits: int = 2) -> str:
|
||
"""提取数字,最多max_digits位,取前max_digits位优先。"""
|
||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||
if len(digits) > max_digits:
|
||
candidate = digits[:max_digits]
|
||
# 如果前2位全是0但实际有非0数字,跳0取有效数字
|
||
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
|
||
|
||
mm = _extract_digits(countdown_mm_raw, max_digits=2) if countdown_mm_raw else ""
|
||
ss = _extract_digits(countdown_ss_raw, max_digits=2) if countdown_ss_raw else ""
|
||
|
||
# OCR结果验证:检查倒计时识别结果是否为空
|
||
if not countdown_mm_raw and not countdown_ss_raw:
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"倒计时OCR结果完全为空",
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
elif not mm or not ss:
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"倒计时OCR结果不完整",
|
||
mm_raw=countdown_mm_raw,
|
||
ss_raw=countdown_ss_raw,
|
||
mm_extracted=mm,
|
||
ss_extracted=ss,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果)
|
||
try:
|
||
mm_int = int(mm) if mm else 0
|
||
ss_int = int(ss) if ss else 0
|
||
|
||
# 数值范围验证
|
||
if mm_int < 0 or mm_int >= 60:
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"倒计时分钟数值超出合理范围",
|
||
mm=mm_int,
|
||
mm_raw=countdown_mm_raw,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
if ss_int >= 60:
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"倒计时秒数>=60(可能是识别错误)",
|
||
mm=mm_int,
|
||
ss=ss_int,
|
||
mm_raw=countdown_mm_raw,
|
||
ss_raw=countdown_ss_raw,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
elif ss_int < 0:
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"倒计时秒数<0(可能是识别错误)",
|
||
ss=ss_int,
|
||
ss_raw=countdown_ss_raw,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e_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:
|
||
time_text = f"{mm}:{ss}"
|
||
# 移除重复输出,因为并行OCR详情中已经包含了倒计时信息
|
||
# try:
|
||
# analyser._log_kv(
|
||
# "福袋倒计时",
|
||
# "分割识别成功",
|
||
# mm_raw=countdown_mm_raw,
|
||
# ss_raw=countdown_ss_raw,
|
||
# result=time_text,
|
||
# )
|
||
# except Exception:
|
||
# pass
|
||
else:
|
||
# 识别失败,time_text 保持为空字符串
|
||
try:
|
||
analyser._log_kv(
|
||
"福袋倒计时",
|
||
"分割识别失败(分钟或秒为空)",
|
||
mm_raw=countdown_mm_raw,
|
||
ss_raw=countdown_ss_raw,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e_inner:
|
||
# 异常时,time_text 保持为空字符串
|
||
try:
|
||
analyser._log_kv(
|
||
"福袋倒计时",
|
||
"分割识别异常",
|
||
error=str(e_inner),
|
||
error_type=type(e_inner).__name__,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 移除重复输出,因为并行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 ""
|
||
)
|
||
|
||
# OCR结果验证:检查价值识别结果
|
||
if not value_raw:
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"价值OCR结果为空",
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
elif prize_value_yuan:
|
||
# 验证价值数值是否合理
|
||
try:
|
||
value_float = float(prize_value_yuan)
|
||
if value_float < 0:
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"价值数值<0(可能是识别错误)",
|
||
value_yuan=prize_value_yuan,
|
||
value_raw=value_raw[:50] if value_raw else "",
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
elif value_float > 100000: # 价值超过10万可能不合理
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"价值数值异常大(可能是识别错误)",
|
||
value_yuan=prize_value_yuan,
|
||
value_raw=value_raw[:50] if value_raw else "",
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e_inner:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"验证价值数值失败",
|
||
error=str(e_inner),
|
||
error_type=type(e_inner).__name__,
|
||
value_raw=value_raw[:50] if value_raw else "",
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
if float(prize_value_yuan).is_integer():
|
||
show_value = int(prize_value_yuan)
|
||
else:
|
||
show_value = prize_value_yuan
|
||
# 移除重复输出,因为并行OCR详情中已经包含了奖品价值信息
|
||
# analyser._log_kv("福袋", "识别奖品价值", value_yuan=show_value)
|
||
else:
|
||
# value_raw不为空但提取失败
|
||
try:
|
||
analyser._log_kv(
|
||
"验证",
|
||
"价值OCR结果无法解析",
|
||
value_raw=value_raw[:100] if value_raw else "",
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 处理直播间标题结果
|
||
if live_room_title_raw or live_room_title_text_raw:
|
||
try:
|
||
analyser.current_room_title = live_room_title_raw
|
||
analyser.current_room_title_raw = live_room_title_text_raw
|
||
# 移除重复输出,因为并行OCR详情中已经包含了直播间标题信息
|
||
# analyser._log_kv(
|
||
# "直播间标题",
|
||
# "OCR识别直播间标题",
|
||
# title=live_room_title_raw,
|
||
# raw_text=live_room_title_text_raw,
|
||
# log_type="INFO",
|
||
# )
|
||
except Exception as e_inner:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"设置直播间标题结果失败",
|
||
error=str(e_inner),
|
||
error_type=type(e_inner).__name__,
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 在有福袋的情况下,记录完整OCR详情到映射表(即使标题未识别)
|
||
try:
|
||
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||
room_pos_map = getattr(analyser, "_room_pos_to_title_map", {})
|
||
|
||
# 兼容旧格式:若已有旧元组格式,先转为 dict
|
||
existing_info = room_pos_map.get(room_pos, {})
|
||
base_info = {}
|
||
if isinstance(existing_info, dict):
|
||
base_info = dict(existing_info)
|
||
elif existing_info:
|
||
try:
|
||
base_info = {
|
||
"title": existing_info[0] if len(existing_info) > 0 else "",
|
||
"title_raw": existing_info[1] if len(existing_info) > 1 else "",
|
||
}
|
||
except Exception:
|
||
base_info = {}
|
||
|
||
title_for_map = (
|
||
live_room_title_raw
|
||
or base_info.get("title")
|
||
or str(getattr(analyser, "current_room_title", "") or "")
|
||
)
|
||
title_raw_for_map = (
|
||
live_room_title_text_raw
|
||
or base_info.get("title_raw")
|
||
or str(getattr(analyser, "current_room_title_raw", "") or "")
|
||
)
|
||
|
||
button_text_for_map = str(button_text_raw or "") or str(
|
||
getattr(analyser, "button_text_raw", "") or ""
|
||
)
|
||
|
||
room_info = dict(base_info)
|
||
room_info.update(
|
||
{
|
||
"title": title_for_map or "",
|
||
"title_raw": title_raw_for_map or "",
|
||
"has_fudai": True,
|
||
"fudai_content": fudai_content_text,
|
||
"fudai_detail": {
|
||
"content": fudai_content_text,
|
||
"task_list": str(task_list_raw or ""),
|
||
"countdown_mm": str(countdown_mm_raw or ""),
|
||
"countdown_ss": str(countdown_ss_raw or ""),
|
||
"time_text": time_text,
|
||
"participants": participants,
|
||
"copies": copies,
|
||
"prize_value_yuan": prize_value_yuan,
|
||
"value_raw": str(value_raw or ""),
|
||
"button_text": button_text_for_map,
|
||
"button_text_raw": str(button_text_raw or ""),
|
||
"live_room_title": str(live_room_title_raw or title_for_map or ""),
|
||
"live_room_title_raw": str(
|
||
live_room_title_text_raw or title_raw_for_map or ""
|
||
),
|
||
"timestamp": time.time(),
|
||
},
|
||
"timestamp": time.time(),
|
||
}
|
||
)
|
||
|
||
# 并行OCR 已生成完整的 fudai_detail,写入运行时映射表并落盘
|
||
try:
|
||
room_pos_map[room_pos] = room_info
|
||
try:
|
||
analyser._room_pos_to_title_map = room_pos_map
|
||
except Exception:
|
||
pass
|
||
try:
|
||
from douyin.reservation import douyin_reservation_handler
|
||
|
||
douyin_reservation_handler._dump_room_pos_map_to_state(analyser)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
analyser._log_kv(
|
||
"预约",
|
||
"[预约] 并行OCR完成(已写入映射表并写盘)",
|
||
room_pos=room_pos,
|
||
title=(title_for_map[:30] if title_for_map else ""),
|
||
fudai_content=(
|
||
fudai_content_text[:30] if fudai_content_text else ""
|
||
),
|
||
prize_value_yuan=prize_value_yuan,
|
||
log_type="DEBUG",
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
except Exception as e_update:
|
||
try:
|
||
analyser._log_kv(
|
||
"错误",
|
||
"并行OCR完成后记录映射表信息失败",
|
||
error=str(e_update),
|
||
level="WARNING",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
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。
|
||
|
||
|