Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import os, sys
  14. sys.path.insert(
  15. 0,
  16. os.path.abspath(
  17. os.path.join(
  18. os.path.dirname(
  19. os.path.abspath(__file__)),
  20. '../../')))
  21. from deepdoc.vision.seeit import draw_box
  22. from deepdoc.vision import Recognizer, LayoutRecognizer, TableStructureRecognizer, OCR, init_in_out
  23. from api.utils.file_utils import get_project_base_directory
  24. import argparse
  25. import re
  26. import numpy as np
  27. def main(args):
  28. images, outputs = init_in_out(args)
  29. if args.mode.lower() == "layout":
  30. labels = LayoutRecognizer.labels
  31. detr = Recognizer(
  32. labels,
  33. "layout",
  34. os.path.join(
  35. get_project_base_directory(),
  36. "rag/res/deepdoc/"))
  37. if args.mode.lower() == "tsr":
  38. labels = TableStructureRecognizer.labels
  39. detr = TableStructureRecognizer()
  40. ocr = OCR()
  41. layouts = detr(images, float(args.threshold))
  42. for i, lyt in enumerate(layouts):
  43. if args.mode.lower() == "tsr":
  44. #lyt = [t for t in lyt if t["type"] == "table column"]
  45. html = get_table_html(images[i], lyt, ocr)
  46. with open(outputs[i] + ".html", "w+") as f:
  47. f.write(html)
  48. lyt = [{
  49. "type": t["label"],
  50. "bbox": [t["x0"], t["top"], t["x1"], t["bottom"]],
  51. "score": t["score"]
  52. } for t in lyt]
  53. img = draw_box(images[i], lyt, labels, float(args.threshold))
  54. img.save(outputs[i], quality=95)
  55. print("save result to: " + outputs[i])
  56. def get_table_html(img, tb_cpns, ocr):
  57. boxes = ocr(np.array(img))
  58. boxes = Recognizer.sort_Y_firstly(
  59. [{"x0": b[0][0], "x1": b[1][0],
  60. "top": b[0][1], "text": t[0],
  61. "bottom": b[-1][1],
  62. "layout_type": "table",
  63. "page_number": 0} for b, t in boxes if b[0][0] <= b[1][0] and b[0][1] <= b[-1][1]],
  64. np.mean([b[-1][1] - b[0][1] for b, _ in boxes]) / 3
  65. )
  66. def gather(kwd, fzy=10, ption=0.6):
  67. nonlocal boxes
  68. eles = Recognizer.sort_Y_firstly(
  69. [r for r in tb_cpns if re.match(kwd, r["label"])], fzy)
  70. eles = Recognizer.layouts_cleanup(boxes, eles, 5, ption)
  71. return Recognizer.sort_Y_firstly(eles, 0)
  72. headers = gather(r".*header$")
  73. rows = gather(r".* (row|header)")
  74. spans = gather(r".*spanning")
  75. clmns = sorted([r for r in tb_cpns if re.match(
  76. r"table column$", r["label"])], key=lambda x: x["x0"])
  77. clmns = Recognizer.layouts_cleanup(boxes, clmns, 5, 0.5)
  78. for b in boxes:
  79. ii = Recognizer.find_overlapped_with_threashold(b, rows, thr=0.3)
  80. if ii is not None:
  81. b["R"] = ii
  82. b["R_top"] = rows[ii]["top"]
  83. b["R_bott"] = rows[ii]["bottom"]
  84. ii = Recognizer.find_overlapped_with_threashold(b, headers, thr=0.3)
  85. if ii is not None:
  86. b["H_top"] = headers[ii]["top"]
  87. b["H_bott"] = headers[ii]["bottom"]
  88. b["H_left"] = headers[ii]["x0"]
  89. b["H_right"] = headers[ii]["x1"]
  90. b["H"] = ii
  91. ii = Recognizer.find_horizontally_tightest_fit(b, clmns)
  92. if ii is not None:
  93. b["C"] = ii
  94. b["C_left"] = clmns[ii]["x0"]
  95. b["C_right"] = clmns[ii]["x1"]
  96. ii = Recognizer.find_overlapped_with_threashold(b, spans, thr=0.3)
  97. if ii is not None:
  98. b["H_top"] = spans[ii]["top"]
  99. b["H_bott"] = spans[ii]["bottom"]
  100. b["H_left"] = spans[ii]["x0"]
  101. b["H_right"] = spans[ii]["x1"]
  102. b["SP"] = ii
  103. html = """
  104. <html>
  105. <head>
  106. <style>
  107. ._table_1nkzy_11 {
  108. margin: auto;
  109. width: 70%%;
  110. padding: 10px;
  111. }
  112. ._table_1nkzy_11 p {
  113. margin-bottom: 50px;
  114. border: 1px solid #e1e1e1;
  115. }
  116. caption {
  117. color: #6ac1ca;
  118. font-size: 20px;
  119. height: 50px;
  120. line-height: 50px;
  121. font-weight: 600;
  122. margin-bottom: 10px;
  123. }
  124. ._table_1nkzy_11 table {
  125. width: 100%%;
  126. border-collapse: collapse;
  127. }
  128. th {
  129. color: #fff;
  130. background-color: #6ac1ca;
  131. }
  132. td:hover {
  133. background: #c1e8e8;
  134. }
  135. tr:nth-child(even) {
  136. background-color: #f2f2f2;
  137. }
  138. ._table_1nkzy_11 th,
  139. ._table_1nkzy_11 td {
  140. text-align: center;
  141. border: 1px solid #ddd;
  142. padding: 8px;
  143. }
  144. </style>
  145. </head>
  146. <body>
  147. %s
  148. </body>
  149. </html>
  150. """ % TableStructureRecognizer.construct_table(boxes, html=True)
  151. return html
  152. if __name__ == "__main__":
  153. parser = argparse.ArgumentParser()
  154. parser.add_argument('--inputs',
  155. help="Directory where to store images or PDFs, or a file path to a single image or PDF",
  156. required=True)
  157. parser.add_argument('--output_dir', help="Directory where to store the output images. Default: './layouts_outputs'",
  158. default="./layouts_outputs")
  159. parser.add_argument(
  160. '--threshold',
  161. help="A threshold to filter out detections. Default: 0.5",
  162. default=0.5)
  163. parser.add_argument('--mode', help="Task mode: layout recognition or table structure recognition", choices=["layout", "tsr"],
  164. default="layout")
  165. args = parser.parse_args()
  166. main(args)