image_batch_sampler.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import ast
  16. from pathlib import Path
  17. import numpy as np
  18. from ....utils import logging
  19. from ....utils.download import download
  20. from ....utils.cache import CACHE_DIR
  21. from ...utils.io import PDFReader
  22. from .base_batch_sampler import BaseBatchSampler
  23. class ImgInstance:
  24. def __init__(self):
  25. self.instances = []
  26. self.input_paths = []
  27. self.page_indexes = []
  28. def append(self, instance, input_path, page_index):
  29. self.instances.append(instance)
  30. self.input_paths.append(input_path)
  31. self.page_indexes.append(page_index)
  32. def reset(self):
  33. self.instances = []
  34. self.input_paths = []
  35. self.page_indexes = []
  36. def __len__(self):
  37. return len(self.instances)
  38. class ImageBatchSampler(BaseBatchSampler):
  39. SUFFIX = ["jpg", "png", "jpeg", "JPEG", "JPG", "bmp"]
  40. def __init__(self, *args, **kwargs):
  41. super().__init__(*args, **kwargs)
  42. self.pdf_reader = PDFReader()
  43. # XXX: auto download for url
  44. def _download_from_url(self, in_path):
  45. file_name = Path(in_path).name
  46. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  47. download(in_path, save_path, overwrite=True)
  48. return save_path.as_posix()
  49. def _get_files_list(self, fp):
  50. file_list = []
  51. if fp is None or not os.path.exists(fp):
  52. raise Exception(f"Not found any img file in path: {fp}")
  53. if os.path.isfile(fp) and fp.split(".")[-1] in self.SUFFIX:
  54. file_list.append(fp)
  55. elif os.path.isdir(fp):
  56. for root, dirs, files in os.walk(fp):
  57. for single_file in files:
  58. if single_file.split(".")[-1] in self.SUFFIX:
  59. file_list.append(os.path.join(root, single_file))
  60. if len(file_list) == 0:
  61. raise Exception("Not found any file in {}".format(fp))
  62. file_list = sorted(file_list)
  63. return file_list
  64. def sample(self, inputs):
  65. if not isinstance(inputs, list):
  66. inputs = [inputs]
  67. batch = {"instances": [], "input_paths": [], "page_indexes": []}
  68. batch = ImgInstance()
  69. for input in inputs:
  70. if isinstance(input, np.ndarray):
  71. batch.append(input, None, None)
  72. if len(batch) == self.batch_size:
  73. yield batch
  74. batch.reset()
  75. elif isinstance(input, str) and input.split(".")[-1] in ("PDF", "pdf"):
  76. file_path = (
  77. self._download_from_url(input)
  78. if input.startswith("http")
  79. else input
  80. )
  81. for page_idx, page_img in enumerate(self.pdf_reader.read(file_path)):
  82. batch.append(page_img, file_path, page_idx)
  83. if len(batch) == self.batch_size:
  84. yield batch
  85. batch.reset()
  86. elif isinstance(input, str):
  87. file_path = (
  88. self._download_from_url(input)
  89. if input.startswith("http")
  90. else input
  91. )
  92. file_list = self._get_files_list(file_path)
  93. for file_path in file_list:
  94. batch.append(file_path, file_path, None)
  95. if len(batch) == self.batch_size:
  96. yield batch
  97. batch.reset()
  98. else:
  99. logging.warning(
  100. f"Not supported input data type! Only `numpy.ndarray` and `str` are supported! So has been ignored: {input}."
  101. )
  102. if len(batch) > 0:
  103. yield batch
  104. def _rand_batch(self, data_size):
  105. def parse_size(s):
  106. res = ast.literal_eval(s)
  107. if isinstance(res, int):
  108. return (res, res)
  109. else:
  110. assert isinstance(res, (tuple, list))
  111. assert len(res) == 2
  112. assert all(isinstance(item, int) for item in res)
  113. return res
  114. size = parse_size(data_size)
  115. rand_batch = [
  116. np.random.randint(0, 256, (*size, 3), dtype=np.uint8)
  117. for _ in range(self.batch_size)
  118. ]
  119. return rand_batch