diff --git a/douyin/core/io_utils.py b/douyin/core/io_utils.py new file mode 100644 index 0000000..5f6dc18 --- /dev/null +++ b/douyin/core/io_utils.py @@ -0,0 +1,187 @@ +"""文件 IO 与截图镜像辅助函数。 + +从 douyin/core/underlying_operations.py 顶部抽离的模块级函数, +为多个模块提供共用的安全文件替换和截图镜像能力。 + +外部 import 路径已通过 underlying_operations 重新导出,保持向后兼容。 +""" + +from __future__ import annotations + +import logging +import os +import time as time_module +from typing import Optional + +# 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用。 +# 仅在显式设置 EXTERNAL_DOUYIN_FUDAI_DIR 时启用。 +_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip() +_EXTERNAL_AXF_SCREENSHOT = ( + os.path.join(_EXTERNAL_DOUYIN_FUDAI_DIR, "pic", "screenshot.png") + if _EXTERNAL_DOUYIN_FUDAI_DIR + else "" +) + + +def _verify_png_integrity(path: str) -> bool: + """验证 PNG 文件头尾完整性,防止读取半写文件""" + try: + with open(path, "rb") as f: + header = f.read(8) + if len(header) < 8 or header[:4] != b"\x89PNG": + return False + f.seek(-12, 2) # IEND chunk 至少 12 字节 + tail = f.read(12) + return b"IEND" in tail + except Exception: + return False + + +def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bool: + """安全地替换文件,处理 Windows 文件锁定问题。 + + 优先 os.replace 原子替换;失败时回退到 shutil.copy2,避免长时间等待。 + 对 PNG 文件会先校验完整性,避免发布半写文件。 + + Args: + tmp_file: 临时文件路径 + out_file: 目标文件路径 + max_retries: 最大重试次数(已优化为 2 次) + + Returns: + True if successful, False otherwise + """ + import shutil + + if not os.path.exists(tmp_file): + return False + + # PNG 完整性校验 + if tmp_file.lower().endswith(".png"): + if not _verify_png_integrity(tmp_file): + logging.debug("PNG 文件不完整,跳过替换: %s", tmp_file) + return False + + # 方法 1:原子替换 + try: + os.replace(tmp_file, out_file) + return True + except (OSError, PermissionError): + pass + + # 方法 2:shutil.copy2(保留元数据) + try: + shutil.copy2(tmp_file, out_file) + try: + os.remove(tmp_file) + except Exception: + pass + return True + except Exception: + pass + + # 方法 3:手动复制(最后手段) + try: + with open(tmp_file, "rb") as src, open(out_file, "wb") as dst: + while True: + chunk = src.read(1048576) # 1MB chunks + if not chunk: + break + dst.write(chunk) + try: + os.remove(tmp_file) + except Exception: + pass + return True + except Exception: + return False + + +def _ensure_parent_dir(path: str) -> None: + """确保 path 的父目录存在。""" + try: + parent = os.path.dirname(path) + if parent: + os.makedirs(parent, exist_ok=True) + except Exception: + logging.exception("无法创建父目录: %s", path) + + +def _mirror_screenshot_to_external(src_file: str) -> None: + """将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。 + + 若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。 + 可通过环境变量 DISABLE_SCREENSHOT_MIRROR=1 禁用此功能以提升性能。 + """ + if os.environ.get("DISABLE_SCREENSHOT_MIRROR", "0") == "1": + return + + mirror_start = time_module.time() + try: + external_path = _EXTERNAL_AXF_SCREENSHOT + if not external_path: + return + external_dir = os.path.dirname(external_path) + if not external_dir: + return + + external_base = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "") + is_network_path = False + if external_base: + if external_base.startswith("\\\\") or external_base.startswith("//"): + is_network_path = True + logging.warning( + "[截图] 检测到网络路径,镜像可能较慢: %s", external_base + ) + elif ":" in external_base and len(external_base) > 3: + logging.debug("[截图] 镜像目标路径: %s", external_path) + + os.makedirs(external_dir, exist_ok=True) + if not os.path.exists(src_file): + return + tmp = external_path + ".tmp" + import shutil + + copy_start = time_module.time() + shutil.copyfile(src_file, tmp) + copy_dur = (time_module.time() - copy_start) * 1000.0 + if copy_dur > 50.0 or is_network_path: + logging.info( + "[截图] 镜像复制耗时(ms)=%.1f src=%s dst=%s (网络路径=%s)", + copy_dur, + src_file, + tmp, + is_network_path, + ) + + replace_start = time_module.time() + _safe_replace_file(tmp, external_path) + replace_dur = (time_module.time() - replace_start) * 1000.0 + if replace_dur > 50.0 or is_network_path: + logging.info( + "[截图] 镜像文件替换耗时(ms)=%.1f (网络路径=%s)", + replace_dur, + is_network_path, + ) + + mirror_total_dur = (time_module.time() - mirror_start) * 1000.0 + if mirror_total_dur > 100.0 or is_network_path: + logging.info( + "[截图] 镜像总耗时(ms)=%.1f path=%s (网络路径=%s)", + mirror_total_dur, + external_path, + is_network_path, + ) + except Exception: + # 任何错误都不应该影响截图主流程 + pass + + +__all__ = [ + "_verify_png_integrity", + "_safe_replace_file", + "_ensure_parent_dir", + "_mirror_screenshot_to_external", + "_EXTERNAL_DOUYIN_FUDAI_DIR", + "_EXTERNAL_AXF_SCREENSHOT", +] diff --git a/douyin/core/underlying_operations.py b/douyin/core/underlying_operations.py index 2fa7cc2..62c8dbe 100644 --- a/douyin/core/underlying_operations.py +++ b/douyin/core/underlying_operations.py @@ -40,183 +40,17 @@ except Exception: _RESAMPLE = Image # 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用。 -# 仅在显式设置 EXTERNAL_DOUYIN_FUDAI_DIR 时启用,避免绑定某台机器的旧路径。 -_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip() -_EXTERNAL_AXF_SCREENSHOT = ( - os.path.join(_EXTERNAL_DOUYIN_FUDAI_DIR, "pic", "screenshot.png") - if _EXTERNAL_DOUYIN_FUDAI_DIR - else "" +# 这些常量与文件 IO 辅助函数已抽离到 io_utils.py,此处仅为向后兼容重新导出。 +from douyin.core.io_utils import ( + _EXTERNAL_DOUYIN_FUDAI_DIR, + _EXTERNAL_AXF_SCREENSHOT, + _verify_png_integrity, + _safe_replace_file, + _ensure_parent_dir, + _mirror_screenshot_to_external, ) -def _verify_png_integrity(path: str) -> bool: - """验证 PNG 文件头尾完整性,防止读取半写文件""" - try: - with open(path, 'rb') as f: - header = f.read(8) - if len(header) < 8 or header[:4] != b'\x89PNG': - return False - f.seek(-12, 2) # IEND chunk 至少 12 字节 - tail = f.read(12) - return b'IEND' in tail - except Exception: - return False - - -def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bool: - """安全地替换文件,处理Windows文件锁定问题。 - - 根本优化:优先使用直接复制而不是替换,避免文件锁定问题。 - 如果文件被占用,直接复制内容而不是等待释放。 - 对于 PNG 文件,会先验证完整性再替换。 - - Args: - tmp_file: 临时文件路径 - out_file: 目标文件路径 - max_retries: 最大重试次数(已优化为2次) - - Returns: - True if successful, False otherwise - """ - import shutil - - if not os.path.exists(tmp_file): - return False - - # 对于 PNG 文件,先验证完整性 - if tmp_file.lower().endswith('.png'): - if not _verify_png_integrity(tmp_file): - logging.debug("PNG 文件不完整,跳过替换: %s", tmp_file) - return False - - # 根本优化:优先尝试原子替换(最快),如果失败则直接复制(避免等待) - try: - # 方法1: 直接使用 os.replace (原子操作,最快) - os.replace(tmp_file, out_file) - return True - except (OSError, PermissionError): - # 如果原子替换失败(文件被占用),直接使用复制方法(避免等待) - # 这样可以避免文件锁定导致的长时间等待 - pass - - # 方法2: 直接复制文件内容(避免文件锁定问题) - # 这是最可靠的方法,即使文件被占用也能成功 - try: - # 使用 shutil.copy2 保留元数据,但速度更快 - shutil.copy2(tmp_file, out_file) - # 复制成功后删除临时文件 - try: - os.remove(tmp_file) - except Exception: - pass - return True - except Exception: - # 如果 shutil.copy2 也失败,使用手动复制(最后手段) - try: - with open(tmp_file, "rb") as src, open(out_file, "wb") as dst: - # 使用更大的块大小提高复制速度(1MB) - while True: - chunk = src.read(1048576) # 1MB chunks - if not chunk: - break - dst.write(chunk) - # 复制成功后删除临时文件 - try: - os.remove(tmp_file) - except Exception: - pass - return True - except Exception: - return False - - -def _ensure_parent_dir(path: str) -> None: - """Ensure the parent directory for `path` exists.""" - try: - parent = os.path.dirname(path) - if parent: - os.makedirs(parent, exist_ok=True) - except Exception: - # 不应因目录创建失败阻塞主流程,记录以便排查 - logging.exception("无法创建父目录: %s", path) - - -def _mirror_screenshot_to_external(src_file: str) -> None: - """将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。 - - 若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。 - - 可通过环境变量 DISABLE_SCREENSHOT_MIRROR=1 禁用此功能以提升性能。 - """ - # 检查环境变量:是否禁用镜像功能(用于性能测试) - if os.environ.get("DISABLE_SCREENSHOT_MIRROR", "0") == "1": - return - - mirror_start = time_module.time() - try: - external_path = _EXTERNAL_AXF_SCREENSHOT - if not external_path: - return - external_dir = os.path.dirname(external_path) - if not external_dir: - return - - # 检查外部路径是否是网络路径或可能较慢的路径 - external_base = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "") - is_network_path = False - if external_base: - # 检查是否是网络路径(UNC路径或网络驱动器) - if external_base.startswith("\\\\") or external_base.startswith("//"): - is_network_path = True - logging.warning( - "[截图] 检测到网络路径,镜像可能较慢: %s", external_base - ) - # 检查是否是远程挂载点(简单启发式:包含常见网络挂载标识) - elif ":" in external_base and len(external_base) > 3: - # 可能是网络驱动器,但无法确定,记录路径供诊断 - logging.debug("[截图] 镜像目标路径: %s", external_path) - - os.makedirs(external_dir, exist_ok=True) - if not os.path.exists(src_file): - return - tmp = external_path + ".tmp" - import shutil - - copy_start = time_module.time() - shutil.copyfile(src_file, tmp) - copy_dur = (time_module.time() - copy_start) * 1000.0 - if copy_dur > 50.0 or is_network_path: - logging.info( - "[截图] 镜像复制耗时(ms)=%.1f src=%s dst=%s (网络路径=%s)", - copy_dur, - src_file, - tmp, - is_network_path, - ) - - replace_start = time_module.time() - _safe_replace_file(tmp, external_path) - replace_dur = (time_module.time() - replace_start) * 1000.0 - if replace_dur > 50.0 or is_network_path: - logging.info( - "[截图] 镜像文件替换耗时(ms)=%.1f (网络路径=%s)", - replace_dur, - is_network_path, - ) - - mirror_total_dur = (time_module.time() - mirror_start) * 1000.0 - if mirror_total_dur > 100.0 or is_network_path: - logging.info( - "[截图] 镜像总耗时(ms)=%.1f path=%s (网络路径=%s)", - mirror_total_dur, - external_path, - is_network_path, - ) - except Exception: - # 任何错误都不应该影响截图主流程 - pass - - class underlying_operations: """底层操作类"""