image_batch_sampler.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 ImageBatchSampler(BaseBatchSampler):
  24. SUFFIX = ["jpg", "png", "jpeg", "JPEG", "JPG", "bmp"]
  25. def __init__(self, *args, **kwargs):
  26. super().__init__(*args, **kwargs)
  27. self.pdf_reader = PDFReader()
  28. # XXX: auto download for url
  29. def _download_from_url(self, in_path):
  30. file_name = Path(in_path).name
  31. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  32. download(in_path, save_path, overwrite=True)
  33. return save_path.as_posix()
  34. def _get_files_list(self, fp):
  35. file_list = []
  36. if fp is None or not os.path.exists(fp):
  37. raise Exception(f"Not found any img file in path: {fp}")
  38. if os.path.isfile(fp) and fp.split(".")[-1] in self.SUFFIX:
  39. file_list.append(fp)
  40. elif os.path.isdir(fp):
  41. for root, dirs, files in os.walk(fp):
  42. for single_file in files:
  43. if single_file.split(".")[-1] in self.SUFFIX:
  44. file_list.append(os.path.join(root, single_file))
  45. if len(file_list) == 0:
  46. raise Exception("Not found any file in {}".format(fp))
  47. file_list = sorted(file_list)
  48. return file_list
  49. def sample(self, inputs):
  50. if not isinstance(inputs, list):
  51. inputs = [inputs]
  52. batch = []
  53. for input in inputs:
  54. if isinstance(input, np.ndarray):
  55. batch.append(input)
  56. if len(batch) == self.batch_size:
  57. yield batch
  58. batch = []
  59. elif isinstance(input, str) and input.split(".")[-1] in ("PDF", "pdf"):
  60. file_path = (
  61. self._download_from_url(input)
  62. if input.startswith("http")
  63. else input
  64. )
  65. for page_img in self.pdf_reader.read(file_path):
  66. batch.append(page_img)
  67. if len(batch) == self.batch_size:
  68. yield batch
  69. batch = []
  70. elif isinstance(input, str):
  71. file_path = (
  72. self._download_from_url(input)
  73. if input.startswith("http")
  74. else input
  75. )
  76. file_list = self._get_files_list(file_path)
  77. for file_path in file_list:
  78. batch.append(file_path)
  79. if len(batch) == self.batch_size:
  80. yield batch
  81. batch = []
  82. else:
  83. logging.warning(
  84. f"Not supported input data type! Only `numpy.ndarray` and `str` are supported! So has been ignored: {input}."
  85. )
  86. if len(batch) > 0:
  87. yield batch
  88. def _rand_batch(self, data_size):
  89. def parse_size(s):
  90. res = ast.literal_eval(s)
  91. if isinstance(res, int):
  92. return (res, res)
  93. else:
  94. assert isinstance(res, (tuple, list))
  95. assert len(res) == 2
  96. assert all(isinstance(item, int) for item in res)
  97. return res
  98. size = parse_size(data_size)
  99. rand_batch = [
  100. np.random.randint(0, 256, (*size, 3), dtype=np.uint8)
  101. for _ in range(self.batch_size)
  102. ]
  103. return rand_batch