覆盖 14 个文件中的 Image.open() 未正确关闭问题: - fansclub_handler: 5 处(pic/pic_rgb/img 未 close) - image_ops: 2 处(crop 后 pic 未 close) - douyin_popups: 2 处(pic.convert 重赋值泄漏原始句柄) - douyin_fudai: 1 处(open().convert() 链式调用泄漏) - douyin_robot: 2 处(同上) - save_files/direct_attend/finder/stage/find_open/detail/_common/ocr_preprocess: 各 1-2 处 统一修复模式:分离 open 与 convert,try/finally 确保原始句柄关闭。 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
196 lines
6.7 KiB
Python
196 lines
6.7 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
from typing import Any
|
|
|
|
from PIL import Image # type: ignore[import]
|
|
|
|
from douyin.fudai.core.coords import LIVE_VERIFY1, LIVE_VERIFY2, ROBOT_VERIFY
|
|
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
|
|
|
import logging as _logging
|
|
|
|
# 模块级日志:优先走 analyser._log_kv,回退到 logging。
|
|
_LOGGER = _logging.getLogger("douyin.other.douyin_robot")
|
|
|
|
|
|
def _robot_log(analyser, msg: str, level: str = "INFO") -> None:
|
|
"""统一人机校验日志出口;失败兜底 stdout。"""
|
|
try:
|
|
log_kv = getattr(analyser, "_log_kv", None) if analyser is not None else None
|
|
if callable(log_kv):
|
|
log_kv("人机校验", str(msg), level=str(level or "INFO"))
|
|
return
|
|
except Exception:
|
|
pass
|
|
try:
|
|
lv = str(level or "INFO").upper()
|
|
if lv == "ERROR":
|
|
_LOGGER.error(str(msg))
|
|
elif lv == "WARNING":
|
|
_LOGGER.warning(str(msg))
|
|
elif lv == "DEBUG":
|
|
_LOGGER.debug(str(msg))
|
|
else:
|
|
_LOGGER.info(str(msg))
|
|
except Exception:
|
|
try:
|
|
print(str(msg))
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
|
|
|
|
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:
|
|
"""检查是否存在人机校验。
|
|
|
|
返回:
|
|
- 1: 滑动图片验证
|
|
- 2: 点击图片验证(形状相同)
|
|
- 3: 人脸识别验证
|
|
- False: 未检测到人机验证
|
|
"""
|
|
analyser.cut_pic(*LIVE_VERIFY1, "", "直播验证")
|
|
name_live = preprocess_for_ocr(analyser, "直播验证")
|
|
result = analyser.operation.analyse_pic_word(name_live, 0)
|
|
if "验证" in result:
|
|
_robot_log(analyser, "存在滑动图片人机校验,需要等待完成验证。")
|
|
return 1
|
|
if "形状相同" in result:
|
|
_robot_log(analyser, "存在点击图片人机校验,需要等待完成验证。")
|
|
return 2
|
|
|
|
analyser.cut_pic(*LIVE_VERIFY2, "", "直播验证")
|
|
name_live2 = preprocess_for_ocr(analyser, "直播验证")
|
|
result = analyser.operation.analyse_pic_word(name_live2)
|
|
if "开始检测" in result:
|
|
_robot_log(analyser, "存在人脸识别人机校验,需要等待完成验证。")
|
|
return 3
|
|
return False
|
|
|
|
|
|
def deal_swipe_robot_analyse(analyser, distance: int = 400) -> None:
|
|
"""处理滑动图片的人机验证。"""
|
|
if distance:
|
|
targetx = (222 + distance) * analyser.resolution_ratio_x // 1080
|
|
else:
|
|
targetx = 622 * analyser.resolution_ratio_x // 1080
|
|
analyser.swipe(222, 1444, targetx, 1444, 300)
|
|
_robot_log(analyser, "滑轨滑动{}距离解锁人机验证".format(distance))
|
|
analyser.operation.delay(1)
|
|
|
|
|
|
def deal_robot_analyse(analyser) -> None:
|
|
"""处理人机校验,包含各种情况。"""
|
|
swipe_times = 0
|
|
while swipe_times < 10:
|
|
robot_result = check_have_robot_analyse(analyser)
|
|
if robot_result == 1:
|
|
distance = check_robot_pic_distance(analyser)
|
|
deal_swipe_robot_analyse(analyser, distance)
|
|
analyser.operation.delay(10)
|
|
analyser._shot_and_diagnose("人机校验", "校验后复查", analyser.device_id)
|
|
elif robot_result == 2:
|
|
_robot_log(analyser, "无法处理图片验证的人机,点击关闭退出验证,等待30分钟", level="WARNING")
|
|
analyser.click(910, 800) # 点击关闭
|
|
analyser.operation.delay(1800)
|
|
break
|
|
elif robot_result == 3:
|
|
_robot_log(analyser, "无法处理人脸识别验证的人机,点击返回退出验证,等待30分钟", level="WARNING")
|
|
analyser.operation.click_back(analyser.device_id)
|
|
analyser.operation.delay(2)
|
|
analyser.operation.click_back(analyser.device_id)
|
|
analyser.operation.delay(1800)
|
|
break
|
|
else:
|
|
break
|
|
swipe_times += 1
|
|
if swipe_times >= 10:
|
|
_robot_log(analyser, "无法处理图片验证的人机,点击关闭退出验证,等待30分钟", level="WARNING")
|
|
analyser.click(910, 800) # 点击关闭
|
|
analyser.operation.delay(1800)
|
|
|
|
|
|
def deal_robot_pic_change_color(analyser) -> None:
|
|
"""处理人机验证的图片,转为黑白图。"""
|
|
analyser.cut_pic(*ROBOT_VERIFY, "save", "机器人验证")
|
|
from douyin.core import path_config
|
|
|
|
path = path_config.get_robot_verify_pic_path(save_subdir=True)
|
|
pic = path
|
|
|
|
_raw = Image.open(pic)
|
|
try:
|
|
img = _raw.convert("RGB")
|
|
finally:
|
|
_raw.close()
|
|
width, height = img.size
|
|
for x in range(5, width - 40):
|
|
for y in range(20, height - 30):
|
|
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))
|
|
|
|
os.makedirs(path, exist_ok=True)
|
|
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}")
|
|
|
|
_raw = Image.open(pic_path)
|
|
try:
|
|
img = _raw.convert("RGB")
|
|
finally:
|
|
_raw.close()
|
|
width, height = img.size
|
|
|
|
first_x = 0
|
|
first_y = 0
|
|
found_first = False
|
|
for y in range(20, height - 30):
|
|
for x in range(5, width - 40):
|
|
r, g, b = _to_rgb_tuple(img.getpixel((x, y)))
|
|
if r > 240 and g > 240 and b > 240:
|
|
_robot_log(analyser, f"找到首像素 ({x}, {y})", level="DEBUG")
|
|
first_x = x
|
|
first_y = y
|
|
found_first = True
|
|
break
|
|
if found_first:
|
|
break
|
|
|
|
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:
|
|
_robot_log(analyser, f"找到末像素 ({x1}, {first_y})", level="DEBUG")
|
|
_robot_log(analyser, "需要滑动的距离为{}".format(x1 - first_x))
|
|
return x1 - first_x
|
|
|
|
return 0
|