utils.py 72 KB

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