pdf_ocr / main.py
fasdfsa's picture
fix 0701
e1311eb
# 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
import fitz
from PIL import Image # 需要安装Pillow库
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) # 将图片字节码 bytes 转换成一维的 numpy 数组到缓存中
ocr_frame = cv2.imdecode(img_buffer_numpy, 1) # 从指定的内存缓存中读取一维 numpy 数据,并把数据转换(解码)成图像矩阵格式
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 提取(图片会变得大很多!!!)')
# 提取不到图像先用 Acrobat 导出全部图片,再新建 pdf 替换原 pdf 就可以了
if is_except:
# 这个方法很稳,但是图片较大
page = pdfDoc[page_num - 1]
# 关键参数设置(保持原始尺寸和分辨率)
matrix = fitz.Matrix(fitz.Identity) # 使用Identity矩阵确保不缩放[6,8](@ref)
pix = page.get_pixmap(
matrix=matrix, # 保持原始尺寸
dpi=250, # 设置输出分辨率(默认72dpi)
alpha=False, # 关闭透明通道(提高兼容性)
colorspace="rgb" # 使用RGB色彩空间[8](@ref)
)
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) # 将图片字节码 bytes 转换成一维的 numpy 数组到缓存中
ocr_frame = cv2.imdecode(img_buffer_numpy, 1) # 从指定的内存缓存中读取一维 numpy 数据,并把数据转换(解码)成图像矩阵格式
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) # 将图片字节码 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)
pdfDoc = fitz.open(pth_pdf)
number_of_pages = len(reader.pages)
number_of_pages2 = pdfDoc.page_count
assert number_of_pages == number_of_pages2
# 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 > 2000:
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))
# 把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/互動日本語201701/互動日本語201701.pdf') # 李致雨N2词汇详解 提取的图片几乎不可见,不要了