File size: 13,180 Bytes
61a23ae
 
 
 
 
 
aeec220
 
 
61a23ae
 
d3fb9af
04843eb
d3fb9af
 
61a23ae
04843eb
61a23ae
04843eb
61a23ae
f04d7a9
04843eb
f04d7a9
61a23ae
 
029d62b
 
 
61a23ae
 
0927466
029d62b
0927466
 
029d62b
04843eb
 
61a23ae
0927466
 
 
 
 
 
 
 
 
 
 
04843eb
0927466
04843eb
 
0927466
 
04843eb
d3fb9af
61a23ae
 
 
d3fb9af
656acc9
d3fb9af
 
 
 
 
 
145407d
d3fb9af
 
 
 
 
 
 
 
 
 
 
 
145407d
 
 
 
 
 
 
 
060f835
 
 
 
 
145407d
 
 
 
 
 
 
 
 
 
 
 
 
d3fb9af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cd015d
d3fb9af
 
 
 
 
 
 
 
61a23ae
d3fb9af
 
 
 
 
 
 
 
 
656acc9
 
 
 
 
 
d3fb9af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cd015d
 
 
d3fb9af
 
 
060f835
 
d3fb9af
 
 
 
 
 
 
 
 
 
 
 
 
060f835
 
 
d3fb9af
 
 
 
 
 
 
1cd015d
d3fb9af
 
 
 
 
 
 
 
1cd015d
d3fb9af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145407d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

# see huggingface_echodict/typst-app-clone/tools/extract_pdf_images.py

# see https://huggingface.co/PaddlePaddle/PP-OCRv6_medium_det_safetensors
# see https://huggingface.co/PaddlePaddle/PP-OCRv6_medium_rec_safetensors

# see https://github.com/PaddlePaddle/PaddleOCR/issues/16137  矫正后的图像我们也返回了,坐标是对应于矫正后图像的。另外图像矫正模块是不可逆的,没法把坐标映射回去。想要原图的结果可以关掉图像矫正模块


"""

.venv/Scripts/python post.py
    .venv/bin/python post.py
    测试接口

curl -LsSf https://astral.sh/uv/install.sh | sh
    # linux
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
    # Windows.

apt-get update && apt-get install -y libgl1-mesa-glx libglib2.0-0 libgl1 libglib2.0-0t64
    # linux

uv venv --python 3.10 --seed --clear

$env:UV_DEFAULT_INDEX="https://pypi.tuna.tsinghua.edu.cn/simple"
    export UV_DEFAULT_INDEX="https://pypi.tuna.tsinghua.edu.cn/simple"
    加速


CPU 版本:

    .venv/Scripts/pip install "paddleocr[all]"
        .venv/bin/pip install "paddleocr[all]"

    .venv/Scripts/pip install transformers --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.tuna.tsinghua.edu.cn/simple
        .venv/bin/pip install transformers --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.tuna.tsinghua.edu.cn/simple

    .venv/Scripts/pip install paddlepaddle -i https://www.paddlepaddle.org.cn/packages/stable/cpu/
        .venv/bin/pip install paddlepaddle -i https://www.paddlepaddle.org.cn/packages/stable/cpu/

    .venv/Scripts/pip install flask

GPU 版本:

    .venv/Scripts/pip install "paddleocr[all]"
        .venv/bin/pip install "paddleocr[all]"

    .venv/Scripts/pip install paddlepaddle-gpu -i https://www.paddlepaddle.org.cn/packages/stable/cu130/
        .venv/bin/pip install paddlepaddle-gpu==3.3.1 -i https://www.paddlepaddle.org.cn/packages/stable/cu130/
    
    .venv/Scripts/pip install transformers --index-url https://download.pytorch.org/whl/cu130 --extra-index-url https://pypi.tuna.tsinghua.edu.cn/simple
        .venv/bin/pip install transformers --index-url https://download.pytorch.org/whl/cu130 --extra-index-url https://pypi.tuna.tsinghua.edu.cn/simple

    .venv/Scripts/pip install flask
        .venv/bin/pip install flask

"""


is_debug = False
is_debug_api = False

dic_cache = {}

from flask import Flask, request, jsonify
import threading
import platform
import os

app = Flask(__name__)

import json
import decimal
import datetime
import base64
import numpy as np
import cv2

from collections import OrderedDict

def _parse_csv_env(name: str, default: str):
    raw = os.environ.get(name, default)
    parts = [p.strip() for p in raw.split(",")]
    return [p for p in parts if p]

_cors_allowed_origins = set(_parse_csv_env("PPV5_CORS_ALLOWED_ORIGINS", "https://typst-app-clone.pages.dev"))

def _add_cors_headers(resp):
    resp.headers["Access-Control-Allow-Origin"] = "*"
    resp.headers["Access-Control-Allow-Methods"] = "POST, OPTIONS"
    resp.headers["Access-Control-Allow-Headers"] = "Content-Type"
    resp.headers["Access-Control-Allow-Private-Network"] = "true"
    resp.headers["Access-Control-Max-Age"] = "86400"
    return resp

@app.before_request
def _handle_options_preflight():
    if request.method != "OPTIONS":
        return None
    resp = app.make_response(("", 204))
    return _add_cors_headers(resp)

@app.after_request
def _after_request(resp):
    return _add_cors_headers(resp)

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        elif isinstance(o, datetime.datetime):
            return str(o)
        super(DecimalEncoder, self).default(o)

def save_json(filename, dics):
    with open(filename, 'w', encoding='utf-8') as fp:
        json.dump(dics, fp, indent=4, cls=DecimalEncoder, ensure_ascii=False)
        fp.close()

def load_json(filename):
    with open(filename, encoding='utf-8') as fp:
        js = json.load(fp)
        fp.close()
        return js

def base64_to_mat(base64_str):
    """
    将 Base64 字符串转换为 OpenCV Mat 对象(NumPy 数组)
    
    参数:
        base64_str (str): Base64 编码的图片字符串(不可以含前缀如 "data:image/jpeg;base64,")
    
    返回:
        Mat: OpenCV 图像对象(NumPy 数组),格式为 BGR
    """
    # 处理可能存在的 Base64 前缀(如 "data:image/jpeg;base64,")
    # if ',' in base64_str:
    #     base64_data = base64_str.split(',')[1]  # 提取纯 Base64 数据部分
    # else:
    # base64_data = base64_str
    
    # 解码 Base64 字符串为二进制字节流
    image_bytes = base64.b64decode(base64_str)
    
    # 将字节流转换为 NumPy 数组(数据类型 uint8)
    nparr = np.frombuffer(image_bytes, np.uint8)
    
    # 使用 OpenCV 解码为 Mat 对象(BGR 格式)
    mat = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)

    if len(mat.shape) != 3:  # 转彩图
        mat = cv2.cvtColor(mat, cv2.COLOR_GRAY2BGR)
    
    return mat


def ppresult_tojson(img, result, reverse=False): # reverse=True 逆序结果行 古籍可能需要逆序
    global is_debug

    jn = OrderedDict()
    prism_wordsInfo = []
    jn["prism_wordsInfo"] = prism_wordsInfo
    jn["height"] = img.shape[0]
    jn["width"] = img.shape[1]

    for res in result:
        output_img = res['doc_preprocessor_res']['output_img']  # 这是预处理后的图片,坐标是这张图的坐标,而且还原不回去。关掉图像矫正后坐标就和原图坐标一致了
        # use_doc_unwarping=False。
        # img = output_img 
        jsn = res.json['res']
        text_word = jsn['text_word']
        text_word_boxes = jsn['text_word_boxes']
        rec_texts = jsn['rec_texts']
        rec_boxes = jsn['rec_boxes']

        if reverse:
            text_word = text_word[::-1]
            text_word_boxes = text_word_boxes[::-1]
            rec_texts = rec_texts[::-1]
            rec_boxes = rec_boxes[::-1]

        for idx_line, (words, boxs) in enumerate(zip(text_word, text_word_boxes)):
            text_line = rec_texts[idx_line]
            text_box = rec_boxes[idx_line]

            j = OrderedDict()
            prism_wordsInfo.append( j )

            lu = OrderedDict(x=text_box[0], y=text_box[1])
            ru = OrderedDict(x=text_box[2], y=text_box[1])
            rd = OrderedDict(x=text_box[2], y=text_box[3])
            ld = OrderedDict(x=text_box[0], y=text_box[3])

            j["word"] = text_line
            j["pos"] = [ lu, ru, rd, ld ]


            charInfo = []
            j['charInfo'] = charInfo
            j['angle'] = -1
            j["x"] = lu["x"]
            j["y"] = lu["y"]
            j["width"] = ( max(ru["x"], rd["x"])) - ( min(lu["x"], ld["x"]) )
            j["height"] = ( max(ld["y"], rd["y"])) - ( min(lu["y"], ru["y"]) )


            img = cv2.rectangle(img, (lu['x'], lu['y']), (rd['x'], rd['y']), (255, 0, 0), 2)
            if platform.system() == "Windows":
                if is_debug_api:
                    cv2.imshow('orig', img)
                    cv2.waitKey(0)
                pass
            for idx_word, (word, box) in enumerate(zip(words, boxs)):

                if (len(word) == 1):
                    info = OrderedDict()
                    charInfo.append( info )
                    info["word"] = word
                    info["x"] = box[0]
                    info["y"] = box[1]
                    info["w"] = box[2] - box[0]
                    info["h"] = box[3] - box[1]
                elif (len(word) > 1):
                    for w in word:
                        info = OrderedDict()
                        charInfo.append( info )
                        info["word"] = w
                        info["x"] = box[0]
                        info["y"] = box[1]
                        info["w"] = box[2] - box[0]
                        info["h"] = box[3] - box[1]

                # print(word)
                img = cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)  # 矩形的左上角, 矩形的右下角
                if platform.system() == "Windows":
                    if is_debug_api:
                        cv2.imshow('orgin', img)
                        cv2.waitKey(0)
                    pass

        # save_json('out.json', jn)
        break  # 只处理第一张图的结果
    
    return jn

from paddleocr import PaddleOCR
import paddle
print(f"Paddle版本: {paddle.__version__}")
print(f"GPU可用: {paddle.is_compiled_with_cuda()}")
print(f"GPU数量: {paddle.device.cuda.device_count()}")
ocr = PaddleOCR(
    text_detection_model_dir="./PPv6/PP-OCRv6_medium_det_safetensors",
    text_recognition_model_dir="./PPv6/PP-OCRv6_medium_rec_safetensors",
    lang='chinese_cht',                  # 繁体字典
    return_word_box=True,                # 返回每个字符的坐标
    use_doc_orientation_classify=True,   # 整页方向(横/倒)
    use_doc_unwarping=False,             # 关闭弯曲矫正,单字坐标它才准。否则坐标是矫正后图像的坐标
    use_textline_orientation=True,       # 文本行方向分类,竖排靠它
    text_det_thresh=0.1,                 # 默认 0.3 对古籍太高,漏淡墨
    text_det_box_thresh=0.1,             # 同上
    text_rec_score_thresh=0.3,           # 过滤低置信,古籍可放低
)
"""
ch, chinese_cht, en, japan, af, az, bs, ca, cs, cy, da, de, es, et, eu, fi, fr, ga, gl, hr, hu, id, is, it, ku, la, lb, lt, lv, mi, ms, mt, nl, no, oc, pl, pt, qu, rm, ro, rs_latin, sk, sl, sq, sv, sw, tl, tr, uz, vi, french, german
"""

# 限制同时处理的请求数量为1
ocr_semaphore = threading.Semaphore(1)
@app.route('/ppocrv6', methods=['POST', 'OPTIONS'])
@app.route('/ocr', methods=['POST', 'OPTIONS'])
def ppv6():
    # request.json 只能够接受方法为POST、Body为raw,header 内容为 application/json类型的数据
    # print(request.json, type(request.json))

    # 使用 request.form 来接受 x-www-form-urlencoded 格式的数据
    # print(request.form, type(request.form))
    
    # form_data = request.form.to_dict()
    # if "img" not in form_data:
    #     return jsonify([])
    
    # base64_str = form_data["img"]

    if request.method == "OPTIONS":
        return _add_cors_headers(app.make_response(("", 204)))

    # 非阻塞方式获取信号量
    if not ocr_semaphore.acquire(blocking=False):
        return jsonify({"warning": "wait pre task done."})

    try:

        base64_str = request.json['img']
        reverse = request.json['reverse'] or False
        
        img = base64_to_mat(base64_str)

        result = ocr.predict(
            input = img, 
            return_word_box=True
            )
            
        jn = ppresult_tojson(img.copy(), result, reverse)

        return jsonify(jn)
    
    except Exception as e:
        return jsonify({"error": str(e)})
    finally:
        ocr_semaphore.release()

if __name__ == '__main__':

    if is_debug:
        import cv2

        result = ocr.predict("./data/SWX0005_00000_00001.webp")
        for res in result:
            res.print()
            res.save_to_img("output")
            res.save_to_json("output")

            # 单独保存预处理各阶段的图片(均为 BGR 格式)
            pre = res['doc_preprocessor_res']  # pre['output_img'] draw_box.py 画字符框大体上准,但还不太准,坐标对应的就是 output_img , 而不是原图
            cv2.imwrite("output/SWX0005_00000_00001_input_img.png",     pre['input_img'])
            cv2.imwrite("output/SWX0005_00000_00001_rot_img.png",       pre['rot_img'])
            cv2.imwrite("output/SWX0005_00000_00001_output_img.png",    pre['output_img'])  # draw_box.py 
        pass
    else:
        use_https = os.environ.get("PPV5_USE_HTTPS", "").lower() in ("1", "true", "yes", "on")
        host = os.environ.get("PPV5_HOST", "127.0.0.1" if use_https else "0.0.0.0")
        port = int(os.environ.get("PPV5_PORT", "9346"))

        if use_https:
            cert_file = os.environ.get("PPV5_TLS_CERT", os.path.join(".", "certs", "localhost.pem"))
            key_file = os.environ.get("PPV5_TLS_KEY", os.path.join(".", "certs", "localhost-key.pem"))
            if not (os.path.exists(cert_file) and os.path.exists(key_file)):
                raise FileNotFoundError(
                    "TLS 证书不存在。请先用 mkcert 生成并安装根证书,然后生成 localhost 证书:\n"
                    "  mkcert -install\n"
                    "  mkcert -key-file certs\\localhost-key.pem -cert-file certs\\localhost.pem localhost 127.0.0.1 ::1\n"
                    f"当前期望证书路径:{cert_file}\n"
                    f"当前期望私钥路径:{key_file}\n"
                    "也可用环境变量 PPV5_TLS_CERT / PPV5_TLS_KEY 指定实际路径。"
                )
            app.run(host=host, port=port, debug=True, ssl_context=(cert_file, key_file))
        else:
            app.run(host=host, port=port, debug=True)