# 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词汇详解 提取的图片几乎不可见,不要了