Compare commits
93
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
273adbb677 | ||
|
|
7aeb0c881c | ||
|
|
0629906449 | ||
|
|
5355e52b06 | ||
|
|
8da7dcc819 | ||
|
|
2594788a8c | ||
|
|
1801e50a4c | ||
|
|
e5f7434034 | ||
|
|
ee6ce26338 | ||
|
|
61e37f6644 | ||
|
|
48d78147b5 | ||
|
|
df8942e7b8 | ||
|
|
2899c932c4 | ||
|
|
5383bbc131 | ||
|
|
2f21b2a0b4 | ||
|
|
acd8f5c387 | ||
|
|
42ef73a9ee | ||
|
|
6d5b2cfb15 | ||
|
|
01034347f4 | ||
|
|
e3daeab024 | ||
|
|
411fd96804 | ||
|
|
0bd71a5e76 | ||
|
|
cec4a2d692 | ||
|
|
ca071250be | ||
|
|
398133bbb0 | ||
|
|
06c3e54d26 | ||
|
|
28dcbc75c7 | ||
|
|
dadb0b6852 | ||
|
|
6aec4ae314 | ||
|
|
4ce62a1907 | ||
|
|
f0150cb3f4 | ||
|
|
8d426676f6 | ||
|
|
f5b603e39e | ||
|
|
b1f70aa94d | ||
|
|
81b82e6cba | ||
|
|
2ba2168665 | ||
|
|
d9323f2012 | ||
|
|
e3372fa51d | ||
|
|
0b3d69d28b | ||
|
|
0eb4670d46 | ||
|
|
5f713afc5c | ||
|
|
722b57a7b9 | ||
|
|
43da92f6e6 | ||
|
|
798286776d | ||
|
|
77d7113ca1 | ||
|
|
b8ccb899c0 | ||
|
|
d109e94c68 | ||
|
|
887f8bad3e | ||
|
|
c2a44f2544 | ||
|
|
f2b5aaa2c4 | ||
|
|
4f042f95cd | ||
|
|
23e24a9f27 | ||
|
|
c5a70d4a62 | ||
|
|
3de07d7a66 | ||
|
|
d35fadde54 | ||
|
|
241c35f21d | ||
|
|
1468d14d0e | ||
|
|
45f925b597 | ||
|
|
e21e5a5fca | ||
|
|
7694e233f9 | ||
|
|
a90a885a51 | ||
|
|
48f4af5848 | ||
|
|
3af7c6d894 | ||
|
|
6f796a8aaf | ||
|
|
e351745e92 | ||
|
|
0114af2321 | ||
|
|
849160304e | ||
|
|
7307b2abb5 | ||
|
|
c9a07cc91e | ||
|
|
b5d7943af0 | ||
|
|
da552d18cc | ||
|
|
40b4169aac | ||
|
|
265a533cf0 | ||
|
|
37b3454e32 | ||
|
|
77351bafd4 | ||
|
|
9675df2cdb | ||
|
|
d34e39ec9c | ||
|
|
34bdf44d73 | ||
|
|
6f4dbb2d8b | ||
|
|
4e89fadd2e | ||
|
|
331860ee5c | ||
|
|
4abd053957 | ||
|
|
8fea99a168 | ||
|
|
51d859150d | ||
|
|
c509bf1262 | ||
|
|
3b600c9f64 | ||
|
|
d7201866a5 | ||
|
|
a3fe7b3ef0 | ||
|
|
1c1f0abfc0 | ||
|
|
5d2a0ac3ff | ||
|
|
c8df6a1588 | ||
|
|
b1ee0e6b4e | ||
|
|
b9f0389e58 |
No files matched your search
+129
-3655
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,167 @@
|
||||
"""fudai_choujiang 辅助函数
|
||||
|
||||
从 douyin_fudai.py:fudai_choujiang 中提取的独立子块:
|
||||
- cleanup_stale_screenshot:清理启动时残留的旧截图
|
||||
- resolve_device_resolution:解析设备分辨率(带重试和默认回退)
|
||||
- write_actions_log:写运行起止标记到 actions.log
|
||||
- run_loop_with_timeout:fudai_choujiang 的主循环(定时/无限)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
# 用于 write_actions_log 的 log_dir_anchor:从 helper 文件位置回溯到 douyin_fudai.py 所在目录
|
||||
_ANCHOR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "douyin_fudai.py")
|
||||
|
||||
|
||||
def cleanup_stale_screenshot(analyser) -> None:
|
||||
"""启动时清理旧截图文件,避免复用过期截图。"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
os.remove(pic_path)
|
||||
analyser._log_kv(
|
||||
"启动",
|
||||
"清理旧截图文件,避免复用过期截图",
|
||||
path=pic_path,
|
||||
log_type="SCREENSHOT",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"启动",
|
||||
f"清理旧截图文件失败 - {str(e)}",
|
||||
level="WARNING",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def resolve_device_resolution(analyser) -> None:
|
||||
"""获取设备分辨率(重试 5 次),失败回退到 1080x2400 默认值。
|
||||
|
||||
直接写入 analyser.resolution_ratio_x / analyser.resolution_ratio_y。
|
||||
"""
|
||||
resolved = False
|
||||
if analyser.device_id:
|
||||
for attempt in range(5):
|
||||
try:
|
||||
rx, ry = analyser.operation.get_device_resolution(analyser.device_id)
|
||||
analyser.resolution_ratio_x = int(rx or 1080)
|
||||
analyser.resolution_ratio_y = int(ry or 2400)
|
||||
resolved = True
|
||||
break
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"截图",
|
||||
"获取分辨率失败,重试中",
|
||||
attempt=attempt + 1,
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
logging.warning(
|
||||
f"[DEBUG] get_device_resolution attempt {attempt + 1} failed: {e}"
|
||||
)
|
||||
time.sleep(1.0)
|
||||
if not resolved:
|
||||
try:
|
||||
analyser._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = 1080, 2400
|
||||
|
||||
|
||||
def run_loop_with_timeout(analyser, wait_minutes: int) -> None:
|
||||
"""fudai_choujiang 主循环:定时模式 vs 无限循环模式。
|
||||
|
||||
定时模式(wait_minutes > 0):在 wait_minutes 分钟内反复跑 run_once_basic。
|
||||
无限模式(wait_minutes <= 0):直到 Ctrl+C。
|
||||
|
||||
异常时延迟 2s 后继续,每轮之间延迟 1s 避免频繁截图。
|
||||
"""
|
||||
if wait_minutes and wait_minutes > 0:
|
||||
end_ts = time.time() + int(wait_minutes) * 60
|
||||
while time.time() < end_ts:
|
||||
try:
|
||||
analyser.run_once_basic()
|
||||
except Exception as exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"循环",
|
||||
"run_once_basic 异常",
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.delay(2.0)
|
||||
except Exception:
|
||||
time.sleep(2.0)
|
||||
continue
|
||||
|
||||
try:
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
time.sleep(1.0)
|
||||
|
||||
write_actions_log("程序运行结束(时间到)", _ANCHOR)
|
||||
else:
|
||||
analyser._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
|
||||
while True:
|
||||
try:
|
||||
analyser.run_once_basic()
|
||||
except KeyboardInterrupt:
|
||||
analyser._log_kv("循环", "收到中断信号,退出循环")
|
||||
write_actions_log("程序运行结束(中断退出)", _ANCHOR)
|
||||
raise
|
||||
except Exception as exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"循环",
|
||||
"run_once_basic 异常",
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.delay(2.0)
|
||||
except Exception:
|
||||
time.sleep(2.0)
|
||||
continue
|
||||
|
||||
try:
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
time.sleep(1.0)
|
||||
|
||||
|
||||
def write_actions_log(message: str, log_dir_anchor: str) -> None:
|
||||
"""写一条带时间戳的标记到 logs/actions.log。
|
||||
|
||||
log_dir_anchor 用于定位 logs 目录(通常是 douyin_fudai 模块所在目录)。
|
||||
"""
|
||||
try:
|
||||
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(log_dir_anchor), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
with open(
|
||||
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
|
||||
) as f:
|
||||
f.write("=" * 80 + "\n")
|
||||
f.write(f"{ts} - [GUI] - [运行] {message}\n")
|
||||
f.flush()
|
||||
except Exception:
|
||||
pass
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,281 @@
|
||||
"""福袋图像辅助函数
|
||||
|
||||
从 douyin_fudai.py 中提取的图像处理工具函数:
|
||||
- capture_roi_screenshot:捕获 ROI 截图
|
||||
- match_icon_template:模板匹配
|
||||
|
||||
这两个函数原本是 fudai_analyse 类的方法 (_capture_roi_screenshot / _match_icon_template),
|
||||
对 self 的依赖很轻,提取为模块级函数后,类内方法变为薄包装。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
from typing import Tuple
|
||||
|
||||
from PIL import Image, UnidentifiedImageError # type: ignore[import]
|
||||
import numpy as np # type: ignore[import]
|
||||
|
||||
|
||||
def capture_roi_screenshot(
|
||||
analyser,
|
||||
label: str,
|
||||
sx: int,
|
||||
sy: int,
|
||||
size: int,
|
||||
screenshot_path: str | None = None,
|
||||
) -> str:
|
||||
"""捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。
|
||||
|
||||
返回 ROI 图片路径(绝对路径),失败返回空字符串。
|
||||
"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
if screenshot_path is None:
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
except Exception:
|
||||
pass
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
else:
|
||||
pic_path = screenshot_path
|
||||
if not os.path.exists(pic_path):
|
||||
return ""
|
||||
|
||||
half = int(size // 2)
|
||||
left = int(max(0, sx - half))
|
||||
top = int(max(0, sy - half))
|
||||
right = int(sx + half)
|
||||
bottom = int(sy + half)
|
||||
|
||||
data = None
|
||||
for attempt in range(6):
|
||||
try:
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not os.path.exists(pic_path):
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
sz = os.path.getsize(pic_path)
|
||||
if sz < 1024:
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
with open(pic_path, "rb") as f:
|
||||
data = f.read()
|
||||
if not data or not data.startswith(b"\x89PNG"):
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
if b"IEND" not in data[-512:]:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
|
||||
try:
|
||||
img_test = Image.open(io.BytesIO(data))
|
||||
img_test.verify()
|
||||
except Exception:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
|
||||
break
|
||||
except Exception:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
|
||||
if not data:
|
||||
return ""
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img.load()
|
||||
except UnidentifiedImageError:
|
||||
return ""
|
||||
except Exception:
|
||||
try:
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
with open(pic_path, "rb") as f:
|
||||
data2 = f.read()
|
||||
if (
|
||||
data2
|
||||
and data2.startswith(b"\x89PNG")
|
||||
and b"IEND" in data2[-512:]
|
||||
):
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data2))
|
||||
img.load()
|
||||
except Exception:
|
||||
return ""
|
||||
else:
|
||||
return ""
|
||||
except Exception:
|
||||
return ""
|
||||
w, h = img.size
|
||||
left = max(0, min(left, w - 1))
|
||||
top = max(0, min(top, h - 1))
|
||||
right = max(1, min(right, w))
|
||||
bottom = max(1, min(bottom, h))
|
||||
|
||||
roi = img.crop((left, top, right, bottom))
|
||||
out_dir = path_config.get_pic_dir()
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
fname = (
|
||||
f"roi_{label}_{getattr(analyser, '_run_id', 'run')}_{int(time.time())}.png"
|
||||
)
|
||||
out_path = os.path.join(out_dir, fname)
|
||||
roi.save(out_path)
|
||||
return out_path
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"截图",
|
||||
"_capture_roi_screenshot 失败",
|
||||
label=label,
|
||||
sx=sx,
|
||||
sy=sy,
|
||||
size=size,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def match_icon_template(
|
||||
analyser,
|
||||
roi_path: str,
|
||||
template_path: str,
|
||||
threshold: float | None = None,
|
||||
) -> Tuple[bool, float]:
|
||||
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
|
||||
|
||||
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
|
||||
如果提供 `threshold` 则使用该阈值判断匹配,否则回退到配置 `yanghao_icon_match_threshold`。
|
||||
返回 (detected, score),若发生错误或文件缺失返回 (False, 0.0)。
|
||||
"""
|
||||
try:
|
||||
if not roi_path or not os.path.exists(roi_path):
|
||||
return False, 0.0
|
||||
if not template_path or not os.path.exists(template_path):
|
||||
return False, 0.0
|
||||
|
||||
roi_img = Image.open(roi_path).convert("RGB")
|
||||
tpl_img = Image.open(template_path).convert("RGB")
|
||||
|
||||
rw, rh = roi_img.size
|
||||
tw, th = tpl_img.size
|
||||
if tw > rw or th > rh:
|
||||
scale = min(rw / tw, rh / th, 1.0)
|
||||
new_w = max(1, int(tw * scale))
|
||||
new_h = max(1, int(th * scale))
|
||||
tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
||||
tw, th = tpl_img.size
|
||||
|
||||
roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32)
|
||||
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
|
||||
|
||||
if (
|
||||
roi_gray.shape[0] == tpl_gray.shape[0]
|
||||
and roi_gray.shape[1] == tpl_gray.shape[1]
|
||||
):
|
||||
A = roi_gray.flatten()
|
||||
B = tpl_gray.flatten()
|
||||
else:
|
||||
ih, iw = roi_gray.shape
|
||||
th, tw = tpl_gray.shape
|
||||
if ih >= th and iw >= tw:
|
||||
cy = ih // 2 - th // 2
|
||||
cx = iw // 2 - tw // 2
|
||||
cy = max(0, min(cy, ih - th))
|
||||
cx = max(0, min(cx, iw - tw))
|
||||
window = roi_gray[cy : cy + th, cx : cx + tw]
|
||||
a = window.flatten()
|
||||
b = tpl_gray.flatten()
|
||||
a = a - a.mean()
|
||||
b = b - b.mean()
|
||||
denom = np.linalg.norm(a) * np.linalg.norm(b)
|
||||
if denom > 1e-6:
|
||||
score = float(np.dot(a, b) / denom)
|
||||
else:
|
||||
score = -1.0
|
||||
if score >= 0.55:
|
||||
used_thr = (
|
||||
float(threshold)
|
||||
if threshold is not None
|
||||
else float(
|
||||
getattr(analyser, "yanghao_icon_match_threshold", 0.70)
|
||||
or 0.70
|
||||
)
|
||||
)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
|
||||
ih, iw = roi_gray.shape
|
||||
th, tw = tpl_gray.shape
|
||||
best = -1.0
|
||||
step_y = max(1, th // 6)
|
||||
step_x = max(1, tw // 6)
|
||||
for y in range(0, ih - th + 1, step_y):
|
||||
for x in range(0, iw - tw + 1, step_x):
|
||||
window = roi_gray[y : y + th, x : x + tw]
|
||||
a = window.flatten()
|
||||
b = tpl_gray.flatten()
|
||||
a = a - a.mean()
|
||||
b = b - b.mean()
|
||||
denom = np.linalg.norm(a) * np.linalg.norm(b)
|
||||
if denom <= 1e-6:
|
||||
continue
|
||||
score = float(np.dot(a, b) / denom)
|
||||
if score > best:
|
||||
best = score
|
||||
if best < -0.5:
|
||||
return False, 0.0
|
||||
score = float(best)
|
||||
used_thr = (
|
||||
float(threshold)
|
||||
if threshold is not None
|
||||
else float(
|
||||
getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70
|
||||
)
|
||||
)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
|
||||
A = roi_gray.flatten()
|
||||
B = tpl_gray.flatten()
|
||||
A = A - A.mean()
|
||||
B = B - B.mean()
|
||||
denom = np.linalg.norm(A) * np.linalg.norm(B)
|
||||
if denom <= 1e-6:
|
||||
return False, 0.0
|
||||
score = float(np.dot(A, B) / denom)
|
||||
used_thr = (
|
||||
float(threshold)
|
||||
if threshold is not None
|
||||
else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70)
|
||||
)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"检测",
|
||||
"_match_icon_template 异常",
|
||||
roi_path=roi_path,
|
||||
template_path=template_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
@@ -0,0 +1,287 @@
|
||||
"""福袋分析器默认配置初始化
|
||||
|
||||
从 douyin_fudai.py:fudai_analyse.__init__ 中提取的默认配置块。
|
||||
所有字段都是简单的 self.X = literal 赋值,无逻辑分支。
|
||||
后续 load_config() 会从 config.json 读取覆盖这些默认值。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def init_basic_state(self) -> None:
|
||||
"""初始化基础状态字段:device、分辨率、计数器、operation、config_path。"""
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
self.device_id: str = ""
|
||||
self.y_pianyi: int = 0
|
||||
self.resolution_ratio_x: int = 1080
|
||||
self.resolution_ratio_y: int = 2400
|
||||
self._swipe_times: int = 0
|
||||
self.operation = underlying_operations()
|
||||
self.config_path = "config/config.json"
|
||||
|
||||
|
||||
def init_log_infra(self) -> None:
|
||||
"""初始化日志相关字段:_run_id、_log_seq、_log_kv 闭包等。"""
|
||||
import logging
|
||||
import time as _time
|
||||
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
self._run_id = datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
except Exception as e:
|
||||
logging.debug("生成 run_id 失败,回退到时间戳: %s", e)
|
||||
self._run_id = str(int(_time.time()))
|
||||
self._log_seq = 0
|
||||
self._log_kv_orig = None
|
||||
self._use_real_timestamp = False
|
||||
|
||||
from douyin.logging import douyin_logging_wrapper
|
||||
|
||||
self._log_kv = lambda *args, **kwargs: douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv(
|
||||
self, *args, **kwargs
|
||||
)
|
||||
self._last_log_tag = None
|
||||
self._std_logger = None # type: ignore[assignment]
|
||||
|
||||
|
||||
def init_diag_timeout_state(self) -> None:
|
||||
"""初始化阶段诊断 + 30 分钟超时相关状态字段。"""
|
||||
import time as _time
|
||||
|
||||
self._last_diag_stage: str = "INIT"
|
||||
self._last_diag_seen: str = "-"
|
||||
self._last_diag_ts: float = 0.0
|
||||
|
||||
self._last_successful_attend_ts: float = 0.0
|
||||
self._no_attend_timeout_minutes: float = 30.0
|
||||
self._run_start_ts: float = _time.time()
|
||||
self._reservations_state_last_write_ts: float = 0.0
|
||||
self.last_fudai_x: int = 0
|
||||
|
||||
|
||||
def init_reservation_runtime_state(self) -> None:
|
||||
"""初始化预约运行时状态字段(单次运行内有效)。"""
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
self.reservations: list[dict[str, Any]] = []
|
||||
self._first_run_once_basic: bool = True
|
||||
self.room_pos: int = 0
|
||||
self.reservation_focus_until_ts: float = 0.0
|
||||
self.reservation_after_action_pending: bool = False
|
||||
self.reset_to_list_after_reservations: bool = False
|
||||
self.queue_full_waiting_at_earliest: bool = False
|
||||
|
||||
# 预约队列状态文件(供 WebGUI / 其他进程查看)
|
||||
try:
|
||||
from douyin.core import path_config as _pc
|
||||
|
||||
self._reservations_state_path: str = _pc.get_reservations_path()
|
||||
except Exception:
|
||||
self._reservations_state_path = os.path.join(
|
||||
os.path.dirname(__file__), "state", "reservations.json"
|
||||
)
|
||||
|
||||
|
||||
def init_logging_system(self) -> None:
|
||||
"""初始化统一日志系统 + traceId(MDC)。
|
||||
|
||||
设置 self._std_logger 和 trace_id(基于 _run_id)。
|
||||
"""
|
||||
import logging
|
||||
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
if not getattr(douyin_logging, "_logging_configured", False):
|
||||
douyin_logging.configure_logging()
|
||||
except Exception as e:
|
||||
logging.warning("日志系统初始化失败: %s", e)
|
||||
|
||||
try:
|
||||
from douyin.logging.unified_logger import MDC, get_unified_logger
|
||||
|
||||
MDC.set_trace_id(f"run_{self._run_id}")
|
||||
self._std_logger = get_unified_logger("douyin.fudai")
|
||||
except ImportError:
|
||||
self._std_logger = logging.getLogger("douyin.fudai")
|
||||
root_logger = logging.getLogger()
|
||||
if not root_logger.handlers:
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def cleanup_old_room_pos_map_files(self) -> None:
|
||||
"""每次重新运行时丢弃磁盘上旧的映射表导出文件(JSON/CSV/MD)。"""
|
||||
import os
|
||||
|
||||
try:
|
||||
state_dir = os.path.dirname(self._reservations_state_path)
|
||||
state_path = os.path.join(state_dir, "room_pos_map.json")
|
||||
csv_path = os.path.join(state_dir, "room_pos_map.csv")
|
||||
md_path = os.path.join(state_dir, "room_pos_map.md")
|
||||
for p in (state_path, csv_path, md_path):
|
||||
try:
|
||||
if os.path.exists(p):
|
||||
os.remove(p)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def init_runtime_state_flags(self) -> None:
|
||||
"""初始化运行时状态标志(避免在外部定义属性的警告)。
|
||||
|
||||
包括等待开奖、预约参与、跳过阶段、刚切换、高价值重访、福袋详情等状态字段。
|
||||
"""
|
||||
import time
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
self.needswitch: bool | None = None
|
||||
self._waiting_for_lottery_result: bool = False
|
||||
self._current_attending_reservation_fudai: bool = False
|
||||
self._skip_stage_diagnosis_and_find_fudai: bool = False
|
||||
self._just_switched_room: bool = False
|
||||
|
||||
self._last_high_value_revisit_ts: float = time.time()
|
||||
self._current_run_revisit_count: int = 0
|
||||
self._current_run_high_value_rooms: list[dict[str, Any]] = []
|
||||
self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = None
|
||||
self._current_fudai_future_ts: float = 0.0
|
||||
self._current_fudai_content: str = ""
|
||||
self._fudai_detail_first_read: bool = False
|
||||
self._fudai_detail_consecutive_failures: int = 0
|
||||
self._detail_closed_by_attend: bool = False
|
||||
self._lottery_result_expected_ts: float = 0.0
|
||||
self._lottery_wait_start_ts: float = 0.0
|
||||
|
||||
|
||||
def init_default_config(self) -> None:
|
||||
"""初始化所有配置字段的默认值。
|
||||
|
||||
分组:
|
||||
- 福袋筛选与基础配置
|
||||
- 福袋图标检测节流
|
||||
- 优化查找器与阈值
|
||||
- 直播间检测阈值
|
||||
- 高价值福袋 / 预约
|
||||
- 粉丝团
|
||||
- 预约回退
|
||||
- 滑动次数重置
|
||||
- 意外返回桌面自救
|
||||
- 养号配置
|
||||
"""
|
||||
# 与配置相关的核心字段(只初始化最关键的几项,其余保持默认)
|
||||
self.contains_not_want: list[str] = []
|
||||
self.contains_want: list[str] = []
|
||||
self.min_prize_value_yuan: float = 0.0
|
||||
self.min_participants: int = 0
|
||||
self.max_participants: int = 0
|
||||
self.skip_if_countdown_gt_seconds: int = 900
|
||||
self.skip_if_countdown_lt_seconds: int = 0
|
||||
self.no_fudai_watchdog_enabled: bool = False
|
||||
# 福袋图标检测节流
|
||||
self.fudai_icon_retry_delay_seconds: float = 0.6
|
||||
self.fudai_icon_max_wait_seconds: float = 5.0
|
||||
self.fudai_exit_after_misses: int = 999999
|
||||
self.enable_back_on_misses: bool = False
|
||||
self.fudai_click_wait_seconds: float = 1.0
|
||||
self.switch_room_wait_after_stage_diag_seconds: float = 7.0
|
||||
self.swipe_duration_ms: int = 600
|
||||
self.fudai_find_max_attempts: int = 10
|
||||
|
||||
# 优化查找器
|
||||
self.fudai_finder_optimized_enabled: bool = True
|
||||
self.fudai_click_verify_enabled: bool = True
|
||||
self.fudai_find_max_retries: int = 3
|
||||
self.screenshot_diagnose_min_interval_seconds: float = 8.0
|
||||
self.lucky_draw_red_ratio_threshold: float = 0.9
|
||||
self.coupon_template_match_threshold: float = 0.75
|
||||
self.attend_button_red_ratio_threshold: float = 0.25
|
||||
self.fansclub_join_red_ratio_threshold: float = 0.25
|
||||
|
||||
# 直播间检测阈值
|
||||
self.live_room_match_threshold: float = 0.8
|
||||
self.fudai_template_match_enabled: bool = False
|
||||
self.fudai_template_match_threshold: float = 0.7
|
||||
|
||||
# 高价值福袋 / 预约
|
||||
self.high_value_fudai_enabled: bool = False
|
||||
self.high_value_fudai_threshold_yuan: float = 500.0
|
||||
self.high_value_fudai_join_ahead_seconds: int = 100
|
||||
self.high_value_fudai_max_swipe_back: int = 35
|
||||
self.high_value_fudai_max_reservations: int = 3
|
||||
self.high_value_fudai_after_action: str = "continue"
|
||||
self.high_value_fudai_after_stay_seconds: int = 120
|
||||
self.high_value_fudai_poll_before_seconds: float = 10.0
|
||||
|
||||
# 高价值直播间回访
|
||||
self.high_value_room_revisit_enabled: bool = False
|
||||
self.high_value_room_revisit_only_current_run: bool = False
|
||||
self.high_value_room_revisit_min_interval_seconds: int = 300
|
||||
self.high_value_room_revisit_max_per_run: int = 5
|
||||
self.high_value_room_revisit_min_prize_value: float = 0.0
|
||||
self.high_value_room_revisit_max_age_days: int = 30
|
||||
|
||||
# 粉丝团
|
||||
self.auto_join_fansclub: bool = False
|
||||
self.fansclub_fail_action: str = "stay"
|
||||
|
||||
# 预约回退
|
||||
self.reservation_back_verify_enabled: bool = True
|
||||
self.reservation_back_swipe_delay: float = 0.6
|
||||
|
||||
# 滑动次数重置
|
||||
self.reset_after_swipes_enabled: bool = False
|
||||
self.reset_after_swipes: int = 10
|
||||
|
||||
# 意外返回桌面自救
|
||||
self.desktop_icon_x: int = 153
|
||||
self.desktop_icon_y: int = 260
|
||||
self.yanghao_fallback_live_x: int = 540
|
||||
self.yanghao_fallback_live_y: int = 2000
|
||||
self.yanghao_fallback_enter_live_x: int = 540
|
||||
self.yanghao_fallback_enter_live_y: int = 1200
|
||||
|
||||
# 养号配置
|
||||
self.yanghao_enabled: bool = True
|
||||
self.yanghao_enable_actions: bool = True
|
||||
self.yanghao_step_screenshot: bool = False
|
||||
self.yanghao_recommend_duration_seconds: int = 60
|
||||
self.yanghao_recommend_interval_seconds: int = 0
|
||||
self.yanghao_like_prob: float = 0.15
|
||||
self.yanghao_fav_prob: float = 0.05
|
||||
self.yanghao_comment_prob: float = 0.0
|
||||
self.yanghao_dwell_on_action_min_seconds: float = 5.0
|
||||
self.yanghao_dwell_on_action_max_seconds: float = 30.0
|
||||
self.yanghao_icon_roi_size: int = 180
|
||||
self.yanghao_icon_match_threshold: float = 0.70
|
||||
self.yanghao_like_roi_scale: float = 1.5
|
||||
self.yanghao_fav_roi_scale: float = 1.5
|
||||
self.yanghao_like_icon_match_threshold: float | None = None
|
||||
self.yanghao_fav_icon_match_threshold: float | None = None
|
||||
self.yanghao_like_icon_x: int = 0
|
||||
self.yanghao_like_icon_y: int = 0
|
||||
self.yanghao_fav_icon_x: int = 0
|
||||
self.yanghao_fav_icon_y: int = 0
|
||||
self.yanghao_like_roi_offset_x: int = 0
|
||||
self.yanghao_like_roi_offset_y: int = 0
|
||||
self.yanghao_fav_roi_offset_x: int = 0
|
||||
self.yanghao_fav_roi_offset_y: int = 0
|
||||
self._last_yanghao_ts: float = 0.0
|
||||
|
||||
self.yanghao_comment_btn_x: int = 0
|
||||
self.yanghao_comment_btn_y: int = 0
|
||||
self.yanghao_comment_input_x: int = 0
|
||||
self.yanghao_comment_input_y: int = 0
|
||||
self.yanghao_comment_send_x: int = 0
|
||||
self.yanghao_comment_send_y: int = 0
|
||||
self.yanghao_comment_close_x: int = 0
|
||||
self.yanghao_comment_close_y: int = 0
|
||||
self.yanghao_comment_texts: list[str] = []
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,131 @@
|
||||
"""find_fudai 辅助:循环中的调试日志
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
- log_fudai_found_and_metrics:命中福袋后记录"进入直播间→找到福袋"耗时统计 + 命中调试信息
|
||||
- log_loop_progress:每 3 次循环记录一次轻量调试信息
|
||||
- log_no_fudai_found:未找到时记录总耗时与循环次数
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
def log_fudai_found_and_metrics(
|
||||
analyser: Any,
|
||||
detected_x,
|
||||
func_start: float,
|
||||
loop: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
) -> None:
|
||||
"""命中福袋后:记录"进入直播间→找到福袋"耗时统计 + 命中调试信息。"""
|
||||
# 统计:每次"进入直播间"后首次找到福袋图标耗时
|
||||
try:
|
||||
enter_ts = float(getattr(analyser, "_enter_live_ts", 0.0) or 0.0)
|
||||
except Exception:
|
||||
enter_ts = 0.0
|
||||
try:
|
||||
already = bool(getattr(analyser, "_enter_live_fudai_logged", False))
|
||||
except Exception:
|
||||
already = False
|
||||
if (enter_ts > 0) and (not already):
|
||||
try:
|
||||
dt = float(time.time() - enter_ts)
|
||||
except Exception:
|
||||
dt = -1.0
|
||||
if dt >= 0:
|
||||
try:
|
||||
reason = str(getattr(analyser, "_enter_live_reason", "") or "")
|
||||
except Exception:
|
||||
reason = ""
|
||||
try:
|
||||
analyser._enter_live_fudai_logged = True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"性能",
|
||||
"进入直播间后找到福袋耗时",
|
||||
seconds=round(dt, 2),
|
||||
enter_reason=reason,
|
||||
fudai_x=int(detected_x or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 命中时记录调试信息
|
||||
try:
|
||||
elapsed_ms = int((time.time() - func_start) * 1000)
|
||||
scan_y_for_log = 403 * ry // 2400 + y_pianyi_val
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 命中",
|
||||
loop=loop,
|
||||
elapsed_ms=elapsed_ms,
|
||||
scan_y=scan_y_for_log,
|
||||
x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def log_loop_progress(
|
||||
analyser: Any,
|
||||
loop: int,
|
||||
func_start: float,
|
||||
pic_new,
|
||||
width: int,
|
||||
height: int,
|
||||
scan_x_start: int,
|
||||
scan_x_end: int,
|
||||
scan_y: int,
|
||||
consecutive_failures: int,
|
||||
) -> None:
|
||||
"""每 3 次循环记录一次轻量调试信息(帮助诊断为何未命中)。"""
|
||||
if loop % 3 != 0:
|
||||
return
|
||||
try:
|
||||
elapsed_ms = int((time.time() - func_start) * 1000)
|
||||
sample_color = None
|
||||
try:
|
||||
mid_x = (scan_x_start + scan_x_end) // 2
|
||||
if 0 <= scan_y < height and 0 <= mid_x < width:
|
||||
pix_sample = pic_new.load()
|
||||
sample_color = pix_sample[mid_x, scan_y]
|
||||
except Exception:
|
||||
sample_color = None
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 循环中",
|
||||
loop=loop,
|
||||
elapsed_ms=elapsed_ms,
|
||||
scan_y=scan_y,
|
||||
scan_x_start=scan_x_start,
|
||||
scan_x_end=scan_x_end,
|
||||
sample_color=(
|
||||
str(sample_color) if sample_color is not None else "None"
|
||||
),
|
||||
consecutive_failures=consecutive_failures,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def log_no_fudai_found(
|
||||
analyser: Any,
|
||||
func_start: float,
|
||||
loop: int,
|
||||
max_wait_s: float,
|
||||
retry_delay_s: float,
|
||||
) -> None:
|
||||
"""像素检测未找到时记录总耗时与循环次数。"""
|
||||
try:
|
||||
total_elapsed_ms = int((time.time() - func_start) * 1000)
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 未找到福袋图标",
|
||||
elapsed_ms=total_elapsed_ms,
|
||||
total_loops=loop,
|
||||
max_wait_s=max_wait_s,
|
||||
retry_delay_s=retry_delay_s,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,156 @@
|
||||
"""find_fudai 辅助:numpy 加速水平带扫描
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
使用 numpy 批量处理,从最优位置向左右两侧交替搜索福袋图标的特征颜色。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
def numpy_band_scan(
|
||||
analyser: Any,
|
||||
detected: bool,
|
||||
detected_x,
|
||||
pic_new,
|
||||
width: int,
|
||||
height: int,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
optimal_x_scaled: int,
|
||||
) -> Tuple[bool, Any]:
|
||||
"""numpy 加速扫描水平带,查找福袋图标的特征颜色。
|
||||
|
||||
返回更新后的 (detected, detected_x)。
|
||||
"""
|
||||
try:
|
||||
import numpy as _np
|
||||
|
||||
# 计算检测区域,考虑分辨率缩放和偏移
|
||||
# 将像素检测的扫描带左上角改为图片坐标 x=157, y=354(右下不变)
|
||||
y0 = 354 * ry // 2400 + y_pianyi_val
|
||||
x1 = max(0, 157 * rx // 1080)
|
||||
x2 = min(width, 410 * rx // 1080)
|
||||
y_top = max(0, y0 - 3)
|
||||
y_bottom = min(height, y0 + 4)
|
||||
|
||||
# 边界检查
|
||||
if x1 < x2 and y_top < y_bottom:
|
||||
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
|
||||
|
||||
# 双截图记录:保存实时操作截图(像素检测区域)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
arr = _np.array(roi)
|
||||
if arr.size > 0:
|
||||
r = arr[:, :, 0] # type: ignore[index]
|
||||
g = arr[:, :, 1] # type: ignore[index]
|
||||
b = arr[:, :, 2] # type: ignore[index]
|
||||
# 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度)
|
||||
# 原来的范围:R[193-203], G[176-193], B[237-247]
|
||||
# 优化后:适度放宽范围,但保持中心值权重
|
||||
mask_center = (r >= 190) & (r <= 206) & (g >= 173) & (g <= 196) & (b >= 234) & (b <= 250) # type: ignore[operator]
|
||||
# 速度优化:使用更宽松的预筛选,减少计算量
|
||||
mask = mask_center
|
||||
# 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判)
|
||||
cols = _np.sum(mask, axis=0)
|
||||
# 至少需要2个像素匹配(避免单个噪点误判)
|
||||
valid_cols = cols >= 2
|
||||
if valid_cols.any():
|
||||
# 优化:从最优位置开始向左右两侧搜索
|
||||
roi_width = x2 - x1
|
||||
optimal_col = optimal_x_scaled - x1 # 转换为ROI内的列索引
|
||||
optimal_col = max(0, min(optimal_col, roi_width - 1))
|
||||
|
||||
# 从最优位置开始,向左右两侧交替搜索
|
||||
found_col = None
|
||||
search_range = max(optimal_col, roi_width - optimal_col)
|
||||
|
||||
# 先检查最优位置本身
|
||||
if valid_cols[optimal_col]:
|
||||
found_col = optimal_col
|
||||
else:
|
||||
# 向左右两侧交替搜索
|
||||
for offset in range(1, search_range + 1):
|
||||
# 先检查右侧
|
||||
right_col = optimal_col + offset
|
||||
if right_col < roi_width and valid_cols[right_col]:
|
||||
found_col = right_col
|
||||
break
|
||||
# 再检查左侧
|
||||
left_col = optimal_col - offset
|
||||
if left_col >= 0 and valid_cols[left_col]:
|
||||
found_col = left_col
|
||||
break
|
||||
|
||||
# 如果没找到,回退到原来的方法(从左到右)
|
||||
if found_col is None:
|
||||
found_col = int(_np.argmax(valid_cols))
|
||||
|
||||
col_idx = found_col
|
||||
# 计算检测到的x坐标:转换为1080基准坐标,确保精度
|
||||
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
|
||||
detected = True
|
||||
|
||||
# 保存找到的位置作为下次的最优位置
|
||||
try:
|
||||
analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
|
||||
# 保存完整截图(检测成功)
|
||||
pic_rgb_full = pic_new.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=(x1, y_top, x2, y_bottom),
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": x1 + col_idx,
|
||||
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
except (ImportError, ValueError, IndexError, AttributeError):
|
||||
# numpy不可用或计算错误,回退到逐像素检测
|
||||
detected = False
|
||||
|
||||
|
||||
return detected, detected_x
|
||||
@@ -0,0 +1,207 @@
|
||||
"""find_fudai 辅助:逐像素扫描兜底
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
当 numpy 加速扫描未命中或不可用时,回退到原始逐像素检查。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
def pixel_scan_fallback(
|
||||
analyser: Any,
|
||||
detected: bool,
|
||||
detected_x,
|
||||
pic_new,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
) -> Tuple[bool, Any]:
|
||||
"""numpy 未命中或不可用时的原始逐像素检查兜底。
|
||||
|
||||
返回更新后的 (detected, detected_x)。
|
||||
"""
|
||||
if not detected:
|
||||
try:
|
||||
pix = pic_new.load()
|
||||
pic_width, pic_height = pic_new.size
|
||||
# 计算实际扫描范围,防止越界
|
||||
scan_x_start = 41 * rx // 1080
|
||||
scan_x_end = min(410 * rx // 1080, pic_width)
|
||||
scan_y = 403 * ry // 2400 + y_pianyi_val
|
||||
|
||||
# 获取最优搜索起始位置(使用历史记录或默认值)
|
||||
try:
|
||||
# 尝试获取上次找到的福袋位置(1080基准)
|
||||
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
|
||||
if (
|
||||
last_fudai_x > 0
|
||||
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
|
||||
):
|
||||
optimal_x_scaled = last_fudai_x * rx // 1080
|
||||
else:
|
||||
# 使用默认最优位置:最热门区域中心(98-240的中心,约169)
|
||||
optimal_x_scaled = 169 * rx // 1080
|
||||
except Exception:
|
||||
# 使用默认最优位置
|
||||
optimal_x_scaled = 169 * rx // 1080
|
||||
|
||||
# 确保最优位置在搜索范围内
|
||||
optimal_x_scaled = max(
|
||||
scan_x_start, min(optimal_x_scaled, scan_x_end - 1)
|
||||
)
|
||||
|
||||
# 确保y坐标在有效范围内
|
||||
if 0 <= scan_y < pic_height:
|
||||
# 精度优化:同时检查上下几行像素,提高检测准确性
|
||||
for offset_y in [0, -1, 1, -2, 2]: # 检查当前行及上下2行
|
||||
check_y = scan_y + offset_y
|
||||
if not (0 <= check_y < pic_height):
|
||||
continue
|
||||
|
||||
# 优化:从最优位置开始向左右两侧搜索
|
||||
found_x = None
|
||||
search_range = max(
|
||||
optimal_x_scaled - scan_x_start,
|
||||
scan_x_end - optimal_x_scaled,
|
||||
)
|
||||
|
||||
# 先检查最优位置本身
|
||||
try:
|
||||
px = pix[optimal_x_scaled, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = optimal_x_scaled
|
||||
except (IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# 如果最优位置没找到,向左右两侧交替搜索
|
||||
if found_x is None:
|
||||
for offset in range(1, search_range + 1):
|
||||
# 先检查右侧
|
||||
right_x = optimal_x_scaled + offset
|
||||
if right_x < scan_x_end:
|
||||
try:
|
||||
px = pix[right_x, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = right_x
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
# 再检查左侧
|
||||
left_x = optimal_x_scaled - offset
|
||||
if left_x >= scan_x_start:
|
||||
try:
|
||||
px = pix[left_x, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = left_x
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
# 如果还是没找到,回退到原来的方法(从左到右)
|
||||
if found_x is None:
|
||||
for x_scaled in range(scan_x_start, scan_x_end):
|
||||
try:
|
||||
px = pix[x_scaled, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = x_scaled
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
if found_x is not None:
|
||||
# 转换回1080基准坐标
|
||||
detected_x = int(found_x * 1080.0 / max(1, rx))
|
||||
detected = True
|
||||
|
||||
# 保存找到的位置作为下次的最优位置
|
||||
try:
|
||||
analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
detect_roi = pic_new.crop(
|
||||
(
|
||||
scan_x_start,
|
||||
max(0, scan_y - 3),
|
||||
scan_x_end,
|
||||
min(pic_height, scan_y + 4),
|
||||
)
|
||||
).convert("RGB")
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
detect_roi,
|
||||
operation_type="pixel_detect",
|
||||
)
|
||||
|
||||
# 保存完整截图(检测成功)
|
||||
pic_rgb_full = pic_new.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=(
|
||||
scan_x_start,
|
||||
max(0, scan_y - 3),
|
||||
scan_x_end,
|
||||
min(pic_height, scan_y + 4),
|
||||
),
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": found_x,
|
||||
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
break # 找到后退出offset_y循环
|
||||
|
||||
except Exception:
|
||||
# 像素检测失败,记录但不影响主流程
|
||||
pass
|
||||
|
||||
|
||||
return detected, detected_x
|
||||
@@ -0,0 +1,111 @@
|
||||
"""find_fudai 辅助:截图获取 + 验证 + 重试
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
|
||||
def capture_screenshot_for_loop(analyser: Any, screenshot_ready: bool, loop: int, pic1_path: str) -> None:
|
||||
"""每次循环开始时获取截图(除了第一次如果已提供)。
|
||||
|
||||
流程:
|
||||
1. 调用 _shot_and_diagnose 截图(diagnose=False)
|
||||
2. 失败时调用 get_screenshot 并用 PIL 验证文件完整性
|
||||
3. 如验证失败再尝试一次截图作为最后回退
|
||||
"""
|
||||
if screenshot_ready and loop == 0:
|
||||
return
|
||||
|
||||
try:
|
||||
analyser._shot_and_diagnose(
|
||||
"找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False
|
||||
)
|
||||
except Exception:
|
||||
# 如果截图失败,尝试直接调用 get_screenshot 并验证文件可读性
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
valid = False
|
||||
try:
|
||||
if (
|
||||
os.path.exists(pic1_path)
|
||||
and os.path.getsize(pic1_path) >= 1024
|
||||
):
|
||||
from PIL import Image as PILImage
|
||||
|
||||
with PILImage.open(pic1_path) as _im:
|
||||
_im.verify()
|
||||
valid = True
|
||||
except Exception:
|
||||
valid = False
|
||||
if not valid:
|
||||
# 再尝试一次直接截图作为最后回退
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def load_screenshot_with_retry(analyser: Any, pic1_path: str):
|
||||
"""读取截图,失败时重新截图后重试。返回 PIL Image 或 None。"""
|
||||
from PIL import Image
|
||||
|
||||
pic = None
|
||||
try:
|
||||
pic = Image.open(pic1_path)
|
||||
pic.load()
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
pic = Image.open(pic1_path)
|
||||
pic.load()
|
||||
except Exception:
|
||||
pass
|
||||
return pic
|
||||
|
||||
|
||||
def handle_screenshot_load_failure(
|
||||
analyser: Any,
|
||||
consecutive_failures: int,
|
||||
max_consecutive_failures: int,
|
||||
func_start: float,
|
||||
max_wait_s: float,
|
||||
retry_delay_s: float,
|
||||
) -> str:
|
||||
"""截图读取失败时的处理:
|
||||
|
||||
- 连续失败超过阈值 → 写警告日志,返回 "break"(外层 while 应 break)
|
||||
- 否则等待 retry_delay_s 秒后返回 "continue"(外层 while 应 continue)
|
||||
"""
|
||||
if consecutive_failures >= max_consecutive_failures:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 警告",
|
||||
"连续截图失败次数过多,提前退出",
|
||||
consecutive_failures=consecutive_failures,
|
||||
elapsed_s=round(time.time() - func_start, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return "break"
|
||||
|
||||
# 检查是否还有剩余时间
|
||||
elapsed = time.time() - func_start
|
||||
if elapsed < max_wait_s:
|
||||
remaining_time = max_wait_s - elapsed
|
||||
sleep_time = min(retry_delay_s, remaining_time)
|
||||
if sleep_time > 0:
|
||||
try:
|
||||
analyser.operation.delay(sleep_time)
|
||||
except Exception:
|
||||
time.sleep(sleep_time)
|
||||
return "continue"
|
||||
@@ -0,0 +1,257 @@
|
||||
"""find_fudai 辅助:模板匹配兜底(OpenCV)
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
当像素检测未命中时,使用 cv2.matchTemplate 在指定区域查找福袋图标。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
def template_match_fallback(
|
||||
analyser: Any,
|
||||
detected: bool,
|
||||
detected_x,
|
||||
pic_new,
|
||||
width: int,
|
||||
height: int,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
loop: int,
|
||||
) -> Tuple[bool, Any]:
|
||||
"""像素检测未命中时的 OpenCV 模板匹配兜底。
|
||||
|
||||
返回更新后的 (detected, detected_x)。
|
||||
"""
|
||||
# 像素检测未命中时,使用模板匹配作为兜底
|
||||
if not detected or detected_x is None:
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# 获取模板路径
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
template_path = path_config.get_assets_dir() + "/fudai.png"
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
base_dir = os.path.dirname(__file__)
|
||||
template_path = os.path.join(base_dir, "assets", "fudai.png")
|
||||
|
||||
if os.path.exists(template_path):
|
||||
# 获取匹配阈值
|
||||
try:
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
except Exception:
|
||||
template_threshold = 0.7
|
||||
|
||||
# 读取模板
|
||||
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
|
||||
if template is not None:
|
||||
# 将PIL图片转换为OpenCV格式
|
||||
pic_rgb = pic_new.convert("RGB")
|
||||
screenshot_bgr = cv2.cvtColor(
|
||||
np.array(pic_rgb), cv2.COLOR_RGB2BGR
|
||||
)
|
||||
|
||||
# 定义搜索区域:X=156-269(1080基准),Y=351-451(2400基准)
|
||||
x1 = max(0, 156 * rx // 1080)
|
||||
x2 = min(width, 269 * rx // 1080)
|
||||
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
|
||||
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
|
||||
|
||||
if x1 < x2 and y_top < y_bottom:
|
||||
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
|
||||
|
||||
if search_roi.size > 0:
|
||||
th, tw = template.shape[:2]
|
||||
rh, rw = search_roi.shape[:2]
|
||||
|
||||
# 保存搜索区域截图到 last_match.png
|
||||
try:
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_base = os.path.join(base_dir, "pic")
|
||||
match_dir = os.path.join(pic_base, "template_match")
|
||||
os.makedirs(match_dir, exist_ok=True)
|
||||
last_match_path = os.path.join(
|
||||
match_dir, "last_match.png"
|
||||
)
|
||||
|
||||
# 保存截图并检查是否成功
|
||||
save_success = cv2.imwrite(
|
||||
last_match_path, search_roi
|
||||
)
|
||||
if save_success:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 已保存搜索区域截图",
|
||||
loop=loop,
|
||||
文件路径=last_match_path,
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 保存搜索区域截图失败",
|
||||
loop=loop,
|
||||
文件路径=last_match_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as save_err:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 保存搜索区域截图异常",
|
||||
loop=loop,
|
||||
错误类型=type(save_err).__name__,
|
||||
错误信息=str(save_err),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果模板太大,缩小模板
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale > 0:
|
||||
template = cv2.resize(
|
||||
template,
|
||||
(
|
||||
max(1, int(tw * scale)),
|
||||
max(1, int(th * scale)),
|
||||
),
|
||||
)
|
||||
th, tw = template.shape[:2]
|
||||
|
||||
# 执行模板匹配
|
||||
if th <= rh and tw <= rw:
|
||||
res = cv2.matchTemplate(
|
||||
search_roi, template, cv2.TM_CCOEFF_NORMED
|
||||
)
|
||||
_min_val, max_val, _min_loc, max_loc = (
|
||||
cv2.minMaxLoc(res)
|
||||
)
|
||||
|
||||
# 双截图记录:保存实时操作截图(搜索区域)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
search_roi_pil,
|
||||
operation_type="template_match",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配兜底",
|
||||
loop=loop,
|
||||
匹配分数=round(max_val, 4),
|
||||
阈值=template_threshold,
|
||||
是否通过=bool(
|
||||
max_val >= template_threshold
|
||||
),
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
截图尺寸=f"{width}x{height}",
|
||||
分辨率=f"{rx}x{ry}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if max_val >= template_threshold:
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(
|
||||
search_roi, cv2.COLOR_BGR2RGB
|
||||
)
|
||||
)
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
search_roi_pil,
|
||||
operation_type="template_match",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 计算检测到的X坐标(1080基准)
|
||||
detected_x_in_roi = max_loc[0]
|
||||
detected_x = int(
|
||||
(x1 + detected_x_in_roi + tw // 2)
|
||||
* 1080.0
|
||||
/ max(1, rx)
|
||||
)
|
||||
detected = True
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 模板尺寸不匹配,记录调试信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-尺寸不匹配",
|
||||
loop=loop,
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 搜索区域为空,记录调试信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-搜索区域为空",
|
||||
loop=loop,
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
截图尺寸=f"{width}x{height}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 搜索区域坐标无效,记录调试信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-坐标无效",
|
||||
loop=loop,
|
||||
x1=x1,
|
||||
x2=x2,
|
||||
y_top=y_top,
|
||||
y_bottom=y_bottom,
|
||||
截图尺寸=f"{width}x{height}",
|
||||
分辨率=f"{rx}x{ry}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except (ImportError, Exception) as e:
|
||||
# OpenCV不可用或模板匹配失败,继续使用像素检测结果
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配异常",
|
||||
loop=loop,
|
||||
错误类型=type(e).__name__,
|
||||
错误信息=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
return detected, detected_x
|
||||
+53
-1548
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,496 @@
|
||||
"""attend_choujiang 分支辅助函数
|
||||
|
||||
从 douyin/fudai/core/fudai_attend.py:attend_choujiang 中提取的相对独立的早返回分支。
|
||||
每个 helper 处理一个 button_text 命中情况,返回 True/False(与原代码 return 值一致)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def resolve_attend_button_text(analyser):
|
||||
"""从 analyser 缓存解析"参与按钮文本"。
|
||||
|
||||
优先级:
|
||||
1. 已有的 _fudai_button_text + _fudai_button_status(并行 OCR 设置)
|
||||
2. 缺失则从 button_text_raw / 映射表中查找候选并推断状态
|
||||
3. 检查 OCR 时间戳:5 秒内有效 → 直接使用;超时但同房间 → 复用
|
||||
|
||||
返回 attend_button_text(若不可用则返回空字符串)。
|
||||
"""
|
||||
button_status = getattr(analyser, "_fudai_button_status", None)
|
||||
button_text = getattr(analyser, "_fudai_button_text", "")
|
||||
|
||||
try:
|
||||
current_room_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
except Exception:
|
||||
current_room_pos = 0
|
||||
try:
|
||||
cached_room_pos = int(getattr(analyser, "_fudai_button_room_pos", 0) or 0)
|
||||
except Exception:
|
||||
cached_room_pos = 0
|
||||
|
||||
# 如果并行 OCR 属性缺失或不完整,尝试从其它缓存字段复用识别结果
|
||||
if not button_text or not button_status:
|
||||
try:
|
||||
candidate = getattr(analyser, "button_text_raw", None)
|
||||
if not candidate:
|
||||
try:
|
||||
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
room_map = getattr(analyser, "_room_pos_to_title_map", {}) or {}
|
||||
if room_map and room_pos in room_map:
|
||||
info = room_map.get(room_pos) or {}
|
||||
if isinstance(info, dict):
|
||||
fudai_detail = info.get("fudai_detail") or {}
|
||||
candidate = (
|
||||
fudai_detail.get("button_text")
|
||||
or fudai_detail.get("button_text_raw")
|
||||
or None
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if candidate:
|
||||
bt = str(candidate or "").strip()
|
||||
if bt:
|
||||
# 推断按钮状态(与并行 OCR 的判断逻辑保持一致)
|
||||
if "参与成功" in bt or "等待开奖" in bt:
|
||||
bs = "已参与"
|
||||
elif "加入粉丝团" in bt or "粉丝团" in bt:
|
||||
bs = "需要加入粉丝团"
|
||||
elif "评论" in bt or "发表评论" in bt or "一键发表评论" in bt:
|
||||
bs = "需要评论"
|
||||
elif "还需看播" in bt or "开始观看" in bt:
|
||||
bs = "需要观看"
|
||||
elif "未达成" in bt:
|
||||
bs = "未达成要求"
|
||||
elif "参与抽奖" in bt or "参与" in bt:
|
||||
bs = "可以参与"
|
||||
else:
|
||||
bs = "未知状态"
|
||||
|
||||
try:
|
||||
analyser._fudai_button_status = bs
|
||||
analyser._fudai_button_text = bt
|
||||
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(
|
||||
"参与",
|
||||
"复用缓存的并行OCR文本作为按钮状态",
|
||||
button_text=(bt[:100] if bt else ""),
|
||||
button_status=bs,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
button_text = bt
|
||||
button_status = bs
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 使用并行 OCR 识别的按钮状态(如果可用且在有效期内)
|
||||
attend_button_text = ""
|
||||
try:
|
||||
button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0)
|
||||
current_time = time.time()
|
||||
if button_text and button_status and current_time - button_ocr_time < 5.0:
|
||||
attend_button_text = button_text
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"使用并行OCR识别的按钮状态",
|
||||
button_text=(
|
||||
attend_button_text[:100] if attend_button_text else ""
|
||||
),
|
||||
button_status=button_status,
|
||||
)
|
||||
elif button_text and button_status:
|
||||
same_room = (
|
||||
not current_room_pos
|
||||
or not cached_room_pos
|
||||
or current_room_pos == cached_room_pos
|
||||
)
|
||||
if same_room:
|
||||
attend_button_text = button_text
|
||||
try:
|
||||
age_ms = int(
|
||||
max(0.0, current_time - float(button_ocr_time)) * 1000
|
||||
)
|
||||
except Exception:
|
||||
age_ms = None
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"使用并行OCR缓存的按钮状态(超时复用)",
|
||||
button_text=(
|
||||
attend_button_text[:100] if attend_button_text else ""
|
||||
),
|
||||
button_status=button_status,
|
||||
age_ms=age_ms,
|
||||
room_pos=current_room_pos,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return attend_button_text
|
||||
|
||||
|
||||
def handle_simple_click(analyser, action_label: str, log_message: str) -> bool:
|
||||
"""通用"点击 543,2070 + 简单日志"分支模板,覆盖"开始观看"/"参与"等无额外副作用的点击。
|
||||
|
||||
流程:click(543, 2070) → 记录日志 → 返回 True。
|
||||
"""
|
||||
analyser.click(543, 2070)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
log_message,
|
||||
action=action_label,
|
||||
base_x=543,
|
||||
base_y=2070,
|
||||
region="(306,2030)-(780,2110)",
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def handle_attend_already_success(analyser, attend_button_text: str) -> bool:
|
||||
"""处理"参与成功/已参与"分支:记录、设置等待开奖标志、关闭详情。返回 True。"""
|
||||
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
|
||||
|
||||
future_ts = 0.0
|
||||
try:
|
||||
future_ts = float(getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0)
|
||||
except Exception:
|
||||
future_ts = 0.0
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="success",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
future_ts=int(future_ts) if future_ts else None,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._last_successful_attend_ts = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
future_ts = 0.0
|
||||
try:
|
||||
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
|
||||
if not future_ts:
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
|
||||
content, time_text, participants, copies, prize_value_yuan = (
|
||||
douyin_fudai_core.get_fudai_contain(analyser, renwu=1)
|
||||
)
|
||||
try:
|
||||
res = analyser.operation.check_countdown(time_text)
|
||||
if isinstance(res, tuple) and len(res) == 2:
|
||||
_, parsed_future = res
|
||||
future_ts = float(parsed_future or 0.0)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
if future_ts > 0:
|
||||
participated_fudai_ts = getattr(
|
||||
analyser, "_participated_fudai_future_ts", set()
|
||||
)
|
||||
if not isinstance(participated_fudai_ts, set):
|
||||
participated_fudai_ts = set()
|
||||
participated_fudai_ts.add(future_ts)
|
||||
analyser._participated_fudai_future_ts = participated_fudai_ts
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"记录已参与福袋",
|
||||
future_ts=future_ts,
|
||||
total_participated=len(participated_fudai_ts),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if future_ts > 0:
|
||||
try:
|
||||
current_time = time.time()
|
||||
remain_seconds = max(0, future_ts - current_time)
|
||||
if remain_seconds > 0:
|
||||
analyser._waiting_for_lottery_result = True
|
||||
analyser._lottery_result_expected_ts = future_ts
|
||||
analyser._lottery_wait_start_ts = current_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"参与成功,设置等待开奖标志",
|
||||
remain_seconds=int(remain_seconds),
|
||||
future_ts=int(future_ts),
|
||||
lottery_result_expected_ts=int(
|
||||
analyser._lottery_result_expected_ts
|
||||
),
|
||||
)
|
||||
else:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"参与成功,但倒计时已过期,不设置等待标志",
|
||||
future_ts=int(future_ts),
|
||||
remain_seconds=int(remain_seconds),
|
||||
)
|
||||
except Exception as e:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"设置开奖等待状态时出错",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
|
||||
try:
|
||||
analyser._detail_closed_by_attend = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser.click(500, 470)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return True
|
||||
|
||||
|
||||
def handle_activity_ended(analyser) -> bool:
|
||||
"""处理"活动已结束/福袋超时"分支:按返回键退出详情。返回 False。"""
|
||||
analyser.last_attend_fail_reason = "activity_ended"
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"活动已结束/福袋超时:按返回键退出详情",
|
||||
result="activity_ended",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason="activity_ended",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.click(500, 470)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def handle_no_parallel_ocr(analyser) -> bool:
|
||||
"""处理"并行OCR结果不可用"分支:放弃参与并关闭详情。返回 False。"""
|
||||
analyser.last_attend_fail_reason = "no_parallel_ocr_result"
|
||||
analyser._log_kv("参与", "并行OCR结果不可用,放弃参与", result="不参与")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason="no_parallel_ocr_result",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(500, 470)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return False
|
||||
|
||||
|
||||
def handle_condition_not_met(analyser) -> bool:
|
||||
"""处理"不满足参与条件"分支:放弃参与并关闭详情。返回 False。"""
|
||||
analyser.last_attend_fail_reason = "condition_not_met"
|
||||
analyser._log_kv("参与", "不满足参与条件,直接放弃", result="不满足条件")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason="condition_not_met",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(500, 470)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return False
|
||||
|
||||
|
||||
def handle_simple_fail(
|
||||
analyser, log_message: str, log_result: str, fail_reason: str
|
||||
) -> bool:
|
||||
"""通用"简单失败 + 关闭详情"模板,覆盖 watch_required / cannot_participate / watch_duration_insufficient 等。
|
||||
|
||||
流程:
|
||||
1. 设置 last_attend_fail_reason = fail_reason
|
||||
2. 记录"参与"日志(log_message + result=log_result)
|
||||
3. 记录 metric: fudai_attend / fail / reason=fail_reason
|
||||
4. click(500, 470) 关闭详情
|
||||
5. 返回 False
|
||||
"""
|
||||
try:
|
||||
analyser.last_attend_fail_reason = fail_reason
|
||||
except Exception:
|
||||
pass
|
||||
analyser._log_kv("参与", log_message, result=log_result)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason=fail_reason,
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(500, 470)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return False
|
||||
|
||||
|
||||
def handle_attend_click(analyser, mode: str) -> bool:
|
||||
"""处理"评论"或"参与抽奖"分支:点击参与按钮、记录 metric。返回 True。
|
||||
|
||||
"参与抽奖"模式下还会:
|
||||
- 设置 _skip_stage_diagnosis_and_find_fudai 标志
|
||||
- 写 debug log(开始设置等待开奖标志)
|
||||
- 设置 _waiting_for_lottery_result / _lottery_result_expected_ts
|
||||
- 写 debug log(成功设置等待开奖标志)
|
||||
"""
|
||||
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
|
||||
# 区域中心 X = 543, Y = 2070
|
||||
analyser.click(543, 2070)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖(基于截图优化坐标)",
|
||||
action="点击参与",
|
||||
mode=mode,
|
||||
base_x=543,
|
||||
base_y=2070,
|
||||
region="(306,2030)-(780,2110)",
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="attempt",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
mode=mode,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if mode != "普通":
|
||||
# 评论分支:直接返回,不设置等待开奖标志
|
||||
return True
|
||||
|
||||
# 参与抽奖分支:设置标志 + 等待开奖
|
||||
try:
|
||||
analyser._skip_stage_diagnosis_and_find_fudai = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
import json as _json
|
||||
import time as _time
|
||||
from douyin.core.path_config import get_debug_log_path
|
||||
|
||||
current_ts_debug = int(_time.time() * 1000)
|
||||
try:
|
||||
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
|
||||
f.write(
|
||||
_json.dumps(
|
||||
{
|
||||
"id": f"log_{current_ts_debug}_set_countdown_start",
|
||||
"timestamp": current_ts_debug,
|
||||
"location": "fudai_attend_branches.py:handle_attend_click",
|
||||
"message": "开始设置等待开奖标志",
|
||||
"data": {
|
||||
"future_ts": getattr(
|
||||
analyser, "_current_fudai_future_ts", 0.0
|
||||
)
|
||||
},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "countdown_debug_run1",
|
||||
"hypothesisId": "countdown_hyp2",
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
|
||||
if future_ts > 0:
|
||||
current_time = _time.time()
|
||||
remain_seconds = int(future_ts - current_time)
|
||||
if remain_seconds > 0:
|
||||
analyser._waiting_for_lottery_result = True
|
||||
analyser._lottery_result_expected_ts = future_ts
|
||||
analyser._lottery_wait_start_ts = current_time
|
||||
|
||||
try:
|
||||
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
|
||||
f.write(
|
||||
_json.dumps(
|
||||
{
|
||||
"id": f"log_{current_ts_debug}_countdown_set",
|
||||
"timestamp": current_ts_debug,
|
||||
"location": "fudai_attend_branches.py:handle_attend_click",
|
||||
"message": "成功设置等待开奖标志",
|
||||
"data": {
|
||||
"waiting_for_lottery_result": analyser._waiting_for_lottery_result,
|
||||
"lottery_result_expected_ts": analyser._lottery_result_expected_ts,
|
||||
"future_ts": future_ts,
|
||||
"current_time": current_time,
|
||||
"remain_seconds": remain_seconds,
|
||||
},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "countdown_debug_run1",
|
||||
"hypothesisId": "countdown_hyp2",
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖后,设置等待开奖标志",
|
||||
future_ts=int(future_ts),
|
||||
remain_seconds=remain_seconds,
|
||||
expected_result_ts=int(analyser._lottery_result_expected_ts),
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖后,设置等待开奖标志时出错",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测",
|
||||
)
|
||||
return True
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,420 @@
|
||||
"""attend_window 中"回退校验失败 + 映射表二次回退"块的 helper
|
||||
|
||||
从 process_reservation_attend_window 中提取的最大独立块(约 375 行深嵌套)。
|
||||
当 verify_ok=False 时执行映射表查找 → 二次回退尝试。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, List, Optional
|
||||
|
||||
from ._common import (
|
||||
ReservationItem,
|
||||
_RESERVATION_ERROR_UTILS_AVAILABLE,
|
||||
format_reservation_context,
|
||||
log_reservation_error,
|
||||
safe_write_state,
|
||||
)
|
||||
|
||||
|
||||
def handle_verify_failure_retry_via_mapping(
|
||||
analyser: Any,
|
||||
target: ReservationItem,
|
||||
reservations: List[ReservationItem],
|
||||
verify_detail: Any,
|
||||
target_room_title: str,
|
||||
target_room_title_raw: str,
|
||||
ft: float,
|
||||
poll_before: float,
|
||||
reservation_focus_until_ts_ref: List[float],
|
||||
reservation_after_action_pending_ref: List[bool],
|
||||
seek_reservation_room_callback: Callable[[ReservationItem], bool],
|
||||
write_state_callback: Callable[[], None],
|
||||
) -> bool:
|
||||
"""处理"回退校验失败 → 通过映射表二次回退"的逻辑。
|
||||
|
||||
流程:
|
||||
1. 写"回退校验失败"日志(log_reservation_error 或 _log_kv)
|
||||
2. 通过映射表查找目标和当前直播间位置
|
||||
3. 计算映射差值,决定是否重试 seek
|
||||
4. 如果重试成功 → 设置锁定期 + 待处理标志,返回 True
|
||||
5. 如果重试失败 → 清理锁定相关标志,返回 False
|
||||
|
||||
返回:
|
||||
True:第二次回退成功(调用方应直接 return True)
|
||||
False:第二次回退失败或被跳过(调用方应直接 return False)
|
||||
"""
|
||||
if not verify_ok:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
Exception("回退校验失败:回退操作成功但校验未通过"),
|
||||
format_reservation_context(
|
||||
item=target,
|
||||
reservations=reservations,
|
||||
verify_detail=verify_detail,
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
),
|
||||
level="WARNING",
|
||||
stage="回退校验",
|
||||
)
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验失败:回退操作成功但校验未通过(不再自动回退重试,避免循环卡死)",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 回退校验失败:根据映射表尝试再次回退到对应直播间,且不进入锁定期
|
||||
try:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验失败:尝试根据映射表回退到对应直播间并跳过设置锁定期",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 校验失败意味着位置信息可能不准确,尝试用映射表识别“当前/目标”位置差
|
||||
updated_target = dict(target)
|
||||
try:
|
||||
room_pos_before_map = int(
|
||||
getattr(analyser, "room_pos", 0) or 0
|
||||
)
|
||||
except Exception:
|
||||
room_pos_before_map = 0
|
||||
mapped_target_pos = None
|
||||
mapped_current_pos = None
|
||||
try:
|
||||
from douyin.reservation.douyin_reservation_handler import (
|
||||
ReservationHandler,
|
||||
)
|
||||
|
||||
mapped_target_pos = (
|
||||
ReservationHandler.find_room_pos_by_title(
|
||||
analyser,
|
||||
target_room_title,
|
||||
target_room_title_raw,
|
||||
)
|
||||
)
|
||||
if (
|
||||
mapped_target_pos is not None
|
||||
and mapped_target_pos > 0
|
||||
):
|
||||
updated_target["pos_seen"] = int(
|
||||
mapped_target_pos
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标直播间位置成功",
|
||||
old_pos=int(target.get("pos_seen", 0)),
|
||||
new_pos=int(mapped_target_pos),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标直播间位置失败,使用原有位置",
|
||||
target_pos=int(
|
||||
target.get("pos_seen", 0)
|
||||
),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 识别当前直播间标题(优先缓存,必要时重新识别)
|
||||
current_room_title = str(
|
||||
getattr(analyser, "current_room_title", "")
|
||||
or ""
|
||||
).strip()
|
||||
current_room_title_raw = str(
|
||||
getattr(analyser, "current_room_title_raw", "")
|
||||
or ""
|
||||
).strip()
|
||||
if (
|
||||
not current_room_title
|
||||
and not current_room_title_raw
|
||||
):
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
|
||||
y_pianyi_val = int(
|
||||
getattr(analyser, "y_pianyi", 0) or 0
|
||||
)
|
||||
(
|
||||
current_room_title,
|
||||
current_room_title_raw,
|
||||
) = douyin_fudai_detail.read_live_room_title_core(
|
||||
analyser, y_pianyi_val
|
||||
)
|
||||
try:
|
||||
analyser.current_room_title = (
|
||||
current_room_title
|
||||
)
|
||||
analyser.current_room_title_raw = (
|
||||
current_room_title_raw
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
current_room_title = ""
|
||||
current_room_title_raw = ""
|
||||
|
||||
if current_room_title or current_room_title_raw:
|
||||
mapped_current_pos = (
|
||||
ReservationHandler.find_room_pos_by_title(
|
||||
analyser,
|
||||
current_room_title,
|
||||
current_room_title_raw,
|
||||
)
|
||||
)
|
||||
if (
|
||||
mapped_current_pos is not None
|
||||
and mapped_current_pos > 0
|
||||
):
|
||||
try:
|
||||
old_room_pos = int(
|
||||
getattr(analyser, "room_pos", 0)
|
||||
or 0
|
||||
)
|
||||
except Exception:
|
||||
old_room_pos = 0
|
||||
try:
|
||||
analyser.room_pos = int(
|
||||
mapped_current_pos
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 通过映射表识别当前直播间位置",
|
||||
old_pos=int(old_room_pos),
|
||||
new_pos=int(mapped_current_pos),
|
||||
current_room_title=(
|
||||
current_room_title[:50]
|
||||
if current_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标/当前直播间位置时出错",
|
||||
error=str(e),
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 尝试使用回退回调根据映射表差值重新回退
|
||||
ok2 = False
|
||||
should_retry_seek = True
|
||||
mapped_pos_diff = None
|
||||
if (
|
||||
mapped_current_pos is not None
|
||||
and mapped_target_pos is not None
|
||||
):
|
||||
try:
|
||||
mapped_pos_diff = int(mapped_target_pos) - int(
|
||||
mapped_current_pos
|
||||
)
|
||||
except Exception:
|
||||
mapped_pos_diff = None
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表差值回退准备",
|
||||
mapped_current_pos=int(mapped_current_pos),
|
||||
mapped_target_pos=int(mapped_target_pos),
|
||||
mapped_pos_diff=(
|
||||
int(mapped_pos_diff)
|
||||
if mapped_pos_diff is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if mapped_pos_diff == 0:
|
||||
# 若映射表显示已在目标位置但校验失败,尝试根据回退前位置进行一次纠偏回退
|
||||
if (
|
||||
mapped_target_pos is not None
|
||||
and room_pos_before_map != mapped_target_pos
|
||||
):
|
||||
try:
|
||||
if room_pos_before_map > int(
|
||||
mapped_target_pos
|
||||
):
|
||||
updated_target[
|
||||
"_seek_direction_hint"
|
||||
] = "down"
|
||||
elif room_pos_before_map < int(
|
||||
mapped_target_pos
|
||||
):
|
||||
updated_target[
|
||||
"_seek_direction_hint"
|
||||
] = "up"
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表显示已在目标位置但校验失败,启用纠偏回退",
|
||||
mapped_current_pos=int(
|
||||
mapped_current_pos
|
||||
),
|
||||
mapped_target_pos=int(
|
||||
mapped_target_pos
|
||||
),
|
||||
room_pos_before_map=int(
|
||||
room_pos_before_map
|
||||
),
|
||||
direction_hint=updated_target.get(
|
||||
"_seek_direction_hint", ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
should_retry_seek = False
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表显示已在目标位置,但校验失败,跳过二次回退",
|
||||
mapped_current_pos=int(
|
||||
mapped_current_pos
|
||||
),
|
||||
mapped_target_pos=int(
|
||||
mapped_target_pos
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if should_retry_seek:
|
||||
try:
|
||||
if seek_reservation_room_callback:
|
||||
ok2 = bool(
|
||||
seek_reservation_room_callback(
|
||||
updated_target
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
ok2 = False
|
||||
|
||||
if ok2:
|
||||
# 第二次回退成功,设置锁定期并标记待处理
|
||||
focus_until_new = ft + max(0.0, poll_before)
|
||||
if reservation_focus_until_ts_ref:
|
||||
reservation_focus_until_ts_ref[0] = (
|
||||
focus_until_new
|
||||
)
|
||||
else:
|
||||
reservation_focus_until_ts_ref.append(
|
||||
focus_until_new
|
||||
)
|
||||
|
||||
if reservation_after_action_pending_ref:
|
||||
reservation_after_action_pending_ref[0] = True
|
||||
else:
|
||||
reservation_after_action_pending_ref.append(
|
||||
True
|
||||
)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 第二次回退成功:已根据映射表回退到目标直播间",
|
||||
target_pos=int(
|
||||
updated_target.get("pos_seen", 0)
|
||||
),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
focus_until=int(focus_until_new),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
write_state_callback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 返回 True 表示回退成功
|
||||
return True
|
||||
else:
|
||||
# 第二次回退也失败,清理锁定相关标志
|
||||
try:
|
||||
if reservation_focus_until_ts_ref:
|
||||
reservation_focus_until_ts_ref[0] = 0.0
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if reservation_after_action_pending_ref:
|
||||
reservation_after_action_pending_ref[0] = (
|
||||
False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 第二次回退失败:无法根据映射表定位到目标直播间",
|
||||
target_pos=int(
|
||||
updated_target.get("pos_seen", 0)
|
||||
),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
write_state_callback()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 不设置锁定期,回退校验失败视作本次未成功回退,返回 False 以便上层继续处理
|
||||
return False
|
||||
+87
-1199
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,383 @@
|
||||
"""阶段诊断辅助:步骤3 OCR弹窗确认 + 步骤2.5 购物红包OCR复查
|
||||
|
||||
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取的
|
||||
两个相对独立的 OCR 复查块:
|
||||
|
||||
- verify_popup_via_ocr:步骤3,所有像素检测都未命中特定阶段、但像素检测到弹窗
|
||||
背景特征(优惠券/购物红包)时,OCR 二次确认是否为弹窗。
|
||||
- verify_redpacket_outside_live_room:步骤2.5,不在直播间但检测到购物红包背景
|
||||
时,OCR 复查(支持模式0/模式1,置信度阈值)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from douyin.fudai.core.coords import (
|
||||
SHOPPING_REDPACKET_AREA,
|
||||
COUPON_PARTICIPATE_BUTTON_ALT,
|
||||
)
|
||||
|
||||
|
||||
def verify_redpacket_outside_live_room(
|
||||
analyser,
|
||||
pixel_state: dict,
|
||||
pixel_details: dict,
|
||||
enable_ocr_mode1: bool,
|
||||
max_step_time: float,
|
||||
diag_start: float,
|
||||
log_fn,
|
||||
log_summary_fn,
|
||||
preprocess_for_ocr,
|
||||
):
|
||||
"""步骤2.5:不在直播间,但像素检测到购物红包背景时的 OCR 复查。
|
||||
|
||||
Args:
|
||||
analyser: fudai_analyse 实例
|
||||
pixel_state: 像素检测结果字典
|
||||
pixel_details: 像素检测详细信息
|
||||
enable_ocr_mode1: 是否启用 OCR 模式1(关键词未命中时再跑模式1)
|
||||
max_step_time: 单步最大耗时(秒)
|
||||
diag_start: 阶段诊断起始时间戳
|
||||
log_fn: 详细日志函数(_log)
|
||||
log_summary_fn: 概要日志函数(_log_summary)
|
||||
preprocess_for_ocr: OCR 预处理函数
|
||||
|
||||
Returns:
|
||||
- (stage, reason) 二元组:检测到购物红包弹窗时
|
||||
- None:未检测到(调用方继续后续逻辑)
|
||||
"""
|
||||
if not pixel_state.get("has_redpacket_bg", False):
|
||||
return None
|
||||
|
||||
step_redpacket_ocr_start = time.time()
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
try:
|
||||
redpacket_detail = (
|
||||
pixel_details.get("has_redpacket_bg", {})
|
||||
if isinstance(pixel_details, dict)
|
||||
else {}
|
||||
)
|
||||
red_ratio = redpacket_detail.get("red_ratio")
|
||||
red_threshold = redpacket_detail.get("effective_threshold")
|
||||
except Exception:
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
|
||||
log_fn(
|
||||
"步骤2.5[购物红包OCR复查]-开始",
|
||||
说明="不在直播间也执行红包OCR复查",
|
||||
红色比例=(round(float(red_ratio), 4) if red_ratio is not None else None),
|
||||
阈值=(
|
||||
round(float(red_threshold), 4) if red_threshold is not None else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_verified = False
|
||||
ocr_confidence_info = None
|
||||
try:
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(
|
||||
*SHOPPING_REDPACKET_AREA,
|
||||
"",
|
||||
"診斷購物紅包-非直播间复查",
|
||||
)
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_fn("步骤2.5[购物红包OCR复查]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp0 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result = analyser.operation.analyse_pic_word(
|
||||
name_rp0, 0, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result
|
||||
else:
|
||||
redpacket_text = str(ocr_result or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if enable_ocr_mode1 and (
|
||||
not redpacket_text
|
||||
or not any(kw in redpacket_text for kw in redpacket_keywords)
|
||||
):
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start_1 = time.time()
|
||||
name_rp1 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result_1 = analyser.operation.analyse_pic_word(
|
||||
name_rp1, 1, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result_1, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result_1
|
||||
else:
|
||||
redpacket_text = str(ocr_result_1 or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log_fn(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=(
|
||||
redpacket_text[:50] if redpacket_text else ""
|
||||
),
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
# 检查关键词匹配或置信度阈值
|
||||
has_keyword_match = redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
has_high_confidence = (
|
||||
ocr_confidence_info
|
||||
and ocr_confidence_info.get("max_confidence", 0)
|
||||
>= analyser.shopping_redpacket_ocr_confidence_threshold
|
||||
)
|
||||
|
||||
if has_keyword_match or has_high_confidence:
|
||||
redpacket_verified = True
|
||||
log_fn(
|
||||
"步骤2.5[购物红包OCR复查]-命中",
|
||||
关键词匹配=has_keyword_match,
|
||||
高置信度匹配=has_high_confidence,
|
||||
阈值=analyser.shopping_redpacket_ocr_confidence_threshold,
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤2.5[购物红包OCR复查]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log_summary_fn(
|
||||
"阶段诊断完成(购物红包弹窗-非直播间复查)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(不在直播间)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(不在直播间)"
|
||||
else:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log_fn("步骤2.5[购物红包OCR复查]-未命中", 耗时毫秒=redpacket_elapsed)
|
||||
return None
|
||||
|
||||
|
||||
def verify_popup_via_ocr(
|
||||
analyser,
|
||||
pixel_state: dict,
|
||||
enable_ocr_mode1: bool,
|
||||
max_step_time: float,
|
||||
diag_start: float,
|
||||
max_diag_time: float,
|
||||
log_fn,
|
||||
log_summary_fn,
|
||||
preprocess_for_ocr,
|
||||
):
|
||||
"""步骤3:OCR确认弹窗。
|
||||
|
||||
Args:
|
||||
analyser: fudai_analyse 实例
|
||||
pixel_state: 像素检测结果字典
|
||||
enable_ocr_mode1: 是否启用 OCR 模式1(并行执行模式0+模式1)
|
||||
max_step_time: 单步最大耗时(秒)
|
||||
diag_start: 阶段诊断起始时间戳
|
||||
max_diag_time: 阶段诊断最大耗时(秒)
|
||||
log_fn: 详细日志函数(_log)
|
||||
log_summary_fn: 概要日志函数(_log_summary)
|
||||
preprocess_for_ocr: OCR 预处理函数
|
||||
|
||||
Returns:
|
||||
- (stage, reason) 二元组:检测到弹窗时
|
||||
- None:未检测到(调用方继续后续逻辑)
|
||||
"""
|
||||
has_suspicious_popup_pixel = pixel_state.get(
|
||||
"has_coupon_bg", False
|
||||
) or pixel_state.get("has_redpacket_bg", False)
|
||||
|
||||
if not has_suspicious_popup_pixel:
|
||||
return None
|
||||
|
||||
step_ocr_verify_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
log_fn(
|
||||
"步骤3[OCR确认弹窗]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
|
||||
)
|
||||
|
||||
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
|
||||
if pixel_state.get("has_coupon_bg", False):
|
||||
coupon_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*COUPON_PARTICIPATE_BUTTON_ALT, "", "参与按钮")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_fn("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
if enable_ocr_mode1:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode0 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part0, 0
|
||||
)
|
||||
name_part1 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode1 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part1, 1
|
||||
)
|
||||
text_mode0 = str(future_mode0.result() or "")
|
||||
text_mode1 = str(future_mode1.result() or "")
|
||||
if text_mode0 and "开心收下" in text_mode0:
|
||||
coupon_text = text_mode0
|
||||
elif text_mode1 and "开心收下" in text_mode1:
|
||||
coupon_text = text_mode1
|
||||
elif text_mode0:
|
||||
coupon_text = text_mode0
|
||||
else:
|
||||
coupon_text = text_mode1
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
else:
|
||||
pname = preprocess_for_ocr(analyser, "参与按钮")
|
||||
coupon_text = str(
|
||||
analyser.operation.analyse_pic_word(pname, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
coupon_verified = True
|
||||
except Exception as e:
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR确认弹窗]-优惠券异常",
|
||||
耗时毫秒=coupon_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if coupon_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_summary_fn(
|
||||
"阶段诊断完成(优惠券弹窗-OCR确认)",
|
||||
阶段="COUPON_POPUP",
|
||||
原因="像素检测到背景+OCR确认(开心收下)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
优惠券检测耗时毫秒=coupon_elapsed,
|
||||
)
|
||||
return "COUPON_POPUP", "OCR确认(开心收下)"
|
||||
|
||||
# 检测购物红包弹窗
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
redpacket_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_fn("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(
|
||||
analyser.operation.analyse_pic_word(name_rp2, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
):
|
||||
redpacket_verified = True
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR确认弹窗]-购物红包异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_summary_fn(
|
||||
"阶段诊断完成(购物红包弹窗-OCR确认)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(购物红包)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
|
||||
|
||||
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
|
||||
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR确认弹窗]-未匹配到弹窗",
|
||||
耗时毫秒=ocr_verify_elapsed,
|
||||
说明="OCR确认后未匹配,判定为直播间背景颜色",
|
||||
)
|
||||
|
||||
# 步骤3结束计时(OCR确认弹窗)
|
||||
step3_ocr_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_fn("步骤3[OCR确认弹窗]-完成", 总耗时毫秒=step3_ocr_elapsed)
|
||||
return None
|
||||
@@ -0,0 +1,137 @@
|
||||
"""阶段诊断辅助:步骤 1(抽奖结果弹窗)+ 步骤 1.5(购物红包弹窗)
|
||||
|
||||
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取的
|
||||
两个相邻的 priority 检测块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from douyin.fudai.core.coords import (
|
||||
SHOPPING_REDPACKET_AREA,
|
||||
)
|
||||
|
||||
|
||||
def detect_lottery_or_redpacket_popup(
|
||||
analyser,
|
||||
pixel_state: dict,
|
||||
max_step_time: float,
|
||||
diag_start: float,
|
||||
max_diag_time: float,
|
||||
log_fn,
|
||||
log_summary_fn,
|
||||
log_separator_fn,
|
||||
preprocess_for_ocr,
|
||||
):
|
||||
"""步骤 1(抽奖结果弹窗 OCR 确认)+ 步骤 1.5(购物红包弹窗 OCR 检测)。
|
||||
|
||||
返回:
|
||||
(stage, reason) 二元组:检测到弹窗时
|
||||
None:未检测到,调用方继续后续流程
|
||||
"""
|
||||
if pixel_state.get("has_lucky_draw_result", False):
|
||||
step1_start = time.time()
|
||||
log_separator_fn("步骤1:检测抽奖结果弹窗(简化)")
|
||||
try:
|
||||
from douyin.utils.douyin_helpers import HelperFunctions
|
||||
|
||||
detected = HelperFunctions.check_lottery_result_by_ocr(analyser)
|
||||
if detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
log_summary_fn(
|
||||
"阶段诊断完成(抽奖结果弹窗)",
|
||||
阶段="FUDai_RESULT",
|
||||
原因="像素检测+按钮OCR确认",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_fn("最终结果:FUDai_RESULT(抽奖结果弹窗)")
|
||||
return "FUDai_RESULT", "像素检测+按钮OCR确认"
|
||||
else:
|
||||
log_fn("步骤1:像素检测到弹窗但未识别出按钮,继续后续检测")
|
||||
except Exception as e:
|
||||
log_fn(
|
||||
"步骤1[检测抽奖结果弹窗]-简化OCR异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
# 步骤1结束计时
|
||||
step1_elapsed = (time.time() - step1_start) * 1000
|
||||
log_fn("步骤1[检测抽奖结果弹窗]-完成", 总耗时毫秒=step1_elapsed)
|
||||
|
||||
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
log_separator_fn("步骤1.5:检测购物红包弹窗")
|
||||
step_redpacket_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
log_fn(
|
||||
"步骤1.5[检测购物红包弹窗]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="像素检测到购物红包背景",
|
||||
)
|
||||
|
||||
redpacket_detected = False
|
||||
try:
|
||||
if time.time() - step_redpacket_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_fn("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_redpacket_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(
|
||||
analyser.operation.analyse_pic_word(name_rp, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
)
|
||||
|
||||
# 检查是否包含购物红包关键词
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
):
|
||||
redpacket_detected = True
|
||||
else:
|
||||
# OCR未识别到关键词,不判定为购物红包弹窗(以OCR为准)
|
||||
log_fn(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR未识别到关键词",
|
||||
说明="OCR未匹配,不判定为购物红包弹窗",
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
log_fn(
|
||||
"步骤1.5[检测购物红包弹窗]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
# OCR异常时,不判定为购物红包弹窗(以OCR为准)
|
||||
log_fn(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗",
|
||||
说明="需要OCR确认才能判定",
|
||||
)
|
||||
|
||||
if redpacket_detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
log_summary_fn(
|
||||
"阶段诊断完成(购物红包弹窗)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="检测到购物红包弹窗",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)"
|
||||
|
||||
# 步骤1.5结束计时
|
||||
step15_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
log_fn("步骤1.5[检测购物红包弹窗]-完成", 总耗时毫秒=step15_elapsed)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,231 @@
|
||||
"""阶段诊断辅助:步骤 0 第一步(并行像素检测 + 详情日志记录)
|
||||
|
||||
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取。
|
||||
基于一张截图并行采集所有像素特征(直播间图标、福袋详情页、抽奖结果、
|
||||
优惠券背景等),然后逐项记录详情日志。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Tuple
|
||||
|
||||
|
||||
def run_parallel_pixel_detection(
|
||||
analyser,
|
||||
in_live_room: bool,
|
||||
live_room_score: float,
|
||||
detection_method: str,
|
||||
pixel_threshold: float,
|
||||
step_start: float,
|
||||
log_fn,
|
||||
) -> Tuple[dict, dict, bool, float, str]:
|
||||
"""步骤 0 第一步:并行像素检测 + 详情日志记录。
|
||||
|
||||
返回 (pixel_state, pixel_details, in_live_room, live_room_score, detection_method) 五元组。
|
||||
"""
|
||||
# ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)==========
|
||||
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
|
||||
# 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测
|
||||
pixel_state = {}
|
||||
pixel_details = {}
|
||||
pixel_detection_start = time.time()
|
||||
try:
|
||||
result = analyser._read_pixel_stage_state(return_details=True)
|
||||
if isinstance(result, tuple):
|
||||
pixel_state, pixel_details = result
|
||||
else:
|
||||
pixel_state = result
|
||||
pixel_details = {}
|
||||
|
||||
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
|
||||
|
||||
# 从并行检测结果中获取直播间图标检测结果
|
||||
# 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间
|
||||
live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False))
|
||||
|
||||
# 获取检测分数(白色像素比例)
|
||||
pixel_confidence = 0.0
|
||||
if "has_live_room_pixel" in pixel_details:
|
||||
pixel_confidence = float(
|
||||
pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0
|
||||
)
|
||||
|
||||
# 如果像素检测通过(白色比例 >= 阈值),判定为在直播间
|
||||
if live_room_pixel_detected:
|
||||
in_live_room = True
|
||||
detection_method = "像素检测(多边形区域白色像素)"
|
||||
live_room_score = pixel_confidence # 白色像素比例即为置信度
|
||||
log_fn(
|
||||
"步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)",
|
||||
白色像素比例=round(pixel_confidence, 3),
|
||||
阈值=pixel_threshold,
|
||||
)
|
||||
else:
|
||||
# 像素检测未通过(直播间图标未命中)
|
||||
in_live_room = False
|
||||
detection_method = "像素检测未命中"
|
||||
log_fn(
|
||||
"步骤0[检测直播间]-像素检测未命中",
|
||||
白色像素比例=round(pixel_confidence, 3),
|
||||
阈值=pixel_threshold,
|
||||
)
|
||||
# 简单策略:若检测到抽奖结果弹窗,也可视为在直播间(减少漏报)
|
||||
try:
|
||||
if pixel_state.get("has_lucky_draw_result", False):
|
||||
# 如果并行检测里抽奖弹窗命中,则视为在直播间
|
||||
in_live_room = True
|
||||
detection_method = "抽奖结果弹窗(像素检测)"
|
||||
# 尽量使用该项的置信度作为分数(回退为0.0)
|
||||
try:
|
||||
live_room_score = float(
|
||||
pixel_details.get("has_lucky_draw_result", {}).get(
|
||||
"confidence", 0.0
|
||||
)
|
||||
or 0.0
|
||||
)
|
||||
except Exception:
|
||||
live_room_score = 0.0
|
||||
log_fn(
|
||||
"步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)",
|
||||
抽奖弹窗置信度=round(live_room_score, 4),
|
||||
)
|
||||
except Exception:
|
||||
# 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中
|
||||
pass
|
||||
|
||||
if in_live_room:
|
||||
total_elapsed = (time.time() - step_start) * 1000
|
||||
log_fn(
|
||||
"步骤0[检测直播间]-最终结果:在直播间",
|
||||
检测方法=detection_method,
|
||||
分数=live_room_score,
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
|
||||
# 记录每个检测步骤的详细信息
|
||||
for key, detail in pixel_details.items():
|
||||
step_name_map = {
|
||||
"has_coupon_bg": "优惠券背景",
|
||||
"has_redpacket_bg": "购物红包背景",
|
||||
"has_lucky_draw_result": "抽奖结果弹窗",
|
||||
"has_attend_button_red": "参与按钮红色区域",
|
||||
"has_fansclub_join_red": "粉丝团加入红色区域",
|
||||
"has_fudai_detail": "福袋详情页",
|
||||
"has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)",
|
||||
}
|
||||
step_name = step_name_map.get(key, key)
|
||||
detected = detail.get("detected", False)
|
||||
method = detail.get("method", "unknown")
|
||||
|
||||
log_fields = {
|
||||
"步骤": step_name,
|
||||
"检测结果": "命中" if detected else "未命中",
|
||||
"检测方法": method,
|
||||
}
|
||||
|
||||
# 添加耗时信息
|
||||
if "elapsed_ms" in detail:
|
||||
log_fields["耗时(ms)"] = detail["elapsed_ms"]
|
||||
|
||||
# 添加分数信息
|
||||
if "template_score" in detail and detail["template_score"] is not None:
|
||||
log_fields["分数"] = round(detail["template_score"], 4)
|
||||
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
|
||||
# 对于像素检测,添加置信度信息
|
||||
if "confidence" in detail and detail["confidence"] is not None:
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["confidence"], 4)
|
||||
log_fields["置信度"] = round(detail["confidence"], 4)
|
||||
# 如果是三部分识别,显示平均分和区域结果
|
||||
if "avg_score" in detail and detail["avg_score"] is not None:
|
||||
log_fields["平均分"] = round(detail["avg_score"], 4)
|
||||
if "detected_parts" in detail and detail["detected_parts"]:
|
||||
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
|
||||
if "best_region" in detail and detail["best_region"]:
|
||||
log_fields["最佳区域"] = detail["best_region"]
|
||||
if "region_results" in detail and detail["region_results"]:
|
||||
region_scores = detail["region_results"]
|
||||
if isinstance(region_scores, dict):
|
||||
log_fields["区域分数"] = (
|
||||
f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
|
||||
)
|
||||
# 对于像素检测,red_ratio也作为分数显示
|
||||
if "red_ratio" in detail and detail["red_ratio"] is not None:
|
||||
log_fields["红色比例"] = round(detail["red_ratio"], 4)
|
||||
# 如果还没有分数,将red_ratio作为分数显示
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["red_ratio"], 4)
|
||||
# 显示阈值(无论是否为None都显示,方便调试)
|
||||
if "effective_threshold" in detail:
|
||||
threshold_val = detail["effective_threshold"]
|
||||
if threshold_val is not None:
|
||||
log_fields["阈值"] = round(threshold_val, 4)
|
||||
else:
|
||||
log_fields["阈值"] = "未设置"
|
||||
# 对于福袋详情页,额外显示配置的阈值(用于调试)
|
||||
if key == "has_fudai_detail":
|
||||
# 显示任务数量信息(无论是否为None都显示,便于调试)
|
||||
if "task_count" in detail:
|
||||
task_count_val = detail["task_count"]
|
||||
log_fields["任务数量"] = task_count_val
|
||||
# 如果任务数量存在但检测结果为False,记录警告
|
||||
if (
|
||||
task_count_val is not None
|
||||
and task_count_val > 0
|
||||
and not detected
|
||||
):
|
||||
try:
|
||||
log_fn( # type: ignore[misc]
|
||||
"警告:检测到任务数量但 has_fudai_detail 为 False",
|
||||
任务数量=task_count_val,
|
||||
detected=detected,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
log_fields["任务数量"] = "未获取"
|
||||
try:
|
||||
configured_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None)
|
||||
or getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
log_fields["配置阈值"] = round(configured_threshold, 4)
|
||||
except Exception:
|
||||
pass
|
||||
if "reason" in detail:
|
||||
log_fields["原因"] = detail["reason"]
|
||||
if "error" in detail:
|
||||
log_fields["错误"] = detail["error"]
|
||||
|
||||
log_fn(f"并行检测-{step_name}", **log_fields)
|
||||
|
||||
log_fn(
|
||||
"像素状态(并行检测完成)",
|
||||
耗时毫秒=pixel_detection_elapsed,
|
||||
直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)),
|
||||
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
|
||||
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
|
||||
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
|
||||
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
|
||||
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
|
||||
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
|
||||
log_fn(
|
||||
"并行检测异常",
|
||||
耗时毫秒=pixel_detection_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
pixel_state = {}
|
||||
pixel_details = {}
|
||||
|
||||
# 步骤0结束计时
|
||||
step0_elapsed = (time.time() - step_start) * 1000
|
||||
log_fn("步骤0[并行检测]-完成", 总耗时毫秒=step0_elapsed)
|
||||
|
||||
return pixel_state, pixel_details, in_live_room, live_room_score, detection_method
|
||||
@@ -0,0 +1,347 @@
|
||||
"""阶段诊断辅助:步骤 1(像素检测福袋详情页)+ 步骤 1.5(OCR 检测邀你抢红包)
|
||||
|
||||
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from douyin.fudai.core.coords import (
|
||||
STAGE_RED_PACKET_OCR,
|
||||
)
|
||||
|
||||
|
||||
def detect_fudai_detail_or_invite_redpacket(
|
||||
analyser,
|
||||
pixel_state: dict,
|
||||
pixel_details: dict,
|
||||
trigger_reason: str,
|
||||
max_step_time: float,
|
||||
diag_start: float,
|
||||
max_diag_time: float,
|
||||
log_fn,
|
||||
log_summary_fn,
|
||||
log_separator_fn,
|
||||
preprocess_for_ocr,
|
||||
):
|
||||
"""步骤 1:从并行检测结果获取福袋详情页(任务数量检测)+ 步骤 1.5:OCR 检测邀你抢红包文字。
|
||||
|
||||
返回:
|
||||
(stage, reason) 二元组:检测到福袋详情页时
|
||||
None:未检测到,调用方继续后续流程
|
||||
"""
|
||||
# ========== 步骤1:像素检测福袋详情页(从并行检测结果获取)==========
|
||||
step1_fudai_start = time.time()
|
||||
# 从并行检测结果中获取福袋详情页检测结果(任务数量检测)
|
||||
# 注意:即使 has_fudai_detail 为 False,pixel_details 中可能仍然有任务数量信息
|
||||
detail_detected = bool(pixel_state.get("has_fudai_detail", False))
|
||||
detail_task_count = None
|
||||
|
||||
# 尝试从 pixel_details 中获取任务数量(无论 has_fudai_detail 是否为 True)
|
||||
if "has_fudai_detail" in pixel_details:
|
||||
detail_task_count = pixel_details["has_fudai_detail"].get("task_count")
|
||||
# 保存任务数量到 analyser 对象,供后续读取详情时使用
|
||||
# 特殊处理:如果是点击验证触发的原因,总是保存检测结果(包括0和None)
|
||||
if trigger_reason == "find_and_open_fudai_detail_click_verification":
|
||||
try:
|
||||
analyser._fudai_detail_task_count_from_stage = detail_task_count
|
||||
try:
|
||||
log_fn( # type: ignore[misc]
|
||||
"阶段检测:设置任务数量到 analyser(点击验证)",
|
||||
任务数量=detail_task_count,
|
||||
触发原因=trigger_reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 如果任务数量 > 0,标记截图可以复用,避免OCR时重复截图
|
||||
if detail_task_count is not None and detail_task_count > 0:
|
||||
analyser._screenshot_ready_for_ocr = True
|
||||
try:
|
||||
log_fn( # type: ignore[misc]
|
||||
"标记截图可复用(任务数量>0)",
|
||||
任务数量=detail_task_count,
|
||||
screenshot_ready=True,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
elif detail_task_count is not None and detail_task_count > 0:
|
||||
# 其他情况下,只有检测到有效的任务数量才保存
|
||||
try:
|
||||
analyser._fudai_detail_task_count_from_stage = detail_task_count
|
||||
try:
|
||||
log_fn( # type: ignore[misc]
|
||||
"阶段检测:设置任务数量到 analyser",
|
||||
任务数量=detail_task_count,
|
||||
触发原因=trigger_reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 如果任务数量 > 0,标记截图可以复用,避免OCR时重复截图
|
||||
if detail_task_count > 0:
|
||||
analyser._screenshot_ready_for_ocr = True
|
||||
try:
|
||||
log_fn( # type: ignore[misc]
|
||||
"标记截图可复用(任务数量>0)",
|
||||
任务数量=detail_task_count,
|
||||
screenshot_ready=True,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
pass
|
||||
try:
|
||||
log_fn( # type: ignore[misc]
|
||||
"保存任务数量到 analyser 对象",
|
||||
任务数量=detail_task_count,
|
||||
has_fudai_detail=detail_detected,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果任务数量为 None,记录警告日志
|
||||
if detail_task_count is None:
|
||||
try:
|
||||
log_fn( # type: ignore[misc]
|
||||
"警告:任务数量为 None,无法保存到 analyser 对象",
|
||||
任务数量=None,
|
||||
has_fudai_detail=detail_detected,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# pixel_details 中没有 has_fudai_detail 信息,记录警告
|
||||
try:
|
||||
log_fn( # type: ignore[misc]
|
||||
"警告:pixel_details 中没有 has_fudai_detail 信息",
|
||||
has_fudai_detail=detail_detected,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果并行检测到福袋详情页,直接返回
|
||||
if detail_detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
log_summary_fn(
|
||||
"阶段诊断完成(任务数量检测)",
|
||||
阶段="FUDai_DETAIL",
|
||||
原因="并行检测任务数量检测确认",
|
||||
任务数量=detail_task_count,
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_fn("最终结果:FUDai_DETAIL(福袋详情页)")
|
||||
return "FUDai_DETAIL", f"任务数量检测确认(任务数量={detail_task_count})"
|
||||
|
||||
# 额外检测:在指定区域检测"邀你抢红包"文字(用于检测红包/福袋详情页)
|
||||
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
|
||||
# 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间
|
||||
# 暂时禁用:将默认值改为 False
|
||||
enable_invite_redpacket_ocr = bool(
|
||||
getattr(analyser, "enable_invite_redpacket_ocr", False)
|
||||
)
|
||||
template_match_score_threshold = float(
|
||||
getattr(analyser, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4
|
||||
)
|
||||
# 获取模板匹配分数(如果存在),用于判断是否跳过OCR
|
||||
template_match_score = float(
|
||||
getattr(analyser, "_last_template_match_score", 0.0) or 0.0
|
||||
)
|
||||
should_skip_redpacket_ocr = (
|
||||
not detail_detected
|
||||
and template_match_score > 0
|
||||
and template_match_score < template_match_score_threshold
|
||||
)
|
||||
|
||||
if should_skip_redpacket_ocr:
|
||||
log_fn(
|
||||
"步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)",
|
||||
模板匹配分数=template_match_score,
|
||||
阈值=template_match_score_threshold,
|
||||
说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间",
|
||||
)
|
||||
|
||||
# 步骤1结束计时(像素检测福袋详情页)
|
||||
step1_fudai_elapsed = (time.time() - step1_fudai_start) * 1000
|
||||
log_fn("步骤1[像素检测福袋详情页]-完成", 总耗时毫秒=step1_fudai_elapsed)
|
||||
|
||||
if (
|
||||
not detail_detected
|
||||
and enable_invite_redpacket_ocr
|
||||
and not should_skip_redpacket_ocr
|
||||
):
|
||||
step_ocr_redpacket_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
# 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待
|
||||
ocr_max_step_time = float(
|
||||
getattr(analyser, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0
|
||||
)
|
||||
if remaining_time_before > ocr_max_step_time:
|
||||
try:
|
||||
log_fn(
|
||||
"步骤1.5[OCR检测邀你抢红包]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="在指定区域检测邀你抢红包文字",
|
||||
)
|
||||
|
||||
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
|
||||
cut_start = time.time()
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
# 保存完整截图并标注OCR区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from douyin.core import path_config
|
||||
import os
|
||||
from PIL import Image
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
|
||||
width, height = pic_rgb.size
|
||||
rx = int(
|
||||
getattr(analyser, "resolution_ratio_x", 1080) or 1080
|
||||
)
|
||||
ry = int(
|
||||
getattr(analyser, "resolution_ratio_y", 2400) or 2400
|
||||
)
|
||||
|
||||
x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545
|
||||
x1 = int(x1_base * width / rx)
|
||||
y1 = int((y1_base + y_pianyi) * height / ry)
|
||||
x2 = int(x2_base * width / rx)
|
||||
y2 = int((y2_base + y_pianyi) * height / ry)
|
||||
|
||||
x1 = max(0, min(x1, width - 1))
|
||||
y1 = max(0, min(y1, height - 1))
|
||||
x2 = max(0, min(x2, width - 1))
|
||||
y2 = max(0, min(y2, height - 1))
|
||||
|
||||
if x1 < x2 and y1 < y2:
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="ocr",
|
||||
picname="阶段诊断邀你抢红包区域",
|
||||
step="before_ocr",
|
||||
coords=(x1, y1, x2, y2),
|
||||
extra_info={
|
||||
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
|
||||
"y_offset": y_pianyi,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
log_fn(
|
||||
"OCR识别前保存完整截图(阶段诊断邀你抢红包区域)",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser.cut_pic(
|
||||
*STAGE_RED_PACKET_OCR, "", "阶段诊断邀你抢红包区域", y_pianyi
|
||||
)
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_fn("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_red0 = preprocess_for_ocr(
|
||||
analyser, "阶段诊断邀你抢红包区域"
|
||||
)
|
||||
ocr_text = str(
|
||||
analyser.operation.analyse_pic_word(name_red0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤1.5[OCR检测邀你抢红包]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(ocr_text),
|
||||
文本预览=ocr_text[:50] if ocr_text else "",
|
||||
)
|
||||
|
||||
# 如果模式0未识别到,尝试模式1
|
||||
enable_ocr_mode1 = bool(
|
||||
getattr(analyser, "enable_ocr_mode1", False)
|
||||
)
|
||||
if enable_ocr_mode1 and (
|
||||
not ocr_text
|
||||
or not any(
|
||||
kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气")
|
||||
)
|
||||
):
|
||||
if (
|
||||
time.time() - step_ocr_redpacket_start
|
||||
< ocr_max_step_time
|
||||
):
|
||||
name_red1 = preprocess_for_ocr(
|
||||
analyser, "阶段诊断邀你抢红包区域"
|
||||
)
|
||||
ocr_text = str(
|
||||
analyser.operation.analyse_pic_word(name_red1, 1)
|
||||
or ""
|
||||
)
|
||||
log_fn(
|
||||
"步骤1.5[OCR检测邀你抢红包]-OCR模式1",
|
||||
文本长度=len(ocr_text),
|
||||
文本预览=ocr_text[:50] if ocr_text else "",
|
||||
)
|
||||
|
||||
# 检测是否包含"邀你抢红包"相关关键词(支持变体)
|
||||
redpacket_keywords = (
|
||||
"邀你抢红包",
|
||||
"邀你抢手气红包",
|
||||
"邀你抢",
|
||||
"抢红包",
|
||||
"抢手气",
|
||||
)
|
||||
if ocr_text and any(
|
||||
kw in ocr_text for kw in redpacket_keywords
|
||||
):
|
||||
redpacket_elapsed = (
|
||||
time.time() - step_ocr_redpacket_start
|
||||
) * 1000
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
log_fn(
|
||||
"步骤1.5[OCR检测邀你抢红包]-命中",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
总耗时毫秒=total_elapsed,
|
||||
OCR文本=ocr_text[:50],
|
||||
)
|
||||
log_summary_fn(
|
||||
"阶段诊断完成(OCR检测邀你抢红包)",
|
||||
阶段="FUDai_DETAIL",
|
||||
原因="检测到邀你抢红包文字",
|
||||
OCR文本=ocr_text[:50],
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
return "FUDai_DETAIL", "OCR检测确认(邀你抢红包)"
|
||||
else:
|
||||
redpacket_elapsed = (
|
||||
time.time() - step_ocr_redpacket_start
|
||||
) * 1000
|
||||
log_fn(
|
||||
"步骤1.5[OCR检测邀你抢红包]-未命中",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
OCR文本=ocr_text[:50] if ocr_text else "",
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
|
||||
log_fn(
|
||||
"步骤1.5[OCR检测邀你抢红包]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
# 步骤1.5结束计时(OCR检测邀你抢红包)
|
||||
step15_ocr_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
|
||||
log_fn("步骤1.5[OCR检测邀你抢红包]-完成", 总耗时毫秒=step15_ocr_elapsed)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,314 @@
|
||||
"""阶段诊断辅助:步骤3 OCR 推荐页/关注列表/直播列表检测
|
||||
|
||||
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取的
|
||||
"步骤3:OCR 检测推荐页/关注列表/直播列表"独立块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from douyin.fudai.core.coords import (
|
||||
RECOMMEND_TAB,
|
||||
FOLLOW_TAB,
|
||||
LIVE_LIST_TAB,
|
||||
)
|
||||
|
||||
|
||||
def detect_tab_pages_via_ocr(
|
||||
analyser,
|
||||
enable_ocr_mode1: bool,
|
||||
max_step_time: float,
|
||||
diag_start: float,
|
||||
max_diag_time: float,
|
||||
log_fn,
|
||||
log_summary_fn,
|
||||
log_separator_fn,
|
||||
preprocess_for_ocr,
|
||||
):
|
||||
"""步骤3:OCR 检测推荐页/关注列表/直播列表标签栏。
|
||||
|
||||
返回 (stage, reason) 二元组:
|
||||
- "RECOMMEND_PAGE" / "FOLLOW_LIST" / "LIVE_LIST" / "IN_LIVE_ROOM"
|
||||
|
||||
无论命中哪个分支都返回,调用方应直接 return 该结果。
|
||||
"""
|
||||
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测)
|
||||
step_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
log_fn(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before
|
||||
)
|
||||
t_recommend = ""
|
||||
t_follow = ""
|
||||
t_list = ""
|
||||
try:
|
||||
# 检测推荐页标签栏区域(包含"推荐"、"关注"、"直播"标签)
|
||||
log_fn("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*RECOMMEND_TAB, "", "推荐页标签栏")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_fn("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name0 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(
|
||||
analyser.operation.analyse_pic_word(name0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_recommend),
|
||||
文本预览=t_recommend[:50] if t_recommend else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and (
|
||||
not t_recommend
|
||||
or (
|
||||
"推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
and "直播" not in t_recommend
|
||||
)
|
||||
)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
name1 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(
|
||||
analyser.operation.analyse_pic_word(name1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_recommend),
|
||||
文本预览=t_recommend[:50] if t_recommend else "",
|
||||
)
|
||||
elapsed_recommend = (time.time() - step_start) * 1000
|
||||
|
||||
# 如果识别到"推荐",直接返回推荐页面
|
||||
if "推荐" in t_recommend:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
seen_text = t_recommend[:50] if t_recommend else "-"
|
||||
log_fn(
|
||||
"步骤3[OCR推荐页标签栏]-命中推荐",
|
||||
耗时毫秒=elapsed_recommend,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=seen_text,
|
||||
)
|
||||
log_summary_fn(
|
||||
"阶段诊断完成",
|
||||
阶段="RECOMMEND_PAGE",
|
||||
原因=f"标题='{t_recommend}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_fn("最终结果:RECOMMEND_PAGE(推荐页)")
|
||||
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
|
||||
|
||||
# 如果识别到"关注"但没有"推荐",可能是关注列表
|
||||
if "关注" in t_recommend and "推荐" not in t_recommend:
|
||||
log_fn(
|
||||
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
|
||||
精确区域="(658,147)-(765,194)",
|
||||
)
|
||||
step_start_follow = time.time()
|
||||
try:
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*FOLLOW_TAB, "", "关注列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_fn("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
namef0 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(
|
||||
analyser.operation.analyse_pic_word(namef0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR关注列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_follow),
|
||||
文本预览=t_follow[:50] if t_follow else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and ("关注" not in t_follow)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
namef1 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(
|
||||
analyser.operation.analyse_pic_word(namef1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR关注列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_follow),
|
||||
文本预览=t_follow[:50] if t_follow else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
log_fn(
|
||||
"步骤3[OCR关注列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_follow = (time.time() - step_start_follow) * 1000
|
||||
if "关注" in t_follow:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
follow_text = t_follow[:50] if t_follow else "-"
|
||||
log_fn(
|
||||
"步骤3[OCR关注列表]-命中",
|
||||
耗时毫秒=elapsed_follow,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=follow_text,
|
||||
)
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(
|
||||
t_follow or ""
|
||||
).strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
log_summary_fn(
|
||||
"阶段诊断完成",
|
||||
阶段="FOLLOW_LIST",
|
||||
原因=f"标题='{t_follow}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_fn("最终结果:FOLLOW_LIST(关注列表)")
|
||||
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
|
||||
|
||||
# 如果识别到"正在直播"标签,判定为直播列表
|
||||
if "正在直播" in t_recommend or (
|
||||
"直播" in t_recommend
|
||||
and "推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
):
|
||||
log_fn(
|
||||
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
|
||||
精确区域="(650,145)-(800,195)",
|
||||
)
|
||||
step_start_list = time.time()
|
||||
try:
|
||||
ocr_start = time.time() # 初始化ocr_start
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*LIVE_LIST_TAB, "", "直播列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_fn("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
# else分支不需要,因为ocr_start已经在上面初始化了
|
||||
namel0 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(analyser.operation.analyse_pic_word(namel0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR直播列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and ("正在直播" not in t_list)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
namel1 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(
|
||||
analyser.operation.analyse_pic_word(namel1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log_fn(
|
||||
"步骤3[OCR直播列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
log_fn(
|
||||
"步骤3[OCR直播列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_list = (time.time() - step_start_list) * 1000
|
||||
if "正在直播" in t_list:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
list_text = t_list[:50] if t_list else "-"
|
||||
log_fn(
|
||||
"步骤3[OCR直播列表]-命中",
|
||||
耗时毫秒=elapsed_list,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=list_text,
|
||||
)
|
||||
log_summary_fn(
|
||||
"阶段诊断完成",
|
||||
阶段="LIVE_LIST",
|
||||
原因=f"标题='{t_list}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_fn("最终结果:LIVE_LIST(直播列表)")
|
||||
return "LIVE_LIST", "标题='{}'".format(t_list)
|
||||
|
||||
# 记录诊断时看到的"关注页标题"
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
if elapsed_total > max_step_time * 1000:
|
||||
log_fn(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
|
||||
耗时毫秒=elapsed_total,
|
||||
阈值毫秒=max_step_time * 1000,
|
||||
)
|
||||
else:
|
||||
log_fn(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
|
||||
耗时毫秒=elapsed_total,
|
||||
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
|
||||
)
|
||||
except Exception as e:
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
import traceback
|
||||
|
||||
log_fn(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
|
||||
耗时毫秒=elapsed_total,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
# 步骤3结束计时
|
||||
step3_elapsed = (time.time() - step_start) * 1000
|
||||
log_fn("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
|
||||
|
||||
# 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
log_summary_fn(
|
||||
"阶段诊断完成",
|
||||
阶段="IN_LIVE_ROOM",
|
||||
原因="不在直播间且未识别到特定页面,默认判定为在直播间",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_fn("最终结果:IN_LIVE_ROOM(默认直播间)")
|
||||
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
|
||||
Reference in new issue
Block a user