mixin.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. from typing import Union, Tuple, List, Dict, Any, Iterator
  15. from abc import abstractmethod
  16. from pathlib import Path
  17. import mimetypes
  18. import json
  19. import copy
  20. import numpy as np
  21. from PIL import Image
  22. import pandas as pd
  23. from ....utils import logging
  24. from ...utils.io import (
  25. JsonWriter,
  26. ImageReader,
  27. ImageWriter,
  28. CSVWriter,
  29. HtmlWriter,
  30. XlsxWriter,
  31. TextWriter,
  32. VideoWriter,
  33. )
  34. class StrMixin:
  35. """Mixin class for adding string conversion capabilities."""
  36. @property
  37. def str(self) -> str:
  38. """Property to get the string representation of the result.
  39. Returns:
  40. str: The str type string representation of the result.
  41. """
  42. return self._to_str(self)
  43. def _to_str(
  44. self,
  45. data: dict,
  46. json_format: bool = False,
  47. indent: int = 4,
  48. ensure_ascii: bool = False,
  49. ) -> str:
  50. """Convert the given result data to a string representation.
  51. Args:
  52. data (dict): The data would be converted to str.
  53. json_format (bool): If True, return a JSON formatted string. Default is False.
  54. indent (int): Number of spaces to indent for JSON formatting. Default is 4.
  55. ensure_ascii (bool): If True, ensure all characters are ASCII. Default is False.
  56. Returns:
  57. str: The string representation of the data.
  58. """
  59. if json_format:
  60. return json.dumps(data.json, indent=indent, ensure_ascii=ensure_ascii)
  61. else:
  62. return str(data)
  63. def print(
  64. self, json_format: bool = False, indent: int = 4, ensure_ascii: bool = False
  65. ) -> None:
  66. """Print the string representation of the result.
  67. Args:
  68. json_format (bool): If True, print a JSON formatted string. Default is False.
  69. indent (int): Number of spaces to indent for JSON formatting. Default is 4.
  70. ensure_ascii (bool): If True, ensure all characters are ASCII. Default is False.
  71. """
  72. str_ = self._to_str(
  73. self, json_format=json_format, indent=indent, ensure_ascii=ensure_ascii
  74. )
  75. logging.info(str_)
  76. class JsonMixin:
  77. """Mixin class for adding JSON serialization capabilities."""
  78. def __init__(self) -> None:
  79. self._json_writer = JsonWriter()
  80. self._save_funcs.append(self.save_to_json)
  81. def _to_json(self) -> Dict[str, Any]:
  82. """Convert the object to a JSON-serializable format.
  83. Returns:
  84. Dict[str, Any]: A dictionary representation of the object that is JSON-serializable.
  85. """
  86. def _format_data(obj):
  87. """Helper function to format data into a JSON-serializable format.
  88. Args:
  89. obj: The object to be formatted.
  90. Returns:
  91. Any: The formatted object.
  92. """
  93. if isinstance(obj, np.float32):
  94. return float(obj)
  95. elif isinstance(obj, np.ndarray):
  96. return [_format_data(item) for item in obj.tolist()]
  97. elif isinstance(obj, pd.DataFrame):
  98. return obj.to_json(orient="records", force_ascii=False)
  99. elif isinstance(obj, Path):
  100. return obj.as_posix()
  101. elif isinstance(obj, dict):
  102. return dict({k: _format_data(v) for k, v in obj.items()})
  103. elif isinstance(obj, (list, tuple)):
  104. return [_format_data(i) for i in obj]
  105. else:
  106. return obj
  107. return _format_data(copy.deepcopy(self))
  108. @property
  109. def json(self) -> Dict[str, Any]:
  110. """Property to get the JSON representation of the result.
  111. Returns:
  112. Dict[str, Any]: The dict type JSON representation of the result.
  113. """
  114. return self._to_json()
  115. def save_to_json(
  116. self,
  117. save_path: str,
  118. indent: int = 4,
  119. ensure_ascii: bool = False,
  120. *args: List,
  121. **kwargs: Dict,
  122. ) -> None:
  123. """Save the JSON representation of the object to a file.
  124. Args:
  125. save_path (str): The path to save the JSON file. If the save path does not end with '.json', it appends the base name and suffix of the input path.
  126. indent (int): The number of spaces to indent for pretty printing. Default is 4.
  127. ensure_ascii (bool): If False, non-ASCII characters will be included in the output. Default is False.
  128. *args: Additional positional arguments to pass to the underlying writer.
  129. **kwargs: Additional keyword arguments to pass to the underlying writer.
  130. """
  131. def _is_json_file(file_path):
  132. mime_type, _ = mimetypes.guess_type(file_path)
  133. return mime_type is not None and mime_type == "application/json"
  134. if not _is_json_file(save_path):
  135. save_path = Path(save_path) / f"{Path(self['input_path']).stem}.json"
  136. save_path = save_path.as_posix()
  137. self._json_writer.write(
  138. save_path,
  139. self.json,
  140. indent=indent,
  141. ensure_ascii=ensure_ascii,
  142. *args,
  143. **kwargs,
  144. )
  145. class Base64Mixin:
  146. """Mixin class for adding Base64 encoding capabilities."""
  147. def __init__(self, *args: List, **kwargs: Dict) -> None:
  148. """Initializes the Base64Mixin.
  149. Args:
  150. *args: Positional arguments to pass to the TextWriter.
  151. **kwargs: Keyword arguments to pass to the TextWriter.
  152. """
  153. self._base64_writer = TextWriter(*args, **kwargs)
  154. self._save_funcs.append(self.save_to_base64)
  155. @abstractmethod
  156. def _to_base64(self) -> str:
  157. """Abstract method to convert the result to Base64.
  158. Returns:
  159. str: The str type Base64 representation result.
  160. """
  161. raise NotImplementedError
  162. @property
  163. def base64(self) -> str:
  164. """
  165. Property that returns the Base64 encoded content.
  166. Returns:
  167. str: The base64 representation of the result.
  168. """
  169. return self._to_base64()
  170. def save_to_base64(self, save_path: str, *args: List, **kwargs: Dict) -> None:
  171. """Saves the Base64 encoded content to the specified path.
  172. Args:
  173. save_path (str): The path to save the base64 representation result. If the save path does not end with '.b64', it appends the base name and suffix of the input path.
  174. *args: Additional positional arguments that will be passed to the base64 writer.
  175. **kwargs: Additional keyword arguments that will be passed to the base64 writer.
  176. """
  177. if not str(save_path).lower().endswith((".b64")):
  178. fp = Path(self["input_path"])
  179. save_path = Path(save_path) / f"{fp.stem}{fp.suffix}"
  180. else:
  181. save_path = Path(save_path)
  182. self._base64_writer.write(save_path.as_posix(), self.base64, *args, **kwargs)
  183. class ImgMixin:
  184. """Mixin class for adding image handling capabilities."""
  185. def __init__(self, backend: str = "pillow", *args: List, **kwargs: Dict) -> None:
  186. """Initializes ImgMixin.
  187. Args:
  188. backend (str): The backend to use for image processing. Defaults to "pillow".
  189. *args: Additional positional arguments to pass to the ImageWriter.
  190. **kwargs: Additional keyword arguments to pass to the ImageWriter.
  191. """
  192. self._img_writer = ImageWriter(backend=backend, *args, **kwargs)
  193. self._save_funcs.append(self.save_to_img)
  194. @abstractmethod
  195. def _to_img(self) -> Union[Image.Image, Dict[str, Image.Image]]:
  196. """Abstract method to convert the result to an image.
  197. Returns:
  198. Union[Image.Image, Dict[str, Image.Image]]: The image representation result.
  199. """
  200. raise NotImplementedError
  201. @property
  202. def img(self) -> Union[Image.Image, Dict[str, Image.Image]]:
  203. """Property to get the image representation of the result.
  204. Returns:
  205. Union[Image.Image, Dict[str, Image.Image]]: The image representation of the result.
  206. """
  207. return self._to_img()
  208. def save_to_img(self, save_path: str, *args: List, **kwargs: Dict) -> None:
  209. """Saves the image representation of the result to the specified path.
  210. Args:
  211. save_path (str): The path to save the image. If the save path does not end with .jpg or .png, it appends the input path's stem and suffix to the save path.
  212. *args: Additional positional arguments that will be passed to the image writer.
  213. **kwargs: Additional keyword arguments that will be passed to the image writer.
  214. """
  215. def _is_image_file(file_path):
  216. mime_type, _ = mimetypes.guess_type(file_path)
  217. return mime_type is not None and mime_type.startswith("image/")
  218. img = self.img
  219. if isinstance(img, dict):
  220. if not _is_image_file(save_path):
  221. fp = Path(self["input_path"])
  222. stem = fp.stem
  223. suffix = fp.suffix
  224. else:
  225. stem = save_path.stem
  226. suffix = save_path.suffix
  227. base_save_path = Path(save_path)
  228. for key in img:
  229. save_path = base_save_path / f"{stem}_{key}{suffix}"
  230. self._img_writer.write(save_path.as_posix(), img[key], *args, **kwargs)
  231. else:
  232. if not _is_image_file(save_path):
  233. fp = Path(self["input_path"])
  234. save_path = Path(save_path) / f"{fp.stem}{fp.suffix}"
  235. self._img_writer.write(save_path.as_posix(), img, *args, **kwargs)
  236. class CSVMixin:
  237. """Mixin class for adding CSV handling capabilities."""
  238. def __init__(self, backend: str = "pandas", *args: List, **kwargs: Dict) -> None:
  239. """Initializes the CSVMixin.
  240. Args:
  241. backend (str): The backend to use for CSV operations (default is "pandas").
  242. *args: Optional positional arguments to pass to the CSVWriter.
  243. **kwargs: Optional keyword arguments to pass to the CSVWriter.
  244. """
  245. self._csv_writer = CSVWriter(backend=backend, *args, **kwargs)
  246. if not hasattr(self, "_save_funcs"):
  247. self._save_funcs = []
  248. self._save_funcs.append(self.save_to_csv)
  249. @property
  250. def csv(self) -> pd.DataFrame:
  251. """Property to get the pandas Dataframe representation of the result.
  252. Returns:
  253. pandas.DataFrame: The pandas.DataFrame representation of the result.
  254. """
  255. return self._to_csv()
  256. @abstractmethod
  257. def _to_csv(self) -> pd.DataFrame:
  258. """Abstract method to convert the result to pandas.DataFrame.
  259. Returns:
  260. pandas.DataFrame: The pandas.DataFrame representation result.
  261. """
  262. raise NotImplementedError
  263. def save_to_csv(self, save_path: str, *args: List, **kwargs: Dict) -> None:
  264. """Saves the result to a CSV file.
  265. Args:
  266. save_path (str): The path to save the CSV file. If the path does not end with ".csv",
  267. the stem of the input path attribute (self['input_path']) will be used as the filename.
  268. *args: Optional positional arguments to pass to the CSV writer's write method.
  269. **kwargs: Optional keyword arguments to pass to the CSV writer's write method.
  270. """
  271. if not str(save_path).endswith(".csv"):
  272. save_path = Path(save_path) / f"{Path(self['input_path']).stem}.csv"
  273. else:
  274. save_path = Path(save_path)
  275. self._csv_writer.write(save_path.as_posix(), self.csv, *args, **kwargs)
  276. class HtmlMixin:
  277. """Mixin class for adding HTML handling capabilities."""
  278. def __init__(self, *args: List, **kwargs: Dict) -> None:
  279. """
  280. Initializes the HTML writer and appends the save_to_html method to the save functions list.
  281. Args:
  282. *args: Positional arguments passed to the HtmlWriter.
  283. **kwargs: Keyword arguments passed to the HtmlWriter.
  284. """
  285. self._html_writer = HtmlWriter(*args, **kwargs)
  286. self._save_funcs.append(self.save_to_html)
  287. @property
  288. def html(self) -> str:
  289. """Property to get the HTML representation of the result.
  290. Returns:
  291. str: The str type HTML representation of the result.
  292. """
  293. return self._to_html()
  294. @abstractmethod
  295. def _to_html(self) -> str:
  296. """Abstract method to convert the result to str type HTML representation.
  297. Returns:
  298. str: The str type HTML representation result.
  299. """
  300. raise NotImplementedError
  301. def save_to_html(self, save_path: str, *args: List, **kwargs: Dict) -> None:
  302. """Saves the HTML representation of the object to the specified path.
  303. Args:
  304. save_path (str): The path to save the HTML file.
  305. *args: Additional positional arguments.
  306. **kwargs: Additional keyword arguments.
  307. """
  308. if not str(save_path).endswith(".html"):
  309. save_path = Path(save_path) / f"{Path(self['input_path']).stem}.html"
  310. else:
  311. save_path = Path(save_path)
  312. self._html_writer.write(save_path.as_posix(), self.html, *args, **kwargs)
  313. class XlsxMixin:
  314. """Mixin class for adding XLSX handling capabilities."""
  315. def __init__(self, *args: List, **kwargs: Dict) -> None:
  316. """Initializes the XLSX writer and appends the save_to_xlsx method to the save functions.
  317. Args:
  318. *args: Positional arguments to be passed to the XlsxWriter constructor.
  319. **kwargs: Keyword arguments to be passed to the XlsxWriter constructor.
  320. """
  321. self._xlsx_writer = XlsxWriter(*args, **kwargs)
  322. self._save_funcs.append(self.save_to_xlsx)
  323. @property
  324. def xlsx(self) -> str:
  325. """Property to get the XLSX representation of the result.
  326. Returns:
  327. str: The str type XLSX representation of the result.
  328. """
  329. return self._to_xlsx()
  330. @abstractmethod
  331. def _to_xlsx(self) -> str:
  332. """Abstract method to convert the result to str type XLSX representation.
  333. Returns:
  334. str: The str type HTML representation result.
  335. """
  336. raise NotImplementedError
  337. def save_to_xlsx(self, save_path: str, *args: List, **kwargs: Dict) -> None:
  338. """Saves the HTML representation to an XLSX file.
  339. Args:
  340. save_path (str): The path to save the XLSX file. If the path does not end with ".xlsx",
  341. the filename will be set to the stem of the input path with ".xlsx" extension.
  342. *args: Additional positional arguments to pass to the XLSX writer.
  343. **kwargs: Additional keyword arguments to pass to the XLSX writer.
  344. """
  345. if not str(save_path).endswith(".xlsx"):
  346. save_path = Path(save_path) / f"{Path(self['input_path']).stem}.xlsx"
  347. else:
  348. save_path = Path(save_path)
  349. self._xlsx_writer.write(save_path.as_posix(), self.xlsx, *args, **kwargs)
  350. class VideoMixin:
  351. def __init__(self, backend="opencv", *args, **kwargs):
  352. self._backend = backend
  353. self._save_funcs.append(self.save_to_video)
  354. @abstractmethod
  355. def _to_video(self):
  356. raise NotImplementedError
  357. @property
  358. def video(self):
  359. video = self._to_video()
  360. return video
  361. def save_to_video(self, save_path, *args, **kwargs):
  362. video_writer = VideoWriter(backend=self._backend, *args, **kwargs)
  363. if not str(save_path).lower().endswith((".mp4", ".avi", ".mkv", ".webm")):
  364. fp = Path(self["input_path"])
  365. save_path = Path(save_path) / f"{fp.stem}{fp.suffix}"
  366. _save_list_data(video_writer.write, save_path, self.video, *args, **kwargs)