feat: 添加工具以查找重复的异常处理,增强代码质量检查;新增验证 GUI 回退方式的自检脚本

This commit is contained in:
Your Name committed 2026-01-05 21:32:50 +08:00
1 parent 982357927e
commit 43e39f4db6
16 files changed
+472 -180

No files matched your search

+53 -45
View File
@@ -14,10 +14,13 @@ os.environ.setdefault("OMP_NUM_THREADS", "1")
warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning)
warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning)
import time
from PIL import Image, ImageFilter
from PIL import UnidentifiedImageError
import numpy as np
import time as time_module
# alias for existing code that uses `time` name
time = time_module
from PIL import Image, ImageFilter # type: ignore[import]
from PIL import UnidentifiedImageError # type: ignore[import]
import numpy as np # type: ignore[import]
import logging
import re
import random
@@ -27,7 +30,6 @@ import contextlib
import base64
from typing import Tuple, Optional, Any
import time as time_module
# Pillow 版本兼容:使用 Image.Resampling 或回退到 Image 常量
try:
@@ -495,7 +497,7 @@ class underlying_operations:
返回:
是否成功获取截图
"""
start_ts = time.time()
start_ts = time_module.time()
# 如果启用服务模式,使用后台截图服务;若服务不可用或返回 False,则回退到直接截图
if use_service:
try:
@@ -521,7 +523,7 @@ class underlying_operations:
try:
service_result = service.get_screenshot(device_id, force=False)
if service_result:
dur = (time.time() - start_ts) * 1000.0
dur = (time_module.time() - start_ts) * 1000.0
logging.info(
"[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id
)
@@ -555,7 +557,7 @@ class underlying_operations:
# 原有的直接截图逻辑(保持向后兼容),测量其耗时
result = self._get_screenshot_direct(device_id, path)
dur = (time.time() - start_ts) * 1000.0
dur = (time_module.time() - start_ts) * 1000.0
logging.info(
"[截图] 总耗时(ms)=%.1f device=%s use_service=%s result=%s",
dur,
@@ -1405,9 +1407,9 @@ class underlying_operations:
if change_color in (1, 2):
img = img.convert("L")
if change_color == 1:
img = img.point(lambda x: 0 if x < 128 else 255)
img = img.point(lambda x: 0 if int(x) < 128 else 255)
else:
img = img.point(lambda x: 0 if x < 180 else 255)
img = img.point(lambda x: 0 if int(x) < 180 else 255)
img = img.convert("RGB")
else:
img = img.convert("RGB")
@@ -1680,18 +1682,21 @@ class underlying_operations:
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
try:
logging.info(
f"[OCR置信度] {picname}: "
f"平均={ocr_confidence_info.get('avg_confidence', 0.0):.4f}, "
f"最小={ocr_confidence_info.get('min_confidence', 0.0):.4f}, "
f"最大={ocr_confidence_info.get('max_confidence', 0.0):.4f}, "
f"项目数={ocr_confidence_info.get('item_count', 0)}"
"[OCR置信度] %s: 平均=%.4f, 最小=%.4f, 最大=%.4f, 项目数=%d",
picname,
ocr_confidence_info.get("avg_confidence", 0.0),
ocr_confidence_info.get("min_confidence", 0.0),
ocr_confidence_info.get("max_confidence", 0.0),
int(ocr_confidence_info.get("item_count", 0) or 0),
)
except Exception:
pass
if debug_path:
try:
logging.info(
f"[调试图像] OCR结果保存: {debug_path}, 文本: {ocr_result_preview}"
"[调试图像] OCR结果保存: %s, 文本: %s",
debug_path,
ocr_result_preview,
)
except Exception:
pass
@@ -1782,9 +1787,9 @@ class underlying_operations:
# 数字识别更适合使用二值化处理
img = img.convert("L")
if change_color == 1:
img = img.point(lambda x: 0 if x < 128 else 255)
img = img.point(lambda x: 0 if int(x) < 128 else 255)
elif change_color == 2:
img = img.point(lambda x: 0 if x < 180 else 255)
img = img.point(lambda x: 0 if int(x) < 180 else 255)
img = img.convert("RGB")
w, h = img.size
@@ -1959,18 +1964,21 @@ class underlying_operations:
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
try:
logging.info(
f"[OCR置信度] {picname}: "
f"平均={ocr_confidence_info.get('avg_confidence', 0.0):.4f}, "
f"最小={ocr_confidence_info.get('min_confidence', 0.0):.4f}, "
f"最大={ocr_confidence_info.get('max_confidence', 0.0):.4f}, "
f"项目数={ocr_confidence_info.get('item_count', 0)}"
"[OCR置信度] %s: 平均=%.4f, 最小=%.4f, 最大=%.4f, 项目数=%d",
picname,
ocr_confidence_info.get("avg_confidence", 0.0),
ocr_confidence_info.get("min_confidence", 0.0),
ocr_confidence_info.get("max_confidence", 0.0),
int(ocr_confidence_info.get("item_count", 0) or 0),
)
except Exception:
pass
if debug_path:
try:
logging.info(
f"[调试图像] OCR数字结果保存: {debug_path}, 数字: {digits_result}"
"[调试图像] OCR数字结果保存: %s, 数字: %s",
debug_path,
digits_result,
)
except Exception:
pass
@@ -2241,7 +2249,7 @@ class underlying_operations:
return "".join([t[2] for t in extracted_items])
def delay(self, seconds: float = 1):
time.sleep(seconds)
time_module.sleep(seconds)
def random_delay(self, min_seconds=1, max_seconds=100):
"""等待随机的时长"""
@@ -2467,12 +2475,12 @@ class underlying_operations:
# 记录错误但不抛出异常,避免中断主流程
error_msg = stderr_text.strip() if stderr_text else "权限不足"
print(f"[警告] 滑动操作失败: {error_msg}")
print(f"[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
print("[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
print(
f" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'"
" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'"
)
print(f" 2. 使用已 root 的设备")
print(f" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
print(" 2. 使用已 root 的设备")
print(" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
# 不抛出异常,让程序继续运行(可能只是滑动失败,其他功能仍可用)
except subprocess.TimeoutExpired:
print("[警告] 滑动操作超时")
@@ -2496,11 +2504,11 @@ class underlying_operations:
)
if "event" not in result.stdout.lower():
raise Exception("无法找到触摸设备")
raise FileNotFoundError("无法找到触摸设备")
# 简化实现:直接使用 input 命令的替代参数
# 注意:sendevent 需要 root 权限,这里只是尝试
raise Exception("sendevent 需要 root 权限,暂不支持")
raise PermissionError("sendevent 需要 root 权限,暂不支持")
def _swipe_with_uiautomator(self, device_id, x1, y1, x2, y2):
"""使用 uiautomator 滑动(如果可用)
@@ -2524,7 +2532,7 @@ class underlying_operations:
)
if result.returncode != 0:
raise Exception(
raise RuntimeError(
f"uiautomator swipe 失败: {result.stderr.decode('utf-8', errors='ignore')}"
)
@@ -2555,14 +2563,14 @@ class underlying_operations:
# 4. 发送 DOWN -> MOVE -> UP 事件序列
if "event" not in result.stdout.lower():
raise Exception("无法找到触摸设备(需要 root 权限)")
raise FileNotFoundError("无法找到触摸设备(需要 root 权限)")
# 注意:完整的 sendevent 实现非常复杂,需要:
# - 设备特定的坐标转换
# - 正确的事件序列(SYN_REPORT 等)
# - 不同 Android 版本的事件格式可能不同
raise Exception("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
raise PermissionError("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
def click(self, device_id, x=500, y=500):
"""点击坐标位置"""
@@ -2907,13 +2915,13 @@ class underlying_operations:
success = True
# 给 IME 一点时间把文本真正“打进”输入框
time.sleep(0.35)
time_module.sleep(0.35)
return success
finally:
# 尝试恢复原输入法,避免影响手动使用
if restore_prev and prev and prev != adb_ime:
# 再稍等一下,避免过早切回导致输入丢失
time.sleep(0.25)
time_module.sleep(0.25)
self.restore_ime(device_id, prev)
def paste_text_at(self, device_id: str, x: int, y: int, text: str) -> bool:
@@ -2929,10 +2937,10 @@ class underlying_operations:
# 先确保输入框获得焦点
try:
self.click(device_id, int(x), int(y))
time.sleep(0.2)
time_module.sleep(0.2)
# 有些输入框第一次点不进,补一次轻点
self.click(device_id, int(x), int(y))
time.sleep(0.15)
time_module.sleep(0.15)
except Exception:
pass
@@ -2947,7 +2955,7 @@ class underlying_operations:
# 1) 优先:剪贴板 + 粘贴键
if self.set_clipboard_text(device_id, t):
# 给系统一点时间刷新剪贴板
time.sleep(0.15)
time_module.sleep(0.15)
if self.paste_from_clipboard(device_id):
return True
@@ -3010,7 +3018,7 @@ class underlying_operations:
import path_config
local_path = path_config.get_window_dump_path()
start = time.time()
start = time_module.time()
while True:
if self._uiautomator_dump(device_id, local_path):
try:
@@ -3043,9 +3051,9 @@ class underlying_operations:
self.click(device_id, cx, cy)
return True
if time.time() - start >= timeout_seconds:
if time_module.time() - start >= timeout_seconds:
return False
time.sleep(0.2)
time_module.sleep(0.2)
def tap_close_icon(
self, device_id: str, screen_width: int = 1080, timeout_seconds: float = 2.0
@@ -3063,7 +3071,7 @@ class underlying_operations:
import path_config
local_path = path_config.get_window_dump_path()
start = time.time()
start = time_module.time()
def _score(node_attrib: dict, bounds_tuple) -> int:
x1, y1, x2, y2 = bounds_tuple
@@ -3131,6 +3139,6 @@ class underlying_operations:
self.click(device_id, cx, cy)
return True
if time.time() - start >= timeout_seconds:
if time_module.time() - start >= timeout_seconds:
return False
time.sleep(0.2)
time_module.sleep(0.2)
+2 -2
View File
@@ -132,7 +132,7 @@
"fudai_template_match_enabled": false,
"fudai_template_match_threshold": 0.7,
"lucky_draw_red_ratio_threshold": 0.8,
"y_pianyi": -8,
"y_pianyi": 0,
"skip_if_countdown_lt_seconds": 5,
"no_attend_timeout_minutes": 30.0,
"logging": {
@@ -186,7 +186,7 @@
"debug_captures": {
"enabled": false,
"keep_days": 3,
"max_files": 200,
"max_files": 2000,
"auto_cleanup": true,
"async_save": false,
"log_on_complete": false
+1 -1
View File
@@ -241,7 +241,7 @@ def find_and_open_fudai_detail(
pass
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
try:
from PIL import Image
from PIL import Image # type: ignore[import]
import importlib
douyin_screenshot_manager = importlib.import_module(
+35 -31
View File
@@ -10,12 +10,16 @@
from __future__ import annotations
from typing import Any, List, Tuple, Optional
from typing import Any, List, Tuple, Optional, cast
import os
import time
import subprocess
import logging
# Optional heavy dependencies used in image processing; Pylance may not have them in analysis env
from PIL import Image # type: ignore[import]
import numpy as np # type: ignore[import]
from Underlying_Operations import underlying_operations
from douyin.stage import douyin_stage
@@ -709,7 +713,8 @@ class fudai_analyse:
"""
try:
import path_config
from PIL import Image
# use module-level `Image`
# 确保有最新全图
try:
@@ -730,7 +735,7 @@ class fudai_analyse:
# 以原子方式读取文件内容再由 PIL 解析,避免因文件替换/锁定导致的半写入问题
import io
from PIL import UnidentifiedImageError
from PIL import UnidentifiedImageError # type: ignore[import]
data = None
# 增强读取:多次尝试并在每次读到字节后用 PIL 验证,避免半写入/损坏 PNG 导致解析异常
@@ -853,8 +858,7 @@ class fudai_analyse:
if not template_path or not os.path.exists(template_path):
return False, 0.0
from PIL import Image
import numpy as np
# use module-level `Image` and `np` imports
roi_img = Image.open(roi_path).convert("RGB")
tpl_img = Image.open(template_path).convert("RGB")
@@ -1846,8 +1850,6 @@ class fudai_analyse:
len(self.reservations) if self.reservations else 0
),
)
except Exception:
pass
# use module-level `douyin_reservation_logic`
douyin_reservation_logic.cleanup_expired_reservations(
@@ -2178,9 +2180,9 @@ class fudai_analyse:
base_y=567,
)
self.operation.delay(1.0) # 等待返回完成
except Exception as exc:
except Exception as exc_inner:
self._log_kv(
"粉丝团处理", "点击返回直播间失败", error=str(exc)
"粉丝团处理", "点击返回直播间失败", error=str(exc_inner)
)
except Exception:
pass
@@ -2207,8 +2209,8 @@ class fudai_analyse:
base_y=567,
)
self.operation.delay(1.0) # 等待返回完成
except Exception as exc:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(exc))
except Exception as exc_inner2:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(exc_inner2))
# 延迟后返回,让主循环继续处理
self.operation.delay(0.5)
@@ -2448,6 +2450,7 @@ class fudai_analyse:
self
)
# pylint: disable=too-many-nested-blocks
def _handle_in_fudai_detail(self) -> None:
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
start_time = time.time()
@@ -2497,8 +2500,8 @@ class fudai_analyse:
and isinstance(detail, tuple)
and len(detail) >= 6
):
# 使用索引读取以避免静态分析对解包的误报
countdown_tuple = detail[5]
# detail 已校验为 tuple 且长度足够,可直接索引读取倒计时信息
countdown_tuple = detail[5] # pylint: disable=unsubscriptable-object
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
@@ -2799,7 +2802,9 @@ class fudai_analyse:
)
or "adb"
)
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
if not adb_cmd.startswith(
'"'
) and not adb_cmd.endswith('"'):
adb_cmd = f'"{adb_cmd}"'
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300"
subprocess.run(
@@ -2975,7 +2980,9 @@ class fudai_analyse:
)
or "adb"
)
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
if not adb_cmd.startswith(
'"'
) and not adb_cmd.endswith('"'):
adb_cmd = f'"{adb_cmd}"'
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300"
subprocess.run(
@@ -3101,14 +3108,15 @@ class fudai_analyse:
# 记录当前福袋的 future_ts,供 attend_choujiang 使用
try:
if isinstance(detail, tuple) and len(detail) >= 6:
countdown_tuple = detail[5]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
):
future_ts = float(countdown_tuple[1] or 0.0)
if future_ts > 0:
self._current_fudai_future_ts = future_ts
d_cast: Tuple[Any, ...] = cast(Tuple[Any, ...], detail)
countdown_tuple = d_cast[5]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
):
future_ts = float(countdown_tuple[1] or 0.0)
if future_ts > 0:
self._current_fudai_future_ts = future_ts
except Exception:
pass
@@ -3143,7 +3151,8 @@ class fudai_analyse:
remain_seconds = 0
future_timestamp = 0.0
if isinstance(detail, tuple) and len(detail) >= 6:
countdown_tuple = detail[5]
d_cast: Tuple[Any, ...] = cast(Tuple[Any, ...], detail)
countdown_tuple = d_cast[5]
if isinstance(countdown_tuple, tuple) and len(countdown_tuple) >= 2:
# countdown_tuple[0] 是 countdown_start(开始时间戳)
# countdown_tuple[1] 是 countdown_end(结束时间戳/开奖时间戳)
@@ -3185,10 +3194,7 @@ class fudai_analyse:
# 从预约队列中移除已完成的预约(匹配 future_ts,允许5秒误差)
if hasattr(self, "reservations") and self.reservations:
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
# use module-level `douyin_reservation_logic`
reservations_to_remove = []
for idx, r in enumerate(self.reservations):
try:
@@ -3312,9 +3318,7 @@ class fudai_analyse:
# 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情
try:
import time as time_module
now_ts = time_module.time()
now_ts = time.time()
focus_until = float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0)
queue_full_waiting = bool(
getattr(self, "queue_full_waiting_at_earliest", False) or False
+9 -2
View File
@@ -81,6 +81,15 @@ def attend_choujiang(analyser) -> bool:
attend_button_text and "参与成功" in attend_button_text
): # 如果识别到已经参与抽奖
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
# future_ts 可能尚未在此分支前赋值,先做兜底初始化(供 metric 使用)
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(
"统计",
@@ -202,8 +211,6 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.5)
+2 -2
View File
@@ -5,9 +5,9 @@ import time
import os
import threading
from typing import Tuple, Any, Optional, Dict
from PIL import Image
from PIL import Image # type: ignore[import]
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import numpy as np # type: ignore[import]
from douyin.utils.douyin_utils import extract_prize_value_yuan
from douyin.reservation import douyin_reservation_logic
+3 -3
View File
@@ -489,7 +489,7 @@ def configure_logging(
monitor_warning_mb: 监控警告大小阈值(MB),默认500MB
monitor_critical_mb: 监控严重大小阈值(MB),默认2000MB
"""
global _logging_configured
global _logging_configured # noqa: PLW0603 # pylint: disable=global-statement # pyright: ignore[reportGlobalStatement]
# rotation 相关默认值(函数级),确保在所有分支可用,避免可能的未赋值使用
rotation_enabled = False
@@ -1121,7 +1121,7 @@ def start_log_monitor(
check_interval: 检查间隔(秒)
alert_callback: 告警回调函数
"""
global _log_monitor
global _log_monitor # noqa: PLW0603 # pylint: disable=global-statement # pyright: ignore[reportGlobalStatement]
if _log_monitor:
_log_monitor.stop()
@@ -1139,7 +1139,7 @@ def start_log_monitor(
def stop_log_monitor() -> None:
"""停止日志轮转监控器"""
global _log_monitor
global _log_monitor # noqa: PLW0603 # pylint: disable=global-statement # pyright: ignore[reportGlobalStatement]
if _log_monitor:
_log_monitor.stop()
+53 -65
View File
@@ -3,17 +3,25 @@ from __future__ import annotations
import os
from typing import Any
from PIL import Image
from douyin.fudai.core.coords import (
LIVE_VERIFY1,
LIVE_VERIFY2,
ROBOT_VERIFY,
) # pylint: disable=no-name-in-module
from PIL import Image # type: ignore[import]
# OCR 预处理接口(直接导入)
from douyin.fudai.core.coords import LIVE_VERIFY1, LIVE_VERIFY2, ROBOT_VERIFY
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
def _to_rgb_tuple(color: Any) -> tuple[int, int, int]:
if isinstance(color, (int, float)):
v = int(color)
return (v, v, v)
if isinstance(color, (tuple, list)):
if len(color) >= 3:
try:
return (int(color[0]), int(color[1]), int(color[2]))
except Exception:
return (0, 0, 0)
return (0, 0, 0)
def check_have_robot_analyse(analyser) -> int | bool:
"""检查是否存在人机校验。
@@ -29,9 +37,10 @@ def check_have_robot_analyse(analyser) -> int | bool:
if "验证" in result:
print("存在滑动图片人机校验,需要等待完成验证。")
return 1
elif "形状相同" in result:
if "形状相同" in result:
print("存在点击图片人机校验,需要等待完成验证。")
return 2
analyser.cut_pic(*LIVE_VERIFY2, "", "直播验证")
name_live2 = preprocess_for_ocr(analyser, "直播验证")
result = analyser.operation.analyse_pic_word(name_live2)
@@ -86,81 +95,60 @@ def deal_robot_analyse(analyser) -> None:
def deal_robot_pic_change_color(analyser) -> None:
"""处理人机验证的图片,转为黑白图。"""
analyser.cut_pic(*ROBOT_VERIFY, "save", "机器人验证")
try:
import path_config
import path_config
path = path_config.get_robot_verify_pic_path(save_subdir=True)
pic = path
except Exception:
import path_config
path = path_config.get_robot_verify_pic_path(save_subdir=True)
pic = path
path = path_config.get_robot_verify_pic_path(save_subdir=True)
pic = path
img = Image.open(pic)
img = img.convert("RGB")
img = Image.open(pic).convert("RGB")
width, height = img.size
for x in range(5, width - 40):
for y in range(20, height - 30):
current_color = img.getpixel((x, y))
if (
current_color[0] > 240
and current_color[1] > 240
and current_color[2] > 240
):
img.putpixel((x, y), (255, 255, 255)) # 白色
elif (
current_color[0] < 35
and current_color[1] < 20
and current_color[2] < 20
):
img.putpixel((x, y), (0, 0, 0)) # 黑色
r, g, b = _to_rgb_tuple(img.getpixel((x, y)))
if r > 240 and g > 240 and b > 240:
img.putpixel((x, y), (255, 255, 255))
elif r < 35 and g < 20 and b < 20:
img.putpixel((x, y), (0, 0, 0))
else:
img.putpixel((x, y), (128, 128, 128)) # 灰色
img.putpixel((x, y), (128, 128, 128))
os.makedirs(path, exist_ok=True)
save_pic = os.path.join(path, "机器人验证_新.png")
img.save(save_pic)
img.save(os.path.join(path, "机器人验证_新.png"))
def check_robot_pic_distance(analyser) -> int:
"""根据人机图片计算需要滑动的距离。"""
analyser.cut_pic(*ROBOT_VERIFY, "", "机器人验证")
# 使用新的路径查找方法(支持新旧位置)
pic_path = analyser.operation._find_pic_path("机器人验证", for_reading=True)
if not pic_path or not os.path.exists(pic_path):
raise FileNotFoundError(f"机器人验证图片不存在: {pic_path}")
img = Image.open(pic_path)
img = img.convert("RGB")
img = Image.open(pic_path).convert("RGB")
width, height = img.size
printed_first_result = False # 用于记录第一个结果是否已经输出过
printed_second_result = False # 用于记录第二个结果是否已经输出过
x = 0
y = 0
first_x = 0
first_y = 0
found_first = False
for y in range(20, height - 30):
for x in range(5, width - 40):
current_color = img.getpixel((x, y))
if (
current_color[0] > 240
and current_color[1] > 240
and current_color[2] > 240
):
if not printed_first_result: # 确保只输出一次第一个结果
print(x, y)
printed_first_result = True
r, g, b = _to_rgb_tuple(img.getpixel((x, y)))
if r > 240 and g > 240 and b > 240:
print(x, y)
first_x = x
first_y = y
found_first = True
break
if printed_first_result: # 如果已经输出过第一个结果,则退出外层循环
if found_first:
break
for x1 in range(x, width - 40):
current_color = img.getpixel((x1, y))
if (
current_color[0] < 50
and current_color[1] < 55
and current_color[2] < 85
and current_color[0] + current_color[1] + current_color[2] < 150
):
if not printed_second_result: # 确保只输出一次第二个结果
print(x1, y)
printed_second_result = True
print("需要滑动的距离为{}".format(x1 - x))
return x1 - x
# 如果没有检测到,返回一个兜底值 0
if not found_first:
return 0
for x1 in range(first_x, width - 40):
r, g, b = _to_rgb_tuple(img.getpixel((x1, first_y)))
if r < 50 and g < 55 and b < 85 and (r + g + b) < 150:
print(x1, first_y)
print("需要滑动的距离为{}".format(x1 - first_x))
return x1 - first_x
return 0
+10 -1
View File
@@ -449,6 +449,13 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
pass
return False, tpl_path
# 预先定义变量,避免静态分析器在异常路径中报告未定义错误
like_tpl = ""
fav_tpl = ""
like_tpl_exists = False
fav_tpl_exists = False
project_root = None
try:
like_tpl = str(
getattr(analyser, "yanghao_like_template_path", "") or ""
@@ -979,7 +986,9 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
debug_on = False
if debug_on:
print(
f"[养号][DEBUG] like_tpl='{like_tpl}' exists={like_tpl_exists}; fav_tpl='{fav_tpl}' exists={fav_tpl_exists}; project_root={project_root}"
f"[养号][DEBUG] like_tpl='{getattr(analyser, 'yanghao_like_template_path', '')}' "
f"fav_tpl='{getattr(analyser, 'yanghao_fav_template_path', '')}' "
f"project_root='{getattr(analyser, 'config_path', None)}'"
)
pass
return
+3 -4
View File
@@ -1,7 +1,4 @@
from __future__ import annotations
"""
工具方法模块
"""工具方法模块
============
职责:通用工具方法
@@ -12,6 +9,8 @@ from __future__ import annotations
- 读取像素阶段状态
"""
from __future__ import annotations
import os
import time
import shutil
+6 -4
View File
@@ -14,7 +14,7 @@ _project_root = os.path.dirname(_script_dir)
if _project_root not in sys.path:
sys.path.insert(0, _project_root)
from PIL import Image, ImageTk
from PIL import Image, ImageTk # type: ignore[import]
# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)
from gui.gui_core import (
@@ -2810,7 +2810,9 @@ def main():
(".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif")
):
# 获取相对路径
rel_path = os.path.relpath(os.path.join(root, file), images_dir)
rel_path = os.path.relpath(
os.path.join(root, file), str(images_dir)
)
# 统一使用正斜杠(Windows和Unix都支持)
rel_path = rel_path.replace("\\", "/")
image_files.append(rel_path)
@@ -3164,7 +3166,7 @@ def main():
seconds = uptime_seconds % 60
lines.append(f"运行时长: {hours:02d}:{minutes:02d}:{seconds:02d}")
else:
lines.append(f"运行时长: -")
lines.append("运行时长: -")
last_log_ts = stats.get("last_log_ts")
if last_log_ts:
@@ -4099,7 +4101,7 @@ def main():
lines.append(
f"│ 🏠 直播间名称(原始):{room_title_raw or '未知'}"
)
lines.append(f"│")
lines.append("│")
lines.append(f"│ 📝 记录时间:{created_str_full}")
lines.append(f"└{'─' * 58}")
lines.append("")
+5 -2
View File
@@ -50,6 +50,7 @@ def list_adb_devices(adb_exe: str) -> list[str]:
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
except FileNotFoundError:
return []
@@ -1020,13 +1021,13 @@ class Runner:
f"Python路径: {sys.executable}\n"
f"run_cli.py路径: {run_cli_path}\n"
f"原始错误: {e}"
)
) from e
except Exception as e:
raise RuntimeError(
f"启动进程失败:{e}\n"
f"命令: {' '.join(cmd)}\n"
f"工作目录: {path_config.PROJECT_ROOT}"
)
) from e
with self._lock:
self._proc = p
@@ -1127,6 +1128,7 @@ class Runner:
encoding="utf-8",
errors="replace",
timeout=5.0,
check=False,
)
if proc.returncode == 0:
@@ -1182,6 +1184,7 @@ class Runner:
["taskkill", "/PID", str(pid), "/T", "/F"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
else:
# 类 Unix:尝试向进程组发送 SIGKILL
+14 -15
View File
@@ -57,6 +57,7 @@ def list_adb_devices(adb_exe: str) -> list[str]:
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
except FileNotFoundError:
return []
@@ -118,6 +119,12 @@ class ProcRunner:
"updated_ts": None,
}
# 延迟属性:预先声明,避免静态检查报“在 __init__ 外定义属性”
self._log_permission_warned: bool = False
self._log_write_error_warned: bool = False
self._current_trace_id: str = ""
self._mdc_context: dict[str, str] = {}
# 事件流(用于趋势/分布/Top 统计),保留最近 N 条
self._events: list[dict] = []
self._events_cap: int = 5000
@@ -166,13 +173,13 @@ class ProcRunner:
f.flush() # 确保立即写入磁盘,避免缓冲区延迟导致日志丢失
except PermissionError as e:
# 权限错误,只输出一次警告避免刷屏
if not hasattr(self, "_log_permission_warned"):
if not self._log_permission_warned:
print(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}")
print(f"[WEB_GUI] 错误详情: {e}")
self._log_permission_warned = True
except Exception as e:
# 其他文件写失败不应影响主流程,但记录第一次错误以便调试
if not hasattr(self, "_log_write_error_warned"):
if not self._log_write_error_warned:
print(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}")
print(f"[WEB_GUI] 错误详情: {e}")
self._log_write_error_warned = True
@@ -277,7 +284,7 @@ class ProcRunner:
if trace_id_match:
trace_id = trace_id_match.group(1)
# 存储当前traceId(用于统计和显示)
if not hasattr(self, "_current_trace_id"):
if not self._current_trace_id:
self._current_trace_id = trace_id
elif trace_id != "N/A":
self._current_trace_id = trace_id
@@ -290,8 +297,6 @@ class ProcRunner:
mdc_pairs = re.findall(r"(\w+)=([^,\s]+)", mdc_str)
for key, value in mdc_pairs:
# 存储MDC信息(可用于统计)
if not hasattr(self, "_mdc_context"):
self._mdc_context = {}
self._mdc_context[key] = value
# --- 福袋:抽取"最近一次"识别到的信息 ---
@@ -1424,7 +1429,7 @@ class ProcRunner:
self._append_log(f"[网页] 读取线程启动,监视 PID={p.pid}")
out = p.stdout
if out is None:
self._append_log(f"[网页] 读取线程:stdout 为 None,无法读取子进程输出")
self._append_log("[网页] 读取线程:stdout 为 None,无法读取子进程输出")
try:
rc = p.wait()
except Exception:
@@ -1448,7 +1453,7 @@ class ProcRunner:
pass
except BrokenPipeError:
# 进程已关闭stdout
self._append_log(f"[网页] 读取线程:子进程stdout已关闭")
self._append_log("[网页] 读取线程:子进程stdout已关闭")
except Exception as e:
self._append_log(f"[网页] 读取线程异常:{e}")
@@ -1456,7 +1461,7 @@ class ProcRunner:
rc = p.wait(timeout=1)
except subprocess.TimeoutExpired:
rc = None
self._append_log(f"[网页] 等待进程退出超时,强制终止")
self._append_log("[网页] 等待进程退出超时,强制终止")
try:
p.kill()
rc = p.wait(timeout=5)
@@ -1691,7 +1696,7 @@ class Handler(BaseHTTPRequestHandler):
if not safe.startswith("pic/"):
self.send_error(HTTPStatus.FORBIDDEN)
return
full = os.path.join(path_config.PROJECT_ROOT, safe)
full = os.path.join(str(path_config.PROJECT_ROOT), safe)
if not os.path.isfile(full):
self.send_error(HTTPStatus.NOT_FOUND)
return
@@ -1893,12 +1898,6 @@ class Handler(BaseHTTPRequestHandler):
self.send_error(HTTPStatus.NOT_FOUND)
def log_message(self, format, *args): # type: ignore[override]
# 覆盖基类方法以抑制日志输出
# 参数名从 fmt 改为 format 以匹配基类签名
return
def main() -> int:
host = "127.0.0.1"
# 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000
+1 -3
View File
@@ -11,9 +11,7 @@ import sys
# 修复Windows控制台编码问题
if sys.platform == "win32":
try:
reconfigure_func = getattr(sys.stdout, "reconfigure", None)
if reconfigure_func:
reconfigure_func(encoding="utf-8")
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
+75
View File
@@ -0,0 +1,75 @@
from __future__ import annotations
import ast
import sys
from pathlib import Path
from typing import Iterable
def _iter_py_files(path: Path) -> Iterable[Path]:
if path.is_file():
if path.suffix.lower() == ".py":
yield path
return
for p in path.rglob("*.py"):
if p.is_file():
yield p
def _exc_type_key(exc: ast.expr | None) -> str:
if exc is None:
return "BaseException" # bare except
try:
return ast.unparse(exc)
except Exception:
return type(exc).__name__
class DuplicateExceptVisitor(ast.NodeVisitor):
def __init__(self, file_path: Path) -> None:
self.file_path = file_path
def visit_Try(self, node: ast.Try) -> None:
seen: dict[str, int] = {}
for handler in node.handlers:
key = _exc_type_key(handler.type)
lineno = int(getattr(handler, "lineno", 0) or 0)
if key in seen:
prev = seen[key]
print(
f"{self.file_path}:{lineno}: duplicate except for {key} (previous at line {prev})"
)
else:
seen[key] = lineno
self.generic_visit(node)
def main(argv: list[str] | None = None) -> int:
argv = list(sys.argv[1:] if argv is None else argv)
target = Path(argv[0]) if argv else Path("douyin")
if not target.exists():
print(f"Path not found: {target}")
return 2
exit_code = 0
for py_file in _iter_py_files(target):
try:
source = py_file.read_text(encoding="utf-8")
tree = ast.parse(source)
except (OSError, UnicodeDecodeError) as e:
print(f"{py_file}: read error: {e}")
exit_code = 1
continue
except SyntaxError as e:
print(f"{py_file}:{getattr(e, 'lineno', 0)}: SyntaxError: {e}")
exit_code = 1
continue
DuplicateExceptVisitor(py_file).visit(tree)
return exit_code
if __name__ == "__main__":
raise SystemExit(main())
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env python3
"""
验证 GUI 回退方式控件注入情况的自检脚本。
功能:
- 检查 `gui/gui_app.py` 是否包含关键标记字符串(用于确认控件已被添加)。
- 读取 `config/config.json` 中的 `return_to_first_back_method` 当前值。
- 尝试列出当前运行的 Python 进程并检查命令行中是否包含 `gui_app.py`(Windows 下使用 PowerShell/CIM;若可用,优先使用 psutil)。
用法:
python tools/verify_gui_back_method.py
返回:
退出码 0 = 检查通过(所有标记存在);1 = 标记缺失或其他问题。
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from typing import List
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
GUI_APP_PATH = os.path.join(ROOT, "gui", "gui_app.py")
CONFIG_PATH = os.path.join(ROOT, "config", "config.json")
def check_file_markers(path: str) -> List[str]:
# 使用变量名和明显的中文标签作为检测标记,兼容不同位置的控件注入实现
markers = [
"return_to_first_back_method_var",
"top_back_method_display_var",
"back_method_display_var",
"top_back_method_combo",
"回退方式:",
"return_to_first_back_method",
]
missing = []
if not os.path.exists(path):
return [f"MISSING_FILE:{path}"]
import unicodedata
with open(path, "r", encoding="utf-8") as f:
txt = f.read()
# normalize unicode to NFKC to avoid full-width/half-width or similar variants
txt_norm = unicodedata.normalize("NFKC", txt).lower()
for m in markers:
m_norm = unicodedata.normalize("NFKC", m).lower()
if m_norm in txt_norm:
# debug: print where found
try:
print(f"DEBUG: marker '{m}' found at index {txt_norm.index(m_norm)}")
except Exception:
pass
continue
# try a looser check: replace full-width colon variants and simple punctuation
m_alt = m_norm.replace(":", ":")
if m_alt in txt_norm:
try:
print(f"DEBUG: marker alt '{m}' found at index {txt_norm.index(m_alt)}")
except Exception:
pass
continue
missing.append(m)
# Additional raw checks for debugging and fuzzy regex matching
if missing:
import re
for m in list(missing):
raw_idx = txt.find(m)
norm_idx = txt_norm.find(unicodedata.normalize("NFKC", m).lower())
print(f"DEBUG-RAW: marker '{m}' raw_index={raw_idx}, norm_index={norm_idx}")
# try fuzzy regex: split by non-word/underscore and allow any separators
parts = [p for p in re.split(r"[_\W]+", m) if p]
if parts:
pattern = r"\b" + r"\W*".join([re.escape(p) for p in parts]) + r"\b"
if re.search(pattern, txt, flags=re.IGNORECASE):
print(f"DEBUG-FUZZY: marker '{m}' matched fuzzy pattern: {pattern}")
missing.remove(m)
continue
if raw_idx >= 0 and m in txt:
# show surrounding repr for inspection
start = max(0, raw_idx - 40)
end = min(len(txt), raw_idx + len(m) + 40)
print("DEBUG-SURROUND:", repr(txt[start:end]))
# debug: if missing all, print snippet to help diagnosis
if missing:
try:
snippet = txt[:800].replace("\n", " ")[:800]
print("DEBUG: file starts with:", snippet)
print("DEBUG: file length:", len(txt))
except Exception:
pass
return missing
def read_config_value(
path: str, key: str = "return_to_first_back_method"
) -> str | None:
if not os.path.exists(path):
return None
try:
with open(path, "r", encoding="utf-8") as f:
cfg = json.load(f)
return str(cfg.get(key))
except Exception:
return None
def list_python_processes_filtering_gui() -> List[dict]:
"""尝试列出运行中的 python/pythonw 进程并返回其命令行中包含 gui_app.py 的条目。
优先使用 psutil(如可用),否则在 Windows 上使用 PowerShell CIM 查询。
"""
procs = []
try:
import psutil # type: ignore[import]
for p in psutil.process_iter(["pid", "name", "cmdline"]):
try:
name = (p.info.get("name") or "").lower()
if "python" in name:
cmd = " ".join(p.info.get("cmdline") or [])
if "gui_app.py" in cmd or "gui\\gui_app.py" in cmd:
procs.append({"pid": p.info.get("pid"), "cmdline": cmd})
except Exception:
continue
return procs
except Exception:
pass
# Fallback: Windows PowerShell CIM query
try:
pw_cmd = [
"powershell",
"-NoProfile",
"-Command",
"Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and ($_.CommandLine -match 'gui_app.py') } | Select-Object ProcessId,CommandLine | ConvertTo-Json",
]
proc = subprocess.run(
pw_cmd, capture_output=True, text=True, timeout=5, check=False
)
out = proc.stdout.strip()
if not out:
return []
# out may be a JSON array or object
try:
j = json.loads(out)
if isinstance(j, dict):
j = [j]
for item in j:
procs.append(
{"pid": item.get("ProcessId"), "cmdline": item.get("CommandLine")}
)
except Exception:
# fallback to raw parsing
for line in out.splitlines():
if "gui_app.py" in line:
procs.append({"pid": None, "cmdline": line})
return procs
except Exception:
return []
def main() -> int:
print("Verifying gui injection and runtime usage\n")
print(f"Workspace root: {ROOT}")
print(f"Checking file: {GUI_APP_PATH}")
missing = check_file_markers(GUI_APP_PATH)
if missing:
print("Missing markers in gui_app.py:")
for m in missing:
print(" -", m)
else:
print("All expected markers present in gui_app.py")
cfg_val = read_config_value(CONFIG_PATH)
print(f"Config: {CONFIG_PATH} -> return_to_first_back_method = {cfg_val}")
procs = list_python_processes_filtering_gui()
if procs:
print("Found running Python processes with gui_app.py in command line:")
for p in procs:
print(f" - PID={p.get('pid')}, CMD={p.get('cmdline')}")
else:
print(
"No running Python processes with gui_app.py detected (psutil/PowerShell lookup)"
)
# Exit code: 0 if no missing markers, else 1
return 0 if not missing else 1
if __name__ == "__main__":
rc = main()
sys.exit(rc)