refactor(underlying): 抽 cut_pic 图片裁剪到 image_ops (1574 → 1327)

underlying_operations.cut_pic L474-721 是 248 行图片裁剪管道:
- 默认/命名两个分支共享重试 3 次的截图加载验证
- 默认分支裁出 cut.png 或 ocr/<name>.png;命名分支裁出 pic/<target>/<name>.png
- 写入 _ocr_coords_cache 供 analyse_pic_word 调试图像引用
- SAVE_CUT_PIC_DEBUG_IMAGES=1 时保存 cut_pic 调试图

抽到 underlying_operations_pkg/image_ops.py:
- cut_pic(self, left_up, right_down, target, name) -> bool
- _ensure_parent_dir / _validate_coords / _save_cut_debug_images 内部 helper

主类方法替换为 4 行委托。

更新两个旧的源码断言测试以适配抽离:
- test_cut_pic_path:从 inspect.getsource(op.cut_pic) 改为读 image_ops.py 文件源码
- test_runtime_path_anchors:把 path_config.get_pic_dir() 检查范围从单一文件
  扩展到 underlying_operations.py + image_ops.py + ocr_pipeline.py 三处

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-23 02:43:36 +08:00
1 parent 8457219241
commit e46497ea80
4 files changed
+305 -258

No files matched your search

+5 -247
View File
@@ -472,253 +472,11 @@ class underlying_operations:
def save_reward_pic(self, device_id):
return _impl_save_reward_pic(device_id)
def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target="", name=""):
"""裁剪图片,获取需要的区域小图片方便识别
添加了错误处理:
- 检查文件是否存在
- 验证图片完整性
- 重试机制(如果文件损坏)
- 异常处理避免程序崩溃
"""
max_retries = 3
retry_delay = 0.1
for attempt in range(max_retries):
try:
if target == "" or target == False:
from douyin.core import path_config
path = path_config.get_pic_dir()
pic1_path = path_config.get_screenshot_path()
# 检查文件是否存在
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
# 验证文件大小(至少应该有一些内容)
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
# 尝试打开并验证图片
try:
pic = Image.open(pic1_path)
# 验证图片完整性(通过访问尺寸属性)
_ = pic.size
# 确保图片已加载
pic.load()
except (SyntaxError, IOError, OSError) as e:
# 图片损坏,重试或返回False
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
# 最后一次尝试失败,让外层异常处理
raise
if name == "":
cut_pic_path = path + "/cut.png"
else:
# 使用新的路径查找方法(写入到新位置ocr/)
cut_pic_path = self._find_pic_path(name, for_reading=False)
# 验证裁剪坐标有效性
width, height = pic.size
left, top = left_up
right, bottom = right_down
if (
left < 0
or top < 0
or right > width
or bottom > height
or left >= right
or top >= bottom
):
raise ValueError(
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
)
cropped_img = pic.crop((left, top, right, bottom))
assert cut_pic_path is not None
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
# 存储坐标信息供analyse_pic_word使用
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
# 优化:只在明确启用调试模式时保存调试图像(减少I/O操作)
# 默认不保存,避免每次cut_pic都进行文件I/O操作(可节省50-200ms)
try:
# 检查是否启用调试图像保存
save_debug = (
os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1"
)
if not save_debug:
# 检查全局配置
try:
save_debug = (
os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1"
)
except Exception:
pass
if save_debug:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
cropped_img, operation_type="cut_pic"
)
# 保存调试图像(完整截图+区域标注)
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": "screenshot.png",
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.info(
"[调试图像] cut_pic保存: %s", debug_path
)
except Exception:
pass
except Exception:
pass
return True
else:
from douyin.core import path_config
path_target = os.path.join(path_config.get_pic_dir(), target)
pic1_path = os.path.join(path_target, "screenshot.png")
# 检查文件是否存在
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
# 验证文件大小
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
# 尝试打开并验证图片
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
# 图片损坏,重试或返回False
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
# 最后一次尝试失败,让外层异常处理
raise
if name == "":
cut_pic_path = path_target + "/cut.png"
else:
cut_pic_path = path_target + "/" + name + ".png"
# 验证裁剪坐标有效性
width, height = pic.size
left, top = left_up
right, bottom = right_down
if (
left < 0
or top < 0
or right > width
or bottom > height
or left >= right
or top >= bottom
):
error_msg = f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
if attempt == max_retries - 1:
_uo_log(f"[错误] {error_msg}")
return False
continue
assert cut_pic_path is not None
cropped_img = pic.crop((left, top, right, bottom))
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
return False
# 存储坐标信息供analyse_pic_word使用
if name:
try:
with self._ocr_coords_lock:
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(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": target + "/screenshot.png",
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
return True
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
# 裁剪或读取图片时发生错误,最后一次尝试失败则记录并返回 False
if attempt == max_retries - 1:
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
_uo_log(error_msg)
_uo_log(f" 源文件: {locals().get('pic1_path', 'N/A')}")
_uo_log(f" 目标文件: {locals().get('cut_pic_path', 'N/A')}")
return False
# 否则继续重试
continue
"""裁剪图片,获取需要的区域小图片方便识别。"""
from douyin.core.underlying_operations_pkg.image_ops import (
cut_pic as _impl,
)
return _impl(self, left_up, right_down, target, name)
def analyse_pic_word(
self, picname, change_color=0, pic_path=None, return_confidence=False
@@ -0,0 +1,270 @@
"""douyin/core/underlying_operations_pkg/image_ops - cut_pic 图片裁剪管道
把 underlying_operations.cut_pic 整段抽出来。流程:
- 默认分支(target=""):从项目根 pic/screenshot.png 读图,裁出 cut.png 或 ocr/<name>.png
- 命名分支(target="xxx"):从 pic/<target>/screenshot.png 读图,裁出 pic/<target>/<name>.png
- 重试 3 次(截图缺失/文件太小/PIL 损坏)
- 写入坐标缓存供 analyse_pic_word 调试图像用
- 可选保存 cut_pic 调试图(SAVE_CUT_PIC_DEBUG_IMAGES=1)
入口:cut_pic(self, left_up, right_down, target, name) -> bool
self 必须提供:_find_pic_path / _ocr_coords_lock / _ocr_coords_cache
"""
from __future__ import annotations
import logging
import os
import time as time_module
from typing import Any
from PIL import Image
def _ensure_parent_dir(path: str) -> None:
"""确保路径的父目录存在。"""
try:
parent = os.path.dirname(path)
if parent:
os.makedirs(parent, exist_ok=True)
except Exception:
pass
def _validate_coords(
left_up: tuple, right_down: tuple, image_size: tuple
) -> bool:
"""检查裁剪坐标在图片范围内且非空。"""
left, top = left_up
right, bottom = right_down
width, height = image_size
return not (
left < 0 or top < 0
or right > width or bottom > height
or left >= right or top >= bottom
)
def _save_cut_debug_images(self: Any, cropped_img, pic, name: str, source_label: str, left: int, top: int, right: int, bottom: int) -> None:
"""根据环境变量决定是否保存 cut_pic 调试图。"""
try:
save_debug = os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1"
if not save_debug:
try:
save_debug = os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1"
except Exception:
pass
if not save_debug:
return
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
cropped_img, operation_type="cut_pic"
)
# 保存调试图像(完整截图+区域标注)
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": source_label,
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
def cut_pic(
self: Any,
left_up=(0, 63),
right_down=(1080, 1620),
target: str = "",
name: str = "",
) -> bool:
"""裁剪图片,获取需要的区域小图片方便识别。"""
from douyin.core.underlying_operations import _uo_log
max_retries = 3
retry_delay = 0.1
for attempt in range(max_retries):
try:
if target == "" or target is False:
from douyin.core import path_config
path = path_config.get_pic_dir()
pic1_path = path_config.get_screenshot_path()
cut_pic_path = None
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
# 尝试打开并验证图片
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
raise
if name == "":
cut_pic_path = path + "/cut.png"
else:
cut_pic_path = self._find_pic_path(name, for_reading=False)
if not _validate_coords(left_up, right_down, pic.size):
raise ValueError(
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
)
left, top = left_up
right, bottom = right_down
cropped_img = pic.crop((left, top, right, bottom))
assert cut_pic_path is not None
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
# 存储坐标信息供 analyse_pic_word 使用
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
_save_cut_debug_images(
self, cropped_img, pic, name,
"screenshot.png", left, top, right, bottom,
)
return True
else:
from douyin.core import path_config
path_target = os.path.join(path_config.get_pic_dir(), target)
pic1_path = os.path.join(path_target, "screenshot.png")
cut_pic_path = None
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
raise
if name == "":
cut_pic_path = path_target + "/cut.png"
else:
cut_pic_path = path_target + "/" + name + ".png"
if not _validate_coords(left_up, right_down, pic.size):
error_msg = (
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, "
f"image_size={pic.size}"
)
if attempt == max_retries - 1:
_uo_log(f"[错误] {error_msg}")
return False
continue
left, top = left_up
right, bottom = right_down
assert cut_pic_path is not None
cropped_img = pic.crop((left, top, right, bottom))
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
return False
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
# 命名分支总是保存 cut_pic 调试图(与原版行为一致 — 没有开关检查)
try:
from douyin.handlers import douyin_screenshot_manager
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": target + "/screenshot.png",
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
return True
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
if attempt == max_retries - 1:
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
_uo_log(error_msg)
_uo_log(f" 源文件: {locals().get('pic1_path', 'N/A')}")
_uo_log(f" 目标文件: {locals().get('cut_pic_path', 'N/A')}")
return False
continue
return False
+17 -7
View File
@@ -16,16 +16,26 @@ import pytest
def test_cut_pic_uses_path_config_not_local_dirname():
"""cut_pic 源码不能再用 os.path.dirname(__file__) + "/pic"。"""
from douyin.core.underlying_operations import underlying_operations
op = underlying_operations()
src = inspect.getsource(op.cut_pic)
"""cut_pic 实现源码不能再用 os.path.dirname(__file__) + "/pic"。
cut_pic 已抽到 underlying_operations_pkg/image_ops.py。
主类方法 op.cut_pic 是 delegation wrapper,inspect.getsource 取到的是 wrapper 源码;
所以这里直接读 image_ops.py 文件源码做断言。
"""
import os as _os
repo_root = _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__)))
image_ops_path = _os.path.join(
repo_root, "douyin", "core", "underlying_operations_pkg", "image_ops.py"
)
with open(image_ops_path, "r", encoding="utf-8") as f:
src = f.read()
assert 'os.path.dirname(__file__) + "/pic"' not in src, (
"cut_pic 仍在用 dirname(__file__) 推路径,"
"会指向 douyin/core/pic/(不存在),应该用 path_config.get_pic_dir()"
"image_ops.cut_pic 仍在用 dirname(__file__) 推路径,"
"会指向错误位置,应该用 path_config.get_pic_dir()"
)
assert 'os.path.dirname(__file__) + "/pic/' not in src, (
"cut_pic target 分支仍在用 dirname(__file__) 推路径"
"image_ops.cut_pic target 分支仍在用 dirname(__file__) 推路径"
)
# 至少一处使用 path_config
assert "path_config.get_pic_dir" in src or "path_config.get_screenshot_path" in src
+13 -4
View File
@@ -39,10 +39,19 @@ class TestUnderlyingOperationsPaths:
)
def test_ocr_category_dir_uses_path_config(self):
src = _read("douyin", "core", "underlying_operations.py")
# 之前是 base_dir = dirname(__file__); pic_base = os.path.join(base_dir, "pic")
# 修复后必须用 get_pic_dir
assert "path_config.get_pic_dir()" in src
"""OCR category 目录与 cut_pic 都用 path_config.get_pic_dir 派生路径。
cut_pic 已抽到 underlying_operations_pkg/image_ops.py,
OCR category 已抽到 underlying_operations_pkg/ocr_pipeline.py。
在所有 3 个文件至少一处使用 path_config.get_pic_dir() 即视为通过。
"""
sources = [
_read("douyin", "core", "underlying_operations.py"),
_read("douyin", "core", "underlying_operations_pkg", "image_ops.py"),
_read("douyin", "core", "underlying_operations_pkg", "ocr_pipeline.py"),
]
combined = "\n".join(sources)
assert "path_config.get_pic_dir()" in combined
def test_no_dirname_pic_pattern_anywhere(self):
"""整个文件不应再出现 `dirname(__file__) ... "pic"` 这种**单步**拼接。