File size: 14,662 Bytes
84a6570 44cc7be ed74f54 44cc7be ed74f54 44cc7be ed74f54 44cc7be 7e42bb0 9fdb992 7e42bb0 9fdb992 7e42bb0 0e2b960 30b28fc 7e42bb0 ed74f54 7e42bb0 9fdb992 7e42bb0 44cc7be ed74f54 44cc7be ed74f54 44cc7be 43ca156 ceac6f3 44cc7be ceac6f3 44cc7be deca49c 6e0aa72 44cc7be ed74f54 30b28fc 44cc7be 1dcc835 ceac6f3 6e81c40 ceac6f3 1dcc835 44cc7be 761c16f 1dcc835 44cc7be 1dcc835 ad5305b 44cc7be 1dcc835 44cc7be 1dcc835 2ca757b 1dcc835 44cc7be 43ca156 2ca757b 1dcc835 2ca757b 1dcc835 ceac6f3 1dcc835 44cc7be e17a15b 44cc7be b2d7894 b252b0e f73275f 471ad88 e1311eb 4d7ccc0 |
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 |
# 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词汇详解 提取的图片几乎不可见,不要了
|