refactor(preflight): 移除音轨判定与补轨/改默认音轨相关代码
- 不再检测默认音轨、不再提供 add_ac3 / fix_default_audio / 改默认标志 - 音频信息仅保留在报告 audio_codecs 列,不参与 verdict - 同步移除 [Compatibility] auto_add_ac3 / direct_audio / auto_fix_default_audio / backup_dir / refresh_jellyfin_after_prep 及 TaskManager 的 prepare 阶段 - DV Profile 7 不再算 TRANSCODE(视频可去 DV 元数据直传),仅 DV5 需 tonemap
This commit is contained in:
@@ -78,22 +78,14 @@ api_key =
|
|||||||
max_direct_mbps = 70
|
max_direct_mbps = 70
|
||||||
# 超过该体积且含内嵌 ASS 时,提前抽外挂字幕
|
# 超过该体积且含内嵌 ASS 时,提前抽外挂字幕
|
||||||
pre_extract_ass_gb = 15
|
pre_extract_ass_gb = 15
|
||||||
# 没有可直传音轨时自动补 AC3(先保持关闭,观察后再开)
|
|
||||||
auto_add_ac3 = false
|
|
||||||
# 大文件自动抽 ASS(当前 export=ass 时已天然满足)
|
# 大文件自动抽 ASS(当前 export=ass 时已天然满足)
|
||||||
auto_extract_ass = true
|
auto_extract_ass = true
|
||||||
# 每次扫描是否输出 preflight_report.csv
|
# 每次扫描是否输出体检报告
|
||||||
write_report = true
|
write_report = true
|
||||||
# 补轨替换后是否触发 Jellyfin 刷新
|
|
||||||
refresh_jellyfin_after_prep = true
|
|
||||||
# 补轨前的原文件备份目录(相对视频所在目录)
|
|
||||||
backup_dir = .preflight_backup
|
|
||||||
# 体检报告集中存放目录(每次生成带时间戳 xlsx)
|
# 体检报告集中存放目录(每次生成带时间戳 xlsx)
|
||||||
report_dir = /hdd/sda1/Quark-Down/_reports
|
report_dir = /hdd/sda1/Quark-Down/_reports
|
||||||
# 报告保留份数(<=0 表示不清理)
|
# 报告保留份数(<=0 表示不清理)
|
||||||
report_keep = 6
|
report_keep = 6
|
||||||
# 电视能直传的音频编码(逗号分隔,按你的电视/客户端实测调整)
|
|
||||||
direct_audio = ac3,eac3,dts,truehd,aac,mp3,mp2,flac,opus,vorbis,pcm_s16le,pcm_s24le,pcm_s32le,pcm_bluray,mlp
|
|
||||||
|
|
||||||
[System]
|
[System]
|
||||||
log_file_path = media_manager.log
|
log_file_path = media_manager.log
|
||||||
@@ -189,14 +181,8 @@ JELLYFIN_API_KEY = _parser.get('Jellyfin', 'api_key', fallback='').strip()
|
|||||||
# 7.5 入库前兼容性检查
|
# 7.5 入库前兼容性检查
|
||||||
MAX_DIRECT_MBPS = _parser.getfloat('Compatibility', 'max_direct_mbps', fallback=70.0)
|
MAX_DIRECT_MBPS = _parser.getfloat('Compatibility', 'max_direct_mbps', fallback=70.0)
|
||||||
PRE_EXTRACT_ASS_GB = _parser.getfloat('Compatibility', 'pre_extract_ass_gb', fallback=15.0)
|
PRE_EXTRACT_ASS_GB = _parser.getfloat('Compatibility', 'pre_extract_ass_gb', fallback=15.0)
|
||||||
AUTO_ADD_AC3 = _parser.getboolean('Compatibility', 'auto_add_ac3', fallback=False)
|
|
||||||
AUTO_EXTRACT_ASS = _parser.getboolean('Compatibility', 'auto_extract_ass', fallback=True)
|
AUTO_EXTRACT_ASS = _parser.getboolean('Compatibility', 'auto_extract_ass', fallback=True)
|
||||||
PREFLIGHT_REPORT = _parser.getboolean('Compatibility', 'write_report', fallback=True)
|
PREFLIGHT_REPORT = _parser.getboolean('Compatibility', 'write_report', fallback=True)
|
||||||
PREFLIGHT_REFRESH_JELLYFIN = _parser.getboolean('Compatibility', 'refresh_jellyfin_after_prep', fallback=True)
|
|
||||||
PREFLIGHT_BACKUP_DIRNAME = _parser.get('Compatibility', 'backup_dir', fallback='.preflight_backup').strip() or '.preflight_backup'
|
|
||||||
DIRECT_AUDIO_CODECS = _csv_set(
|
|
||||||
'Compatibility', 'direct_audio',
|
|
||||||
fallback='ac3,eac3,dts,truehd,aac,mp3,mp2,flac,opus,vorbis,pcm_s16le,pcm_s24le,pcm_s32le,pcm_bluray,mlp')
|
|
||||||
PREFLIGHT_CACHE_PATH = BASE_DIR / 'preflight_cache.json'
|
PREFLIGHT_CACHE_PATH = BASE_DIR / 'preflight_cache.json'
|
||||||
PREFLIGHT_CACHE_VERSION = 3
|
PREFLIGHT_CACHE_VERSION = 3
|
||||||
PREFLIGHT_REPORT_DIR = Path(
|
PREFLIGHT_REPORT_DIR = Path(
|
||||||
|
|||||||
@@ -43,10 +43,7 @@ class MediaPipeline:
|
|||||||
|
|
||||||
if self.task_mgr.preview_and_confirm(self.auto_execute):
|
if self.task_mgr.preview_and_confirm(self.auto_execute):
|
||||||
if not self.auto_execute: log.info("⚙️ 正在执行物理任务...")
|
if not self.auto_execute: log.info("⚙️ 正在执行物理任务...")
|
||||||
had_prepare = bool(self.task_mgr.tasks.get('prepare'))
|
|
||||||
self.task_mgr.execute()
|
self.task_mgr.execute()
|
||||||
if had_prepare:
|
|
||||||
PreflightService.refresh_jellyfin()
|
|
||||||
log.info("🎉 流水线操作圆满落地!")
|
log.info("🎉 流水线操作圆满落地!")
|
||||||
elif not self.auto_execute:
|
elif not self.auto_execute:
|
||||||
log.info("💤 任务已由用户取消。")
|
log.info("💤 任务已由用户取消。")
|
||||||
@@ -103,22 +100,9 @@ class MediaPipeline:
|
|||||||
log.error(f"⛔ 无法直传,跳过入库: {f.name} | {'; '.join(pf.reasons)}")
|
log.error(f"⛔ 无法直传,跳过入库: {f.name} | {'; '.join(pf.reasons)}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
audio_tag = None
|
|
||||||
if 'add_ac3' in pf.actions:
|
|
||||||
if config.AUTO_ADD_AC3:
|
|
||||||
tmp = f.with_name(f".{f.stem}.ac3prep{f.suffix}")
|
|
||||||
self.task_mgr.add_prepare(
|
|
||||||
f"[补 AC3 音轨] {f.name}",
|
|
||||||
PreflightService.prepare_ac3,
|
|
||||||
(f, tmp),
|
|
||||||
)
|
|
||||||
audio_tag = 'AC3.5.1'
|
|
||||||
else:
|
|
||||||
log.warning(f"🟡 [需要补 AC3] {f.name} | auto_add_ac3=false,本次仅提示")
|
|
||||||
|
|
||||||
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 = ParserService.get_target_info(
|
target_stem, folder_name = ParserService.get_target_info(
|
||||||
f, m_type, title, year, season_num, is_multi, audio_tag=audio_tag)
|
f, m_type, title, year, season_num, is_multi)
|
||||||
|
|
||||||
# 集数防撞防爆锁
|
# 集数防撞防爆锁
|
||||||
if m_type == "tv":
|
if m_type == "tv":
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from services.fileops import FileOpsService
|
|||||||
class TaskManager:
|
class TaskManager:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.tasks = {
|
self.tasks = {
|
||||||
'prepare': [], 'extract': [], 'clean': [], 'rename_file': [],
|
'extract': [], 'clean': [], 'rename_file': [],
|
||||||
'rename_season_dir': [], 'rename_root_dir': []
|
'rename_season_dir': [], 'rename_root_dir': []
|
||||||
}
|
}
|
||||||
self.dir_renames = set()
|
self.dir_renames = set()
|
||||||
@@ -55,7 +55,6 @@ class TaskManager:
|
|||||||
self.claimants[str(final_path.resolve())] = source_name
|
self.claimants[str(final_path.resolve())] = source_name
|
||||||
return final_path
|
return final_path
|
||||||
|
|
||||||
def add_prepare(self, desc, func, args): self.tasks['prepare'].append((desc, func, args))
|
|
||||||
def add_extract(self, desc, func, args): self.tasks['extract'].append((desc, func, args))
|
def add_extract(self, desc, func, args): self.tasks['extract'].append((desc, func, args))
|
||||||
def add_clean(self, desc, func, args): self.tasks['clean'].append((desc, func, args))
|
def add_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_file_rename(self, desc, func, args): self.tasks['rename_file'].append((desc, func, args))
|
||||||
@@ -78,7 +77,6 @@ class TaskManager:
|
|||||||
log.info("==================== 待执行任务预览 ====================")
|
log.info("==================== 待执行任务预览 ====================")
|
||||||
|
|
||||||
labels = [
|
labels = [
|
||||||
('prepare', '🧪 阶段 0: 入库前预处理(补音轨/抽字幕)'),
|
|
||||||
('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
|
('extract', '🛠️ 阶段 1: 提取内置文本字幕'),
|
||||||
('clean', '🧹 阶段 2: 清理元数据广告'),
|
('clean', '🧹 阶段 2: 清理元数据广告'),
|
||||||
('rename_file', '📄 阶段 3: 视频与外挂字幕规范化重命名'),
|
('rename_file', '📄 阶段 3: 视频与外挂字幕规范化重命名'),
|
||||||
@@ -113,7 +111,7 @@ class TaskManager:
|
|||||||
log.warning("⛔ 无效输入:请输入 y(执行) 或 n/q(取消)")
|
log.warning("⛔ 无效输入:请输入 y(执行) 或 n/q(取消)")
|
||||||
|
|
||||||
def execute(self):
|
def execute(self):
|
||||||
stages = ['prepare', '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]:
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ class ParserService:
|
|||||||
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
|
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False, audio_tag: str = None):
|
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)
|
||||||
tmdb = TMDBService.search_media(title, year, m_type, season_num)
|
tmdb = TMDBService.search_media(title, year, m_type, season_num)
|
||||||
|
|
||||||
@@ -87,9 +87,7 @@ class ParserService:
|
|||||||
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 ""
|
||||||
|
|
||||||
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
||||||
# 预补 AC3 时,命名按处理后的音轨来(避免写入真实文件不存在的音轨)
|
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||||
audio_info = audio_tag or tags['a_info']
|
|
||||||
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{audio_info}"
|
|
||||||
|
|
||||||
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
||||||
|
|
||||||
|
|||||||
+384
-482
@@ -1,482 +1,384 @@
|
|||||||
# src/services/preflight.py
|
# src/services/preflight.py
|
||||||
"""入库前兼容性体检(Preflight)。
|
"""入库前兼容性体检(Preflight)。
|
||||||
|
|
||||||
目标:入库后电视点开即播,服务器尽量直传不转码。
|
目标:入库后电视点开即播,服务器尽量直传不转码。
|
||||||
结论四档:
|
结论四档:
|
||||||
READY 直接入库,客户端直传
|
READY 直接入库,客户端直传
|
||||||
PREP 轻量预处理后即可直传(补 AC3 / 抽外挂 ASS / 改默认音轨)
|
PREP 轻量预处理后即可直传(补 AC3 / 抽外挂 ASS / 改默认音轨)
|
||||||
TRANSCODE 不能直传,但服务端转码可正常播放(DV5、老编码、码率超限)
|
TRANSCODE 不能直传,但服务端转码可正常播放(DV5、老编码、码率超限)
|
||||||
BLOCKED 连转码都救不了(文件损坏、无视频轨),不入库,写报告
|
BLOCKED 连转码都救不了(文件损坏、无视频轨),不入库,写报告
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import time
|
||||||
import shutil
|
from dataclasses import dataclass, field
|
||||||
import subprocess
|
from pathlib import Path
|
||||||
import time
|
|
||||||
from dataclasses import dataclass, field
|
from core import config
|
||||||
from pathlib import Path
|
from core.logger import log
|
||||||
|
from core.utils import FFprobeUtil
|
||||||
from core import config
|
|
||||||
from core.logger import log
|
READY, PREP, TRANSCODE, BLOCKED = "READY", "PREP", "TRANSCODE", "BLOCKED"
|
||||||
from core.utils import FFprobeUtil
|
_ORDER = {READY: 0, PREP: 1, TRANSCODE: 2, BLOCKED: 3}
|
||||||
|
|
||||||
READY, PREP, TRANSCODE, BLOCKED = "READY", "PREP", "TRANSCODE", "BLOCKED"
|
|
||||||
_ORDER = {READY: 0, PREP: 1, TRANSCODE: 2, BLOCKED: 3}
|
@dataclass
|
||||||
|
class PreflightResult:
|
||||||
|
verdict: str = READY
|
||||||
@dataclass
|
reasons: list = field(default_factory=list)
|
||||||
class PreflightResult:
|
actions: list = field(default_factory=list)
|
||||||
verdict: str = READY
|
info: dict = field(default_factory=dict)
|
||||||
reasons: list = field(default_factory=list)
|
|
||||||
actions: list = field(default_factory=list)
|
@property
|
||||||
info: dict = field(default_factory=dict)
|
def summary(self) -> str:
|
||||||
|
return f"{self.verdict}" + (f" | {', '.join(self.reasons)}" if self.reasons else "")
|
||||||
@property
|
|
||||||
def summary(self) -> str:
|
|
||||||
return f"{self.verdict}" + (f" | {', '.join(self.reasons)}" if self.reasons else "")
|
class PreflightService:
|
||||||
|
"""ffprobe 体检 + 补 AC3 音轨 + 报告输出。"""
|
||||||
|
|
||||||
class PreflightService:
|
# 电视(Amlogic S905X3 + Jellyfin Android TV 0.20)实测可直传的编码
|
||||||
"""ffprobe 体检 + 补 AC3 音轨 + 报告输出。"""
|
VIDEO_OK = {"hevc", "h264"}
|
||||||
|
SUB_OK = {
|
||||||
# 电视(Amlogic S905X3 + Jellyfin Android TV 0.20)实测可直传的编码
|
"ass", "ssa", "subrip", "srt", "webvtt", "mov_text",
|
||||||
VIDEO_OK = {"hevc", "h264"}
|
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "idx",
|
||||||
# 可在 config.ini [Compatibility] direct_audio 里按实测调整
|
}
|
||||||
AUDIO_OK = set(config.DIRECT_AUDIO_CODECS)
|
HDR_TRANSFERS = {"smpte2084", "arib-std-b67"}
|
||||||
SUB_OK = {
|
ASS_OK = {"ass", "ssa"}
|
||||||
"ass", "ssa", "subrip", "srt", "webvtt", "mov_text",
|
|
||||||
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "idx",
|
# ------------------------------------------------------------------ 评估
|
||||||
}
|
|
||||||
HDR_TRANSFERS = {"smpte2084", "arib-std-b67"}
|
@classmethod
|
||||||
ASS_OK = {"ass", "ssa"}
|
def _raise(cls, r: PreflightResult, level: str, reason: str) -> None:
|
||||||
|
r.reasons.append(reason)
|
||||||
# ------------------------------------------------------------------ 评估
|
if _ORDER[level] > _ORDER[r.verdict]:
|
||||||
|
r.verdict = level
|
||||||
@classmethod
|
|
||||||
def _raise(cls, r: PreflightResult, level: str, reason: str) -> None:
|
@staticmethod
|
||||||
r.reasons.append(reason)
|
def _primary_video(streams: list) -> dict | None:
|
||||||
if _ORDER[level] > _ORDER[r.verdict]:
|
for s in streams:
|
||||||
r.verdict = level
|
if s.get("codec_type") != "video":
|
||||||
|
continue
|
||||||
@staticmethod
|
if (s.get("disposition") or {}).get("attached_pic"):
|
||||||
def _primary_video(streams: list) -> dict | None:
|
continue # 封面图(mjpeg/png)
|
||||||
for s in streams:
|
return s
|
||||||
if s.get("codec_type") != "video":
|
return None
|
||||||
continue
|
|
||||||
if (s.get("disposition") or {}).get("attached_pic"):
|
@staticmethod
|
||||||
continue # 封面图(mjpeg/png)
|
def _dv_profile(video: dict) -> int | None:
|
||||||
return s
|
for sd in video.get("side_data_list") or []:
|
||||||
return None
|
name = str(sd.get("side_data_type", "")).lower()
|
||||||
|
if "dovi" in name or "dolby vision" in name:
|
||||||
@staticmethod
|
profile = sd.get("dv_profile")
|
||||||
def _dv_profile(video: dict) -> int | None:
|
return int(profile) if profile is not None else None
|
||||||
for sd in video.get("side_data_list") or []:
|
return None
|
||||||
name = str(sd.get("side_data_type", "")).lower()
|
|
||||||
if "dovi" in name or "dolby vision" in name:
|
@classmethod
|
||||||
profile = sd.get("dv_profile")
|
def evaluate(cls, path: Path, use_cache: bool = True) -> PreflightResult:
|
||||||
return int(profile) if profile is not None else None
|
cached = cls._cache_get(path) if use_cache else None
|
||||||
return None
|
if cached:
|
||||||
|
return cached
|
||||||
@classmethod
|
|
||||||
def evaluate(cls, path: Path, use_cache: bool = True) -> PreflightResult:
|
r = PreflightResult()
|
||||||
cached = cls._cache_get(path) if use_cache else None
|
data = FFprobeUtil.get_json(path, "-show_format", "-show_streams")
|
||||||
if cached:
|
if not data:
|
||||||
return cached
|
r.verdict, r.reasons = BLOCKED, ["ffprobe 读取失败"]
|
||||||
|
return r
|
||||||
r = PreflightResult()
|
|
||||||
data = FFprobeUtil.get_json(path, "-show_format", "-show_streams")
|
streams = data.get("streams", [])
|
||||||
if not data:
|
fmt = data.get("format", {})
|
||||||
r.verdict, r.reasons = BLOCKED, ["ffprobe 读取失败"]
|
size_gb = int(fmt.get("size") or 0) / 1e9
|
||||||
return r
|
v = cls._primary_video(streams)
|
||||||
|
if not v:
|
||||||
streams = data.get("streams", [])
|
r.verdict, r.reasons = BLOCKED, ["无主视频轨"]
|
||||||
fmt = data.get("format", {})
|
return r
|
||||||
size_gb = int(fmt.get("size") or 0) / 1e9
|
|
||||||
v = cls._primary_video(streams)
|
codec = (v.get("codec_name") or "").lower()
|
||||||
if not v:
|
height = int(v.get("height") or 0)
|
||||||
r.verdict, r.reasons = BLOCKED, ["无主视频轨"]
|
width = int(v.get("width") or 0)
|
||||||
return r
|
level = v.get("level")
|
||||||
|
v_bitrate = int(v.get("bit_rate") or 0) or int(fmt.get("bit_rate") or 0)
|
||||||
codec = (v.get("codec_name") or "").lower()
|
mbps = v_bitrate / 1e6
|
||||||
height = int(v.get("height") or 0)
|
dv_profile = cls._dv_profile(v)
|
||||||
width = int(v.get("width") or 0)
|
transfer = (v.get("color_transfer") or "").lower()
|
||||||
level = v.get("level")
|
|
||||||
v_bitrate = int(v.get("bit_rate") or 0) or int(fmt.get("bit_rate") or 0)
|
audios = []
|
||||||
mbps = v_bitrate / 1e6
|
for s in streams:
|
||||||
dv_profile = cls._dv_profile(v)
|
if s.get("codec_type") != "audio":
|
||||||
transfer = (v.get("color_transfer") or "").lower()
|
continue
|
||||||
|
audios.append({
|
||||||
audios = []
|
"codec": (s.get("codec_name") or "").lower(),
|
||||||
for s in streams:
|
"channels": int(s.get("channels") or 0),
|
||||||
if s.get("codec_type") != "audio":
|
"language": (s.get("tags") or {}).get("language", ""),
|
||||||
continue
|
"title": (s.get("tags") or {}).get("title", ""),
|
||||||
audios.append({
|
"default": bool((s.get("disposition") or {}).get("default")),
|
||||||
"codec": (s.get("codec_name") or "").lower(),
|
})
|
||||||
"channels": int(s.get("channels") or 0),
|
subs = [
|
||||||
"language": (s.get("tags") or {}).get("language", ""),
|
{"codec": (s.get("codec_name") or "").lower(),
|
||||||
"title": (s.get("tags") or {}).get("title", ""),
|
"language": (s.get("tags") or {}).get("language", "")}
|
||||||
"default": bool((s.get("disposition") or {}).get("default")),
|
for s in streams if s.get("codec_type") == "subtitle"
|
||||||
})
|
]
|
||||||
subs = [
|
|
||||||
{"codec": (s.get("codec_name") or "").lower(),
|
r.info.update(
|
||||||
"language": (s.get("tags") or {}).get("language", "")}
|
codec=codec, width=width, height=height, level=level,
|
||||||
for s in streams if s.get("codec_type") == "subtitle"
|
mbps=round(mbps, 1), dv_profile=dv_profile,
|
||||||
]
|
hdr=transfer in cls.HDR_TRANSFERS, color_transfer=transfer,
|
||||||
|
size_gb=round(size_gb, 1), audio=audios, subs=subs,
|
||||||
r.info.update(
|
duration=int(float(fmt.get("duration") or 0)),
|
||||||
codec=codec, width=width, height=height, level=level,
|
)
|
||||||
mbps=round(mbps, 1), dv_profile=dv_profile,
|
|
||||||
hdr=transfer in cls.HDR_TRANSFERS, color_transfer=transfer,
|
# 1. 容器
|
||||||
size_gb=round(size_gb, 1), audio=audios, subs=subs,
|
if path.suffix.lower() not in {".mkv", ".mp4"}:
|
||||||
duration=int(float(fmt.get("duration") or 0)),
|
cls._raise(r, TRANSCODE, f"容器 {path.suffix} 需重新封装或转码")
|
||||||
)
|
r.actions.append("server_transcode")
|
||||||
|
# 2. 视频编码
|
||||||
# 1. 容器
|
if codec not in cls.VIDEO_OK:
|
||||||
if path.suffix.lower() not in {".mkv", ".mp4"}:
|
cls._raise(r, TRANSCODE, f"视频编码 {codec} 电视无法解码,需服务端转码")
|
||||||
cls._raise(r, TRANSCODE, f"容器 {path.suffix} 需重新封装或转码")
|
r.actions.append("server_transcode")
|
||||||
r.actions.append("server_transcode")
|
# 3. 分辨率
|
||||||
# 2. 视频编码
|
if height > 2160:
|
||||||
if codec not in cls.VIDEO_OK:
|
cls._raise(r, TRANSCODE, f"{height}p 超过 4K,需服务端缩放转码")
|
||||||
cls._raise(r, TRANSCODE, f"视频编码 {codec} 电视无法解码,需服务端转码")
|
r.actions.append("server_transcode")
|
||||||
r.actions.append("server_transcode")
|
# 4. HEVC level(153 = 5.1):仅提示,很多片源 tag 偏高但实际能解
|
||||||
# 3. 分辨率
|
if codec == "hevc" and isinstance(level, int) and level > 153:
|
||||||
if height > 2160:
|
r.reasons.append(f"HEVC level {level}(>5.1,实际解码可能仍正常)")
|
||||||
cls._raise(r, TRANSCODE, f"{height}p 超过 4K,需服务端缩放转码")
|
# 5. Dolby Vision
|
||||||
r.actions.append("server_transcode")
|
if dv_profile == 5:
|
||||||
# 4. HEVC level(153 = 5.1):仅提示,很多片源 tag 偏高但实际能解
|
cls._raise(r, TRANSCODE, "纯 DV Profile 5 无 HDR10 兼容层,需服务端 tonemap 转码")
|
||||||
if codec == "hevc" and isinstance(level, int) and level > 153:
|
r.actions.append("server_tonemap")
|
||||||
r.reasons.append(f"HEVC level {level}(>5.1,实际解码可能仍正常)")
|
elif dv_profile == 7:
|
||||||
# 5. Dolby Vision
|
# 有 HDR10 基座:Jellyfin 会剥掉 DV 元数据后视频直传(Direct Stream),不重编码
|
||||||
if dv_profile == 5:
|
r.reasons.append("DV Profile 7(HDR10 基座),视频可去 DV 元数据直传")
|
||||||
cls._raise(r, TRANSCODE, "纯 DV Profile 5 无 HDR10 兼容层,需服务端 tonemap 转码")
|
# 6. 码率
|
||||||
r.actions.append("server_tonemap")
|
if mbps > config.MAX_DIRECT_MBPS:
|
||||||
elif dv_profile == 7:
|
cls._raise(r, TRANSCODE, f"码率 {mbps:.1f} Mbps 超过直传上限 {config.MAX_DIRECT_MBPS:g},需转码")
|
||||||
cls._raise(r, TRANSCODE, "DV Profile 7(HDR10 基座),客户端不支持 DV,需服务端 tonemap 转码")
|
r.actions.append("transcode_bitrate")
|
||||||
r.actions.append("server_tonemap")
|
# 7. 音频:只记录,不参与判定(默认音轨保持原样,音频是否转码交给 Jellyfin)
|
||||||
# 6. 码率
|
# 8. 字幕编码
|
||||||
if mbps > config.MAX_DIRECT_MBPS:
|
# 8. 字幕编码
|
||||||
cls._raise(r, TRANSCODE, f"码率 {mbps:.1f} Mbps 超过直传上限 {config.MAX_DIRECT_MBPS:g},需转码")
|
bad = [s["codec"] for s in subs if s["codec"] not in cls.SUB_OK]
|
||||||
r.actions.append("transcode_bitrate")
|
if bad:
|
||||||
# 7. 音频
|
r.reasons.append(f"未知字幕编码: {sorted(set(bad))}")
|
||||||
playable = [a for a in audios if a["codec"] in cls.AUDIO_OK and 0 < a["channels"] <= 8]
|
# 9. 大文件内嵌 ASS:客户端首次播放要现场抽取,会超时
|
||||||
if not playable:
|
has_ass = any(s["codec"] in cls.ASS_OK for s in subs)
|
||||||
cls._raise(r, PREP, "没有可直传的音轨(需补 AC3)")
|
if has_ass and size_gb > config.PRE_EXTRACT_ASS_GB and 'ass' not in config.SUBTITLE_EXPORT:
|
||||||
r.actions.append("add_ac3")
|
cls._raise(r, PREP, f"内嵌 ASS + {size_gb:.0f}GB 大文件,需提前抽外挂")
|
||||||
else:
|
r.actions.append("extract_ass")
|
||||||
# 默认轨若不可直传,客户端可能仍按默认轨触发转码;没有显式默认时以第一条为准
|
|
||||||
defaults = [a for a in audios if a["default"]] or audios[:1]
|
cls._cache_set(path, r)
|
||||||
if defaults and not any(a["codec"] in cls.AUDIO_OK for a in defaults):
|
return r
|
||||||
cls._raise(r, PREP, "默认音轨不可直传,建议把兼容轨设为默认")
|
|
||||||
r.actions.append("fix_default_audio")
|
# ------------------------------------------------------------------ 缓存
|
||||||
# 8. 字幕编码
|
|
||||||
bad = [s["codec"] for s in subs if s["codec"] not in cls.SUB_OK]
|
@staticmethod
|
||||||
if bad:
|
def _cache_path() -> Path:
|
||||||
r.reasons.append(f"未知字幕编码: {sorted(set(bad))}")
|
return config.PREFLIGHT_CACHE_PATH
|
||||||
# 9. 大文件内嵌 ASS:客户端首次播放要现场抽取,会超时
|
|
||||||
has_ass = any(s["codec"] in cls.ASS_OK for s in subs)
|
@classmethod
|
||||||
if has_ass and size_gb > config.PRE_EXTRACT_ASS_GB and 'ass' not in config.SUBTITLE_EXPORT:
|
def _load_cache(cls) -> dict:
|
||||||
cls._raise(r, PREP, f"内嵌 ASS + {size_gb:.0f}GB 大文件,需提前抽外挂")
|
try:
|
||||||
r.actions.append("extract_ass")
|
if cls._cache_data is None:
|
||||||
|
p = cls._cache_path()
|
||||||
cls._cache_set(path, r)
|
raw = json.loads(p.read_text("utf-8")) if p.exists() else {}
|
||||||
return r
|
if isinstance(raw, dict) and raw.get("version") == config.PREFLIGHT_CACHE_VERSION:
|
||||||
|
cls._cache_data = raw.get("entries", {})
|
||||||
# ------------------------------------------------------------------ 缓存
|
else:
|
||||||
|
cls._cache_data = {} # 旧版本/格式不匹配,丢弃重建
|
||||||
@staticmethod
|
except Exception:
|
||||||
def _cache_path() -> Path:
|
cls._cache_data = {}
|
||||||
return config.PREFLIGHT_CACHE_PATH
|
return cls._cache_data
|
||||||
|
|
||||||
@classmethod
|
_cache_data = None
|
||||||
def _load_cache(cls) -> dict:
|
|
||||||
try:
|
@classmethod
|
||||||
if cls._cache_data is None:
|
def _cache_key(cls, path: Path) -> str:
|
||||||
p = cls._cache_path()
|
st = path.stat()
|
||||||
raw = json.loads(p.read_text("utf-8")) if p.exists() else {}
|
return f"{path}|{st.st_size}|{int(st.st_mtime)}"
|
||||||
if isinstance(raw, dict) and raw.get("version") == config.PREFLIGHT_CACHE_VERSION:
|
|
||||||
cls._cache_data = raw.get("entries", {})
|
@classmethod
|
||||||
else:
|
def _cache_get(cls, path: Path) -> PreflightResult | None:
|
||||||
cls._cache_data = {} # 旧版本/格式不匹配,丢弃重建
|
try:
|
||||||
except Exception:
|
entry = cls._load_cache().get(cls._cache_key(path))
|
||||||
cls._cache_data = {}
|
except OSError:
|
||||||
return cls._cache_data
|
return None
|
||||||
|
if not entry:
|
||||||
_cache_data = None
|
return None
|
||||||
|
r = PreflightResult(verdict=entry.get("verdict", READY),
|
||||||
@classmethod
|
reasons=entry.get("reasons", []),
|
||||||
def _cache_key(cls, path: Path) -> str:
|
actions=entry.get("actions", []),
|
||||||
st = path.stat()
|
info=entry.get("info", {}))
|
||||||
return f"{path}|{st.st_size}|{int(st.st_mtime)}"
|
return r
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _cache_get(cls, path: Path) -> PreflightResult | None:
|
def _cache_set(cls, path: Path, result: PreflightResult) -> None:
|
||||||
try:
|
cache = cls._load_cache()
|
||||||
entry = cls._load_cache().get(cls._cache_key(path))
|
try:
|
||||||
except OSError:
|
cache[cls._cache_key(path)] = {
|
||||||
return None
|
"verdict": result.verdict, "reasons": result.reasons,
|
||||||
if not entry:
|
"actions": result.actions, "info": result.info,
|
||||||
return None
|
"ts": int(time.time()),
|
||||||
r = PreflightResult(verdict=entry.get("verdict", READY),
|
}
|
||||||
reasons=entry.get("reasons", []),
|
except OSError:
|
||||||
actions=entry.get("actions", []),
|
return
|
||||||
info=entry.get("info", {}))
|
try:
|
||||||
return r
|
cls._cache_path().write_text(
|
||||||
|
json.dumps({"version": config.PREFLIGHT_CACHE_VERSION, "entries": cache},
|
||||||
@classmethod
|
ensure_ascii=False, indent=1),
|
||||||
def _cache_set(cls, path: Path, result: PreflightResult) -> None:
|
"utf-8")
|
||||||
cache = cls._load_cache()
|
except Exception as e:
|
||||||
try:
|
log.debug(f"preflight 缓存写入失败: {e}")
|
||||||
cache[cls._cache_key(path)] = {
|
|
||||||
"verdict": result.verdict, "reasons": result.reasons,
|
# ------------------------------------------------------------------ 报告
|
||||||
"actions": result.actions, "info": result.info,
|
|
||||||
"ts": int(time.time()),
|
HEADERS = ["path", "verdict", "codec", "height", "mbps", "dv_profile",
|
||||||
}
|
"audio_codecs", "sub_codecs", "actions", "reasons"]
|
||||||
except OSError:
|
|
||||||
return
|
@classmethod
|
||||||
try:
|
def _report_rows(cls, results: list) -> list:
|
||||||
cls._cache_path().write_text(
|
order = {BLOCKED: 0, TRANSCODE: 1, PREP: 2, READY: 3}
|
||||||
json.dumps({"version": config.PREFLIGHT_CACHE_VERSION, "entries": cache},
|
rows = []
|
||||||
ensure_ascii=False, indent=1),
|
for path, r in sorted(results, key=lambda x: (order.get(x[1].verdict, 9), str(x[0]))):
|
||||||
"utf-8")
|
i = r.info
|
||||||
except Exception as e:
|
audio = "/".join(f"{a['codec']}{a['channels']}" for a in i.get("audio", []))
|
||||||
log.debug(f"preflight 缓存写入失败: {e}")
|
subs = "/".join(sorted({s["codec"] for s in i.get("subs", [])}))
|
||||||
|
rows.append((path, r, [
|
||||||
# ------------------------------------------------------------------ 动作
|
str(path), r.verdict, i.get("codec", ""), i.get("height", ""),
|
||||||
|
i.get("mbps", ""), i.get("dv_profile") or "",
|
||||||
@staticmethod
|
audio, subs, "/".join(r.actions), " | ".join(r.reasons),
|
||||||
def add_ac3_track(src: Path, dst: Path) -> Path:
|
]))
|
||||||
"""视频/字幕 copy,首条音轨转 AC3 5.1 并设为默认,其余音轨保留。"""
|
return rows
|
||||||
data = FFprobeUtil.get_json(src, "-show_streams")
|
|
||||||
audio_count = 0
|
@staticmethod
|
||||||
if data:
|
def _prune_reports() -> None:
|
||||||
audio_count = sum(1 for s in data.get("streams", []) if s.get("codec_type") == "audio")
|
"""只保留最近 N 份报告([Compatibility] report_keep,<=0 表示不清理)。"""
|
||||||
|
keep = config.PREFLIGHT_REPORT_KEEP
|
||||||
maps = ["-map", "0:v:0", "-map", "0:a:0", "-map", "0:a:0"]
|
if keep <= 0:
|
||||||
for i in range(1, max(audio_count, 1)):
|
return
|
||||||
maps += ["-map", f"0:a:{i}"]
|
try:
|
||||||
maps += ["-map", "0:s?"]
|
files = [p for p in config.PREFLIGHT_REPORT_DIR.glob("preflight-*.*")
|
||||||
|
if p.is_file() and p.suffix.lower() in {".xlsx", ".csv"}]
|
||||||
cmd = [
|
files.sort(key=lambda p: p.stat().st_mtime, reverse=True)
|
||||||
"ffmpeg", "-y", "-v", "error", "-i", str(src), *maps,
|
except OSError:
|
||||||
"-c:v", "copy", "-c:s", "copy",
|
return
|
||||||
"-c:a", "copy",
|
for old in files[keep:]:
|
||||||
"-c:a:0", "ac3", "-b:a:0", "640k", "-ac:a:0", "6",
|
try:
|
||||||
"-metadata:s:a:0", "title=AC3 5.1",
|
old.unlink()
|
||||||
"-disposition:a:0", "default", "-disposition:a:1", "0",
|
log.debug(f"🧹 清理旧报告: {old.name}")
|
||||||
"-map_metadata", "0", "-map_chapters", "0",
|
except OSError as e:
|
||||||
str(dst),
|
log.warning(f"⚠️ 清理旧报告失败: {old.name} -> {e}")
|
||||||
]
|
|
||||||
log.info(f"🎚️ 补 AC3 音轨: {src.name} → {dst.name}")
|
@staticmethod
|
||||||
res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
def _report_path(ext: str) -> Path:
|
||||||
text=True, errors="ignore")
|
"""集中目录 + 时间戳:<report_dir>/preflight-YYYYmmdd-HHMMSS.<ext>"""
|
||||||
if res.returncode != 0:
|
report_dir = config.PREFLIGHT_REPORT_DIR
|
||||||
tail = [line for line in (res.stderr or "").strip().splitlines() if line.strip()]
|
report_dir.mkdir(parents=True, exist_ok=True)
|
||||||
raise RuntimeError(f"ffmpeg 失败: {tail[-1][:300] if tail else res.returncode}")
|
stamp = time.strftime("%Y%m%d-%H%M%S")
|
||||||
return dst
|
path = report_dir / f"preflight-{stamp}.{ext}"
|
||||||
|
n = 2
|
||||||
@staticmethod
|
while path.exists():
|
||||||
def verify_ac3(path: Path) -> bool:
|
path = report_dir / f"preflight-{stamp}-{n}.{ext}"
|
||||||
data = FFprobeUtil.get_json(path, "-show_streams", "-select_streams", "a")
|
n += 1
|
||||||
if not data:
|
return path
|
||||||
return False
|
|
||||||
audio = data.get("streams", [])
|
@classmethod
|
||||||
if not audio:
|
def write_report(cls, root: Path, results: list, only_issues: bool = False) -> Path | None:
|
||||||
return False
|
"""results: [(path, PreflightResult)],输出 root/preflight_report.xlsx(无 openpyxl 时退回 csv)。"""
|
||||||
first = audio[0]
|
if not config.PREFLIGHT_REPORT or not results:
|
||||||
is_default = bool((first.get("disposition") or {}).get("default"))
|
return None
|
||||||
return (first.get("codec_name") == "ac3" and is_default)
|
if only_issues:
|
||||||
|
results = [(p, r) for p, r in results if r.verdict != READY]
|
||||||
@classmethod
|
if not results:
|
||||||
def prepare_ac3(cls, src: Path, tmp: Path) -> Path:
|
return None
|
||||||
"""生成 AC3 版本 → 备份原文件 → 原子替换。返回最终路径。"""
|
|
||||||
tmp.unlink(missing_ok=True)
|
rows = cls._report_rows(results)
|
||||||
cls.add_ac3_track(src, tmp)
|
|
||||||
if not tmp.exists() or tmp.stat().st_size == 0:
|
try:
|
||||||
raise RuntimeError("输出文件为空")
|
from openpyxl import Workbook
|
||||||
if not cls.verify_ac3(tmp):
|
from openpyxl.styles import Alignment, Font, PatternFill
|
||||||
raise RuntimeError("校验失败:首条音轨不是 AC3 或未设为默认")
|
from openpyxl.utils import get_column_letter
|
||||||
|
except ImportError:
|
||||||
backup_dir = src.parent / config.PREFLIGHT_BACKUP_DIRNAME
|
log.warning("⚠️ 未安装 openpyxl,报告退回 CSV(pip install openpyxl 可启用 xlsx)")
|
||||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
return cls._write_csv(root, rows)
|
||||||
backup = backup_dir / src.name
|
|
||||||
if backup.exists():
|
wb = Workbook()
|
||||||
backup = backup_dir / f"{src.stem}.{int(time.time())}{src.suffix}"
|
ws = wb.active
|
||||||
shutil.move(str(src), str(backup))
|
ws.title = "preflight"
|
||||||
os.replace(tmp, src)
|
ws.append(cls.HEADERS)
|
||||||
log.info(f"✅ 已替换为 AC3 版本(原文件备份: {backup})")
|
|
||||||
return src
|
header_fill = PatternFill("solid", fgColor="305496")
|
||||||
|
for cell in ws[1]:
|
||||||
# ------------------------------------------------------------------ 报告
|
cell.font = Font(bold=True, color="FFFFFF")
|
||||||
|
cell.fill = header_fill
|
||||||
HEADERS = ["path", "verdict", "codec", "height", "mbps", "dv_profile",
|
cell.alignment = Alignment(vertical="center")
|
||||||
"audio_codecs", "sub_codecs", "actions", "reasons"]
|
|
||||||
|
fills = {
|
||||||
@classmethod
|
BLOCKED: PatternFill("solid", fgColor="F8CBAD"),
|
||||||
def _report_rows(cls, results: list) -> list:
|
TRANSCODE: PatternFill("solid", fgColor="BDD7EE"),
|
||||||
order = {BLOCKED: 0, TRANSCODE: 1, PREP: 2, READY: 3}
|
PREP: PatternFill("solid", fgColor="FFE699"),
|
||||||
rows = []
|
}
|
||||||
for path, r in sorted(results, key=lambda x: (order.get(x[1].verdict, 9), str(x[0]))):
|
for path, r, values in rows:
|
||||||
i = r.info
|
ws.append(values)
|
||||||
audio = "/".join(f"{a['codec']}{a['channels']}" for a in i.get("audio", []))
|
row_idx = ws.max_row
|
||||||
subs = "/".join(sorted({s["codec"] for s in i.get("subs", [])}))
|
if r.verdict in fills:
|
||||||
rows.append((path, r, [
|
for cell in ws[row_idx]:
|
||||||
str(path), r.verdict, i.get("codec", ""), i.get("height", ""),
|
cell.fill = fills[r.verdict]
|
||||||
i.get("mbps", ""), i.get("dv_profile") or "",
|
|
||||||
audio, subs, "/".join(r.actions), " | ".join(r.reasons),
|
last_col = get_column_letter(len(cls.HEADERS))
|
||||||
]))
|
ws.auto_filter.ref = f"A1:{last_col}{ws.max_row}"
|
||||||
return rows
|
# verdict 列(0-based colId=1)默认只勾选 PREP/BLOCKED,并把 READY 行隐藏;
|
||||||
|
# 若整份报告全是 READY,就保持全部可见,避免打开是空表
|
||||||
@staticmethod
|
has_issues = any(r.verdict != READY for _, r, _ in rows)
|
||||||
def _prune_reports() -> None:
|
if has_issues:
|
||||||
"""只保留最近 N 份报告([Compatibility] report_keep,<=0 表示不清理)。"""
|
ws.auto_filter.add_filter_column(1, [PREP, TRANSCODE, BLOCKED])
|
||||||
keep = config.PREFLIGHT_REPORT_KEEP
|
for offset, (_, r, _) in enumerate(rows):
|
||||||
if keep <= 0:
|
if r.verdict == READY:
|
||||||
return
|
ws.row_dimensions[offset + 2].hidden = True
|
||||||
try:
|
ws.freeze_panes = "A2"
|
||||||
files = [p for p in config.PREFLIGHT_REPORT_DIR.glob("preflight-*.*")
|
|
||||||
if p.is_file() and p.suffix.lower() in {".xlsx", ".csv"}]
|
widths = {"A": 80, "B": 10, "C": 11, "D": 8, "E": 9, "F": 10,
|
||||||
files.sort(key=lambda p: p.stat().st_mtime, reverse=True)
|
"G": 26, "H": 32, "I": 22, "J": 60}
|
||||||
except OSError:
|
for col, width in widths.items():
|
||||||
return
|
ws.column_dimensions[col].width = width
|
||||||
for old in files[keep:]:
|
|
||||||
try:
|
report = cls._report_path("xlsx")
|
||||||
old.unlink()
|
wb.save(report)
|
||||||
log.debug(f"🧹 清理旧报告: {old.name}")
|
cls._prune_reports()
|
||||||
except OSError as e:
|
log.info(f"📄 兼容性报告: {report}")
|
||||||
log.warning(f"⚠️ 清理旧报告失败: {old.name} -> {e}")
|
return report
|
||||||
|
|
||||||
@staticmethod
|
@classmethod
|
||||||
def _report_path(ext: str) -> Path:
|
def _write_csv(cls, root: Path, rows: list) -> Path:
|
||||||
"""集中目录 + 时间戳:<report_dir>/preflight-YYYYmmdd-HHMMSS.<ext>"""
|
report = cls._report_path("csv")
|
||||||
report_dir = config.PREFLIGHT_REPORT_DIR
|
lines = [",".join(cls.HEADERS) + "\n"]
|
||||||
report_dir.mkdir(parents=True, exist_ok=True)
|
for _, _, values in rows:
|
||||||
stamp = time.strftime("%Y%m%d-%H%M%S")
|
lines.append(",".join('"' + str(v).replace('"', '""') + '"' for v in values) + "\n")
|
||||||
path = report_dir / f"preflight-{stamp}.{ext}"
|
report.write_text("".join(lines), "utf-8")
|
||||||
n = 2
|
cls._prune_reports()
|
||||||
while path.exists():
|
log.info(f"📄 兼容性报告(CSV): {report}")
|
||||||
path = report_dir / f"preflight-{stamp}-{n}.{ext}"
|
return report
|
||||||
n += 1
|
|
||||||
return path
|
@classmethod
|
||||||
|
def scan(cls, root: Path) -> list:
|
||||||
@classmethod
|
"""check 模式:只体检不动文件。"""
|
||||||
def write_report(cls, root: Path, results: list, only_issues: bool = False) -> Path | None:
|
results = []
|
||||||
"""results: [(path, PreflightResult)],输出 root/preflight_report.xlsx(无 openpyxl 时退回 csv)。"""
|
files = [
|
||||||
if not config.PREFLIGHT_REPORT or not results:
|
p for p in root.rglob("*")
|
||||||
return None
|
if p.is_file() and p.suffix.lower() in config.SUPPORTED_EXTS
|
||||||
if only_issues:
|
and not any(excl in str(p) for excl in config.EXCLUDE_DIRS)
|
||||||
results = [(p, r) for p, r in results if r.verdict != READY]
|
]
|
||||||
if not results:
|
for p in sorted(files):
|
||||||
return None
|
r = cls.evaluate(p)
|
||||||
|
results.append((p, r))
|
||||||
rows = cls._report_rows(results)
|
mark = {"READY": "✅", "PREP": "🟡", "TRANSCODE": "🎞️", "BLOCKED": "⛔"}.get(r.verdict, "?")
|
||||||
|
detail = f"{r.info.get('codec')} {r.info.get('height')}p {r.info.get('mbps')}Mbps"
|
||||||
try:
|
log.info(f"{mark} {r.verdict:<7} {p.name} [{detail}]"
|
||||||
from openpyxl import Workbook
|
+ (f" | {', '.join(r.reasons)}" if r.reasons else ""))
|
||||||
from openpyxl.styles import Alignment, Font, PatternFill
|
|
||||||
from openpyxl.utils import get_column_letter
|
counts = {}
|
||||||
except ImportError:
|
for _, r in results:
|
||||||
log.warning("⚠️ 未安装 openpyxl,报告退回 CSV(pip install openpyxl 可启用 xlsx)")
|
counts[r.verdict] = counts.get(r.verdict, 0) + 1
|
||||||
return cls._write_csv(root, rows)
|
log.info(f"📊 共 {len(results)} 个文件: " +
|
||||||
|
", ".join(f"{k}={v}" for k, v in sorted(counts.items())))
|
||||||
wb = Workbook()
|
cls.write_report(root, results)
|
||||||
ws = wb.active
|
return results
|
||||||
ws.title = "preflight"
|
|
||||||
ws.append(cls.HEADERS)
|
|
||||||
|
|
||||||
header_fill = PatternFill("solid", fgColor="305496")
|
|
||||||
for cell in ws[1]:
|
|
||||||
cell.font = Font(bold=True, color="FFFFFF")
|
|
||||||
cell.fill = header_fill
|
|
||||||
cell.alignment = Alignment(vertical="center")
|
|
||||||
|
|
||||||
fills = {
|
|
||||||
BLOCKED: PatternFill("solid", fgColor="F8CBAD"),
|
|
||||||
TRANSCODE: PatternFill("solid", fgColor="BDD7EE"),
|
|
||||||
PREP: PatternFill("solid", fgColor="FFE699"),
|
|
||||||
}
|
|
||||||
for path, r, values in rows:
|
|
||||||
ws.append(values)
|
|
||||||
row_idx = ws.max_row
|
|
||||||
if r.verdict in fills:
|
|
||||||
for cell in ws[row_idx]:
|
|
||||||
cell.fill = fills[r.verdict]
|
|
||||||
|
|
||||||
last_col = get_column_letter(len(cls.HEADERS))
|
|
||||||
ws.auto_filter.ref = f"A1:{last_col}{ws.max_row}"
|
|
||||||
# verdict 列(0-based colId=1)默认只勾选 PREP/BLOCKED,并把 READY 行隐藏;
|
|
||||||
# 若整份报告全是 READY,就保持全部可见,避免打开是空表
|
|
||||||
has_issues = any(r.verdict != READY for _, r, _ in rows)
|
|
||||||
if has_issues:
|
|
||||||
ws.auto_filter.add_filter_column(1, [PREP, TRANSCODE, BLOCKED])
|
|
||||||
for offset, (_, r, _) in enumerate(rows):
|
|
||||||
if r.verdict == READY:
|
|
||||||
ws.row_dimensions[offset + 2].hidden = True
|
|
||||||
ws.freeze_panes = "A2"
|
|
||||||
|
|
||||||
widths = {"A": 80, "B": 10, "C": 11, "D": 8, "E": 9, "F": 10,
|
|
||||||
"G": 26, "H": 32, "I": 22, "J": 60}
|
|
||||||
for col, width in widths.items():
|
|
||||||
ws.column_dimensions[col].width = width
|
|
||||||
|
|
||||||
report = cls._report_path("xlsx")
|
|
||||||
wb.save(report)
|
|
||||||
cls._prune_reports()
|
|
||||||
log.info(f"📄 兼容性报告: {report}")
|
|
||||||
return report
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _write_csv(cls, root: Path, rows: list) -> Path:
|
|
||||||
report = cls._report_path("csv")
|
|
||||||
lines = [",".join(cls.HEADERS) + "\n"]
|
|
||||||
for _, _, values in rows:
|
|
||||||
lines.append(",".join('"' + str(v).replace('"', '""') + '"' for v in values) + "\n")
|
|
||||||
report.write_text("".join(lines), "utf-8")
|
|
||||||
cls._prune_reports()
|
|
||||||
log.info(f"📄 兼容性报告(CSV): {report}")
|
|
||||||
return report
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def scan(cls, root: Path) -> list:
|
|
||||||
"""check 模式:只体检不动文件。"""
|
|
||||||
results = []
|
|
||||||
files = [
|
|
||||||
p for p in root.rglob("*")
|
|
||||||
if p.is_file() and p.suffix.lower() in config.SUPPORTED_EXTS
|
|
||||||
and not any(excl in str(p) for excl in config.EXCLUDE_DIRS)
|
|
||||||
]
|
|
||||||
for p in sorted(files):
|
|
||||||
r = cls.evaluate(p)
|
|
||||||
results.append((p, r))
|
|
||||||
mark = {"READY": "✅", "PREP": "🟡", "TRANSCODE": "🎞️", "BLOCKED": "⛔"}.get(r.verdict, "?")
|
|
||||||
detail = f"{r.info.get('codec')} {r.info.get('height')}p {r.info.get('mbps')}Mbps"
|
|
||||||
log.info(f"{mark} {r.verdict:<7} {p.name} [{detail}]"
|
|
||||||
+ (f" | {', '.join(r.reasons)}" if r.reasons else ""))
|
|
||||||
|
|
||||||
counts = {}
|
|
||||||
for _, r in results:
|
|
||||||
counts[r.verdict] = counts.get(r.verdict, 0) + 1
|
|
||||||
log.info(f"📊 共 {len(results)} 个文件: " +
|
|
||||||
", ".join(f"{k}={v}" for k, v in sorted(counts.items())))
|
|
||||||
cls.write_report(root, results)
|
|
||||||
return results
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ Jellyfin
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def refresh_jellyfin() -> None:
|
|
||||||
if not config.PREFLIGHT_REFRESH_JELLYFIN:
|
|
||||||
return
|
|
||||||
if not config.JELLYFIN_API_KEY:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
import urllib.request
|
|
||||||
req = urllib.request.Request(
|
|
||||||
f"{config.JELLYFIN_URL.rstrip('/')}/Library/Refresh",
|
|
||||||
headers={"X-Emby-Token": config.JELLYFIN_API_KEY},
|
|
||||||
method="POST",
|
|
||||||
)
|
|
||||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
||||||
log.info(f"🎞️ 已触发 Jellyfin 库刷新(HTTP {resp.status})")
|
|
||||||
except Exception as e:
|
|
||||||
log.warning(f"⚠️ Jellyfin 刷新失败: {e}")
|
|
||||||
|
|||||||
Reference in New Issue
Block a user