Download ocr.py from Kervyn-AI/Kervyn-OCR-130M-Preview: direct link, hf CLI and curl.
- Browser
- Download file 3.22 kB
-
https://huggingface.co/Kervyn-AI/Kervyn-OCR-130M-Preview/resolve/main/ocr.py
- Command line
-
hf download hf://Kervyn-AI/Kervyn-OCR-130M-Preview/ocr.py
-
curl -L -o ocr.py https://huggingface.co/Kervyn-AI/Kervyn-OCR-130M-Preview/resolve/main/ocr.py
3.22 kB
| """Kervyn-OCR: lee documentos (PDF o imágenes de página) y escribe su Markdown. | |
| python ocr.py informe.pdf pagina.png --out salida/ [--pages 1-3,7] [--json] [--device cpu] [--threads 8] | |
| De cada documento sale ``salida/<nombre>.md``: títulos con almohadillas, párrafos con sus líneas unidas, tablas en | |
| Markdown (en HTML si tienen celdas combinadas) y fórmulas en LaTeX entre ``$$``. Cabeceras y pies de página no se | |
| copian. Un PDF se pinta a 150 ppp; de una imagen se supone que es una hoja entera, o se le dice su resolución con | |
| ``--image-dpi``. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| import time | |
| from pathlib import Path | |
| # Sin resolver enlaces: en una carpeta de descarga hecha de enlaces, el fichero real vive en otro sitio y con otro nombre. | |
| HERE = Path(__file__).absolute().parent | |
| sys.path.insert(0, str(HERE)) | |
| from kervyn_ocr import KervynOCR # noqa: E402 | |
| def page_numbers(spec: str | None) -> list[int] | None: | |
| if not spec: | |
| return None | |
| chosen: set[int] = set() | |
| for part in spec.split(","): | |
| first, _, last = part.strip().partition("-") | |
| chosen.update(range(int(first) - 1, int(last or first))) | |
| return sorted(chosen) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("inputs", nargs="+", type=Path, help="PDF o imágenes de página") | |
| parser.add_argument("--model", type=Path, default=HERE, help="carpeta de los pesos") | |
| parser.add_argument("--out", type=Path, required=True) | |
| parser.add_argument("--pages", default=None, help="páginas de cada PDF, contando desde 1: 1-3,7") | |
| parser.add_argument("--image-dpi", type=float, default=0.0) | |
| parser.add_argument("--device", default="auto") | |
| parser.add_argument("--threads", type=int, default=0) | |
| parser.add_argument("--batch", type=int, default=8) | |
| parser.add_argument("--json", action="store_true", help="además, <nombre>.json con las regiones de cada página") | |
| args = parser.parse_args() | |
| ocr = KervynOCR.load(args.model, device=args.device, threads=args.threads, batch=args.batch) | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| for source in args.inputs: | |
| parts, record = [], [] | |
| began = time.perf_counter() | |
| for number, page in enumerate(ocr.pages(source, page_numbers(args.pages), args.image_dpi)): | |
| parts.append(page.markdown()) | |
| record.append({"regiones": [{"clase": block.kind, "caja": [round(value) for value in block.box], "texto": block.text, | |
| "seguridad": round(block.score, 3)} | |
| for block in page.blocks]}) | |
| print(f"{source.name}: página leída {number + 1}, {len(page.blocks)} regiones, {time.perf_counter() - began:.1f} s", flush=True) | |
| began = time.perf_counter() | |
| (args.out / f"{source.stem}.md").write_text("\n".join(part for part in parts if part), encoding="utf-8") | |
| if args.json: | |
| (args.out / f"{source.stem}.json").write_text(json.dumps(record, ensure_ascii=False, indent=1), encoding="utf-8") | |
| if __name__ == "__main__": | |
| main() | |