writers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 enum
  16. import json
  17. from pathlib import Path
  18. import cv2
  19. import numpy as np
  20. from PIL import Image
  21. import pandas as pd
  22. import yaml
  23. from .tablepyxl import document_to_xl
  24. __all__ = [
  25. "WriterType",
  26. "ImageWriter",
  27. "TextWriter",
  28. "JsonWriter",
  29. "CSVWriter",
  30. "HtmlWriter",
  31. "XlsxWriter",
  32. "YAMLWriter",
  33. "VideoWriter",
  34. ]
  35. class WriterType(enum.Enum):
  36. """WriterType"""
  37. IMAGE = 1
  38. VIDEO = 2
  39. TEXT = 3
  40. JSON = 4
  41. HTML = 5
  42. XLSX = 6
  43. CSV = 7
  44. YAML = 8
  45. class _BaseWriter(object):
  46. """_BaseWriter"""
  47. def __init__(self, backend, **bk_args):
  48. super().__init__()
  49. if len(bk_args) == 0:
  50. bk_args = self.get_default_backend_args()
  51. self.bk_type = backend
  52. self.bk_args = bk_args
  53. self._backend = self.get_backend()
  54. def write(self, out_path, obj):
  55. """write"""
  56. raise NotImplementedError
  57. def get_backend(self, bk_args=None):
  58. """get backend"""
  59. if bk_args is None:
  60. bk_args = self.bk_args
  61. return self._init_backend(self.bk_type, bk_args)
  62. def set_backend(self, backend, **bk_args):
  63. self.bk_type = backend
  64. self.bk_args = bk_args
  65. self._backend = self.get_backend()
  66. def _init_backend(self, bk_type, bk_args):
  67. """init backend"""
  68. raise NotImplementedError
  69. def get_type(self):
  70. """get type"""
  71. raise NotImplementedError
  72. def get_default_backend_args(self):
  73. """get default backend arguments"""
  74. return {}
  75. class ImageWriter(_BaseWriter):
  76. """ImageWriter"""
  77. def __init__(self, backend="opencv", **bk_args):
  78. super().__init__(backend=backend, **bk_args)
  79. def write(self, out_path, obj):
  80. """write"""
  81. return self._backend.write_obj(str(out_path), obj)
  82. def _init_backend(self, bk_type, bk_args):
  83. """init backend"""
  84. if bk_type == "opencv":
  85. return OpenCVImageWriterBackend(**bk_args)
  86. elif bk_type == "pil" or bk_type == "pillow":
  87. return PILImageWriterBackend(**bk_args)
  88. else:
  89. raise ValueError("Unsupported backend type")
  90. def get_type(self):
  91. """get type"""
  92. return WriterType.IMAGE
  93. class VideoWriter(_BaseWriter):
  94. """VideoWriter"""
  95. def __init__(self, backend="opencv", **bk_args):
  96. super().__init__(backend=backend, **bk_args)
  97. def write(self, out_path, obj):
  98. """write"""
  99. return self._backend.write_obj(str(out_path), obj)
  100. def _init_backend(self, bk_type, bk_args):
  101. """init backend"""
  102. if bk_type == "opencv":
  103. return OpenCVVideoWriterBackend(**bk_args)
  104. else:
  105. raise ValueError("Unsupported backend type")
  106. def get_type(self):
  107. """get type"""
  108. return WriterType.VIDEO
  109. class TextWriter(_BaseWriter):
  110. """TextWriter"""
  111. def __init__(self, backend="python", **bk_args):
  112. super().__init__(backend=backend, **bk_args)
  113. def write(self, out_path, obj):
  114. """write"""
  115. return self._backend.write_obj(str(out_path), obj)
  116. def _init_backend(self, bk_type, bk_args):
  117. """init backend"""
  118. if bk_type == "python":
  119. return TextWriterBackend(**bk_args)
  120. else:
  121. raise ValueError("Unsupported backend type")
  122. def get_type(self):
  123. """get type"""
  124. return WriterType.TEXT
  125. class JsonWriter(_BaseWriter):
  126. def __init__(self, backend="json", **bk_args):
  127. super().__init__(backend=backend, **bk_args)
  128. def write(self, out_path, obj, **bk_args):
  129. return self._backend.write_obj(str(out_path), obj, **bk_args)
  130. def _init_backend(self, bk_type, bk_args):
  131. if bk_type == "json":
  132. return JsonWriterBackend(**bk_args)
  133. elif bk_type == "ujson":
  134. return UJsonWriterBackend(**bk_args)
  135. else:
  136. raise ValueError("Unsupported backend type")
  137. def get_type(self):
  138. """get type"""
  139. return WriterType.JSON
  140. class HtmlWriter(_BaseWriter):
  141. def __init__(self, backend="html", **bk_args):
  142. super().__init__(backend=backend, **bk_args)
  143. def write(self, out_path, obj, **bk_args):
  144. return self._backend.write_obj(str(out_path), obj, **bk_args)
  145. def _init_backend(self, bk_type, bk_args):
  146. if bk_type == "html":
  147. return HtmlWriterBackend(**bk_args)
  148. else:
  149. raise ValueError("Unsupported backend type")
  150. def get_type(self):
  151. """get type"""
  152. return WriterType.HTML
  153. class XlsxWriter(_BaseWriter):
  154. def __init__(self, backend="xlsx", **bk_args):
  155. super().__init__(backend=backend, **bk_args)
  156. def write(self, out_path, obj, **bk_args):
  157. return self._backend.write_obj(str(out_path), obj, **bk_args)
  158. def _init_backend(self, bk_type, bk_args):
  159. if bk_type == "xlsx":
  160. return XlsxWriterBackend(**bk_args)
  161. else:
  162. raise ValueError("Unsupported backend type")
  163. def get_type(self):
  164. """get type"""
  165. return WriterType.XLSX
  166. class YAMLWriter(_BaseWriter):
  167. def __init__(self, backend="PyYAML", **bk_args):
  168. super().__init__(backend=backend, **bk_args)
  169. def write(self, out_path, obj, **bk_args):
  170. return self._backend.write_obj(str(out_path), obj, **bk_args)
  171. def _init_backend(self, bk_type, bk_args):
  172. if bk_type == "PyYAML":
  173. return YAMLWriterBackend(**bk_args)
  174. else:
  175. raise ValueError("Unsupported backend type")
  176. def get_type(self):
  177. """get type"""
  178. return WriterType.YAML
  179. class _BaseWriterBackend(object):
  180. """_BaseWriterBackend"""
  181. def write_obj(self, out_path, obj, **bk_args):
  182. """write object"""
  183. Path(out_path).parent.mkdir(parents=True, exist_ok=True)
  184. return self._write_obj(out_path, obj, **bk_args)
  185. def _write_obj(self, out_path, obj, **bk_args):
  186. """write object"""
  187. raise NotImplementedError
  188. class TextWriterBackend(_BaseWriterBackend):
  189. """TextWriterBackend"""
  190. def __init__(self, mode="w", encoding="utf-8"):
  191. super().__init__()
  192. self.mode = mode
  193. self.encoding = encoding
  194. def _write_obj(self, out_path, obj):
  195. """write text object"""
  196. with open(out_path, mode=self.mode, encoding=self.encoding) as f:
  197. f.write(obj)
  198. class HtmlWriterBackend(_BaseWriterBackend):
  199. def __init__(self, mode="w", encoding="utf-8"):
  200. super().__init__()
  201. self.mode = mode
  202. self.encoding = encoding
  203. def _write_obj(self, out_path, obj, **bk_args):
  204. with open(out_path, mode=self.mode, encoding=self.encoding) as f:
  205. f.write(obj)
  206. class XlsxWriterBackend(_BaseWriterBackend):
  207. def _write_obj(self, out_path, obj, **bk_args):
  208. document_to_xl(obj, out_path)
  209. class _ImageWriterBackend(_BaseWriterBackend):
  210. """_ImageWriterBackend"""
  211. pass
  212. class OpenCVImageWriterBackend(_ImageWriterBackend):
  213. """OpenCVImageWriterBackend"""
  214. def _write_obj(self, out_path, obj):
  215. """write image object by OpenCV"""
  216. if isinstance(obj, Image.Image):
  217. arr = np.asarray(obj)
  218. elif isinstance(obj, np.ndarray):
  219. arr = obj
  220. else:
  221. raise TypeError("Unsupported object type")
  222. return cv2.imwrite(out_path, arr)
  223. class PILImageWriterBackend(_ImageWriterBackend):
  224. """PILImageWriterBackend"""
  225. def __init__(self, format_=None):
  226. super().__init__()
  227. self.format = format_
  228. def _write_obj(self, out_path, obj):
  229. """write image object by PIL"""
  230. if isinstance(obj, Image.Image):
  231. img = obj
  232. elif isinstance(obj, np.ndarray):
  233. img = Image.fromarray(obj)
  234. else:
  235. raise TypeError("Unsupported object type")
  236. if len(img.getbands()) == 4:
  237. self.format = "PNG"
  238. return img.save(out_path, format=self.format)
  239. class _VideoWriterBackend(_BaseWriterBackend):
  240. """_VideoWriterBackend"""
  241. pass
  242. class OpenCVVideoWriterBackend(_VideoWriterBackend):
  243. """OpenCVImageWriterBackend"""
  244. def _write_obj(self, out_path, obj):
  245. """write video object by OpenCV"""
  246. obj, fps = obj
  247. if isinstance(obj, np.ndarray):
  248. vr = obj
  249. width, height = vr[0].shape[1], vr[0].shape[0]
  250. fourcc = cv2.VideoWriter_fourcc(*"mp4v") # Alternatively, use 'XVID'
  251. out = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
  252. for frame in vr:
  253. out.write(frame)
  254. out.release()
  255. else:
  256. raise TypeError("Unsupported object type")
  257. class _BaseJsonWriterBackend(object):
  258. def __init__(self, indent=4, ensure_ascii=False):
  259. super().__init__()
  260. self.indent = indent
  261. self.ensure_ascii = ensure_ascii
  262. def write_obj(self, out_path, obj, **bk_args):
  263. Path(out_path).parent.mkdir(parents=True, exist_ok=True)
  264. return self._write_obj(out_path, obj, **bk_args)
  265. def _write_obj(self, out_path, obj):
  266. raise NotImplementedError
  267. class JsonWriterBackend(_BaseJsonWriterBackend):
  268. def _write_obj(self, out_path, obj, **bk_args):
  269. with open(out_path, "w") as f:
  270. json.dump(obj, f, **bk_args)
  271. class UJsonWriterBackend(_BaseJsonWriterBackend):
  272. # TODO
  273. def _write_obj(self, out_path, obj, **bk_args):
  274. raise NotImplementedError
  275. class YAMLWriterBackend(_BaseWriterBackend):
  276. def __init__(self, mode="w", encoding="utf-8"):
  277. super().__init__()
  278. self.mode = mode
  279. self.encoding = encoding
  280. def _write_obj(self, out_path, obj, **bk_args):
  281. """write text object"""
  282. with open(out_path, mode=self.mode, encoding=self.encoding) as f:
  283. yaml.dump(obj, f, **bk_args)
  284. class CSVWriter(_BaseWriter):
  285. """CSVWriter"""
  286. def __init__(self, backend="pandas", **bk_args):
  287. super().__init__(backend=backend, **bk_args)
  288. def write(self, out_path, obj):
  289. """write"""
  290. return self._backend.write_obj(str(out_path), obj)
  291. def _init_backend(self, bk_type, bk_args):
  292. """init backend"""
  293. if bk_type == "pandas":
  294. return PandasCSVWriterBackend(**bk_args)
  295. else:
  296. raise ValueError("Unsupported backend type")
  297. def get_type(self):
  298. """get type"""
  299. return WriterType.CSV
  300. class _CSVWriterBackend(_BaseWriterBackend):
  301. """_CSVWriterBackend"""
  302. pass
  303. class PandasCSVWriterBackend(_CSVWriterBackend):
  304. """PILImageWriterBackend"""
  305. def __init__(self):
  306. super().__init__()
  307. def _write_obj(self, out_path, obj):
  308. """write image object by PIL"""
  309. if isinstance(obj, pd.DataFrame):
  310. ts = obj
  311. else:
  312. raise TypeError("Unsupported object type")
  313. return ts.to_csv(out_path)