Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75385c8255 | ||
|
|
73a328887f | ||
|
|
b389fc3901 | ||
|
|
53fdb1572c | ||
|
|
dfee0049fb |
+29
@@ -0,0 +1,29 @@
|
||||
.gitignore
|
||||
# 编译生成的文件
|
||||
*.o
|
||||
*.so
|
||||
*.exe
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.pyc
|
||||
|
||||
# 忽略 media 下的虚拟环境目录
|
||||
/media/bin/
|
||||
/media/include/
|
||||
/media/lib
|
||||
/media/lib64
|
||||
/media/pyvenv.cfg
|
||||
/media/README.md
|
||||
__pycache__/
|
||||
|
||||
/media/src/config.ini
|
||||
media/media_manager.log
|
||||
media/src/tmdb_data.json
|
||||
media/src/media_manager.log
|
||||
未来功能建议.md
|
||||
media/src_source*
|
||||
|
||||
# 与本项目无关的临时数据目录
|
||||
/xlsx/
|
||||
@@ -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,138 @@
|
||||
# src/core/pipeline.py
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from core.logger import log
|
||||
from core import config
|
||||
from core.constants import RegexPatterns
|
||||
from core.task import TaskManager
|
||||
from services.parser import ParserService
|
||||
from services.subtitle import SubtitleService
|
||||
from services.metadata import MetadataService
|
||||
from services.renamer import RenamerService
|
||||
|
||||
class MediaPipeline:
|
||||
"""中央流水线协调器:接管扫描、判定与防爆防撞逻辑"""
|
||||
|
||||
def __init__(self, target_dir: Path, args, auto_execute=False):
|
||||
self.target_dir = target_dir
|
||||
self.args = args
|
||||
self.auto_execute = auto_execute
|
||||
self.task_mgr = TaskManager()
|
||||
self.context_cache = {}
|
||||
self.media_types_by_root = {}
|
||||
self.tv_episode_tracker = {}
|
||||
self.valid_files = []
|
||||
|
||||
def run(self):
|
||||
self._analyze_files()
|
||||
if not self.valid_files:
|
||||
if not self.auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。")
|
||||
return
|
||||
|
||||
self._generate_plan()
|
||||
|
||||
if not self.task_mgr.has_tasks():
|
||||
if not self.auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何物理变更。")
|
||||
return
|
||||
|
||||
if self.task_mgr.preview_and_confirm(self.auto_execute):
|
||||
if not self.auto_execute: log.info("⚙️ 正在执行物理任务...")
|
||||
self.task_mgr.execute()
|
||||
log.info("🎉 流水线操作圆满落地!")
|
||||
elif not self.auto_execute:
|
||||
log.info("💤 任务已由用户取消。")
|
||||
|
||||
def _analyze_files(self):
|
||||
files_to_process = self.target_dir.rglob("*")
|
||||
if not self.auto_execute: log.info("🔍 开始执行文件结构分析...")
|
||||
|
||||
for f in files_to_process:
|
||||
if f.is_file() and f.suffix.lower() in config.SUPPORTED_EXTS:
|
||||
|
||||
# 黑名单拦截
|
||||
if any(excl in str(f) for excl in config.EXCLUDE_DIRS):
|
||||
log.debug(f"🛑 [黑名单拦截] 命中排除规则,跳过扫描: {f.parent.name}/{f.name}")
|
||||
continue
|
||||
|
||||
struct = ParserService.infer_structure(f, self.context_cache, forced_type=getattr(self.args, 'force_type', None))
|
||||
if not struct: continue
|
||||
|
||||
m_type = struct[0]
|
||||
root_dir_path = struct[5]
|
||||
|
||||
log.debug(f"判定: [{m_type.upper():^5}] <- {f.parent.name}/{f.name}")
|
||||
|
||||
# 剧集电影目录防爆锁
|
||||
if root_dir_path not in self.media_types_by_root:
|
||||
self.media_types_by_root[root_dir_path] = set()
|
||||
|
||||
self.media_types_by_root[root_dir_path].add(m_type)
|
||||
|
||||
if len(self.media_types_by_root[root_dir_path]) > 1:
|
||||
log.error(f"❌ 严重安全拦截:在同一目录 [{root_dir_path.name}] 下混合了电影和电视剧!")
|
||||
log.error(f"⚠️ 触发拦截的嫌疑文件: {f.name} (被判定为 {m_type})")
|
||||
if not self.auto_execute: sys.exit(1)
|
||||
return
|
||||
|
||||
self.valid_files.append((f, *struct))
|
||||
|
||||
def _generate_plan(self):
|
||||
if not self.auto_execute: log.info("📝 正在生成执行计划...")
|
||||
dir_video_counts = {f.parent: 0 for f, *_ in self.valid_files}
|
||||
for f, m_type, *_ in self.valid_files:
|
||||
if m_type == "movie": dir_video_counts[f.parent] += 1
|
||||
|
||||
for f, m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder in self.valid_files:
|
||||
is_multi = (m_type == "movie" and dir_video_counts.get(f.parent, 0) > 1)
|
||||
target_stem, folder_name = ParserService.get_target_info(f, m_type, title, year, season_num, is_multi)
|
||||
|
||||
# 集数防撞防爆锁
|
||||
if m_type == "tv":
|
||||
ep_match = RegexPatterns.TRACKER_EP.search(target_stem)
|
||||
if ep_match:
|
||||
ep_id = ep_match.group(1)
|
||||
tracker_key = (str(root_dir_path), ep_id)
|
||||
|
||||
if tracker_key in self.tv_episode_tracker:
|
||||
conflict_file = self.tv_episode_tracker[tracker_key]
|
||||
log.error("=" * 80)
|
||||
log.error(f"❌ 严重安全拦截:同剧集下发现重复的集号 [{ep_id}]!")
|
||||
log.error(f" ├─ [冲突文件 A]: {conflict_file.absolute()}")
|
||||
log.error(f" └─ [冲突文件 B]: {f.absolute()}")
|
||||
if not self.auto_execute: sys.exit(1)
|
||||
return
|
||||
else:
|
||||
self.tv_episode_tracker[tracker_key] = f
|
||||
|
||||
# 智能路由决策中心
|
||||
is_flat_tv = (m_type == "tv" and f.parent == root_dir_path)
|
||||
if is_flat_tv:
|
||||
ep_match = RegexPatterns.ROUTING_S_NUM.search(target_stem)
|
||||
s_num = ep_match.group(1) if ep_match else "01"
|
||||
dest_dir = root_dir_path / f"Season {s_num}"
|
||||
else:
|
||||
dest_dir = f.parent
|
||||
|
||||
is_perfect = (f.name == f"{target_stem}{f.suffix.lower()}")
|
||||
skip_heavy = config.SKIP_PERFECT_MATCH and is_perfect and self.args.mode not in ["clean-ads", "extract-subs"]
|
||||
|
||||
if skip_heavy and not self.auto_execute:
|
||||
if self.args.extract_internal:
|
||||
log.info(f"💡 [特权放行] {f.name} 检测到强制参数,放行底层扫描。")
|
||||
else:
|
||||
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
|
||||
|
||||
if self.args.mode != "clean-ads":
|
||||
has_ext_sub = RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, self.task_mgr)
|
||||
should_extract_internal = (not has_ext_sub) or config.EXTRACT_INTERNAL_SUBS or self.args.extract_internal
|
||||
|
||||
if should_extract_internal and (not skip_heavy or self.args.extract_internal or self.args.mode == "extract-subs"):
|
||||
SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||||
|
||||
if self.args.mode != "extract-subs" and not skip_heavy:
|
||||
MetadataService.scan_ads(f, self.task_mgr)
|
||||
MetadataService.scan_audio_tracks(f, self.task_mgr)
|
||||
|
||||
if self.args.mode not in ["clean-ads", "extract-subs"]:
|
||||
RenamerService.scan_rename(f, target_stem, m_type, dest_dir, target_season_folder, root_dir_path, folder_name, self.task_mgr)
|
||||
+8
-17
@@ -1,7 +1,9 @@
|
||||
# src/core/task.py
|
||||
|
||||
from pathlib import Path
|
||||
from .logger import log
|
||||
from core.logger import log
|
||||
# 💡 解耦:引入专门的文件操作服务
|
||||
from services.fileops import FileOpsService
|
||||
|
||||
class TaskManager:
|
||||
def __init__(self):
|
||||
@@ -15,13 +17,10 @@ class TaskManager:
|
||||
def has_tasks(self) -> bool:
|
||||
return any(self.tasks.values())
|
||||
|
||||
# 💡 增加 source_path,如果存在的文件就是自己,就不需要加 .2 防撞
|
||||
def reserve_path(self, desired_path: Path, source_path: Path = None) -> Path:
|
||||
if not hasattr(self, 'claimants'):
|
||||
self.claimants = {}
|
||||
|
||||
# 💡 终极防卫:认主机制(幂等性校验)
|
||||
# 如果这个坑位已经被占了,并且占坑的人就是“当前申请人”自己,直接返回原路径,绝不自己撞自己!
|
||||
source_name = source_path.name if source_path else "未知"
|
||||
if desired_path in self.reserved_paths:
|
||||
if self.claimants.get(str(desired_path.resolve())) == source_name:
|
||||
@@ -59,22 +58,21 @@ class TaskManager:
|
||||
def add_extract(self, desc, func, args): self.tasks['extract'].append((desc, func, args))
|
||||
def add_clean(self, desc, func, args): self.tasks['clean'].append((desc, func, args))
|
||||
def add_file_rename(self, desc, func, args): self.tasks['rename_file'].append((desc, func, args))
|
||||
|
||||
def add_season_dir_rename(self, old_dir, new_dir):
|
||||
if old_dir not in self.dir_renames:
|
||||
# 💡 补上 [季目录] 前缀
|
||||
desc = f"[季目录] {old_dir.name} --> {new_dir.name}"
|
||||
self.tasks['rename_season_dir'].append((desc, old_dir.rename, new_dir))
|
||||
# 💡 强制使用 FileOpsService 统一接管物理移动
|
||||
self.tasks['rename_season_dir'].append((desc, FileOpsService.move_file, (old_dir, new_dir)))
|
||||
self.dir_renames.add(old_dir)
|
||||
|
||||
def add_root_dir_rename(self, old_dir, new_dir):
|
||||
if old_dir not in self.dir_renames:
|
||||
# 💡 补上 [根目录] 前缀
|
||||
desc = f"[根目录] {old_dir.name} --> {new_dir.name}"
|
||||
self.tasks['rename_root_dir'].append((desc, old_dir.rename, new_dir))
|
||||
self.tasks['rename_root_dir'].append((desc, FileOpsService.move_file, (old_dir, new_dir)))
|
||||
self.dir_renames.add(old_dir)
|
||||
|
||||
def preview_and_confirm(self, auto_execute=False) -> bool:
|
||||
# 💡 去掉了原来的 all_empty 相关的逻辑,因为现在会在外部提前拦截
|
||||
if not auto_execute:
|
||||
log.info("==================== 待执行任务预览 ====================")
|
||||
|
||||
@@ -106,7 +104,6 @@ class TaskManager:
|
||||
if ans in ['n', 'q']:
|
||||
log.debug("用户取消任务执行。")
|
||||
return False
|
||||
# elif ans in ['y', '']: # 包含直接敲回车的情况
|
||||
elif ans in ['y']:
|
||||
log.debug("用户确认执行任务。")
|
||||
return True
|
||||
@@ -119,27 +116,21 @@ class TaskManager:
|
||||
if not self.tasks[cat]: continue
|
||||
for desc, func, arg in self.tasks[cat]:
|
||||
try:
|
||||
# 💡 针对重命名操作,开启详细物理路径追踪
|
||||
if cat in ['rename_file', 'rename_season_dir', 'rename_root_dir']:
|
||||
# 智能提取原始路径和目标路径
|
||||
old_p = arg[0] if isinstance(arg, tuple) else getattr(func, '__self__', None)
|
||||
new_p = arg[1] if isinstance(arg, tuple) else arg
|
||||
|
||||
if old_p and hasattr(old_p, 'exists') and old_p.exists():
|
||||
if old_p.resolve() != new_p.resolve():
|
||||
# 执行物理变更
|
||||
if isinstance(arg, tuple): func(*arg)
|
||||
else: func(arg)
|
||||
|
||||
# 💡 记录全景绝对路径日志
|
||||
log.info(f"✅ 重命名成功: [源] {old_p.absolute()} --> [终] {new_p.absolute()}")
|
||||
else:
|
||||
log.warning(f"⚠️ 跳过重命名,源路径不存在: {old_p}")
|
||||
else:
|
||||
# 对于非重命名任务(清理、提取等),保持常规日志
|
||||
action_name = desc.split(' -->')[0]
|
||||
log.info(f"⚙️ 正在执行 -> {action_name}")
|
||||
if isinstance(arg, tuple): func(*arg)
|
||||
else: func(arg)
|
||||
except Exception as e:
|
||||
log.error(f"❌ 任务执行失败: {desc} | 错误: {e}")
|
||||
log.error(f"❌ 任务执行失败: {desc} | 错误: {e}")
|
||||
|
||||
@@ -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"
|
||||
|
||||
+5
-148
@@ -2,154 +2,11 @@
|
||||
|
||||
import sys
|
||||
import argparse
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from core.logger import log
|
||||
from core import config
|
||||
from core.shell import check_dependencies
|
||||
from core.exceptions import MediaDependencyError
|
||||
from core.task import TaskManager
|
||||
from services.subtitle import SubtitleService
|
||||
from services.metadata import MetadataService
|
||||
from services.renamer import RenamerService
|
||||
|
||||
def run_pipeline(target_dir: Path, args, auto_execute=False):
|
||||
"""流水线作业:可被手动或守护进程触发"""
|
||||
# 💡 核心修改:废弃平铺的 glob,让所有模式(包括 extract-subs, clean-ads 等)统统使用 rglob 递归深入子目录
|
||||
files_to_process = target_dir.rglob("*")
|
||||
|
||||
media_types_by_root = {}
|
||||
valid_files = []
|
||||
context_cache = {}
|
||||
|
||||
if not auto_execute: log.info("🔍 开始执行文件结构分析...")
|
||||
for f in files_to_process:
|
||||
if f.is_file() and f.suffix.lower() in config.SUPPORTED_EXTS:
|
||||
|
||||
# 🛡️ 神器 1:黑名单绝对拦截机制
|
||||
if any(excl in str(f) for excl in config.EXCLUDE_DIRS):
|
||||
log.debug(f"🛑 [黑名单拦截] 命中排除规则,跳过扫描: {f.parent.name}/{f.name}")
|
||||
continue
|
||||
|
||||
# 🛠️ 神器 2:结构分析 (带上一票否决权 force_type)
|
||||
struct = RenamerService.infer_structure(f, context_cache, forced_type=getattr(args, 'force_type', None))
|
||||
if not struct: continue
|
||||
|
||||
m_type = struct[0]
|
||||
root_dir_path = struct[5]
|
||||
|
||||
log.debug(f"判定: [{m_type.upper():^5}] <- {f.parent.name}/{f.name}")
|
||||
|
||||
# 💣 神器 3:精确制导防爆锁 (防撞判定缩小到单个剧集/电影目录下)
|
||||
if root_dir_path not in media_types_by_root:
|
||||
media_types_by_root[root_dir_path] = set()
|
||||
|
||||
media_types_by_root[root_dir_path].add(m_type)
|
||||
|
||||
if len(media_types_by_root[root_dir_path]) > 1:
|
||||
log.error(f"❌ 严重安全拦截:在同一目录 [{root_dir_path.name}] 下混合了电影和电视剧!")
|
||||
log.error(f"⚠️ 触发拦截的嫌疑文件: {f.name} (被判定为 {m_type})")
|
||||
log.error("💡 提示:通常是因为剧集根目录下散落了未标明 S01E01 格式的花絮(SP/NCOP等)。")
|
||||
if not auto_execute: sys.exit(1)
|
||||
return # 守护模式下直接 return,不中断进程
|
||||
|
||||
valid_files.append((f, *struct))
|
||||
|
||||
if not valid_files:
|
||||
if not auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。")
|
||||
return
|
||||
|
||||
dir_video_counts = {f.parent: 0 for f, *_ in valid_files}
|
||||
for f, m_type, *_ in valid_files:
|
||||
if m_type == "movie": dir_video_counts[f.parent] += 1
|
||||
|
||||
if not auto_execute: log.info("📝 正在生成执行计划...")
|
||||
task_mgr = TaskManager()
|
||||
|
||||
# 🛡️ 神器 4:集数追尾防爆追踪器
|
||||
# 用于记录:{(剧集根目录, SxxExx) : 原始文件路径}
|
||||
tv_episode_tracker = {}
|
||||
|
||||
for f, m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder in valid_files:
|
||||
is_multi = (m_type == "movie" and dir_video_counts.get(f.parent, 0) > 1)
|
||||
target_stem, folder_name = RenamerService.get_target_info(f, m_type, title, year, season_num, is_multi)
|
||||
|
||||
# 💡 [保留原样] 新增:集数防撞绝对拦截逻辑
|
||||
if m_type == "tv":
|
||||
ep_match = re.search(r'(S\d{1,2}E\d{1,3})', target_stem)
|
||||
if ep_match:
|
||||
ep_id = ep_match.group(1) # 例如:S01E06
|
||||
tracker_key = (str(root_dir_path), ep_id)
|
||||
|
||||
if tracker_key in tv_episode_tracker:
|
||||
conflict_file = tv_episode_tracker[tracker_key]
|
||||
log.error("=" * 80)
|
||||
log.error(f"❌ 严重安全拦截:同剧集下发现重复的集号 [{ep_id}]!")
|
||||
log.error(f" ├─ [冲突文件 A]: {conflict_file.absolute()}")
|
||||
log.error(f" └─ [冲突文件 B]: {f.absolute()}")
|
||||
log.error("💡 提示:这通常是因为花絮/SP未加 S00 标签,或命名极其不规范导致正则提取碰撞。")
|
||||
log.error("🛡️ 为保护您的数据不被覆盖或错乱命名,流水线已紧急拉闸。请手动排查上述两个文件。")
|
||||
log.error("=" * 80)
|
||||
if not auto_execute: sys.exit(1)
|
||||
return # 守护模式下安全退出,不中断进程
|
||||
else:
|
||||
tv_episode_tracker[tracker_key] = f
|
||||
|
||||
# ==================== 💡 NEW: 智能路由决策中心 ====================
|
||||
is_flat_tv = (m_type == "tv" and f.parent == root_dir_path)
|
||||
|
||||
if is_flat_tv:
|
||||
# 扁平结构的 TV,提取季号,强制分配到根目录下的 Season 目录
|
||||
ep_match = re.search(r'S(\d{1,2})E', target_stem)
|
||||
s_num = ep_match.group(1) if ep_match else "01"
|
||||
dest_dir = root_dir_path / f"Season {s_num}"
|
||||
else:
|
||||
# 电影,或原本就已经在子目录的 TV,目标仍是当前目录(由后期的文件夹重命名接管)
|
||||
dest_dir = f.parent
|
||||
# ==================================================================
|
||||
|
||||
is_perfect = (f.name == f"{target_stem}{f.suffix.lower()}")
|
||||
skip_heavy = config.SKIP_PERFECT_MATCH and is_perfect and args.mode not in ["clean-ads", "extract-subs"]
|
||||
|
||||
if skip_heavy and not auto_execute:
|
||||
if args.extract_internal:
|
||||
log.info(f"💡 [特权放行] {f.name} 检测到强制参数,放行底层扫描。")
|
||||
else:
|
||||
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
|
||||
|
||||
if args.mode != "clean-ads":
|
||||
# 💡 步骤 1:先扫描外挂字幕,接收状态反馈
|
||||
has_ext_sub = RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, task_mgr)
|
||||
|
||||
# 💡 步骤 2:联动决策
|
||||
# 如果没有外挂字幕,或者用户在 config 开了全局强制,或者使用了 --extract-internal 参数,才执行内置提取
|
||||
should_extract_internal = (not has_ext_sub) or config.EXTRACT_INTERNAL_SUBS or args.extract_internal
|
||||
|
||||
if should_extract_internal and (not skip_heavy or args.extract_internal or args.mode == "extract-subs"):
|
||||
SubtitleService.scan_subtitles(f, task_mgr, target_stem, dest_dir)
|
||||
|
||||
if args.mode != "extract-subs" and not skip_heavy:
|
||||
MetadataService.scan_ads(f, task_mgr)
|
||||
MetadataService.scan_audio_tracks(f, task_mgr)
|
||||
|
||||
if args.mode not in ["clean-ads", "extract-subs"]:
|
||||
# 💡 传入 dest_dir
|
||||
RenamerService.scan_rename(f, target_stem, m_type, dest_dir, target_season_folder, root_dir_path, folder_name, task_mgr)
|
||||
|
||||
# 💡 [保留原样] 核心修复:提前拦截空任务,不再进入预览流程产生逻辑报错
|
||||
if not task_mgr.has_tasks():
|
||||
if not auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何物理变更。")
|
||||
return
|
||||
|
||||
# 这里才真正进入交互流程
|
||||
if task_mgr.preview_and_confirm(auto_execute):
|
||||
if not auto_execute: log.info("⚙️ 正在执行物理任务...")
|
||||
task_mgr.execute()
|
||||
log.info("🎉 流水线操作圆满落地!")
|
||||
elif not auto_execute:
|
||||
log.info("💤 任务已由用户取消。")
|
||||
|
||||
from core.pipeline import MediaPipeline # 💡 引入高度封装的管道中枢
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
|
||||
@@ -168,7 +25,6 @@ def main():
|
||||
target_dir = Path(args.path).resolve()
|
||||
log.info(f"🚀 启动模式: [{args.mode.upper()}] | 扫描目标: {target_dir}")
|
||||
|
||||
# 💡 守护模式接管入口
|
||||
if args.mode == "watch":
|
||||
try:
|
||||
from core.watcher import start_watch_daemon
|
||||
@@ -177,15 +33,16 @@ def main():
|
||||
sys.exit(1)
|
||||
|
||||
def scan_callback():
|
||||
run_pipeline(target_dir, args, auto_execute=True)
|
||||
# 💡 将重任交接给全新的 MediaPipeline
|
||||
MediaPipeline(target_dir, args, auto_execute=True).run()
|
||||
|
||||
start_watch_daemon(target_dir, scan_callback)
|
||||
else:
|
||||
run_pipeline(target_dir, args, auto_execute=False)
|
||||
MediaPipeline(target_dir, args, auto_execute=False).run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
log.error("🛑 接收到手动中断指令 (Ctrl+C),任务已安全终止。")
|
||||
sys.exit(130)
|
||||
sys.exit(130)
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# src/services/fileops.py
|
||||
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from core.logger import log
|
||||
|
||||
class FileOpsService:
|
||||
"""纯粹的物理层文件与目录操作服务"""
|
||||
|
||||
@staticmethod
|
||||
def move_file(old_path: Path, new_path: Path):
|
||||
"""执行物理重命名/移动任务,并记录审计日志。接入 shutil.move 保障跨盘跨 Docker 卷的安全"""
|
||||
if old_path.exists() and old_path != new_path:
|
||||
# 物理层变更审计:检测并创建缺失的目录
|
||||
if not new_path.parent.exists():
|
||||
log.info(f"🆕 发现目标目录不存在,正在执行物理创建: {new_path.parent.absolute()}")
|
||||
new_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
try:
|
||||
# 💡 替换掉了脆弱的 old_path.rename()
|
||||
shutil.move(str(old_path), str(new_path))
|
||||
except Exception as e:
|
||||
log.error(f"❌ 跨盘或物理移动失败 [源: {old_path.name}] -> [异常: {e}]")
|
||||
raise e
|
||||
@@ -1,9 +1,8 @@
|
||||
# src/services/mediainfo.py
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from core import config
|
||||
from core.utils import FFprobeUtil
|
||||
|
||||
class MediaInfoService:
|
||||
@staticmethod
|
||||
@@ -15,43 +14,38 @@ class MediaInfoService:
|
||||
"""
|
||||
利用 ffprobe 获取专业 Scene 技术标签及判定是否为 REMUX
|
||||
"""
|
||||
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", str(f_path)]
|
||||
# 兜底默认值
|
||||
tags = {
|
||||
"res": "1080p", "v_codec": "H264", "bits": "8bit",
|
||||
"a_info": "AAC.2.0", "is_remux": False
|
||||
}
|
||||
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
data = json.loads(res.stdout)
|
||||
# 💡 重构:直接调用 FFprobeUtil
|
||||
data = FFprobeUtil.get_json(f_path, "-show_format", "-show_streams")
|
||||
if not data:
|
||||
return tags
|
||||
|
||||
try:
|
||||
duration = float(data.get('format', {}).get('duration', 0))
|
||||
if duration > 0:
|
||||
size_bytes = f_path.stat().st_size
|
||||
mbps = (size_bytes * 8) / duration / 1_000_000
|
||||
|
||||
# 💡 就是漏了下面这一行!找回丢失的视频流数据!
|
||||
v_stream = next((s for s in data.get('streams', []) if s['codec_type'] == 'video'), {})
|
||||
|
||||
h = int(v_stream.get('height', 1080)) if v_stream.get('height') else 1080
|
||||
|
||||
# 接入动态码率阈值
|
||||
if (h > 2000 and mbps > config.REMUX_BITRATE_4K) or (h <= 2000 and mbps > config.REMUX_BITRATE_1080P):
|
||||
tags['is_remux'] = True
|
||||
|
||||
# 技术标签提取
|
||||
tags['res'] = "2160p" if h > 2000 else ("1080p" if h > 700 else "720p")
|
||||
|
||||
codec_name = v_stream.get('codec_name', '')
|
||||
if '265' in codec_name or 'hevc' in codec_name:
|
||||
tags['v_codec'] = "HEVC"
|
||||
|
||||
# 位深判定
|
||||
if '10' in v_stream.get('pix_fmt', '') or '12' in v_stream.get('pix_fmt', ''):
|
||||
tags['bits'] = "10bit"
|
||||
|
||||
# 音轨提取
|
||||
a_stream = next((s for s in data.get('streams', []) if s['codec_type'] == 'audio'), {})
|
||||
a_codec_raw = a_stream.get('codec_name', 'AAC').upper()
|
||||
if 'DTS' in a_codec_raw: a_cod = 'DTS'
|
||||
@@ -65,4 +59,4 @@ class MediaInfoService:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return tags
|
||||
return tags
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
# src/services/metadata.py
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from core import config
|
||||
from core.utils import FFprobeUtil
|
||||
|
||||
class MetadataService:
|
||||
@staticmethod
|
||||
def scan_ads(file_path: Path, task_mgr):
|
||||
if file_path.suffix.lower() != ".mkv": return
|
||||
cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream_tags=title", "-of", "csv=p=0:nk=1", str(file_path)]
|
||||
# 💡 补上 stderr=subprocess.DEVNULL 堵住 FFmpeg 的底层报错
|
||||
video_title = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True).stdout.strip()
|
||||
|
||||
if any(ad in video_title for ad in config.AD_KEYWORDS):
|
||||
@@ -29,11 +28,12 @@ class MetadataService:
|
||||
if f_path.suffix.lower() != '.mkv':
|
||||
return
|
||||
|
||||
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "a", str(f_path)]
|
||||
# 💡 补上 stderr=subprocess.DEVNULL
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
# 💡 重构:直接调用 FFprobeUtil
|
||||
data = FFprobeUtil.get_json(f_path, "-show_streams", "-select_streams", "a")
|
||||
if not data:
|
||||
return
|
||||
|
||||
try:
|
||||
data = json.loads(res.stdout)
|
||||
streams = data.get('streams', [])
|
||||
|
||||
if len(streams) != 2:
|
||||
@@ -75,4 +75,4 @@ class MetadataService:
|
||||
"--edit", f"track:a{c_idx}", "--set", "flag-default=1",
|
||||
"--edit", f"track:a{m_idx}", "--set", "flag-default=0"
|
||||
]
|
||||
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# src/services/parser.py
|
||||
|
||||
from pathlib import Path
|
||||
from core import config
|
||||
from core.logger import log
|
||||
from core.constants import RegexPatterns
|
||||
from core.utils import StringUtil
|
||||
from services.mediainfo import MediaInfoService
|
||||
from services.tmdb import TMDBService
|
||||
|
||||
class ParserService:
|
||||
"""纯业务计算与媒体结构解析器 (无状态)"""
|
||||
|
||||
@staticmethod
|
||||
def infer_structure(file_path: Path, context_cache: dict, forced_type: str = None):
|
||||
parent_name = file_path.parent.name
|
||||
grandparent_name = file_path.parent.parent.name
|
||||
|
||||
season_match = RegexPatterns.SEASON_DIR.match(parent_name)
|
||||
flat_tv_match = RegexPatterns.FLAT_TV.search(file_path.stem)
|
||||
pure_number_match = RegexPatterns.PURE_NUMBER.fullmatch(file_path.stem)
|
||||
|
||||
if forced_type == "tv" or (not forced_type and season_match):
|
||||
m_type = "tv"
|
||||
if season_match:
|
||||
season_num = season_match.group(1).zfill(2)
|
||||
target_season_folder = f"Season {season_num}"
|
||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||
else:
|
||||
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
|
||||
target_season_folder = None
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
|
||||
elif forced_type == "movie" or (not forced_type and not season_match and not (flat_tv_match or pure_number_match)):
|
||||
m_type = "movie"
|
||||
season_num = "01"
|
||||
target_season_folder = None
|
||||
|
||||
if season_match:
|
||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||
else:
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
|
||||
elif not forced_type and (flat_tv_match or pure_number_match):
|
||||
m_type = "tv"
|
||||
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
|
||||
target_season_folder = None
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
else:
|
||||
return None
|
||||
|
||||
root_key = str(root_dir_path)
|
||||
if root_key not in context_cache:
|
||||
clean_name = RegexPatterns.TMDB_CLEAN.sub('', target_name).strip()
|
||||
tm = RegexPatterns.TMDB_CLEAN.search(target_name)
|
||||
if tm:
|
||||
title, year = tm.group(1).strip().replace(' ', '.'), tm.group(2)
|
||||
else:
|
||||
title, year = clean_name.strip().replace(' ', '.'), ""
|
||||
|
||||
if not year:
|
||||
context_path = " / ".join(file_path.parts[-3:])
|
||||
log.warning(f"目录命名不规范: {root_dir_path.name}")
|
||||
log.warning(f"📁 案发现场: {context_path}")
|
||||
|
||||
user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip()
|
||||
if user_title: title = user_title.replace(' ', '.')
|
||||
while not RegexPatterns.YEAR_EXACT.match(year):
|
||||
year = input(f" ➤ 请输入 4 位年份: ").strip()
|
||||
|
||||
context_cache[root_key] = (title, year)
|
||||
|
||||
title, year = context_cache[root_key]
|
||||
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
|
||||
|
||||
@staticmethod
|
||||
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False):
|
||||
tags = MediaInfoService.get_scene_tags(f_path)
|
||||
tmdb = TMDBService.search_media(title, year, m_type, season_num)
|
||||
|
||||
orig = tmdb['original_title'] if tmdb else ""
|
||||
if orig:
|
||||
display_name = orig
|
||||
else:
|
||||
display_name = StringUtil.sanitize_title(title)
|
||||
|
||||
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
|
||||
|
||||
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
||||
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||
|
||||
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
||||
|
||||
if m_type == "movie":
|
||||
if is_multi_version:
|
||||
return f"{title} ({year}) - {tech}", target_folder
|
||||
return f"{display_name}.{year}.{tech}", target_folder
|
||||
else:
|
||||
match = RegexPatterns.TARGET_EP.search(f_path.stem)
|
||||
ep = next((g for g in match.groups() if g), "01").zfill(2) if match else "01"
|
||||
|
||||
episode_year = year
|
||||
if tmdb and "season_years" in tmdb:
|
||||
episode_year = tmdb["season_years"].get(season_num, year)
|
||||
|
||||
return f"{display_name}.S{season_num}E{ep}.{episode_year}.{tech}", target_folder
|
||||
+22
-154
@@ -1,175 +1,64 @@
|
||||
# src/services/renamer.py
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from .mediainfo import MediaInfoService
|
||||
from .tmdb import TMDBService
|
||||
from core import config
|
||||
from core.logger import log
|
||||
from core.constants import RegexPatterns
|
||||
from core.utils import MediaUtil
|
||||
from services.fileops import FileOpsService
|
||||
|
||||
class RenamerService:
|
||||
"""媒体文件规范重命名编排器"""
|
||||
|
||||
@staticmethod
|
||||
def infer_structure(file_path: Path, context_cache: dict, forced_type: str = None):
|
||||
parent_name = file_path.parent.name
|
||||
grandparent_name = file_path.parent.parent.name
|
||||
|
||||
season_match = re.match(r'^(?:S(?:eason)?[\s\-\_]*)?(\d{1,2})$', parent_name, re.IGNORECASE)
|
||||
flat_tv_match = re.search(r'S(\d{1,2})E\d{1,3}|(?<!\d)(?:EP|E|第)(\d{1,3})(?:集)?(?!\d)', file_path.stem, re.IGNORECASE)
|
||||
pure_number_match = re.fullmatch(r'\d{1,3}', file_path.stem)
|
||||
|
||||
# 💡 核心改动:最高优先级判断 forced_type
|
||||
if forced_type == "tv" or (not forced_type and season_match):
|
||||
m_type = "tv"
|
||||
if season_match:
|
||||
season_num = season_match.group(1).zfill(2)
|
||||
target_season_folder = f"Season {season_num}"
|
||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||
else:
|
||||
# 扁平 TV 兜底
|
||||
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
|
||||
target_season_folder = None
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
|
||||
elif forced_type == "movie" or (not forced_type and not season_match and not (flat_tv_match or pure_number_match)):
|
||||
m_type = "movie"
|
||||
season_num = "01"
|
||||
target_season_folder = None
|
||||
|
||||
# 容错:如果用户把电影放进了 "Season 1" 这种文件夹里,且被强制指定为 movie,需向上一级找根目录
|
||||
if season_match:
|
||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||
else:
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
|
||||
elif not forced_type and (flat_tv_match or pure_number_match):
|
||||
# 原本的自动扁平 TV 判断
|
||||
m_type = "tv"
|
||||
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
|
||||
target_season_folder = None
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
else:
|
||||
return None # 异常流保护
|
||||
|
||||
root_key = str(root_dir_path)
|
||||
if root_key not in context_cache:
|
||||
clean_name = re.sub(r'\s*[\[\(]tmdbid-\d+[\]\)]', '', target_name).strip()
|
||||
tm = re.search(r'^(.*?)\s*[\[\(](\d{4})[\]\)]', clean_name)
|
||||
if tm:
|
||||
title, year = tm.group(1).strip().replace(' ', '.'), tm.group(2)
|
||||
else:
|
||||
title, year = clean_name.strip().replace(' ', '.'), ""
|
||||
|
||||
if not year:
|
||||
# 💡 取路径的最后三级(爷爷/爸爸/儿子),给用户提供充足的上下文
|
||||
context_path = " / ".join(file_path.parts[-3:])
|
||||
log.warning(f"目录命名不规范: {root_dir_path.name}")
|
||||
log.warning(f"📁 案发现场: {context_path}") # 👈 增加这一行,清晰定位
|
||||
|
||||
user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip()
|
||||
if user_title: title = user_title.replace(' ', '.')
|
||||
while not re.match(r'^\d{4}$', year):
|
||||
year = input(f" ➤ 请输入 4 位年份: ").strip()
|
||||
|
||||
context_cache[root_key] = (title, year)
|
||||
|
||||
title, year = context_cache[root_key]
|
||||
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
|
||||
|
||||
@staticmethod
|
||||
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False):
|
||||
tags = MediaInfoService.get_scene_tags(f_path)
|
||||
# 💡 这里多传一个 season_num,让 TMDB 服务自己决定要不要更新缓存
|
||||
tmdb = TMDBService.search_media(title, year, m_type, season_num)
|
||||
orig = tmdb['original_title'] if tmdb else ""
|
||||
if orig:
|
||||
display_name = orig
|
||||
else:
|
||||
display_name = re.sub(r'[\\/*?:"<>|,!&:,!?、\s]+|\.+', '.', title.replace("'", "").replace("’", "")).strip('.')
|
||||
|
||||
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
|
||||
|
||||
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
||||
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||
|
||||
# ⚠️ 根目录文件夹使用主年份 (剧集首播年份)
|
||||
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
||||
|
||||
if m_type == "movie":
|
||||
if is_multi_version:
|
||||
return f"{title} ({year}) - {tech}", target_folder
|
||||
return f"{display_name}.{year}.{tech}", target_folder
|
||||
else:
|
||||
regex = 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])'
|
||||
match = re.search(regex, f_path.stem, re.IGNORECASE)
|
||||
ep = next((g for g in match.groups() if g), "01").zfill(2) if match else "01"
|
||||
|
||||
# 💡 核心新增:提取本季独立年份
|
||||
# 默认使用主年份兜底,如果缓存中有 season_years 且包含当前 season_num,则覆盖
|
||||
episode_year = year
|
||||
if tmdb and "season_years" in tmdb:
|
||||
episode_year = tmdb["season_years"].get(season_num, year)
|
||||
|
||||
# 文件名使用本季独立年份 episode_year
|
||||
return f"{display_name}.S{season_num}E{ep}.{episode_year}.{tech}", target_folder
|
||||
|
||||
@staticmethod
|
||||
def detect_subtitle_language(sub_path: Path) -> str:
|
||||
name = sub_path.name.lower()
|
||||
if re.search(r'\.(cht|big5|zh-tw|tw|繁体)\.', name): return "zh-TW"
|
||||
if re.search(r'\.(chs|gb|zh-cn|cn|简体|中英|双语|国语|粤语)\.', name): return "zh-CN"
|
||||
if re.search(r'\.(eng|en|english)\.', name): return "en"
|
||||
|
||||
try:
|
||||
content = sub_path.read_text(encoding='utf-8', errors='ignore')[:5000]
|
||||
if re.search(r'[\u4e00-\u9fa5]', content):
|
||||
return "zh-TW" if len(re.findall(r'[傳統萬與飛沒]', content)) > 5 else "zh-CN"
|
||||
return "und"
|
||||
except: return "und"
|
||||
|
||||
@staticmethod
|
||||
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, task_mgr) -> bool:
|
||||
has_external_sub = False # 💡 初始化状态标识
|
||||
has_external_sub = False
|
||||
for sub in f_path.parent.glob("*"):
|
||||
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
|
||||
is_match = False
|
||||
if f_path.stem in sub.name: is_match = True
|
||||
elif m_type == "tv":
|
||||
match = re.search(r'S\d{1,2}E(\d{1,3})|(?<!\d)E(\d{1,3})(?!\d)', sub.name, re.IGNORECASE)
|
||||
match = RegexPatterns.SUB_EP_MATCH.search(sub.name)
|
||||
if match:
|
||||
ep = next((g for g in match.groups() if g), None)
|
||||
target_ep_match = re.search(r'E(\d{2,3})', target_stem)
|
||||
target_ep_match = RegexPatterns.SUB_TARGET_EP.search(target_stem)
|
||||
if target_ep_match and ep and ep.zfill(2) == target_ep_match.group(1):
|
||||
is_match = True
|
||||
|
||||
if is_match:
|
||||
has_external_sub = True # 💡 只要匹配到,就说明存在外挂字幕
|
||||
lang_tag = RenamerService.detect_subtitle_language(sub)
|
||||
has_external_sub = True
|
||||
lang_tag = MediaUtil.detect_subtitle_language(sub)
|
||||
|
||||
# 💡 核心修改 1.2: 如果不是 srt,执行转换任务
|
||||
if sub.suffix.lower() != '.srt':
|
||||
desired_path = dest_dir / f"{target_stem}.{lang_tag}.srt"
|
||||
|
||||
# ==========================================
|
||||
# 🛡️ 恢复丢失的外挂转换前置拦截器
|
||||
# ==========================================
|
||||
if desired_path.exists() and desired_path.stat().st_size > 0:
|
||||
log.debug(f"✨ [跳过转换] 孪生 SRT 已存在,忽略外挂源文件: {sub.name}")
|
||||
continue
|
||||
|
||||
reserved_path = task_mgr.reserve_path(desired_path, source_path=sub)
|
||||
|
||||
from services.subtitle import SubtitleService # 延迟导入
|
||||
from services.subtitle import SubtitleService
|
||||
task_mgr.add_extract(
|
||||
f"[外挂字幕转换] {sub.name} --> {reserved_path.name}",
|
||||
SubtitleService.convert_to_srt,
|
||||
(sub, reserved_path)
|
||||
)
|
||||
else:
|
||||
# 是 srt,正常走重命名
|
||||
desired_path = dest_dir / f"{target_stem}.{lang_tag}.srt"
|
||||
reserved_path = task_mgr.reserve_path(desired_path, source_path=sub)
|
||||
|
||||
if sub.resolve() != reserved_path.resolve():
|
||||
task_mgr.add_file_rename(
|
||||
f"[规范外挂字幕] {sub.name} --> {reserved_path.name}",
|
||||
RenamerService.do_rename_single,
|
||||
FileOpsService.move_file,
|
||||
(sub, reserved_path)
|
||||
)
|
||||
|
||||
return has_external_sub # 💡 把结果返回给 main.py
|
||||
return has_external_sub
|
||||
|
||||
@staticmethod
|
||||
def scan_rename(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, target_season_folder: str, root_dir_path: Path, target_root_folder: str, task_mgr):
|
||||
@@ -179,31 +68,23 @@ class RenamerService:
|
||||
if f_path.resolve() != reserved_new_path.resolve():
|
||||
task_mgr.add_file_rename(
|
||||
f"[主视频] {f_path.name} --> {reserved_new_path.name}",
|
||||
RenamerService.do_rename_single,
|
||||
FileOpsService.move_file,
|
||||
(f_path, reserved_new_path)
|
||||
)
|
||||
|
||||
for asset in f_path.parent.glob(f"{f_path.stem}*"):
|
||||
if asset.is_file() and asset.suffix.lower() in config.SIDECAR_EXTS:
|
||||
|
||||
# 💡 核心修复:边界安全检查
|
||||
# 截取被匹配文件名多出来的“尾巴”部分
|
||||
rest_of_name = asset.name[len(f_path.stem):]
|
||||
|
||||
# 如果尾巴的第一个字符是字母或数字(比如 E10 匹配到了 E103,尾巴是 '3.nfo')
|
||||
# 说明这是一个“假匹配”,立刻跳过!
|
||||
if rest_of_name and rest_of_name[0].isalnum():
|
||||
continue
|
||||
|
||||
# 💡 安全组装:目标主文件名 + 剩余的合法尾巴 (如 '-thumb.jpg' 或 '.nfo')
|
||||
new_asset_name = f"{target_stem}{rest_of_name}"
|
||||
|
||||
reserved_asset = task_mgr.reserve_path(dest_dir / new_asset_name, source_path=asset)
|
||||
|
||||
if asset.resolve() != reserved_asset.resolve():
|
||||
task_mgr.add_file_rename(
|
||||
f"[附属元数据] {asset.name} --> {reserved_asset.name}",
|
||||
RenamerService.do_rename_single,
|
||||
FileOpsService.move_file,
|
||||
(asset, reserved_asset)
|
||||
)
|
||||
|
||||
@@ -214,16 +95,3 @@ class RenamerService:
|
||||
|
||||
if root_dir_path.name != target_root_folder:
|
||||
task_mgr.add_root_dir_rename(root_dir_path, root_dir_path.with_name(target_root_folder))
|
||||
|
||||
@staticmethod
|
||||
def do_rename_single(old_path: Path, new_path: Path):
|
||||
"""执行物理重命名/移动任务,并记录审计日志"""
|
||||
if old_path.exists() and old_path != new_path:
|
||||
# 💡 物理层变更审计:检测并创建缺失的季目录/电影目录
|
||||
if not new_path.parent.exists():
|
||||
log.info(f"🆕 发现目标目录不存在,正在执行物理创建: {new_path.parent.absolute()}")
|
||||
new_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 执行移动
|
||||
old_path.rename(new_path)
|
||||
# 注意:成功移动后的日志由 task.py 的 execute() 统一接管输出,此处无需重复打印
|
||||
@@ -1,22 +1,21 @@
|
||||
# src/services/subtitle.py
|
||||
|
||||
import re
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import pysubs2
|
||||
from core import config
|
||||
from core.logger import log
|
||||
from core.utils import FFprobeUtil
|
||||
|
||||
class SubtitleService:
|
||||
|
||||
# 💡 NEW: 新增专属的格式转换方法
|
||||
@staticmethod
|
||||
def convert_to_srt(in_sub: Path, out_srt: Path):
|
||||
"""将非 srt 的外挂字幕洗白并转换为 srt,成功后抹除源文件"""
|
||||
"""将非 srt 的外挂字幕洗白并转换为 srt,安全保留源文件"""
|
||||
try:
|
||||
subs = pysubs2.load(str(in_sub), encoding="utf-8")
|
||||
for line in subs:
|
||||
# 洗白特效标签
|
||||
line.text = re.sub(r'\{.*?\}', '', line.text)
|
||||
subs.save(str(out_srt), format="srt", encoding="utf-8")
|
||||
|
||||
@@ -25,11 +24,11 @@ class SubtitleService:
|
||||
|
||||
@staticmethod
|
||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path):
|
||||
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "s", str(file_path)]
|
||||
data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s")
|
||||
if not data:
|
||||
return
|
||||
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
data = json.loads(res.stdout)
|
||||
data = json.loads(res.stdout)
|
||||
streams = data.get('streams', [])
|
||||
lang_counts = {}
|
||||
|
||||
@@ -57,15 +56,21 @@ class SubtitleService:
|
||||
if lang_code == "und" and lang != "und":
|
||||
lang_code = lang[:3]
|
||||
|
||||
# 💡 核心新增:语言白名单拦截系统
|
||||
if config.EXTRACT_SUBTITLE_LANGUAGES and lang_code not in config.EXTRACT_SUBTITLE_LANGUAGES:
|
||||
continue
|
||||
|
||||
lang_counts[lang_code] = lang_counts.get(lang_code, 0) + 1
|
||||
lang_suffix = "" if lang_counts[lang_code] == 1 else f".{lang_counts[lang_code]}"
|
||||
|
||||
# 💡 核心修改 1.1:加上 .internal 标签,明确表示是由内置流提取的
|
||||
desired_out_srt = dest_dir / f"{target_stem}.internal.{lang_code}{lang_suffix}.srt"
|
||||
|
||||
# ==========================================
|
||||
# 🛡️ 恢复丢失的内置提取前置拦截器
|
||||
# ==========================================
|
||||
if desired_out_srt.exists() and desired_out_srt.stat().st_size > 0:
|
||||
log.debug(f"✨ [跳过提取] 目标内置字幕已存在,触发幂等保护: {desired_out_srt.name}")
|
||||
continue
|
||||
|
||||
out_srt = task_mgr.reserve_path(desired_out_srt)
|
||||
|
||||
temp_ass = dest_dir / f"{target_stem}.temp.{out_srt.name}.ass"
|
||||
@@ -94,4 +99,5 @@ class SubtitleService:
|
||||
finally:
|
||||
temp_ass.unlink(missing_ok=True)
|
||||
else:
|
||||
temp_ass.unlink(missing_ok=True)
|
||||
temp_ass.unlink(missing_ok=True)
|
||||
|
||||
|
||||
+16
-40
@@ -1,31 +1,15 @@
|
||||
# src/services/tmdb.py
|
||||
|
||||
import json
|
||||
import requests
|
||||
import re
|
||||
from pathlib import Path
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
from core import config
|
||||
from core.logger import log
|
||||
from core.utils import StringUtil
|
||||
from core.cache import JsonCacheManager # 💡 接入统一缓存层
|
||||
|
||||
class TMDBService:
|
||||
_cache_file = config.TMDB_CACHE_PATH
|
||||
_cache = None
|
||||
_notified_cache_hits = set() # 💡 新增:用于记录已经打印过“缓存命中”的键值,防止刷屏
|
||||
|
||||
@classmethod
|
||||
def _load_cache(cls):
|
||||
if cls._cache is None:
|
||||
if cls._cache_file.exists():
|
||||
try: cls._cache = json.loads(cls._cache_file.read_text('utf-8'))
|
||||
except: cls._cache = {}
|
||||
else: cls._cache = {}
|
||||
|
||||
@classmethod
|
||||
def _save_cache(cls):
|
||||
if cls._cache is not None:
|
||||
cls._cache_file.write_text(json.dumps(cls._cache, ensure_ascii=False, indent=2), 'utf-8')
|
||||
_notified_cache_hits = set()
|
||||
|
||||
@staticmethod
|
||||
def _get_session():
|
||||
@@ -36,7 +20,6 @@ class TMDBService:
|
||||
|
||||
@classmethod
|
||||
def _fetch_season_years(cls, session, tmdb_id):
|
||||
"""🛠️ 专属辅助方法:根据 ID 获取所有季的年份字典"""
|
||||
details_url = f"https://api.themoviedb.org/3/tv/{tmdb_id}"
|
||||
season_years = {}
|
||||
try:
|
||||
@@ -52,17 +35,17 @@ class TMDBService:
|
||||
return season_years
|
||||
|
||||
@staticmethod
|
||||
def search_media(title, year=None, m_type="movie", season_num=None): # 💡 1. 接收 season_num 传入
|
||||
def search_media(title, year=None, m_type="movie", season_num=None):
|
||||
if not config.TMDB_API_KEY:
|
||||
return None
|
||||
|
||||
TMDBService._load_cache()
|
||||
cache_path = config.TMDB_CACHE_PATH
|
||||
cache_key = f"{m_type}_{title}_{year}"
|
||||
|
||||
if cache_key in TMDBService._cache:
|
||||
cached_data = TMDBService._cache[cache_key]
|
||||
|
||||
# 💡 2. 局部缓存穿透检测与按需更新
|
||||
# 💡 利用解耦的缓存管理器
|
||||
cached_data = JsonCacheManager.get(cache_path, cache_key)
|
||||
|
||||
if cached_data:
|
||||
if m_type == "tv" and season_num:
|
||||
if season_num not in cached_data.get("season_years", {}):
|
||||
log.info(f"🔄 {title} 缓存缺失新季数 (S{season_num}) 的年份,触发按需增量更新...")
|
||||
@@ -74,27 +57,21 @@ class TMDBService:
|
||||
if "season_years" not in cached_data:
|
||||
cached_data["season_years"] = {}
|
||||
|
||||
# 合并 TMDB 返回的最新数据
|
||||
if new_sy:
|
||||
cached_data["season_years"].update(new_sy)
|
||||
|
||||
# 🛡️ 3. 终极防御:负向缓存 (Negative Cache)
|
||||
# 如果 TMDB 上目前确实连这部剧的第四季条目都没有创建,
|
||||
# 为了防止后续 E02、E03 疯狂请求接口引发雪崩限流,我们用首播年份给它强行占个坑
|
||||
if season_num not in cached_data["season_years"]:
|
||||
cached_data["season_years"][season_num] = year
|
||||
log.debug(f"⚠️ TMDB 暂无 S{season_num} 年份记录,已使用首播年份 ({year}) 兜底并锁定缓存。")
|
||||
|
||||
TMDBService._save_cache()
|
||||
JsonCacheManager.set(cache_path, cache_key, cached_data)
|
||||
JsonCacheManager.save(cache_path)
|
||||
|
||||
if cache_key not in TMDBService._notified_cache_hits:
|
||||
log.debug(f"⚡ TMDB 缓存命中: {title} ({year})")
|
||||
TMDBService._notified_cache_hits.add(cache_key)
|
||||
return cached_data
|
||||
|
||||
# =========================================================
|
||||
# 下面是常规的完全没有缓存时,首次搜索的逻辑
|
||||
# =========================================================
|
||||
endpoint = "tv" if m_type == "tv" else "movie"
|
||||
url = f"https://api.themoviedb.org/3/search/{endpoint}"
|
||||
params = {"api_key": config.TMDB_API_KEY.strip(), "query": title, "language": config.TMDB_LANGUAGE}
|
||||
@@ -113,7 +90,7 @@ class TMDBService:
|
||||
res = data['results'][0]
|
||||
orig = res.get('original_name') if m_type == "tv" else res.get('original_title')
|
||||
|
||||
clean_orig = re.sub(r'[\\/*?:"<>|,!&:,!?、\s]+|\.+', '.', orig.replace("'", "").replace("’", "")).strip('.') if orig else ""
|
||||
clean_orig = StringUtil.sanitize_title(orig)
|
||||
tmdb_id = res.get('id')
|
||||
|
||||
result = {
|
||||
@@ -121,16 +98,15 @@ class TMDBService:
|
||||
"tmdb_id": tmdb_id
|
||||
}
|
||||
|
||||
# 首次全量拉取
|
||||
if m_type == "tv" and tmdb_id:
|
||||
result["season_years"] = TMDBService._fetch_season_years(session, tmdb_id)
|
||||
# 同样执行负向缓存
|
||||
if season_num and season_num not in result["season_years"]:
|
||||
result["season_years"][season_num] = year
|
||||
|
||||
TMDBService._cache[cache_key] = result
|
||||
TMDBService._save_cache()
|
||||
JsonCacheManager.set(cache_path, cache_key, result)
|
||||
JsonCacheManager.save(cache_path)
|
||||
return result
|
||||
except Exception as e:
|
||||
log.error(f"TMDB 异常 [{title}]: {e}")
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Media Manager - 架构升级与边缘场景攻坚待办清单
|
||||
## 🔴 P0 - 底层稳定性与致命异常修复 (Critical Fixes)
|
||||
* [ ] **跨盘移动崩溃修复**: 将物理移动逻辑由 Path.rename() 升级为 shutil.move(),解决 Docker 跨卷或跨硬盘分区时的 Invalid cross-device link 异常。
|
||||
* [ ] **文件权限阻断降级**: 增加对 Read-Only 等权限异常的 try-catch 精细化捕获,防止 mkvpropedit 洗白广告时因权限不足导致整个扫描任务崩溃。
|
||||
## 🟠 P1 - 核心业务增强:解析边界突破 (Core Parsing Enhancements)
|
||||
### 电视节目深水区 (TV Show Edges)
|
||||
* [ ] **多集文件连播支持 (Multi-Episode)**: 优化正则提取与装箱逻辑,正确识别并保留 S01E01-E02 格式,保障播放器无缝连播体验。
|
||||
* [ ] **动漫绝对集数隔离 (Absolute Numbering)**: 阻断超大集数(如 1085)被误配为 Season 01 的情况,引入 Anime 专用识别特征或手动偏移映射。
|
||||
* [ ] **日期类节目兼容 (Daily Shows)**: 恢复并加固日期格式(YYYY.MM.DD / YYYY-MM-DD)正则,支持日更节目的准确定位与刮削。
|
||||
* [ ] **特殊剧集收容 (Specials & OVA)**: 将带有 SP、OVA、Extras 关键字的文件无条件归置入 Season 00 目录。
|
||||
### 电影深水区 (Movie Edges)
|
||||
* [ ] **分盘电影无缝组装 (Split Parts)**: 识别 CD1/CD2 或 Part1/Part2,确保同属一部电影的分片保留顺序后缀并落入同一文件夹。
|
||||
* [ ] **特殊版本信息提取 (Edition Tags)**: 解析并保留 Directors.Cut、Theatrical、Extended、Unrated 等关键标签,完善播放器的多版本管理机制。
|
||||
* [ ] **合集大包解构 (Collections)**: 增加对 Boxset / Collection 文件夹的下穿透逻辑,避免将合集总名称丢给 TMDB 搜索导致匹配失败。
|
||||
## 🟡 P2 - 字幕与周边元数据精细化治理 (Subtitles & Metadata)
|
||||
* [ ] **外挂字幕内容去重 (MD5 Deduplication)**: 引入文件指纹计算,自动剔除同一目录下内容完全相同但名称不同的外挂字幕。
|
||||
* [ ] **双语/多语种精准探针**: 改进语言识别权重计算,支持识别出带有 中英双语 标签的字幕并打上复合语言标签(如避免默认回退至单一 zh-CN)。
|
||||
* [ ] **孤儿文件垃圾回收**: 制定策略处理未包含在 SIDECAR_EXTS 白名单中的残余文件(如 宣传.url,打赏.jpg),防止源目录遗留空文件夹。
|
||||
* [ ] **TMDB 别名回退策略**: 解决动漫罗马音与中文偏好不匹配的问题,增加无结果时的搜索降级策略。
|
||||
## 🟣 P3 - 终极架构重构:影剧智能混排 (Next-Gen Architecture)
|
||||
* [ ] **接入 /search/multi 多维接口**: 剥离本地正则强判定的业务比重,将基础分词交由 TMDB 混合搜索接口进行判定。
|
||||
* [ ] **云端类型感知与动态路由**: 读取远端返回的 media_type 字段(tv 或 movie),以此为第一权重决定执行流水线。
|
||||
* [ ] **本地-云端冲突仲裁器**: 构建冲突解决逻辑(例如:云端返回 movie 但本地存在高置信度的 SxxExx 标签时,触发降级告警或强制覆盖保护)。
|
||||
Reference in New Issue
Block a user