anyconv-ocr-basic 1.0.1__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.
- anyconv_ocr_basic/__init__.py +5 -0
- anyconv_ocr_basic/anyconv.module.yaml +71 -0
- anyconv_ocr_basic/module.py +213 -0
- anyconv_ocr_basic-1.0.1.dist-info/METADATA +53 -0
- anyconv_ocr_basic-1.0.1.dist-info/RECORD +9 -0
- anyconv_ocr_basic-1.0.1.dist-info/WHEEL +5 -0
- anyconv_ocr_basic-1.0.1.dist-info/entry_points.txt +2 -0
- anyconv_ocr_basic-1.0.1.dist-info/licenses/LICENSE +21 -0
- anyconv_ocr_basic-1.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
spec: "^1.0"
|
|
2
|
+
api: ">=1.0,<2.0"
|
|
3
|
+
id: com.gitlab.raceozr.ocr-basic
|
|
4
|
+
version: 1.0.1
|
|
5
|
+
title:
|
|
6
|
+
en: "Basic OCR"
|
|
7
|
+
ru: "Базовый OCR"
|
|
8
|
+
description:
|
|
9
|
+
en: "Recognize text in images and PDF files with Tesseract."
|
|
10
|
+
ru: "Распознавание текста в изображениях и PDF через Tesseract."
|
|
11
|
+
license: MIT
|
|
12
|
+
homepage: "https://gitlab.com/raceozr/anyconv-modules"
|
|
13
|
+
keywords: [ocr, tesseract, pdf, image, text]
|
|
14
|
+
stability: stable
|
|
15
|
+
entrypoint:
|
|
16
|
+
kind: python
|
|
17
|
+
target: "anyconv_ocr_basic.module:OcrModule"
|
|
18
|
+
config:
|
|
19
|
+
schema:
|
|
20
|
+
type: object
|
|
21
|
+
additionalProperties: false
|
|
22
|
+
properties:
|
|
23
|
+
tesseract_path: {type: string}
|
|
24
|
+
tessdata_dir: {type: string}
|
|
25
|
+
requires:
|
|
26
|
+
python: ">=3.10"
|
|
27
|
+
packages:
|
|
28
|
+
- "anyconv-core>=1.0,<2.0"
|
|
29
|
+
- "Pillow>=10"
|
|
30
|
+
- "pypdfium2>=4.30,<5"
|
|
31
|
+
|
|
32
|
+
capabilities:
|
|
33
|
+
- id: ocr-extract
|
|
34
|
+
op: convert
|
|
35
|
+
since: 1.0.0
|
|
36
|
+
routing: auto
|
|
37
|
+
fidelity: lossy
|
|
38
|
+
determinism: deterministic
|
|
39
|
+
cache: {reuse: true}
|
|
40
|
+
cost: {weight: 30}
|
|
41
|
+
limits: {timeout_s: 600, max_input_bytes: 104857600, max_outputs: 1}
|
|
42
|
+
inputs:
|
|
43
|
+
- name: source
|
|
44
|
+
cardinality: one
|
|
45
|
+
accept:
|
|
46
|
+
formats:
|
|
47
|
+
- image:jpeg
|
|
48
|
+
- image:png
|
|
49
|
+
- image:webp
|
|
50
|
+
- image:avif
|
|
51
|
+
- image:heic
|
|
52
|
+
- image:gif
|
|
53
|
+
- image:bmp
|
|
54
|
+
- image:tiff
|
|
55
|
+
- image:ico
|
|
56
|
+
- image:psd
|
|
57
|
+
- image:mpo
|
|
58
|
+
- doc:pdf
|
|
59
|
+
outputs:
|
|
60
|
+
- name: result
|
|
61
|
+
cardinality: one
|
|
62
|
+
kind: data
|
|
63
|
+
produce:
|
|
64
|
+
formats: [text:plain]
|
|
65
|
+
settings:
|
|
66
|
+
type: object
|
|
67
|
+
additionalProperties: false
|
|
68
|
+
properties:
|
|
69
|
+
languages: {type: string, default: "rus+eng", maxLength: 100}
|
|
70
|
+
psm: {type: integer, minimum: 0, maximum: 13, default: 6}
|
|
71
|
+
dpi: {type: integer, minimum: 150, maximum: 400, default: 200}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Tesseract OCR module for AnyConv."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
from importlib.resources import files
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import yaml
|
|
14
|
+
from anyconv.sdk import Availability, CheckContext, Context, OpResult, Request
|
|
15
|
+
from anyconv.sdk.errors import CorruptInput, ModuleUnavailable, OpNotImplemented
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
import pypdfium2 as pdfium
|
|
19
|
+
except ImportError: # pragma: no cover
|
|
20
|
+
pdfium = None
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
from PIL import Image
|
|
24
|
+
except ImportError: # pragma: no cover
|
|
25
|
+
Image = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class OcrModule:
|
|
29
|
+
@staticmethod
|
|
30
|
+
def manifest() -> dict[str, Any]:
|
|
31
|
+
return yaml.safe_load(
|
|
32
|
+
files("anyconv_ocr_basic")
|
|
33
|
+
.joinpath("anyconv.module.yaml")
|
|
34
|
+
.read_text("utf-8")
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
def check(self, ctx: CheckContext) -> Availability:
|
|
38
|
+
missing: list[str] = []
|
|
39
|
+
if _tesseract(ctx.config) is None:
|
|
40
|
+
missing.append("binary:tesseract")
|
|
41
|
+
if Image is None:
|
|
42
|
+
missing.append("package:Pillow")
|
|
43
|
+
if pdfium is None:
|
|
44
|
+
missing.append("package:pypdfium2")
|
|
45
|
+
if missing:
|
|
46
|
+
return Availability(status="unavailable", missing=missing)
|
|
47
|
+
return Availability(status="ready")
|
|
48
|
+
|
|
49
|
+
def convert(self, req: Request, ctx: Context) -> OpResult:
|
|
50
|
+
if req.capability_id != "ocr-extract":
|
|
51
|
+
raise OpNotImplemented(
|
|
52
|
+
f"Неизвестная возможность {req.capability_id!r}",
|
|
53
|
+
details={"capability": req.capability_id},
|
|
54
|
+
)
|
|
55
|
+
source = req.inputs["source"][0]
|
|
56
|
+
source_format = source.typeref.format if source.typeref is not None else None
|
|
57
|
+
if source_format not in _INPUT_FORMATS:
|
|
58
|
+
raise CorruptInput(
|
|
59
|
+
f"OCR не поддерживает {source_format!r}",
|
|
60
|
+
details={"format": source_format},
|
|
61
|
+
)
|
|
62
|
+
languages = str(ctx.settings.get("languages", "rus+eng"))
|
|
63
|
+
psm = int(ctx.settings.get("psm", 6))
|
|
64
|
+
dpi = int(ctx.settings.get("dpi", 200))
|
|
65
|
+
if source_format == "doc:pdf":
|
|
66
|
+
text, pages = _ocr_pdf(ctx, source, languages, psm, dpi)
|
|
67
|
+
else:
|
|
68
|
+
text, pages = _ocr_image(ctx, source, languages, psm), 1
|
|
69
|
+
output = ctx.out_text("result", text, encoding="utf-8")
|
|
70
|
+
provenance = {
|
|
71
|
+
"engine": "tesseract",
|
|
72
|
+
"languages": languages,
|
|
73
|
+
"psm": psm,
|
|
74
|
+
"pages": pages,
|
|
75
|
+
"source_format": source_format,
|
|
76
|
+
}
|
|
77
|
+
ctx.emit_provenance(provenance)
|
|
78
|
+
return OpResult(outputs={"result": output}, provenance=provenance)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _tesseract(config: Any) -> str | None:
|
|
82
|
+
configured = config.get("tesseract_path") if hasattr(config, "get") else None
|
|
83
|
+
candidates = [
|
|
84
|
+
configured,
|
|
85
|
+
os.environ.get("TESSERACT_CMD"),
|
|
86
|
+
shutil.which("tesseract"),
|
|
87
|
+
r"C:\Program Files\Tesseract-OCR\tesseract.exe",
|
|
88
|
+
]
|
|
89
|
+
for candidate in candidates:
|
|
90
|
+
if candidate and Path(str(candidate)).is_file():
|
|
91
|
+
return str(candidate)
|
|
92
|
+
if candidate:
|
|
93
|
+
found = shutil.which(str(candidate))
|
|
94
|
+
if found:
|
|
95
|
+
return found
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _tessdata(config: Any) -> str | None:
|
|
100
|
+
configured = config.get("tessdata_dir") if hasattr(config, "get") else None
|
|
101
|
+
if configured and Path(str(configured)).is_dir():
|
|
102
|
+
return str(configured)
|
|
103
|
+
env = os.environ.get("TESSDATA_PREFIX")
|
|
104
|
+
if env and Path(env).is_dir():
|
|
105
|
+
return env
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _ocr(ctx: Context, config: Any, image_path: Path, languages: str, psm: int) -> str:
|
|
110
|
+
tesseract = _tesseract(config)
|
|
111
|
+
if tesseract is None:
|
|
112
|
+
raise ModuleUnavailable(
|
|
113
|
+
"Tesseract не найден",
|
|
114
|
+
details={"tesseract_path": "PATH / TESSERACT_CMD"},
|
|
115
|
+
)
|
|
116
|
+
args = [
|
|
117
|
+
tesseract,
|
|
118
|
+
str(image_path),
|
|
119
|
+
"stdout",
|
|
120
|
+
"-l",
|
|
121
|
+
languages,
|
|
122
|
+
"--psm",
|
|
123
|
+
str(psm),
|
|
124
|
+
]
|
|
125
|
+
tessdata = _tessdata(config)
|
|
126
|
+
if tessdata:
|
|
127
|
+
args += ["--tessdata-dir", tessdata]
|
|
128
|
+
try:
|
|
129
|
+
completed = subprocess.run(
|
|
130
|
+
args,
|
|
131
|
+
check=False,
|
|
132
|
+
capture_output=True,
|
|
133
|
+
text=True,
|
|
134
|
+
encoding="utf-8",
|
|
135
|
+
errors="replace",
|
|
136
|
+
timeout=ctx.limits.timeout_s,
|
|
137
|
+
)
|
|
138
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
139
|
+
raise CorruptInput("Не удалось запустить Tesseract") from exc
|
|
140
|
+
if completed.returncode != 0:
|
|
141
|
+
raise CorruptInput(
|
|
142
|
+
"Tesseract не смог распознать изображение",
|
|
143
|
+
details={"stderr": completed.stderr.strip()[:500]},
|
|
144
|
+
)
|
|
145
|
+
return completed.stdout.strip()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _ocr_image(ctx: Context, source: Any, languages: str, psm: int) -> str:
|
|
149
|
+
data = ctx.read_input("source")
|
|
150
|
+
try:
|
|
151
|
+
image = Image.open(io.BytesIO(data))
|
|
152
|
+
image.seek(0)
|
|
153
|
+
if image.mode not in ("RGB", "L"):
|
|
154
|
+
image = image.convert("RGB")
|
|
155
|
+
path = ctx.tmp().with_suffix(".png")
|
|
156
|
+
image.save(path, format="PNG")
|
|
157
|
+
except (OSError, ValueError) as exc:
|
|
158
|
+
raise CorruptInput("Не удалось открыть изображение для OCR") from exc
|
|
159
|
+
return _ocr(ctx, ctx.config, path, languages, psm)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _ocr_pdf(
|
|
163
|
+
ctx: Context,
|
|
164
|
+
source: Any,
|
|
165
|
+
languages: str,
|
|
166
|
+
psm: int,
|
|
167
|
+
dpi: int,
|
|
168
|
+
) -> tuple[str, int]:
|
|
169
|
+
if pdfium is None: # pragma: no cover
|
|
170
|
+
raise ModuleUnavailable("Для OCR PDF требуется pypdfium2")
|
|
171
|
+
data = ctx.read_input("source")
|
|
172
|
+
try:
|
|
173
|
+
document = pdfium.PdfDocument(io.BytesIO(data))
|
|
174
|
+
except Exception as exc:
|
|
175
|
+
raise CorruptInput("Не удалось открыть PDF для OCR") from exc
|
|
176
|
+
pages: list[str] = []
|
|
177
|
+
try:
|
|
178
|
+
count = len(document)
|
|
179
|
+
limit = ctx.limits.max_outputs or 512
|
|
180
|
+
if count > limit:
|
|
181
|
+
raise CorruptInput(
|
|
182
|
+
f"Слишком много страниц для OCR: {count}, максимум {limit}",
|
|
183
|
+
details={"pages": count, "limit": limit},
|
|
184
|
+
)
|
|
185
|
+
for index in range(count):
|
|
186
|
+
ctx.check_cancel()
|
|
187
|
+
page = document[index]
|
|
188
|
+
image = page.render(scale=dpi / 72).to_pil()
|
|
189
|
+
path = ctx.tmp().with_suffix(".png")
|
|
190
|
+
image.save(path, format="PNG")
|
|
191
|
+
pages.append(_ocr(ctx, ctx.config, path, languages, psm))
|
|
192
|
+
finally:
|
|
193
|
+
document.close()
|
|
194
|
+
return "\n\f\n".join(pages).strip() + "\n", len(pages)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
_INPUT_FORMATS = {
|
|
198
|
+
"image:jpeg",
|
|
199
|
+
"image:png",
|
|
200
|
+
"image:webp",
|
|
201
|
+
"image:avif",
|
|
202
|
+
"image:heic",
|
|
203
|
+
"image:gif",
|
|
204
|
+
"image:bmp",
|
|
205
|
+
"image:tiff",
|
|
206
|
+
"image:ico",
|
|
207
|
+
"image:psd",
|
|
208
|
+
"image:mpo",
|
|
209
|
+
"doc:pdf",
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
__all__ = ["OcrModule"]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: anyconv-ocr-basic
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: AnyConv OCR module based on Tesseract
|
|
5
|
+
Author: AnyConv
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: anyconv,ocr,tesseract,pdf,text
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: anyconv-core<2.0,>=1.0
|
|
12
|
+
Requires-Dist: Pillow>=10
|
|
13
|
+
Requires-Dist: pypdfium2<5,>=4.30
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
16
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# anyconv-ocr-basic
|
|
20
|
+
|
|
21
|
+
OCR изображений и PDF через Tesseract.
|
|
22
|
+
|
|
23
|
+
## Возможности
|
|
24
|
+
|
|
25
|
+
- **`ocr-extract`** — изображение или PDF → `text:plain`.
|
|
26
|
+
- Языки: `rus+eng` по умолчанию; PDF рендерится постранично через `pypdfium2`.
|
|
27
|
+
- Настройки: `languages`, `psm`, `dpi`.
|
|
28
|
+
|
|
29
|
+
## Требования
|
|
30
|
+
|
|
31
|
+
Установленный Tesseract 5 и языковые данные:
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
tesseract
|
|
35
|
+
eng.traineddata
|
|
36
|
+
rus.traineddata
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Путь задаётся в конфигурации модуля (`tesseract_path`, `tessdata_dir`) или через
|
|
40
|
+
`TESSERACT_CMD`/`TESSDATA_PREFIX`.
|
|
41
|
+
|
|
42
|
+
## Установка
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install "anyconv-core[all] @ git+https://gitlab.com/raceozr/anyconv-core.git@v1.0.0"
|
|
46
|
+
pip install "git+https://gitlab.com/raceozr/anyconv-modules.git@v1.0.1#subdirectory=modules/ocr-basic"
|
|
47
|
+
# ?????????? ?? checkout anyconv-modules
|
|
48
|
+
cd modules/ocr-basic
|
|
49
|
+
pip install -e ".[dev]"
|
|
50
|
+
pytest
|
|
51
|
+
anyconv module validate .
|
|
52
|
+
anyconv module test .
|
|
53
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
anyconv_ocr_basic/__init__.py,sha256=4bIIdd2MV81iHHVK1tfOU85pzgzx7PFeMdnfVO5da0c,92
|
|
2
|
+
anyconv_ocr_basic/anyconv.module.yaml,sha256=2WdjUUl1YHkxWkhwoe3y90eKb__96VS6z7iYdwpVm-w,1851
|
|
3
|
+
anyconv_ocr_basic/module.py,sha256=QXnIbDaZkx-RKSGpyNspd2zcWFiXT5yt3wB6qG4-k6o,6781
|
|
4
|
+
anyconv_ocr_basic-1.0.1.dist-info/licenses/LICENSE,sha256=Wahb1xasoYXZBxdcuh2ETI6eaWi4JazPi9yhb0eFBxU,1077
|
|
5
|
+
anyconv_ocr_basic-1.0.1.dist-info/METADATA,sha256=WXqdG6NNF0I3vDBc606-0llkEUq_sPwj8h-icXzdyu8,1528
|
|
6
|
+
anyconv_ocr_basic-1.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
anyconv_ocr_basic-1.0.1.dist-info/entry_points.txt,sha256=3y6aVDjBhkV3VIWedRm9yhgqtiovig8mSMp6x7PywlU,65
|
|
8
|
+
anyconv_ocr_basic-1.0.1.dist-info/top_level.txt,sha256=KmqwSzvDTXxsOiZMRjvK53Pcs2AAIWoIdmDriZS6MAU,18
|
|
9
|
+
anyconv_ocr_basic-1.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AnyConv contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
anyconv_ocr_basic
|