utils.py 68 KB

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