您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

pdf_parser.py 66KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715
  1. # -*- coding: utf-8 -*-
  2. import random
  3. import fitz
  4. import xgboost as xgb
  5. from io import BytesIO
  6. import torch
  7. import re
  8. import pdfplumber
  9. import logging
  10. from PIL import Image
  11. import numpy as np
  12. from rag.nlp import huqie
  13. from collections import Counter
  14. from copy import deepcopy
  15. from rag.cv.table_recognize import TableTransformer
  16. from rag.cv.ppdetection import PPDet
  17. from huggingface_hub import hf_hub_download
  18. logging.getLogger("pdfminer").setLevel(logging.WARNING)
  19. class HuParser:
  20. def __init__(self):
  21. from paddleocr import PaddleOCR
  22. logging.getLogger("ppocr").setLevel(logging.ERROR)
  23. self.ocr = PaddleOCR(use_angle_cls=False, lang="ch")
  24. self.layouter = PPDet("/data/newpeak/medical-gpt/res/ppdet")
  25. self.tbl_det = PPDet("/data/newpeak/medical-gpt/res/ppdet.tbl")
  26. self.updown_cnt_mdl = xgb.Booster()
  27. if torch.cuda.is_available():
  28. self.updown_cnt_mdl.set_param({"device": "cuda"})
  29. self.updown_cnt_mdl.load_model(hf_hub_download(repo_id="InfiniFlow/text_concat_xgb_v1.0",
  30. filename="updown_concat_xgb.model"))
  31. """
  32. If you have trouble downloading HuggingFace models, -_^ this might help!!
  33. For Linux:
  34. export HF_ENDPOINT=https://hf-mirror.com
  35. For Windows:
  36. Good luck
  37. ^_-
  38. """
  39. def __char_width(self, c):
  40. return (c["x1"] - c["x0"]) // len(c["text"])
  41. def __height(self, c):
  42. return c["bottom"] - c["top"]
  43. def _x_dis(self, a, b):
  44. return min(abs(a["x1"] - b["x0"]), abs(a["x0"] - b["x1"]),
  45. abs(a["x0"] + a["x1"] - b["x0"] - b["x1"]) / 2)
  46. def _y_dis(
  47. self, a, b):
  48. return (
  49. b["top"] + b["bottom"] - a["top"] - a["bottom"]) / 2
  50. def _match_proj(self, b):
  51. proj_patt = [
  52. r"第[零一二三四五六七八九十百]+章",
  53. r"第[零一二三四五六七八九十百]+[条节]",
  54. r"[零一二三四五六七八九十百]+[、是  ]",
  55. r"[\((][零一二三四五六七八九十百]+[)\)]",
  56. r"[\((][0-9]+[)\)]",
  57. r"[0-9]+(、|\.[  ]|)|\.[^0-9./a-zA-Z_%><-]{4,})",
  58. r"[0-9]+\.[0-9.]+(、|\.[  ])",
  59. r"[⚫•➢①② ]",
  60. ]
  61. return any([re.match(p, b["text"]) for p in proj_patt])
  62. def _updown_concat_features(self, up, down):
  63. w = max(self.__char_width(up), self.__char_width(down))
  64. h = max(self.__height(up), self.__height(down))
  65. y_dis = self._y_dis(up, down)
  66. LEN = 6
  67. tks_down = huqie.qie(down["text"][:LEN]).split(" ")
  68. tks_up = huqie.qie(up["text"][-LEN:]).split(" ")
  69. tks_all = up["text"][-LEN:].strip() \
  70. + (" " if re.match(r"[a-zA-Z0-9]+",
  71. up["text"][-1] + down["text"][0]) else "") \
  72. + down["text"][:LEN].strip()
  73. tks_all = huqie.qie(tks_all).split(" ")
  74. fea = [
  75. up.get("R", -1) == down.get("R", -1),
  76. y_dis / h,
  77. down["page_number"] - up["page_number"],
  78. up["layout_type"] == down["layout_type"],
  79. up["layout_type"] == "text",
  80. down["layout_type"] == "text",
  81. up["layout_type"] == "table",
  82. down["layout_type"] == "table",
  83. True if re.search(
  84. r"([。?!;!?;+))]|[a-z]\.)$",
  85. up["text"]) else False,
  86. True if re.search(r"[,:‘“、0-9(+-]$", up["text"]) else False,
  87. True if re.search(
  88. r"(^.?[/,?;:\],。;:’”?!》】)-])",
  89. down["text"]) else False,
  90. True if re.match(r"[\((][^\(\)()]+[)\)]$", up["text"]) else False,
  91. True if re.search(r"[,,][^。.]+$", up["text"]) else False,
  92. True if re.search(r"[,,][^。.]+$", up["text"]) else False,
  93. True if re.search(r"[\((][^\))]+$", up["text"])
  94. and re.search(r"[\))]", down["text"]) else False,
  95. self._match_proj(down),
  96. True if re.match(r"[A-Z]", down["text"]) else False,
  97. True if re.match(r"[A-Z]", up["text"][-1]) else False,
  98. True if re.match(r"[a-z0-9]", up["text"][-1]) else False,
  99. True if re.match(r"[0-9.%,-]+$", down["text"]) else False,
  100. up["text"].strip()[-2:] == down["text"].strip()[-2:] if len(up["text"].strip()
  101. ) > 1 and len(
  102. down["text"].strip()) > 1 else False,
  103. up["x0"] > down["x1"],
  104. abs(self.__height(up) - self.__height(down)) / min(self.__height(up),
  105. self.__height(down)),
  106. self._x_dis(up, down) / max(w, 0.000001),
  107. (len(up["text"]) - len(down["text"])) /
  108. max(len(up["text"]), len(down["text"])),
  109. len(tks_all) - len(tks_up) - len(tks_down),
  110. len(tks_down) - len(tks_up),
  111. tks_down[-1] == tks_up[-1],
  112. max(down["in_row"], up["in_row"]),
  113. abs(down["in_row"] - up["in_row"]),
  114. len(tks_down) == 1 and huqie.tag(tks_down[0]).find("n") >= 0,
  115. len(tks_up) == 1 and huqie.tag(tks_up[0]).find("n") >= 0
  116. ]
  117. return fea
  118. @staticmethod
  119. def sort_Y_firstly(arr, threashold):
  120. # sort using y1 first and then x1
  121. arr = sorted(arr, key=lambda r: (r["top"], r["x0"]))
  122. for i in range(len(arr) - 1):
  123. for j in range(i, -1, -1):
  124. # restore the order using th
  125. if abs(arr[j + 1]["top"] - arr[j]["top"]) < threashold \
  126. and arr[j + 1]["x0"] < arr[j]["x0"]:
  127. tmp = deepcopy(arr[j])
  128. arr[j] = deepcopy(arr[j + 1])
  129. arr[j + 1] = deepcopy(tmp)
  130. return arr
  131. @staticmethod
  132. def sort_X_by_page(arr, threashold):
  133. # sort using y1 first and then x1
  134. arr = sorted(arr, key=lambda r: (r["page_number"], r["x0"], r["top"]))
  135. for i in range(len(arr) - 1):
  136. for j in range(i, -1, -1):
  137. # restore the order using th
  138. if abs(arr[j + 1]["x0"] - arr[j]["x0"]) < threashold \
  139. and arr[j + 1]["top"] < arr[j]["top"]\
  140. and arr[j + 1]["page_number"] == arr[j]["page_number"]:
  141. tmp = arr[j]
  142. arr[j] = arr[j + 1]
  143. arr[j + 1] = tmp
  144. return arr
  145. @staticmethod
  146. def sort_R_firstly(arr, thr=0):
  147. # sort using y1 first and then x1
  148. # sorted(arr, key=lambda r: (r["top"], r["x0"]))
  149. arr = HuParser.sort_Y_firstly(arr, thr)
  150. for i in range(len(arr) - 1):
  151. for j in range(i, -1, -1):
  152. if "R" not in arr[j] or "R" not in arr[j + 1]:
  153. continue
  154. if arr[j + 1]["R"] < arr[j]["R"] \
  155. or (
  156. arr[j + 1]["R"] == arr[j]["R"]
  157. and arr[j + 1]["x0"] < arr[j]["x0"]
  158. ):
  159. tmp = arr[j]
  160. arr[j] = arr[j + 1]
  161. arr[j + 1] = tmp
  162. return arr
  163. @staticmethod
  164. def sort_X_firstly(arr, threashold, copy=True):
  165. # sort using y1 first and then x1
  166. arr = sorted(arr, key=lambda r: (r["x0"], r["top"]))
  167. for i in range(len(arr) - 1):
  168. for j in range(i, -1, -1):
  169. # restore the order using th
  170. if abs(arr[j + 1]["x0"] - arr[j]["x0"]) < threashold \
  171. and arr[j + 1]["top"] < arr[j]["top"]:
  172. tmp = deepcopy(arr[j]) if copy else arr[j]
  173. arr[j] = deepcopy(arr[j + 1]) if copy else arr[j + 1]
  174. arr[j + 1] = deepcopy(tmp) if copy else tmp
  175. return arr
  176. @staticmethod
  177. def sort_C_firstly(arr, thr=0):
  178. # sort using y1 first and then x1
  179. # sorted(arr, key=lambda r: (r["x0"], r["top"]))
  180. arr = HuParser.sort_X_firstly(arr, thr)
  181. for i in range(len(arr) - 1):
  182. for j in range(i, -1, -1):
  183. # restore the order using th
  184. if "C" not in arr[j] or "C" not in arr[j + 1]:
  185. continue
  186. if arr[j + 1]["C"] < arr[j]["C"] \
  187. or (
  188. arr[j + 1]["C"] == arr[j]["C"]
  189. and arr[j + 1]["top"] < arr[j]["top"]
  190. ):
  191. tmp = arr[j]
  192. arr[j] = arr[j + 1]
  193. arr[j + 1] = tmp
  194. return arr
  195. return sorted(arr, key=lambda r: (r.get("C", r["x0"]), r["top"]))
  196. def _has_color(self, o):
  197. if o.get("ncs", "") == "DeviceGray":
  198. if o["stroking_color"] and o["stroking_color"][0] == 1 and o["non_stroking_color"] and \
  199. o["non_stroking_color"][0] == 1:
  200. if re.match(r"[a-zT_\[\]\(\)-]+", o.get("text", "")):
  201. return False
  202. return True
  203. def __overlapped_area(self, a, b, ratio=True):
  204. tp, btm, x0, x1 = a["top"], a["bottom"], a["x0"], a["x1"]
  205. if b["x0"] > x1 or b["x1"] < x0:
  206. return 0
  207. if b["bottom"] < tp or b["top"] > btm:
  208. return 0
  209. x0_ = max(b["x0"], x0)
  210. x1_ = min(b["x1"], x1)
  211. assert x0_ <= x1_, "Fuckedup! T:{},B:{},X0:{},X1:{} ==> {}".format(
  212. tp, btm, x0, x1, b)
  213. tp_ = max(b["top"], tp)
  214. btm_ = min(b["bottom"], btm)
  215. assert tp_ <= btm_, "Fuckedup! T:{},B:{},X0:{},X1:{} => {}".format(
  216. tp, btm, x0, x1, b)
  217. ov = (btm_ - tp_) * (x1_ - x0_) if x1 - \
  218. x0 != 0 and btm - tp != 0 else 0
  219. if ov > 0 and ratio:
  220. ov /= (x1 - x0) * (btm - tp)
  221. return ov
  222. def __find_overlapped_with_threashold(self, box, boxes, thr=0.3):
  223. if not boxes:
  224. return
  225. max_overlaped_i, max_overlaped, _max_overlaped = None, thr, 0
  226. s, e = 0, len(boxes)
  227. for i in range(s, e):
  228. ov = self.__overlapped_area(box, boxes[i])
  229. _ov = self.__overlapped_area(boxes[i], box)
  230. if (ov, _ov) < (max_overlaped, _max_overlaped):
  231. continue
  232. max_overlaped_i = i
  233. max_overlaped = ov
  234. _max_overlaped = _ov
  235. return max_overlaped_i
  236. def __find_overlapped(self, box, boxes_sorted_by_y, naive=False):
  237. if not boxes_sorted_by_y:
  238. return
  239. bxs = boxes_sorted_by_y
  240. s, e, ii = 0, len(bxs), 0
  241. while s < e and not naive:
  242. ii = (e + s) // 2
  243. pv = bxs[ii]
  244. if box["bottom"] < pv["top"]:
  245. e = ii
  246. continue
  247. if box["top"] > pv["bottom"]:
  248. s = ii + 1
  249. continue
  250. break
  251. while s < ii:
  252. if box["top"] > bxs[s]["bottom"]:
  253. s += 1
  254. break
  255. while e - 1 > ii:
  256. if box["bottom"] < bxs[e - 1]["top"]:
  257. e -= 1
  258. break
  259. max_overlaped_i, max_overlaped = None, 0
  260. for i in range(s, e):
  261. ov = self.__overlapped_area(bxs[i], box)
  262. if ov <= max_overlaped:
  263. continue
  264. max_overlaped_i = i
  265. max_overlaped = ov
  266. return max_overlaped_i
  267. def _is_garbage(self, b):
  268. patt = [r"^•+$", r"(版权归©|免责条款|地址[::])", r"\.{3,}", "^[0-9]{1,2} / ?[0-9]{1,2}$",
  269. r"^[0-9]{1,2} of [0-9]{1,2}$", "^http://[^ ]{12,}",
  270. "(资料|数据)来源[::]", "[0-9a-z._-]+@[a-z0-9-]+\\.[a-z]{2,3}",
  271. "\\(cid *: *[0-9]+ *\\)"
  272. ]
  273. return any([re.search(p, b["text"]) for p in patt])
  274. def __layouts_cleanup(self, boxes, layouts, far=2, thr=0.7):
  275. def notOverlapped(a, b):
  276. return any([a["x1"] < b["x0"],
  277. a["x0"] > b["x1"],
  278. a["bottom"] < b["top"],
  279. a["top"] > b["bottom"]])
  280. i = 0
  281. while i + 1 < len(layouts):
  282. j = i + 1
  283. while j < min(i + far, len(layouts)) \
  284. and (layouts[i].get("type", "") != layouts[j].get("type", "")
  285. or notOverlapped(layouts[i], layouts[j])):
  286. j += 1
  287. if j >= min(i + far, len(layouts)):
  288. i += 1
  289. continue
  290. if self.__overlapped_area(layouts[i], layouts[j]) < thr \
  291. and self.__overlapped_area(layouts[j], layouts[i]) < thr:
  292. i += 1
  293. continue
  294. if layouts[i].get("score") and layouts[j].get("score"):
  295. if layouts[i]["score"] > layouts[j]["score"]:
  296. layouts.pop(j)
  297. else:
  298. layouts.pop(i)
  299. continue
  300. area_i, area_i_1 = 0, 0
  301. for b in boxes:
  302. if not notOverlapped(b, layouts[i]):
  303. area_i += self.__overlapped_area(b, layouts[i], False)
  304. if not notOverlapped(b, layouts[j]):
  305. area_i_1 += self.__overlapped_area(b, layouts[j], False)
  306. if area_i > area_i_1:
  307. layouts.pop(j)
  308. else:
  309. layouts.pop(i)
  310. return layouts
  311. def __table_paddle(self, images):
  312. tbls = self.tbl_det([np.array(img) for img in images], thr=0.5)
  313. res = []
  314. # align left&right for rows, align top&bottom for columns
  315. for tbl in tbls:
  316. lts = [{"label": b["type"],
  317. "score": b["score"],
  318. "x0": b["bbox"][0], "x1": b["bbox"][2],
  319. "top": b["bbox"][1], "bottom": b["bbox"][-1]
  320. } for b in tbl]
  321. if not lts:
  322. continue
  323. left = [b["x0"] for b in lts if b["label"].find(
  324. "row") > 0 or b["label"].find("header") > 0]
  325. right = [b["x1"] for b in lts if b["label"].find(
  326. "row") > 0 or b["label"].find("header") > 0]
  327. if not left:
  328. continue
  329. left = np.median(left) if len(left) > 4 else np.min(left)
  330. right = np.median(right) if len(right) > 4 else np.max(right)
  331. for b in lts:
  332. if b["label"].find("row") > 0 or b["label"].find("header") > 0:
  333. if b["x0"] > left:
  334. b["x0"] = left
  335. if b["x1"] < right:
  336. b["x1"] = right
  337. top = [b["top"] for b in lts if b["label"] == "table column"]
  338. bottom = [b["bottom"] for b in lts if b["label"] == "table column"]
  339. if not top:
  340. res.append(lts)
  341. continue
  342. top = np.median(top) if len(top) > 4 else np.min(top)
  343. bottom = np.median(bottom) if len(bottom) > 4 else np.max(bottom)
  344. for b in lts:
  345. if b["label"] == "table column":
  346. if b["top"] > top:
  347. b["top"] = top
  348. if b["bottom"] < bottom:
  349. b["bottom"] = bottom
  350. res.append(lts)
  351. return res
  352. def _table_transformer_job(self, ZM):
  353. logging.info("Table processing...")
  354. imgs, pos = [], []
  355. tbcnt = [0]
  356. MARGIN = 10
  357. self.tb_cpns = []
  358. assert len(self.page_layout) == len(self.page_images)
  359. for p, tbls in enumerate(self.page_layout): # for page
  360. tbls = [f for f in tbls if f["type"] == "table"]
  361. tbcnt.append(len(tbls))
  362. if not tbls:
  363. continue
  364. for tb in tbls: # for table
  365. left, top, right, bott = tb["x0"] - MARGIN, tb["top"] - MARGIN, \
  366. tb["x1"] + MARGIN, tb["bottom"] + MARGIN
  367. left *= ZM
  368. top *= ZM
  369. right *= ZM
  370. bott *= ZM
  371. pos.append((left, top))
  372. imgs.append(self.page_images[p].crop((left, top, right, bott)))
  373. assert len(self.page_images) == len(tbcnt) - 1
  374. if not imgs:
  375. return
  376. recos = self.__table_paddle(imgs)
  377. tbcnt = np.cumsum(tbcnt)
  378. for i in range(len(tbcnt) - 1): # for page
  379. pg = []
  380. for j, tb_items in enumerate(
  381. recos[tbcnt[i]: tbcnt[i + 1]]): # for table
  382. poss = pos[tbcnt[i]: tbcnt[i + 1]]
  383. for it in tb_items: # for table components
  384. it["x0"] = (it["x0"] + poss[j][0])
  385. it["x1"] = (it["x1"] + poss[j][0])
  386. it["top"] = (it["top"] + poss[j][1])
  387. it["bottom"] = (it["bottom"] + poss[j][1])
  388. for n in ["x0", "x1", "top", "bottom"]:
  389. it[n] /= ZM
  390. it["top"] += self.page_cum_height[i]
  391. it["bottom"] += self.page_cum_height[i]
  392. it["pn"] = i
  393. it["layoutno"] = j
  394. pg.append(it)
  395. self.tb_cpns.extend(pg)
  396. def gather(kwd, fzy=10, ption=0.6):
  397. eles = self.sort_Y_firstly(
  398. [r for r in self.tb_cpns if re.match(kwd, r["label"])], fzy)
  399. eles = self.__layouts_cleanup(self.boxes, eles, 5, ption)
  400. return self.sort_Y_firstly(eles, 0)
  401. # add R,H,C,SP tag to boxes within table layout
  402. headers = gather(r".*header$")
  403. rows = gather(r".* (row|header)")
  404. spans = gather(r".*spanning")
  405. clmns = sorted([r for r in self.tb_cpns if re.match(
  406. r"table column$", r["label"])], key=lambda x: (x["pn"], x["layoutno"], x["x0"]))
  407. clmns = self.__layouts_cleanup(self.boxes, clmns, 5, 0.5)
  408. for b in self.boxes:
  409. if b.get("layout_type", "") != "table":
  410. continue
  411. ii = self.__find_overlapped_with_threashold(b, rows, thr=0.3)
  412. if ii is not None:
  413. b["R"] = ii
  414. b["R_top"] = rows[ii]["top"]
  415. b["R_bott"] = rows[ii]["bottom"]
  416. ii = self.__find_overlapped_with_threashold(b, headers, thr=0.3)
  417. if ii is not None:
  418. b["H_top"] = headers[ii]["top"]
  419. b["H_bott"] = headers[ii]["bottom"]
  420. b["H_left"] = headers[ii]["x0"]
  421. b["H_right"] = headers[ii]["x1"]
  422. b["H"] = ii
  423. ii = self.__find_overlapped_with_threashold(b, clmns, thr=0.3)
  424. if ii is not None:
  425. b["C"] = ii
  426. b["C_left"] = clmns[ii]["x0"]
  427. b["C_right"] = clmns[ii]["x1"]
  428. ii = self.__find_overlapped_with_threashold(b, spans, thr=0.3)
  429. if ii is not None:
  430. b["H_top"] = spans[ii]["top"]
  431. b["H_bott"] = spans[ii]["bottom"]
  432. b["H_left"] = spans[ii]["x0"]
  433. b["H_right"] = spans[ii]["x1"]
  434. b["SP"] = ii
  435. def __ocr_paddle(self, pagenum, img, chars, ZM=3):
  436. bxs = self.ocr.ocr(np.array(img), cls=True)[0]
  437. if not bxs:
  438. self.boxes.append([])
  439. return
  440. bxs = [(line[0], line[1][0]) for line in bxs]
  441. bxs = self.sort_Y_firstly(
  442. [{"x0": b[0][0] / ZM, "x1": b[1][0] / ZM,
  443. "top": b[0][1] / ZM, "text": "", "txt": t,
  444. "bottom": b[-1][1] / ZM,
  445. "page_number": pagenum} for b, t in bxs if b[0][0] <= b[1][0] and b[0][1] <= b[-1][1]],
  446. self.mean_height[-1] / 3
  447. )
  448. # merge chars in the same rect
  449. for c in self.sort_X_firstly(chars, self.mean_width[pagenum - 1] // 4):
  450. ii = self.__find_overlapped(c, bxs)
  451. if ii is None:
  452. self.lefted_chars.append(c)
  453. continue
  454. ch = c["bottom"] - c["top"]
  455. bh = bxs[ii]["bottom"] - bxs[ii]["top"]
  456. if abs(ch - bh) / max(ch, bh) >= 0.7 and c["text"] != ' ':
  457. self.lefted_chars.append(c)
  458. continue
  459. if c["text"] == " " and bxs[ii]["text"]:
  460. if re.match(r"[0-9a-zA-Z,.?;:!%%]", bxs[ii]["text"][-1]): bxs[ii]["text"] += " "
  461. else:
  462. bxs[ii]["text"] += c["text"]
  463. for b in bxs:
  464. if not b["text"]:
  465. b["text"] = b["txt"]
  466. del b["txt"]
  467. if self.mean_height[-1] == 0:
  468. self.mean_height[-1] = np.median([b["bottom"] - b["top"]
  469. for b in bxs])
  470. self.boxes.append(bxs)
  471. def _layouts_paddle(self, ZM):
  472. assert len(self.page_images) == len(self.boxes)
  473. # Tag layout type
  474. boxes = []
  475. layouts = self.layouter([np.array(img) for img in self.page_images])
  476. assert len(self.page_images) == len(layouts)
  477. for pn, lts in enumerate(layouts):
  478. bxs = self.boxes[pn]
  479. lts = [{"type": b["type"],
  480. "score": float(b["score"]),
  481. "x0": b["bbox"][0] / ZM, "x1": b["bbox"][2] / ZM,
  482. "top": b["bbox"][1] / ZM, "bottom": b["bbox"][-1] / ZM,
  483. "page_number": pn,
  484. } for b in lts]
  485. lts = self.sort_Y_firstly(lts, self.mean_height[pn] / 2)
  486. lts = self.__layouts_cleanup(bxs, lts)
  487. self.page_layout.append(lts)
  488. # Tag layout type, layouts are ready
  489. def findLayout(ty):
  490. nonlocal bxs, lts
  491. lts_ = [lt for lt in lts if lt["type"] == ty]
  492. i = 0
  493. while i < len(bxs):
  494. if bxs[i].get("layout_type"):
  495. i += 1
  496. continue
  497. if self._is_garbage(bxs[i]):
  498. logging.debug("GARBAGE: " + bxs[i]["text"])
  499. bxs.pop(i)
  500. continue
  501. ii = self.__find_overlapped_with_threashold(bxs[i], lts_,
  502. thr=0.4)
  503. if ii is None: # belong to nothing
  504. bxs[i]["layout_type"] = ""
  505. i += 1
  506. continue
  507. lts_[ii]["visited"] = True
  508. if lts_[ii]["type"] in ["footer", "header", "reference"]:
  509. if lts_[ii]["type"] not in self.garbages:
  510. self.garbages[lts_[ii]["type"]] = []
  511. self.garbages[lts_[ii]["type"]].append(bxs[i]["text"])
  512. logging.debug("GARBAGE: " + bxs[i]["text"])
  513. bxs.pop(i)
  514. continue
  515. bxs[i]["layoutno"] = f"{ty}-{ii}"
  516. bxs[i]["layout_type"] = lts_[ii]["type"]
  517. i += 1
  518. for lt in ["footer", "header", "reference", "figure caption",
  519. "table caption", "title", "text", "table", "figure"]:
  520. findLayout(lt)
  521. # add box to figure layouts which has not text box
  522. for i, lt in enumerate(
  523. [lt for lt in lts if lt["type"] == "figure"]):
  524. if lt.get("visited"):
  525. continue
  526. lt = deepcopy(lt)
  527. del lt["type"]
  528. lt["text"] = ""
  529. lt["layout_type"] = "figure"
  530. lt["layoutno"] = f"figure-{i}"
  531. bxs.append(lt)
  532. boxes.extend(bxs)
  533. self.boxes = boxes
  534. garbage = set()
  535. for k in self.garbages.keys():
  536. self.garbages[k] = Counter(self.garbages[k])
  537. for g, c in self.garbages[k].items():
  538. if c > 1:
  539. garbage.add(g)
  540. logging.debug("GARBAGE:" + ",".join(garbage))
  541. self.boxes = [b for b in self.boxes if b["text"].strip() not in garbage]
  542. # cumlative Y
  543. for i in range(len(self.boxes)):
  544. self.boxes[i]["top"] += \
  545. self.page_cum_height[self.boxes[i]["page_number"] - 1]
  546. self.boxes[i]["bottom"] += \
  547. self.page_cum_height[self.boxes[i]["page_number"] - 1]
  548. def _text_merge(self):
  549. # merge adjusted boxes
  550. bxs = self.boxes
  551. def end_with(b, txt):
  552. txt = txt.strip()
  553. tt = b.get("text", "").strip()
  554. return tt and tt.find(txt) == len(tt) - len(txt)
  555. def start_with(b, txts):
  556. tt = b.get("text", "").strip()
  557. return tt and any([tt.find(t.strip()) == 0 for t in txts])
  558. # horizontally merge adjacent box with the same layout
  559. i = 0
  560. while i < len(bxs) - 1:
  561. b = bxs[i]
  562. b_ = bxs[i + 1]
  563. if b.get("layoutno", "0") != b_.get("layoutno", "1"):
  564. i += 1
  565. continue
  566. dis_thr = 1
  567. dis = b["x1"] - b_["x0"]
  568. if b.get("layout_type", "") != "text" or b_.get(
  569. "layout_type", "") != "text":
  570. if end_with(b, ",") or start_with(b_, "(,"):
  571. dis_thr = -8
  572. else:
  573. i += 1
  574. continue
  575. if abs(self._y_dis(b, b_)) < self.mean_height[bxs[i]["page_number"] - 1] / 5 \
  576. and dis >= dis_thr and b["x1"] < b_["x1"]:
  577. # merge
  578. bxs[i]["x1"] = b_["x1"]
  579. bxs[i]["top"] = (b["top"] + b_["top"]) / 2
  580. bxs[i]["bottom"] = (b["bottom"] + b_["bottom"]) / 2
  581. bxs[i]["text"] += b_["text"]
  582. bxs.pop(i + 1)
  583. continue
  584. i += 1
  585. self.boxes = bxs
  586. def _concat_downward(self, concat_between_pages=True):
  587. # count boxes in the same row as a feature
  588. for i in range(len(self.boxes)):
  589. mh = self.mean_height[self.boxes[i]["page_number"] - 1]
  590. self.boxes[i]["in_row"] = 0
  591. j = max(0, i - 12)
  592. while j < min(i + 12, len(self.boxes)):
  593. if j == i:
  594. j += 1
  595. continue
  596. ydis = self._y_dis(self.boxes[i], self.boxes[j]) / mh
  597. if abs(ydis) < 1:
  598. self.boxes[i]["in_row"] += 1
  599. elif ydis > 0:
  600. break
  601. j += 1
  602. # concat between rows
  603. boxes = deepcopy(self.boxes)
  604. blocks = []
  605. while boxes:
  606. chunks = []
  607. def dfs(up, dp):
  608. chunks.append(up)
  609. i = dp
  610. while i < min(dp + 12, len(boxes)):
  611. ydis = self._y_dis(up, boxes[i])
  612. smpg = up["page_number"] == boxes[i]["page_number"]
  613. mh = self.mean_height[up["page_number"] - 1]
  614. mw = self.mean_width[up["page_number"] - 1]
  615. if smpg and ydis > mh * 4:
  616. break
  617. if not smpg and ydis > mh * 16:
  618. break
  619. down = boxes[i]
  620. if not concat_between_pages and down["page_number"] > up["page_number"]:
  621. break
  622. if up.get("R", "") != down.get(
  623. "R", "") and up["text"][-1] != ",":
  624. i += 1
  625. continue
  626. if re.match(r"[0-9]{2,3}/[0-9]{3}$", up["text"]) \
  627. or re.match(r"[0-9]{2,3}/[0-9]{3}$", down["text"]):
  628. i += 1
  629. continue
  630. if not down["text"].strip():
  631. i += 1
  632. continue
  633. if up["x1"] < down["x0"] - 10 * \
  634. mw or up["x0"] > down["x1"] + 10 * mw:
  635. i += 1
  636. continue
  637. if i - dp < 5 and up.get("layout_type") == "text":
  638. if up.get("layoutno", "1") == down.get(
  639. "layoutno", "2"):
  640. dfs(down, i + 1)
  641. boxes.pop(i)
  642. return
  643. i += 1
  644. continue
  645. fea = self._updown_concat_features(up, down)
  646. if self.updown_cnt_mdl.predict(
  647. xgb.DMatrix([fea]))[0] <= 0.5:
  648. i += 1
  649. continue
  650. dfs(down, i + 1)
  651. boxes.pop(i)
  652. return
  653. dfs(boxes[0], 1)
  654. boxes.pop(0)
  655. if chunks:
  656. blocks.append(chunks)
  657. # concat within each block
  658. boxes = []
  659. for b in blocks:
  660. if len(b) == 1:
  661. boxes.append(b[0])
  662. continue
  663. t = b[0]
  664. for c in b[1:]:
  665. t["text"] = t["text"].strip()
  666. c["text"] = c["text"].strip()
  667. if not c["text"]:
  668. continue
  669. if t["text"] and re.match(
  670. r"[0-9\.a-zA-Z]+$", t["text"][-1] + c["text"][-1]):
  671. t["text"] += " "
  672. t["text"] += c["text"]
  673. t["x0"] = min(t["x0"], c["x0"])
  674. t["x1"] = max(t["x1"], c["x1"])
  675. t["page_number"] = min(t["page_number"], c["page_number"])
  676. t["bottom"] = c["bottom"]
  677. if not t["layout_type"] \
  678. and c["layout_type"]:
  679. t["layout_type"] = c["layout_type"]
  680. boxes.append(t)
  681. self.boxes = self.sort_Y_firstly(boxes, 0)
  682. def _filter_forpages(self):
  683. if not self.boxes:
  684. return
  685. i = 0
  686. while i < len(self.boxes):
  687. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$", re.sub(r"( | |\u3000)+", "", self.boxes[i]["text"].lower())):
  688. i += 1
  689. continue
  690. eng = re.match(r"[0-9a-zA-Z :'.-]{5,}", self.boxes[i]["text"].strip())
  691. self.boxes.pop(i)
  692. if i >= len(self.boxes): break
  693. prefix = self.boxes[i]["text"].strip()[:3] if not eng else " ".join(self.boxes[i]["text"].strip().split(" ")[:2])
  694. while not prefix:
  695. self.boxes.pop(i)
  696. if i >= len(self.boxes): break
  697. prefix = self.boxes[i]["text"].strip()[:3] if not eng else " ".join(self.boxes[i]["text"].strip().split(" ")[:2])
  698. self.boxes.pop(i)
  699. if i >= len(self.boxes) or not prefix: break
  700. for j in range(i, min(i + 128, len(self.boxes))):
  701. if not re.match(prefix, self.boxes[j]["text"]):
  702. continue
  703. for k in range(i, j): self.boxes.pop(i)
  704. break
  705. def _merge_with_same_bullet(self):
  706. i = 0
  707. while i + 1 < len(self.boxes):
  708. b = self.boxes[i]
  709. b_ = self.boxes[i + 1]
  710. if b["text"].strip()[0] != b_["text"].strip()[0] \
  711. or b["text"].strip()[0].lower() in set("qwertyuopasdfghjklzxcvbnm") \
  712. or b["top"] > b_["bottom"]:
  713. i += 1
  714. continue
  715. b_["text"] = b["text"] + "\n" + b_["text"]
  716. b_["x0"] = min(b["x0"], b_["x0"])
  717. b_["x1"] = max(b["x1"], b_["x1"])
  718. b_["top"] = b["top"]
  719. self.boxes.pop(i)
  720. def _blockType(self, b):
  721. patt = [
  722. ("^(20|19)[0-9]{2}[年/-][0-9]{1,2}[月/-][0-9]{1,2}日*$", "Dt"),
  723. (r"^(20|19)[0-9]{2}年$", "Dt"),
  724. (r"^(20|19)[0-9]{2}[年-][0-9]{1,2}月*$", "Dt"),
  725. ("^[0-9]{1,2}[月-][0-9]{1,2}日*$", "Dt"),
  726. (r"^第*[一二三四1-4]季度$", "Dt"),
  727. (r"^(20|19)[0-9]{2}年*[一二三四1-4]季度$", "Dt"),
  728. (r"^(20|19)[0-9]{2}[ABCDE]$", "Dt"),
  729. ("^[0-9.,+%/ -]+$", "Nu"),
  730. (r"^[0-9A-Z/\._~-]+$", "Ca"),
  731. (r"^[A-Z]*[a-z' -]+$", "En"),
  732. (r"^[0-9.,+-]+[0-9A-Za-z/$¥%<>()()' -]+$", "NE"),
  733. (r"^.{1}$", "Sg")
  734. ]
  735. for p, n in patt:
  736. if re.search(p, b["text"].strip()):
  737. return n
  738. tks = [t for t in huqie.qie(b["text"]).split(" ") if len(t) > 1]
  739. if len(tks) > 3:
  740. if len(tks) < 12:
  741. return "Tx"
  742. else:
  743. return "Lx"
  744. if len(tks) == 1 and huqie.tag(tks[0]) == "nr":
  745. return "Nr"
  746. return "Ot"
  747. def __cal_spans(self, boxes, rows, cols, tbl, html=True):
  748. # caculate span
  749. clft = [np.mean([c.get("C_left", c["x0"]) for c in cln])
  750. for cln in cols]
  751. crgt = [np.mean([c.get("C_right", c["x1"]) for c in cln])
  752. for cln in cols]
  753. rtop = [np.mean([c.get("R_top", c["top"]) for c in row])
  754. for row in rows]
  755. rbtm = [np.mean([c.get("R_btm", c["bottom"])
  756. for c in row]) for row in rows]
  757. for b in boxes:
  758. if "SP" not in b:
  759. continue
  760. b["colspan"] = [b["cn"]]
  761. b["rowspan"] = [b["rn"]]
  762. # col span
  763. for j in range(0, len(clft)):
  764. if j == b["cn"]:
  765. continue
  766. if clft[j] + (crgt[j] - clft[j]) / 2 < b["H_left"]:
  767. continue
  768. if crgt[j] - (crgt[j] - clft[j]) / 2 > b["H_right"]:
  769. continue
  770. b["colspan"].append(j)
  771. # row span
  772. for j in range(0, len(rtop)):
  773. if j == b["rn"]:
  774. continue
  775. if rtop[j] + (rbtm[j] - rtop[j]) / 2 < b["H_top"]:
  776. continue
  777. if rbtm[j] - (rbtm[j] - rtop[j]) / 2 > b["H_bott"]:
  778. continue
  779. b["rowspan"].append(j)
  780. def join(arr):
  781. if not arr:
  782. return ""
  783. return "".join([t["text"] for t in arr])
  784. # rm the spaning cells
  785. for i in range(len(tbl)):
  786. for j, arr in enumerate(tbl[i]):
  787. if not arr:
  788. continue
  789. if all(["rowspan" not in a and "colspan" not in a for a in arr]):
  790. continue
  791. rowspan, colspan = [], []
  792. for a in arr:
  793. if isinstance(a.get("rowspan", 0), list):
  794. rowspan.extend(a["rowspan"])
  795. if isinstance(a.get("colspan", 0), list):
  796. colspan.extend(a["colspan"])
  797. rowspan, colspan = set(rowspan), set(colspan)
  798. if len(rowspan) < 2 and len(colspan) < 2:
  799. for a in arr:
  800. if "rowspan" in a:
  801. del a["rowspan"]
  802. if "colspan" in a:
  803. del a["colspan"]
  804. continue
  805. rowspan, colspan = sorted(rowspan), sorted(colspan)
  806. rowspan = list(range(rowspan[0], rowspan[-1] + 1))
  807. colspan = list(range(colspan[0], colspan[-1] + 1))
  808. assert i in rowspan, rowspan
  809. assert j in colspan, colspan
  810. arr = []
  811. for r in rowspan:
  812. for c in colspan:
  813. arr_txt = join(arr)
  814. if tbl[r][c] and join(tbl[r][c]) != arr_txt:
  815. arr.extend(tbl[r][c])
  816. tbl[r][c] = None if html else arr
  817. for a in arr:
  818. if len(rowspan) > 1:
  819. a["rowspan"] = len(rowspan)
  820. elif "rowspan" in a:
  821. del a["rowspan"]
  822. if len(colspan) > 1:
  823. a["colspan"] = len(colspan)
  824. elif "colspan" in a:
  825. del a["colspan"]
  826. tbl[rowspan[0]][colspan[0]] = arr
  827. return tbl
  828. def __construct_table(self, boxes, html=False):
  829. cap = ""
  830. i = 0
  831. while i < len(boxes):
  832. if self.is_caption(boxes[i]):
  833. cap += boxes[i]["text"]
  834. boxes.pop(i)
  835. i -= 1
  836. i += 1
  837. if not boxes:
  838. return []
  839. for b in boxes:
  840. b["btype"] = self._blockType(b)
  841. max_type = Counter([b["btype"] for b in boxes]).items()
  842. max_type = max(max_type, key=lambda x: x[1])[0] if max_type else ""
  843. logging.debug("MAXTYPE: " + max_type)
  844. rowh = [b["R_bott"] - b["R_top"] for b in boxes if "R" in b]
  845. rowh = np.min(rowh) if rowh else 0
  846. # boxes = self.sort_Y_firstly(boxes, rowh/5)
  847. boxes = self.sort_R_firstly(boxes, rowh / 2)
  848. boxes[0]["rn"] = 0
  849. rows = [[boxes[0]]]
  850. btm = boxes[0]["bottom"]
  851. for b in boxes[1:]:
  852. b["rn"] = len(rows) - 1
  853. lst_r = rows[-1]
  854. if lst_r[-1].get("R", "") != b.get("R", "") \
  855. or (b["top"] >= btm - 3 and lst_r[-1].get("R", "-1") != b.get("R", "-2")
  856. ): # new row
  857. btm = b["bottom"]
  858. b["rn"] += 1
  859. rows.append([b])
  860. continue
  861. btm = (btm + b["bottom"]) / 2.
  862. rows[-1].append(b)
  863. colwm = [b["C_right"] - b["C_left"] for b in boxes if "C" in b]
  864. colwm = np.min(colwm) if colwm else 0
  865. crosspage = len(set([b["page_number"] for b in boxes])) > 1
  866. if crosspage:
  867. boxes = self.sort_X_firstly(boxes, colwm / 2, False)
  868. else:
  869. boxes = self.sort_C_firstly(boxes, colwm / 2)
  870. boxes[0]["cn"] = 0
  871. cols = [[boxes[0]]]
  872. right = boxes[0]["x1"]
  873. for b in boxes[1:]:
  874. b["cn"] = len(cols) - 1
  875. lst_c = cols[-1]
  876. if (int(b.get("C", "1")) - int(lst_c[-1].get("C", "1")) == 1 and b["page_number"] == lst_c[-1][
  877. "page_number"]) \
  878. or (b["x0"] >= right and lst_c[-1].get("C", "-1") != b.get("C", "-2")): # new col
  879. right = b["x1"]
  880. b["cn"] += 1
  881. cols.append([b])
  882. continue
  883. right = (right + b["x1"]) / 2.
  884. cols[-1].append(b)
  885. tbl = [[[] for _ in range(len(cols))] for _ in range(len(rows))]
  886. for b in boxes:
  887. tbl[b["rn"]][b["cn"]].append(b)
  888. if len(rows) >= 4:
  889. # remove single in column
  890. j = 0
  891. while j < len(tbl[0]):
  892. e, ii = 0, 0
  893. for i in range(len(tbl)):
  894. if tbl[i][j]:
  895. e += 1
  896. ii = i
  897. if e > 1:
  898. break
  899. if e > 1:
  900. j += 1
  901. continue
  902. f = (j > 0 and tbl[ii][j - 1] and tbl[ii]
  903. [j - 1][0].get("text")) or j == 0
  904. ff = (j + 1 < len(tbl[ii]) and tbl[ii][j + 1] and tbl[ii]
  905. [j + 1][0].get("text")) or j + 1 >= len(tbl[ii])
  906. if f and ff:
  907. j += 1
  908. continue
  909. bx = tbl[ii][j][0]
  910. logging.debug("Relocate column single: " + bx["text"])
  911. # j column only has one value
  912. left, right = 100000, 100000
  913. if j > 0 and not f:
  914. for i in range(len(tbl)):
  915. if tbl[i][j - 1]:
  916. left = min(left, np.min(
  917. [bx["x0"] - a["x1"] for a in tbl[i][j - 1]]))
  918. if j + 1 < len(tbl[0]) and not ff:
  919. for i in range(len(tbl)):
  920. if tbl[i][j + 1]:
  921. right = min(right, np.min(
  922. [a["x0"] - bx["x1"] for a in tbl[i][j + 1]]))
  923. assert left < 100000 or right < 100000
  924. if left < right:
  925. for jj in range(j, len(tbl[0])):
  926. for i in range(len(tbl)):
  927. for a in tbl[i][jj]:
  928. a["cn"] -= 1
  929. if tbl[ii][j - 1]:
  930. tbl[ii][j - 1].extend(tbl[ii][j])
  931. else:
  932. tbl[ii][j - 1] = tbl[ii][j]
  933. for i in range(len(tbl)):
  934. tbl[i].pop(j)
  935. else:
  936. for jj in range(j + 1, len(tbl[0])):
  937. for i in range(len(tbl)):
  938. for a in tbl[i][jj]:
  939. a["cn"] -= 1
  940. if tbl[ii][j + 1]:
  941. tbl[ii][j + 1].extend(tbl[ii][j])
  942. else:
  943. tbl[ii][j + 1] = tbl[ii][j]
  944. for i in range(len(tbl)):
  945. tbl[i].pop(j)
  946. cols.pop(j)
  947. assert len(cols) == len(tbl[0]), "Column NO. miss matched: %d vs %d" % (
  948. len(cols), len(tbl[0]))
  949. if len(cols) >= 4:
  950. # remove single in row
  951. i = 0
  952. while i < len(tbl):
  953. e, jj = 0, 0
  954. for j in range(len(tbl[i])):
  955. if tbl[i][j]:
  956. e += 1
  957. jj = j
  958. if e > 1:
  959. break
  960. if e > 1:
  961. i += 1
  962. continue
  963. f = (i > 0 and tbl[i - 1][jj] and tbl[i - 1]
  964. [jj][0].get("text")) or i == 0
  965. ff = (i + 1 < len(tbl) and tbl[i + 1][jj] and tbl[i + 1]
  966. [jj][0].get("text")) or i + 1 >= len(tbl)
  967. if f and ff:
  968. i += 1
  969. continue
  970. bx = tbl[i][jj][0]
  971. logging.debug("Relocate row single: " + bx["text"])
  972. # i row only has one value
  973. up, down = 100000, 100000
  974. if i > 0 and not f:
  975. for j in range(len(tbl[i - 1])):
  976. if tbl[i - 1][j]:
  977. up = min(up, np.min(
  978. [bx["top"] - a["bottom"] for a in tbl[i - 1][j]]))
  979. if i + 1 < len(tbl) and not ff:
  980. for j in range(len(tbl[i + 1])):
  981. if tbl[i + 1][j]:
  982. down = min(down, np.min(
  983. [a["top"] - bx["bottom"] for a in tbl[i + 1][j]]))
  984. assert up < 100000 or down < 100000
  985. if up < down:
  986. for ii in range(i, len(tbl)):
  987. for j in range(len(tbl[ii])):
  988. for a in tbl[ii][j]:
  989. a["rn"] -= 1
  990. if tbl[i - 1][jj]:
  991. tbl[i - 1][jj].extend(tbl[i][jj])
  992. else:
  993. tbl[i - 1][jj] = tbl[i][jj]
  994. tbl.pop(i)
  995. else:
  996. for ii in range(i + 1, len(tbl)):
  997. for j in range(len(tbl[ii])):
  998. for a in tbl[ii][j]:
  999. a["rn"] -= 1
  1000. if tbl[i + 1][jj]:
  1001. tbl[i + 1][jj].extend(tbl[i][jj])
  1002. else:
  1003. tbl[i + 1][jj] = tbl[i][jj]
  1004. tbl.pop(i)
  1005. rows.pop(i)
  1006. # which rows are headers
  1007. hdset = set([])
  1008. for i in range(len(tbl)):
  1009. cnt, h = 0, 0
  1010. for j, arr in enumerate(tbl[i]):
  1011. if not arr:
  1012. continue
  1013. cnt += 1
  1014. if max_type == "Nu" and arr[0]["btype"] == "Nu":
  1015. continue
  1016. if any([a.get("H") for a in arr]) \
  1017. or (max_type == "Nu" and arr[0]["btype"] != "Nu"):
  1018. h += 1
  1019. if h / cnt > 0.5:
  1020. hdset.add(i)
  1021. if html:
  1022. return [self.__html_table(cap, hdset,
  1023. self.__cal_spans(boxes, rows,
  1024. cols, tbl, True)
  1025. )]
  1026. return self.__desc_table(cap, hdset,
  1027. self.__cal_spans(boxes, rows, cols, tbl, False))
  1028. def __html_table(self, cap, hdset, tbl):
  1029. # constrcut HTML
  1030. html = "<table>"
  1031. if cap:
  1032. html += f"<caption>{cap}</caption>"
  1033. for i in range(len(tbl)):
  1034. row = "<tr>"
  1035. txts = []
  1036. for j, arr in enumerate(tbl[i]):
  1037. if arr is None:
  1038. continue
  1039. if not arr:
  1040. row += "<td></td>" if i not in hdset else "<th></th>"
  1041. continue
  1042. txt = ""
  1043. if arr:
  1044. h = min(np.min([c["bottom"] - c["top"] for c in arr]) / 2,
  1045. self.mean_height[arr[0]["page_number"] - 1] / 2)
  1046. txt = "".join([c["text"]
  1047. for c in self.sort_Y_firstly(arr, h)])
  1048. txts.append(txt)
  1049. sp = ""
  1050. if arr[0].get("colspan"):
  1051. sp = "colspan={}".format(arr[0]["colspan"])
  1052. if arr[0].get("rowspan"):
  1053. sp += " rowspan={}".format(arr[0]["rowspan"])
  1054. if i in hdset:
  1055. row += f"<th {sp} >" + txt + "</th>"
  1056. else:
  1057. row += f"<td {sp} >" + txt + "</td>"
  1058. if i in hdset:
  1059. if all([t in hdset for t in txts]):
  1060. continue
  1061. for t in txts:
  1062. hdset.add(t)
  1063. if row != "<tr>":
  1064. row += "</tr>"
  1065. else:
  1066. row = ""
  1067. html += "\n" + row
  1068. html += "\n</table>"
  1069. return html
  1070. def __desc_table(self, cap, hdr_rowno, tbl):
  1071. # get text of every colomn in header row to become header text
  1072. clmno = len(tbl[0])
  1073. rowno = len(tbl)
  1074. headers = {}
  1075. hdrset = set()
  1076. lst_hdr = []
  1077. de = "的" if not self.is_english else " for "
  1078. for r in sorted(list(hdr_rowno)):
  1079. headers[r] = ["" for _ in range(clmno)]
  1080. for i in range(clmno):
  1081. if not tbl[r][i]:
  1082. continue
  1083. txt = "".join([a["text"].strip() for a in tbl[r][i]])
  1084. headers[r][i] = txt
  1085. hdrset.add(txt)
  1086. if all([not t for t in headers[r]]):
  1087. del headers[r]
  1088. hdr_rowno.remove(r)
  1089. continue
  1090. for j in range(clmno):
  1091. if headers[r][j]:
  1092. continue
  1093. if j >= len(lst_hdr):
  1094. break
  1095. headers[r][j] = lst_hdr[j]
  1096. lst_hdr = headers[r]
  1097. for i in range(rowno):
  1098. if i not in hdr_rowno:
  1099. continue
  1100. for j in range(i + 1, rowno):
  1101. if j not in hdr_rowno:
  1102. break
  1103. for k in range(clmno):
  1104. if not headers[j - 1][k]:
  1105. continue
  1106. if headers[j][k].find(headers[j - 1][k]) >= 0:
  1107. continue
  1108. if len(headers[j][k]) > len(headers[j - 1][k]):
  1109. headers[j][k] += (de if headers[j][k]
  1110. else "") + headers[j - 1][k]
  1111. else:
  1112. headers[j][k] = headers[j - 1][k] \
  1113. + (de if headers[j - 1][k] else "") \
  1114. + headers[j][k]
  1115. logging.debug(
  1116. f">>>>>>>>>>>>>>>>>{cap}:SIZE:{rowno}X{clmno} Header: {hdr_rowno}")
  1117. row_txt = []
  1118. for i in range(rowno):
  1119. if i in hdr_rowno:
  1120. continue
  1121. rtxt = []
  1122. def append(delimer):
  1123. nonlocal rtxt, row_txt
  1124. rtxt = delimer.join(rtxt)
  1125. if row_txt and len(row_txt[-1]) + len(rtxt) < 64:
  1126. row_txt[-1] += "\n" + rtxt
  1127. else:
  1128. row_txt.append(rtxt)
  1129. r = 0
  1130. if len(headers.items()):
  1131. _arr = [(i - r, r) for r, _ in headers.items() if r < i]
  1132. if _arr:
  1133. _, r = min(_arr, key=lambda x: x[0])
  1134. if r not in headers and clmno <= 2:
  1135. for j in range(clmno):
  1136. if not tbl[i][j]:
  1137. continue
  1138. txt = "".join([a["text"].strip() for a in tbl[i][j]])
  1139. if txt:
  1140. rtxt.append(txt)
  1141. if rtxt:
  1142. append(":")
  1143. continue
  1144. for j in range(clmno):
  1145. if not tbl[i][j]:
  1146. continue
  1147. txt = "".join([a["text"].strip() for a in tbl[i][j]])
  1148. if not txt:
  1149. continue
  1150. ctt = headers[r][j] if r in headers else ""
  1151. if ctt:
  1152. ctt += ":"
  1153. ctt += txt
  1154. if ctt:
  1155. rtxt.append(ctt)
  1156. if rtxt:
  1157. row_txt.append("; ".join(rtxt))
  1158. if cap:
  1159. if self.is_english:
  1160. from_ = " in "
  1161. else:
  1162. from_ = "来自"
  1163. row_txt = [t + f"\t——{from_}“{cap}”" for t in row_txt]
  1164. return row_txt
  1165. @staticmethod
  1166. def is_caption(bx):
  1167. patt = [
  1168. r"[图表]+[ 0-9::]{2,}"
  1169. ]
  1170. if any([re.match(p, bx["text"].strip()) for p in patt]) \
  1171. or bx["layout_type"].find("caption") >= 0:
  1172. return True
  1173. return False
  1174. def _extract_table_figure(self, need_image, ZM, return_html):
  1175. tables = {}
  1176. figures = {}
  1177. # extract figure and table boxes
  1178. i = 0
  1179. lst_lout_no = ""
  1180. nomerge_lout_no = []
  1181. while i < len(self.boxes):
  1182. if "layoutno" not in self.boxes[i]:
  1183. i += 1
  1184. continue
  1185. lout_no = str(self.boxes[i]["page_number"]) + \
  1186. "-" + str(self.boxes[i]["layoutno"])
  1187. if self.is_caption(self.boxes[i]) or self.boxes[i]["layout_type"] in ["table caption", "title",
  1188. "figure caption", "reference"]:
  1189. nomerge_lout_no.append(lst_lout_no)
  1190. if self.boxes[i]["layout_type"] == "table":
  1191. if re.match(r"(数据|资料|图表)*来源[:: ]", self.boxes[i]["text"]):
  1192. self.boxes.pop(i)
  1193. continue
  1194. if lout_no not in tables:
  1195. tables[lout_no] = []
  1196. tables[lout_no].append(self.boxes[i])
  1197. self.boxes.pop(i)
  1198. lst_lout_no = lout_no
  1199. continue
  1200. if need_image and self.boxes[i]["layout_type"] == "figure":
  1201. if re.match(r"(数据|资料|图表)*来源[:: ]", self.boxes[i]["text"]):
  1202. self.boxes.pop(i)
  1203. continue
  1204. if lout_no not in figures:
  1205. figures[lout_no] = []
  1206. figures[lout_no].append(self.boxes[i])
  1207. self.boxes.pop(i)
  1208. lst_lout_no = lout_no
  1209. continue
  1210. i += 1
  1211. # merge table on different pages
  1212. nomerge_lout_no = set(nomerge_lout_no)
  1213. tbls = sorted([(k, bxs) for k, bxs in tables.items()],
  1214. key=lambda x: (x[1][0]["top"], x[1][0]["x0"]))
  1215. i = len(tbls) - 1
  1216. while i - 1 >= 0:
  1217. k0, bxs0 = tbls[i - 1]
  1218. k, bxs = tbls[i]
  1219. i -= 1
  1220. if k0 in nomerge_lout_no:
  1221. continue
  1222. if bxs[0]["page_number"] == bxs0[0]["page_number"]:
  1223. continue
  1224. if bxs[0]["page_number"] - bxs0[0]["page_number"] > 1:
  1225. continue
  1226. mh = self.mean_height[bxs[0]["page_number"] - 1]
  1227. if self._y_dis(bxs0[-1], bxs[0]) > mh * 23:
  1228. continue
  1229. tables[k0].extend(tables[k])
  1230. del tables[k]
  1231. def x_overlapped(a, b):
  1232. return not any([a["x1"] < b["x0"], a["x0"] > b["x1"]])
  1233. # find captions and pop out
  1234. i = 0
  1235. while i < len(self.boxes):
  1236. c = self.boxes[i]
  1237. # mh = self.mean_height[c["page_number"]-1]
  1238. if not self.is_caption(c):
  1239. i += 1
  1240. continue
  1241. # find the nearest layouts
  1242. def nearest(tbls):
  1243. nonlocal c
  1244. mink = ""
  1245. minv = 1000000000
  1246. for k, bxs in tbls.items():
  1247. for b in bxs[:10]:
  1248. if b.get("layout_type", "").find("caption") >= 0:
  1249. continue
  1250. y_dis = self._y_dis(c, b)
  1251. x_dis = self._x_dis(
  1252. c, b) if not x_overlapped(
  1253. c, b) else 0
  1254. dis = y_dis * y_dis + x_dis * x_dis
  1255. if dis < minv:
  1256. mink = k
  1257. minv = dis
  1258. return mink, minv
  1259. tk, tv = nearest(tables)
  1260. fk, fv = nearest(figures)
  1261. if min(tv, fv) > 2000:
  1262. i += 1
  1263. continue
  1264. if tv < fv:
  1265. tables[tk].insert(0, c)
  1266. logging.debug(
  1267. "TABLE:" +
  1268. self.boxes[i]["text"] +
  1269. "; Cap: " +
  1270. tk)
  1271. else:
  1272. figures[fk].insert(0, c)
  1273. logging.debug(
  1274. "FIGURE:" +
  1275. self.boxes[i]["text"] +
  1276. "; Cap: " +
  1277. tk)
  1278. self.boxes.pop(i)
  1279. res = []
  1280. def cropout(bxs, ltype):
  1281. nonlocal ZM
  1282. pn = set([b["page_number"] - 1 for b in bxs])
  1283. if len(pn) < 2:
  1284. pn = list(pn)[0]
  1285. ht = self.page_cum_height[pn]
  1286. b = {
  1287. "x0": np.min([b["x0"] for b in bxs]),
  1288. "top": np.min([b["top"] for b in bxs]) - ht,
  1289. "x1": np.max([b["x1"] for b in bxs]),
  1290. "bottom": np.max([b["bottom"] for b in bxs]) - ht
  1291. }
  1292. louts = [l for l in self.page_layout[pn] if l["type"] == ltype]
  1293. ii = self.__find_overlapped(b, louts, naive=True)
  1294. if ii is not None:
  1295. b = louts[ii]
  1296. else:
  1297. logging.warn(
  1298. f"Missing layout match: {pn + 1},%s" %
  1299. (bxs[0].get(
  1300. "layoutno", "")))
  1301. left, top, right, bott = b["x0"], b["top"], b["x1"], b["bottom"]
  1302. return self.page_images[pn] \
  1303. .crop((left * ZM, top * ZM,
  1304. right * ZM, bott * ZM))
  1305. pn = {}
  1306. for b in bxs:
  1307. p = b["page_number"] - 1
  1308. if p not in pn:
  1309. pn[p] = []
  1310. pn[p].append(b)
  1311. pn = sorted(pn.items(), key=lambda x: x[0])
  1312. imgs = [cropout(arr, ltype) for p, arr in pn]
  1313. pic = Image.new("RGB",
  1314. (int(np.max([i.size[0] for i in imgs])),
  1315. int(np.sum([m.size[1] for m in imgs]))),
  1316. (245, 245, 245))
  1317. height = 0
  1318. for img in imgs:
  1319. pic.paste(img, (0, int(height)))
  1320. height += img.size[1]
  1321. return pic
  1322. # crop figure out and add caption
  1323. for k, bxs in figures.items():
  1324. txt = "\n".join(
  1325. [b["text"] for b in bxs
  1326. if not re.match(r"[0-9a-z.\+%-]", b["text"].strip())
  1327. and len(b["text"].strip()) >= 4
  1328. ]
  1329. )
  1330. if not txt:
  1331. continue
  1332. res.append(
  1333. (cropout(
  1334. bxs,
  1335. "figure"),
  1336. [txt] if not return_html else [f"<p>{txt}</p>"]))
  1337. for k, bxs in tables.items():
  1338. if not bxs:
  1339. continue
  1340. res.append((cropout(bxs, "table"),
  1341. self.__construct_table(bxs, html=return_html)))
  1342. return res
  1343. def proj_match(self, line):
  1344. if len(line) <= 2:
  1345. return
  1346. if re.match(r"[0-9 ().,%%+/-]+$", line):
  1347. return False
  1348. for p, j in [
  1349. (r"第[零一二三四五六七八九十百]+章", 1),
  1350. (r"第[零一二三四五六七八九十百]+[条节]", 2),
  1351. (r"[零一二三四五六七八九十百]+[、  ]", 3),
  1352. (r"[\((][零一二三四五六七八九十百]+[)\)]", 4),
  1353. (r"[0-9]+(、|\.[  ]|\.[^0-9])", 5),
  1354. (r"[0-9]+\.[0-9]+(、|[.  ]|[^0-9])", 6),
  1355. (r"[0-9]+\.[0-9]+\.[0-9]+(、|[  ]|[^0-9])", 7),
  1356. (r"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(、|[  ]|[^0-9])", 8),
  1357. (r".{,48}[::??]$", 9),
  1358. (r"[0-9]+)", 10),
  1359. (r"[\((][0-9]+[)\)]", 11),
  1360. (r"[零一二三四五六七八九十百]+是", 12),
  1361. (r"[⚫•➢✓]", 12)
  1362. ]:
  1363. if re.match(p, line):
  1364. return j
  1365. return
  1366. def _line_tag(self, bx, ZM):
  1367. pn = [bx["page_number"]]
  1368. top = bx["top"] - self.page_cum_height[pn[0] - 1]
  1369. bott = bx["bottom"] - self.page_cum_height[pn[0] - 1]
  1370. while bott * ZM > self.page_images[pn[-1] - 1].size[1]:
  1371. bott -= self.page_images[pn[-1] - 1].size[1] / ZM
  1372. pn.append(pn[-1] + 1)
  1373. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  1374. .format("-".join([str(p) for p in pn]),
  1375. bx["x0"], bx["x1"], top, bott)
  1376. def __filterout_scraps(self, boxes, ZM):
  1377. def width(b):
  1378. return b["x1"] - b["x0"]
  1379. def height(b):
  1380. return b["bottom"] - b["top"]
  1381. def usefull(b):
  1382. if b.get("layout_type"):
  1383. return True
  1384. if width(
  1385. b) > self.page_images[b["page_number"] - 1].size[0] / ZM / 3:
  1386. return True
  1387. if b["bottom"] - b["top"] > self.mean_height[b["page_number"] - 1]:
  1388. return True
  1389. return False
  1390. res = []
  1391. while boxes:
  1392. lines = []
  1393. widths = []
  1394. pw = self.page_images[boxes[0]["page_number"] - 1].size[0] / ZM
  1395. mh = self.mean_height[boxes[0]["page_number"] - 1]
  1396. mj = self.proj_match(
  1397. boxes[0]["text"]) or boxes[0].get(
  1398. "layout_type",
  1399. "") == "title"
  1400. def dfs(line, st):
  1401. nonlocal mh, pw, lines, widths
  1402. lines.append(line)
  1403. widths.append(width(line))
  1404. width_mean = np.mean(widths)
  1405. mmj = self.proj_match(
  1406. line["text"]) or line.get(
  1407. "layout_type",
  1408. "") == "title"
  1409. for i in range(st + 1, min(st + 20, len(boxes))):
  1410. if (boxes[i]["page_number"] - line["page_number"]) > 0:
  1411. break
  1412. if not mmj and self._y_dis(
  1413. line, boxes[i]) >= 3 * mh and height(line) < 1.5 * mh:
  1414. break
  1415. if not usefull(boxes[i]):
  1416. continue
  1417. if mmj or \
  1418. (self._x_dis(boxes[i], line) < pw / 10): \
  1419. # and abs(width(boxes[i])-width_mean)/max(width(boxes[i]),width_mean)<0.5):
  1420. # concat following
  1421. dfs(boxes[i], i)
  1422. boxes.pop(i)
  1423. break
  1424. try:
  1425. if usefull(boxes[0]):
  1426. dfs(boxes[0], 0)
  1427. else:
  1428. logging.debug("WASTE: " + boxes[0]["text"])
  1429. except Exception as e:
  1430. pass
  1431. boxes.pop(0)
  1432. mw = np.mean(widths)
  1433. if mj or mw / pw >= 0.35 or mw > 200:
  1434. res.append("\n".join([c["text"] + self._line_tag(c, ZM) for c in lines]))
  1435. else:
  1436. logging.debug("REMOVED: " +
  1437. "<<".join([c["text"] for c in lines]))
  1438. return "\n\n".join(res)
  1439. @staticmethod
  1440. def total_page_number(fnm, binary=None):
  1441. try:
  1442. pdf = pdfplumber.open(fnm) if not binary else pdfplumber.open(BytesIO(binary))
  1443. return len(pdf.pages)
  1444. except Exception as e:
  1445. pdf = fitz.open(fnm) if not binary else fitz.open(stream=fnm, filetype="pdf")
  1446. return len(pdf)
  1447. def __images__(self, fnm, zoomin=3, page_from=0, page_to=299):
  1448. self.lefted_chars = []
  1449. self.mean_height = []
  1450. self.mean_width = []
  1451. self.boxes = []
  1452. self.garbages = {}
  1453. self.page_cum_height = [0]
  1454. self.page_layout = []
  1455. try:
  1456. self.pdf = pdfplumber.open(fnm) if isinstance(fnm, str) else pdfplumber.open(BytesIO(fnm))
  1457. self.page_images = [p.to_image(resolution=72 * zoomin).annotated for i, p in
  1458. enumerate(self.pdf.pages[page_from:page_to])]
  1459. self.page_chars = [[c for c in self.pdf.pages[i].chars if self._has_color(c)] for i in
  1460. range(len(self.page_images))]
  1461. self.total_page = len(self.pdf.pages)
  1462. except Exception as e:
  1463. self.pdf = fitz.open(fnm) if isinstance(fnm, str) else fitz.open(stream=fnm, filetype="pdf")
  1464. self.page_images = []
  1465. self.page_chars = []
  1466. mat = fitz.Matrix(zoomin, zoomin)
  1467. self.total_page = len(self.pdf)
  1468. for page in self.pdf[page_from:page_to]:
  1469. pix = page.getPixmap(matrix=mat)
  1470. img = Image.frombytes("RGB", [pix.width, pix.height],
  1471. pix.samples)
  1472. self.page_images.append(img)
  1473. self.page_chars.append([])
  1474. logging.info("Images converted.")
  1475. self.is_english = [re.search(r"[a-zA-Z0-9,/¸;:'\[\]\(\)!@#$%^&*\"?<>._-]{30,}", "".join(random.choices([c["text"] for c in self.page_chars[i]], k=100))) for i in range(len(self.page_chars))]
  1476. if sum([1 if e else 0 for e in self.is_english]) > len(self.page_images) / 2:
  1477. self.is_english = True
  1478. else:
  1479. self.is_english = False
  1480. for i, img in enumerate(self.page_images):
  1481. chars = self.page_chars[i] if not self.is_english else []
  1482. self.mean_height.append(
  1483. np.median(sorted([c["height"] for c in chars])) if chars else 0
  1484. )
  1485. self.mean_width.append(
  1486. np.median(sorted([c["width"] for c in chars])) if chars else 8
  1487. )
  1488. self.page_cum_height.append(img.size[1] / zoomin)
  1489. j = 0
  1490. while j + 1 < len(chars):
  1491. if chars[j]["text"] and chars[j + 1]["text"] \
  1492. and re.match(r"[0-9a-zA-Z,.:;!%]+", chars[j]["text"] + chars[j + 1]["text"]) \
  1493. and chars[j + 1]["x0"] - chars[j]["x1"] >= min(chars[j + 1]["width"],
  1494. chars[j]["width"]) / 2:
  1495. chars[j]["text"] += " "
  1496. j += 1
  1497. # if i > 0:
  1498. # if not chars:
  1499. # self.page_cum_height.append(img.size[1] / zoomin)
  1500. # else:
  1501. # self.page_cum_height.append(
  1502. # np.max([c["bottom"] for c in chars]))
  1503. self.__ocr_paddle(i + 1, img, chars, zoomin)
  1504. if not self.is_english and not all([c for c in self.page_chars]) and self.boxes:
  1505. self.is_english = re.search(r"[\na-zA-Z0-9,/¸;:'\[\]\(\)!@#$%^&*\"?<>._-]{30,}", "".join([b["text"] for b in random.choices(self.boxes, k=30)]))
  1506. logging.info("Is it English:", self.is_english)
  1507. self.page_cum_height = np.cumsum(self.page_cum_height)
  1508. assert len(self.page_cum_height) == len(self.page_images) + 1
  1509. def __call__(self, fnm, need_image=True, zoomin=3, return_html=False):
  1510. self.__images__(fnm, zoomin)
  1511. self._layouts_paddle(zoomin)
  1512. self._table_transformer_job(zoomin)
  1513. self._text_merge()
  1514. self._concat_downward()
  1515. self._filter_forpages()
  1516. tbls = self._extract_table_figure(need_image, zoomin, return_html)
  1517. return self.__filterout_scraps(deepcopy(self.boxes), zoomin), tbls
  1518. def remove_tag(self, txt):
  1519. return re.sub(r"@@[\t0-9.-]+?##", "", txt)
  1520. def crop(self, text, ZM=3):
  1521. imgs = []
  1522. for tag in re.findall(r"@@[0-9-]+\t[0-9.\t]+##", text):
  1523. pn, left, right, top, bottom = tag.strip(
  1524. "#").strip("@").split("\t")
  1525. left, right, top, bottom = float(left), float(
  1526. right), float(top), float(bottom)
  1527. bottom *= ZM
  1528. pns = [int(p) - 1 for p in pn.split("-")]
  1529. for pn in pns[1:]:
  1530. bottom += self.page_images[pn - 1].size[1]
  1531. imgs.append(
  1532. self.page_images[pns[0]].crop((left * ZM, top * ZM,
  1533. right *
  1534. ZM, min(
  1535. bottom, self.page_images[pns[0]].size[1])
  1536. ))
  1537. )
  1538. bottom -= self.page_images[pns[0]].size[1]
  1539. for pn in pns[1:]:
  1540. imgs.append(
  1541. self.page_images[pn].crop((left * ZM, 0,
  1542. right * ZM,
  1543. min(bottom,
  1544. self.page_images[pn].size[1])
  1545. ))
  1546. )
  1547. bottom -= self.page_images[pn].size[1]
  1548. if not imgs:
  1549. return
  1550. GAP = 2
  1551. height = 0
  1552. for img in imgs:
  1553. height += img.size[1] + GAP
  1554. height = int(height)
  1555. pic = Image.new("RGB",
  1556. (int(np.max([i.size[0] for i in imgs])), height),
  1557. (245, 245, 245))
  1558. height = 0
  1559. for img in imgs:
  1560. pic.paste(img, (0, int(height)))
  1561. height += img.size[1] + GAP
  1562. return pic
  1563. if __name__ == "__main__":
  1564. pass