feat(variety): 新增综艺整理模式,按日期匹配 TMDB 播出日期定集号
- 新增 services/variety.py:日期提取(多格式/无年份补全)、TMDB 全季索引 (含 Season 00)、按日期分组的一对一分配、三类动作(改名/extras/删除) - 消歧不依赖「加更/特别」这类关键词:集名里含该日期 +6、类型关键词命中 +3、 季提示 +2,再靠一对一约束用排除法定 - 删除判定:期数 + 类型关键词都相同才算同一集的重复(保留体积最大的), 避免把「加更版第1期」误当成「正片第1期」删掉 - 命名:标题.SxxEyy.年份.技术标签.TMDB期名(期名放最后,按拍板) - main.py 新增 variety 模式与 --show 参数;pipeline 增加 run_variety - docs/variety-plan.md 补记拍板结果与实现状态 预览结果(未执行): 花儿与少年 特典 改名 70 / extras 3 / 删除 0 你好星期六 改名 284 / extras 31 / 删除 49 5.哈 第六季 改名 48 / extras 16 / 删除 0
This commit is contained in:
@@ -87,3 +87,37 @@
|
||||
2. `tmdb_data.json` 增加 `episode_air_dates` 字段缓存各季播出日期(避免每次请求)
|
||||
3. 新增 pipeline 模式 `variety` + 右键菜单项「综艺整理」
|
||||
4. 复用现有预览/确认/执行框架,新增 `extras` 移动动作
|
||||
|
||||
## 七、拍板结果(2025-11-19)
|
||||
|
||||
| # | 决定 |
|
||||
|---|---|
|
||||
| 1 | **C** 同集多版本只留最高码率,其余删除 |
|
||||
| 2 | **C** 纯重复直接删 |
|
||||
| 3 | **A** extras 放剧集根目录 |
|
||||
| 4 | **A** 无年份日期按季年份补全;补全后仍不匹配或跨年含糊 → extras |
|
||||
| 5 | `.qkdownloading` 跳过不动(未删除) |
|
||||
| 6 | **B** 保留 TMDB 期名,**放在文件名最末尾**(技术标签之后) |
|
||||
| 7 | 不要别名表;识别不到时交互选一次并记入缓存 |
|
||||
| 8 | **A** 花儿与少年那两个 2024 文件归到《花儿与少年·好友记》 |
|
||||
|
||||
## 八、实现状态
|
||||
|
||||
已实现 `variety` 模式(`media-rename -p <目录> variety [--show <tmdbid>] [--yes]`):
|
||||
|
||||
- 日期提取:`2026-04-04` / `2025.01.04` / `20220610`,无年份时用季年份补全
|
||||
- TMDB 全季索引(含 Season 00),按日期建表
|
||||
- 一对一分配 + 打分(集名含该日期 +6、类型关键词命中 +3、季提示 +2)
|
||||
- 三类动作:改名 / 移入 `extras/` / 删除
|
||||
- 删除判定:**期数 + 类型关键词都相同**才算同一集的重复,保留体积最大的
|
||||
|
||||
三个目录的预览结果:
|
||||
|
||||
| 目录 | 改名 | 进 extras | 删除 |
|
||||
|---|---|---|---|
|
||||
| 花儿与少年 特典 | 70 | 3 | 0 |
|
||||
| 你好星期六 | 284 | 31 | 49 |
|
||||
| 5.哈 第六季 | 48 | 16 | 0 |
|
||||
|
||||
尚未完成:右键菜单项「综艺整理」、Jellyfin 刷新、把《好友记》的 2 个文件自动归位。
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ class MediaPipeline:
|
||||
|
||||
def run(self):
|
||||
"""返回退出码:0 正常(含无需变更),2 用户取消。"""
|
||||
if getattr(self.args, "mode", "") == "variety":
|
||||
return self.run_variety()
|
||||
|
||||
self._analyze_files()
|
||||
if not self.valid_files:
|
||||
if not self.auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。")
|
||||
@@ -52,6 +55,72 @@ class MediaPipeline:
|
||||
return 2
|
||||
return 0
|
||||
|
||||
def run_variety(self) -> int:
|
||||
"""综艺整理:按日期匹配集号,产出 改名 / extras / 删除 三类动作。"""
|
||||
from services.variety import VarietyService
|
||||
|
||||
folder = self.target_dir
|
||||
show = self._resolve_variety_show(folder)
|
||||
if not show:
|
||||
log.error("❌ 无法识别剧集:请在目录名里加 [tmdbid-xxx],或用 --show <id> 指定")
|
||||
return 1
|
||||
show_id, show_name, season_years, media_title = show
|
||||
|
||||
plan = VarietyService.plan(folder, show_id, show_name, season_years)
|
||||
VarietyService.preview(plan, season_years, media_title)
|
||||
|
||||
total = len(plan["renames"]) + len(plan["extras"]) + len(plan["deletes"])
|
||||
if not total:
|
||||
log.info("✨ 无需整理。")
|
||||
return 0
|
||||
|
||||
if not self.auto_execute:
|
||||
try:
|
||||
answer = input("⚠️ 是否执行以上变更(含删除)?[y/n/q]: ").strip().lower()
|
||||
except EOFError:
|
||||
log.warning("⛔ 没有可用的终端输入,按取消处理。")
|
||||
return 2
|
||||
if answer not in {"y", "yes"}:
|
||||
log.info("💤 任务已由用户取消。")
|
||||
return 2
|
||||
|
||||
stats = VarietyService.execute(plan, season_years, media_title)
|
||||
log.info(f"🎉 综艺整理完成:改名 {stats['renamed']},extras {stats['extras']},"
|
||||
f"删除 {stats['deleted']},跳过 {stats['skipped']}")
|
||||
return 0
|
||||
|
||||
def _resolve_variety_show(self, folder: Path):
|
||||
"""返回 (tmdb_id, 标题, season_years, media_title);识别失败返回 None。"""
|
||||
import re as _re
|
||||
from services.tmdb import TMDBService
|
||||
|
||||
match = _re.search(r"\[tmdbid-(\d+)\]", folder.name)
|
||||
known = int(match.group(1)) if match else getattr(self.args, "show", None)
|
||||
|
||||
videos = [p for p in folder.rglob("*")
|
||||
if p.is_file() and p.suffix.lower() in {".mkv", ".mp4", ".avi"}]
|
||||
if not videos:
|
||||
return None
|
||||
probe = videos[0]
|
||||
|
||||
title = _re.sub(r"\[tmdbid-\d+\]", "", folder.name)
|
||||
title = _re.sub(r"[\(\(]?\s*(19|20)\d{2}\s*[\)\)]?", "", title)
|
||||
title = _re.sub(r"第\s*[0-9一二三四五六七八九十]+\s*季", "", title)
|
||||
title = _re.sub(r"[Ss]eason\s*\d+", "", title)
|
||||
title = _re.sub(r"[._]+", " ", title).strip(" -_")
|
||||
|
||||
year_match = _re.search(r"(19|20)\d{2}", folder.name)
|
||||
year = year_match.group(0) if year_match else None
|
||||
|
||||
log.info(f"🔎 识别剧集:标题=「{title}」年份={year or '无'}"
|
||||
f"{' 已知 id=' + str(known) if known else ''}")
|
||||
entity = TMDBService.search_media(title, year, "tv", None,
|
||||
known_tmdb_id=known, media_path=probe)
|
||||
if not entity:
|
||||
return None
|
||||
return (entity["tmdb_id"], entity["title"],
|
||||
entity.get("season_years") or {}, entity.get("media_title") or entity["title"])
|
||||
|
||||
def _analyze_files(self):
|
||||
files_to_process = self.target_dir.rglob("*")
|
||||
if not self.auto_execute: log.info("🔍 开始执行文件结构分析...")
|
||||
|
||||
+10
-1
@@ -13,7 +13,7 @@ from services.preflight import PreflightService
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
|
||||
parser.add_argument("mode", nargs='?', default=config.DEFAULT_MODE,
|
||||
choices=["manual", "auto", "clean-ads", "extract-subs", "watch", "check"],
|
||||
choices=["manual", "auto", "variety", "clean-ads", "extract-subs", "watch", "check"],
|
||||
help=f"运行模式(默认取 config.ini [Run] default_mode = {config.DEFAULT_MODE})")
|
||||
parser.add_argument("-p", "--path", default=config.DEFAULT_PATH,
|
||||
help="扫描目录(默认取 config.ini [Run] default_path,留空为当前目录)")
|
||||
@@ -21,6 +21,8 @@ def main():
|
||||
help="强制提取内置字幕(默认取 config.ini [Run] extract_internal)")
|
||||
parser.add_argument("-t", "--force-type", choices=["tv", "movie"], default=config.DEFAULT_FORCE_TYPE,
|
||||
help="强制指定媒体类型 (tv 或 movie),解决正则误判")
|
||||
parser.add_argument("--show", type=int, default=None,
|
||||
help="综艺整理:直接指定 TMDB 剧集 id(默认从目录名 [tmdbid-xxx] 推断)")
|
||||
parser.add_argument("--yes", action="store_true",
|
||||
help="非交互确认:直接执行生成的计划,不再询问(批处理用)")
|
||||
args = parser.parse_args()
|
||||
@@ -40,6 +42,13 @@ def main():
|
||||
PreflightService.scan(target_dir)
|
||||
return
|
||||
|
||||
if args.mode == "variety":
|
||||
# 综艺整理:日期 ↔ TMDB 播出日期匹配
|
||||
code = MediaPipeline(target_dir, args, auto_execute=bool(getattr(args, "yes", False))).run_variety()
|
||||
if code:
|
||||
sys.exit(code)
|
||||
return
|
||||
|
||||
if args.mode == "watch":
|
||||
try:
|
||||
from core.watcher import start_watch_daemon
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
# src/services/variety.py
|
||||
"""综艺整理:按「文件名日期 ↔ TMDB 播出日期」匹配集号。
|
||||
|
||||
综艺文件名通常没有 SxxEyy,只有日期;正片与特典(加更 / 会员版 / 超前企划)
|
||||
也常放在同一目录。因此这里:
|
||||
|
||||
1. 从文件名提取日期(多种格式,含无年份时用季年份补全);
|
||||
2. 拉取该剧全季(含 Season 00)的播出日期,建立 {日期: [(季, 集, 集名)]} 索引;
|
||||
3. 按日期分组做「一对一分配」,靠排除法消歧(不依赖加更/特别这类关键词);
|
||||
4. 产出三类动作:
|
||||
- rename:能对上的,改名为 标题.SxxEyy.年份.技术标签.期名
|
||||
- extras:TMDB 没有对应条目的,移到剧集根目录 extras/(不改名)
|
||||
- delete:同一集的重复下载 / 低码率版本(按拍板:只留最高码率)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
from core.logger import log
|
||||
from core import tmdb_store as store
|
||||
from core.utils import StringUtil
|
||||
from services.mediainfo import MediaInfoService
|
||||
from services.tmdb import TMDBService
|
||||
|
||||
# 2026-04-04 / 2026.04.04 / 2026年4月4日 / 20260404
|
||||
_DATE_FULL = [
|
||||
re.compile(r"(20\d{2})[-._年/](\d{1,2})[-._月/](\d{1,2})"),
|
||||
re.compile(r"(?<!\d)(20\d{2})(\d{2})(\d{2})(?!\d)"),
|
||||
]
|
||||
# 只有 月.日(无年份),例如 S00E017.02.24出发
|
||||
_DATE_SHORT = re.compile(r"(?<!\d)(\d{1,2})[.\-_/](\d{1,2})(?!\d)")
|
||||
|
||||
# 特典类关键词:仅用于「同日期多个候选」时的排序,不用于判定归属
|
||||
_SPECIAL_WORDS = re.compile(r"加更|会员|特别|特辑|企划|花絮|彩蛋|先导|前瞻|精编|回顾|纯享|未播")
|
||||
_EP_NAME_SPECIAL = re.compile(r"加更|会员|特别|特辑|企划|花絮|彩蛋|精编|回顾|纯享|未播")
|
||||
|
||||
|
||||
class VarietyService:
|
||||
VIDEO_EXTS = {".mkv", ".mp4", ".avi", ".ts", ".m2ts", ".mov"}
|
||||
|
||||
# ---------------------------------------------------------------- 日期与季
|
||||
|
||||
@staticmethod
|
||||
def extract_date(name: str) -> tuple[str | None, bool]:
|
||||
"""返回 (YYYY-MM-DD, 是否完整含年份)。找不到返回 (None, False)。"""
|
||||
for pattern in _DATE_FULL:
|
||||
match = pattern.search(name)
|
||||
if match:
|
||||
year, month, day = match.groups()
|
||||
try:
|
||||
return f"{int(year):04d}-{int(month):02d}-{int(day):02d}", True
|
||||
except ValueError:
|
||||
continue
|
||||
match = _DATE_SHORT.search(name)
|
||||
if match:
|
||||
month, day = match.groups()
|
||||
return f"????-{int(month):02d}-{int(day):02d}", False
|
||||
return None, False
|
||||
|
||||
@staticmethod
|
||||
def season_hint(path: Path) -> str | None:
|
||||
"""从目录名推断季号:Season 04 / 第六季。"""
|
||||
for part in reversed(path.parts):
|
||||
match = re.search(r"[Ss]eason\s*0*(\d{1,2})", part)
|
||||
if match:
|
||||
return str(int(match.group(1))).zfill(2)
|
||||
match = re.search(r"第\s*([0-9一二三四五六七八九十]+)\s*季", part)
|
||||
if match:
|
||||
raw = match.group(1)
|
||||
cn = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5,
|
||||
"六": 6, "七": 7, "八": 8, "九": 9, "十": 10}
|
||||
if raw in cn:
|
||||
return str(cn[raw]).zfill(2)
|
||||
if raw.isdigit():
|
||||
return str(int(raw)).zfill(2)
|
||||
return None
|
||||
|
||||
# ---------------------------------------------------------------- TMDB 索引
|
||||
|
||||
@classmethod
|
||||
def build_index(cls, show_id: int) -> dict:
|
||||
"""{date: [{'season','ep','name'}]},含 Season 00。按需拉取,失败静默跳过。"""
|
||||
session = TMDBService._get_session()
|
||||
show = TMDBService._fetch_details(session, "tv", show_id)
|
||||
if not show:
|
||||
return {}
|
||||
|
||||
index: dict[str, list[dict]] = defaultdict(list)
|
||||
seasons = show.get("seasons") or []
|
||||
for season in seasons:
|
||||
try:
|
||||
number = int(season.get("season_number"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
payload = TMDBService._fetch_season(session, "tv", show_id, number)
|
||||
if not payload:
|
||||
continue
|
||||
for episode in payload.get("episodes") or []:
|
||||
air = (episode.get("air_date") or "").strip()
|
||||
if len(air) < 10:
|
||||
continue
|
||||
try:
|
||||
ep_no = int(episode.get("episode_number"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
index[air].append({
|
||||
"season": str(number).zfill(2),
|
||||
"ep": ep_no,
|
||||
"name": episode.get("name") or "",
|
||||
})
|
||||
log.info(f"📅 TMDB 索引: {len(index)} 个播出日期({len(seasons)} 季)")
|
||||
return dict(index)
|
||||
|
||||
# ---------------------------------------------------------------- 打分与分配
|
||||
|
||||
@staticmethod
|
||||
def _score(candidate: dict, file_name: str, hint: str | None, compact: str) -> int:
|
||||
score = 0
|
||||
episode_name = candidate["name"]
|
||||
if compact and compact in re.sub(r"[-.\s]", "", episode_name):
|
||||
score += 6 # TMDB 集名里直接写了这个日期
|
||||
file_special = bool(_SPECIAL_WORDS.search(file_name))
|
||||
ep_special = bool(_EP_NAME_SPECIAL.search(episode_name))
|
||||
if file_special and ep_special:
|
||||
score += 3
|
||||
elif ep_special and not file_special:
|
||||
score -= 1
|
||||
if hint:
|
||||
if candidate["season"] == hint:
|
||||
score += 2
|
||||
elif candidate["season"] != "00":
|
||||
score -= 2
|
||||
if hint == "00" and candidate["season"] == "00":
|
||||
score += 1
|
||||
return score
|
||||
|
||||
@classmethod
|
||||
def _assign(cls, files: list[Path], candidates: list[dict], hint: str | None) -> tuple[list, list]:
|
||||
"""一对一贪心分配。返回 (已分配 [(file, cand)], 剩余文件)。"""
|
||||
pairs = []
|
||||
for file in files:
|
||||
date, _ = cls.extract_date(file.name)
|
||||
compact = (date or "").replace("-", "")
|
||||
for candidate in candidates:
|
||||
pairs.append((cls._score(candidate, file.name, hint, compact), file, candidate))
|
||||
pairs.sort(key=lambda item: -item[0])
|
||||
|
||||
used_files, used_eps, result = set(), set(), []
|
||||
for score, file, candidate in pairs:
|
||||
key = (candidate["season"], candidate["ep"])
|
||||
if file in used_files or key in used_eps:
|
||||
continue
|
||||
used_files.add(file)
|
||||
used_eps.add(key)
|
||||
result.append((file, candidate, score))
|
||||
leftover = [f for f in files if f not in used_files]
|
||||
return result, leftover
|
||||
|
||||
# ---------------------------------------------------------------- 主流程
|
||||
|
||||
@classmethod
|
||||
def plan(cls, folder: Path, show_id: int, show_name: str, season_years: dict) -> dict:
|
||||
index = cls.build_index(show_id)
|
||||
videos = [p for p in sorted(folder.rglob("*"))
|
||||
if p.is_file() and p.suffix.lower() in cls.VIDEO_EXTS
|
||||
and ".qkdownloading" not in p.name]
|
||||
|
||||
# 按日期分组;无日期的先放着
|
||||
groups: dict[str, list[Path]] = defaultdict(list)
|
||||
undated: list[Path] = []
|
||||
for file in videos:
|
||||
date, complete = cls.extract_date(file.name)
|
||||
if date and not complete:
|
||||
hint = cls.season_hint(file.relative_to(folder)) or cls.season_hint(folder)
|
||||
year = season_years.get(hint or "", "")
|
||||
if year:
|
||||
date = f"{year}-{date[5:]}"
|
||||
else:
|
||||
undated.append(file)
|
||||
continue
|
||||
if not date:
|
||||
undated.append(file)
|
||||
continue
|
||||
groups[date].append(file)
|
||||
|
||||
plan = {"show_id": show_id, "show": show_name, "folder": folder,
|
||||
"renames": [], "extras": [], "deletes": [], "undated": undated}
|
||||
|
||||
for date, files in sorted(groups.items()):
|
||||
candidates = index.get(date) or []
|
||||
if not candidates:
|
||||
plan["extras"].extend(files)
|
||||
continue
|
||||
|
||||
hint = cls.season_hint(files[0].relative_to(folder)) or cls.season_hint(folder)
|
||||
|
||||
# 文件数多于候选数 → 同一天多份,按码率取前 N 个参与分配,
|
||||
# 其余:同期数的低码率版本删除,无法归期的进 extras(绝不静默丢弃)
|
||||
if len(files) > len(candidates):
|
||||
ranked = sorted(files, key=cls._quality, reverse=True)
|
||||
keep, surplus = ranked[:len(candidates)], ranked[len(candidates):]
|
||||
assigned, _ = cls._assign(keep, candidates, hint)
|
||||
kept_sigs = {cls._signature(f.name) for f in keep}
|
||||
for file in surplus:
|
||||
# 只有「期数 + 类型关键词」完全相同才算同一集的重复;
|
||||
# 加更 / 超前探班 / 正片 是不同内容,绝不能当重复删掉。
|
||||
if cls._signature(file.name) in kept_sigs:
|
||||
plan["deletes"].append((file, "同集高码率已保留,此为重复版本"))
|
||||
else:
|
||||
plan["extras"].append(file)
|
||||
else:
|
||||
assigned, leftover = cls._assign(files, candidates, hint)
|
||||
plan["extras"].extend(leftover)
|
||||
|
||||
for file, candidate, _score in assigned:
|
||||
plan["renames"].append((file, candidate))
|
||||
|
||||
# 无日期的一律进 extras(无法定位)
|
||||
plan["extras"].extend(plan.pop("undated"))
|
||||
return plan
|
||||
|
||||
@staticmethod
|
||||
def _quality(path: Path) -> tuple:
|
||||
tags = MediaInfoService.get_scene_tags(path)
|
||||
order = {"2160p": 4, "1440p": 3, "1080p": 2, "720p": 1}
|
||||
return (order.get(tags.get("res"), 0), path.stat().st_size)
|
||||
|
||||
@staticmethod
|
||||
def _period_of(name: str) -> str | None:
|
||||
match = re.search(r"第\s*(\d+)\s*期", name)
|
||||
return match.group(1) if match else None
|
||||
|
||||
_TYPE_WORDS = re.compile(r"加更|会员|特别|特辑|企划|花絮|彩蛋|先导|前瞻|精编|回顾|纯享|未播|超前|探班")
|
||||
|
||||
@classmethod
|
||||
def _signature(cls, name: str) -> tuple:
|
||||
"""同一集的指纹:期数 + 类型关键词。不同指纹 = 不同内容。"""
|
||||
return (cls._period_of(name), tuple(sorted(set(cls._TYPE_WORDS.findall(name)))))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 预览与执行
|
||||
|
||||
@staticmethod
|
||||
def _target_name(file: Path, candidate: dict, media_title: str, season_years: dict) -> str:
|
||||
tags = MediaInfoService.get_scene_tags(file)
|
||||
tech = f"{tags['res']}.WEB-DL.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||
season = candidate["season"]
|
||||
year = season_years.get(season) or ""
|
||||
ep_name = StringUtil.sanitize_title(candidate["name"])[:40].strip(".")
|
||||
parts = [media_title, f"S{season}E{candidate['ep']:02d}"]
|
||||
if year:
|
||||
parts.append(str(year))
|
||||
parts.append(tech)
|
||||
if ep_name:
|
||||
parts.append(ep_name)
|
||||
return ".".join(parts) + file.suffix.lower()
|
||||
|
||||
@classmethod
|
||||
def preview(cls, plan: dict, season_years: dict, media_title: str) -> None:
|
||||
log.info("=" * 60)
|
||||
log.info(f"📺 综艺整理:{plan['show']}(tv/{plan['show_id']})")
|
||||
log.info(f" 改名 {len(plan['renames'])} | 进 extras {len(plan['extras'])} | 删除 {len(plan['deletes'])}")
|
||||
for file, candidate in plan["renames"][:8]:
|
||||
target = cls._target_name(file, candidate, media_title, season_years)
|
||||
log.info(f" [改名] {file.name[:46]}")
|
||||
log.info(f" → {target[:80]}")
|
||||
if len(plan["renames"]) > 8:
|
||||
log.info(f" …… 其余 {len(plan['renames']) - 8} 个改名略")
|
||||
for file in plan["extras"][:5]:
|
||||
log.info(f" [extras] {file.name[:60]}")
|
||||
for file, reason in plan["deletes"][:5]:
|
||||
log.info(f" [删除] {file.name[:60]} ← {reason}")
|
||||
log.info("=" * 60)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, plan: dict, season_years: dict, media_title: str) -> dict:
|
||||
"""执行改名 / 移入 extras / 删除。返回统计。"""
|
||||
folder: Path = plan["folder"]
|
||||
extras_dir = folder / "extras"
|
||||
stats = {"renamed": 0, "extras": 0, "deleted": 0, "skipped": 0}
|
||||
|
||||
for file, candidate in plan["renames"]:
|
||||
target = file.with_name(cls._target_name(file, candidate, media_title, season_years))
|
||||
if target.exists():
|
||||
log.warning(f"⚠️ 目标已存在,跳过: {target.name}")
|
||||
stats["skipped"] += 1
|
||||
continue
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
file.rename(target)
|
||||
log.info(f"✅ 改名: {file.name} → {target.name}")
|
||||
stats["renamed"] += 1
|
||||
|
||||
for file in plan["extras"]:
|
||||
extras_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = extras_dir / file.name
|
||||
if target.exists():
|
||||
log.warning(f"⚠️ extras 里已有同名文件,跳过: {file.name}")
|
||||
stats["skipped"] += 1
|
||||
continue
|
||||
file.rename(target)
|
||||
log.info(f"📦 移入 extras: {file.name}")
|
||||
stats["extras"] += 1
|
||||
|
||||
for file, reason in plan["deletes"]:
|
||||
try:
|
||||
file.unlink()
|
||||
log.info(f"🗑 删除: {file.name}({reason})")
|
||||
stats["deleted"] += 1
|
||||
except OSError as exc:
|
||||
log.warning(f"⚠️ 删除失败 {file.name}: {exc}")
|
||||
stats["skipped"] += 1
|
||||
return stats
|
||||
Reference in New Issue
Block a user