utils.py 80 KB

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