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147c
5c3cf2c
 
 
 
84b147c
5c3cf2c
 
84b147c
5c3cf2c
 
 
 
 
 
 
 
 
 
84b147c
5c3cf2c
 
84b147c
5c3cf2c
 
 
 
84b147c
5c3cf2c
 
 
84b147c
5c3cf2c
84b147c
5c3cf2c
 
 
 
 
84b147c
5c3cf2c
84b147c
5c3cf2c
 
84b147c
5c3cf2c
 
84b147c
5c3cf2c
 
84b147c
b5e5202
 
5c3cf2c
 
84b147c
 
5c3cf2c
84b147c
5c3cf2c
84b147c
 
5c3cf2c
84b147c
 
 
5c3cf2c
 
 
 
 
84b147c
5c3cf2c
 
 
 
 
84b147c
 
 
5c3cf2c
84b147c
5c3cf2c
84b147c
5c3cf2c
84b147c
5c3cf2c
84b147c
5c3cf2c
84b147c
5c3cf2c
84b147c
 
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482


# see huggingface/rwkv5-jp-trimvd_new/PaddleOCR_ali1k_det_rec_300epoch_standalone/requirements.txt

# 第一次 aliocr 识别中文   main.py
# 第二次用 ppocr 识别日文  jp_ocr.py

from ocr import rec as ppocr

import json, cv2

def save_json(filename, dics):
    with open(filename, 'w', encoding='utf-8') as fp:
        json.dump(dics, fp, indent=4, 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


if __name__ == '__main__':

    import glob
    import numpy as np
    from pathlib import Path
    pth_jsons = glob.glob('pdfs/jp/李致雨N3词汇详解/*.json', recursive=True)
    pth_zh_jsons = [ str( Path(pth).resolve() ) for pth in pth_jsons if '_jp' not in pth ]

    pth_zh_jsons = sorted(pth_zh_jsons, key=lambda l:l, reverse=False)

    array = []
    for idx, pth in enumerate(pth_zh_jsons):
        js = load_json(pth)
        array.append( { "pth":pth, "js":js, "idx":idx } )
        # break

    for item in array:
        pth = item['pth']
        pth_img = pth.replace('.json', '.jpg')
        pth_json_jp = pth.replace('.json', '_jp.json')
        jsn = item['js']
        imgData = np.fromfile(pth_img, dtype=np.uint8)
        img_color = cv2.imdecode(imgData, -1)

        if 'prism_wordsInfo' in jsn:
            wordsInfo = jsn['prism_wordsInfo']
        else:
            wordsInfo = []
        for j in range(len(wordsInfo)):
            jo = wordsInfo[j]
            word = jo["word"]

            # prism-wordsInfo 里的 angle 文字块的角度,这个角度只影响width和height,当角度为-90、90、-270、270,width和height的值需要自行互换
            angle = jo['angle']

            word_x = jo['x']
            word_y = jo['y']
            word_width = jo['width']
            word_height = jo['height']

            if abs(angle) == 90 or abs(angle) == 270:
                word_width = jo['height']
                word_height = jo['width']

            pos = jo['pos']

            # 四个角的位置 左上、右上、右下、左下  顺时针方向
            lu = [pos[0]['x'], pos[0]['y']] 
            ru = [pos[1]['x'], pos[1]['y']]
            rd = [pos[2]['x'], pos[2]['y']]
            ld = [pos[3]['x'], pos[3]['y']]


            x1 = min( pos[0]['x'], pos[3]['x'] )   # 当前行的极左
            x2 = max( pos[1]['x'], pos[2]['x'] )   # 当前行的极右

            y1 = min( pos[0]['y'], pos[1]['y'] )   # 当前行的极上
            y2 = max( pos[2]['y'], pos[3]['y'] )   # 当前行的极下

            # img_color = cv2.rectangle(img_color, (lu[0], lu[1]), (rd[0], rd[1]), (0, 255, 0), 2)  # 矩形的左上角, 矩形的右下角

            # cv2.imshow("green", img_color)
            # cv2.waitKey(0)

            # h = img_color.shape[0]  # 注意:高是行数
            # w = img_color.shape[1]  # 宽是列数
            
            img_crop = img_color[lu[1]:lu[1]+(rd[1]-lu[1]), lu[0]:lu[0]+(rd[0]-lu[0])]
                # img_crop = m4.ocr_frame[y:y+height, x:x+width]
            txts, boxes, scores, pil_image = ppocr(img_crop)
            txts = "\n".join(txts)
            if txts.strip():
                jo["word_jp"] = txts.strip()
            else:
                jo["word_jp"] = ""
        
            print( txts )

            pass


            # cv2.imshow("img_crop", img_crop)
            # cv2.waitKey(0)


        save_json(pth_json_jp, jsn)

    pass










    # ocr_one_pdf('pdfs/jp/高木直子学日语文法不要想太多/高木直子学日语文法不要想太多.pdf')

    # ocr_one_pdf('pdfs/jp/刘炳善英汉双解莎士比亚大词典续编/刘炳善英汉双解莎士比亚大词典续编.pdf')
    
    # ocr_one_pdf('pdfs/en/TIME单挑1000/TIME单挑1000.pdf')

    # ocr_one_pdf('pdfs/en/TIME片挑200/TIME片挑200.pdf')
    
    # ocr_one_pdf('pdfs/jp/徐一平日本语句型辞典/徐一平日本语句型辞典.pdf')
















# pip install pypdf==5.0.0
    # https://github.com/py-pdf/pypdf
    #   # https://github.com/freddyaboulton/gradio-pdf   
    # gradio_pdf==0.0.15

# aliocr first then autuo pdf trim
# see huggingface/project/zh_jp_auto_selection.py
# see huggingface/rwkv5-jp-trimvd/config.py
    # see huggingface/rwkv5-jp-trimvd/appv4.py # aliocr first then autuo pdf trim
# see huggingface/PPOCRLabel  use this to correct ocr result

# from config import alicr_config

# def ali_ocr(img_data, config):

#     # https://market.aliyun.com/apimarket/detail/cmapi028554#sku=yuncode22554000016

#     import requests
#     import json

#     api = config['api']
#     app_code = config['app_code']
#     appSecret = config['appSecret']
#     try:
#         # 设置请求头
#         headers = {
#             "Authorization": f"APPCODE {app_code}",
#             "Content-Type": "application/json;charset=UTF-8"
#         }

#         # 设置请求体
#         payload = json.dumps({
#             "img": img_data,
#             "prob": True,
#             "charInfo": True,
#             "table": True,
#             "sortPage": True,
#             "NeedRotate": True
#         })

#         # 发送POST请求
#         response = requests.post(api, headers=headers, data=payload, timeout=120)

#         # 检查响应状态
#         if response.status_code != 200:
#             return None, {"error_code": response.status_code, "error_msg": response.text}

#         # 解析返回结果
#         try:
#             ali_result = response.json()
#         except Exception as ex:
#             print("#####ERROR: aliyun ocr parse error.")
#             print(ex)
#             print("Response Text:", response.text)
#             return None, {"error_code": "JSON_PARSE_ERROR", "error_msg": str(ex)}

#         return ali_result, None

#     except requests.RequestException as error:
#         print('#####ERROR: aliyun ocr fail.')
#         print(error)
#         return None, {"error_code": "REQUEST_ERROR", "error_msg": str(error)}


# def ocr_one_img():
#     import numpy as np
#     import cv2, base64
#     np_array = np.fromfile('data/no_think_more.png', dtype=np.uint8)
#     img = cv2.imdecode(np_array, -1)
#     # bytes = img.tobytes()  # 转字节数组  # 或者使用img.tostring(),两者是等价的
#         # 注意了:得到的bytes数据并不等价于open(file,"rb")数据

#     if len(img.shape) != 3:  # 转彩图
#         img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
#         img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)  # DBNet 原版只能处理彩图,这里转一下

#     else:
#         img_color = img.copy()

#     # 把img 对象编码为jpg 格式
#     success, encoded_image = cv2.imencode(".jpg", img) 
#     # 将数组转为bytes
#     img_bts = encoded_image.tobytes() # 等价于tostring() 
#     img_b64_str = base64.b64encode(img_bts).decode('utf-8')

#     jsn, error = ali_ocr(img_b64_str, alicr_config)

#     wordsInfo = jsn['prism_wordsInfo']
#     for j in range(len(wordsInfo)):
#         jo = wordsInfo[j]
#         word = jo["word"]

#         # prism-wordsInfo 里的 angle 文字块的角度,这个角度只影响width和height,当角度为-90、90、-270、270,width和height的值需要自行互换
#         angle = jo['angle']

#         word_x = jo['x']
#         word_y = jo['y']
#         word_width = jo['width']
#         word_height = jo['height']

#         if abs(angle) == 90 or abs(angle) == 270:
#             word_width = jo['height']
#             word_height = jo['width']

#         pos = jo['pos']

#         # 四个角的位置 左上、右上、右下、左下  顺时针方向
#         lu = [pos[0]['x'], pos[0]['y']] 
#         ru = [pos[1]['x'], pos[1]['y']]
#         rd = [pos[2]['x'], pos[2]['y']]
#         ld = [pos[3]['x'], pos[3]['y']]

#         x1 = min( pos[0]['x'], pos[3]['x'] )   # 当前行的极左
#         x2 = max( pos[1]['x'], pos[2]['x'] )   # 当前行的极右

#         y1 = min( pos[0]['y'], pos[1]['y'] )   # 当前行的极上
#         y2 = max( pos[2]['y'], pos[3]['y'] )   # 当前行的极下

#         # img_color = cv2.rectangle(img_color, (x1, y1), (x2, y2), (0, 255, 0), 2)  # 矩形的左上角, 矩形的右下角
#         img_color = cv2.rectangle(img_color, (lu[0], lu[1]), (rd[0], rd[1]), (0, 255, 0), 2)  # 矩形的左上角, 矩形的右下角

#         # cv2.imshow("green", img_color)
#         # cv2.waitKey(0)

#     cv2.imwrite('./tmp.jpg', img_color)

#     if error:
#         print("Error occurred:", error)
#     else:
#         print("Result:", jsn)
# # ocr_one_img()

# def ocr_one_pdf(pth_pdf):
#     """
#       see huggingface/PPOCRLabel  use this to correct ocr result
#     """
#     import cv2
#     import numpy as np
#     import base64
#     import hashlib
#     from pathlib import Path
#     import os
#     import json

#     base = Path(pth_pdf).stem
#     dir = os.path.dirname(pth_pdf)


#     def get_page_image(reader, page_num):
#         page_num = int(page_num)
#         page = reader.pages[page_num - 1]
#         text = page.extract_text()
#         for idx, image_file_object in enumerate(page.images):
#             img_bytes = image_file_object.data
#             img_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8)  # 将图片字节码 bytes 转换成一维的 numpy 数组到缓存中
#             ocr_frame = cv2.imdecode(img_buffer_numpy, 1)   # 从指定的内存缓存中读取一维 numpy 数据,并把数据转换(解码)成图像矩阵格式
#             ocr_frame = cv2.cvtColor(ocr_frame, cv2.COLOR_BGR2RGB)
#             # cv2.imshow('test', self.ocr_frame)
#             # cv2.waitKey(0)
#             break
#         return ocr_frame

#     def md5_file(fname):
#         hash_md5 = hashlib.md5()
#         with open(fname, "rb") as f:
#             for chunk in iter(lambda: f.read(4096), b""):
#                 hash_md5.update(chunk)
#         return hash_md5.hexdigest()

#     def md5_bytes(bts):
#         hash_md5 = hashlib.md5()
#         chunk_size = 4096
#         for i in range(0, len(bts), chunk_size):
#             chunk = bts[i:i+chunk_size]
#             hash_md5.update(chunk)
#         return hash_md5.hexdigest()

#     def jsonparse(s):
#         return json.loads(s, strict=False )

#     def jsonstring(d):
#         return json.dumps(d, ensure_ascii=False)

#     from pypdf import PdfReader
#     reader = PdfReader(pth_pdf)
#     number_of_pages = len(reader.pages)

#     # see huggingface/PPOCRLabel/PPOCRLabel.py   for image notation
#     name_pp_label = 'Label.txt'
#     pth_pp_label = os.path.join(dir, name_pp_label)
#     pp_label_text = ''
#         # real/0010.jpg	[{"transcription": "待识别", "points": [[137, 77], [740, 77], [740, 165], [137, 165]], "difficult": false}]
#         # points 是框选的矩形四个角坐标: 左上 右上  右下 左下
#     name_pp_state = 'fileState.txt'
#     pth_pp_state = os.path.join(dir, name_pp_state)
#     pp_state_text = ''
#         # E:\huggingface\pdf_ocr\pdfs\jp\高木直子学日语文法不要想太多\0010.jpg	1
#             # 只能在 windows 平台用绝对路径

    
#     for nth_page in range(1, number_of_pages+1):

#         if nth_page > 1000:
#             break

#         img_color = get_page_image(reader, nth_page)

#         cv2.imwrite('./tmp.jpg', cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR))

#         # 把img 对象编码为jpg 格式
#         success, encoded_image = cv2.imencode(".jpg", cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR))
#         # 将数组转为bytes
#         img_bts = encoded_image.tobytes() # 等价于tostring() 
        
#         m51 = md5_bytes(img_bts)
#         with open('tmp.jpg', 'wb') as f:
#             f.write(img_bts)
#         m52 = md5_file('tmp.jpg')
#         assert m51 == m52

#         img_b64_str = base64.b64encode(img_bts).decode('utf-8')

#         img_name = "{:04d}.jpg".format(nth_page)
#         pth_img = os.path.join(dir, img_name)
#         jsn_name = "{:04d}.json".format(nth_page)
#         pth_jsn = os.path.join(dir, jsn_name)

#         label_left = f'{Path(dir).stem}/{img_name}' # for ppocrlabel
#         label_right = []

#         pp_state_text += 'E:\\huggingface\\pdf_ocr\\'+ dir.replace('/', '\\') + '\\' + "{:04d}.jpg".format(nth_page) + '\t' + '1\n'

#         jsn = None

#         if not os.path.exists(pth_jsn):
#             jsn, error = ali_ocr(img_b64_str, alicr_config)
#             if not jsn:
#                 raise Exception(f'### error: ocr fail. {error}')
            
#             print(jsn)

#             with open(pth_jsn, 'w', encoding='utf-8') as f:
#                 f.write( jsonstring(jsn) )

#             with open(pth_img, 'wb') as f:
#                 f.write(img_bts)
#         else:
#             print(f'### this page ocr already: {pth_jsn}')

#             if not os.path.exists(pth_jsn):
#                 raise Exception(f'### error: not jsn file. {pth_jsn}')
            
#             with open(pth_jsn, 'r', encoding='utf-8') as f:
#                 s = f.read()
#                 jsn = jsonparse(s)
#         if 'prism_wordsInfo' in jsn:
#             wordsInfo = jsn['prism_wordsInfo']
#         else:
#             wordsInfo = []
#         for j in range(len(wordsInfo)):
#             jo = wordsInfo[j]
#             word = jo["word"]

#             # prism-wordsInfo 里的 angle 文字块的角度,这个角度只影响width和height,当角度为-90、90、-270、270,width和height的值需要自行互换
#             angle = jo['angle']

#             word_x = jo['x']
#             word_y = jo['y']
#             word_width = jo['width']
#             word_height = jo['height']

#             if abs(angle) == 90 or abs(angle) == 270:
#                 word_width = jo['height']
#                 word_height = jo['width']

#             pos = jo['pos']

#             # 四个角的位置 左上、右上、右下、左下  顺时针方向
#             lu = [pos[0]['x'], pos[0]['y']] 
#             ru = [pos[1]['x'], pos[1]['y']]
#             rd = [pos[2]['x'], pos[2]['y']]
#             ld = [pos[3]['x'], pos[3]['y']]

#             label_right.append( { "transcription": word, "points":[ lu, ru, rd, ld ] } )

#             x1 = min( pos[0]['x'], pos[3]['x'] )   # 当前行的极左
#             x2 = max( pos[1]['x'], pos[2]['x'] )   # 当前行的极右

#             y1 = min( pos[0]['y'], pos[1]['y'] )   # 当前行的极上
#             y2 = max( pos[2]['y'], pos[3]['y'] )   # 当前行的极下

#             # img_color = cv2.rectangle(img_color, (x1, y1), (x2, y2), (0, 255, 0), 2)  # 矩形的左上角, 矩形的右下角
#             img_color = cv2.rectangle(img_color, (lu[0], lu[1]), (rd[0], rd[1]), (0, 255, 0), 2)  # 矩形的左上角, 矩形的右下角



#             # cv2.imshow("green", img_color)
#             # cv2.waitKey(0)


#         pp_label_text += f'{label_left}\t{jsonstring(label_right)}\n'

#         cv2.imwrite('./tmp.jpg', cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR))


#         print( f'one page done. {nth_page} / {number_of_pages}' )



#     if not os.path.exists(pth_pp_label):
#         # if exist, maybe ppocrlabel edited already. DO NOT rewrite it!!!
#         if pp_label_text:
#             with open(pth_pp_label, 'w', encoding='utf-8') as f:
#                 f.write(pp_label_text)

#     if not os.path.exists(pth_pp_state):
#         # if exist, maybe ppocrlabel edited already. DO NOT rewrite it!!!
#         if pp_state_text:
#             with open(pth_pp_state, 'w', encoding='utf-8') as f:
#                 f.write(pp_state_text)



# if __name__ == '__main__':

#     # ocr_one_pdf('pdfs/jp/高木直子学日语文法不要想太多/高木直子学日语文法不要想太多.pdf')

#     # ocr_one_pdf('pdfs/jp/刘炳善英汉双解莎士比亚大词典续编/刘炳善英汉双解莎士比亚大词典续编.pdf')
    
#     # ocr_one_pdf('pdfs/en/TIME单挑1000/TIME单挑1000.pdf')

#     # ocr_one_pdf('pdfs/en/TIME片挑200/TIME片挑200.pdf')
    
#     ocr_one_pdf('pdfs/jp/徐一平日本语句型辞典/徐一平日本语句型辞典.pdf')  # 李致雨N2词汇详解 提取的图片几乎不可见,不要了