ocris 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ocris/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """ocris: Zero-cv2 multilingual 360-degree & curved OCR on NetCL."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .api import OCR, Ocris
6
+ from .hub import download_models, get_cache_dir
7
+ from .layout import OCRResult, TextBox, TextLine
8
+
9
+ __all__ = [
10
+ "__version__",
11
+ "Ocris",
12
+ "OCR",
13
+ "OCRResult",
14
+ "TextLine",
15
+ "TextBox",
16
+ "download_models",
17
+ "get_cache_dir",
18
+ ]
ocris/api.py ADDED
@@ -0,0 +1,139 @@
1
+ """Ergonomic public Python API for Ocris."""
2
+ import io
3
+ from pathlib import Path
4
+ from typing import Iterable
5
+
6
+ import numpy as np
7
+ from PIL import Image
8
+ from netcl.core.device import manager
9
+
10
+ from .hub import ensure_model
11
+ from .layout import OCRResult
12
+ from .pipeline import OmniOCR
13
+
14
+ ImageInput = str | Path | bytes | bytearray | Image.Image | np.ndarray
15
+
16
+
17
+ def _coerce_rgb(image: ImageInput) -> np.ndarray:
18
+ """Convert path, bytes, PIL.Image, or NumPy array into contiguous RGB uint8 (H, W, 3)."""
19
+ if isinstance(image, (str, Path)):
20
+ with Image.open(image) as im:
21
+ return np.asarray(im.convert("RGB"), dtype=np.uint8)
22
+ if isinstance(image, (bytes, bytearray)):
23
+ with Image.open(io.BytesIO(image)) as im:
24
+ return np.asarray(im.convert("RGB"), dtype=np.uint8)
25
+ if isinstance(image, Image.Image):
26
+ return np.asarray(image.convert("RGB"), dtype=np.uint8)
27
+ if isinstance(image, np.ndarray):
28
+ arr = image
29
+ if arr.ndim == 2:
30
+ arr = np.stack([arr, arr, arr], axis=-1)
31
+ elif arr.ndim == 3 and arr.shape[2] == 4:
32
+ arr = arr[:, :, :3]
33
+ elif arr.ndim != 3 or arr.shape[2] != 3:
34
+ raise ValueError(f"Expected 2D/RGB/RGBA array, got shape {arr.shape}")
35
+ return np.ascontiguousarray(arr, dtype=np.uint8)
36
+ raise TypeError(
37
+ f"Unsupported image type {type(image).__name__}; expected str, Path, bytes, PIL.Image.Image, or np.ndarray"
38
+ )
39
+
40
+
41
+ def _resolve_queue(backend: str):
42
+ if backend == "auto":
43
+ return manager.default().queue
44
+ if backend in ("vulkan", "opencl", "cpu"):
45
+ manager.set_default_backend(backend)
46
+ return manager.default(backend).queue
47
+ raise ValueError(f"Unknown backend {backend!r}; expected 'auto', 'vulkan', 'opencl', or 'cpu'")
48
+
49
+
50
+ class Ocris:
51
+ """Zero-cv2 multilingual 360-degree & curved OCR engine on NetCL.
52
+
53
+ Models are downloaded lazily from GitHub on the first inference call and cached locally.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ *,
59
+ mode: str = "hybrid",
60
+ backend: str = "auto",
61
+ max_side: int = 1024,
62
+ det_thresh: float = 0.45,
63
+ kernel_thresh: float = 0.45,
64
+ min_det_score: float = 0.50,
65
+ ar_threshold: float = -0.35,
66
+ det_model: str | Path | None = None,
67
+ rec_model: str | Path | None = None,
68
+ cache_dir: str | Path | None = None,
69
+ base_url: str | None = None,
70
+ auto_download: bool = True,
71
+ verify_sha256: bool = True,
72
+ preload: bool = False,
73
+ queue=None,
74
+ ):
75
+ self.mode = mode
76
+ self.backend = backend
77
+ self.max_side = int(max_side)
78
+ self.det_thresh = float(det_thresh)
79
+ self.kernel_thresh = float(kernel_thresh)
80
+ self.min_det_score = float(min_det_score)
81
+ self.ar_threshold = float(ar_threshold)
82
+ self.det_model = det_model
83
+ self.rec_model = rec_model
84
+ self.cache_dir = cache_dir
85
+ self.base_url = base_url
86
+ self.auto_download = auto_download
87
+ self.verify_sha256 = verify_sha256
88
+ self._queue = queue
89
+ self._engine: OmniOCR | None = None
90
+ if preload:
91
+ self._ensure_loaded()
92
+
93
+ def _ensure_loaded(self) -> OmniOCR:
94
+ if self._engine is None:
95
+ det_path = ensure_model(
96
+ "det",
97
+ explicit_path=self.det_model,
98
+ cache_dir=self.cache_dir,
99
+ base_url=self.base_url,
100
+ auto_download=self.auto_download,
101
+ verify_sha256=self.verify_sha256,
102
+ )
103
+ rec_path = ensure_model(
104
+ "rec",
105
+ explicit_path=self.rec_model,
106
+ cache_dir=self.cache_dir,
107
+ base_url=self.base_url,
108
+ auto_download=self.auto_download,
109
+ verify_sha256=self.verify_sha256,
110
+ )
111
+ q = self._queue if self._queue is not None else _resolve_queue(self.backend)
112
+ self._engine = OmniOCR(
113
+ det_path,
114
+ rec_path,
115
+ mode=self.mode,
116
+ max_side=self.max_side,
117
+ det_thresh=self.det_thresh,
118
+ kernel_thresh=self.kernel_thresh,
119
+ min_det_score=self.min_det_score,
120
+ ar_threshold=self.ar_threshold,
121
+ queue=q,
122
+ )
123
+ return self._engine
124
+
125
+ def read(self, image: ImageInput) -> OCRResult:
126
+ """Run OCR on a single image (path, bytes, PIL Image, or RGB NumPy array)."""
127
+ rgb = _coerce_rgb(image)
128
+ engine = self._ensure_loaded()
129
+ return engine(rgb)
130
+
131
+ def read_batch(self, images: Iterable[ImageInput]) -> list[OCRResult]:
132
+ """Run OCR sequentially over an iterable of images."""
133
+ return [self.read(im) for im in images]
134
+
135
+ def __call__(self, image: ImageInput) -> OCRResult:
136
+ return self.read(image)
137
+
138
+
139
+ OCR = Ocris
ocris/cli.py ADDED
@@ -0,0 +1,34 @@
1
+ """Command-line interface for Ocris."""
2
+ import argparse
3
+ from pathlib import Path
4
+
5
+ from .api import Ocris
6
+ from .hub import download_models
7
+
8
+
9
+ def main() -> None:
10
+ p = argparse.ArgumentParser(prog="ocris", description="Multilingual 360-degree & curved OCR on NetCL.")
11
+ p.add_argument("image", nargs="?", type=Path, help="Path to an input image")
12
+ p.add_argument("--mode", default="hybrid", choices=("fast", "hybrid", "accurate"), help="Decoding mode")
13
+ p.add_argument("--backend", default="auto", choices=("auto", "vulkan", "opencl", "cpu"), help="Compute backend")
14
+ p.add_argument("--max-side", type=int, default=1024, help="Maximum detector input side length")
15
+ p.add_argument("--json", action="store_true", help="Output structured JSON instead of plain text")
16
+ p.add_argument("--download-only", action="store_true", help="Download model weights to cache and exit")
17
+ p.add_argument("--cache-dir", type=Path, default=None, help="Override local model cache directory")
18
+ args = p.parse_args()
19
+
20
+ if args.download_only:
21
+ det, rec = download_models(cache_dir=args.cache_dir)
22
+ print(f"Models ready:\n det: {det}\n rec: {rec}")
23
+ return
24
+
25
+ if args.image is None:
26
+ p.error("the following arguments are required: image (unless --download-only is used)")
27
+
28
+ ocr = Ocris(mode=args.mode, backend=args.backend, max_side=args.max_side, cache_dir=args.cache_dir)
29
+ res = ocr(args.image)
30
+ print(res.to_json() if args.json else res.text)
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()