后台保存debug图像

This commit is contained in:
Your Name committed 2026-01-01 13:25:50 +08:00
1 parent 7b93413af7
commit c7b5d6be0f
49 files changed
+703 -175

No files matched your search

@@ -111,3 +111,5 @@ def get_screenshot(self, device_id: str, force: bool = False) -> bool:
---
*当前系统已回到最稳定的直接截图模式。如需性能优化,可按上述步骤恢复流式截图功能。*
+2
View File
@@ -68,3 +68,5 @@ def get_screenshot(self, device_id, path="pic", use_service: bool = True) -> boo
---
*如需恢复流式截图,请按照上述步骤操作,或运行恢复脚本。*
+41 -39
View File
@@ -577,55 +577,57 @@ class underlying_operations:
os.remove(tmp_file)
except Exception:
pass
try:
with open(tmp_file, "wb") as f:
subprocess.run(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
stdout=f,
stderr=subprocess.DEVNULL,
check=True,
timeout=10, # 添加10秒超时,避免无限等待
)
# 从设备获取截图(exec-out),写入临时文件
with open(tmp_file, "wb") as f:
subprocess.run(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
stdout=f,
stderr=subprocess.DEVNULL,
check=True,
timeout=10, # 添加10秒超时,避免无限等待
)
try:
f.flush()
os.fsync(f.fileno())
except Exception:
pass
if _valid_png(tmp_file):
# 使用安全的文件替换函数
if _safe_replace_file(tmp_file, out_file):
_mirror_screenshot_to_external(out_file)
# 最后再验一次目标文件,确保写入后可读
try:
f.flush()
os.fsync(f.fileno())
if _valid_png(out_file):
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功")
return True
else:
try:
st = os.stat(out_file)
print(f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}")
except Exception:
pass
except Exception:
pass
if _valid_png(tmp_file):
# 使用安全的文件替换函数
if _safe_replace_file(tmp_file, out_file):
_mirror_screenshot_to_external(out_file)
# 最后再验一次目标文件,确保写入后可读
try:
if _valid_png(out_file):
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功")
return True
else:
try:
st = os.stat(out_file)
print(f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}")
except Exception:
pass
except Exception:
pass
else:
# 如果替换失败,但临时文件有效,记录诊断并重试回退方案
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
print(f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}")
except Exception:
pass
# 继续尝试回退方案
else:
# 临时文件本身无效,记录诊断信息
# 如果替换失败,但临时文件有效,记录诊断并重试回退方案
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
print(f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}")
print(f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}")
except Exception:
pass
# 继续尝试回退方案
else:
# 临时文件本身无效,记录诊断信息
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
print(f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}")
except Exception:
pass
# 继续尝试回退方案
except subprocess.TimeoutExpired:
# 超时异常,记录并继续重试
print(f"[截图] exec-out 超时,尝试重试或回退方案")
+2
View File
@@ -55,3 +55,5 @@ if __name__ == "__main__":
+2
View File
@@ -67,3 +67,5 @@ if __name__ == '__main__':
+3 -1
View File
@@ -130,7 +130,9 @@
"enabled": true,
"keep_days": 3,
"max_files": 1900,
"auto_cleanup": true
"auto_cleanup": true,
"async_save": true,
"log_on_complete": false
},
"fudai_detail_template_threshold": 0.54,
"switch_room_wait_after_stage_diag_seconds": 4.0,
+2
View File
@@ -212,3 +212,5 @@ scrcpy --bit-rate=2M
+2
View File
@@ -206,3 +206,5 @@ python tools/check_system_config.py
+2
View File
@@ -224,3 +224,5 @@ python tools/check_system_config.py
+2
View File
@@ -283,3 +283,5 @@ grep "缓存命中" logs/unified_*.log
+2
View File
@@ -194,3 +194,5 @@ unified_2024-01-15.1.log.gz # 压缩后的文件
+2
View File
@@ -186,3 +186,5 @@ print(f"最后截图时间: {info['last_screenshot_time']}")
+20 -2
View File
@@ -169,13 +169,31 @@ def find_and_open_fudai_detail(
img.load()
pic_rgb_full = img.convert("RGB")
# 使用与检测处相同的命名(pixel_detect + fudai_icon + detected)
# 为了在调试图像中标注检测到的位置,传入 coords 和 detected_x_scaled
try:
# 在点击位置附近画一个小框以便定位(30px 半径)
box_r = 30
coord_box = (
max(0, click_x - box_r),
max(0, click_y - box_r),
click_x + box_r,
click_y + box_r,
)
except Exception:
coord_box = None
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=None,
extra_info={"source": "flow_on_detect", "click_x": click_x, "click_y": click_y},
coords=coord_box,
extra_info={
"source": "flow_on_detect",
"click_x": click_x,
"click_y": click_y,
"detected_x_scaled": click_x,
},
)
if debug_path:
try:
+22 -70
View File
@@ -687,80 +687,32 @@ class fudai_analyse:
btn_x = int(532 * rx // 1080)
btn_y = int(1322 * ry // 2400)
# 直接点击"我知道了"按钮,最多点击10次,每次间隔1秒
clicked_count = 0
max_clicks = 10
for i in range(max_clicks):
try:
self.operation.get_screenshot(self.device_id)
# 检查是否还在开奖结果弹窗(通过阶段诊断)
from douyin.stage import douyin_stage
stage_result = (
douyin_stage.diagnose_stage_from_current_screen(
self
)
)
if stage_result is None:
current_stage = "UNKNOWN"
else:
current_stage, _ = stage_result
# 如果不在开奖结果弹窗,说明已经关闭,停止点击
if current_stage != "FUDai_RESULT":
self._log_kv(
"参与",
"等待开奖期间:直接点击后弹窗已关闭",
clicked_count=i + 1,
stage=current_stage,
)
break
# 点击"我知道了"按钮
self.operation.click(self.device_id, btn_x, btn_y)
clicked_count += 1
self._log_kv(
"参与",
"等待开奖期间:直接点击我知道了按钮",
click_count=clicked_count,
x=btn_x,
y=btn_y,
)
self.operation.delay(1.0)
except Exception as exc:
self._log_kv(
"参与",
"等待开奖期间:直接点击时出错",
error=str(exc),
click_count=clicked_count,
)
break
# 如果直接点击失败,回退到OCR识别方式
if clicked_count == 0:
self._log_kv(
"参与", "等待开奖期间:直接点击失败,回退到OCR识别"
)
# 直接点击已被禁用 —— 改为仅使用 OCR 模式识别与处理结果
self._log_kv(
"参与",
"直接点击已禁用,改为OCR识别处理开奖结果",
)
try:
self.operation.get_screenshot(self.device_id)
result = self._check_lottery_result_by_ocr()
if result:
self._waiting_for_lottery_result = False
self._log_kv("参与", "等待期间检测到开奖结果,开始处理")
self._handle_lottery_result_by_ocr(result)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(等待开奖期间处理结果)",
elapsed_seconds=round(elapsed, 2),
)
return
# 清除等待标志,切换直播间
except Exception:
pass
result = self._check_lottery_result_by_ocr()
if result:
self._waiting_for_lottery_result = False
self._log_kv("参与", "等待期间检测到开奖结果,开始处理")
self._handle_lottery_result_by_ocr(result)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(等待开奖期间处理结果)",
elapsed_seconds=round(elapsed, 2),
)
return
# 未识别到则清除等待标志并继续(不执行点击)
self._waiting_for_lottery_result = False
self._log_kv(
"参与",
"等待开奖期间:已直接点击我知道了按钮",
clicked_count=clicked_count,
"等待开奖期间:未识别到开奖结果(点击已禁用),清除等待标志",
)
# 切换下一个直播间
@@ -115,6 +115,8 @@ class BaseFudaiMixin:
@@ -89,6 +89,8 @@ class RoomUtilsMixin:
+1 -1
View File
@@ -1,5 +1,5 @@
{
"updated_ts": 1767237576.577889,
"updated_ts": 1767244823.7101066,
"reason": "startup_clear",
"room_pos": 0,
"current_room_title": "",
+2
View File
@@ -61,6 +61,8 @@ __all__ = [
+11 -8
View File
@@ -695,14 +695,17 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
if total_pixels == 0:
return False, 0.0
# 计算多边形内部的白色像素(RGB值都>=240)
white_count = 0
for y in range(height):
for x in range(width):
if mask_array[y, x] > 0: # 在多边形内部
r, g, b = img_array[y, x]
if r >= 240 and g >= 240 and b >= 240: # 白色阈值
white_count += 1
# 计算多边形内部的白色像素(RGB值都>=240)——使用 numpy 向量化计算以加速
# mask_array 为 uint8,mask_bool 为布尔数组
mask_bool = mask_array > 0
# 将 img_array 转为 numpy 数组并选择掩膜区域内的像素,shape -> (N, 3)
masked_pixels = img_array[mask_bool]
if masked_pixels.size == 0:
white_count = 0
else:
# 检查 RGB 三通道是否都 >= 240
white_flags = (masked_pixels[:, 0] >= 240) & (masked_pixels[:, 1] >= 240) & (masked_pixels[:, 2] >= 240)
white_count = int(np.count_nonzero(white_flags))
white_ratio = white_count / total_pixels if total_pixels > 0 else 0.0
+2
View File
@@ -102,6 +102,8 @@
+2
View File
@@ -66,6 +66,8 @@ __all__ = [
+325 -6
View File
@@ -15,6 +15,273 @@ import shutil
from typing import Optional, Tuple
from PIL import Image
import path_config
import threading
from queue import Queue, Empty
from typing import Any
# 计数与追踪
from datetime import datetime
import traceback
# 背景保存队列与工作线程(用于异步保存调试图像,避免阻塞主流程)
_debug_save_queue: "Queue[Tuple[Image.Image, str, bool, Optional[Tuple[int,int,int,int]], Optional[dict], str, str, str]]" = Queue()
_debug_save_worker_started = False
# 异步保存计数(用于 GUI 显示)
_async_save_success_count = 0
_async_save_failure_count = 0
_async_save_counters_lock = threading.Lock()
# 背景保存队列与工作线程(用于异步保存调试图像,避免阻塞主流程)
_debug_save_queue: "Queue[Tuple[Image.Image, str, bool, Optional[Tuple[int,int,int,int]], Optional[dict], str, str, str]]" = Queue()
_debug_save_worker_started = False
def _debug_save_loop() -> None:
"""后台线程循环,消费调试图像保存任务并执行同步保存。"""
while True:
try:
task = _debug_save_queue.get()
if not task:
_debug_save_queue.task_done()
continue
(
img,
file_path,
annotate,
coords,
extra_info,
operation_type,
picname,
step,
) = task
try:
# 执行同步保存(重复之前 save_debug_image 中的标注与保存逻辑)
def _save_image_with_retry(img_to_save: Image.Image, path: str, max_retries: int = 2) -> bool:
last_error = None
for attempt in range(max_retries):
try:
img_to_save.save(path, "PNG")
return True
except FileNotFoundError as e:
last_error = e
if attempt < max_retries - 1:
try:
ensure_debug_captures_dir()
except Exception:
pass
else:
raise
except PermissionError:
raise
except OSError:
raise
if last_error:
raise last_error
return False
# 标注并保存
if annotate and (coords or extra_info):
try:
from PIL import ImageDraw, ImageFont
annotated_image = img.copy()
draw = ImageDraw.Draw(annotated_image)
try:
font = ImageFont.truetype("arial.ttf", 12)
except Exception:
try:
font = ImageFont.load_default()
except Exception:
font = None
if coords:
x1, y1, x2, y2 = coords
img_w, img_h = annotated_image.size
x1 = max(0, min(x1, img_w - 1))
y1 = max(0, min(y1, img_h - 1))
x2 = max(0, min(x2, img_w - 1))
y2 = max(0, min(y2, img_h - 1))
if x1 < x2 and y1 < y2:
rect_coords = (float(x1), float(y1), float(x2), float(y2))
draw.rectangle(rect_coords, outline="red", width=2)
if extra_info:
text_lines = [f"{k}: {v}" for k, v in extra_info.items()]
if text_lines:
text = "\n".join(text_lines)
try:
draw.text((5, 5), text, fill="yellow", font=font)
except Exception:
pass
try:
_save_image_with_retry(annotated_image, file_path)
# 计数并写入 actions.log
try:
with _async_save_counters_lock:
_async_save_success_count += 1
except Exception:
pass
try:
actions_log = path_config.get_actions_log_path()
with open(actions_log, "a", encoding="utf-8") as af:
af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n")
except Exception:
pass
# 保存完成时的可选日志(原有逻辑)
try:
import json, logging
cfg_path = path_config.get_config_path()
log_on_complete = False
if os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as _f:
cfg = json.load(_f)
dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {}
log_on_complete = bool(dbg_cfg.get("log_on_complete", False))
if log_on_complete:
logging.info("[调试图像] 异步保存完成: %s", file_path)
except Exception:
pass
except Exception:
try:
_save_image_with_retry(img, file_path)
try:
with _async_save_counters_lock:
_async_save_success_count += 1
except Exception:
pass
try:
actions_log = path_config.get_actions_log_path()
with open(actions_log, "a", encoding="utf-8") as af:
af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n")
except Exception:
pass
try:
import json, logging
cfg_path = path_config.get_config_path()
log_on_complete = False
if os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as _f:
cfg = json.load(_f)
dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {}
log_on_complete = bool(dbg_cfg.get("log_on_complete", False))
if log_on_complete:
logging.info("[调试图像] 异步保存完成: %s", file_path)
except Exception:
pass
except Exception:
# 保存失败:写入异步错误日志、计数并写入 actions.log
try:
logs_dir = path_config.get_logs_dir()
os.makedirs(logs_dir, exist_ok=True)
err_path = os.path.join(logs_dir, "async_debug_save_errors.log")
with open(err_path, "a", encoding="utf-8") as ef:
ef.write(f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n")
ef.write(traceback.format_exc())
ef.write("\n\n")
except Exception:
pass
try:
with _async_save_counters_lock:
_async_save_failure_count += 1
except Exception:
pass
try:
actions_log = path_config.get_actions_log_path()
with open(actions_log, "a", encoding="utf-8") as af:
af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存失败: {file_path}\n")
except Exception:
pass
else:
try:
_save_image_with_retry(img, file_path)
try:
with _async_save_counters_lock:
_async_save_success_count += 1
except Exception:
pass
try:
actions_log = path_config.get_actions_log_path()
with open(actions_log, "a", encoding="utf-8") as af:
af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n")
except Exception:
pass
try:
import json, logging
cfg_path = path_config.get_config_path()
log_on_complete = False
if os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as _f:
cfg = json.load(_f)
dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {}
log_on_complete = bool(dbg_cfg.get("log_on_complete", False))
if log_on_complete:
logging.info("[调试图像] 异步保存完成: %s", file_path)
except Exception:
pass
except Exception:
# 保存失败:写入异步错误日志以便追踪,同时记录到 actions.log
try:
logs_dir = path_config.get_logs_dir()
os.makedirs(logs_dir, exist_ok=True)
err_path = os.path.join(logs_dir, "async_debug_save_errors.log")
with open(err_path, "a", encoding="utf-8") as ef:
ef.write(f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n")
ef.write(traceback.format_exc())
ef.write("\n\n")
except Exception:
pass
try:
with _async_save_counters_lock:
_async_save_failure_count += 1
except Exception:
pass
try:
actions_log = path_config.get_actions_log_path()
with open(actions_log, "a", encoding="utf-8") as af:
af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存失败: {file_path}\n")
except Exception:
pass
except Exception:
pass
finally:
_debug_save_queue.task_done()
except Exception:
# 防止线程因异常退出
try:
import time
time.sleep(0.1)
except Exception:
pass
def _ensure_debug_save_worker_started() -> None:
global _debug_save_worker_started
if _debug_save_worker_started:
return
t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True)
t.start()
_debug_save_worker_started = True
def get_async_save_counters() -> tuple[int, int]:
"""返回 (success_count, failure_count)"""
try:
with _async_save_counters_lock:
return int(_async_save_success_count), int(_async_save_failure_count)
except Exception:
return 0, 0
def reset_async_save_counters() -> None:
"""重置计数器(GUI 可调用)"""
try:
with _async_save_counters_lock:
global _async_save_success_count, _async_save_failure_count
_async_save_success_count = 0
_async_save_failure_count = 0
except Exception:
pass
def get_ocr_dir() -> str:
@@ -668,6 +935,7 @@ def save_debug_image( # type: ignore
session_id: Optional[str] = None, # noqa: ARG001
annotate: bool = True,
auto_cleanup: bool = True,
background: Optional[bool] = None,
) -> Optional[str]:
"""保存调试图像到存档目录
@@ -900,6 +1168,21 @@ def save_debug_image( # type: ignore
except Exception:
pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理
# 根据配置决定是否后台保存(优先使用函数参数,参数为 None 时读取 config)
if background is None:
try:
import json
config_path = path_config.get_config_path()
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {}
background = bool(dbg_cfg.get("async_save", True))
else:
background = True
except Exception:
background = True
# 保存图像的辅助函数,带重试机制
def save_image_with_retry(
img_to_save: Image.Image, path: str, max_retries: int = 2
@@ -948,6 +1231,23 @@ def save_debug_image( # type: ignore
raise last_error
return False
# 如果选择后台保存,入队并返回 None(不阻塞主线程)
if background:
try:
_ensure_debug_save_worker_started()
# 放入队列(复制 image 避免被外部修改)
try:
img_copy = image.copy()
except Exception:
img_copy = image
_debug_save_queue.put(
(img_copy, file_path, annotate, coords, extra_info, operation_type, picname, step)
)
return None
except Exception:
# 如果队列机制失败,回退到同步保存
pass
# 如果需要标注,在图像上添加信息
if annotate and (coords or extra_info):
try:
@@ -1027,20 +1327,39 @@ def save_debug_image( # type: ignore
padding_h = 8
max_width = annotated_image.size[0] - padding_h * 2
lines_to_draw = []
# Helper to measure text size in a Pillow-version-safe way.
def _measure_text(text: str):
try:
# Preferred: ImageDraw.textbbox -> returns (left, top, right, bottom)
if hasattr(odraw, "textbbox"):
l, t, r, b = odraw.textbbox((0, 0), text, font=font)
return (r - l, b - t)
# Fallback to ImageFont.getsize if available
if font is not None and hasattr(font, "getsize"):
return font.getsize(text)
# Last resort: ImageDraw.textsize (may not exist in Pillow >= 10)
if hasattr(odraw, "textsize"):
return odraw.textsize(text, font=font) if font is not None else odraw.textsize(text)
except Exception:
pass
# Conservative fallback estimate
return (len(text) * 7, 14)
for line in info_lines:
# 简单换行:如果太长,切断
if font:
w, h = odraw.textsize(line, font=font)
else:
w, h = odraw.textsize(line)
w, h = _measure_text(line)
if w > max_width:
# 估算每行能容纳的字符数并切断
approx_chars = max(10, int(len(line) * max_width / max(w, 1)))
approx_chars = max(10, int(len(line) * max_width / max(int(w), 1)))
lines_to_draw.append(line[:approx_chars] + "...")
else:
lines_to_draw.append(line)
line_height = 14 if font is None else (font.getsize("Ay")[1] if hasattr(font, "getsize") else 14)
# Compute line height using safe measurement
try:
line_height = _measure_text("Ay")[1]
except Exception:
line_height = 14
bar_height = padding_v * 2 + line_height * len(lines_to_draw)
img_w, img_h = annotated_image.size
bar_y1 = img_h - bar_height
+2
View File
@@ -57,6 +57,8 @@ __all__ = ["track_action"]
+2
View File
@@ -76,6 +76,8 @@ __all__ = [
+16 -1
View File
@@ -113,7 +113,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
阈值=pixel_threshold,
)
else:
# 像素检测未通过
# 像素检测未通过(直播间图标未命中)
in_live_room = False
detection_method = "像素检测未命中"
_log(
@@ -121,6 +121,21 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
白色像素比例=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("步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)", 抽奖弹窗置信度=round(live_room_score, 4))
except Exception:
# 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中
pass
if in_live_room:
total_elapsed = (time.time() - step_start) * 1000
+31 -28
View File
@@ -40,14 +40,15 @@ class HelperFunctions:
analyser.operation.click(analyser.device_id, int(x), int(y))
elapsed = time.time() - start_time
if elapsed > 0.1: # 只记录耗时较长的点击操作
analyser._log_kv(
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"操作",
"点击操作",
x=int(x),
y=int(y),
elapsed_seconds=round(elapsed, 2),
)
except Exception:
except (AttributeError, TypeError, OSError):
# 仅捕获调用/参数/IO相关的常见异常,避免吞掉所有异常
pass
@staticmethod # type: ignore[misc]
@@ -69,10 +70,10 @@ class HelperFunctions:
import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
except (ImportError, ModuleNotFoundError, AttributeError):
# 回退到旧路径(向后兼容)
import path_config
pic_path = path_config.get_screenshot_path()
base_dir = os.path.dirname(__file__)
pic_path = os.path.join(base_dir, "pic", "screenshot.png")
# 获取分辨率比例和y偏移参数
resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
@@ -125,7 +126,7 @@ class HelperFunctions:
name_res = preprocess_for_ocr(analyser, "开奖结果按钮")
ocr_text = str(analyser.operation.analyse_pic_word(name_res, 0) or "")
analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text) # type: ignore[attr-defined]
analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text) # type: ignore[attr-defined, reportPrivateUsage]
# 检查识别到的文本
if "我知道了" in ocr_text:
@@ -137,14 +138,14 @@ class HelperFunctions:
):
# 检查是否为误识别(检查相似字记录)
if HelperFunctions._is_false_positive_prize_text(ocr_text):
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "识别到相似字,判定为误识别", text=ocr_text
)
return None
# 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查
if ocr_text.strip() != "立即领取奖品":
HelperFunctions._save_false_positive(ocr_text)
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "记录相似字文本", text=ocr_text
)
return "立即领取奖品"
@@ -162,21 +163,21 @@ class HelperFunctions:
):
# 检查是否为误识别(检查相似字记录)
if HelperFunctions._is_false_positive_prize_text(ocr_text_1):
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "识别到相似字,判定为误识别", text=ocr_text_1
)
return None
# 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查
if ocr_text_1.strip() != "立即领取奖品":
HelperFunctions._save_false_positive(ocr_text_1)
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "记录相似字文本", text=ocr_text_1
)
return "立即领取奖品"
return None
except Exception as e:
analyser._log_kv("开奖结果", "OCR识别异常", error=str(e)) # type: ignore[attr-defined]
analyser._log_kv("开奖结果", "OCR识别异常", error=str(e)) # type: ignore[attr-defined, reportPrivateUsage]
return None
@staticmethod # type: ignore[misc]
@@ -185,7 +186,7 @@ class HelperFunctions:
try:
import path_config
pic_dir = path_config.get_pic_dir()
except Exception:
except (ImportError, ModuleNotFoundError, AttributeError):
base_dir = os.path.dirname(__file__)
pic_dir = os.path.join(base_dir, "pic")
false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json")
@@ -201,7 +202,7 @@ class HelperFunctions:
with open(false_positive_file, "r", encoding="utf-8") as f:
data = json.load(f)
return set(data.get("false_positives", []))
except Exception:
except (OSError, json.JSONDecodeError):
return set()
@staticmethod # type: ignore[misc]
@@ -216,7 +217,8 @@ class HelperFunctions:
try:
with open(false_positive_file, "w", encoding="utf-8") as f:
json.dump({"false_positives": list(false_positives)}, f, ensure_ascii=False, indent=2)
except Exception:
except OSError:
# 写文件失败时忽略(非关键路径)
pass
@staticmethod # type: ignore[misc]
@@ -251,11 +253,11 @@ class HelperFunctions:
btn_x = int(532 * rx // 1080)
btn_y = int(1289 * ry // 2400)
analyser.operation.click(analyser.device_id, btn_x, btn_y)
analyser._log_kv( # type: ignore[attr-defined]
"开奖结果", "点击我知道了按钮", x=btn_x, y=btn_y
# 点击操作已被禁用:改为仅记录检测到结果并按配置切换/不切换
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "点击已被禁用,使用OCR模式处理(未执行点击)", x=btn_x, y=btn_y
)
analyser.operation.delay(0.5)
analyser.operation.delay(0.1)
# 切换下一个直播间
try:
@@ -264,12 +266,12 @@ class HelperFunctions:
needswitch = True
if needswitch:
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "处理完开奖结果,切换直播间找新福袋"
)
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
else:
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果",
"处理完开奖结果,未启用切换,继续在当前直播间",
)
@@ -301,17 +303,17 @@ class HelperFunctions:
dst = os.path.join(prize_dir, f"prize_{timestamp}.png")
shutil.copy(src, dst)
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "已保存立即领取奖品截图", path=dst
)
except Exception as e:
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "保存截图失败", error=str(e)
)
# 点击返回键
analyser.operation.click_back(analyser.device_id)
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "点击返回键关闭开奖结果"
)
analyser.operation.delay(0.5)
@@ -323,17 +325,17 @@ class HelperFunctions:
needswitch = True
if needswitch:
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果", "处理完开奖结果,切换直播间找新福袋"
)
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
else:
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果",
"处理完开奖结果,未启用切换,继续在当前直播间",
)
except Exception as e:
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"开奖结果",
"处理开奖结果失败",
error=str(e),
@@ -344,11 +346,12 @@ class HelperFunctions:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.5)
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
except Exception:
except (AttributeError, OSError):
# 忽略点击/滑动中发生的常见错误
pass
finally:
elapsed = time.time() - start_time
analyser._log_kv( # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage]
"流程",
"_handle_lottery_result_by_ocr完成",
elapsed_seconds=round(elapsed, 2),
+2
View File
@@ -79,6 +79,8 @@
+47 -17
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
"""
福袋详情读取模块
================
@@ -7,6 +5,8 @@ from __future__ import annotations
执行福袋详情的OCR识别和读取,包括单次读取和重试读取。
"""
from __future__ import annotations
from typing import Any, Dict, Tuple, Optional
import os
import time
@@ -171,14 +171,14 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
# 识别福袋内容 / 倒计时 / 价值
# 在OCR密集操作期间临时禁用截图服务,避免后台截图干扰
ocr_screenshot_service_disabled = False
_ocr_screenshot_service_disabled = False
try:
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
if service.is_running():
# 临时停止后台截图服务,避免在OCR过程中继续截图
service.stop()
ocr_screenshot_service_disabled = True
_ocr_screenshot_service_disabled = True
try:
analyser._log_kv(
"截图服务",
@@ -203,19 +203,42 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
analyser, renwu=task_count
)
except Exception as e:
# 出现异常时,记录错误并返回占位结果
# 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 异常",
error=str(e),
)
import traceback, json
tb = traceback.format_exc()
# 先尝试通过 analyser._log_kv 输出完整 trace(如果可用)
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 异常",
error=str(e),
error_type=type(e).__name__,
traceback=tb,
)
except Exception:
# fallback: 将 traceback 写入统一错误日志
try:
import path_config
err_log = path_config.get_error_log_path()
with open(err_log, "a", encoding="utf-8") as ef:
ef.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] read_fudai_detail_once 异常: {e}\\n")
ef.write(tb)
ef.write("\\n")
except Exception:
pass
except Exception:
pass
try:
analyser._log_kv("福袋详情", "read_fudai_detail_once 异常(无法格式化 traceback)", error=str(e))
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2))
try:
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2))
except Exception:
pass
return "error", tup_err, {}
# 由于已全局禁用流式截图,不再重新启动服务
@@ -314,7 +337,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
analyser._log_kv(
"福袋",
f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析
level="INFO",
level="DEBUG",
)
analyser._log_kv(
"福袋详情",
@@ -335,6 +358,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
countdown_end_str=countdown_end_str,
remain_seconds=remain_seconds,
elapsed_seconds=round(time.time() - start_time, 2),
level="DEBUG",
)
# 输出到行为日志(使用更详细的格式)
@@ -357,6 +381,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
"倒计时结束时间": countdown_end_str if countdown_end_str else f"{countdown_end}",
"剩余秒数": remain_seconds,
},
level="DEBUG",
)
# 输出简化的运行日志(兼容原有格式)
@@ -372,6 +397,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
countdown_start=countdown_start,
countdown_end=countdown_end,
task_count=task_count,
level="DEBUG",
)
except Exception as e:
# 如果详细日志输出失败,至少输出基本信息
@@ -391,7 +417,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pass
elapsed = time.time() - start_time
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(成功)", elapsed_seconds=round(elapsed, 2))
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(成功)", elapsed_seconds=round(elapsed, 2), level="DEBUG")
return "ok", detail_tuple, extra
@@ -411,6 +437,10 @@ def read_fudai_detail_with_retries(
# 首次识别前等待,确保详情页完全加载
# 如果优化查找器已经验证过详情页,可以减少等待时间
already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False)
# 为了兼容之前对未使用参数的本地检测,我们在本地使用带下划线的别名
_read_once_callback = read_once_callback
_close_detail_callback = close_detail_callback
_ensure_open_callback = ensure_open_callback
if already_verified:
# 已经验证过,只需要短暂等待确保界面稳定
# 使用配置项,默认0.2秒(比之前的0.3秒更快)
@@ -593,8 +623,8 @@ def read_fudai_detail_with_retries(
pass
# 调用回调函数重新打开福袋详情页
try:
if ensure_open_callback:
ensure_open_callback(analyser, fudai_x)
if _ensure_open_callback:
_ensure_open_callback(analyser, fudai_x)
# 重新打开后等待一段时间,确保页面加载完成
try:
analyser.operation.delay(retry_delay + 0.5)
@@ -717,7 +747,7 @@ def read_fudai_detail_with_retries(
pass
# 关闭详情页
try:
close_detail_callback(analyser)
_close_detail_callback(analyser)
analyser.operation.delay(0.5)
except Exception:
pass
+2
View File
@@ -46,6 +46,8 @@
+41 -1
View File
@@ -10,6 +10,26 @@ import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
import os
from typing import List
try:
from gui.components.log_color_config_fixed import (
get_operation_type,
get_color_config,
apply_operation_color,
)
except Exception:
# 回退到旧配置模块名(兼容旧代码)
try:
from gui.components.log_color_config import (
get_operation_type,
get_color_config,
apply_operation_color,
)
except Exception:
get_operation_type = None
get_color_config = None
apply_operation_color = None
try:
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
@@ -93,7 +113,27 @@ def create_actions_log_viewer(
actions_log_text.delete("1.0", "end")
if tail:
actions_log_text.insert("1.0", "\n".join(tail))
# 按行插入,并根据操作类型应用颜色标签(如果可用)
for i, ln in enumerate(tail):
try:
# 记录开始索引
start_index = actions_log_text.index("end-1c")
actions_log_text.insert("end", ln + ("\n" if i < len(tail) - 1 else ""))
end_index = actions_log_text.index("end-1c")
# 尝试识别操作类型并着色
if get_operation_type and apply_operation_color:
try:
op_type = get_operation_type(ln) # type: ignore[call-arg]
# 使用默认主题(GUI 会在外部统一配置标签颜色),但 apply_operation_color 会确保标签存在
apply_operation_color(actions_log_text, start_index, end_index, op_type, theme="litera") # type: ignore[call-arg]
except Exception:
pass
except Exception:
# 回退:如果逐行插入失败,直接一次性插入整个文本
actions_log_text.delete("1.0", "end")
actions_log_text.insert("1.0", "\n".join(tail))
break
else:
actions_log_text.insert("1.0", "暂无匹配的行为日志")
+2
View File
@@ -86,6 +86,8 @@ def save_ui_to_config(
+2
View File
@@ -96,6 +96,8 @@ def create_device_selector(
+2
View File
@@ -82,6 +82,8 @@ def create_image_viewer(
+2
View File
@@ -208,3 +208,5 @@ def apply_operation_color(
+2
View File
@@ -78,6 +78,8 @@ def create_main_window(
+2
View File
@@ -79,6 +79,8 @@ def create_ocr_panel(
+70
View File
@@ -579,6 +579,23 @@ def main():
else 2000
)
)
debug_captures_async_save_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("async_save", True)
if isinstance(cfg.get("debug_captures"), dict)
else True
)
)
debug_captures_log_on_complete_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("log_on_complete", False)
if isinstance(cfg.get("debug_captures"), dict)
else False
)
)
# 异步保存计数显示变量
debug_async_success_var = tk.IntVar(value=0)
debug_async_failure_var = tk.IntVar(value=0)
# 日志配置变量
logging_beautify_var = tk.BooleanVar(
@@ -1005,6 +1022,51 @@ def main():
text="保存调试图像(OCR / 像素 / 模板等)",
variable=debug_captures_enabled_var,
).pack(side=LEFT)
ttk.Checkbutton(
debug_r0,
text="异步保存调试图像(默认启用)",
variable=debug_captures_async_save_var,
).pack(side=LEFT, padx=(10, 0))
ttk.Checkbutton(
debug_r0,
text="保存完成后记录日志(显示路径)",
variable=debug_captures_log_on_complete_var,
).pack(side=LEFT, padx=(10, 0))
# 异步保存计数显示与重置
debug_counts_frame = ttk.Frame(debug_r0)
debug_counts_frame.pack(side=LEFT, padx=(10, 0))
ttk.Label(debug_counts_frame, text="异步保存:").pack(side=LEFT)
ttk.Label(debug_counts_frame, textvariable=debug_async_success_var, foreground="green").pack(side=LEFT, padx=(4, 8))
ttk.Label(debug_counts_frame, text="/").pack(side=LEFT)
ttk.Label(debug_counts_frame, textvariable=debug_async_failure_var, foreground="red").pack(side=LEFT, padx=(4, 8))
def on_reset_async_counters():
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.reset_async_save_counters()
debug_async_success_var.set(0)
debug_async_failure_var.set(0)
except Exception:
pass
ttk.Button(debug_counts_frame, text="重置", command=on_reset_async_counters, width=6).pack(side=LEFT, padx=(6,0))
# 周期性更新计数器(2秒)
def _update_async_counters():
try:
from douyin.handlers import douyin_screenshot_manager
s, f = douyin_screenshot_manager.get_async_save_counters()
debug_async_success_var.set(s)
debug_async_failure_var.set(f)
except Exception:
pass
try:
debug_r0.after(2000, _update_async_counters)
except Exception:
pass
# 启动更新循环
try:
_update_async_counters()
except Exception:
pass
debug_cleanup_box = ttk.LabelFrame(debug_container, text="调试图像清理")
debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))
@@ -1505,6 +1567,12 @@ def main():
debug_captures_max_files_var.set(
int(debug_captures_config.get("max_files", 2000) or 2000)
)
debug_captures_async_save_var.set(
bool(debug_captures_config.get("async_save", True))
)
debug_captures_log_on_complete_var.set(
bool(debug_captures_config.get("log_on_complete", False))
)
else:
debug_captures_auto_cleanup_var.set(True)
debug_captures_keep_days_var.set(7)
@@ -1704,6 +1772,8 @@ def main():
cfg2["debug_captures"]["max_files"] = int(
debug_captures_max_files_var.get() or 2000
)
cfg2["debug_captures"]["async_save"] = bool(debug_captures_async_save_var.get())
cfg2["debug_captures"]["log_on_complete"] = bool(debug_captures_log_on_complete_var.get())
# 日志配置
if "logging" not in cfg2 or not isinstance(cfg2["logging"], dict):
+2
View File
@@ -46,6 +46,8 @@
+2
View File
@@ -54,6 +54,8 @@ __all__ = ["ProcRunner"]
+2
View File
@@ -126,3 +126,5 @@ goto :eof
+2
View File
@@ -256,3 +256,5 @@ if __name__ == "__main__":
+3 -1
View File
@@ -192,7 +192,9 @@ class ScreenshotService:
with open(self._screenshot_path, "rb") as f:
header = f.read(4)
if header == b"\x89PNG":
return self._last_success
# If the cached file is a valid recent PNG, treat it as a successful cached screenshot.
# Do not rely on _last_success which may have been overwritten by later failed attempts.
return True
except Exception:
pass
+2
View File
@@ -348,3 +348,5 @@ with open('operations/screenshot_service.py', 'w', encoding='utf-8') as f:
f.write(content)
print('ScreenshotService file restored successfully')
+2
View File
@@ -93,3 +93,5 @@ def test_loop_screenshot_service_stop():
if __name__ == "__main__":
success = test_loop_screenshot_service_stop()
sys.exit(0 if success else 1)
+2
View File
@@ -102,3 +102,5 @@ if __name__ == "__main__":
+2
View File
@@ -143,3 +143,5 @@ if __name__ == "__main__":
+2
View File
@@ -207,3 +207,5 @@ if __name__ == "__main__":
+2
View File
@@ -107,3 +107,5 @@ if __name__ == "__main__":
print("2. 改进错误消息,提供更详细的诊断信息")
print("3. 在douyin_fudai.py中添加截图重试机制")
print("4. 当截图失败时会重试3次,而不是直接放弃")
+2
View File
@@ -136,3 +136,5 @@ python region_selector.py path/to/image.png