writers.py 12 KB

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