You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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