#!/usr/bin/env python3 """Транслитерация кириллических имён файлов в латиницу.""" from __future__ import annotations import argparse import os import re import sys import unicodedata from pathlib import Path TRANSLIT = { "а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "yo", "ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m", "н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u", "ф": "f", "х": "kh", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "shch", "ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya", "і": "i", "ї": "yi", "є": "ye", "ґ": "g", } CYRILLIC = re.compile(r"[А-Яа-яЁёІіЇїЄєҐґ]") INVALID = re.compile(r"[^\w.\- ]", re.UNICODE) def split_name(name: str) -> tuple[str, str, int]: leading = len(name) - len(name.lstrip(".")) if leading >= len(name): return "", "", 0 core = name[leading:] suffix = Path(core).suffix stem = core[: -len(suffix)] if suffix else core return stem, suffix, leading def transliterate(text: str) -> str: result = [] for char in text: mapped = TRANSLIT.get(char.lower()) if mapped is None: result.append(char) elif char.isupper() and mapped: result.append(mapped.capitalize()) else: result.append(mapped) return "".join(result) def transliterate_name(name: str) -> str: stem, suffix, leading = split_name(name) text = unicodedata.normalize("NFKC", transliterate(stem)) text = re.sub(r"\s+", "_", text) text = INVALID.sub("", text) text = re.sub(r"_+", "_", text).strip("._- ") if not text: text = "file" suffix = INVALID.sub("", unicodedata.normalize("NFKC", suffix)) return "." * leading + text + suffix def unique_path(path: Path, reserved: set[Path]) -> Path: if path not in reserved and not path.exists(): return path for index in range(2, 10000): candidate = path.with_name(f"{path.stem}_{index}{path.suffix}") if candidate not in reserved and not candidate.exists(): return candidate raise RuntimeError(f"Не удалось подобрать имя для {path}") def iter_files(root: Path, recursive: bool): if recursive: for current, dirs, names in os.walk(root): current_path = Path(current) dirs[:] = [name for name in dirs if not (current_path / name).is_symlink()] for name in names: path = current_path / name if path.is_file() and not path.is_symlink(): yield path else: for path in root.iterdir(): if path.is_file() and not path.is_symlink(): yield path def main() -> int: parser = argparse.ArgumentParser(description="Транслитерировать имена файлов") parser.add_argument("--dir", type=Path, required=True, help="Папка с файлами") parser.add_argument("--recursive", action="store_true", help="Обходить вложенные папки") parser.add_argument("--apply", action="store_true", help="Выполнить переименование") args = parser.parse_args() root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") reserved: set[Path] = set() plan: list[tuple[Path, Path]] = [] skipped = 0 for source in iter_files(root, args.recursive): if not CYRILLIC.search(source.name): skipped += 1 continue new_name = transliterate_name(source.name) if new_name == source.name: skipped += 1 continue destination = unique_path(source.with_name(new_name), reserved) reserved.add(destination) plan.append((source, destination)) if not plan: print("Файлы с кириллицей не найдены.") return 0 for source, destination in plan: print(f"{source.relative_to(root)} -> {destination.name}") if not args.apply: print(f"\nПредпросмотр: {len(plan)} переименований. Для применения добавьте --apply.") return 0 renamed = 0 failed = 0 for source, destination in plan: try: source.rename(destination) renamed += 1 except OSError as error: failed += 1 print(f"Ошибка {source}: {error}", file=sys.stderr) print(f"\nПереименовано: {renamed}, пропущено: {skipped}, ошибок: {failed}") return 0 if failed == 0 else 1 if __name__ == "__main__": raise SystemExit(main())