-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
148 lines (123 loc) · 4.54 KB
/
server.py
File metadata and controls
148 lines (123 loc) · 4.54 KB
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
144
145
146
147
148
from pathlib import Path
from mokuro.manga_page_ocr import MangaPageOcr, InvalidImage
from mokuro import __version__
from mokuro.utils import NumpyEncoder
import cv2
import numpy as np
from PIL import Image
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import hashlib
import argparse
# https://github.com/kha-white/mokuro/blob/master/mokuro/manga_page_ocr.py
class OCRD(MangaPageOcr):
def __call__(self, image_bytes):
img = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
if img is None:
raise InvalidImage()
H, W, *_ = img.shape
result = {"version": __version__, "img_width": W, "img_height": H, "blocks": []}
if self.disable_ocr:
return result
mask, mask_refined, blk_list = self.text_detector(img, refine_mode=1, keep_undetected_mask=True)
for blk_idx, blk in enumerate(blk_list):
result_blk = {
"box": list(blk.xyxy),
"vertical": blk.vertical,
"font_size": blk.font_size,
"lines_coords": [],
"lines": [],
}
for line_idx, line in enumerate(blk.lines_array()):
if blk.vertical:
max_ratio = self.max_ratio_vert
else:
max_ratio = self.max_ratio_hor
line_crops, cut_points = self.split_into_chunks(
img,
mask_refined,
blk,
line_idx,
textheight=self.text_height,
max_ratio=max_ratio,
anchor_window=self.anchor_window,
)
line_text = ""
for line_crop in line_crops:
if blk.vertical:
line_crop = cv2.rotate(line_crop, cv2.ROTATE_90_CLOCKWISE)
line_text += self.mocr(Image.fromarray(line_crop))
result_blk["lines_coords"].append(line.tolist())
result_blk["lines"].append(line_text)
result["blocks"].append(result_blk)
return result
class OCR:
def __init__(self):
self.mpocr = None
self.init_models()
def init_models(self):
if self.mpocr is None:
self.mpocr = OCRD(
"kha-white/manga-ocr-base",
)
def ocr(self, image_bytes):
result = self.mpocr(image_bytes)
return result
class OCRHandler(BaseHTTPRequestHandler):
cache_location = Path("_cache")
def do_POST(self):
init_ocr()
content_length = int(self.headers["Content-Length"])
image_bytes = self.rfile.read(content_length)
try:
sha256 = hashlib.sha256(image_bytes).hexdigest()
size = len(image_bytes)
cache_path = self.cache_location / f"{sha256}_{size}.json"
if cache_path.exists():
with open(cache_path, "r", encoding="utf-8") as f:
result = json.load(f)
result = json.dumps(result, ensure_ascii=False, cls=NumpyEncoder)
print("Cache hit")
else:
result = ocr.ocr(image_bytes)
result = json.dumps(result, ensure_ascii=False, cls=NumpyEncoder)
if not self.cache_location.exists():
self.cache_location.mkdir()
with open(cache_path, "w", encoding="utf-8") as f:
f.write(result)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(result.encode("utf-8"))
except InvalidImage:
self.send_error(400, "Invalid image")
except Exception as e:
self.send_error(500, str(e))
ocr = None
def init_ocr():
global ocr
if ocr is None:
ocr = OCR()
print("OCR model initialized")
def run_server(port=4527):
server_address = ("", port)
httpd = HTTPServer(server_address, OCRHandler)
print(f"Server running on port {port}")
httpd.serve_forever()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--port",
type=int,
default=4527,
help="Port number for the server to listen on (default: 4527)",
)
parser.add_argument(
"--preload",
action="store_true",
help="Preload the OCR model (default: False)",
)
args = parser.parse_args()
if args.preload:
init_ocr()
run_server(args.port)