chore: Remove obsolete scripts and enhance path configuration

- Deleted `check_md_files.py` and `fix_cursor_md_issue.py` as they are no longer needed.
- Added new functions in `path_config.py` for better path management, including actions log and run_cli paths.
- Updated various modules to utilize the new path configuration, ensuring consistency and maintainability across the project.
This commit is contained in:
Your Name committed 2025-12-28 20:55:34 +08:00
1 parent b9849b9f5a
commit bdf9312bc9
58 files changed
+2472 -854

No files matched your search

+255 -21
View File
@@ -220,6 +220,8 @@ class underlying_operations:
# 支持延迟初始化(测试流程/只做点击时不需要 OCR)。
self.ocr: Any = None
self.ocr_type = None # 'easyocr' 或 'paddleocr'
# 用于存储OCR区域的坐标信息(key为picname,value为(left, top, right, bottom))
self._ocr_coords_cache: dict[str, tuple[int, int, int, int]] = {}
# 检测GPU是否可用(自动检测)
self._gpu_available = self._detect_gpu_available()
@@ -495,8 +497,12 @@ class underlying_operations:
Returns:
图片的完整路径,如果找不到且for_reading=True则返回None
"""
base_dir = os.path.dirname(__file__)
pic_base = os.path.join(base_dir, "pic")
try:
import path_config
pic_base = path_config.get_pic_dir()
except Exception:
import path_config
pic_base = path_config.get_pic_dir()
# 运行时必需文件始终在根目录(不需要移动)
runtime_files = {"screenshot", "cut"}
@@ -536,7 +542,12 @@ class underlying_operations:
def get_screenshot(self, device_id, path="pic"):
"""截图3个adb命令需要2S左右的时间"""
if path == "pic":
out_dir = os.path.join(os.path.dirname(__file__), "pic")
try:
import path_config
out_dir = path_config.get_pic_dir()
except Exception:
import path_config
out_dir = path_config.get_pic_dir()
else:
out_dir = os.path.join(os.path.dirname(__file__), "target_pic")
if not os.path.exists(out_dir):
@@ -756,7 +767,12 @@ class underlying_operations:
raise ValueError("Could not find resolution in adb output")
def save_reward_pic(self, device_id):
out_dir = os.path.join(os.path.dirname(__file__), "pic")
try:
import path_config
out_dir = path_config.get_pic_dir()
except Exception:
import path_config
out_dir = path_config.get_pic_dir()
if not os.path.exists(out_dir):
os.makedirs(out_dir)
timepic = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
@@ -891,6 +907,13 @@ class underlying_operations:
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
# 存储坐标信息供analyse_pic_word使用
if name:
try:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
# 双截图记录:保存实时操作截图
try:
from douyin.handlers import douyin_screenshot_manager
@@ -899,9 +922,10 @@ class underlying_operations:
cropped_img, operation_type="cut_pic"
)
# 保存调试图像(带详细信息)
# 保存调试图像(完整截图+区域标注)
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
cropped_img,
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
@@ -987,12 +1011,20 @@ class underlying_operations:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
return False
# 保存调试图像
# 存储坐标信息供analyse_pic_word使用
if name:
try:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
# 保存调试图像(完整截图+区域标注)
try:
from douyin.handlers import douyin_screenshot_manager
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
cropped_img,
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
@@ -1089,19 +1121,43 @@ class underlying_operations:
except Exception:
img1 = img # Fallback to original image
# 保存预处理后的调试图像(OCR前)
# 保存预处理后的调试图像(OCR前)- 使用完整截图
try:
from douyin.handlers import douyin_screenshot_manager
import path_config
# 尝试获取OCR区域坐标
ocr_coords = None
try:
ocr_coords = self._ocr_coords_cache.get(picname)
except Exception:
pass
# 加载完整截图
full_screenshot = None
try:
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
full_screenshot = Image.open(screenshot_path)
full_screenshot.load()
full_screenshot = full_screenshot.convert("RGB")
except Exception:
pass
# 如果成功加载完整截图,使用完整截图;否则使用预处理图像
debug_image = full_screenshot if full_screenshot is not None else img1
debug_path = douyin_screenshot_manager.save_debug_image(
img1,
debug_image,
operation_type="ocr",
picname=picname,
step="preprocessed",
coords=ocr_coords,
extra_info={
"mode": change_color,
"size": f"{w}x{h}",
"source": pic_path if pic_path else picname,
"has_full_screenshot": full_screenshot is not None,
"has_coords": ocr_coords is not None,
},
)
if debug_path:
@@ -1202,7 +1258,7 @@ class underlying_operations:
img_for_attempt, operation_type="ocr"
)
# 保存OCR结果后的调试图像(带OCR文本结果和置信度)
# 保存OCR结果后的调试图像(带OCR文本结果和置信度)- 使用完整截图
ocr_result_preview = (
(text or text2 or "").strip()[:50] if (text or text2) else ""
)
@@ -1227,11 +1283,36 @@ class underlying_operations:
"item_count", 0
)
# 尝试获取OCR区域坐标
ocr_coords = None
try:
ocr_coords = self._ocr_coords_cache.get(picname)
except Exception:
pass
# 加载完整截图
full_screenshot = None
try:
import path_config
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
full_screenshot = Image.open(screenshot_path)
full_screenshot.load()
full_screenshot = full_screenshot.convert("RGB")
except Exception:
pass
# 如果成功加载完整截图,使用完整截图;否则使用预处理图像
debug_image = full_screenshot if full_screenshot is not None else img_for_attempt
extra_info_dict["has_full_screenshot"] = full_screenshot is not None
extra_info_dict["has_coords"] = ocr_coords is not None
debug_path = douyin_screenshot_manager.save_debug_image(
img_for_attempt,
debug_image,
operation_type="ocr",
picname=picname,
step="after_ocr",
coords=ocr_coords,
extra_info=extra_info_dict,
)
@@ -1358,29 +1439,172 @@ class underlying_operations:
# 锐化处理,提高数字识别准确率
from PIL import ImageEnhance
img1 = img
try:
img_sharpened = img.filter(
ImageFilter.UnsharpMask(radius=1, percent=200, threshold=3)
)
enhancer = ImageEnhance.Contrast(img_sharpened)
img = enhancer.enhance(1.3) # 更高的对比度
img1 = enhancer.enhance(1.3) # 更高的对比度
except Exception:
try:
img = img.filter(ImageFilter.SHARPEN)
img1 = img.filter(ImageFilter.SHARPEN)
except Exception:
img1 = img # Fallback to original image
# 保存预处理后的调试图像(OCR前)- 使用完整截图
try:
from douyin.handlers import douyin_screenshot_manager
import path_config
# 尝试获取OCR区域坐标
ocr_coords = None
try:
ocr_coords = self._ocr_coords_cache.get(picname)
except Exception:
pass
img_np = np.array(img)
# 加载完整截图
full_screenshot = None
try:
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
full_screenshot = Image.open(screenshot_path)
full_screenshot.load()
full_screenshot = full_screenshot.convert("RGB")
except Exception:
pass
# 如果成功加载完整截图,使用完整截图;否则使用预处理图像
debug_image = full_screenshot if full_screenshot is not None else img1
debug_path = douyin_screenshot_manager.save_debug_image(
debug_image,
operation_type="ocr",
picname=picname,
step="preprocessed",
coords=ocr_coords,
extra_info={
"mode": change_color,
"size": f"{w}x{h}",
"source": pic_path if pic_path else picname,
"has_full_screenshot": full_screenshot is not None,
"has_coords": ocr_coords is not None,
"type": "digits",
},
)
if debug_path:
try:
logging.info(f"[调试图像] OCR数字预处理保存: {debug_path}")
except Exception:
pass
except Exception:
pass
img_np = np.array(img1)
# 使用OCR识别(与analyse_pic_word相同的OCR引擎)
ocr_confidence_info = None
if getattr(self, "ocr_type", None) == "easyocr":
result = self.ocr.readtext(img_np)
text = self.extract_ocr_content(result)
extract_result = self.extract_ocr_content(result, return_confidence=True)
if isinstance(extract_result, tuple):
text, ocr_confidence_info = extract_result
else:
text = extract_result
else:
result = self.ocr.ocr(img_np)
if result == [None]:
return ""
text = self.extract_ocr_content(result)
extract_result = self.extract_ocr_content(result, return_confidence=True)
if isinstance(extract_result, tuple):
text, ocr_confidence_info = extract_result
else:
text = extract_result
# 保存OCR结果后的调试图像(带OCR文本结果和置信度)- 使用完整截图
try:
from douyin.handlers import douyin_screenshot_manager
import path_config
# 尝试获取OCR区域坐标
ocr_coords = None
try:
ocr_coords = self._ocr_coords_cache.get(picname)
except Exception:
pass
# 加载完整截图
full_screenshot = None
try:
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
full_screenshot = Image.open(screenshot_path)
full_screenshot.load()
full_screenshot = full_screenshot.convert("RGB")
except Exception:
pass
# 如果成功加载完整截图,使用完整截图;否则使用预处理图像
debug_image = full_screenshot if full_screenshot is not None else img1
# 准备额外信息
digits_result = ""
if text:
digits_result = "".join(ch for ch in str(text) if ch.isdigit())
extra_info_dict = {
"mode": change_color,
"text_len": len(text or ""),
"digits": digits_result,
"type": "digits",
}
# 添加置信度信息
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["has_full_screenshot"] = full_screenshot is not None
extra_info_dict["has_coords"] = ocr_coords is not None
debug_path = douyin_screenshot_manager.save_debug_image(
debug_image,
operation_type="ocr",
picname=picname,
step="after_ocr",
coords=ocr_coords,
extra_info=extra_info_dict,
)
# 记录OCR置信度到日志
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)}"
)
except Exception:
pass
if debug_path:
try:
logging.info(
f"[调试图像] OCR数字结果保存: {debug_path}, 数字: {digits_result}"
)
except Exception:
pass
except Exception:
pass
# 只提取数字字符,并进行智能过滤
if text:
@@ -1817,14 +2041,14 @@ class underlying_operations:
left_up_y=0,
right_down_x=1080,
right_down_y=1500,
steps=200,
steps=300,
):
"""划动屏幕
参数说明:
- left_up_x, left_up_y: 滑动起始位置(手指按下位置)
- right_down_x, right_down_y: 滑动结束位置(手指抬起位置)
- steps: 滑动步数(影响滑动速度,数值越大滑动越慢)
- steps: 滑动持续时间(毫秒),数值越大滑动越慢,默认300ms(已优化,比之前的200ms更快)
执行命令:adb shell input swipe <start_x> <start_y> <end_x> <end_y> <duration_ms>
"""
@@ -2401,7 +2625,12 @@ class underlying_operations:
if not text:
return False
local_path = os.path.join(os.path.dirname(__file__), "pic", "window_dump.xml")
try:
import path_config
local_path = path_config.get_window_dump_path()
except Exception:
import path_config
local_path = path_config.get_window_dump_path()
start = time.time()
while True:
if self._uiautomator_dump(device_id, local_path):
@@ -2447,7 +2676,12 @@ class underlying_operations:
逻辑:从 uiautomator dump 里找顶部(较小 y)的可点击小图标,优先命中 content-desc/text 含“关闭/退出/返回”。
如果没有文字,就在顶部区域按“最像关闭”的位置进行启发式选择。
"""
local_path = os.path.join(os.path.dirname(__file__), "pic", "window_dump.xml")
try:
import path_config
local_path = path_config.get_window_dump_path()
except Exception:
import path_config
local_path = path_config.get_window_dump_path()
start = time.time()
def _score(node_attrib: dict, bounds_tuple) -> int: