dlxj commited on
Commit
9ee3a3d
·
1 Parent(s): a4e4d78
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ out.json
data/0022.jpg ADDED

Git LFS Details

  • SHA256: 1886349b012f1518e38a3c20f7f817df534666dc255de133e292e05ff97eef01
  • Pointer size: 131 Bytes
  • Size of remote file: 372 kB
data/0025.jpg ADDED

Git LFS Details

  • SHA256: 22c2a2fe98b506cd5649b54c135404e6b192854b7741a8342551c3d4c48a25f1
  • Pointer size: 132 Bytes
  • Size of remote file: 1.31 MB
data/0055.jpg ADDED

Git LFS Details

  • SHA256: 08d0e74b5c1d6355898c211ffcb2e6391e0c14bf80aeaa0eebcef36b8bc75e34
  • Pointer size: 131 Bytes
  • Size of remote file: 297 kB
data/0074.jpg ADDED

Git LFS Details

  • SHA256: 8d6fe192510da230b83252df9b1b3d7ed06972b83335444304f7559179787283
  • Pointer size: 131 Bytes
  • Size of remote file: 632 kB
data/0082.jpg ADDED

Git LFS Details

  • SHA256: 6be825444627a3d5a8f11011d60eb96d1615bfb8b81e0f8c88c0382b56b2807b
  • Pointer size: 131 Bytes
  • Size of remote file: 605 kB
data/0375.jpg ADDED

Git LFS Details

  • SHA256: e7c49eb4cf1066647067ac255c38c4799f0157147d5bb9a221569772620e7225
  • Pointer size: 131 Bytes
  • Size of remote file: 901 kB
data/CRNN.jpg ADDED

Git LFS Details

  • SHA256: f3dcbac24d9095baaee8e67eb4a3d31d262cf34acfbd55c81adfa99790f9ded5
  • Pointer size: 129 Bytes
  • Size of remote file: 1.61 kB
data/comic.jpg ADDED

Git LFS Details

  • SHA256: 0d00ca83d91627de844eb6d5a352f673df5286cb80c02aa1ff8998bc8576f890
  • Pointer size: 130 Bytes
  • Size of remote file: 38.9 kB
data/er.jpeg ADDED

Git LFS Details

  • SHA256: 2262724734ddf70b5d41f971cc7b713f99b52c0ad2c4e915ef05bd8c1fd04b53
  • Pointer size: 130 Bytes
  • Size of remote file: 59.6 kB
data/第一单元.jpg ADDED

Git LFS Details

  • SHA256: e4b5abd604e150665b17de76a52401450efdb36f21f3fafac1253b997d87c715
  • Pointer size: 129 Bytes
  • Size of remote file: 7.27 kB
main.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # see huggingface/project/flask_auto_selection.py
3
+
4
+ # C:\Users\echod\.paddlex\official_models\PP-OCRv5_server_det
5
+ # c:\Users\echod\.conda\envs\ppv5\lib\site-packages\paddle\utils\cpp_extension\extension_utils.py 看标型加载的代码在哪
6
+
7
+ """
8
+
9
+ conda create -n ppv5 python==3.10 pip \
10
+ && conda activate ppv5 \
11
+ && python -m pip install paddlepaddle-gpu==3.1.1 -i https://www.paddlepaddle.org.cn/packages/stable/cu118 \
12
+ && pip install paddleocr
13
+ # python -m pip install paddlepaddle==3.1.1 -i https://www.paddlepaddle.org.cn/packages/stable/cpu/
14
+ # cpu 就这样
15
+
16
+ # pip install numpy==2.2.4 pillow==11.1.0 protobuf==6.30.2 flask==3.1.2 opencv-python==4.12.0.88 paddlepaddle==3.1.1 paddleocr==3.2.0 --proxy=http://127.0.0.1:7897
17
+ # -i https://mirrors.aliyun.com/pypi/simple/
18
+
19
+ """
20
+
21
+ is_debug = True
22
+
23
+ dic_cache = {}
24
+
25
+ from flask import Flask, request, jsonify
26
+ import threading
27
+ import platform
28
+
29
+ app = Flask(__name__)
30
+
31
+ import json
32
+ import decimal
33
+ import datetime
34
+ import base64
35
+ import numpy as np
36
+ import cv2
37
+
38
+ from collections import OrderedDict
39
+
40
+ class DecimalEncoder(json.JSONEncoder):
41
+ def default(self, o):
42
+ if isinstance(o, decimal.Decimal):
43
+ return float(o)
44
+ elif isinstance(o, datetime.datetime):
45
+ return str(o)
46
+ super(DecimalEncoder, self).default(o)
47
+
48
+ def save_json(filename, dics):
49
+ with open(filename, 'w', encoding='utf-8') as fp:
50
+ json.dump(dics, fp, indent=4, cls=DecimalEncoder, ensure_ascii=False)
51
+ fp.close()
52
+
53
+ def load_json(filename):
54
+ with open(filename, encoding='utf-8') as fp:
55
+ js = json.load(fp)
56
+ fp.close()
57
+ return js
58
+
59
+ def base64_to_mat(base64_str):
60
+ """
61
+ 将 Base64 字符串转换为 OpenCV Mat 对象(NumPy 数组)
62
+
63
+ 参数:
64
+ base64_str (str): Base64 编码的图片字符串(不可以含前缀如 "data:image/jpeg;base64,")
65
+
66
+ 返回:
67
+ Mat: OpenCV 图像对象(NumPy 数组),格式为 BGR
68
+ """
69
+ # 处理可能存在的 Base64 前缀(如 "data:image/jpeg;base64,")
70
+ # if ',' in base64_str:
71
+ # base64_data = base64_str.split(',')[1] # 提取纯 Base64 数据部分
72
+ # else:
73
+ # base64_data = base64_str
74
+
75
+ # 解码 Base64 字符串为二进制字节流
76
+ image_bytes = base64.b64decode(base64_str)
77
+
78
+ # 将字节流转换为 NumPy 数组(数据类型 uint8)
79
+ nparr = np.frombuffer(image_bytes, np.uint8)
80
+
81
+ # 使用 OpenCV 解码为 Mat 对象(BGR 格式)
82
+ mat = cv2.imdecode(nparr, cv2.IMREAD_COLOR_BGR) # cv2.IMREAD_COLOR 保留色彩通道
83
+
84
+ return mat
85
+
86
+
87
+ from paddleocr import PaddleOCR
88
+
89
+ ocr = PaddleOCR(
90
+ use_doc_orientation_classify=False,
91
+ use_doc_unwarping=False,
92
+ use_textline_orientation=False)
93
+
94
+ def ppresult_tojson(img, result):
95
+ global is_debug
96
+
97
+ jn = OrderedDict()
98
+ prism_wordsInfo = []
99
+ jn["prism_wordsInfo"] = prism_wordsInfo
100
+ jn["height"] = img.shape[0]
101
+ jn["width"] = img.shape[1]
102
+
103
+ for res in result:
104
+ output_img = res['doc_preprocessor_res']['output_img'] # 这是预处理后的图片,坐标可能是这张图的坐标,而且还原不回去
105
+ jsn = res.json['res']
106
+ text_word = jsn['text_word']
107
+ text_word_boxes = jsn['text_word_boxes']
108
+ rec_texts = jsn['rec_texts']
109
+ rec_boxes = jsn['rec_boxes']
110
+
111
+ for idx_line, (words, boxs) in enumerate(zip(text_word, text_word_boxes)):
112
+ text_line = rec_texts[idx_line]
113
+ text_box = rec_boxes[idx_line]
114
+
115
+ j = OrderedDict()
116
+ prism_wordsInfo.append( j )
117
+
118
+ lu = OrderedDict(x=text_box[0], y=text_box[1])
119
+ ru = OrderedDict(x=text_box[2], y=text_box[1])
120
+ rd = OrderedDict(x=text_box[2], y=text_box[3])
121
+ ld = OrderedDict(x=text_box[0], y=text_box[3])
122
+
123
+ j["word"] = text_line
124
+ j["pos"] = [ lu, ru, rd, ld ]
125
+
126
+
127
+ charInfo = []
128
+ j['charInfo'] = charInfo
129
+
130
+ img = cv2.rectangle(img, (lu['x'], lu['y']), (rd['x'], rd['y']), (255, 0, 0), 2)
131
+ if platform.system() == "Windows":
132
+ # if is_debug:
133
+ # cv2.imshow('orig', img)
134
+ # cv2.waitKey(0)
135
+ pass
136
+ for idx_word, (word, box) in enumerate(zip(words, boxs)):
137
+
138
+ if (len(word) == 1):
139
+ info = OrderedDict()
140
+ charInfo.append( info )
141
+ info["word"] = word
142
+ info["x"] = box[0]
143
+ info["y"] = box[1]
144
+ info["w"] = box[2] - box[0]
145
+ info["h"] = box[3] - box[1]
146
+ elif (len(word) > 1):
147
+ for w in word:
148
+ info = OrderedDict()
149
+ charInfo.append( info )
150
+ info["word"] = w
151
+ info["x"] = box[0]
152
+ info["y"] = box[1]
153
+ info["w"] = box[2] - box[0]
154
+ info["h"] = box[3] - box[1]
155
+
156
+ # print(word)
157
+ img = cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
158
+ if platform.system() == "Windows":
159
+ # if is_debug:
160
+ # cv2.imshow('orgin', img)
161
+ # cv2.waitKey(0)
162
+ pass
163
+
164
+ # save_json('out.json', jn)
165
+ break # 只处理第一张图的结果
166
+
167
+ return jn
168
+
169
+ # 限制同时处理的请求数量为1
170
+ ocr_semaphore = threading.Semaphore(1)
171
+ @app.route('/ppocr', methods=['post'])
172
+ def autoselection():
173
+ # request.json 只能够接受方法为POST、Body为raw,header 内容为 application/json类型的数据
174
+ # print(request.json, type(request.json))
175
+
176
+ # 使用 request.form 来接受 x-www-form-urlencoded 格式的数据
177
+ # print(request.form, type(request.form))
178
+
179
+ # form_data = request.form.to_dict()
180
+ # if "img" not in form_data:
181
+ # return jsonify([])
182
+
183
+ # base64_str = form_data["img"]
184
+
185
+ # 非阻塞方式获取信号量
186
+ if not ocr_semaphore.acquire(blocking=False):
187
+ return jsonify({"warning": "wait pre task done."})
188
+
189
+ try:
190
+
191
+ base64_str = request.json['img']
192
+
193
+ img = base64_to_mat(base64_str)
194
+
195
+ result = ocr.predict(
196
+ input = img,
197
+ return_word_box=True
198
+ )
199
+
200
+ jn = ppresult_tojson(img.copy(), result)
201
+
202
+ return jsonify(jn)
203
+
204
+ except Exception as e:
205
+ return jsonify({"error": str(e)})
206
+ finally:
207
+ ocr_semaphore.release()
208
+
209
+ if __name__ == '__main__':
210
+
211
+ if is_debug:
212
+ pth_img = "data/0170.jpg" # "data/第一单元.jpg"
213
+
214
+ imgData = np.fromfile(pth_img, dtype=np.uint8)
215
+ img = cv2.imdecode(imgData, cv2.IMREAD_COLOR_BGR)
216
+
217
+ # cv2.imshow('orgin', img)
218
+ # cv2.waitKey(0)
219
+
220
+ result = ocr.predict(
221
+ input = img, # pth_img, # "data/无标点符号.jpg",
222
+ return_word_box=True
223
+ )
224
+
225
+ jn =ppresult_tojson(img.copy(), result)
226
+ save_json('out.json', jn)
227
+
228
+ # res.print()
229
+ # res.save_to_img("output")
230
+ # res.save_to_json("output")
231
+ else:
232
+ app.run(host="0.0.0.0", port=8889, debug=True)