#!/usr/bin/env python3 """Распознавание текста на изображениях через Tesseract.""" from __future__ import annotations import argparse import shutil import sys from pathlib import Path try: from PIL import Image, ImageOps except ImportError: sys.exit("Нужен Pillow: python3 -m pip install Pillow") try: import pytesseract except ImportError: sys.exit("Нужен pytesseract: python3 -m pip install pytesseract") EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"} def collect(source: Path, recursive: bool) -> list[Path]: if source.is_file(): return [source] pattern = "**/*" if recursive else "*" return sorted( path for path in source.glob(pattern) if path.is_file() and path.suffix.lower() in EXTENSIONS ) def main() -> int: parser = argparse.ArgumentParser(description="Распознать текст на изображениях") parser.add_argument("--input", type=Path) parser.add_argument("--dir", type=Path) parser.add_argument("--out", type=Path, help="Папка для TXT, без нее текст печатается") parser.add_argument("--lang", default="eng") parser.add_argument("--psm", type=int, default=3) parser.add_argument("--tesseract", type=Path, help="Путь к tesseract.exe на Windows") parser.add_argument("--recursive", action="store_true") parser.add_argument("--overwrite", action="store_true") args = parser.parse_args() if bool(args.input) == bool(args.dir): parser.error("Укажите либо --input, либо --dir") if args.tesseract: pytesseract.pytesseract.tesseract_cmd = str(args.tesseract.expanduser().resolve()) elif shutil.which("tesseract") is None: print("Tesseract не найден в PATH. Установите его или укажите --tesseract.") return 2 source = (args.input or args.dir).expanduser().resolve() if not source.exists(): parser.error(f"Источник не найден: {source}") files = collect(source, args.recursive) if not files: print("Изображения не найдены.") return 0 out_dir = None if args.out: out_dir = args.out.expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) done = skipped = failed = 0 for path in files: target = out_dir / (path.stem + ".txt") if out_dir else None if target and target.exists() and not args.overwrite: skipped += 1 continue try: with Image.open(path) as opened: image = ImageOps.exif_transpose(opened).convert("RGB") text = pytesseract.image_to_string( image, lang=args.lang, config=f"--psm {args.psm}", ).strip() if target: target.write_text(text + "\n", encoding="utf-8") print(f"Готово: {path.name} -> {target.name} ({len(text)} символов)") else: print(f"--- {path.name} ---") print(text if text else "(текст не найден)") except Exception as error: print(f"Ошибка {path}: {error}") failed += 1 continue done += 1 print(f"Итог: {done} обработано, {skipped} пропущено, {failed} ошибок") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(main())