Peach: Local-first video metadata scraper and media manager.
fix(naming): 英文文件名分词不拆缩写、站点编号与混合字母词
longmeidao77caa5ab8735
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 45bd8f9ab..a71c1bd50 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -223,7 +223,7 @@ A 盘同父目录改名复用 CloudDrive 官方 `RenameFile`;跨父且改名下载站的 DNS 导航步骤、hav.so 横幅、固定英文横幅和带下载套话的 HiHSP 地址卡片,按文件名与 2 MiB 上限进入复核;用户确认的「社區最新情報」精确名称 MP4 按 32 MiB 上限进入复核。普通作品图片和 `images.rar` 保留。CloudDrive WebDAV 的小文件删除复用原生 `Path.unlink`:同目录隔离改名报 WinError 50 时,最多 1 MiB 的文件先用标准库 `shutil.copyfile` 完整备份到 `generated/purge-staging/`,记录原路径、大小和 SHA256,再删除。数据库失败时恢复备份,提交后清退;大文件继续报告阻塞。该路径没有新增依赖,备份和恢复只由 `purge_assets` 管理。-英文媒体文件名分词复用 `wordninja-enhanced==3.2.0`(MIT,2026-09-04 发布,Python ≥3.9,纯 Python,wheel 11.4 MB,无传递依赖)。源码经 `opensrc path pypi:[email protected]` 读取;原版 wordninja 的发布较旧,增强版提供标点保留和可补充词典。`space_media_names.py` 先出逐文件复核 CSV,只插入空格,保留序号、字符与扩展名,不推断人物或出处;指定目录内的真实文件核验后复用 `organize.apply_plan`、SQLite 备份及回滚日志。领域词汇在 `english_filename_words.txt`,有分词歧义时可按原名回滚。+英文媒体文件名分词复用 `wordninja-enhanced==3.2.0`(MIT,2026-09-04 发布,Python ≥3.9,纯 Python,wheel 11.4 MB,无传递依赖)。源码经 `opensrc path pypi:[email protected]` 读取;原版 wordninja 的发布较旧,增强版提供标点保留和可补充词典。`space_media_names.py` 先出逐文件复核 CSV,只插入空格,保留序号、字符与扩展名,不推断人物或出处;指定目录内的真实文件核验后复用 `organize.apply_plan`、SQLite 备份及回滚日志。领域词汇在 `english_filename_words.txt`(置顶加权,条目宜少:每多一条都会压低 `a`、`of` 等高频词),常被误当成单词的拼接串在 `english_filename_nonwords.txt` 里移出词频表。撇号缩写、全大写缩写、域名与站点编号、十六进制 viewkey 不拆;西里尔形近字母按拉丁字母算切点、原字符保留。已执行批次用 `--recompute-batch <日志>` 按原名重算出复核 CSV,再走 `--apply --review-csv`。A 盘垃圾隔离使用短名称 `peach-purge-<32 位 UUID>.peach-quarantine`,扫描入口仅跳过这一精确格式;普通媒体和其他 `.tmp` 文件仍需复核。`51风流.png`、`代开实习证明.png`、`扫码约炮.png`、`探花社区.png` 仅在不超过 4 KiB 时进入图片内容复核,不凭名称自动删除。隔离恢复与本地完整备份沿用 `purge_assets` 的事务边界。diff --git a/resources/naming/english_filename_nonwords.txt b/resources/naming/english_filename_nonwords.txtnew file mode 100644index 000000000..ba700ce2d--- /dev/null+++ b/resources/naming/english_filename_nonwords.txt@@ -0,0 +1,13 @@+# 从通用英文词频里移除的拼接词;它们在媒体文件名里几乎总是两个词粘在一起。+# 只影响插入空格的位置,不用于身份归属。人名(Irina、Sona、Rina 等)不要放进来:+# 移出词频表后,整词出现的名字会被切成碎片。+ahot+alot+asa+cockin+froms+gota+hiscock+mein+sowell+tfidiff --git a/resources/naming/english_filename_words.txt b/resources/naming/english_filename_words.txtindex df7ab8e08..1b5f1de29 100644--- a/resources/naming/english_filename_words.txt+++ b/resources/naming/english_filename_words.txt@@ -22,7 +22,13 @@ brunettesfacialfacialsrough+footjob+footjobs+jizz+plumpy+stepsisPOV+CIMASMR4KOnlyFansdiff --git a/scripts/space_media_names.py b/scripts/space_media_names.pyindex e017a1477..746ae0e19 100644--- a/scripts/space_media_names.py+++ b/scripts/space_media_names.py@@ -1,4 +1,13 @@-"""恢复英文媒体文件名的单词间隔,保留原字符、序号和扩展名。"""+"""恢复英文媒体文件名的单词间隔,保留原字符、序号和扩展名。++只插入空格,不改任何字符。以下几类不拆:撇号缩写(`Couldn't`、`Year's`)、全大写缩写+(`POV`、`CIM`)与紧挨数字的全大写编号(`SPANKPH6`、`ASMR4K`)、网站域名及紧跟的编号+(`xvideos.com_abcdefgh`)、Pornhub viewkey 与十六进制编号(`ph5f8a9bcdef12345`)。+混入西里尔形近字母的词(`withсum`)按拉丁字母算切点,原字符照旧保留。++`--recompute-batch` 按修正后的分词重算一个已执行批次:对日志里每条的原名重新分词,+与现名不同的行写成复核 CSV,交给 `--apply --review-csv` 执行。+"""from __future__ import annotationsimport argparse@@ -18,27 +27,84 @@ from peach.review_csv import read_rows, write_rowsfrom peach.scripting import add_ledger_write_args, open_for_write, open_readonlyfrom wordninja_enhanced import LanguageModel-WORDS = PROJECT / 'resources' / 'naming' / 'english_filename_words.txt'+NAMING = PROJECT / 'resources' / 'naming'+WORDS = NAMING / 'english_filename_words.txt'+NONWORDS = NAMING / 'english_filename_nonwords.txt'FIELDS = (*organize.PLAN_FIELDS, 'size', 'original_name', 'new_name')+VIDEO_SUFFIXES = {'.mp4', '.mkv', '.avi', '.mov', '.wmv', '.webm'}++#: 西里尔形近字母与右单引号,一一映射到拉丁字母与直撇号;只用来算切点,长度不变。+LOOKALIKES = 'аеорсухіјѕАВЕКМНОРСТХІЈЅ'+SHADOW = str.maketrans(LOOKALIKES + '’', 'aeopcyxijsABEKMHOPCTXIJS' + "'")+LETTER = 'A-Za-z' + LOOKALIKES+CHUNK = rf"[{LETTER}]+(?:['’][{LETTER}]+)*"+TLD = 'com|net|org|tv|xxx|xyz|cc|io|top|vip|club|info|live|site|porn|sex|biz'+DOMAIN = rf"(?:[A-Za-z0-9-]+\.)+(?:{TLD})(?![A-Za-z0-9])(?:[_-][A-Za-z0-9]+)?"+HEX_ID = r"(?<![A-Za-z0-9])(?:ph)?(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{8,}(?![A-Za-z0-9])"+VIEWKEY = r"viewkey=?[A-Za-z0-9]+"+TOKEN = re.compile(rf"(?P<keep>{DOMAIN}|{VIEWKEY}|{HEX_ID})|(?P<word>{CHUNK})")+++def _entries(path):+ return [line.strip() for line in path.read_text(encoding='utf-8').splitlines()+ if line.strip() and not line.startswith('#')]def model():- words = [line.strip() for line in WORDS.read_text(encoding='utf-8').splitlines()- if line.strip() and not line.startswith('#')]- return LanguageModel(add_words=words, add_to_top=True, overwrite=True)+ return LanguageModel(add_words=_entries(WORDS),+ blacklist=[word.lower() for word in _entries(NONWORDS)],+ add_to_top=True, overwrite=True)+++def _cuts(shadow, language):+ """词段里该插空格的位置:小写接大写处必切,其余由词频模型定;撇号两侧与 n't 之前不切。"""+ cuts, start = set(), 0+ forced = [i for i in range(1, len(shadow)) if shadow[i - 1].islower() and shadow[i].isupper()]+ for end in [*forced, len(shadow)]:+ offset = start+ for character in language.rejoin(shadow[start:end]):+ if character == ' ':+ cuts.add(offset)+ else:+ offset += 1+ cuts.add(end)+ start = end+ return sorted(cut for cut in cuts if 0 < cut < len(shadow)+ and "'" not in (shadow[cut - 1], shadow[cut])+ and shadow[cut:cut + 3].lower() != "n't")+++def _spaced_chunk(text, before, after, language):+ shadow = text.translate(SHADOW)+ if not re.search('[A-Za-z]', text):+ return text+ letters = shadow.replace("'", '')+ if letters.isupper() and (len(letters) <= 4 or before.isdigit() or after.isdigit()):+ return text+ parts, last = [], 0+ for cut in _cuts(shadow, language):+ parts.append(text[last:cut])+ last = cut+ parts.append(text[last:])+ return ' '.join(parts)def spaced_name(name, language):"""仅插入空格,词典不确定性不会改写内容字符。"""path = PureWindowsPath(name)- if path.suffix.casefold() not in {'.mp4', '.mkv', '.avi', '.mov', '.wmv', '.webm'}:+ if path.suffix.casefold() not in VIDEO_SUFFIXES:return name+ original = path.stem+def words(match):- text = re.sub(r'(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])', ' ', match.group())- return language.rejoin(text)- stem = re.sub(r'[A-Za-z]+', words, path.stem)+ if match.group('keep'):+ return match.group()+ before = original[match.start() - 1] if match.start() else ''+ after = original[match.end()] if match.end() < len(original) else ''+ return _spaced_chunk(match.group(), before, after, language)+ stem = TOKEN.sub(words, original)stem = re.sub(r'([,;!])(?=[A-Za-z])', r'\1 ', stem)- if re.sub(r'\s', '', stem) != re.sub(r'\s', '', path.stem):+ if re.sub(r'\s', '', stem) != re.sub(r'\s', '', original):raise ValueError('英文分词改变了内容字符')return stem + path.suffix@@ -65,13 +131,61 @@ def plan(connection, root):return result+def recompute_batch(connection, root, log_path):+ """按修正后的分词重算已执行批次:原名重新分词,与现名不同的行出改名计划,只读。++ 批次之后文件可能已被目录整理搬走,所以按 asset_id 找账本里的当前行,只要求文件名+ 仍是批次写下的那个名字、所在目录是 `root`。名字已被改过、行已不在库或不在 `root`+ 的条目不出计划,放进第二个返回值。+ """+ canonical_root = str(PureWindowsPath(root))+ entries = json.loads(Path(log_path).read_text(encoding='utf-8')).get('entries') or []+ language = model()+ result, skipped, claimed = [], [], set()+ for entry in entries:+ original, current = PureWindowsPath(entry['old_path']), PureWindowsPath(entry['new_path'])+ new = spaced_name(original.name, language)+ if new == current.name:+ continue+ row = connection.execute('SELECT location,path,size FROM asset WHERE id=? AND disposal IS NULL',+ (int(entry['asset_id']),)).fetchone()+ held = PureWindowsPath(row['path']) if row else None+ reason = ('已不在库' if held is None+ else '文件名已不是批次写下的名字' if held.name != current.name+ else '不在 --root 指定的目录' if str(held.parent).casefold() != canonical_root.casefold()+ else '')+ if reason:+ skipped.append(dict(asset_id=int(entry['asset_id']), path=str(held or current), reason=reason))+ continue+ target = str(held.with_name(new))+ if len(target) > organize.MAX_PATH or target.casefold() in claimed:+ raise ValueError('分词目标重名或路径过长')+ claimed.add(target.casefold())+ result.append(dict(asset_id=int(entry['asset_id']), location=row['location'],+ current_path=row['path'], target_path=target, action='rename',+ reason='按修正后的分词重算', size=row['size'],+ original_name=held.name, new_name=new))+ return result, skipped++def main(argv=None):parser = argparse.ArgumentParser(description=__doc__)add_ledger_write_args(parser)parser.add_argument('--root', required=True)parser.add_argument('--review-csv', type=Path)+ parser.add_argument('--recompute-batch', type=Path,+ help='已执行的分词批次日志;只出重算计划,不能与 --apply 同用')parser.add_argument('--out', type=Path, default=GENERATED_DIR / 'english-name-spacing.csv')args = parser.parse_args(argv)+ if args.recompute_batch:+ if args.apply:+ parser.error('--recompute-batch 只出计划;执行用 --apply --review-csv')+ with closing(open_readonly(args.db)) as connection:+ rows, skipped = recompute_batch(connection, args.root, args.recompute_batch)+ write_rows(args.out, FIELDS, rows, atomic=True)+ print(json.dumps(dict(planned=len(rows), skipped=skipped, review=str(args.out)),+ ensure_ascii=False))+ return 0if not args.apply:with closing(open_readonly(args.db)) as connection:rows = plan(connection, args.root)diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 367238b39..9e3581880 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -67,6 +67,88 @@ class EnglishNameSpacingTests(unittest.TestCase):for name in ('01_作品封面.jpg', 'FC2-PPV-123456.zip', '作品.mp4'):self.assertEqual(self.script.spaced_name(name, self.language), name)+ def test_titles_from_the_executed_batch_split_at_word_bounds(self):+ """2026-10-07 那批里切错过的真实片名。"""+ cases = {+ "29_Couldn'tresistherhotcowgirl,shegotacreampie.mp4":+ "29_Couldn't resist her hot cowgirl, she got a creampie.mp4",+ "56_HoldingmyhairsoIdon'tResist.mp4": "56_Holding my hair so I don't Resist.mp4",+ "54_Hisdickdoesn'tfitinmyMouth.mp4": "54_His dick doesn't fit in my Mouth.mp4",+ '48_oiledPOVfootjob.mp4': '48_oiled POV footjob.mp4',+ '40_PetitebrunettemakeshimCIMwithhotdeepthroat.mp4':+ '40_Petite brunette makes him CIM with hot deepthroat.mp4',+ '74_HUGELOADonherFaceandSwallowed.mp4': '74_HUGE LOAD on her Face and Swallowed.mp4',+ '36_Bitchwithplumpyredlips.mp4': '36_Bitch with plumpy red lips.mp4',+ '35_Hotbrunettetakesabigcockinherthroat.mp4': '35_Hot brunette takes a big cock in her throat.mp4',+ '52_Iinterruptedherfromaphotoshootwithahotdeepthroat.mp4':+ '52_I interrupted her from a photoshoot with a hot deepthroat.mp4',+ 'stepsisstuckinwasher.mp4': 'stepsis stuck in washer.mp4',+ 'SPANKPH6-SpankingherRoughly.mp4': 'SPANKPH6-Spanking her Roughly.mp4',+ 'POVblowjobASMR4K.mp4': 'POV blowjob ASMR4K.mp4',+ }+ for name, expected in cases.items():+ with self.subTest(name=name):+ self.assertEqual(self.script.spaced_name(name, self.language), expected)++ def test_mixed_script_words_split_and_keep_their_characters(self):+ spaced = self.script.spaced_name('17_Filledwithсumallthethroat.mp4', self.language)+ self.assertEqual(spaced, '17_Filled with сum all the throat.mp4')+ self.assertIn('сum', spaced)++ def test_performer_names_stay_whole(self):+ for name, expected in (('IrinaSucksAndRides.mp4', 'Irina Sucks And Rides.mp4'),+ ('SonaGetsFucked.mp4', 'Sona Gets Fucked.mp4')):+ with self.subTest(name=name):+ self.assertEqual(self.script.spaced_name(name, self.language), expected)++ def test_site_identifiers_are_left_whole(self):+ for name in ('ph5f8a9bcdef12345.mp4', 'xvideos.com_abcdefgh.mp4',+ 'viewkey=ph5f8a9bcdef12345.mp4'):+ with self.subTest(name=name):+ self.assertEqual(self.script.spaced_name(name, self.language), name)++ def test_recompute_batch_plans_only_mis_split_rows_and_apply_accepts_it(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ db = fresh_ledger(root)+ wrong = root / "29_Could n't resist her.mp4"+ right = root / '02_Throat fucking.mp4'+ moved = root / '03_Sloppy throat.mp4'+ for path in (wrong, right):+ path.write_bytes(b'media')+ with closing(sqlite3.connect(db)) as connection:+ for asset_id, path in ((1, wrong), (2, right), (3, root / 'elsewhere' / moved.name)):+ connection.execute('INSERT INTO asset(id,location,path,name,medium,size) VALUES(?,?,?,?,?,?)',+ (asset_id, 'local', str(path), path.name, 'video', 5))+ connection.commit()+ log = root / 'organize-batch.json'+ # 第 1 条在批次之后被目录整理从 New 搬到了 root:按 asset_id 找当前行。+ log.write_text(json.dumps({'entries': [+ {'asset_id': 1, 'old_path': str(root / 'New' / "29_Couldn'tresisther.mp4"),+ 'new_path': str(root / 'New' / wrong.name)},+ {'asset_id': 2, 'old_path': str(root / '02_Throatfucking.mp4'), 'new_path': str(right)},+ {'asset_id': 3, 'old_path': str(root / '03_Sloppythroatt.mp4'), 'new_path': str(moved)},+ ]}), encoding='utf-8')+ review = root / 'recompute.csv'+ with redirect_stdout(io.StringIO()) as output:+ self.assertEqual(self.script.main(['--db', str(db), '--root', str(root),+ '--recompute-batch', str(log), '--out', str(review)]), 0)+ report = json.loads(output.getvalue())+ self.assertEqual(report['planned'], 1)+ self.assertEqual([item['asset_id'] for item in report['skipped']], [3])+ rows = self.script.read_rows(review)+ self.assertEqual([(row['asset_id'], PureWindowsPath(row['target_path']).name) for row in rows],+ [('1', "29_Couldn't resist her.mp4")])+ self.assertTrue(wrong.exists())++ with mock.patch.object(self.script, 'location_roots', return_value={'local': [str(root)]}), \+ mock.patch.object(self.script, 'GENERATED_DIR', root / 'generated'), \+ redirect_stdout(io.StringIO()):+ self.assertEqual(self.script.main(['--db', str(db), '--root', str(root), '--review-csv', str(review),+ '--apply', '--backup', str(root / 'backup.db')]), 0)+ self.assertFalse(wrong.exists())+ self.assertTrue((root / "29_Couldn't resist her.mp4").exists())+def test_apply_rejects_character_changes_before_opening_writer(self):with tempfile.TemporaryDirectory() as directory:root = Path(directory)