utils.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. import hashlib
  2. import inspect
  3. import json
  4. import os
  5. import socket
  6. import subprocess
  7. import sys
  8. from io import BytesIO
  9. from subprocess import Popen
  10. import requests
  11. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  12. import difflib
  13. import logging
  14. import mimetypes
  15. import platform
  16. import re
  17. import traceback
  18. import filetype
  19. from bs4 import BeautifulSoup
  20. import yaml
  21. from pdfminer.layout import *
  22. from format_convert import _global
  23. from functools import wraps
  24. import psutil
  25. import time
  26. from format_convert.judge_platform import get_platform
  27. if get_platform() == "Linux":
  28. import resource
  29. def judge_error_code(_list, code=[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]):
  30. """
  31. [0] : continue
  32. [-1]: 逻辑处理错误
  33. [-2]: 接口调用错误
  34. [-3]: 文件格式错误,无法打开
  35. [-4]: 各类文件调用第三方包读取超时
  36. [-5]: 整个转换过程超时
  37. [-6]: 阿里云UDF队列超时
  38. [-7]: 文件需密码,无法打开
  39. [-8]: 调用现成接口报错
  40. [-9]: 接口接收数据为空
  41. """
  42. for c in code:
  43. if _list == [c]:
  44. return True
  45. return False
  46. def add_div(text):
  47. if text == "" or text is None:
  48. return text
  49. # if get_platform() == "Windows":
  50. # print("add_div", text)
  51. if re.findall("<div>", text):
  52. return text
  53. text = "<div>" + text + "\n"
  54. text = re.sub("\n", "</div>\n<div>", text)
  55. # text += "</div>"
  56. if text[-5:] == "<div>":
  57. # print("add_div has cut", text[-30:])
  58. text = text[:-5]
  59. return text
  60. def get_platform():
  61. sys = platform.system()
  62. return sys
  63. def get_html_p(html_path):
  64. log("into get_html_p")
  65. try:
  66. with open(html_path, "r") as ff:
  67. html_str = ff.read()
  68. soup = BeautifulSoup(html_str, 'lxml')
  69. text = ""
  70. for p in soup.find_all("p"):
  71. p_text = p.text
  72. p_text = p_text.strip()
  73. if p.string != "":
  74. text += p_text
  75. text += "\n"
  76. return text
  77. except Exception as e:
  78. log("get_html_p error!")
  79. return [-1]
  80. def string_similarity(str1, str2):
  81. # 去掉<div>和回车
  82. str1 = re.sub("<div>", "", str1)
  83. str1 = re.sub("</div>", "", str1)
  84. str1 = re.sub("\n", "", str1)
  85. str2 = re.sub("<div>", "", str2)
  86. str2 = re.sub("</div>", "", str2)
  87. str2 = re.sub("\n", "", str2)
  88. # print("********************************")
  89. # print("str1", str1)
  90. # print("********************************")
  91. # print("str2", str2)
  92. # print("********************************")
  93. score = difflib.SequenceMatcher(None, str1, str2).ratio()
  94. print("string_similarity", score)
  95. return score
  96. def get_sequential_data(text_list, bbox_list, html=False):
  97. logging.info("into get_sequential_data")
  98. try:
  99. text = ""
  100. order_list = []
  101. for i in range(len(text_list)):
  102. length_start = bbox_list[i][0][0]
  103. length_end = bbox_list[i][1][0]
  104. height_start = bbox_list[i][0][1]
  105. height_end = bbox_list[i][-1][1]
  106. # print([length_start, length_end, height_start, height_end])
  107. order_list.append([text_list[i], length_start, length_end, height_start, height_end])
  108. # text = text + infomation['text'] + "\n"
  109. if get_platform() == "Windows":
  110. print("get_sequential_data", order_list)
  111. if not order_list:
  112. if get_platform() == "Windows":
  113. print("get_sequential_data", "no order list")
  114. return ""
  115. # 根据bbox的坐标对输出排序
  116. order_list.sort(key=lambda x: (x[3], x[1], x[0]))
  117. # 根据bbox分行分列
  118. # col_list = []
  119. # height_end = int((order_list[0][4] + order_list[0][3]) / 2)
  120. # for i in range(len(order_list)):
  121. # if height_end - threshold <= order_list[i][3] <= height_end + threshold:
  122. # col_list.append(order_list[i])
  123. # else:
  124. # row_list.append(col_list)
  125. # col_list = []
  126. # height_end = int((order_list[i][4] + order_list[i][3]) / 2)
  127. # col_list.append(order_list[i])
  128. # if i == len(order_list) - 1:
  129. # row_list.append(col_list)
  130. row_list = []
  131. used_box = []
  132. threshold = 5
  133. for box in order_list:
  134. if box in used_box:
  135. continue
  136. height_center = (box[4] + box[3]) / 2
  137. row = []
  138. for box2 in order_list:
  139. if box2 in used_box:
  140. continue
  141. height_center2 = (box2[4] + box2[3]) / 2
  142. if height_center - threshold <= height_center2 <= height_center + threshold:
  143. if box2 not in row:
  144. row.append(box2)
  145. used_box.append(box2)
  146. row.sort(key=lambda x: x[0])
  147. row_list.append(row)
  148. for row in row_list:
  149. if not row:
  150. continue
  151. if len(row) <= 1:
  152. text = text + row[0][0] + "\n"
  153. else:
  154. sub_text = ""
  155. row.sort(key=lambda x: x[1])
  156. for col in row:
  157. sub_text = sub_text + col[0] + " "
  158. sub_text = sub_text + "\n"
  159. text += sub_text
  160. if html:
  161. text = "<div>" + text
  162. text = re.sub("\n", "</div>\n<div>", text)
  163. text += "</div>"
  164. # if text[-5:] == "<div>":
  165. # text = text[:-5]
  166. return text
  167. except Exception as e:
  168. logging.info("get_sequential_data error!")
  169. print("get_sequential_data", traceback.print_exc())
  170. return [-1]
  171. # def get_formatted_table(text_list, text_bbox_list, table_bbox_list, split_line):
  172. # logging.info("into get_formatted_table")
  173. # try:
  174. # # 重新定义text_bbox_list,[point, point, text]
  175. # text_bbox_list = [[text_bbox_list[i][0], text_bbox_list[i][2], text_list[i]] for i in
  176. # range(len(text_bbox_list))]
  177. # # 按纵坐标排序
  178. # text_bbox_list.sort(key=lambda x: (x[0][1], x[0][0]))
  179. # table_bbox_list.sort(key=lambda x: (x[0][1], x[0][0]))
  180. #
  181. # # print("text_bbox_list", text_bbox_list)
  182. # # print("table_bbox_list", table_bbox_list)
  183. #
  184. # # bbox位置 threshold
  185. # threshold = 5
  186. #
  187. # # 根据split_line分区,可能有个区多个表格 [(), ()]
  188. # area_text_bbox_list = []
  189. # area_table_bbox_list = []
  190. # # print("get_formatted_table, split_line", split_line)
  191. # for j in range(1, len(split_line)):
  192. # last_y = split_line[j - 1][0][1]
  193. # current_y = split_line[j][0][1]
  194. # temp_text_bbox_list = []
  195. # temp_table_bbox_list = []
  196. #
  197. # # 找出该区域下text bbox
  198. # for text_bbox in text_bbox_list:
  199. # # 计算 text bbox 中心点
  200. # text_bbox_center = ((text_bbox[1][0] + text_bbox[0][0]) / 2,
  201. # (text_bbox[1][1] + text_bbox[0][1]) / 2)
  202. # if last_y - threshold <= text_bbox_center[1] <= current_y + threshold:
  203. # temp_text_bbox_list.append(text_bbox)
  204. # area_text_bbox_list.append(temp_text_bbox_list)
  205. #
  206. # # 找出该区域下table bbox
  207. # for table_bbox in table_bbox_list:
  208. # # 计算 table bbox 中心点
  209. # table_bbox_center = ((table_bbox[1][0] + table_bbox[0][0]) / 2,
  210. # (table_bbox[1][1] + table_bbox[0][1]) / 2)
  211. # if last_y < table_bbox_center[1] < current_y:
  212. # temp_table_bbox_list.append(table_bbox)
  213. # area_table_bbox_list.append(temp_table_bbox_list)
  214. #
  215. # # for j in range(len(area_text_bbox_list)):
  216. # # print("area_text_bbox_list", j, area_text_bbox_list[j])
  217. #
  218. # # 对每个区域分别进行两个bbox匹配,生成表格
  219. # area_text_list = []
  220. # area_column_list = []
  221. # for j in range(len(area_text_bbox_list)):
  222. # # 每个区域的table bbox 和text bbox
  223. # temp_table_bbox_list = area_table_bbox_list[j]
  224. # temp_text_bbox_list = area_text_bbox_list[j]
  225. #
  226. # # 判断该区域有无表格bbox
  227. # # 若无表格,将该区域文字连接
  228. # if not temp_table_bbox_list:
  229. # # 找出该区域的所有text bbox
  230. # only_text_list = []
  231. # only_bbox_list = []
  232. # for text_bbox in temp_text_bbox_list:
  233. # only_text_list.append(text_bbox[2])
  234. # only_bbox_list.append([text_bbox[0], text_bbox[1]])
  235. # only_text = get_sequential_data(only_text_list, only_bbox_list, True)
  236. # if only_text == [-1]:
  237. # return [-1], [-1]
  238. # area_text_list.append(only_text)
  239. # area_column_list.append(0)
  240. # continue
  241. #
  242. # # 有表格
  243. # # 文本对应的表格格子
  244. # text_in_table = {}
  245. # for i in range(len(temp_text_bbox_list)):
  246. # text_bbox = temp_text_bbox_list[i]
  247. #
  248. # # 计算 text bbox 中心点
  249. # text_bbox_center = ((text_bbox[1][0] + text_bbox[0][0]) / 2,
  250. # (text_bbox[1][1] + text_bbox[0][1]) / 2)
  251. #
  252. # # 判断中心点在哪个table bbox中
  253. # for table_bbox in temp_table_bbox_list:
  254. # # 中心点在table bbox中,将text写入字典
  255. # if table_bbox[0][0] <= text_bbox_center[0] <= table_bbox[1][0] and \
  256. # table_bbox[0][1] <= text_bbox_center[1] <= table_bbox[1][1]:
  257. # if str(table_bbox) in text_in_table.keys():
  258. # text_in_table[str(table_bbox)] = text_in_table.get(str(table_bbox)) + text_bbox[2]
  259. # else:
  260. # text_in_table[str(table_bbox)] = text_bbox[2]
  261. # break
  262. #
  263. # # 如果未找到text bbox匹配的table bbox,加大threshold匹配
  264. # # elif (table_bbox[0][0] <= text_bbox_center[0]+threshold <= table_bbox[1][0] and
  265. # # table_bbox[0][1] <= text_bbox_center[1]+threshold <= table_bbox[1][1]) or \
  266. # # (table_bbox[0][0] <= text_bbox_center[0]-threshold <= table_bbox[1][0] and
  267. # # table_bbox[0][1] <= text_bbox_center[1]-threshold <= table_bbox[1][1]) or \
  268. # # (table_bbox[0][0] <= text_bbox_center[0]+threshold <= table_bbox[1][0] and
  269. # # table_bbox[0][1] <= text_bbox_center[1]-threshold <= table_bbox[1][1]) or \
  270. # # (table_bbox[0][0] <= text_bbox_center[0]-threshold <= table_bbox[1][0] and
  271. # # table_bbox[0][1] <= text_bbox_center[1]+threshold <= table_bbox[1][1]):
  272. # # if str(table_bbox) in text_in_table.keys():
  273. # # text_in_table[str(table_bbox)] = text_in_table.get(str(table_bbox)) + text_bbox[2]
  274. # # else:
  275. # # text_in_table[str(table_bbox)] = text_bbox[2]
  276. # # break
  277. #
  278. # # 对表格格子进行分行分列,并计算总计多少小列
  279. # # 放入坐标
  280. # all_col_list = []
  281. # all_row_list = []
  282. # for i in range(len(temp_table_bbox_list)):
  283. # table_bbox = temp_table_bbox_list[i]
  284. #
  285. # # 放入所有坐标x
  286. # if table_bbox[0][0] not in all_col_list:
  287. # all_col_list.append(table_bbox[0][0])
  288. # if table_bbox[1][0] not in all_col_list:
  289. # all_col_list.append(table_bbox[1][0])
  290. #
  291. # # 放入所有坐标y
  292. # if table_bbox[0][1] not in all_row_list:
  293. # all_row_list.append(table_bbox[0][1])
  294. # if table_bbox[1][1] not in all_row_list:
  295. # all_row_list.append(table_bbox[1][1])
  296. # all_col_list.sort(key=lambda x: x)
  297. # all_row_list.sort(key=lambda x: x)
  298. #
  299. # # 分行
  300. # row_list = []
  301. # rows = []
  302. # temp_table_bbox_list.sort(key=lambda x: (x[0][1], x[0][0], x[1][1], x[1][0]))
  303. # y_row = temp_table_bbox_list[0][0][1]
  304. # for i in range(len(temp_table_bbox_list)):
  305. # table_bbox = temp_table_bbox_list[i]
  306. #
  307. # if y_row - threshold <= table_bbox[0][1] <= y_row + threshold:
  308. # rows.append(table_bbox)
  309. # else:
  310. # y_row = table_bbox[0][1]
  311. # if rows:
  312. # rows.sort(key=lambda x: x[0][0])
  313. # row_list.append(rows)
  314. # rows = []
  315. # rows.append(table_bbox)
  316. # # print("*" * 30)
  317. # # print(row_list)
  318. #
  319. # if i == len(temp_table_bbox_list) - 1:
  320. # if rows:
  321. # rows.sort(key=lambda x: x[0][0])
  322. # row_list.append(rows)
  323. #
  324. # # 生成表格,包括文字和格子宽度
  325. # area_column = []
  326. # text = '<table border="1">' + "\n"
  327. # for row in row_list:
  328. # text += "<tr>" + "\n"
  329. # for col in row:
  330. # # 计算bbox y坐标之间有多少其他点,+1即为所占行数
  331. # row_span = 1
  332. # for y in all_row_list:
  333. # if col[0][1] < y < col[1][1]:
  334. # if y - col[0][1] >= 2 and col[1][1] - y >= 2:
  335. # row_span += 1
  336. #
  337. # # 计算bbox x坐标之间有多少其他点,+1即为所占列数
  338. # col_span = 1
  339. # for x in all_col_list:
  340. # if col[0][0] < x < col[1][0]:
  341. # if x - col[0][0] >= 2 and col[1][0] - x >= 2:
  342. # col_span += 1
  343. #
  344. # text += "<td colspan=" + str(col_span) + " rowspan=" + str(row_span) + ">"
  345. #
  346. # if str(col) in text_in_table.keys():
  347. # text += text_in_table.get(str(col))
  348. # else:
  349. # text += ""
  350. # text += "</td>" + "\n"
  351. # text += "</tr>" + "\n"
  352. # text += "</table>" + "\n"
  353. #
  354. # # 计算最大column
  355. # max_col_num = 0
  356. # for row in row_list:
  357. # col_num = 0
  358. # for col in row:
  359. # col_num += 1
  360. # if max_col_num < col_num:
  361. # max_col_num = col_num
  362. #
  363. # area_text_list.append(text)
  364. # area_column_list.append(max_col_num)
  365. #
  366. # text = ""
  367. # if get_platform() == "Windows":
  368. # print("get_formatted_table area_text_list", area_text_list)
  369. # for area_text in area_text_list:
  370. # text += area_text
  371. # return text, area_column_list
  372. # except Exception as e:
  373. # logging.info("get_formatted_table error!")
  374. # print("get_formatted_table", traceback.print_exc())
  375. # return [-1], [-1]
  376. def rename_inner_files(root_path):
  377. try:
  378. logging.info("into rename_inner_files")
  379. # 获取解压文件夹下所有文件+文件夹,不带根路径
  380. path_list = []
  381. for root, dirs, files in os.walk(root_path, topdown=False):
  382. for name in dirs:
  383. p = os.path.join(root, name) + os.sep
  384. if get_platform() == "Windows":
  385. root_path = slash_replace(root_path)
  386. p = slash_replace(p)
  387. p = re.sub(root_path, "", p)
  388. root_path = slash_replace(root_path, True)
  389. p = slash_replace(p, True)
  390. else:
  391. p = re.sub(root_path, "", p)
  392. path_list.append(p)
  393. for name in files:
  394. p = os.path.join(root, name)
  395. if get_platform() == "Windows":
  396. root_path = slash_replace(root_path)
  397. p = slash_replace(p)
  398. p = re.sub(root_path, "", p)
  399. root_path = slash_replace(root_path, True)
  400. p = slash_replace(p, True)
  401. else:
  402. p = re.sub(root_path, "", p)
  403. path_list.append(p)
  404. # 按路径长度排序
  405. path_list.sort(key=lambda x: len(x), reverse=True)
  406. # 循环改名
  407. for old_path in path_list:
  408. # 按路径分隔符分割
  409. ss = old_path.split(os.sep)
  410. # 判断是否文件夹
  411. is_dir = 0
  412. file_type = ""
  413. if os.path.isdir(root_path + old_path):
  414. ss = ss[:-1]
  415. is_dir = 1
  416. else:
  417. if "." in old_path:
  418. file_type = "." + old_path.split(".")[-1]
  419. else:
  420. file_type = ""
  421. # 最后一级需要用hash改名
  422. new_path = ""
  423. # new_path = re.sub(ss[-1], str(hash(ss[-1])), old_path) + file_type
  424. current_level = 0
  425. for s in ss:
  426. # 路径拼接
  427. if current_level < len(ss) - 1:
  428. new_path += s + os.sep
  429. else:
  430. new_path += str(hash(s)) + file_type
  431. current_level += 1
  432. new_ab_path = root_path + new_path
  433. old_ab_path = root_path + old_path
  434. os.rename(old_ab_path, new_ab_path)
  435. # 重新获取解压文件夹下所有文件+文件夹
  436. new_path_list = []
  437. for root, dirs, files in os.walk(root_path, topdown=False):
  438. for name in dirs:
  439. new_path_list.append(os.path.join(root, name) + os.sep)
  440. for name in files:
  441. new_path_list.append(os.path.join(root, name))
  442. return new_path_list
  443. except:
  444. traceback.print_exc()
  445. return [-1]
  446. def judge_format(path):
  447. guess1 = mimetypes.guess_type(path)
  448. _type = None
  449. if guess1[0]:
  450. _type = guess1[0]
  451. else:
  452. guess2 = filetype.guess(path)
  453. if guess2:
  454. _type = guess2.mime
  455. if _type == "application/pdf":
  456. return "pdf"
  457. if _type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
  458. return "docx"
  459. if _type == "application/x-zip-compressed" or _type == "application/zip":
  460. return "zip"
  461. if _type == "application/x-rar-compressed" or _type == "application/rar":
  462. return "rar"
  463. if _type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
  464. return "xlsx"
  465. if _type == "application/msword":
  466. return "doc"
  467. if _type == "image/png":
  468. return "png"
  469. if _type == "image/jpeg":
  470. return "jpg"
  471. # 猜不到,返回None
  472. return None
  473. def slash_replace(_str, reverse=False):
  474. if reverse:
  475. _str = eval(repr(_str).replace('/', '\\\\'))
  476. else:
  477. _str = eval(repr(_str).replace('\\\\', '/'))
  478. return _str
  479. class LineTable:
  480. def recognize_table(self,list_textbox, list_line,sourceP_LB=True):
  481. self.list_line = list_line
  482. self.list_crosspoints = self.recognize_crosspoints(list_line)
  483. # 聚类
  484. cluster_crosspoints = []
  485. for _point in self.list_crosspoints:
  486. cluster_crosspoints.append({"lines": _point.get("lines"), "points": [_point]})
  487. while 1:
  488. _find = False
  489. new_cluster_crosspoints = []
  490. for l_point in cluster_crosspoints:
  491. _flag = False
  492. for l_n_point in new_cluster_crosspoints:
  493. line1 = l_point.get("lines")
  494. line2 = l_n_point.get("lines")
  495. if len(line1&line2) > 0:
  496. _find = True
  497. _flag = True
  498. l_n_point["lines"] = line1.union(line2)
  499. l_n_point["points"].extend(l_point["points"])
  500. if not _flag:
  501. new_cluster_crosspoints.append({"lines":l_point.get("lines"),"points":l_point.get("points")})
  502. cluster_crosspoints = new_cluster_crosspoints
  503. if not _find:
  504. break
  505. list_l_rect = []
  506. for table_crosspoint in cluster_crosspoints:
  507. list_rect = self.crosspoint2rect(table_crosspoint.get("points"))
  508. list_l_rect.append(list_rect)
  509. in_objs = set()
  510. list_tables = []
  511. for l_rect in list_l_rect:
  512. _ta = self.rect2table(list_textbox,l_rect,in_objs,sourceP_LB=sourceP_LB)
  513. if _ta:
  514. list_tables.append(_ta)
  515. # self._plot(list_line, list_textbox)
  516. return list_tables, in_objs, list_l_rect
  517. def recognize_table_by_rect(self, list_textbox, list_rect, margin=2):
  518. dump_margin = 5
  519. list_rect_tmp = []
  520. # 去重
  521. for _rect in list_rect:
  522. if (_rect.bbox[3]-_rect.bbox[1] < 10) or (abs(_rect.bbox[2]-_rect.bbox[0]) < 5):
  523. continue
  524. _find = False
  525. for _tmp in list_rect_tmp:
  526. for i in range(4):
  527. if abs(_rect.bbox[i]-_tmp.bbox[i]) < dump_margin:
  528. pass
  529. else:
  530. _find = False
  531. break
  532. if i == 3:
  533. _find = True
  534. if _find:
  535. break
  536. if not _find:
  537. list_rect_tmp.append(_rect)
  538. # print("=====",len(list_rect),len(list_rect_tmp))
  539. # print(list_rect_tmp)
  540. # from matplotlib import pyplot as plt
  541. # plt.figure()
  542. # for _rect in list_rect_tmp:
  543. # x0,y0,x1,y1 = _rect.bbox
  544. # plt.boxplot(_rect.bbox)
  545. # plt.show()
  546. cluster_rect = []
  547. for _rect in list_rect:
  548. _find = False
  549. for cr in cluster_rect:
  550. for cr_rect in cr:
  551. if abs((cr_rect.bbox[2]-cr_rect.bbox[0]+_rect.bbox[2]-_rect.bbox[0])-(max(cr_rect.bbox[2],_rect.bbox[2])-min(cr_rect.bbox[0],_rect.bbox[0])))<margin:
  552. _find = True
  553. cr.append(_rect)
  554. break
  555. elif abs((cr_rect.bbox[3]-cr_rect.bbox[1]+_rect.bbox[3]-_rect.bbox[1])-(max(cr_rect.bbox[3],_rect.bbox[3])-min(cr_rect.bbox[1],_rect.bbox[1])))<margin:
  556. _find = True
  557. cr.append(_rect)
  558. break
  559. if _find:
  560. break
  561. if not _find:
  562. cluster_rect.append([_rect])
  563. list_l_rect = cluster_rect
  564. in_objs = set()
  565. list_tables = []
  566. for l_rect in list_l_rect:
  567. _ta = self.rect2table(list_textbox,l_rect,in_objs)
  568. if _ta:
  569. list_tables.append(_ta)
  570. return list_tables,in_objs,list_l_rect
  571. def recognize_crosspoints(self, list_line,fixLine=True):
  572. list_crosspoints = []
  573. # print("lines num",len(list_line))
  574. def getMaxPoints(list_x,margin=5,reverse=False):
  575. clust_x = []
  576. for _x in list_x:
  577. _find = False
  578. for cx in clust_x:
  579. if abs(cx[0]-_x)<margin:
  580. _find = True
  581. cx.append(_x)
  582. break
  583. if not _find:
  584. clust_x.append([_x])
  585. clust_x.sort(key=lambda x:x,reverse=reverse)
  586. return clust_x[0][0],len(clust_x[0])
  587. for _i in range(len(list_line)):
  588. for _j in range(len(list_line)):
  589. line1 = list_line[_i].__dict__.get("bbox")
  590. line2 = list_line[_j].__dict__.get("bbox")
  591. exists,point = self.cross_point(line1,line2)
  592. if exists:
  593. list_crosspoints.append(point)
  594. if fixLine:
  595. #聚类
  596. cluster_crosspoints = []
  597. for _point in list_crosspoints:
  598. cluster_crosspoints.append({"lines":_point.get("lines"),"points":[_point]})
  599. while 1:
  600. _find = False
  601. new_cluster_crosspoints = []
  602. for l_point in cluster_crosspoints:
  603. _flag = False
  604. for l_n_point in new_cluster_crosspoints:
  605. line1 = l_point.get("lines")
  606. line2 = l_n_point.get("lines")
  607. if len(line1&line2)>0:
  608. _find = True
  609. _flag = True
  610. l_n_point["lines"] = line1.union(line2)
  611. l_n_point["points"].extend(l_point["points"])
  612. if not _flag:
  613. new_cluster_crosspoints.append({"lines":l_point.get("lines"),"points":l_point.get("points")})
  614. cluster_crosspoints = new_cluster_crosspoints
  615. if not _find:
  616. break
  617. list_crosspoints = []
  618. for list_cp in cluster_crosspoints:
  619. points = list_cp.get("points")
  620. l_lines = []
  621. for p in points:
  622. l_lines.extend(p.get("p_lines"))
  623. l_lines = list(set(l_lines))
  624. l_lines.sort(key=lambda x:x[0])
  625. min_x,_count = getMaxPoints([l[0] for l in l_lines],reverse=False)
  626. if _count<=2:
  627. min_x = None
  628. min_y,_count = getMaxPoints([l[1] for l in l_lines],reverse=False)
  629. if _count<2:
  630. min_y = None
  631. max_x,_count = getMaxPoints([l[2] for l in l_lines],reverse=True)
  632. if _count<=2:
  633. max_x = None
  634. max_y,_count = getMaxPoints([l[3] for l in l_lines],reverse=True)
  635. if _count<=2:
  636. max_y = None
  637. if min_x and min_y and max_x and max_y:
  638. points.sort(key=lambda x:x["point"][0])
  639. if abs(min_x-points[0]["point"][0])>30:
  640. _line = LTLine(1,(min_x,min_y),(min_x,max_y))
  641. list_line.append(_line)
  642. l_lines.append(_line.bbox)
  643. # print("add=====",_line.bbox)
  644. if abs(max_x-points[-1]["point"][0])>30:
  645. _line = LTLine(1,(max_x,min_y),(max_x,max_y))
  646. list_line.append(_line)
  647. l_lines.append(_line.bbox)
  648. # print("add=====1",_line.bbox)
  649. points.sort(key=lambda x:x["point"][1])
  650. if abs(min_y-points[0]["point"][1])>30:
  651. _line = LTLine(1,(min_x,min_y),(max_x,min_y))
  652. list_line.append(_line)
  653. l_lines.append(_line.bbox)
  654. # print("add=====2",_line.bbox)
  655. if abs(max_y-points[-1]["point"][1])>30:
  656. _line = LTLine(1,(min_x,max_y),(max_x,max_y))
  657. list_line.append(_line)
  658. l_lines.append(_line.bbox)
  659. # print("add=====2",_line.bbox)
  660. for _i in range(len(l_lines)):
  661. for _j in range(len(l_lines)):
  662. line1 = l_lines[_i]
  663. line2 = l_lines[_j]
  664. exists,point = self.cross_point(line1,line2)
  665. if exists:
  666. list_crosspoints.append(point)
  667. # from matplotlib import pyplot as plt
  668. # plt.figure()
  669. # for _line in l_lines:
  670. # x0,y0,x1,y1 = _line
  671. # plt.plot([x0,x1],[y0,y1])
  672. # for point in list_crosspoints:
  673. # plt.scatter(point.get("point")[0],point.get("point")[1])
  674. # plt.show()
  675. # print(list_crosspoints)
  676. # print("points num",len(list_crosspoints))
  677. return list_crosspoints
  678. def recognize_rect(self, _page):
  679. list_line = []
  680. for _obj in _page._objs:
  681. if isinstance(_obj, (LTLine)):
  682. list_line.append(_obj)
  683. list_crosspoints = self.recognize_crosspoints(list_line)
  684. #聚类
  685. cluster_crosspoints = []
  686. for _point in list_crosspoints:
  687. cluster_crosspoints.append({"lines":_point.get("lines"),"points":[_point]})
  688. while 1:
  689. _find = False
  690. new_cluster_crosspoints = []
  691. for l_point in cluster_crosspoints:
  692. _flag = False
  693. for l_n_point in new_cluster_crosspoints:
  694. line1 = l_point.get("lines")
  695. line2 = l_n_point.get("lines")
  696. if len(line1&line2)>0:
  697. _find = True
  698. _flag = True
  699. l_n_point["lines"] = line1.union(line2)
  700. l_n_point["points"].extend(l_point["points"])
  701. if not _flag:
  702. new_cluster_crosspoints.append({"lines":l_point.get("lines"),"points":l_point.get("points")})
  703. cluster_crosspoints = new_cluster_crosspoints
  704. if not _find:
  705. break
  706. # print(len(cluster_crosspoints))
  707. list_l_rect = []
  708. for table_crosspoint in cluster_crosspoints:
  709. list_rect = self.crosspoint2rect(table_crosspoint.get("points"))
  710. list_l_rect.append(list_rect)
  711. return list_l_rect
  712. def crosspoint2rect(self, list_crosspoint, margin=5):
  713. dict_line_points = {}
  714. for _point in list_crosspoint:
  715. lines = list(_point.get("lines"))
  716. for _line in lines:
  717. if _line not in dict_line_points:
  718. dict_line_points[_line] = {"direct":None,"points":[]}
  719. dict_line_points[_line]["points"].append(_point)
  720. # 排序
  721. for k, v in dict_line_points.items():
  722. list_x = []
  723. list_y = []
  724. for _p in v["points"]:
  725. list_x.append(_p.get("point")[0])
  726. list_y.append(_p.get("point")[1])
  727. if max(list_x)-min(list_x)>max(list_y)-min(list_y):
  728. v.get("points").sort(key=lambda x:x.get("point")[0])
  729. v["direct"] = "row"
  730. else:
  731. v.get("points").sort(key=lambda x:x.get("point")[1])
  732. v["direct"] = "column"
  733. list_rect = []
  734. for _point in list_crosspoint:
  735. if _point["buttom"]>=margin and _point["right"]>=margin:
  736. lines = list(_point.get("lines"))
  737. _line = lines[0]
  738. if dict_line_points[_line]["direct"]=="column":
  739. _line = lines[1]
  740. next_point = None
  741. for p1 in dict_line_points[_line]["points"]:
  742. if p1["buttom"]>=margin and p1["point"][0]>_point["point"][0]:
  743. next_point = p1
  744. break
  745. if not next_point:
  746. continue
  747. lines = list(next_point.get("lines"))
  748. _line = lines[0]
  749. if dict_line_points[_line]["direct"]=="row":
  750. _line = lines[1]
  751. final_point = None
  752. for p1 in dict_line_points[_line]["points"]:
  753. if p1["left"]>=margin and p1["point"][1]>next_point["point"][1]:
  754. final_point = p1
  755. break
  756. if not final_point:
  757. continue
  758. _r = LTRect(1,(_point["point"][0],_point["point"][1],final_point["point"][0],final_point["point"][1]))
  759. list_rect.append(_r)
  760. tmp_rect = []
  761. set_bbox = set()
  762. for _r in list_rect:
  763. _bbox = "%.2f-%.2f-%.2f-%.2f"%_r.bbox
  764. width = _r.bbox[2]-_r.bbox[0]
  765. height = _r.bbox[3]-_r.bbox[1]
  766. if width<=margin or height<=margin:
  767. continue
  768. if _bbox not in set_bbox:
  769. tmp_rect.append(_r)
  770. set_bbox.add(_bbox)
  771. list_rect = tmp_rect
  772. # import cv2
  773. # import numpy as np
  774. # import random
  775. # img = np.zeros(shape=(1000,1000),dtype=np.uint8)
  776. # img += 255
  777. #
  778. # color = []
  779. # for rect in list_rect:
  780. # color += 10
  781. # x0,y0,x1,y1 = rect.bbox
  782. # x0 *= 10/18
  783. # y0 *= 10/18
  784. # x1 *= 10/18
  785. # y1 *= 10/18
  786. # print(rect.bbox)
  787. # cv2.rectangle(img, (int(x0),int(y0)),(int(x1),int(y1)), (color%255, (color+10)%255, (color+20)%255), 3)
  788. # cv2.imshow("bbox", img)
  789. # cv2.waitKey(0)
  790. return list_rect
  791. def cross_point(self, line1, line2, segment=True, margin=2):
  792. point_is_exist = False
  793. x = y = 0
  794. x1, y1, x2, y2 = line1
  795. x3, y3, x4, y4 = line2
  796. if (x2 - x1) == 0:
  797. k1 = None
  798. b1 = 0
  799. else:
  800. k1 = (y2 - y1) * 1.0 / (x2 - x1) # 计算k1,由于点均为整数,需要进行浮点数转化
  801. b1 = y1 * 1.0 - x1 * k1 * 1.0 # 整型转浮点型是关键
  802. if (x4 - x3) == 0: # L2直线斜率不存在
  803. k2 = None
  804. b2 = 0
  805. else:
  806. k2 = (y4 - y3) * 1.0 / (x4 - x3) # 斜率存在
  807. b2 = y3 * 1.0 - x3 * k2 * 1.0
  808. if k1 is None:
  809. if not k2 is None:
  810. x = x1
  811. y = k2 * x1 + b2
  812. point_is_exist = True
  813. elif k2 is None:
  814. x = x3
  815. y = k1 * x3 + b1
  816. elif not k2 == k1:
  817. x = (b2 - b1) * 1.0 / (k1 - k2)
  818. y = k1 * x * 1.0 + b1 * 1.0
  819. point_is_exist = True
  820. left = 0
  821. right = 0
  822. top = 0
  823. buttom = 0
  824. if point_is_exist:
  825. if segment:
  826. if x>=(min(x1,x2)-margin) and x<=(max(x1,x2)+margin) and y>=(min(y1,y2)-margin) and y<=(max(y1,y2)+margin):
  827. if x>=(min(x3,x4)-margin) and x<=(max(x3,x4)+margin) and y>=(min(y3,y4)-margin) and y<=(max(y3,y4)+margin):
  828. point_is_exist = True
  829. left = abs(min(x1,x3)-x)
  830. right = abs(max(x2,x4)-x)
  831. top = abs(min(y1,y3)-y)
  832. buttom = abs(max(y2,y4)-y)
  833. else:
  834. point_is_exist = False
  835. else:
  836. point_is_exist = False
  837. line1_key = "%.2f-%.2f-%.2f-%.2f"%(x1, y1, x2, y2)
  838. line2_key = "%.2f-%.2f-%.2f-%.2f"%(x3, y3, x4, y4)
  839. return point_is_exist, {"point": [x, y], "left": left, "right": right,
  840. "top": top, "buttom": buttom, "lines": set([line1_key,line2_key]),"p_lines":[line1,line2]}
  841. def unionTable(self, list_table, fixspan=True, margin=2):
  842. set_x = set()
  843. set_y = set()
  844. list_cell = []
  845. for _t in list_table:
  846. for _line in _t:
  847. list_cell.extend(_line)
  848. clusters_rects = []
  849. #根据y1聚类
  850. set_id = set()
  851. list_cell_dump = []
  852. for _cell in list_cell:
  853. _id = id(_cell)
  854. if _id in set_id:
  855. continue
  856. set_id.add(_id)
  857. list_cell_dump.append(_cell)
  858. list_cell = list_cell_dump
  859. list_cell.sort(key=lambda x:x.get("bbox")[3])
  860. for _rect in list_cell:
  861. _y0 = _rect.get("bbox")[3]
  862. _find = False
  863. for l_cr in clusters_rects:
  864. if abs(l_cr[0].get("bbox")[3]-_y0)<2:
  865. _find = True
  866. l_cr.append(_rect)
  867. break
  868. if not _find:
  869. clusters_rects.append([_rect])
  870. clusters_rects.sort(key=lambda x:x[0].get("bbox")[3],reverse=True)
  871. for l_cr in clusters_rects:
  872. l_cr.sort(key=lambda x:x.get("bbox")[0])
  873. # print("=============:")
  874. # for l_r in clusters_rects:
  875. # print(len(l_r))
  876. for _line in clusters_rects:
  877. for _rect in _line:
  878. (x0,y0,x1,y1) = _rect.get("bbox")
  879. set_x.add(x0)
  880. set_x.add(x1)
  881. set_y.add(y0)
  882. set_y.add(y1)
  883. if len(set_x)==0 or len(set_y)==0:
  884. return
  885. list_x = list(set_x)
  886. list_y = list(set_y)
  887. list_x.sort(key=lambda x:x)
  888. list_y.sort(key=lambda x:x,reverse=True)
  889. _table = []
  890. for _line in clusters_rects:
  891. table_line = []
  892. for _rect in _line:
  893. (x0,y0,x1,y1) = _rect.get("bbox")
  894. _cell = {"bbox":(x0,y0,x1,y1),"rect":_rect.get("rect"),"rowspan":self.getspan(list_y,y0,y1,margin),"columnspan":self.getspan(list_x,x0,x1,margin),"text":_rect.get("text","")}
  895. table_line.append(_cell)
  896. _table.append(table_line)
  897. # print("=====================>>")
  898. # for _line in _table:
  899. # for _cell in _line:
  900. # print(_cell,end="\t")
  901. # print("\n")
  902. # print("=====================>>")
  903. # print(_table)
  904. if fixspan:
  905. for _line in _table:
  906. extend_line = []
  907. for c_i in range(len(_line)):
  908. _cell = _line[c_i]
  909. if _cell.get("columnspan")>1:
  910. _cospan = _cell.get("columnspan")
  911. _cell["columnspan"] = 1
  912. for i in range(1,_cospan):
  913. extend_line.append({"index":c_i+1,"cell":_cell})
  914. extend_line.sort(key=lambda x:x["index"],reverse=True)
  915. for _el in extend_line:
  916. _line.insert(_el["index"],_el["cell"])
  917. for l_i in range(len(_table)):
  918. _line = _table[l_i]
  919. for c_i in range(len(_line)):
  920. _cell = _line[c_i]
  921. if _cell.get("rowspan")>1:
  922. _rospan = _cell.get("rowspan")
  923. _cell["rowspan"] = 1
  924. for i in range(1,_rospan):
  925. _table[l_i+i].insert(c_i,_cell)
  926. table_bbox = (_table[0][0].get("bbox")[0],_table[0][0].get("bbox")[1],_table[-1][-1].get("bbox")[2],_table[-1][-1].get("bbox")[3])
  927. ta = {"bbox":table_bbox,"table":_table}
  928. return ta
  929. def rect2table(self, list_textbox, list_rect, in_objs, margin=5, fixspan=True,sourceP_LB=True,fixRect=True):
  930. def getIOU(bbox0,bbox1):
  931. width = max(bbox0[2],bbox1[2])-min(bbox0[0],bbox1[0])-(bbox0[2]-bbox0[0]+bbox1[2]-bbox1[0])
  932. height = max(bbox0[3],bbox1[3])-min(bbox0[1],bbox1[1])-(bbox0[3]-bbox0[1]+bbox1[3]-bbox1[1])
  933. if width<0 and height<0:
  934. return abs(width*height/min(abs((bbox0[2]-bbox0[0])*(bbox0[3]-bbox0[1])),abs((bbox1[2]-bbox1[0])*(bbox1[3]-bbox1[1]))))
  935. return 0
  936. _table = []
  937. set_x = set()
  938. set_y = set()
  939. clusters_rects = []
  940. # 根据y1聚类
  941. if sourceP_LB:
  942. list_rect.sort(key=lambda x:x.bbox[3])
  943. for _rect in list_rect:
  944. _y0 = _rect.bbox[3]
  945. _find = False
  946. for l_cr in clusters_rects:
  947. if abs(l_cr[0].bbox[3]-_y0)<margin:
  948. _find = True
  949. l_cr.append(_rect)
  950. break
  951. if not _find:
  952. clusters_rects.append([_rect])
  953. else:
  954. list_rect.sort(key=lambda x:x.bbox[1])
  955. for _rect in list_rect:
  956. _y0 = _rect.bbox[1]
  957. _find = False
  958. for l_cr in clusters_rects:
  959. if abs(l_cr[0].bbox[1]-_y0)<margin:
  960. _find = True
  961. l_cr.append(_rect)
  962. break
  963. if not _find:
  964. clusters_rects.append([_rect])
  965. # cul spans
  966. for _line in clusters_rects:
  967. for _rect in _line:
  968. (x0,y0,x1,y1) = _rect.bbox
  969. set_x.add(x0)
  970. set_x.add(x1)
  971. set_y.add(y0)
  972. set_y.add(y1)
  973. if len(set_x)==0 or len(set_y)==0:
  974. return
  975. if len(list_rect)<=1:
  976. return
  977. list_x = list(set_x)
  978. list_y = list(set_y)
  979. list_x.sort(key=lambda x:x)
  980. list_y.sort(key=lambda x:x,reverse=sourceP_LB)
  981. # print("clusters_rects", len(clusters_rects))
  982. if sourceP_LB:
  983. clusters_rects.sort(key=lambda x:x[0].bbox[3],reverse=sourceP_LB)
  984. else:
  985. clusters_rects.sort(key=lambda x:x[0].bbox[1],reverse=sourceP_LB)
  986. for l_cr in clusters_rects:
  987. l_cr.sort(key=lambda x:x.bbox[0])
  988. pop_x = []
  989. for i in range(len(list_x)-1):
  990. _i = len(list_x)-i-1
  991. l_i = _i-1
  992. if abs(list_x[_i]-list_x[l_i])<5:
  993. pop_x.append(_i)
  994. pop_x.sort(key=lambda x:x,reverse=True)
  995. for _x in pop_x:
  996. list_x.pop(_x)
  997. #
  998. pop_x = []
  999. for i in range(len(list_y)-1):
  1000. _i = len(list_y)-i-1
  1001. l_i = _i-1
  1002. if abs(list_y[_i]-list_y[l_i])<5:
  1003. pop_x.append(_i)
  1004. pop_x.sort(key=lambda x:x,reverse=True)
  1005. for _x in pop_x:
  1006. list_y.pop(_x)
  1007. # print(list_x)
  1008. # print(list_y)
  1009. for _line in clusters_rects:
  1010. table_line = []
  1011. for _rect in _line:
  1012. (x0, y0, x1, y1) = _rect.bbox
  1013. _cell = {"bbox": (x0, y0, x1, y1),
  1014. "rect": _rect,
  1015. "rowspan": self.getspan(list_y, y0, y1, margin),
  1016. "columnspan": self.getspan(list_x, x0, x1, margin),
  1017. "text": ""}
  1018. table_line.append(_cell)
  1019. _table.append(table_line)
  1020. list_textbox.sort(key=lambda x:x.bbox[0])
  1021. list_textbox.sort(key=lambda x:x.bbox[3],reverse=sourceP_LB)
  1022. # print("list_textbox", list_textbox)
  1023. for textbox in list_textbox:
  1024. (x0,y0,x1,y1) = textbox.bbox
  1025. _text = textbox.get_text()
  1026. _find = False
  1027. for table_line in _table:
  1028. for _cell in table_line:
  1029. if self.inbox(textbox.bbox, _cell["bbox"], textbox.get_text()):
  1030. _cell["text"] += _text
  1031. in_objs.add(textbox)
  1032. _find = True
  1033. break
  1034. if _find:
  1035. break
  1036. if fixspan:
  1037. for _line in _table:
  1038. for c_i in range(len(_line)):
  1039. _cell = _line[c_i]
  1040. if _cell.get("columnspan")>1:
  1041. _cospan = _cell.get("columnspan")
  1042. _cell["columnspan"] = 1
  1043. n_cell = {}
  1044. n_cell.update(_cell)
  1045. for i in range(1,_cospan):
  1046. _line.insert(c_i,n_cell)
  1047. for l_i in range(len(_table)):
  1048. _line = _table[l_i]
  1049. for c_i in range(len(_line)):
  1050. _cell = _line[c_i]
  1051. if _cell.get("rowspan")>1:
  1052. _rospan = _cell.get("rowspan")
  1053. _cell["rowspan"] = 1
  1054. n_cell = {}
  1055. n_cell.update(_cell)
  1056. for i in range(1,_rospan):
  1057. if l_i+i<=len(_table)-1:
  1058. # print(len(_table),l_i+i)
  1059. _table[l_i+i].insert(c_i,n_cell)
  1060. # print("=======")
  1061. # for _line in _table:
  1062. # for _cell in _line:
  1063. # _text = _cell["text"][:2]+"_"+str(_cell["columnspan"])+"_"+str(_cell["rowspan"])
  1064. # if _text=="":
  1065. # _text = "=="
  1066. # print(_text,end="\t")
  1067. # print("\n")
  1068. # print("===========")
  1069. if fixRect:
  1070. for _line in _table:
  1071. extend_line = []
  1072. for c_i in range(len(_line)):
  1073. c_cell = _line[c_i]
  1074. if c_i==0 and c_cell["bbox"][0]!=list_x[0]:
  1075. _bbox = (list_x[0],c_cell["bbox"][1], c_cell["bbox"][0],c_cell["bbox"][3])
  1076. _cell = {"bbox": _bbox,
  1077. "rect": LTRect(1,_bbox),
  1078. "rowspan": self.getspan(list_y,_bbox[1], _bbox[3], margin),
  1079. "columnspan": self.getspan(list_x, _bbox[0], _bbox[2], margin),
  1080. "text": ""}
  1081. extend_line.append({"index":c_i,"cell":_cell})
  1082. if c_i<len(_line)-1:
  1083. n_cell = _line[c_i+1]
  1084. _bbox = c_cell["bbox"]
  1085. n_bbox = n_cell["bbox"]
  1086. if _bbox[0]==n_bbox[0] and _bbox[2]==n_bbox[2]:
  1087. continue
  1088. else:
  1089. if abs(_bbox[2]-n_bbox[0])>margin:
  1090. _bbox = (_bbox[2],_bbox[1], n_bbox[0],_bbox[3])
  1091. _cell = {"bbox": _bbox,
  1092. "rect": LTRect(1,_bbox),
  1093. "rowspan": self.getspan(list_y,_bbox[1], _bbox[3], margin),
  1094. "columnspan": self.getspan(list_x, _bbox[0], _bbox[2], margin),
  1095. "text": ""}
  1096. extend_line.append({"index":c_i+1,"cell":_cell})
  1097. if c_i==len(_line)-1:
  1098. if abs(c_cell["bbox"][2]-list_x[-1])>margin:
  1099. _bbox = (c_cell["bbox"][2],c_cell["bbox"][1], list_x[-1],c_cell["bbox"][3])
  1100. _cell = {"bbox": _bbox,
  1101. "rect": LTRect(1,_bbox),
  1102. "rowspan": self.getspan(list_y,_bbox[1], _bbox[3], margin),
  1103. "columnspan": self.getspan(list_x, _bbox[0], _bbox[2], margin),
  1104. "text": ""}
  1105. extend_line.append({"index":c_i+1,"cell":_cell})
  1106. extend_line.sort(key=lambda x:x["index"],reverse=True)
  1107. for _tmp in extend_line:
  1108. _line.insert(_tmp["index"],_tmp["cell"])
  1109. list_textbox.sort(key=lambda x:x.bbox[0])
  1110. list_textbox.sort(key=lambda x:x.bbox[3],reverse=sourceP_LB)
  1111. for textbox in list_textbox:
  1112. if textbox in in_objs:
  1113. continue
  1114. (x0,y0,x1,y1) = textbox.bbox
  1115. _text = textbox.get_text()
  1116. _find = False
  1117. for table_line in _table:
  1118. for _cell in table_line:
  1119. if self.inbox(textbox.bbox,_cell["bbox"], textbox.get_text()):
  1120. _cell["text"] += _text
  1121. in_objs.add(textbox)
  1122. _find = True
  1123. break
  1124. if _find:
  1125. break
  1126. # print("=======")
  1127. # for _line in _table:
  1128. # for _cell in _line:
  1129. # _text = _cell["text"][:2]
  1130. # if _text=="":
  1131. # _text = "=="
  1132. # print(_text,end="\t")
  1133. # print("\n")
  1134. # print("===========")
  1135. table_bbox = (_table[0][0].get("bbox")[0],
  1136. _table[0][0].get("bbox")[1],
  1137. _table[-1][-1].get("bbox")[2],
  1138. _table[-1][-1].get("bbox")[3])
  1139. ta = {"bbox": table_bbox, "table": _table}
  1140. return ta
  1141. def inbox(self, bbox0, bbox_g, text=""):
  1142. # if bbox_g[0]<=bbox0[0] and bbox_g[1]<=bbox0[1] and bbox_g[2]>=bbox0[2] and bbox_g[3]>=bbox0[3]:
  1143. # return 1
  1144. # print("utils inbox", text, self.getIOU(bbox0,bbox_g), bbox0, bbox_g)
  1145. if self.getIOU(bbox0,bbox_g)>0.5:
  1146. return 1
  1147. return 0
  1148. def getIOU(self, bbox0, bbox1):
  1149. width = max(bbox0[2],bbox1[2])-min(bbox0[0],bbox1[0])-(bbox0[2]-bbox0[0]+bbox1[2]-bbox1[0])
  1150. height = max(bbox0[3],bbox1[3])-min(bbox0[1],bbox1[1])-(bbox0[3]-bbox0[1]+bbox1[3]-bbox1[1])
  1151. if width < 0 and height < 0:
  1152. iou = abs(width*height/min(abs((bbox0[2]-bbox0[0])*(bbox0[3]-bbox0[1])),
  1153. abs((bbox1[2]-bbox1[0])*(bbox1[3]-bbox1[1]))))
  1154. # print("getIOU", iou)
  1155. return iou
  1156. return 0
  1157. def getspan(self, _list, x0, x1, margin):
  1158. _count = 0
  1159. (x0,x1) = (min(x0,x1),max(x0,x1))
  1160. for _x in _list:
  1161. if _x>=(x0-margin) and _x<=(x1+margin):
  1162. _count += 1
  1163. return _count-1
  1164. def _plot(self, list_line, list_textbox):
  1165. from matplotlib import pyplot as plt
  1166. plt.figure()
  1167. for _line in list_line:
  1168. x0, y0, x1, y1 = _line.__dict__.get("bbox")
  1169. plt.plot([x0, x1], [y0, y1])
  1170. for _line in list_line:
  1171. x0, y0, x1, y1 = _line.bbox
  1172. plt.plot([x0, x1], [y0, y1])
  1173. # for point in list_crosspoints:
  1174. # plt.scatter(point.get("point")[0],point.get("point")[1])
  1175. for textbox in list_textbox:
  1176. x0, y0, x1, y1 = textbox.bbox
  1177. plt.plot([x0, x1], [y0, y1])
  1178. plt.show()
  1179. def get_table_html(table):
  1180. html_text = '<table border="1">' + "\n"
  1181. for row in table:
  1182. html_text += "<tr>" + "\n"
  1183. for col in row:
  1184. row_span = col.get("rowspan")
  1185. col_span = col.get("columnspan")
  1186. bbox_text = col.get("text")
  1187. html_text += "<td colspan=" + str(col_span) + " rowspan=" + str(row_span) + ">"
  1188. html_text += bbox_text + "</td>" + "\n"
  1189. html_text += "</tr>" + "\n"
  1190. html_text += "</table>" + "\n"
  1191. return html_text
  1192. def sort_object(obj_list, is_reverse=False):
  1193. from format_convert.convert_tree import _Table, _Image, _Sentence, _Page
  1194. if len(obj_list) == 0:
  1195. return obj_list
  1196. if isinstance(obj_list[0], (_Table, _Sentence, _Image)):
  1197. obj_list.sort(key=lambda x: (x.y, x.x), reverse=is_reverse)
  1198. return obj_list
  1199. elif isinstance(obj_list[0], _Page):
  1200. obj_list.sort(key=lambda x: x.page_no)
  1201. return obj_list
  1202. else:
  1203. return obj_list
  1204. def request_post(url, param, time_out=1000):
  1205. fails = 0
  1206. text = json.dumps([-2])
  1207. while True:
  1208. try:
  1209. if fails >= 1:
  1210. break
  1211. headers = {'content-type': 'application/json'}
  1212. result = requests.post(url, data=param, timeout=time_out)
  1213. # print('result.status_code', result.status_code)
  1214. # print('result.text', result.text)
  1215. if result.status_code == 200:
  1216. text = result.text
  1217. break
  1218. else:
  1219. print('result.status_code', result.status_code)
  1220. print('result.text', result.text)
  1221. fails += 1
  1222. continue
  1223. except socket.timeout:
  1224. fails += 1
  1225. print('timeout! fail times:', fails)
  1226. except:
  1227. fails += 1
  1228. print('fail! fail times:', fails)
  1229. traceback.print_exc()
  1230. return text
  1231. def test_gpu():
  1232. print("="*30)
  1233. import paddle
  1234. paddle.utils.run_check()
  1235. # import tensorflow as tf
  1236. # print("tf gpu", tf.config.list_physical_devices('GPU'))
  1237. print("="*30)
  1238. def my_subprocess_call(*popenargs, timeout=None):
  1239. logging.info("into my_subprocess_call")
  1240. with Popen(*popenargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
  1241. try:
  1242. for line in p.stdout:
  1243. print("stdout", line)
  1244. for line in p.stderr:
  1245. print("stderr", line)
  1246. p.wait(timeout=timeout)
  1247. # p.communicate()
  1248. return p.pid, p.returncode
  1249. except: # Including KeyboardInterrupt, wait handled that.
  1250. p.kill()
  1251. # We don't call p.wait() again as p.__exit__ does that for us.
  1252. raise
  1253. finally:
  1254. logging.info("out my_subprocess_call")
  1255. p.kill()
  1256. def parse_yaml():
  1257. yaml_path = os.path.dirname(os.path.abspath(__file__)) + "/interface.yml"
  1258. with open(yaml_path, "r", encoding='utf-8') as f:
  1259. cfg = f.read()
  1260. params = yaml.load(cfg, Loader=yaml.SafeLoader)
  1261. return params
  1262. def get_ip_port(node_type=None, interface_type=None):
  1263. if node_type is None:
  1264. node_type_list = ["master", "slave"]
  1265. else:
  1266. node_type_list = [node_type]
  1267. if interface_type is None:
  1268. interface_type_list = ["convert", "ocr", "otr", "office", "path"]
  1269. else:
  1270. interface_type_list = [interface_type]
  1271. ip_port_dict = {}
  1272. params = parse_yaml()
  1273. for type1 in node_type_list:
  1274. node_type = type1.upper()
  1275. ip_list = params.get(node_type).get("ip")
  1276. for type2 in interface_type_list:
  1277. interface_type = type2.upper()
  1278. processes = 0
  1279. python_path = None
  1280. project_path = None
  1281. if interface_type in ["convert".upper()]:
  1282. _port = params.get(node_type).get(interface_type).get("port")
  1283. if _port is None:
  1284. port_list = []
  1285. else:
  1286. port_list = [str(_port)]
  1287. if interface_type == "convert".upper():
  1288. processes = params.get(node_type).get(interface_type).get("processes")
  1289. elif interface_type == "path".upper():
  1290. python_path = params.get(node_type).get(interface_type).get("python")
  1291. project_path = params.get(node_type).get(interface_type).get("project")
  1292. else:
  1293. port_start = params.get(node_type).get(interface_type).get("port_start")
  1294. port_no = params.get(node_type).get(interface_type).get("port_no")
  1295. if port_start is None or port_no is None:
  1296. port_list = []
  1297. else:
  1298. port_list = [str(x) for x in range(port_start, port_start+port_no, 1)]
  1299. if ip_list:
  1300. for _ip in ip_list:
  1301. if _ip is None:
  1302. continue
  1303. if _ip in ip_port_dict.keys():
  1304. if port_list:
  1305. ip_port_dict.get(_ip).update({interface_type.lower(): port_list})
  1306. else:
  1307. if port_list:
  1308. ip_port_dict[_ip] = {interface_type.lower(): port_list}
  1309. if processes:
  1310. ip_port_dict.get(_ip).update({interface_type.lower()+"_processes": processes})
  1311. if project_path and python_path:
  1312. ip_port_dict.get(_ip).update({"project_path": project_path,
  1313. "python_path": python_path})
  1314. return ip_port_dict
  1315. def get_intranet_ip():
  1316. try:
  1317. # Create a new socket using the given address family,
  1318. # socket type and protocol number.
  1319. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1320. # Connect to a remote socket at address.
  1321. # (The format of address depends on the address family.)
  1322. address = ("8.8.8.8", 80)
  1323. s.connect(address)
  1324. # Return the socket’s own address.
  1325. # This is useful to find out the port number of an IPv4/v6 socket, for instance.
  1326. # (The format of the address returned depends on the address family.)
  1327. sockname = s.getsockname()
  1328. ip = sockname[0]
  1329. port = sockname[1]
  1330. finally:
  1331. s.close()
  1332. return ip
  1333. def memory_decorator(func):
  1334. @wraps(func)
  1335. def get_memory_info(*args, **kwargs):
  1336. if get_platform() == "Windows":
  1337. return func(*args, **kwargs)
  1338. # 只有linux有resource包
  1339. # usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
  1340. usage = psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024
  1341. start_time = time.time()
  1342. logging.info("----- memory info start - " + func.__qualname__
  1343. + " - " + str(os.getpid())
  1344. + " - " + str(round(usage, 2)) + " GB"
  1345. + " - " + str(round(time.time()-start_time, 2)) + " sec")
  1346. result = func(*args, **kwargs)
  1347. # usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
  1348. usage = psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024
  1349. logging.info("----- memory info end - " + func.__qualname__
  1350. + " - " + str(os.getpid())
  1351. + " - " + str(round(usage, 2)) + " GB"
  1352. + " - " + str(round(time.time()-start_time, 2)) + " sec")
  1353. return result
  1354. return get_memory_info
  1355. def log(msg):
  1356. call_func_name = inspect.currentframe().f_back.f_code.co_name
  1357. logger = get_logger(call_func_name, {"md5": _global.get("md5"),
  1358. "port": _global.get("port")})
  1359. logger.info(msg)
  1360. # logging.info(msg)
  1361. def get_logger(_name, _dict):
  1362. extra = _dict
  1363. _format = '%(asctime)s - %(name)s - %(levelname)s - %(md5)s - %(port)s - %(message)s'
  1364. logger = logging.getLogger(_name)
  1365. create_new_flag = 1
  1366. handlers = logger.handlers
  1367. if handlers:
  1368. for h in handlers:
  1369. if h.formatter.__dict__.get("_fmt") == _format:
  1370. create_new_flag = 0
  1371. break
  1372. if create_new_flag:
  1373. formatter = logging.Formatter(_format)
  1374. handler = logging.StreamHandler()
  1375. handler.setFormatter(formatter)
  1376. logger.addHandler(handler)
  1377. logger.setLevel(logging.INFO)
  1378. logger.propagate = False
  1379. logger = logging.LoggerAdapter(logger, extra)
  1380. return logger
  1381. def set_flask_global():
  1382. # 接口轮询所需锁、参数
  1383. ip_port_flag = {}
  1384. ip_port_dict = get_ip_port()
  1385. for _k in ip_port_dict.keys():
  1386. ip_port_flag.update({_k: {"ocr": 0,
  1387. "otr": 0,
  1388. "convert": 0,
  1389. "office": 0
  1390. }})
  1391. _global.update({"ip_port_flag": ip_port_flag})
  1392. _global.update({"ip_port": ip_port_dict})
  1393. # print(globals().get("ip_port"))
  1394. def get_md5_from_bytes(_bytes):
  1395. def generate_fp(_b):
  1396. bio = BytesIO()
  1397. bio.write(_b)
  1398. return bio
  1399. _length = 0
  1400. try:
  1401. _md5 = hashlib.md5()
  1402. ff = generate_fp(_bytes)
  1403. ff.seek(0)
  1404. while True:
  1405. data = ff.read(4096)
  1406. if not data:
  1407. break
  1408. _length += len(data)
  1409. _md5.update(data)
  1410. return _md5.hexdigest(), _length
  1411. except Exception as e:
  1412. traceback.print_exc()
  1413. return None, _length
  1414. if __name__ == "__main__":
  1415. # strs = r"D:\Project\temp\04384fcc9e8911ecbd2844f971944973\043876ca9e8911eca5e144f971944973_rar\1624114035529.jpeg"
  1416. # print(slash_replace(strs))
  1417. # from matplotlib import pyplot as plt
  1418. # import random
  1419. # fig = plt.figure()
  1420. # plt.xlim(100)
  1421. # plt.ylim(100)
  1422. # fig.add_subplot(111)
  1423. # x0,y0,x1,y1 = (1,2,3,4)
  1424. # plt.gca().add_patch(plt.Rectangle(xy=(x0, y0),
  1425. # width=x1-x0,
  1426. # height=y1-y0,
  1427. # edgecolor=(random.randint(0,255)/255,random.randint(0,255)/255,random.randint(0,255)/255),
  1428. # fill=False, linewidth=2))
  1429. #
  1430. # # plt.show()
  1431. # import cv2
  1432. # import numpy as np
  1433. # img = np.zeros(shape=(1800,1800),dtype=np.uint8)
  1434. # img += 255
  1435. # cv2.imshow("bbox", img)
  1436. # cv2.waitKey(0)
  1437. # print(json.dumps({"data":[1, 2]}))
  1438. # print(parse_yaml())
  1439. print(get_ip_port())
  1440. # print(get_intranet_ip())