video_batch_sampler.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 .base_batch_sampler import BaseBatchSampler
  22. class VideoBatchSampler(BaseBatchSampler):
  23. SUFFIX = ["mp4", "avi", "mkv", "webm"]
  24. # XXX: auto download for url
  25. def _download_from_url(self, in_path):
  26. file_name = Path(in_path).name
  27. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  28. download(in_path, save_path, overwrite=True)
  29. return save_path.as_posix()
  30. def _get_files_list(self, fp):
  31. file_list = []
  32. if fp is None or not os.path.exists(fp):
  33. raise Exception(f"Not found any video file in path: {fp}")
  34. if os.path.isfile(fp) and fp.split(".")[-1] in self.SUFFIX:
  35. file_list.append(fp)
  36. elif os.path.isdir(fp):
  37. for root, dirs, files in os.walk(fp):
  38. for single_file in files:
  39. if single_file.split(".")[-1] in self.SUFFIX:
  40. file_list.append(os.path.join(root, single_file))
  41. if len(file_list) == 0:
  42. raise Exception("Not found any file in {}".format(fp))
  43. file_list = sorted(file_list)
  44. return file_list
  45. def sample(self, inputs):
  46. if not isinstance(inputs, list):
  47. inputs = [inputs]
  48. batch = []
  49. for input in inputs:
  50. if isinstance(input, str):
  51. file_path = (
  52. self._download_from_url(input)
  53. if input.startswith("http")
  54. else input
  55. )
  56. file_list = self._get_files_list(file_path)
  57. for file_path in file_list:
  58. batch.append(file_path)
  59. if len(batch) == self.batch_size:
  60. yield batch
  61. batch = []
  62. else:
  63. logging.warning(
  64. f"Not supported input data type! Only `str` are supported! So has been ignored: {input}."
  65. )
  66. if len(batch) > 0:
  67. yield batch
  68. def _rand_batch(self, data_size):
  69. def parse_size(s):
  70. res = ast.literal_eval(s)
  71. if isinstance(res, int):
  72. return (res, res)
  73. else:
  74. assert isinstance(res, (tuple, list))
  75. assert len(res) == 2
  76. assert all(isinstance(item, int) for item in res)
  77. return res
  78. size = parse_size(data_size)
  79. rand_batch = [
  80. np.random.randint(0, 256, (*size, 3), dtype=np.uint8)
  81. for _ in range(self.batch_size)
  82. ]
  83. return rand_batch