utils.py 74 KB

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