Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  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)$", 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 _blockType(self, b):
  706. patt = [
  707. ("^(20|19)[0-9]{2}[年/-][0-9]{1,2}[月/-][0-9]{1,2}日*$", "Dt"),
  708. (r"^(20|19)[0-9]{2}年$", "Dt"),
  709. (r"^(20|19)[0-9]{2}[年-][0-9]{1,2}月*$", "Dt"),
  710. ("^[0-9]{1,2}[月-][0-9]{1,2}日*$", "Dt"),
  711. (r"^第*[一二三四1-4]季度$", "Dt"),
  712. (r"^(20|19)[0-9]{2}年*[一二三四1-4]季度$", "Dt"),
  713. (r"^(20|19)[0-9]{2}[ABCDE]$", "Dt"),
  714. ("^[0-9.,+%/ -]+$", "Nu"),
  715. (r"^[0-9A-Z/\._~-]+$", "Ca"),
  716. (r"^[A-Z]*[a-z' -]+$", "En"),
  717. (r"^[0-9.,+-]+[0-9A-Za-z/$¥%<>()()' -]+$", "NE"),
  718. (r"^.{1}$", "Sg")
  719. ]
  720. for p, n in patt:
  721. if re.search(p, b["text"].strip()):
  722. return n
  723. tks = [t for t in huqie.qie(b["text"]).split(" ") if len(t) > 1]
  724. if len(tks) > 3:
  725. if len(tks) < 12:
  726. return "Tx"
  727. else:
  728. return "Lx"
  729. if len(tks) == 1 and huqie.tag(tks[0]) == "nr":
  730. return "Nr"
  731. return "Ot"
  732. def __cal_spans(self, boxes, rows, cols, tbl, html=True):
  733. # caculate span
  734. clft = [np.mean([c.get("C_left", c["x0"]) for c in cln])
  735. for cln in cols]
  736. crgt = [np.mean([c.get("C_right", c["x1"]) for c in cln])
  737. for cln in cols]
  738. rtop = [np.mean([c.get("R_top", c["top"]) for c in row])
  739. for row in rows]
  740. rbtm = [np.mean([c.get("R_btm", c["bottom"])
  741. for c in row]) for row in rows]
  742. for b in boxes:
  743. if "SP" not in b:
  744. continue
  745. b["colspan"] = [b["cn"]]
  746. b["rowspan"] = [b["rn"]]
  747. # col span
  748. for j in range(0, len(clft)):
  749. if j == b["cn"]:
  750. continue
  751. if clft[j] + (crgt[j] - clft[j]) / 2 < b["H_left"]:
  752. continue
  753. if crgt[j] - (crgt[j] - clft[j]) / 2 > b["H_right"]:
  754. continue
  755. b["colspan"].append(j)
  756. # row span
  757. for j in range(0, len(rtop)):
  758. if j == b["rn"]:
  759. continue
  760. if rtop[j] + (rbtm[j] - rtop[j]) / 2 < b["H_top"]:
  761. continue
  762. if rbtm[j] - (rbtm[j] - rtop[j]) / 2 > b["H_bott"]:
  763. continue
  764. b["rowspan"].append(j)
  765. def join(arr):
  766. if not arr:
  767. return ""
  768. return "".join([t["text"] for t in arr])
  769. # rm the spaning cells
  770. for i in range(len(tbl)):
  771. for j, arr in enumerate(tbl[i]):
  772. if not arr:
  773. continue
  774. if all(["rowspan" not in a and "colspan" not in a for a in arr]):
  775. continue
  776. rowspan, colspan = [], []
  777. for a in arr:
  778. if isinstance(a.get("rowspan", 0), list):
  779. rowspan.extend(a["rowspan"])
  780. if isinstance(a.get("colspan", 0), list):
  781. colspan.extend(a["colspan"])
  782. rowspan, colspan = set(rowspan), set(colspan)
  783. if len(rowspan) < 2 and len(colspan) < 2:
  784. for a in arr:
  785. if "rowspan" in a:
  786. del a["rowspan"]
  787. if "colspan" in a:
  788. del a["colspan"]
  789. continue
  790. rowspan, colspan = sorted(rowspan), sorted(colspan)
  791. rowspan = list(range(rowspan[0], rowspan[-1] + 1))
  792. colspan = list(range(colspan[0], colspan[-1] + 1))
  793. assert i in rowspan, rowspan
  794. assert j in colspan, colspan
  795. arr = []
  796. for r in rowspan:
  797. for c in colspan:
  798. arr_txt = join(arr)
  799. if tbl[r][c] and join(tbl[r][c]) != arr_txt:
  800. arr.extend(tbl[r][c])
  801. tbl[r][c] = None if html else arr
  802. for a in arr:
  803. if len(rowspan) > 1:
  804. a["rowspan"] = len(rowspan)
  805. elif "rowspan" in a:
  806. del a["rowspan"]
  807. if len(colspan) > 1:
  808. a["colspan"] = len(colspan)
  809. elif "colspan" in a:
  810. del a["colspan"]
  811. tbl[rowspan[0]][colspan[0]] = arr
  812. return tbl
  813. def __construct_table(self, boxes, html=False):
  814. cap = ""
  815. i = 0
  816. while i < len(boxes):
  817. if self.is_caption(boxes[i]):
  818. cap += boxes[i]["text"]
  819. boxes.pop(i)
  820. i -= 1
  821. i += 1
  822. if not boxes:
  823. return []
  824. for b in boxes:
  825. b["btype"] = self._blockType(b)
  826. max_type = Counter([b["btype"] for b in boxes]).items()
  827. max_type = max(max_type, key=lambda x: x[1])[0] if max_type else ""
  828. logging.debug("MAXTYPE: " + max_type)
  829. rowh = [b["R_bott"] - b["R_top"] for b in boxes if "R" in b]
  830. rowh = np.min(rowh) if rowh else 0
  831. # boxes = self.sort_Y_firstly(boxes, rowh/5)
  832. boxes = self.sort_R_firstly(boxes, rowh / 2)
  833. boxes[0]["rn"] = 0
  834. rows = [[boxes[0]]]
  835. btm = boxes[0]["bottom"]
  836. for b in boxes[1:]:
  837. b["rn"] = len(rows) - 1
  838. lst_r = rows[-1]
  839. if lst_r[-1].get("R", "") != b.get("R", "") \
  840. or (b["top"] >= btm - 3 and lst_r[-1].get("R", "-1") != b.get("R", "-2")
  841. ): # new row
  842. btm = b["bottom"]
  843. b["rn"] += 1
  844. rows.append([b])
  845. continue
  846. btm = (btm + b["bottom"]) / 2.
  847. rows[-1].append(b)
  848. colwm = [b["C_right"] - b["C_left"] for b in boxes if "C" in b]
  849. colwm = np.min(colwm) if colwm else 0
  850. crosspage = len(set([b["page_number"] for b in boxes])) > 1
  851. if crosspage:
  852. boxes = self.sort_X_firstly(boxes, colwm / 2, False)
  853. else:
  854. boxes = self.sort_C_firstly(boxes, colwm / 2)
  855. boxes[0]["cn"] = 0
  856. cols = [[boxes[0]]]
  857. right = boxes[0]["x1"]
  858. for b in boxes[1:]:
  859. b["cn"] = len(cols) - 1
  860. lst_c = cols[-1]
  861. if (int(b.get("C", "1")) - int(lst_c[-1].get("C", "1")) == 1 and b["page_number"] == lst_c[-1][
  862. "page_number"]) \
  863. or (b["x0"] >= right and lst_c[-1].get("C", "-1") != b.get("C", "-2")): # new col
  864. right = b["x1"]
  865. b["cn"] += 1
  866. cols.append([b])
  867. continue
  868. right = (right + b["x1"]) / 2.
  869. cols[-1].append(b)
  870. tbl = [[[] for _ in range(len(cols))] for _ in range(len(rows))]
  871. for b in boxes:
  872. tbl[b["rn"]][b["cn"]].append(b)
  873. if len(rows) >= 4:
  874. # remove single in column
  875. j = 0
  876. while j < len(tbl[0]):
  877. e, ii = 0, 0
  878. for i in range(len(tbl)):
  879. if tbl[i][j]:
  880. e += 1
  881. ii = i
  882. if e > 1:
  883. break
  884. if e > 1:
  885. j += 1
  886. continue
  887. f = (j > 0 and tbl[ii][j - 1] and tbl[ii]
  888. [j - 1][0].get("text")) or j == 0
  889. ff = (j + 1 < len(tbl[ii]) and tbl[ii][j + 1] and tbl[ii]
  890. [j + 1][0].get("text")) or j + 1 >= len(tbl[ii])
  891. if f and ff:
  892. j += 1
  893. continue
  894. bx = tbl[ii][j][0]
  895. logging.debug("Relocate column single: " + bx["text"])
  896. # j column only has one value
  897. left, right = 100000, 100000
  898. if j > 0 and not f:
  899. for i in range(len(tbl)):
  900. if tbl[i][j - 1]:
  901. left = min(left, np.min(
  902. [bx["x0"] - a["x1"] for a in tbl[i][j - 1]]))
  903. if j + 1 < len(tbl[0]) and not ff:
  904. for i in range(len(tbl)):
  905. if tbl[i][j + 1]:
  906. right = min(right, np.min(
  907. [a["x0"] - bx["x1"] for a in tbl[i][j + 1]]))
  908. assert left < 100000 or right < 100000
  909. if left < right:
  910. for jj in range(j, len(tbl[0])):
  911. for i in range(len(tbl)):
  912. for a in tbl[i][jj]:
  913. a["cn"] -= 1
  914. if tbl[ii][j - 1]:
  915. tbl[ii][j - 1].extend(tbl[ii][j])
  916. else:
  917. tbl[ii][j - 1] = tbl[ii][j]
  918. for i in range(len(tbl)):
  919. tbl[i].pop(j)
  920. else:
  921. for jj in range(j + 1, len(tbl[0])):
  922. for i in range(len(tbl)):
  923. for a in tbl[i][jj]:
  924. a["cn"] -= 1
  925. if tbl[ii][j + 1]:
  926. tbl[ii][j + 1].extend(tbl[ii][j])
  927. else:
  928. tbl[ii][j + 1] = tbl[ii][j]
  929. for i in range(len(tbl)):
  930. tbl[i].pop(j)
  931. cols.pop(j)
  932. assert len(cols) == len(tbl[0]), "Column NO. miss matched: %d vs %d" % (
  933. len(cols), len(tbl[0]))
  934. if len(cols) >= 4:
  935. # remove single in row
  936. i = 0
  937. while i < len(tbl):
  938. e, jj = 0, 0
  939. for j in range(len(tbl[i])):
  940. if tbl[i][j]:
  941. e += 1
  942. jj = j
  943. if e > 1:
  944. break
  945. if e > 1:
  946. i += 1
  947. continue
  948. f = (i > 0 and tbl[i - 1][jj] and tbl[i - 1]
  949. [jj][0].get("text")) or i == 0
  950. ff = (i + 1 < len(tbl) and tbl[i + 1][jj] and tbl[i + 1]
  951. [jj][0].get("text")) or i + 1 >= len(tbl)
  952. if f and ff:
  953. i += 1
  954. continue
  955. bx = tbl[i][jj][0]
  956. logging.debug("Relocate row single: " + bx["text"])
  957. # i row only has one value
  958. up, down = 100000, 100000
  959. if i > 0 and not f:
  960. for j in range(len(tbl[i - 1])):
  961. if tbl[i - 1][j]:
  962. up = min(up, np.min(
  963. [bx["top"] - a["bottom"] for a in tbl[i - 1][j]]))
  964. if i + 1 < len(tbl) and not ff:
  965. for j in range(len(tbl[i + 1])):
  966. if tbl[i + 1][j]:
  967. down = min(down, np.min(
  968. [a["top"] - bx["bottom"] for a in tbl[i + 1][j]]))
  969. assert up < 100000 or down < 100000
  970. if up < down:
  971. for ii in range(i, len(tbl)):
  972. for j in range(len(tbl[ii])):
  973. for a in tbl[ii][j]:
  974. a["rn"] -= 1
  975. if tbl[i - 1][jj]:
  976. tbl[i - 1][jj].extend(tbl[i][jj])
  977. else:
  978. tbl[i - 1][jj] = tbl[i][jj]
  979. tbl.pop(i)
  980. else:
  981. for ii in range(i + 1, len(tbl)):
  982. for j in range(len(tbl[ii])):
  983. for a in tbl[ii][j]:
  984. a["rn"] -= 1
  985. if tbl[i + 1][jj]:
  986. tbl[i + 1][jj].extend(tbl[i][jj])
  987. else:
  988. tbl[i + 1][jj] = tbl[i][jj]
  989. tbl.pop(i)
  990. rows.pop(i)
  991. # which rows are headers
  992. hdset = set([])
  993. for i in range(len(tbl)):
  994. cnt, h = 0, 0
  995. for j, arr in enumerate(tbl[i]):
  996. if not arr:
  997. continue
  998. cnt += 1
  999. if max_type == "Nu" and arr[0]["btype"] == "Nu":
  1000. continue
  1001. if any([a.get("H") for a in arr]) \
  1002. or (max_type == "Nu" and arr[0]["btype"] != "Nu"):
  1003. h += 1
  1004. if h / cnt > 0.5:
  1005. hdset.add(i)
  1006. if html:
  1007. return [self.__html_table(cap, hdset,
  1008. self.__cal_spans(boxes, rows,
  1009. cols, tbl, True)
  1010. )]
  1011. return self.__desc_table(cap, hdset,
  1012. self.__cal_spans(boxes, rows, cols, tbl, False))
  1013. def __html_table(self, cap, hdset, tbl):
  1014. # constrcut HTML
  1015. html = "<table>"
  1016. if cap:
  1017. html += f"<caption>{cap}</caption>"
  1018. for i in range(len(tbl)):
  1019. row = "<tr>"
  1020. txts = []
  1021. for j, arr in enumerate(tbl[i]):
  1022. if arr is None:
  1023. continue
  1024. if not arr:
  1025. row += "<td></td>" if i not in hdset else "<th></th>"
  1026. continue
  1027. txt = ""
  1028. if arr:
  1029. h = min(np.min([c["bottom"] - c["top"] for c in arr]) / 2,
  1030. self.mean_height[arr[0]["page_number"] - 1] / 2)
  1031. txt = "".join([c["text"]
  1032. for c in self.sort_Y_firstly(arr, h)])
  1033. txts.append(txt)
  1034. sp = ""
  1035. if arr[0].get("colspan"):
  1036. sp = "colspan={}".format(arr[0]["colspan"])
  1037. if arr[0].get("rowspan"):
  1038. sp += " rowspan={}".format(arr[0]["rowspan"])
  1039. if i in hdset:
  1040. row += f"<th {sp} >" + txt + "</th>"
  1041. else:
  1042. row += f"<td {sp} >" + txt + "</td>"
  1043. if i in hdset:
  1044. if all([t in hdset for t in txts]):
  1045. continue
  1046. for t in txts:
  1047. hdset.add(t)
  1048. if row != "<tr>":
  1049. row += "</tr>"
  1050. else:
  1051. row = ""
  1052. html += "\n" + row
  1053. html += "\n</table>"
  1054. return html
  1055. def __desc_table(self, cap, hdr_rowno, tbl):
  1056. # get text of every colomn in header row to become header text
  1057. clmno = len(tbl[0])
  1058. rowno = len(tbl)
  1059. headers = {}
  1060. hdrset = set()
  1061. lst_hdr = []
  1062. de = "的" if not self.is_english else " for "
  1063. for r in sorted(list(hdr_rowno)):
  1064. headers[r] = ["" for _ in range(clmno)]
  1065. for i in range(clmno):
  1066. if not tbl[r][i]:
  1067. continue
  1068. txt = "".join([a["text"].strip() for a in tbl[r][i]])
  1069. headers[r][i] = txt
  1070. hdrset.add(txt)
  1071. if all([not t for t in headers[r]]):
  1072. del headers[r]
  1073. hdr_rowno.remove(r)
  1074. continue
  1075. for j in range(clmno):
  1076. if headers[r][j]:
  1077. continue
  1078. if j >= len(lst_hdr):
  1079. break
  1080. headers[r][j] = lst_hdr[j]
  1081. lst_hdr = headers[r]
  1082. for i in range(rowno):
  1083. if i not in hdr_rowno:
  1084. continue
  1085. for j in range(i + 1, rowno):
  1086. if j not in hdr_rowno:
  1087. break
  1088. for k in range(clmno):
  1089. if not headers[j - 1][k]:
  1090. continue
  1091. if headers[j][k].find(headers[j - 1][k]) >= 0:
  1092. continue
  1093. if len(headers[j][k]) > len(headers[j - 1][k]):
  1094. headers[j][k] += (de if headers[j][k]
  1095. else "") + headers[j - 1][k]
  1096. else:
  1097. headers[j][k] = headers[j - 1][k] \
  1098. + (de if headers[j - 1][k] else "") \
  1099. + headers[j][k]
  1100. logging.debug(
  1101. f">>>>>>>>>>>>>>>>>{cap}:SIZE:{rowno}X{clmno} Header: {hdr_rowno}")
  1102. row_txt = []
  1103. for i in range(rowno):
  1104. if i in hdr_rowno:
  1105. continue
  1106. rtxt = []
  1107. def append(delimer):
  1108. nonlocal rtxt, row_txt
  1109. rtxt = delimer.join(rtxt)
  1110. if row_txt and len(row_txt[-1]) + len(rtxt) < 64:
  1111. row_txt[-1] += "\n" + rtxt
  1112. else:
  1113. row_txt.append(rtxt)
  1114. r = 0
  1115. if len(headers.items()):
  1116. _arr = [(i - r, r) for r, _ in headers.items() if r < i]
  1117. if _arr:
  1118. _, r = min(_arr, key=lambda x: x[0])
  1119. if r not in headers and clmno <= 2:
  1120. for j in range(clmno):
  1121. if not tbl[i][j]:
  1122. continue
  1123. txt = "".join([a["text"].strip() for a in tbl[i][j]])
  1124. if txt:
  1125. rtxt.append(txt)
  1126. if rtxt:
  1127. append(":")
  1128. continue
  1129. for j in range(clmno):
  1130. if not tbl[i][j]:
  1131. continue
  1132. txt = "".join([a["text"].strip() for a in tbl[i][j]])
  1133. if not txt:
  1134. continue
  1135. ctt = headers[r][j] if r in headers else ""
  1136. if ctt:
  1137. ctt += ":"
  1138. ctt += txt
  1139. if ctt:
  1140. rtxt.append(ctt)
  1141. if rtxt:
  1142. row_txt.append("; ".join(rtxt))
  1143. if cap:
  1144. if self.is_english:
  1145. from_ = " in "
  1146. else:
  1147. from_ = "来自"
  1148. row_txt = [t + f"\t——{from_}“{cap}”" for t in row_txt]
  1149. return row_txt
  1150. @staticmethod
  1151. def is_caption(bx):
  1152. patt = [
  1153. r"[图表]+[ 0-9::]{2,}"
  1154. ]
  1155. if any([re.match(p, bx["text"].strip()) for p in patt]) \
  1156. or bx["layout_type"].find("caption") >= 0:
  1157. return True
  1158. return False
  1159. def _extract_table_figure(self, need_image, ZM, return_html):
  1160. tables = {}
  1161. figures = {}
  1162. # extract figure and table boxes
  1163. i = 0
  1164. lst_lout_no = ""
  1165. nomerge_lout_no = []
  1166. while i < len(self.boxes):
  1167. if "layoutno" not in self.boxes[i]:
  1168. i += 1
  1169. continue
  1170. lout_no = str(self.boxes[i]["page_number"]) + \
  1171. "-" + str(self.boxes[i]["layoutno"])
  1172. if self.is_caption(self.boxes[i]) or self.boxes[i]["layout_type"] in ["table caption", "title",
  1173. "figure caption", "reference"]:
  1174. nomerge_lout_no.append(lst_lout_no)
  1175. if self.boxes[i]["layout_type"] == "table":
  1176. if re.match(r"(数据|资料|图表)*来源[:: ]", self.boxes[i]["text"]):
  1177. self.boxes.pop(i)
  1178. continue
  1179. if lout_no not in tables:
  1180. tables[lout_no] = []
  1181. tables[lout_no].append(self.boxes[i])
  1182. self.boxes.pop(i)
  1183. lst_lout_no = lout_no
  1184. continue
  1185. if need_image and self.boxes[i]["layout_type"] == "figure":
  1186. if re.match(r"(数据|资料|图表)*来源[:: ]", self.boxes[i]["text"]):
  1187. self.boxes.pop(i)
  1188. continue
  1189. if lout_no not in figures:
  1190. figures[lout_no] = []
  1191. figures[lout_no].append(self.boxes[i])
  1192. self.boxes.pop(i)
  1193. lst_lout_no = lout_no
  1194. continue
  1195. i += 1
  1196. # merge table on different pages
  1197. nomerge_lout_no = set(nomerge_lout_no)
  1198. tbls = sorted([(k, bxs) for k, bxs in tables.items()],
  1199. key=lambda x: (x[1][0]["top"], x[1][0]["x0"]))
  1200. i = len(tbls) - 1
  1201. while i - 1 >= 0:
  1202. k0, bxs0 = tbls[i - 1]
  1203. k, bxs = tbls[i]
  1204. i -= 1
  1205. if k0 in nomerge_lout_no:
  1206. continue
  1207. if bxs[0]["page_number"] == bxs0[0]["page_number"]:
  1208. continue
  1209. if bxs[0]["page_number"] - bxs0[0]["page_number"] > 1:
  1210. continue
  1211. mh = self.mean_height[bxs[0]["page_number"] - 1]
  1212. if self._y_dis(bxs0[-1], bxs[0]) > mh * 23:
  1213. continue
  1214. tables[k0].extend(tables[k])
  1215. del tables[k]
  1216. def x_overlapped(a, b):
  1217. return not any([a["x1"] < b["x0"], a["x0"] > b["x1"]])
  1218. # find captions and pop out
  1219. i = 0
  1220. while i < len(self.boxes):
  1221. c = self.boxes[i]
  1222. # mh = self.mean_height[c["page_number"]-1]
  1223. if not self.is_caption(c):
  1224. i += 1
  1225. continue
  1226. # find the nearest layouts
  1227. def nearest(tbls):
  1228. nonlocal c
  1229. mink = ""
  1230. minv = 1000000000
  1231. for k, bxs in tbls.items():
  1232. for b in bxs[:10]:
  1233. if b.get("layout_type", "").find("caption") >= 0:
  1234. continue
  1235. y_dis = self._y_dis(c, b)
  1236. x_dis = self._x_dis(
  1237. c, b) if not x_overlapped(
  1238. c, b) else 0
  1239. dis = y_dis * y_dis + x_dis * x_dis
  1240. if dis < minv:
  1241. mink = k
  1242. minv = dis
  1243. return mink, minv
  1244. tk, tv = nearest(tables)
  1245. fk, fv = nearest(figures)
  1246. if min(tv, fv) > 2000:
  1247. i += 1
  1248. continue
  1249. if tv < fv:
  1250. tables[tk].insert(0, c)
  1251. logging.debug(
  1252. "TABLE:" +
  1253. self.boxes[i]["text"] +
  1254. "; Cap: " +
  1255. tk)
  1256. else:
  1257. figures[fk].insert(0, c)
  1258. logging.debug(
  1259. "FIGURE:" +
  1260. self.boxes[i]["text"] +
  1261. "; Cap: " +
  1262. tk)
  1263. self.boxes.pop(i)
  1264. res = []
  1265. def cropout(bxs, ltype):
  1266. nonlocal ZM
  1267. pn = set([b["page_number"] - 1 for b in bxs])
  1268. if len(pn) < 2:
  1269. pn = list(pn)[0]
  1270. ht = self.page_cum_height[pn]
  1271. b = {
  1272. "x0": np.min([b["x0"] for b in bxs]),
  1273. "top": np.min([b["top"] for b in bxs]) - ht,
  1274. "x1": np.max([b["x1"] for b in bxs]),
  1275. "bottom": np.max([b["bottom"] for b in bxs]) - ht
  1276. }
  1277. louts = [l for l in self.page_layout[pn] if l["type"] == ltype]
  1278. ii = self.__find_overlapped(b, louts, naive=True)
  1279. if ii is not None:
  1280. b = louts[ii]
  1281. else:
  1282. logging.warn(
  1283. f"Missing layout match: {pn + 1},%s" %
  1284. (bxs[0].get(
  1285. "layoutno", "")))
  1286. left, top, right, bott = b["x0"], b["top"], b["x1"], b["bottom"]
  1287. return self.page_images[pn] \
  1288. .crop((left * ZM, top * ZM,
  1289. right * ZM, bott * ZM))
  1290. pn = {}
  1291. for b in bxs:
  1292. p = b["page_number"] - 1
  1293. if p not in pn:
  1294. pn[p] = []
  1295. pn[p].append(b)
  1296. pn = sorted(pn.items(), key=lambda x: x[0])
  1297. imgs = [cropout(arr, ltype) for p, arr in pn]
  1298. pic = Image.new("RGB",
  1299. (int(np.max([i.size[0] for i in imgs])),
  1300. int(np.sum([m.size[1] for m in imgs]))),
  1301. (245, 245, 245))
  1302. height = 0
  1303. for img in imgs:
  1304. pic.paste(img, (0, int(height)))
  1305. height += img.size[1]
  1306. return pic
  1307. # crop figure out and add caption
  1308. for k, bxs in figures.items():
  1309. txt = "\n".join(
  1310. [b["text"] for b in bxs
  1311. if not re.match(r"[0-9a-z.\+%-]", b["text"].strip())
  1312. and len(b["text"].strip()) >= 4
  1313. ]
  1314. )
  1315. if not txt:
  1316. continue
  1317. res.append(
  1318. (cropout(
  1319. bxs,
  1320. "figure"),
  1321. [txt] if not return_html else [f"<p>{txt}</p>"]))
  1322. for k, bxs in tables.items():
  1323. if not bxs:
  1324. continue
  1325. res.append((cropout(bxs, "table"),
  1326. self.__construct_table(bxs, html=return_html)))
  1327. return res
  1328. def proj_match(self, line):
  1329. if len(line) <= 2:
  1330. return
  1331. if re.match(r"[0-9 ().,%%+/-]+$", line):
  1332. return False
  1333. for p, j in [
  1334. (r"第[零一二三四五六七八九十百]+章", 1),
  1335. (r"第[零一二三四五六七八九十百]+[条节]", 2),
  1336. (r"[零一二三四五六七八九十百]+[、  ]", 3),
  1337. (r"[\((][零一二三四五六七八九十百]+[)\)]", 4),
  1338. (r"[0-9]+(、|\.[  ]|\.[^0-9])", 5),
  1339. (r"[0-9]+\.[0-9]+(、|[.  ]|[^0-9])", 6),
  1340. (r"[0-9]+\.[0-9]+\.[0-9]+(、|[  ]|[^0-9])", 7),
  1341. (r"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(、|[  ]|[^0-9])", 8),
  1342. (r".{,48}[::??]$", 9),
  1343. (r"[0-9]+)", 10),
  1344. (r"[\((][0-9]+[)\)]", 11),
  1345. (r"[零一二三四五六七八九十百]+是", 12),
  1346. (r"[⚫•➢✓]", 12)
  1347. ]:
  1348. if re.match(p, line):
  1349. return j
  1350. return
  1351. def _line_tag(self, bx, ZM):
  1352. pn = [bx["page_number"]]
  1353. top = bx["top"] - self.page_cum_height[pn[0] - 1]
  1354. bott = bx["bottom"] - self.page_cum_height[pn[0] - 1]
  1355. while bott * ZM > self.page_images[pn[-1] - 1].size[1]:
  1356. bott -= self.page_images[pn[-1] - 1].size[1] / ZM
  1357. pn.append(pn[-1] + 1)
  1358. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  1359. .format("-".join([str(p) for p in pn]),
  1360. bx["x0"], bx["x1"], top, bott)
  1361. def __filterout_scraps(self, boxes, ZM):
  1362. def width(b):
  1363. return b["x1"] - b["x0"]
  1364. def height(b):
  1365. return b["bottom"] - b["top"]
  1366. def usefull(b):
  1367. if b.get("layout_type"):
  1368. return True
  1369. if width(
  1370. b) > self.page_images[b["page_number"] - 1].size[0] / ZM / 3:
  1371. return True
  1372. if b["bottom"] - b["top"] > self.mean_height[b["page_number"] - 1]:
  1373. return True
  1374. return False
  1375. res = []
  1376. while boxes:
  1377. lines = []
  1378. widths = []
  1379. pw = self.page_images[boxes[0]["page_number"] - 1].size[0] / ZM
  1380. mh = self.mean_height[boxes[0]["page_number"] - 1]
  1381. mj = self.proj_match(
  1382. boxes[0]["text"]) or boxes[0].get(
  1383. "layout_type",
  1384. "") == "title"
  1385. def dfs(line, st):
  1386. nonlocal mh, pw, lines, widths
  1387. lines.append(line)
  1388. widths.append(width(line))
  1389. width_mean = np.mean(widths)
  1390. mmj = self.proj_match(
  1391. line["text"]) or line.get(
  1392. "layout_type",
  1393. "") == "title"
  1394. for i in range(st + 1, min(st + 20, len(boxes))):
  1395. if (boxes[i]["page_number"] - line["page_number"]) > 0:
  1396. break
  1397. if not mmj and self._y_dis(
  1398. line, boxes[i]) >= 3 * mh and height(line) < 1.5 * mh:
  1399. break
  1400. if not usefull(boxes[i]):
  1401. continue
  1402. if mmj or \
  1403. (self._x_dis(boxes[i], line) < pw / 10): \
  1404. # and abs(width(boxes[i])-width_mean)/max(width(boxes[i]),width_mean)<0.5):
  1405. # concat following
  1406. dfs(boxes[i], i)
  1407. boxes.pop(i)
  1408. break
  1409. try:
  1410. if usefull(boxes[0]):
  1411. dfs(boxes[0], 0)
  1412. else:
  1413. logging.debug("WASTE: " + boxes[0]["text"])
  1414. except Exception as e:
  1415. pass
  1416. boxes.pop(0)
  1417. mw = np.mean(widths)
  1418. if mj or mw / pw >= 0.35 or mw > 200:
  1419. res.append("\n".join([c["text"] + self._line_tag(c, ZM) for c in lines]))
  1420. else:
  1421. logging.debug("REMOVED: " +
  1422. "<<".join([c["text"] for c in lines]))
  1423. return "\n\n".join(res)
  1424. @staticmethod
  1425. def total_page_number(fnm, binary=None):
  1426. try:
  1427. pdf = pdfplumber.open(fnm) if not binary else pdfplumber.open(BytesIO(binary))
  1428. return len(pdf.pages)
  1429. except Exception as e:
  1430. pdf = fitz.open(fnm) if not binary else fitz.open(stream=fnm, filetype="pdf")
  1431. return len(pdf)
  1432. def __images__(self, fnm, zoomin=3, page_from=0, page_to=299):
  1433. self.lefted_chars = []
  1434. self.mean_height = []
  1435. self.mean_width = []
  1436. self.boxes = []
  1437. self.garbages = {}
  1438. self.page_cum_height = [0]
  1439. self.page_layout = []
  1440. try:
  1441. self.pdf = pdfplumber.open(fnm) if isinstance(fnm, str) else pdfplumber.open(BytesIO(fnm))
  1442. self.page_images = [p.to_image(resolution=72 * zoomin).annotated for i, p in
  1443. enumerate(self.pdf.pages[page_from:page_to])]
  1444. self.page_chars = [[c for c in self.pdf.pages[i].chars if self._has_color(c)] for i in
  1445. range(len(self.page_images))]
  1446. self.total_page = len(self.pdf.pages)
  1447. except Exception as e:
  1448. self.pdf = fitz.open(fnm) if isinstance(fnm, str) else fitz.open(stream=fnm, filetype="pdf")
  1449. self.page_images = []
  1450. self.page_chars = []
  1451. mat = fitz.Matrix(zoomin, zoomin)
  1452. self.total_page = len(self.pdf)
  1453. for page in self.pdf[page_from:page_to]:
  1454. pix = page.getPixmap(matrix=mat)
  1455. img = Image.frombytes("RGB", [pix.width, pix.height],
  1456. pix.samples)
  1457. self.page_images.append(img)
  1458. self.page_chars.append([])
  1459. logging.info("Images converted.")
  1460. 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))]
  1461. if sum([1 if e else 0 for e in self.is_english]) > len(self.page_images) / 2:
  1462. self.is_english = True
  1463. else:
  1464. self.is_english = False
  1465. for i, img in enumerate(self.page_images):
  1466. chars = self.page_chars[i] if not self.is_english else []
  1467. self.mean_height.append(
  1468. np.median(sorted([c["height"] for c in chars])) if chars else 0
  1469. )
  1470. self.mean_width.append(
  1471. np.median(sorted([c["width"] for c in chars])) if chars else 8
  1472. )
  1473. self.page_cum_height.append(img.size[1] / zoomin)
  1474. j = 0
  1475. while j + 1 < len(chars):
  1476. if chars[j]["text"] and chars[j + 1]["text"] \
  1477. and re.match(r"[0-9a-zA-Z,.:;!%]+", chars[j]["text"] + chars[j + 1]["text"]) \
  1478. and chars[j + 1]["x0"] - chars[j]["x1"] >= min(chars[j + 1]["width"],
  1479. chars[j]["width"]) / 2:
  1480. chars[j]["text"] += " "
  1481. j += 1
  1482. # if i > 0:
  1483. # if not chars:
  1484. # self.page_cum_height.append(img.size[1] / zoomin)
  1485. # else:
  1486. # self.page_cum_height.append(
  1487. # np.max([c["bottom"] for c in chars]))
  1488. self.__ocr_paddle(i + 1, img, chars, zoomin)
  1489. if not self.is_english and not all([c for c in self.page_chars]) and self.boxes:
  1490. self.is_english = re.search(r"[\na-zA-Z0-9,/¸;:'\[\]\(\)!@#$%^&*\"?<>._-]{30,}", "".join([b["text"] for b in random.choices(self.boxes, k=30)]))
  1491. logging.info("Is it English:", self.is_english)
  1492. self.page_cum_height = np.cumsum(self.page_cum_height)
  1493. assert len(self.page_cum_height) == len(self.page_images) + 1
  1494. def __call__(self, fnm, need_image=True, zoomin=3, return_html=False):
  1495. self.__images__(fnm, zoomin)
  1496. self._layouts_paddle(zoomin)
  1497. self._table_transformer_job(zoomin)
  1498. self._text_merge()
  1499. self._concat_downward()
  1500. self._filter_forpages()
  1501. tbls = self._extract_table_figure(need_image, zoomin, return_html)
  1502. return self.__filterout_scraps(deepcopy(self.boxes), zoomin), tbls
  1503. def remove_tag(self, txt):
  1504. return re.sub(r"@@[\t0-9.-]+?##", "", txt)
  1505. def crop(self, text, ZM=3):
  1506. imgs = []
  1507. for tag in re.findall(r"@@[0-9-]+\t[0-9.\t]+##", text):
  1508. pn, left, right, top, bottom = tag.strip(
  1509. "#").strip("@").split("\t")
  1510. left, right, top, bottom = float(left), float(
  1511. right), float(top), float(bottom)
  1512. bottom *= ZM
  1513. pns = [int(p) - 1 for p in pn.split("-")]
  1514. for pn in pns[1:]:
  1515. bottom += self.page_images[pn - 1].size[1]
  1516. imgs.append(
  1517. self.page_images[pns[0]].crop((left * ZM, top * ZM,
  1518. right *
  1519. ZM, min(
  1520. bottom, self.page_images[pns[0]].size[1])
  1521. ))
  1522. )
  1523. bottom -= self.page_images[pns[0]].size[1]
  1524. for pn in pns[1:]:
  1525. imgs.append(
  1526. self.page_images[pn].crop((left * ZM, 0,
  1527. right * ZM,
  1528. min(bottom,
  1529. self.page_images[pn].size[1])
  1530. ))
  1531. )
  1532. bottom -= self.page_images[pn].size[1]
  1533. if not imgs:
  1534. return
  1535. GAP = 2
  1536. height = 0
  1537. for img in imgs:
  1538. height += img.size[1] + GAP
  1539. height = int(height)
  1540. pic = Image.new("RGB",
  1541. (int(np.max([i.size[0] for i in imgs])), height),
  1542. (245, 245, 245))
  1543. height = 0
  1544. for img in imgs:
  1545. pic.paste(img, (0, int(height)))
  1546. height += img.size[1] + GAP
  1547. return pic
  1548. if __name__ == "__main__":
  1549. pass