read_data.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. from ....utils.download import download
  17. from ....utils.cache import CACHE_DIR
  18. from ..base import BaseComponent
  19. class _BaseRead(BaseComponent):
  20. """Load image from the file."""
  21. NAME = "ReadCmp"
  22. SUFFIX = []
  23. def __init__(self, batch_size=1):
  24. super().__init__()
  25. self._batch_size = batch_size
  26. @property
  27. def batch_size(self):
  28. return self._batch_size
  29. @batch_size.setter
  30. def batch_size(self, value):
  31. if value <= 0:
  32. raise ValueError("Batch size must be positive.")
  33. self._batch_size = value
  34. # XXX: auto download for url
  35. def _download_from_url(self, in_path):
  36. if in_path.startswith("http"):
  37. file_name = Path(in_path).name
  38. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  39. download(in_path, save_path, overwrite=True)
  40. return save_path.as_posix()
  41. return in_path
  42. def _get_files_list(self, fp):
  43. file_list = []
  44. if fp is None or not os.path.exists(fp):
  45. raise Exception(f"Not found any img file in path: {fp}")
  46. if os.path.isfile(fp) and fp.split(".")[-1] in self.SUFFIX:
  47. file_list.append(fp)
  48. elif os.path.isdir(fp):
  49. for root, dirs, files in os.walk(fp):
  50. for single_file in files:
  51. if single_file.split(".")[-1] in self.SUFFIX:
  52. file_list.append(os.path.join(root, single_file))
  53. if len(file_list) == 0:
  54. raise Exception("Not found any file in {}".format(fp))
  55. file_list = sorted(file_list)
  56. return file_list