#!/usr/bin/env python3 """Нормализует рейтинги NFO к десятибалльной шкале.""" from __future__ import annotations import argparse import json import re import shutil from pathlib import Path RATING_BLOCK = re.compile( r'(]*\bmax="(?P\d+)"[^>]*>)(?P.*?)()', re.IGNORECASE | re.DOTALL, ) VALUE = re.compile(r'(\s*)([0-9]+(?:\.[0-9]+)?)(\s*)', re.IGNORECASE) BARE = re.compile(r'(\s*)([0-9]+(?:\.[0-9]+)?)(\s*)', re.IGNORECASE) def scale(value: float, maximum: int) -> float: if maximum == 5: return value * 2 if maximum == 100: return value / 10 return value def normalize(text: str) -> tuple[str, int, int]: changes = 0 ambiguous = 0 def fix_block(match: re.Match) -> str: nonlocal changes maximum = int(match.group("max")) body = match.group("body") def fix_value(value_match: re.Match) -> str: nonlocal changes value = float(value_match.group(2)) fixed = scale(value, maximum) if abs(fixed - value) > 0.001: changes += 1 return f"{value_match.group(1)}{fixed:.1f}{value_match.group(3)}" body = VALUE.sub(fix_value, body) return match.group(1) + body + match.group(4) text = RATING_BLOCK.sub(fix_block, text) def fix_bare(match: re.Match) -> str: nonlocal changes, ambiguous value = float(match.group(2)) if value > 10: changes += 1 return f"{match.group(1)}{value / 10:.1f}{match.group(3)}" if 0 < value <= 5: ambiguous += 1 return match.group(0) text = BARE.sub(fix_bare, text) return text, changes, ambiguous def main() -> int: parser = argparse.ArgumentParser(description="Нормализовать рейтинги NFO") parser.add_argument("--dir", type=Path, required=True, help="Папка с NFO") parser.add_argument("--apply", action="store_true", help="Записать изменения") parser.add_argument("--json", type=Path, help="Сохранить отчёт") args = parser.parse_args() root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") report = [] for path in sorted(root.rglob("*.nfo")): try: text = path.read_text(encoding="utf-8") except UnicodeDecodeError: text = path.read_text(encoding="cp1251") fixed, changes, ambiguous = normalize(text) if changes == 0 and ambiguous == 0: continue print(f"{path}: изменений {changes}, неоднозначных {ambiguous}") report.append({"file": str(path), "changes": changes, "ambiguous": ambiguous}) if args.apply and changes: backup = path.with_name(path.name + ".bak") index = 1 while backup.exists(): backup = path.with_name(f"{path.name}.bak{index}") index += 1 shutil.copy2(path, backup) path.write_text(fixed, encoding="utf-8") if not report: print("Проблемных рейтингов не найдено.") return 0 print(f"Файлов в отчёте: {len(report)}") if args.json: target = args.json.expanduser() target.parent.mkdir(parents=True, exist_ok=True) target.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Отчёт: {target}") if not args.apply: print("Это предпросмотр. Для записи добавьте --apply.") return 0 if __name__ == "__main__": raise SystemExit(main())