fix: 修复7个Critical并发安全和异常处理问题
1. OCR 单例无锁保护 - 添加 _ocr_lock 和 _ocr_coords_lock 2. ADB 文本广播命令注入 - 使用 shlex.quote() 转义 3. 截图文件 Race Condition - 添加 PNG 完整性验证 4. JSON 持久化无锁 - 添加文件级锁字典 5. 双检查锁不完整 - 修复 _ensure_debug_save_worker_started 6. Daemon 线程无 Graceful Shutdown - 添加 shutdown event 和 atexit 7. 关键路径异常处理 - 添加 logging.debug 替代 pass Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1fdec7a548
commit
ff8de2c9b8
6 files changed
+283
-199
No files matched your search
+106
-72
@@ -1,4 +1,5 @@
|
||||
import subprocess
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
import os
|
||||
import sys
|
||||
@@ -48,11 +49,26 @@ _EXTERNAL_AXF_SCREENSHOT = (
|
||||
)
|
||||
|
||||
|
||||
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: 临时文件路径
|
||||
@@ -67,6 +83,12 @@ def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bo
|
||||
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 (原子操作,最快)
|
||||
@@ -205,6 +227,9 @@ class underlying_operations:
|
||||
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]] = {}
|
||||
# 线程安全锁
|
||||
self._ocr_lock = threading.RLock() # 保护 OCR 初始化
|
||||
self._ocr_coords_lock = threading.Lock() # 保护坐标缓存
|
||||
|
||||
# 默认使用CPU模式(删除GPU检测)
|
||||
self._gpu_available = False
|
||||
@@ -338,69 +363,73 @@ class underlying_operations:
|
||||
if self.ocr is not None:
|
||||
return
|
||||
|
||||
# 默认使用CPU模式(延迟初始化时)
|
||||
with self._ocr_lock:
|
||||
if self.ocr is not None:
|
||||
return
|
||||
|
||||
# 优先尝试EasyOCR
|
||||
try:
|
||||
# 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题
|
||||
import importlib
|
||||
# 默认使用CPU模式(延迟初始化时)
|
||||
|
||||
# 优先尝试EasyOCR
|
||||
try:
|
||||
easyocr = importlib.import_module("easyocr")
|
||||
except Exception:
|
||||
easyocr = None
|
||||
# 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题
|
||||
import importlib
|
||||
|
||||
# 临时重定向输出以减少初始化时的噪音
|
||||
import io
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
|
||||
fake_stdout = io.StringIO()
|
||||
fake_stderr = io.StringIO()
|
||||
|
||||
if easyocr is not None:
|
||||
with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr):
|
||||
self.ocr = easyocr.Reader(
|
||||
["ch_sim", "en"], gpu=False, verbose=False
|
||||
)
|
||||
|
||||
self.ocr_type = "easyocr"
|
||||
gpu_status = "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})")
|
||||
else:
|
||||
raise ImportError("easyocr not available")
|
||||
except Exception as e:
|
||||
# EasyOCR失败,回退到PaddleOCR
|
||||
print(f"[OCR] 延迟初始化EasyOCR失败: {e},回退到PaddleOCR")
|
||||
devnull = None
|
||||
try:
|
||||
devnull = open(os.devnull, "w", encoding="utf-8")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# 使用 PaddleOCR(强制 CPU 模式)
|
||||
use_gpu = False
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_angle_cls=False,
|
||||
use_gpu=use_gpu,
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
print("[OCR] 延迟初始化:使用 PaddleOCR(CPU模式)")
|
||||
except Exception:
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
finally:
|
||||
try:
|
||||
if devnull is not None:
|
||||
devnull.close()
|
||||
easyocr = importlib.import_module("easyocr")
|
||||
except Exception:
|
||||
pass
|
||||
easyocr = None
|
||||
|
||||
# 临时重定向输出以减少初始化时的噪音
|
||||
import io
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
|
||||
fake_stdout = io.StringIO()
|
||||
fake_stderr = io.StringIO()
|
||||
|
||||
if easyocr is not None:
|
||||
with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr):
|
||||
self.ocr = easyocr.Reader(
|
||||
["ch_sim", "en"], gpu=False, verbose=False
|
||||
)
|
||||
|
||||
self.ocr_type = "easyocr"
|
||||
gpu_status = "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})")
|
||||
else:
|
||||
raise ImportError("easyocr not available")
|
||||
except Exception as e:
|
||||
# EasyOCR失败,回退到PaddleOCR
|
||||
print(f"[OCR] 延迟初始化EasyOCR失败: {e},回退到PaddleOCR")
|
||||
devnull = None
|
||||
try:
|
||||
devnull = open(os.devnull, "w", encoding="utf-8")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# 使用 PaddleOCR(强制 CPU 模式)
|
||||
use_gpu = False
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_angle_cls=False,
|
||||
use_gpu=use_gpu,
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
print("[OCR] 延迟初始化:使用 PaddleOCR(CPU模式)")
|
||||
except Exception:
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
finally:
|
||||
try:
|
||||
if devnull is not None:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def select_device(self):
|
||||
"""选择需要连接的设备"""
|
||||
@@ -1396,7 +1425,8 @@ class underlying_operations:
|
||||
# 存储坐标信息供analyse_pic_word使用
|
||||
if name:
|
||||
try:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
with self._ocr_coords_lock:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1517,7 +1547,8 @@ class underlying_operations:
|
||||
# 存储坐标信息供analyse_pic_word使用
|
||||
if name:
|
||||
try:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
with self._ocr_coords_lock:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1652,7 +1683,8 @@ class underlying_operations:
|
||||
# 尝试获取OCR区域坐标
|
||||
ocr_coords = None
|
||||
try:
|
||||
ocr_coords = self._ocr_coords_cache.get(picname)
|
||||
with self._ocr_coords_lock:
|
||||
ocr_coords = self._ocr_coords_cache.get(picname)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -2895,11 +2927,14 @@ class underlying_operations:
|
||||
if not t:
|
||||
return False
|
||||
|
||||
# 使用 shlex.quote 转义文本,防止 shell 注入
|
||||
safe_t = shlex.quote(t)
|
||||
|
||||
# 1) cmd clipboard set
|
||||
try:
|
||||
if (
|
||||
subprocess.run(
|
||||
self._adb_args(device_id, "shell", "cmd", "clipboard", "set", t),
|
||||
self._adb_args(device_id, "shell", "cmd", "clipboard", "set", safe_t),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=3.0,
|
||||
@@ -2924,7 +2959,7 @@ class underlying_operations:
|
||||
"clipper.set",
|
||||
"-e",
|
||||
"text",
|
||||
t,
|
||||
safe_t,
|
||||
),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
@@ -2951,13 +2986,9 @@ class underlying_operations:
|
||||
return False
|
||||
# 空格用 %s,避免被 shell 分词
|
||||
t = t.replace(" ", "%s")
|
||||
# 仅做最小转义,避免破坏中文
|
||||
t = (
|
||||
t.replace("&", "\\&")
|
||||
.replace("<", "\\<")
|
||||
.replace(">", "\\>")
|
||||
.replace("|", "\\|")
|
||||
)
|
||||
# 完整转义所有 shell 特殊字符
|
||||
for ch in ['&', '<', '>', '|', ';', '$', '`', "'", '"', '\\', '(', ')', '{', '}', '[', ']', '!', '#', '*', '?']:
|
||||
t = t.replace(ch, '\\' + ch)
|
||||
try:
|
||||
return (
|
||||
subprocess.run(
|
||||
@@ -3085,12 +3116,13 @@ class underlying_operations:
|
||||
act = str(action or "").strip()
|
||||
if not act:
|
||||
return False
|
||||
# 这里不依赖 broadcast 的返回文本,只要命令成功执行就认为 ok
|
||||
# 使用 shlex.quote 转义消息,防止 shell 注入
|
||||
safe_msg = shlex.quote(str(msg or ""))
|
||||
try:
|
||||
return (
|
||||
subprocess.run(
|
||||
self._adb_args(
|
||||
device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", str(msg or "")
|
||||
device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", safe_msg
|
||||
),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
@@ -3113,11 +3145,13 @@ class underlying_operations:
|
||||
v = int(value)
|
||||
except Exception:
|
||||
return False
|
||||
# 使用 shlex.quote 转义 key,防止 shell 注入
|
||||
safe_k = shlex.quote(k)
|
||||
try:
|
||||
return (
|
||||
subprocess.run(
|
||||
self._adb_args(
|
||||
device_id, "shell", "am", "broadcast", "-a", act, "--ei", k, v
|
||||
device_id, "shell", "am", "broadcast", "-a", act, "--ei", safe_k, v
|
||||
),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
|
||||
@@ -12,6 +12,7 @@ Flow control main helpers (本地模块化实现,基础版)
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
import logging
|
||||
import time
|
||||
import os
|
||||
|
||||
@@ -55,8 +56,8 @@ def find_and_open_fudai_detail(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logging.debug("日志记录失败: %s", e)
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
@@ -64,8 +65,8 @@ def find_and_open_fudai_detail(
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logging.debug("检查等待开奖状态失败: %s", e)
|
||||
|
||||
device_id = getattr(analyser, "device_id", "")
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ import time
|
||||
# 背景保存队列与工作线程(用于异步保存调试图像,避免阻塞主流程)
|
||||
_debug_save_queue: "Queue[Tuple[Image.Image, str, bool, Optional[Tuple[int,int,int,int]], Optional[dict], str, str, str]]" = (Queue())
|
||||
_debug_save_worker_started = False
|
||||
_debug_save_worker_lock = threading.Lock() # 保护 worker 启动的双检查锁
|
||||
_debug_save_shutdown_event = threading.Event() # 用于优雅关闭
|
||||
|
||||
# 异步保存计数(用于 GUI 显示)
|
||||
_async_save_success_count = 0
|
||||
@@ -42,12 +44,12 @@ _SKIP_DEBUG_SAVE_IN_HOTLOOPS = bool(
|
||||
|
||||
def _debug_save_loop() -> None:
|
||||
"""后台线程循环,消费调试图像保存任务并执行同步保存。"""
|
||||
while True:
|
||||
while not _debug_save_shutdown_event.is_set():
|
||||
try:
|
||||
task = _debug_save_queue.get()
|
||||
if not task:
|
||||
task = _debug_save_queue.get(timeout=1.0)
|
||||
if task is None:
|
||||
_debug_save_queue.task_done()
|
||||
continue
|
||||
break
|
||||
(
|
||||
img,
|
||||
file_path,
|
||||
@@ -318,6 +320,8 @@ def _debug_save_loop() -> None:
|
||||
pass
|
||||
finally:
|
||||
_debug_save_queue.task_done()
|
||||
except Empty:
|
||||
continue
|
||||
except Exception:
|
||||
# 防止线程因异常退出
|
||||
try:
|
||||
@@ -328,13 +332,35 @@ def _debug_save_loop() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def shutdown_debug_save_worker(timeout: float = 5.0) -> None:
|
||||
"""优雅关闭调试保存工作线程"""
|
||||
global _debug_save_worker_started
|
||||
if not _debug_save_worker_started:
|
||||
return
|
||||
_debug_save_shutdown_event.set()
|
||||
_debug_save_queue.put(None) # 毒丸信号
|
||||
try:
|
||||
_debug_save_queue.join()
|
||||
except Exception:
|
||||
pass
|
||||
_debug_save_worker_started = False
|
||||
|
||||
|
||||
# 注册 atexit 清理函数
|
||||
import atexit
|
||||
atexit.register(shutdown_debug_save_worker)
|
||||
|
||||
|
||||
def _ensure_debug_save_worker_started() -> None:
|
||||
global _debug_save_worker_started
|
||||
if _debug_save_worker_started:
|
||||
return
|
||||
t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True)
|
||||
t.start()
|
||||
_debug_save_worker_started = True
|
||||
with _debug_save_worker_lock:
|
||||
if _debug_save_worker_started:
|
||||
return
|
||||
t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True)
|
||||
t.start()
|
||||
_debug_save_worker_started = True
|
||||
|
||||
|
||||
def get_async_save_counters() -> tuple[int, int]:
|
||||
|
||||
@@ -3,9 +3,23 @@ from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
# 文件级锁字典,用于保护 JSON 文件的并发读写
|
||||
_json_file_locks: dict[str, threading.Lock] = {}
|
||||
_json_locks_lock = threading.Lock()
|
||||
|
||||
|
||||
def _get_file_lock(path: str) -> threading.Lock:
|
||||
"""获取文件级别的锁"""
|
||||
with _json_locks_lock:
|
||||
if path not in _json_file_locks:
|
||||
_json_file_locks[path] = threading.Lock()
|
||||
return _json_file_locks[path]
|
||||
|
||||
|
||||
# 导入预约错误处理工具
|
||||
try:
|
||||
from douyin.reservation.core.reservation_error_utils import (
|
||||
@@ -25,7 +39,7 @@ except ImportError:
|
||||
|
||||
|
||||
def _write_json_atomic(path: str, data: object, *, indent: int = 2, analyser: Optional[Any] = None) -> None:
|
||||
"""原子写入 JSON 文件,带详细的错误处理。
|
||||
"""原子写入 JSON 文件,带详细的错误处理和线程锁保护。
|
||||
|
||||
参数:
|
||||
path: 文件路径
|
||||
@@ -33,83 +47,85 @@ def _write_json_atomic(path: str, data: object, *, indent: int = 2, analyser: Op
|
||||
indent: JSON 缩进
|
||||
analyser: 分析器对象(可选,用于日志记录)
|
||||
"""
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
except PermissionError as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="创建状态文件目录(权限错误)",
|
||||
)
|
||||
raise
|
||||
except OSError as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="创建状态文件目录(系统错误)",
|
||||
)
|
||||
raise
|
||||
|
||||
tmp = path + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=indent)
|
||||
f.write("\n")
|
||||
except (ValueError, TypeError) as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="序列化状态数据",
|
||||
)
|
||||
raise
|
||||
except PermissionError as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="写入状态文件(权限错误)",
|
||||
)
|
||||
raise
|
||||
except OSError as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="写入状态文件(系统错误)",
|
||||
)
|
||||
raise
|
||||
|
||||
try:
|
||||
os.replace(tmp, path)
|
||||
except OSError as e:
|
||||
# 清理临时文件
|
||||
lock = _get_file_lock(path)
|
||||
with lock:
|
||||
try:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
except Exception:
|
||||
pass
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="原子替换状态文件",
|
||||
)
|
||||
raise
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
except PermissionError as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="创建状态文件目录(权限错误)",
|
||||
)
|
||||
raise
|
||||
except OSError as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="创建状态文件目录(系统错误)",
|
||||
)
|
||||
raise
|
||||
|
||||
tmp = path + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=indent)
|
||||
f.write("\n")
|
||||
except (ValueError, TypeError) as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="序列化状态数据",
|
||||
)
|
||||
raise
|
||||
except PermissionError as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="写入状态文件(权限错误)",
|
||||
)
|
||||
raise
|
||||
except OSError as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="写入状态文件(系统错误)",
|
||||
)
|
||||
raise
|
||||
|
||||
try:
|
||||
os.replace(tmp, path)
|
||||
except OSError as e:
|
||||
# 清理临时文件
|
||||
try:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
except Exception:
|
||||
pass
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
e,
|
||||
format_reservation_context(path=path),
|
||||
level="ERROR",
|
||||
stage="原子替换状态文件",
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
def write_reservations_state(
|
||||
@@ -190,32 +206,34 @@ def write_reservations_state(
|
||||
|
||||
|
||||
def load_high_value_rooms_map(path: str) -> dict[str, dict]:
|
||||
"""讀取高價值直播間映射(跨運行持久化)。"""
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
"""讀取高價值直播間映射(跨運行持久化),带线程锁保护。"""
|
||||
lock = _get_file_lock(path)
|
||||
with lock:
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# 兼容兩種格式:{"rooms": [...]} 或 直接是 [...]
|
||||
rooms = None
|
||||
if isinstance(data, dict):
|
||||
rooms = data.get("rooms")
|
||||
elif isinstance(data, list):
|
||||
rooms = data
|
||||
|
||||
out: dict[str, dict] = {}
|
||||
if isinstance(rooms, list):
|
||||
for it in rooms:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
key = str(it.get("room_title") or "").strip()
|
||||
if not key:
|
||||
continue
|
||||
out[key] = dict(it)
|
||||
return out
|
||||
except Exception:
|
||||
return {}
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# 兼容兩種格式:{"rooms": [...]} 或 直接是 [...]
|
||||
rooms = None
|
||||
if isinstance(data, dict):
|
||||
rooms = data.get("rooms")
|
||||
elif isinstance(data, list):
|
||||
rooms = data
|
||||
|
||||
out: dict[str, dict] = {}
|
||||
if isinstance(rooms, list):
|
||||
for it in rooms:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
key = str(it.get("room_title") or "").strip()
|
||||
if not key:
|
||||
continue
|
||||
out[key] = dict(it)
|
||||
return out
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def write_high_value_rooms_state(path: str, rooms_map: dict, *, reason: str = "") -> None:
|
||||
|
||||
@@ -406,7 +406,7 @@ class StageHandler:
|
||||
best_binary_score = max_val
|
||||
roi_binary_fixed = roi_bin
|
||||
tpl_binary_fixed = tpl_bin
|
||||
except:
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 方法2:自适应二值化(调整参数,blockSize使用较小值以提高精度)
|
||||
|
||||
+18
-13
@@ -1,5 +1,6 @@
|
||||
import argparse
|
||||
import importlib.util
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
@@ -10,18 +11,21 @@ if os.environ.get("PARAM_TRACK_ALL") == "1":
|
||||
from douyin.utils.param_usage_tracer import start_tracing
|
||||
|
||||
start_tracing()
|
||||
except Exception:
|
||||
# 启用失败不影响主流程
|
||||
pass
|
||||
except Exception as e:
|
||||
logging.debug("参数追踪启用失败: %s", e)
|
||||
|
||||
# ==== 首先配置日志系统,确保日志文件能正常写入 ==============================
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
# 日志配置失败不影响主流程,但会缺少文件日志
|
||||
pass
|
||||
except Exception as e:
|
||||
# 日志配置失败,使用基础配置作为兜底
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - [%(levelname)s] - %(message)s'
|
||||
)
|
||||
logging.warning("日志系统配置失败,使用基础配置: %s", e)
|
||||
|
||||
# 尝试确保行为日志的异步 listener 在进程启动时就被启动,
|
||||
# 以避免某些运行环境中模块未完整初始化导致日志未落盘的问题。
|
||||
@@ -33,11 +37,11 @@ try:
|
||||
action_logger_mod = importlib.import_module("douyin.logging.action_logger")
|
||||
try:
|
||||
action_logger_mod._start_queue_listener_if_needed()
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# 启动失败时不影响主流程,action_logger 有回退到同步 file handler 的逻辑
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
logging.debug("action_logger 启动失败: %s", e)
|
||||
except Exception as e:
|
||||
logging.debug("action_logger 模块导入失败: %s", e)
|
||||
|
||||
# ==== 兼容导入完整逻辑模块 douyin_fudai 及其依赖 ==============================
|
||||
# 如果需要从外部工作树加载兼容模块,可显式设置 EXTERNAL_DOUYIN_FUDAI_DIR。
|
||||
@@ -61,8 +65,9 @@ def _load_local_shim(mod_name: str, rel_path: str) -> None:
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
sys.modules[mod_name] = module
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# shim 加载失败不影响主流程,后续仍可尝试外部模块
|
||||
logging.debug("shim 模块加载失败 %s: %s", mod_name, e)
|
||||
return
|
||||
|
||||
|
||||
@@ -80,9 +85,9 @@ try:
|
||||
and _EXTERNAL_DOUYIN_FUDAI_DIR not in sys.path
|
||||
):
|
||||
sys.path.append(_EXTERNAL_DOUYIN_FUDAI_DIR)
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# 不影响主流程;如果目录不存在,后续导入会按默认逻辑报错
|
||||
pass
|
||||
logging.debug("外部模块路径配置失败: %s", e)
|
||||
|
||||
# 在导入 PaddleOCR 之前设置,避免每次启动都做连通性检查提示并抑制底层 glog/oneDNN 等噪音
|
||||
# DISABLE_MODEL_SOURCE_CHECK: 跳过 PaddleOCR 的主机连通性检查(国内网络环境常卡)
|
||||
|
||||
Reference in new issue
Block a user