feat: Refactor and reorganize project structure with new modules and files

- Deleted obsolete files including test scripts and configuration files to streamline the project.
- Introduced new modules for handling Douyin functionalities, including core operations, logging, and GUI components.
- Updated import paths to reflect the new module structure, enhancing code organization and maintainability.
- Added configuration files and documentation to support the new structure and improve user guidance.
This commit is contained in:
Your Name committed 2025-12-28 14:16:40 +08:00
1 parent ea7159355b
commit c67f22f76f
139 files changed
+7571 -7828

No files matched your search

+145 -94
View File
@@ -208,10 +208,10 @@ class underlying_operations:
# 支持延迟初始化(测试流程/只做点击时不需要 OCR)。
self.ocr: Any = None
self.ocr_type = None # 'easyocr' 或 'paddleocr'
# 检测GPU是否可用(自动检测)
self._gpu_available = self._detect_gpu_available()
if not str(os.environ.get("SKIP_OCR_INIT", "")).strip():
# 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR
# 首先尝试EasyOCR
@@ -221,7 +221,7 @@ class underlying_operations:
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
devnull
):
import easyocr # type: ignore[import-untyped]
import easyocr # type: ignore[import-untyped] # pyright: ignore[reportMissingImports]
# 只加载中文和英文,加快初始化速度
# 自动检测GPU可用性,如果可用则启用GPU加速
@@ -252,11 +252,15 @@ class underlying_operations:
use_gpu = False
try:
import paddle
if paddle.device.is_compiled_with_cuda() and paddle.device.get_device():
if (
paddle.device.is_compiled_with_cuda()
and paddle.device.get_device()
):
use_gpu = self._gpu_available
except Exception:
pass
self.ocr = PaddleOCR(
lang="ch",
ocr_version="PP-OCRv4",
@@ -311,19 +315,24 @@ class underlying_operations:
def _detect_gpu_available(self) -> bool:
"""检测GPU是否可用
默认返回False(CPU模式),除非通过环境变量明确启用GPU
返回:
True: GPU可用且已启用
False: 使用CPU模式(默认)
"""
# 默认使用CPU模式,除非环境变量明确要求使用GPU
# 检查环境变量是否强制启用GPU
if str(os.environ.get("FORCE_GPU_OCR", "")).strip().lower() in ("1", "true", "yes"):
if str(os.environ.get("FORCE_GPU_OCR", "")).strip().lower() in (
"1",
"true",
"yes",
):
# 强制启用时,验证GPU是否真的可用
try:
import torch # type: ignore[import-untyped]
if torch.cuda.is_available():
gpu_name = torch.cuda.get_device_name(0)
print(f"[OCR] 环境变量强制启用GPU: {gpu_name},将使用GPU加速")
@@ -337,17 +346,17 @@ class underlying_operations:
except Exception as e:
print(f"[OCR] GPU检测失败: {e},使用CPU模式")
return False
# 默认使用CPU模式
return False
def _ensure_ocr(self):
if self.ocr is not None:
return
# 重新检测GPU(延迟初始化时)
self._gpu_available = self._detect_gpu_available()
# 优先尝试EasyOCR
devnull = None
try:
@@ -357,7 +366,9 @@ class underlying_operations:
):
import easyocr # type: ignore[import-untyped]
self.ocr = easyocr.Reader(["ch_sim", "en"], gpu=self._gpu_available, verbose=False)
self.ocr = easyocr.Reader(
["ch_sim", "en"], gpu=self._gpu_available, verbose=False
)
self.ocr_type = "easyocr"
gpu_status = "GPU加速" if self._gpu_available else "CPU模式"
print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})")
@@ -382,11 +393,15 @@ class underlying_operations:
use_gpu = False
try:
import paddle
if paddle.device.is_compiled_with_cuda() and paddle.device.get_device():
if (
paddle.device.is_compiled_with_cuda()
and paddle.device.get_device()
):
use_gpu = self._gpu_available
except Exception:
pass
self.ocr = PaddleOCR(
lang="ch",
ocr_version="PP-OCRv4",
@@ -479,7 +494,7 @@ class underlying_operations:
# OCR图片文件:按分类组织到子目录
try:
import douyin_screenshot_manager
from douyin.handlers import douyin_screenshot_manager
category = douyin_screenshot_manager.get_category_for_picname(picname)
except Exception:
@@ -866,12 +881,12 @@ class underlying_operations:
# 双截图记录:保存实时操作截图
try:
import douyin_screenshot_manager
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
cropped_img, operation_type="cut_pic"
)
# 保存调试图像(带详细信息)
debug_path = douyin_screenshot_manager.save_debug_image(
cropped_img,
@@ -881,8 +896,8 @@ class underlying_operations:
coords=(left, top, right, bottom),
extra_info={
"source": "screenshot.png",
"size": f"{right-left}x{bottom-top}"
}
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
@@ -959,10 +974,11 @@ class underlying_operations:
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
return False
# 保存调试图像
try:
import douyin_screenshot_manager
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
cropped_img,
operation_type="cut_pic",
@@ -971,8 +987,8 @@ class underlying_operations:
coords=(left, top, right, bottom),
extra_info={
"source": target + "/screenshot.png",
"size": f"{right-left}x{bottom-top}"
}
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
@@ -981,7 +997,7 @@ class underlying_operations:
pass
except Exception:
pass
return True
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
@@ -1063,7 +1079,8 @@ class underlying_operations:
# 保存预处理后的调试图像(OCR前)
try:
import douyin_screenshot_manager
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
img1,
operation_type="ocr",
@@ -1072,8 +1089,8 @@ class underlying_operations:
extra_info={
"mode": change_color,
"size": f"{w}x{h}",
"source": pic_path if pic_path else picname
}
"source": pic_path if pic_path else picname,
},
)
if debug_path:
try:
@@ -1087,7 +1104,7 @@ class underlying_operations:
# 用于收集置信度信息
ocr_confidence_info = None
if getattr(self, "ocr_type", None) == "easyocr":
result = self.ocr.readtext(img_np)
extract_result = self.extract_ocr_content(result, return_confidence=True)
@@ -1161,7 +1178,7 @@ class underlying_operations:
pass
try:
import douyin_screenshot_manager
from douyin.handlers import douyin_screenshot_manager
# Ensure img1 is defined before use
if "img1" not in locals():
@@ -1172,30 +1189,40 @@ class underlying_operations:
douyin_screenshot_manager.save_latest_attempt(
img_for_attempt, operation_type="ocr"
)
# 保存OCR结果后的调试图像(带OCR文本结果和置信度)
ocr_result_preview = (text or text2 or "").strip()[:50] if (text or text2) else ""
ocr_result_preview = (
(text or text2 or "").strip()[:50] if (text or text2) else ""
)
extra_info_dict = {
"mode": change_color,
"text_len": len(text or text2 or ""),
"text_preview": ocr_result_preview,
"used_img2": bool(img2 is not None and text2 and text2.strip())
"used_img2": bool(img2 is not None and text2 and text2.strip()),
}
# 添加置信度信息
if ocr_confidence_info:
extra_info_dict["avg_confidence"] = round(ocr_confidence_info.get("avg_confidence", 0.0), 4)
extra_info_dict["min_confidence"] = round(ocr_confidence_info.get("min_confidence", 0.0), 4)
extra_info_dict["max_confidence"] = round(ocr_confidence_info.get("max_confidence", 0.0), 4)
extra_info_dict["confidence_items"] = ocr_confidence_info.get("item_count", 0)
extra_info_dict["avg_confidence"] = round(
ocr_confidence_info.get("avg_confidence", 0.0), 4
)
extra_info_dict["min_confidence"] = round(
ocr_confidence_info.get("min_confidence", 0.0), 4
)
extra_info_dict["max_confidence"] = round(
ocr_confidence_info.get("max_confidence", 0.0), 4
)
extra_info_dict["confidence_items"] = ocr_confidence_info.get(
"item_count", 0
)
debug_path = douyin_screenshot_manager.save_debug_image(
img_for_attempt,
operation_type="ocr",
picname=picname,
step="after_ocr",
extra_info=extra_info_dict
extra_info=extra_info_dict,
)
# 记录OCR置信度到日志
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
try:
@@ -1210,7 +1237,9 @@ class underlying_operations:
pass
if debug_path:
try:
logging.info(f"[调试图像] OCR结果保存: {debug_path}, 文本: {ocr_result_preview}")
logging.info(
f"[调试图像] OCR结果保存: {debug_path}, 文本: {ocr_result_preview}"
)
except Exception:
pass
except Exception:
@@ -1219,7 +1248,7 @@ class underlying_operations:
if text and text.strip() and picname:
try:
try:
import douyin_screenshot_manager
from douyin.handlers import douyin_screenshot_manager
category = douyin_screenshot_manager.get_category_for_picname(
picname
@@ -1242,7 +1271,7 @@ class underlying_operations:
else:
img_to_save = img1
try:
import douyin_screenshot_manager
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_last_success(
img_to_save, operation_type="ocr"
@@ -1263,12 +1292,12 @@ class underlying_operations:
def analyse_pic_digits(self, picname, change_color=1, pic_path=None):
"""轻量数字OCR识别函数,专门用于识别数字(0-9)。
相比analyse_pic_word,这个函数:
1. 使用二值化预处理(change_color=1),更适合数字识别
2. 只提取数字字符,忽略其他字符
3. 使用更轻量的OCR配置(如果支持)
参数:
picname: 用于分类和调试的图片名(如"福袋价值")
change_color: 颜色处理模式,默认1=二值化(更适合数字)
@@ -1316,6 +1345,7 @@ class underlying_operations:
# 锐化处理,提高数字识别准确率
from PIL import ImageEnhance
try:
img_sharpened = img.filter(
ImageFilter.UnsharpMask(radius=1, percent=200, threshold=3)
@@ -1344,7 +1374,7 @@ class underlying_operations:
if text:
# 提取所有数字字符
digits = "".join(ch for ch in str(text) if ch.isdigit())
# 智能过滤:如果识别到的数字太多(可能是识别到了文件名或坐标),
# 尝试提取合理的数字段
if len(digits) > 10:
@@ -1353,53 +1383,60 @@ class underlying_operations:
# 尝试提取最后几个数字(通常是实际值)
# 或者提取最短的连续数字段
import re
# 提取所有连续的数字段
digit_segments = re.findall(r'\d+', str(text))
digit_segments = re.findall(r"\d+", str(text))
if digit_segments:
# 对于价值,选择最大的合理数字段(不超过6位)
# 对于倒计时,选择1-2位的数字段
# 这里先返回所有数字,让调用方处理
# 但优先选择较短的段(1-6位)
reasonable_segments = [s for s in digit_segments if 1 <= len(s) <= 6]
reasonable_segments = [
s for s in digit_segments if 1 <= len(s) <= 6
]
if reasonable_segments:
# 如果有多段,优先选择较短的(倒计时)或较长的(价值)
# 这里返回最长的合理段(通常是价值)
return max(reasonable_segments, key=len)
else:
# 如果没有合理段,返回最短的段
return min(digit_segments, key=len) if digit_segments else digits[:6]
return (
min(digit_segments, key=len)
if digit_segments
else digits[:6]
)
return digits
return ""
def extract_ocr_content(self, content=[], return_confidence=False):
"""对OCR识别到的内容进行取值和拼接,变成完整的一段内容
参数:
content: OCR识别结果
return_confidence: 是否返回置信度信息(默认False,保持向后兼容)
返回:
如果return_confidence=False: 返回文本字符串
如果return_confidence=True: 返回(text, confidence_info)元组,其中confidence_info是置信度信息字典
"""
ocr_result = content
# 用于收集置信度信息
confidence_scores = []
confidence_info = {
"avg_confidence": 0.0,
"min_confidence": 1.0,
"max_confidence": 0.0,
"item_count": 0
"item_count": 0,
}
def _extract_text_and_confidence_from_item(item):
"""提取文本和置信度"""
text = ""
confidence = None
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
if isinstance(item, (list, tuple)) and len(item) >= 2:
# EasyOCR格式:item = (bbox, text, confidence),text在索引1,confidence在索引2
@@ -1546,11 +1583,11 @@ class underlying_operations:
# 按从上到下、从左到右排序;解决同一行多个框的乱序拼接(例如倒计时两段数字)
extracted_items.sort(key=lambda t: (t[0], t[1]))
# 如果不需要返回置信度,直接返回文本(保持向后兼容)
if not return_confidence:
return "".join([t[2] for t in extracted_items])
# 如果需要返回置信度,提取置信度信息
if return_confidence:
for item in items:
@@ -1565,24 +1602,30 @@ class underlying_operations:
confidence = second[1]
elif isinstance(second, dict):
confidence = second.get("confidence") or second.get("score")
if confidence is not None:
try:
conf_float = float(confidence)
confidence_scores.append(conf_float)
confidence_info["min_confidence"] = min(confidence_info["min_confidence"], conf_float)
confidence_info["max_confidence"] = max(confidence_info["max_confidence"], conf_float)
confidence_info["min_confidence"] = min(
confidence_info["min_confidence"], conf_float
)
confidence_info["max_confidence"] = max(
confidence_info["max_confidence"], conf_float
)
except (ValueError, TypeError):
pass
if confidence_scores:
confidence_info["avg_confidence"] = sum(confidence_scores) / len(confidence_scores)
confidence_info["avg_confidence"] = sum(confidence_scores) / len(
confidence_scores
)
confidence_info["item_count"] = len(confidence_scores)
else:
confidence_info["min_confidence"] = 0.0
return "".join([t[2] for t in extracted_items]), confidence_info
return "".join([t[2] for t in extracted_items])
def delay(self, seconds: float = 1):
@@ -1765,20 +1808,21 @@ class underlying_operations:
steps=200,
):
"""划动屏幕
参数说明:
- left_up_x, left_up_y: 滑动起始位置(手指按下位置)
- right_down_x, right_down_y: 滑动结束位置(手指抬起位置)
- steps: 滑动步数(影响滑动速度,数值越大滑动越慢)
执行命令:adb shell input swipe <start_x> <start_y> <end_x> <end_y> <duration_ms>
"""
import subprocess
adb_cmd = self._adb()
# 注意:adb input swipe 的参数顺序是:start_x start_y end_x end_y duration_ms
# 这里 left_up_x/y 是起始位置,right_down_x/y 是结束位置
cmd = f"{adb_cmd} -s {device_id} shell input swipe {left_up_x} {left_up_y} {right_down_x} {right_down_y} {steps}"
try:
# 使用 subprocess 执行命令,捕获错误输出
result = subprocess.run(
@@ -1789,29 +1833,32 @@ class underlying_operations:
timeout=5.0,
text=True,
)
# 检查是否有权限错误
stderr_text = result.stderr if result.stderr else ""
has_permission_error = (
result.returncode != 0
and ("SecurityException" in stderr_text
or "INJECT_EVENTS" in stderr_text
or "Injecting to another application" in stderr_text)
has_permission_error = result.returncode != 0 and (
"SecurityException" in stderr_text
or "INJECT_EVENTS" in stderr_text
or "Injecting to another application" in stderr_text
)
if has_permission_error:
# 尝试使用 uiautomator(如果可用,某些设备可能支持)
try:
self._swipe_with_uiautomator(device_id, left_up_x, left_up_y, right_down_x, right_down_y)
self._swipe_with_uiautomator(
device_id, left_up_x, left_up_y, right_down_x, right_down_y
)
return
except Exception:
pass
# 记录错误但不抛出异常,避免中断主流程
error_msg = stderr_text.strip() if stderr_text else "权限不足"
print(f"[警告] 滑动操作失败: {error_msg}")
print(f"[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
print(f" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'")
print(
f" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'"
)
print(f" 2. 使用已 root 的设备")
print(f" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
# 不抛出异常,让程序继续运行(可能只是滑动失败,其他功能仍可用)
@@ -1823,12 +1870,12 @@ class underlying_operations:
os.system(cmd)
except Exception:
print(f"[警告] 滑动操作失败: {type(e).__name__}: {e}")
def _swipe_with_sendevent(self, device_id, x1, y1, x2, y2, steps):
"""使用 sendevent 方法滑动(需要 root 权限)"""
import subprocess
import time
# 获取触摸设备路径
result = subprocess.run(
f"{self._adb()} -s {device_id} shell getevent -p | grep -A 5 ABS_MT",
@@ -1837,25 +1884,27 @@ class underlying_operations:
stderr=subprocess.DEVNULL,
text=True,
)
if "event" not in result.stdout.lower():
raise Exception("无法找到触摸设备")
# 简化实现:直接使用 input 命令的替代参数
# 注意:sendevent 需要 root 权限,这里只是尝试
raise Exception("sendevent 需要 root 权限,暂不支持")
def _swipe_with_uiautomator(self, device_id, x1, y1, x2, y2):
"""使用 uiautomator 滑动(如果可用)
注意:uiautomator 在某些设备上可能也需要权限,但可以尝试作为备选方案。
"""
import subprocess
# 使用 uiautomator swipe 命令
# 注意:uiautomator 命令格式可能因 Android 版本而异
# Android 5.0+: uiautomator swipe <x1> <y1> <x2> <y2> [steps]
cmd = f"{self._adb()} -s {device_id} shell uiautomator swipe {x1} {y1} {x2} {y2}"
cmd = (
f"{self._adb()} -s {device_id} shell uiautomator swipe {x1} {y1} {x2} {y2}"
)
result = subprocess.run(
cmd,
shell=True,
@@ -1863,20 +1912,22 @@ class underlying_operations:
stderr=subprocess.PIPE,
timeout=5.0,
)
if result.returncode != 0:
raise Exception(f"uiautomator swipe 失败: {result.stderr.decode('utf-8', errors='ignore')}")
raise Exception(
f"uiautomator swipe 失败: {result.stderr.decode('utf-8', errors='ignore')}"
)
def _swipe_with_sendevent_improved(self, device_id, x1, y1, x2, y2, steps=50):
"""使用 sendevent 方法滑动(需要 root 权限)
这是更底层的触摸事件模拟方式,通过直接向 /dev/input/eventX 写入事件。
优点:绕过部分权限检查
缺点:需要 root 权限,实现复杂,不同设备的事件格式可能不同
"""
import subprocess
import time
# 获取触摸设备路径(通常是 /dev/input/eventX)
result = subprocess.run(
f"{self._adb()} -s {device_id} shell getevent -p 2>/dev/null | grep -A 10 ABS_MT",
@@ -1886,22 +1937,22 @@ class underlying_operations:
text=True,
timeout=3.0,
)
# 解析设备路径(简化版,实际需要更复杂的解析)
# 这里只是示例,完整实现需要:
# 1. 解析 getevent -p 输出找到触摸设备
# 2. 计算触摸事件的坐标范围(ABS_MT_POSITION_X/Y 的 min/max)
# 3. 将屏幕坐标转换为设备坐标
# 4. 发送 DOWN -> MOVE -> UP 事件序列
if "event" not in result.stdout.lower():
raise Exception("无法找到触摸设备(需要 root 权限)")
# 注意:完整的 sendevent 实现非常复杂,需要:
# - 设备特定的坐标转换
# - 正确的事件序列(SYN_REPORT 等)
# - 不同 Android 版本的事件格式可能不同
raise Exception("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
def click(self, device_id, x=500, y=500):