選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

t_ocr.py 3.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import os
  17. import sys
  18. sys.path.insert(
  19. 0,
  20. os.path.abspath(
  21. os.path.join(
  22. os.path.dirname(
  23. os.path.abspath(__file__)),
  24. '../../')))
  25. from deepdoc.vision.seeit import draw_box
  26. from deepdoc.vision import OCR, init_in_out
  27. import argparse
  28. import numpy as np
  29. import trio
  30. # os.environ['CUDA_VISIBLE_DEVICES'] = '0,2' #2 gpus, uncontinuous
  31. os.environ['CUDA_VISIBLE_DEVICES'] = '0' #1 gpu
  32. # os.environ['CUDA_VISIBLE_DEVICES'] = '' #cpu
  33. def main(args):
  34. import torch.cuda
  35. cuda_devices = torch.cuda.device_count()
  36. limiter = [trio.CapacityLimiter(1) for _ in range(cuda_devices)] if cuda_devices > 1 else None
  37. ocr = OCR(parallel_devices = cuda_devices)
  38. images, outputs = init_in_out(args)
  39. def __ocr(i, id, img):
  40. print("Task {} start".format(i))
  41. bxs = ocr(np.array(img), id)
  42. bxs = [(line[0], line[1][0]) for line in bxs]
  43. bxs = [{
  44. "text": t,
  45. "bbox": [b[0][0], b[0][1], b[1][0], b[-1][1]],
  46. "type": "ocr",
  47. "score": 1} for b, t in bxs if b[0][0] <= b[1][0] and b[0][1] <= b[-1][1]]
  48. img = draw_box(images[i], bxs, ["ocr"], 1.)
  49. img.save(outputs[i], quality=95)
  50. with open(outputs[i] + ".txt", "w+", encoding='utf-8') as f:
  51. f.write("\n".join([o["text"] for o in bxs]))
  52. print("Task {} done".format(i))
  53. async def __ocr_thread(i, id, img, limiter = None):
  54. if limiter:
  55. async with limiter:
  56. print("Task {} use device {}".format(i, id))
  57. await trio.to_thread.run_sync(lambda: __ocr(i, id, img))
  58. else:
  59. __ocr(i, id, img)
  60. async def __ocr_launcher():
  61. if cuda_devices > 1:
  62. async with trio.open_nursery() as nursery:
  63. for i, img in enumerate(images):
  64. nursery.start_soon(__ocr_thread, i, i % cuda_devices, img, limiter[i % cuda_devices])
  65. await trio.sleep(0.1)
  66. else:
  67. for i, img in enumerate(images):
  68. await __ocr_thread(i, 0, img)
  69. trio.run(__ocr_launcher)
  70. print("OCR tasks are all done")
  71. if __name__ == "__main__":
  72. parser = argparse.ArgumentParser()
  73. parser.add_argument('--inputs',
  74. help="Directory where to store images or PDFs, or a file path to a single image or PDF",
  75. required=True)
  76. parser.add_argument('--output_dir', help="Directory where to store the output images. Default: './ocr_outputs'",
  77. default="./ocr_outputs")
  78. args = parser.parse_args()
  79. main(args)