refactor(core): 抽出正则、探针与缓存等公共基础设施
- 新增 core/constants.py:集中管理结构解析、命名与字幕识别用到的正则表达式 - 新增 core/utils.py:StringUtil(标题清洗)、FFprobeUtil(ffprobe JSON 调用)、MediaUtil(字幕语言推断) - 新增 core/cache.py:JsonCacheManager 统一 JSON 缓存读写,替代 TMDBService 内联的 _load_cache/_save_cache
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
# src/core/utils.py
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from core.constants import RegexPatterns
|
||||
|
||||
class StringUtil:
|
||||
"""字符串与文件命名安全处理工具"""
|
||||
@staticmethod
|
||||
def sanitize_title(title: str) -> str:
|
||||
if not title:
|
||||
return ""
|
||||
# 接入核心正则
|
||||
return RegexPatterns.FILE_SANITIZE.sub('.', title.replace("'", "").replace("’", "")).strip('.')
|
||||
|
||||
class FFprobeUtil:
|
||||
"""FFprobe 探针调用与 JSON 解析工具"""
|
||||
@staticmethod
|
||||
def get_json(file_path: Path, *args) -> dict:
|
||||
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json"] + list(args) + [str(file_path)]
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
if res.stdout.strip():
|
||||
return json.loads(res.stdout)
|
||||
return {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
class MediaUtil:
|
||||
"""媒体文件分析与推断辅助工具"""
|
||||
@staticmethod
|
||||
def detect_subtitle_language(sub_path: Path) -> str:
|
||||
name = sub_path.name.lower()
|
||||
if RegexPatterns.SUB_LANG_CHT.search(name): return "zh-TW"
|
||||
if RegexPatterns.SUB_LANG_CHS.search(name): return "zh-CN"
|
||||
if RegexPatterns.SUB_LANG_ENG.search(name): return "en"
|
||||
|
||||
try:
|
||||
content = sub_path.read_text(encoding='utf-8', errors='ignore')[:5000]
|
||||
if RegexPatterns.SUB_LANG_ZH_CHARS.search(content):
|
||||
return "zh-TW" if len(RegexPatterns.SUB_LANG_CHT_CHARS.findall(content)) > 5 else "zh-CN"
|
||||
return "und"
|
||||
except:
|
||||
return "und"
|
||||
|
||||
Reference in New Issue
Block a user