Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(library): 补齐馆藏目录分类与推广附件复核

longmeidaoe5995eb41fb1
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 9300e2222..a537732f1 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -197,9 +197,9 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/
每条移动先复验真实目录,部分失败立即恢复本条,账本事务失败恢复本批。
不新增依赖;Python 标准库的路径操作和 SQLite 已覆盖底层能力,Peach 保留冗余名称、广告和账本一致性判据。
-完整目录分类归位使用 `scripts/organize_library_dirs.py`,复用 `organize._rename`、目录折叠入口、番号解析器、实体分类与进程锁。默认冻结计划,`--apply --backup` 才执行;`--batch` 分开保存计划与回执,失败可恢复。同目录已确认作品与缺厂牌配套图作为整包处理;未知视频、冲突身份和覆盖目标均保留。目录名的发行站、画质和分片标记复用 `release_code_from_filename`;一本道的日期式分隔符匹配复用其官网作品号解析,不跨片商合并日期编号。路径同步覆盖资产与已登记字幕,不填图片身份字段。
+完整目录分类归位使用 `scripts/organize_library_dirs.py`,复用 `organize._rename`、目录折叠入口、番号解析器、实体分类与进程锁。默认冻结计划,`--apply --backup` 才执行;`--batch` 分开保存计划与回执,失败可恢复。`--stage flatten` 自行生成折叠复核 CSV。同目录已确认作品与缺厂牌配套图作为整包处理;混合目录只移动已知文件组及配对字幕,物理文件去重,未知视频、冲突身份和覆盖目标均保留。目录名的发行站、画质和分片标记复用 `release_code_from_filename`;一本道的日期式分隔符匹配复用其官网作品号解析,不跨片商合并日期编号。FC2 发行目录可使用 `FC-` 简写并附带标题;缺番号的 `@fc编号_分片` 同时核对父目录编号与厂牌,目录编号不补写账本。韩国 MIB 按厂牌归置。已有唯一创作者关系但细分类未确认时归入通用「创作者」目录,不提升身份候选。路径同步覆盖资产与已登记字幕,不补写真相字段。
-推广网页资源目录中的横幅、标志和导航图片由 `web_batch._attachment_junk_reason` 进入复核队列。判据同时要求 `_files`、网址推广套话、域名、导航元素文件名和体积上限;继承的作品番号不豁免网页导航图片,作品图片、字幕、NFO 与普通 `_files` 目录保留。永久删除仍走 `trash_junk.py --purge --review-csv` 和 `purge_assets`。
+推广网页资源目录中的横幅、标志和导航图片由 `web_batch._attachment_junk_reason` 进入复核队列。判据同时要求 `_files`、网址推广套话、域名、导航元素文件名和体积上限;继承的作品番号不豁免网页导航图片,作品图片、字幕、NFO 与普通 `_files` 目录保留。`1024核工厂.rar` 经嵌套目录清单核验仅含安装程序,精确名称且不超过 64 KiB 的附件进入复核,不泛化为所有压缩包。永久删除仍走 `trash_junk.py --purge --review-csv` 和 `purge_assets`。
保留自研不是永久豁免:约束改变或候选实现更新时重新跑 POC,不因本表结论跳过外部检索。
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 36cc31854..902e26d2d 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -21,13 +21,13 @@
- 访问密码未开,局域网匿名可读;可选密码首启可跳过,配置页可改可关,登录可记住设备。
- macOS 是 reader,代码与 `peach-data` 在内置盘;`peach.local` 经 8900/8443 和 pf 提供 80/443,GET 正常、写入回 409。
- 两端各用本机 CA,私钥与凭据不跨机;代码走 Git、账本单写者复制、图片走 Syncthing;本机坐标见 `<数据根>/config.toml`。
-- Windows ledger `0045`(2026-10-07);`asset_subtitle` 195 行(孤立 19),175 部带字幕轨,`asset` 80,202 行。
+- Windows ledger `0045`;字幕 195 行(孤立 19),175 部带字幕轨;10-07 删除确认垃圾 14 个,资产 80,188 行。
- Mac ledger 经授权从共享副本拉取,恢复 `in-sync`;`sources` 在内置盘,`archive`、`tools` 可指向外置盘。
- Windows doctor、诊断页通过 CA 核验;本地目录缺失,115/PikPak 可读取;密码未开、历史失败为警告。
- 本机 Python 3.14;`requires-python` 下限 3.12,CI 同测 3.12 与 3.14;Windows FFmpeg/ffprobe 在 `peach-data/tools/ffmpeg`,macOS 走 PATH。
- amane 桥(ADR-0048)代码在 `tools/amane-bridge/`,venv 在 `peach-data/tools/amane-bridge/.venv`,四类番号链都经它问。
- 发行名 `peach`、目录名 `peach-app`。macOS 先按序做完待办「待执行的操作」第 26 条再重启菜单栏:无口令的 `peach serve --host 0.0.0.0` 会拒绝启动。
-- 扫描与采集显示项目与等待时长;无进展 120 秒预警,单项外部动作(资料 90 秒、封面 240 秒)超时跳过可重试;问题在 `state/library-processing-<job_id>.issues.jsonl`。
+- 扫描与采集 120 秒无进展预警;资料 90 秒、封面 240 秒超时可重试;问题见 `state/library-processing-<job_id>.issues.jsonl`。
- 口味、复核、关注等聚合按账本版本号与文件版本缓存;补女优资料后继每轮存量至多 16 条。
- 实体种子(ADR-0075)由扫描结算的 `seed-import` 后继导入,只填空、换旧种子行;不一致与重复身份在 `generated/seed-landing.csv`。
- 推送发现开:本地 watch 加 CloudDrive 云端前缀 `/115open→B:`、`/Pikpak→A:`;关注每 60 分钟轮询;自动更新关闭。
@@ -36,4 +36,4 @@
## 批处理进度
-账本与产物的现算数字由 hook 写进 `peach-data/state/job-status.md`(不进 Git),手动重算 `python scripts/job_status.py`。
+批处理现状见 `peach-data/state/job-status.md`;目录与垃圾复核见 `generated/library-organize/`,未确认归属保留原位。
diff --git a/scripts/organize_library_dirs.py b/scripts/organize_library_dirs.py
index bf8df4c5f..85a083ee0 100644
--- a/scripts/organize_library_dirs.py
+++ b/scripts/organize_library_dirs.py
@@ -1,7 +1,6 @@
"""馆藏目录分类:冻结整包计划、同盘移动、逐目录回执与失败恢复。"""
from __future__ import annotations
import argparse
-import csv
import hashlib
import importlib.util
import json
@@ -11,6 +10,7 @@ import sys
import tempfile
import time
from collections import Counter, defaultdict
+from contextlib import closing
from pathlib import Path, PureWindowsPath
PROJECT = Path(__file__).resolve().parent.parent
@@ -35,7 +35,7 @@ _spec = importlib.util.spec_from_file_location('directory_flatten', Path(__file_
flatten = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(flatten)
FIELDS = ('id', 'path', 'name', 'medium', 'disposal', 'code', 'studio', 'creator', 'mutation_revision')
-GENERIC = {'创作者', '网黄博主', '卖家', '动画作者', '日本', '西方', '欧美', '番号',
+GENERIC = {'创作者', '网黄博主', '卖家', '动画作者', '日本', '韩国', '西方', '欧美', '番号',
'MVP', 'xxr', 'kkg', '云下载', 'Pack From Shared', 'My Pack', '_未知厂牌', 'FC2-PPV', 'FC2'}
def save(path, payload):
@@ -55,7 +55,9 @@ def beneath(path, root):
def rewrite(path, source, target):
return str(PureWindowsPath(target, *PureWindowsPath(path).parts[len(PureWindowsPath(source).parts):]))
-def snapshots(db, source):
+def snapshots(db, source, ids=None):
+ if ids is not None:
+ return [signature(r) for r in db.execute('SELECT '+','.join(FIELDS)+' FROM asset WHERE id IN (' + ','.join('?' for _ in ids) + ') ORDER BY id', ids)]
prefix = str(source).rstrip('\\') + '\\'
escaped = prefix.replace('!', '!!').replace('%', '!%').replace('_', '!_') + '%'
return [signature(r) for r in db.execute('SELECT '+','.join(FIELDS)+' FROM asset WHERE path LIKE ? ESCAPE ? ORDER BY id', (escaped, '!'))]
@@ -77,13 +79,15 @@ def operation(kind, source, target, rows, reason):
key = hashlib.sha256((kind + '\0' + source + '\0' + target).encode()).hexdigest()[:20]
return dict(key=key, kind=kind, source=source, target=target, rows=rows, reason=reason)
-def entity_guard(db, source):
+def entity_guard(db, source, ids=None):
prefix = str(source).rstrip('\\') + '\\'
escaped = prefix.replace('!', '!!').replace('%', '!%').replace('_', '!_') + '%'
- entities = [dict(r) for r in db.execute("SELECT DISTINCT ae.asset_id,ae.role,e.id,e.canonical_name,e.region FROM asset a JOIN asset_entity ae ON ae.asset_id=a.id JOIN entity e ON e.id=ae.entity_id WHERE a.path LIKE ? ESCAPE '!' AND e.kind IN ('creator','studio') ORDER BY ae.asset_id,e.id,ae.role", (escaped,))]
- ids = {r['id'] for r in entities}
- facts = [dict(r) for r in db.execute('SELECT entity_id,facet,value,status,source FROM entity_classification ORDER BY entity_id,facet,value,status,source') if r['entity_id'] in ids]
- regions = [dict(r) for r in db.execute("SELECT id,region FROM asset WHERE path LIKE ? ESCAPE '!' ORDER BY id", (escaped,))]
+ where = "a.path LIKE ? ESCAPE '!'" if ids is None else 'a.id IN (' + ','.join('?' for _ in ids) + ')'
+ params = (escaped,) if ids is None else ids
+ entities = [dict(r) for r in db.execute("SELECT DISTINCT ae.asset_id,ae.role,e.id,e.canonical_name,e.region FROM asset a JOIN asset_entity ae ON ae.asset_id=a.id JOIN entity e ON e.id=ae.entity_id WHERE " + where + " AND e.kind IN ('creator','studio') ORDER BY ae.asset_id,e.id,ae.role", params)]
+ eids = {r['id'] for r in entities}
+ facts = [dict(r) for r in db.execute('SELECT entity_id,facet,value,status,source FROM entity_classification ORDER BY entity_id,facet,value,status,source') if r['entity_id'] in eids]
+ regions = [dict(r) for r in db.execute('SELECT a.id,a.region FROM asset a WHERE ' + where + ' ORDER BY a.id', params)]
return dict(entities=entities, facts=facts, regions=regions)
def entity_guard_index(db):
@@ -102,30 +106,55 @@ def indexed_guard(rows, regions, index):
return dict(entities=linked, facts=[entry for eid in identities for entry in facts.get(eid, [])],
regions=[dict(id=row['id'], region=regions[row['id']]) for row in rows])
+def release_code(row):
+ """已有编号优先;FC 简写分片同时核对文件与父目录编号。"""
+ code = normalise_code_key(row['code'])
+ if code:
+ return code
+ studio = re.sub(r'[-_ ]', '', row['studio'] or '').upper()
+ if studio not in {'', 'FC2', 'FC2PPV'}:
+ return ''
+ explicit = re.match(r'^@?FC2(?:[-_ ]?PPV)?[-_ ]*(\d{5,})(?!\d)', row['name'], re.I)
+ if explicit:
+ return normalise_code_key('FC2-' + explicit.group(1))
+ short = re.match(r'^@?FC[-_ ]*(\d{5,})(?=[_.-]|$)', row['name'], re.I)
+ parent = re.match(r'^FC(?:2)?(?:[-_ ]?PPV)?[-_ ]*(\d{5,})(?!\d)',
+ PureWindowsPath(row.get('path', '')).parent.name, re.I)
+ if short and parent and short.group(1) == parent.group(1):
+ return normalise_code_key('FC2-' + short.group(1))
+ return ''
+
def label(row, creators, categories, unverified):
if row['disposal'] is not None or row['medium'] not in {'video', 'image', 'audio', 'archive'}:
return None
- code = normalise_code_key(row['code'])
+ code = release_code(row)
region = row.get('effective_region', '')
+ if row['studio'] == 'MIB' and region in ('', 'kr'):
+ return ('publisher', '韩国', 'MIB')
if is_jav_code(code) and region in ('', 'jp') and not is_korean_mib_code(code):
if code.startswith('FC2'):
return ('release', '日本', 'FC2', code)
if row['studio']:
return ('release', '日本', row['studio'], code)
- return None
owners = creators.get(row['id'], [])
if len(owners) == 1:
entity_id, name = owners[0]
- if entity_id not in unverified and not is_structural_creator(name):
+ if not is_structural_creator(name):
matched = categories.get(entity_id, [])
- if len(matched) == 1:
+ if len(matched) == 1 and entity_id not in unverified:
return ('creator', matched[0], name)
+ if not matched or entity_id in unverified:
+ return ('creator', '创作者', name)
if row['studio'] and region in ('', 'west') and western_release_identity(row['name']):
return ('western', '西方', row['studio'])
return None
def release_directory_matches(name, owner):
"""整包目录可含发行站、画质与分片标记;日期编号保留片商边界。"""
+ if owner[3].startswith('FC2-PPV-'):
+ head = re.match(r'^FC(?:2)?(?:[-_ ]?PPV)?[-_ ]*(\d{5,})(?!\d)', name, re.I)
+ if head:
+ return normalise_code_key('FC2-' + head.group(1)) == owner[3]
parsed = release_code_from_filename(name)
if not parsed:
return promo_free_key(name) == promo_free_key(owner[3])
@@ -134,11 +163,21 @@ def release_directory_matches(name, owner):
return (owner[2] == ONEPONDO_STUDIO and bool(movie_id(parsed))
and movie_id(parsed) == movie_id(owner[3]))
-def compatible_sidecar(row, owner, creators):
+def compatible_sidecar(row, owner, creators, allowed_creators=()):
"""配套图只随确定的整包移动,不给图片补身份字段。"""
if row['medium'] != 'image' or row['disposal'] is not None:
return False
- if row.get('creator') or creators.get(row['id']):
+ if owner[0] == 'creator':
+ return (not row.get('code') and not row.get('studio')
+ and (not row.get('creator') or row['creator'] == owner[2])
+ and all(name == owner[2] for _, name in creators.get(row['id'], [])))
+ if owner[0] == 'publisher':
+ return (row.get('effective_region', '') in ('', 'kr')
+ and (not row.get('studio') or row['studio'] == owner[2])
+ and not row.get('creator') and not creators.get(row['id'])
+ and (not row.get('code') or is_korean_mib_code(row['code'])))
+ if ((row.get('creator') and row['creator'] not in allowed_creators)
+ or any(name not in allowed_creators for _, name in creators.get(row['id'], []))):
return False
if owner[0] != 'release' or row.get('effective_region', '') not in ('', 'jp'):
return False
@@ -149,127 +188,221 @@ def compatible_sidecar(row, owner, creators):
owner[2] == ONEPONDO_STUDIO and bool(movie_id(code))
and movie_id(code) == movie_id(owner[3]))
+def classification_inputs(db):
+ predicates = category_predicates(connection=db)
+ categories = {}
+ names = {'blogger': '网黄博主', 'seller': '卖家', 'animation': '动画作者'}
+ for entity_id, name, *matched in db.execute('SELECT e.id,e.canonical_name,' + ','.join(
+ '(' + predicates[k] + ')' for k in names) + " FROM entity e WHERE e.kind='creator'"):
+ categories[entity_id] = [name for name, value in zip(names.values(), matched) if value]
+ unverified = {r[0] for r in db.execute("SELECT entity_id FROM entity_classification WHERE facet='identity' AND value='unknown' AND status='candidate'")}
+ creators = defaultdict(list)
+ for asset_id, entity_id, name in db.execute("SELECT DISTINCT ae.asset_id,e.id,e.canonical_name FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id WHERE e.kind='creator' AND ae.role='creator'"):
+ creators[asset_id].append((entity_id, name))
+ return creators, categories, unverified
+
+def catalog_nodes(all_rows, roots, creators, categories, unverified, skipped):
+ nodes = {}
+ for row in all_rows:
+ location, index, _ = resolve_root(row['path'], roots)
+ if location != row['location'] or index < 0:
+ skipped.append(dict(source=row['path'], reason='不在来源根内'))
+ continue
+ root = roots[location][index]
+ owner = label(row, creators, categories, unverified)
+ row['_owner'], row['_root'] = owner, root
+ parent = PureWindowsPath(row['path']).parent
+ while str(parent).casefold() != str(PureWindowsPath(root)).casefold():
+ key = str(parent)
+ node = nodes.setdefault(key, dict(rows=[], labels=set(), unknown=[], root=root))
+ node['rows'].append(signature(row))
+ if owner:
+ node['labels'].add(owner)
+ elif row['disposal'] is None and row['medium'] in {'video', 'image', 'audio', 'archive'}:
+ node['unknown'].append(row)
+ if parent.parent == parent:
+ raise ValueError('目录不在声明来源根内')
+ parent = parent.parent
+ return nodes
+
+def directory_owner(source, node, rows_by_id, creators):
+ path = PureWindowsPath(source)
+ primary = [rows_by_id[r['id']] for r in node['rows']
+ if r['medium'] in {'video', 'audio', 'archive'} and r['disposal'] is None]
+ labels = {r['_owner'] for r in primary if r['_owner']} or node['labels']
+ if path.name in GENERIC or len(labels) != 1:
+ return None
+ owner = next(iter(labels))
+ allowed_creators = {name for r in primary for _, name in creators.get(r['id'], [])}
+ allowed_creators.update(r['creator'] for r in primary if r.get('creator'))
+ conflicting = [rows_by_id[r['id']] for r in node['rows']
+ if rows_by_id[r['id']]['_owner'] != owner and r['disposal'] is None
+ and r['medium'] in {'video', 'image', 'audio', 'archive'}]
+ if any(not compatible_sidecar(row, owner, creators, allowed_creators) for row in conflicting):
+ return None
+ for row in node['rows']:
+ if rows_by_id[row['id']]['_owner'] is None:
+ rows_by_id[row['id']]['_owner'] = owner
+ return owner
+
+def owner_directory(root, path, owner):
+ parts = owner[1:]
+ if owner[0] != 'release':
+ category, canonical = owner[1:]
+ relative = path.relative_to(PureWindowsPath(root)).parts
+ tail = list(relative)
+ while tail and tail[0] in GENERIC:
+ tail.pop(0)
+ if tail and promo_free_key(tail[0]) == promo_free_key(canonical):
+ tail.pop(0)
+ if tail and promo_free_key(tail[-1]) == promo_free_key(canonical):
+ tail.pop()
+ parts = (category, canonical, *tail)
+ return str(PureWindowsPath(root, *(sanitise_component(part) for part in parts)))
+
+def directory_target(source, node, owner, rows_by_id, skipped):
+ path = PureWindowsPath(source)
+ if owner[0] == 'release':
+ if not release_directory_matches(path.name, owner):
+ return None
+ for row in node['rows']:
+ rows_by_id[row['id']]['_owner'] = owner
+ target = owner_directory(node['root'], path, owner)
+ if target.casefold() == source.casefold():
+ return None
+ if beneath(target, source) or beneath(source, target):
+ skipped.append(dict(source=source, reason='目标与来源相互包含'))
+ return None
+ if any(len(rewrite(r['path'], source, target).encode('utf-16-le')) // 2 > MAX_PATH for r in node['rows']):
+ skipped.append(dict(source=source, reason='路径过长'))
+ return None
+ return target
+
+def directory_operations(nodes, rows_by_id, creators, skipped):
+ operations, selected = [], set()
+ for source, node in sorted(nodes.items(), key=lambda pair: (len(PureWindowsPath(pair[0]).parts), pair[0])):
+ owner = directory_owner(source, node, rows_by_id, creators)
+ if owner is None:
+ continue
+ target = directory_target(source, node, owner, rows_by_id, skipped)
+ if target is None:
+ continue
+ path = PureWindowsPath(source)
+ if any(str(parent).casefold() in selected for parent in (path, *path.parents)):
+ continue
+ selected.add(source.casefold())
+ operations.append(operation('rename', source, target, sorted(node['rows'], key=lambda r:r['id']),
+ '账本规范归属:' + '/'.join(owner[1:])))
+ return operations
+
+def file_operations(db, all_rows, rows_by_path, covered):
+ operations = []
+ file_groups = defaultdict(list)
+ for row in all_rows:
+ owner, root = row.get('_owner'), row.get('_root')
+ if row['id'] in covered or not root or not owner or row['disposal'] is not None:
+ continue
+ parent = str(PureWindowsPath(row['path']).parent)
+ target = owner_directory(root, PureWindowsPath(parent), owner)
+ if beneath(row['path'], target):
+ continue
+ if len(str(PureWindowsPath(target, PureWindowsPath(row['path']).name)).encode('utf-16-le')) // 2 > MAX_PATH:
+ continue
+ file_groups[(parent, target, owner)].append(signature(row))
+ for (source, target, owner), rows in sorted(file_groups.items()):
+ aids = {r['id'] for r in rows}
+ for subtitle in subtitles(db, source):
+ extra = rows_by_path.get(subtitle['path'].casefold())
+ if subtitle['asset_id'] in aids and extra and extra['id'] not in aids:
+ rows.append(signature(extra))
+ aids.add(extra['id'])
+ rows.sort(key=lambda r: r['id'])
+ operations.append(operation('files', source, target, rows,
+ '混合目录内按已知归属分组:' + '/'.join(owner[1:])))
+ covered.update(r['id'] for r in rows)
+ return operations
+
+def pending_paths(all_rows, mounts, covered):
+ skipped = []
+ for row in all_rows:
+ if row['disposal'] is None and row['id'] not in covered:
+ owner, root = row.get('_owner'), row.get('_root')
+ if root and not mounts[root]:
+ reason = '来源离线,保留原位置'
+ elif owner and beneath(row['path'], str(PureWindowsPath(root, *(sanitise_component(p) for p in (owner[1:] if owner[0]=='release' else owner[1:3]))))):
+ reason = '已在规范分类目录'
+ elif row['medium'] == 'other':
+ reason = '附带文件缺少明确作品目录,保留原位置'
+ elif owner:
+ reason = '归属明确,但目录混合、命名不足或路径过长,保留原位置'
+ else:
+ reason = '归属未确认,保留原位置'
+ skipped.append(dict(source=row['path'], reason=reason))
+ return skipped
+
+def attach_plan_guards(db, operations, stage, all_rows):
+ if stage == 'rehome':
+ guard_index = entity_guard_index(db)
+ regions = {row['id']:row['region'] for row in all_rows}
+ ids = [row['id'] for op in operations for row in op['rows']]
+ if len(ids) != len(set(ids)):
+ raise ValueError('目录计划重复覆盖资产,请复核字幕或整包归属')
+ for op in operations:
+ op['subtitles'] = subtitles(db, op['source'])
+ if op['kind'] == 'files':
+ ids = {row['id'] for row in op['rows']}
+ op['subtitles'] = [row for row in op['subtitles'] if row['asset_id'] in ids]
+ if stage == 'rehome':
+ op['entities'] = indexed_guard(op['rows'], regions, guard_index)
+
+def flatten_operations(db, stem):
+ operations, skipped = [], []
+ rows = flatten.plan_operations(db)
+ for row in rows:
+ row['verified'] = flatten.verify(row, translate_ledger_path)
+ if row['verified'] == 'ok':
+ operations.append(operation(row['kind'],row['ledger_dir'],row['target_dir'],
+ snapshots(db,row['ledger_dir']),'冗余目录层或广告标记'))
+ else:
+ skipped.append(dict(source=row['ledger_dir'],reason=row['verified']))
+ write_rows(OUT/f'{stem}-plan.csv',flatten.PLAN_FIELDS,rows)
+ return operations, skipped
+
+def write_plan(payload, stem):
+ operations, skipped = payload['operations'], payload['skipped']
+ save(OUT/f'{stem}-manifest.json',payload)
+ write_rows(OUT/f'{stem}-directories.csv',['key','kind','source','target','assets','reason'],
+ [dict(key=op['key'],kind=op['kind'],source=op['source'],target=op['target'],assets=len(op['rows']),reason=op['reason']) for op in operations])
+ write_rows(OUT/f'{stem}-pending.csv',['source','reason'],skipped)
+ print(json.dumps(dict(stage=payload['stage'],directories=len(operations),assets=len({r['id'] for op in operations for r in op['rows']}),pending=len(skipped)),ensure_ascii=False))
+
def build_plan(stage, batch=None):
stem = stage + ('-' + batch if batch else '')
- receipt_path = OUT / f'{stem}-receipt.json'
- if receipt_path.exists() and json.loads(receipt_path.read_text(encoding='utf-8')).get('entries'):
+ receipt = OUT/f'{stem}-receipt.json'
+ if receipt.exists() and json.loads(receipt.read_text(encoding='utf-8')).get('entries'):
raise ValueError('已有执行回执,请使用新的批次编号')
roots = location_roots()
- with open_readonly(DATABASE_PATH) as db:
+ all_rows = []
+ with closing(open_readonly(DATABASE_PATH)) as db:
db.execute('BEGIN')
- operations, skipped = [], []
if stage == 'flatten':
- with (OUT / f'{stem}-plan.csv').open(encoding='utf-8-sig', newline='') as handle:
- for row in csv.DictReader(handle):
- if row['verified'] == 'ok':
- operations.append(operation(row['kind'], row['ledger_dir'], row['target_dir'],
- snapshots(db, row['ledger_dir']), '冗余目录层或广告标记'))
- else:
- skipped.append(dict(source=row['ledger_dir'], reason=row['verified']))
+ operations, skipped = flatten_operations(db,stem)
else:
- predicates = category_predicates(connection=db)
- categories = {}
- names = {'blogger': '网黄博主', 'seller': '卖家', 'animation': '动画作者'}
- for entity_id, name, *matched in db.execute('SELECT e.id,e.canonical_name,' + ','.join(
- '(' + predicates[k] + ')' for k in names) + " FROM entity e WHERE e.kind='creator'"):
- categories[entity_id] = [name for name, value in zip(names.values(), matched) if value]
- unverified = {r[0] for r in db.execute("SELECT entity_id FROM entity_classification WHERE facet='identity' AND value='unknown' AND status='candidate'")}
- creators = defaultdict(list)
- for asset_id, entity_id, name in db.execute("SELECT DISTINCT ae.asset_id,e.id,e.canonical_name FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id WHERE e.kind='creator' AND ae.role='creator'"):
- creators[asset_id].append((entity_id, name))
- nodes = {}
- db.create_function('infer_region', 2, infer_region, deterministic=True)
+ creators, categories, unverified = classification_inputs(db)
+ db.create_function('infer_region',2,infer_region,deterministic=True)
all_rows = [dict(r) for r in db.execute("SELECT a.*,"+effective_region_sql()+" AS effective_region FROM asset a WHERE a.location IN ('115','pikpak','local') AND a.path IS NOT NULL AND trim(a.path)<>'' ORDER BY a.id")]
- rows_by_id = {row['id']: row for row in all_rows}
+ by_id = {row['id']:row for row in all_rows}
+ by_path = {row['path'].casefold():row for row in all_rows}
mounts = {root:root_online(translate_ledger_path(root)) for values in roots.values() for root in values}
- for row in all_rows:
- location, index, _ = resolve_root(row['path'], roots)
- if location != row['location'] or index < 0:
- skipped.append(dict(source=row['path'], reason='不在来源根内'))
- continue
- root = roots[location][index]
- owner = label(row, creators, categories, unverified)
- row['_owner'], row['_root'] = owner, root
- parent = PureWindowsPath(row['path']).parent
- while str(parent).casefold() != str(PureWindowsPath(root)).casefold():
- key = str(parent)
- node = nodes.setdefault(key, dict(rows=[], labels=set(), unknown=[], root=root))
- node['rows'].append(signature(row))
- if owner:
- node['labels'].add(owner)
- elif row['disposal'] is None and row['medium'] in {'video', 'image', 'audio', 'archive'}:
- node['unknown'].append(row)
- if parent.parent == parent:
- raise ValueError('目录不在声明来源根内')
- parent = parent.parent
- selected = set()
- for source, node in sorted(nodes.items(), key=lambda pair: (len(PureWindowsPath(pair[0]).parts), pair[0])):
- path = PureWindowsPath(source)
- if path.name in GENERIC or len(node['labels']) != 1:
- continue
- owner = next(iter(node['labels']))
- if any(not compatible_sidecar(row, owner, creators) for row in node['unknown']):
- continue
- if owner[0] == 'release':
- if not release_directory_matches(path.name, owner):
- continue
- for row in node['rows']:
- rows_by_id[row['id']]['_owner'] = owner
- parts = owner[1:]
- else:
- category, canonical = owner[1:]
- relative = path.relative_to(PureWindowsPath(node['root'])).parts
- tail = list(relative)
- while tail and tail[0] in GENERIC:
- tail.pop(0)
- if tail and promo_free_key(tail[0]) == promo_free_key(canonical):
- tail.pop(0)
- if tail and promo_free_key(tail[-1]) == promo_free_key(canonical):
- tail.pop()
- parts = (category, canonical, *tail)
- target = str(PureWindowsPath(node['root'], *(sanitise_component(part) for part in parts)))
- if target.casefold() == source.casefold():
- continue
- if beneath(target, source) or beneath(source, target):
- skipped.append(dict(source=source, reason='目标与来源相互包含'))
- continue
- if any(len(rewrite(r['path'], source, target).encode('utf-16-le')) // 2 > MAX_PATH for r in node['rows']):
- skipped.append(dict(source=source, reason='路径过长'))
- continue
- if any(str(parent).casefold() in selected for parent in (path, *path.parents)):
- continue
- selected.add(source.casefold())
- operations.append(operation('rename', source, target, sorted(node['rows'], key=lambda r: r['id']),
- '账本规范归属:' + '/'.join(owner[1:])))
+ skipped = []
+ nodes = catalog_nodes(all_rows,roots,creators,categories,unverified,skipped)
+ operations = directory_operations(nodes,by_id,creators,skipped)
covered = {r['id'] for op in operations for r in op['rows']}
- for row in all_rows:
- if row['disposal'] is None and row['id'] not in covered:
- owner, root = row.get('_owner'), row.get('_root')
- if root and not mounts[root]:
- reason = '来源离线,保留原位置'
- elif owner and beneath(row['path'], str(PureWindowsPath(root, *(sanitise_component(p) for p in (owner[1:] if owner[0]=='release' else owner[1:3]))))):
- reason = '已在规范分类目录'
- elif row['medium'] == 'other':
- reason = '附带文件缺少明确作品目录,保留原位置'
- elif owner:
- reason = '归属明确,但目录混合、命名不足或路径过长,保留原位置'
- else:
- reason = '归属未确认,保留原位置'
- skipped.append(dict(source=row['path'], reason=reason))
- if stage == 'rehome':
- guard_index = entity_guard_index(db)
- regions = {row['id']: row['region'] for row in all_rows}
- for op in operations:
- op['subtitles'] = subtitles(db, op['source'])
- if stage == 'rehome':
- op['entities'] = indexed_guard(op['rows'], regions, guard_index)
- payload = dict(format=1, stage=stage, roots=roots, operations=operations, skipped=skipped)
- path = OUT / f'{stem}-manifest.json'
- save(path, payload)
- write_rows(OUT / f'{stem}-directories.csv', ['key', 'kind', 'source', 'target', 'assets', 'reason'],
- [dict(key=op['key'], kind=op['kind'], source=op['source'], target=op['target'], assets=len(op['rows']), reason=op['reason']) for op in operations])
- write_rows(OUT / f'{stem}-pending.csv', ['source', 'reason'], skipped)
- print(json.dumps(dict(stage=stage, directories=len(operations), assets=len({r['id'] for op in operations for r in op['rows']}), pending=len(skipped)), ensure_ascii=False))
+ operations.extend(file_operations(db,all_rows,by_path,covered))
+ skipped.extend(pending_paths(all_rows,mounts,covered))
+ attach_plan_guards(db,operations,stage,all_rows)
+ payload = dict(format=1,stage=stage,roots=roots,operations=operations,skipped=skipped)
+ write_plan(payload,stem)
def expand(source, target, *, deadline, count=None):
count = [0] if count is None else count
@@ -398,165 +531,212 @@ def recover(db, payload, receipt, path):
raise RuntimeError('中断批次的账本已经发生其他变化')
save(path, receipt)
+class OfflineSource(ValueError):
+ pass
+
+def operation_paths(op, roots):
+ exclusive_parent = False
+ source, target = op['source'], op['target']
+ old_location, old_index, _ = resolve_root(source + '\\_', roots)
+ new_location, new_index, _ = resolve_root(target + '\\_', roots)
+ if old_location != new_location or old_index != new_index or old_index < 0:
+ raise ValueError('来源根不一致')
+ root = roots[old_location][old_index]
+ if not beneath(source, root) or not beneath(target, root) or not root_online(translate_ledger_path(root)):
+ raise OfflineSource('来源未挂载或操作越出根目录')
+ if op['kind'] != 'files' and (beneath(target, source) or (beneath(source, target) and op['kind'] != 'collapse')):
+ raise ValueError('来源与目标相互包含')
+ local_source, local_target = translate_ledger_path(source), translate_ledger_path(target)
+ if not local_source.is_dir():
+ raise ValueError('源路径不是目录或未挂载')
+ if local_source.is_symlink() or local_target.is_symlink():
+ raise ValueError('拒绝符号链接目录')
+ if op['kind'] == 'collapse':
+ if PureWindowsPath(source).parent != PureWindowsPath(target):
+ raise ValueError('合并目标不是直接父目录')
+ if flatten.directory_key(PureWindowsPath(source).name) != flatten.directory_key(PureWindowsPath(target).name):
+ raise ValueError('目录名不冗余')
+ exclusive_parent = sorted(p.name for p in local_target.iterdir()) == [local_source.name]
+ return local_source, local_target, root, exclusive_parent
+
+def verify_frozen_operation(db, op, stage):
+ source = op['source']
+ row_ids = [r['id'] for r in op['rows']] if op['kind'] == 'files' else None
+ if snapshots(db, source, row_ids) != op['rows']:
+ raise ValueError('冻结计划已失效:路径或元数据发生变化')
+ current_subtitles = subtitles(db, source)
+ if row_ids is not None:
+ current_subtitles = [r for r in current_subtitles if r['asset_id'] in row_ids]
+ if current_subtitles != op['subtitles']:
+ raise ValueError('冻结计划已失效:字幕路径发生变化')
+ if stage == 'rehome' and entity_guard(db, source, row_ids) != op['entities']:
+ raise ValueError('冻结计划已失效:创作者身份发生变化')
+
+def file_group_moves(op):
+ source, target = op['source'], op['target']
+ physical_pairs = [(r['path'], rewrite(r['path'], source, target))
+ for r in (*op['rows'], *op['subtitles'])]
+ physical_pairs = list(dict.fromkeys(physical_pairs))
+ for old, new in physical_pairs:
+ old, new = translate_ledger_path(old), translate_ledger_path(new)
+ if old.is_symlink() or new.is_symlink() or not old.is_file() or new.exists():
+ raise ValueError('分组文件未取得、符号链接或目标冲突')
+ empty = [source]
+ return physical_pairs, empty
+
+def shared_collapse_moves(local_source, local_target, root, source):
+ temporary = local_source.with_name('.peach-organize-' + hashlib.sha256(source.encode()).hexdigest()[:20])
+ if temporary.exists() or temporary.is_symlink() or not beneath(str(temporary), root):
+ raise ValueError('暂存目录冲突或越出根目录')
+ entries = list(local_source.iterdir())
+ for entry in entries:
+ if entry.is_symlink() or (entry.name.casefold() != local_source.name.casefold()
+ and (local_target / entry.name).exists()):
+ raise ValueError('目标条目冲突或符号链接')
+ shared_stage = dict(original=source, temporary=str(temporary))
+ physical_pairs = [(str(local_source), str(temporary))] + [
+ (str(temporary / p.name), str(local_target / p.name)) for p in entries]
+ empty = [str(temporary)]
+ return physical_pairs, empty, shared_stage
+
+def prepare_moves(op, local_source, local_target, root, exclusive_parent, deadline):
+ source, target = op['source'], op['target']
+ collapse, shared_stage = None, None
+ if op['kind'] == 'files':
+ pairs, empty = file_group_moves(op)
+ elif op['kind'] == 'collapse' and exclusive_parent:
+ pairs, collapse = collapse_moves(source,target)
+ if not beneath(pairs[0][1],root):
+ raise ValueError('临时目录越出根目录')
+ empty = []
+ elif op['kind'] == 'collapse' and any(p.name.casefold()==local_source.name.casefold() for p in local_source.iterdir()):
+ pairs, empty, shared_stage = shared_collapse_moves(local_source,local_target,root,source)
+ else:
+ pairs, empty = expand(local_source,local_target,deadline=min(deadline,time.monotonic()+90))
+ return [(str(PureWindowsPath(a)),str(PureWindowsPath(b))) for a,b in pairs], empty, collapse, shared_stage
+
+def move_files(journal, receipt, receipt_path):
+ for index,(old,new) in enumerate(journal['moves']):
+ organize._rename(old,new)
+ if not translate_ledger_path(new).exists():
+ raise ValueError('移动后目标未取得')
+ if journal['shared_stage'] and index==0:
+ journal['shared_started'] = True
+ save(receipt_path,receipt)
+ journal['status'] = 'filesystem'
+ save(receipt_path,receipt)
+
+def commit_paths(db, op):
+ update_paths(db,op)
+ for table,rows in (('asset',op['rows']),('asset_subtitle',op['subtitles'])):
+ for row in rows:
+ present = db.execute(f'SELECT path FROM {table} WHERE id=?',(row['id'],)).fetchone()
+ if not present or present[0]!=rewrite(row['path'],op['source'],op['target']):
+ raise ValueError('目标账本路径核对失败')
+ db.commit()
+
+def cleanup_empty_paths(paths):
+ for path in sorted(paths,key=lambda p:len(Path(p).parts),reverse=True):
+ try:
+ translate_ledger_path(path).rmdir()
+ except OSError:
+ pass
+
+def execute_operation(db, payload, op, stage, receipt, receipt_path, deadline, retry_failed):
+ journal, committed = None, False
+ try:
+ local_source,local_target,root,exclusive = operation_paths(op,payload['roots'])
+ db.execute('BEGIN IMMEDIATE')
+ verify_frozen_operation(db,op,stage)
+ pairs,empty,collapse,shared_stage = prepare_moves(op,local_source,local_target,root,exclusive,deadline)
+ journal = dict(key=op['key'],status='intent',source=op['source'],target=op['target'],moves=pairs,empty=empty,
+ assets=len(op['rows']),collapse=collapse,shared_stage=shared_stage,retry_failed=retry_failed)
+ receipt['entries'].append(journal)
+ save(receipt_path,receipt)
+ move_files(journal,receipt,receipt_path)
+ commit_paths(db,op)
+ committed = True
+ journal['status'] = 'committed'
+ cleanup_collapse(journal)
+ save(receipt_path,receipt)
+ cleanup_empty_paths(empty)
+ except Exception as error:
+ if committed:
+ raise RuntimeError('账本已提交,回执保存失败;保留文件位置供续跑核对') from error
+ db.rollback()
+ failures = restore_entry(journal) if journal is not None else []
+ if journal is not None:
+ journal['status'] = 'rollback_failed' if failures else 'restored'
+ receipt['failures'].append(dict(key=op['key'],source=op['source'],error=str(error),rollback_failures=failures))
+ save(receipt_path,receipt)
+ if failures:
+ raise RuntimeError('文件恢复未完成,停止本批') from error
+ return error
+ return None
+
+def pending_operations(payload, receipt, retry_failed, skip_collapses, location):
+ done = {r['key'] for r in receipt['entries'] if r['status']=='committed'}
+ failed = set() if retry_failed else {r['key'] for r in receipt['failures']}
+ for op in payload['operations']:
+ if (skip_collapses and op['kind']=='collapse') or op['key'] in done or op['key'] in failed:
+ continue
+ owner,_,_ = resolve_root(op['source'] + '\\_',payload['roots'])
+ if not location or owner==location:
+ yield op,owner
+
+def verify_result(db, assets, subtitle_count, baseline):
+ result = dict(asset_before=assets,asset_after=db.execute('SELECT count(*) FROM asset').fetchone()[0],
+ subtitles_before=subtitle_count,subtitles_after=db.execute('SELECT count(*) FROM asset_subtitle').fetchone()[0],
+ integrity=db.execute('PRAGMA integrity_check').fetchone()[0],existing_foreign_keys=len(baseline),
+ new_foreign_keys=list({tuple(r) for r in db.execute('PRAGMA foreign_key_check')}-baseline))
+ if result['asset_before']!=result['asset_after'] or result['subtitles_before']!=result['subtitles_after'] or result['integrity']!='ok' or result['new_foreign_keys']:
+ raise RuntimeError('目录执行后的账本计数或完整性核验失败')
+ return result
+
def run_apply(stage, backup, limit, seconds, location=None, retry_failed=False, skip_collapses=False, batch=None):
if backup is None:
raise ValueError('--apply 必须同时给 --backup')
stem = stage + ('-' + batch if batch else '')
- payload = json.loads((OUT / f'{stem}-manifest.json').read_text(encoding='utf-8'))
- if payload.get('format') != 1 or payload.get('stage') != stage:
+ payload = json.loads((OUT/f'{stem}-manifest.json').read_text(encoding='utf-8'))
+ if payload.get('format')!=1 or payload.get('stage')!=stage:
raise ValueError('计划格式不受支持,请使用新的批次编号冻结计划')
- receipt_path = OUT / f'{stem}-receipt.json'
- receipt = json.loads(receipt_path.read_text(encoding='utf-8')) if receipt_path.exists() else dict(entries=[], failures=[])
- lock = PidFileLock(OUT / 'directory-job.lock')
+ receipt_path = OUT/f'{stem}-receipt.json'
+ receipt = json.loads(receipt_path.read_text(encoding='utf-8')) if receipt_path.exists() else dict(entries=[],failures=[])
+ lock = PidFileLock(OUT/'directory-job.lock')
lock.acquire()
+ db = None
try:
- sqlite_backup(DATABASE_PATH, backup)
- receipt.setdefault('backups', []).append(str(backup))
- db = sqlite3.connect(DATABASE_PATH, timeout=15)
+ sqlite_backup(DATABASE_PATH,backup)
+ receipt.setdefault('backups',[]).append(str(backup))
+ db = sqlite3.connect(DATABASE_PATH,timeout=15)
db.row_factory = sqlite3.Row
- recover(db, payload, receipt, receipt_path)
+ recover(db,payload,receipt,receipt_path)
baseline = {tuple(r) for r in db.execute('PRAGMA foreign_key_check')}
- before_assets = db.execute('SELECT count(*) FROM asset').fetchone()[0]
- before_subtitles = db.execute('SELECT count(*) FROM asset_subtitle').fetchone()[0]
- done = {r['key'] for r in receipt['entries'] if r['status'] == 'committed'}
- failed = set() if retry_failed else {r['key'] for r in receipt['failures']}
- deadline, checked = time.monotonic() + seconds, 0
- unavailable = set()
- provider_errors = Counter()
- for op in payload['operations']:
- if skip_collapses and op['kind'] == 'collapse':
- continue
- if op['key'] in done or op['key'] in failed:
- continue
- if checked >= limit or time.monotonic() >= deadline:
+ assets = db.execute('SELECT count(*) FROM asset').fetchone()[0]
+ subtitle_count = db.execute('SELECT count(*) FROM asset_subtitle').fetchone()[0]
+ deadline,checked = time.monotonic()+seconds,0
+ unavailable,provider_errors = set(),Counter()
+ for op,owner in pending_operations(payload,receipt,retry_failed,skip_collapses,location):
+ if checked>=limit or time.monotonic()>=deadline:
break
- op_location, _, _ = resolve_root(op['source'] + '\\_', payload['roots'])
- if (location and op_location != location) or op_location in unavailable:
+ if owner in unavailable:
continue
checked += 1
- pairs, journal, committed = [], None, False
- try:
- source, target = op['source'], op['target']
- old_location, old_index, _ = resolve_root(source + '\\_', payload['roots'])
- new_location, new_index, _ = resolve_root(target + '\\_', payload['roots'])
- if old_location != new_location or old_index != new_index or old_index < 0:
- raise ValueError('来源根不一致')
- root = payload['roots'][old_location][old_index]
- if not beneath(source, root) or not beneath(target, root) or not root_online(translate_ledger_path(root)):
- unavailable.add(old_location)
- raise ValueError('来源未挂载或操作越出根目录')
- if beneath(target, source) or (beneath(source, target) and op['kind'] != 'collapse'):
- raise ValueError('来源与目标相互包含')
- local_source, local_target = translate_ledger_path(source), translate_ledger_path(target)
- if not local_source.is_dir():
- raise ValueError('源路径不是目录或未挂载')
- if local_source.is_symlink() or local_target.is_symlink():
- raise ValueError('拒绝符号链接目录')
- if op['kind'] == 'collapse':
- if PureWindowsPath(source).parent != PureWindowsPath(target):
- raise ValueError('合并目标不是直接父目录')
- if flatten.directory_key(PureWindowsPath(source).name) != flatten.directory_key(PureWindowsPath(target).name):
- raise ValueError('目录名不冗余')
- exclusive_parent = sorted(p.name for p in local_target.iterdir()) == [local_source.name]
- db.execute('BEGIN IMMEDIATE')
- if snapshots(db, source) != op['rows']:
- raise ValueError('冻结计划已失效:路径或元数据发生变化')
- if subtitles(db, source) != op['subtitles']:
- raise ValueError('冻结计划已失效:字幕路径发生变化')
- if stage == 'rehome' and entity_guard(db, source) != op['entities']:
- raise ValueError('冻结计划已失效:创作者身份发生变化')
- collapse, shared_stage = None, None
- if op['kind'] == 'collapse' and exclusive_parent:
- physical_pairs, collapse = collapse_moves(source, target)
- if not beneath(physical_pairs[0][1], root):
- raise ValueError('临时目录越出根目录')
- empty = []
- elif op['kind'] == 'collapse' and any(
- p.name.casefold() == local_source.name.casefold() for p in local_source.iterdir()):
- temporary = local_source.with_name('.peach-organize-' + hashlib.sha256(source.encode()).hexdigest()[:20])
- if temporary.exists() or temporary.is_symlink() or not beneath(str(temporary), root):
- raise ValueError('暂存目录冲突或越出根目录')
- entries = list(local_source.iterdir())
- for entry in entries:
- if entry.is_symlink() or (entry.name.casefold() != local_source.name.casefold()
- and (local_target / entry.name).exists()):
- raise ValueError('目标条目冲突或符号链接')
- shared_stage = dict(original=source, temporary=str(temporary))
- physical_pairs = [(str(local_source), str(temporary))] + [
- (str(temporary / p.name), str(local_target / p.name)) for p in entries]
- empty = [str(temporary)]
- else:
- physical_pairs, empty = expand(local_source, local_target, deadline=min(deadline, time.monotonic() + 90))
- pairs = [(str(PureWindowsPath(a)), str(PureWindowsPath(b))) for a, b in physical_pairs]
- journal = dict(key=op['key'], status='intent', source=source, target=target, moves=pairs, empty=empty,
- assets=len(op['rows']), collapse=collapse, shared_stage=shared_stage,
- retry_failed=retry_failed)
- receipt['entries'].append(journal)
- save(receipt_path, receipt)
- for move_index, (old, new) in enumerate(pairs):
- organize._rename(old, new)
- if not translate_ledger_path(new).exists():
- raise ValueError('移动后目标未取得')
- if shared_stage and move_index == 0:
- journal['shared_started'] = True
- save(receipt_path, receipt)
- journal['status'] = 'filesystem'
- save(receipt_path, receipt)
- update_paths(db, op)
- for table, rows in (('asset', op['rows']), ('asset_subtitle', op['subtitles'])):
- for row in rows:
- path = db.execute(f'SELECT path FROM {table} WHERE id=?', (row['id'],)).fetchone()
- if not path or path[0] != rewrite(row['path'], source, target):
- raise ValueError('目标账本路径核对失败')
- db.commit()
- committed = True
- journal['status'] = 'committed'
- cleanup_collapse(journal)
- save(receipt_path, receipt)
- for path in sorted(empty, key=lambda p: len(Path(p).parts), reverse=True):
- try:
- Path(path).rmdir()
- except OSError:
- pass
- except Exception as error:
- if committed:
- raise RuntimeError('账本已提交,回执保存失败;保留文件位置供续跑核对') from error
- db.rollback()
- rollback_failures = restore_entry(journal) if journal is not None else []
- if journal is not None:
- journal['status'] = 'rollback_failed' if rollback_failures else 'restored'
- receipt['failures'].append(dict(key=op['key'], source=op['source'], error=str(error), rollback_failures=rollback_failures))
- if isinstance(error, OSError) and getattr(error, 'winerror', None) in {50, 1}:
- provider_errors[op_location] += 1
- if provider_errors[op_location] >= 3:
- unavailable.add(op_location)
- save(receipt_path, receipt)
- if rollback_failures:
- raise RuntimeError('文件恢复未完成,停止本批') from error
- if checked % 10 == 0:
- print(json.dumps(dict(checked=checked, committed=sum(r['status']=='committed' for r in receipt['entries']), failed=len(receipt['failures'])), ensure_ascii=False), flush=True)
- after_assets = db.execute('SELECT count(*) FROM asset').fetchone()[0]
- after_subtitles = db.execute('SELECT count(*) FROM asset_subtitle').fetchone()[0]
- integrity = db.execute('PRAGMA integrity_check').fetchone()[0]
- final_fk = {tuple(r) for r in db.execute('PRAGMA foreign_key_check')}
- receipt['verification'] = dict(asset_before=before_assets, asset_after=after_assets, integrity=integrity,
- subtitles_before=before_subtitles, subtitles_after=after_subtitles,
- existing_foreign_keys=len(baseline), new_foreign_keys=list(final_fk-baseline))
- save(receipt_path, receipt)
- db.close()
- row = dict(id=1, disposal=None, medium='video', code='ABP-123', studio='Prestige',
- name='ABP-123.mp4', effective_region='jp')
- assert label(row, {}, {}, set()) == ('release','日本','Prestige','ABP-123')
- assert label(dict(row,code='MDX-0123',effective_region='cn'), {}, {}, set()) is None
- assert label(dict(row,code='CA-103',effective_region='kr'), {}, {}, set()) is None
- creator_row = dict(row,code=None,studio=None,effective_region='')
- assert label(creator_row, {1:[(12,'creator')]}, {12:['卖家']}, set()) == ('creator','卖家','creator')
- assert label(creator_row, {1:[(12,'creator')]}, {12:['卖家']}, {12}) is None
- assert label(creator_row, {1:[(12,'creator')]}, {12:['卖家','动画作者']}, set()) is None
- assert before_assets == after_assets and before_subtitles == after_subtitles and integrity == 'ok' and not final_fk-baseline
- print(json.dumps(dict(stage=stage, checked=checked, committed=sum(r['status']=='committed' for r in receipt['entries']),
- failed=len(receipt['failures']), verification=receipt['verification']), ensure_ascii=False))
+ error = execute_operation(db,payload,op,stage,receipt,receipt_path,deadline,retry_failed)
+ if isinstance(error,OfflineSource):
+ unavailable.add(owner)
+ if isinstance(error,OSError) and getattr(error,'winerror',None) in {50,1}:
+ provider_errors[owner] += 1
+ if provider_errors[owner]>=3:
+ unavailable.add(owner)
+ if checked%10==0:
+ print(json.dumps(dict(checked=checked,committed=sum(r['status']=='committed' for r in receipt['entries']),failed=len(receipt['failures'])),ensure_ascii=False),flush=True)
+ receipt['verification'] = verify_result(db,assets,subtitle_count,baseline)
+ save(receipt_path,receipt)
+ print(json.dumps(dict(stage=stage,checked=checked,committed=sum(r['status']=='committed' for r in receipt['entries']),failed=len(receipt['failures']),verification=receipt['verification']),ensure_ascii=False))
finally:
+ if db is not None:
+ db.close()
lock.release()
def self_check():
diff --git a/src/peach/web_batch.py b/src/peach/web_batch.py
index b2ce4a55f..b56f7e672 100644
--- a/src/peach/web_batch.py
+++ b/src/peach/web_batch.py
@@ -141,6 +141,7 @@ JUNK_KINDS = frozenset({"video", "image", "audio", "archive", "url", "other"})
JUNK_VIDEO_MAX_BYTES = 120 * 1024**2
MEDIA_SIDECAR_SUFFIXES = frozenset({".nfo", ".srt", ".ass", ".ssa", ".vtt", ".sub", ".idx"})
INSTALLER_SUFFIXES = frozenset({".apk", ".exe", ".msi"})
+INSTALLER_ARCHIVE_NAMES = frozenset({'1024核工厂.rar'})
PAGE_COMPONENT_SUFFIXES = frozenset({".js", ".css", ".aspx"})
PAGE_CHROME_IMAGE = re.compile(r"^(?:banner(?:_[bs])?|1000x90(?:yunding)?|count\d*|logo|lan\d*|you|zuo|zuoxia)$", re.I)
PAGE_PROMO_CLAIM = re.compile(r"(?:记住|記住).{0,12}(?:网址|網址)|(?:网址|網址).{0,8}(?:发布|發布)")
@@ -314,6 +315,8 @@ def _attachment_junk_reason(suffix: str, path: str, size: int) -> str:
"""区分安装附件与网页存档组件。"""
if suffix in INSTALLER_SUFFIXES and size < 64 * 1024**2:
return "媒体目录中的安装附件"
+ if PureWindowsPath(path).name.casefold() in INSTALLER_ARCHIVE_NAMES and 0 < size <= 64 * 1024:
+ return "已核验的推广安装包附件"
if suffix in PAGE_COMPONENT_SUFFIXES and any(
part.casefold().endswith("_files") for part in PureWindowsPath(path).parent.parts):
return "网页存档的脚本或样式附件"
diff --git a/tests/test_ad_judgement.py b/tests/test_ad_judgement.py
index bbd828092..05a245464 100644
--- a/tests/test_ad_judgement.py
+++ b/tests/test_ad_judgement.py
@@ -392,6 +392,18 @@ class ResourceJunkQueueTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "invalid junk status"):
q_ads(self.contract, status="deleted")
+ def test_verified_small_installer_archive_with_release_code(self):
+ path = r'B:\MVP\Tokyo-Hot n1025-FHD\1024核工厂.rar'
+ self.add(211, '115', path, 'archive', 4111)
+ with closing(sqlite3.connect(self.db_path)) as db:
+ db.execute('UPDATE asset SET code=? WHERE id=?', ('n1025', 211))
+ db.commit()
+ items = q_ads(self.contract, limit=200)['items']
+ self.assertEqual([item['id'] for item in items], [211])
+ self.assertIn('推广安装包', items[0]['why'])
+ self.assertEqual(web_batch._attachment_junk_reason('.rar', path, 128 * 1024), '')
+ self.assertEqual(web_batch._attachment_junk_reason('.rar', r'B:\MVP\n1025.rar', 4111), '')
+
def test_promotional_page_navigation_images_with_inherited_release_code(self):
base = r'B:\MVP\1pon-092415_001-fhd'
page = base + r'\花一分钟记住我们的网址 - sex5.xxx_files'
@@ -404,7 +416,7 @@ class ResourceJunkQueueTests(unittest.TestCase):
db.commit()
items = q_ads(self.contract, limit=200)['items']
self.assertEqual([item['id'] for item in items], [201])
- self.assertTrue(any('导航图片' in reason for reason in items[0]['why']))
+ self.assertIn('导航图片', items[0]['why'])
self.assertEqual(web_batch._attachment_junk_reason('.gif', page + r'\1.gif', 974),
'推广网页存档的横幅、标志或导航图片')
self.assertEqual(web_batch._attachment_junk_reason('.gif', page + r'\1.gif', 6000), '')
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 5b7e4eaf6..4f248097c 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -80,7 +80,7 @@ class LibraryDirectoryTests(unittest.TestCase):
self.assertEqual(op['source'], source)
self.assertEqual(op['target'], r'B:\日本\一本道\092415-001')
self.assertEqual([row['id'] for row in op['rows']], [1, 2, 3])
- with self.script.open_readonly(ledger) as db:
+ with closing(self.script.open_readonly(ledger)) as db:
self.assertEqual(op['entities'], self.script.entity_guard(db, source))
with closing(sqlite3.connect(ledger)) as db:
db.execute('INSERT INTO asset(id,location,path,name,medium) VALUES(4,?,?,?,?)',
@@ -88,7 +88,9 @@ class LibraryDirectoryTests(unittest.TestCase):
db.commit()
self.script.build_plan('rehome', 'mixed')
mixed = json.loads((root / 'rehome-mixed-manifest.json').read_text(encoding='utf-8'))
- self.assertEqual(mixed['operations'], [])
+ self.assertEqual(len(mixed['operations']), 1)
+ self.assertEqual(mixed['operations'][0]['kind'], 'files')
+ self.assertEqual([r['id'] for r in mixed['operations'][0]['rows']], [1, 2])
def test_sidecar_identity_conflicts_and_date_publishers(self):
script = self.script
@@ -103,11 +105,150 @@ class LibraryDirectoryTests(unittest.TestCase):
self.assertTrue(script.release_directory_matches('1pon-092415_001-fhd', owner))
self.assertFalse(script.release_directory_matches('1pon-092416_001-fhd', owner))
self.assertFalse(script.release_directory_matches('092415_001', ('release', '日本', '加勒比', '092415-001')))
+ fc2 = ('release', '日本', 'FC2', 'FC2-PPV-389339')
+ self.assertTrue(script.release_directory_matches('FC-389339最高峰 市島亜美', fc2))
+ self.assertFalse(script.release_directory_matches('FC-3893390', fc2))
+
+ def test_creator_subtype_and_korean_publisher_destinations(self):
+ script = self.script
+ row = dict(id=1, disposal=None, medium='video', code=None, studio=None,
+ name='film.mp4', creator='account', effective_region='')
+ self.assertEqual(script.label(row, {1: [(9, 'account')]}, {}, {9}),
+ ('creator', '创作者', 'account'))
+ self.assertEqual(script.label(row, {1: [(9, 'account')]}, {9: ['网黄博主']}, set()),
+ ('creator', '网黄博主', 'account'))
+ self.assertEqual(script.label(dict(row, studio='MIB', code='AR-101', effective_region='kr'), {}, {}, set()),
+ ('publisher', '韩国', 'MIB'))
+ image = dict(row, medium='image', creator=None)
+ self.assertTrue(script.compatible_sidecar(image, ('creator', '创作者', 'account'), {}))
+ self.assertFalse(script.compatible_sidecar(dict(image, code='ABP-123'), ('creator', '创作者', 'account'), {}))
def test_directory_execution_preserves_sidecars_and_recovers(self):
with redirect_stdout(io.StringIO()):
self.script.self_check()
+ def test_fc_short_parts_require_matching_parent_and_publisher(self):
+ row = dict(code=None, studio=None, name='@fc1780822_1.mp4',
+ path=r'B:\MVP\FC2 collection\FC-1780822耐久黑田4K\@fc1780822_1.mp4')
+ self.assertEqual(self.script.release_code(row), 'FC2-PPV-1780822')
+ self.assertEqual(self.script.release_code(dict(row,path=r'B:\unconfirmed\@fc1780822_1.mp4')), '')
+ self.assertEqual(self.script.release_code(dict(row,path=r'B:\FC-1780823\@fc1780822_1.mp4')), '')
+ self.assertEqual(self.script.release_code(dict(row,studio='Prestige')), '')
+ self.assertIsNone(row['code'])
+
+ def test_flatten_plan_generates_its_own_csv(self):
+ script = self.script
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ ledger = fresh_ledger(root)
+ source = r'B:\ABC-123\ABC-123'
+ media = root / 'media'
+ def translate(path):
+ return media.joinpath(*PureWindowsPath(path).parts[1:])
+ translate(source).mkdir(parents=True)
+ translate(source + r'\film.mp4').write_bytes(b'film')
+ with closing(sqlite3.connect(ledger)) as db:
+ db.execute('INSERT INTO asset(id,location,path,name,medium) VALUES(1,?,?,?,?)',
+ ('115',source+r'\film.mp4','film.mp4','video'))
+ db.commit()
+ with mock.patch.object(script, 'DATABASE_PATH', ledger), mock.patch.object(script, 'OUT', root), \
+ mock.patch.object(script, 'location_roots', return_value={'115':['B:\\']}), \
+ mock.patch.object(script, 'translate_ledger_path', side_effect=translate), \
+ redirect_stdout(io.StringIO()):
+ script.build_plan('flatten', 'example')
+ manifest = json.loads((root/'flatten-example-manifest.json').read_text(encoding='utf-8'))
+ self.assertEqual([(op['kind'],op['source'],op['target']) for op in manifest['operations']],
+ [('collapse',source,r'B:\ABC-123')])
+ self.assertTrue((root/'flatten-example-plan.csv').is_file())
+
+ def test_mixed_file_group_and_database_failure_restore(self):
+ script = self.script
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ ledger = fresh_ledger(root)
+ media = root / 'media'
+ source = r'B:\MVP\collection'
+ target = r'B:\日本\FC2\FC2-PPV-1234567'
+ def translate(path):
+ return media.joinpath(*PureWindowsPath(path).parts[1:])
+ film = source + r'\FC2-PPV-1234567.mp4'
+ translate(film).parent.mkdir(parents=True)
+ translate(film).write_bytes(b'film')
+ subtitle = source + r'\FC2-PPV-1234567.srt'
+ translate(subtitle).write_bytes(b'subtitle')
+ translate(source + r'\unknown.mp4').write_bytes(b'other')
+ with closing(sqlite3.connect(ledger)) as db:
+ db.row_factory = sqlite3.Row
+ db.execute('INSERT INTO asset(id,location,path,name,medium,code) VALUES(1,?,?,?,?,?)',
+ ('115', film, 'FC2-PPV-1234567.mp4', 'video', 'FC2-PPV-1234567'))
+ db.execute('INSERT INTO asset(id,location,path,name,medium) VALUES(2,?,?,?,?)',
+ ('115', source + r'\unknown.mp4', 'unknown.mp4', 'video'))
+ db.execute("INSERT INTO asset_subtitle(id,asset_id,location,path,name,format,pairing,first_seen,last_seen) VALUES(1,1,?,?,?,'srt','exact','2026-10-07','2026-10-07')",
+ ('115', subtitle, PureWindowsPath(subtitle).name))
+ db.execute('INSERT INTO asset(id,location,path,name,medium) VALUES(3,?,?,?,?)',
+ ('115', subtitle, PureWindowsPath(subtitle).name, 'other'))
+ db.commit()
+ op = script.operation('files', source, target, script.snapshots(db, source, [1, 3]), '已知作品')
+ op['subtitles'] = script.subtitles(db, source)
+ op['entities'] = script.entity_guard(db, source, [1, 3])
+ db.execute("CREATE TRIGGER refuse_path BEFORE UPDATE OF path ON asset BEGIN SELECT RAISE(ABORT,'refuse'); END")
+ db.commit()
+ payload = dict(format=1, stage='rehome', roots={'115': ['B:\\']}, operations=[op])
+ script.save(root / 'rehome-example-manifest.json', payload)
+ with mock.patch.object(script, 'DATABASE_PATH', ledger), mock.patch.object(script, 'OUT', root), \
+ mock.patch.object(script, 'translate_ledger_path', side_effect=translate), \
+ mock.patch.object(script, 'root_online', return_value=True), \
+ mock.patch.object(script.organize, '_rename', side_effect=lambda old, new: (translate(new).parent.mkdir(parents=True, exist_ok=True), translate(old).rename(translate(new)))), \
+ redirect_stdout(io.StringIO()):
+ script.run_apply('rehome', root / 'backup1.db', 10, 20, batch='example')
+ receipt = json.loads((root / 'rehome-example-receipt.json').read_text(encoding='utf-8'))
+ self.assertEqual(receipt['entries'][0]['status'], 'restored')
+ self.assertEqual(translate(film).read_bytes(), b'film')
+ self.assertEqual(translate(subtitle).read_bytes(), b'subtitle')
+ self.assertFalse(translate(target + r'\FC2-PPV-1234567.mp4').exists())
+ with closing(sqlite3.connect(ledger)) as db:
+ self.assertEqual(db.execute('SELECT path FROM asset WHERE id=1').fetchone()[0], film)
+ db.execute('DROP TRIGGER refuse_path')
+ db.commit()
+ script.run_apply('rehome', root / 'backup2.db', 10, 20, retry_failed=True, batch='example')
+ self.assertEqual(translate(target + r'\FC2-PPV-1234567.mp4').read_bytes(), b'film')
+ self.assertEqual(translate(target + r'\FC2-PPV-1234567.srt').read_bytes(), b'subtitle')
+ self.assertEqual(translate(source + r'\unknown.mp4').read_bytes(), b'other')
+ with closing(sqlite3.connect(ledger)) as db:
+ self.assertEqual(db.execute('SELECT path FROM asset WHERE id=1').fetchone()[0], target + r'\FC2-PPV-1234567.mp4')
+ self.assertEqual(db.execute('SELECT path FROM asset_subtitle WHERE id=1').fetchone()[0], target + r'\FC2-PPV-1234567.srt')
+ self.assertEqual(db.execute('SELECT path FROM asset WHERE id=3').fetchone()[0], target + r'\FC2-PPV-1234567.srt')
+
+
+ def test_mixed_creator_files_keep_unknown_media_and_original_structure(self):
+ from peach.entity_classification import write_claim
+ script = self.script
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ ledger = fresh_ledger(root)
+ source = r'B:\MVP\shared collection'
+ with closing(sqlite3.connect(ledger)) as db:
+ for aid,name in [(1,'known.mp4'),(2,'unknown.mp4')]:
+ db.execute('INSERT INTO asset(id,location,path,name,medium) VALUES(?,?,?,?,?)',
+ (aid,'115',source+'\\'+name,name,'video'))
+ db.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) VALUES(9,'creator','account','account','2026-10-07','2026-10-07')")
+ db.execute("INSERT INTO asset_entity(asset_id,entity_id,role,source) VALUES(1,9,'creator','test')")
+ write_claim(db,entity_id=9,facet='identity',value='unknown',source='test',evidence='归属关系存在,身份待复核')
+ db.commit()
+ with mock.patch.object(script,'DATABASE_PATH',ledger), mock.patch.object(script,'OUT',root), \
+ mock.patch.object(script,'location_roots',return_value={'115':['B:\\']}), \
+ mock.patch.object(script,'root_online',return_value=True), redirect_stdout(io.StringIO()):
+ script.build_plan('rehome','mixed-creators')
+ plan=json.loads((root/'rehome-mixed-creators-manifest.json').read_text(encoding='utf-8'))
+ self.assertEqual(len(plan['operations']),1)
+ op=plan['operations'][0]
+ self.assertEqual((op['kind'],op['source'],op['target']),
+ ('files',source,r'B:\创作者\account\shared collection'))
+ self.assertEqual([row['id'] for row in op['rows']],[1])
+ self.assertEqual(plan['skipped'],[dict(source=source+r'\unknown.mp4',reason='归属未确认,保留原位置')])
+ with closing(sqlite3.connect(ledger)) as db:
+ self.assertIsNone(db.execute('SELECT creator FROM asset WHERE id=1').fetchone()[0])
+
class OperationalScriptTests(unittest.TestCase):
@classmethod