convert_pdf.py 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  1. import copy
  2. import inspect
  3. import io
  4. import logging
  5. import os
  6. import re
  7. import sys
  8. from bs4 import BeautifulSoup
  9. sys.path.append(os.path.dirname(__file__) + "/../")
  10. from pdfplumber import PDF
  11. from pdfplumber.table import TableFinder
  12. from pdfplumber.page import Page as pdfPage
  13. from format_convert.convert_tree import _Document, _Page, _Image, _Sentence, _Table
  14. import time
  15. import pdfminer
  16. import math
  17. from scipy.stats import linregress
  18. from matplotlib import pyplot as plt
  19. from shapely.geometry import LineString, Point
  20. from format_convert import timeout_decorator
  21. from PIL import Image
  22. from format_convert.convert_image import image_process
  23. from format_convert.convert_need_interface import from_ocr_interface, from_office_interface
  24. import traceback
  25. import cv2
  26. import PyPDF2
  27. from PyPDF2 import PdfFileReader, PdfFileWriter
  28. from pdfminer.pdfparser import PDFParser
  29. from pdfminer.pdfdocument import PDFDocument
  30. from pdfminer.pdfpage import PDFPage
  31. from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
  32. from pdfminer.converter import PDFPageAggregator
  33. from pdfminer.layout import LTTextBoxHorizontal, LAParams, LTFigure, LTImage, LTCurve, LTText, LTChar, LTRect, \
  34. LTTextBoxVertical, LTLine, LTTextContainer
  35. from format_convert.utils import judge_error_code, add_div, get_platform, get_html_p, string_similarity, LineTable, \
  36. get_logger, log, memory_decorator, draw_lines_plt, get_garble_code, line_is_cross
  37. import fitz
  38. from format_convert.wrapt_timeout_decorator import timeout
  39. @memory_decorator
  40. def pdf2Image(path, save_dir):
  41. log("into pdf2Image")
  42. try:
  43. try:
  44. doc = fitz.open(path)
  45. except Exception as e:
  46. log("pdf format error!")
  47. # print("pdf format error!", e)
  48. return [-3]
  49. # output_image_list = []
  50. output_image_dict = {}
  51. page_count = doc.page_count
  52. for page_no in range(page_count):
  53. # 限制pdf页数,只取前10页后10页
  54. if page_count > 20:
  55. if 10 <= page_no < page_count - 10:
  56. # log("pdf2Image: pdf pages count " + str(doc.page_count)
  57. # + ", only get 70 pages")
  58. continue
  59. try:
  60. page = doc.loadPage(page_no)
  61. output = save_dir + "_page" + str(page_no) + ".png"
  62. rotate = int(0)
  63. # 每个尺寸的缩放系数为1.3,这将为我们生成分辨率提高2.6的图像。
  64. # 此处若是不做设置,默认图片大小为:792X612, dpi=96
  65. # (1.33333333 --> 1056x816) (2 --> 1584x1224)
  66. # (1.183, 2.28 --> 1920x1080)
  67. zoom_x = 3.
  68. zoom_y = 3.
  69. # mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
  70. mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
  71. pix = page.getPixmap(matrix=mat, alpha=False)
  72. pix.writePNG(output)
  73. pdf_image = cv2.imread(output)
  74. print("pdf_image", page_no, pdf_image.shape)
  75. # output_image_list.append([page_no, output])
  76. output_image_dict[int(page_no)] = output
  77. except ValueError as e:
  78. traceback.print_exc()
  79. if str(e) == "page not in document":
  80. log("pdf2Image page not in document! continue..." + str(page_no))
  81. continue
  82. elif "encrypted" in str(e):
  83. log("pdf2Image document need password " + str(page_no))
  84. return [-7]
  85. except RuntimeError as e:
  86. if "cannot find page" in str(e):
  87. log("pdf2Image page {} not in document! continue... ".format(str(page_no)) + str(e))
  88. continue
  89. else:
  90. traceback.print_exc()
  91. return [-3]
  92. return [output_image_dict]
  93. except Exception as e:
  94. log("pdf2Image error!")
  95. print("pdf2Image", traceback.print_exc())
  96. return [-1]
  97. @timeout(10, timeout_exception=TimeoutError)
  98. def pdf_analyze(interpreter, page, device, page_no):
  99. log("into pdf_analyze")
  100. pdf_time = time.time()
  101. # print("pdf_analyze interpreter process...")
  102. interpreter.process_page(page)
  103. # print("pdf_analyze device get_result...")
  104. layout = device.get_result()
  105. log("pdf2text page " + str(page_no) + " read time " + str(time.time() - pdf_time))
  106. return layout
  107. @memory_decorator
  108. def pdf2text(path, unique_type_dir):
  109. log("into pdf2text")
  110. try:
  111. # pymupdf pdf to image
  112. save_dir = path.split(".")[-2] + "_" + path.split(".")[-1]
  113. output_image_dict = pdf2Image(path, save_dir)
  114. if judge_error_code(output_image_dict):
  115. return output_image_dict
  116. output_image_dict = output_image_dict[0]
  117. output_image_no_list = list(output_image_dict.keys())
  118. output_image_no_list.sort(key=lambda x: x)
  119. # 获取每页pdf提取的文字、表格的列数、轮廓点、是否含表格、页码
  120. # page_info_list = []
  121. page_info_dict = {}
  122. has_table_dict = {}
  123. no_table_dict = {}
  124. for page_no in output_image_no_list:
  125. img_path = output_image_dict.get(page_no)
  126. print("pdf page", page_no, "in total", output_image_no_list[-1])
  127. # 读不出来的跳过
  128. try:
  129. img = cv2.imread(img_path)
  130. img_size = img.shape
  131. except:
  132. log("pdf2text read image in page fail! continue...")
  133. continue
  134. # 每张图片处理
  135. text, column_list, outline_points, is_table = image_process(img, img_path, use_ocr=False)
  136. if judge_error_code(text):
  137. return text
  138. # page_info_list.append([text, column_list, outline_points, is_table,
  139. # page_no, img_size])
  140. page_info = [text, column_list, outline_points, is_table, img_size]
  141. page_info_dict[int(page_no)] = page_info
  142. # 包含table的和不包含table的
  143. if is_table:
  144. has_table_dict[int(page_no)] = page_info
  145. else:
  146. no_table_dict[int(page_no)] = page_info
  147. has_table_no_list = list(has_table_dict.keys())
  148. has_table_no_list.sort(key=lambda x: x)
  149. page_no_list = list(page_info_dict.keys())
  150. page_no_list.sort(key=lambda x: x)
  151. # 页码表格连接
  152. table_connect_list, connect_text_list = page_table_connect(has_table_dict)
  153. if judge_error_code(table_connect_list):
  154. return table_connect_list
  155. # 连接的页码
  156. table_connect_page_no_list = []
  157. for area in connect_text_list:
  158. table_connect_page_no_list.append(area[1])
  159. print("pdf2text table_connect_list", table_connect_list)
  160. print("connect_text_list", connect_text_list)
  161. # pdfminer 方式
  162. try:
  163. fp = open(path, 'rb')
  164. # 用文件对象创建一个PDF文档分析器
  165. parser = PDFParser(fp)
  166. # 创建一个PDF文档
  167. doc = PDFDocument(parser)
  168. # 连接分析器,与文档对象
  169. rsrcmgr = PDFResourceManager()
  170. device = PDFPageAggregator(rsrcmgr, laparams=LAParams())
  171. interpreter = PDFPageInterpreter(rsrcmgr, device)
  172. # 判断是否能读pdf
  173. for page in PDFPage.create_pages(doc):
  174. break
  175. except pdfminer.psparser.PSEOF as e:
  176. # pdfminer 读不了空白页的对象,直接使用pymupdf转换出的图片进行ocr识别
  177. log("pdf2text " + str(e) + " use ocr read pdf!")
  178. text_list = []
  179. for page_no in page_no_list:
  180. log("pdf2text ocr page_no " + str(page_no))
  181. page_info = page_info_dict.get(page_no)
  182. # 表格
  183. if page_info[3]:
  184. # 判断表格是否跨页连接
  185. area_no = 0
  186. jump_page = 0
  187. for area in table_connect_list:
  188. if page_no in area:
  189. # 只记录一次text
  190. if page_no == area[0]:
  191. image_text = connect_text_list[area_no][0]
  192. text_list.append([image_text, page_no, 0])
  193. jump_page = 1
  194. area_no += 1
  195. # 是连接页的跳过后面步骤
  196. if jump_page:
  197. continue
  198. # 直接取text
  199. image_text = page_info_dict.get(page_no)[0]
  200. text_list.append([image_text, page_no, 0])
  201. # 非表格
  202. else:
  203. with open(output_image_dict.get(page_no), "rb") as ff:
  204. image_stream = ff.read()
  205. image_text = from_ocr_interface(image_stream)
  206. text_list.append([image_text, page_no, 0])
  207. text_list.sort(key=lambda z: z[1])
  208. text = ""
  209. for t in text_list:
  210. text += t[0]
  211. return [text]
  212. except Exception as e:
  213. log("pdf format error!")
  214. traceback.print_exc()
  215. return [-3]
  216. text_list = []
  217. page_no = 0
  218. pages = PDFPage.create_pages(doc)
  219. pages = list(pages)
  220. page_count = len(pages)
  221. for page in pages:
  222. log("pdf2text pymupdf page_no " + str(page_no))
  223. # 限制pdf页数,只取前100页
  224. # if page_no >= 70:
  225. # log("pdf2text: pdf pages only get 70 pages")
  226. # break
  227. if page_count > 20:
  228. if 10 <= page_no < page_count - 10:
  229. page_no += 1
  230. continue
  231. # 判断页码在含表格页码中,直接拿已生成的text
  232. if page_no in has_table_no_list:
  233. # 判断表格是否跨页连接
  234. area_no = 0
  235. jump_page = 0
  236. for area in table_connect_list:
  237. if page_no in area:
  238. # 只记录一次text
  239. if page_no == area[0]:
  240. image_text = connect_text_list[area_no][0]
  241. text_list.append([image_text, page_no, 0])
  242. jump_page = 1
  243. area_no += 1
  244. # 是连接页的跳过后面步骤
  245. if jump_page:
  246. page_no += 1
  247. continue
  248. # 直接取text
  249. image_text = has_table_dict.get(page_no)[0]
  250. text_list.append([image_text, page_no, 0])
  251. page_no += 1
  252. continue
  253. # 不含表格的解析pdf
  254. else:
  255. if get_platform() == "Windows":
  256. try:
  257. interpreter.process_page(page)
  258. layout = device.get_result()
  259. except Exception:
  260. log("pdf2text pdfminer read pdf page error! continue...")
  261. continue
  262. else:
  263. # 设置超时时间
  264. try:
  265. # 解析pdf中的不含表格的页
  266. if get_platform() == "Windows":
  267. origin_pdf_analyze = pdf_analyze.__wrapped__
  268. layout = origin_pdf_analyze(interpreter, page, device)
  269. else:
  270. layout = pdf_analyze(interpreter, page, device, page_no)
  271. except TimeoutError as e:
  272. log("pdf2text pdfminer read pdf page time out!")
  273. return [-4]
  274. except Exception:
  275. log("pdf2text pdfminer read pdf page error! continue...")
  276. continue
  277. # 判断该页有没有文字对象,没有则有可能是有水印
  278. only_image = 1
  279. image_count = 0
  280. for x in layout:
  281. if isinstance(x, LTTextBoxHorizontal):
  282. only_image = 0
  283. if isinstance(x, LTFigure):
  284. image_count += 1
  285. # 如果该页图片数量过多,直接ocr整页识别
  286. log("pdf2text image_count " + str(image_count))
  287. if image_count >= 3:
  288. image_text = page_info_dict.get(page_no)[0]
  289. if image_text is None:
  290. with open(output_image_dict.get(page_no), "rb") as ff:
  291. image_stream = ff.read()
  292. image_text = from_ocr_interface(image_stream)
  293. if judge_error_code(image_text):
  294. return image_text
  295. page_info_dict[page_no][0] = image_text
  296. text_list.append([image_text, page_no, 0])
  297. page_no += 1
  298. continue
  299. order_list = []
  300. for x in layout:
  301. # 该对象是否是ocr识别
  302. ocr_flag = 0
  303. if get_platform() == "Windows":
  304. # print("x", page_no, x)
  305. print()
  306. if isinstance(x, LTTextBoxHorizontal):
  307. image_text = x.get_text()
  308. # 无法识别编码,用ocr
  309. if re.search('[(]cid:[0-9]+[)]', image_text):
  310. print(re.search('[(]cid:[0-9]+[)]', image_text))
  311. image_text = page_info_dict.get(page_no)[0]
  312. if image_text is None:
  313. with open(output_image_dict.get(page_no), "rb") as ff:
  314. image_stream = ff.read()
  315. image_text = from_ocr_interface(image_stream)
  316. if judge_error_code(image_text):
  317. return image_text
  318. page_info_dict[page_no][0] = image_text
  319. image_text = add_div(image_text)
  320. # order_list.append([image_text, page_no, x.bbox[1]])
  321. order_list = [[image_text, page_no, x.bbox[1]]]
  322. break
  323. else:
  324. image_text = add_div(image_text)
  325. order_list.append([image_text, page_no, x.bbox[1]])
  326. continue
  327. if isinstance(x, LTFigure):
  328. for image in x:
  329. if isinstance(image, LTImage):
  330. try:
  331. print("pdf2text LTImage size", page_no, image.width, image.height)
  332. image_stream = image.stream.get_data()
  333. # 小的图忽略
  334. if image.width <= 300 and image.height <= 300:
  335. continue
  336. # 有些水印导致pdf分割、读取报错
  337. # if image.width <= 200 and image.height<=200:
  338. # continue
  339. # img_test = Image.open(io.BytesIO(image_stream))
  340. # img_test.save('temp/LTImage.jpg')
  341. # 查看提取的图片高宽,太大则抛错用pdf输出图进行ocr识别
  342. img_test = Image.open(io.BytesIO(image_stream))
  343. if img_test.size[1] > 2000 or img_test.size[0] > 1500:
  344. print("pdf2text LTImage stream output size", img_test.size)
  345. raise Exception
  346. # 比较小的图则直接保存用ocr识别
  347. else:
  348. img_test.save('temp/LTImage.jpg')
  349. with open('temp/LTImage.jpg', "rb") as ff:
  350. image_stream = ff.read()
  351. image_text = from_ocr_interface(image_stream)
  352. if judge_error_code(image_text):
  353. return image_text
  354. # except pdfminer.pdftypes.PDFNotImplementedError:
  355. # with open(output_image_list[page_no], "rb") as ff:
  356. # image_stream = ff.read()
  357. except Exception:
  358. log("pdf2text pdfminer read image in page " + str(page_no) +
  359. " fail! use pymupdf read image...")
  360. # print(traceback.print_exc())
  361. image_text = page_info_dict.get(page_no)[0]
  362. if image_text is None:
  363. with open(output_image_dict.get(page_no), "rb") as ff:
  364. image_stream = ff.read()
  365. image_text = from_ocr_interface(image_stream)
  366. if judge_error_code(image_text):
  367. return image_text
  368. page_info_dict[page_no][0] = image_text
  369. ocr_flag = 1
  370. # 判断只拿到了水印图: 无文字输出且只有图片对象
  371. if image_text == "" and only_image:
  372. # 拆出该页pdf
  373. try:
  374. log("pdf2text guess pdf has watermark")
  375. split_path = get_single_pdf(path, page_no)
  376. except:
  377. # 如果拆分抛异常,则大概率不是水印图,用ocr识别图片
  378. log("pdf2text guess pdf has no watermark")
  379. image_text = page_info_dict.get(page_no)[0]
  380. if image_text is None:
  381. with open(output_image_dict.get(page_no), "rb") as ff:
  382. image_stream = ff.read()
  383. image_text = from_ocr_interface(image_stream)
  384. order_list.append([image_text, page_no, -1])
  385. page_info_dict[page_no][0] = image_text
  386. ocr_flag = 1
  387. continue
  388. if judge_error_code(split_path):
  389. return split_path
  390. # 调用office格式转换
  391. file_path = from_office_interface(split_path, unique_type_dir, 'html', 3)
  392. # if file_path == [-3]:
  393. # return [-3]
  394. if judge_error_code(file_path):
  395. return file_path
  396. # 获取html文本
  397. image_text = get_html_p(file_path)
  398. if judge_error_code(image_text):
  399. return image_text
  400. if get_platform() == "Windows":
  401. print("image_text", page_no, x.bbox[1], image_text)
  402. with open("temp" + str(x.bbox[0]) + ".jpg", "wb") as ff:
  403. ff.write(image_stream)
  404. image_text = add_div(image_text)
  405. if ocr_flag:
  406. order_list.append([image_text, page_no, -1])
  407. else:
  408. order_list.append([image_text, page_no, x.bbox[1]])
  409. order_list.sort(key=lambda z: z[2], reverse=True)
  410. # 有ocr参与识别
  411. if order_list[-1][2] == -1:
  412. ocr_order_list = [order_list[-1]]
  413. not_ocr_order_list = []
  414. not_ocr_text = ""
  415. # 去重,因读取失败而重复获取
  416. for order in order_list:
  417. if order[2] != -1:
  418. not_ocr_order_list.append(order)
  419. not_ocr_text += order[0]
  420. if string_similarity(ocr_order_list[0][0], not_ocr_text) >= 0.85:
  421. order_list = not_ocr_order_list
  422. else:
  423. order_list = ocr_order_list
  424. for order in order_list:
  425. text_list.append(order)
  426. page_no += 1
  427. text = ""
  428. for t in text_list:
  429. # text += add_div(t[0])
  430. if t[0] is not None:
  431. text += t[0]
  432. return [text]
  433. except UnicodeDecodeError as e:
  434. log("pdf2text pdfminer create pages failed! " + str(e))
  435. return [-3]
  436. except Exception as e:
  437. log("pdf2text error!")
  438. traceback.print_exc()
  439. return [-1]
  440. def get_single_pdf(path, page_no):
  441. log("into get_single_pdf")
  442. try:
  443. # print("path, ", path)
  444. pdf_origin = PdfFileReader(path, strict=False)
  445. pdf_new = PdfFileWriter()
  446. pdf_new.addPage(pdf_origin.getPage(page_no))
  447. path_new = path.split(".")[0] + "_split.pdf"
  448. with open(path_new, "wb") as ff:
  449. pdf_new.write(ff)
  450. return path_new
  451. except PyPDF2.utils.PdfReadError as e:
  452. raise e
  453. except Exception as e:
  454. log("get_single_pdf error! page " + str(page_no))
  455. traceback.print_exc()
  456. raise e
  457. def page_table_connect(has_table_dict):
  458. log("into page_table_connect")
  459. if not has_table_dict:
  460. return [], []
  461. try:
  462. # 判断是否有页码的表格相连
  463. table_connect_list = []
  464. temp_list = []
  465. # 离图片顶部或底部距离,页面高度的1/7
  466. threshold = 7
  467. page_no_list = list(has_table_dict.keys())
  468. page_no_list.sort(key=lambda x: x)
  469. for i in range(1, len(page_no_list)):
  470. page_info = has_table_dict.get(page_no_list[i])
  471. last_page_info = has_table_dict.get(page_no_list[i - 1])
  472. # 页码需相连
  473. if page_no_list[i] - page_no_list[i - 1] == 1:
  474. # 上一页最后一个区域的列数和下一页第一个区域列数都为0,且相等
  475. if not last_page_info[1][-1] and not page_info[1][0] and \
  476. last_page_info[1][-1] == page_info[1][0]:
  477. # 上一页的轮廓点要离底部一定距离内,下一页的轮廓点要离顶部一定距离内
  478. if last_page_info[4][0] - last_page_info[2][-1][1][1] \
  479. <= int(last_page_info[4][0] / threshold) \
  480. and page_info[2][0][0][1] - 0 \
  481. <= int(page_info[4][0] / threshold):
  482. temp_list.append(page_no_list[i - 1])
  483. temp_list.append(page_no_list[i])
  484. continue
  485. # 条件不符合的,存储之前保存的连接页码
  486. if len(temp_list) > 1:
  487. temp_list = list(set(temp_list))
  488. temp_list.sort(key=lambda x: x)
  489. table_connect_list.append(temp_list)
  490. temp_list = []
  491. if len(temp_list) > 1:
  492. temp_list = list(set(temp_list))
  493. temp_list.sort(key=lambda x: x)
  494. table_connect_list.append(temp_list)
  495. temp_list = []
  496. # 连接两页内容
  497. connect_text_list = []
  498. for area in table_connect_list:
  499. first_page_no = area[0]
  500. area_page_text = str(has_table_dict.get(first_page_no)[0])
  501. for i in range(1, len(area)):
  502. current_page_no = area[i]
  503. current_page_text = str(has_table_dict.get(current_page_no)[0])
  504. # 连接两个table
  505. table_prefix = re.finditer('<table border="1">', current_page_text)
  506. index_list = []
  507. for t in table_prefix:
  508. index_list.append(t.span())
  509. delete_index = index_list[0]
  510. current_page_text = current_page_text[:delete_index[0]] \
  511. + current_page_text[delete_index[1]:]
  512. table_suffix = re.finditer('</table>', area_page_text)
  513. index_list = []
  514. for t in table_suffix:
  515. index_list.append(t.span())
  516. delete_index = index_list[-1]
  517. area_page_text = area_page_text[:delete_index[0]] \
  518. + area_page_text[delete_index[1]:]
  519. area_page_text = area_page_text + current_page_text
  520. connect_text_list.append([area_page_text, area])
  521. return table_connect_list, connect_text_list
  522. except Exception as e:
  523. # print("page_table_connect", e)
  524. log("page_table_connect error!")
  525. traceback.print_exc()
  526. return [-1], [-1]
  527. @timeout(30, timeout_exception=TimeoutError)
  528. def read_pdf(path, package_name, packages):
  529. log(package_name)
  530. laparams = LAParams(line_overlap=0.01,
  531. char_margin=0.3,
  532. line_margin=0.01,
  533. word_margin=0.01,
  534. boxes_flow=0.1, )
  535. if package_name == packages[0]:
  536. fp = open(path, 'rb')
  537. parser = PDFParser(fp)
  538. doc_pdfminer = PDFDocument(parser)
  539. rsrcmgr = PDFResourceManager()
  540. device = PDFPageAggregator(rsrcmgr, laparams=laparams)
  541. interpreter = PDFPageInterpreter(rsrcmgr, device)
  542. return doc_pdfminer, device, interpreter
  543. elif package_name == packages[1]:
  544. doc_pymupdf = fitz.open(path)
  545. return doc_pymupdf
  546. elif package_name == packages[2]:
  547. doc_pypdf2 = PdfFileReader(path, strict=False)
  548. doc_pypdf2_new = PdfFileWriter()
  549. return doc_pypdf2, doc_pypdf2_new
  550. elif package_name == packages[3]:
  551. fp = open(path, 'rb')
  552. lt = LineTable()
  553. doc_top = 0
  554. doc_pdfplumber = read_pdfplumber(fp, laparams)
  555. return lt, doc_top, doc_pdfplumber
  556. @timeout(25, timeout_exception=TimeoutError)
  557. def read_pdfminer(path, laparams):
  558. fp = open(path, 'rb')
  559. parser = PDFParser(fp)
  560. doc_pdfminer = PDFDocument(parser)
  561. rsrcmgr = PDFResourceManager()
  562. device = PDFPageAggregator(rsrcmgr, laparams=laparams)
  563. interpreter = PDFPageInterpreter(rsrcmgr, device)
  564. return doc_pdfminer, device, interpreter
  565. @timeout(15, timeout_exception=TimeoutError)
  566. def read_pymupdf(path):
  567. return fitz.open(path)
  568. @timeout(15, timeout_exception=TimeoutError)
  569. def read_pypdf2(path):
  570. doc_pypdf2 = PdfFileReader(path, strict=False)
  571. doc_pypdf2_new = PdfFileWriter()
  572. return doc_pypdf2, doc_pypdf2_new
  573. @timeout(25, timeout_exception=TimeoutError, use_signals=False)
  574. def read_pdfplumber(path, laparams):
  575. fp = open(path, 'rb')
  576. lt = LineTable()
  577. doc_top = 0
  578. doc_pdfplumber = PDF(fp, laparams=laparams.__dict__)
  579. return lt, doc_top, doc_pdfplumber
  580. class PDFConvert:
  581. def __init__(self, path, unique_type_dir, need_page_no):
  582. self._doc = _Document(path)
  583. self.path = path
  584. self.unique_type_dir = unique_type_dir
  585. if not os.path.exists(self.unique_type_dir):
  586. os.mkdir(self.unique_type_dir)
  587. # 指定提取的页码范围
  588. self.need_page_no = need_page_no
  589. self.start_page_no = None
  590. self.end_page_no = None
  591. # 默认使用limit_page_cnt控制,前10页后10页
  592. if self.need_page_no is None:
  593. self.limit_page_cnt = 20
  594. else:
  595. # 使用start_page_no,end_page_no范围控制,例如2,5
  596. ss = self.need_page_no.split(',')
  597. if len(ss) != 2:
  598. self._doc.error_code = [-14]
  599. else:
  600. self.start_page_no = int(ss[0])
  601. self.end_page_no = int(ss[-1])
  602. if self.end_page_no == -1:
  603. self.end_page_no = 1000000
  604. self.start_page_no -= 1
  605. self.end_page_no -= 1
  606. if self.end_page_no <= self.start_page_no or self.start_page_no < 0 or self.end_page_no < -1:
  607. self._doc.error_code = [-14]
  608. self.packages = ["pdfminer", "PyMuPDF", "PyPDF2", "pdfplumber"]
  609. self.has_init_pdf = [0] * len(self.packages)
  610. @memory_decorator
  611. def init_package(self, package_name):
  612. # 各个包初始化
  613. try:
  614. laparams = LAParams(line_overlap=0.01,
  615. char_margin=0.3,
  616. line_margin=0.01,
  617. word_margin=0.01,
  618. boxes_flow=0.1, )
  619. if package_name == self.packages[0]:
  620. # fp = open(self.path, 'rb')
  621. # parser = PDFParser(fp)
  622. # self.doc_pdfminer = PDFDocument(parser)
  623. # rsrcmgr = PDFResourceManager()
  624. # self.laparams = LAParams(line_overlap=0.01,
  625. # char_margin=0.3,
  626. # line_margin=0.01,
  627. # word_margin=0.01,
  628. # boxes_flow=0.1,)
  629. # self.device = PDFPageAggregator(rsrcmgr, laparams=self.laparams)
  630. # self.interpreter = PDFPageInterpreter(rsrcmgr, self.device)
  631. self.doc_pdfminer, self.device, self.interpreter = read_pdfminer(self.path, laparams)
  632. self.has_init_pdf[0] = 1
  633. elif package_name == self.packages[1]:
  634. self.doc_pymupdf = read_pymupdf(self.path)
  635. self.has_init_pdf[1] = 1
  636. elif package_name == self.packages[2]:
  637. # self.doc_pypdf2 = PdfFileReader(self.path, strict=False)
  638. # self.doc_pypdf2_new = PdfFileWriter()
  639. self.doc_pypdf2, self.doc_pypdf2_new = read_pypdf2(self.path)
  640. self.has_init_pdf[2] = 1
  641. elif package_name == self.packages[3]:
  642. # self.fp = open(self.path, 'rb')
  643. # self.lt = LineTable()
  644. # self.doc_top = 0
  645. # self.doc_pdfplumber = PDF(self.fp, laparams=self.laparams.__dict__)
  646. self.lt, self.doc_top, self.doc_pdfplumber = read_pdfplumber(self.path, laparams)
  647. self.has_init_pdf[3] = 0
  648. else:
  649. log("Only Support Packages " + str(self.packages))
  650. raise Exception
  651. except Exception as e:
  652. log(package_name + " cannot open pdf!")
  653. traceback.print_exc()
  654. self._doc.error_code = [-3]
  655. def convert(self, limit_page_cnt=20):
  656. if self.has_init_pdf[0] == 0:
  657. self.init_package("pdfminer")
  658. if self._doc.error_code is not None:
  659. self._doc.error_code = None
  660. # pdfminer读不了直接转成图片识别
  661. self.get_all_page_image()
  662. return
  663. # 判断是否能读pdf
  664. try:
  665. pages = PDFPage.create_pages(self.doc_pdfminer)
  666. for page in pages:
  667. break
  668. pages = list(pages)
  669. # except pdfminer.psparser.PSEOF as e:
  670. except:
  671. # pdfminer 读不了空白页的对象,直接使用pymupdf转换出的图片进行ocr识别
  672. log("pdf2text pdfminer read failed! read by pymupdf!")
  673. traceback.print_exc()
  674. try:
  675. self.get_all_page_image()
  676. return
  677. except:
  678. traceback.print_exc()
  679. log("pdf2text use pymupdf read failed!")
  680. self._doc.error_code = [-3]
  681. return
  682. # 每一页进行处理
  683. pages = PDFPage.create_pages(self.doc_pdfminer)
  684. pages = list(pages)
  685. page_count = len(pages)
  686. page_no = 0
  687. for page in pages:
  688. # 指定pdf页码
  689. if self.start_page_no is not None and self.end_page_no is not None:
  690. if page_count < self.end_page_no:
  691. self.end_page_no = page_count
  692. if page_no < self.start_page_no or page_no >= self.end_page_no:
  693. page_no += 1
  694. continue
  695. # 限制pdf页数,只取前后各10页
  696. else:
  697. if page_count > limit_page_cnt and int(limit_page_cnt/2) <= page_no < page_count - int(limit_page_cnt/2):
  698. page_no += 1
  699. continue
  700. # 解析单页
  701. self._page = _Page(page, page_no)
  702. self.convert_page(page, page_no)
  703. if self._doc.error_code is None and self._page.error_code is not None:
  704. if self._page.error_code[0] in [-4, -3, 0]:
  705. page_no += 1
  706. continue
  707. else:
  708. self._doc.error_code = self._page.error_code
  709. break
  710. self._doc.add_child(self._page)
  711. page_no += 1
  712. def clean_text(self, _text):
  713. return re.sub("\s", "", _text)
  714. def get_text_lines(self, page, page_no):
  715. lt_line_list = []
  716. page_plumber = pdfPage(self.doc_pdfplumber, page, page_number=page_no, initial_doctop=self.doc_top)
  717. self.doc_top += page_plumber.height
  718. table_finder = TableFinder(page_plumber)
  719. all_width_zero = True
  720. for _edge in table_finder.get_edges():
  721. if _edge.get('linewidth') and _edge.get('linewidth') > 0:
  722. all_width_zero = False
  723. break
  724. for _edge in table_finder.get_edges():
  725. # print(_edge)
  726. if _edge.get('linewidth', 0.1) > 0 or all_width_zero:
  727. lt_line_list.append(LTLine(1, (float(_edge["x0"]), float(_edge["y0"])),
  728. (float(_edge["x1"]), float(_edge["y1"]))))
  729. log("pdf page %s has %s lines" % (str(page_no), str(len(lt_line_list))))
  730. return lt_line_list
  731. def get_page_lines(self, layout, page_no, show=0):
  732. def _plot(_line_list, mode=1):
  733. for _line in _line_list:
  734. if mode == 1:
  735. x0, y0, x1, y1 = _line.__dict__.get("bbox")
  736. elif mode == 2:
  737. x0, y0, x1, y1 = _line
  738. plt.plot([x0, x1], [y0, y1])
  739. plt.show()
  740. return
  741. def is_cross(A, B, C, D):
  742. if A[0] == B[0] == C[0] == D[0]:
  743. if A[1] <= C[1] <= B[1] or A[1] <= D[1] <= B[1] \
  744. or C[1] <= A[1] <= D[1] or C[1] <= B[1] <= D[1]:
  745. return True
  746. if A[1] == B[1] == C[1] == D[1]:
  747. if A[0] <= C[0] <= B[0] or A[0] <= D[0] <= B[0] \
  748. or C[0] <= A[0] <= D[0] or C[0] <= B[0] <= D[0]:
  749. return True
  750. line1 = LineString([A, B])
  751. line2 = LineString([C, D])
  752. int_pt = line1.intersection(line2)
  753. try:
  754. point_of_intersection = int_pt.x, int_pt.y
  755. return True
  756. except:
  757. return False
  758. def calculate_k(bbox):
  759. x = [bbox[0], bbox[2]]
  760. y = [bbox[1], bbox[3]]
  761. slope, intercept, r_value, p_value, std_err = linregress(x, y)
  762. # print('k', slope)
  763. if math.isnan(slope):
  764. slope = 0
  765. return slope
  766. def line_iou(line1, line2, axis=0):
  767. inter = min(line1[1][axis], line2[1][axis]) - max(line1[0][axis], line2[0][axis])
  768. # union = max(line1[1][axis], line2[1][axis]) - min(line1[0][axis], line2[0][axis])
  769. union = min(abs(line1[0][axis] - line1[1][axis]), abs(line2[0][axis] - line2[1][axis]))
  770. if union in [0, 0.]:
  771. iou = 0.
  772. else:
  773. iou = inter / union
  774. return iou
  775. def get_cross_line(_line_list, threshold=1, cross_times=0):
  776. # 根据是否有交点判断表格线
  777. _cross_line_list = []
  778. for line1 in _line_list:
  779. if line1 in _cross_line_list:
  780. continue
  781. if abs(line1[2] - line1[0]) > abs(line1[3] - line1[1]):
  782. p1 = [max(0, line1[0] - threshold), line1[1]]
  783. p2 = [min(line1[2] + threshold, page_w), line1[3]]
  784. else:
  785. p1 = [line1[0], max(0, line1[1] - threshold)]
  786. p2 = [line1[2], min(line1[3] + threshold, page_h)]
  787. line1 = [p1[0], p1[1], p2[0], p2[1]]
  788. _times = 0
  789. for line2 in _line_list:
  790. if abs(line2[2] - line2[0]) > abs(line2[3] - line2[1]):
  791. p3 = [max(0, line2[0] - threshold), line2[1]]
  792. p4 = [min(line2[2] + threshold, page_w), line2[3]]
  793. else:
  794. p3 = [line2[0], max(0, line2[1] - threshold)]
  795. p4 = [line2[2], min(line2[3] + threshold, page_h)]
  796. line2 = [p3[0], p3[1], p4[0], p4[1]]
  797. if line1 == line2:
  798. continue
  799. if is_cross(p1, p2, p3, p4):
  800. _times += 1
  801. if _times >= cross_times:
  802. _cross_line_list += [line1]
  803. break
  804. return _cross_line_list
  805. def repair_bias_line(_line_list):
  806. temp_list = []
  807. for line in _line_list:
  808. x0, y0, x1, y1 = line
  809. _y = min(y0, y1)
  810. _x = min(x0, x1)
  811. if abs(x0 - x1) > abs(y0 - y1):
  812. temp_list.append([x0, _y, x1, _y])
  813. else:
  814. temp_list.append([_x, y0, _x, y1])
  815. _line_list = temp_list
  816. return _line_list
  817. def repair_col_line(_straight_list, _bias_list, threshold=2, min_width=7):
  818. if not _straight_list or not _bias_list:
  819. print('add_col_bias_line empty', len(_straight_list), len(_bias_list))
  820. return []
  821. # 分列
  822. _straight_list.sort(key=lambda x: (x[0], x[1]))
  823. cols = []
  824. col = []
  825. current_w = _straight_list[0][0]
  826. for line in _straight_list:
  827. if abs(line[0] - line[2]) > abs(line[1] - line[3]):
  828. continue
  829. if min(line[0], line[2]) - threshold <= current_w <= max(line[0], line[2]) + threshold:
  830. col.append(line)
  831. else:
  832. if col:
  833. cols.append(col)
  834. col = [line]
  835. current_w = line[0]
  836. if col:
  837. cols.append(col)
  838. # 补充col
  839. new_list = []
  840. for line in bias_line_list:
  841. if abs(line[0] - line[2]) > abs(line[1] - line[3]):
  842. continue
  843. for col in cols:
  844. w = col[0][0]
  845. if w - threshold <= line[0] <= w + threshold or w - threshold <= line[2] <= w + threshold:
  846. new_list.append([w, line[1] - 3, w, line[3] + 3])
  847. new_list += _straight_list
  848. # 去重
  849. new_list = [str(x) for x in new_list]
  850. new_list = list(set(new_list))
  851. new_list = [eval(x) for x in new_list]
  852. # 分列
  853. new_list.sort(key=lambda x: (x[0], x[1]))
  854. cols = []
  855. col = []
  856. current_w = new_list[0][0]
  857. for line in new_list:
  858. if abs(line[0] - line[2]) > abs(line[1] - line[3]):
  859. continue
  860. if min(line[0], line[2]) - threshold <= current_w <= max(line[0], line[2]) + threshold:
  861. col.append(line)
  862. else:
  863. if col:
  864. cols.append(col)
  865. col = [line]
  866. current_w = line[0]
  867. if col:
  868. cols.append(col)
  869. # 删除col
  870. for col1 in cols:
  871. for col2 in cols:
  872. if col1 == col2 or abs(col1[0][0] - col2[0][0]) > min_width:
  873. continue
  874. col1_len, col2_len = 0, 0
  875. for c in col1:
  876. col1_len += abs(c[1] - c[3])
  877. for c in col2:
  878. col2_len += abs(c[1] - c[3])
  879. if col1_len > col2_len * 3:
  880. for c in col2:
  881. if c in new_list:
  882. new_list.remove(c)
  883. if col2_len > col1_len * 3:
  884. for c in col1:
  885. if c in new_list:
  886. new_list.remove(c)
  887. return new_list
  888. def merge_line(_line_list, threshold=2):
  889. new_line_list = []
  890. # 分列
  891. _line_list.sort(key=lambda x: (x[0], x[1]))
  892. cols = []
  893. col = [_line_list[0]]
  894. current_w = _line_list[0][0]
  895. for line in _line_list:
  896. if abs(line[0] - line[2]) > abs(line[1] - line[3]):
  897. continue
  898. if min(line[0], line[2]) - threshold <= current_w <= max(line[0], line[2]) + threshold \
  899. and is_cross(line[0:2], line[2:4], col[-1][0:2], col[-1][2:4]):
  900. col.append(line)
  901. else:
  902. if col:
  903. cols.append(col)
  904. col = [line]
  905. current_w = line[0]
  906. if col:
  907. cols.append(col)
  908. for col in cols:
  909. temp_c = col[0]
  910. col_w = col[0][0]
  911. for i in range(len(col) - 1):
  912. c = col[i]
  913. next_c = col[i + 1]
  914. if is_cross(c[0:2], c[2:4], next_c[0:2], next_c[2:4]):
  915. temp_c = [col_w, min(temp_c[1], c[1], c[3], next_c[1], next_c[3]), col_w,
  916. max(temp_c[3], c[1], c[3], next_c[1], next_c[3])]
  917. else:
  918. new_line_list.append(temp_c)
  919. temp_c = next_c
  920. if not new_line_list or (new_line_list and new_line_list[-1] != temp_c):
  921. new_line_list.append(temp_c)
  922. # 分行
  923. _line_list.sort(key=lambda x: (x[1], x[0]))
  924. rows = []
  925. row = []
  926. current_h = _line_list[0][1]
  927. for line in _line_list:
  928. if abs(line[0] - line[2]) < abs(line[1] - line[3]):
  929. continue
  930. if min(line[1], line[3]) - threshold <= current_h <= max(line[1], line[3]) + threshold:
  931. row.append(line)
  932. else:
  933. if row:
  934. rows.append(row)
  935. row = [line]
  936. current_h = line[1]
  937. if row:
  938. rows.append(row)
  939. for row in rows:
  940. temp_r = row[0]
  941. row_h = row[0][1]
  942. for i in range(len(row) - 1):
  943. r = row[i]
  944. next_r = row[i + 1]
  945. # if is_cross(r[0:2], r[2:4], next_r[0:2], next_r[2:4]):
  946. if line_iou([r[0:2], r[2:4]], [next_r[0:2], next_r[2:4]], axis=0):
  947. temp_r = [min(temp_r[0], r[0], r[2], next_r[0], next_r[2]), row_h,
  948. max(temp_r[2], r[0], r[2], next_r[0], next_r[2]), row_h]
  949. else:
  950. new_line_list.append(temp_r)
  951. temp_r = next_r
  952. if not new_line_list or (new_line_list and new_line_list[-1] != temp_r):
  953. new_line_list.append(temp_r)
  954. return new_line_list
  955. def remove_outline_no_cross(_line_list):
  956. row_list = []
  957. col_list = []
  958. for line in _line_list:
  959. # 存所有行
  960. if abs(line[0] - line[2]) > abs(line[1] - line[3]):
  961. row_list.append(line)
  962. # 存所有列
  963. if abs(line[0] - line[2]) < abs(line[1] - line[3]):
  964. col_list.append(line)
  965. if not col_list:
  966. return _line_list
  967. # 左右两条边框
  968. col_list.sort(key=lambda x: (x[0], x[1]))
  969. left_col = col_list[0]
  970. right_col = col_list[-1]
  971. # 判断有交点但中间区域无交点
  972. compare_list = []
  973. for col in [left_col, right_col]:
  974. add_h = abs(col[1]-col[3]) / 8
  975. center_area = [col[1]+add_h, col[3]-add_h]
  976. cross_cnt = 0
  977. center_cross_cnt = 0
  978. center_row_cnt = 0
  979. for row in row_list:
  980. if is_cross(row[0:2], row[2:4], col[0:2], col[2:4]):
  981. if center_area[0] <= row[1] <= center_area[1]:
  982. center_cross_cnt += 1
  983. else:
  984. cross_cnt += 1
  985. else:
  986. if center_area[0] <= row[1] <= center_area[1]:
  987. center_row_cnt += 1
  988. compare_list.append([cross_cnt, center_cross_cnt, center_row_cnt])
  989. _flag = True
  990. for c in compare_list:
  991. if c[0] >= 2 and c[1] == 0 and c[2] >= 2:
  992. continue
  993. _flag = False
  994. print('compare_list', compare_list)
  995. if _flag and compare_list[0][1] == compare_list[1][1] \
  996. and compare_list[0][2] == compare_list[1][2]:
  997. for col in [left_col, right_col]:
  998. if col in _line_list:
  999. _line_list.remove(col)
  1000. return _line_list
  1001. log('into get_page_lines')
  1002. page_h = layout.height
  1003. page_w = layout.width
  1004. element_list = []
  1005. line_list = []
  1006. bias_line_list = []
  1007. text_bbox_list = []
  1008. for element in layout:
  1009. if isinstance(element, LTTextContainer):
  1010. text_bbox_list.append(element.bbox)
  1011. # 只取这三种类型的bbox
  1012. if isinstance(element, (LTRect, LTCurve, LTLine)):
  1013. element_list.append(element)
  1014. if element.height > 0.5 and element.width > 0.5:
  1015. # print('element.height, element.width', element.height, element.width)
  1016. k = calculate_k(element.bbox)
  1017. if 1.73 / 3 < abs(k) < 1.73:
  1018. continue
  1019. else:
  1020. bias_line_list.append(element.bbox)
  1021. continue
  1022. line_list.append(element.bbox)
  1023. if not line_list and not bias_line_list:
  1024. return []
  1025. # 是否使用斜线来生成表格
  1026. if len(line_list) < 6 and len(bias_line_list) > len(line_list) * 2:
  1027. # print('use bias line')
  1028. # bias_line_list += add_col_bias_line(line_list, bias_line_list)
  1029. line_list = bias_line_list
  1030. # 去重
  1031. line_list = [str(x) for x in line_list]
  1032. line_list = list(set(line_list))
  1033. line_list = [eval(x) for x in line_list]
  1034. # 根据是否有交点判断表格线
  1035. cross_line_list = get_cross_line(line_list, threshold=2, cross_times=1)
  1036. if not cross_line_list:
  1037. return []
  1038. # 斜线校正
  1039. if cross_line_list:
  1040. cross_line_list = repair_bias_line(cross_line_list)
  1041. # 修复竖线
  1042. if bias_line_list:
  1043. cross_line_list = repair_col_line(cross_line_list, bias_line_list)
  1044. # 根据是否有交点判断表格线
  1045. cross_line_list = get_cross_line(cross_line_list, threshold=1, cross_times=1)
  1046. # 合并线条
  1047. if not cross_line_list:
  1048. return []
  1049. cross_line_list = merge_line(cross_line_list)
  1050. # 删除最外层嵌套边框
  1051. cross_line_list = remove_outline_no_cross(cross_line_list)
  1052. # 复用otr的部分后处理,补线
  1053. from otr.table_line_new import table_line_pdf
  1054. cross_line_list = table_line_pdf(cross_line_list, page_w, page_h)
  1055. # show
  1056. if show:
  1057. print('len(cross_line_list)', len(cross_line_list))
  1058. # _plot(line_list, mode=2)
  1059. _plot(cross_line_list, mode=2)
  1060. lt_line_list = []
  1061. for line in cross_line_list:
  1062. lt_line_list.append(LTLine(1, (float(line[0]), float(line[1])),
  1063. (float(line[2]), float(line[3]))))
  1064. log("pdf page %s has %s lines" % (str(page_no), str(len(lt_line_list))))
  1065. return lt_line_list
  1066. def recognize_text(self, layout, page_no, lt_text_list, lt_line_list):
  1067. list_tables, filter_objs, _, connect_textbox_list = self.lt.recognize_table(lt_text_list, lt_line_list, from_pdf=True)
  1068. self._page.in_table_objs = filter_objs
  1069. # print("=======text_len:%d:filter_len:%d"%(len(lt_text_list),len(filter_objs)))
  1070. for table in list_tables:
  1071. _table = _Table(table["table"], table["bbox"])
  1072. # self._page.children.append(_table)
  1073. self._page.add_child(_table)
  1074. list_sentences = ParseUtils.recognize_sentences(lt_text_list, filter_objs,
  1075. layout.bbox, page_no)
  1076. for sentence in list_sentences:
  1077. _sen = _Sentence(sentence.text, sentence.bbox)
  1078. self._page.add_child(_sen)
  1079. # pdf对象需反向排序
  1080. self._page.is_reverse = True
  1081. return list_tables
  1082. def is_text_legal(self, lt_text_list, page_no):
  1083. # 无法识别pdf字符编码,整页用ocr
  1084. text_temp = ""
  1085. for _t in lt_text_list:
  1086. text_temp += _t.get_text()
  1087. if re.search('[(]cid:[0-9]+[)]', text_temp):
  1088. log("text has cid! try pymupdf...")
  1089. page_image = self.get_page_image(page_no)
  1090. if judge_error_code(page_image):
  1091. self._page.error_code = page_image
  1092. else:
  1093. _image = _Image(page_image[1], page_image[0])
  1094. self._page.add_child(_image)
  1095. return False
  1096. match1 = re.findall(get_garble_code(), text_temp)
  1097. # match2 = re.search('[\u4e00-\u9fa5]', text_temp)
  1098. if len(match1) > 3 and len(text_temp) > 10:
  1099. log("pdf garbled code! try pymupdf... " + text_temp[:20])
  1100. page_image = self.get_page_image(page_no)
  1101. if judge_error_code(page_image):
  1102. self._page.error_code = page_image
  1103. else:
  1104. _image = _Image(page_image[1], page_image[0])
  1105. self._page.add_child(_image)
  1106. return False
  1107. return True
  1108. def judge_b_table(self, lt_text_list, table_list):
  1109. table_h_list = []
  1110. for table in table_list:
  1111. table_h_list.append([table.get('bbox')[1], table.get('bbox')[3]])
  1112. # 先分行
  1113. lt_text_list.sort(key=lambda x: (x.bbox[1], x.bbox[0]))
  1114. lt_text_row_list = []
  1115. current_h = lt_text_list[0].bbox[1]
  1116. row = []
  1117. threshold = 2
  1118. for lt_text in lt_text_list:
  1119. bbox = lt_text.bbox
  1120. if current_h - threshold <= bbox[1] <= current_h + threshold:
  1121. row.append(lt_text)
  1122. else:
  1123. if row:
  1124. lt_text_row_list.append(row)
  1125. row = [lt_text]
  1126. current_h = lt_text.bbox[1]
  1127. if row:
  1128. lt_text_row_list.append(row)
  1129. # print('lt_text_row_list')
  1130. # for r in lt_text_row_list:
  1131. # print('r', [x.get_text() for x in r])
  1132. # 判断文本中间是否是空格,或一行文本中间有多个
  1133. is_b_table_flag = False
  1134. is_b_table_cnt = 3
  1135. tolerate_cnt = 2
  1136. t_cnt = 0
  1137. row_cnt = 0
  1138. b_table_row_list = []
  1139. for row in lt_text_row_list:
  1140. # 水印行跳过
  1141. if len(row) == 1 and len(row[0].get_text()[:-1]) == 1:
  1142. continue
  1143. if len(row) == 1:
  1144. text = row[0].get_text()
  1145. bbox = row[0].bbox
  1146. match = re.search('[ ]{3,}', text)
  1147. if match and re.search('[\u4e00-\u9fff]{2,}', text[:match.span()[0]]) \
  1148. and re.search('[\u4e00-\u9fff]{2,}', text[match.span()[1]:]):
  1149. row_cnt += 1
  1150. t_cnt = 0
  1151. b_table_row_list += row
  1152. else:
  1153. # 容忍
  1154. if t_cnt < tolerate_cnt:
  1155. t_cnt += 1
  1156. continue
  1157. row_cnt = 0
  1158. b_table_row_list = []
  1159. else:
  1160. row_cnt += 1
  1161. t_cnt = 0
  1162. b_table_row_list += row
  1163. if row_cnt >= is_b_table_cnt:
  1164. # 判断在不在有边框表格的范围
  1165. in_flag = False
  1166. for table_h in table_h_list:
  1167. for b in b_table_row_list:
  1168. # print('b.bbox', b.bbox)
  1169. # print(table_h)
  1170. if table_h[1] <= b.bbox[1] <= table_h[0] or table_h[1] <= b.bbox[3] <= table_h[0]:
  1171. in_flag = True
  1172. break
  1173. if in_flag:
  1174. break
  1175. if in_flag:
  1176. is_b_table_flag = False
  1177. t_cnt = 0
  1178. row_cnt = 0
  1179. else:
  1180. print('True b_table_row_list', b_table_row_list)
  1181. print('table_h_list', table_h_list)
  1182. is_b_table_flag = True
  1183. break
  1184. log('pdf is_b_table_flag ' + str(is_b_table_flag))
  1185. return is_b_table_flag
  1186. def convert_page(self, page, page_no):
  1187. layout = self.get_layout(page, page_no)
  1188. if self._doc.error_code is not None:
  1189. return
  1190. if judge_error_code(layout):
  1191. self._page.error_code = layout
  1192. return
  1193. # 判断该页的对象类型,并存储
  1194. lt_text_list = []
  1195. lt_image_list = []
  1196. for x in layout:
  1197. if isinstance(x, (LTTextBoxHorizontal, LTTextBoxVertical)):
  1198. lt_text_list.append(x)
  1199. if isinstance(x, LTFigure):
  1200. for y in x:
  1201. if isinstance(y, LTImage):
  1202. # 小的图忽略
  1203. if y.width <= 300 and y.height <= 300:
  1204. continue
  1205. # 图的width超过layout width,很大可能是水印
  1206. if y.width > layout.width + 20:
  1207. continue
  1208. lt_image_list.append(y)
  1209. lt_text_list = self.delete_water_mark(lt_text_list, layout.bbox, 15)
  1210. log("convert_pdf page " + str(page_no))
  1211. log("len(lt_image_list), len(lt_text_list) " + str(len(lt_image_list)) + " " + str(len(lt_text_list)))
  1212. log('layout.width, layout.height' + str(layout.width) + str(layout.height))
  1213. # 若只有文本且图片数为0,直接提取文字及表格
  1214. # if only_image == 0 and image_count == 0:
  1215. # if len(lt_image_list) == 0 and len(lt_text_list) > 0:
  1216. # # PDFPlumber
  1217. # if self.has_init_pdf[3] == 0:
  1218. # self.init_package("pdfplumber")
  1219. # if self._doc.error_code is not None:
  1220. # self._doc.error_code = None
  1221. # log("init pdfplumber failed! try pymupdf...")
  1222. # # 调用pdfplumber获取pdf图片报错,则使用pypdf2将pdf转html
  1223. # page_image = self.get_page_image(page_no)
  1224. # if judge_error_code(page_image):
  1225. # self._page.error_code = page_image
  1226. # else:
  1227. # _image = _Image(page_image[1], page_image[0])
  1228. # self._page.add_child(_image)
  1229. # return
  1230. #
  1231. # if not self.is_text_legal(lt_text_list, page_no):
  1232. # return
  1233. #
  1234. # # 根据text规律,判断该页是否可能有无边框表格
  1235. # start_time = time.time()
  1236. # if self.judge_b_table(lt_text_list):
  1237. # page_image = self.get_page_image(page_no)
  1238. # if judge_error_code(page_image):
  1239. # self._page.error_code = page_image
  1240. # else:
  1241. # _image = _Image(page_image[1], page_image[0])
  1242. # _image.is_from_pdf = True
  1243. # _image.b_table_from_text = True
  1244. # _image.b_table_text_obj_list = lt_text_list
  1245. # _image.b_table_layout_size = (layout.width, layout.height)
  1246. # self._page.add_child(_image)
  1247. # log('convert_pdf judge_b_table set image cost: ' + str(time.time()-start_time))
  1248. #
  1249. # try:
  1250. # lt_line_list = self.get_page_lines(layout, page_no)
  1251. # except:
  1252. # traceback.print_exc()
  1253. # lt_line_list = []
  1254. # self._page.error_code = [-13]
  1255. # try:
  1256. # # lt_line_list = self.get_text_lines(page,page_no)
  1257. # self.recognize_text(layout, page_no, lt_text_list, lt_line_list)
  1258. # except:
  1259. # traceback.print_exc()
  1260. # self._page.error_code = [-8]
  1261. # 若该页图片数量过多,或无文本,则直接ocr整页识别
  1262. # elif image_count > 3 or only_image == 1:
  1263. if len(lt_image_list) > 3 or len(lt_text_list) == 0:
  1264. page_image = self.get_page_image(page_no)
  1265. if judge_error_code(page_image):
  1266. self._page.error_code = page_image
  1267. else:
  1268. _image = _Image(page_image[1], page_image[0])
  1269. _image.is_from_pdf = True
  1270. self._page.add_child(_image)
  1271. # 正常读取该页对象
  1272. else:
  1273. # 图表对象
  1274. for image in lt_image_list:
  1275. try:
  1276. print("pdf2text LTImage size", page_no, image.width, image.height)
  1277. image_stream = image.stream.get_data()
  1278. # 小的图忽略
  1279. if image.width <= 300 and image.height <= 300:
  1280. continue
  1281. # 查看提取的图片高宽,太大则用pdf输出图进行ocr识别
  1282. img_test = Image.open(io.BytesIO(image_stream))
  1283. if image.height >= 1000 and image.width >= 1000:
  1284. page_image = self.get_page_image(page_no)
  1285. if judge_error_code(page_image):
  1286. self._page.error_code = page_image
  1287. else:
  1288. _image = _Image(page_image[1], page_image[0])
  1289. _image.is_from_pdf = True
  1290. self._page.add_child(_image)
  1291. return
  1292. # 比较小的图则直接保存用ocr识别
  1293. else:
  1294. temp_path = self.unique_type_dir + 'page' + str(page_no) \
  1295. + '_lt' + str(lt_image_list.index(image)) + '.jpg'
  1296. img_test.save(temp_path)
  1297. with open(temp_path, "rb") as ff:
  1298. image_stream = ff.read()
  1299. _image = _Image(image_stream, temp_path, image.bbox)
  1300. self._page.add_child(_image)
  1301. except Exception:
  1302. log("pdf2text pdfminer read image in page " + str(page_no) +
  1303. " fail! use pymupdf read image...")
  1304. traceback.print_exc()
  1305. # pdf对象需反向排序
  1306. self._page.is_reverse = True
  1307. self.init_package("pdfplumber")
  1308. if not self.is_text_legal(lt_text_list, page_no):
  1309. return
  1310. try:
  1311. lt_line_list = self.get_page_lines(layout, page_no)
  1312. except:
  1313. traceback.print_exc()
  1314. lt_line_list = []
  1315. self._page.error_code = [-13]
  1316. table_list = self.recognize_text(layout, page_no, lt_text_list, lt_line_list)
  1317. # 根据text规律,判断该页是否可能有无边框表格
  1318. if self.judge_b_table(lt_text_list, table_list):
  1319. page_image = self.get_page_image(page_no)
  1320. if judge_error_code(page_image):
  1321. self._page.error_code = page_image
  1322. else:
  1323. _image = _Image(page_image[1], page_image[0])
  1324. _image.is_from_pdf = True
  1325. _image.b_table_from_text = True
  1326. _image.b_table_text_obj_list = lt_text_list
  1327. _image.b_table_layout_size = (layout.width, layout.height)
  1328. self._page.add_child(_image)
  1329. def get_layout(self, page, page_no):
  1330. log("get_layout")
  1331. if self.has_init_pdf[0] == 0:
  1332. self.init_package("pdfminer")
  1333. if self._doc.error_code is not None:
  1334. return
  1335. # 获取该页layout
  1336. start_time = time.time()
  1337. try:
  1338. if get_platform() == "Windows":
  1339. # origin_pdf_analyze = pdf_analyze.__wrapped__
  1340. # layout = origin_pdf_analyze(self.interpreter, page, self.device)
  1341. layout = pdf_analyze(self.interpreter, page, self.device, page_no)
  1342. else:
  1343. layout = pdf_analyze(self.interpreter, page, self.device, page_no)
  1344. except TimeoutError as e:
  1345. log("pdf2text pdfminer read pdf page " + str(page_no) + " time out! " + str(time.time() - start_time))
  1346. layout = [-4]
  1347. except Exception:
  1348. traceback.print_exc()
  1349. log("pdf2text pdfminer read pdf page " + str(page_no) + " error! continue...")
  1350. layout = [-3]
  1351. return layout
  1352. def get_page_image(self, page_no):
  1353. log("")
  1354. try:
  1355. if self.has_init_pdf[1] == 0:
  1356. self.init_package("PyMuPDF")
  1357. if self._doc.error_code is not None:
  1358. return
  1359. # save_dir = self.path.split(".")[-2] + "_" + self.path.split(".")[-1]
  1360. output = self.unique_type_dir + "page" + str(page_no) + ".png"
  1361. page = self.doc_pymupdf.loadPage(page_no)
  1362. rotate = int(0)
  1363. zoom_x = 2.
  1364. zoom_y = 2.
  1365. mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
  1366. pix = page.getPixmap(matrix=mat, alpha=False)
  1367. pix.writePNG(output)
  1368. # 输出图片resize
  1369. self.resize_image(output)
  1370. with open(output, "rb") as f:
  1371. pdf_image = f.read()
  1372. return [output, pdf_image]
  1373. except ValueError as e:
  1374. traceback.print_exc()
  1375. if str(e) == "page not in document":
  1376. log("pdf2Image page not in document! continue... page " + str(page_no))
  1377. return [0]
  1378. elif "encrypted" in str(e):
  1379. log("pdf2Image document need password " + str(page_no))
  1380. return [-7]
  1381. except RuntimeError as e:
  1382. if "cannot find page" in str(e):
  1383. log("pdf2Image page {} not in document! continue... ".format(str(page_no)) + str(e))
  1384. return [0]
  1385. else:
  1386. traceback.print_exc()
  1387. return [-3]
  1388. def get_all_page_image(self):
  1389. log("")
  1390. if self.has_init_pdf[1] == 0:
  1391. self.init_package("PyMuPDF")
  1392. if self._doc.error_code is not None:
  1393. return
  1394. page_count = self.doc_pymupdf.page_count
  1395. for page_no in range(page_count):
  1396. # 限制pdf页数,只取前10页后10页
  1397. if page_count > 20:
  1398. if 10 <= page_no < page_count - 10:
  1399. continue
  1400. self._page = _Page(None, page_no)
  1401. page_image = self.get_page_image(page_no)
  1402. if judge_error_code(page_image):
  1403. self._page.error_code = page_image
  1404. else:
  1405. _image = _Image(page_image[1], page_image[0])
  1406. self._page.add_child(_image)
  1407. # 报错继续读后面页面
  1408. if self._doc.error_code is None and self._page.error_code is not None:
  1409. continue
  1410. self._doc.add_child(self._page)
  1411. def connect_table(self, html_list):
  1412. if not html_list:
  1413. return html_list
  1414. # 判断初始条件1
  1415. # 0: 前一页最后一个表格为A,后一页第一个表格为B
  1416. # 1.1: A后无文本(除了页码),且B前无文本(除了页码)
  1417. # 1.2: B前有文字(可能是页眉,小于60字),且B的第一行前几个单元格为空,且第一行不为空的单元格有文字较多的格子
  1418. connect_flag_list = []
  1419. soup_list = []
  1420. for i, h in enumerate(html_list):
  1421. soup = BeautifulSoup(h, 'lxml')
  1422. soup_list.append(soup)
  1423. # 找最后一个表格
  1424. last_table_start, last_table_end = None, None
  1425. # print('h', h)
  1426. match = re.finditer('<table', h)
  1427. for m in match:
  1428. last_table_start = m.span()[0]
  1429. if last_table_start is not None:
  1430. match = re.finditer('</table>', h[last_table_start:])
  1431. for m in match:
  1432. last_table_end = m.span()[1] + last_table_start
  1433. # 最后一个表格后有无除了页码外的内容
  1434. connect_flag1 = False
  1435. if last_table_end is not None:
  1436. match = re.search('[^-/第页0-9,,]*', re.sub('<div>|</div>', '', h[last_table_end:]))
  1437. # print('match1', match.group())
  1438. if not match or match.group() == '':
  1439. connect_flag1 = True
  1440. # 找第一个表格
  1441. first_table_start, first_table_end = None, None
  1442. match = re.finditer('<table', h)
  1443. for m in match:
  1444. first_table_start = m.span()[0]
  1445. break
  1446. # 第一个表格后有无内容
  1447. connect_flag2 = False
  1448. if first_table_start is not None and first_table_start == 0:
  1449. connect_flag2 = True
  1450. # 有内容但是是页眉
  1451. if not connect_flag2:
  1452. tables = soup.findAll('table')
  1453. if tables:
  1454. first_table = tables[0]
  1455. rows = first_table.findAll('tr')
  1456. if rows:
  1457. first_row = rows[0]
  1458. col_text_list = [len(x.text) for x in first_row]
  1459. if len(h[:first_table_start]) <= 60 and col_text_list[0] == 0 and max(col_text_list) >= 30:
  1460. connect_flag2 = True
  1461. connect_flag_list.append([i, connect_flag2, connect_flag1])
  1462. # print('connect_flag_list', connect_flag_list)
  1463. # 根据条件1合并需连接页码,形成组
  1464. connect_pages_list = []
  1465. temp_list = []
  1466. for i, c in enumerate(connect_flag_list):
  1467. if temp_list and c[1]:
  1468. temp_list.append(c)
  1469. elif not temp_list and c[2]:
  1470. temp_list.append(c)
  1471. else:
  1472. if temp_list:
  1473. connect_pages_list.append(temp_list)
  1474. temp_list = []
  1475. connect_pages_list.append([c])
  1476. if temp_list:
  1477. connect_pages_list.append(temp_list)
  1478. # print('connect_pages_list', connect_pages_list)
  1479. # 判断后续条件:判断组内列数是否相同
  1480. connect_pages_list2 = []
  1481. for c_list in connect_pages_list:
  1482. if len(c_list) == 1:
  1483. connect_pages_list2.append(c_list)
  1484. else:
  1485. col_cnt_list = []
  1486. for c in c_list:
  1487. soup = soup_list[c[0]]
  1488. table1 = soup.findAll('table')[-1]
  1489. table2 = soup.findAll('table')[0]
  1490. tr1 = table1.findAll('tr')
  1491. tr2 = table2.findAll('tr')
  1492. td1 = tr1[-1].findAll('td')
  1493. td2 = tr2[0].findAll('td')
  1494. col_cnt_list.append([len(td2), len(td1)])
  1495. new_c_list = [c_list[0]]
  1496. # print('col_cnt_list', col_cnt_list)
  1497. for i in range(len(col_cnt_list) - 1):
  1498. if col_cnt_list[i][1] != col_cnt_list[i + 1][0]:
  1499. connect_pages_list2.append(new_c_list)
  1500. new_c_list = [c_list[i + 1]]
  1501. else:
  1502. new_c_list.append(c_list[i + 1])
  1503. if new_c_list:
  1504. connect_pages_list2.append(new_c_list)
  1505. # print('connect_pages_list2', connect_pages_list2)
  1506. # 符合连接条件的拼接表格
  1507. new_html_list = []
  1508. for c_list in connect_pages_list2:
  1509. if len(c_list) == 1:
  1510. new_html_list.append(html_list[c_list[0][0]])
  1511. continue
  1512. new_html = ''
  1513. for c in c_list:
  1514. # 加#@#@#防止替换错表格
  1515. new_html += html_list[c[0]] + '#@#@#'
  1516. new_html = new_html[:-5]
  1517. # ([-/第页0-9]|<div>|</div>)*
  1518. new_html = re.sub('</table>((<div>[-/第页0-9,,]*</div>#@#@#)|(#@#@#<div>[^<]*</div>)|#@#@#)<table border="1">',
  1519. '<tr><td>#@#@#</td></tr>',
  1520. new_html)
  1521. # print('new_html', new_html)
  1522. soup = BeautifulSoup(new_html, 'lxml')
  1523. trs = soup.findAll('tr')
  1524. for i in range(len(trs)):
  1525. if trs[i].get_text() == '#@#@#':
  1526. td1 = trs[i - 1].findAll('td')
  1527. td2 = trs[i + 1].findAll('td')
  1528. if td2[0].get_text() == '':
  1529. for j in range(len(td1)):
  1530. td1[j].string = td1[j].get_text() + td2[j].get_text()
  1531. trs[i + 1].decompose()
  1532. trs[i].decompose()
  1533. new_html = str(soup)
  1534. new_html_list.append(new_html)
  1535. html_str = ''
  1536. for h in new_html_list:
  1537. html_str += h
  1538. return [html_str]
  1539. def get_html(self):
  1540. if self._doc.error_code is not None:
  1541. return self._doc.error_code
  1542. self.convert()
  1543. if self._doc.error_code is not None:
  1544. return self._doc.error_code
  1545. html = self._doc.get_html(return_list=True)
  1546. # 表格连接
  1547. try:
  1548. html = self.connect_table(html)
  1549. except:
  1550. traceback.print_exc()
  1551. return [-12]
  1552. return html
  1553. def delete_water_mark(self, lt_text_list, page_bbox, times=5):
  1554. # 删除过多重复字句,为水印
  1555. duplicate_dict = {}
  1556. for _obj in lt_text_list:
  1557. t = _obj.get_text()
  1558. if t in duplicate_dict.keys():
  1559. duplicate_dict[t][0] += 1
  1560. duplicate_dict[t][1].append(_obj)
  1561. else:
  1562. duplicate_dict[t] = [1, [_obj]]
  1563. delete_text = []
  1564. for t in duplicate_dict.keys():
  1565. if duplicate_dict[t][0] >= times:
  1566. obj_list = duplicate_dict[t][1]
  1567. obj_list.sort(key=lambda x: x.bbox[3])
  1568. obj_distance_h = abs(obj_list[-1].bbox[3] - obj_list[0].bbox[1])
  1569. obj_list.sort(key=lambda x: x.bbox[2])
  1570. obj_distance_w = abs(obj_list[-1].bbox[2] - obj_list[0].bbox[0])
  1571. if obj_distance_h >= abs(page_bbox[1] - page_bbox[3]) * 0.7 \
  1572. and obj_distance_w >= abs(page_bbox[0] - page_bbox[2]) * 0.7:
  1573. delete_text.append(t)
  1574. temp_text_list = []
  1575. for _obj in lt_text_list:
  1576. t = _obj.get_text()
  1577. if t not in delete_text:
  1578. temp_text_list.append(_obj)
  1579. return temp_text_list
  1580. def resize_image(self, img_path, max_size=2000):
  1581. _img = cv2.imread(img_path)
  1582. if _img.shape[0] <= max_size or _img.shape[1] <= max_size:
  1583. return
  1584. else:
  1585. resize_axis = 0 if _img.shape[0] >= _img.shape[1] else 1
  1586. ratio = max_size / _img.shape[resize_axis]
  1587. new_shape = [0, 0]
  1588. new_shape[resize_axis] = max_size
  1589. new_shape[1 - resize_axis] = int(_img.shape[1 - resize_axis] * ratio)
  1590. _img = cv2.resize(_img, (new_shape[1], new_shape[0]))
  1591. cv2.imwrite(img_path, _img)
  1592. def get_single_pdf(self, path, page_no):
  1593. log("into get_single_pdf")
  1594. try:
  1595. pdf_origin = copy.deepcopy(self.doc_pypdf2)
  1596. pdf_new = copy.deepcopy(self.doc_pypdf2_new)
  1597. pdf_new.addPage(pdf_origin.getPage(page_no))
  1598. path_new = path.split(".")[0] + "_split.pdf"
  1599. with open(path_new, "wb") as ff:
  1600. pdf_new.write(ff)
  1601. return path_new
  1602. except PyPDF2.utils.PdfReadError as e:
  1603. return [-3]
  1604. except Exception as e:
  1605. log("get_single_pdf error! page " + str(page_no))
  1606. return [-3]
  1607. def get_text_font():
  1608. def flags_decomposer(flags):
  1609. """Make font flags human readable."""
  1610. l = []
  1611. if flags & 2 ** 0:
  1612. l.append("superscript")
  1613. if flags & 2 ** 1:
  1614. l.append("italic")
  1615. if flags & 2 ** 2:
  1616. l.append("serifed")
  1617. else:
  1618. l.append("sans")
  1619. if flags & 2 ** 3:
  1620. l.append("monospaced")
  1621. else:
  1622. l.append("proportional")
  1623. if flags & 2 ** 4:
  1624. l.append("bold")
  1625. return ", ".join(l)
  1626. def get_underlined_textLines(page):
  1627. """
  1628. 获取某页pdf上的所有下划线文本信息
  1629. :param page: fitz中的一页
  1630. :return: list of tuples,每个tuple都是一个完整的下划线覆盖的整体:[(下划线句, 所在blk_no, 所在line_no), ...]
  1631. """
  1632. paths = page.get_drawings() # get drawings on the current page
  1633. # 获取该页内所有的height很小的bbox。因为下划线其实大多是这种矩形
  1634. # subselect things we may regard as lines
  1635. lines = []
  1636. for p in paths:
  1637. for item in p["items"]:
  1638. if item[0] == "l": # an actual line
  1639. p1, p2 = item[1:]
  1640. if p1.y == p2.y:
  1641. lines.append((p1, p2))
  1642. elif item[0] == "re": # a rectangle: check if height is small
  1643. r = item[1]
  1644. if r.width > r.height and r.height <= 2:
  1645. lines.append((r.tl, r.tr)) # take top left / right points
  1646. # 获取该页的`max_lineheight`,用于下面比较距离使用
  1647. blocks = page.get_text("dict", flags=11)["blocks"]
  1648. max_lineheight = 0
  1649. for b in blocks:
  1650. for l in b["lines"]:
  1651. bbox = fitz.Rect(l["bbox"])
  1652. if bbox.height > max_lineheight:
  1653. max_lineheight = bbox.height
  1654. underlined_res = []
  1655. # 开始对下划线内容进行查询
  1656. # make a list of words
  1657. words = page.get_text("words")
  1658. # if underlined, the bottom left / right of a word
  1659. # should not be too far away from left / right end of some line:
  1660. for wdx, w in enumerate(words): # w[4] is the actual word string
  1661. r = fitz.Rect(w[:4]) # first 4 items are the word bbox
  1662. for p1, p2 in lines: # check distances for start / end points
  1663. if abs(r.bl - p1) <= max_lineheight: # 当前word的左下满足下划线左下
  1664. if abs(r.br - p2) <= max_lineheight: # 当前word的右下满足下划线右下(单个词,无空格)
  1665. print(f"Word '{w[4]}' is underlined! Its block-line number is {w[-3], w[-2]}")
  1666. underlined_res.append((w[4], w[-3], w[-2])) # 分别是(下划线词,所在blk_no,所在line_no)
  1667. break # don't check more lines
  1668. else: # 继续寻找同line右侧的有缘人,因为有些下划线覆盖的词包含多个词,多个词之间有空格
  1669. curr_line_num = w[-2] # line nunmber
  1670. for right_wdx in range(wdx + 1, len(words), 1):
  1671. _next_w = words[right_wdx]
  1672. if _next_w[-2] != curr_line_num: # 当前遍历到的右侧word已经不是当前行的了(跨行是不行的)
  1673. break
  1674. _r_right = fitz.Rect(_next_w[:4]) # 获取当前同行右侧某word的方框4点
  1675. if abs(_r_right.br - p2) <= max_lineheight: # 用此word右下点和p2(目标下划线右上点)算距离,距离要小于max_lineheight
  1676. print(
  1677. f"Word '{' '.join([_one_word[4] for _one_word in words[wdx:right_wdx + 1]])}' is underlined! " +
  1678. f"Its block-line number is {w[-3], w[-2]}")
  1679. underlined_res.append(
  1680. (' '.join([_one_word[4] for _one_word in words[wdx:right_wdx + 1]]),
  1681. w[-3], w[-2])
  1682. ) # 分别是(下划线词,所在blk_no,所在line_no)
  1683. break # don't check more lines
  1684. return underlined_res
  1685. _p = r'C:\Users\Administrator\Desktop\test_pdf\error2-2.pdf'
  1686. doc_pymupdf = read_pymupdf(_p)
  1687. page = doc_pymupdf[0]
  1688. blocks = page.get_text("dict", flags=11)["blocks"]
  1689. for b in blocks: # iterate through the text blocks
  1690. for l in b["lines"]: # iterate through the text lines
  1691. for s in l["spans"]: # iterate through the text spans
  1692. print("")
  1693. font_properties = "Font: '%s' (%s), size %g, color #%06x" % (
  1694. s["font"], # font name
  1695. flags_decomposer(s["flags"]), # readable font flags
  1696. s["size"], # font size
  1697. s["color"], # font color
  1698. )
  1699. print(s)
  1700. print("Text: '%s'" % s["text"]) # simple print of text
  1701. print(font_properties)
  1702. get_underlined_textLines(page)
  1703. # 以下为现成pdf单页解析接口
  1704. class ParseSentence:
  1705. def __init__(self, bbox, fontname, fontsize, _text, _title, title_text, _pattern, title_degree, is_outline,
  1706. outline_location, page_no):
  1707. (x0, y0, x1, y1) = bbox
  1708. self.x0 = x0
  1709. self.y0 = y0
  1710. self.x1 = x1
  1711. self.y1 = y1
  1712. self.bbox = bbox
  1713. self.fontname = fontname
  1714. self.fontsize = fontsize
  1715. self.text = _text
  1716. self.title = _title
  1717. self.title_text = title_text
  1718. self.groups = _pattern
  1719. self.title_degree = title_degree
  1720. self.is_outline = is_outline
  1721. self.outline_location = outline_location
  1722. self.page_no = page_no
  1723. def __repr__(self):
  1724. return "%s,%s,%s,%d,%s" % (self.text, self.title, self.is_outline, self.outline_location, str(self.bbox))
  1725. class ParseUtils:
  1726. @staticmethod
  1727. def getFontinfo(_page):
  1728. for _obj in _page._objs:
  1729. if isinstance(_obj, (LTTextBoxHorizontal, LTTextBoxVertical)):
  1730. for textline in _obj._objs:
  1731. done = False
  1732. for lchar in textline._objs:
  1733. if isinstance(lchar, (LTChar)):
  1734. _obj.fontname = lchar.fontname
  1735. _obj.fontsize = lchar.size
  1736. done = True
  1737. break
  1738. if done:
  1739. break
  1740. @staticmethod
  1741. def recognize_sentences(list_textbox, filter_objs, page_bbox, page_no,
  1742. remove_space=True, sourceP_LB=True):
  1743. list_textbox.sort(key=lambda x: x.bbox[0])
  1744. list_textbox.sort(key=lambda x: x.bbox[3], reverse=sourceP_LB)
  1745. cluster_textbox = []
  1746. for _textbox in list_textbox:
  1747. if _textbox in filter_objs:
  1748. continue
  1749. _find = False
  1750. for _ct in cluster_textbox:
  1751. if abs(_ct["y"] - _textbox.bbox[1]) < 5:
  1752. _find = True
  1753. _ct["textbox"].append(_textbox)
  1754. if not _find:
  1755. cluster_textbox.append({"y": _textbox.bbox[1], "textbox": [_textbox]})
  1756. cluster_textbox.sort(key=lambda x: x["y"], reverse=sourceP_LB)
  1757. list_sentences = []
  1758. for _line in cluster_textbox:
  1759. _textboxs = _line["textbox"]
  1760. _textboxs.sort(key=lambda x: x.bbox[0])
  1761. _linetext = _textboxs[0].get_text()
  1762. for _i in range(1, len(_textboxs)):
  1763. if abs(_textboxs[_i].bbox[0] - _textboxs[_i - 1].bbox[2]) > 60:
  1764. if _linetext[-1] not in (",", ",", "。", ".", "、", ";"):
  1765. _linetext += "=,="
  1766. _linetext += _textboxs[_i].get_text()
  1767. _linetext = re.sub("[\s\r\n]", "", _linetext)
  1768. _bbox = (_textboxs[0].bbox[0], _textboxs[0].bbox[1],
  1769. _textboxs[-1].bbox[2], _textboxs[-1].bbox[3])
  1770. _title = None
  1771. _pattern_groups = None
  1772. title_text = ""
  1773. if not _title:
  1774. _groups = ParseUtils.find_title_by_pattern(_textboxs[0].get_text())
  1775. if _groups:
  1776. _title = _groups[0][0]
  1777. title_text = _groups[0][1]
  1778. _pattern_groups = _groups
  1779. if not _title:
  1780. _groups = ParseUtils.find_title_by_pattern(_linetext)
  1781. if _groups:
  1782. _title = _groups[0][0]
  1783. title_text = _groups[0][1]
  1784. _pattern_groups = _groups
  1785. if not _title:
  1786. _title = ParseUtils.rec_incenter(_bbox, page_bbox)
  1787. title_degree = 2
  1788. if not _title:
  1789. _linetext = _linetext.replace("=,=", ",")
  1790. else:
  1791. _linetext = _linetext.replace("=,=", "")
  1792. title_degree = int(_title.split("_")[1])
  1793. # 页码
  1794. if ParseUtils.rec_incenter(_bbox, page_bbox) and re.search("^\d+$", _linetext) is not None:
  1795. continue
  1796. if _linetext == "" or re.search("^,+$", _linetext) is not None:
  1797. continue
  1798. is_outline = False
  1799. outline_location = -1
  1800. _search = re.search("(?P<text>.+?)\.{5,}(?P<nums>\d+)$", _linetext)
  1801. if _search is not None:
  1802. is_outline = True
  1803. _linetext = _search.group("text")
  1804. outline_location = int(_search.group("nums"))
  1805. list_sentences.append(
  1806. ParseSentence(_bbox, _textboxs[-1].__dict__.get("fontname"), _textboxs[-1].__dict__.get("fontsize"),
  1807. _linetext, _title, title_text, _pattern_groups, title_degree, is_outline,
  1808. outline_location, page_no))
  1809. # for _sen in list_sentences:
  1810. # print(_sen.__dict__)
  1811. return list_sentences
  1812. @staticmethod
  1813. def find_title_by_pattern(_text,
  1814. _pattern="(?P<title_1>(?P<title_1_index_0_0>^第?)(?P<title_1_index_1_1>[一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+)(?P<title_1_index_2_0>[、章]))|" \
  1815. "(?P<title_3>^(?P<title_3_index_0_1>[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+))|" \
  1816. "(?P<title_4>^(?P<title_4_index_0_0>第?)(?P<title_4_index_1_1>[一二三四五六七八九十]+)(?P<title_4_index_2_0>[节]))|" \
  1817. "(?P<title_11>^(?P<title_11_index_0_0>\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-])(?P<title_11_index_1_1>\d{1,2})(?P<title_11_index_2_0>[\..、\s\-]))|" \
  1818. "(?P<title_10>^(?P<title_10_index_0_0>\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-])(?P<title_10_index_1_1>\d{1,2})(?P<title_10_index_2_0>[\..、\s\-]))|" \
  1819. "(?P<title_7>^(?P<title_7_index_0_0>\d{1,2}[\..、\s\-])(?P<title_7_index_1_1>\d{1,2})(?P<title_7_index_2_0>[\..、\s\-]))|" \
  1820. "(?P<title_6>^(?P<title_6_index_0_1>\d{1,2})(?P<title_6_index_1_0>[\..、\s\-]))|" \
  1821. "(?P<title_15>^(?P<title_15_index_0_0>(?)(?P<title_15_index_1_1>\d{1,2})(?P<title_15_index_2_0>)))|" \
  1822. "(?P<title_17>^(?P<title_17_index_0_0>(?)(?P<title_17_index_1_1>[a-zA-Z]+)(?P<title_17_index_2_0>)))|"
  1823. "(?P<title_19>^(?P<title_19_index_0_0>(?)(?P<title_19_index_1_1>[一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+)(?P<title_19_index_2_0>)))|" \
  1824. ):
  1825. _se = re.search(_pattern, _text)
  1826. groups = []
  1827. if _se is not None:
  1828. _gd = _se.groupdict()
  1829. for k, v in _gd.items():
  1830. if v is not None:
  1831. groups.append((k, v))
  1832. if len(groups):
  1833. groups.sort(key=lambda x: x[0])
  1834. return groups
  1835. return None
  1836. @staticmethod
  1837. def rec_incenter(o_bbox, p_bbox):
  1838. p_width = p_bbox[2] - p_bbox[0]
  1839. l_space = (o_bbox[0] - p_bbox[0]) / p_width
  1840. r_space = (p_bbox[2] - o_bbox[2]) / p_width
  1841. if abs((l_space - r_space)) < 0.1 and l_space > 0.2:
  1842. return "title_2"
  1843. @staticmethod
  1844. def is_first_title(_title):
  1845. if _title is None:
  1846. return False
  1847. if re.search("^\d+$", _title) is not None:
  1848. if int(_title) == 1:
  1849. return True
  1850. return False
  1851. if re.search("^[一二三四五六七八九十百]+$", _title) is not None:
  1852. if _title == "一":
  1853. return True
  1854. return False
  1855. if re.search("^[a-z]+$", _title) is not None:
  1856. if _title == "a":
  1857. return True
  1858. return False
  1859. if re.search("^[A-Z]+$", _title) is not None:
  1860. if _title == "A":
  1861. return True
  1862. return False
  1863. if re.search("^[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]$", _title) is not None:
  1864. if _title == "Ⅰ":
  1865. return True
  1866. return False
  1867. return False
  1868. @staticmethod
  1869. def get_next_title(_title):
  1870. if re.search("^\d+$", _title) is not None:
  1871. return str(int(_title) + 1)
  1872. if re.search("^[一二三四五六七八九十百]+$", _title) is not None:
  1873. _next_title = ParseUtils.make_increase(['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'],
  1874. re.sub("[十百]", '', _title))
  1875. _next_title = list(_next_title)
  1876. _next_title.reverse()
  1877. if _next_title[-1] != "十":
  1878. if len(_next_title) >= 2:
  1879. _next_title.insert(-1, '十')
  1880. if len(_next_title) >= 4:
  1881. _next_title.insert(-3, '百')
  1882. if _title[0] == "十":
  1883. if _next_title == "十":
  1884. _next_title = ["二", "十"]
  1885. _next_title.insert(0, "十")
  1886. _next_title = "".join(_next_title)
  1887. return _next_title
  1888. if re.search("^[a-z]+$", _title) is not None:
  1889. _next_title = ParseUtils.make_increase([chr(i + ord('a')) for i in range(26)], _title)
  1890. _next_title = list(_next_title)
  1891. _next_title.reverse()
  1892. return "".join(_next_title)
  1893. if re.search("^[A-Z]+$", _title) is not None:
  1894. _next_title = ParseUtils.make_increase([chr(i + ord('A')) for i in range(26)], _title)
  1895. _next_title = list(_next_title)
  1896. _next_title.reverse()
  1897. return "".join(_next_title)
  1898. if re.search("^[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]$", _title) is not None:
  1899. _sort = ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ", "Ⅻ"]
  1900. _index = _sort.index(_title)
  1901. if _index < len(_sort) - 1:
  1902. return _sort[_index + 1]
  1903. return None
  1904. @staticmethod
  1905. def make_increase(_sort, _title, _add=1):
  1906. if len(_title) == 0 and _add == 0:
  1907. return ""
  1908. if len(_title) == 0 and _add == 1:
  1909. return _sort[0]
  1910. _index = _sort.index(_title[-1])
  1911. next_index = (_index + _add) % len(_sort)
  1912. next_chr = _sort[next_index]
  1913. if _index == len(_sort) - 1:
  1914. _add = 1
  1915. else:
  1916. _add = 0
  1917. return next_chr + ParseUtils.make_increase(_sort, _title[:-1], _add)
  1918. @staticmethod
  1919. def rec_serial(_text, o_bbox, p_bbox, fontname, _pattern="(?P<title_1>^[一二三四五六七八九十]+[、])|" \
  1920. "(?P<title_2>^\d+[\.、\s])|" \
  1921. "(?P<title_3>^\d+\.\d+[\.、\s])|" \
  1922. "(?P<title_4>^\d+\.\d+\.\d+[\.、\s])|" \
  1923. "(?P<title_5>^\d+\.\d+\.\d+\.\d+[\.、\s])"):
  1924. # todo :recog the serial of the sentence
  1925. _se = re.search(_pattern, _text)
  1926. if _se is not None:
  1927. _gd = _se.groupdict()
  1928. for k, v in _gd.items():
  1929. if v is not None:
  1930. return k
  1931. return None
  1932. if __name__ == '__main__':
  1933. # get_text_font()
  1934. PDFConvert(r"C:/Users/Administrator/Downloads/1651896704621.pdf", "C:/Users/Administrator/Downloads/1").get_html()
  1935. # print(b'\x10')