image_batch_sampler.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. from pathlib import Path
  16. import numpy as np
  17. from ....utils import logging
  18. from ....utils.download import download
  19. from ....utils.cache import CACHE_DIR
  20. from ...utils.io import PDFReader
  21. from .base_batch_sampler import BaseBatchSampler
  22. class ImgInstance:
  23. def __init__(self):
  24. self.instances = []
  25. self.input_paths = []
  26. self.page_indexes = []
  27. def append(self, instance, input_path, page_index):
  28. self.instances.append(instance)
  29. self.input_paths.append(input_path)
  30. self.page_indexes.append(page_index)
  31. def reset(self):
  32. self.instances = []
  33. self.input_paths = []
  34. self.page_indexes = []
  35. def __len__(self):
  36. return len(self.instances)
  37. class ImageBatchSampler(BaseBatchSampler):
  38. SUFFIX = ["jpg", "png", "jpeg", "JPEG", "JPG", "bmp"]
  39. def __init__(self, *args, **kwargs):
  40. super().__init__(*args, **kwargs)
  41. self.pdf_reader = PDFReader()
  42. # XXX: auto download for url
  43. def _download_from_url(self, in_path):
  44. file_name = Path(in_path).name
  45. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  46. download(in_path, save_path, overwrite=True)
  47. return save_path.as_posix()
  48. def _get_files_list(self, fp):
  49. file_list = []
  50. if fp is None or not os.path.exists(fp):
  51. raise Exception(f"Not found any img file in path: {fp}")
  52. if os.path.isfile(fp) and fp.split(".")[-1] in self.SUFFIX:
  53. file_list.append(fp)
  54. elif os.path.isdir(fp):
  55. for root, dirs, files in os.walk(fp):
  56. for single_file in files:
  57. if single_file.split(".")[-1] in self.SUFFIX:
  58. file_list.append(os.path.join(root, single_file))
  59. if len(file_list) == 0:
  60. raise Exception("Not found any file in {}".format(fp))
  61. file_list = sorted(file_list)
  62. return file_list
  63. def sample(self, inputs):
  64. if not isinstance(inputs, list):
  65. inputs = [inputs]
  66. batch = ImgInstance()
  67. for input in inputs:
  68. if isinstance(input, np.ndarray):
  69. batch.append(input, None, None)
  70. if len(batch) == self.batch_size:
  71. yield batch
  72. batch = ImgInstance()
  73. elif isinstance(input, str) and input.split(".")[-1] in ("PDF", "pdf"):
  74. file_path = (
  75. self._download_from_url(input)
  76. if input.startswith("http")
  77. else input
  78. )
  79. for page_idx, page_img in enumerate(self.pdf_reader.read(file_path)):
  80. batch.append(page_img, file_path, page_idx)
  81. if len(batch) == self.batch_size:
  82. yield batch
  83. batch = ImgInstance()
  84. elif isinstance(input, str):
  85. file_path = (
  86. self._download_from_url(input)
  87. if input.startswith("http")
  88. else input
  89. )
  90. file_list = self._get_files_list(file_path)
  91. for file_path in file_list:
  92. batch.append(file_path, file_path, None)
  93. if len(batch) == self.batch_size:
  94. yield batch
  95. batch = ImgInstance()
  96. else:
  97. logging.warning(
  98. f"Not supported input data type! Only `numpy.ndarray` and `str` are supported! So has been ignored: {input}."
  99. )
  100. if len(batch) > 0:
  101. yield batch