File size: 6,286 Bytes
34d78c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""CLI silnika OCR.



Komendy:

  ocr recognize <image> [--lang pl|en] [--json] [--correct] ...

  ocr check-fabryka [--fabryka-model MODEL]

"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from .config import OcrConfig
from .pipeline import OcrEngine
from .postprocess import TextCorrector


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="ocr", description="Silnik OCR (CRAFT + TrOCR)")
    sub = parser.add_subparsers(dest="command", required=True)

    # recognize
    rec = sub.add_parser("recognize", help="Rozpoznaj tekst z obrazu lub PDF")
    rec.add_argument("image", type=Path, help="艢cie偶ka do obrazu lub PDF")
    rec.add_argument("--lang", choices=["pl", "en"], default=None, help="Wymu艣 j臋zyk")
    rec.add_argument("--json", action="store_true", help="Wyj艣cie JSON")
    rec.add_argument("--no-deskew", action="store_true", help="Pomi艅 korekt臋 pochylenia")
    rec.add_argument("--pages", default=None,
                     help="Zakres stron PDF, np. '1-3,5' (domy艣lnie: wszystkie)")
    rec.add_argument("--dpi", type=int, default=300, help="DPI renderowania stron PDF")
    rec.add_argument("--correct", action=argparse.BooleanOptionalAction, default=None,
                     help="Korekta tekstu przez Fabryka API (wymaga FABRYKA_API_KEY)")
    rec.add_argument("--correct-low-only", action=argparse.BooleanOptionalAction, default=None,
                     help="Korekta tylko linii z confidence < --confidence-threshold")
    rec.add_argument("--confidence-threshold", type=float, default=None,
                     help="Pr贸g niskiego confidence (flaga w JSON / selektywna korekta)")
    rec.add_argument("--fabryka-model", default=None,
                     help="Model Fabryka do korekty (domy艣lnie: bielik-11b-v3)")
    rec.add_argument("--device", choices=["auto", "cpu", "cuda"], default=None)
    rec.add_argument("--backend", choices=["trocr", "paddlevl", "kraken", "unlimitedocr", "auto"], default=None,
                     help="Backend: trocr, paddlevl, kraken, unlimitedocr (pe艂na strona, CUDA), auto")
    rec.add_argument("--max-new-tokens", type=int, default=None,
                     help="Limit wygenerowanych token贸w Unlimited-OCR (domy艣lnie 4096)")
    # Jev (TypeSafe AI)
    rec.add_argument("--jev-route", action=argparse.BooleanOptionalAction, default=None,
                     help="Jev routing backendu (wymaga TYPESAFE_API_KEY)")
    rec.add_argument("--jev-score", action=argparse.BooleanOptionalAction, default=None,
                     help="Jev scoring jako艣ci linii OCR")
    rec.add_argument("--jev-validate", action=argparse.BooleanOptionalAction, default=None,
                     help="Jev walidacja korekty Fabryka")
    rec.add_argument("--jev-quality-threshold", type=float, default=None,
                     help="Pr贸g jako艣ci Jev (0-2) do flagowania linii")

    # check-fabryka
    chk = sub.add_parser("check-fabryka", help="Sprawd藕 po艂膮czenie z Fabryka API")
    chk.add_argument("--fabryka-model", default=None,
                     help="Model do przetestowania (domy艣lnie: bielik-11b-v3)")
    return parser


def _cmd_recognize(args) -> int:
    if not args.image.exists():
        print(f"Plik nie istnieje: {args.image}", file=sys.stderr)
        return 2
    config = OcrConfig.from_env()
    for arg, field in (("lang", "force_language"), ("correct", "correct_text"),
                       ("correct_low_only", "correct_low_confidence_only"),
                       ("confidence_threshold", "confidence_threshold"),
                       ("fabryka_model", "fabryka_model"), ("device", "device"),
                       ("backend", "recognizer_backend"),
                       ("max_new_tokens", "unlimited_max_new_tokens"),
                       ("jev_route", "jev_route_backend"),
                       ("jev_score", "jev_score_lines"),
                       ("jev_validate", "jev_validate_correction"),
                       ("jev_quality_threshold", "jev_quality_threshold")):
        value = getattr(args, arg)
        if value is not None:
            setattr(config, field, value)
    if args.no_deskew:
        config.deskew = False
    if args.correct_low_only:
        config.correct_text = True
    if config.correct_low_confidence_only and config.confidence_threshold <= 0:
        raise ValueError("Selective correction requires confidence-threshold > 0")
    with OcrEngine(config) as engine:
        if args.image.suffix.lower() == ".pdf":
            results = engine.recognize_pdf(args.image, pages=args.pages, dpi=args.dpi)
        else:
            results = [engine.recognize(args.image)]

    if args.json:
        out = [r.to_dict(config.confidence_threshold) for r in results]
        print(json.dumps(out[0] if len(out) == 1 else out, ensure_ascii=False, indent=2))
    else:
        for i, r in enumerate(results):
            if len(results) > 1:
                print(f"--- strona {r.page_number or i + 1} ---")
            print(r.text)
    return 0


def _cmd_check_fabryka(args) -> int:
    config = OcrConfig.from_env()
    if args.fabryka_model is not None:
        config.fabryka_model = args.fabryka_model
    corrector = TextCorrector(config)

    print(f"Endpoint: {corrector.base_url}")
    print(f"Model:    {config.fabryka_model}")
    key = corrector.api_key
    if key:
        # poka偶 tylko prefix ze wzgl臋d贸w bezpiecze艅stwa
        print(f"Klucz:    {key[:12]}...{key[-4:]} (d艂ugo艣膰: {len(key)})")
    else:
        print("Klucz:    BRAK (ustaw FABRYKA_API_KEY)")
        return 1

    print()
    ok, msg = corrector.check_connection()
    if ok:
        print(f"[OK] {msg}")
        return 0
    else:
        print(f"[FAIL] {msg}")
        return 1


def main(argv: list[str] | None = None) -> int:
    parser = _build_parser()
    args = parser.parse_args(argv)

    if args.command == "recognize":
        return _cmd_recognize(args)
    if args.command == "check-fabryka":
        return _cmd_check_fabryka(args)
    return 1


if __name__ == "__main__":
    raise SystemExit(main())