dlxj commited on
Commit
d3fb9af
·
1 Parent(s): aeec220

add v6 api

Browse files
Files changed (2) hide show
  1. main_v6.py +235 -33
  2. post.py +6 -2
main_v6.py CHANGED
@@ -9,6 +9,9 @@
9
 
10
  """
11
 
 
 
 
12
  curl -LsSf https://astral.sh/uv/install.sh | sh
13
  # On Windows.
14
  powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
@@ -31,40 +34,239 @@ $env:UV_DEFAULT_INDEX="https://pypi.tuna.tsinghua.edu.cn/simple"
31
  .venv/Scripts/pip install paddlepaddle -i https://www.paddlepaddle.org.cn/packages/stable/cpu/
32
  .venv/bin/pip install paddlepaddle -i https://www.paddlepaddle.org.cn/packages/stable/cpu/
33
 
 
 
34
  """
35
 
36
- if __name__ == '__main__':
37
 
38
- from paddleocr import PaddleOCR
39
-
40
- import paddle
41
- print(f"Paddle版本: {paddle.__version__}")
42
- print(f"GPU可用: {paddle.is_compiled_with_cuda()}")
43
- print(f"GPU数量: {paddle.device.cuda.device_count()}")
44
-
45
- ocr = PaddleOCR(
46
- text_detection_model_dir="./PPv6/PP-OCRv6_medium_det_safetensors",
47
- text_recognition_model_dir="./PPv6/PP-OCRv6_medium_rec_safetensors",
48
- lang='chinese_cht', # 繁体字典
49
- return_word_box=True, # 返回每个字符的坐标
50
- use_doc_orientation_classify=True, # 整页方向(横/倒)
51
- use_doc_unwarping=False, # 关闭弯曲矫正,单字坐标它才准。否则坐标是矫正后图像的坐标
52
- use_textline_orientation=True, # 文本行方向分类,竖排靠它
53
- text_det_thresh=0.1, # 默认 0.3 对古籍太高,漏淡墨
54
- text_det_box_thresh=0.1, # 同上
55
- text_rec_score_thresh=0.3, # 过滤低置信,古籍可放低
56
- )
57
- import cv2
58
-
59
- result = ocr.predict("./data/SWX0005_00000_00001.webp")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  for res in result:
61
- res.print()
62
- res.save_to_img("output")
63
- res.save_to_json("output")
64
-
65
- # 单独保存预处理各阶段的图片(均为 BGR 格式)
66
- pre = res['doc_preprocessor_res'] # pre['output_img'] draw_box.py 画字符框大体上准,但还不太准,坐标对应的就是 output_img , 而不是原图
67
- cv2.imwrite("output/SWX0005_00000_00001_input_img.png", pre['input_img'])
68
- cv2.imwrite("output/SWX0005_00000_00001_rot_img.png", pre['rot_img'])
69
- cv2.imwrite("output/SWX0005_00000_00001_output_img.png", pre['output_img']) # draw_box.py
70
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  """
11
 
12
+ .venv/Scripts/python post.py
13
+ 测试接口
14
+
15
  curl -LsSf https://astral.sh/uv/install.sh | sh
16
  # On Windows.
17
  powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
 
34
  .venv/Scripts/pip install paddlepaddle -i https://www.paddlepaddle.org.cn/packages/stable/cpu/
35
  .venv/bin/pip install paddlepaddle -i https://www.paddlepaddle.org.cn/packages/stable/cpu/
36
 
37
+ .venv/Scripts/pip install flask
38
+
39
  """
40
 
 
41
 
42
+ is_debug = False
43
+ is_debug_api = True
44
+
45
+ dic_cache = {}
46
+
47
+ from flask import Flask, request, jsonify
48
+ import threading
49
+ import platform
50
+
51
+ app = Flask(__name__)
52
+
53
+ import json
54
+ import decimal
55
+ import datetime
56
+ import base64
57
+ import numpy as np
58
+ import cv2
59
+
60
+ from collections import OrderedDict
61
+
62
+ class DecimalEncoder(json.JSONEncoder):
63
+ def default(self, o):
64
+ if isinstance(o, decimal.Decimal):
65
+ return float(o)
66
+ elif isinstance(o, datetime.datetime):
67
+ return str(o)
68
+ super(DecimalEncoder, self).default(o)
69
+
70
+ def save_json(filename, dics):
71
+ with open(filename, 'w', encoding='utf-8') as fp:
72
+ json.dump(dics, fp, indent=4, cls=DecimalEncoder, ensure_ascii=False)
73
+ fp.close()
74
+
75
+ def load_json(filename):
76
+ with open(filename, encoding='utf-8') as fp:
77
+ js = json.load(fp)
78
+ fp.close()
79
+ return js
80
+
81
+ def base64_to_mat(base64_str):
82
+ """
83
+ 将 Base64 字符串转换为 OpenCV Mat 对象(NumPy 数组)
84
+
85
+ 参数:
86
+ base64_str (str): Base64 编码的图片字符串(不可以含前缀如 "data:image/jpeg;base64,")
87
+
88
+ 返回:
89
+ Mat: OpenCV 图像对象(NumPy 数组),格式为 BGR
90
+ """
91
+ # 处理可能存在的 Base64 前缀(如 "data:image/jpeg;base64,")
92
+ # if ',' in base64_str:
93
+ # base64_data = base64_str.split(',')[1] # 提取纯 Base64 数据部分
94
+ # else:
95
+ # base64_data = base64_str
96
+
97
+ # 解码 Base64 字符串为二进制字节流
98
+ image_bytes = base64.b64decode(base64_str)
99
+
100
+ # 将字节流转换为 NumPy 数组(数据类型 uint8)
101
+ nparr = np.frombuffer(image_bytes, np.uint8)
102
+
103
+ # 使用 OpenCV 解码为 Mat 对象(BGR 格式)
104
+ mat = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)
105
+
106
+ if len(mat.shape) != 3: # 转彩图
107
+ mat = cv2.cvtColor(mat, cv2.COLOR_GRAY2BGR)
108
+
109
+ return mat
110
+
111
+
112
+ def ppresult_tojson(img, result):
113
+ global is_debug
114
+
115
+ jn = OrderedDict()
116
+ prism_wordsInfo = []
117
+ jn["prism_wordsInfo"] = prism_wordsInfo
118
+ jn["height"] = img.shape[0]
119
+ jn["width"] = img.shape[1]
120
+
121
  for res in result:
122
+ output_img = res['doc_preprocessor_res']['output_img'] # 这是预处理后的图片,坐标是这张图的坐标,而且还原不回去。关掉图像矫正后坐标就和原图坐标一致了
123
+ # use_doc_unwarping=False。
124
+ # img = output_img
125
+ jsn = res.json['res']
126
+ text_word = jsn['text_word']
127
+ text_word_boxes = jsn['text_word_boxes']
128
+ rec_texts = jsn['rec_texts']
129
+ rec_boxes = jsn['rec_boxes']
130
+
131
+ for idx_line, (words, boxs) in enumerate(zip(text_word, text_word_boxes)):
132
+ text_line = rec_texts[idx_line]
133
+ text_box = rec_boxes[idx_line]
134
+
135
+ j = OrderedDict()
136
+ prism_wordsInfo.append( j )
137
+
138
+ lu = OrderedDict(x=text_box[0], y=text_box[1])
139
+ ru = OrderedDict(x=text_box[2], y=text_box[1])
140
+ rd = OrderedDict(x=text_box[2], y=text_box[3])
141
+ ld = OrderedDict(x=text_box[0], y=text_box[3])
142
+
143
+ j["word"] = text_line
144
+ j["pos"] = [ lu, ru, rd, ld ]
145
+
146
+
147
+ charInfo = []
148
+ j['charInfo'] = charInfo
149
+ j['angle'] = -1
150
+ j["x"] = lu["x"]
151
+ j["y"] = lu["y"]
152
+ j["width"] = ( max(ru["x"], rd["x"])) - ( min(lu["x"], ld["x"]) )
153
+ j["height"] = ( max(ld["y"], rd["y"])) - ( min(lu["y"], ru["y"]) )
154
+
155
+
156
+ img = cv2.rectangle(img, (lu['x'], lu['y']), (rd['x'], rd['y']), (255, 0, 0), 2)
157
+ if platform.system() == "Windows":
158
+ if is_debug_api:
159
+ cv2.imshow('orig', img)
160
+ cv2.waitKey(0)
161
+ pass
162
+ for idx_word, (word, box) in enumerate(zip(words, boxs)):
163
+
164
+ if (len(word) == 1):
165
+ info = OrderedDict()
166
+ charInfo.append( info )
167
+ info["word"] = word
168
+ info["x"] = box[0]
169
+ info["y"] = box[1]
170
+ info["w"] = box[2] - box[0]
171
+ info["h"] = box[3] - box[1]
172
+ elif (len(word) > 1):
173
+ for w in word:
174
+ info = OrderedDict()
175
+ charInfo.append( info )
176
+ info["word"] = w
177
+ info["x"] = box[0]
178
+ info["y"] = box[1]
179
+ info["w"] = box[2] - box[0]
180
+ info["h"] = box[3] - box[1]
181
+
182
+ # print(word)
183
+ img = cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
184
+ if platform.system() == "Windows":
185
+ if is_debug_api:
186
+ cv2.imshow('orgin', img)
187
+ cv2.waitKey(0)
188
+ pass
189
+
190
+ # save_json('out.json', jn)
191
+ break # 只处理第一张图的结果
192
+
193
+ return jn
194
+
195
+ from paddleocr import PaddleOCR
196
+ import paddle
197
+ print(f"Paddle版本: {paddle.__version__}")
198
+ print(f"GPU可用: {paddle.is_compiled_with_cuda()}")
199
+ print(f"GPU数量: {paddle.device.cuda.device_count()}")
200
+ ocr = PaddleOCR(
201
+ text_detection_model_dir="./PPv6/PP-OCRv6_medium_det_safetensors",
202
+ text_recognition_model_dir="./PPv6/PP-OCRv6_medium_rec_safetensors",
203
+ lang='chinese_cht', # 繁体字典
204
+ return_word_box=True, # 返回每个字符的坐标
205
+ use_doc_orientation_classify=True, # 整页方向(横/倒)
206
+ use_doc_unwarping=False, # 关闭弯曲矫正,单字坐标它才准。否则坐标是矫正后图像的坐标
207
+ use_textline_orientation=True, # 文本行方向分类,竖排靠它
208
+ text_det_thresh=0.1, # 默认 0.3 对古籍太高,漏淡墨
209
+ text_det_box_thresh=0.1, # 同上
210
+ text_rec_score_thresh=0.3, # 过滤低置信,古籍可放低
211
+ )
212
+
213
+
214
+ # 限制同时处理的请求数量为1
215
+ ocr_semaphore = threading.Semaphore(1)
216
+ @app.route('/ppocrv6', methods=['post'])
217
+ def ppv6():
218
+ # request.json 只能够接受方法为POST、Body为raw,header 内容为 application/json类型的数据
219
+ # print(request.json, type(request.json))
220
+
221
+ # 使用 request.form 来接受 x-www-form-urlencoded 格式的数据
222
+ # print(request.form, type(request.form))
223
+
224
+ # form_data = request.form.to_dict()
225
+ # if "img" not in form_data:
226
+ # return jsonify([])
227
+
228
+ # base64_str = form_data["img"]
229
+
230
+ # 非阻塞方式获取信号量
231
+ if not ocr_semaphore.acquire(blocking=False):
232
+ return jsonify({"warning": "wait pre task done."})
233
+
234
+ try:
235
+
236
+ base64_str = request.json['img']
237
+
238
+ img = base64_to_mat(base64_str)
239
+
240
+ result = ocr.predict(
241
+ input = img,
242
+ return_word_box=True
243
+ )
244
+
245
+ jn = ppresult_tojson(img.copy(), result)
246
+
247
+ return jsonify(jn)
248
+
249
+ except Exception as e:
250
+ return jsonify({"error": str(e)})
251
+ finally:
252
+ ocr_semaphore.release()
253
+
254
+ if __name__ == '__main__':
255
+
256
+ if is_debug:
257
+ import cv2
258
+
259
+ result = ocr.predict("./data/SWX0005_00000_00001.webp")
260
+ for res in result:
261
+ res.print()
262
+ res.save_to_img("output")
263
+ res.save_to_json("output")
264
+
265
+ # 单独保存预处理各阶段的图片(均为 BGR 格式)
266
+ pre = res['doc_preprocessor_res'] # pre['output_img'] draw_box.py 画字符框大体上准,但还不太准,坐标对应的就是 output_img , 而不是原图
267
+ cv2.imwrite("output/SWX0005_00000_00001_input_img.png", pre['input_img'])
268
+ cv2.imwrite("output/SWX0005_00000_00001_rot_img.png", pre['rot_img'])
269
+ cv2.imwrite("output/SWX0005_00000_00001_output_img.png", pre['output_img']) # draw_box.py
270
+ pass
271
+ else:
272
+ app.run(host="0.0.0.0", port=9346, debug=True)
post.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  import requests
2
  import base64
3
  import json
@@ -5,8 +8,9 @@ import os
5
 
6
  def test_ppocr():
7
  # Configuration
8
- url = "http://127.0.0.1:8889/ppocr"
9
- image_path = r"e:\huggingface_echodict\t\PPOCRLLM\data\0022.jpg"
 
10
 
11
  # Check if image exists
12
  if not os.path.exists(image_path):
 
1
+
2
+ # .venv/Scripts/python post.py
3
+
4
  import requests
5
  import base64
6
  import json
 
8
 
9
  def test_ppocr():
10
  # Configuration
11
+ # url = "http://127.0.0.1:8889/ppocr"
12
+ url = "http://127.0.0.1:9346/ppocrv6"
13
+ image_path = r"data/SWX0005_00000_00001.webp"
14
 
15
  # Check if image exists
16
  if not os.path.exists(image_path):