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,42 @@
|
|||||||
|
# src/core/cache.py
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from core.logger import log
|
||||||
|
|
||||||
|
class JsonCacheManager:
|
||||||
|
"""全局无状态 JSON 缓存管理器"""
|
||||||
|
_caches = {}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _load_if_needed(cls, cache_path: Path):
|
||||||
|
path_str = str(cache_path)
|
||||||
|
if path_str not in cls._caches:
|
||||||
|
if cache_path.exists():
|
||||||
|
try:
|
||||||
|
cls._caches[path_str] = json.loads(cache_path.read_text('utf-8'))
|
||||||
|
except Exception as e:
|
||||||
|
log.warning(f"⚠️ 读取缓存失败 {cache_path}: {e}")
|
||||||
|
cls._caches[path_str] = {}
|
||||||
|
else:
|
||||||
|
cls._caches[path_str] = {}
|
||||||
|
return cls._caches[path_str]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get(cls, cache_path: Path, key: str, default=None):
|
||||||
|
cache_dict = cls._load_if_needed(cache_path)
|
||||||
|
return cache_dict.get(key, default)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def set(cls, cache_path: Path, key: str, value):
|
||||||
|
cache_dict = cls._load_if_needed(cache_path)
|
||||||
|
cache_dict[key] = value
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def save(cls, cache_path: Path):
|
||||||
|
path_str = str(cache_path)
|
||||||
|
if path_str in cls._caches:
|
||||||
|
try:
|
||||||
|
cache_path.write_text(json.dumps(cls._caches[path_str], ensure_ascii=False, indent=2), 'utf-8')
|
||||||
|
except Exception as e:
|
||||||
|
log.error(f"❌ 保存缓存落盘失败 {cache_path}: {e}")
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# src/core/constants.py
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
class RegexPatterns:
|
||||||
|
# 1. 结构与目录解析 (Parser)
|
||||||
|
SEASON_DIR = re.compile(r'^(?:S(?:eason)?[\s\-\_]*)?(\d{1,2})$', re.IGNORECASE)
|
||||||
|
FLAT_TV = re.compile(r'S(\d{1,2})E\d{1,3}|(?<!\d)(?:EP|E|第)(\d{1,3})(?:集)?(?!\d)', re.IGNORECASE)
|
||||||
|
PURE_NUMBER = re.compile(r'\d{1,3}')
|
||||||
|
YEAR_EXACT = re.compile(r'^\d{4}$')
|
||||||
|
TMDB_CLEAN = re.compile(r'^(.*?)\s*[\[\(](\d{4})[\]\)]')
|
||||||
|
|
||||||
|
# 2. 目标命名与集数提取 (Target Extraction)
|
||||||
|
TARGET_EP = re.compile(r'S\d{1,2}E(\d{1,4})|(?:EP|E|第|期)(\d{1,4})(?:集|话)?|(?<![a-zA-Z0-9])(\d{1,4})(?![a-zA-Z0-9])', re.IGNORECASE)
|
||||||
|
SUB_EP_MATCH = re.compile(r'S\d{1,2}E(\d{1,3})|(?<!\d)E(\d{1,3})(?!\d)', re.IGNORECASE)
|
||||||
|
SUB_TARGET_EP = re.compile(r'E(\d{2,3})')
|
||||||
|
|
||||||
|
# 3. 管道路由与防撞防爆锁 (Pipeline Anti-Collision)
|
||||||
|
TRACKER_EP = re.compile(r'(S\d{1,2}E\d{1,3})')
|
||||||
|
ROUTING_S_NUM = re.compile(r'S(\d{1,2})E')
|
||||||
|
|
||||||
|
# 4. 字幕探测与清洗 (Subtitle Tools)
|
||||||
|
SUB_LANG_CHT = re.compile(r'\.(cht|big5|zh-tw|tw|繁体)\.', re.IGNORECASE)
|
||||||
|
SUB_LANG_CHS = re.compile(r'\.(chs|gb|zh-cn|cn|简体|中英|双语|国语|粤语)\.', re.IGNORECASE)
|
||||||
|
SUB_LANG_ENG = re.compile(r'\.(eng|en|english)\.', re.IGNORECASE)
|
||||||
|
SUB_LANG_ZH_CHARS = re.compile(r'[\u4e00-\u9fa5]')
|
||||||
|
SUB_LANG_CHT_CHARS = re.compile(r'[傳統萬與飛沒]')
|
||||||
|
SUB_CLEAN_TAGS = re.compile(r'\{.*?\}')
|
||||||
|
|
||||||
|
# 5. 文件系统安全清理 (File System Santization)
|
||||||
|
FILE_SANITIZE = re.compile(r'[\\/*?:"<>|,!&:,!?、\s]+|\.+')
|
||||||
@@ -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