meikiocr 0.1.3__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.
- meikiocr/__init__.py +5 -0
- meikiocr/ocr.py +281 -0
- meikiocr-0.1.3.dist-info/METADATA +148 -0
- meikiocr-0.1.3.dist-info/RECORD +7 -0
- meikiocr-0.1.3.dist-info/WHEEL +5 -0
- meikiocr-0.1.3.dist-info/licenses/LICENSE +202 -0
- meikiocr-0.1.3.dist-info/top_level.txt +1 -0
meikiocr/__init__.py
ADDED
meikiocr/ocr.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
# ./meikiocr/ocr.py
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import cv2
|
|
5
|
+
import numpy as np
|
|
6
|
+
from huggingface_hub import hf_hub_download
|
|
7
|
+
import onnxruntime as ort
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
logger.addHandler(logging.NullHandler())
|
|
12
|
+
|
|
13
|
+
# --- configuration ---
|
|
14
|
+
DET_MODEL_REPO = "rtr46/meiki.text.detect.v0"
|
|
15
|
+
DET_MODEL_NAME = "meiki.text.detect.v0.1.960x544.onnx"
|
|
16
|
+
REC_MODEL_REPO = "rtr46/meiki.txt.recognition.v0"
|
|
17
|
+
REC_MODEL_NAME = "meiki.text.rec.v0.960x32.onnx"
|
|
18
|
+
|
|
19
|
+
INPUT_DET_WIDTH = 960
|
|
20
|
+
INPUT_DET_HEIGHT = 544
|
|
21
|
+
INPUT_REC_HEIGHT = 32
|
|
22
|
+
INPUT_REC_WIDTH = 960
|
|
23
|
+
|
|
24
|
+
X_OVERLAP_THRESHOLD = 0.3
|
|
25
|
+
EPSILON = 1e-6
|
|
26
|
+
|
|
27
|
+
def _get_model_path(repo_id, filename):
|
|
28
|
+
"""Downloads a model from the hugging face hub if not cached and returns the path."""
|
|
29
|
+
try:
|
|
30
|
+
return hf_hub_download(repo_id=repo_id, filename=filename)
|
|
31
|
+
except Exception as e:
|
|
32
|
+
print(f"Error downloading model {filename}: {e}")
|
|
33
|
+
raise
|
|
34
|
+
|
|
35
|
+
class MeikiOCR:
|
|
36
|
+
def __init__(self, provider=None, max_batch_size=8):
|
|
37
|
+
"""
|
|
38
|
+
Initializes the meikiocr pipeline by loading detection and recognition models.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
provider (str, optional): The ONNX Runtime execution provider to use.
|
|
42
|
+
Defaults to None, which lets ONNX Runtime choose.
|
|
43
|
+
Recommended: 'CUDAExecutionProvider' for NVIDIA GPUs,
|
|
44
|
+
'CPUExecutionProvider' for CPU.
|
|
45
|
+
max_batch_size (int, optional): The maximum batch size for the recognition model
|
|
46
|
+
to control memory usage. Defaults to 8.
|
|
47
|
+
"""
|
|
48
|
+
ort.set_default_logger_severity(3)
|
|
49
|
+
|
|
50
|
+
det_model_path = _get_model_path(DET_MODEL_REPO, DET_MODEL_NAME)
|
|
51
|
+
rec_model_path = _get_model_path(REC_MODEL_REPO, REC_MODEL_NAME)
|
|
52
|
+
|
|
53
|
+
available_providers = ort.get_available_providers()
|
|
54
|
+
if provider and provider in available_providers:
|
|
55
|
+
chosen_providers = [provider]
|
|
56
|
+
elif 'CUDAExecutionProvider' in available_providers:
|
|
57
|
+
chosen_providers = ['CUDAExecutionProvider']
|
|
58
|
+
elif 'CPUExecutionProvider' in available_providers:
|
|
59
|
+
chosen_providers = ['CPUExecutionProvider']
|
|
60
|
+
else:
|
|
61
|
+
chosen_providers = available_providers
|
|
62
|
+
|
|
63
|
+
self.det_session = ort.InferenceSession(det_model_path, providers=chosen_providers)
|
|
64
|
+
self.rec_session = ort.InferenceSession(rec_model_path, providers=chosen_providers)
|
|
65
|
+
|
|
66
|
+
self.active_provider = self.det_session.get_providers()[0]
|
|
67
|
+
self.max_batch_size = max_batch_size
|
|
68
|
+
logger.info(f"meikiocr running on: {self.active_provider}; max_batch_size = {self.max_batch_size}")
|
|
69
|
+
|
|
70
|
+
def run_ocr(self, image, det_threshold=0.5, rec_threshold=0.1):
|
|
71
|
+
"""
|
|
72
|
+
Runs the full OCR pipeline on a given image.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
image (np.ndarray): The input image in OpenCV format (BGR, HxWxC).
|
|
76
|
+
det_threshold (float): Confidence threshold for text detection.
|
|
77
|
+
rec_threshold (float): Confidence threshold for character recognition.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
list[dict]: A list of dictionaries, where each dictionary contains the
|
|
81
|
+
recognized 'text' and a list of 'chars' with their bounding
|
|
82
|
+
boxes and confidence scores for a detected text line.
|
|
83
|
+
"""
|
|
84
|
+
text_boxes = self.run_detection(image, det_threshold)
|
|
85
|
+
|
|
86
|
+
if not text_boxes:
|
|
87
|
+
return []
|
|
88
|
+
|
|
89
|
+
rec_batch, valid_indices, crop_metadata = self._preprocess_for_recognition(image, text_boxes)
|
|
90
|
+
|
|
91
|
+
if rec_batch is None:
|
|
92
|
+
return [{'text': '', 'chars': []} for _ in range(len(text_boxes))]
|
|
93
|
+
|
|
94
|
+
# Process the recognition in smaller batches to control memory usage
|
|
95
|
+
all_labels_chunks, all_boxes_chunks, all_scores_chunks = [], [], []
|
|
96
|
+
for i in range(0, len(rec_batch), self.max_batch_size):
|
|
97
|
+
batch_chunk = rec_batch[i:i + self.max_batch_size]
|
|
98
|
+
labels_chunk, boxes_chunk, scores_chunk = self._run_recognition_inference(batch_chunk)
|
|
99
|
+
all_labels_chunks.append(labels_chunk)
|
|
100
|
+
all_boxes_chunks.append(boxes_chunk)
|
|
101
|
+
all_scores_chunks.append(scores_chunk)
|
|
102
|
+
|
|
103
|
+
all_rec_raw = (
|
|
104
|
+
np.concatenate(all_labels_chunks, axis=0),
|
|
105
|
+
np.concatenate(all_boxes_chunks, axis=0),
|
|
106
|
+
np.concatenate(all_scores_chunks, axis=0)
|
|
107
|
+
)
|
|
108
|
+
results = self._postprocess_recognition_results(all_rec_raw, valid_indices, crop_metadata, rec_threshold, len(text_boxes))
|
|
109
|
+
return results
|
|
110
|
+
|
|
111
|
+
def run_detection(self, image, conf_threshold=0.5):
|
|
112
|
+
"""
|
|
113
|
+
Runs only the text detection part of the pipeline.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
image (np.ndarray): The input image in OpenCV format (BGR, HxWxC).
|
|
117
|
+
conf_threshold (float): Confidence threshold for text detection.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
list[dict]: A list of detected text boxes, sorted from top to bottom.
|
|
121
|
+
Each box is a dictionary with 'bbox' and 'conf'.
|
|
122
|
+
"""
|
|
123
|
+
det_input, scale = self._preprocess_for_detection(image)
|
|
124
|
+
det_raw = self._run_detection_inference(det_input, scale)
|
|
125
|
+
text_boxes = self._postprocess_detection_results(det_raw, image, conf_threshold)
|
|
126
|
+
return text_boxes
|
|
127
|
+
|
|
128
|
+
def run_recognition(self, text_line_images, conf_threshold=0.1):
|
|
129
|
+
"""
|
|
130
|
+
Runs only the text recognition part of the pipeline on a batch of text line images.
|
|
131
|
+
Note: This is an advanced method. `run_ocr` is recommended for general use.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
text_line_images (list[np.ndarray]): A list of cropped text line images (BGR, HxWxC).
|
|
135
|
+
conf_threshold (float): Confidence threshold for character recognition.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
list[dict]: A list of recognition results, one for each input image.
|
|
139
|
+
"""
|
|
140
|
+
if not text_line_images:
|
|
141
|
+
return []
|
|
142
|
+
|
|
143
|
+
# Create dummy text_boxes to fit the existing pipeline.
|
|
144
|
+
text_boxes = [{'bbox': [0, 0, img.shape[1], img.shape[0]]} for img in text_line_images]
|
|
145
|
+
|
|
146
|
+
# We need to process each image as if it were a crop from a larger canvas.
|
|
147
|
+
# For simplicity, we process them one by one, though batching is possible with more complex metadata handling.
|
|
148
|
+
results = []
|
|
149
|
+
for i, image in enumerate(text_line_images):
|
|
150
|
+
rec_batch, valid_indices, crop_metadata = self._preprocess_for_recognition(image, [text_boxes[i]])
|
|
151
|
+
if rec_batch is None:
|
|
152
|
+
results.append({'text': '', 'chars': []})
|
|
153
|
+
continue
|
|
154
|
+
rec_raw = self._run_recognition_inference(rec_batch)
|
|
155
|
+
result = self._postprocess_recognition_results(rec_raw, valid_indices, crop_metadata, conf_threshold, 1)
|
|
156
|
+
results.extend(result)
|
|
157
|
+
|
|
158
|
+
return results
|
|
159
|
+
|
|
160
|
+
# --- Internal "private" methods (prefixed with _) ---
|
|
161
|
+
|
|
162
|
+
def _preprocess_for_detection(self, image):
|
|
163
|
+
h_orig, w_orig = image.shape[:2]
|
|
164
|
+
scale = min(INPUT_DET_WIDTH / w_orig, INPUT_DET_HEIGHT / h_orig)
|
|
165
|
+
w_resized, h_resized = int(w_orig * scale), int(h_orig * scale)
|
|
166
|
+
resized = cv2.resize(image, (w_resized, h_resized), interpolation=cv2.INTER_LINEAR)
|
|
167
|
+
normalized_resized = resized.astype(np.float32) / 255.0
|
|
168
|
+
tensor = np.zeros((INPUT_DET_HEIGHT, INPUT_DET_WIDTH, 3), dtype=np.float32)
|
|
169
|
+
tensor[:h_resized, :w_resized] = normalized_resized
|
|
170
|
+
tensor = np.transpose(tensor, (2, 0, 1)) # HWC -> CHW
|
|
171
|
+
tensor = np.expand_dims(tensor, axis=0) # Add batch dimension
|
|
172
|
+
return tensor, scale
|
|
173
|
+
|
|
174
|
+
def _run_detection_inference(self, tensor: np.ndarray, scale):
|
|
175
|
+
inputs = {
|
|
176
|
+
self.det_session.get_inputs()[0].name: tensor,
|
|
177
|
+
self.det_session.get_inputs()[1].name: np.array([[INPUT_DET_WIDTH / scale, INPUT_DET_HEIGHT / scale]], dtype=np.int64)
|
|
178
|
+
}
|
|
179
|
+
return self.det_session.run(None, inputs)
|
|
180
|
+
|
|
181
|
+
def _postprocess_detection_results(self, raw_outputs: list, image, conf_threshold: float):
|
|
182
|
+
h_orig, w_orig = image.shape[:2]
|
|
183
|
+
_, boxes, scores = raw_outputs
|
|
184
|
+
boxes, scores = boxes[0], scores[0]
|
|
185
|
+
confident_boxes = boxes[scores > conf_threshold]
|
|
186
|
+
if confident_boxes.shape[0] == 0:
|
|
187
|
+
return []
|
|
188
|
+
max_bounds = np.array([w_orig, h_orig, w_orig, h_orig])
|
|
189
|
+
clamped_boxes = np.clip(confident_boxes, 0, max_bounds).astype(np.int32)
|
|
190
|
+
text_boxes = [{'bbox': box.tolist()} for box in clamped_boxes]
|
|
191
|
+
text_boxes.sort(key=lambda tb: tb['bbox'][1])
|
|
192
|
+
return text_boxes
|
|
193
|
+
|
|
194
|
+
def _preprocess_for_recognition(self, image, text_boxes):
|
|
195
|
+
tensors, valid_indices, crop_metadata = [], [], []
|
|
196
|
+
for i, tb in enumerate(text_boxes):
|
|
197
|
+
x1, y1, x2, y2 = tb['bbox']
|
|
198
|
+
width, height = x2 - x1, y2 - y1
|
|
199
|
+
if width < height or width <= 0 or height <= 0:
|
|
200
|
+
continue
|
|
201
|
+
|
|
202
|
+
crop = image[y1:y2, x1:x2]
|
|
203
|
+
h, w = crop.shape[:2]
|
|
204
|
+
new_h, new_w = INPUT_REC_HEIGHT, int(round(w * (INPUT_REC_HEIGHT / h)))
|
|
205
|
+
if new_w > INPUT_REC_WIDTH:
|
|
206
|
+
scale = INPUT_REC_WIDTH / new_w
|
|
207
|
+
new_w, new_h = INPUT_REC_WIDTH, int(round(new_h * scale))
|
|
208
|
+
|
|
209
|
+
resized = cv2.resize(crop, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
|
|
210
|
+
pad_w, pad_h = INPUT_REC_WIDTH - new_w, INPUT_REC_HEIGHT - new_h
|
|
211
|
+
padded = np.pad(resized, ((0, pad_h), (0, pad_w), (0, 0)), constant_values=0)
|
|
212
|
+
|
|
213
|
+
tensor = (padded.astype(np.float32) / 255.0).transpose(2, 0, 1)
|
|
214
|
+
tensors.append(tensor)
|
|
215
|
+
valid_indices.append(i)
|
|
216
|
+
crop_metadata.append({'orig_bbox': [x1, y1, x2, y2], 'effective_w': new_w})
|
|
217
|
+
|
|
218
|
+
if not tensors: return None, [], []
|
|
219
|
+
return np.stack(tensors, axis=0), valid_indices, crop_metadata
|
|
220
|
+
|
|
221
|
+
def _run_recognition_inference(self, batch_tensor):
|
|
222
|
+
if batch_tensor is None: return []
|
|
223
|
+
orig_size = np.array([[INPUT_REC_WIDTH, INPUT_REC_HEIGHT]], dtype=np.int64)
|
|
224
|
+
return self.rec_session.run(None, {"images": batch_tensor, "orig_target_sizes": orig_size})
|
|
225
|
+
|
|
226
|
+
def _postprocess_recognition_results(self, raw_rec_outputs, valid_indices, crop_metadata, rec_conf_threshold, num_total_boxes):
|
|
227
|
+
labels_batch, boxes_batch, scores_batch = raw_rec_outputs
|
|
228
|
+
full_results = [{'text': '', 'chars': []} for _ in range(num_total_boxes)]
|
|
229
|
+
|
|
230
|
+
for i, (labels, boxes, scores) in enumerate(zip(labels_batch, boxes_batch, scores_batch)):
|
|
231
|
+
meta = crop_metadata[i]
|
|
232
|
+
gx1, gy1, gx2, gy2 = meta['orig_bbox']
|
|
233
|
+
crop_w, crop_h = gx2 - gx1, gy2 - gy1
|
|
234
|
+
effective_w = meta['effective_w']
|
|
235
|
+
|
|
236
|
+
candidates = []
|
|
237
|
+
for lbl, box, scr in zip(labels, boxes, scores):
|
|
238
|
+
if scr < rec_conf_threshold:
|
|
239
|
+
continue
|
|
240
|
+
char = chr(lbl)
|
|
241
|
+
rx1, ry1, rx2, ry2 = box
|
|
242
|
+
if rx1 >= effective_w:
|
|
243
|
+
continue
|
|
244
|
+
rx1, rx2 = min(rx1, effective_w), min(rx2, effective_w)
|
|
245
|
+
|
|
246
|
+
cx1, cx2 = (rx1 / effective_w) * crop_w, (rx2 / effective_w) * crop_w
|
|
247
|
+
cy1, cy2 = (ry1 / INPUT_REC_HEIGHT) * crop_h, (ry2 / INPUT_REC_HEIGHT) * crop_h
|
|
248
|
+
|
|
249
|
+
gx1_char, gy1_char = gx1 + int(cx1), gy1 + int(cy1)
|
|
250
|
+
gx2_char, gy2_char = gx1 + int(cx2), gy1 + int(cy2)
|
|
251
|
+
|
|
252
|
+
candidates.append({
|
|
253
|
+
'char': char, 'bbox': [gx1_char, gy1_char, gx2_char, gy2_char],
|
|
254
|
+
'conf': float(scr), 'x_interval': (gx1_char, gx2_char)
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
candidates.sort(key=lambda c: c['conf'], reverse=True)
|
|
258
|
+
accepted = []
|
|
259
|
+
accepted_intervals = []
|
|
260
|
+
for cand in candidates:
|
|
261
|
+
x1_c, x2_c = cand['x_interval']
|
|
262
|
+
width_c = x2_c - x1_c + EPSILON
|
|
263
|
+
is_overlap = False
|
|
264
|
+
|
|
265
|
+
for x1_a, x2_a in accepted_intervals:
|
|
266
|
+
if (x1_c >= x2_a) or (x1_a >= x2_c):
|
|
267
|
+
continue
|
|
268
|
+
if ((min(x2_c, x2_a) - max(x1_c, x1_a)) / width_c) > X_OVERLAP_THRESHOLD:
|
|
269
|
+
is_overlap = True
|
|
270
|
+
break
|
|
271
|
+
|
|
272
|
+
if not is_overlap:
|
|
273
|
+
accepted.append(cand)
|
|
274
|
+
accepted_intervals.append(cand['x_interval'])
|
|
275
|
+
|
|
276
|
+
accepted.sort(key=lambda c: c['x_interval'][0])
|
|
277
|
+
text = ''.join(c['char'] for c in accepted)
|
|
278
|
+
result_chars = [{'char': c['char'], 'bbox': c['bbox'], 'conf': c['conf']} for c in accepted]
|
|
279
|
+
full_results[valid_indices[i]] = {'text': text, 'chars': result_chars}
|
|
280
|
+
|
|
281
|
+
return full_results
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: meikiocr
|
|
3
|
+
Version: 0.1.3
|
|
4
|
+
Summary: High-speed, high-accuracy, local OCR for Japanese video games.
|
|
5
|
+
Author: rtr46
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/rtr46/meikiocr
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/rtr46/meikiocr/issues
|
|
9
|
+
Project-URL: Hugging Face, https://huggingface.co/spaces/rtr46/meikiocr
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: numpy
|
|
17
|
+
Requires-Dist: opencv-python-headless
|
|
18
|
+
Requires-Dist: huggingface-hub
|
|
19
|
+
Requires-Dist: onnxruntime
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# meikiocr
|
|
23
|
+
|
|
24
|
+
[](https://github.com/your-github-username/meikiocr/blob/main/license)
|
|
25
|
+
[](https://huggingface.co/spaces/rtr46/meikiocr)
|
|
26
|
+
[](https://huggingface.co/rtr46/meiki.text.detect.v0)
|
|
27
|
+
[](https://huggingface.co/rtr46/meiki.txt.recognition.v0)
|
|
28
|
+
|
|
29
|
+
high-speed, high-accuracy, local ocr for japanese video games.
|
|
30
|
+
|
|
31
|
+
`meikiocr` is a python-based ocr pipeline that combines state-of-the-art detection and recognition models to provide an unparalleled open-source solution for extracting japanese text from video games and similar rendered content.
|
|
32
|
+
|
|
33
|
+
| original image | ocr result |
|
|
34
|
+
| :---: | :---: |
|
|
35
|
+
|  |  |
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
ナルホド
|
|
40
|
+
こ、こんなにドキドキするの、
|
|
41
|
+
小学校の学級裁判のとき以来です。
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## live demo
|
|
47
|
+
|
|
48
|
+
the easiest way to see `meikiocr` in action is to try the live demo hosted on hugging face spaces. no installation required!
|
|
49
|
+
|
|
50
|
+
**[try the meikiocr live demo here](https://huggingface.co/spaces/rtr46/meikiocr)**
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## core features
|
|
55
|
+
|
|
56
|
+
* **high accuracy:** purpose-built and trained on japanese video game text, `meikiocr` significantly outperforms general-purpose ocr tools like paddleocr or easyocr on this specific domain.
|
|
57
|
+
* **high speed:** the architecture is pareto-optimal, delivering exceptional performance on both cpu and gpu.
|
|
58
|
+
* **fully local & private:** unlike cloud-based services, `meikiocr` runs entirely on your machine, ensuring privacy and eliminating api costs or rate limits.
|
|
59
|
+
* **cross-platform:** it works wherever onnx runtime runs, providing a much-needed local ocr solution for linux users.
|
|
60
|
+
* **open & free:** both the code and the underlying models are freely available under permissive licenses.
|
|
61
|
+
|
|
62
|
+
## performance & benchmarks
|
|
63
|
+
|
|
64
|
+
`meikiocr` is built from two highly efficient models that establish a new pareto front for japanese text recognition. this means they offer a better accuracy/latency tradeoff than any other known open-weight model.
|
|
65
|
+
|
|
66
|
+
| detection (cpu) | detection (gpu) |
|
|
67
|
+
|:---:|:---:|
|
|
68
|
+
|  |  |
|
|
69
|
+
|
|
70
|
+
| recognition (cpu) | recognition (gpu) |
|
|
71
|
+
| :---: | :---: |
|
|
72
|
+
|  |  |
|
|
73
|
+
|
|
74
|
+
## installation
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pip install meikiocr
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### for nvidia gpu users (recommended)
|
|
81
|
+
|
|
82
|
+
for a massive performance boost, you can install the gpu-enabled version of the onnx runtime. this will be detected automatically by the script.
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
pip install meikiocr
|
|
86
|
+
pip uninstall onnxruntime
|
|
87
|
+
pip install onnxruntime-gpu
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## usage
|
|
91
|
+
|
|
92
|
+
this is how meikiocr can be called. you can also run [demo.py](https://github.com/rtr46/meikiocr/blob/main/demo.py) for additional visual output.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
import cv2
|
|
96
|
+
import numpy as np
|
|
97
|
+
from urllib.request import urlopen
|
|
98
|
+
from meikiocr import MeikiOCR
|
|
99
|
+
|
|
100
|
+
IMAGE_URL = "https://huggingface.co/spaces/rtr46/meikiocr/resolve/main/example.jpg"
|
|
101
|
+
|
|
102
|
+
with urlopen(IMAGE_URL) as resp:
|
|
103
|
+
image = cv2.imdecode(np.asarray(bytearray(resp.read()), dtype="uint8"), cv2.IMREAD_COLOR)
|
|
104
|
+
|
|
105
|
+
ocr = MeikiOCR() # Initialize the OCR pipeline
|
|
106
|
+
results = ocr.run_ocr(image) # Run the full OCR pipeline
|
|
107
|
+
print('\n'.join([line['text'] for line in results if line['text']]))
|
|
108
|
+
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### adjusting thresholds
|
|
112
|
+
|
|
113
|
+
you can adjust the confidence thresholds for both the text line detection and the character recognition models. lowering the thresholds results in more detected text lines and characters, while higher values prevent false positives.
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
MeikiOCR().run_ocr(self, image, det_threshold=0.8, rec_threshold=0.2) # less, but more confident text boxes and characters returned
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### running dedicated detection
|
|
120
|
+
|
|
121
|
+
if you only care about the position of the text and not the content you can run the detection by itself, which is faster than running the whole ocr pipeline:
|
|
122
|
+
```python
|
|
123
|
+
MeikiOCR().run_detection(self, image, det_threshold=0.8, rec_threshold=0.2) # only returns text line coordinates (for horizontal and vertical text lines)
|
|
124
|
+
```
|
|
125
|
+
in the same way you can also run_recognition by itself on images of precropped (horizontal) text lines.
|
|
126
|
+
|
|
127
|
+
## how it works
|
|
128
|
+
|
|
129
|
+
`meikiocr` is a two-stage pipeline:
|
|
130
|
+
1. **text detection:** the [meiki.text.detect.v0](https://huggingface.co/rtr46/meiki.text.detect.v0) model first identifies the bounding boxes of all horizontal text lines in the image.
|
|
131
|
+
2. **text recognition:** each detected text line is then cropped and processed in a batch by the [meiki.text.recognition.v0](https://huggingface.co/rtr46/meiki.txt.recognition.v0) model, which recognizes the individual characters within it.
|
|
132
|
+
|
|
133
|
+
## limitations
|
|
134
|
+
|
|
135
|
+
while `meikiocr` is state-of-the-art for its niche, it's important to understand its design constraints:
|
|
136
|
+
* **domain specific:** it is highly optimized for rendered text from video games and may not perform well on handwritten or complex real-world scene text.
|
|
137
|
+
* **horizontal text only:** it does not currently support vertical text.
|
|
138
|
+
* **architectural limits:** the detection model is capped at finding 64 text boxes, and the recognition model can process up to 48 characters per line. these limits are sufficient for over 99% of video game scenarios but may be a constraint for other use cases.
|
|
139
|
+
|
|
140
|
+
## advanced usage & potential
|
|
141
|
+
|
|
142
|
+
the `meiki_ocr.py` script provides a straightforward implementation of a post-processing pipeline that selects the most confident prediction for each character. however, the raw output from the recognition model is richer and can be used for more advanced applications. for example, one could build a language-aware post-processing step using n-grams to correct ocr mistakes by considering alternative character predictions.
|
|
143
|
+
|
|
144
|
+
this opens the door for `meikiocr` to be integrated into a variety of projects.
|
|
145
|
+
|
|
146
|
+
## license
|
|
147
|
+
|
|
148
|
+
this project is licensed under the apache 2.0 license. see the [license](LICENSE) file for details.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
meikiocr/__init__.py,sha256=upivPToX7Mcfgxj9wPMv5PN4X7NZ-Fk9l7BmM2OikWU,78
|
|
2
|
+
meikiocr/ocr.py,sha256=mY9ZIITjm9wzqniU-YvWHKiZMqeRC4Zt-QURjhSyG0M,13081
|
|
3
|
+
meikiocr-0.1.3.dist-info/licenses/LICENSE,sha256=Pd-b5cKP4n2tFDpdx27qJSIq0d1ok0oEcGTlbtL6QMU,11560
|
|
4
|
+
meikiocr-0.1.3.dist-info/METADATA,sha256=EFxFg01MXF9-k0i88cCH0D7ioCwsrcFQjY-ZkjDoY8c,7608
|
|
5
|
+
meikiocr-0.1.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
6
|
+
meikiocr-0.1.3.dist-info/top_level.txt,sha256=bZU6k61cDzh_VaYSiXtgSgn2ByX8_LuyT-nuyGb_HfE,9
|
|
7
|
+
meikiocr-0.1.3.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
meikiocr
|