writers.py 9.0 KB

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