refactor(fudai_core): 抽 7 个并行 OCR 闭包到 ocr_tasks 模块 (1659 → 1328)

get_fudai_contain L222-553 有 7 个 ocr_* 闭包:task_list / content /
countdown_mm / countdown_ss / value / button / live_room_title。每个都遵循
同样的模板(计时 + analyse_pic_word/digits + perf 字典 + 异常日志),共 330 行。

抽到 douyin_fudai_core_pkg/ocr_tasks.py 的 OcrTaskRunner 类:
- 7 个方法对应 7 个并行任务
- 共享耗时 dict + lock 在构造器传入
- _record_duration / _log_warn 提取出共有的 finally + except 模板
- _BUTTON_KEYWORDS 关键词常量化(原本是闭包里硬编码 tuple)
- _safe_preprocess 顶层 helper

主流程从 7 个闭包定义 + 配置开关重复读取(330 行)变成 22 行 runner 实例化 +
方法绑定,并保留 ocr_task_list / ocr_content / ... 名字给后续 executor.submit
当作 Callable 传入,行为完全不变。

新增 22 个单元测试覆盖:
- _safe_preprocess 兜底
- 7 个方法的成功 / disable 跳过 / 异常 / 边界
- ocr_button 关键词短路 + 重试逻辑
- 所有方法都正确记录耗时到 perf_durations

1294 passed (+22)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-23 01:52:22 +08:00
1 parent 457edcfdc8
commit f38b373636
3 files changed
+545 -331

No files matched your search

+22 -331
View File
@@ -219,338 +219,29 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
perf_task_durations: Dict[str, float] = {}
perf_task_lock = threading.Lock()
def ocr_task_list():
"""OCR识别任务列表(用于检测观看任务)"""
start = time.time()
try:
# 运行时读取开关,优先使用 analyser 属性,其次读取 config.json
try:
disable_task_recognition = bool(
getattr(analyser, "fudai_disable_task_recognition", False)
)
except Exception:
disable_task_recognition = False
if not disable_task_recognition:
try:
import json
# 读取内容 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",
)
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
disable_task_recognition = bool(
cfg.get("fudai_disable_task_recognition", False)
)
except Exception:
pass
if disable_task_recognition:
try:
analyser._log_kv(
"福袋",
"跳过福袋任务列表OCR识别(配置启用)",
)
except Exception:
pass
return None
name_tl = preprocess_for_ocr(analyser, "福袋任务列表")
return analyser.operation.analyse_pic_word(name_tl, 0)
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
return None
finally:
try:
dur = round((time.time() - start) * 1000, 1)
with perf_task_lock:
perf_task_durations["ocr_task_list"] = dur
# 移除单独的性能日志输出,避免日志重复
# try:
# analyser._log_kv(
# "性能",
# "并行OCR子任务单项耗时(ms)",
# field="task_list",
# duration_ms=dur,
# )
# except Exception:
# pass
except Exception:
pass
# 读取配置开关:优先使用 analyser 属性覆盖,其次读取 config.json
try:
disable_content_recognition = bool(
getattr(analyser, "fudai_disable_content_recognition", False)
)
except Exception:
disable_content_recognition = False
if not disable_content_recognition:
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
disable_content_recognition = bool(
cfg.get("fudai_disable_content_recognition", False)
)
except Exception:
pass
def ocr_content():
"""OCR识别福袋内容"""
start = time.time()
try:
if disable_content_recognition:
try:
analyser._log_kv(
"福袋",
"跳过福袋内容OCR识别(配置启用)",
)
except Exception:
pass
return None
name_fc = preprocess_for_ocr(analyser, "福袋内容")
return analyser.operation.analyse_pic_word(name_fc, 0)
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
return None
finally:
try:
dur = round((time.time() - start) * 1000, 1)
with perf_task_lock:
perf_task_durations["ocr_content"] = dur
# 移除单独的性能日志输出,避免日志重复
# try:
# analyser._log_kv(
# "性能",
# "并行OCR子任务单项耗时(ms)",
# field="content",
# duration_ms=dur,
# )
# except Exception:
# pass
except Exception:
pass
def ocr_countdown_mm():
"""OCR识别福袋倒计时分钟(纯数字模型,无回退)。"""
start = time.time()
try:
raw = str(analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0) or "")
digits = "".join(ch for ch in raw if ch.isdigit())
return digits
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
return None
finally:
try:
dur = round((time.time() - start) * 1000, 1)
with perf_task_lock:
perf_task_durations["ocr_countdown_mm"] = dur
# 移除单独的性能日志输出,避免日志重复
# try:
# analyser._log_kv(
# "性能",
# "并行OCR子任务单项耗时(ms)",
# field="countdown_mm",
# duration_ms=dur,
# )
# except Exception:
# pass
except Exception:
pass
def ocr_countdown_ss():
"""OCR识别福袋倒计时秒(纯数字模型,无回退)。"""
start = time.time()
try:
raw = str(analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0) or "")
digits = "".join(ch for ch in raw if ch.isdigit())
return digits
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
return None
finally:
try:
dur = round((time.time() - start) * 1000, 1)
with perf_task_lock:
perf_task_durations["ocr_countdown_ss"] = dur
# 移除单独的性能日志输出,避免日志重复
# try:
# analyser._log_kv(
# "性能",
# "并行OCR子任务单项耗时(ms)",
# field="countdown_ss",
# duration_ms=dur,
# )
# except Exception:
# pass
except Exception:
pass
def ocr_value():
"""OCR识别福袋价值:使用普通OCR获取文本,支持小数点。"""
start = time.time()
try:
try:
name_val = preprocess_for_ocr(analyser, "福袋价值")
except Exception:
name_val = "福袋价值"
# 使用普通OCR获取文本,支持小数点等
word_raw = str(analyser.operation.analyse_pic_word(name_val, 0) or "")
return word_raw
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
return None
finally:
try:
dur = round((time.time() - start) * 1000, 1)
with perf_task_lock:
perf_task_durations["ocr_value"] = dur
# 移除单独的性能日志输出,避免日志重复
# try:
# analyser._log_kv(
# "性能",
# "并行OCR子任务单项耗时(ms)",
# field="value",
# duration_ms=dur,
# )
# except Exception:
# pass
except Exception:
pass
def ocr_button():
"""OCR识别参与按钮(用于检测参与状态)"""
try:
name_btn = preprocess_for_ocr(analyser, "参与按钮")
# 优化:只尝试模式0,如果识别到关键信息就返回,避免二次OCR(节省50%时间)
button_text = str(analyser.operation.analyse_pic_word(name_btn, 0) or "")
# 如果模式0识别到关键信息,直接返回(不再尝试模式1)
if button_text and any(
k in button_text
for k in (
"参与成功",
"还需看播",
"评论",
"参与抽奖",
"开始观看",
"参与",
"加入粉丝团",
"粉丝团",
"等待开奖",
"未达成",
)
):
return button_text
# 只有在模式0完全失败时才尝试模式1
if not button_text:
button_text = str(
analyser.operation.analyse_pic_word(name_btn, 0) or ""
)
return button_text
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
return None
def ocr_live_room_title():
"""OCR识别直播间标题"""
start = time.time()
try:
# 导入直播间标题识别函数
from douyin.fudai.core.fudai_detail_room_title import _ocr_try_room_title
# 使用已切割的图片进行OCR识别
title, raw_text = _ocr_try_room_title(analyser, "live_room_title_mid", 0)
# 返回结果元组
return title, raw_text
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
return "", ""
finally:
try:
dur = round((time.time() - start) * 1000, 1)
with perf_task_lock:
perf_task_durations["ocr_live_room_title"] = dur
# 移除单独的性能日志输出,避免日志重复
# try:
# analyser._log_kv(
# "性能",
# "并行OCR子任务单项耗时(ms)",
# field="live_room_title",
# duration_ms=dur,
# )
# except Exception:
# pass
except Exception:
pass
# 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 参数
@@ -0,0 +1,226 @@
"""douyin_fudai_core_pkg.ocr_tasks - 福袋详情 7 个并行 OCR 子任务
把 get_fudai_contain 中 7 个 ocr_* 闭包封装成一个类。每个方法对应
ThreadPoolExecutor 的一个并行任务:
OcrTaskRunner.ocr_task_list 福袋任务列表
OcrTaskRunner.ocr_content 福袋内容
OcrTaskRunner.ocr_countdown_mm 倒计时分钟(数字模型)
OcrTaskRunner.ocr_countdown_ss 倒计时秒(数字模型)
OcrTaskRunner.ocr_value 福袋价值
OcrTaskRunner.ocr_button 参与按钮状态
OcrTaskRunner.ocr_live_room_title 直播间标题
每个方法的 finally 把单项耗时(ms)写入共享 dict(用 lock 保护),便于
主流程后续聚合输出性能日志。所有日志、配置开关读取行为与原闭包一致。
"""
from __future__ import annotations
import threading
import time
from typing import Any, Dict, Optional, Tuple
# OCR 按钮关键词列表(识别到任一即可短路返回,省 50% 时间)
_BUTTON_KEYWORDS = (
"参与成功",
"还需看播",
"评论",
"参与抽奖",
"开始观看",
"参与",
"加入粉丝团",
"粉丝团",
"等待开奖",
"未达成",
)
def _safe_preprocess(analyser, name: str) -> str:
"""preprocess_for_ocr 的安全包装:失败时返回原 name。"""
try:
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
return preprocess_for_ocr(analyser, name)
except Exception:
return name
class OcrTaskRunner:
"""7 个并行 OCR 子任务的运行器。
Args:
analyser: fudai_analyse 实例
perf_durations: 共享 dict,存放各任务的耗时(ms)
perf_lock: 保护 perf_durations 的 Lock
disable_content_recognition: 主流程已经读到的内容 OCR 开关(避免每次任务再读一次)
"""
def __init__(
self,
analyser,
perf_durations: Dict[str, float],
perf_lock: threading.Lock,
*,
disable_content_recognition: bool = False,
):
self.analyser = analyser
self.durations = perf_durations
self.lock = perf_lock
self.disable_content_recognition = bool(disable_content_recognition)
# ============================================================
# 内部工具
# ============================================================
def _record_duration(self, key: str, start: float) -> None:
try:
dur = round((time.time() - start) * 1000, 1)
with self.lock:
self.durations[key] = dur
except Exception:
pass
def _log_warn(self, msg: str, exc: BaseException) -> None:
try:
self.analyser._log_kv(
"错误",
msg,
error=str(exc),
error_type=type(exc).__name__,
level="WARNING",
)
except Exception:
pass
# ============================================================
# 7 个并行 OCR 子任务
# ============================================================
def ocr_task_list(self) -> Optional[str]:
"""OCR 识别福袋任务列表(用于检测观看任务,尊重配置开关)。"""
start = time.time()
try:
from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import (
_read_disable_flag,
)
disable = _read_disable_flag(
self.analyser,
"fudai_disable_task_recognition",
"fudai_disable_task_recognition",
)
if disable:
try:
self.analyser._log_kv(
"福袋", "跳过福袋任务列表OCR识别(配置启用)"
)
except Exception:
pass
return None
name_tl = _safe_preprocess(self.analyser, "福袋任务列表")
return self.analyser.operation.analyse_pic_word(name_tl, 0)
except Exception as e:
self._log_warn("OCR识别任务列表失败", e)
return None
finally:
self._record_duration("ocr_task_list", start)
def ocr_content(self) -> Optional[str]:
"""OCR 识别福袋内容。"""
start = time.time()
try:
if self.disable_content_recognition:
try:
self.analyser._log_kv(
"福袋", "跳过福袋内容OCR识别(配置启用)"
)
except Exception:
pass
return None
name_fc = _safe_preprocess(self.analyser, "福袋内容")
return self.analyser.operation.analyse_pic_word(name_fc, 0)
except Exception as e:
self._log_warn("OCR识别福袋内容失败", e)
return None
finally:
self._record_duration("ocr_content", start)
def ocr_countdown_mm(self) -> Optional[str]:
"""OCR 识别福袋倒计时分钟(纯数字模型,无回退)。"""
start = time.time()
try:
raw = str(
self.analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0) or ""
)
return "".join(ch for ch in raw if ch.isdigit())
except Exception as e:
self._log_warn("OCR识别倒计时分钟失败", e)
return None
finally:
self._record_duration("ocr_countdown_mm", start)
def ocr_countdown_ss(self) -> Optional[str]:
"""OCR 识别福袋倒计时秒(纯数字模型,无回退)。"""
start = time.time()
try:
raw = str(
self.analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0) or ""
)
return "".join(ch for ch in raw if ch.isdigit())
except Exception as e:
self._log_warn("OCR识别倒计时秒失败", e)
return None
finally:
self._record_duration("ocr_countdown_ss", start)
def ocr_value(self) -> Optional[str]:
"""OCR 识别福袋价值(普通文本模型,支持小数点)。"""
start = time.time()
try:
name_val = _safe_preprocess(self.analyser, "福袋价值")
word_raw = str(
self.analyser.operation.analyse_pic_word(name_val, 0) or ""
)
return word_raw
except Exception as e:
self._log_warn("OCR识别福袋价值失败", e)
return None
finally:
self._record_duration("ocr_value", start)
def ocr_button(self) -> Optional[str]:
"""OCR 识别参与按钮状态(关键词短路,节省 50% OCR 时间)。
注意:原闭包没有 finally 计时(按钮属于同步路径),保留这个差异。
"""
try:
name_btn = _safe_preprocess(self.analyser, "参与按钮")
# 模式 0 试一次:若识别到关键词直接返回
button_text = str(
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
)
if button_text and any(k in button_text for k in _BUTTON_KEYWORDS):
return button_text
# 模式 0 完全失败时再试一次(保留旧逻辑:仍是模式 0)
if not button_text:
button_text = str(
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
)
return button_text
except Exception as e:
self._log_warn("OCR识别参与按钮失败", e)
return None
def ocr_live_room_title(self) -> Tuple[str, str]:
"""OCR 识别直播间标题,返回 (title, raw_text)。"""
start = time.time()
try:
from douyin.fudai.core.fudai_detail_room_title import (
_ocr_try_room_title,
)
return _ocr_try_room_title(self.analyser, "live_room_title_mid", 0)
except Exception as e:
self._log_warn("OCR识别直播间标题失败", e)
return "", ""
finally:
self._record_duration("ocr_live_room_title", start)
+297
View File
@@ -0,0 +1,297 @@
"""douyin_fudai_core_pkg.ocr_tasks 单元测试。
覆盖 OcrTaskRunner 的 7 个方法 + 内部 helper:
- _safe_preprocess: 失败时回退原 name
- ocr_task_list / ocr_content: disable_flag 跳过 / 正常路径 / 异常
- ocr_countdown_mm / ocr_countdown_ss: digits 提取 / 异常
- ocr_value / ocr_button: 文本路径 / button 关键词短路 / 异常
- ocr_live_room_title: 委托到 _ocr_try_room_title
- 各方法的耗时 (ms) 都进 perf_durations
"""
from __future__ import annotations
import threading
from unittest.mock import MagicMock, patch
import pytest
from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import (
OcrTaskRunner,
_BUTTON_KEYWORDS,
_safe_preprocess,
)
def _mk_analyser():
a = MagicMock()
a._log_kv = MagicMock(return_value=None)
a.operation = MagicMock()
return a
def _mk_runner(analyser=None, *, disable_content=False):
if analyser is None:
analyser = _mk_analyser()
durations = {}
lock = threading.Lock()
runner = OcrTaskRunner(
analyser,
durations,
lock,
disable_content_recognition=disable_content,
)
return runner, durations
# ============================================================
# _safe_preprocess
# ============================================================
class TestSafePreprocess:
def test_success(self):
with patch(
"douyin.utils.ocr_preprocess.preprocess_for_ocr",
return_value="processed_name",
):
assert _safe_preprocess(MagicMock(), "X") == "processed_name"
def test_throws_returns_original_name(self):
with patch(
"douyin.utils.ocr_preprocess.preprocess_for_ocr",
side_effect=RuntimeError("preprocess fail"),
):
assert _safe_preprocess(MagicMock(), "原名") == "原名"
# ============================================================
# ocr_task_list
# ============================================================
class TestOcrTaskList:
def test_disabled_skips(self):
runner, durations = _mk_runner()
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=True,
):
assert runner.ocr_task_list() is None
# 跳过路径仍记录耗时
assert "ocr_task_list" in durations
def test_success(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="任务1\n任务2"
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
assert runner.ocr_task_list() == "任务1\n任务2"
assert durations["ocr_task_list"] >= 0
def test_exception(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
side_effect=RuntimeError("ocr fail")
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
assert runner.ocr_task_list() is None
# 异常仍写日志 + 耗时
assert "ocr_task_list" in durations
# ============================================================
# ocr_content
# ============================================================
class TestOcrContent:
def test_disabled_skips(self):
runner, durations = _mk_runner(disable_content=True)
runner.analyser.operation.analyse_pic_word = MagicMock()
assert runner.ocr_content() is None
# 不应调用 OCR
runner.analyser.operation.analyse_pic_word.assert_not_called()
assert "ocr_content" in durations
def test_success(self):
runner, durations = _mk_runner(disable_content=False)
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="福袋内容"
)
assert runner.ocr_content() == "福袋内容"
assert durations["ocr_content"] >= 0
# ============================================================
# ocr_countdown_mm / ocr_countdown_ss
# ============================================================
class TestOcrCountdown:
def test_mm_extracts_digits(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
return_value="abc23def"
)
assert runner.ocr_countdown_mm() == "23"
assert "ocr_countdown_mm" in durations
def test_ss_extracts_digits(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
return_value="45"
)
assert runner.ocr_countdown_ss() == "45"
def test_mm_empty(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
return_value=None
)
assert runner.ocr_countdown_mm() == ""
def test_mm_throws(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
side_effect=RuntimeError()
)
assert runner.ocr_countdown_mm() is None
# ============================================================
# ocr_value
# ============================================================
class TestOcrValue:
def test_success(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="¥500"
)
assert runner.ocr_value() == "¥500"
assert "ocr_value" in durations
def test_returns_empty_string_for_none(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(return_value=None)
# str(None or "") = ""
assert runner.ocr_value() == ""
def test_throws(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
side_effect=RuntimeError()
)
assert runner.ocr_value() is None
# ============================================================
# ocr_button
# ============================================================
class TestOcrButton:
def test_keyword_short_circuits(self):
"""识别到关键词应立即返回,不再二次 OCR。"""
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="参与抽奖"
)
assert runner.ocr_button() == "参与抽奖"
# 模式 0 一次就够
assert runner.analyser.operation.analyse_pic_word.call_count == 1
def test_no_keyword_returns_text_anyway(self):
"""识别到非关键词文本也会返回。"""
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="未知按钮文本"
)
# 不在关键词里 → 仍返回,但可能再尝试一次(保留旧逻辑)
result = runner.ocr_button()
assert result == "未知按钮文本"
def test_empty_first_then_retry(self):
"""模式 0 完全失败时再试一次。"""
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
side_effect=["", "重试得到的文本"]
)
assert runner.ocr_button() == "重试得到的文本"
assert runner.analyser.operation.analyse_pic_word.call_count == 2
def test_throws_returns_none(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
side_effect=RuntimeError()
)
assert runner.ocr_button() is None
def test_button_keywords_constant(self):
"""关键词里至少含一些核心字串。"""
for k in ("参与抽奖", "等待开奖", "未达成"):
assert k in _BUTTON_KEYWORDS
# ============================================================
# ocr_live_room_title
# ============================================================
class TestOcrLiveRoomTitle:
def test_delegates_to_ocr_try_room_title(self):
runner, durations = _mk_runner()
with patch(
"douyin.fudai.core.fudai_detail_room_title._ocr_try_room_title",
return_value=("主播间标题", "raw text"),
):
title, raw = runner.ocr_live_room_title()
assert title == "主播间标题"
assert raw == "raw text"
assert "ocr_live_room_title" in durations
def test_throws_returns_empty_tuple(self):
runner, durations = _mk_runner()
with patch(
"douyin.fudai.core.fudai_detail_room_title._ocr_try_room_title",
side_effect=RuntimeError(),
):
assert runner.ocr_live_room_title() == ("", "")
# ============================================================
# 通用:所有方法都记录耗时到共享 dict
# ============================================================
class TestPerfDurations:
def test_all_keys_present_after_one_call_each(self):
runner, durations = _mk_runner()
# 让 OCR 都返回固定值
runner.analyser.operation.analyse_pic_word = MagicMock(return_value="x")
runner.analyser.operation.analyse_pic_digits = MagicMock(return_value="1")
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
), patch(
"douyin.fudai.core.fudai_detail_room_title._ocr_try_room_title",
return_value=("title", "raw"),
):
runner.ocr_task_list()
runner.ocr_content()
runner.ocr_countdown_mm()
runner.ocr_countdown_ss()
runner.ocr_value()
runner.ocr_live_room_title()
# ocr_button 不计耗时(保留原行为差异)
for k in (
"ocr_task_list",
"ocr_content",
"ocr_countdown_mm",
"ocr_countdown_ss",
"ocr_value",
"ocr_live_room_title",
):
assert k in durations, f"missing duration for {k}"
assert durations[k] >= 0