fasdfsa commited on
Commit
84b147c
·
1 Parent(s): 3488e63

add jp_ocr.py

Browse files
Files changed (1) hide show
  1. jp_ocr.py +385 -0
jp_ocr.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ # see huggingface/rwkv5-jp-trimvd_new/PaddleOCR_ali1k_det_rec_300epoch_standalone/requirements.txt
4
+
5
+ # 第一次 aliocr 识别中文 main.py
6
+ # 第二次用 ppocr 识别日文 jp_ocr.py
7
+
8
+
9
+
10
+ if __name__ == '__main__':
11
+
12
+ import glob
13
+ from pathlib import Path
14
+ pth_jsons = glob.glob('pdfs/jp/李致雨N3词汇详解/*.json', recursive=True)
15
+ pth_zh_jsons = [ str( Path(pth).resolve() ) for pth in pth_jsons if '_jp' not in pth ]
16
+
17
+ pass
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+ # ocr_one_pdf('pdfs/jp/高木直子学日语文法不要想太多/高木直子学日语文法不要想太多.pdf')
29
+
30
+ # ocr_one_pdf('pdfs/jp/刘炳善英汉双解莎士比亚大词典续编/刘炳善英汉双解莎士比亚大词典续编.pdf')
31
+
32
+ # ocr_one_pdf('pdfs/en/TIME单挑1000/TIME单挑1000.pdf')
33
+
34
+ # ocr_one_pdf('pdfs/en/TIME片挑200/TIME片挑200.pdf')
35
+
36
+ # ocr_one_pdf('pdfs/jp/徐一平日本语句型辞典/徐一平日本语句型辞典.pdf')
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+ # pip install pypdf==5.0.0
54
+ # https://github.com/py-pdf/pypdf
55
+ # # https://github.com/freddyaboulton/gradio-pdf
56
+ # gradio_pdf==0.0.15
57
+
58
+ # aliocr first then autuo pdf trim
59
+ # see huggingface/project/zh_jp_auto_selection.py
60
+ # see huggingface/rwkv5-jp-trimvd/config.py
61
+ # see huggingface/rwkv5-jp-trimvd/appv4.py # aliocr first then autuo pdf trim
62
+ # see huggingface/PPOCRLabel use this to correct ocr result
63
+
64
+ from config import alicr_config
65
+
66
+ def ali_ocr(img_data, config):
67
+
68
+ # https://market.aliyun.com/apimarket/detail/cmapi028554#sku=yuncode22554000016
69
+
70
+ import requests
71
+ import json
72
+
73
+ api = config['api']
74
+ app_code = config['app_code']
75
+ appSecret = config['appSecret']
76
+ try:
77
+ # 设置请求头
78
+ headers = {
79
+ "Authorization": f"APPCODE {app_code}",
80
+ "Content-Type": "application/json;charset=UTF-8"
81
+ }
82
+
83
+ # 设置请求体
84
+ payload = json.dumps({
85
+ "img": img_data,
86
+ "prob": True,
87
+ "charInfo": True,
88
+ "table": True,
89
+ "sortPage": True,
90
+ "NeedRotate": True
91
+ })
92
+
93
+ # 发送POST请求
94
+ response = requests.post(api, headers=headers, data=payload, timeout=120)
95
+
96
+ # 检查响应状态
97
+ if response.status_code != 200:
98
+ return None, {"error_code": response.status_code, "error_msg": response.text}
99
+
100
+ # 解析返回结果
101
+ try:
102
+ ali_result = response.json()
103
+ except Exception as ex:
104
+ print("#####ERROR: aliyun ocr parse error.")
105
+ print(ex)
106
+ print("Response Text:", response.text)
107
+ return None, {"error_code": "JSON_PARSE_ERROR", "error_msg": str(ex)}
108
+
109
+ return ali_result, None
110
+
111
+ except requests.RequestException as error:
112
+ print('#####ERROR: aliyun ocr fail.')
113
+ print(error)
114
+ return None, {"error_code": "REQUEST_ERROR", "error_msg": str(error)}
115
+
116
+
117
+ def ocr_one_img():
118
+ import numpy as np
119
+ import cv2, base64
120
+ np_array = np.fromfile('data/no_think_more.png', dtype=np.uint8)
121
+ img = cv2.imdecode(np_array, -1)
122
+ # bytes = img.tobytes() # 转字节数组 # 或者使用img.tostring(),两者是等价的
123
+ # 注意了:得到的bytes数据并不等价于open(file,"rb")数据
124
+
125
+ if len(img.shape) != 3: # 转彩图
126
+ img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
127
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # DBNet 原版只能处理彩图,这里转一下
128
+
129
+ else:
130
+ img_color = img.copy()
131
+
132
+ # 把img 对象编码为jpg 格式
133
+ success, encoded_image = cv2.imencode(".jpg", img)
134
+ # 将数组转为bytes
135
+ img_bts = encoded_image.tobytes() # 等价于tostring()
136
+ img_b64_str = base64.b64encode(img_bts).decode('utf-8')
137
+
138
+ jsn, error = ali_ocr(img_b64_str, alicr_config)
139
+
140
+ wordsInfo = jsn['prism_wordsInfo']
141
+ for j in range(len(wordsInfo)):
142
+ jo = wordsInfo[j]
143
+ word = jo["word"]
144
+
145
+ # prism-wordsInfo 里的 angle 文字块的角度,这个角度只影响width和height,当角度为-90、90、-270、270,width和height的值需要自行互换
146
+ angle = jo['angle']
147
+
148
+ word_x = jo['x']
149
+ word_y = jo['y']
150
+ word_width = jo['width']
151
+ word_height = jo['height']
152
+
153
+ if abs(angle) == 90 or abs(angle) == 270:
154
+ word_width = jo['height']
155
+ word_height = jo['width']
156
+
157
+ pos = jo['pos']
158
+
159
+ # 四个角的位置 左上、右上、右下、左下 顺时针方向
160
+ lu = [pos[0]['x'], pos[0]['y']]
161
+ ru = [pos[1]['x'], pos[1]['y']]
162
+ rd = [pos[2]['x'], pos[2]['y']]
163
+ ld = [pos[3]['x'], pos[3]['y']]
164
+
165
+ x1 = min( pos[0]['x'], pos[3]['x'] ) # 当前行的极左
166
+ x2 = max( pos[1]['x'], pos[2]['x'] ) # 当前行的极右
167
+
168
+ y1 = min( pos[0]['y'], pos[1]['y'] ) # 当前行的极上
169
+ y2 = max( pos[2]['y'], pos[3]['y'] ) # 当前行的极下
170
+
171
+ # img_color = cv2.rectangle(img_color, (x1, y1), (x2, y2), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
172
+ img_color = cv2.rectangle(img_color, (lu[0], lu[1]), (rd[0], rd[1]), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
173
+
174
+ # cv2.imshow("green", img_color)
175
+ # cv2.waitKey(0)
176
+
177
+ cv2.imwrite('./tmp.jpg', img_color)
178
+
179
+ if error:
180
+ print("Error occurred:", error)
181
+ else:
182
+ print("Result:", jsn)
183
+ # ocr_one_img()
184
+
185
+ def ocr_one_pdf(pth_pdf):
186
+ """
187
+ see huggingface/PPOCRLabel use this to correct ocr result
188
+ """
189
+ import cv2
190
+ import numpy as np
191
+ import base64
192
+ import hashlib
193
+ from pathlib import Path
194
+ import os
195
+ import json
196
+
197
+ base = Path(pth_pdf).stem
198
+ dir = os.path.dirname(pth_pdf)
199
+
200
+
201
+ def get_page_image(reader, page_num):
202
+ page_num = int(page_num)
203
+ page = reader.pages[page_num - 1]
204
+ text = page.extract_text()
205
+ for idx, image_file_object in enumerate(page.images):
206
+ img_bytes = image_file_object.data
207
+ img_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8) # 将图片字节码 bytes 转换成一维的 numpy 数组到缓存中
208
+ ocr_frame = cv2.imdecode(img_buffer_numpy, 1) # 从指定的内存缓存中读取一维 numpy 数据,并把数据转换(解码)成图像矩阵格式
209
+ ocr_frame = cv2.cvtColor(ocr_frame, cv2.COLOR_BGR2RGB)
210
+ # cv2.imshow('test', self.ocr_frame)
211
+ # cv2.waitKey(0)
212
+ break
213
+ return ocr_frame
214
+
215
+ def md5_file(fname):
216
+ hash_md5 = hashlib.md5()
217
+ with open(fname, "rb") as f:
218
+ for chunk in iter(lambda: f.read(4096), b""):
219
+ hash_md5.update(chunk)
220
+ return hash_md5.hexdigest()
221
+
222
+ def md5_bytes(bts):
223
+ hash_md5 = hashlib.md5()
224
+ chunk_size = 4096
225
+ for i in range(0, len(bts), chunk_size):
226
+ chunk = bts[i:i+chunk_size]
227
+ hash_md5.update(chunk)
228
+ return hash_md5.hexdigest()
229
+
230
+ def jsonparse(s):
231
+ return json.loads(s, strict=False )
232
+
233
+ def jsonstring(d):
234
+ return json.dumps(d, ensure_ascii=False)
235
+
236
+ from pypdf import PdfReader
237
+ reader = PdfReader(pth_pdf)
238
+ number_of_pages = len(reader.pages)
239
+
240
+ # see huggingface/PPOCRLabel/PPOCRLabel.py for image notation
241
+ name_pp_label = 'Label.txt'
242
+ pth_pp_label = os.path.join(dir, name_pp_label)
243
+ pp_label_text = ''
244
+ # real/0010.jpg [{"transcription": "待识别", "points": [[137, 77], [740, 77], [740, 165], [137, 165]], "difficult": false}]
245
+ # points 是框选的矩形四个角坐标: 左上 右上 右下 左下
246
+ name_pp_state = 'fileState.txt'
247
+ pth_pp_state = os.path.join(dir, name_pp_state)
248
+ pp_state_text = ''
249
+ # E:\huggingface\pdf_ocr\pdfs\jp\高木直子学日语文法不要想太多\0010.jpg 1
250
+ # 只能在 windows 平台用绝对路径
251
+
252
+
253
+ for nth_page in range(1, number_of_pages+1):
254
+
255
+ if nth_page > 1000:
256
+ break
257
+
258
+ img_color = get_page_image(reader, nth_page)
259
+ cv2.imwrite('./tmp.jpg', cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR))
260
+
261
+ # 把img 对象编码为jpg 格式
262
+ success, encoded_image = cv2.imencode(".jpg", cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR))
263
+ # 将数组转为bytes
264
+ img_bts = encoded_image.tobytes() # 等价于tostring()
265
+
266
+ m51 = md5_bytes(img_bts)
267
+ with open('tmp.jpg', 'wb') as f:
268
+ f.write(img_bts)
269
+ m52 = md5_file('tmp.jpg')
270
+ assert m51 == m52
271
+
272
+ img_b64_str = base64.b64encode(img_bts).decode('utf-8')
273
+
274
+ img_name = "{:04d}.jpg".format(nth_page)
275
+ pth_img = os.path.join(dir, img_name)
276
+ jsn_name = "{:04d}.json".format(nth_page)
277
+ pth_jsn = os.path.join(dir, jsn_name)
278
+
279
+ label_left = f'{Path(dir).stem}/{img_name}' # for ppocrlabel
280
+ label_right = []
281
+
282
+ pp_state_text += 'E:\\huggingface\\pdf_ocr\\'+ dir.replace('/', '\\') + '\\' + "{:04d}.jpg".format(nth_page) + '\t' + '1\n'
283
+
284
+ jsn = None
285
+
286
+ if not os.path.exists(pth_jsn):
287
+ jsn, error = ali_ocr(img_b64_str, alicr_config)
288
+ if not jsn:
289
+ raise Exception(f'### error: ocr fail. {error}')
290
+
291
+ print(jsn)
292
+
293
+ with open(pth_jsn, 'w', encoding='utf-8') as f:
294
+ f.write( jsonstring(jsn) )
295
+
296
+ with open(pth_img, 'wb') as f:
297
+ f.write(img_bts)
298
+ else:
299
+ print(f'### this page ocr already: {pth_jsn}')
300
+
301
+ if not os.path.exists(pth_jsn):
302
+ raise Exception(f'### error: not jsn file. {pth_jsn}')
303
+
304
+ with open(pth_jsn, 'r', encoding='utf-8') as f:
305
+ s = f.read()
306
+ jsn = jsonparse(s)
307
+ if 'prism_wordsInfo' in jsn:
308
+ wordsInfo = jsn['prism_wordsInfo']
309
+ else:
310
+ wordsInfo = []
311
+ for j in range(len(wordsInfo)):
312
+ jo = wordsInfo[j]
313
+ word = jo["word"]
314
+
315
+ # prism-wordsInfo 里的 angle 文字块的角度,这个角度只影响width和height,当角度为-90、90、-270、270,width和height的值需要自行互换
316
+ angle = jo['angle']
317
+
318
+ word_x = jo['x']
319
+ word_y = jo['y']
320
+ word_width = jo['width']
321
+ word_height = jo['height']
322
+
323
+ if abs(angle) == 90 or abs(angle) == 270:
324
+ word_width = jo['height']
325
+ word_height = jo['width']
326
+
327
+ pos = jo['pos']
328
+
329
+ # 四个角的位置 左上、右上、右下、左下 顺时针方向
330
+ lu = [pos[0]['x'], pos[0]['y']]
331
+ ru = [pos[1]['x'], pos[1]['y']]
332
+ rd = [pos[2]['x'], pos[2]['y']]
333
+ ld = [pos[3]['x'], pos[3]['y']]
334
+
335
+ label_right.append( { "transcription": word, "points":[ lu, ru, rd, ld ] } )
336
+
337
+ x1 = min( pos[0]['x'], pos[3]['x'] ) # 当前行的极左
338
+ x2 = max( pos[1]['x'], pos[2]['x'] ) # 当前行的极右
339
+
340
+ y1 = min( pos[0]['y'], pos[1]['y'] ) # 当前行的极上
341
+ y2 = max( pos[2]['y'], pos[3]['y'] ) # 当前行的极下
342
+
343
+ # img_color = cv2.rectangle(img_color, (x1, y1), (x2, y2), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
344
+ img_color = cv2.rectangle(img_color, (lu[0], lu[1]), (rd[0], rd[1]), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
345
+
346
+ # cv2.imshow("green", img_color)
347
+ # cv2.waitKey(0)
348
+
349
+
350
+ pp_label_text += f'{label_left}\t{jsonstring(label_right)}\n'
351
+
352
+ cv2.imwrite('./tmp.jpg', cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR))
353
+
354
+
355
+ print( f'one page done. {nth_page} / {number_of_pages}' )
356
+
357
+
358
+
359
+ if not os.path.exists(pth_pp_label):
360
+ # if exist, maybe ppocrlabel edited already. DO NOT rewrite it!!!
361
+ if pp_label_text:
362
+ with open(pth_pp_label, 'w', encoding='utf-8') as f:
363
+ f.write(pp_label_text)
364
+
365
+ if not os.path.exists(pth_pp_state):
366
+ # if exist, maybe ppocrlabel edited already. DO NOT rewrite it!!!
367
+ if pp_state_text:
368
+ with open(pth_pp_state, 'w', encoding='utf-8') as f:
369
+ f.write(pp_state_text)
370
+
371
+
372
+
373
+ if __name__ == '__main__':
374
+
375
+ # ocr_one_pdf('pdfs/jp/高木直子学日语文法不要想太多/高木直子学日语文法不要想太多.pdf')
376
+
377
+ # ocr_one_pdf('pdfs/jp/刘炳善英汉双解莎士比亚大词典续编/刘炳善英汉双解莎士比亚大词典续编.pdf')
378
+
379
+ # ocr_one_pdf('pdfs/en/TIME单挑1000/TIME单挑1000.pdf')
380
+
381
+ # ocr_one_pdf('pdfs/en/TIME片挑200/TIME片挑200.pdf')
382
+
383
+ ocr_one_pdf('pdfs/jp/徐一平日本语句型辞典/徐一平日本语句型辞典.pdf') # 李致雨N2词汇详解 提取的图片几乎不可见,不要了
384
+
385
+