This commit is contained in:
Hraulein
2026-05-09 20:00:30 +08:00
parent ab1fc775e9
commit d2fcb0df76
12 changed files with 604 additions and 235 deletions
+85 -10
View File
@@ -1,19 +1,94 @@
# src/core/config.py # src/core/config.py
import configparser import configparser
import sys
import os
from pathlib import Path from pathlib import Path
# 获取上一级目录(src)下的 config.ini 绝对路径 # 💡 1. 路径兼容逻辑:确保无论是源码还是二进制执行,都能找到正确的位置
_config_file = Path(__file__).parent.parent / 'config.ini' if getattr(sys, 'frozen', False):
# 二进制执行模式:.exe 所在的目录
BASE_DIR = Path(sys.executable).parent
else:
# 源码执行模式:src 的父目录
BASE_DIR = Path(__file__).parent.parent.parent
CONFIG_PATH = BASE_DIR / 'config.ini'
# 💡 2. 初始配置模板 (包含所有你刚才提到的灵活性参数)
DEFAULT_CONFIG_CONTENT = """# Media Manager 初始配置文件
[TMDB]
api_key =
language = zh-CN
timeout = 10
max_retries = 3
[Media]
supported_exts = .mkv,.mp4,.avi
sidecar_exts = .nfo,.jpg,.jpeg,.png,.bif,.xml
[Ads]
keywords = TG频道,@yunpantv
[Features]
include_tmdb_id = true
extract_internal_subs = false
skip_perfect_match = true
extract_subtitle_codecs = ass,ssa,webvtt,subrip,mov_text
extract_subtitle_languages = zh-CN,zh-TW,en,und
[Advanced]
watch_delay = 15
remux_bitrate_1080p = 22.0
remux_bitrate_4k = 45.0
[System]
# 日志文件路径:支持绝对路径或相对于程序根目录的相对路径
log_file_path = media_manager.log
console_log_level = INFO
file_log_level = DEBUG
"""
_parser = configparser.ConfigParser() _parser = configparser.ConfigParser()
# 读取配置文件,指定 utf-8 防止中文乱码
_parser.read(_config_file, encoding='utf-8')
# 解析为 Python 可用的集合与列表 # 💡 3. 自动初始化逻辑
SUPPORTED_EXTS = set(_parser.get('Media', 'supported_exts', fallback='.mkv,.mp4,.avi').split(',')) if not CONFIG_PATH.exists():
AD_KEYWORDS = _parser.get('Ads', 'keywords', fallback='TG频道,@yunpantv').split(',') with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
f.write(DEFAULT_CONFIG_CONTENT)
print(f"✨ 已为您自动生成初始配置文件: {CONFIG_PATH}")
print("💡 请编辑该文件填入 TMDB API Key 后重新启动。")
# 如果没有配置就退出,或者你也可以选择继续运行基本模式
# sys.exit(0)
# 新增 Features 配置解析 (布尔值) _parser.read(CONFIG_PATH, encoding='utf-8')
EXTRACT_INTERNAL_SUBS = _parser.getboolean('Features', 'extract_internal_subs', fallback=False)
SKIP_PERFECT_MATCH = _parser.getboolean('Features', 'skip_perfect_match', fallback=True) # --- 配置读取 (去冗余,靠默认值保障) ---
# 💡 新增:日志路径自定义 (处理相对/绝对路径)
_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)
# 其他配置项读取 (直接使用 _parser,因为文件肯定存在了)
SUPPORTED_EXTS = set(_parser.get('Media', 'supported_exts').lower().split(','))
SIDECAR_EXTS = set(_parser.get('Media', 'sidecar_exts').lower().split(','))
AD_KEYWORDS = _parser.get('Ads', 'keywords').split(',')
TMDB_API_KEY = _parser.get('TMDB', 'api_key')
TMDB_LANGUAGE = _parser.get('TMDB', 'language')
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()
+34
View File
@@ -0,0 +1,34 @@
# src/core/logger.py
import logging
import sys
from core import config # 💡 引入新配置
def setup_logger():
logger = logging.getLogger("MediaManager")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
fmt='[%(asctime)s] %(levelname)-7s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# 1. 控制台
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(getattr(logging, config.CONSOLE_LOG_LEVEL))
console_handler.setFormatter(formatter)
# 2. 文件 (路径从 config 获取)
# 💡 确保日志目录存在
config.LOG_FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
file_handler = logging.FileHandler(config.LOG_FILE_PATH, encoding='utf-8')
file_handler.setLevel(getattr(logging, config.FILE_LOG_LEVEL))
file_handler.setFormatter(formatter)
if not logger.handlers:
logger.addHandler(console_handler)
logger.addHandler(file_handler)
return logger
log = setup_logger()
+10 -2
View File
@@ -1,16 +1,24 @@
# python/core/shell.py # src/core/shell.py
import shutil import shutil
import subprocess import subprocess
from .exceptions import MediaDependencyError from .exceptions import MediaDependencyError
from .logger import log # 💡 引入日志
def check_dependencies(): def check_dependencies():
"""检查系统依赖是否已正确安装""" """检查系统依赖是否已正确安装"""
tools = ['ffmpeg', 'ffprobe', 'mkvpropedit', 'mediainfo'] tools = ['ffmpeg', 'ffprobe', 'mkvpropedit', 'mediainfo']
log.debug(f"正在检查系统依赖: {', '.join(tools)}")
missing = [tool for tool in tools if not shutil.which(tool)] missing = [tool for tool in tools if not shutil.which(tool)]
if missing: if missing:
raise MediaDependencyError(f"容器内缺少依赖: {', '.join(missing)}") error_msg = f"容器内缺少必要依赖: {', '.join(missing)}"
log.critical(error_msg) # 💡 致命错误级别
raise MediaDependencyError(error_msg)
log.debug("所有系统依赖检查通过。")
def run_command(cmd: list) -> subprocess.CompletedProcess: def run_command(cmd: list) -> subprocess.CompletedProcess:
"""安全执行终端命令""" """安全执行终端命令"""
log.debug(f"执行系统命令: {' '.join(cmd)}")
return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+42 -20
View File
@@ -1,6 +1,7 @@
# python/core/task_mgr.py # src/core/task.py
from pathlib import Path from pathlib import Path
from .logger import log
class TaskManager: class TaskManager:
def __init__(self): def __init__(self):
@@ -9,16 +10,18 @@ class TaskManager:
'rename_season_dir': [], 'rename_root_dir': [] 'rename_season_dir': [], 'rename_root_dir': []
} }
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 reserve_path(self, desired_path: Path) -> Path:
"""保证生成的路径全局唯一,冲突则自动追加数字 (如 .zh-CN.2.srt)"""
final_path = desired_path final_path = desired_path
idx = 2 idx = 2
while final_path.exists() or final_path in self.reserved_paths: while final_path.exists() or final_path in self.reserved_paths:
# 冲突时,在语言代码后缀前追加序号
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:
log.debug(f"检测到路径冲突,已自动调整: {final_path.name}")
self.reserved_paths.add(final_path) self.reserved_paths.add(final_path)
return final_path return final_path
@@ -43,38 +46,57 @@ class TaskManager:
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) -> bool: def preview_and_confirm(self, auto_execute=False) -> bool:
all_empty = True all_empty = True
print("\n================== 待执行任务预览 ==================")
if not auto_execute:
log.info("" + "="*20 + " 待执行任务预览 " + "="*20)
labels = [ labels = [
('extract', '🛠️ 阶段 1: 提取非SRT内置文本字幕'), ('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
('clean', '🧹 阶段 2: 清理元数据广告'), ('clean', '🧹 阶段 2: 清理元数据广告'),
('rename_file', '📄 阶段 3: 视频与外挂字幕规范化重命名'), ('rename_file', '📄 阶段 3: 视频与外挂字幕规范化重命名'),
('rename_season_dir', '📁 阶段 4: 季集目录规范化'), ('rename_season_dir', '📁 阶段 4: 季集目录规范化'),
('rename_root_dir', '🎬 阶段 5: 剧集/电影根目录规范化 (补充年份与标题)') ('rename_root_dir', '🎬 阶段 5: 剧集/电影根目录规范化')
] ]
for cat, label in labels: for cat, label in labels:
if self.tasks[cat]: if self.tasks[cat]:
all_empty = False all_empty = False
print(f"\n{label}") if not auto_execute:
for desc, _, _ in self.tasks[cat]: log.info(f"\n{label}")
print(f" - {desc}") for desc, _, _ in self.tasks[cat]:
log.info(f" - {desc}")
if not auto_execute:
log.info("\n" + "="*56)
print("\n====================================================")
if all_empty: if all_empty:
print("无需执行任何操作,您的媒体库目前非常完美!") if not auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何操作。")
return False return False
ans = input("⚠️ 请确认是否真实执行以上所有操作?(y/n): ") # 💡 守护模式接管,免除手工 y/n 敲击
return ans.lower() == 'y' if auto_execute:
log.info("🤖 守护模式已接管:发现待规范文件,自动确认并开始执行物理变更。")
return True
ans = input("⚠️ 是否确认执行以上物理变更?(y/n): ")
if ans.lower() == 'y':
log.debug("用户确认执行任务。")
return True
else:
log.debug("用户取消任务执行。")
return False
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
for desc, func, arg in self.tasks[cat]: for desc, func, arg in self.tasks[cat]:
print(f"执行 -> {desc.split(' -->')[0]}") action_name = desc.split(' -->')[0]
if isinstance(arg, tuple): log.info(f"正在执行 -> {action_name}")
func(*arg) try:
else: if isinstance(arg, tuple): func(*arg)
func(arg) else: func(arg)
except Exception as e:
log.error(f"任务执行失败: {action_name} | 错误: {e}")
+52
View File
@@ -0,0 +1,52 @@
# src/core/watcher.py
import time
import threading
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from .logger import log
from core import config
class MediaDirectoryWatcher(FileSystemEventHandler):
def __init__(self, target_dir, scan_callback):
self.target_dir = target_dir
self.scan_callback = scan_callback
self._timer = None
self._delay = config.WATCH_DELAY
def on_modified(self, event):
self._trigger(event.src_path)
def on_created(self, event):
self._trigger(event.src_path)
def on_moved(self, event):
self._trigger(event.dest_path)
def _trigger(self, path):
# 只对核心媒体文件的变动敏感
if any(path.lower().endswith(ext) for ext in ['.mkv', '.mp4', '.avi']):
if self._timer is not None:
self._timer.cancel()
# 重新启动倒计时 (防抖机制)
self._timer = threading.Timer(self._delay, self._run_callback)
self._timer.start()
def _run_callback(self):
log.info("👀 监测到新媒体文件落盘且已稳定,唤醒自动化流水线...")
self.scan_callback()
def start_watch_daemon(target_dir: Path, scan_callback):
log.info(f"👁️ 守护进程已启动,正时刻监听目录变动: {target_dir}")
event_handler = MediaDirectoryWatcher(target_dir, scan_callback)
observer = Observer()
observer.schedule(event_handler, str(target_dir), recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
log.info("🛑 守护进程已安全退出。")
observer.join()
+65 -76
View File
@@ -4,6 +4,7 @@ import sys
import argparse import argparse
from pathlib import Path from pathlib import Path
from core.logger import log
from core import config from core import config
from core.shell import check_dependencies from core.shell import check_dependencies
from core.exceptions import MediaDependencyError from core.exceptions import MediaDependencyError
@@ -11,118 +12,106 @@ from core.task import TaskManager
from services.subtitle import SubtitleService from services.subtitle import SubtitleService
from services.metadata import MetadataService from services.metadata import MetadataService
from services.renamer import RenamerService from services.renamer import RenamerService
from services.mediainfo import MediaInfoService
def main(): def run_pipeline(target_dir: Path, args, auto_execute=False):
parser = argparse.ArgumentParser( """流水线作业:可被手动或守护进程触发"""
description="🎬 流媒体高级自动化管理工具 (Media Manager)\n" files_to_process = target_dir.rglob("*") if args.mode in ["auto", "watch"] else target_dir.glob("*")
"===================================================\n"
"专为 Jellyfin/Emby 打造的本地媒体库刮削、去广告、字幕提取神器。",
formatter_class=argparse.RawTextHelpFormatter
)
mode_help = (
"指定要执行的工作模式 (默认为 manual):\n"
" manual : 【安全模式】仅处理指定目录的当前层级,不递归子目录。\n"
" auto : 【全自动模式】递归遍历所有子目录,智能整理整个媒体库。\n"
" clean-ads : 【专项清理】仅扫描并清除 MKV 元数据中的广告,不修改文件名。\n"
" extract-subs : 【专项字幕】仅提取并洗白内置中文字幕,不修改文件名。"
)
parser.add_argument("mode", nargs='?', default="manual", help=mode_help)
parser.add_argument("-p", "--path", default=".", help="指定要扫描的目标目录路径")
# 💡 新增:命令行动态覆盖参数
parser.add_argument(
"--extract-internal",
action="store_true",
help="[覆盖覆盖] 临时强制开启内置字幕提取 (无视 config.ini 中的 false)"
)
args = parser.parse_args()
try:
check_dependencies()
except MediaDependencyError as e:
print(f"❌ {e}")
sys.exit(1)
target_dir = Path(args.path).resolve()
print(f"🚀 启动模式: [{args.mode.upper()}] | 扫描目标: {target_dir}")
files_to_process = target_dir.rglob("*") if args.mode == "auto" else target_dir.glob("*")
media_types_found = set() media_types_found = set()
valid_files = [] valid_files = []
context_cache = {} context_cache = {}
print("🔍 正在执行第一次扫描 (分析文件结构)...") 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) struct = RenamerService.infer_structure(f, context_cache)
if not struct: continue
m_type = struct[0] m_type = struct[0]
media_types_found.add(m_type) media_types_found.add(m_type)
if len(media_types_found) > 1: if len(media_types_found) > 1:
print("\n❌ 严重安全拦截:同一个扫描根目录下同时检测到了【电影】和【电视剧】格式的混合体!") log.error("❌ 严重安全拦截:同一扫描目录下混合了电影和电视剧,请分目录存放!")
print(" 任务已强制终止!") if not auto_execute: sys.exit(1)
sys.exit(1) return # 守护模式下直接 return,不中断进程
valid_files.append((f, *struct)) valid_files.append((f, *struct))
# 👇👇👇 将下面这段全新的拦截逻辑插入到这里 👇👇👇
if not valid_files: if not valid_files:
print("\n⚠️ 扫描结束:未检测到任何支持的媒体文件。") if not auto_execute: log.warning("⚠️ 扫描结束:未检测到任何支持的媒体文件。")
if args.mode == "manual": return
print("💡 提示:您当前处于 [MANUAL] 模式,仅扫描指定目录的第一层级。")
print(" 如果您的视频都在子文件夹内,请追加 auto 参数 (例: media-rename auto)。")
sys.exit(0)
# 👆👆👆 -------------------------------- 👆👆👆
print("\n📝 正在生成执行计划...") 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() task_mgr = TaskManager()
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:
meta = MediaInfoService.get_info(f) is_multi = (m_type == "movie" and dir_video_counts.get(f.parent, 0) > 1)
target_stem = RenamerService.get_target_stem(f, m_type, title, year, season_num, meta) target_stem, folder_name = RenamerService.get_target_info(f, m_type, title, year, season_num, is_multi)
is_perfect_name = (f.name == f"{target_stem}{f.suffix.lower()}") is_perfect = (f.name == f"{target_stem}{f.suffix.lower()}")
skip_heavy_tasks = config.SKIP_PERFECT_MATCH and is_perfect_name 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_tasks:
if args.extract_internal: if args.extract_internal:
print(f" 💡 [特权放行] {f.name} 虽已合规,但检测到强制参数,放行字幕扫描。") log.info(f"💡 [特权放行] 《{title}》检测到强制参数,放行底层扫描。")
else: else:
print(f" ⏭️ [智能跳过] {f.name} 已完美合规,免除底层扫描。") log.info(f"✨ [完美豁免] 《{title}》已达最高工业标准,本次体检直接放行~")
if args.mode != "clean-ads": if args.mode != "clean-ads":
# 无论如何都要对齐外挂字幕
RenamerService.scan_existing_subtitles(f, target_stem, m_type, task_mgr) RenamerService.scan_existing_subtitles(f, target_stem, m_type, task_mgr)
if (config.EXTRACT_INTERNAL_SUBS or args.extract_internal) and (not skip_heavy or args.extract_internal):
should_extract_subs = config.EXTRACT_INTERNAL_SUBS or args.extract_internal
# 💡 核心修复:即使触发了跳过,只要携带了 args.extract_internal 依然强制提取
if should_extract_subs and (not skip_heavy_tasks or args.extract_internal):
SubtitleService.scan_subtitles(f, task_mgr, target_stem) SubtitleService.scan_subtitles(f, task_mgr, target_stem)
# 去广告任务依然遵守跳过原则(因为你没强制要求去广告) if args.mode != "extract-subs" and not skip_heavy:
if args.mode != "extract-subs" and not skip_heavy_tasks:
MetadataService.scan_ads(f, task_mgr) MetadataService.scan_ads(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, target_root_folder, task_mgr) RenamerService.scan_rename(f, target_stem, m_type, target_season_folder, root_dir_path, folder_name, task_mgr)
if task_mgr.preview_and_confirm(): if task_mgr.preview_and_confirm(auto_execute):
print("\n⚙️ 正在执行物理任务...") if not auto_execute: log.info("⚙️ 正在执行物理任务...")
task_mgr.execute() task_mgr.execute()
print("\n🎉 全部操作圆满落地!") log.info("🎉 流水线操作圆满落地!")
elif not auto_execute:
log.info("💤 任务已由用户取消。")
def main():
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
parser.add_argument("mode", nargs='?', default="manual", choices=["manual", "auto", "clean-ads", "extract-subs", "watch"])
parser.add_argument("-p", "--path", default=".")
parser.add_argument("--extract-internal", action="store_true")
args = parser.parse_args()
try:
check_dependencies()
except MediaDependencyError as e:
log.error(f"环境依赖检查失败: {e}")
sys.exit(1)
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
except ImportError:
log.critical("❌ 缺少 watchdog 依赖!请在终端执行: pip install watchdog")
sys.exit(1)
def scan_callback():
run_pipeline(target_dir, args, auto_execute=True)
start_watch_daemon(target_dir, scan_callback)
else:
run_pipeline(target_dir, args, auto_execute=False)
if __name__ == "__main__": if __name__ == "__main__":
try: try:
main() main()
except KeyboardInterrupt: except KeyboardInterrupt:
print("\n\n🛑 接收到手动中断指令 (Ctrl+C),任务已强制终止!") log.error("🛑 接收到手动中断指令 (Ctrl+C),任务已安全终止。")
print("💡 提示: 如果有正在提取的字幕,可能会留下 .temp.srt 临时文件。")
print(" 不用担心,您只需重新运行一次命令,脚本会自动覆盖并修复它们。")
sys.exit(130) sys.exit(130)
+55 -25
View File
@@ -1,36 +1,66 @@
# python/services/mediainfo_srv.py # src/services/mediainfo.py
import json import json
import subprocess
from pathlib import Path from pathlib import Path
from core.shell import run_command
class MediaInfoService: class MediaInfoService:
@staticmethod @staticmethod
def get_info(file_path: Path) -> dict: def get_info(file_path: Path):
cmd = ["mediainfo", "--Output=JSON", str(file_path)] # 兼容旧的方法,这里可以保留空或返回基础信息
return {}
@staticmethod
def get_scene_tags(f_path: Path):
"""
利用 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: try:
data = json.loads(run_command(cmd).stdout) # 💡 将 stderr 丢进 DEVNULL,强行让 ffprobe 的警告闭嘴
tracks = data.get("media", {}).get("track", []) res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
v_track = next((t for t in tracks if t.get("@type") == "Video"), {}) data = json.loads(res.stdout)
a_tracks = [t for t in tracks if t.get("@type") == "Audio"]
w = int(v_track.get("Width", 0)) # REMUX 判定逻辑:计算真实物理码率
res = "2160p" if w >= 3648 else "1080p" if w >= 1824 else "720p" if w >= 1216 else f"{w}x{v_track.get('Height', 0)}" duration = float(data.get('format', {}).get('duration', 0))
codec = v_track.get("Format", "") if duration > 0:
codec = "HEVC" if "HEVC" in codec or "H.265" in codec else "H264" if "AVC" in codec else codec size_bytes = f_path.stat().st_size
mbps = (size_bytes * 8) / duration / 1_000_000
audio_info, channels = "", "" h = int(v_stream.get('height', 1080)) if v_stream.get('height') else 1080
if a_tracks:
fmt = a_tracks[0].get("Format", "") # 💡 接入动态码率阈值
audio_info = "AC3" if "AC-3" in fmt else "EAC3" if "E-AC-3" in fmt else fmt.replace(" ", "") if (h > 2000 and mbps > config.REMUX_BITRATE_4K) or (h <= 2000 and mbps > config.REMUX_BITRATE_1080P):
channels = a_tracks[0].get("Channels", "") tags['is_remux'] = True
if len(a_tracks) > 1: audio_info = f"{len(a_tracks)}Audios"
# 技术标签提取
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"
# 修改 get_scene_tags 内部的位深判定
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'
elif 'TRUEHD' in a_codec_raw: a_cod = 'TrueHD'
elif 'AC3' in a_codec_raw: a_cod = 'AC3'
else: a_cod = a_codec_raw
ch = int(a_stream.get('channels', 2)) if a_stream.get('channels') else 2
tags['a_info'] = f"{a_cod}.{'5.1' if ch==6 else ('7.1' if ch==8 else '2.0')}"
return {
"res": res, "codec": codec,
"hdr": "HDR" if v_track.get("HDR_Format") else "",
"bit": f"{v_track.get('BitDepth')}bit" if v_track.get("BitDepth") else "",
"audio": audio_info, "ch": channels
}
except Exception: except Exception:
return {} pass
return tags
+60
View File
@@ -1,5 +1,6 @@
# python/services/metadata_srv.py # python/services/metadata_srv.py
import json
import subprocess import subprocess
from pathlib import Path from pathlib import Path
from core import config from core import config
@@ -21,3 +22,62 @@ 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)
# 👇👇👇 新增:音轨智能钦定逻辑 👇👇👇
@staticmethod
def scan_audio_tracks(f_path: Path, task_mgr):
if f_path.suffix.lower() != '.mkv':
return
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "a", str(f_path)]
res = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
try:
data = json.loads(res.stdout)
streams = data.get('streams', [])
# 💡 严格遵守需求:例外:如果有第三条或以上音轨,或只有一条,则不操作
if len(streams) != 2:
return
cantonese_aid = None
mandarin_aid = None
for i, s in enumerate(streams):
a_idx = i + 1 # 对应 mkvpropedit 的 track:a1, track:a2
lang = s.get('tags', {}).get('language', '').lower()
title = s.get('tags', {}).get('title', '').lower()
is_default = s.get('disposition', {}).get('default', 0)
# 识别粤语
if '粤' in title or lang == 'yue':
cantonese_aid = (a_idx, is_default)
# 识别国语/普通话
elif '国' in title or '普' in title or lang in ['cmn', 'chi', 'zho']:
mandarin_aid = (a_idx, is_default)
# 如果确实是一国一粤的经典配置
if cantonese_aid and mandarin_aid and cantonese_aid[0] != mandarin_aid[0]:
c_idx, c_def = cantonese_aid
m_idx, m_def = mandarin_aid
# 如果粤语已经是唯一的 default,且国语不是 default,直接跳过
if c_def == 1 and m_def == 0:
return
task_mgr.add_file_rename(
f"[音轨钦定] {f_path.name} --> 设置 粤语(轨道{c_idx}) 为默认音轨",
MetadataService.do_set_default_audio,
(f_path, c_idx, m_idx)
)
except Exception:
pass
@staticmethod
def do_set_default_audio(f_path, c_idx, m_idx):
# 瞬间修改 MKV 头部元数据
cmd = [
"mkvpropedit", str(f_path),
"--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)
+74 -73
View File
@@ -1,8 +1,11 @@
# python/services/renamer_srv.py # src/services/renamer.py
import re import re
from pathlib import Path from pathlib import Path
from .mediainfo import MediaInfoService from .mediainfo import MediaInfoService
from .tmdb import TMDBService
from core import config
from core.logger import log
class RenamerService: class RenamerService:
@staticmethod @staticmethod
@@ -10,6 +13,7 @@ class RenamerService:
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)
if season_match: if season_match:
@@ -17,121 +21,109 @@ class RenamerService:
target_season_folder = f"Season {season_num}" target_season_folder = f"Season {season_num}"
target_name, root_dir_path = grandparent_name, file_path.parent.parent target_name, root_dir_path = grandparent_name, file_path.parent.parent
else: else:
m_type, season_num = "movie", "01" # 💡 2. 扁平电视节目嗅探 (Flat TV Show)
target_season_folder = None 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 = parent_name, file_path.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:
m_type, season_num = "movie", "01"
target_season_folder = None
target_name, root_dir_path = parent_name, file_path.parent
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:
tm = re.match(r'^(.*?)(?:\s*[\[\(]?(\d{4})[\]\)]?)?$', target_name) # 💡 核心修复:先剔除已有的 [tmdbid] 干扰
title = tm.group(1).strip().replace(' ', '.') if tm else target_name clean_name = re.sub(r'\s*[\[\(]tmdbid-\d+[\]\)]', '', target_name).strip()
year = tm.group(2) if tm else ""
# 重新匹配标题和年份
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: if not year:
print(f"\n⚠️ 发现不规范的媒体目录: {root_dir_path.name}") log.warning(f"目录命名不规范: {root_dir_path.name}")
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 year: while not re.match(r'^\d{4}$', year):
year = input(f" ➤ 请输入正确的 4 位年份 (如 2023): ").strip() year = input(f" ➤ 请输入 4 位年份: ").strip()
if not re.match(r'^\d{4}$', year): year = ""
context_cache[root_key] = (title, year) context_cache[root_key] = (title, year)
else:
title, year = context_cache[root_key]
target_root_folder = f"{title.replace('.', ' ')} ({year})" title, year = context_cache[root_key]
return m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
@staticmethod @staticmethod
def get_target_stem(f_path: Path, m_type: str, title: str, year: str, season: str, meta: dict) -> str: def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False):
tags = [title] tags = MediaInfoService.get_scene_tags(f_path)
if m_type == "tv": # 💡 调用新的 search_media,并把 m_type 传给它
match = re.search(r'S\d{1,2}E(\d{1,3})|E(\d{1,3})|(?<!\d)(\d{2,3})(?!\d)', f_path.name, re.IGNORECASE) tmdb = TMDBService.search_media(title, year, m_type)
ep = next((g for g in match.groups() if g), "00").zfill(2) if match else "00"
tags.append(f"S{season}E{ep}")
if year: tags.append(year) # 💡 策略:文件名用英文/原名,文件夹用中文
if meta.get("res"): tags.append(meta.get("res")) eng = tmdb['english_title'] if tmdb else ""
if meta.get("hdr"): tags.append(meta.get("hdr")) tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
if meta.get("codec"): tags.append(meta.get("codec"))
if meta.get("bit"): tags.append(meta.get("bit"))
audio = meta.get("audio") # 组装技术串 (Scene 规范)
if audio: source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
if m_type == "movie" and meta.get("ch"): audio += f".{meta.get('ch')}.1" tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
tags.append(audio)
return re.sub(r'\s+', '.', ".".join(filter(None, tags))) # 📁 文件夹:中文 (年份) [tmdbid]
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
# 🎬 文件名:英文原名.年份.技术串
display_name = eng if eng else title
if m_type == "movie":
if is_multi_version:
return f"{title} ({year}) - {display_name}.{tech}", target_folder
return f"{display_name}.{year}.{tech}", target_folder
else:
# 💡 强化正则:提取 S01E01, EP01, E01, 或纯数字 01
match = re.search(r'S\d{1,2}E(\d{1,3})|(?<!\d)(?:EP|E|第)?(\d{1,3})(?:集)?(?!\d)', f_path.name, re.IGNORECASE)
ep = next((g for g in match.groups() if g), "01").zfill(2)
return f"{display_name}.S{season_num}E{ep}.{year}.{tech}", target_folder
@staticmethod @staticmethod
def detect_subtitle_language(sub_path: Path) -> str: def detect_subtitle_language(sub_path: Path) -> str:
"""无需三方库,通过文件名标签或字符嗅探识别语言"""
name = sub_path.name.lower() name = sub_path.name.lower()
if re.search(r'\.(cht|big5|zh-tw|tw|繁体)\.', name): return "zh-TW" if re.search(r'\.(cht|big5|zh-tw|tw|繁体)\.', name): return "zh-TW"
# 即使是中英双语,也统一归类为标准的 zh-CN
if re.search(r'\.(chs|gb|zh-cn|cn|简体|中英|双语|国语|粤语)\.', name): return "zh-CN" if re.search(r'\.(chs|gb|zh-cn|cn|简体|中英|双语|国语|粤语)\.', name): return "zh-CN"
if re.search(r'\.(eng|en|english)\.', name): return "en" if re.search(r'\.(eng|en|english)\.', name): return "en"
if re.search(r'\.(jpn|ja|jp)\.', name): return "ja"
if re.search(r'\.(kor|ko|kr)\.', name): return "ko"
try: try:
# 嗅探文件头 5000 字符
content = sub_path.read_text(encoding='utf-8', errors='ignore')[:5000] content = sub_path.read_text(encoding='utf-8', errors='ignore')[:5000]
# 核心修复:剔除 ASS 字幕的特效代码头,防止英文误判
content = re.sub(r'\[.*?\]', '', content)
content = re.sub(r'(Format|Style|Dialogue):.*?\n', '', content)
if re.search(r'[\u4e00-\u9fa5]', content): if re.search(r'[\u4e00-\u9fa5]', content):
# 简单繁体特征字判定 return "zh-TW" if len(re.findall(r'[傳統萬與飛沒]', content)) > 5 else "zh-CN"
if len(re.findall(r'[傳統萬與飛沒]', content)) > 5:
return "zh-TW"
return "zh-CN"
if re.search(r'[\u3040-\u30ff]', content): return "ja"
if re.search(r'[\uac00-\ud7af]', content): return "ko"
return "und"
except:
return "und" 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, 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
if f_path.stem in sub.name: is_match = True
# 关联判定策略
if f_path.stem in sub.name:
is_match = True
elif m_type == "tv": elif m_type == "tv":
# 匹配 E01 等集号
match = re.search(r'S\d{1,2}E(\d{1,3})|(?<!\d)E(\d{1,3})(?!\d)', sub.name, re.IGNORECASE) match = re.search(r'S\d{1,2}E(\d{1,3})|(?<!\d)E(\d{1,3})(?!\d)', sub.name, re.IGNORECASE)
if match: if match:
ep = next((g for g in match.groups() if g), None) 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 = re.search(r'E(\d{2,3})', target_stem)
if target_ep_match and ep and ep.zfill(2) == target_ep_match.group(1): if target_ep_match and ep and ep.zfill(2) == target_ep_match.group(1):
is_match = True is_match = True
else:
# 电影:当前目录只有一个视频时,通吃所有字幕
videos = [v for v in f_path.parent.glob("*") if v.suffix.lower() in {'.mkv', '.mp4', '.avi'}]
if len(videos) == 1:
is_match = True
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()}"
# 💡 核心修复:检查现有的名字是否已经完全合规 if sub.name != new_name:
# 合规正则: target_stem + .lang_tag + (可选的 .数字) + 后缀
pattern = r'^' + re.escape(target_stem) + r'\.' + re.escape(lang_tag) + r'(?:\.\d+)?' + re.escape(sub.suffix.lower()) + r'$'
# 如果不能完美匹配这个正则,说明语言后缀不对(比如存在 .zh-CN.en 或 .und),必须重命名
if not re.match(pattern, sub.name):
desired_path = sub.with_name(f"{target_stem}.{lang_tag}{sub.suffix.lower()}")
new_sub_path = task_mgr.reserve_path(desired_path)
task_mgr.add_file_rename( task_mgr.add_file_rename(
f"[外挂字幕] {sub.name} --> {new_sub_path.name}", f"[外挂字幕] {sub.name} --> {new_name}",
RenamerService.do_rename_single, RenamerService.do_rename_single,
(sub, new_sub_path) (sub, task_mgr.reserve_path(sub.with_name(new_name)))
) )
@staticmethod @staticmethod
@@ -144,8 +136,17 @@ class RenamerService:
RenamerService.do_rename_single, RenamerService.do_rename_single,
(f_path, task_mgr.reserve_path(new_path)) (f_path, task_mgr.reserve_path(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:
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)))
)
if m_type == "tv" and f_path.parent.name != target_season_folder: # 💡 只有在 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)) 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:
+16 -21
View File
@@ -1,33 +1,32 @@
# python/src/services/subtitle_srv.py # src/services/subtitle.py
import re import re
import json import json
import subprocess import subprocess
from pathlib import Path from pathlib import Path
import pysubs2 import pysubs2
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):
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)]
res = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
try: try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
data = json.loads(res.stdout)
data = json.loads(res.stdout) data = json.loads(res.stdout)
streams = data.get('streams', []) streams = data.get('streams', [])
lang_counts = {}
# 允许提取的文本字幕编码
text_codecs = ['ass', 'ssa', 'mov_text', 'webvtt', 'subrip']
for s in streams: for s in streams:
codec = s.get('codec_name', '') codec = s.get('codec_name', '')
if codec not in text_codecs: if codec not in config.EXTRACT_SUBTITLE_CODECS:
continue continue
lang = s.get('tags', {}).get('language', 'und').lower() lang = s.get('tags', {}).get('language', 'und').lower()
title = s.get('tags', {}).get('title', '').lower() title = s.get('tags', {}).get('title', '').lower()
stream_idx = s['index'] stream_idx = s['index']
# 语言推断引擎
lang_code = "und" lang_code = "und"
if lang in ['chi', 'zho', 'zh', 'chi-cn', 'zh-cn']: lang_code = 'zh-CN' if lang in ['chi', 'zho', 'zh', 'chi-cn', 'zh-cn']: lang_code = 'zh-CN'
elif lang in ['tw', 'hk', 'zh-tw']: lang_code = 'zh-TW' elif lang in ['tw', 'hk', 'zh-tw']: lang_code = 'zh-TW'
@@ -35,7 +34,6 @@ class SubtitleService:
elif lang in ['jpn', 'ja']: lang_code = 'ja' elif lang in ['jpn', 'ja']: lang_code = 'ja'
elif lang in ['kor', 'ko']: lang_code = 'ko' elif lang in ['kor', 'ko']: lang_code = 'ko'
# 标题语义纠偏:所有双语均归为标准 zh-CN
if '繁' in title or 'tw' in title or 'hk' in title or 'cht' in title: lang_code = 'zh-TW' if '繁' in title or 'tw' in title or 'hk' in title or 'cht' in title: lang_code = 'zh-TW'
elif '简' in title or 'cn' in title or '双语' in title or '中' in title or 'chs' in title: lang_code = 'zh-CN' elif '简' in title or 'cn' in title or '双语' in title or '中' in title or 'chs' in title: lang_code = 'zh-CN'
elif '英' in title and lang_code == 'und': lang_code = 'en' elif '英' in title and lang_code == 'und': lang_code = 'en'
@@ -44,14 +42,20 @@ class SubtitleService:
if lang_code == "und" and lang != "und": if lang_code == "und" and lang != "und":
lang_code = lang[:3] lang_code = lang[:3]
desired_out_srt = file_path.with_name(f"{target_stem}.{lang_code}.srt") # 💡 核心新增:语言白名单拦截系统
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]}"
desired_out_srt = file_path.with_name(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)
# 💡 核心改变:临时文件使用 .ass 后缀,让 ffmpeg 完整保留结构
temp_ass = file_path.with_name(f"{target_stem}.temp.{out_srt.name}.ass") temp_ass = file_path.with_name(f"{target_stem}.temp.{out_srt.name}.ass")
task_mgr.add_extract( task_mgr.add_extract(
f"{file_path.name} (内置轨道 {stream_idx}) --> {out_srt.name}", f"{file_path.name} (内置轨道 {stream_idx} | 格式: {codec.upper()}) --> {out_srt.name}",
SubtitleService.do_extract, SubtitleService.do_extract,
(file_path, stream_idx, temp_ass, out_srt) (file_path, stream_idx, temp_ass, out_srt)
) )
@@ -60,27 +64,18 @@ class SubtitleService:
@staticmethod @staticmethod
def do_extract(file_path, stream_index, temp_ass, out_srt): def do_extract(file_path, stream_index, temp_ass, out_srt):
# 1. 使用 ffmpeg 原样抽出 ASS 字幕(强制封入 ass 容器,防止丢失原始时间轴和特效块)
cmd = ["ffmpeg", "-i", str(file_path), "-map", f"0:{stream_index}", "-c:s", "ass", "-f", "ass", "-y", str(temp_ass)] cmd = ["ffmpeg", "-i", str(file_path), "-map", f"0:{stream_index}", "-c:s", "ass", "-f", "ass", "-y", str(temp_ass)]
res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# 如果 ffmpeg 提取成功且文件不为空
if res.returncode == 0 and temp_ass.exists() and temp_ass.stat().st_size > 0: if res.returncode == 0 and temp_ass.exists() and temp_ass.stat().st_size > 0:
try: try:
# 2. 召唤 pysubs2 进行降维打击
subs = pysubs2.load(str(temp_ass), encoding="utf-8") subs = pysubs2.load(str(temp_ass), encoding="utf-8")
# 双重保险:pysubs2 导出时会自动去掉特效,但为了防止某些极端绘图代码残留,手动擦除 {\...} 标签
for line in subs: for line in subs:
line.text = re.sub(r'\{.*?\}', '', line.text) line.text = re.sub(r'\{.*?\}', '', line.text)
# 3. 输出为完美纯净的 srt
subs.save(str(out_srt), format="srt", encoding="utf-8") subs.save(str(out_srt), format="srt", encoding="utf-8")
except Exception as e: except Exception as e:
print(f"\n⚠️ 字幕 {out_srt.name} 深度洗白失败,已跳过。报错信息: {e}") print(f"\n⚠️ 字幕 {out_srt.name} 洗白失败,已跳过。报错信息: {e}")
finally: finally:
# 无论成功失败,都清理临时文件
temp_ass.unlink(missing_ok=True) temp_ass.unlink(missing_ok=True)
else: else:
temp_ass.unlink(missing_ok=True) temp_ass.unlink(missing_ok=True)
+101
View File
@@ -0,0 +1,101 @@
# src/services/tmdb.py
import json
import requests
from pathlib import Path
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from core import config
from core.logger import log
class TMDBService:
# 💡 缓存文件路径放在根目录
_cache_file = Path(__file__).parent.parent.parent / 'tmdb_cache.json'
_cache = None
@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')
@staticmethod
def _get_session():
s = requests.Session()
retries = Retry(total=config.TMDB_MAX_RETRIES, backoff_factor=1, status_forcelist=[429, 502, 503, 504])
s.mount('https://', HTTPAdapter(max_retries=retries))
return s
@staticmethod
def search_media(title, year=None, m_type="movie"):
"""
智能搜索接口:自动区分电影/电视剧,并接入本地缓存
"""
if not config.TMDB_API_KEY:
log.debug("TMDB API Key 未配置,跳过在线刮削")
return None
# 💡 1. 拦截层:检查本地缓存
TMDBService._load_cache()
cache_key = f"{m_type}_{title}_{year}"
if cache_key in TMDBService._cache:
log.debug(f"⚡ 命中 TMDB 本地缓存: {title} ({year})")
return TMDBService._cache[cache_key]
# 💡 2. 路由层:分流 Movie 和 TV 接口
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
}
# 电视剧的年份查询参数和电影不一样
if year:
if m_type == "tv":
params["first_air_date_year"] = year
else:
params["year"] = year
try:
session = TMDBService._get_session()
log.debug(f"🌐 正在请求 TMDB [{endpoint.upper()}]: {title} ({year})")
resp = session.get(url, params=params, timeout=config.TMDB_TIMEOUT)
data = resp.json()
if resp.status_code == 200 and data.get('results'):
res = data['results'][0]
# 💡 电视剧取 original_name,电影取 original_title
original_title = res.get('original_name') if m_type == "tv" else res.get('original_title')
result = {
"english_title": original_title.replace(' ', '.') if original_title else "",
"tmdb_id": res.get('id')
}
# 💡 3. 存储层:写回缓存并持久化
TMDBService._cache[cache_key] = result
TMDBService._save_cache()
return result
except Exception as e:
log.error(f"TMDB 请求异常 [{title}]: {str(e)[:100]}...")
return None
+2
View File
@@ -1 +1,3 @@
pysubs2 pysubs2
requests
watchdog