utils.py 60 KB

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