utils.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  1. # -*- coding:utf-8 -*-
  2. import argparse
  3. import copy
  4. import hashlib
  5. import inspect
  6. import json
  7. import os
  8. import socket
  9. import subprocess
  10. import sys
  11. from io import BytesIO
  12. from subprocess import Popen
  13. from shapely.geometry import LineString
  14. import cv2
  15. import requests
  16. from PIL import Image
  17. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  18. import difflib
  19. import logging
  20. import mimetypes
  21. import platform
  22. import re
  23. import traceback
  24. import filetype
  25. from bs4 import BeautifulSoup
  26. import yaml
  27. from pdfminer.layout import *
  28. from format_convert import _global
  29. from functools import wraps
  30. import psutil
  31. import time
  32. import numpy as np
  33. from format_convert.judge_platform import get_platform
  34. if get_platform() == "Linux":
  35. import resource
  36. import math
  37. def judge_error_code(_list, code=[0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14]):
  38. """
  39. [0] : continue
  40. [-1]: 逻辑处理错误
  41. [-2]: 接口调用错误
  42. [-3]: 文件格式错误,无法打开
  43. [-4]: 各类文件调用第三方包读取超时
  44. [-5]: 整个转换过程超时
  45. [-6]: 阿里云UDF队列超时
  46. [-7]: 文件需密码,无法打开
  47. [-8]: 调用现成接口报错
  48. [-9]: 接口接收数据为空
  49. [-10]: 长图分割报错
  50. [-11]: 新接口idc、isr、atc报错
  51. [-12]: 表格跨页连接报错
  52. [-13]: pdf表格线处理报错
  53. [-14]: 指定页码报错
  54. """
  55. for c in code:
  56. if isinstance(_list, list) and _list == [c]:
  57. return True
  58. return False
  59. def add_div(text):
  60. if text == "" or text is None:
  61. return text
  62. # if get_platform() == "Windows":
  63. # print("add_div", text)
  64. if re.findall("<div>", text):
  65. return text
  66. text = "<div>" + text + "\n"
  67. text = re.sub("\n", "</div><div>", text)
  68. # text += "</div>"
  69. if text[-5:] == "<div>":
  70. # print("add_div has cut", text[-30:])
  71. text = text[:-5]
  72. return text
  73. def get_platform():
  74. sys = platform.system()
  75. return sys
  76. def get_html_p(html_path):
  77. log("into get_html_p")
  78. try:
  79. with open(html_path, "r") as ff:
  80. html_str = ff.read()
  81. soup = BeautifulSoup(html_str, 'lxml')
  82. text = ""
  83. for p in soup.find_all("p"):
  84. p_text = p.text
  85. p_text = p_text.strip()
  86. if p.string != "":
  87. text += p_text
  88. text += "\n"
  89. return text
  90. except Exception as e:
  91. log("get_html_p error!")
  92. return [-1]
  93. def string_similarity(str1, str2):
  94. # 去掉<div>和回车
  95. str1 = re.sub("<div>", "", str1)
  96. str1 = re.sub("</div>", "", str1)
  97. str1 = re.sub("\n", "", str1)
  98. str2 = re.sub("<div>", "", str2)
  99. str2 = re.sub("</div>", "", str2)
  100. str2 = re.sub("\n", "", str2)
  101. # print("********************************")
  102. # print("str1", str1)
  103. # print("********************************")
  104. # print("str2", str2)
  105. # print("********************************")
  106. score = difflib.SequenceMatcher(None, str1, str2).ratio()
  107. print("string_similarity", score)
  108. return score
  109. def get_sequential_data(text_list, bbox_list, html=False):
  110. logging.info("into get_sequential_data")
  111. try:
  112. text = ""
  113. order_list = []
  114. for i in range(len(text_list)):
  115. length_start = bbox_list[i][0][0]
  116. length_end = bbox_list[i][1][0]
  117. height_start = bbox_list[i][0][1]
  118. height_end = bbox_list[i][-1][1]
  119. # print([length_start, length_end, height_start, height_end])
  120. order_list.append([text_list[i], length_start, length_end, height_start, height_end])
  121. # text = text + infomation['text'] + "\n"
  122. if get_platform() == "Windows":
  123. print("get_sequential_data", order_list)
  124. if not order_list:
  125. if get_platform() == "Windows":
  126. print("get_sequential_data", "no order list")
  127. return ""
  128. # 根据bbox的坐标对输出排序
  129. order_list.sort(key=lambda x: (x[3], x[1], x[0]))
  130. # 根据bbox分行分列
  131. # col_list = []
  132. # height_end = int((order_list[0][4] + order_list[0][3]) / 2)
  133. # for i in range(len(order_list)):
  134. # if height_end - threshold <= order_list[i][3] <= height_end + threshold:
  135. # col_list.append(order_list[i])
  136. # else:
  137. # row_list.append(col_list)
  138. # col_list = []
  139. # height_end = int((order_list[i][4] + order_list[i][3]) / 2)
  140. # col_list.append(order_list[i])
  141. # if i == len(order_list) - 1:
  142. # row_list.append(col_list)
  143. row_list = []
  144. used_box = []
  145. threshold = 5
  146. for box in order_list:
  147. if box in used_box:
  148. continue
  149. height_center = (box[4] + box[3]) / 2
  150. row = []
  151. for box2 in order_list:
  152. if box2 in used_box:
  153. continue
  154. height_center2 = (box2[4] + box2[3]) / 2
  155. if height_center - threshold <= height_center2 <= height_center + threshold:
  156. if box2 not in row:
  157. row.append(box2)
  158. used_box.append(box2)
  159. row.sort(key=lambda x: x[0])
  160. row_list.append(row)
  161. for row in row_list:
  162. if not row:
  163. continue
  164. if len(row) <= 1:
  165. text = text + row[0][0] + "\n"
  166. else:
  167. sub_text = ""
  168. row.sort(key=lambda x: x[1])
  169. for col in row:
  170. sub_text = sub_text + col[0] + " "
  171. sub_text = sub_text + "\n"
  172. text += sub_text
  173. if html:
  174. text = "<div>" + text
  175. text = re.sub("\n", "</div>\n<div>", text)
  176. text += "</div>"
  177. # if text[-5:] == "<div>":
  178. # text = text[:-5]
  179. return text
  180. except Exception as e:
  181. logging.info("get_sequential_data error!")
  182. print("get_sequential_data", traceback.print_exc())
  183. return [-1]
  184. def rename_inner_files(root_path):
  185. try:
  186. logging.info("into rename_inner_files")
  187. # 获取解压文件夹下所有文件+文件夹,不带根路径
  188. path_list = []
  189. for root, dirs, files in os.walk(root_path, topdown=False):
  190. for name in dirs:
  191. p = os.path.join(root, name) + os.sep
  192. if get_platform() == "Windows":
  193. root_path = slash_replace(root_path)
  194. p = slash_replace(p)
  195. p = re.sub(root_path, "", p)
  196. root_path = slash_replace(root_path, True)
  197. p = slash_replace(p, True)
  198. else:
  199. p = re.sub(root_path, "", p)
  200. path_list.append(p)
  201. for name in files:
  202. p = os.path.join(root, name)
  203. if get_platform() == "Windows":
  204. root_path = slash_replace(root_path)
  205. p = slash_replace(p)
  206. p = re.sub(root_path, "", p)
  207. root_path = slash_replace(root_path, True)
  208. p = slash_replace(p, True)
  209. else:
  210. p = re.sub(root_path, "", p)
  211. path_list.append(p)
  212. # 按路径长度排序
  213. path_list.sort(key=lambda x: len(x), reverse=True)
  214. # 循环改名
  215. for old_path in path_list:
  216. # 按路径分隔符分割
  217. ss = old_path.split(os.sep)
  218. # 判断是否文件夹
  219. is_dir = 0
  220. file_type = ""
  221. if os.path.isdir(root_path + old_path):
  222. ss = ss[:-1]
  223. is_dir = 1
  224. else:
  225. if "." in old_path:
  226. file_type = "." + old_path.split(".")[-1]
  227. else:
  228. file_type = ""
  229. # 最后一级需要用hash改名
  230. new_path = ""
  231. # new_path = re.sub(ss[-1], str(hash(ss[-1])), old_path) + file_type
  232. current_level = 0
  233. for s in ss:
  234. # 路径拼接
  235. if current_level < len(ss) - 1:
  236. new_path += s + os.sep
  237. else:
  238. new_path += str(hash(s)) + file_type
  239. current_level += 1
  240. new_ab_path = root_path + new_path
  241. old_ab_path = root_path + old_path
  242. os.rename(old_ab_path, new_ab_path)
  243. # 重新获取解压文件夹下所有文件+文件夹
  244. new_path_list = []
  245. for root, dirs, files in os.walk(root_path, topdown=False):
  246. for name in dirs:
  247. new_path_list.append(os.path.join(root, name) + os.sep)
  248. for name in files:
  249. new_path_list.append(os.path.join(root, name))
  250. return new_path_list
  251. except:
  252. traceback.print_exc()
  253. return [-1]
  254. def judge_format(path):
  255. guess1 = mimetypes.guess_type(path)
  256. _type = None
  257. if guess1[0]:
  258. _type = guess1[0]
  259. else:
  260. guess2 = filetype.guess(path)
  261. if guess2:
  262. _type = guess2.mime
  263. if _type == "application/pdf":
  264. return "pdf"
  265. if _type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
  266. return "docx"
  267. if _type == "application/x-zip-compressed" or _type == "application/zip":
  268. return "zip"
  269. if _type == "application/x-rar-compressed" or _type == "application/rar":
  270. return "rar"
  271. if _type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
  272. return "xlsx"
  273. if _type == "application/msword":
  274. return "doc"
  275. if _type == "image/png":
  276. return "png"
  277. if _type == "image/jpeg":
  278. return "jpg"
  279. # 猜不到,返回None
  280. return None
  281. def draw_lines_plt(bboxes):
  282. import matplotlib.pyplot as plt
  283. plt.figure()
  284. for bbox in bboxes:
  285. x = [bbox[0], bbox[2]]
  286. y = [bbox[1], bbox[3]]
  287. plt.plot(x, y)
  288. plt.show()
  289. def slash_replace(_str, reverse=False):
  290. if reverse:
  291. _str = eval(repr(_str).replace('/', '\\\\'))
  292. else:
  293. _str = eval(repr(_str).replace('\\\\', '/'))
  294. return _str
  295. class LineTable:
  296. def recognize_table(self, list_textbox, list_line, sourceP_LB=True, splited=False, from_pdf=False):
  297. self.list_line = list_line
  298. self.list_crosspoints = self.recognize_crosspoints(list_line)
  299. self.from_pdf = from_pdf
  300. self.splited = splited
  301. # 聚类
  302. cluster_crosspoints = []
  303. for _point in self.list_crosspoints:
  304. cluster_crosspoints.append({"lines": _point.get("lines"), "points": [_point]})
  305. while 1:
  306. _find = False
  307. new_cluster_crosspoints = []
  308. for l_point in cluster_crosspoints:
  309. _flag = False
  310. for l_n_point in new_cluster_crosspoints:
  311. line1 = l_point.get("lines")
  312. line2 = l_n_point.get("lines")
  313. if len(line1 & line2) > 0:
  314. _find = True
  315. _flag = True
  316. l_n_point["lines"] = line1.union(line2)
  317. l_n_point["points"].extend(l_point["points"])
  318. if not _flag:
  319. new_cluster_crosspoints.append({"lines": l_point.get("lines"), "points": l_point.get("points")})
  320. cluster_crosspoints = new_cluster_crosspoints
  321. if not _find:
  322. break
  323. # need to sort to deal with the inner tables
  324. for clu_cp in cluster_crosspoints:
  325. points = clu_cp["points"]
  326. list_p = np.array([p["point"] for p in points])
  327. max_x = max(list_p[..., 0])
  328. min_x = min(list_p[..., 0])
  329. max_y = max(list_p[..., 1])
  330. min_y = min(list_p[..., 1])
  331. _area = (max_y - min_y) * (max_x - min_x)
  332. clu_cp["area"] = _area
  333. cluster_crosspoints.sort(key=lambda x: x["area"])
  334. list_l_rect = []
  335. for table_crosspoint in cluster_crosspoints:
  336. list_rect = self.crosspoint2rect(table_crosspoint.get("points"))
  337. list_l_rect.append(list_rect)
  338. in_objs = set()
  339. list_tables = []
  340. for l_rect in list_l_rect:
  341. _ta = self.rect2table(list_textbox, l_rect, in_objs, sourceP_LB=sourceP_LB)
  342. if self.connect_bbox_list:
  343. return [], [], [], self.connect_bbox_list
  344. if _ta:
  345. list_tables.append(_ta)
  346. # 展示表格及文字
  347. # self._plot(list_line, list_textbox)
  348. return list_tables, in_objs, list_l_rect, []
  349. # def recognize_table_by_rect(self, list_textbox, list_rect, margin=2):
  350. #
  351. # dump_margin = 5
  352. # list_rect_tmp = []
  353. # # 去重
  354. # for _rect in list_rect:
  355. # if (_rect.bbox[3] - _rect.bbox[1] < 10) or (abs(_rect.bbox[2] - _rect.bbox[0]) < 5):
  356. # continue
  357. # _find = False
  358. # for _tmp in list_rect_tmp:
  359. # for i in range(4):
  360. # if abs(_rect.bbox[i] - _tmp.bbox[i]) < dump_margin:
  361. # pass
  362. # else:
  363. # _find = False
  364. # break
  365. # if i == 3:
  366. # _find = True
  367. # if _find:
  368. # break
  369. # if not _find:
  370. # list_rect_tmp.append(_rect)
  371. #
  372. # # print("=====",len(list_rect),len(list_rect_tmp))
  373. # # print(list_rect_tmp)
  374. # # from matplotlib import pyplot as plt
  375. # # plt.figure()
  376. # # for _rect in list_rect_tmp:
  377. # # x0,y0,x1,y1 = _rect.bbox
  378. # # plt.boxplot(_rect.bbox)
  379. # # plt.show()
  380. #
  381. # cluster_rect = []
  382. # for _rect in list_rect:
  383. # _find = False
  384. # for cr in cluster_rect:
  385. # for cr_rect in cr:
  386. # if abs((cr_rect.bbox[2] - cr_rect.bbox[0] + _rect.bbox[2] - _rect.bbox[0]) - (
  387. # max(cr_rect.bbox[2], _rect.bbox[2]) - min(cr_rect.bbox[0], _rect.bbox[0]))) < margin:
  388. # _find = True
  389. # cr.append(_rect)
  390. # break
  391. # elif abs((cr_rect.bbox[3] - cr_rect.bbox[1] + _rect.bbox[3] - _rect.bbox[1]) - (
  392. # max(cr_rect.bbox[3], _rect.bbox[3]) - min(cr_rect.bbox[1], _rect.bbox[1]))) < margin:
  393. # _find = True
  394. # cr.append(_rect)
  395. # break
  396. # if _find:
  397. # break
  398. # if not _find:
  399. # cluster_rect.append([_rect])
  400. #
  401. # list_l_rect = cluster_rect
  402. #
  403. # in_objs = set()
  404. # list_tables = []
  405. # for l_rect in list_l_rect:
  406. # _ta = self.rect2table(list_textbox, l_rect, in_objs)
  407. # if _ta:
  408. # list_tables.append(_ta)
  409. # return list_tables, in_objs, list_l_rect
  410. def recognize_crosspoints(self, list_line, fixLine=True):
  411. list_crosspoints = []
  412. # print("lines num",len(list_line))
  413. def getMaxPoints(list_x, margin=5, reverse=False):
  414. clust_x = []
  415. for _x in list_x:
  416. _find = False
  417. for cx in clust_x:
  418. if abs(cx[0] - _x) < margin:
  419. _find = True
  420. cx.append(_x)
  421. break
  422. if not _find:
  423. clust_x.append([_x])
  424. clust_x.sort(key=lambda x: x, reverse=reverse)
  425. return clust_x[0][0], len(clust_x[0])
  426. for _i in range(len(list_line)):
  427. for _j in range(len(list_line)):
  428. line1 = list_line[_i].__dict__.get("bbox")
  429. line2 = list_line[_j].__dict__.get("bbox")
  430. exists, point = self.cross_point(line1, line2)
  431. if exists:
  432. list_crosspoints.append(point)
  433. if fixLine:
  434. # 聚类
  435. cluster_crosspoints = []
  436. for _point in list_crosspoints:
  437. cluster_crosspoints.append({"lines": _point.get("lines"), "points": [_point]})
  438. while 1:
  439. _find = False
  440. new_cluster_crosspoints = []
  441. for l_point in cluster_crosspoints:
  442. _flag = False
  443. for l_n_point in new_cluster_crosspoints:
  444. line1 = l_point.get("lines")
  445. line2 = l_n_point.get("lines")
  446. if len(line1 & line2) > 0:
  447. _find = True
  448. _flag = True
  449. l_n_point["lines"] = line1.union(line2)
  450. l_n_point["points"].extend(l_point["points"])
  451. if not _flag:
  452. new_cluster_crosspoints.append({"lines": l_point.get("lines"), "points": l_point.get("points")})
  453. cluster_crosspoints = new_cluster_crosspoints
  454. if not _find:
  455. break
  456. list_crosspoints = []
  457. for list_cp in cluster_crosspoints:
  458. points = list_cp.get("points")
  459. l_lines = []
  460. for p in points:
  461. l_lines.extend(p.get("p_lines"))
  462. l_lines = list(set(l_lines))
  463. l_lines.sort(key=lambda x: x[0])
  464. min_x, _count = getMaxPoints([l[0] for l in l_lines], reverse=False)
  465. if _count <= 2:
  466. min_x = None
  467. min_y, _count = getMaxPoints([l[1] for l in l_lines], reverse=False)
  468. if _count < 2:
  469. min_y = None
  470. max_x, _count = getMaxPoints([l[2] for l in l_lines], reverse=True)
  471. if _count <= 2:
  472. max_x = None
  473. max_y, _count = getMaxPoints([l[3] for l in l_lines], reverse=True)
  474. if _count <= 2:
  475. max_y = None
  476. if min_x and min_y and max_x and max_y:
  477. points.sort(key=lambda x: x["point"][0])
  478. if abs(min_x - points[0]["point"][0]) > 30:
  479. _line = LTLine(1, (min_x, min_y), (min_x, max_y))
  480. list_line.append(_line)
  481. l_lines.append(_line.bbox)
  482. # print("add=====",_line.bbox)
  483. if abs(max_x - points[-1]["point"][0]) > 30:
  484. _line = LTLine(1, (max_x, min_y), (max_x, max_y))
  485. list_line.append(_line)
  486. l_lines.append(_line.bbox)
  487. # print("add=====1",_line.bbox)
  488. points.sort(key=lambda x: x["point"][1])
  489. if abs(min_y - points[0]["point"][1]) > 30:
  490. _line = LTLine(1, (min_x, min_y), (max_x, min_y))
  491. list_line.append(_line)
  492. l_lines.append(_line.bbox)
  493. # print("add=====2",_line.bbox)
  494. if abs(max_y - points[-1]["point"][1]) > 30:
  495. _line = LTLine(1, (min_x, max_y), (max_x, max_y))
  496. list_line.append(_line)
  497. l_lines.append(_line.bbox)
  498. # print("add=====2",_line.bbox)
  499. for _i in range(len(l_lines)):
  500. for _j in range(len(l_lines)):
  501. line1 = l_lines[_i]
  502. line2 = l_lines[_j]
  503. exists, point = self.cross_point(line1, line2)
  504. if exists:
  505. list_crosspoints.append(point)
  506. # from matplotlib import pyplot as plt
  507. # plt.figure()
  508. # for _line in l_lines:
  509. # x0,y0,x1,y1 = _line
  510. # plt.plot([x0,x1],[y0,y1])
  511. # for point in list_crosspoints:
  512. # plt.scatter(point.get("point")[0],point.get("point")[1])
  513. # plt.show()
  514. # print(list_crosspoints)
  515. # print("points num",len(list_crosspoints))
  516. return list_crosspoints
  517. # def recognize_rect(self, _page):
  518. # list_line = []
  519. # for _obj in _page._objs:
  520. # if isinstance(_obj, (LTLine)):
  521. # list_line.append(_obj)
  522. # list_crosspoints = self.recognize_crosspoints(list_line)
  523. #
  524. # # 聚类
  525. # cluster_crosspoints = []
  526. # for _point in list_crosspoints:
  527. # cluster_crosspoints.append({"lines": _point.get("lines"), "points": [_point]})
  528. # while 1:
  529. # _find = False
  530. # new_cluster_crosspoints = []
  531. # for l_point in cluster_crosspoints:
  532. # _flag = False
  533. # for l_n_point in new_cluster_crosspoints:
  534. # line1 = l_point.get("lines")
  535. # line2 = l_n_point.get("lines")
  536. # if len(line1 & line2) > 0:
  537. # _find = True
  538. # _flag = True
  539. # l_n_point["lines"] = line1.union(line2)
  540. # l_n_point["points"].extend(l_point["points"])
  541. # if not _flag:
  542. # new_cluster_crosspoints.append({"lines": l_point.get("lines"), "points": l_point.get("points")})
  543. # cluster_crosspoints = new_cluster_crosspoints
  544. # if not _find:
  545. # break
  546. # # print(len(cluster_crosspoints))
  547. #
  548. # list_l_rect = []
  549. # for table_crosspoint in cluster_crosspoints:
  550. # list_rect = self.crosspoint2rect(table_crosspoint.get("points"))
  551. # list_l_rect.append(list_rect)
  552. #
  553. # return list_l_rect
  554. def crosspoint2rect(self, list_crosspoint, margin=10):
  555. dict_line_points = {}
  556. for _point in list_crosspoint:
  557. lines = list(_point.get("lines"))
  558. for _line in lines:
  559. if _line not in dict_line_points:
  560. dict_line_points[_line] = {"direct": None, "points": []}
  561. dict_line_points[_line]["points"].append(_point)
  562. # 排序
  563. for k, v in dict_line_points.items():
  564. list_x = []
  565. list_y = []
  566. for _p in v["points"]:
  567. list_x.append(_p.get("point")[0])
  568. list_y.append(_p.get("point")[1])
  569. if max(list_x) - min(list_x) > max(list_y) - min(list_y):
  570. v.get("points").sort(key=lambda x: x.get("point")[0])
  571. v["direct"] = "row"
  572. else:
  573. v.get("points").sort(key=lambda x: x.get("point")[1])
  574. v["direct"] = "column"
  575. list_rect = []
  576. for _point in list_crosspoint:
  577. if _point["buttom"] >= margin and _point["right"] >= margin:
  578. lines = list(_point.get("lines"))
  579. _line = lines[0]
  580. if dict_line_points[_line]["direct"] == "column":
  581. _line = lines[1]
  582. next_point = None
  583. for p1 in dict_line_points[_line]["points"]:
  584. if p1["buttom"] >= margin and p1["point"][0] > _point["point"][0]:
  585. next_point = p1
  586. break
  587. if not next_point:
  588. continue
  589. lines = list(next_point.get("lines"))
  590. _line = lines[0]
  591. if dict_line_points[_line]["direct"] == "row":
  592. _line = lines[1]
  593. final_point = None
  594. for p1 in dict_line_points[_line]["points"]:
  595. if p1["left"] >= margin and p1["point"][1] > next_point["point"][1]:
  596. final_point = p1
  597. break
  598. if not final_point:
  599. continue
  600. _r = LTRect(1,
  601. (_point["point"][0], _point["point"][1], final_point["point"][0], final_point["point"][1]))
  602. list_rect.append(_r)
  603. tmp_rect = []
  604. set_bbox = set()
  605. for _r in list_rect:
  606. _bbox = "%.2f-%.2f-%.2f-%.2f" % _r.bbox
  607. width = _r.bbox[2] - _r.bbox[0]
  608. height = _r.bbox[3] - _r.bbox[1]
  609. if width <= margin or height <= margin:
  610. continue
  611. if _bbox not in set_bbox:
  612. tmp_rect.append(_r)
  613. set_bbox.add(_bbox)
  614. list_rect = tmp_rect
  615. # _l = [x.get('point') for x in list_crosspoint]
  616. # _l.sort(key=lambda x: (x[0], x[1]))
  617. # print('list_crosspoint', _l)
  618. # print('list_rect', list_rect)
  619. # import cv2
  620. # import numpy as np
  621. # import random
  622. # img = np.zeros(shape=(1000,1000),dtype=np.uint8)
  623. # img += 255
  624. #
  625. # color = []
  626. # for rect in list_rect:
  627. # color += 10
  628. # x0,y0,x1,y1 = rect.bbox
  629. # x0 *= 10/18
  630. # y0 *= 10/18
  631. # x1 *= 10/18
  632. # y1 *= 10/18
  633. # print(rect.bbox)
  634. # cv2.rectangle(img, (int(x0),int(y0)),(int(x1),int(y1)), (color%255, (color+10)%255, (color+20)%255), 3)
  635. # cv2.imshow("bbox", img)
  636. # cv2.waitKey(0)
  637. return list_rect
  638. def cross_point(self, line1, line2, segment=True, margin=2):
  639. point_is_exist = False
  640. x = y = 0
  641. x1, y1, x2, y2 = line1
  642. x3, y3, x4, y4 = line2
  643. if (x2 - x1) == 0:
  644. k1 = None
  645. b1 = 0
  646. else:
  647. k1 = (y2 - y1) * 1.0 / (x2 - x1) # 计算k1,由于点均为整数,需要进行浮点数转化
  648. b1 = y1 * 1.0 - x1 * k1 * 1.0 # 整型转浮点型是关键
  649. if (x4 - x3) == 0: # L2直线斜率不存在
  650. k2 = None
  651. b2 = 0
  652. else:
  653. k2 = (y4 - y3) * 1.0 / (x4 - x3) # 斜率存在
  654. b2 = y3 * 1.0 - x3 * k2 * 1.0
  655. if k1 is None:
  656. if not k2 is None:
  657. x = x1
  658. y = k2 * x1 + b2
  659. point_is_exist = True
  660. elif k2 is None:
  661. x = x3
  662. y = k1 * x3 + b1
  663. elif not k2 == k1:
  664. x = (b2 - b1) * 1.0 / (k1 - k2)
  665. y = k1 * x * 1.0 + b1 * 1.0
  666. point_is_exist = True
  667. left = 0
  668. right = 0
  669. top = 0
  670. buttom = 0
  671. if point_is_exist:
  672. if segment:
  673. if x >= (min(x1, x2) - margin) and x <= (max(x1, x2) + margin) and y >= (
  674. min(y1, y2) - margin) and y <= (max(y1, y2) + margin):
  675. if x >= (min(x3, x4) - margin) and x <= (max(x3, x4) + margin) and y >= (
  676. min(y3, y4) - margin) and y <= (max(y3, y4) + margin):
  677. point_is_exist = True
  678. left = abs(min(x1, x3) - x)
  679. right = abs(max(x2, x4) - x)
  680. top = abs(min(y1, y3) - y)
  681. buttom = abs(max(y2, y4) - y)
  682. else:
  683. point_is_exist = False
  684. else:
  685. point_is_exist = False
  686. line1_key = "%.2f-%.2f-%.2f-%.2f" % (x1, y1, x2, y2)
  687. line2_key = "%.2f-%.2f-%.2f-%.2f" % (x3, y3, x4, y4)
  688. return point_is_exist, {"point": [x, y], "left": left, "right": right,
  689. "top": top, "buttom": buttom, "lines": set([line1_key, line2_key]),
  690. "p_lines": [line1, line2]}
  691. # def unionTable(self, list_table, fixspan=True, margin=2):
  692. # set_x = set()
  693. # set_y = set()
  694. #
  695. # list_cell = []
  696. # for _t in list_table:
  697. # for _line in _t:
  698. # list_cell.extend(_line)
  699. #
  700. # clusters_rects = []
  701. # # 根据y1聚类
  702. # set_id = set()
  703. # list_cell_dump = []
  704. # for _cell in list_cell:
  705. # _id = id(_cell)
  706. # if _id in set_id:
  707. # continue
  708. # set_id.add(_id)
  709. # list_cell_dump.append(_cell)
  710. # list_cell = list_cell_dump
  711. # list_cell.sort(key=lambda x: x.get("bbox")[3])
  712. # for _rect in list_cell:
  713. # _y0 = _rect.get("bbox")[3]
  714. # _find = False
  715. # for l_cr in clusters_rects:
  716. # if abs(l_cr[0].get("bbox")[3] - _y0) < 2:
  717. # _find = True
  718. # l_cr.append(_rect)
  719. # break
  720. # if not _find:
  721. # clusters_rects.append([_rect])
  722. #
  723. # clusters_rects.sort(key=lambda x: x[0].get("bbox")[3], reverse=True)
  724. # for l_cr in clusters_rects:
  725. # l_cr.sort(key=lambda x: x.get("bbox")[0])
  726. #
  727. # # print("=============:")
  728. # # for l_r in clusters_rects:
  729. # # print(len(l_r))
  730. #
  731. # for _line in clusters_rects:
  732. # for _rect in _line:
  733. # (x0, y0, x1, y1) = _rect.get("bbox")
  734. # set_x.add(x0)
  735. # set_x.add(x1)
  736. # set_y.add(y0)
  737. # set_y.add(y1)
  738. # if len(set_x) == 0 or len(set_y) == 0:
  739. # return
  740. # list_x = list(set_x)
  741. # list_y = list(set_y)
  742. #
  743. # list_x.sort(key=lambda x: x)
  744. # list_y.sort(key=lambda x: x, reverse=True)
  745. # _table = []
  746. # line_i = 0
  747. # for _line in clusters_rects:
  748. #
  749. # table_line = []
  750. # cell_i = 0
  751. # for _rect in _line:
  752. # (x0, y0, x1, y1) = _rect.get("bbox")
  753. # _cell = {"bbox": (x0, y0, x1, y1), "rect": _rect.get("rect"),
  754. # "rowspan": self.getspan(list_y, y0, y1, margin),
  755. # "columnspan": self.getspan(list_x, x0, x1, margin), "text": _rect.get("text", "")}
  756. # table_line.append(_cell)
  757. #
  758. # cell_i += 1
  759. # line_i += 1
  760. # _table.append(table_line)
  761. #
  762. # # print("=====================>>")
  763. # # for _line in _table:
  764. # # for _cell in _line:
  765. # # print(_cell,end="\t")
  766. # # print("\n")
  767. # # print("=====================>>")
  768. #
  769. # # print(_table)
  770. # if fixspan:
  771. # for _line in _table:
  772. # extend_line = []
  773. # for c_i in range(len(_line)):
  774. # _cell = _line[c_i]
  775. # if _cell.get("columnspan") > 1:
  776. # _cospan = _cell.get("columnspan")
  777. # _cell["columnspan"] = 1
  778. # for i in range(1, _cospan):
  779. # extend_line.append({"index": c_i + 1, "cell": _cell})
  780. # extend_line.sort(key=lambda x: x["index"], reverse=True)
  781. # for _el in extend_line:
  782. # _line.insert(_el["index"], _el["cell"])
  783. # for l_i in range(len(_table)):
  784. # _line = _table[l_i]
  785. # for c_i in range(len(_line)):
  786. # _cell = _line[c_i]
  787. # if _cell.get("rowspan") > 1:
  788. # _rospan = _cell.get("rowspan")
  789. # _cell["rowspan"] = 1
  790. # for i in range(1, _rospan):
  791. # _table[l_i + i].insert(c_i, _cell)
  792. #
  793. # table_bbox = (_table[0][0].get("bbox")[0], _table[0][0].get("bbox")[1], _table[-1][-1].get("bbox")[2],
  794. # _table[-1][-1].get("bbox")[3])
  795. #
  796. # ta = {"bbox": table_bbox, "table": _table}
  797. # return ta
  798. # 获取点阵
  799. def getSpanLocation(self, _list, x0, x1, margin):
  800. list_location = []
  801. (x0, x1) = (min(x0, x1), max(x0, x1))
  802. for _x in _list:
  803. if _x >= (x0 - margin) and _x <= (x1 + margin):
  804. list_location.append(_x)
  805. return list_location
  806. def fixSpan(self, _table, list_x, list_y, sourceP_LB):
  807. def checkPosition(_line, _position, bbox, margin=5):
  808. # check y
  809. if len(_line) > 0:
  810. _bbox = _line[0].get("bbox")
  811. # check if has lap
  812. if (min(_bbox[1], _bbox[3]) > max(bbox[1], bbox[3]) or max(_bbox[1], _bbox[3]) < min(bbox[1], bbox[3])):
  813. # if abs(min(_bbox[1],_bbox[3])-min(bbox[1],bbox[3]))>margin or abs(max(_bbox[1],_bbox[3])-max(bbox[1],bbox[3]))>margin:
  814. # print(_bbox)
  815. # print(bbox)
  816. # print("check position y false")
  817. return False
  818. # check x
  819. if _position <= len(_line) - 1:
  820. after_bbox = _line[_position].get("bbox")
  821. # the insert bbox.x1 should not less then the after bbox.x0
  822. if not (after_bbox[0] >= bbox[2]):
  823. # print("check position x after false")
  824. return False
  825. if _position - 1 > 0 and _position - 1 < len(_line):
  826. before_bbox = _line[_position - 1].get("bbox")
  827. # the insert bbox.x1 should less equal than the first bbox.x0
  828. if not (bbox[0] >= before_bbox[2]):
  829. # print("check position x before false")
  830. return False
  831. return True
  832. # 拓展columnspan的数据
  833. for _line in _table:
  834. c_i = 0
  835. while c_i < len(_line):
  836. _cell = _line[c_i]
  837. if _cell.get("columnspan") > 1:
  838. x0, y0, x1, y1 = _cell.get("bbox")
  839. _cospan = _cell.get("columnspan")
  840. locations = self.getSpanLocation(list_x, x0, x1, 10)
  841. if len(locations) == _cospan + 1:
  842. _cell["bbox"] = (x0, y0, locations[1], y1)
  843. _cell["columnspan"] = 1
  844. # len(locations)==_colspan+1
  845. for i in range(1, _cospan):
  846. n_cell = {}
  847. n_cell.update(_cell)
  848. n_cell["bbox"] = (locations[i], y0, locations[i + 1], y1)
  849. c_i += 1
  850. # check the position
  851. if checkPosition(_line, c_i, n_cell["bbox"]):
  852. _line.insert(c_i, n_cell)
  853. c_i += 1
  854. # 拓展rowspan的数据
  855. for l_i in range(len(_table)):
  856. _line = _table[l_i]
  857. c_i = 0
  858. while c_i < len(_line):
  859. _cell = _line[c_i]
  860. if _cell.get("rowspan") > 1:
  861. x0, y0, x1, y1 = _cell.get("bbox")
  862. _rospan = _cell.get("rowspan")
  863. locations = self.getSpanLocation(list_y, y0, y1, 10)
  864. if len(locations) == _rospan + 1:
  865. _cell["bbox"] = (x0, y0, x1, locations[1])
  866. _cell["rowspan"] = 1
  867. for i in range(1, _rospan):
  868. n_cell = {}
  869. n_cell.update(_cell)
  870. if l_i + i <= len(_table) - 1:
  871. # print(len(_table),l_i+i)
  872. n_cell["bbox"] = (x0, locations[i], x1, locations[i + 1])
  873. if checkPosition(_table[l_i + i], c_i, n_cell["bbox"]):
  874. _table[l_i + i].insert(c_i, n_cell)
  875. c_i += 1
  876. def fixRect(self, _table, list_x, list_y, sourceP_LB, margin):
  877. self.fixSpan(_table, list_x, list_y, sourceP_LB)
  878. # for line_i in range(len(_table)):
  879. # for cell_i in range(len(_table[line_i])):
  880. # _cell = _table[line_i][cell_i]
  881. # print(line_i,cell_i,_cell["bbox"],_cell["text"])
  882. for _line in _table:
  883. extend_line = []
  884. for c_i in range(len(_line)):
  885. c_cell = _line[c_i]
  886. # first cell missing
  887. if c_i == 0 and c_cell["bbox"][0] != list_x[0]:
  888. _bbox = (list_x[0], c_cell["bbox"][1], c_cell["bbox"][0], c_cell["bbox"][3])
  889. _cell = {"bbox": _bbox,
  890. "rect": LTRect(1, _bbox),
  891. "rowspan": self.getspan(list_y, _bbox[1], _bbox[3], margin),
  892. "columnspan": self.getspan(list_x, _bbox[0], _bbox[2], margin),
  893. "text": ""}
  894. extend_line.append({"index": c_i, "cell": _cell})
  895. # cell in the median missing
  896. if c_i < len(_line) - 1:
  897. n_cell = _line[c_i + 1]
  898. _bbox = c_cell["bbox"]
  899. n_bbox = n_cell["bbox"]
  900. if _bbox[0] == n_bbox[0] and _bbox[2] == n_bbox[2]:
  901. continue
  902. else:
  903. if abs(_bbox[2] - n_bbox[0]) > margin:
  904. _bbox = (_bbox[2], _bbox[1], n_bbox[0], _bbox[3])
  905. _cell = {"bbox": _bbox,
  906. "rect": LTRect(1, _bbox),
  907. "rowspan": self.getspan(list_y, _bbox[1], _bbox[3], margin),
  908. "columnspan": self.getspan(list_x, _bbox[0], _bbox[2], margin),
  909. "text": ""}
  910. extend_line.append({"index": c_i + 1, "cell": _cell})
  911. # last cell missing
  912. if c_i == len(_line) - 1:
  913. if abs(c_cell["bbox"][2] - list_x[-1]) > margin:
  914. _bbox = (c_cell["bbox"][2], c_cell["bbox"][1], list_x[-1], c_cell["bbox"][3])
  915. _cell = {"bbox": _bbox,
  916. "rect": LTRect(1, _bbox),
  917. "rowspan": self.getspan(list_y, _bbox[1], _bbox[3], margin),
  918. "columnspan": self.getspan(list_x, _bbox[0], _bbox[2], margin),
  919. "text": ""}
  920. extend_line.append({"index": c_i + 1, "cell": _cell})
  921. extend_line.sort(key=lambda x: x["index"], reverse=True)
  922. for _tmp in extend_line:
  923. _line.insert(_tmp["index"], _tmp["cell"])
  924. def feedText2table(self, _table, list_textbox, in_objs, sourceP_LB):
  925. # find the suitable cell of the textbox
  926. list_cells = []
  927. for table_line in _table:
  928. for _cell in table_line:
  929. list_cells.append({"cell": _cell, "inbox_textbox_list": []})
  930. self.connect_bbox_list = []
  931. for textbox in list_textbox:
  932. list_iou = []
  933. for _d in list_cells:
  934. _cell = _d["cell"]
  935. _iou = self.getIOU(textbox.bbox, _cell["bbox"])
  936. list_iou.append(_iou)
  937. max_iou_index = np.argmax(list_iou)
  938. max_iou = list_iou[max_iou_index]
  939. if max_iou > 0.1 and textbox not in in_objs:
  940. list_cells[max_iou_index]["inbox_textbox_list"].append(textbox)
  941. in_objs.add(textbox)
  942. if not self.from_pdf and not self.splited:
  943. # 多个iou大于0.3的,可能是ocr将两个文本合成一个了
  944. iou_index_list = np.where(np.array(list_iou) >= 0.3)[0].tolist()
  945. if len(iou_index_list) >= 2:
  946. print('len(iou_index_list) >= 2 textbox', textbox)
  947. self.connect_bbox_list.append(textbox)
  948. has_matched_box_list = []
  949. for _d in list_cells:
  950. _cell = _d["cell"]
  951. inbox_textbox_list = _d["inbox_textbox_list"]
  952. # 分行,根据y重合
  953. all_match_box_list = []
  954. inbox_textbox_list.sort(key=lambda x: x.bbox[1], reverse=sourceP_LB)
  955. for i in range(len(inbox_textbox_list)):
  956. match_box_list = []
  957. box1 = inbox_textbox_list[i]
  958. if box1 in has_matched_box_list:
  959. continue
  960. min_y1 = box1.bbox[1] + 1 / 3 * abs(box1.bbox[3] - box1.bbox[1])
  961. max_y1 = box1.bbox[3] - 1 / 3 * abs(box1.bbox[3] - box1.bbox[1])
  962. match_box_list.append(
  963. [box1.get_text(), box1.bbox[0], box1.bbox[1], box1.bbox[2], box1.bbox[3], min_y1, max_y1])
  964. has_matched_box_list.append(box1)
  965. for j in range(i + 1, len(inbox_textbox_list)):
  966. box2 = inbox_textbox_list[j]
  967. if box2 in has_matched_box_list:
  968. continue
  969. # print(min_y1, box2.bbox[1], box2.bbox[3], max_y1)
  970. # print(min_y2, box1.bbox[3], max_y2)
  971. if min_y1 <= box2.bbox[1] <= max_y1 or \
  972. min_y1 <= box2.bbox[3] <= max_y1 or \
  973. box2.bbox[1] <= min_y1 <= max_y1 <= box2.bbox[3]:
  974. match_box_list.append(
  975. [box2.get_text(), box2.bbox[0], box2.bbox[1], box2.bbox[2], box2.bbox[3], min_y1, max_y1])
  976. has_matched_box_list.append(box2)
  977. match_box_list.sort(key=lambda x: x[1])
  978. all_match_box_list.append(match_box_list)
  979. # print("match_box_list", all_match_box_list)
  980. all_match_box_list.sort(key=lambda x: (round(x[0][2] + x[0][4]) / 2, 0), reverse=sourceP_LB)
  981. for box_list in all_match_box_list:
  982. for box in box_list:
  983. _cell["text"] += re.sub("\s", '', box[0])
  984. def makeTableByRect(self, list_rect, margin, sourceP_LB):
  985. _table = []
  986. set_x = set()
  987. set_y = set()
  988. clusters_rects = []
  989. # 根据y1聚类
  990. if sourceP_LB:
  991. list_rect.sort(key=lambda x: x.bbox[3])
  992. for _rect in list_rect:
  993. _y0 = _rect.bbox[3]
  994. _y1 = _rect.bbox[1]
  995. _find = False
  996. for l_cr in clusters_rects:
  997. if abs(l_cr[0].bbox[3] - _y0) < margin:
  998. _find = True
  999. l_cr.append(_rect)
  1000. break
  1001. if not _find:
  1002. clusters_rects.append([_rect])
  1003. else:
  1004. list_rect.sort(key=lambda x: x.bbox[1])
  1005. for _rect in list_rect:
  1006. _y0 = _rect.bbox[1]
  1007. _y1 = _rect.bbox[3]
  1008. _find = False
  1009. for l_cr in clusters_rects:
  1010. if abs(l_cr[0].bbox[1] - _y0) < margin:
  1011. _find = True
  1012. l_cr.append(_rect)
  1013. break
  1014. if not _find:
  1015. clusters_rects.append([_rect])
  1016. # print("textbox:===================")
  1017. # for _textbox in list_textbox:
  1018. # print(_textbox.get_text())
  1019. # print("textbox:======>>>>>>>>>>>>>")
  1020. # for c in clusters_rects:
  1021. # print("+"*30)
  1022. # for cc in c:
  1023. # print("rect", cc.)
  1024. # cul spans
  1025. for _line in clusters_rects:
  1026. for _rect in _line:
  1027. (x0, y0, x1, y1) = _rect.bbox
  1028. set_x.add(x0)
  1029. set_x.add(x1)
  1030. set_y.add(y0)
  1031. set_y.add(y1)
  1032. if len(set_x) == 0 or len(set_y) == 0:
  1033. return None, [], []
  1034. if len(list_rect) <= 1:
  1035. return None, [], []
  1036. list_x = list(set_x)
  1037. list_y = list(set_y)
  1038. list_x.sort(key=lambda x: x)
  1039. list_y.sort(key=lambda x: x, reverse=sourceP_LB)
  1040. # print("clusters_rects", len(clusters_rects))
  1041. if sourceP_LB:
  1042. clusters_rects.sort(key=lambda x: (x[0].bbox[1] + x[0].bbox[3]) / 2, reverse=sourceP_LB)
  1043. clusters_rects.sort(key=lambda x: (x[0].bbox[1] + x[0].bbox[3]) / 2, reverse=sourceP_LB)
  1044. for l_cr in clusters_rects:
  1045. l_cr.sort(key=lambda x: x.bbox[0])
  1046. pop_x = []
  1047. for i in range(len(list_x) - 1):
  1048. _i = len(list_x) - i - 1
  1049. l_i = _i - 1
  1050. if abs(list_x[_i] - list_x[l_i]) < 5:
  1051. pop_x.append(_i)
  1052. pop_x.sort(key=lambda x: x, reverse=True)
  1053. for _x in pop_x:
  1054. list_x.pop(_x)
  1055. #
  1056. pop_x = []
  1057. for i in range(len(list_y) - 1):
  1058. _i = len(list_y) - i - 1
  1059. l_i = _i - 1
  1060. if abs(list_y[_i] - list_y[l_i]) < 5:
  1061. pop_x.append(_i)
  1062. pop_x.sort(key=lambda x: x, reverse=True)
  1063. for _x in pop_x:
  1064. list_y.pop(_x)
  1065. # print("list_x", list_x)
  1066. # print("list_y", list_y)
  1067. line_i = 0
  1068. for _line in clusters_rects:
  1069. table_line = []
  1070. cell_i = 0
  1071. for _rect in _line:
  1072. (x0, y0, x1, y1) = _rect.bbox
  1073. _cell = {"bbox": (x0, y0, x1, y1),
  1074. "rect": _rect,
  1075. "rowspan": self.getspan(list_y, y0, y1, margin),
  1076. "columnspan": self.getspan(list_x, x0, x1, margin),
  1077. "text": ""}
  1078. cell_i += 1
  1079. table_line.append(_cell)
  1080. line_i += 1
  1081. _table.append(table_line)
  1082. return _table, list_x, list_y
  1083. def rect2table(self, list_textbox, list_rect, in_objs, margin=5, sourceP_LB=True):
  1084. def getIOU(bbox0, bbox1):
  1085. width = max(bbox0[2], bbox1[2]) - min(bbox0[0], bbox1[0]) - (bbox0[2] - bbox0[0] + bbox1[2] - bbox1[0])
  1086. height = max(bbox0[3], bbox1[3]) - min(bbox0[1], bbox1[1]) - (bbox0[3] - bbox0[1] + bbox1[3] - bbox1[1])
  1087. if width < 0 and height < 0:
  1088. return abs(width * height / min(abs((bbox0[2] - bbox0[0]) * (bbox0[3] - bbox0[1])),
  1089. abs((bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]))))
  1090. return 0
  1091. _table, list_x, list_y = self.makeTableByRect(list_rect, margin, sourceP_LB)
  1092. if _table is None:
  1093. return
  1094. self.feedText2table(_table, list_textbox, in_objs, sourceP_LB)
  1095. # print("table===========================>")
  1096. # for _line in _table:
  1097. # for _cell in _line:
  1098. # print("||%d%d"%(_cell["rowspan"],_cell["columnspan"]),end="\t")
  1099. # print()
  1100. # print("table===========================>")
  1101. #
  1102. # print("------------")
  1103. # for _line in _table:
  1104. # for _cell in _line:
  1105. # print(_cell["text"],end="\t")
  1106. # print("\n")
  1107. # print("------------")
  1108. self.fixRect(_table, list_x, list_y, sourceP_LB, margin)
  1109. # print("table===========================>")
  1110. # for _line in _table:
  1111. # for _cell in _line:
  1112. # print("||%d%d"%(_cell["rowspan"],_cell["columnspan"]),end="\t")
  1113. # print()
  1114. # print("table===========================>")
  1115. self.feedText2table(_table, list_textbox, in_objs, sourceP_LB)
  1116. # feedText2table后,有textbox符合多个单元格iou的,可能是文本错误连接了,需拆开
  1117. if self.connect_bbox_list:
  1118. return {}
  1119. table_bbox = (_table[0][0].get("bbox")[0],
  1120. _table[0][0].get("bbox")[1],
  1121. _table[-1][-1].get("bbox")[2],
  1122. _table[-1][-1].get("bbox")[3])
  1123. # print("=======")
  1124. # for _line in _table:
  1125. # for _cell in _line:
  1126. # print(_cell["text"])
  1127. # print("\n")
  1128. # print("===========")
  1129. ta = {"bbox": table_bbox, "table": _table}
  1130. return ta
  1131. def inbox(self, bbox0, bbox_g, text=""):
  1132. # if bbox_g[0]<=bbox0[0] and bbox_g[1]<=bbox0[1] and bbox_g[2]>=bbox0[2] and bbox_g[3]>=bbox0[3]:
  1133. # return 1
  1134. # print("utils inbox", text, self.getIOU(bbox0,bbox_g), bbox0, bbox_g)
  1135. if self.getIOU(bbox0, bbox_g) > 0.2:
  1136. return 1
  1137. return 0
  1138. def getIOU(self, bbox0, bbox1):
  1139. width = abs(max(bbox0[2], bbox1[2]) - min(bbox0[0], bbox1[0])) - (
  1140. abs(bbox0[2] - bbox0[0]) + abs(bbox1[2] - bbox1[0]))
  1141. height = abs(max(bbox0[3], bbox1[3]) - min(bbox0[1], bbox1[1])) - (
  1142. abs(bbox0[3] - bbox0[1]) + abs(bbox1[3] - bbox1[1]))
  1143. if width < 0 and height < 0:
  1144. iou = abs(width * height / min(abs((bbox0[2] - bbox0[0]) * (bbox0[3] - bbox0[1])),
  1145. abs((bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]))))
  1146. # print("getIOU", iou)
  1147. return iou
  1148. return 0
  1149. def getspan(self, _list, x0, x1, margin):
  1150. _count = 0
  1151. (x0, x1) = (min(x0, x1), max(x0, x1))
  1152. for _x in _list:
  1153. if _x >= (x0 - margin) and _x <= (x1 + margin):
  1154. _count += 1
  1155. return _count - 1
  1156. def _plot(self, list_line, list_textbox):
  1157. from matplotlib import pyplot as plt
  1158. plt.figure()
  1159. for _line in list_line:
  1160. x0, y0, x1, y1 = _line.__dict__.get("bbox")
  1161. plt.plot([x0, x1], [y0, y1])
  1162. for _line in list_line:
  1163. x0, y0, x1, y1 = _line.bbox
  1164. plt.plot([x0, x1], [y0, y1])
  1165. # for point in list_crosspoints:
  1166. # plt.scatter(point.get("point")[0],point.get("point")[1])
  1167. for textbox in list_textbox:
  1168. x0, y0, x1, y1 = textbox.bbox
  1169. plt.plot([x0, x1], [y0, y1])
  1170. plt.show()
  1171. def get_table_html(table):
  1172. html_text = '<table border="1">'
  1173. for row in table:
  1174. html_text += "<tr>"
  1175. for col in row:
  1176. row_span = col.get("rowspan")
  1177. col_span = col.get("columnspan")
  1178. bbox_text = col.get("text")
  1179. html_text += "<td colspan=" + str(col_span) + " rowspan=" + str(row_span) + ">"
  1180. html_text += bbox_text + "</td>"
  1181. html_text += "</tr>"
  1182. html_text += "</table>"
  1183. return html_text
  1184. def sort_object(obj_list, is_reverse=False):
  1185. from format_convert.convert_tree import _Table, _Image, _Sentence, _Page
  1186. obj_list = combine_object(obj_list)
  1187. if len(obj_list) == 0:
  1188. return obj_list
  1189. if isinstance(obj_list[0], (_Table, _Sentence, _Image)):
  1190. obj_list.sort(key=lambda x: (x.y, x.x), reverse=is_reverse)
  1191. return obj_list
  1192. elif isinstance(obj_list[0], _Page):
  1193. obj_list.sort(key=lambda x: x.page_no)
  1194. return obj_list
  1195. else:
  1196. return obj_list
  1197. def combine_object(obj_list, threshold=5):
  1198. from format_convert.convert_tree import _Sentence
  1199. sentence_list = []
  1200. for obj in obj_list:
  1201. if isinstance(obj, _Sentence) and not obj.is_html:
  1202. obj.content = re.sub("\s", "", obj.content)
  1203. sentence_list.append(obj)
  1204. sentence_list.sort(key=lambda x: (x.y, x.x))
  1205. for sen in sentence_list:
  1206. obj_list.remove(sen)
  1207. delete_list = []
  1208. for i in range(1, len(sentence_list)):
  1209. sen1 = sentence_list[i - 1]
  1210. sen2 = sentence_list[i]
  1211. if sen1.combine is False or sen2.combine is False:
  1212. continue
  1213. if abs(sen2.y - sen1.y) <= threshold:
  1214. if sen2.x > sen1.x:
  1215. sen2.x = sen1.x
  1216. sen2.content = sen1.content + sen2.content
  1217. else:
  1218. sen2.content = sen2.content + sen1.content
  1219. if sen2.y > sen1.y:
  1220. sen2.y = sen1.y
  1221. delete_list.append(sen1)
  1222. for sen in delete_list:
  1223. sentence_list.remove(sen)
  1224. for sen in sentence_list:
  1225. obj_list.append(sen)
  1226. return obj_list
  1227. session_ocr = requests.Session()
  1228. session_otr = requests.Session()
  1229. session_all = requests.Session()
  1230. def request_post(url, param, time_out=1000, use_zlib=False):
  1231. fails = 0
  1232. text = json.dumps([-2])
  1233. while True:
  1234. try:
  1235. if fails >= 1:
  1236. break
  1237. headers = {'content-type': 'application/json'}
  1238. # result = requests.post(url, data=param, timeout=time_out)
  1239. if param.get("model_type") == "ocr":
  1240. result = session_ocr.post(url, data=param, timeout=time_out)
  1241. elif param.get("model_type") == "otr":
  1242. result = session_otr.post(url, data=param, timeout=time_out)
  1243. else:
  1244. result = session_all.post(url, data=param, timeout=time_out)
  1245. # print('result.status_code', result.status_code)
  1246. # print('result.text', result.text)
  1247. if result.status_code == 200:
  1248. text = result.text
  1249. break
  1250. else:
  1251. # print('result.status_code', result.status_code)
  1252. # print('result.text', result.text)
  1253. fails += 1
  1254. continue
  1255. except socket.timeout:
  1256. fails += 1
  1257. # print('timeout! fail times:', fails)
  1258. except:
  1259. fails += 1
  1260. # print('fail! fail times:', fails)
  1261. traceback.print_exc()
  1262. return text
  1263. def test_gpu():
  1264. print("=" * 30)
  1265. import paddle
  1266. paddle.utils.run_check()
  1267. # import tensorflow as tf
  1268. # print("tf gpu", tf.config.list_physical_devices('GPU'))
  1269. print("=" * 30)
  1270. def my_subprocess_call(*popenargs, timeout=None):
  1271. logging.info("into my_subprocess_call")
  1272. with Popen(*popenargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
  1273. try:
  1274. for line in p.stdout:
  1275. print("stdout", line)
  1276. for line in p.stderr:
  1277. print("stderr", line)
  1278. p.wait(timeout=timeout)
  1279. # p.communicate()
  1280. return p.pid, p.returncode
  1281. except: # Including KeyboardInterrupt, wait handled that.
  1282. p.kill()
  1283. # We don't call p.wait() again as p.__exit__ does that for us.
  1284. raise
  1285. finally:
  1286. logging.info("out my_subprocess_call")
  1287. p.kill()
  1288. def parse_yaml():
  1289. yaml_path = os.path.dirname(os.path.abspath(__file__)) + "/interface.yml"
  1290. with open(yaml_path, "r", encoding='utf-8') as f:
  1291. cfg = f.read()
  1292. params = yaml.load(cfg, Loader=yaml.SafeLoader)
  1293. return params
  1294. def get_ip_port(node_type=None, interface_type=None):
  1295. if node_type is None:
  1296. node_type_list = ["master", "slave"]
  1297. else:
  1298. node_type_list = [node_type]
  1299. if interface_type is None:
  1300. interface_type_list = ["convert", "ocr", "otr", "office", "path", "isr", "idc", "atc", "yolo"]
  1301. else:
  1302. interface_type_list = [interface_type]
  1303. ip_port_dict = {}
  1304. params = parse_yaml()
  1305. # 循环 master slave
  1306. for type1 in node_type_list:
  1307. node_type = type1.upper()
  1308. ip_list = params.get(node_type).get("ip")
  1309. # 循环多个IP
  1310. for j in range(len(ip_list)):
  1311. _ip = ip_list[j]
  1312. if ip_port_dict.get(_ip):
  1313. ip_port_dict.get(_ip).update({node_type: {}})
  1314. else:
  1315. ip_port_dict.update({_ip: {node_type: {}}})
  1316. # 有IP时,循环多个参数
  1317. for type2 in interface_type_list:
  1318. python_path = None
  1319. project_path = None
  1320. gunicorn_path = None
  1321. processes = 0
  1322. port_list = []
  1323. interface_type = type2.upper()
  1324. # if interface_type in ["convert".upper()]:
  1325. # _port = params.get(node_type).get(interface_type).get("port")
  1326. # if _port is None:
  1327. # port_list = []
  1328. # else:
  1329. # if interface_type == "convert".upper():
  1330. # processes = params.get(node_type).get(interface_type).get("processes")[j]
  1331. # port_list = [str(_port[j])]*int(processes)
  1332. # # port_list = [str(_port)]
  1333. if interface_type == "path".upper():
  1334. python_path = params.get(node_type).get(interface_type).get("python")[j]
  1335. project_path = params.get(node_type).get(interface_type).get("project")[j]
  1336. gunicorn_path = params.get(node_type).get(interface_type).get("gunicorn")[j]
  1337. else:
  1338. port_start = params.get(node_type).get(interface_type).get("port_start")
  1339. port_no = params.get(node_type).get(interface_type).get("port_no")
  1340. if port_start is None or port_no is None:
  1341. port_list = []
  1342. else:
  1343. if interface_type in ["office".upper()]:
  1344. port_list = [str(x) for x in range(port_start[j], port_start[j] + port_no[j], 1)]
  1345. else:
  1346. port_list = [str(port_start[j])] * port_no[j]
  1347. # if ip_list:
  1348. # for i in range(len(ip_list)):
  1349. # 参数放入dict
  1350. if port_list:
  1351. ip_port_dict.get(_ip).get(node_type).update({interface_type.lower(): port_list})
  1352. if processes:
  1353. ip_port_dict.get(_ip).get(node_type).update({interface_type.lower() + "_processes": processes})
  1354. if project_path and python_path and gunicorn_path:
  1355. ip_port_dict.get(_ip).get(node_type).update({"project_path": project_path,
  1356. "python_path": python_path,
  1357. "gunicorn_path": gunicorn_path})
  1358. # print("ip_port_dict", ip_port_dict)
  1359. return ip_port_dict
  1360. def get_ip_port_old(node_type=None, interface_type=None):
  1361. if node_type is None:
  1362. node_type_list = ["master", "slave"]
  1363. else:
  1364. node_type_list = [node_type]
  1365. if interface_type is None:
  1366. interface_type_list = ["convert", "ocr", "otr", "office", "path"]
  1367. else:
  1368. interface_type_list = [interface_type]
  1369. ip_port_dict = {}
  1370. params = parse_yaml()
  1371. for type1 in node_type_list:
  1372. node_type = type1.upper()
  1373. ip_list = params.get(node_type).get("ip")
  1374. for type2 in interface_type_list:
  1375. interface_type = type2.upper()
  1376. processes = 0
  1377. python_path = None
  1378. project_path = None
  1379. if interface_type in ["convert".upper()]:
  1380. _port = params.get(node_type).get(interface_type).get("port")
  1381. if _port is None:
  1382. port_list = []
  1383. else:
  1384. if interface_type == "convert".upper():
  1385. processes = params.get(node_type).get(interface_type).get("processes")
  1386. port_list = [str(_port)] * int(processes)
  1387. # port_list = [str(_port)]
  1388. elif interface_type == "path".upper():
  1389. python_path = params.get(node_type).get(interface_type).get("python")
  1390. project_path = params.get(node_type).get(interface_type).get("project")
  1391. else:
  1392. port_start = params.get(node_type).get(interface_type).get("port_start")
  1393. port_no = params.get(node_type).get(interface_type).get("port_no")
  1394. if port_start is None or port_no is None:
  1395. port_list = []
  1396. else:
  1397. port_list = [str(x) for x in range(port_start, port_start + port_no, 1)]
  1398. if ip_list:
  1399. for _ip in ip_list:
  1400. if _ip is None:
  1401. continue
  1402. if _ip in ip_port_dict.keys():
  1403. if port_list:
  1404. ip_port_dict.get(_ip).update({interface_type.lower(): port_list})
  1405. else:
  1406. if port_list:
  1407. ip_port_dict[_ip] = {interface_type.lower(): port_list}
  1408. if processes:
  1409. ip_port_dict.get(_ip).update({interface_type.lower() + "_processes": processes})
  1410. if project_path and python_path:
  1411. ip_port_dict.get(_ip).update({"project_path": project_path,
  1412. "python_path": python_path})
  1413. return ip_port_dict
  1414. def get_intranet_ip():
  1415. try:
  1416. # Create a new socket using the given address family,
  1417. # socket type and protocol number.
  1418. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1419. # Connect to a remote socket at address.
  1420. # (The format of address depends on the address family.)
  1421. address = ("8.8.8.8", 80)
  1422. s.connect(address)
  1423. # Return the socket’s own address.
  1424. # This is useful to find out the port number of an IPv4/v6 socket, for instance.
  1425. # (The format of the address returned depends on the address family.)
  1426. sockname = s.getsockname()
  1427. ip = sockname[0]
  1428. port = sockname[1]
  1429. finally:
  1430. s.close()
  1431. return ip
  1432. def get_all_ip():
  1433. if get_platform() == "Windows":
  1434. ips = ['127.0.0.1']
  1435. else:
  1436. ips = [ip.split('/')[0] for ip in os.popen("ip addr | grep 'inet '|awk '{print $2}'").readlines()]
  1437. for i in range(len(ips)):
  1438. ips[i] = "http://" + ips[i]
  1439. return ips
  1440. def get_using_ip():
  1441. ip_port_dict = get_ip_port()
  1442. ips = get_all_ip()
  1443. ip = "http://127.0.0.1"
  1444. for key in ip_port_dict.keys():
  1445. if key in ips:
  1446. ip = key
  1447. break
  1448. return ip
  1449. def memory_decorator(func):
  1450. @wraps(func)
  1451. def get_memory_info(*args, **kwargs):
  1452. if get_platform() == "Windows":
  1453. return func(*args, **kwargs)
  1454. # 只有linux有resource包
  1455. # usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
  1456. usage = psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024
  1457. start_time = time.time()
  1458. logging.info("----- memory info start - " + func.__qualname__
  1459. + " - " + str(os.getpid())
  1460. + " - " + str(round(usage, 2)) + " GB"
  1461. + " - " + str(round(time.time() - start_time, 2)) + " sec")
  1462. result = func(*args, **kwargs)
  1463. # usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
  1464. usage = psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024
  1465. logging.info("----- memory info end - " + func.__qualname__
  1466. + " - " + str(os.getpid())
  1467. + " - " + str(round(usage, 2)) + " GB"
  1468. + " - " + str(round(time.time() - start_time, 2)) + " sec")
  1469. return result
  1470. return get_memory_info
  1471. def log(msg):
  1472. call_func_name = inspect.currentframe().f_back.f_code.co_name
  1473. logger = get_logger(call_func_name, {"md5": _global.get("md5"),
  1474. "port": _global.get("port")})
  1475. logger.info(msg)
  1476. # logging.info(msg)
  1477. def get_logger(_name, _dict):
  1478. extra = _dict
  1479. _format = '%(asctime)s - %(name)s - %(levelname)s - %(md5)s - %(port)s - %(message)s'
  1480. logger = logging.getLogger(_name)
  1481. create_new_flag = 1
  1482. handlers = logger.handlers
  1483. if handlers:
  1484. for h in handlers:
  1485. if h.formatter.__dict__.get("_fmt") == _format:
  1486. create_new_flag = 0
  1487. break
  1488. if create_new_flag:
  1489. formatter = logging.Formatter(_format)
  1490. handler = logging.StreamHandler()
  1491. handler.setFormatter(formatter)
  1492. logger.addHandler(handler)
  1493. logger.setLevel(logging.INFO)
  1494. logger.propagate = False
  1495. logger = logging.LoggerAdapter(logger, extra)
  1496. return logger
  1497. def set_flask_global():
  1498. # 接口轮询所需锁、参数
  1499. ip_port_flag = {}
  1500. # ip_flag = []
  1501. ip_port_dict = get_ip_port()
  1502. for _k in ip_port_dict.keys():
  1503. ip_port_flag.update({_k: {}})
  1504. for interface in ["ocr", "otr", "convert", "idc", "isr", "atc", 'yolo', "office"]:
  1505. if ip_port_dict.get(_k).get("MASTER"):
  1506. if ip_port_dict.get(_k).get("MASTER").get(interface):
  1507. ip_port_flag[_k][interface] = 0
  1508. else:
  1509. if ip_port_dict.get(_k).get("SLAVE").get(interface):
  1510. ip_port_flag[_k][interface] = 0
  1511. # ip_port_flag.update({_k: {"ocr": 0,
  1512. # "otr": 0,
  1513. # "convert": 0,
  1514. # "idc": 0,
  1515. # "isr": 0,
  1516. # "office": 0
  1517. # }})
  1518. # if ip_port_dict.get(_k).get("MASTER"):
  1519. # ip_flag.append([_k+"_master", 0])
  1520. # if ip_port_dict.get(_k).get("SLAVE"):
  1521. # ip_flag.append([_k+"_slave", 0])
  1522. _global.update({"ip_port_flag": ip_port_flag})
  1523. _global.update({"ip_port": ip_port_dict})
  1524. # _global.update({"ip_flag": ip_flag})
  1525. # print(globals().get("ip_port"))
  1526. def get_md5_from_bytes(_bytes):
  1527. def generate_fp(_b):
  1528. bio = BytesIO()
  1529. bio.write(_b)
  1530. return bio
  1531. _length = 0
  1532. try:
  1533. _md5 = hashlib.md5()
  1534. ff = generate_fp(_bytes)
  1535. ff.seek(0)
  1536. while True:
  1537. data = ff.read(4096)
  1538. if not data:
  1539. break
  1540. _length += len(data)
  1541. _md5.update(data)
  1542. return _md5.hexdigest(), _length
  1543. except Exception as e:
  1544. traceback.print_exc()
  1545. return None, _length
  1546. # def to_share_memory(np_data, name=None):
  1547. # # from multiprocessing.resource_tracker import unregister
  1548. # from multiprocessing import shared_memory
  1549. # if name is None:
  1550. # sm_name = "psm_" + str(os.getpid())
  1551. # else:
  1552. # sm_name = name
  1553. # logging.info("into from_share_memory sm_name " + sm_name)
  1554. # shm = shared_memory.SharedMemory(name=sm_name, create=True, size=np_data.nbytes)
  1555. # # unregister(sm_name, 'shared_memory')
  1556. # sm_data = np.ndarray(np_data.shape, dtype=np_data.dtype, buffer=shm.buf)
  1557. # sm_data[:] = np_data[:] # Copy the original data into shared memory
  1558. #
  1559. # shm.close()
  1560. # del sm_data
  1561. # return shm
  1562. # def from_share_memory(sm_name, _shape, _dtype, if_close=True):
  1563. # from multiprocessing import shared_memory
  1564. # logging.info("into from_share_memory sm_name " + sm_name)
  1565. # shm = shared_memory.SharedMemory(name=sm_name, create=False)
  1566. # b = np.ndarray(_shape, dtype=_dtype, buffer=shm.buf)
  1567. # sm_data = copy.deepcopy(b)
  1568. # b[::] = 0
  1569. #
  1570. # if if_close:
  1571. # try:
  1572. # shm.close()
  1573. # shm.unlink()
  1574. # except Exception:
  1575. # log("file not found! " + sm_name)
  1576. # return sm_data
  1577. # def get_share_memory(sm_name):
  1578. # try:
  1579. # from multiprocessing import shared_memory
  1580. # shm = shared_memory.SharedMemory(name=sm_name, create=False)
  1581. # return shm
  1582. # except:
  1583. # return None
  1584. # def release_share_memory(shm):
  1585. # try:
  1586. # if shm is None:
  1587. # return
  1588. # shm.close()
  1589. # shm.unlink()
  1590. # log(str(shm.name) + " release successfully!")
  1591. # except FileNotFoundError:
  1592. # log(str(shm.name) + " has released!")
  1593. # except Exception as e:
  1594. # traceback.print_exc()
  1595. # def get_share_memory_list(sm_list_name, list_size=None):
  1596. # # from multiprocessing.resource_tracker import unregister
  1597. # from multiprocessing import shared_memory
  1598. # if list_size is None:
  1599. # sm_list = shared_memory.ShareableList(name=sm_list_name)
  1600. # else:
  1601. # sm_list = shared_memory.ShareableList(name=sm_list_name, sequence=["0"]+[' '*2048]*(list_size-2)+["0"])
  1602. # # unregister(sm_list_name, 'shared_memory')
  1603. # return sm_list
  1604. # def close_share_memory_list(sm_list):
  1605. # try:
  1606. # sm_list.shm.close()
  1607. # except Exception:
  1608. # traceback.print_exc()
  1609. def get_np_type(_str):
  1610. _dtype = None
  1611. if _str == 'uint8':
  1612. _dtype = np.uint8
  1613. elif _str == 'float16':
  1614. _dtype = np.float16
  1615. elif _str == 'float32':
  1616. _dtype = np.float32
  1617. logging.info("get_np_type " + _str + " " + str(_dtype))
  1618. return _dtype
  1619. def namespace_to_dict(agrs_or_dict, reverse=False):
  1620. if reverse:
  1621. agrs_or_dict = argparse.Namespace(**agrs_or_dict)
  1622. else:
  1623. agrs_or_dict = vars(agrs_or_dict)
  1624. return agrs_or_dict
  1625. def get_args_from_config(ip_port_dict, ip, arg_type, node_type=None):
  1626. if node_type is None:
  1627. node_type = ["MASTER", "SLAVE"]
  1628. else:
  1629. node_type = [node_type]
  1630. arg_list = []
  1631. for _type in node_type:
  1632. if ip_port_dict.get(ip).get(_type):
  1633. if ip_port_dict.get(ip).get(_type).get(arg_type):
  1634. arg_list.append(ip_port_dict.get(ip).get(_type).get(arg_type))
  1635. return arg_list
  1636. def remove_red_seal(image_np):
  1637. """
  1638. 去除红色印章
  1639. """
  1640. cv2.namedWindow("image_np", 0)
  1641. cv2.resizeWindow("image_np", 1000, 800)
  1642. cv2.imshow("image_np", image_np)
  1643. height, width, c = image_np.shape
  1644. window_h = int(height / 15)
  1645. image_hsv = cv2.cvtColor(image_np, cv2.COLOR_BGR2HSV)
  1646. # 遍历numpy
  1647. red_point_list = []
  1648. image_list = image_np.tolist()
  1649. hsv_dict = {}
  1650. for index_1 in range(len(image_list)):
  1651. for index_2 in range(len(image_list[index_1])):
  1652. h, s, v = image_hsv[index_1][index_2]
  1653. if (0 <= h <= 10 or 156 <= h <= 180) and 43 <= s <= 255 and 46 <= v <= 255:
  1654. key = str(image_hsv[index_1][index_2].tolist())
  1655. red_point_list.append([key, index_1, index_2])
  1656. if hsv_dict.get(key):
  1657. hsv_dict[key] += 1
  1658. else:
  1659. hsv_dict[key] = 1
  1660. # 找出相同最多的hsv值
  1661. hsv_most_key = None
  1662. hsv_most_value = 0
  1663. for hsv in hsv_dict.keys():
  1664. if hsv_dict.get(hsv) > hsv_most_value:
  1665. hsv_most_value = hsv_dict.get(hsv)
  1666. hsv_most_key = hsv
  1667. # print(hsv_dict)
  1668. # 根据hsv判断其填充为黑色还是白色
  1669. hsv_most_key = eval(hsv_most_key)
  1670. for point in red_point_list:
  1671. if abs(eval(point[0])[2] - hsv_most_key[2]) <= 70:
  1672. image_np[point[1]][point[2]][0] = 255
  1673. image_np[point[1]][point[2]][1] = 255
  1674. image_np[point[1]][point[2]][2] = 255
  1675. else:
  1676. image_np[point[1]][point[2]][0] = 0
  1677. image_np[point[1]][point[2]][1] = 0
  1678. image_np[point[1]][point[2]][2] = 0
  1679. cv2.namedWindow("remove_red_seal", 0)
  1680. cv2.resizeWindow("remove_red_seal", 1000, 800)
  1681. cv2.imshow("remove_red_seal", image_np)
  1682. # cv2.imwrite("C:/Users/Administrator/Downloads/1.png", image_np)
  1683. cv2.waitKey(0)
  1684. return image_np
  1685. def pil_resize(image_np, height, width):
  1686. # limit pixels 89478485
  1687. if image_np.shape[0] * image_np.shape[1] * image_np.shape[2] >= 89478485:
  1688. # print("image too large, limit 89478485 pixels", image_np.shape)
  1689. ratio = image_np.shape[0] / image_np.shape[1]
  1690. if image_np.shape[0] >= image_np.shape[1]:
  1691. image_np = cv2.resize(image_np, (int(3000 / ratio), 3000), interpolation=cv2.INTER_AREA)
  1692. else:
  1693. image_np = cv2.resize(image_np, (3000, int(3000 * ratio)), interpolation=cv2.INTER_AREA)
  1694. image_pil = Image.fromarray(cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB))
  1695. image_pil = image_pil.resize((int(width), int(height)), Image.BICUBIC)
  1696. image_np = cv2.cvtColor(np.asarray(image_pil), cv2.COLOR_RGB2BGR)
  1697. return image_np
  1698. def np2pil(image_np):
  1699. image_pil = Image.fromarray(cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB))
  1700. return image_pil
  1701. def pil2np(image_pil):
  1702. image_np = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
  1703. return image_np
  1704. def bytes2np(_b):
  1705. try:
  1706. # 二进制数据流转np.ndarray [np.uint8: 8位像素]
  1707. image_np = cv2.imdecode(np.frombuffer(_b, np.uint8), cv2.IMREAD_COLOR)
  1708. # 将rgb转为bgr
  1709. # image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
  1710. return image_np
  1711. except cv2.error as e:
  1712. if "src.empty()" in str(e):
  1713. log("bytes2np image is empty!")
  1714. return None
  1715. except:
  1716. traceback.print_exc()
  1717. return None
  1718. def np2bytes(image_np):
  1719. # numpy转为可序列化的string
  1720. success, img_encode = cv2.imencode(".jpg", image_np)
  1721. # numpy -> bytes
  1722. img_bytes = img_encode.tobytes()
  1723. return img_bytes
  1724. def ocr_cant_read(text_list, box_list):
  1725. """
  1726. 判断ocr因为图片方向无法识别情况
  1727. :param text_list: 文字list
  1728. :param box_list: 文字框list
  1729. :return: bool
  1730. """
  1731. # 无文字及框
  1732. if not text_list or not box_list:
  1733. return True
  1734. # 根据bbox长宽比判断
  1735. box_cnt = 0
  1736. box_flag = 0
  1737. for box in box_list:
  1738. if abs(box[0][1] - box[2][1]) > abs(box[0][0] - box[2][0]):
  1739. box_cnt += 1
  1740. if box_cnt >= int(len(box_list) / 2):
  1741. box_flag = 1
  1742. # 根据识别字数判断
  1743. charac_flag = 0
  1744. charac_set = set()
  1745. for text in text_list:
  1746. charac_set.update(text)
  1747. if len(charac_set) < 40:
  1748. charac_flag = 1
  1749. # 字数少
  1750. if charac_flag:
  1751. result = True
  1752. # 字数多但格子长
  1753. elif box_flag:
  1754. result = True
  1755. else:
  1756. result = False
  1757. log(result)
  1758. return result
  1759. def file_lock(file_name):
  1760. """
  1761. 获取文件排它锁,返回文件句柄,需手动close文件以释放排它锁
  1762. :param file_name:
  1763. :return:
  1764. """
  1765. import fcntl
  1766. if not os.path.exists(file_name):
  1767. with open(file_name, 'w') as f:
  1768. f.write('0')
  1769. file = open(file_name, 'r')
  1770. # 获取排它锁
  1771. fcntl.flock(file.fileno(), fcntl.LOCK_EX)
  1772. return file
  1773. def get_garble_code():
  1774. reg_str = '[ÿÝØÐÙÚÛÜÒÓÔÕÖÊÄẨòóôäåüúîïìþ¡¢£¤§èéêëȟš' + \
  1775. 'Ϸᱦ¼ŒÞ¾Çœø‡Æ�ϐ㏫⮰≧ڝⶹӇⰚڣༀងϦȠ⚓Ⴭᐬ⩔ⅮⰚࡦࣽ' + \
  1776. '䕆㶃䌛㻰䙹䔮㔭䶰䰬䉰䶰䘔䉥喌䶥䶰䛳䉙䄠' + \
  1777. ''.join(['\\x0' + str(x) for x in range(1, 10)]) + \
  1778. ''.join(['\\x' + str(x) for x in range(10, 20)]) + \
  1779. ']'
  1780. return reg_str
  1781. def line_is_cross(A, B, C, D):
  1782. line1 = LineString([A, B])
  1783. line2 = LineString([C, D])
  1784. int_pt = line1.intersection(line2)
  1785. try:
  1786. point_of_intersection = int_pt.x, int_pt.y
  1787. return True
  1788. except:
  1789. return False
  1790. if __name__ == "__main__":
  1791. # strs = r"D:\Project\temp\04384fcc9e8911ecbd2844f971944973\043876ca9e8911eca5e144f971944973_rar\1624114035529.jpeg"
  1792. # print(slash_replace(strs))
  1793. # from matplotlib import pyplot as plt
  1794. # import random
  1795. # fig = plt.figure()
  1796. # plt.xlim(100)
  1797. # plt.ylim(100)
  1798. # fig.add_subplot(111)
  1799. # x0,y0,x1,y1 = (1,2,3,4)
  1800. # plt.gca().add_patch(plt.Rectangle(xy=(x0, y0),
  1801. # width=x1-x0,
  1802. # height=y1-y0,
  1803. # edgecolor=(random.randint(0,255)/255,random.randint(0,255)/255,random.randint(0,255)/255),
  1804. # fill=False, linewidth=2))
  1805. #
  1806. # # plt.show()
  1807. # import cv2
  1808. # import numpy as np
  1809. # img = np.zeros(shape=(1800,1800),dtype=np.uint8)
  1810. # img += 255
  1811. # cv2.imshow("bbox", img)
  1812. # cv2.waitKey(0)
  1813. # print(json.dumps({"data":[1, 2]}))
  1814. # print(parse_yaml())
  1815. print(get_ip_port())
  1816. # set_flask_global()
  1817. # print(get_all_ip())
  1818. print(get_args_from_config(get_ip_port(), get_all_ip()[0], "idc"))
  1819. print(get_args_from_config(get_ip_port(), get_all_ip()[0], "atc"))
  1820. # print(get_args_from_config(get_ip_port(), "http://127.0.0.1", "gunicorn_path"))
  1821. # print(get_intranet_ip())
  1822. # _path = "C:/Users/Administrator/Downloads/3.png"
  1823. # remove_red_seal(cv2.imread(_path))