feat(metaclean): 命中广告的视频轨名重写为技术摘要
发布组把「年糕封装-xxxxx」写进 MKV 第一条视频轨名,Jellyfin 详情页 「视频」行会把它拼在分辨率前面。命中 [Ads] 特征后不再清空,改为按 ffprobe 实测重写成「分辨率 编码 HDR」(2160p HEVC DV / 1080p H264), SDR 无第三段;探不到流参数才退回空串。 音频/字幕轨名一律不碰;没命中就不写文件,避免白白改 mtime 触发 Jellyfin 重抽章节图。metadata.scan_ads 的老路径同步改成重写。
This commit is contained in:
+147
-11
@@ -9,6 +9,14 @@
|
|||||||
Jellyfin 扫描时会把这些标签读成 plot / genre 写进 NFO,界面上就成了「备注」里的广告。
|
Jellyfin 扫描时会把这些标签读成 plot / genre 写进 NFO,界面上就成了「备注」里的广告。
|
||||||
治本的办法是无损重封装,丢掉全局元数据(`-map_metadata -1`),顺带把 NFO 里的
|
治本的办法是无损重封装,丢掉全局元数据(`-map_metadata -1`),顺带把 NFO 里的
|
||||||
对应字段也清掉。
|
对应字段也清掉。
|
||||||
|
|
||||||
|
另一类残留是**视频轨名(TrackName)**:Jellyfin 详情页「视频」那一行是
|
||||||
|
`轨名 · 分辨率 · 编码 · HDR类型`,发布组把「年糕封装」之类的品牌写进轨道名,
|
||||||
|
界面上就成了片名旁边的一串怪字。它跟容器 Info.Title 是两个字段,
|
||||||
|
`--edit info --set title=` 清不掉,得 `--edit track:v1 --set name=`。
|
||||||
|
命中特征后轨名不是清空,而是整条改写成这条流自己的技术摘要
|
||||||
|
(`2160p HEVC HDR10`,见 `build_video_track_name`),空轨名在部分播放器里
|
||||||
|
等于没信息。音频/字幕轨名(国语 / 简英双语)是有用的,一律不碰。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -21,11 +29,16 @@ from pathlib import Path
|
|||||||
from core import config
|
from core import config
|
||||||
from core.logger import log
|
from core.logger import log
|
||||||
from core.utils import FFprobeUtil
|
from core.utils import FFprobeUtil
|
||||||
|
from services.mediainfo import MediaInfoService
|
||||||
|
|
||||||
# 广告特征由 config.ini [Ads] keywords(字面量)+ patterns(正则)合成,
|
# 广告特征由 config.ini [Ads] keywords(字面量)+ patterns(正则)合成,
|
||||||
# 定义在 core/config.py;这里保留同名变量给本模块与其它调用方用。
|
# 定义在 core/config.py;这里保留同名变量给本模块与其它调用方用。
|
||||||
AD_PATTERN = config.AD_PATTERN
|
AD_PATTERN = config.AD_PATTERN
|
||||||
|
|
||||||
|
# 视频轨名在 inspect() 返回的字典里用的键:它不在 format tags 里,
|
||||||
|
# 用一个不会和真实标签重名的键,预览日志会打成「视频轨名=年糕封装」。
|
||||||
|
VIDEO_TITLE_KEY = "视频轨名"
|
||||||
|
|
||||||
|
|
||||||
class MetaCleanService:
|
class MetaCleanService:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -35,6 +48,57 @@ class MetaCleanService:
|
|||||||
tags = ((data.get("format") or {}).get("tags") or {})
|
tags = ((data.get("format") or {}).get("tags") or {})
|
||||||
return {k: v for k, v in tags.items() if AD_PATTERN.search(str(v))}
|
return {k: v for k, v in tags.items() if AD_PATTERN.search(str(v))}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def scan_video_title(path: Path) -> str:
|
||||||
|
"""返回第一条视频轨的名称(TrackName);非 MKV 或没有则返回空串。
|
||||||
|
|
||||||
|
Jellyfin 的 `MediaSources[].MediaStreams[视频].Title` 就是这个字段,
|
||||||
|
详情页会把它拼在「视频」行最前面。注意它不是容器 Info.Title。
|
||||||
|
"""
|
||||||
|
if path.suffix.lower() != ".mkv":
|
||||||
|
return ""
|
||||||
|
data = FFprobeUtil.get_json(path, "-select_streams", "v:0", "-show_streams")
|
||||||
|
for stream in data.get("streams") or []:
|
||||||
|
return str(((stream.get("tags") or {}).get("title") or "")).strip()
|
||||||
|
return ""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def build_video_track_name(path: Path) -> str:
|
||||||
|
"""按实测参数重写视频轨名,格式对齐 Scene 命名:`2160p HEVC HDR10`。
|
||||||
|
|
||||||
|
轨名里原来的发布组品牌(「年糕封装-xxxxx」)整条替换成这条流自己的技术
|
||||||
|
摘要,而不是留空——空轨名在部分播放器里等于没有信息。HDR 为 SDR 时没有
|
||||||
|
第三段,退化成分辨率+编码(`1080p H264`)。
|
||||||
|
|
||||||
|
取不到流参数时返回空串,调用方会退回清空:宁可空,也不留广告。
|
||||||
|
"""
|
||||||
|
data = FFprobeUtil.get_json(path, "-show_streams")
|
||||||
|
stream = MediaInfoService._main_video_stream(data.get("streams") or [])
|
||||||
|
if not stream:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
width = int(stream.get("width") or 0)
|
||||||
|
height = int(stream.get("height") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return ""
|
||||||
|
if not width or not height:
|
||||||
|
return ""
|
||||||
|
parts = [
|
||||||
|
MediaInfoService.classify_resolution(width, height),
|
||||||
|
MediaInfoService.video_codec_name(stream.get("codec_name") or ""),
|
||||||
|
MediaInfoService.hdr_tag(stream),
|
||||||
|
]
|
||||||
|
return " ".join(part for part in parts if part)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def inspect(path: Path) -> dict:
|
||||||
|
"""容器里带广告的字段:全局 Tag(format tags)+ 命中特征的视频轨名。"""
|
||||||
|
junk = dict(MetaCleanService.scan(path))
|
||||||
|
video_title = MetaCleanService.scan_video_title(path)
|
||||||
|
if video_title and AD_PATTERN.search(video_title):
|
||||||
|
junk[VIDEO_TITLE_KEY] = video_title
|
||||||
|
return junk
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _has_space(path: Path) -> bool:
|
def _has_space(path: Path) -> bool:
|
||||||
try:
|
try:
|
||||||
@@ -44,21 +108,92 @@ class MetaCleanService:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def strip(path: Path) -> bool:
|
def _strip_mkv_tags(path: Path, video_title: str | None = None,
|
||||||
"""无损重封装,丢弃全局元数据;失败时保留原文件。"""
|
clear_global: bool = True) -> bool:
|
||||||
|
"""MKV 优先原地清标签(mkvpropedit),不重封装。
|
||||||
|
|
||||||
|
为什么必须优先走这条路:REMUX 里的字体附件常常没有 mimetype,`-map 0 -c copy`
|
||||||
|
会被 matroska 复用器直接拒绝(`Attachment stream N has no mimetype tag` →
|
||||||
|
`Could not write header`),文件根本写不出来;而全片重封装一个 78G 的 REMUX
|
||||||
|
还要 2 倍以上的空闲空间。原地改标签是毫秒级、零额外空间的。
|
||||||
|
|
||||||
|
分工:
|
||||||
|
- `--tags global:` 清掉 Segment 级 Tag(GENRE/COMMENT 这类广告常藏在这里);
|
||||||
|
- `--edit info --set title=` 清 TITLE(它是 Info 字段,不属于 Tag);
|
||||||
|
- `--edit track:v1 --set name=<技术摘要>` 把**第一条视频轨的名称**从发布组
|
||||||
|
品牌改写成实测参数(Jellyfin「视频」行的前缀)。
|
||||||
|
`video_title` 为 None 表示轨名没命中广告、一个字都不动;传空串则清空轨名。
|
||||||
|
轨道级 Tag 仍然刻意不用 `--tags all:`:音频/字幕轨名(国语、简英双语)是
|
||||||
|
正常信息,误清会让 Jellyfin 里轨名全丢。
|
||||||
|
"""
|
||||||
|
cmd = ["mkvpropedit", str(path)]
|
||||||
|
if clear_global:
|
||||||
|
cmd += ["--edit", "info", "--set", "title=", "--tags", "global:"]
|
||||||
|
if video_title is not None:
|
||||||
|
cmd += ["--edit", "track:v1", "--set", f"name={video_title}"]
|
||||||
|
if len(cmd) == 2:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||||
|
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||||
|
log.warning(f"⚠️ mkvpropedit 执行失败: {path.name} — {exc}")
|
||||||
|
return False
|
||||||
|
if result.returncode != 0:
|
||||||
|
lines = (result.stderr or result.stdout or "").strip().splitlines()
|
||||||
|
detail = lines[-1] if lines else f"返回码 {result.returncode}"
|
||||||
|
log.warning(f"⚠️ mkvpropedit 执行失败: {path.name} — {detail[:120]}")
|
||||||
|
return False
|
||||||
|
leftover = MetaCleanService.inspect(path)
|
||||||
|
if leftover:
|
||||||
|
# 广告藏在 muxing/writing application 之类 Info 字段里,原地清不掉
|
||||||
|
log.warning(f"⚠️ 原地清标签后仍有残留({', '.join(leftover)}),改用重封装: {path.name}")
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def strip(path: Path, junk: dict | None = None) -> bool:
|
||||||
|
"""清掉容器里的广告元数据;失败时保留原文件。"""
|
||||||
|
junk = MetaCleanService.inspect(path) if junk is None else junk
|
||||||
|
rewrite_title = VIDEO_TITLE_KEY in junk
|
||||||
|
clear_global = any(k != VIDEO_TITLE_KEY for k in junk)
|
||||||
|
# 轨名命中就整条替换成实测摘要;探测失败(空串)时退回清空,绝不留广告
|
||||||
|
video_title = MetaCleanService.build_video_track_name(path) if rewrite_title else None
|
||||||
|
suffix = path.suffix.lower()
|
||||||
|
# MKV 走原地改标签:不需要额外空间,也不会碰附件流
|
||||||
|
if suffix == ".mkv" and MetaCleanService._strip_mkv_tags(path, video_title, clear_global):
|
||||||
|
detail = f",视频轨名 → {video_title or '空'}" if rewrite_title else ""
|
||||||
|
log.info(f"🧹 已清除广告元数据(原地改标签): {path.name}{detail}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
if not clear_global:
|
||||||
|
# 只有视频轨名命中,容器又不是 MKV:没有无损的原地改法,别去动文件
|
||||||
|
log.warning(f"⚠️ {path.name} 只有视频轨名命中广告,非 MKV 容器跳过清理")
|
||||||
|
return False
|
||||||
|
|
||||||
if not MetaCleanService._has_space(path):
|
if not MetaCleanService._has_space(path):
|
||||||
log.warning(f"⚠️ 磁盘空间不足,跳过重封装: {path.name}")
|
log.warning(f"⚠️ 磁盘空间不足,跳过重封装: {path.name}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
tmp = path.with_name(f".{path.stem}.cleanmeta{path.suffix}")
|
tmp = path.with_name(f".{path.stem}.cleanmeta{path.suffix}")
|
||||||
base = ["-map_metadata", "-1", "-map_chapters", "-1", str(tmp)]
|
base = ["-map_metadata", "-1", "-map_chapters", "-1", str(tmp)]
|
||||||
# 先按「原样拷贝所有流」试;MP4 装不了 subrip 之类的字幕流时会失败,
|
# 先按「原样拷贝所有流」试;装不下的容器(MP4 放不了 subrip 字幕、
|
||||||
# 再退化成「视频/音频原样 + 字幕转 mov_text」
|
# MKV 里有缺 mimetype 的附件流)再退化。
|
||||||
attempts = [
|
attempts = [
|
||||||
["ffmpeg", "-v", "error", "-y", "-i", str(path), "-map", "0", "-c", "copy", *base],
|
["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", str(path), "-map", "0", "-c", "copy", *base],
|
||||||
["ffmpeg", "-v", "error", "-y", "-i", str(path),
|
|
||||||
"-map", "0:v", "-map", "0:a", "-map", "0:s?", "-c", "copy", "-c:s", "mov_text", *base],
|
|
||||||
]
|
]
|
||||||
|
if suffix in {".mp4", ".m4v", ".mov"}:
|
||||||
|
# mov_text 只在 MP4 系容器合法,绝不能用于 matroska
|
||||||
|
attempts.append(
|
||||||
|
["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", str(path),
|
||||||
|
"-map", "0:v", "-map", "0:a?", "-map", "0:s?",
|
||||||
|
"-c", "copy", "-c:s", "mov_text", *base])
|
||||||
|
else:
|
||||||
|
# MKV 兜底:排除附件流(缺 mimetype 会导致写头失败)
|
||||||
|
attempts.append(
|
||||||
|
["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", str(path),
|
||||||
|
"-map", "0:v", "-map", "0:a?", "-map", "0:s?",
|
||||||
|
"-c", "copy", *base])
|
||||||
|
|
||||||
result = None
|
result = None
|
||||||
for cmd in attempts:
|
for cmd in attempts:
|
||||||
try:
|
try:
|
||||||
@@ -120,11 +255,12 @@ class MetaCleanService:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def process(cls, path: Path) -> dict:
|
def process(cls, path: Path) -> dict:
|
||||||
"""扫描 + 重封装 + 清 NFO,返回统计。"""
|
"""扫描 + 改写标签 + 清 NFO,返回统计。"""
|
||||||
junk = cls.scan(path)
|
junk = cls.inspect(path)
|
||||||
if not junk:
|
if not junk:
|
||||||
return {"hit": False}
|
return {"hit": False}
|
||||||
if not cls.strip(path):
|
if not cls.strip(path, junk):
|
||||||
return {"hit": True, "stripped": False}
|
return {"hit": True, "stripped": False}
|
||||||
cls.clean_nfo(path)
|
cls.clean_nfo(path)
|
||||||
return {"hit": True, "stripped": True, "tags": junk}
|
track_name = cls.scan_video_title(path) if VIDEO_TITLE_KEY in junk else ""
|
||||||
|
return {"hit": True, "stripped": True, "tags": junk, "track_name": track_name}
|
||||||
|
|||||||
@@ -12,16 +12,25 @@ class MetadataService:
|
|||||||
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, stderr=subprocess.DEVNULL, text=True).stdout.strip()
|
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 video_title and config.AD_PATTERN.search(video_title):
|
||||||
task_mgr.add_clean(
|
task_mgr.add_clean(
|
||||||
f"抹除 {file_path.name} 中的广告 -> '{video_title}'",
|
f"规范化 {file_path.name} 的视频轨名 -> '{video_title}'",
|
||||||
MetadataService.do_clear,
|
MetadataService.do_clear,
|
||||||
file_path
|
file_path
|
||||||
)
|
)
|
||||||
|
|
||||||
@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, stderr=subprocess.DEVNULL)
|
"""命中广告后重写轨名,与阶段 2(metaclean)保持一致——不是删空。
|
||||||
|
|
||||||
|
正常流程里阶段 2 已经先跑过一轮,轨名会被换成技术摘要,这里通常命中不到;
|
||||||
|
只有关掉 `[Ads] clean_ad_tags` 时才会走到这条老路径,所以两者行为必须一样。
|
||||||
|
"""
|
||||||
|
from services.metaclean import MetaCleanService
|
||||||
|
track_name = MetaCleanService.build_video_track_name(file_path)
|
||||||
|
subprocess.run(["mkvpropedit", str(file_path), "--edit", "track:v1",
|
||||||
|
"--set", f"name={track_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):
|
||||||
|
|||||||
Reference in New Issue
Block a user