- screenshot_operations.py: 19 处 print → _ops_log(带 [截图]/[截图操作] 前缀) - ocr_operations.py: 7 处 print → _ocr_log(带 [OCR] 前缀) - 两处都新增模块级 logger + 兜底 helper,与 douyin_yanghao / screenshot_service 采用相同模式 回归:149 .py 编译通过;test_filter_logging / check_web_gui_config_sync 通过; ScreenshotOperations、analyse_pic_word 仍可正常加载。 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
414 lines
17 KiB
Python
414 lines
17 KiB
Python
"""截图操作模块
|
||
|
||
包含截图、图片裁剪等截图相关操作。
|
||
支持后台截图服务和多线程优化。
|
||
"""
|
||
# pyright: reportOptionalMemberAccess=false
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import subprocess
|
||
import time
|
||
from datetime import datetime
|
||
from typing import Optional
|
||
|
||
from douyin.core.underlying_operations import _safe_replace_file, _mirror_screenshot_to_external
|
||
|
||
# 日志节流:当后台服务不可用并回退到直接截图时,避免每次都打印相同的日志
|
||
_last_service_fallback_log_ts: float = 0.0
|
||
_SERVICE_FALLBACK_LOG_INTERVAL = 10.0 # seconds
|
||
|
||
import logging as _logging
|
||
|
||
# 模块级 logger:原代码用 print 输出截图操作日志,统一走 logging。
|
||
# 保留消息中已有的 "[截图]"/"[截图操作]" 前缀,避免改变历史搜索习惯。
|
||
_LOGGER = _logging.getLogger("operations.screenshot_operations")
|
||
|
||
|
||
def _ops_log(msg: str, level: str = "INFO") -> None:
|
||
"""统一截图操作日志出口;失败兜底 stdout。"""
|
||
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:
|
||
_ops_log(str(msg))
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
|
||
|
||
class ScreenshotOperations:
|
||
"""截图操作类"""
|
||
|
||
@staticmethod
|
||
def _adb() -> str:
|
||
"""返回adb命令路径"""
|
||
import os
|
||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||
# 始终加引号,避免路径带空格 / 版本混用
|
||
if adb.startswith('"') and adb.endswith('"'):
|
||
return adb
|
||
return f'"{adb}"'
|
||
|
||
@staticmethod
|
||
def _adb_path() -> str:
|
||
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
|
||
import os
|
||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||
if adb.startswith('"') and adb.endswith('"'):
|
||
adb = adb[1:-1]
|
||
return adb
|
||
|
||
def get_screenshot(self, device_id, path="pic", use_service: bool = False) -> bool:
|
||
"""截图(支持后台服务模式)
|
||
|
||
参数:
|
||
device_id: 设备ID
|
||
path: 路径(默认"pic")
|
||
use_service: 是否使用后台截图服务(默认True,可显著提升性能)
|
||
|
||
返回:
|
||
是否成功获取截图
|
||
"""
|
||
# 如果启用服务模式,使用后台截图服务
|
||
if use_service:
|
||
try:
|
||
from operations.screenshot_service import ScreenshotService
|
||
service = ScreenshotService.get_instance()
|
||
# 若后台服务未能返回有效截图(False),回退到直接截图
|
||
try:
|
||
service_result = service.get_screenshot(device_id, force=False)
|
||
if service_result:
|
||
return True
|
||
else:
|
||
now = time.time()
|
||
global _last_service_fallback_log_ts
|
||
if now - _last_service_fallback_log_ts > _SERVICE_FALLBACK_LOG_INTERVAL:
|
||
timetag = datetime.now().strftime("%H:%M:%S")
|
||
_ops_log(f"[{timetag}] [截图操作] 后台服务未提供有效截图,回退到直接截图")
|
||
_last_service_fallback_log_ts = now
|
||
return self._get_screenshot_direct(device_id, path)
|
||
except Exception:
|
||
# 如果服务调用抛出异常,回退到直接截图
|
||
return self._get_screenshot_direct(device_id, path)
|
||
except Exception as e:
|
||
# 服务不可用时,回退到直接截图
|
||
timetag = datetime.now().strftime("%H:%M:%S")
|
||
_ops_log(f"[{timetag}] [截图操作] ⚠️ 服务模式失败,回退到直接截图: {e}")
|
||
|
||
# 原有的直接截图逻辑(保持向后兼容)
|
||
return self._get_screenshot_direct(device_id, path)
|
||
|
||
def _get_screenshot_direct(self, device_id, path="pic") -> bool:
|
||
"""直接截图(不使用服务模式)"""
|
||
direct_start = time.time()
|
||
if path == "pic":
|
||
try:
|
||
from douyin.core import path_config
|
||
out_dir = path_config.get_pic_dir()
|
||
except Exception: # type: ignore
|
||
# 回退到旧路径(向后兼容)
|
||
out_dir = os.path.join(os.path.dirname(__file__), "pic")
|
||
else: # type: ignore
|
||
out_dir = os.path.join(os.path.dirname(__file__), "target_pic")
|
||
if not os.path.exists(out_dir):
|
||
os.makedirs(out_dir)
|
||
|
||
# 统一输出到固定文件名,兼容现有 cut_pic()/后续流程
|
||
out_file = os.path.join(out_dir, "screenshot.png")
|
||
tmp_file = out_file + ".tmp"
|
||
timetag = datetime.now().strftime("%H:%M:%S")
|
||
|
||
adb = self._adb_path()
|
||
|
||
def _valid_png(path0: str) -> bool:
|
||
try:
|
||
if not os.path.exists(path0):
|
||
return False
|
||
sz = os.path.getsize(path0)
|
||
# PNG 通常远大于 1KB;0 字节/极小文件大概率是 adb 输出异常/中断
|
||
if sz < 1024:
|
||
return False
|
||
# 额外校验 PNG 头与文件尾(以及使用 PIL 验证文件完整性)
|
||
try:
|
||
with open(path0, "rb") as _f:
|
||
header = _f.read(4)
|
||
if header != b"\x89PNG":
|
||
return False
|
||
# 快速检查 IEND
|
||
_f.seek(-64, 2)
|
||
tail = _f.read(64)
|
||
if b"IEND" not in tail:
|
||
return False
|
||
except Exception:
|
||
return False
|
||
# 尝试使用 PIL 验证(更可靠地发现截断/损坏)
|
||
try:
|
||
from PIL import Image
|
||
|
||
with Image.open(path0) as im:
|
||
im.verify()
|
||
except Exception:
|
||
return False
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
# 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿
|
||
# 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。
|
||
for _ in range(2):
|
||
try:
|
||
try:
|
||
if os.path.exists(tmp_file):
|
||
os.remove(tmp_file)
|
||
except Exception:
|
||
pass
|
||
# 使用 Popen 流式读取,边接收数据边写入文件,提高性能
|
||
t_exec_start = time.time()
|
||
try:
|
||
process = subprocess.Popen(
|
||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
|
||
# 流式写入文件,避免等待整个命令完成
|
||
with open(tmp_file, "wb") as f:
|
||
while True:
|
||
chunk = process.stdout.read(65536) # 64KB 缓冲
|
||
if not chunk:
|
||
break
|
||
f.write(chunk)
|
||
# 确保数据落盘,避免后续读取到半写文件
|
||
try:
|
||
f.flush()
|
||
os.fsync(f.fileno())
|
||
except Exception:
|
||
pass
|
||
|
||
# 等待进程完成并检查返回码
|
||
return_code = process.wait(timeout=10)
|
||
if return_code != 0:
|
||
# 特殊处理常见的adb错误码
|
||
if return_code == 4294967295: # 0xFFFFFFFF
|
||
raise subprocess.CalledProcessError(
|
||
return_code,
|
||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||
f"设备连接失败或ADB服务异常 (错误码: {return_code})"
|
||
)
|
||
else:
|
||
raise subprocess.CalledProcessError(return_code, [adb, "-s", device_id, "exec-out", "screencap", "-p"])
|
||
|
||
t_exec_end = time.time()
|
||
exec_ms = (t_exec_end - t_exec_start) * 1000
|
||
timetag2 = datetime.now().strftime("%H:%M:%S")
|
||
_ops_log(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})")
|
||
|
||
except subprocess.TimeoutExpired:
|
||
# Popen 超时,记录并重新抛出异常
|
||
_ops_log(f"[截图] exec-out 流式读取超时")
|
||
raise
|
||
if _valid_png(tmp_file):
|
||
# 使用安全的文件替换函数并二次验证目标文件,避免写入截断导致后续读取失败
|
||
if _safe_replace_file(tmp_file, out_file):
|
||
# 目标文件替换后再验证一次,确保不是零字节或截断
|
||
if _valid_png(out_file):
|
||
_mirror_screenshot_to_external(out_file)
|
||
elapsed = (time.time() - direct_start) * 1000
|
||
_ops_log(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (exec-out,耗时: {elapsed:.0f}ms)")
|
||
return True
|
||
else:
|
||
# 替换后目标文件不完整,记录并尝试回退到 pull
|
||
_ops_log(f"[{timetag}] [截图] 警告:替换后目标文件不完整,回退到 pull")
|
||
try:
|
||
if os.path.exists(out_file):
|
||
os.remove(out_file)
|
||
except Exception:
|
||
pass
|
||
# 不立即返回,继续尝试回退方案
|
||
else:
|
||
# 如果替换失败,但临时文件有效,记录并尝试回退方案
|
||
_ops_log(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案")
|
||
except subprocess.TimeoutExpired:
|
||
# 超时异常,记录并继续重试
|
||
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案")
|
||
try:
|
||
if os.path.exists(tmp_file):
|
||
os.remove(tmp_file)
|
||
except Exception:
|
||
pass
|
||
except subprocess.CalledProcessError as e:
|
||
# 特殊处理adb错误
|
||
if e.returncode == 4294967295:
|
||
_ops_log(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})")
|
||
else:
|
||
_ops_log(f"[截图] exec-out 异常:{e}")
|
||
except Exception as e:
|
||
# 继续回退/重试
|
||
_ops_log(f"[截图] exec-out 异常:{e}")
|
||
try:
|
||
if os.path.exists(tmp_file):
|
||
os.remove(tmp_file)
|
||
except Exception:
|
||
pass
|
||
|
||
# 回退方案:老式 shell screencap + pull(兼容极少数不支持 exec-out 的环境)
|
||
try:
|
||
# 测量设备端生成与传输两部分耗时,分别记录
|
||
t_shell_start = time.time()
|
||
subprocess.run(
|
||
[
|
||
adb,
|
||
"-s",
|
||
device_id,
|
||
"shell",
|
||
"screencap",
|
||
"-p",
|
||
"/sdcard/DCIM/screenshot.png",
|
||
],
|
||
stdout=subprocess.DEVNULL,
|
||
stderr=subprocess.DEVNULL,
|
||
check=True,
|
||
timeout=10, # 添加超时
|
||
)
|
||
t_shell_end = time.time()
|
||
t_pull_start = time.time()
|
||
subprocess.run(
|
||
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file],
|
||
stdout=subprocess.DEVNULL,
|
||
stderr=subprocess.DEVNULL,
|
||
check=True,
|
||
timeout=10, # 添加超时
|
||
)
|
||
t_pull_end = time.time()
|
||
shell_ms = (t_shell_end - t_shell_start) * 1000
|
||
pull_ms = (t_pull_end - t_pull_start) * 1000
|
||
timetag3 = datetime.now().strftime("%H:%M:%S")
|
||
_ops_log(f"[{timetag3}] [DEBUG] shell_screencap: {shell_ms:.0f}ms, pull: {pull_ms:.0f}ms (device_id={device_id})")
|
||
if _valid_png(tmp_file):
|
||
# 使用安全的文件替换函数
|
||
if _safe_replace_file(tmp_file, out_file):
|
||
_mirror_screenshot_to_external(out_file)
|
||
elapsed = (time.time() - direct_start) * 1000
|
||
_ops_log(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (回退方案,耗时: {elapsed:.0f}ms)")
|
||
return True
|
||
else:
|
||
_ops_log("[截图] 回退方案文件替换失败")
|
||
return False
|
||
else:
|
||
_ops_log("[截图] 回退方案截图无效")
|
||
return False
|
||
except subprocess.CalledProcessError as e:
|
||
# 特殊处理adb错误
|
||
if e.returncode == 4294967295:
|
||
_ops_log(f"[截图] 回退方案失败:设备连接失败或ADB服务异常 (设备ID: {device_id})")
|
||
else:
|
||
_ops_log(f"[截图] 回退方案失败:ADB命令错误 (返回码: {e.returncode})")
|
||
except subprocess.TimeoutExpired:
|
||
_ops_log(f"[截图] 回退方案失败:操作超时 (设备ID: {device_id})")
|
||
except Exception as e:
|
||
_ops_log(f"[截图] 回退方案失败:{e}")
|
||
return False
|
||
|
||
def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]:
|
||
"""根据图片名称查找图片路径。
|
||
|
||
参数:
|
||
picname: 图片文件名
|
||
for_reading: 是否用于读取(决定搜索的目录顺序)
|
||
|
||
返回:
|
||
图片的完整路径,如果未找到则返回 None
|
||
"""
|
||
# 搜索目录优先级
|
||
try:
|
||
from douyin.core import path_config
|
||
pic_dir = path_config.get_pic_dir()
|
||
except Exception:
|
||
from douyin.core import path_config
|
||
pic_dir = path_config.get_pic_dir()
|
||
|
||
search_dirs = []
|
||
if for_reading:
|
||
# 读取时优先搜索当前目录的pic文件夹
|
||
search_dirs = [
|
||
pic_dir,
|
||
os.path.join(os.path.dirname(__file__), "target_pic"),
|
||
os.path.dirname(__file__), # 当前目录
|
||
]
|
||
else:
|
||
# 写入时优先使用pic目录
|
||
search_dirs = [
|
||
pic_dir,
|
||
]
|
||
|
||
# 尝试在每个目录中查找文件
|
||
for search_dir in search_dirs:
|
||
if not os.path.exists(search_dir):
|
||
continue
|
||
|
||
pic_path = os.path.join(search_dir, picname)
|
||
if os.path.exists(pic_path):
|
||
return pic_path
|
||
|
||
return None
|
||
|
||
def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target="", name=""):
|
||
"""裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。"""
|
||
# 这里应该实现图片裁剪逻辑
|
||
# 暂时从原文件导入以保持功能
|
||
from douyin.core.underlying_operations import underlying_operations
|
||
instance = underlying_operations()
|
||
return instance.cut_pic(left_up, right_down, target, name)
|
||
|
||
def save_reward_pic(self, device_id):
|
||
"""保存奖励图片"""
|
||
# 这里应该实现奖励图片保存逻辑
|
||
# 暂时从原文件导入以保持功能
|
||
from douyin.core.underlying_operations import underlying_operations
|
||
instance = underlying_operations()
|
||
return instance.save_reward_pic(device_id)
|
||
|
||
|
||
# 全局截图操作实例
|
||
_screenshot_ops = ScreenshotOperations()
|
||
|
||
|
||
def get_screenshot(device_id, path="pic", use_service: bool = False) -> bool:
|
||
"""获取屏幕截图(向后兼容接口)"""
|
||
return _screenshot_ops.get_screenshot(device_id, path, use_service=use_service)
|
||
|
||
|
||
def _find_pic_path(picname: str, for_reading: bool = True) -> Optional[str]:
|
||
"""查找图片路径(向后兼容接口)"""
|
||
return _screenshot_ops._find_pic_path(picname, for_reading)
|
||
|
||
|
||
def cut_pic(left_up=(0, 63), right_down=(1080, 1620), target="", name=""):
|
||
"""裁剪图片(向后兼容接口)"""
|
||
return _screenshot_ops.cut_pic(left_up, right_down, target, name)
|
||
|
||
|
||
def save_reward_pic(device_id):
|
||
"""保存奖励图片(向后兼容接口)"""
|
||
return _screenshot_ops.save_reward_pic(device_id)
|
||
|
||
|
||
__all__ = [
|
||
"ScreenshotOperations",
|
||
"get_screenshot",
|
||
"_find_pic_path",
|
||
"cut_pic",
|
||
"save_reward_pic",
|
||
]
|