convert_pdf.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. import copy
  2. import io
  3. import os
  4. import re
  5. import sys
  6. from bs4 import BeautifulSoup
  7. sys.path.append(os.path.dirname(__file__) + "/../")
  8. from pdfplumber import PDF
  9. from pdfplumber.table import TableFinder
  10. from pdfplumber.page import Page as pdfPage
  11. from format_convert.convert_tree import _Document, _Page, _Image, _Sentence, _Table, TextBox
  12. import time
  13. from PIL import Image
  14. import traceback
  15. import cv2
  16. import PyPDF2
  17. from PyPDF2 import PdfFileReader, PdfFileWriter
  18. from pdfminer.pdfparser import PDFParser
  19. from pdfminer.pdfdocument import PDFDocument
  20. from pdfminer.pdfpage import PDFPage
  21. from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
  22. from pdfminer.converter import PDFPageAggregator
  23. from pdfminer.layout import LTTextBoxHorizontal, LAParams, LTFigure, LTImage, LTCurve, LTText, LTChar, LTRect, \
  24. LTTextBoxVertical, LTLine, LTTextContainer, LTTextLine
  25. from format_convert.utils import judge_error_code, get_platform, LineTable, log, \
  26. memory_decorator, get_garble_code, get_md5_from_bytes, bytes2np, bbox_iou, get_garble_code2, get_traditional_chinese
  27. import fitz
  28. from format_convert.wrapt_timeout_decorator import timeout
  29. from otr.table_line_pdf import table_line_pdf
  30. # import jieba
  31. @memory_decorator
  32. def pdf2text(path, unique_type_dir):
  33. return
  34. @timeout(10, timeout_exception=TimeoutError)
  35. def pdf_analyze(interpreter, page, device, page_no):
  36. pdf_time = time.time()
  37. interpreter.process_page(page)
  38. layout = device.get_result()
  39. log("page_no: " + str(page_no) + " pdf_analyze cost: " + str(time.time() - pdf_time))
  40. return layout
  41. @timeout(25, timeout_exception=TimeoutError)
  42. def read_pdfminer(path, laparams):
  43. fp = open(path, 'rb')
  44. parser = PDFParser(fp)
  45. doc_pdfminer = PDFDocument(parser)
  46. rsrcmgr = PDFResourceManager()
  47. device = PDFPageAggregator(rsrcmgr, laparams=laparams)
  48. interpreter = PDFPageInterpreter(rsrcmgr, device)
  49. return doc_pdfminer, device, interpreter
  50. @timeout(15, timeout_exception=TimeoutError)
  51. def read_pymupdf(path):
  52. return fitz.open(path)
  53. @timeout(15, timeout_exception=TimeoutError)
  54. def read_pypdf2(path):
  55. doc_pypdf2 = PdfFileReader(path, strict=False)
  56. doc_pypdf2_new = PdfFileWriter()
  57. return doc_pypdf2, doc_pypdf2_new
  58. @timeout(25, timeout_exception=TimeoutError, use_signals=False)
  59. def read_pdfplumber(path, laparams):
  60. fp = open(path, 'rb')
  61. lt = LineTable()
  62. doc_top = 0
  63. doc_pdfplumber = PDF(fp, laparams=laparams.__dict__)
  64. return lt, doc_top, doc_pdfplumber
  65. class PDFConvert:
  66. def __init__(self, path, unique_type_dir, need_page_no):
  67. self._doc = _Document(path)
  68. self.path = path
  69. self.unique_type_dir = unique_type_dir
  70. if not os.path.exists(self.unique_type_dir):
  71. os.mkdir(self.unique_type_dir)
  72. # 指定提取的页码范围
  73. self.need_page_no = need_page_no
  74. self.start_page_no = None
  75. self.end_page_no = None
  76. # 默认使用limit_page_cnt控制,前10页后10页
  77. if self.need_page_no is None:
  78. self.limit_page_cnt = 20
  79. else:
  80. # 使用start_page_no,end_page_no范围控制,例如2,5
  81. ss = self.need_page_no.split(',')
  82. if len(ss) != 2:
  83. self._doc.error_code = [-14]
  84. else:
  85. self.start_page_no = int(ss[0])
  86. self.end_page_no = int(ss[-1])
  87. if self.end_page_no == -1:
  88. self.end_page_no = 1000000
  89. self.start_page_no -= 1
  90. self.end_page_no -= 1
  91. if self.end_page_no <= self.start_page_no or self.start_page_no < 0 or self.end_page_no < -1:
  92. self._doc.error_code = [-14]
  93. self.packages = ["pdfminer", "PyMuPDF", "PyPDF2", "pdfplumber"]
  94. self.has_init_pdf = [0] * len(self.packages)
  95. # 记录图片对象的md5,用于去除大量重复图片
  96. self.md5_image_obj_list = []
  97. @memory_decorator
  98. def init_package(self, package_name):
  99. # 各个包初始化
  100. try:
  101. laparams = LAParams(line_overlap=0.01,
  102. char_margin=0.3,
  103. line_margin=0.01,
  104. word_margin=0.01,
  105. boxes_flow=0.1, )
  106. if package_name == self.packages[0]:
  107. self.doc_pdfminer, self.device, self.interpreter = read_pdfminer(self.path, laparams)
  108. self.has_init_pdf[0] = 1
  109. elif package_name == self.packages[1]:
  110. self.doc_pymupdf = read_pymupdf(self.path)
  111. self.has_init_pdf[1] = 1
  112. elif package_name == self.packages[2]:
  113. self.doc_pypdf2, self.doc_pypdf2_new = read_pypdf2(self.path)
  114. self.has_init_pdf[2] = 1
  115. elif package_name == self.packages[3]:
  116. self.lt, self.doc_top, self.doc_pdfplumber = read_pdfplumber(self.path, laparams)
  117. self.has_init_pdf[3] = 1
  118. else:
  119. log("Only Support Packages " + str(self.packages))
  120. raise Exception
  121. except Exception as e:
  122. log(package_name + " cannot open pdf!")
  123. traceback.print_exc()
  124. self._doc.error_code = [-3]
  125. def convert(self, limit_page_cnt=20):
  126. if self.has_init_pdf[0] == 0:
  127. self.init_package("pdfminer")
  128. if self._doc.error_code is not None:
  129. self._doc.error_code = None
  130. # pdfminer读不了直接转成图片识别
  131. self.get_all_page_image()
  132. return
  133. # 判断是否能读pdf
  134. try:
  135. pages = PDFPage.create_pages(self.doc_pdfminer)
  136. for page in pages:
  137. break
  138. pages = list(pages)
  139. # except pdfminer.psparser.PSEOF as e:
  140. except:
  141. # pdfminer 读不了空白页的对象,直接使用pymupdf转换出的图片进行ocr识别
  142. log("pdfminer read failed! read by pymupdf!")
  143. traceback.print_exc()
  144. try:
  145. self.get_all_page_image()
  146. return
  147. except:
  148. traceback.print_exc()
  149. log("use pymupdf read failed!")
  150. self._doc.error_code = [-3]
  151. return
  152. # 每一页进行处理
  153. pages = PDFPage.create_pages(self.doc_pdfminer)
  154. pages = list(pages)
  155. page_count = len(pages)
  156. page_no = 0
  157. for page in pages:
  158. # 指定pdf页码
  159. if self.start_page_no is not None and self.end_page_no is not None:
  160. if page_count < self.end_page_no:
  161. self.end_page_no = page_count
  162. if page_no < self.start_page_no or page_no >= self.end_page_no:
  163. page_no += 1
  164. continue
  165. # 限制pdf页数,只取前后各10页
  166. else:
  167. if page_count > limit_page_cnt and int(limit_page_cnt/2) <= page_no < page_count - int(limit_page_cnt/2):
  168. page_no += 1
  169. continue
  170. # 解析单页
  171. start_time = time.time()
  172. self._page = _Page(page, page_no)
  173. self.convert_page(page, page_no)
  174. log('convert_page page_no: ' + str(page_no) + ' cost: ' + str(time.time()-start_time))
  175. if self._doc.error_code is None and self._page.error_code is not None:
  176. if self._page.error_code[0] in [-4, -3, 0]:
  177. page_no += 1
  178. continue
  179. else:
  180. self._doc.error_code = self._page.error_code
  181. break
  182. self._doc.add_child(self._page)
  183. page_no += 1
  184. self.delete_same_image()
  185. self.delete_header_footer()
  186. # self.delete_bold_text_duplicate()
  187. def delete_same_image(self, show=0):
  188. # 剔除大量重复图片
  189. md5_dict = {}
  190. for _md5, image_obj in self.md5_image_obj_list:
  191. if _md5 in md5_dict.keys():
  192. md5_dict[_md5] += [image_obj]
  193. else:
  194. md5_dict[_md5] = [image_obj]
  195. cnt_threshold = 10
  196. delete_obj_list = []
  197. for _md5 in md5_dict.keys():
  198. img_list = md5_dict.get(_md5)
  199. # print('len(md5_dict.get(_md5))', _md5, len(img_list))
  200. if len(img_list) >= cnt_threshold:
  201. if show:
  202. img_np = bytes2np(img_list[0].content)
  203. cv2.namedWindow('delete same img_np', cv2.WINDOW_NORMAL)
  204. cv2.imshow('delete same img_np', img_np)
  205. cv2.waitKey(0)
  206. delete_obj_list += img_list
  207. for page in self._doc.children:
  208. for obj in delete_obj_list:
  209. if obj in page.children:
  210. page.children.remove(obj)
  211. if show:
  212. for page in self._doc.children:
  213. for obj in page.children:
  214. if isinstance(obj, _Image):
  215. img_np = bytes2np(obj.content)
  216. cv2.imshow('page img_np', img_np)
  217. cv2.waitKey(0)
  218. def delete_header_footer(self):
  219. sen_dict = {}
  220. for page in self._doc.children:
  221. for obj in page.children:
  222. if isinstance(obj, _Sentence):
  223. key = str(obj.content) + ' ' + str(int(obj.y))
  224. # print('key', key)
  225. if key in sen_dict.keys():
  226. sen_dict[key] += [obj]
  227. else:
  228. sen_dict[key] = [obj]
  229. for key in sen_dict.keys():
  230. l = sen_dict.get(key)
  231. if len(l) >= 2/3 * max(10, len(self._doc.children)):
  232. for page in self._doc.children:
  233. new_children = []
  234. for obj in page.children:
  235. if isinstance(obj, _Sentence):
  236. if obj not in l:
  237. new_children.append(obj)
  238. else:
  239. new_children.append(obj)
  240. page.children = new_children
  241. print('len(l)', len(l), len(self._doc.children))
  242. print('delete_header_footer l[0]', l[0].content, l[0].y)
  243. return
  244. def delete_bold_text_duplicate(self, lt_text_box_list):
  245. # 拿出所有LTChar
  246. lt_char_list = []
  247. for lt_text_box in lt_text_box_list:
  248. for lt_text_line in lt_text_box:
  249. for lt_char in lt_text_line:
  250. if isinstance(lt_char, LTChar):
  251. lt_char_list.append(lt_char)
  252. # 找出需剔除的
  253. lt_char_list.sort(key=lambda x: (int(x.bbox[1]), x.bbox[0]))
  254. delete_list = []
  255. for i in range(len(lt_char_list)):
  256. lt_char1 = lt_char_list[i]
  257. bbox1 = lt_char1.bbox
  258. # lt_char2 = lt_char_list[i+1]
  259. # bbox2 = lt_char2.bbox
  260. if lt_char1 in delete_list:
  261. continue
  262. # if lt_char2 in delete_list:
  263. # continue
  264. # if lt_char1.get_text() == lt_char2.get_text() and bbox1[0] <= bbox2[0] <= bbox1[2] <= bbox2[2] \
  265. # and int(bbox1[1]) == int(bbox2[1]) and int(bbox1[3]) == int(bbox2[3]) \
  266. # and re.search('[\u4e00-\u9fff():、,。]', lt_char1.get_text()):
  267. for j in range(i+1, len(lt_char_list)):
  268. lt_char2 = lt_char_list[j]
  269. bbox2 = lt_char2.bbox
  270. if lt_char2 in delete_list:
  271. continue
  272. if lt_char1.get_text() == lt_char2.get_text() and bbox_iou(bbox1, bbox2) >= 0.3 \
  273. and re.search('[\u4e00-\u9fff():、,。]', lt_char1.get_text()):
  274. # continue
  275. delete_list.append(lt_char2)
  276. # 重新组装
  277. new_lt_text_box_list = []
  278. for lt_text_box in lt_text_box_list:
  279. new_lt_text_box = LTTextBoxHorizontal()
  280. for lt_text_line in lt_text_box:
  281. new_lt_text_line = LTTextLine(0.01)
  282. for lt_char in lt_text_line:
  283. if lt_char in delete_list:
  284. continue
  285. if isinstance(lt_char, LTChar):
  286. new_lt_text_line.add(lt_char)
  287. new_lt_text_box.add(new_lt_text_line)
  288. new_lt_text_box_list.append(new_lt_text_box)
  289. return new_lt_text_box_list
  290. def clean_text(self, _text):
  291. return re.sub("\s", "", _text)
  292. def get_text_lines(self, page, page_no):
  293. lt_line_list = []
  294. page_plumber = pdfPage(self.doc_pdfplumber, page, page_number=page_no, initial_doctop=self.doc_top)
  295. self.doc_top += page_plumber.height
  296. table_finder = TableFinder(page_plumber)
  297. all_width_zero = True
  298. for _edge in table_finder.get_edges():
  299. if _edge.get('linewidth') and _edge.get('linewidth') > 0:
  300. all_width_zero = False
  301. break
  302. for _edge in table_finder.get_edges():
  303. # print(_edge)
  304. if _edge.get('linewidth', 0.1) > 0 or all_width_zero:
  305. lt_line_list.append(LTLine(1, (float(_edge["x0"]), float(_edge["y0"])),
  306. (float(_edge["x1"]), float(_edge["y1"]))))
  307. log("pdf page_no %s has %s lines" % (str(page_no), str(len(lt_line_list))))
  308. return lt_line_list
  309. def get_page_lines(self, layout, page_no, show=0):
  310. lt_line_list = table_line_pdf(layout, page_no, show)
  311. return lt_line_list
  312. def recognize_text(self, layout, page_no, lt_text_list, lt_line_list):
  313. list_tables, filter_objs, _, connect_textbox_list = self.lt.recognize_table(lt_text_list, lt_line_list, from_pdf=True)
  314. self._page.in_table_objs = filter_objs
  315. # print("=======text_len:%d:filter_len:%d"%(len(lt_text_list),len(filter_objs)))
  316. for table in list_tables:
  317. _table = _Table(table["table"], table["bbox"])
  318. # self._page.children.append(_table)
  319. self._page.add_child(_table)
  320. list_sentences = ParseUtils.recognize_sentences(lt_text_list, filter_objs,
  321. layout.bbox, page_no)
  322. for sentence in list_sentences:
  323. # print('sentence.text', sentence.text)
  324. _sen = _Sentence(sentence.text, sentence.bbox)
  325. self._page.add_child(_sen)
  326. # pdf对象需反向排序
  327. self._page.is_reverse = True
  328. return list_tables
  329. def is_text_legal(self, lt_text_list, page_no):
  330. # 无法识别pdf字符编码,整页用ocr
  331. text_temp = ""
  332. for _t in lt_text_list:
  333. text_temp += _t.get_text()
  334. if re.search('[(]cid:[0-9]+[)]', text_temp):
  335. log("page_no: " + str(page_no) + " text has cid! try pymupdf...")
  336. page_image = self.get_page_image(page_no)
  337. if judge_error_code(page_image):
  338. self._page.error_code = page_image
  339. else:
  340. _image = _Image(page_image[1], page_image[0])
  341. self._page.add_child(_image)
  342. return False
  343. match1 = re.findall(get_garble_code(), text_temp)
  344. # match2 = re.search('[\u4e00-\u9fa5]', text_temp)
  345. if len(match1) > 8 and len(text_temp) > 10:
  346. log("page_no: " + str(page_no) + " garbled code! try pymupdf... " + text_temp[:20])
  347. page_image = self.get_page_image(page_no)
  348. if judge_error_code(page_image):
  349. self._page.error_code = page_image
  350. else:
  351. _image = _Image(page_image[1], page_image[0])
  352. self._page.add_child(_image)
  353. return False
  354. return True
  355. def judge_b_table(self, lt_text_list, table_list, page_no):
  356. table_h_list = []
  357. for table in table_list:
  358. table_h_list.append([table.get('bbox')[1], table.get('bbox')[3]])
  359. # 先分行
  360. lt_text_list.sort(key=lambda x: (x.bbox[1], x.bbox[0]))
  361. lt_text_row_list = []
  362. current_h = lt_text_list[0].bbox[1]
  363. row = []
  364. threshold = 2
  365. for lt_text in lt_text_list:
  366. bbox = lt_text.bbox
  367. if current_h - threshold <= bbox[1] <= current_h + threshold:
  368. row.append(lt_text)
  369. else:
  370. if row:
  371. lt_text_row_list.append(row)
  372. row = [lt_text]
  373. current_h = lt_text.bbox[1]
  374. if row:
  375. lt_text_row_list.append(row)
  376. # 判断文本中间是否是空格,或一行文本中间有多个
  377. is_b_table_cnt = 3
  378. tolerate_cnt = 2
  379. t_cnt = 0
  380. row_cnt = 0
  381. b_table_row_list = []
  382. all_b_table = []
  383. for row in lt_text_row_list:
  384. # 水印行跳过
  385. if len(row) == 1 and len(row[0].get_text()[:-1]) == 1:
  386. continue
  387. # 目录行跳过
  388. continue_flag = False
  389. for r in row:
  390. if re.search('[.·]{7,}', r.get_text()):
  391. continue_flag = True
  392. break
  393. if continue_flag:
  394. continue
  395. if len(row) == 1:
  396. text = row[0].get_text()
  397. bbox = row[0].bbox
  398. match = re.search('[ ]{3,}', text)
  399. if match and re.search('[\u4e00-\u9fff]{2,}', text[:match.span()[0]]) \
  400. and re.search('[\u4e00-\u9fff]{2,}', text[match.span()[1]:]):
  401. row_cnt += 1
  402. t_cnt = 0
  403. b_table_row_list += row
  404. else:
  405. # 容忍
  406. if t_cnt < tolerate_cnt:
  407. t_cnt += 1
  408. continue
  409. if b_table_row_list and row_cnt >= is_b_table_cnt:
  410. all_b_table.append(b_table_row_list)
  411. row_cnt = 0
  412. b_table_row_list = []
  413. else:
  414. row_cnt += 1
  415. t_cnt = 0
  416. b_table_row_list += row
  417. if b_table_row_list and row_cnt >= is_b_table_cnt:
  418. all_b_table.append(b_table_row_list)
  419. # 对每个可能的b_table判断是否与table相交
  420. is_b_table_flag = False
  421. for b_table in all_b_table:
  422. # 判断在不在有边框表格的范围
  423. in_flag = False
  424. for table_h in table_h_list:
  425. for b in b_table:
  426. if min(table_h) <= b.bbox[1] <= max(table_h) or min(table_h) <= b.bbox[3] <= max(table_h):
  427. in_flag = True
  428. break
  429. if in_flag:
  430. break
  431. if in_flag:
  432. is_b_table_flag = False
  433. else:
  434. is_b_table_flag = True
  435. # print('is_b_table_flag True ', [[x.get_text(), x.bbox] for x in b_table])
  436. # print('table_h_list', table_h_list)
  437. break
  438. log("page_no: " + str(page_no) + ' is_b_table_flag ' + str(is_b_table_flag))
  439. return is_b_table_flag
  440. def convert_page(self, page, page_no):
  441. layout = self.get_layout(page, page_no)
  442. if self._doc.error_code is not None:
  443. return
  444. if judge_error_code(layout):
  445. self._page.error_code = layout
  446. return
  447. # 判断该页的对象类型,并存储
  448. lt_text_list = []
  449. lt_image_list = []
  450. for x in layout:
  451. if isinstance(x, (LTTextBoxHorizontal, LTTextBoxVertical)):
  452. lt_text_list.append(x)
  453. if isinstance(x, LTFigure):
  454. for y in x:
  455. if isinstance(y, LTImage):
  456. # 小的图忽略
  457. if y.width <= 300 and y.height <= 300:
  458. continue
  459. # 图的width超过layout width,很大可能是水印
  460. if y.width > layout.width + 20:
  461. continue
  462. lt_image_list.append(y)
  463. # 判断读出来的是乱码,但有图片直接识别
  464. all_text = ''.join([x.get_text() for x in lt_text_list])
  465. all_text = re.sub('[\s\d]', '', all_text)
  466. if len(re.findall(get_garble_code2(), all_text)) >= 3 and len(lt_image_list) >= 1:
  467. log('嵌入的文字是乱码1: ' + str(all_text[:10]))
  468. lt_text_list = []
  469. # print('11111', re.findall(get_traditional_chinese(), all_text))
  470. if 3 <= len(re.findall(get_traditional_chinese(), all_text)) <= len(all_text) / 2 and len(lt_image_list) >= 1:
  471. log('嵌入的文字是乱码2: ' + str(all_text[:10]))
  472. lt_text_list = []
  473. # 解决重复粗体字问题
  474. lt_text_list = self.delete_bold_text_duplicate(lt_text_list)
  475. # 删除水印字
  476. lt_text_list = self.delete_water_mark(lt_text_list, layout.bbox, 15)
  477. log("page_no: " + str(page_no) + " len(lt_image_list), len(lt_text_list) " + str(len(lt_image_list)) + " " + str(len(lt_text_list)))
  478. # 若该页图片数量过多,或无文本,则直接ocr整页识别
  479. if len(lt_image_list) > 4 or len(lt_text_list) == 0:
  480. page_image = self.get_page_image(page_no)
  481. if judge_error_code(page_image):
  482. self._page.error_code = page_image
  483. else:
  484. _image = _Image(page_image[1], page_image[0])
  485. _image.is_from_pdf = True
  486. self._page.add_child(_image)
  487. # 正常读取该页对象
  488. else:
  489. # 图表对象
  490. for image in lt_image_list:
  491. try:
  492. # print("pdf2text LTImage size", page_no, image.width, image.height)
  493. image_stream = image.stream.get_data()
  494. # 小的图忽略
  495. if image.width <= 300 and image.height <= 300:
  496. continue
  497. # 查看提取的图片高宽,太大则用pdf输出图进行ocr识别
  498. img_test = Image.open(io.BytesIO(image_stream))
  499. if image.height >= 1000 and image.width >= 1000:
  500. page_image = self.get_page_image(page_no)
  501. if judge_error_code(page_image):
  502. self._page.error_code = page_image
  503. else:
  504. _image = _Image(page_image[1], page_image[0])
  505. _image.is_from_pdf = True
  506. self._page.add_child(_image)
  507. image_md5 = get_md5_from_bytes(page_image[1])
  508. self.md5_image_obj_list.append([image_md5, _image])
  509. return
  510. # 比较小的图则直接保存用ocr识别
  511. else:
  512. temp_path = self.unique_type_dir + 'page' + str(page_no) \
  513. + '_lt' + str(lt_image_list.index(image)) + '.jpg'
  514. img_test.save(temp_path)
  515. with open(temp_path, "rb") as ff:
  516. image_stream = ff.read()
  517. _image = _Image(image_stream, temp_path, image.bbox)
  518. self._page.add_child(_image)
  519. image_md5 = get_md5_from_bytes(image_stream)
  520. self.md5_image_obj_list.append([image_md5, _image])
  521. except Exception:
  522. log("page_no: " + str(page_no) + " pdfminer read image fail! use pymupdf read image...")
  523. traceback.print_exc()
  524. # pdf对象需反向排序
  525. self._page.is_reverse = True
  526. if self.has_init_pdf[3] == 0:
  527. self.init_package("pdfplumber")
  528. if not self.is_text_legal(lt_text_list, page_no):
  529. return
  530. try:
  531. lt_line_list = self.get_page_lines(layout, page_no)
  532. except:
  533. traceback.print_exc()
  534. lt_line_list = []
  535. self._page.error_code = [-13]
  536. table_list = self.recognize_text(layout, page_no, lt_text_list, lt_line_list)
  537. # 根据text规律,判断该页是否可能有无边框表格
  538. if self.judge_b_table(lt_text_list, table_list, page_no):
  539. page_image = self.get_page_image(page_no)
  540. if judge_error_code(page_image):
  541. self._page.error_code = page_image
  542. else:
  543. _image = _Image(page_image[1], page_image[0])
  544. _image.is_from_pdf = True
  545. _image.b_table_from_text = True
  546. _image.b_table_text_obj_list = lt_text_list
  547. _image.b_table_layout_size = (layout.width, layout.height)
  548. self._page.add_child(_image)
  549. def get_layout(self, page, page_no):
  550. if self.has_init_pdf[0] == 0:
  551. self.init_package("pdfminer")
  552. if self._doc.error_code is not None:
  553. return
  554. # 获取该页layout
  555. start_time = time.time()
  556. try:
  557. if get_platform() == "Windows":
  558. layout = pdf_analyze(self.interpreter, page, self.device, page_no)
  559. else:
  560. layout = pdf_analyze(self.interpreter, page, self.device, page_no)
  561. except TimeoutError as e:
  562. log("page_no: " + str(page_no) + " pdfminer read page time out! " + str(time.time() - start_time))
  563. layout = [-4]
  564. except Exception:
  565. traceback.print_exc()
  566. log("page_no: " + str(page_no) + " pdfminer read page error! continue...")
  567. layout = [-3]
  568. log("page_no: " + str(page_no) + " get_layout cost: " + str(time.time()-start_time))
  569. return layout
  570. def get_page_image(self, page_no):
  571. start_time = time.time()
  572. try:
  573. if self.has_init_pdf[1] == 0:
  574. self.init_package("PyMuPDF")
  575. if self._doc.error_code is not None:
  576. return
  577. # save_dir = self.path.split(".")[-2] + "_" + self.path.split(".")[-1]
  578. output = self.unique_type_dir + "page" + str(page_no) + ".png"
  579. page = self.doc_pymupdf.loadPage(page_no)
  580. rotate = int(0)
  581. zoom_x = 2.
  582. zoom_y = 2.
  583. mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
  584. pix = page.getPixmap(matrix=mat, alpha=False)
  585. pix.writePNG(output)
  586. # 输出图片resize
  587. self.resize_image(output)
  588. with open(output, "rb") as f:
  589. pdf_image = f.read()
  590. log("page_no: " + str(page_no) + ' get_page_image cost: ' + str(time.time()-start_time))
  591. return [output, pdf_image]
  592. except ValueError as e:
  593. traceback.print_exc()
  594. if str(e) == "page not in document":
  595. log("page_no: " + str(page_no) + " page not in document! continue...")
  596. return [0]
  597. elif "encrypted" in str(e):
  598. log("page_no: " + str(page_no) + " document need password")
  599. return [-7]
  600. except RuntimeError as e:
  601. if "cannot find page" in str(e):
  602. log("page_no: " + str(page_no) + " page cannot find in document! continue...")
  603. return [0]
  604. else:
  605. traceback.print_exc()
  606. return [-3]
  607. def get_all_page_image(self):
  608. start_time = time.time()
  609. if self.has_init_pdf[1] == 0:
  610. self.init_package("PyMuPDF")
  611. if self._doc.error_code is not None:
  612. return
  613. page_count = self.doc_pymupdf.page_count
  614. for page_no in range(page_count):
  615. # 限制pdf页数,只取前10页后10页
  616. if page_count > 20:
  617. if 10 <= page_no < page_count - 10:
  618. continue
  619. self._page = _Page(None, page_no)
  620. page_image = self.get_page_image(page_no)
  621. if judge_error_code(page_image):
  622. self._page.error_code = page_image
  623. else:
  624. _image = _Image(page_image[1], page_image[0])
  625. self._page.add_child(_image)
  626. # 报错继续读后面页面
  627. if self._doc.error_code is None and self._page.error_code is not None:
  628. continue
  629. self._doc.add_child(self._page)
  630. log('get_all_page_image cost: ' + str(time.time()-start_time))
  631. def connect_table(self, html_list):
  632. if not html_list:
  633. return html_list
  634. # 判断初始条件1
  635. # 0: 前一页最后一个表格为A,后一页第一个表格为B
  636. # 1.1: A后无文本(除了页码),且B前无文本(除了页码)
  637. # 1.2: B前有文字(可能是页眉,小于60字),且B的第一行前几个单元格为空,且第一行不为空的单元格有文字较多的格子
  638. # 1.3: B前有文字(可能是页眉,小于60字),且B的第一行第一个单元格为空,且有文字的格子数量占所有格子的一半
  639. # 1.4: B前有文字(可能是页眉,小于60字),且B的第一行第一个单元格为纯数字序号
  640. # 1.5: A后有文字(除了页码还有页眉),且A的后面只有一行且中文不超过15个字
  641. connect_flag_list = []
  642. soup_list = []
  643. for i, h in enumerate(html_list):
  644. soup = BeautifulSoup(h, 'lxml')
  645. soup_list.append(soup)
  646. # 找最后一个表格
  647. last_table_start, last_table_end = None, None
  648. match = re.finditer('<table', h)
  649. for m in match:
  650. last_table_start = m.span()[0]
  651. if last_table_start is not None:
  652. match = re.finditer('</table>', h[last_table_start:])
  653. for m in match:
  654. last_table_end = m.span()[1] + last_table_start
  655. # 最后一个表格后有无除了页码外的内容
  656. connect_flag1 = False
  657. if last_table_end is not None:
  658. match = re.findall('[^-/第页0-9,,]', re.sub('<div>|</div>', '', h[last_table_end:]))
  659. # print('match', match.group())
  660. # if not match or match.group() == '':
  661. if len(match) == 0:
  662. connect_flag1 = True
  663. # 有页脚
  664. if not connect_flag1:
  665. if len(re.findall('<div>', h[last_table_end:])) <= 1 \
  666. and len(re.findall('[\u4e00-\u9fff]', h[last_table_end:])) <= 60:
  667. connect_flag1 = True
  668. # 找第一个表格
  669. first_table_start, first_table_end = None, None
  670. match = re.finditer('<table', h)
  671. for m in match:
  672. first_table_start = m.span()[0]
  673. break
  674. # 第一个表格前有无内容
  675. connect_flag2 = False
  676. if first_table_start is not None and first_table_start == 0:
  677. connect_flag2 = True
  678. # 有内容但是是页眉
  679. if not connect_flag2:
  680. tables = soup.findAll('table')
  681. if tables:
  682. first_table = tables[0]
  683. rows = first_table.findAll('tr')
  684. if rows:
  685. first_row = rows[0]
  686. col_text_len_list = [len(x.text) for x in first_row]
  687. col_text_list = [x.text for x in first_row]
  688. # 文字大于60且第一个为空
  689. if not connect_flag2 and len(h[:first_table_start]) <= 60 and col_text_len_list[0] == 0 and max(col_text_len_list) >= 30:
  690. connect_flag2 = True
  691. # 有文字格子数占一半一下且第一个格子为空
  692. if not connect_flag2 and col_text_len_list.count(0) >= len(col_text_len_list) / 2 and col_text_len_list[0] == 0:
  693. connect_flag2 = True
  694. # 表格前最多只有一行且第一个格子为纯数字
  695. if not connect_flag2 and len(col_text_list) > 0 and \
  696. len(re.findall('<div>', h[:first_table_start])) <= 0 and \
  697. len(re.findall('\d', col_text_list[0])) == len(col_text_list[0]):
  698. connect_flag2 = True
  699. # if not connect_flag2 and len(re.findall('<div>', h[:first_table_start])) <= 0 and len(re.findall('[\u4e00-\u9fff]', h[:first_table_start])) <= 25:
  700. # connect_flag2 = True
  701. connect_flag_list.append([i, connect_flag2, connect_flag1])
  702. print('connect_flag_list', connect_flag_list)
  703. # 根据条件1合并需连接页码,形成组
  704. connect_pages_list = []
  705. if connect_flag_list:
  706. temp_list = [connect_flag_list[0]]
  707. for i in range(1, len(connect_flag_list)):
  708. c = connect_flag_list[i]
  709. if c[1] and temp_list[-1][2]:
  710. temp_list.append(c)
  711. else:
  712. if temp_list:
  713. connect_pages_list.append(temp_list)
  714. temp_list = [c]
  715. # connect_pages_list.append([c])
  716. if temp_list:
  717. connect_pages_list.append(temp_list)
  718. print('connect_pages_list', connect_pages_list)
  719. # 判断后续条件:判断组内列数是否相同
  720. connect_pages_list2 = []
  721. for c_list in connect_pages_list:
  722. if len(c_list) == 1:
  723. connect_pages_list2.append(c_list)
  724. else:
  725. col_cnt_list = []
  726. # 单元格可能被复制了,相同的合并当做一列
  727. merge_col_cnt_list = []
  728. for c in c_list:
  729. soup = soup_list[c[0]]
  730. table1 = soup.findAll('table')[-1]
  731. table2 = soup.findAll('table')[0]
  732. tr1 = table1.findAll('tr')
  733. tr2 = table2.findAll('tr')
  734. td1 = tr1[-1].findAll('td')
  735. td2 = tr2[0].findAll('td')
  736. col_cnt_list.append([len(td2), len(td1)])
  737. # # 计算合并重复文本格子后的列数
  738. # last_text = td1[0].text
  739. # merge_td1 = [last_text]
  740. # for td in td1:
  741. # if td.text == last_text:
  742. # continue
  743. # else:
  744. # merge_td1.append(td.text)
  745. # last_text = td.text
  746. # last_text = td2[0].text
  747. # merge_td2 = [last_text]
  748. # for td in td2:
  749. # if td.text == last_text:
  750. # continue
  751. # else:
  752. # merge_td2.append(td.text)
  753. # last_text = td.text
  754. # merge_col_cnt_list.append([len(merge_td2), len(merge_td1)])
  755. # 判断
  756. new_c_list = [c_list[0]]
  757. # print('col_cnt_list', col_cnt_list)
  758. for i in range(len(col_cnt_list) - 1):
  759. if col_cnt_list[i][1] != col_cnt_list[i + 1][0]:
  760. # and merge_col_cnt_list[i][1] != merge_col_cnt_list[i + 1][0]:
  761. connect_pages_list2.append(new_c_list)
  762. new_c_list = [c_list[i + 1]]
  763. else:
  764. new_c_list.append(c_list[i + 1])
  765. if new_c_list:
  766. connect_pages_list2.append(new_c_list)
  767. print('connect_pages_list2', connect_pages_list2)
  768. # 符合连接条件的拼接表格
  769. new_html_list = []
  770. for c_list in connect_pages_list2:
  771. if len(c_list) == 1:
  772. new_html_list.append(html_list[c_list[0][0]])
  773. continue
  774. new_html = ''
  775. for c in c_list:
  776. match = re.finditer('</table>', new_html)
  777. last_table_index = None
  778. for m in match:
  779. last_table_index = m.span()[0]
  780. new_html += html_list[c[0]]
  781. # print('html_list[c[0]]', html_list[c[0]])
  782. if last_table_index is None:
  783. continue
  784. match = re.finditer('<table border="1">', new_html[last_table_index:])
  785. first_table_index = None
  786. for m in match:
  787. first_table_index = last_table_index + m.span()[1]
  788. break
  789. if first_table_index is None:
  790. continue
  791. # print('re', re.findall('</table>.*?<table border="1">', new_html[last_table_index:first_table_index]))
  792. # 非贪婪匹配
  793. new_html_sub = re.sub('</table>.*?<table border="1">',
  794. '<tr><td>#@#@#</td></tr>',
  795. new_html[last_table_index:first_table_index])
  796. new_html = new_html[:last_table_index] + new_html_sub + new_html[first_table_index:]
  797. # print('new_html', new_html)
  798. # new_html = new_html[:-5]
  799. # ([-/第页0-9]|<div>|</div>)*
  800. # 非贪婪匹配
  801. # match = re.finditer('</table>.*?<table border="1">', new_html)
  802. # for m in match:
  803. # if '#@#@#' in m.group():
  804. #
  805. # new_html = re.sub('</table>.*#@#@#.*?<table border="1">',
  806. # '<tr><td>#@#@#</td></tr>',
  807. # new_html)
  808. # print('new_html', new_html)
  809. soup = BeautifulSoup(new_html, 'lxml')
  810. trs = soup.findAll('tr')
  811. decompose_trs = []
  812. for i in range(len(trs)):
  813. if trs[i].get_text() == '#@#@#':
  814. td1 = trs[i - 1].findAll('td')
  815. td2 = trs[i + 1].findAll('td')
  816. if td2[0].get_text() == '':
  817. # 解决连续多页是一行表格,该行会被去掉问题
  818. find_father = False
  819. for father, son in decompose_trs:
  820. # print('son', son)
  821. # print('td1', trs[i - 1])
  822. if father != '' and son == trs[i - 1]:
  823. td_father = father.findAll('td')
  824. for j in range(len(td_father)):
  825. # print('td_father[j].string3', td_father[j].string)
  826. td_father[j].string = td_father[j].get_text() + td2[j].get_text()
  827. # print('td_father[j].string4', td_father[j].string)
  828. find_father = True
  829. decompose_trs.append([father, trs[i + 1]])
  830. break
  831. if not find_father:
  832. for j in range(len(td1)):
  833. # print('td1[j].string1', td1[j].string)
  834. td1[j].string = td1[j].get_text() + td2[j].get_text()
  835. # print('td1[j].string2', td1[j].string)
  836. decompose_trs.append([trs[i - 1], trs[i + 1]])
  837. # print('trs[i + 1]', trs[i + 1])
  838. # trs[i + 1].decompose()
  839. # print('trs[i-1]', trs[i-1])
  840. # trs[i].decompose()
  841. decompose_trs.append(['', trs[i]])
  842. # print('decompose_trs', decompose_trs)
  843. # for father, son in decompose_trs:
  844. # print('father', father)
  845. # print('son', son)
  846. # print('len(decompose_trs)', len(decompose_trs))
  847. for father, son in decompose_trs:
  848. for tr in trs:
  849. if tr == son:
  850. tr.decompose()
  851. break
  852. new_html = str(soup)
  853. new_html_list.append(new_html)
  854. html_str = ''
  855. for h in new_html_list:
  856. html_str += h
  857. return [html_str]
  858. def get_html(self):
  859. if self._doc.error_code is not None:
  860. return self._doc.error_code
  861. self.convert()
  862. if self._doc.error_code is not None:
  863. return self._doc.error_code
  864. html = self._doc.get_html(return_list=True)
  865. # 表格连接
  866. try:
  867. html = self.connect_table(html)
  868. except:
  869. traceback.print_exc()
  870. return [-12]
  871. return html
  872. def delete_water_mark(self, lt_text_list, page_bbox, times=5):
  873. # 删除过多重复字句,为水印
  874. duplicate_dict = {}
  875. for _obj in lt_text_list:
  876. t = _obj.get_text()
  877. if t in duplicate_dict.keys():
  878. duplicate_dict[t][0] += 1
  879. duplicate_dict[t][1].append(_obj)
  880. else:
  881. duplicate_dict[t] = [1, [_obj]]
  882. delete_text = []
  883. for t in duplicate_dict.keys():
  884. if duplicate_dict[t][0] >= times:
  885. obj_list = duplicate_dict[t][1]
  886. obj_list.sort(key=lambda x: x.bbox[3])
  887. obj_distance_h = abs(obj_list[-1].bbox[3] - obj_list[0].bbox[1])
  888. obj_list.sort(key=lambda x: x.bbox[2])
  889. obj_distance_w = abs(obj_list[-1].bbox[2] - obj_list[0].bbox[0])
  890. if obj_distance_h >= abs(page_bbox[1] - page_bbox[3]) * 0.7 \
  891. and obj_distance_w >= abs(page_bbox[0] - page_bbox[2]) * 0.7:
  892. delete_text.append(t)
  893. temp_text_list = []
  894. for _obj in lt_text_list:
  895. t = _obj.get_text()
  896. if t not in delete_text:
  897. temp_text_list.append(_obj)
  898. return temp_text_list
  899. def resize_image(self, img_path, max_size=2000):
  900. _img = cv2.imread(img_path)
  901. if _img.shape[0] <= max_size or _img.shape[1] <= max_size:
  902. return
  903. else:
  904. resize_axis = 0 if _img.shape[0] >= _img.shape[1] else 1
  905. ratio = max_size / _img.shape[resize_axis]
  906. new_shape = [0, 0]
  907. new_shape[resize_axis] = max_size
  908. new_shape[1 - resize_axis] = int(_img.shape[1 - resize_axis] * ratio)
  909. _img = cv2.resize(_img, (new_shape[1], new_shape[0]))
  910. cv2.imwrite(img_path, _img)
  911. def get_single_pdf(self, path, page_no):
  912. start_time = time.time()
  913. try:
  914. pdf_origin = copy.deepcopy(self.doc_pypdf2)
  915. pdf_new = copy.deepcopy(self.doc_pypdf2_new)
  916. pdf_new.addPage(pdf_origin.getPage(page_no))
  917. path_new = path.split(".")[0] + "_split.pdf"
  918. with open(path_new, "wb") as ff:
  919. pdf_new.write(ff)
  920. log("page_no: " + str(page_no) + " get_single_pdf cost: " + str(time.time()-start_time))
  921. return path_new
  922. except PyPDF2.utils.PdfReadError as e:
  923. return [-3]
  924. except Exception as e:
  925. log("page_no: " + str(page_no) + " get_single_pdf error!")
  926. return [-3]
  927. def get_text_font():
  928. def flags_decomposer(flags):
  929. """Make font flags human readable."""
  930. l = []
  931. if flags & 2 ** 0:
  932. l.append("superscript")
  933. if flags & 2 ** 1:
  934. l.append("italic")
  935. if flags & 2 ** 2:
  936. l.append("serifed")
  937. else:
  938. l.append("sans")
  939. if flags & 2 ** 3:
  940. l.append("monospaced")
  941. else:
  942. l.append("proportional")
  943. if flags & 2 ** 4:
  944. l.append("bold")
  945. return ", ".join(l)
  946. def get_underlined_textLines(page):
  947. """
  948. 获取某页pdf上的所有下划线文本信息
  949. :param page: fitz中的一页
  950. :return: list of tuples,每个tuple都是一个完整的下划线覆盖的整体:[(下划线句, 所在blk_no, 所在line_no), ...]
  951. """
  952. paths = page.get_drawings() # get drawings on the current page
  953. # 获取该页内所有的height很小的bbox。因为下划线其实大多是这种矩形
  954. # subselect things we may regard as lines
  955. lines = []
  956. for p in paths:
  957. for item in p["items"]:
  958. if item[0] == "l": # an actual line
  959. p1, p2 = item[1:]
  960. if p1.y == p2.y:
  961. lines.append((p1, p2))
  962. elif item[0] == "re": # a rectangle: check if height is small
  963. r = item[1]
  964. if r.width > r.height and r.height <= 2:
  965. lines.append((r.tl, r.tr)) # take top left / right points
  966. # 获取该页的`max_lineheight`,用于下面比较距离使用
  967. blocks = page.get_text("dict", flags=11)["blocks"]
  968. max_lineheight = 0
  969. for b in blocks:
  970. for l in b["lines"]:
  971. bbox = fitz.Rect(l["bbox"])
  972. if bbox.height > max_lineheight:
  973. max_lineheight = bbox.height
  974. underlined_res = []
  975. # 开始对下划线内容进行查询
  976. # make a list of words
  977. words = page.get_text("words")
  978. # if underlined, the bottom left / right of a word
  979. # should not be too far away from left / right end of some line:
  980. for wdx, w in enumerate(words): # w[4] is the actual word string
  981. r = fitz.Rect(w[:4]) # first 4 items are the word bbox
  982. for p1, p2 in lines: # check distances for start / end points
  983. if abs(r.bl - p1) <= max_lineheight: # 当前word的左下满足下划线左下
  984. if abs(r.br - p2) <= max_lineheight: # 当前word的右下满足下划线右下(单个词,无空格)
  985. print(f"Word '{w[4]}' is underlined! Its block-line number is {w[-3], w[-2]}")
  986. underlined_res.append((w[4], w[-3], w[-2])) # 分别是(下划线词,所在blk_no,所在line_no)
  987. break # don't check more lines
  988. else: # 继续寻找同line右侧的有缘人,因为有些下划线覆盖的词包含多个词,多个词之间有空格
  989. curr_line_num = w[-2] # line nunmber
  990. for right_wdx in range(wdx + 1, len(words), 1):
  991. _next_w = words[right_wdx]
  992. if _next_w[-2] != curr_line_num: # 当前遍历到的右侧word已经不是当前行的了(跨行是不行的)
  993. break
  994. _r_right = fitz.Rect(_next_w[:4]) # 获取当前同行右侧某word的方框4点
  995. if abs(_r_right.br - p2) <= max_lineheight: # 用此word右下点和p2(目标下划线右上点)算距离,距离要小于max_lineheight
  996. print(
  997. f"Word '{' '.join([_one_word[4] for _one_word in words[wdx:right_wdx + 1]])}' is underlined! " +
  998. f"Its block-line number is {w[-3], w[-2]}")
  999. underlined_res.append(
  1000. (' '.join([_one_word[4] for _one_word in words[wdx:right_wdx + 1]]),
  1001. w[-3], w[-2])
  1002. ) # 分别是(下划线词,所在blk_no,所在line_no)
  1003. break # don't check more lines
  1004. return underlined_res
  1005. _p = r'C:\Users\Administrator\Desktop\test_pdf\error2-2.pdf'
  1006. doc_pymupdf = read_pymupdf(_p)
  1007. page = doc_pymupdf[0]
  1008. blocks = page.get_text("dict", flags=11)["blocks"]
  1009. for b in blocks: # iterate through the text blocks
  1010. for l in b["lines"]: # iterate through the text lines
  1011. for s in l["spans"]: # iterate through the text spans
  1012. print("")
  1013. font_properties = "Font: '%s' (%s), size %g, color #%06x" % (
  1014. s["font"], # font name
  1015. flags_decomposer(s["flags"]), # readable font flags
  1016. s["size"], # font size
  1017. s["color"], # font color
  1018. )
  1019. print(s)
  1020. print("Text: '%s'" % s["text"]) # simple print of text
  1021. print(font_properties)
  1022. get_underlined_textLines(page)
  1023. # 以下为现成pdf单页解析接口
  1024. class ParseSentence:
  1025. def __init__(self, bbox, fontname, fontsize, _text, _title, title_text, _pattern, title_degree, is_outline,
  1026. outline_location, page_no):
  1027. (x0, y0, x1, y1) = bbox
  1028. self.x0 = x0
  1029. self.y0 = y0
  1030. self.x1 = x1
  1031. self.y1 = y1
  1032. self.bbox = bbox
  1033. self.fontname = fontname
  1034. self.fontsize = fontsize
  1035. self.text = _text
  1036. self.title = _title
  1037. self.title_text = title_text
  1038. self.groups = _pattern
  1039. self.title_degree = title_degree
  1040. self.is_outline = is_outline
  1041. self.outline_location = outline_location
  1042. self.page_no = page_no
  1043. def __repr__(self):
  1044. return "%s,%s,%s,%d,%s" % (self.text, self.title, self.is_outline, self.outline_location, str(self.bbox))
  1045. class ParseUtils:
  1046. @staticmethod
  1047. def getFontinfo(_page):
  1048. for _obj in _page._objs:
  1049. if isinstance(_obj, (LTTextBoxHorizontal, LTTextBoxVertical)):
  1050. for textline in _obj._objs:
  1051. done = False
  1052. for lchar in textline._objs:
  1053. if isinstance(lchar, (LTChar)):
  1054. _obj.fontname = lchar.fontname
  1055. _obj.fontsize = lchar.size
  1056. done = True
  1057. break
  1058. if done:
  1059. break
  1060. @staticmethod
  1061. def recognize_sentences(list_textbox, filter_objs, page_bbox, page_no,
  1062. remove_space=True, sourceP_LB=True):
  1063. list_textbox.sort(key=lambda x: x.bbox[0])
  1064. list_textbox.sort(key=lambda x: x.bbox[3], reverse=sourceP_LB)
  1065. cluster_textbox = []
  1066. for _textbox in list_textbox:
  1067. if _textbox in filter_objs:
  1068. continue
  1069. _find = False
  1070. for _ct in cluster_textbox:
  1071. if abs(_ct["y"] - _textbox.bbox[1]) < 5:
  1072. _find = True
  1073. _ct["textbox"].append(_textbox)
  1074. if not _find:
  1075. cluster_textbox.append({"y": _textbox.bbox[1], "textbox": [_textbox]})
  1076. cluster_textbox.sort(key=lambda x: x["y"], reverse=sourceP_LB)
  1077. list_sentences = []
  1078. for _line in cluster_textbox:
  1079. _textboxs = _line["textbox"]
  1080. _textboxs.sort(key=lambda x: x.bbox[0])
  1081. _linetext = _textboxs[0].get_text()
  1082. for _i in range(1, len(_textboxs)):
  1083. if abs(_textboxs[_i].bbox[0] - _textboxs[_i - 1].bbox[2]) > 60:
  1084. if _linetext and _linetext[-1] not in (",", ",", "。", ".", "、", ";"):
  1085. _linetext += "=,="
  1086. _linetext += _textboxs[_i].get_text()
  1087. _linetext = re.sub("[\s\r\n]", "", _linetext)
  1088. _bbox = (_textboxs[0].bbox[0], _textboxs[0].bbox[1],
  1089. _textboxs[-1].bbox[2], _textboxs[-1].bbox[3])
  1090. _title = None
  1091. _pattern_groups = None
  1092. title_text = ""
  1093. if not _title:
  1094. _groups = ParseUtils.find_title_by_pattern(_textboxs[0].get_text())
  1095. if _groups:
  1096. _title = _groups[0][0]
  1097. title_text = _groups[0][1]
  1098. _pattern_groups = _groups
  1099. if not _title:
  1100. _groups = ParseUtils.find_title_by_pattern(_linetext)
  1101. if _groups:
  1102. _title = _groups[0][0]
  1103. title_text = _groups[0][1]
  1104. _pattern_groups = _groups
  1105. if not _title:
  1106. _title = ParseUtils.rec_incenter(_bbox, page_bbox)
  1107. title_degree = 2
  1108. if not _title:
  1109. _linetext = _linetext.replace("=,=", ",")
  1110. else:
  1111. _linetext = _linetext.replace("=,=", "")
  1112. title_degree = int(_title.split("_")[1])
  1113. # 页码
  1114. if ParseUtils.rec_incenter(_bbox, page_bbox) and re.search("^\d+$", _linetext) is not None:
  1115. continue
  1116. if _linetext == "" or re.search("^,+$", _linetext) is not None:
  1117. continue
  1118. is_outline = False
  1119. outline_location = -1
  1120. _search = re.search("(?P<text>.+?)\.{5,}(?P<nums>\d+)$", _linetext)
  1121. if _search is not None:
  1122. is_outline = True
  1123. _linetext = _search.group("text")
  1124. outline_location = int(_search.group("nums"))
  1125. list_sentences.append(
  1126. ParseSentence(_bbox, _textboxs[-1].__dict__.get("fontname"), _textboxs[-1].__dict__.get("fontsize"),
  1127. _linetext, _title, title_text, _pattern_groups, title_degree, is_outline,
  1128. outline_location, page_no))
  1129. # for _sen in list_sentences:
  1130. # print(_sen.__dict__)
  1131. return list_sentences
  1132. @staticmethod
  1133. def find_title_by_pattern(_text,
  1134. _pattern="(?P<title_1>(?P<title_1_index_0_0>^第?)(?P<title_1_index_1_1>[一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+)(?P<title_1_index_2_0>[、章]))|" \
  1135. "(?P<title_3>^(?P<title_3_index_0_1>[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+))|" \
  1136. "(?P<title_4>^(?P<title_4_index_0_0>第?)(?P<title_4_index_1_1>[一二三四五六七八九十]+)(?P<title_4_index_2_0>[节]))|" \
  1137. "(?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\-]))|" \
  1138. "(?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\-]))|" \
  1139. "(?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\-]))|" \
  1140. "(?P<title_6>^(?P<title_6_index_0_1>\d{1,2})(?P<title_6_index_1_0>[\..、\s\-]))|" \
  1141. "(?P<title_15>^(?P<title_15_index_0_0>(?)(?P<title_15_index_1_1>\d{1,2})(?P<title_15_index_2_0>)))|" \
  1142. "(?P<title_17>^(?P<title_17_index_0_0>(?)(?P<title_17_index_1_1>[a-zA-Z]+)(?P<title_17_index_2_0>)))|"
  1143. "(?P<title_19>^(?P<title_19_index_0_0>(?)(?P<title_19_index_1_1>[一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+)(?P<title_19_index_2_0>)))|" \
  1144. ):
  1145. _se = re.search(_pattern, _text)
  1146. groups = []
  1147. if _se is not None:
  1148. _gd = _se.groupdict()
  1149. for k, v in _gd.items():
  1150. if v is not None:
  1151. groups.append((k, v))
  1152. if len(groups):
  1153. groups.sort(key=lambda x: x[0])
  1154. return groups
  1155. return None
  1156. @staticmethod
  1157. def rec_incenter(o_bbox, p_bbox):
  1158. p_width = p_bbox[2] - p_bbox[0]
  1159. l_space = (o_bbox[0] - p_bbox[0]) / p_width
  1160. r_space = (p_bbox[2] - o_bbox[2]) / p_width
  1161. if abs((l_space - r_space)) < 0.1 and l_space > 0.2:
  1162. return "title_2"
  1163. @staticmethod
  1164. def is_first_title(_title):
  1165. if _title is None:
  1166. return False
  1167. if re.search("^\d+$", _title) is not None:
  1168. if int(_title) == 1:
  1169. return True
  1170. return False
  1171. if re.search("^[一二三四五六七八九十百]+$", _title) is not None:
  1172. if _title == "一":
  1173. return True
  1174. return False
  1175. if re.search("^[a-z]+$", _title) is not None:
  1176. if _title == "a":
  1177. return True
  1178. return False
  1179. if re.search("^[A-Z]+$", _title) is not None:
  1180. if _title == "A":
  1181. return True
  1182. return False
  1183. if re.search("^[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]$", _title) is not None:
  1184. if _title == "Ⅰ":
  1185. return True
  1186. return False
  1187. return False
  1188. @staticmethod
  1189. def get_next_title(_title):
  1190. if re.search("^\d+$", _title) is not None:
  1191. return str(int(_title) + 1)
  1192. if re.search("^[一二三四五六七八九十百]+$", _title) is not None:
  1193. _next_title = ParseUtils.make_increase(['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'],
  1194. re.sub("[十百]", '', _title))
  1195. _next_title = list(_next_title)
  1196. _next_title.reverse()
  1197. if _next_title[-1] != "十":
  1198. if len(_next_title) >= 2:
  1199. _next_title.insert(-1, '十')
  1200. if len(_next_title) >= 4:
  1201. _next_title.insert(-3, '百')
  1202. if _title[0] == "十":
  1203. if _next_title == "十":
  1204. _next_title = ["二", "十"]
  1205. _next_title.insert(0, "十")
  1206. _next_title = "".join(_next_title)
  1207. return _next_title
  1208. if re.search("^[a-z]+$", _title) is not None:
  1209. _next_title = ParseUtils.make_increase([chr(i + ord('a')) for i in range(26)], _title)
  1210. _next_title = list(_next_title)
  1211. _next_title.reverse()
  1212. return "".join(_next_title)
  1213. if re.search("^[A-Z]+$", _title) is not None:
  1214. _next_title = ParseUtils.make_increase([chr(i + ord('A')) for i in range(26)], _title)
  1215. _next_title = list(_next_title)
  1216. _next_title.reverse()
  1217. return "".join(_next_title)
  1218. if re.search("^[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]$", _title) is not None:
  1219. _sort = ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ", "Ⅻ"]
  1220. _index = _sort.index(_title)
  1221. if _index < len(_sort) - 1:
  1222. return _sort[_index + 1]
  1223. return None
  1224. @staticmethod
  1225. def make_increase(_sort, _title, _add=1):
  1226. if len(_title) == 0 and _add == 0:
  1227. return ""
  1228. if len(_title) == 0 and _add == 1:
  1229. return _sort[0]
  1230. _index = _sort.index(_title[-1])
  1231. next_index = (_index + _add) % len(_sort)
  1232. next_chr = _sort[next_index]
  1233. if _index == len(_sort) - 1:
  1234. _add = 1
  1235. else:
  1236. _add = 0
  1237. return next_chr + ParseUtils.make_increase(_sort, _title[:-1], _add)
  1238. @staticmethod
  1239. def rec_serial(_text, o_bbox, p_bbox, fontname, _pattern="(?P<title_1>^[一二三四五六七八九十]+[、])|" \
  1240. "(?P<title_2>^\d+[\.、\s])|" \
  1241. "(?P<title_3>^\d+\.\d+[\.、\s])|" \
  1242. "(?P<title_4>^\d+\.\d+\.\d+[\.、\s])|" \
  1243. "(?P<title_5>^\d+\.\d+\.\d+\.\d+[\.、\s])"):
  1244. # todo :recog the serial of the sentence
  1245. _se = re.search(_pattern, _text)
  1246. if _se is not None:
  1247. _gd = _se.groupdict()
  1248. for k, v in _gd.items():
  1249. if v is not None:
  1250. return k
  1251. return None
  1252. if __name__ == '__main__':
  1253. PDFConvert(r"C:/Users/Administrator/Downloads/1651896704621.pdf", "C:/Users/Administrator/Downloads/1").get_html()