Files
douyin_guaji-main/douyin_fudai_detail.py
T
Your Name 2cd81c05a3 fix: Adjust configuration settings and improve error handling
- Updated `config.json` to modify `yanghao_recommend_interval_seconds` for better timing control.
- Refactored logging in `douyin_detection.py` to enhance readability and error handling.
- Improved pixel loading and error management in image processing functions across multiple modules.
- Enhanced GUI elements in `gui_app.py` to support new configuration options and improve user experience.
2025-12-21 21:55:30 +08:00

771 lines
28 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
"""
Fudai detail helpers shim (WebGUI version)
==========================================
Exports:
- close_fudai_detail
- ensure_fudai_detail_open
- read_live_room_title_core
- read_fudai_detail_once
- read_fudai_detail_with_retries
- is_abnormal_time_value
"""
from typing import Any, Dict, Tuple, List, Optional
import os
import time
import re
from PIL import Image
from douyin_detection import check_detail_height
from douyin_fudai_core import get_fudai_contain
# ============================================================================
# 直播间标题处理辅助函数(模块化)
# ============================================================================
def _room_title_has_ellipsis(s: str) -> bool:
"""检查是否包含省略号。"""
if "…" in s:
return True
if re.search(r"\.{3,}", s):
return True
return False
def _strip_room_noise_text(s: str) -> str:
"""移除直播间名 OCR 常见噪音(点赞/关注/粉丝等)。"""
try:
t = str(s or "")
except Exception:
return ""
t = t.replace("\r", "\n").replace("\t", " ")
t = re.sub(r"[\s\u3000]+", " ", t).strip()
# 计数噪音:例如 1.2万点赞 / 234点赞 / 3W点赞
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞)", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*关注", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*粉丝", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*人(?:在线|在看)?", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
t = re.sub(r"本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "人在线", "在线"):
t = t.replace(w, " ")
t = re.sub(r"\s+", " ", t).strip()
return t
def _extract_room_title_candidate(raw_text: str) -> str:
"""从 OCR 原文中提取更像"直播间名"的片段。"""
t = _strip_room_noise_text(raw_text)
if not t:
return ""
segs = [x.strip() for x in re.split(r"[\n ]+", t) if x.strip()]
best = ""
best_score = -999
for seg in segs:
if not seg:
continue
seg2 = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞|关注|粉丝)$", "", seg).strip()
if not seg2:
continue
seg = seg2
score = len(seg)
if _room_title_has_ellipsis(seg):
score += 30
if re.search(r"[\u4e00-\u9fffA-Za-z]", seg):
score += 5
if score > best_score:
best_score = score
best = seg
if best:
m = re.search(r"(.*?)(…|\.{3,})", best)
if m:
cand = (m.group(1) + m.group(2)).strip()
return cand if cand else best.strip()
return best.strip()
m2 = re.search(r"(.*?)(…|\.{3,})", t)
if m2:
cand2 = (m2.group(1) + m2.group(2)).strip()
if cand2:
return cand2
return t.strip()
def _normalize_room_title(t: str) -> str:
"""规范化直播间标题。"""
s = _extract_room_title_candidate(str(t or ""))
s = s.replace("\r", " ").replace("\n", " ").strip()
s = re.sub(r"\s+", "", s)
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"):
s = s.replace(w, "")
s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s)
s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s)
s = re.sub(r"本场(?:点赞|点赞|点贊|点)", "", s)
s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", s)
return s
def _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tuple[str, str]:
"""尝试 OCR 识别直播间标题。"""
try:
raw0 = analyser.operation.analyse_pic_word(cut_name, change_color)
except Exception:
raw0 = ""
raw_text0 = str(raw0 or "").replace("\r", "\n").strip()
cand_raw0 = _extract_room_title_candidate(raw_text0)
title0 = _normalize_room_title(cand_raw0)
return title0, cand_raw0
def _pick_best_room_title(cands: List[Tuple[str, str, str]], min_len: int = 3) -> Tuple[str, str]:
"""从多个候选结果中选择最佳的一个。"""
best = ("", "")
best_score = -1
for t_norm, t_raw, tag in cands:
if not t_raw and not t_norm:
continue
ln = len(t_norm or "")
score = ln
if ln >= min_len:
score += 10
if ln == 1:
score -= 4
if ln == 2:
score -= 1
if _room_title_has_ellipsis(t_raw or ""):
score += 8
if tag.endswith("_cc0"):
score += 2
if tag.startswith("large"):
score += 2
if tag.startswith("mid"):
score += 1
if score > best_score:
best_score = score
best = (t_norm, t_raw)
return best
def close_fudai_detail(analyser: Any) -> None:
"""关闭福袋详情:当前实现直接按一次返回键。"""
try:
analyser._log_kv("详情", "close_fudai_detail:按返回键一次")
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser.operation.delay(0.5)
except Exception:
time.sleep(0.5)
def ensure_fudai_detail_open(analyser: Any) -> bool:
"""确保福袋详情已打开:当前实现只记录日志并假定已打开。"""
try:
analyser._log_kv("详情", "ensure_fudai_detail_open:假定已打开")
except Exception:
pass
return True
def _is_wrong_coupon_popup(analyser: Any) -> bool:
"""在已点击疑似福袋后,判断当前弹窗是否为优惠券类,而非真正福袋详情。
只在"点击详情后"调用,不在平时循环中使用,避免额外开销。
逻辑:
1. 对屏幕中部区域做颜色统计
2. 如果同时检测到福袋详情和优惠券特征,需要OCR确认"开心收下"字样
3. 只有OCR确认是"开心收下"时,才判定为优惠券弹窗
"""
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
return False
path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
try:
pic = Image.open(path)
pic.load() # Force load to catch truncated files early
except (OSError, IOError, SyntaxError):
# Handle truncated image files
return False
except Exception:
return False
pic = pic.convert("RGBA")
pix = pic.load()
w, h = pic.size
# 扫描区域:153,351 到 266,451(基于1080x2400基准坐标)
# 根据实际分辨率缩放坐标
scale_x = w / 1080.0
scale_y = h / 2400.0
x1 = int(153 * scale_x)
y1 = int(351 * scale_y)
x2 = int(266 * scale_x)
y2 = int(451 * scale_y)
# 边界检查
x1 = max(0, min(x1, w))
y1 = max(0, min(y1, h))
x2 = max(0, min(x2, w))
y2 = max(0, min(y2, h))
if x1 >= x2 or y1 >= y2:
return False
fudai_like = 0
coupon_like = 0
step_x = max(1, (x2 - x1) // 40)
step_y = max(1, (y2 - y1) // 40)
for yy in range(y1, y2, step_y):
for xx in range(x1, x2, step_x):
try:
p = pix[xx, yy]
except Exception:
continue
if not (isinstance(p, tuple) and len(p) >= 3):
continue
r, g, b = int(p[0]), int(p[1]), int(p[2])
# 福袋:粉/紫/粉蓝
if r >= 200 and b >= 210 and 80 <= g <= 230:
fudai_like += 1
# 券:偏橙色
if r >= 200 and 120 <= g <= 230 and b <= 180:
coupon_like += 1
try:
analyser._log_kv(
"弹窗",
"弹窗颜色统计",
fudai_like=fudai_like,
coupon_like=coupon_like,
)
except Exception:
pass
# 如果券像素明显多于粉袋像素,可能需要OCR确认
is_coupon_like_by_color = coupon_like > fudai_like * 1.2
# 检测是否同时有福袋详情特征(通过像素检测)
has_fudai_detail = False
try:
import douyin_pixel
resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
pic_rgb = pic.convert("RGB")
has_fudai_detail = douyin_pixel.detect_fudai_detail_page(pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi)
except Exception:
pass
# 如果颜色统计显示可能是优惠券,但同时也检测到福袋详情,需要OCR确认
if is_coupon_like_by_color and has_fudai_detail:
try:
analyser._log_kv("弹窗", "颜色统计显示可能是优惠券,但检测到福袋详情,需要OCR确认")
# 使用参与按钮区域检测"开心收下"
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
# 如果模式0未识别到,尝试模式1
enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False))
if enable_ocr_mode1 and (not coupon_text or "开心收下" not in coupon_text):
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "")
if coupon_text and "开心收下" in coupon_text:
analyser._log_kv("弹窗", "OCR确认:检测到'开心收下',判定为优惠券弹窗", OCR文本=coupon_text[:50])
return True
else:
analyser._log_kv("弹窗", "OCR确认:未检测到'开心收下',判定为福袋详情页", OCR文本=coupon_text[:50] if coupon_text else "空")
return False
except Exception as e:
# OCR确认失败,如果颜色统计明显偏向优惠券,则按颜色统计结果
analyser._log_kv("弹窗", "OCR确认失败,按颜色统计结果", error=str(e))
return is_coupon_like_by_color
# 如果颜色统计显示可能是优惠券,且未检测到福袋详情,直接判定为优惠券弹窗
if is_coupon_like_by_color:
return True
# 否则判定为福袋详情页
return False
def read_live_room_title_core(
analyser: Any,
y_pianyi: int,
min_len: int = 3,
) -> Tuple[str, str]:
"""读取当前直播间顶部区域的"主播名/直播间名"(OCR,尽量轻量)。
使用多个 ROI 区域和不同的 OCR 模式进行识别,选择最佳结果。
"""
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
pass
cands: List[Tuple[str, str, str]] = []
# mid ROI:优先使用更大区域,减少"只截到尾巴1个字"
try:
analyser.cut_pic(80, 128, 560, 230, '', 'live_room_title_mid', y_pianyi)
t, r = _ocr_try_room_title(analyser, 'live_room_title_mid', 0)
cands.append((t, r, 'mid_cc0'))
if len(t or "") < min_len:
t1, r1 = _ocr_try_room_title(analyser, 'live_room_title_mid', 1)
cands.append((t1, r1, 'mid_cc1'))
except Exception:
pass
# large ROI:进一步扩大,兼容机型/系统字体/刘海偏移
if not cands or max(len(x[0] or "") for x in cands) < min_len:
try:
analyser.cut_pic(40, 110, 660, 260, '', 'live_room_title_large', y_pianyi)
t2, r2 = _ocr_try_room_title(analyser, 'live_room_title_large', 0)
cands.append((t2, r2, 'large_cc0'))
if len(t2 or "") < min_len:
t3, r3 = _ocr_try_room_title(analyser, 'live_room_title_large', 1)
cands.append((t3, r3, 'large_cc1'))
except Exception:
pass
# small ROI:最后兜底(历史区域)
if not cands or max(len(x[0] or "") for x in cands) <= 1:
try:
analyser.cut_pic(138, 144, 335, 185, '', 'live_room_title_small', y_pianyi)
t4, r4 = _ocr_try_room_title(analyser, 'live_room_title_small', 0)
cands.append((t4, r4, 'small_cc0'))
except Exception:
pass
title, raw_text = _pick_best_room_title(cands, min_len)
# 更新 analyser 的属性
try:
analyser.current_room_title_raw = raw_text
if title:
analyser.current_room_title = title
except Exception:
pass
return title, raw_text
def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
"""执行一次福袋详情识别(本地完整版实现)。
流程:
1. 若检测到优惠券弹窗,则视为误点并关闭,返回状态 coupon_popup;
2. 使用像素高度检测任务数 (`check_detail_height`);
3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
"""
# 先检测是否是“优惠券弹窗”
if _is_wrong_coupon_popup(analyser):
try:
analyser._log_kv("弹窗", "检测到优惠券弹窗,视为误点并关闭")
except Exception:
pass
close_fudai_detail(analyser)
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 结果",
status="coupon_popup",
content="",
time_text="",
participants=0,
copies=0,
prize_value_yuan=0.0,
countdown_start=None,
countdown_end=None,
)
except Exception:
pass
return "coupon_popup", (), {"popup_type": "coupon"}
# 任务数:0/1/2/3,异常时默认按 2 个任务处理
try:
task_count = int(check_detail_height(analyser) or 0)
except Exception:
task_count = 0
if task_count not in (1, 2, 3):
task_count = 2
# 识别福袋内容 / 倒计时 / 价值
try:
content, time_text, participants, copies, prize_value_yuan = get_fudai_contain(
analyser, renwu=task_count
)
except Exception as e:
# 出现异常时,记录错误并返回占位结果
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 异常",
error=str(e),
)
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
return "error", tup_err, {}
# 解析倒计时 -> (剩余秒数, 未来时间戳)
countdown_start = time.time()
countdown_end = countdown_start + 60.0
try:
if time_text:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
total_seconds, future_ts = res
try:
total_seconds = int(total_seconds)
except Exception:
total_seconds = int(float(total_seconds or 0))
if total_seconds > 0 and isinstance(future_ts, (int, float)):
countdown_start = float(countdown_start)
countdown_end = float(future_ts)
except Exception:
pass
detail_tuple = (
content or "",
time_text or "",
int(participants or 0),
int(copies or 0),
float(prize_value_yuan or 0.0),
(countdown_start, countdown_end),
)
extra: Dict[str, Any] = {
"task_count": task_count,
}
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 结果",
status="ok",
content=detail_tuple[0],
time_text=detail_tuple[1],
participants=detail_tuple[2],
copies=detail_tuple[3],
prize_value_yuan=detail_tuple[4],
countdown_start=countdown_start,
countdown_end=countdown_end,
task_count=task_count,
)
except Exception:
pass
return "ok", detail_tuple, extra
def read_fudai_detail_with_retries(
analyser: Any,
fudai_x: int,
read_once_callback,
close_detail_callback,
ensure_open_callback,
) -> Tuple:
"""多次重试读取福袋详情,返回 6 字段 detail tuple。
与原版保持兼容:总是返回
(content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
"""
max_attempts = 2
try:
max_attempts = int(getattr(analyser, "fudai_detail_max_attempts", 2) or 2)
except Exception:
max_attempts = 2
if max_attempts < 1:
max_attempts = 1
retry_delay = 0.8
try:
retry_delay = float(getattr(analyser, "fudai_detail_retry_delay_seconds", 0.8) or 0.8)
except Exception:
retry_delay = 0.8
last_tuple: Optional[Tuple] = None
last_status: str = "error"
first_countdown_seconds: Optional[float] = None
first_tuple: Optional[Tuple] = None
first_attempt_time: float = 0.0
for attempt in range(max_attempts):
attempt_start_time = time.time()
status, tup, extra = read_fudai_detail_once(analyser)
last_status = status
if isinstance(tup, tuple) and len(tup) >= 6:
current_tuple = tup[:6]
# 计算当前倒计时秒数
current_countdown_seconds = None
try:
cd = current_tuple[5]
if isinstance(cd, (tuple, list)) and len(cd) >= 2:
cd_start = float(cd[0] or 0.0)
cd_end = float(cd[1] or 0.0)
if cd_start > 0 and cd_end > cd_start:
current_countdown_seconds = cd_end - cd_start
except Exception:
pass
# 记录第一次成功读取的结果(作为基准)
if first_countdown_seconds is None and current_countdown_seconds is not None and status == "ok":
first_countdown_seconds = current_countdown_seconds
first_tuple = current_tuple
first_attempt_time = attempt_start_time
last_tuple = current_tuple
# 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误
elif first_countdown_seconds is not None and current_countdown_seconds is not None:
# 计算时间流逝(从第一次读取到现在的时间差)
time_elapsed = attempt_start_time - first_attempt_time
if time_elapsed < 0:
time_elapsed = 0.5 # 默认假设间隔0.5秒
# 预期倒计时 = 第一次倒计时 - 时间流逝(允许一定误差)
expected_countdown = first_countdown_seconds - time_elapsed
# 计算实际差异(与第一次相比)
diff_ratio = abs(current_countdown_seconds - first_countdown_seconds) / max(first_countdown_seconds, 1.0)
# 计算与预期的差异(考虑时间流逝)
expected_diff_ratio = abs(current_countdown_seconds - expected_countdown) / max(expected_countdown, 1.0) if expected_countdown > 0 else 1.0
# 如果差异过大(超过30%)或与预期差异过大(超过20%),判定为识别错误
# 注意:如果当前倒计时明显大于第一次(时间应该减少),肯定是识别错误
is_inconsistent = (
diff_ratio > 0.3 or
expected_diff_ratio > 0.2 or
current_countdown_seconds > first_countdown_seconds + 10 # 倒计时不应该增加
)
if is_inconsistent:
try:
analyser._log_kv(
"福袋详情",
"倒计时识别不一致,判定为识别错误(拒绝本次结果,保留第一次结果)",
attempt=attempt + 1,
first_countdown_seconds=int(first_countdown_seconds),
current_countdown_seconds=int(current_countdown_seconds),
expected_countdown=int(expected_countdown),
time_elapsed=round(time_elapsed, 2),
diff_ratio=round(diff_ratio, 3),
expected_diff_ratio=round(expected_diff_ratio, 3),
)
except Exception:
pass
# 拒绝本次结果,继续使用第一次的结果
current_tuple = first_tuple
# 如果还有重试机会,继续重试
if attempt < max_attempts - 1:
try:
analyser.operation.delay(retry_delay)
except Exception:
time.sleep(retry_delay)
continue
else:
# 倒计时合理,更新为当前结果
last_tuple = current_tuple
# 如果没有第一次结果,直接使用当前结果
elif first_countdown_seconds is None:
last_tuple = current_tuple
# 如果成功读取,或者检测到优惠券弹窗(已处理完毕),都停止重试
if status == "ok" or status == "coupon_popup":
break
if attempt < max_attempts - 1:
try:
analyser.operation.delay(retry_delay)
except Exception:
time.sleep(retry_delay)
if last_tuple is None:
now = time.time()
last_tuple = ("", "", 0, 0, 0.0, (now, now + 60.0))
content, time_text, participants, copies, prize_value_yuan, cd = last_tuple
cd_start, cd_end = None, None
if isinstance(cd, (tuple, list)) and len(cd) >= 2:
cd_start, cd_end = cd[0], cd[1]
# 如果是优惠券弹窗,记录日志并明确标记
is_coupon_popup = (last_status == "coupon_popup")
if is_coupon_popup:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries 最终结果:优惠券弹窗,已关闭,跳过后续处理",
status=last_status,
fudai_x=fudai_x,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries 最终结果",
status=last_status,
content=content,
time_text=time_text,
participants=participants,
copies=copies,
prize_value_yuan=prize_value_yuan,
countdown_start=cd_start,
countdown_end=cd_end,
fudai_x=fudai_x,
)
except Exception:
pass
# 将状态信息存储在 analyser 中,供调用方检查
try:
analyser._last_fudai_detail_status = last_status # type: ignore[attr-defined]
except Exception:
pass
# 验证福袋详情数据的合理性(仅在成功读取时验证)
if last_status == "ok":
is_valid, reason = validate_fudai_detail(last_tuple, analyser)
if not is_valid:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries:数据验证失败,识别可能出错",
validation_reason=reason,
content=content[:50] if content else "",
prize_value_yuan=prize_value_yuan,
participants=participants,
copies=copies,
time_text=time_text[:30] if time_text else "",
)
# 标记为识别错误
analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined]
except Exception:
pass
return last_tuple
def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, str]:
"""验证福袋详情数据的合理性。
返回:
(is_valid, reason) - is_valid=True 表示数据合理,False 表示识别出错
reason 为失败原因描述
"""
if not isinstance(detail, tuple) or len(detail) < 6:
return False, "detail_tuple_invalid"
content = str(detail[0] or "").strip()
time_text = str(detail[1] or "").strip()
try:
participants = int(detail[2] or 0)
except Exception:
participants = 0
try:
copies = int(detail[3] or 0)
except Exception:
copies = 0
try:
prize_value_yuan = float(detail[4] or 0.0)
except Exception:
prize_value_yuan = 0.0
countdown_tuple = detail[5]
countdown_start, countdown_end = None, None
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
try:
countdown_start = float(countdown_tuple[0] or 0.0)
countdown_end = float(countdown_tuple[1] or 0.0)
except Exception:
pass
# 检查1:内容不能为空(至少要有一些文字)
if not content or len(content.strip()) < 2:
return False, "content_empty_or_too_short"
# 检查2:价值应该大于0(福袋至少应该有价值)
if prize_value_yuan <= 0:
return False, "prize_value_zero_or_negative"
# 检查3:价值应该合理(不能太大,比如超过100万)
if prize_value_yuan > 1000000:
return False, "prize_value_too_large"
# 检查4:倒计时应该合理
if countdown_end is not None and countdown_start is not None:
remain_seconds = countdown_end - countdown_start
# 倒计时不能是负数
if remain_seconds < 0:
return False, "countdown_negative"
# 倒计时不能太长(超过24小时)
if remain_seconds > 24 * 3600:
return False, "countdown_too_long"
# 倒计时不能为0(至少应该有几秒)
if remain_seconds == 0 and not time_text:
return False, "countdown_zero_and_no_time_text"
# 倒计时合理性检查:如果 time_text 存在,验证倒计时与 time_text 是否一致
if time_text:
try:
# 解析 time_text 为秒数
import re
m = re.search(r"(\d{1,2})[::](\d{1,2})", time_text)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
# 如果秒数>=60,尝试交换分秒
if ss >= 60 and mm < 60:
mm, ss = ss, mm
# 如果秒数仍然>=60,进行进位
if ss >= 60:
mm += ss // 60
ss = ss % 60
text_seconds = mm * 60 + ss
# 允许一定误差(±10%),但差异过大则判定为识别错误
if text_seconds > 0:
diff_ratio = abs(remain_seconds - text_seconds) / max(text_seconds, 1.0)
if diff_ratio > 0.15: # 差异超过15%视为不一致
return False, f"countdown_mismatch_time_text (remain={int(remain_seconds)}, text={text_seconds}, diff={round(diff_ratio*100, 1)}%)"
except Exception:
pass
# 检查5:参与人数应该合理(不能是负数)
if participants < 0:
return False, "participants_negative"
# 检查6:份数应该合理(不能是负数,至少应该是1)
if copies < 0:
return False, "copies_negative"
# 检查7:如果份数为0,但参与人数大于0,可能识别错误
if copies == 0 and participants > 0:
return False, "copies_zero_but_participants_positive"
# 检查8:时间文本应该存在(至少应该有倒计时信息)
if not time_text and (countdown_end is None or countdown_end <= 0):
return False, "no_time_text_and_no_countdown"
# 所有检查通过
return True, "ok"
def is_abnormal_time_value(v: float) -> bool:
"""Shim: treat clearly invalid time values as abnormal."""
if v <= 0:
return True
if v > 24 * 3600 * 7:
return True
return False