utils.py 73 KB

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