|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
|
|
| from config import alicr_config |
|
|
| def ali_ocr(img_data, config): |
|
|
| |
|
|
| 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 |
| }) |
|
|
| |
| 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) |
| |
| |
|
|
| if len(img.shape) != 3: |
| img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) |
| img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) |
|
|
| else: |
| img_color = img.copy() |
|
|
| |
| success, encoded_image = cv2.imencode(".jpg", img) |
| |
| img_bts = encoded_image.tobytes() |
| 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"] |
|
|
| |
| 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.imwrite('./tmp.jpg', img_color) |
|
|
| if error: |
| print("Error occurred:", error) |
| else: |
| print("Result:", jsn) |
| |
|
|
| 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 |
| |
| import fitz |
| from PIL import Image |
|
|
| base = Path(pth_pdf).stem |
| dir = os.path.dirname(pth_pdf) |
|
|
|
|
| def get_page_image(reader, pdfDoc, page_num): |
| page_num = int(page_num) |
| page = reader.pages[page_num - 1] |
| |
| text = page.extract_text() |
| is_except = False |
| ocr_frame = None |
| try: |
| 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) |
| ocr_frame = cv2.imdecode(img_buffer_numpy, 1) |
| ocr_frame = cv2.cvtColor(ocr_frame, cv2.COLOR_BGR2RGB) |
| break |
| if ocr_frame is None: |
| is_except = True |
| print('##### Waring: 没有异常但是读不到图片!!!PdfReader 读取图片出错,换成用 fitz 提取(图片会变得大很多!!!)') |
| except Exception: |
| is_except = True |
| print('##### Waring: PdfReader 读取图片出错,换成用 fitz 提取(图片会变得大很多!!!)') |
| |
| |
| if is_except: |
| |
| page = pdfDoc[page_num - 1] |
| |
| matrix = fitz.Matrix(fitz.Identity) |
| pix = page.get_pixmap( |
| matrix=matrix, |
| dpi=250, |
| alpha=False, |
| colorspace="rgb" |
| ) |
| |
| from io import BytesIO |
| byte_io = BytesIO() |
| |
| img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) |
| byte_io = BytesIO() |
| img.save(byte_io, format="JPEG", quality=95) |
| byte_io.seek(0) |
| img_bytes = byte_io.read() |
| |
| img_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8) |
| ocr_frame = cv2.imdecode(img_buffer_numpy, 1) |
| ocr_frame = cv2.cvtColor(ocr_frame, cv2.COLOR_BGR2RGB) |
| |
| elif ocr_frame is None: |
| |
| 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) |
| ocr_frame = cv2.imdecode(img_buffer_numpy, 1) |
| ocr_frame = cv2.cvtColor(ocr_frame, cv2.COLOR_BGR2RGB) |
| |
| |
| 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) |
| pdfDoc = fitz.open(pth_pdf) |
| number_of_pages = len(reader.pages) |
| number_of_pages2 = pdfDoc.page_count |
| |
| assert number_of_pages == number_of_pages2 |
|
|
| |
| name_pp_label = 'Label.txt' |
| pth_pp_label = os.path.join(dir, name_pp_label) |
| pp_label_text = '' |
| |
| |
| name_pp_state = 'fileState.txt' |
| pth_pp_state = os.path.join(dir, name_pp_state) |
| pp_state_text = '' |
| |
| |
|
|
| |
| for nth_page in range(1, number_of_pages+1): |
|
|
| if nth_page > 500: |
| break |
|
|
| img_color = get_page_image(reader, pdfDoc, nth_page) |
| if img_color is None: |
| continue |
| cv2.imwrite('./tmp.jpg', cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR)) |
|
|
| |
| success, encoded_image = cv2.imencode(".jpg", cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR)) |
| |
| img_bts = encoded_image.tobytes() |
| |
| 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}' |
| 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"] |
|
|
| |
| 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, (lu[0], lu[1]), (rd[0], rd[1]), (0, 255, 0), 2) |
|
|
| |
| |
|
|
|
|
| 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 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 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/N1真题2015年12月答案/N1真题2015年12月答案.pdf') |
| |
| |