- [Subtitles] export = ass(默认):ass 轨 -c:s copy 原样导出,其余编码转 ass; 命名 <视频名>.internal.<lang>.ass;export = srt 时退回旧的清洗 SRT 逻辑 - [Subtitles] languages / codecs / prefer_internal 取代 [Features] 里的旧键(旧键仍兼容) - [Run] default_mode / default_path / force_type / extract_internal 作为 CLI 默认值 - [Archive] media_root / refresh_jellyfin 供 media-archive 读取 - 语言标签优先取轨道 tags(title 含「中」即 zh-CN)
321 lines
11 KiB
Python
321 lines
11 KiB
Python
#!/usr/bin/env python3
|
||
"""把整理好的媒体目录归档进 /hdd/sda1/media 的对应分类。
|
||
|
||
用法:
|
||
media-archive # 归档当前目录
|
||
media-archive <目录>
|
||
media-archive --to 电视节目/TV-日韩 # 指定分类,跳过选择
|
||
media-archive --dry-run # 只显示建议,不移动
|
||
media-archive --yes # 不询问确认(配合 --to 用于脚本)
|
||
|
||
说明:
|
||
源目录与媒体库同在 /hdd/sda1,正常情况下 os.rename 即可瞬间完成;
|
||
跨文件系统时自动回退 shutil.move。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import configparser
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import sys
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
from pathlib import Path
|
||
|
||
def resolve_media_root(cfg: configparser.ConfigParser) -> Path:
|
||
env = os.environ.get("SCENERENAME_MEDIA_ROOT")
|
||
if env:
|
||
return Path(env)
|
||
raw = cfg.get("Archive", "media_root", fallback="").strip() if cfg.has_section("Archive") else ""
|
||
return Path(raw or "/hdd/sda1/media")
|
||
CONFIG_PATH = Path(
|
||
os.environ.get(
|
||
"SCENERENAME_CONFIG",
|
||
"/home/ali/docker/tools/python/media/src/config.ini",
|
||
)
|
||
)
|
||
|
||
TMDB_API = "https://api.themoviedb.org/3"
|
||
GENRE_ANIMATION = 16
|
||
GENRE_REALITY = 10764
|
||
GENRE_TALK = 10767
|
||
CHINESE = {"zh", "cn", "cmn", "yue"}
|
||
HK_TW = {"TW", "HK"}
|
||
|
||
|
||
# --------------------------------------------------------------------- 基础
|
||
|
||
def die(msg: str) -> None:
|
||
print(f"❌ {msg}", file=sys.stderr)
|
||
sys.exit(1)
|
||
|
||
|
||
def load_config() -> configparser.ConfigParser:
|
||
cfg = configparser.ConfigParser()
|
||
if CONFIG_PATH.exists():
|
||
cfg.read(CONFIG_PATH, encoding="utf-8")
|
||
return cfg
|
||
|
||
|
||
def http_json(url: str, headers: dict | None = None, method: str = "GET", timeout: float = 10.0):
|
||
req = urllib.request.Request(url, headers=headers or {}, method=method)
|
||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||
body = resp.read()
|
||
if not body:
|
||
return None, resp.status
|
||
return json.loads(body.decode("utf-8")), resp.status
|
||
|
||
|
||
def human_size(num: int) -> str:
|
||
for unit in ("B", "KB", "MB", "GB", "TB"):
|
||
if num < 1024 or unit == "TB":
|
||
return f"{num:.1f} {unit}" if unit != "B" else f"{num} B"
|
||
num /= 1024
|
||
return f"{num:.1f} TB"
|
||
|
||
|
||
# --------------------------------------------------------------------- 识别
|
||
|
||
def detect_kind(path: Path) -> str:
|
||
"""有 Season 目录或 SxxExx 文件 → tv,否则 movie。"""
|
||
for child in path.iterdir():
|
||
if child.is_dir() and re.match(r"^(season\s*\d+|s\d{1,2})$", child.name, re.I):
|
||
return "tv"
|
||
for child in path.rglob("*"):
|
||
if child.is_file() and re.search(r"[.\s_-]S\d{1,2}E\d{1,3}", child.name):
|
||
return "tv"
|
||
return "movie"
|
||
|
||
|
||
def count_media(path: Path) -> tuple[int, int]:
|
||
files = [p for p in path.rglob("*") if p.is_file()]
|
||
total = sum(p.stat().st_size for p in files)
|
||
return len(files), total
|
||
|
||
|
||
def tmdb_id_of(name: str) -> str | None:
|
||
m = re.search(r"tmdbid-(\d+)", name)
|
||
return m.group(1) if m else None
|
||
|
||
|
||
def tmdb_info(tmdb_id: str, kind: str, cfg: configparser.ConfigParser) -> dict | None:
|
||
if not cfg.has_section("TMDB"):
|
||
return None
|
||
api_key = (cfg.get("TMDB", "api_key", fallback="") or "").strip()
|
||
if not api_key:
|
||
return None
|
||
language = cfg.get("TMDB", "language", fallback="zh-CN").strip() or "zh-CN"
|
||
endpoint = "tv" if kind == "tv" else "movie"
|
||
query = urllib.parse.urlencode({"api_key": api_key, "language": language})
|
||
url = f"{TMDB_API}/{endpoint}/{tmdb_id}?{query}"
|
||
try:
|
||
data, _ = http_json(url, timeout=float(cfg.get("TMDB", "timeout", fallback="10")))
|
||
return data or None
|
||
except (urllib.error.URLError, TimeoutError, ValueError):
|
||
return None
|
||
|
||
|
||
def region_of(info: dict) -> str:
|
||
lang = (info.get("original_language") or "").lower()
|
||
countries = {str(c).upper() for c in (info.get("origin_country") or []) if c}
|
||
if lang in CHINESE or "CN" in countries or "HK" in countries or "TW" in countries:
|
||
return "港台" if countries & HK_TW else "华语"
|
||
if lang in {"ja", "ko"}:
|
||
return "日韩"
|
||
return "欧美"
|
||
|
||
|
||
def suggest_category(kind: str, info: dict | None) -> str | None:
|
||
if not info:
|
||
return None
|
||
genres = {int(g.get("id", 0)) for g in info.get("genres", []) if isinstance(g, dict)}
|
||
region = region_of(info)
|
||
|
||
if genres & {GENRE_REALITY, GENRE_TALK}:
|
||
return "综艺/TVSHOW-华语"
|
||
|
||
if GENRE_ANIMATION in genres:
|
||
top = "动漫节目" if kind == "tv" else "动漫电影"
|
||
prefix = "TV" if kind == "tv" else "MOVIE"
|
||
return f"{top}/{prefix}-{region}"
|
||
|
||
top = "电视节目" if kind == "tv" else "电影"
|
||
prefix = "TV" if kind == "tv" else "MOVIE"
|
||
return f"{top}/{prefix}-{region}"
|
||
|
||
|
||
# --------------------------------------------------------------------- 分类
|
||
|
||
def list_categories(root: Path) -> list[str]:
|
||
if not root.exists():
|
||
die(f"媒体库根目录不存在: {root}")
|
||
cats: list[str] = []
|
||
for top in sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith(".")):
|
||
subs = sorted(p.name for p in top.iterdir() if p.is_dir())
|
||
if subs:
|
||
cats.extend(f"{top.name}/{s}" for s in subs)
|
||
else:
|
||
cats.append(top.name)
|
||
return cats
|
||
|
||
|
||
def resolve_category(root: Path, raw: str, cats: list[str]) -> str | None:
|
||
raw = raw.strip().strip("/")
|
||
if raw in cats:
|
||
return raw
|
||
matches = [c for c in cats if raw.lower() in c.lower()]
|
||
if len(matches) == 1:
|
||
return matches[0]
|
||
return None
|
||
|
||
|
||
# --------------------------------------------------------------------- 动作
|
||
|
||
def move_to(src: Path, dest: Path) -> None:
|
||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||
try:
|
||
os.rename(src, dest)
|
||
except OSError:
|
||
shutil.move(str(src), str(dest))
|
||
|
||
|
||
def refresh_jellyfin(cfg: configparser.ConfigParser) -> str:
|
||
if cfg.has_section("Archive") and not cfg.getboolean("Archive", "refresh_jellyfin", fallback=True):
|
||
return "已按 [Archive] refresh_jellyfin=false 跳过刷新"
|
||
if not cfg.has_section("Jellyfin"):
|
||
return "未配置 [Jellyfin],跳过刷新"
|
||
api_key = (cfg.get("Jellyfin", "api_key", fallback="") or "").strip()
|
||
base = (cfg.get("Jellyfin", "url", fallback="http://127.0.0.1:8096") or "").rstrip("/")
|
||
if not api_key:
|
||
return "未配置 Jellyfin api_key,跳过刷新"
|
||
try:
|
||
_, status = http_json(
|
||
f"{base}/Library/Refresh",
|
||
headers={"X-Emby-Token": api_key},
|
||
method="POST",
|
||
timeout=10,
|
||
)
|
||
return f"已触发 Jellyfin 库刷新(HTTP {status})"
|
||
except Exception as exc: # noqa: BLE001
|
||
return f"⚠️ Jellyfin 刷新失败: {exc}"
|
||
|
||
|
||
def choose_category(cats: list[str], suggestion: str | None) -> str | None:
|
||
print("\n可选分类:")
|
||
for idx, cat in enumerate(cats, 1):
|
||
mark = " ← 建议" if suggestion and cat == suggestion else ""
|
||
print(f" {idx:>2}. {cat}{mark}")
|
||
|
||
while True:
|
||
hint = f"回车接受建议 [{suggestion}]" if suggestion else "输入编号或分类关键字"
|
||
try:
|
||
raw = input(f"\n请选择分类({hint},q 取消): ").strip()
|
||
except EOFError:
|
||
return None
|
||
if raw.lower() in {"q", "quit", "exit"}:
|
||
return None
|
||
if not raw:
|
||
if suggestion:
|
||
return suggestion
|
||
print("⚠️ 没有建议,请显式输入编号")
|
||
continue
|
||
if raw.isdigit():
|
||
idx = int(raw)
|
||
if 1 <= idx <= len(cats):
|
||
return cats[idx - 1]
|
||
print(f"⚠️ 编号超出范围(1-{len(cats)})")
|
||
continue
|
||
picked = resolve_category(MEDIA_ROOT, raw, cats)
|
||
if picked:
|
||
return picked
|
||
print("⚠️ 没有匹配到唯一分类,请重试")
|
||
|
||
|
||
def main() -> int:
|
||
global MEDIA_ROOT
|
||
parser = argparse.ArgumentParser(description="把整理好的媒体目录归档进媒体库")
|
||
parser.add_argument("path", nargs="?", default=".", help="要归档的目录(默认当前目录)")
|
||
parser.add_argument("-p", "--path", dest="path_opt", help="要归档的目录(覆盖位置参数)")
|
||
parser.add_argument("--to", dest="target", help="直接指定分类,如 电视节目/TV-日韩")
|
||
parser.add_argument("--dry-run", action="store_true", help="只显示识别结果,不移动")
|
||
parser.add_argument("--yes", action="store_true", help="跳过最终确认")
|
||
parser.add_argument("--no-jellyfin", action="store_true", help="不触发 Jellyfin 刷新")
|
||
args = parser.parse_args()
|
||
|
||
src = Path(args.path_opt or args.path).resolve()
|
||
if not src.is_dir():
|
||
die(f"目录不存在: {src}")
|
||
if src.parent == MEDIA_ROOT or MEDIA_ROOT in src.parents:
|
||
die(f"源目录已经在媒体库里了: {src}")
|
||
|
||
cfg = load_config()
|
||
MEDIA_ROOT = resolve_media_root(cfg)
|
||
kind = detect_kind(src)
|
||
tmdb_id = tmdb_id_of(src.name)
|
||
info = tmdb_info(tmdb_id, kind, cfg) if tmdb_id else None
|
||
suggestion = suggest_category(kind, info)
|
||
|
||
cats = list_categories(MEDIA_ROOT)
|
||
if suggestion and suggestion not in cats:
|
||
suggestion = None
|
||
|
||
files, size = count_media(src)
|
||
label = "剧集" if kind == "tv" else "电影"
|
||
title = (info or {}).get("name") or (info or {}).get("title") or src.name
|
||
print(f"📁 源目录 : {src}")
|
||
print(f"🎬 识别 : {label} | {title}" + (f" | tmdbid-{tmdb_id}" if tmdb_id else " | 无 tmdbid"))
|
||
if tmdb_id and info is None:
|
||
print("⚠️ TMDB 查询失败(网络或 api_key),将不提供分类建议")
|
||
print(f"📦 内容 : {files} 个文件, {human_size(size)}")
|
||
|
||
if args.target:
|
||
category = resolve_category(MEDIA_ROOT, args.target, cats)
|
||
if not category:
|
||
die(f"分类不存在: {args.target}\n可用: " + ", ".join(cats))
|
||
else:
|
||
category = choose_category(cats, suggestion)
|
||
if not category:
|
||
print("已取消。")
|
||
return 0
|
||
|
||
dest = MEDIA_ROOT / category / src.name
|
||
print(f"\n➡️ 将移动到: {dest}")
|
||
|
||
if args.dry_run:
|
||
print("(dry-run,未执行移动)")
|
||
return 0
|
||
|
||
if dest.exists():
|
||
die(f"目标已存在,未移动: {dest}")
|
||
|
||
if not args.yes:
|
||
try:
|
||
confirm = input("确认归档?[Y/n]: ").strip().lower()
|
||
except EOFError:
|
||
confirm = "n"
|
||
if confirm not in {"", "y", "yes"}:
|
||
print("已取消。")
|
||
return 0
|
||
|
||
move_to(src, dest)
|
||
|
||
new_files, new_size = count_media(dest)
|
||
if src.exists():
|
||
die(f"移动后源目录仍存在,请手工检查: {src}")
|
||
if new_files != files or new_size != size:
|
||
die(f"文件数/体积校验不一致: 源 {files}/{size} → 目标 {new_files}/{new_size}")
|
||
print(f"✅ 归档完成: {dest}")
|
||
print(f" 校验通过: {new_files} 个文件, {human_size(new_size)}")
|
||
|
||
if not args.no_jellyfin:
|
||
print("🎞️ " + refresh_jellyfin(cfg))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|