writers.py 10.0 KB

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