utils.py 81 KB

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