feat(metaclean): 把广告元数据清理做成整理流水线的阶段

- 新增 services/metaclean.py:扫描容器标签(comment/copyright/genre),
  命中广告特征就 -map_metadata -1 无损重封装,再清同名 NFO 里的 plot/genre
- 媒体整理/综艺整理里新增「阶段:清理广告元数据」,在生成改名计划前执行;
  配置 Ads.clean_tags 可关闭(默认 true),--rename-only 时跳过
- 安全检查:磁盘不足、超时、体积偏差 >10% 时保留原文件
- 单文件实测:1,297,318,193 → 1,295,924,416 字节,时长 2582.9s 不变,广告 genre 消失
- 广告特征:link3.cc / yunpantv / ysepan.com / TG@ / Qqun@ / WOW64) / 912484288
This commit is contained in:
ali
2026-11-20 02:10:14 +08:00
parent eb3ff851d7
commit a7e4e2b2be
3 changed files with 168 additions and 0 deletions
+2
View File
@@ -144,6 +144,8 @@ EXTRAS_DIRS = [d.strip().lower() for d in _parser.get(
fallback='extras,featurettes,behind the scenes,deleted scenes,interviews,scenes,shorts,trailers,samples' fallback='extras,featurettes,behind the scenes,deleted scenes,interviews,scenes,shorts,trailers,samples'
).split(',') if d.strip()] ).split(',') if d.strip()]
AD_KEYWORDS = _parser.get('Ads', 'keywords', fallback='推广信息').split(',') AD_KEYWORDS = _parser.get('Ads', 'keywords', fallback='推广信息').split(',')
# 整理时清理文件容器内的广告元数据(无损重封装)
CLEAN_AD_TAGS = _parser.getboolean('Ads', 'clean_tags', fallback=True)
# 3. 运行默认参数(CLI 未给出时生效) # 3. 运行默认参数(CLI 未给出时生效)
DEFAULT_MODE = (_parser.get('Run', 'default_mode', fallback='auto').strip() or 'auto').lower() DEFAULT_MODE = (_parser.get('Run', 'default_mode', fallback='auto').strip() or 'auto').lower()
+45
View File
@@ -36,6 +36,11 @@ class MediaPipeline:
if not self.auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。") if not self.auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。")
return 0 return 0
# 阶段:清理容器里的广告元数据(治本:无损重封装丢掉全局标签)
if (getattr(config, "CLEAN_AD_TAGS", True)
and not getattr(self.args, "rename_only", False)):
self._clean_ad_tags()
self._generate_plan() self._generate_plan()
# 只在「整库扫描」且存在 PREP/BLOCKED 时落报告,避免每个剧目录多一个 CSV # 只在「整库扫描」且存在 PREP/BLOCKED 时落报告,避免每个剧目录多一个 CSV
if self.target_dir.resolve() == config.MEDIA_ROOT.resolve(): if self.target_dir.resolve() == config.MEDIA_ROOT.resolve():
@@ -198,6 +203,46 @@ class MediaPipeline:
self.valid_files.append((f, *struct)) self.valid_files.append((f, *struct))
def _clean_ad_tags(self) -> None:
"""阶段:清理容器里的广告元数据(comment/genre 等被发布组写成广告链接)。
治本做法是无损重封装丢掉全局元数据;顺手清掉同名 NFO 里的广告字段。
"""
from services.metaclean import MetaCleanService
files = [f for f in self.valid_files if f.suffix.lower() in (".mp4", ".mkv", ".mov", ".ts", ".m2ts")]
if not files:
return
hits = []
for path in files:
junk = MetaCleanService.scan(path)
if junk:
hits.append((path, junk))
if not hits:
return
log.info(f"🧹 阶段:发现 {len(hits)} 个文件的容器元数据里带广告")
for path, junk in hits:
preview = "; ".join(f"{k}={str(v)[:40]}" for k, v in junk.items())
log.info(f" - {path.name[:50]} ← {preview}")
if not self.auto_execute:
try:
answer = input(f"⚠️ 是否重封装这 {len(hits)} 个文件以清除广告?[y/n]: ").strip().lower()
except EOFError:
log.warning("⛔ 没有可用的终端输入,跳过广告元数据清理。")
return
if answer not in {"y", "yes"}:
log.info("💤 已跳过广告元数据清理。")
return
stripped = 0
for path, _junk in hits:
result = MetaCleanService.process(path)
if result.get("stripped"):
stripped += 1
log.info(f"🧹 广告元数据清理完成:{stripped}/{len(hits)} 个文件已重封装")
def _generate_plan(self): def _generate_plan(self):
if not self.auto_execute: log.info("📝 正在生成执行计划...") if not self.auto_execute: log.info("📝 正在生成执行计划...")
dir_video_counts = {f.parent: 0 for f, *_ in self.valid_files} dir_video_counts = {f.parent: 0 for f, *_ in self.valid_files}
+121
View File
@@ -0,0 +1,121 @@
# src/services/metaclean.py
"""清理媒体文件容器里的广告元数据(去广告标签)。
有些发布组用魔改的 ffmpeg 封装,把广告写进容器标签:
- MP4 的 ©cmt(comment)→ "TG_CHANNEL https://link3.cc/yunpantv"
- MP4 的 genre → "High Efficiency Video Coding(Windows NT 10.0; WOW64) ... [link3.cc/9420] ..."
- ©cprt(copyright)、description 等
Jellyfin 扫描时会把这些标签读成 plot / genre 写进 NFO,界面上就成了「备注」里的广告。
治本的办法是无损重封装,丢掉全局元数据(`-map_metadata -1`),顺带把 NFO 里的
对应字段也清掉。
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import xml.etree.ElementTree as ET
from pathlib import Path
from core.logger import log
from core.utils import FFprobeUtil
# 广告特征:域名、Telegram、QQ 群、以及魔改 ffmpeg 特有的编码描述
AD_PATTERN = re.compile(
r"link3\.cc|yunpantv|ysepan\.com|TG@|Qqun@|WOW64\)|Advanced Audio Codec Low Comp|912484288",
re.I,
)
class MetaCleanService:
@staticmethod
def scan(path: Path) -> dict:
"""返回该文件里带广告的容器标签;没有则返回空 dict。"""
data = FFprobeUtil.get_json(path, "-show_format")
tags = ((data.get("format") or {}).get("tags") or {})
return {k: v for k, v in tags.items() if AD_PATTERN.search(str(v))}
@staticmethod
def _has_space(path: Path) -> bool:
try:
need = int(path.stat().st_size * 1.05)
return shutil.disk_usage(path.parent).free > need
except OSError:
return False
@staticmethod
def strip(path: Path) -> bool:
"""无损重封装,丢弃全局元数据;失败时保留原文件。"""
if not MetaCleanService._has_space(path):
log.warning(f"⚠️ 磁盘空间不足,跳过重封装: {path.name}")
return False
tmp = path.with_name(f".{path.stem}.cleanmeta{path.suffix}")
cmd = [
"ffmpeg", "-v", "error", "-y", "-i", str(path),
"-map", "0", "-c", "copy", "-map_metadata", "-1", "-map_chapters", "-1",
str(tmp),
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=7200)
except subprocess.TimeoutExpired:
tmp.unlink(missing_ok=True)
log.warning(f"⚠️ 重封装超时: {path.name}")
return False
if result.returncode != 0 or not tmp.exists() or tmp.stat().st_size == 0:
tmp.unlink(missing_ok=True)
log.warning(f"⚠️ 重封装失败: {path.name} — {result.stderr.strip()[:120]}")
return False
# 体积变化过大说明流有问题,放弃替换
old_size = path.stat().st_size
new_size = tmp.stat().st_size
if not (old_size * 0.90 <= new_size <= old_size * 1.10):
tmp.unlink(missing_ok=True)
log.warning(f"⚠️ 重封装后体积异常({old_size} → {new_size}),保留原文件: {path.name}")
return False
os.replace(tmp, path)
log.info(f"🧹 已清除广告元数据: {path.name}")
return True
@staticmethod
def clean_nfo(video: Path) -> bool:
"""清掉同名 NFO 里带广告的 plot / genre(NFO 属主可能是 root,失败只告警)。"""
nfo = video.with_suffix(".nfo")
if not nfo.exists():
return False
try:
tree = ET.parse(nfo)
root = tree.getroot()
except (ET.ParseError, OSError):
return False
changed = False
for tag in ("plot", "outline", "genre", "tagline", "comment"):
for element in root.findall(tag):
if element.text and AD_PATTERN.search(element.text):
root.remove(element)
changed = True
if not changed:
return False
try:
tree.write(nfo, encoding="utf-8", xml_declaration=True)
return True
except OSError as exc:
log.warning(f"⚠️ NFO 清理失败 {nfo.name}: {exc}")
return False
@classmethod
def process(cls, path: Path) -> dict:
"""扫描 + 重封装 + 清 NFO,返回统计。"""
junk = cls.scan(path)
if not junk:
return {"hit": False}
if not cls.strip(path):
return {"hit": True, "stripped": False}
cls.clean_nfo(path)
return {"hit": True, "stripped": True, "tags": junk}