csv.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import csv
  12. from datetime import datetime, timedelta
  13. from typing import Any, Dict, List, Optional, Set
  14. import numpy as np
  15. import pandas as pd
  16. from taipy.config.common.scope import Scope
  17. from .._version._version_manager_factory import _VersionManagerFactory
  18. from ..job.job_id import JobId
  19. from ._file_datanode_mixin import _FileDataNodeMixin
  20. from ._tabular_datanode_mixin import _TabularDataNodeMixin
  21. from .data_node import DataNode
  22. from .data_node_id import DataNodeId, Edit
  23. class CSVDataNode(DataNode, _FileDataNodeMixin, _TabularDataNodeMixin):
  24. """Data Node stored as a CSV file.
  25. Attributes:
  26. config_id (str): Identifier of the data node configuration. This string must be a valid
  27. Python identifier.
  28. scope (Scope^): The scope of this data node.
  29. id (str): The unique identifier of this data node.
  30. owner_id (str): The identifier of the owner (sequence_id, scenario_id, cycle_id) or `None`.
  31. parent_ids (Optional[Set[str]]): The identifiers of the parent tasks or `None`.
  32. last_edit_date (datetime): The date and time of the last modification.
  33. edits (List[Edit^]): The ordered list of edits for that job.
  34. version (str): The string indicates the application version of the data node to instantiate. If not provided,
  35. the current version is used.
  36. validity_period (Optional[timedelta]): The duration implemented as a timedelta since the last edit date for
  37. which the data node can be considered up-to-date. Once the validity period has passed, the data node is
  38. considered stale and relevant tasks will run even if they are skippable (see the
  39. [Task management page](../core/entities/task-mgt.md) for more details).
  40. If _validity_period_ is set to `None`, the data node is always up-to-date.
  41. edit_in_progress (bool): True if a task computing the data node has been submitted
  42. and not completed yet. False otherwise.
  43. editor_id (Optional[str]): The identifier of the user who is currently editing the data node.
  44. editor_expiration_date (Optional[datetime]): The expiration date of the editor lock.
  45. path (str): The path to the CSV file.
  46. properties (dict[str, Any]): A dictionary of additional properties. The _properties_
  47. must have a _"default_path"_ or _"path"_ entry with the path of the CSV file:
  48. - _"default_path"_ `(str)`: The default path of the CSV file.\n
  49. - _"encoding"_ `(str)`: The encoding of the CSV file. The default value is `utf-8`.\n
  50. - _"default_data"_: The default data of the data nodes instantiated from this csv data node.\n
  51. - _"has_header"_ `(bool)`: If True, indicates that the CSV file has a header.\n
  52. - _"exposed_type"_: The exposed type of the data read from CSV file. The default value is `pandas`.\n
  53. """
  54. __STORAGE_TYPE = "csv"
  55. __ENCODING_KEY = "encoding"
  56. _REQUIRED_PROPERTIES: List[str] = []
  57. def __init__(
  58. self,
  59. config_id: str,
  60. scope: Scope,
  61. id: Optional[DataNodeId] = None,
  62. owner_id: Optional[str] = None,
  63. parent_ids: Optional[Set[str]] = None,
  64. last_edit_date: Optional[datetime] = None,
  65. edits: Optional[List[Edit]] = None,
  66. version: Optional[str] = None,
  67. validity_period: Optional[timedelta] = None,
  68. edit_in_progress: bool = False,
  69. editor_id: Optional[str] = None,
  70. editor_expiration_date: Optional[datetime] = None,
  71. properties: Optional[Dict] = None,
  72. ):
  73. self.id = id or self._new_id(config_id)
  74. if properties is None:
  75. properties = {}
  76. if self.__ENCODING_KEY not in properties.keys():
  77. properties[self.__ENCODING_KEY] = "utf-8"
  78. if self._HAS_HEADER_PROPERTY not in properties.keys():
  79. properties[self._HAS_HEADER_PROPERTY] = True
  80. properties[self._EXPOSED_TYPE_PROPERTY] = _TabularDataNodeMixin._get_valid_exposed_type(properties)
  81. self._check_exposed_type(properties[self._EXPOSED_TYPE_PROPERTY])
  82. default_value = properties.pop(self._DEFAULT_DATA_KEY, None)
  83. _FileDataNodeMixin.__init__(self, properties)
  84. _TabularDataNodeMixin.__init__(self, **properties)
  85. DataNode.__init__(
  86. self,
  87. config_id,
  88. scope,
  89. self.id,
  90. owner_id,
  91. parent_ids,
  92. last_edit_date,
  93. edits,
  94. version or _VersionManagerFactory._build_manager()._get_latest_version(),
  95. validity_period,
  96. edit_in_progress,
  97. editor_id,
  98. editor_expiration_date,
  99. **properties,
  100. )
  101. self._write_default_data(default_value)
  102. self._TAIPY_PROPERTIES.update(
  103. {
  104. self._PATH_KEY,
  105. self._DEFAULT_PATH_KEY,
  106. self._DEFAULT_DATA_KEY,
  107. self._IS_GENERATED_KEY,
  108. self._HAS_HEADER_PROPERTY,
  109. self._EXPOSED_TYPE_PROPERTY,
  110. self.__ENCODING_KEY,
  111. }
  112. )
  113. @classmethod
  114. def storage_type(cls) -> str:
  115. return cls.__STORAGE_TYPE
  116. def _read(self):
  117. if self.properties[self._EXPOSED_TYPE_PROPERTY] == self._EXPOSED_TYPE_PANDAS:
  118. return self._read_as_pandas_dataframe()
  119. if self.properties[self._EXPOSED_TYPE_PROPERTY] == self._EXPOSED_TYPE_NUMPY:
  120. return self._read_as_numpy()
  121. return self._read_as()
  122. def _read_as(self):
  123. with open(self._path, encoding=self.properties[self.__ENCODING_KEY]) as csvFile:
  124. if self.properties[self._HAS_HEADER_PROPERTY]:
  125. reader = csv.DictReader(csvFile)
  126. else:
  127. reader = csv.reader(csvFile)
  128. return [self._decoder(line) for line in reader]
  129. def _read_as_numpy(self) -> np.ndarray:
  130. return self._read_as_pandas_dataframe().to_numpy()
  131. def _read_as_pandas_dataframe(
  132. self, usecols: Optional[List[int]] = None, column_names: Optional[List[str]] = None
  133. ) -> pd.DataFrame:
  134. try:
  135. if self.properties[self._HAS_HEADER_PROPERTY]:
  136. if column_names:
  137. return pd.read_csv(self._path, encoding=self.properties[self.__ENCODING_KEY])[column_names]
  138. return pd.read_csv(self._path, encoding=self.properties[self.__ENCODING_KEY])
  139. else:
  140. if usecols:
  141. return pd.read_csv(
  142. self._path, encoding=self.properties[self.__ENCODING_KEY], header=None, usecols=usecols
  143. )
  144. return pd.read_csv(self._path, encoding=self.properties[self.__ENCODING_KEY], header=None)
  145. except pd.errors.EmptyDataError:
  146. return pd.DataFrame()
  147. def _append(self, data: Any):
  148. if isinstance(data, pd.DataFrame):
  149. data.to_csv(self._path, mode="a", index=False, encoding=self.properties[self.__ENCODING_KEY], header=False)
  150. else:
  151. pd.DataFrame(data).to_csv(
  152. self._path, mode="a", index=False, encoding=self.properties[self.__ENCODING_KEY], header=False
  153. )
  154. def _write(self, data: Any):
  155. exposed_type = self.properties[self._EXPOSED_TYPE_PROPERTY]
  156. if self.properties[self._HAS_HEADER_PROPERTY]:
  157. self._convert_data_to_dataframe(exposed_type, data).to_csv(
  158. self._path, index=False, encoding=self.properties[self.__ENCODING_KEY]
  159. )
  160. else:
  161. self._convert_data_to_dataframe(exposed_type, data).to_csv(
  162. self._path, index=False, encoding=self.properties[self.__ENCODING_KEY], header=None
  163. )
  164. def write_with_column_names(self, data: Any, columns: Optional[List[str]] = None, job_id: Optional[JobId] = None):
  165. """Write a selection of columns.
  166. Parameters:
  167. data (Any): The data to write.
  168. columns (Optional[List[str]]): The list of column names to write.
  169. job_id (JobId^): An optional identifier of the writer.
  170. """
  171. df = self._convert_data_to_dataframe(self.properties[self._EXPOSED_TYPE_PROPERTY], data)
  172. if columns and isinstance(df, pd.DataFrame):
  173. df.columns = columns
  174. df.to_csv(self._path, index=False, encoding=self.properties[self.__ENCODING_KEY])
  175. self.track_edit(timestamp=datetime.now(), job_id=job_id)