update 202605101839
This commit is contained in:
+45
-34
@@ -5,17 +5,17 @@ import sys
|
|||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# 💡 1. 路径兼容逻辑:确保无论是源码还是二进制执行,都能找到正确的位置
|
# 💡 路径兼容逻辑:确保无论是源码运行还是打包成二进制(EXE/Bin),都能定位到 main.py 所在的目录
|
||||||
if getattr(sys, 'frozen', False):
|
if getattr(sys, 'frozen', False):
|
||||||
# 二进制执行模式:.exe 所在的目录
|
# 二进制执行模式:获取 .exe/.bin 所在的目录
|
||||||
BASE_DIR = Path(sys.executable).parent
|
BASE_DIR = Path(sys.executable).parent
|
||||||
else:
|
else:
|
||||||
# 源码执行模式:src 的父目录
|
# 源码执行模式:src/core/config.py 的上两级就是 src 目录
|
||||||
BASE_DIR = Path(__file__).parent.parent.parent
|
BASE_DIR = Path(__file__).parent.parent
|
||||||
|
|
||||||
CONFIG_PATH = BASE_DIR / 'config.ini'
|
CONFIG_PATH = BASE_DIR / 'config.ini'
|
||||||
|
|
||||||
# 💡 2. 初始配置模板 (包含所有你刚才提到的灵活性参数)
|
# 💡 初始配置模板:当文件不存在时自动生成
|
||||||
DEFAULT_CONFIG_CONTENT = """# Media Manager 初始配置文件
|
DEFAULT_CONFIG_CONTENT = """# Media Manager 初始配置文件
|
||||||
|
|
||||||
[TMDB]
|
[TMDB]
|
||||||
@@ -27,6 +27,7 @@ max_retries = 3
|
|||||||
[Media]
|
[Media]
|
||||||
supported_exts = .mkv,.mp4,.avi
|
supported_exts = .mkv,.mp4,.avi
|
||||||
sidecar_exts = .nfo,.jpg,.jpeg,.png,.bif,.xml
|
sidecar_exts = .nfo,.jpg,.jpeg,.png,.bif,.xml
|
||||||
|
exclude_dirs =
|
||||||
|
|
||||||
[Ads]
|
[Ads]
|
||||||
keywords = TG频道,@yunpantv
|
keywords = TG频道,@yunpantv
|
||||||
@@ -44,51 +45,61 @@ remux_bitrate_1080p = 22.0
|
|||||||
remux_bitrate_4k = 45.0
|
remux_bitrate_4k = 45.0
|
||||||
|
|
||||||
[System]
|
[System]
|
||||||
# 日志文件路径:支持绝对路径或相对于程序根目录的相对路径
|
|
||||||
log_file_path = media_manager.log
|
log_file_path = media_manager.log
|
||||||
|
tmdb_cache_path = tmdb_data.json
|
||||||
console_log_level = INFO
|
console_log_level = INFO
|
||||||
file_log_level = DEBUG
|
file_log_level = DEBUG
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_parser = configparser.ConfigParser()
|
_parser = configparser.ConfigParser()
|
||||||
|
|
||||||
# 💡 3. 自动初始化逻辑
|
# 💡 自动初始化:如果没找到 config.ini,直接生一个默认的
|
||||||
if not CONFIG_PATH.exists():
|
if not CONFIG_PATH.exists():
|
||||||
with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
|
with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
|
||||||
f.write(DEFAULT_CONFIG_CONTENT)
|
f.write(DEFAULT_CONFIG_CONTENT)
|
||||||
print(f"✨ 已为您自动生成初始配置文件: {CONFIG_PATH}")
|
print(f"✨ 已为您自动生成初始配置文件: {CONFIG_PATH}")
|
||||||
print("💡 请编辑该文件填入 TMDB API Key 后重新启动。")
|
print("💡 请填入 TMDB API Key 后重新启动程序。")
|
||||||
# 如果没有配置就退出,或者你也可以选择继续运行基本模式
|
|
||||||
# sys.exit(0)
|
|
||||||
|
|
||||||
_parser.read(CONFIG_PATH, encoding='utf-8')
|
_parser.read(CONFIG_PATH, encoding='utf-8')
|
||||||
|
|
||||||
# --- 配置读取 (去冗余,靠默认值保障) ---
|
# --- 核心数据解耦 ---
|
||||||
|
|
||||||
# 💡 新增:日志路径自定义 (处理相对/绝对路径)
|
# 1. TMDB 配置
|
||||||
|
TMDB_API_KEY = _parser.get('TMDB', 'api_key', fallback='')
|
||||||
|
TMDB_LANGUAGE = _parser.get('TMDB', 'language', fallback='zh-CN')
|
||||||
|
TMDB_TIMEOUT = _parser.getint('TMDB', 'timeout', fallback=10)
|
||||||
|
TMDB_MAX_RETRIES = _parser.getint('TMDB', 'max_retries', fallback=3)
|
||||||
|
|
||||||
|
# 2. 媒体与广告
|
||||||
|
SUPPORTED_EXTS = set(_parser.get('Media', 'supported_exts', fallback='.mkv,.mp4,.avi').lower().split(','))
|
||||||
|
SIDECAR_EXTS = set(_parser.get('Media', 'sidecar_exts', fallback='.nfo,.jpg,.jpeg,.png,.bif,.xml').lower().split(','))
|
||||||
|
|
||||||
|
# 💡 新增:读取并清洗黑名单关键词
|
||||||
|
_excl_raw = _parser.get('Media', 'exclude_dirs', fallback='')
|
||||||
|
EXCLUDE_DIRS = [d.strip() for d in _excl_raw.split(',') if d.strip()]
|
||||||
|
|
||||||
|
AD_KEYWORDS = _parser.get('Ads', 'keywords', fallback='推广信息').split(',')
|
||||||
|
|
||||||
|
# 3. 功能开关
|
||||||
|
INCLUDE_TMDB_ID = _parser.getboolean('Features', 'include_tmdb_id', fallback=True)
|
||||||
|
EXTRACT_INTERNAL_SUBS = _parser.getboolean('Features', 'extract_internal_subs', fallback=False)
|
||||||
|
SKIP_PERFECT_MATCH = _parser.getboolean('Features', 'skip_perfect_match', fallback=True)
|
||||||
|
EXTRACT_SUBTITLE_CODECS = set(_parser.get('Features', 'extract_subtitle_codecs', fallback='ass,ssa,webvtt,subrip').split(','))
|
||||||
|
_langs_raw = _parser.get('Features', 'extract_subtitle_languages', fallback='zh-CN,zh-TW,en,und').strip()
|
||||||
|
EXTRACT_SUBTITLE_LANGUAGES = set(_langs_raw.split(',')) if _langs_raw.lower() != 'all' else None
|
||||||
|
|
||||||
|
# 4. 高级阈值
|
||||||
|
WATCH_DELAY = _parser.getint('Advanced', 'watch_delay', fallback=15)
|
||||||
|
REMUX_BITRATE_1080P = _parser.getfloat('Advanced', 'remux_bitrate_1080p', fallback=22.0)
|
||||||
|
REMUX_BITRATE_4K = _parser.getfloat('Advanced', 'remux_bitrate_4k', fallback=45.0)
|
||||||
|
|
||||||
|
# 5. 系统与日志路径
|
||||||
_raw_log_path = _parser.get('System', 'log_file_path', fallback='media_manager.log')
|
_raw_log_path = _parser.get('System', 'log_file_path', fallback='media_manager.log')
|
||||||
LOG_FILE_PATH = BASE_DIR / _raw_log_path if not os.path.isabs(_raw_log_path) else Path(_raw_log_path)
|
LOG_FILE_PATH = BASE_DIR / _raw_log_path if not os.path.isabs(_raw_log_path) else Path(_raw_log_path)
|
||||||
|
|
||||||
# 其他配置项读取 (直接使用 _parser,因为文件肯定存在了)
|
# 💡 新增:缓存路径读取与绝对/相对路径适配
|
||||||
SUPPORTED_EXTS = set(_parser.get('Media', 'supported_exts').lower().split(','))
|
_raw_cache_path = _parser.get('System', 'tmdb_cache_path', fallback='tmdb_cache.json')
|
||||||
SIDECAR_EXTS = set(_parser.get('Media', 'sidecar_exts').lower().split(','))
|
TMDB_CACHE_PATH = BASE_DIR / _raw_cache_path if not os.path.isabs(_raw_cache_path) else Path(_raw_cache_path)
|
||||||
AD_KEYWORDS = _parser.get('Ads', 'keywords').split(',')
|
|
||||||
|
|
||||||
TMDB_API_KEY = _parser.get('TMDB', 'api_key')
|
CONSOLE_LOG_LEVEL = _parser.get('System', 'console_log_level', fallback='INFO').upper()
|
||||||
TMDB_LANGUAGE = _parser.get('TMDB', 'language')
|
FILE_LOG_LEVEL = _parser.get('System', 'file_log_level', fallback='DEBUG').upper()
|
||||||
TMDB_TIMEOUT = _parser.getint('TMDB', 'timeout')
|
|
||||||
TMDB_MAX_RETRIES = _parser.getint('TMDB', 'max_retries')
|
|
||||||
|
|
||||||
INCLUDE_TMDB_ID = _parser.getboolean('Features', 'include_tmdb_id')
|
|
||||||
EXTRACT_INTERNAL_SUBS = _parser.getboolean('Features', 'extract_internal_subs')
|
|
||||||
SKIP_PERFECT_MATCH = _parser.getboolean('Features', 'skip_perfect_match')
|
|
||||||
EXTRACT_SUBTITLE_CODECS = set(_parser.get('Features', 'extract_subtitle_codecs').split(','))
|
|
||||||
_langs_raw = _parser.get('Features', 'extract_subtitle_languages').strip()
|
|
||||||
EXTRACT_SUBTITLE_LANGUAGES = set(_langs_raw.split(',')) if _langs_raw.lower() != 'all' else None
|
|
||||||
|
|
||||||
WATCH_DELAY = _parser.getint('Advanced', 'watch_delay')
|
|
||||||
REMUX_BITRATE_1080P = _parser.getfloat('Advanced', 'remux_bitrate_1080p')
|
|
||||||
REMUX_BITRATE_4K = _parser.getfloat('Advanced', 'remux_bitrate_4k')
|
|
||||||
|
|
||||||
CONSOLE_LOG_LEVEL = _parser.get('System', 'console_log_level').upper()
|
|
||||||
FILE_LOG_LEVEL = _parser.get('System', 'file_log_level').upper()
|
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
from core import config # 💡 引入新配置
|
from core import config
|
||||||
|
|
||||||
def setup_logger():
|
def setup_logger():
|
||||||
logger = logging.getLogger("MediaManager")
|
logger = logging.getLogger("MediaManager")
|
||||||
|
|||||||
+82
-37
@@ -12,45 +12,73 @@ class TaskManager:
|
|||||||
self.dir_renames = set()
|
self.dir_renames = set()
|
||||||
self.reserved_paths = set()
|
self.reserved_paths = set()
|
||||||
|
|
||||||
def reserve_path(self, desired_path: Path) -> Path:
|
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:
|
||||||
|
log.debug(f"🛡️ 触发幂等保护: [{source_name}] 尝试重复占用自己的坑位,已直接放行。")
|
||||||
|
return desired_path
|
||||||
|
|
||||||
final_path = desired_path
|
final_path = desired_path
|
||||||
idx = 2
|
idx = 2
|
||||||
while final_path.exists() or final_path in self.reserved_paths:
|
conflict_reason = ""
|
||||||
|
|
||||||
|
while True:
|
||||||
|
if final_path in self.reserved_paths:
|
||||||
|
conflict = True
|
||||||
|
first_claimer = self.claimants.get(str(final_path.resolve()), "未知文件")
|
||||||
|
conflict_reason = f"已被预占 (先占坑的内鬼是: {first_claimer})"
|
||||||
|
elif final_path.exists() and (source_path is None or final_path.resolve() != source_path.resolve()):
|
||||||
|
conflict = True
|
||||||
|
conflict_reason = "磁盘上已存在同名的目标文件"
|
||||||
|
else:
|
||||||
|
conflict = False
|
||||||
|
|
||||||
|
if not conflict:
|
||||||
|
break
|
||||||
|
|
||||||
final_path = desired_path.with_name(f"{desired_path.stem}.{idx}{desired_path.suffix}")
|
final_path = desired_path.with_name(f"{desired_path.stem}.{idx}{desired_path.suffix}")
|
||||||
idx += 1
|
idx += 1
|
||||||
|
|
||||||
if final_path != desired_path:
|
if final_path != desired_path:
|
||||||
log.debug(f"检测到路径冲突,已自动调整: {final_path.name}")
|
log.debug(f"⚠️ 路径冲突 ({conflict_reason}):")
|
||||||
|
log.debug(f" ├─ [源] {source_name}")
|
||||||
|
log.debug(f" └─ [新] {final_path.name}")
|
||||||
|
|
||||||
self.reserved_paths.add(final_path)
|
self.reserved_paths.add(final_path)
|
||||||
|
self.claimants[str(final_path.resolve())] = source_name
|
||||||
return final_path
|
return final_path
|
||||||
|
|
||||||
def add_extract(self, desc, func, args):
|
def add_extract(self, desc, func, args): self.tasks['extract'].append((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_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):
|
def add_season_dir_rename(self, old_dir, new_dir):
|
||||||
if old_dir not in self.dir_renames:
|
if old_dir not in self.dir_renames:
|
||||||
desc = f"{old_dir.name} --> {new_dir.name}"
|
# 💡 补上 [季目录] 前缀
|
||||||
|
desc = f"[季目录] {old_dir.name} --> {new_dir.name}"
|
||||||
self.tasks['rename_season_dir'].append((desc, old_dir.rename, new_dir))
|
self.tasks['rename_season_dir'].append((desc, old_dir.rename, new_dir))
|
||||||
self.dir_renames.add(old_dir)
|
self.dir_renames.add(old_dir)
|
||||||
|
|
||||||
def add_root_dir_rename(self, old_dir, new_dir):
|
def add_root_dir_rename(self, old_dir, new_dir):
|
||||||
if old_dir not in self.dir_renames:
|
if old_dir not in self.dir_renames:
|
||||||
desc = f"{old_dir.name} --> {new_dir.name}"
|
# 💡 补上 [根目录] 前缀
|
||||||
|
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, old_dir.rename, new_dir))
|
||||||
self.dir_renames.add(old_dir)
|
self.dir_renames.add(old_dir)
|
||||||
|
|
||||||
def preview_and_confirm(self, auto_execute=False) -> bool:
|
def preview_and_confirm(self, auto_execute=False) -> bool:
|
||||||
all_empty = True
|
# 💡 去掉了原来的 all_empty 相关的逻辑,因为现在会在外部提前拦截
|
||||||
|
|
||||||
if not auto_execute:
|
if not auto_execute:
|
||||||
log.info("" + "="*20 + " 待执行任务预览 " + "="*20)
|
log.info("==================== 待执行任务预览 ====================")
|
||||||
|
|
||||||
labels = [
|
labels = [
|
||||||
('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
|
('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
|
||||||
@@ -62,41 +90,58 @@ class TaskManager:
|
|||||||
|
|
||||||
for cat, label in labels:
|
for cat, label in labels:
|
||||||
if self.tasks[cat]:
|
if self.tasks[cat]:
|
||||||
all_empty = False
|
|
||||||
if not auto_execute:
|
if not auto_execute:
|
||||||
log.info(f"\n{label}")
|
log.info("")
|
||||||
|
log.info(label)
|
||||||
for desc, _, _ in self.tasks[cat]:
|
for desc, _, _ in self.tasks[cat]:
|
||||||
log.info(f" - {desc}")
|
log.info(f" - {desc}")
|
||||||
|
|
||||||
if not auto_execute:
|
if not auto_execute:
|
||||||
log.info("\n" + "="*56)
|
log.info("========================================================")
|
||||||
|
|
||||||
if all_empty:
|
|
||||||
if not auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何操作。")
|
|
||||||
return False
|
|
||||||
|
|
||||||
# 💡 守护模式接管,免除手工 y/n 敲击
|
|
||||||
if auto_execute:
|
if auto_execute:
|
||||||
log.info("🤖 守护模式已接管:发现待规范文件,自动确认并开始执行物理变更。")
|
log.info("🤖 守护模式已接管:发现待规范文件,自动确认并开始执行物理变更。")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
ans = input("⚠️ 是否确认执行以上物理变更?(y/n): ")
|
while True:
|
||||||
if ans.lower() == 'y':
|
ans = input("⚠️ 是否确认执行以上物理变更?[y/n/q]: ").strip().lower()
|
||||||
log.debug("用户确认执行任务。")
|
if ans in ['n', 'q']:
|
||||||
return True
|
log.debug("用户取消任务执行。")
|
||||||
else:
|
return False
|
||||||
log.debug("用户取消任务执行。")
|
# elif ans in ['y', '']: # 包含直接敲回车的情况
|
||||||
return False
|
elif ans in ['y']:
|
||||||
|
log.debug("用户确认执行任务。")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
log.warning("⛔ 无效输入:请输入 y(执行) 或 n/q(取消)")
|
||||||
|
|
||||||
def execute(self):
|
def execute(self):
|
||||||
stages = ['extract', 'clean', 'rename_file', 'rename_season_dir', 'rename_root_dir']
|
stages = ['extract', 'clean', 'rename_file', 'rename_season_dir', 'rename_root_dir']
|
||||||
for cat in stages:
|
for cat in stages:
|
||||||
if not self.tasks[cat]: continue
|
if not self.tasks[cat]: continue
|
||||||
for desc, func, arg in self.tasks[cat]:
|
for desc, func, arg in self.tasks[cat]:
|
||||||
action_name = desc.split(' -->')[0]
|
|
||||||
log.info(f"正在执行 -> {action_name}")
|
|
||||||
try:
|
try:
|
||||||
if isinstance(arg, tuple): func(*arg)
|
# 💡 针对重命名操作,开启详细物理路径追踪
|
||||||
else: func(arg)
|
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:
|
except Exception as e:
|
||||||
log.error(f"任务执行失败: {action_name} | 错误: {e}")
|
log.error(f"❌ 任务执行失败: {desc} | 错误: {e}")
|
||||||
+81
-11
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import sys
|
import sys
|
||||||
import argparse
|
import argparse
|
||||||
|
import re
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from core.logger import log
|
from core.logger import log
|
||||||
@@ -17,26 +18,46 @@ def run_pipeline(target_dir: Path, args, auto_execute=False):
|
|||||||
"""流水线作业:可被手动或守护进程触发"""
|
"""流水线作业:可被手动或守护进程触发"""
|
||||||
files_to_process = target_dir.rglob("*") if args.mode in ["auto", "watch"] else target_dir.glob("*")
|
files_to_process = target_dir.rglob("*") if args.mode in ["auto", "watch"] else target_dir.glob("*")
|
||||||
|
|
||||||
media_types_found = set()
|
# 💡 注意这里:用 media_types_by_root 替换掉最老的 media_types_found
|
||||||
|
media_types_by_root = {}
|
||||||
valid_files = []
|
valid_files = []
|
||||||
context_cache = {}
|
context_cache = {}
|
||||||
|
|
||||||
if not auto_execute: log.info("🔍 开始执行文件结构分析...")
|
if not auto_execute: log.info("🔍 开始执行文件结构分析...")
|
||||||
for f in files_to_process:
|
for f in files_to_process:
|
||||||
if f.is_file() and f.suffix.lower() in config.SUPPORTED_EXTS:
|
if f.is_file() and f.suffix.lower() in config.SUPPORTED_EXTS:
|
||||||
struct = RenamerService.infer_structure(f, context_cache)
|
|
||||||
|
# 🛡️ 神器 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
|
if not struct: continue
|
||||||
|
|
||||||
m_type = struct[0]
|
m_type = struct[0]
|
||||||
media_types_found.add(m_type)
|
root_dir_path = struct[5]
|
||||||
if len(media_types_found) > 1:
|
|
||||||
log.error("❌ 严重安全拦截:同一扫描目录下混合了电影和电视剧,请分目录存放!")
|
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)
|
if not auto_execute: sys.exit(1)
|
||||||
return # 守护模式下直接 return,不中断进程
|
return # 守护模式下直接 return,不中断进程
|
||||||
|
|
||||||
valid_files.append((f, *struct))
|
valid_files.append((f, *struct))
|
||||||
|
|
||||||
if not valid_files:
|
if not valid_files:
|
||||||
if not auto_execute: log.warning("⚠️ 扫描结束:未检测到任何支持的媒体文件。")
|
if not auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。")
|
||||||
return
|
return
|
||||||
|
|
||||||
dir_video_counts = {f.parent: 0 for f, *_ in valid_files}
|
dir_video_counts = {f.parent: 0 for f, *_ in valid_files}
|
||||||
@@ -46,31 +67,78 @@ def run_pipeline(target_dir: Path, args, auto_execute=False):
|
|||||||
if not auto_execute: log.info("📝 正在生成执行计划...")
|
if not auto_execute: log.info("📝 正在生成执行计划...")
|
||||||
task_mgr = TaskManager()
|
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:
|
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)
|
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)
|
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()}")
|
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"]
|
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 skip_heavy and not auto_execute:
|
||||||
if args.extract_internal:
|
if args.extract_internal:
|
||||||
log.info(f"💡 [特权放行] 《{title}》检测到强制参数,放行底层扫描。")
|
log.info(f"💡 [特权放行] {f.name} 检测到强制参数,放行底层扫描。")
|
||||||
else:
|
else:
|
||||||
log.info(f"✨ [完美豁免] 《{title}》已达最高工业标准,本次体检直接放行~")
|
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
|
||||||
|
|
||||||
if args.mode != "clean-ads":
|
if args.mode != "clean-ads":
|
||||||
RenamerService.scan_existing_subtitles(f, target_stem, m_type, task_mgr)
|
# 💡 传入 dest_dir
|
||||||
|
RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, task_mgr)
|
||||||
if (config.EXTRACT_INTERNAL_SUBS or args.extract_internal) and (not skip_heavy or args.extract_internal):
|
if (config.EXTRACT_INTERNAL_SUBS or args.extract_internal) and (not skip_heavy or args.extract_internal):
|
||||||
SubtitleService.scan_subtitles(f, task_mgr, target_stem)
|
# 💡 传入 dest_dir
|
||||||
|
SubtitleService.scan_subtitles(f, task_mgr, target_stem, dest_dir)
|
||||||
|
|
||||||
if args.mode != "extract-subs" and not skip_heavy:
|
if args.mode != "extract-subs" and not skip_heavy:
|
||||||
MetadataService.scan_ads(f, task_mgr)
|
MetadataService.scan_ads(f, task_mgr)
|
||||||
MetadataService.scan_audio_tracks(f, task_mgr)
|
MetadataService.scan_audio_tracks(f, task_mgr)
|
||||||
|
|
||||||
if args.mode not in ["clean-ads", "extract-subs"]:
|
if args.mode not in ["clean-ads", "extract-subs"]:
|
||||||
RenamerService.scan_rename(f, target_stem, m_type, target_season_folder, root_dir_path, folder_name, task_mgr)
|
# 💡 传入 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 task_mgr.preview_and_confirm(auto_execute):
|
||||||
if not auto_execute: log.info("⚙️ 正在执行物理任务...")
|
if not auto_execute: log.info("⚙️ 正在执行物理任务...")
|
||||||
task_mgr.execute()
|
task_mgr.execute()
|
||||||
@@ -78,11 +146,13 @@ def run_pipeline(target_dir: Path, args, auto_execute=False):
|
|||||||
elif not auto_execute:
|
elif not auto_execute:
|
||||||
log.info("💤 任务已由用户取消。")
|
log.info("💤 任务已由用户取消。")
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
|
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
|
||||||
parser.add_argument("mode", nargs='?', default="manual", choices=["manual", "auto", "clean-ads", "extract-subs", "watch"])
|
parser.add_argument("mode", nargs='?', default="manual", choices=["manual", "auto", "clean-ads", "extract-subs", "watch"])
|
||||||
parser.add_argument("-p", "--path", default=".")
|
parser.add_argument("-p", "--path", default=".")
|
||||||
parser.add_argument("--extract-internal", action="store_true")
|
parser.add_argument("--extract-internal", action="store_true")
|
||||||
|
parser.add_argument("-t", "--force-type", choices=["tv", "movie"], help="强制指定媒体类型 (tv 或 movie),解决正则误判")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
import json
|
import json
|
||||||
import subprocess
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from core import config
|
||||||
|
|
||||||
class MediaInfoService:
|
class MediaInfoService:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_info(file_path: Path):
|
def get_info(file_path: Path):
|
||||||
# 兼容旧的方法,这里可以保留空或返回基础信息
|
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -16,25 +16,27 @@ class MediaInfoService:
|
|||||||
利用 ffprobe 获取专业 Scene 技术标签及判定是否为 REMUX
|
利用 ffprobe 获取专业 Scene 技术标签及判定是否为 REMUX
|
||||||
"""
|
"""
|
||||||
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", str(f_path)]
|
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", str(f_path)]
|
||||||
|
# 兜底默认值
|
||||||
tags = {
|
tags = {
|
||||||
"res": "1080p", "v_codec": "H264", "bits": "8bit",
|
"res": "1080p", "v_codec": "H264", "bits": "8bit",
|
||||||
"a_info": "AAC.2.0", "is_remux": False
|
"a_info": "AAC.2.0", "is_remux": False
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 💡 将 stderr 丢进 DEVNULL,强行让 ffprobe 的警告闭嘴
|
|
||||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||||
data = json.loads(res.stdout)
|
data = json.loads(res.stdout)
|
||||||
|
|
||||||
# REMUX 判定逻辑:计算真实物理码率
|
|
||||||
duration = float(data.get('format', {}).get('duration', 0))
|
duration = float(data.get('format', {}).get('duration', 0))
|
||||||
if duration > 0:
|
if duration > 0:
|
||||||
size_bytes = f_path.stat().st_size
|
size_bytes = f_path.stat().st_size
|
||||||
mbps = (size_bytes * 8) / duration / 1_000_000
|
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
|
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):
|
if (h > 2000 and mbps > config.REMUX_BITRATE_4K) or (h <= 2000 and mbps > config.REMUX_BITRATE_1080P):
|
||||||
tags['is_remux'] = True
|
tags['is_remux'] = True
|
||||||
|
|
||||||
@@ -45,11 +47,11 @@ class MediaInfoService:
|
|||||||
if '265' in codec_name or 'hevc' in codec_name:
|
if '265' in codec_name or 'hevc' in codec_name:
|
||||||
tags['v_codec'] = "HEVC"
|
tags['v_codec'] = "HEVC"
|
||||||
|
|
||||||
# 修改 get_scene_tags 内部的位深判定
|
# 位深判定
|
||||||
if '10' in v_stream.get('pix_fmt', '') or '12' in v_stream.get('pix_fmt', ''):
|
if '10' in v_stream.get('pix_fmt', '') or '12' in v_stream.get('pix_fmt', ''):
|
||||||
tags['bits'] = "10bit"
|
tags['bits'] = "10bit"
|
||||||
|
|
||||||
# 音轨提取 (取第一条主音轨)
|
# 音轨提取
|
||||||
a_stream = next((s for s in data.get('streams', []) if s['codec_type'] == 'audio'), {})
|
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()
|
a_codec_raw = a_stream.get('codec_name', 'AAC').upper()
|
||||||
if 'DTS' in a_codec_raw: a_cod = 'DTS'
|
if 'DTS' in a_codec_raw: a_cod = 'DTS'
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# python/services/metadata_srv.py
|
# src/services/metadata.py
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import subprocess
|
import subprocess
|
||||||
@@ -10,7 +10,8 @@ class MetadataService:
|
|||||||
def scan_ads(file_path: Path, task_mgr):
|
def scan_ads(file_path: Path, task_mgr):
|
||||||
if file_path.suffix.lower() != ".mkv": return
|
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)]
|
cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream_tags=title", "-of", "csv=p=0:nk=1", str(file_path)]
|
||||||
video_title = subprocess.run(cmd, stdout=subprocess.PIPE, text=True).stdout.strip()
|
# 💡 补上 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):
|
if any(ad in video_title for ad in config.AD_KEYWORDS):
|
||||||
task_mgr.add_clean(
|
task_mgr.add_clean(
|
||||||
@@ -21,21 +22,20 @@ class MetadataService:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def do_clear(file_path):
|
def do_clear(file_path):
|
||||||
subprocess.run(["mkvpropedit", str(file_path), "--edit", "track:v1", "--delete", "name"], stdout=subprocess.DEVNULL)
|
subprocess.run(["mkvpropedit", str(file_path), "--edit", "track:v1", "--delete", "name"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
|
||||||
# 👇👇👇 新增:音轨智能钦定逻辑 👇👇👇
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def scan_audio_tracks(f_path: Path, task_mgr):
|
def scan_audio_tracks(f_path: Path, task_mgr):
|
||||||
if f_path.suffix.lower() != '.mkv':
|
if f_path.suffix.lower() != '.mkv':
|
||||||
return
|
return
|
||||||
|
|
||||||
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "a", str(f_path)]
|
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "a", str(f_path)]
|
||||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
|
# 💡 补上 stderr=subprocess.DEVNULL
|
||||||
|
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||||
try:
|
try:
|
||||||
data = json.loads(res.stdout)
|
data = json.loads(res.stdout)
|
||||||
streams = data.get('streams', [])
|
streams = data.get('streams', [])
|
||||||
|
|
||||||
# 💡 严格遵守需求:例外:如果有第三条或以上音轨,或只有一条,则不操作
|
|
||||||
if len(streams) != 2:
|
if len(streams) != 2:
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -43,24 +43,20 @@ class MetadataService:
|
|||||||
mandarin_aid = None
|
mandarin_aid = None
|
||||||
|
|
||||||
for i, s in enumerate(streams):
|
for i, s in enumerate(streams):
|
||||||
a_idx = i + 1 # 对应 mkvpropedit 的 track:a1, track:a2
|
a_idx = i + 1
|
||||||
lang = s.get('tags', {}).get('language', '').lower()
|
lang = s.get('tags', {}).get('language', '').lower()
|
||||||
title = s.get('tags', {}).get('title', '').lower()
|
title = s.get('tags', {}).get('title', '').lower()
|
||||||
is_default = s.get('disposition', {}).get('default', 0)
|
is_default = s.get('disposition', {}).get('default', 0)
|
||||||
|
|
||||||
# 识别粤语
|
|
||||||
if '粤' in title or lang == 'yue':
|
if '粤' in title or lang == 'yue':
|
||||||
cantonese_aid = (a_idx, is_default)
|
cantonese_aid = (a_idx, is_default)
|
||||||
# 识别国语/普通话
|
|
||||||
elif '国' in title or '普' in title or lang in ['cmn', 'chi', 'zho']:
|
elif '国' in title or '普' in title or lang in ['cmn', 'chi', 'zho']:
|
||||||
mandarin_aid = (a_idx, is_default)
|
mandarin_aid = (a_idx, is_default)
|
||||||
|
|
||||||
# 如果确实是一国一粤的经典配置
|
|
||||||
if cantonese_aid and mandarin_aid and cantonese_aid[0] != mandarin_aid[0]:
|
if cantonese_aid and mandarin_aid and cantonese_aid[0] != mandarin_aid[0]:
|
||||||
c_idx, c_def = cantonese_aid
|
c_idx, c_def = cantonese_aid
|
||||||
m_idx, m_def = mandarin_aid
|
m_idx, m_def = mandarin_aid
|
||||||
|
|
||||||
# 如果粤语已经是唯一的 default,且国语不是 default,直接跳过
|
|
||||||
if c_def == 1 and m_def == 0:
|
if c_def == 1 and m_def == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -74,7 +70,6 @@ class MetadataService:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def do_set_default_audio(f_path, c_idx, m_idx):
|
def do_set_default_audio(f_path, c_idx, m_idx):
|
||||||
# 瞬间修改 MKV 头部元数据
|
|
||||||
cmd = [
|
cmd = [
|
||||||
"mkvpropedit", str(f_path),
|
"mkvpropedit", str(f_path),
|
||||||
"--edit", f"track:a{c_idx}", "--set", "flag-default=1",
|
"--edit", f"track:a{c_idx}", "--set", "flag-default=1",
|
||||||
|
|||||||
+106
-51
@@ -8,39 +8,52 @@ from core import config
|
|||||||
from core.logger import log
|
from core.logger import log
|
||||||
|
|
||||||
class RenamerService:
|
class RenamerService:
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def infer_structure(file_path: Path, context_cache: dict):
|
def infer_structure(file_path: Path, context_cache: dict, forced_type: str = None):
|
||||||
parent_name = file_path.parent.name
|
parent_name = file_path.parent.name
|
||||||
grandparent_name = file_path.parent.parent.name
|
grandparent_name = file_path.parent.parent.name
|
||||||
|
|
||||||
# 1. 标准季目录识别
|
|
||||||
season_match = re.match(r'^(?:S(?:eason)?[\s\-\_]*)?(\d{1,2})$', parent_name, re.IGNORECASE)
|
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)
|
||||||
|
|
||||||
if season_match:
|
# 💡 核心改动:最高优先级判断 forced_type
|
||||||
m_type, season_num = "tv", season_match.group(1).zfill(2)
|
if forced_type == "tv" or (not forced_type and season_match):
|
||||||
target_season_folder = f"Season {season_num}"
|
m_type = "tv"
|
||||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
if season_match:
|
||||||
else:
|
season_num = season_match.group(1).zfill(2)
|
||||||
# 💡 2. 扁平电视节目嗅探 (Flat TV Show)
|
target_season_folder = f"Season {season_num}"
|
||||||
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)
|
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||||
pure_number_match = re.fullmatch(r'\d{1,3}', file_path.stem)
|
|
||||||
|
|
||||||
if 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 # 🛡️ 核心保护:设为 None 表示禁止重命名父目录
|
|
||||||
target_name, root_dir_path = parent_name, file_path.parent
|
|
||||||
else:
|
else:
|
||||||
m_type, season_num = "movie", "01"
|
# 扁平 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_season_folder = None
|
||||||
target_name, root_dir_path = parent_name, file_path.parent
|
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)
|
root_key = str(root_dir_path)
|
||||||
if root_key not in context_cache:
|
if root_key not in context_cache:
|
||||||
# 💡 核心修复:先剔除已有的 [tmdbid] 干扰
|
|
||||||
clean_name = re.sub(r'\s*[\[\(]tmdbid-\d+[\]\)]', '', target_name).strip()
|
clean_name = re.sub(r'\s*[\[\(]tmdbid-\d+[\]\)]', '', target_name).strip()
|
||||||
|
|
||||||
# 重新匹配标题和年份
|
|
||||||
tm = re.search(r'^(.*?)\s*[\[\(](\d{4})[\]\)]', clean_name)
|
tm = re.search(r'^(.*?)\s*[\[\(](\d{4})[\]\)]', clean_name)
|
||||||
if tm:
|
if tm:
|
||||||
title, year = tm.group(1).strip().replace(' ', '.'), tm.group(2)
|
title, year = tm.group(1).strip().replace(' ', '.'), tm.group(2)
|
||||||
@@ -48,7 +61,11 @@ class RenamerService:
|
|||||||
title, year = clean_name.strip().replace(' ', '.'), ""
|
title, year = clean_name.strip().replace(' ', '.'), ""
|
||||||
|
|
||||||
if not year:
|
if not year:
|
||||||
|
# 💡 取路径的最后三级(爷爷/爸爸/儿子),给用户提供充足的上下文
|
||||||
|
context_path = " / ".join(file_path.parts[-3:])
|
||||||
log.warning(f"目录命名不规范: {root_dir_path.name}")
|
log.warning(f"目录命名不规范: {root_dir_path.name}")
|
||||||
|
log.warning(f"📁 案发现场: {context_path}") # 👈 增加这一行,清晰定位
|
||||||
|
|
||||||
user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip()
|
user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip()
|
||||||
if user_title: title = user_title.replace(' ', '.')
|
if user_title: title = user_title.replace(' ', '.')
|
||||||
while not re.match(r'^\d{4}$', year):
|
while not re.match(r'^\d{4}$', year):
|
||||||
@@ -62,31 +79,39 @@ class RenamerService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False):
|
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)
|
tags = MediaInfoService.get_scene_tags(f_path)
|
||||||
# 💡 调用新的 search_media,并把 m_type 传给它
|
# 💡 这里多传一个 season_num,让 TMDB 服务自己决定要不要更新缓存
|
||||||
tmdb = TMDBService.search_media(title, year, m_type)
|
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('.')
|
||||||
|
|
||||||
# 💡 策略:文件名用英文/原名,文件夹用中文
|
|
||||||
eng = tmdb['english_title'] if tmdb else ""
|
|
||||||
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
|
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
|
||||||
|
|
||||||
# 组装技术串 (Scene 规范)
|
|
||||||
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
||||||
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||||
|
|
||||||
# 📁 文件夹:中文 (年份) [tmdbid]
|
# ⚠️ 根目录文件夹使用主年份 (剧集首播年份)
|
||||||
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
||||||
|
|
||||||
# 🎬 文件名:英文原名.年份.技术串
|
|
||||||
display_name = eng if eng else title
|
|
||||||
if m_type == "movie":
|
if m_type == "movie":
|
||||||
if is_multi_version:
|
if is_multi_version:
|
||||||
return f"{title} ({year}) - {display_name}.{tech}", target_folder
|
return f"{title} ({year}) - {tech}", target_folder
|
||||||
return f"{display_name}.{year}.{tech}", target_folder
|
return f"{display_name}.{year}.{tech}", target_folder
|
||||||
else:
|
else:
|
||||||
# 💡 强化正则:提取 S01E01, EP01, E01, 或纯数字 01
|
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(r'S\d{1,2}E(\d{1,3})|(?<!\d)(?:EP|E|第)?(\d{1,3})(?:集)?(?!\d)', f_path.name, re.IGNORECASE)
|
match = re.search(regex, f_path.stem, re.IGNORECASE)
|
||||||
ep = next((g for g in match.groups() if g), "01").zfill(2)
|
ep = next((g for g in match.groups() if g), "01").zfill(2) if match else "01"
|
||||||
return f"{display_name}.S{season_num}E{ep}.{year}.{tech}", target_folder
|
|
||||||
|
# 💡 核心新增:提取本季独立年份
|
||||||
|
# 默认使用主年份兜底,如果缓存中有 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
|
@staticmethod
|
||||||
def detect_subtitle_language(sub_path: Path) -> str:
|
def detect_subtitle_language(sub_path: Path) -> str:
|
||||||
@@ -103,7 +128,7 @@ class RenamerService:
|
|||||||
except: return "und"
|
except: return "und"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, task_mgr):
|
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, task_mgr):
|
||||||
for sub in f_path.parent.glob("*"):
|
for sub in f_path.parent.glob("*"):
|
||||||
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
|
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
|
||||||
is_match = False
|
is_match = False
|
||||||
@@ -118,41 +143,71 @@ class RenamerService:
|
|||||||
|
|
||||||
if is_match:
|
if is_match:
|
||||||
lang_tag = RenamerService.detect_subtitle_language(sub)
|
lang_tag = RenamerService.detect_subtitle_language(sub)
|
||||||
new_name = f"{target_stem}.{lang_tag}{sub.suffix.lower()}"
|
desired_path = dest_dir / f"{target_stem}.{lang_tag}{sub.suffix.lower()}"
|
||||||
if sub.name != new_name:
|
# 💡 传入 source_path,如果计算出的名字存在且就是自己,就不会强制加 .2
|
||||||
|
reserved_path = task_mgr.reserve_path(desired_path, source_path=sub)
|
||||||
|
|
||||||
|
|
||||||
|
if sub.resolve() != reserved_path.resolve():
|
||||||
task_mgr.add_file_rename(
|
task_mgr.add_file_rename(
|
||||||
f"[外挂字幕] {sub.name} --> {new_name}",
|
f"[外挂字幕] {sub.name} --> {reserved_path.name}",
|
||||||
RenamerService.do_rename_single,
|
RenamerService.do_rename_single,
|
||||||
(sub, task_mgr.reserve_path(sub.with_name(new_name)))
|
(sub, reserved_path)
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def scan_rename(f_path: Path, target_stem: str, m_type: str, target_season_folder: str, root_dir_path: Path, target_root_folder: str, task_mgr):
|
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):
|
||||||
new_path = f_path.with_name(f"{target_stem}{f_path.suffix.lower()}")
|
new_path = dest_dir / f"{target_stem}{f_path.suffix.lower()}"
|
||||||
|
reserved_new_path = task_mgr.reserve_path(new_path, source_path=f_path)
|
||||||
|
|
||||||
if f_path.name != new_path.name:
|
if f_path.resolve() != reserved_new_path.resolve():
|
||||||
task_mgr.add_file_rename(
|
task_mgr.add_file_rename(
|
||||||
f"[主视频] {f_path.name} --> {new_path.name}",
|
f"[主视频] {f_path.name} --> {reserved_new_path.name}",
|
||||||
RenamerService.do_rename_single,
|
RenamerService.do_rename_single,
|
||||||
(f_path, task_mgr.reserve_path(new_path))
|
(f_path, reserved_new_path)
|
||||||
)
|
)
|
||||||
|
|
||||||
for asset in f_path.parent.glob(f"{f_path.stem}*"):
|
for asset in f_path.parent.glob(f"{f_path.stem}*"):
|
||||||
if asset.is_file() and asset.suffix.lower() in config.SIDECAR_EXTS:
|
if asset.is_file() and asset.suffix.lower() in config.SIDECAR_EXTS:
|
||||||
new_asset_name = asset.name.replace(f_path.stem, target_stem, 1)
|
|
||||||
task_mgr.add_file_rename(
|
|
||||||
f"[附属元数据] {asset.name} --> {new_asset_name}",
|
|
||||||
RenamerService.do_rename_single,
|
|
||||||
(asset, task_mgr.reserve_path(asset.with_name(new_asset_name)))
|
|
||||||
)
|
|
||||||
|
|
||||||
# 💡 只有在 target_season_folder 存在时才允许修改季目录(完美跳过扁平电视节目)
|
# 💡 核心修复:边界安全检查
|
||||||
|
# 截取被匹配文件名多出来的“尾巴”部分
|
||||||
|
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,
|
||||||
|
(asset, reserved_asset)
|
||||||
|
)
|
||||||
|
|
||||||
|
# 这里的目录重命名逻辑保持不变,但增加一个防爆锁
|
||||||
if m_type == "tv" and target_season_folder and f_path.parent.name != target_season_folder:
|
if m_type == "tv" and target_season_folder and f_path.parent.name != target_season_folder:
|
||||||
task_mgr.add_season_dir_rename(f_path.parent, f_path.parent.with_name(target_season_folder))
|
if f_path.parent != root_dir_path: # 🛡️ 防爆锁:绝不允许对根目录执行季目录改名
|
||||||
|
task_mgr.add_season_dir_rename(f_path.parent, f_path.parent.with_name(target_season_folder))
|
||||||
|
|
||||||
if root_dir_path.name != target_root_folder:
|
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))
|
task_mgr.add_root_dir_rename(root_dir_path, root_dir_path.with_name(target_root_folder))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def do_rename_single(old_path: Path, new_path: Path):
|
def do_rename_single(old_path: Path, new_path: Path):
|
||||||
|
"""执行物理重命名/移动任务,并记录审计日志"""
|
||||||
if old_path.exists() and old_path != new_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)
|
old_path.rename(new_path)
|
||||||
|
# 注意:成功移动后的日志由 task.py 的 execute() 统一接管输出,此处无需重复打印
|
||||||
@@ -9,7 +9,7 @@ from core import config
|
|||||||
|
|
||||||
class SubtitleService:
|
class SubtitleService:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str):
|
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)]
|
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "s", str(file_path)]
|
||||||
try:
|
try:
|
||||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||||
@@ -49,10 +49,11 @@ class SubtitleService:
|
|||||||
lang_counts[lang_code] = lang_counts.get(lang_code, 0) + 1
|
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]}"
|
lang_suffix = "" if lang_counts[lang_code] == 1 else f".{lang_counts[lang_code]}"
|
||||||
|
|
||||||
desired_out_srt = file_path.with_name(f"{target_stem}.{lang_code}{lang_suffix}.srt")
|
# 💡 核心新增:确保提取出的字幕直接落地在目标季目录
|
||||||
|
desired_out_srt = dest_dir / f"{target_stem}.{lang_code}{lang_suffix}.srt"
|
||||||
out_srt = task_mgr.reserve_path(desired_out_srt)
|
out_srt = task_mgr.reserve_path(desired_out_srt)
|
||||||
|
|
||||||
temp_ass = file_path.with_name(f"{target_stem}.temp.{out_srt.name}.ass")
|
temp_ass = dest_dir / f"{target_stem}.temp.{out_srt.name}.ass"
|
||||||
|
|
||||||
task_mgr.add_extract(
|
task_mgr.add_extract(
|
||||||
f"{file_path.name} (内置轨道 {stream_idx} | 格式: {codec.upper()}) --> {out_srt.name}",
|
f"{file_path.name} (内置轨道 {stream_idx} | 格式: {codec.upper()}) --> {out_srt.name}",
|
||||||
|
|||||||
+75
-40
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import requests
|
import requests
|
||||||
|
import re
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from requests.adapters import HTTPAdapter
|
from requests.adapters import HTTPAdapter
|
||||||
from urllib3.util.retry import Retry
|
from urllib3.util.retry import Retry
|
||||||
@@ -9,25 +10,20 @@ from core import config
|
|||||||
from core.logger import log
|
from core.logger import log
|
||||||
|
|
||||||
class TMDBService:
|
class TMDBService:
|
||||||
# 💡 缓存文件路径放在根目录
|
_cache_file = config.TMDB_CACHE_PATH
|
||||||
_cache_file = Path(__file__).parent.parent.parent / 'tmdb_cache.json'
|
|
||||||
_cache = None
|
_cache = None
|
||||||
|
_notified_cache_hits = set() # 💡 新增:用于记录已经打印过“缓存命中”的键值,防止刷屏
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _load_cache(cls):
|
def _load_cache(cls):
|
||||||
"""加载本地缓存"""
|
|
||||||
if cls._cache is None:
|
if cls._cache is None:
|
||||||
if cls._cache_file.exists():
|
if cls._cache_file.exists():
|
||||||
try:
|
try: cls._cache = json.loads(cls._cache_file.read_text('utf-8'))
|
||||||
cls._cache = json.loads(cls._cache_file.read_text('utf-8'))
|
except: cls._cache = {}
|
||||||
except:
|
else: cls._cache = {}
|
||||||
cls._cache = {}
|
|
||||||
else:
|
|
||||||
cls._cache = {}
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _save_cache(cls):
|
def _save_cache(cls):
|
||||||
"""保存到本地缓存"""
|
|
||||||
if cls._cache is not None:
|
if cls._cache is not None:
|
||||||
cls._cache_file.write_text(json.dumps(cls._cache, ensure_ascii=False, indent=2), 'utf-8')
|
cls._cache_file.write_text(json.dumps(cls._cache, ensure_ascii=False, indent=2), 'utf-8')
|
||||||
|
|
||||||
@@ -38,64 +34,103 @@ class TMDBService:
|
|||||||
s.mount('https://', HTTPAdapter(max_retries=retries))
|
s.mount('https://', HTTPAdapter(max_retries=retries))
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _fetch_season_years(cls, session, tmdb_id):
|
||||||
|
"""🛠️ 专属辅助方法:根据 ID 获取所有季的年份字典"""
|
||||||
|
details_url = f"https://api.themoviedb.org/3/tv/{tmdb_id}"
|
||||||
|
season_years = {}
|
||||||
|
try:
|
||||||
|
resp = session.get(details_url, params={"api_key": config.TMDB_API_KEY.strip()}, timeout=config.TMDB_TIMEOUT)
|
||||||
|
if resp.status_code == 200:
|
||||||
|
for season in resp.json().get('seasons', []):
|
||||||
|
s_num = str(season.get('season_number', 0)).zfill(2)
|
||||||
|
air_date = season.get('air_date')
|
||||||
|
if air_date and len(air_date) >= 4:
|
||||||
|
season_years[s_num] = air_date[:4]
|
||||||
|
except Exception as e:
|
||||||
|
log.warning(f"获取剧集详情年份失败 [ID:{tmdb_id}]: {e}")
|
||||||
|
return season_years
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def search_media(title, year=None, m_type="movie"):
|
def search_media(title, year=None, m_type="movie", season_num=None): # 💡 1. 接收 season_num 传入
|
||||||
"""
|
|
||||||
智能搜索接口:自动区分电影/电视剧,并接入本地缓存
|
|
||||||
"""
|
|
||||||
if not config.TMDB_API_KEY:
|
if not config.TMDB_API_KEY:
|
||||||
log.debug("TMDB API Key 未配置,跳过在线刮削")
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 💡 1. 拦截层:检查本地缓存
|
|
||||||
TMDBService._load_cache()
|
TMDBService._load_cache()
|
||||||
cache_key = f"{m_type}_{title}_{year}"
|
cache_key = f"{m_type}_{title}_{year}"
|
||||||
|
|
||||||
if cache_key in TMDBService._cache:
|
if cache_key in TMDBService._cache:
|
||||||
log.debug(f"⚡ 命中 TMDB 本地缓存: {title} ({year})")
|
cached_data = TMDBService._cache[cache_key]
|
||||||
return TMDBService._cache[cache_key]
|
|
||||||
|
|
||||||
# 💡 2. 路由层:分流 Movie 和 TV 接口
|
# 💡 2. 局部缓存穿透检测与按需更新
|
||||||
|
if m_type == "tv" and season_num:
|
||||||
|
if season_num not in cached_data.get("season_years", {}):
|
||||||
|
log.info(f"🔄 {title} 缓存缺失新季数 (S{season_num}) 的年份,触发按需增量更新...")
|
||||||
|
tmdb_id = cached_data.get("tmdb_id")
|
||||||
|
if tmdb_id:
|
||||||
|
session = TMDBService._get_session()
|
||||||
|
new_sy = TMDBService._fetch_season_years(session, tmdb_id)
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
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"
|
endpoint = "tv" if m_type == "tv" else "movie"
|
||||||
url = f"https://api.themoviedb.org/3/search/{endpoint}"
|
url = f"https://api.themoviedb.org/3/search/{endpoint}"
|
||||||
|
params = {"api_key": config.TMDB_API_KEY.strip(), "query": title, "language": config.TMDB_LANGUAGE}
|
||||||
|
|
||||||
params = {
|
|
||||||
"api_key": config.TMDB_API_KEY.strip(),
|
|
||||||
"query": title,
|
|
||||||
"language": config.TMDB_LANGUAGE
|
|
||||||
}
|
|
||||||
|
|
||||||
# 电视剧的年份查询参数和电影不一样
|
|
||||||
if year:
|
if year:
|
||||||
if m_type == "tv":
|
if m_type == "tv": params["first_air_date_year"] = year
|
||||||
params["first_air_date_year"] = year
|
else: params["year"] = year
|
||||||
else:
|
|
||||||
params["year"] = year
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
session = TMDBService._get_session()
|
session = TMDBService._get_session()
|
||||||
log.debug(f"🌐 正在请求 TMDB [{endpoint.upper()}]: {title} ({year})")
|
log.debug(f"🌐 请求 TMDB [{endpoint.upper()}]: {title}")
|
||||||
resp = session.get(url, params=params, timeout=config.TMDB_TIMEOUT)
|
resp = session.get(url, params=params, timeout=config.TMDB_TIMEOUT)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
|
|
||||||
if resp.status_code == 200 and data.get('results'):
|
if resp.status_code == 200 and data.get('results'):
|
||||||
res = data['results'][0]
|
res = data['results'][0]
|
||||||
|
orig = res.get('original_name') if m_type == "tv" else res.get('original_title')
|
||||||
|
|
||||||
# 💡 电视剧取 original_name,电影取 original_title
|
clean_orig = re.sub(r'[\\/*?:"<>|,!&:,!?、\s]+|\.+', '.', orig.replace("'", "").replace("’", "")).strip('.') if orig else ""
|
||||||
original_title = res.get('original_name') if m_type == "tv" else res.get('original_title')
|
tmdb_id = res.get('id')
|
||||||
|
|
||||||
result = {
|
result = {
|
||||||
"english_title": original_title.replace(' ', '.') if original_title else "",
|
"original_title": clean_orig,
|
||||||
"tmdb_id": res.get('id')
|
"tmdb_id": tmdb_id
|
||||||
}
|
}
|
||||||
|
|
||||||
# 💡 3. 存储层:写回缓存并持久化
|
# 首次全量拉取
|
||||||
|
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._cache[cache_key] = result
|
||||||
TMDBService._save_cache()
|
TMDBService._save_cache()
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.error(f"TMDB 请求异常 [{title}]: {str(e)[:100]}...")
|
log.error(f"TMDB 异常 [{title}]: {e}")
|
||||||
|
|
||||||
return None
|
return None
|
||||||
Reference in New Issue
Block a user