refactor(fudai_core): 抽 _run_heavy_ocr 闭包到 heavy_ocr 模块 (1953 → 1822)

_run_heavy_ocr 是 get_fudai_contain 中的 142 行闭包,按需对 6 个字段
(task_list / content / countdown_mm / countdown_ss / value / button)
跑较重的 OCR 模型补齐轻量 OCR 漏掉的字段。

抽到 douyin_fudai_core_pkg/heavy_ocr.py:
- run_heavy_ocr(analyser, fields) 顶层主函数
- _read_disable_flag(analyser, attr, cfg_key) 提取重复的 attr→config.json
  fallback 配置开关读取(原闭包里 task_list 和 content 各重复一次)
- _ocr_digits_with_fallback(analyser, picname) 提取 mm/ss 分支共有的
  digits→word 兜底数字提取逻辑

原闭包改为 4 行委托。配置开关、日志和异常兜底行为完全一致。

新增 18 个单元测试覆盖:
- _read_disable_flag 4 种状态(attr 优先 / config 兜底 / 都缺 / 文件不存在)
- _ocr_digits_with_fallback 5 个分支
- run_heavy_ocr 9 个字段组合 + disable 跳过路径

1260 passed (+18)。

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:39:24 +08:00
1 parent 2707773b15
commit 03b471513d
3 files changed
+384 -141

No files matched your search

+3 -141
View File
@@ -153,147 +153,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
return fields
def _run_heavy_ocr(fields: set[str]) -> Dict[str, Any]:
"""按需补充较重的OCR,避免默认就跑全量重模型。"""
results: Dict[str, Any] = {}
heavy_start = time.time()
def _safe_preprocess(name: str) -> str:
try:
return preprocess_for_ocr(analyser, name)
except Exception:
return name
# 任务列表:用于兜底检测观看任务
# 读取任务列表OCR开关(运行时读取 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
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 "task_list" in fields:
if disable_task_recognition:
try:
analyser._log_kv(
"福袋",
"跳过福袋任务列表OCR识别(配置启用)",
)
except Exception:
pass
else:
try:
name_tl = _safe_preprocess("福袋任务列表")
results["task_list"] = analyser.operation.analyse_pic_word(
name_tl, 1
)
except Exception:
pass
# 内容OCR开关(运行时读取 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
# 内容:使用更重的文本模型兜底(尊重配置开关)
if "content" in fields:
if disable_content_recognition:
try:
analyser._log_kv(
"福袋",
"跳过福袋内容OCR识别(配置启用)",
)
except Exception:
pass
else:
try:
name_fc = _safe_preprocess("福袋内容")
results["content"] = analyser.operation.analyse_pic_word(name_fc, 1)
except Exception:
pass
# 倒计时:先数字模型,失败再文本提取数字
if "countdown_mm" in fields:
mm_digits = ""
try:
raw = analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1)
mm_digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
except Exception:
pass
if not mm_digits:
try:
raw = analyser.operation.analyse_pic_word("福袋倒计时_分钟", 1)
mm_digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
except Exception:
pass
if mm_digits:
results["countdown_mm"] = mm_digits
if "countdown_ss" in fields:
ss_digits = ""
try:
raw = analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1)
ss_digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
except Exception:
pass
if not ss_digits:
try:
raw = analyser.operation.analyse_pic_word("福袋倒计时_秒", 1)
ss_digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
except Exception:
pass
if ss_digits:
results["countdown_ss"] = ss_digits
# 价值:重模型兜底一次,兼容带符号文本
if "value" in fields:
try:
name_val = _safe_preprocess("福袋价值")
raw_val = analyser.operation.analyse_pic_word(name_val, 0)
results["value"] = str(raw_val or "")
except Exception:
pass
# 按钮状态:重模型兜底,避免轻量误判
if "button" in fields:
try:
name_btn = _safe_preprocess("参与按钮")
results["button"] = analyser.operation.analyse_pic_word(name_btn, 1)
except Exception:
pass
try:
results["_duration_ms"] = round((time.time() - heavy_start) * 1000, 1)
except Exception:
pass
return results
"""委托给 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)
countdown_box = None
# 使用集中坐标常量,避免在代码中硬编码
@@ -0,0 +1,165 @@
"""douyin_fudai_core_pkg.heavy_ocr - 福袋详情按需补 OCR
从 get_fudai_contain 抽出的 _run_heavy_ocr 闭包:当轻量 OCR 漏字段时,
按需调用更重的文本/数字模型补齐 task_list / content / countdown_mm /
countdown_ss / value / button 共 6 个字段。
签名:
run_heavy_ocr(analyser, fields) -> Dict[str, Any]
返回字典含成功补到的字段值 + "_duration_ms"。失败字段不进字典。
所有日志、配置开关读取行为与原闭包一致。
"""
from __future__ import annotations
import json
import os
import time
from typing import Any, Dict, Set
def _read_disable_flag(analyser, attr_name: str, cfg_key: str) -> bool:
"""读取 analyser 属性,无值再回退到 config.json。"""
try:
flag = bool(getattr(analyser, attr_name, False))
except Exception:
flag = False
if flag:
return True
try:
from douyin.core import path_config
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)
return bool(cfg.get(cfg_key, False))
except Exception:
pass
return False
def run_heavy_ocr(analyser, fields: Set[str]) -> Dict[str, Any]:
"""按需补充较重的 OCR,避免默认就跑全量重模型。
Args:
analyser: fudai_analyse 实例(提供 operation / _log_kv / 配置开关)
fields: 需要补的字段集合,可包含 task_list / content / countdown_mm /
countdown_ss / value / button
Returns:
Dict 含成功识别到的字段;总耗时记在 "_duration_ms"。
"""
try:
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
except Exception:
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
return str(picname)
results: Dict[str, Any] = {}
heavy_start = time.time()
def _safe_preprocess(name: str) -> str:
try:
return preprocess_for_ocr(analyser, name)
except Exception:
return name
# 任务列表:用于兜底检测观看任务(尊重配置开关)
if "task_list" in fields:
if _read_disable_flag(
analyser,
"fudai_disable_task_recognition",
"fudai_disable_task_recognition",
):
try:
analyser._log_kv(
"福袋", "跳过福袋任务列表OCR识别(配置启用)"
)
except Exception:
pass
else:
try:
name_tl = _safe_preprocess("福袋任务列表")
results["task_list"] = analyser.operation.analyse_pic_word(
name_tl, 1
)
except Exception:
pass
# 内容:使用更重的文本模型兜底(尊重配置开关)
if "content" in fields:
if _read_disable_flag(
analyser,
"fudai_disable_content_recognition",
"fudai_disable_content_recognition",
):
try:
analyser._log_kv(
"福袋", "跳过福袋内容OCR识别(配置启用)"
)
except Exception:
pass
else:
try:
name_fc = _safe_preprocess("福袋内容")
results["content"] = analyser.operation.analyse_pic_word(
name_fc, 1
)
except Exception:
pass
# 倒计时:先数字模型,失败再文本提取数字
if "countdown_mm" in fields:
mm_digits = _ocr_digits_with_fallback(analyser, "福袋倒计时_分钟")
if mm_digits:
results["countdown_mm"] = mm_digits
if "countdown_ss" in fields:
ss_digits = _ocr_digits_with_fallback(analyser, "福袋倒计时_秒")
if ss_digits:
results["countdown_ss"] = ss_digits
# 价值:重模型兜底一次,兼容带符号文本
if "value" in fields:
try:
name_val = _safe_preprocess("福袋价值")
raw_val = analyser.operation.analyse_pic_word(name_val, 0)
results["value"] = str(raw_val or "")
except Exception:
pass
# 按钮状态:重模型兜底,避免轻量误判
if "button" in fields:
try:
name_btn = _safe_preprocess("参与按钮")
results["button"] = analyser.operation.analyse_pic_word(name_btn, 1)
except Exception:
pass
try:
results["_duration_ms"] = round((time.time() - heavy_start) * 1000, 1)
except Exception:
pass
return results
def _ocr_digits_with_fallback(analyser, picname: str) -> str:
"""先 analyse_pic_digits,失败再 analyse_pic_word,提取数字。
返回提取到的数字字符串;都失败返回 ""。
"""
digits = ""
try:
raw = analyser.operation.analyse_pic_digits(picname, 1)
digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
except Exception:
pass
if not digits:
try:
raw = analyser.operation.analyse_pic_word(picname, 1)
digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
except Exception:
pass
return digits
+216
View File
@@ -0,0 +1,216 @@
"""douyin_fudai_core_pkg.heavy_ocr 单元测试。
覆盖:
- _read_disable_flag: analyser 属性优先 / config.json fallback / 都缺时 False
- _ocr_digits_with_fallback: digits 成功 / digits 失败 word 兜底成功 / 都失败
- run_heavy_ocr: 各字段独立分支 / 配置开关 / 都失败时只剩 _duration_ms
"""
from __future__ import annotations
import json
from unittest.mock import MagicMock, patch
import pytest
from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import (
_ocr_digits_with_fallback,
_read_disable_flag,
run_heavy_ocr,
)
def _mk_analyser():
a = MagicMock()
a._log_kv = MagicMock(return_value=None)
a.operation = MagicMock()
return a
# ============================================================
# _read_disable_flag
# ============================================================
class TestReadDisableFlag:
def test_attr_true_short_circuits(self):
a = _mk_analyser()
a.fudai_disable_task_recognition = True
assert _read_disable_flag(
a, "fudai_disable_task_recognition", "fudai_disable_task_recognition"
) is True
def test_attr_false_falls_back_to_config_true(self, tmp_path, monkeypatch):
a = _mk_analyser()
a.fudai_disable_task_recognition = False
cfg_path = tmp_path / "config.json"
cfg_path.write_text(
json.dumps({"fudai_disable_task_recognition": True}), encoding="utf-8"
)
from douyin.core import path_config
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg_path))
assert _read_disable_flag(
a, "fudai_disable_task_recognition", "fudai_disable_task_recognition"
) is True
def test_attr_false_config_false_returns_false(self, tmp_path, monkeypatch):
a = _mk_analyser()
a.fudai_disable_task_recognition = False
cfg_path = tmp_path / "config.json"
cfg_path.write_text(json.dumps({}), encoding="utf-8")
from douyin.core import path_config
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg_path))
assert _read_disable_flag(
a, "fudai_disable_task_recognition", "fudai_disable_task_recognition"
) is False
def test_missing_config_file_returns_false(self, tmp_path, monkeypatch):
a = _mk_analyser()
a.x = False
from douyin.core import path_config
monkeypatch.setattr(
path_config, "get_config_path", lambda: str(tmp_path / "nope.json")
)
assert _read_disable_flag(a, "x", "y") is False
# ============================================================
# _ocr_digits_with_fallback
# ============================================================
class TestOcrDigitsWithFallback:
def test_digits_succeeds_immediately(self):
a = _mk_analyser()
a.operation.analyse_pic_digits = MagicMock(return_value="42")
a.operation.analyse_pic_word = MagicMock(return_value="should_not_be_called")
assert _ocr_digits_with_fallback(a, "X") == "42"
a.operation.analyse_pic_word.assert_not_called()
def test_digits_fails_word_succeeds(self):
a = _mk_analyser()
a.operation.analyse_pic_digits = MagicMock(return_value="")
a.operation.analyse_pic_word = MagicMock(return_value="abc12def")
assert _ocr_digits_with_fallback(a, "X") == "12"
def test_digits_throws_word_succeeds(self):
a = _mk_analyser()
a.operation.analyse_pic_digits = MagicMock(side_effect=RuntimeError())
a.operation.analyse_pic_word = MagicMock(return_value="3")
assert _ocr_digits_with_fallback(a, "X") == "3"
def test_both_fail_returns_empty(self):
a = _mk_analyser()
a.operation.analyse_pic_digits = MagicMock(return_value=None)
a.operation.analyse_pic_word = MagicMock(return_value=None)
assert _ocr_digits_with_fallback(a, "X") == ""
def test_both_throw_returns_empty(self):
a = _mk_analyser()
a.operation.analyse_pic_digits = MagicMock(side_effect=RuntimeError())
a.operation.analyse_pic_word = MagicMock(side_effect=RuntimeError())
assert _ocr_digits_with_fallback(a, "X") == ""
# ============================================================
# run_heavy_ocr
# ============================================================
class TestRunHeavyOcr:
def test_empty_fields_returns_only_duration(self):
a = _mk_analyser()
result = run_heavy_ocr(a, set())
# 只应有 _duration_ms
assert set(result.keys()) == {"_duration_ms"}
assert isinstance(result["_duration_ms"], (int, float))
def test_content_field_calls_analyse_pic_word(self):
a = _mk_analyser()
a.fudai_disable_content_recognition = False
a.operation.analyse_pic_word = MagicMock(return_value="福袋内容文本")
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
result = run_heavy_ocr(a, {"content"})
assert result["content"] == "福袋内容文本"
def test_content_skipped_when_disabled(self):
a = _mk_analyser()
a.operation.analyse_pic_word = MagicMock()
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=True,
):
result = run_heavy_ocr(a, {"content"})
# content 不应在结果中
assert "content" not in result
# 但应有跳过日志
assert any("跳过" in str(c) for c in a._log_kv.call_args_list)
def test_task_list_skipped_when_disabled(self):
a = _mk_analyser()
a.operation.analyse_pic_word = MagicMock()
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=True,
):
result = run_heavy_ocr(a, {"task_list"})
assert "task_list" not in result
def test_countdown_mm_uses_digits_path(self):
a = _mk_analyser()
a.operation.analyse_pic_digits = MagicMock(return_value="23")
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
result = run_heavy_ocr(a, {"countdown_mm"})
assert result["countdown_mm"] == "23"
def test_countdown_ss_uses_digits_path(self):
a = _mk_analyser()
a.operation.analyse_pic_digits = MagicMock(return_value="45")
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
result = run_heavy_ocr(a, {"countdown_ss"})
assert result["countdown_ss"] == "45"
def test_value_field(self):
a = _mk_analyser()
a.operation.analyse_pic_word = MagicMock(return_value="¥500")
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
result = run_heavy_ocr(a, {"value"})
assert result["value"] == "¥500"
def test_button_field(self):
a = _mk_analyser()
a.operation.analyse_pic_word = MagicMock(return_value="参与抽奖")
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
result = run_heavy_ocr(a, {"button"})
assert result["button"] == "参与抽奖"
def test_all_fields_at_once(self):
a = _mk_analyser()
a.operation.analyse_pic_word = MagicMock(return_value="word_result")
a.operation.analyse_pic_digits = MagicMock(return_value="11")
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
result = run_heavy_ocr(
a,
{"task_list", "content", "countdown_mm", "countdown_ss", "value", "button"},
)
assert "task_list" in result
assert "content" in result
assert "countdown_mm" in result
assert "countdown_ss" in result
assert "value" in result
assert "button" in result
assert "_duration_ms" in result