diff --git a/ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/exp_avg_sq.pt b/ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..006a108ba49ec266940c2bf37d4162a324ddc33f --- /dev/null +++ b/ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5b62e6ac763e6b168c91d08d0a8eebe05d5a993d9d871af59777d5793f0d716 +size 33555627 diff --git a/ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/fp32.pt b/ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..c124216e7cd0b8109bf64f1504be411d2787d45f --- /dev/null +++ b/ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2349d88812163b3b6d673cc809aa8dc9b6571f3c2dfc8e4b6625835e2cc2263d +size 33555533 diff --git a/ckpts/universal/global_step80/zero/19.attention.dense.weight/fp32.pt b/ckpts/universal/global_step80/zero/19.attention.dense.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..e62c6c2c2717c9e337be1f2b2ffeefa020544db3 --- /dev/null +++ b/ckpts/universal/global_step80/zero/19.attention.dense.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf760ef522c939521fe0d8a7dfe4d7bb297517e0c98c217476377b007be61a7a +size 16778317 diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11f4dfce8451c1be275dfeb470c998c10b3e043f Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_logger.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b08e61b64a6072217192d58bd7d42e97a39b7d75 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_logger.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_null_logger.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_null_logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed2617d114649611e076cb1b824cfd22f24c0fe1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_null_logger.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..674ebc78d5f71c90cc5aafb9e45de6a20f255d32 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/__init__.py @@ -0,0 +1,74 @@ +from ._elasticsearch import ElasticsearchWriter +from ._null import NullTableWriter +from ._table_writer import AbstractTableWriter +from .binary import ( + ExcelXlsTableWriter, + ExcelXlsxTableWriter, + PandasDataFramePickleWriter, + SqliteTableWriter, +) +from .text import ( + AsciiDocTableWriter, + BoldUnicodeTableWriter, + BorderlessTableWriter, + CssTableWriter, + CsvTableWriter, + HtmlTableWriter, + JsonLinesTableWriter, + JsonTableWriter, + LatexMatrixWriter, + LatexTableWriter, + LtsvTableWriter, + MarkdownTableWriter, + MediaWikiTableWriter, + RstCsvTableWriter, + RstGridTableWriter, + RstSimpleTableWriter, + SpaceAlignedTableWriter, + TomlTableWriter, + TsvTableWriter, + UnicodeTableWriter, + YamlTableWriter, +) +from .text.sourcecode import ( + JavaScriptTableWriter, + NumpyTableWriter, + PandasDataFrameWriter, + PythonCodeTableWriter, +) + + +__all__ = ( + "AbstractTableWriter", + "AsciiDocTableWriter", + "BoldUnicodeTableWriter", + "BorderlessTableWriter", + "CssTableWriter", + "CsvTableWriter", + "ElasticsearchWriter", + "ExcelXlsTableWriter", + "ExcelXlsxTableWriter", + "HtmlTableWriter", + "JavaScriptTableWriter", + "JsonLinesTableWriter", + "JsonTableWriter", + "LatexMatrixWriter", + "LatexTableWriter", + "LtsvTableWriter", + "MarkdownTableWriter", + "MediaWikiTableWriter", + "NullTableWriter", + "NumpyTableWriter", + "PandasDataFramePickleWriter", + "PandasDataFrameWriter", + "PythonCodeTableWriter", + "RstCsvTableWriter", + "RstGridTableWriter", + "RstSimpleTableWriter", + "SpaceAlignedTableWriter", + "SqliteTableWriter", + "TomlTableWriter", + "TsvTableWriter", + "UnicodeTableWriter", + "YamlTableWriter", +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9075cafdcccfcff7ec63c838c5a25defe0a897d Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_common.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00baa791c73665c32bffd8b608cd7fbf3a228adf Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_elasticsearch.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_elasticsearch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..254ad9baa624e130e67b2e84403064fd61535680 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_elasticsearch.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_interface.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_interface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf02c54479a9f10a3cf518259ebde041c1c66c5e Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_interface.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_msgfy.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_msgfy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9fa66c9b13a5fe9f2f86a55fca0434a9665d69f Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_msgfy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_null.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_null.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ffe0aac81ace0047c0dc5c72fd6b1dbe2429009 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_null.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_table_writer.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_table_writer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc3c7f733358008fd0932087da6ed7690da383c4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_table_writer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/_common.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..f25d1762a30b71840cf58011b0d4a841827b63cd --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/_common.py @@ -0,0 +1,12 @@ +from textwrap import dedent + + +HEADER_ROW = -1 + + +import_error_msg_template = dedent( + """\ + dependency packages for {0} not found. + you can install the dependencies with 'pip install pytablewriter[{0}]' + """ +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/_elasticsearch.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/_elasticsearch.py new file mode 100644 index 0000000000000000000000000000000000000000..b8c76c839453548927bba305a02715a695637b8d --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/_elasticsearch.py @@ -0,0 +1,204 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + + +import copy +from typing import Any, Dict, Generator + +import dataproperty +from dataproperty import ColumnDataProperty +from typepy import Typecode + +from ..error import EmptyValueError +from ._msgfy import to_error_message +from ._table_writer import AbstractTableWriter + + +DataType = Dict[str, str] +Properties = Dict[str, DataType] + + +def _get_es_datatype(column_dp: ColumnDataProperty) -> DataType: + if column_dp.typecode in ( + Typecode.NONE, + Typecode.NULL_STRING, + Typecode.INFINITY, + Typecode.NAN, + ): + return {"type": "keyword"} + + if column_dp.typecode == Typecode.STRING: + return {"type": "text"} + + if column_dp.typecode == Typecode.DATETIME: + return {"type": "date", "format": "date_optional_time"} + + if column_dp.typecode == Typecode.REAL_NUMBER: + return {"type": "double"} + + if column_dp.typecode == Typecode.BOOL: + return {"type": "boolean"} + + if column_dp.typecode == Typecode.IP_ADDRESS: + return {"type": "ip"} + + if column_dp.typecode == Typecode.INTEGER: + assert column_dp.bit_length is not None + + if column_dp.bit_length <= 8: + return {"type": "byte"} + elif column_dp.bit_length <= 16: + return {"type": "short"} + elif column_dp.bit_length <= 32: + return {"type": "integer"} + elif column_dp.bit_length <= 64: + return {"type": "long"} + + raise ValueError( + f"too large integer bits: expected<=64bits, actual={column_dp.bit_length:d}bits" + ) + + raise ValueError(f"unknown typecode: {column_dp.typecode}") + + +class ElasticsearchWriter(AbstractTableWriter): + """ + A table writer class for Elasticsearch. + + :Dependency Packages: + - `elasticsearch-py `__ + + .. py:attribute:: index_name + :type: str + + Alias attribute for |table_name|. + + .. py:attribute:: document_type + :type: str + :value: "table" + + Specify document type for indices. + + .. py:method:: write_table() + + Create an index and put documents for each row to Elasticsearch. + + You need to pass an + `elasticsearch.Elasticsearch `__ + instance to |stream| before calling this method. + |table_name|/:py:attr:`~pytablewriter.ElasticsearchWriter.index_name` + used as the creating index name, + invalid characters in the name are replaced with underscores (``'_'``). + Document data types for documents are automatically detected from the data. + + :raises ValueError: + If the |stream| has not elasticsearch.Elasticsearch instance. + :Example: + :ref:`example-elasticsearch-table-writer` + """ + + FORMAT_NAME = "elasticsearch" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + @property + def table_name(self) -> str: + return super().table_name + + @table_name.setter + def table_name(self, value: str) -> None: + from pathvalidate import ErrorReason, ValidationError + + from ..sanitizer import ElasticsearchIndexNameSanitizer + + try: + self._table_name = ElasticsearchIndexNameSanitizer(value).sanitize(replacement_text="_") + except ValidationError as e: + if e.reason is ErrorReason.NULL_NAME: + self._table_name = "" + else: + raise + + @property + def index_name(self) -> str: + return self.table_name + + @index_name.setter + def index_name(self, value: str) -> None: + self.table_name = value + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.stream = None + self.is_padding = False + self.is_formatting_float = False + self._is_require_table_name = True + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) + self._dp_extractor.type_value_map = copy.deepcopy(dataproperty.DefaultValue.TYPE_VALUE_MAP) + + self.document_type = "table" + + def write_null_line(self) -> None: + pass + + def _get_mappings(self) -> Dict[str, Dict[str, Dict[str, Properties]]]: + properties: Properties = {} + + for header, column_dp in zip(self.headers, self._column_dp_list): + properties[header] = _get_es_datatype(column_dp) + + return {"mappings": {self.document_type: {"properties": properties}}} + + def _get_body(self) -> Generator: + str_datatype = (Typecode.DATETIME, Typecode.IP_ADDRESS, Typecode.INFINITY, Typecode.NAN) + + for value_dp_list in self._table_value_dp_matrix: + values = [ + value_dp.data if value_dp.typecode not in str_datatype else value_dp.to_str() + for value_dp in value_dp_list + ] + + yield dict(zip(self.headers, values)) + + def _write_table(self, **kwargs: Any) -> None: + import elasticsearch as es + + if not isinstance(self.stream, es.Elasticsearch): + raise ValueError("stream must be an elasticsearch.Elasticsearch instance") + + try: + self._verify_value_matrix() + except EmptyValueError: + self._logger.logger.debug("no tabular data found") + return + + self._preprocess() + + mappings = self._get_mappings() + + try: + result = self.stream.indices.create(index=self.index_name, body=mappings) + self._logger.logger.debug(result) + except es.TransportError as e: + if e.error == "index_already_exists_exception": + # ignore already existing index + self._logger.logger.debug(to_error_message(e)) + else: + raise + + for body in self._get_body(): + try: + self.stream.index(index=self.index_name, body=body, doc_type=self.document_type) + except es.exceptions.RequestError as e: + self._logger.logger.error(f"{to_error_message(e)}, body={body}") + + def _write_value_row_separator(self) -> None: + pass diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/_interface.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..8eecc768d5b114c383fa3c323fd7428ddb410f24 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/_interface.py @@ -0,0 +1,84 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import abc +from typing import IO, Any, Union + + +class TableWriterInterface(metaclass=abc.ABCMeta): + """ + Interface class for writing a table. + """ + + @abc.abstractproperty + def format_name(self) -> str: # pragma: no cover + """Format name for the writer. + + Returns: + |str| + """ + + @abc.abstractproperty + def support_split_write(self) -> bool: # pragma: no cover + """Indicates whether the writer class supports iterative table writing (``write_table_iter``) method. + + Returns: + bool: |True| if the writer supported iterative table writing. + """ + + @abc.abstractmethod + def write_table(self, **kwargs: Any) -> None: # pragma: no cover + """ + |write_table|. + """ + + def dump( + self, output: Union[str, IO], close_after_write: bool, **kwargs: Any + ) -> None: # pragma: no cover + raise NotImplementedError(f"{self.format_name} writer did not support dump method") + + def dumps(self) -> str: # pragma: no cover + raise NotImplementedError(f"{self.format_name} writer did not support dumps method") + + def write_table_iter(self, **kwargs: Any) -> None: # pragma: no cover + """ + Write a table with iteration. + "Iteration" means that divide the table writing into multiple writes. + This method is helpful, especially for extensive data. + The following are the premises to execute this method: + + - set iterator to the |value_matrix| + - set the number of iterations to the |iteration_length| attribute + + Call back function (Optional): + A callback function is called when each iteration of writing a table is completed. + You can set a callback function via the |write_callback| attribute. + + Raises: + pytablewriter.NotSupportedError: If the writer class does not support this method. + + .. note:: + The following classes do not support this method: + + - |HtmlTableWriter| + - |RstGridTableWriter| + - |RstSimpleTableWriter| + + ``support_split_write`` attribute return |True| if the class + is supporting this method. + """ + + self._write_table_iter(**kwargs) + + @abc.abstractmethod + def _write_table_iter(self, **kwargs: Any) -> None: # pragma: no cover + pass + + @abc.abstractmethod + def close(self) -> None: # pragma: no cover + pass + + @abc.abstractmethod + def _write_value_row_separator(self) -> None: # pragma: no cover + pass diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/_msgfy.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/_msgfy.py new file mode 100644 index 0000000000000000000000000000000000000000..eb77f6a2ee55b1955dd25c89832f1472f9a61704 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/_msgfy.py @@ -0,0 +1,56 @@ +""" +Import from https://github.com/thombashi/msgfy +""" + +import inspect +import os.path +from types import FrameType +from typing import Optional + + +DEFAULT_ERROR_MESSAGE_FORMAT = "{exception}: {error_msg}" +DEFAULT_DEBUG_MESSAGE_FORMAT = "{exception} {file_name}({line_no}) {func_name}: {error_msg}" + +error_message_format = DEFAULT_ERROR_MESSAGE_FORMAT +debug_message_format = DEFAULT_DEBUG_MESSAGE_FORMAT + + +def _to_message(exception_obj: Exception, format_str: str, frame: Optional[FrameType]) -> str: + if not isinstance(exception_obj, Exception): + raise ValueError("exception_obj must be an instance of a subclass of the Exception class") + + if frame is None: + return str(exception_obj) + + try: + return ( + format_str.replace("{exception}", exception_obj.__class__.__name__) + .replace("{file_name}", os.path.basename(frame.f_code.co_filename)) + .replace("{line_no}", str(frame.f_lineno)) + .replace("{func_name}", frame.f_code.co_name) + .replace("{error_msg}", str(exception_obj)) + ) + except AttributeError: + raise ValueError("format_str must be a string") + + +def to_error_message(exception_obj: Exception, format_str: Optional[str] = None) -> str: + if not format_str: + format_str = error_message_format + + frame = inspect.currentframe() + if frame is None: + return str(exception_obj) + + return _to_message(exception_obj, format_str, frame.f_back) + + +def to_debug_message(exception_obj: Exception, format_str: Optional[str] = None) -> str: + if not format_str: + format_str = debug_message_format + + frame = inspect.currentframe() + if frame is None: + return str(exception_obj) + + return _to_message(exception_obj, format_str, frame.f_back) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/_null.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/_null.py new file mode 100644 index 0000000000000000000000000000000000000000..0d45b37ad6419c3dd9c381e79fcb1beaa3a16b62 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/_null.py @@ -0,0 +1,61 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from typing import IO, Any, Union + +from ._interface import TableWriterInterface +from .text._interface import IndentationInterface, TextWriterInterface + + +class NullTableWriter(IndentationInterface, TextWriterInterface, TableWriterInterface): + FORMAT_NAME = "null" + + def __init__(self, **kwargs: Any) -> None: + self.table_name = kwargs.get("table_name", "") + self.value_matrix = kwargs.get("value_matrix", []) + self.is_formatting_float = kwargs.get("is_formatting_float", True) + self.headers = kwargs.get("headers", []) + self.type_hints = kwargs.get("type_hints", []) + self.max_workers = kwargs.get("max_workers", 1) + + def __repr__(self) -> str: + return self.dumps() + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def set_indent_level(self, indent_level: int) -> None: + pass + + def inc_indent_level(self) -> None: + pass + + def dec_indent_level(self) -> None: + pass + + def write_null_line(self) -> None: + pass + + def write_table(self, **kwargs: Any) -> None: + pass + + def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None: + pass + + def dumps(self) -> str: + return "" + + def _write_table_iter(self, **kwargs: Any) -> None: + pass + + def close(self) -> None: + pass + + def _write_value_row_separator(self) -> None: + pass diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/_table_writer.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/_table_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6ed20b44f03f9a23cdac933e21f90b317699af --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/_table_writer.py @@ -0,0 +1,1245 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import abc +import copy +import math +import warnings +from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence, Union, cast + +import typepy +from dataproperty import ( + Align, + ColumnDataProperty, + DataProperty, + DataPropertyExtractor, + Format, + MatrixFormatting, + Preprocessor, +) +from dataproperty.typing import TransFunc +from tabledata import TableData, convert_idx_to_alphabet, to_value_matrix +from typepy import Typecode, extract_typepy_from_dtype + +from .._logger import WriterLogger +from ..error import EmptyTableDataError, EmptyTableNameError, EmptyValueError, NotSupportedError +from ..style import ( + Cell, + CheckStyleFilterKeywordArgsFunc, + ColSeparatorStyleFilterFunc, + Style, + StyleFilterFunc, + StylerInterface, + ThousandSeparator, + fetch_theme, +) +from ..typehint import Integer, TypeHint +from ._common import HEADER_ROW +from ._interface import TableWriterInterface +from ._msgfy import to_error_message + + +if TYPE_CHECKING: + import pandas + import tablib + + from .._table_format import TableFormat + +_ts_to_flag: Dict[ThousandSeparator, int] = { + ThousandSeparator.NONE: Format.NONE, + ThousandSeparator.COMMA: Format.THOUSAND_SEPARATOR, + ThousandSeparator.SPACE: Format.THOUSAND_SEPARATOR, + ThousandSeparator.UNDERSCORE: Format.THOUSAND_SEPARATOR, +} + + +def header_style_filter(cell: Cell, **kwargs: Any) -> Optional[Style]: + if cell.is_header_row(): + return Style(align=Align.CENTER) + + return None + + +DEFAULT_STYLE_FILTERS: List[StyleFilterFunc] = [header_style_filter] + + +class AbstractTableWriter(TableWriterInterface, metaclass=abc.ABCMeta): + """ + An abstract base class of table writer classes. + + Args: + max_precision (int): Maximum decimal places for real number values. + + dequote (bool): If |True|, dequote values in :py:attr:`~.value_matrix`. + + .. py:attribute:: stream + + Stream to write tables. + You can use arbitrary streams which support ``write``methods + such as ``sys.stdout``, file stream, ``StringIO``, and so forth. + Defaults to ``sys.stdout``. + + :Example: + :ref:`example-configure-stream` + + .. py:attribute:: is_write_header + :type: bool + + Write headers of a table if the value is |True|. + + .. py:attribute:: is_padding + :type: bool + + Padding for each item in the table if the value is |True|. + + .. py:attribute:: iteration_length + :type: int + + The number of iterations to write a table. + This value is used in :py:meth:`.write_table_iter` method. + (defaults to ``-1``, which means the number of iterations is indefinite) + + .. py:attribute:: style_filter_kwargs + :type: Dict[str, Any] + + Extra keyword arguments for style filter functions. + These arguments will pass to filter functions added by + :py:meth:`.add_style_filter` or :py:meth:`.add_col_separator_style_filter` + + .. py:attribute:: colorize_terminal + :type: bool + :value: True + + [Only available for text format writers] [experimental] + If |True|, colorize text outputs with |Style|. + + .. py:attribute:: enable_ansi_escape + :type: bool + :value: True + + [Only available for text format writers] + If |True|, applies ANSI escape sequences to the terminal's text outputs with |Style|. + + .. py:attribute:: write_callback + + The value expected to a function. + The function is called when each of the iterations of writing a table + completed. (defaults to |None|) + For example, a callback function definition is as follows: + + .. code:: python + + def callback_example(iter_count: int, iter_length: int) -> None: + print("{:d}/{:d}".format(iter_count, iter_length)) + + Arguments that passed to the callback are: + + - first argument: current iteration number (start from ``1``) + - second argument: a total number of iteration + """ + + @property + def margin(self) -> int: + raise NotImplementedError() + + @margin.setter + def margin(self, value: int) -> None: + raise NotImplementedError() + + @property + def value_matrix(self) -> Sequence: + """Data of a table to be outputted.""" + + return self.__value_matrix_org + + @value_matrix.setter + def value_matrix(self, value_matrix: Sequence) -> None: + self.__set_value_matrix(value_matrix) + self.__clear_preprocess() + + @property + def table_format(self) -> "TableFormat": + """TableFormat: Get the format of the writer.""" + + from .._table_format import TableFormat + + table_format = TableFormat.from_name(self.format_name) + assert table_format + + return table_format + + @property + def stream(self) -> Any: + return self._stream + + @stream.setter + def stream(self, value: Any) -> None: + self._stream = value + + @abc.abstractmethod + def _write_table(self, **kwargs: Any) -> None: + pass + + def __init__(self, **kwargs: Any) -> None: + self._logger = WriterLogger(self) + + self.table_name = kwargs.get("table_name", "") + self.value_matrix = kwargs.get("value_matrix", []) + + self.is_write_header = kwargs.get("is_write_header", True) + self.is_write_header_separator_row = kwargs.get("is_write_header_separator_row", True) + self.is_write_value_separator_row = kwargs.get("is_write_value_separator_row", False) + self.is_write_opening_row = kwargs.get("is_write_opening_row", False) + self.is_write_closing_row = kwargs.get("is_write_closing_row", False) + + self._use_default_header = False + + self._dp_extractor = DataPropertyExtractor(max_precision=kwargs.get("max_precision")) + self._dp_extractor.min_column_width = 1 + self._dp_extractor.strip_str_header = '"' + self._dp_extractor.preprocessor = Preprocessor(dequote=kwargs.get("dequote", True)) + self._dp_extractor.type_value_map[Typecode.NONE] = "" + self._dp_extractor.matrix_formatting = MatrixFormatting.HEADER_ALIGNED + self._dp_extractor.update_strict_level_map({Typecode.BOOL: 1}) + + self.is_formatting_float = kwargs.get("is_formatting_float", True) + self.is_padding = kwargs.get("is_padding", True) + + self.headers = kwargs.get("headers", []) + self.type_hints = kwargs.get("type_hints", []) + self._quoting_flags = { + Typecode.BOOL: False, + Typecode.DATETIME: True, + Typecode.DICTIONARY: False, + Typecode.INFINITY: False, + Typecode.INTEGER: False, + Typecode.IP_ADDRESS: True, + Typecode.LIST: False, + Typecode.NAN: False, + Typecode.NONE: False, + Typecode.NULL_STRING: True, + Typecode.REAL_NUMBER: False, + Typecode.STRING: True, + } + + self._is_require_table_name = False + self._is_require_header = False + + self.iteration_length: int = kwargs.get("iteration_length", -1) + self.write_callback = kwargs.get( + "write_callback", lambda _iter_count, _iter_length: None # defaults to NOP callback + ) + self._iter_count: Optional[int] = None + + self.__default_style: Style + self.default_style = kwargs.get("default_style", Style()) + + self.__col_style_list: List[Optional[Style]] = [] + self.column_styles = kwargs.get("column_styles", []) + + self._style_filters: List[StyleFilterFunc] = copy.deepcopy(DEFAULT_STYLE_FILTERS) + self._enable_style_filter = True + self._styler = self._create_styler(self) + self.style_filter_kwargs: Dict[str, Any] = kwargs.get("style_filter_kwargs", {}) + self._check_style_filter_kwargs_funcs: List[CheckStyleFilterKeywordArgsFunc] = [] + self.__colorize_terminal = kwargs.get("colorize_terminal", True) + self.__enable_ansi_escape = kwargs.get("enable_ansi_escape", True) + + self.max_workers = kwargs.get("max_workers", 1) + + if "dataframe" in kwargs: + self.from_dataframe(kwargs["dataframe"]) + + self.__clear_preprocess() + + def _repr_html_(self) -> str: + from .text._html import HtmlTableWriter + + writer = HtmlTableWriter( + table_name=self.table_name, + headers=self.headers, + value_matrix=self.value_matrix, + column_styles=self.column_styles, + colorize_terminal=self.colorize_terminal, + enable_ansi_escape=self.enable_ansi_escape, + ) + writer._dp_extractor = self._dp_extractor + + return writer.dumps() + + @property + def value_preprocessor(self) -> Preprocessor: + return self._dp_extractor.preprocessor + + def __clear_preprocess_status(self) -> None: + self._is_complete_table_dp_preprocess = False + self._is_complete_table_property_preprocess = False + self._is_complete_header_preprocess = False + self._is_complete_value_matrix_preprocess = False + + def __clear_preprocess_data(self) -> None: + self._column_dp_list: List[ColumnDataProperty] = [] + self._table_headers: List[str] = [] + self._table_value_matrix: List[Union[List[str], Dict]] = [] + self._table_value_dp_matrix: Sequence[Sequence[DataProperty]] = [] + + @property + def headers(self) -> Sequence[str]: + """Sequence[str]: Headers of a table to be outputted.""" + + return self._dp_extractor.headers + + @headers.setter + def headers(self, value: Sequence[str]) -> None: + self._dp_extractor.headers = value + + @property + def is_formatting_float(self) -> bool: + return self._dp_extractor.is_formatting_float + + @is_formatting_float.setter + def is_formatting_float(self, value: bool) -> None: + if self._dp_extractor.is_formatting_float == value: + return + + self._dp_extractor.is_formatting_float = value + self.__clear_preprocess() + + @property + def max_workers(self) -> int: + return self._dp_extractor.max_workers + + @max_workers.setter + def max_workers(self, value: Optional[int]) -> None: + self._dp_extractor.max_workers = value + + @property + def tabledata(self) -> TableData: + """tabledata.TableData: Get tabular data of the writer.""" + + return TableData( + self.table_name, + self.headers, + self.value_matrix, + max_workers=self.max_workers, + max_precision=self._dp_extractor.max_precision, + ) + + @property + def table_name(self) -> str: + """str: Name of a table.""" + + return self._table_name + + @table_name.setter + def table_name(self, value: str) -> None: + self._table_name = value + + @property + def type_hints(self) -> List[TypeHint]: + """ + Type hints for each column of the tabular data. + Writers convert data for each column using the type hints information + before writing tables when you call ``write_xxx`` methods. + + Acceptable values are as follows: + + - |None| (automatically detect column type from values in the column) + - :py:class:`pytablewriter.typehint.Bool` or ``"bool"`` + - :py:class:`pytablewriter.typehint.DateTime` or ``"datetime"`` + - :py:class:`pytablewriter.typehint.Dictionary` or ``"dict"`` + - :py:class:`pytablewriter.typehint.Infinity` or ``"inf"`` + - :py:class:`pytablewriter.typehint.Integer` or ``"int"`` + - :py:class:`pytablewriter.typehint.IpAddress` or ``"ipaddr"`` + - :py:class:`pytablewriter.typehint.List` or ``"list"`` + - :py:class:`pytablewriter.typehint.Nan` or ``"nan"`` + - :py:class:`pytablewriter.typehint.NoneType` or ``"none"`` + - :py:class:`pytablewriter.typehint.NullString` or ``"nullstr"`` + - :py:class:`pytablewriter.typehint.RealNumber` or ``"realnumber"`` or ``"float"`` + - :py:class:`pytablewriter.typehint.String` or ``"str"`` + + If a type-hint value is not |None|, the writer tries to + convert data for each data in a column to type-hint class. + If the type-hint value is |None| or failed to convert data, + the writer automatically detects column data type from + the column data. + + If ``type_hints`` is |None|, the writer automatically detects data types + for all of the columns and writes a table using detected column types. + + Defaults to |None|. + + Examples: + - :ref:`example-type-hint-js` + - :ref:`example-type-hint-python` + """ + + return self._dp_extractor.column_type_hints + + @type_hints.setter + def type_hints(self, value: Sequence[Union[str, TypeHint]]) -> None: + hints = list(value) + if self.type_hints == hints: + return + + self.__set_type_hints(hints) + self.__clear_preprocess() + + @property + def default_style(self) -> Style: + """Style: Default |Style| of table cells.""" + + return self.__default_style + + @default_style.setter + def default_style(self, style: Optional[Style]) -> None: + if style is None: + style = Style() + + if not isinstance(style, Style): + raise TypeError("default_style must be a Style instance") + + try: + if self.__default_style == style: + return + except AttributeError: + # not yet initialized + pass + + self.__default_style = style + self._dp_extractor.default_format_flags = _ts_to_flag[ + self.__default_style.thousand_separator + ] + self.__clear_preprocess() + + @property + def column_styles(self) -> List[Optional[Style]]: + """List[Optional[Style]]: |Style| for each column.""" + + return self.__col_style_list + + @column_styles.setter + def column_styles(self, value: Sequence[Optional[Style]]) -> None: + if self.__col_style_list == value: + return + + self.__col_style_list = list(value) + + if self.__col_style_list: + self._dp_extractor.format_flags_list = [ + _ts_to_flag[self._get_col_style(col_idx).thousand_separator] + for col_idx in range(len(self.__col_style_list)) + ] + else: + self._dp_extractor.format_flags_list = [] + + self.__clear_preprocess() + + @property + def colorize_terminal(self) -> bool: + return self.__colorize_terminal + + @colorize_terminal.setter + def colorize_terminal(self, value: bool) -> None: + if self.__colorize_terminal == value: + return + + self.__colorize_terminal = value + self.__clear_preprocess() + + @property + def enable_ansi_escape(self) -> bool: + return self.__enable_ansi_escape + + @enable_ansi_escape.setter + def enable_ansi_escape(self, value: bool) -> None: + if self.__enable_ansi_escape == value: + return + + self.__enable_ansi_escape = value + self.__clear_preprocess() + + @property + def _quoting_flags(self) -> Dict[Typecode, bool]: + return self._dp_extractor.quoting_flags + + @_quoting_flags.setter + def _quoting_flags(self, value: Mapping[Typecode, bool]) -> None: + self._dp_extractor.quoting_flags = value + self.__clear_preprocess() + + def add_style_filter(self, style_filter: StyleFilterFunc) -> None: + """Add a style filter function to the writer. + + Args: + style_filter: + A function called for each table cell to apply a style to table cells. + The function will be required to implement the following Protocol: + + .. code-block:: python + + class StyleFilterFunc(Protocol): + def __call__(self, cell: Cell, **kwargs: Any) -> Optional[Style]: + ... + + If more than one style filter function is added to the writer, + it will be called from the last one added. + These style functions should return |None| when not needed to apply styles. + If all of the style functions returned |None|, + :py:attr:`~.default_style` will be used. + + You can pass keyword arguments to style filter functions via + :py:attr:`~.style_filter_kwargs`. In default, the attribute includes: + + - ``writer``: the writer instance that the caller of a ``style_filter function`` + """ + + self._style_filters.insert(0, style_filter) + self.__clear_preprocess() + + def add_col_separator_style_filter(self, style_filter: ColSeparatorStyleFilterFunc) -> None: + self._logger.logger.debug( + "add_col_separator_style_filter method is only implemented in text format writer classes" + ) + + def clear_theme(self) -> None: + """Remove all of the style filters.""" + + if not self._style_filters: + return + + self._style_filters = copy.deepcopy(DEFAULT_STYLE_FILTERS) + self._check_style_filter_kwargs_funcs = [] + self.__clear_preprocess() + + def enable_style_filter(self) -> None: + """Enable style filters.""" + + if self._enable_style_filter is True: + return + + self._enable_style_filter = True + self.__clear_preprocess() + + def disable_style_filter(self, clear_filters: bool = False) -> None: + """Disable style filters. + + Args: + clear_filters (bool): + If |True|, clear all of the style filters. + Defaults to |False|. + """ + + if clear_filters: + self.clear_theme() + return + + if self._enable_style_filter is False: + return + + self._enable_style_filter = False + self.__clear_preprocess() + + def set_style(self, column: Union[str, int], style: Style) -> None: + """Set |Style| for a specific column. + + Args: + column (|int| or |str|): + Column specifier. Column index or header name correlated with the column. + style (|Style|): + Style value to be set to the column. + + Raises: + ValueError: Raised when the column specifier is invalid. + """ + + column_idx = None + + while len(self.headers) > len(self.__col_style_list): + self.__col_style_list.append(None) + + if isinstance(column, int): + column_idx = column + elif isinstance(column, str): + try: + column_idx = self.headers.index(column) + except ValueError: + pass + + if column_idx is not None: + self.__col_style_list[column_idx] = style + self.__clear_preprocess() + self._dp_extractor.format_flags_list = [ + _ts_to_flag[self._get_col_style(col_idx).thousand_separator] + for col_idx in range(len(self.__col_style_list)) + ] + return + + raise ValueError(f"column must be an int or string: actual={column}") + + def set_theme(self, theme: str, **kwargs: Any) -> None: + """Set style filters for a theme. + + Args: + theme (str): + Name of the theme. pytablewriter theme plugin must be installed + corresponding to the theme name. + + Raises: + RuntimeError: Raised when a theme plugin does not install. + """ + + try: + fetched_theme = fetch_theme(theme.strip()) + except RuntimeError as e: + warnings.warn(f"{e}", UserWarning) + return + + if fetched_theme.style_filter: + self.add_style_filter(fetched_theme.style_filter) + + if fetched_theme.col_separator_style_filter: + self.add_col_separator_style_filter(fetched_theme.col_separator_style_filter) + + if fetched_theme.check_style_filter_kwargs: + self._check_style_filter_kwargs_funcs.append(fetched_theme.check_style_filter_kwargs) + + self.style_filter_kwargs.update(**kwargs) + + def __is_skip_close(self) -> bool: + try: + from _pytest.capture import EncodedFile + + if isinstance(self.stream, EncodedFile): + # avoid closing streams for pytest + return True + except ImportError: + pass + + try: + from _pytest.capture import CaptureIO + + if isinstance(self.stream, CaptureIO): + # avoid closing streams for pytest + return True + except ImportError: + try: + # for pytest 5.4.1 or older versions + from _pytest.compat import CaptureIO + + if isinstance(self.stream, CaptureIO): + # avoid closing streams for pytest + return True + except ImportError: + pass + + try: + from ipykernel.iostream import OutStream + + if isinstance(self.stream, OutStream): + # avoid closing streams for Jupyter Notebook + return True + except ImportError: + pass + + return False + + def close(self) -> None: + """ + Close the current |stream|. + """ + + if self.stream is None: + return + + try: + self.stream.isatty() + + if self.stream.name in ["", "", ""]: + return + except AttributeError: + pass + except ValueError: + # raised when executing an operation to a closed stream + pass + + if self.__is_skip_close(): + return + + try: + self.stream.close() + except AttributeError: + self._logger.logger.warning( + f"the stream has no close method implementation: type={type(self.stream)}" + ) + finally: + self._stream = None + + def from_tabledata(self, value: TableData, is_overwrite_table_name: bool = True) -> None: + """ + Set tabular attributes to the writer from |TableData|. + The following attributes are configured: + + - :py:attr:`~.table_name`. + - :py:attr:`~.headers`. + - :py:attr:`~.value_matrix`. + + |TableData| can be created from various data formats by + ``pytablereader``. More detailed information can be found in + https://pytablereader.rtfd.io/en/latest/ + + :param tabledata.TableData value: Input table data. + """ + + self.__clear_preprocess() + + if is_overwrite_table_name: + self.table_name = value.table_name if value.table_name else "" + + self.headers = value.headers + self.value_matrix = list(value.rows) + + if not value.has_value_dp_matrix: + return + + self._table_value_dp_matrix = value.value_dp_matrix + self._column_dp_list = self._dp_extractor.to_column_dp_list( + self._table_value_dp_matrix, self._column_dp_list + ) + self.__set_type_hints([col_dp.type_class for col_dp in self._column_dp_list]) + + self._is_complete_table_dp_preprocess = True + + def from_csv(self, csv_source: str, delimiter: str = ",") -> None: + """ + Set tabular attributes to the writer from a character-separated values (CSV) data source. + The following attributes are set to the writer by the method: + + - :py:attr:`~.headers`. + - :py:attr:`~.value_matrix`. + + :py:attr:`~.table_name` also be set if the CSV data source is a file. + In that case, :py:attr:`~.table_name` is as same as the filename. + + Args: + csv_source (str): + Input CSV data source can be designated CSV text or a CSV file path. + + delimiter (str): + Delimiter character of the CSV data source. + Defaults to ``,``. + + Examples: + :ref:`example-from-csv` + + :Dependency Packages: + - `pytablereader `__ + """ + + import pytablereader as ptr + + loader = ptr.CsvTableTextLoader(csv_source, quoting_flags=self._quoting_flags) + loader.delimiter = delimiter + try: + for table_data in loader.load(): + self.from_tabledata(table_data, is_overwrite_table_name=False) + return + except ptr.DataError: + pass + + loader = ptr.CsvTableFileLoader(csv_source, quoting_flags=self._quoting_flags) + loader.delimiter = delimiter + for table_data in loader.load(): + self.from_tabledata(table_data) + + def from_dataframe( + self, + dataframe: "pandas.DataFrame", + add_index_column: bool = False, + overwrite_type_hints: bool = True, + ) -> None: + """ + Set tabular attributes to the writer from :py:class:`pandas.DataFrame`. + The following attributes are set by the method: + + - :py:attr:`~.headers` + - :py:attr:`~.value_matrix` + - :py:attr:`~.type_hints` + + Args: + dataframe(pandas.DataFrame or |str|): + Input pandas.DataFrame object or path to a DataFrame pickle. + add_index_column(bool, optional): + If |True|, add a column of ``index`` of the ``dataframe``. + Defaults to |False|. + overwrite_type_hints(bool): + If |True|, Overwrite type hints with dtypes within the DataFrame. + + Example: + :ref:`example-from-pandas-dataframe` + """ + + if typepy.String(dataframe).is_type(): + import pandas as pd + + dataframe = pd.read_pickle(dataframe) + + self.headers = list(dataframe.columns.values) + + if not self.type_hints or overwrite_type_hints: + self.type_hints = [extract_typepy_from_dtype(dtype) for dtype in dataframe.dtypes] + + if add_index_column: + self.headers = [" "] + self.headers + if self.type_hints: + self.type_hints = [Integer] + self.type_hints + self.value_matrix = [ + [index] + row + for index, row in zip(dataframe.index.tolist(), dataframe.values.tolist()) + ] + else: + self.value_matrix = dataframe.values.tolist() + + def from_series(self, series: "pandas.Series", add_index_column: bool = True) -> None: + """ + Set tabular attributes to the writer from :py:class:`pandas.Series`. + The following attributes are set by the method: + + - :py:attr:`~.headers` + - :py:attr:`~.value_matrix` + - :py:attr:`~.type_hints` + + Args: + series(pandas.Series): + Input pandas.Series object. + add_index_column(bool, optional): + If |True|, add a column of ``index`` of the ``series``. + Defaults to |True|. + """ + + if series.name: + self.headers = [series.name] + else: + self.headers = ["value"] + + self.type_hints = [extract_typepy_from_dtype(series.dtype)] + + if add_index_column: + self.headers = [""] + self.headers + if self.type_hints: + self.type_hints = [None] + self.type_hints + self.value_matrix = [ + [index] + [value] for index, value in zip(series.index.tolist(), series.tolist()) + ] + else: + self.value_matrix = [[value] for value in series.tolist()] + + def from_tablib(self, tablib_dataset: "tablib.Dataset") -> None: + """ + Set tabular attributes to the writer from :py:class:`tablib.Dataset`. + """ + + self.headers = tablib_dataset.headers + self.value_matrix = [row for row in tablib_dataset] + + def from_writer( + self, writer: "AbstractTableWriter", is_overwrite_table_name: bool = True + ) -> None: + """ + Copy attributes from another table writer class instance. + + Args: + writer (pytablewriter.writer.AbstractTableWriter): + Another table writer instance. + is_overwrite_table_name (bool, optional): + Overwrite the table name of the writer with the table name of the ``writer``. + Defaults to |True|. + """ + + self.__clear_preprocess() + + if is_overwrite_table_name: + self.table_name = str(writer.table_name) + + self.headers = writer.headers + self.value_matrix = writer.value_matrix + + self.type_hints = writer.type_hints + self.column_styles = writer.column_styles + self._style_filters = writer._style_filters + self.style_filter_kwargs = writer.style_filter_kwargs + self.margin = writer.margin + + self._table_headers = writer._table_headers + self._table_value_dp_matrix = writer._table_value_dp_matrix + self._column_dp_list = writer._column_dp_list + self._table_value_matrix = writer._table_value_matrix + + self.stream = writer.stream + + self._is_complete_table_dp_preprocess = writer._is_complete_table_dp_preprocess + self._is_complete_table_property_preprocess = writer._is_complete_table_property_preprocess + self._is_complete_header_preprocess = writer._is_complete_header_preprocess + self._is_complete_value_matrix_preprocess = writer._is_complete_value_matrix_preprocess + + def register_trans_func(self, trans_func: TransFunc) -> None: + self._dp_extractor.register_trans_func(trans_func) + self.__clear_preprocess() + + def update_preprocessor(self, **kwargs: Any) -> None: + # TODO: documentation + # is_escape_formula_injection: for CSV/Excel + + if not self._dp_extractor.update_preprocessor(**kwargs): + return + + self.__clear_preprocess() + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table|. + """ + + with self._logger: + try: + self._verify_property() + except EmptyTableDataError: + self._logger.logger.debug("no tabular data found") + return + + self._write_table(**kwargs) + + def _write_table_iter(self, **kwargs: Any) -> None: + if not self.support_split_write: + raise NotSupportedError("the class not supported the write_table_iter method") + + self._verify_style_filter_kwargs() + self._verify_table_name() + self._verify_stream() + + if all( + [typepy.is_empty_sequence(self.headers), typepy.is_empty_sequence(self.value_matrix)] + ): + self._logger.logger.debug("no tabular data found") + return + + self._verify_header() + + self._logger.logger.debug(f"_write_table_iter: iteration-length={self.iteration_length:d}") + + stash_is_write_header = self.is_write_header + stach_is_write_opening_row = self.is_write_opening_row + stash_is_write_closing_row = self.is_write_closing_row + + try: + self.is_write_closing_row = False + self._iter_count = 1 + + for work_matrix in self.value_matrix: + is_final_iter = all( + [self.iteration_length > 0, self._iter_count >= self.iteration_length] + ) + + if is_final_iter: + self.is_write_closing_row = True + + self.__set_value_matrix(work_matrix) + self.__clear_preprocess_status() + + with self._logger: + self._write_table(**kwargs) + + if not is_final_iter: + self._write_value_row_separator() + + self.is_write_opening_row = False + self.is_write_header = False + + self.write_callback(self._iter_count, self.iteration_length) + + # update typehint for the next iteration + """ + if self.type_hints is None: + self.__set_type_hints([ + column_dp.type_class for column_dp in self._column_dp_list + ]) + """ + + if is_final_iter: + break + + self._iter_count += 1 + finally: + self.is_write_header = stash_is_write_header + self.is_write_opening_row = stach_is_write_opening_row + self.is_write_closing_row = stash_is_write_closing_row + self._iter_count = None + + def _get_padding_len( + self, column_dp: ColumnDataProperty, value_dp: Optional[DataProperty] = None + ) -> int: + if not self.is_padding: + return 0 + + try: + return cast(DataProperty, value_dp).get_padding_len(column_dp.ascii_char_width) + except AttributeError: + return column_dp.ascii_char_width + + def _to_header_item(self, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + style = self._fetch_style(HEADER_ROW, col_dp, value_dp) + header = self._apply_style_to_header_item(col_dp, value_dp, style) + header = self._styler.apply_terminal_style(header, style=style) + + return header + + def _apply_style_to_header_item( + self, col_dp: ColumnDataProperty, value_dp: DataProperty, style: Style + ) -> str: + return self._styler.apply_align( + self._styler.apply(col_dp.dp_to_str(value_dp), style=style), style=style + ) + + def _to_row_item(self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + style = self._fetch_style(row_idx, col_dp, value_dp) + value = self._apply_style_to_row_item(row_idx, col_dp, value_dp, style) + + return self._styler.apply_terminal_style(value, style=style) + + def _apply_style_to_row_item( + self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty, style: Style + ) -> str: + return self._styler.apply_align( + self._styler.apply(col_dp.dp_to_str(value_dp), style=style), style=style + ) + + def _fetch_style_from_filter( + self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty, default_style: Style + ) -> Style: + if not self._enable_style_filter: + return default_style + + self.style_filter_kwargs.update({"writer": self}) + + style: Optional[Style] = None + for style_filter in self._style_filters: + style = style_filter( + Cell( + row=row_idx, + col=col_dp.column_index, + value=value_dp.data, + default_style=default_style, + ), + **self.style_filter_kwargs, + ) + if style: + break + + if style is None: + style = copy.deepcopy(default_style) + + if style.align is None or (style.align == Align.AUTO and row_idx >= 0): + style.align = self.__retrieve_align_from_data(col_dp, value_dp) + + if style.padding is None: + style.padding = self._get_padding_len(col_dp, value_dp) + + return style + + def _get_col_style(self, col_idx: int) -> Style: + try: + style = self.column_styles[col_idx] + except (TypeError, IndexError, KeyError): + pass + else: + if style: + return style + + return self.default_style + + def _get_align(self, col_idx: int, default_align: Align) -> Align: + align = self._get_col_style(col_idx).align + + if align is None: + return default_align + + if align == Align.AUTO: + return default_align + + return align + + def __retrieve_align_from_data( + self, col_dp: ColumnDataProperty, value_dp: DataProperty + ) -> Align: + if col_dp.typecode == Typecode.STRING and ( + value_dp.typecode in (Typecode.INTEGER, Typecode.REAL_NUMBER) + or value_dp.typecode == Typecode.STRING + and value_dp.is_include_ansi_escape + ): + return value_dp.align + + return col_dp.align + + def _verify_property(self) -> None: + self._verify_style_filter_kwargs() + self._verify_table_name() + self._verify_stream() + + if all( + [ + typepy.is_empty_sequence(self.headers), + typepy.is_empty_sequence(self.value_matrix), + typepy.is_empty_sequence(self._table_value_dp_matrix), + ] + ): + raise EmptyTableDataError() + + self._verify_header() + try: + self._verify_value_matrix() + except EmptyValueError: + pass + + def __set_value_matrix(self, value_matrix: Sequence) -> None: + self.__value_matrix_org = value_matrix + + def __set_type_hints(self, type_hints: Sequence[Union[str, TypeHint]]) -> None: + self._dp_extractor.column_type_hints = type_hints + + def _verify_style_filter_kwargs(self) -> None: + for checker in self._check_style_filter_kwargs_funcs: + checker(**self.style_filter_kwargs) + + def _verify_table_name(self) -> None: + if all([self._is_require_table_name, typepy.is_null_string(self.table_name)]): + raise EmptyTableNameError( + "table_name must be a string, with at least one or more character." + ) + + def _verify_stream(self) -> None: + if self.stream is None: + raise OSError("null output stream") + + def _verify_header(self) -> None: + if self._is_require_header and not self._use_default_header: + self._validate_empty_header() + + def _validate_empty_header(self) -> None: + """ + Raises: + ValueError: If the |headers| is empty. + """ + + if typepy.is_empty_sequence(self.headers): + raise ValueError("headers expected to have one or more header names") + + def _verify_value_matrix(self) -> None: + if typepy.is_empty_sequence(self.value_matrix): + raise EmptyValueError() + + def _create_styler(self, writer: "AbstractTableWriter") -> StylerInterface: + from ..style._styler import NullStyler + + return NullStyler(writer) + + def _preprocess_table_dp(self) -> None: + if self._is_complete_table_dp_preprocess: + return + + self._logger.logger.debug("_preprocess_table_dp") + + if typepy.is_empty_sequence(self.headers) and self._use_default_header: + self.headers = [ + convert_idx_to_alphabet(col_idx) + for col_idx in range(len(self.__value_matrix_org[0])) + ] + + try: + self._table_value_dp_matrix = self._dp_extractor.to_dp_matrix( + to_value_matrix(self.headers, self.__value_matrix_org) + ) + except TypeError as e: + self._logger.logger.debug(to_error_message(e)) + self._table_value_dp_matrix = [] + + self._column_dp_list = self._dp_extractor.to_column_dp_list( + self._table_value_dp_matrix, self._column_dp_list + ) + + self._is_complete_table_dp_preprocess = True + + def _fetch_style(self, row: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> Style: + default_style = self._get_col_style(col_dp.column_index) + return self._fetch_style_from_filter(row, col_dp, value_dp, default_style) + + def _preprocess_table_property(self) -> None: + if self._is_complete_table_property_preprocess: + return + + self._logger.logger.debug("_preprocess_table_property") + + if self._iter_count == 1: + for column_dp in self._column_dp_list: + column_dp.extend_width(int(math.ceil(column_dp.ascii_char_width * 0.25))) + + header_dp_list = self._dp_extractor.to_header_dp_list() + if not header_dp_list: + return + + for column_dp in self._column_dp_list: + style = self._get_col_style(column_dp.column_index) + header_style = self._fetch_style( + HEADER_ROW, column_dp, header_dp_list[column_dp.column_index] + ) + body_width = self._styler.get_additional_char_width(style) + header_width = self._styler.get_additional_char_width(header_style) + column_dp.extend_body_width(max(body_width, header_width)) + + self._is_complete_table_property_preprocess = True + + def _preprocess_header(self) -> None: + if self._is_complete_header_preprocess: + return + + self._logger.logger.debug("_preprocess_header") + + self._table_headers = [ + self._to_header_item(col_dp, header_dp) + for col_dp, header_dp in zip( + self._column_dp_list, self._dp_extractor.to_header_dp_list() + ) + ] + + self._is_complete_header_preprocess = True + + def _preprocess_value_matrix(self) -> None: + if self._is_complete_value_matrix_preprocess: + return + + self._logger.logger.debug( + f"_preprocess_value_matrix: value-rows={len(self._table_value_dp_matrix)}" + ) + + self._table_value_matrix = [ + [ + self._to_row_item(row_idx, col_dp, value_dp) + for col_dp, value_dp in zip(self._column_dp_list, value_dp_list) + ] + for row_idx, value_dp_list in enumerate(self._table_value_dp_matrix) + ] + + self._is_complete_value_matrix_preprocess = True + + def _preprocess(self) -> None: + self._preprocess_table_dp() + self._preprocess_table_property() + self._preprocess_header() + self._preprocess_value_matrix() + + def _clear_preprocess(self) -> None: + self.__clear_preprocess() + + def __clear_preprocess(self) -> None: + self.__clear_preprocess_status() + self.__clear_preprocess_data() diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..616c3ddc9b2e8c4c4cbcfc7e39297bf0a61c9d4c --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__init__.py @@ -0,0 +1,11 @@ +from ._excel import ExcelXlsTableWriter, ExcelXlsxTableWriter +from ._pandas import PandasDataFramePickleWriter +from ._sqlite import SqliteTableWriter + + +__all__ = ( + "ExcelXlsTableWriter", + "ExcelXlsxTableWriter", + "PandasDataFramePickleWriter", + "SqliteTableWriter", +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9a19f848a81527f332393f7832cc75e2637519f Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad476a52dd7139dd6b3bebbb0078cfcb8a867965 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel_workbook.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel_workbook.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa5a020cda32cfe44771e66eee1b28c762598de9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel_workbook.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_interface.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_interface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8631e1c604852c52ce5ad57354f3d4f2aaa3b2f Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_interface.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_pandas.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_pandas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56565ac4ebcf4cb58479fb12998491fb8d1f71de Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_pandas.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_sqlite.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_sqlite.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd5b5ba71ce42039648fad802132314f66cd41a8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_sqlite.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel.py new file mode 100644 index 0000000000000000000000000000000000000000..22fedc16e82416509085ec83c5ebe75f61a3ded2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel.py @@ -0,0 +1,501 @@ +import abc +import copy +import warnings +from typing import IO, TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union, cast + +import dataproperty +import typepy +from dataproperty import DataProperty +from tabledata import TableData +from typepy import Integer + +from .._common import import_error_msg_template +from ._excel_workbook import ExcelWorkbookInterface, ExcelWorkbookXls, ExcelWorkbookXlsx +from ._interface import AbstractBinaryTableWriter + + +if TYPE_CHECKING: + from xlwt import XFStyle + + +class ExcelTableWriter(AbstractBinaryTableWriter, metaclass=abc.ABCMeta): + """ + An abstract class of a table writer for Excel file format. + """ + + FORMAT_NAME = "excel" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def workbook(self) -> Optional[ExcelWorkbookInterface]: + return self._workbook + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self._workbook: Optional[ExcelWorkbookInterface] = None + + self._dp_extractor.type_value_map = { + typepy.Typecode.INFINITY: "Inf", + typepy.Typecode.NAN: "NaN", + } + + self._first_header_row = 0 + self._last_header_row = self.first_header_row + self._first_data_row = self.last_header_row + 1 + self._first_data_col = 0 + self._last_data_row: Optional[int] = None + self._last_data_col: Optional[int] = None + + self._current_data_row = self._first_data_row + + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) + self._quoting_flags[typepy.Typecode.DATETIME] = True + + @property + def first_header_row(self) -> int: + """int: Index of the first row of the header. + + .. note:: |excel_attr| + """ + + return self._first_header_row + + @property + def last_header_row(self) -> int: + """int: Index of the last row of the header. + + .. note:: |excel_attr| + """ + + return self._last_header_row + + @property + def first_data_row(self) -> int: + """int: Index of the first row of the data (table body). + + .. note:: |excel_attr| + """ + + return self._first_data_row + + @property + def last_data_row(self) -> Optional[int]: + """int: Index of the last row of the data (table body). + + .. note:: |excel_attr| + """ + + return self._last_data_row + + @property + def first_data_col(self) -> int: + """int: Index of the first column of the table. + + .. note:: |excel_attr| + """ + + return self._first_data_col + + @property + def last_data_col(self) -> Optional[int]: + """int: Index of the last column of the table. + + .. note:: |excel_attr| + """ + + return self._last_data_col + + def is_opened(self) -> bool: + return self.workbook is not None + + def open(self, file_path: str) -> None: + """ + Open an Excel workbook file. + + :param str file_path: Excel workbook file path to open. + """ + + if self.workbook and self.workbook.file_path == file_path: + self._logger.logger.debug(f"workbook already opened: {self.workbook.file_path}") + return + + self.close() + self._open(file_path) + + @abc.abstractmethod + def _open(self, workbook_path: str) -> None: # pragma: no cover + pass + + def close(self) -> None: + """ + Close the current workbook. + """ + + if self.is_opened(): + self.workbook.close() # type: ignore + self._workbook = None + + def from_tabledata(self, value: TableData, is_overwrite_table_name: bool = True) -> None: + """ + Set following attributes from |TableData| + + - :py:attr:`~.table_name`. + - :py:attr:`~.headers`. + - :py:attr:`~.value_matrix`. + + And create worksheet named from :py:attr:`~.table_name` ABC + if not existed yet. + + :param tabledata.TableData value: Input table data. + """ + + super().from_tabledata(value) + + if self.is_opened(): + self.make_worksheet(self.table_name) + + def make_worksheet(self, sheet_name: Optional[str] = None) -> None: + """Make a worksheet to the current workbook. + + Args: + sheet_name (str): + Name of the worksheet to create. The name will be automatically generated + (like ``"Sheet1"``) if the ``sheet_name`` is empty. + """ + + if sheet_name is None: + sheet_name = self.table_name + if not sheet_name: + sheet_name = "" + + self._stream = self.workbook.add_worksheet(sheet_name) # type: ignore + self._current_data_row = self._first_data_row + + def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None: + """Write a worksheet to the current workbook. + + Args: + output (str): + Path to the workbook file to write. + close_after_write (bool, optional): + Close the workbook after write. + Defaults to |True|. + """ + + if not isinstance(output, str): + raise TypeError(f"output must be a str: actual={type(output)}") + + self.open(output) + try: + self.make_worksheet(self.table_name) + self.write_table(**kwargs) + finally: + if close_after_write: + self.close() + + @abc.abstractmethod + def _write_header(self) -> None: + pass + + @abc.abstractmethod + def _write_cell(self, row: int, col: int, value_dp: DataProperty) -> None: + pass + + def _write_table(self, **kwargs: Any) -> None: + self._preprocess_table_dp() + self._preprocess_table_property() + self._write_header() + self._write_value_matrix() + self._postprocess() + + def _write_value_matrix(self) -> None: + for value_dp_list in self._table_value_dp_matrix: + for col_idx, value_dp in enumerate(value_dp_list): + self._write_cell(self._current_data_row, col_idx, value_dp) + + self._current_data_row += 1 + + def _get_last_column(self) -> int: + if typepy.is_not_empty_sequence(self.headers): + return len(self.headers) - 1 + + if typepy.is_not_empty_sequence(self.value_matrix): + return len(self.value_matrix[0]) - 1 + + raise ValueError("data not found") + + def _postprocess(self) -> None: + self._last_data_row = self._current_data_row + self._last_data_col = self._get_last_column() + + +class ExcelXlsTableWriter(ExcelTableWriter): + """ + A table writer class for Excel file format: ``.xls`` (older or equal to Office 2003). + + ``xlwt`` package required to use this class. + + .. py:method:: write_table() + + Write a table to the current opened worksheet. + + :raises IOError: If failed to write data to the worksheet. + + .. note:: + Specific values in the tabular data are converted when writing: + + - |None|: written as an empty string + - |inf|: written as ``Inf`` + - |nan|: written as ``NaN`` + """ + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.__col_style_table: Dict[int, Any] = {} + + def _open(self, workbook_path: str) -> None: + self._workbook = ExcelWorkbookXls(workbook_path) + + def _write_header(self) -> None: + if not self.is_write_header or typepy.is_empty_sequence(self.headers): + return + + for col, value in enumerate(self.headers): + self.stream.write(self.first_header_row, col, value) + + def _write_cell(self, row: int, col: int, value_dp: DataProperty) -> None: + if value_dp.typecode in [typepy.Typecode.REAL_NUMBER]: + try: + cell_style = self.__get_cell_style(col) + except ValueError: + pass + else: + self.stream.write(row, col, value_dp.data, cell_style) + return + + self.stream.write(row, col, value_dp.data) + + def _postprocess(self) -> None: + super()._postprocess() + + self.__col_style_table = {} + + def __get_cell_style(self, col: int) -> "XFStyle": + try: + import xlwt + except ImportError: + warnings.warn(import_error_msg_template.format("excel")) + raise + + if col in self.__col_style_table: + return self.__col_style_table.get(col) + + try: + col_dp = self._column_dp_list[col] + except KeyError: + return {} + + if col_dp.typecode not in [typepy.Typecode.REAL_NUMBER]: + raise ValueError() + + if not Integer(col_dp.minmax_decimal_places.max_value).is_type(): + raise ValueError() + + float_digit = col_dp.minmax_decimal_places.max_value + if float_digit <= 0: + raise ValueError() + + num_format_str = "#,{:s}0.{:s}".format("#" * int(float_digit), "0" * int(float_digit)) + cell_style = xlwt.easyxf(num_format_str=num_format_str) + self.__col_style_table[col] = cell_style + + return cell_style + + +class ExcelXlsxTableWriter(ExcelTableWriter): + """ + A table writer class for Excel file format: ``.xlsx`` (newer or equal to Office 2007). + + .. py:method:: write_table() + + Write a table to the current opened worksheet. + + :raises IOError: If failed to write data to the worksheet. + + Examples: + :ref:`example-excel-table-writer` + + .. note:: + Specific values in the tabular data are converted when writing: + + - |None|: written as an empty string + - |inf|: written as ``Inf`` + - |nan|: written as ``NaN`` + """ + + MAX_CELL_WIDTH: ClassVar[int] = 60 + + class TableFormat: + HEADER = "header" + CELL = "cell" + NAN = "nan" + + class Default: + FONT_NAME: ClassVar[str] = "MS Gothic" + FONT_SIZE: ClassVar[int] = 9 + + CELL_FORMAT: Dict[str, Union[int, str, bool]] = { + "font_name": FONT_NAME, + "font_size": FONT_SIZE, + "align": "top", + "text_wrap": True, + "top": 1, + "left": 1, + "bottom": 1, + "right": 1, + } + HEADER_FORMAT: Dict[str, Union[int, str, bool]] = { + "font_name": FONT_NAME, + "font_size": FONT_SIZE, + "bg_color": "#DFDFFF", + "bold": True, + "left": 1, + "right": 1, + } + NAN_FORMAT: Dict[str, Union[int, str, bool]] = { + "font_name": FONT_NAME, + "font_size": FONT_SIZE, + "font_color": "silver", + "top": 1, + "left": 1, + "bottom": 1, + "right": 1, + } + + @property + def __nan_format_property(self) -> Dict[str, Union[int, str, bool]]: + return self.format_table.get(self.TableFormat.NAN, self.default_format) + + @property + def __cell_format_property(self) -> Dict[str, Union[int, str, bool]]: + return self.format_table.get(self.TableFormat.CELL, self.default_format) + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.default_format = self.Default.CELL_FORMAT + self.format_table = { + self.TableFormat.CELL: self.Default.CELL_FORMAT, + self.TableFormat.HEADER: self.Default.HEADER_FORMAT, + self.TableFormat.NAN: self.Default.NAN_FORMAT, + } + + self.__col_cell_format_cache: Dict[int, Any] = {} + self.__col_numprops_table: Dict[int, Dict[str, str]] = {} + + def _open(self, workbook_path: str) -> None: + self._workbook = ExcelWorkbookXlsx(workbook_path) + + def _write_header(self) -> None: + if not self.is_write_header or typepy.is_empty_sequence(self.headers): + return + + header_format_props = self.format_table.get(self.TableFormat.HEADER, self.default_format) + header_format = self.__add_format(header_format_props) + + self.stream.write_row( + row=self.first_header_row, col=0, data=self.headers, cell_format=header_format + ) + for row in range(self.first_header_row, self.last_header_row): + self.stream.write_row( + row=row, col=0, data=[""] * len(self.headers), cell_format=header_format + ) + + def _write_cell(self, row: int, col: int, value_dp: DataProperty) -> None: + base_props = dict(self.__cell_format_property) + format_key = f"{col:d}_{value_dp.typecode.name:s}" + + if value_dp.typecode in [typepy.Typecode.INTEGER, typepy.Typecode.REAL_NUMBER]: + num_props = self.__get_number_property(col) + base_props.update(num_props) + cell_format = self.__get_cell_format(format_key, base_props) + + try: + self.stream.write_number(row, col, float(value_dp.data), cell_format) + return + except TypeError: + pass + + if value_dp.typecode is typepy.Typecode.NAN: + base_props = dict(self.__nan_format_property) + + cell_format = self.__get_cell_format(format_key, base_props) + self.stream.write(row, col, value_dp.data, cell_format) + + def __get_number_property(self, col: int) -> Dict[str, str]: + if col in self.__col_numprops_table: + return self.__col_numprops_table[col] + + try: + col_dp = self._column_dp_list[col] + except KeyError: + return {} + + if col_dp.typecode not in [typepy.Typecode.INTEGER, typepy.Typecode.REAL_NUMBER]: + return {} + + num_props = {} + if Integer(col_dp.minmax_decimal_places.max_value).is_type(): + float_digit = col_dp.minmax_decimal_places.max_value + if float_digit > 0: + num_props = {"num_format": "0.{:s}".format("0" * int(float_digit))} + + self.__col_numprops_table[col] = num_props + + return num_props + + def __get_cell_format(self, format_key, cell_props) -> Dict: # type: ignore + cell_format = self.__col_cell_format_cache.get(format_key) + if cell_format is not None: + return cell_format + + # cache miss + cell_format = self.__add_format(cell_props) + self.__col_cell_format_cache[format_key] = cell_format + + return cell_format + + def __add_format(self, dict_property): # type: ignore + assert self.workbook + return self.workbook.workbook.add_format(dict_property) + + def __set_cell_width(self) -> None: + font_size = cast(int, self.__cell_format_property.get("font_size")) + + if not Integer(font_size).is_type(): + return + + for col_idx, col_dp in enumerate(self._column_dp_list): + width = min(col_dp.ascii_char_width, self.MAX_CELL_WIDTH) * (font_size / 10.0) + 2 + self.stream.set_column(col_idx, col_idx, width=width) + + def _preprocess_table_property(self) -> None: + super()._preprocess_table_property() + + self.__set_cell_width() + + def _postprocess(self) -> None: + super()._postprocess() + + self.stream.autofilter( + self.last_header_row, self.first_data_col, self.last_data_row, self.last_data_col + ) + self.stream.freeze_panes(self.first_data_row, self.first_data_col) + + self.__col_cell_format_cache = {} + self.__col_numprops_table = {} diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel_workbook.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel_workbook.py new file mode 100644 index 0000000000000000000000000000000000000000..6da2a86a1dc7aaff5e3b2515e6bc28276e3e91ec --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel_workbook.py @@ -0,0 +1,139 @@ +import abc +import warnings +from typing import Any, Dict, Optional + +import typepy + +from ..._logger import logger +from ...sanitizer import sanitize_excel_sheet_name +from .._common import import_error_msg_template +from .._msgfy import to_error_message + + +class ExcelWorkbookInterface(metaclass=abc.ABCMeta): + @abc.abstractproperty + def workbook(self) -> Any: # pragma: no cover + pass + + @abc.abstractproperty + def file_path(self) -> Optional[str]: # pragma: no cover + pass + + @abc.abstractmethod + def open(self, file_path: str) -> None: # pragma: no cover + pass + + @abc.abstractmethod + def close(self) -> None: # pragma: no cover + pass + + @abc.abstractmethod + def add_worksheet(self, worksheet_name: Optional[str]) -> Any: # pragma: no cover + pass + + +class ExcelWorkbook(ExcelWorkbookInterface): + @property + def workbook(self) -> Any: + return self._workbook + + @property + def file_path(self) -> Optional[str]: + return self._file_path + + def _clear(self) -> None: + self._workbook = None + self._file_path: Optional[str] = None + self._worksheet_table: Dict[str, Any] = {} + + def __init__(self, file_path: str) -> None: + self._clear() + self._file_path = file_path + + def __del__(self) -> None: + self.close() + + +class ExcelWorkbookXls(ExcelWorkbook): + def __init__(self, file_path: str) -> None: + super().__init__(file_path) + + self.open(file_path) + + def open(self, file_path: str) -> None: + try: + import xlwt + except ImportError: + warnings.warn(import_error_msg_template.format("excel")) + raise + + self._workbook = xlwt.Workbook() + + def close(self) -> None: + if self.workbook is None: + return + + try: + self.workbook.save(self._file_path) + except IndexError as e: + logger.debug(to_error_message(e)) + + self._clear() + + def add_worksheet(self, worksheet_name: Optional[str]) -> Any: + if typepy.is_not_null_string(worksheet_name): + assert worksheet_name + worksheet_name = sanitize_excel_sheet_name(worksheet_name) + if worksheet_name in self._worksheet_table: + # the work sheet is already exists + return self._worksheet_table.get(worksheet_name) + else: + sheet_id = 1 + while True: + worksheet_name = f"Sheet{sheet_id:d}" + if worksheet_name not in self._worksheet_table: + break + sheet_id += 1 + + worksheet = self.workbook.add_sheet(worksheet_name) + self._worksheet_table[worksheet.get_name()] = worksheet + + return worksheet + + +class ExcelWorkbookXlsx(ExcelWorkbook): + def __init__(self, file_path: str) -> None: + super().__init__(file_path) + + self.open(file_path) + + def open(self, file_path: str) -> None: + try: + import xlsxwriter + except ImportError: + warnings.warn(import_error_msg_template.format("excel")) + raise + + self._workbook = xlsxwriter.Workbook(file_path) + + def close(self) -> None: + if self.workbook is None: + return + + self._workbook.close() # type: ignore + self._clear() + + def add_worksheet(self, worksheet_name: Optional[str]) -> Any: + if typepy.is_not_null_string(worksheet_name): + assert worksheet_name + worksheet_name = sanitize_excel_sheet_name(worksheet_name) + if worksheet_name in self._worksheet_table: + # the work sheet is already exists + return self._worksheet_table.get(worksheet_name) + else: + worksheet_name = None + + worksheet = self.workbook.add_worksheet(worksheet_name) + self._worksheet_table[worksheet.get_name()] = worksheet + + return worksheet diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_interface.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6cdb3440792891f83db5f1b4bc86bd89fe5e2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_interface.py @@ -0,0 +1,58 @@ +import abc +from typing import Any + +from .._table_writer import AbstractTableWriter + + +class BinaryWriterInterface(metaclass=abc.ABCMeta): + @abc.abstractmethod + def is_opened(self) -> bool: # pragma: no cover + pass + + @abc.abstractmethod + def open(self, file_path: str) -> None: # pragma: no cover + """ + Open a file for output stream. + + Args: + file_path (str): path to the file. + """ + + +class AbstractBinaryTableWriter(AbstractTableWriter, BinaryWriterInterface): + @property + def stream(self) -> Any: + return self._stream + + @stream.setter + def stream(self, value: Any) -> None: + raise RuntimeError( + "cannot assign a stream to binary format writers. use open method instead." + ) + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.table_name = kwargs.get("table_name", "") + + self._stream = None + + def __del__(self) -> None: + self.close() + + def is_opened(self) -> bool: + return self.stream is not None + + def dumps(self) -> str: + raise NotImplementedError("binary format writers did not support dumps method") + + def _verify_stream(self) -> None: + if self.stream is None: + raise OSError("null output stream. required to open(file_path) first.") + + def _write_value_row_separator(self) -> None: + pass diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_pandas.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..4363063f14322d90047ef44c9c8cb4407b8938b1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_pandas.py @@ -0,0 +1,99 @@ +from typing import IO, Any, Optional, Union + +import tabledata + +from ...error import EmptyValueError +from ._interface import AbstractBinaryTableWriter + + +class PandasDataFramePickleWriter(AbstractBinaryTableWriter): + """ + A table writer class for pandas DataFrame pickle. + + .. py:method:: write_table() + + Write a table to a pandas DataFrame pickle file. + """ + + FORMAT_NAME = "pandas_pickle" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return False + + def __init__(self, **kwargs: Any) -> None: + import copy + + import dataproperty + + super().__init__(**kwargs) + + self.is_padding = False + self.is_formatting_float = False + self._use_default_header = True + + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) + + self.__filepath: Optional[str] = None + + def is_opened(self) -> bool: + return self.__filepath is not None + + def open(self, file_path: str) -> None: + self.__filepath = file_path + + def close(self) -> None: + super().close() + self.__filepath = None + + def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None: + """Write data to a DataFrame pickle file. + + Args: + output (str): Path to an output DataFrame pickle file. + """ + + if not isinstance(output, str): + raise TypeError(f"output must be a str: actual={type(output)}") + + self.open(output) + try: + self.write_table(**kwargs) + finally: + if close_after_write: + self.close() + + def _verify_stream(self) -> None: + pass + + def _write_table(self, **kwargs: Any) -> None: + if not self.is_opened(): + self._logger.logger.error("required to open(file_path) first.") + return + + try: + self._verify_value_matrix() + except EmptyValueError: + self._logger.logger.debug("no tabular data found") + return + + self._preprocess() + + table_data = tabledata.TableData( + self.table_name, + self.headers, + [ + [value_dp.data for value_dp in value_dp_list] + for value_dp_list in self._table_value_dp_matrix + ], + type_hints=self.type_hints, + max_workers=self.max_workers, + ) + table_data.as_dataframe().to_pickle(self.__filepath) + + def _write_table_iter(self, **kwargs: Any) -> None: + self._write_table(**kwargs) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_sqlite.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_sqlite.py new file mode 100644 index 0000000000000000000000000000000000000000..e73f0de0192ddf93d75e3adba9fb974097da583f --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_sqlite.py @@ -0,0 +1,104 @@ +from os.path import abspath +from typing import IO, Any, Union + +import tabledata + +from ...error import EmptyValueError +from ._interface import AbstractBinaryTableWriter + + +class SqliteTableWriter(AbstractBinaryTableWriter): + """ + A table writer class for `SQLite `__ database. + + .. py:method:: write_table() + + Write a table to a `SQLite `__ database. + + :raises pytablewriter.EmptyTableNameError: + If the |table_name| is empty. + :Example: + :ref:`example-sqlite-table-writer` + """ + + FORMAT_NAME = "sqlite" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + def __init__(self, **kwargs: Any) -> None: + import copy + + import dataproperty + + super().__init__(**kwargs) + + self.is_padding = False + self.is_formatting_float = False + self._use_default_header = True + + self._is_require_table_name = True + self._is_require_header = True + + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) + + def open(self, file_path: str) -> None: + """ + Open a SQLite database file. + + :param str file_path: SQLite database file path to open. + """ + + from simplesqlite import SimpleSQLite + + if self.is_opened(): + if self.stream.database_path == abspath(file_path): + self._logger.logger.debug(f"database already opened: {self.stream.database_path}") + return + + self.close() + + self._stream = SimpleSQLite(file_path, "w", max_workers=self.max_workers) + + def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None: + """Write data to the SQLite database file. + + Args: + output (str): + path to the output SQLite database file. + close_after_write (bool, optional): + Close the output after write. + Defaults to |True|. + """ + + if not isinstance(output, str): + raise TypeError(f"output must be a str: actual={type(output)}") + + self.open(output) + try: + self.write_table(**kwargs) + finally: + if close_after_write: + self.close() + + def _write_table(self, **kwargs: Any) -> None: + try: + self._verify_value_matrix() + except EmptyValueError: + self._logger.logger.debug("no tabular data found") + return + + self._preprocess() + + table_data = tabledata.TableData( + self.table_name, + self.headers, + [ + [value_dp.data for value_dp in value_dp_list] + for value_dp_list in self._table_value_dp_matrix + ], + type_hints=self.type_hints, + max_workers=self.max_workers, + ) + self.stream.create_table_from_tabledata(table_data) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f051aaa58dcdd6baf0f617a0cd26f742fee5e4fb --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__init__.py @@ -0,0 +1,44 @@ +from ._asciidoc import AsciiDocTableWriter +from ._borderless import BorderlessTableWriter +from ._css import CssTableWriter +from ._csv import CsvTableWriter +from ._html import HtmlTableWriter +from ._json import JsonTableWriter +from ._jsonlines import JsonLinesTableWriter +from ._latex import LatexMatrixWriter, LatexTableWriter +from ._ltsv import LtsvTableWriter +from ._markdown import MarkdownFlavor, MarkdownTableWriter, normalize_md_flavor +from ._mediawiki import MediaWikiTableWriter +from ._rst import RstCsvTableWriter, RstGridTableWriter, RstSimpleTableWriter +from ._spacealigned import SpaceAlignedTableWriter +from ._toml import TomlTableWriter +from ._tsv import TsvTableWriter +from ._unicode import BoldUnicodeTableWriter, UnicodeTableWriter +from ._yaml import YamlTableWriter + + +__all__ = ( + "AsciiDocTableWriter", + "BoldUnicodeTableWriter", + "BorderlessTableWriter", + "CssTableWriter", + "CsvTableWriter", + "HtmlTableWriter", + "JsonTableWriter", + "JsonLinesTableWriter", + "LatexMatrixWriter", + "LatexTableWriter", + "LtsvTableWriter", + "MarkdownFlavor", + "MarkdownTableWriter", + "normalize_md_flavor", + "MediaWikiTableWriter", + "RstCsvTableWriter", + "RstGridTableWriter", + "RstSimpleTableWriter", + "SpaceAlignedTableWriter", + "TomlTableWriter", + "TsvTableWriter", + "UnicodeTableWriter", + "YamlTableWriter", +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b89bc781be866bcbfa8fc7b34ea45efbc796ea7b Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_common.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3724fb3bae7a7006dc7aa8a0aed43660bc00c24b Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_css.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_css.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3cb2a53ce47cee80966ff49711d5979aa24a9096 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_css.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_csv.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_csv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0916769a2adbc7240eec001588890520084327bd Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_csv.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_interface.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_interface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..979bff7e46cf8ed7b316f03a05f5fe44de7b2b50 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_interface.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_latex.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_latex.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e2ed90e4a8fa1ecd8a17e45385810323809f9ae Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_latex.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_ltsv.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_ltsv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0cd6a8ec77f4c49de61c4ba692f1b604a1479e7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_ltsv.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_markdown.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_markdown.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..027d64965d68bcd3afa8d81ad6f7422eff0a1ff1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_markdown.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_mediawiki.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_mediawiki.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0982d500a3670577901d0d68ef1a487c9ddc4005 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_mediawiki.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_spacealigned.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_spacealigned.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac95509b8dff4ddd3ad0df3e10ae48b4dbc76170 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_spacealigned.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_text_writer.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_text_writer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acaee28d1411301634859e4e0f5c160d9e4052a4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_text_writer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_tsv.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_tsv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32f733e3be37baaf1eb97cc87c717d48474efb5b Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_tsv.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_yaml.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_yaml.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e57e2a60214ce0e30f97db5906c2a6dafc3cf2fa Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_yaml.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_asciidoc.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_asciidoc.py new file mode 100644 index 0000000000000000000000000000000000000000..1294da3db3e5de44bf33b5857997a92706668228 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_asciidoc.py @@ -0,0 +1,146 @@ +import copy +from typing import Any, List, Sequence + +import dataproperty as dp +import typepy +from dataproperty import ColumnDataProperty, DataProperty, LineBreakHandling +from mbstrdecoder import MultiByteStrDecoder + +from ...style import ( + Align, + FontStyle, + FontWeight, + Style, + StylerInterface, + TextStyler, + get_align_char, +) +from .._table_writer import AbstractTableWriter +from ._text_writer import TextTableWriter + + +class AsciiDocStyler(TextStyler): + def apply(self, value: str, style: Style) -> str: + value = super().apply(value, style) + if not value: + return value + + try: + fg_color = style.fg_color.name.lower() # type: ignore + except AttributeError: + fg_color = None + + try: + bg_color = style.bg_color.name.lower() # type: ignore + except AttributeError: + bg_color = None + + if fg_color and bg_color: + value = f"[{fg_color} {bg_color}-background]##{value}##" + elif fg_color: + value = f"[{fg_color}]##{value}##" + elif bg_color: + value = f"[{bg_color}-background]##{value}##" + + if style.font_weight == FontWeight.BOLD: + value = f"*{value}*" + + if style.font_style == FontStyle.ITALIC: + value = f"_{value}_" + + return value + + +class AsciiDocTableWriter(TextTableWriter): + """ + A table writer class for `AsciiDoc `__ format. + """ + + FORMAT_NAME = "asciidoc" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.column_delimiter = "\n" + + self.is_padding = False + self.is_write_header_separator_row = True + self.is_write_value_separator_row = True + self.is_write_opening_row = True + self.is_write_closing_row = True + + self.update_preprocessor(line_break_handling=LineBreakHandling.NOP) + + self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS) + + def _create_styler(self, writer: AbstractTableWriter) -> StylerInterface: + return AsciiDocStyler(writer) + + def _write_value_row( + self, row: int, values: Sequence[str], value_dp_list: Sequence[DataProperty] + ) -> None: + self._write_row( + row, + [ + self.__modify_row_element(row, col_idx, value, value_dp) + for col_idx, (value, value_dp), in enumerate(zip(values, value_dp_list)) + ], + ) + + def _get_opening_row_items(self) -> List[str]: + cols = ", ".join( + f"{get_align_char(col_dp.align)}{col_dp.ascii_char_width}" + for col_dp in self._column_dp_list + ) + rows = [f'[cols="{cols}", options="header"]'] + + if typepy.is_not_null_string(self.table_name): + rows.append("." + MultiByteStrDecoder(self.table_name).unicode_str) + + rows.append("|===") + + return ["\n".join(rows)] + + def _get_header_row_separator_items(self) -> List[str]: + return [""] + + def _get_value_row_separator_items(self) -> List[str]: + return self._get_header_row_separator_items() + + def _get_closing_row_items(self) -> List[str]: + return ["|==="] + + def __apply_align(self, value: str, style: Style) -> str: + return f"{get_align_char(Align.CENTER)}|{value}" + + def _apply_style_to_header_item( + self, col_dp: ColumnDataProperty, value_dp: DataProperty, style: Style + ) -> str: + value = self._styler.apply(col_dp.dp_to_str(value_dp), style=style) + return self.__apply_align(value, style) + + def __modify_row_element( + self, row_idx: int, col_idx: int, value: str, value_dp: DataProperty + ) -> str: + col_dp = self._column_dp_list[col_idx] + style = self._fetch_style(row_idx, col_dp, value_dp) + align = col_dp.align + + if style and style.align and style.align != align: + forma_stirng = "{0:s}|{1:s}" + align = style.align + elif value_dp.align != align: + forma_stirng = "{0:s}|{1:s}" + align = value_dp.align + else: + forma_stirng = "|{1:s}" + + return forma_stirng.format(get_align_char(align), value) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_borderless.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_borderless.py new file mode 100644 index 0000000000000000000000000000000000000000..6601b35bbc3011a79ebf5ce314a931cfb7953345 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_borderless.py @@ -0,0 +1,41 @@ +import copy +from typing import Any + +import dataproperty as dp + +from ._text_writer import IndentationTextTableWriter + + +class BorderlessTableWriter(IndentationTextTableWriter): + """ + A table writer class for borderless table. + """ + + FORMAT_NAME = "borderless" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.table_name = "" + + self.column_delimiter = "" + self.char_left_side_row = "" + self.char_right_side_row = "" + + self.indent_string = kwargs.get("indent_string", " ") + self.is_write_header_separator_row = False + self.is_write_value_separator_row = False + self.is_write_opening_row = False + self.is_write_closing_row = False + + self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS) + + self._init_cross_point_maps() diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_common.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..6af3bc7dfd0df4f6603291b3d45d21e2b49601f4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_common.py @@ -0,0 +1,26 @@ +from decimal import Decimal +from typing import Any + +from dataproperty import DataProperty +from typepy import Typecode + + +def bool_to_str(value: Any) -> Any: + if value is True: + return "true" + if value is False: + return "false" + + return value + + +def serialize_dp(dp: DataProperty) -> Any: + if dp.typecode in (Typecode.REAL_NUMBER, Typecode.INFINITY, Typecode.NAN) and isinstance( + dp.data, Decimal + ): + return float(dp.data) + + if dp.typecode == Typecode.DATETIME: + return dp.to_str() + + return dp.data diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_css.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_css.py new file mode 100644 index 0000000000000000000000000000000000000000..6d9b4931a02e100c51ebd05b3e1484fb972f7eb9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_css.py @@ -0,0 +1,157 @@ +import copy +from typing import Any, List, cast + +from dataproperty import NOT_QUOTING_FLAGS, DataProperty +from pathvalidate import replace_symbol + +from ...error import EmptyTableDataError +from ...style import Align, DecorationLine, FontStyle, FontWeight, Style, VerticalAlign +from .._common import HEADER_ROW +from ._text_writer import IndentationTextTableWriter + + +class CssTableWriter(IndentationTextTableWriter): + """ + A CSS writer class. + """ + + FORMAT_NAME = "css" + MARGIN_PIXEL = 6 + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return False + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.is_padding = False + self.indent_string = kwargs.get("indent_string", " ") + + self._dp_extractor.preprocessor.is_escape_html_tag = False + self._quoting_flags = copy.deepcopy(NOT_QUOTING_FLAGS) + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table| with CSS. + """ + + with self._logger: + try: + self._verify_property() + except EmptyTableDataError: + self._logger.logger.debug("no tabular data found") + return + + self._preprocess() + + self.__write_css( + css_class=replace_symbol(self.table_name, replacement_text="-"), + write_style_tag=kwargs.get("write_style_tag", False), + ) + + def __extract_css_tags(self, value_dp: DataProperty, style: Style) -> List[str]: + css_tags: List[str] = [] + + if self._styler.get_font_size(style): + css_tags.append(cast(str, self._styler.get_font_size(style))) + if style.font_weight == FontWeight.BOLD: + css_tags.append("font-weight:bold") + if style.font_style == FontStyle.ITALIC: + css_tags.append("font-style:italic") + + if style.color: + css_tags.append(f"color: {style.color.color_code}") + + if style.bg_color: + css_tags.append(f"background-color: {style.bg_color.color_code}") + + css_tag = self.__extract_align_tag(value_dp, style) + if css_tag: + css_tags.append(css_tag) + + if style.vertical_align != VerticalAlign.BASELINE: + css_tags.append(f"vertical-align: {style.vertical_align.align_str}") + + if style.decoration_line in (DecorationLine.LINE_THROUGH, DecorationLine.STRIKE): + css_tags.append("text-decoration-line: line-through") + elif style.decoration_line == DecorationLine.UNDERLINE: + css_tags.append("text-decoration-line: underline") + + if self.margin > 0: + css_tags.append(f"padding: {self.margin * self.MARGIN_PIXEL}px") + + return css_tags + + def __extract_align_tag(self, value_dp: DataProperty, style: Style) -> str: + if style.align == Align.AUTO: + value = value_dp.align.align_string + else: + value = style.align.align_string + + return f"text-align: {value}" + + def __write_css_thead(self, css_class: str, base_indent_level: int) -> None: + for col_dp, header_dp in zip(self._column_dp_list, self._dp_extractor.to_header_dp_list()): + style = self._fetch_style(HEADER_ROW, col_dp, header_dp) + css_tags = self.__extract_css_tags(header_dp, style) + + if not css_tags: + continue + + self.set_indent_level(base_indent_level) + self._write_line( + ".{css_class} thead th:nth-child({col}) {{".format( + css_class=css_class, col=col_dp.column_index + 1 + ) + ) + + self.set_indent_level(base_indent_level + 1) + for css_tag in css_tags: + self._write_line(f"{css_tag};") + + self.set_indent_level(base_indent_level) + self._write_line("}") + + def __write_css_tbody(self, css_class: str, base_indent_level: int) -> None: + for row_idx, (values, value_dp_list) in enumerate( + zip(self._table_value_matrix, self._table_value_dp_matrix) + ): + for value, value_dp, col_dp in zip(values, value_dp_list, self._column_dp_list): + style = self._fetch_style(row_idx, col_dp, value_dp) + css_tags = self.__extract_css_tags(value_dp, style) + + if not css_tags: + continue + + self.set_indent_level(base_indent_level) + self._write_line( + ".{css_class} tbody tr:nth-child({row}) td:nth-child({col}) {{".format( + css_class=css_class, row=row_idx + 1, col=col_dp.column_index + 1 + ) + ) + + self.set_indent_level(base_indent_level + 1) + for css_tag in css_tags: + self._write_line(f"{css_tag};") + + self.set_indent_level(base_indent_level) + self._write_line("}") + + def __write_css(self, css_class: str, write_style_tag: bool = False) -> None: + base_indent_level = 0 + + if write_style_tag: + self._write_line('") diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_csv.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..011549467e6b465f7f3388a5879eeb4fb1fa45c9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_csv.py @@ -0,0 +1,63 @@ +from typing import Any, List + +import typepy + +from ._text_writer import TextTableWriter + + +class CsvTableWriter(TextTableWriter): + """ + A table writer class for character separated values format. + The default separated character is a comma (``","``). + + :Example: + :ref:`example-csv-table-writer` + """ + + FORMAT_NAME = "csv" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + @property + def margin(self) -> int: + return self._margin + + @margin.setter + def margin(self, value: int) -> None: + # margin setting must be ignored + return + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self._set_chars("") + self.indent_string = "" + self.column_delimiter = kwargs.get("column_delimiter", ",") + self._margin = 0 + + self.is_padding = False + self.is_formatting_float = False + self.is_write_header_separator_row = False + + self._quoting_flags[typepy.Typecode.NULL_STRING] = False + + def _write_header(self) -> None: + if typepy.is_empty_sequence(self.headers): + return + + super()._write_header() + + def _get_opening_row_items(self) -> List[str]: + return [] + + def _get_value_row_separator_items(self) -> List[str]: + return [] + + def _get_closing_row_items(self) -> List[str]: + return [] diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_html.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_html.py new file mode 100644 index 0000000000000000000000000000000000000000..748989d30d6b36ade56892583e44bc0bed8562de --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_html.py @@ -0,0 +1,194 @@ +import copy +import warnings +from typing import Any, List, Optional, Tuple, cast + +import dataproperty +import typepy +from mbstrdecoder import MultiByteStrDecoder +from pathvalidate import replace_symbol + +from ...error import EmptyTableDataError +from ...sanitizer import sanitize_python_var_name +from ...style import Align, FontStyle, FontWeight, HtmlStyler, Style, StylerInterface, VerticalAlign +from .._common import import_error_msg_template +from .._table_writer import AbstractTableWriter +from ._css import CssTableWriter +from ._text_writer import TextTableWriter + + +def _get_tags_module() -> Tuple: + try: + from dominate import tags + from dominate.util import raw + + return tags, raw + except ImportError: + warnings.warn(import_error_msg_template.format("html")) + raise + + +class HtmlTableWriter(TextTableWriter): + """ + A table writer class for HTML format. + + :Example: + :ref:`example-html-table-writer` + """ + + FORMAT_NAME = "html" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return False + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.is_padding = False + self.indent_string = kwargs.get("indent_string", " ") + + self._dp_extractor.preprocessor.line_break_repl = "
" + self._dp_extractor.preprocessor.is_escape_html_tag = False + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) + self._table_tag: Any = None + + self.enable_ansi_escape = False + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table| with HTML table format. + + Args: + write_css (bool): + If |True|, write CSS corresponding to the specified styles, + instead of attributes of HTML tags. + + Example: + :ref:`example-html-table-writer` + + .. note:: + - |None| values will be replaced with an empty value + """ + + tags, raw = _get_tags_module() + write_css: bool = kwargs.get("write_css", False) + + with self._logger: + try: + self._verify_property() + except EmptyTableDataError: + self._logger.logger.debug("no tabular data found") + return + + self._preprocess() + + css_class: Optional[str] = None + + if write_css: + default_css_class_name = replace_symbol(self.table_name, replacement_text="-") + if default_css_class_name: + default_css_class_name += "-css" + else: + default_css_class_name = "ptw-table-css" + + css_class = kwargs.get("css_class", default_css_class_name) + css_writer = CssTableWriter( + table_name=css_class, + margin=self.margin, + stream=self.stream, + ) + css_writer.from_writer(self, is_overwrite_table_name=False) + css_writer.write_table(write_style_tag=True) + + if typepy.is_not_null_string(self.table_name): + if css_class: + self._table_tag = tags.table( + id=sanitize_python_var_name(self.table_name), class_name=css_class + ) + else: + self._table_tag = tags.table(id=sanitize_python_var_name(self.table_name)) + self._table_tag += tags.caption(MultiByteStrDecoder(self.table_name).unicode_str) + else: + if css_class: + self._table_tag = tags.table(class_name=css_class) + else: + self._table_tag = tags.table() + + try: + self._write_header() + except ValueError: + pass + + self._write_body(not write_css) + + def _write_header(self) -> None: + tags, raw = _get_tags_module() + + if not self.is_write_header: + return + + if typepy.is_empty_sequence(self._table_headers): + raise ValueError("headers is empty") + + tr_tag = tags.tr() + for header in self._table_headers: + tr_tag += tags.th(raw(MultiByteStrDecoder(header).unicode_str)) + + thead_tag = tags.thead() + thead_tag += tr_tag + + self._table_tag += thead_tag + + def _write_body(self, write_attr: bool) -> None: + tags, raw = _get_tags_module() + tbody_tag = tags.tbody() + + for row_idx, (values, value_dp_list) in enumerate( + zip(self._table_value_matrix, self._table_value_dp_matrix) + ): + tr_tag = tags.tr() + for value, value_dp, column_dp in zip(values, value_dp_list, self._column_dp_list): + td_tag = tags.td(raw(MultiByteStrDecoder(value).unicode_str)) + + style = self._fetch_style(row_idx, column_dp, value_dp) + + if write_attr: + if style.align == Align.AUTO: + td_tag["align"] = value_dp.align.align_string + else: + td_tag["align"] = style.align.align_string + + if style.vertical_align != VerticalAlign.BASELINE: + td_tag["valign"] = style.vertical_align.align_str + + style_tag = self.__make_style_tag(style=style) + if style_tag: + td_tag["style"] = style_tag + + tr_tag += td_tag + tbody_tag += tr_tag + + self._table_tag += tbody_tag + self._write_line(self._table_tag.render(indent=self.indent_string)) + + def __make_style_tag(self, style: Style) -> Optional[str]: + styles: List[str] = [] + + if self._styler.get_font_size(style): + styles.append(cast(str, self._styler.get_font_size(style))) + if style.font_weight == FontWeight.BOLD: + styles.append("font-weight:bold") + if style.font_style == FontStyle.ITALIC: + styles.append("font-style:italic") + + if not styles: + return None + + return "; ".join(styles) + + def _create_styler(self, writer: AbstractTableWriter) -> StylerInterface: + return HtmlStyler(writer) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_interface.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..16e050bebfe1a05ee3e5b63f89eff1626905daec --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_interface.py @@ -0,0 +1,29 @@ +import abc + + +class TextWriterInterface(metaclass=abc.ABCMeta): + """ + Interface class for writing texts. + """ + + @abc.abstractmethod + def write_null_line(self) -> None: # pragma: no cover + pass + + +class IndentationInterface(metaclass=abc.ABCMeta): + """ + Interface class for indentation methods. + """ + + @abc.abstractmethod + def set_indent_level(self, indent_level: int) -> None: # pragma: no cover + pass + + @abc.abstractmethod + def inc_indent_level(self) -> None: # pragma: no cover + pass + + @abc.abstractmethod + def dec_indent_level(self) -> None: # pragma: no cover + pass diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_json.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_json.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb1e687299ed12e1891fa858f0a0e3d875ea706 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_json.py @@ -0,0 +1,167 @@ +import copy +from textwrap import indent +from typing import Any, List + +import dataproperty +import typepy +from dataproperty import ColumnDataProperty, DataProperty +from mbstrdecoder import MultiByteStrDecoder +from tabledata import to_value_matrix +from typepy import Typecode + +from .._msgfy import to_error_message +from ._common import serialize_dp +from ._text_writer import IndentationTextTableWriter + + +try: + import simplejson as json +except ImportError: + import json # type: ignore + + +class JsonTableWriter(IndentationTextTableWriter): + """ + A table writer class for JSON format. + + Examples: + :ref:`example-json-table-writer` + + .. py:method:: write_table + + |write_table| with JSON format. + + Args: + indent (Optional[int]): + Indent level of an output. + Interpretation of indent level value differ format to format. + Some writer classes may ignore this value. + Defaults to 4. + + sort_keys (Optional[bool]): + If |True|, the output of dictionaries will be sorted by key. + Defaults to |False|. + + Examples: + :ref:`example-json-table-writer` + + .. note:: + Specific values in the tabular data are converted when writing: + + - |None|: written as ``null`` + - |inf|: written as ``Infinity`` + - |nan|: written as ``NaN`` + """ + + FORMAT_NAME = "json" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.set_indent_level(4) + + self.is_formatting_float = False + self.is_write_opening_row = True + self.is_write_closing_row = True + self.char_right_side_row = "," + self.char_opening_row_cross_point = "" + self.char_closing_row_cross_point = "" + + self._is_require_header = True + self._dp_extractor.type_value_map = { + Typecode.INFINITY: "Infinity", + Typecode.NAN: "NaN", + } + self._dp_extractor.update_strict_level_map({Typecode.BOOL: typepy.StrictLevel.MAX}) + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) + + self._init_cross_point_maps() + + def write_null_line(self) -> None: + self._verify_stream() + self.stream.write("\n") + + def _write_table(self, **kwargs: Any) -> None: + sort_keys = kwargs.get("sort_keys", False) + + self._preprocess() + + with self._logger: + self._write_opening_row() + + json_text_list = [] + for json_data in self._table_value_matrix: + json_text = json.dumps( + json_data, indent=self._indent_level, ensure_ascii=False, sort_keys=sort_keys + ) + json_text_list.append(json_text) + + joint_text = self.char_right_side_row + "\n" + json_text = joint_text.join(json_text_list) + if all([not self.is_write_closing_row, typepy.is_not_null_string(json_text)]): + json_text += joint_text + + self.stream.write(indent(json_text, " " * self._indent_level)) + self._write_closing_row() + + def _to_row_item(self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + return value_dp.to_str() + + def _preprocess_table_dp(self) -> None: + if self._is_complete_table_dp_preprocess: + return + + self._logger.logger.debug("_preprocess_table_dp") + + try: + self._table_value_dp_matrix = self._dp_extractor.to_dp_matrix( + to_value_matrix(self.headers, self.value_matrix) + ) + except TypeError as e: + self._logger.logger.debug(to_error_message(e)) + self._table_value_dp_matrix = [] + + self._is_complete_table_dp_preprocess = True + + def _preprocess_header(self) -> None: + if self._is_complete_header_preprocess: + return + + self._logger.logger.debug("_preprocess_header") + + self._table_headers = [ + header_dp.to_str() for header_dp in self._dp_extractor.to_header_dp_list() + ] + + self._is_complete_header_preprocess = True + + def _preprocess_value_matrix(self) -> None: + if self._is_complete_value_matrix_preprocess: + return + + self._table_value_matrix = [ + dict(zip(self._table_headers, [serialize_dp(dp) for dp in dp_list])) + for dp_list in self._table_value_dp_matrix + ] + + self._is_complete_value_matrix_preprocess = True + + def _get_opening_row_items(self) -> List[str]: + if typepy.is_not_null_string(self.table_name): + return [f'{{ "{MultiByteStrDecoder(self.table_name).unicode_str:s}" : ['] + + return ["["] + + def _get_closing_row_items(self) -> List[str]: + if typepy.is_not_null_string(self.table_name): + return ["\n]}"] + + return ["\n]"] diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_jsonlines.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_jsonlines.py new file mode 100644 index 0000000000000000000000000000000000000000..5423f85638f007971dcc787c107a38446668d8e1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_jsonlines.py @@ -0,0 +1,53 @@ +from typing import Any + +from ._json import JsonTableWriter + + +try: + import simplejson as json +except ImportError: + import json # type: ignore + + +class JsonLinesTableWriter(JsonTableWriter): + """ + A table writer class for JSON lines format. + + :Example: + :ref:`example-jsonl-writer` + """ + + FORMAT_NAME = "json_lines" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table| with + `Line-delimited JSON(LDJSON) + `__ + /NDJSON/JSON Lines format. + + Args: + sort_keys (Optional[bool]): + If |True|, the output of dictionaries will be sorted by key. + Defaults to |False|. + + Example: + :ref:`example-jsonl-writer` + """ + + sort_keys = kwargs.get("sort_keys", False) + + with self._logger: + self._verify_property() + self._preprocess() + + for values in self._table_value_matrix: + self._write_line(json.dumps(values, ensure_ascii=False, sort_keys=sort_keys)) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_latex.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_latex.py new file mode 100644 index 0000000000000000000000000000000000000000..884c8b6b836ebf2d95c5ebd83be0812c494db2f1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_latex.py @@ -0,0 +1,226 @@ +import copy +import re +from typing import Any, List + +import dataproperty as dp +import typepy +from dataproperty import ColumnDataProperty, DataProperty +from typepy import Typecode + +from ...style import Align, LatexStyler, StylerInterface +from .._table_writer import AbstractTableWriter +from ._text_writer import IndentationTextTableWriter + + +class LatexWriter(IndentationTextTableWriter): + """ + A base writer class for LaTeX format. + """ + + _RE_MATH_PARTS = re.compile(r"^\\?[a-zA-Z]+$") + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self._set_chars("") + + self.is_write_opening_row = True + self.is_write_closing_row = True + self.indent_string = kwargs.get("indent_string", " ") + self.column_delimiter = " & " + self.char_right_side_row = r" \\" + + self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS) + + self._init_cross_point_maps() + + def _is_math_parts(self, value_dp: DataProperty) -> bool: + if value_dp.typecode in [Typecode.INTEGER, Typecode.REAL_NUMBER]: + return False + + try: + if self._RE_MATH_PARTS.search(value_dp.data): + return True + except TypeError: + pass + + return False + + def _get_col_align_char_list(self) -> List[str]: + col_align_list = [] + + for col_dp in self._column_dp_list: + align = self._get_col_style(col_dp.column_index).align + if align is None or align == Align.AUTO: + align = col_dp.align + + if align == Align.RIGHT: + col_align = "r" + elif align == Align.CENTER: + col_align = "c" + else: + col_align = "l" + + col_align_list.append(col_align) + + return col_align_list + + def _write_opening_row(self) -> None: + super()._write_opening_row() + self.inc_indent_level() + + def _write_closing_row(self) -> None: + self.dec_indent_level() + super()._write_closing_row() + + def _to_math_parts(self, value: str) -> str: + # dollar characters for both sides of math parts are not required in + # Jupyter latex. + # return r"${:s}$".format(value) + + return value + + def _create_styler(self, writer: AbstractTableWriter) -> StylerInterface: + return LatexStyler(writer) + + +class LatexMatrixWriter(LatexWriter): + """ + A matrix writer class for LaTeX environment. + + :Example: + :ref:`example-latex-matrix-writer` + + .. py:method:: write_table + + |write_table| with LaTeX ``array`` environment. + + :Example: + :ref:`example-latex-matrix-writer` + """ + + FORMAT_NAME = "latex_matrix" + _RE_VAR = re.compile(r"^[a-zA-Z]+_\{[a-zA-Z0-9]+\}$") + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.is_write_header = False + self.is_write_header_separator_row = False + + def _to_row_item(self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + row_item = super()._to_row_item(row_idx, col_dp, value_dp) + + if self._RE_VAR.search(row_item): + return row_item + + if self._is_math_parts(value_dp): + return self._to_math_parts(row_item) + + return row_item + + def _get_header_row_separator_items(self) -> List[str]: + return [] + + def _get_opening_row_items(self) -> List[str]: + row_item_list = [] + + if typepy.is_not_null_string(self.table_name): + row_item_list.append(self.table_name + r" = \left( ") + else: + row_item_list.append(r"\left( ") + + row_item_list.extend( + [r"\begin{array}{", "{:s}".format("".join(self._get_col_align_char_list())), "}"] + ) + + return ["".join(row_item_list)] + + def _get_closing_row_items(self) -> List[str]: + return [r"\end{array} \right)"] + + def _write_opening_row(self) -> None: + self._write_line(r"\begin{equation}") + self.inc_indent_level() + super()._write_opening_row() + + def _write_closing_row(self) -> None: + super()._write_closing_row() + self.dec_indent_level() + self._write_line(r"\end{equation}") + + +class LatexTableWriter(LatexWriter): + """ + A matrix writer class for LaTeX environment. + + :Example: + :ref:`example-latex-table-writer` + + .. py:method:: write_table + + |write_table| with LaTeX ``array`` environment. + + :Example: + :ref:`example-latex-table-writer` + """ + + FORMAT_NAME = "latex_table" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.char_right_side_row = r" \\ \hline" + self._dp_extractor.type_value_map[Typecode.INFINITY] = r"\infty" + + def _get_opening_row_items(self) -> List[str]: + return [ + "".join( + [ + r"\begin{array}{", + "{:s}".format(" | ".join(self._get_col_align_char_list())), + r"} \hline", + ] + ) + ] + + def __is_requre_verbatim(self, value_dp: DataProperty) -> bool: + if value_dp.typecode != typepy.Typecode.STRING: + return False + + return True + + def __verbatim(self, value: str) -> str: + return r"\verb" + f"|{value:s}|" + + def _to_header_item(self, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + return self.__verbatim(super()._to_header_item(col_dp, value_dp)) + + def _to_row_item(self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + row_item = super()._to_row_item(row_idx, col_dp, value_dp) + + if self._is_math_parts(value_dp): + return self._to_math_parts(row_item) + + if self.__is_requre_verbatim(value_dp): + return self.__verbatim(row_item) + + return row_item + + def _get_header_row_separator_items(self) -> List[str]: + return [r"\hline"] + + def _get_closing_row_items(self) -> List[str]: + return [r"\end{array}"] diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_ltsv.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_ltsv.py new file mode 100644 index 0000000000000000000000000000000000000000..2da8105a09934a89d8014a8019b2ff4d6fe19eda --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_ltsv.py @@ -0,0 +1,59 @@ +from typing import Any + +import pathvalidate +import typepy + +from ._csv import CsvTableWriter + + +class LtsvTableWriter(CsvTableWriter): + """ + A table writer class for + `Labeled Tab-separated Values (LTSV) `__ format. + + :Example: + :ref:`example-ltsv-table-writer` + """ + + FORMAT_NAME = "ltsv" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.is_write_header = False + + self._is_require_header = True + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table| with + `Labeled Tab-separated Values (LTSV) `__ format. + Invalid characters in labels/data are removed. + + :Example: + :ref:`example-ltsv-table-writer` + """ + + with self._logger: + self._verify_property() + self._preprocess() + + for values in self._table_value_matrix: + ltsv_item_list = [ + f"{pathvalidate.sanitize_ltsv_label(header_name):s}:{value}" + for header_name, value in zip(self.headers, values) + if typepy.is_not_null_string(value) + ] + + if typepy.is_empty_sequence(ltsv_item_list): + continue + + self._write_line("\t".join(ltsv_item_list)) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_markdown.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_markdown.py new file mode 100644 index 0000000000000000000000000000000000000000..d87963b9cd1f3e5550c369ea3ebdb77b6c7b2b88 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_markdown.py @@ -0,0 +1,198 @@ +import copy +from enum import Enum, unique +from typing import Any, List, Union + +import dataproperty as dp +import typepy +from dataproperty import ColumnDataProperty, DataProperty +from mbstrdecoder import MultiByteStrDecoder +from pathvalidate import replace_symbol + +from ..._function import normalize_enum +from ...error import EmptyTableDataError +from ...style import Align, GFMarkdownStyler, MarkdownStyler, StylerInterface +from .._table_writer import AbstractTableWriter +from ._text_writer import IndentationTextTableWriter + + +@unique +class MarkdownFlavor(Enum): + COMMON_MARK = "common_mark" + GITHUB = "github" + GFM = "gfm" + JEKYLL = "jekyll" + KRAMDOWN = "kramdown" + + +def normalize_md_flavor(flavor: Union[str, MarkdownFlavor, None]) -> MarkdownFlavor: + if isinstance(flavor, str): + flavor_str = replace_symbol(flavor.strip(), "_").upper() + flavor_str = flavor_str.replace("COMMONMARK", "COMMON_MARK") + flavor = flavor_str + + norm_flavor = normalize_enum(flavor, MarkdownFlavor, default=MarkdownFlavor.COMMON_MARK) + + if norm_flavor == MarkdownFlavor.GITHUB: + return MarkdownFlavor.GFM + + if norm_flavor == MarkdownFlavor.JEKYLL: + return MarkdownFlavor.KRAMDOWN + + return norm_flavor + + +class MarkdownTableWriter(IndentationTextTableWriter): + """ + A table writer class for Markdown format. + + Example: + :ref:`example-markdown-table-writer` + """ + + FORMAT_NAME = "markdown" + DEFAULT_FLAVOR = MarkdownFlavor.COMMON_MARK + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + self.__flavor = normalize_md_flavor(kwargs.pop("flavor", self.DEFAULT_FLAVOR)) + + super().__init__(**kwargs) + + self.indent_string = "" + self.column_delimiter = "|" + self.char_left_side_row = "|" + self.char_right_side_row = "|" + self.char_cross_point = "|" + self.char_header_row_cross_point = "|" + self.char_header_row_left_cross_point = "|" + self.char_header_row_right_cross_point = "|" + + self.is_write_opening_row = True + self._use_default_header = True + + self._is_require_header = True + self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS) + self._dp_extractor.min_column_width = 3 + + self._init_cross_point_maps() + + def _to_header_item(self, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + return self.__escape_vertical_bar_char(super()._to_header_item(col_dp, value_dp)) + + def _to_row_item(self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + return self.__escape_vertical_bar_char(super()._to_row_item(row_idx, col_dp, value_dp)) + + def _get_opening_row_items(self) -> List[str]: + return [] + + def _get_header_row_separator_items(self) -> List[str]: + header_separator_list = [] + margin = " " * self.margin + + for col_dp in self._column_dp_list: + padding_len = self._get_padding_len(col_dp) + align = self._get_align(col_dp.column_index, col_dp.align) + + if align == Align.RIGHT: + separator_item = "-" * (padding_len - 1) + ":" + elif align == Align.CENTER: + separator_item = ":" + "-" * (padding_len - 2) + ":" + else: + separator_item = "-" * padding_len + + header_separator_list.append( + "{margin}{item}{margin}".format(margin=margin, item=separator_item) + ) + + return header_separator_list + + def _get_value_row_separator_items(self) -> List[str]: + return [] + + def _get_closing_row_items(self) -> List[str]: + return [] + + def _write_header(self) -> None: + super()._write_header() + + if self.__flavor == MarkdownFlavor.KRAMDOWN: + self._write_line() + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table| with Markdown table format. + + Args: + flavor (Optional[str]): + possible flavors are as follows (case insensitive): + + - ``"CommonMark"`` + - ``"gfm"`` + - ``"github"`` (alias of ``"gfm"``) + - ``kramdown`` + - ``Jekyll`` (alias of ``"kramdown"``) + + Defaults to ``"CommonMark"``. + + Example: + :ref:`example-markdown-table-writer` + + .. note:: + - |None| values are written as an empty string + - Vertical bar characters (``'|'``) in table items are escaped + """ + + if "flavor" in kwargs: + new_flavor = normalize_md_flavor(kwargs["flavor"]) + if new_flavor != self.__flavor: + self._clear_preprocess() + self.__flavor = new_flavor + + if self.__flavor: + self._styler = self._create_styler(self) + + with self._logger: + try: + self._verify_property() + except EmptyTableDataError: + self._logger.logger.debug("no tabular data found") + return + + self.__write_chapter() + self._write_table(**kwargs) + if self.is_write_null_line_after_table: + self.write_null_line() + + def _write_table_iter(self, **kwargs: Any) -> None: + self.__write_chapter() + super()._write_table_iter() + + def __write_chapter(self) -> None: + if typepy.is_null_string(self.table_name): + return + + self._write_line( + "{:s} {:s}".format( + "#" * (self._indent_level + 1), MultiByteStrDecoder(self.table_name).unicode_str + ) + ) + + if self.__flavor == MarkdownFlavor.KRAMDOWN: + self._write_line() + + def _create_styler(self, writer: AbstractTableWriter) -> StylerInterface: + if self.__flavor == MarkdownFlavor.GFM: + return GFMarkdownStyler(writer) + + return MarkdownStyler(writer) + + @staticmethod + def __escape_vertical_bar_char(value: str) -> str: + return value.replace("|", r"\|") diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_mediawiki.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_mediawiki.py new file mode 100644 index 0000000000000000000000000000000000000000..95c622e768f4d18d63a3ba3b53bb742f30033e92 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_mediawiki.py @@ -0,0 +1,105 @@ +import copy +import re +from typing import Any, List, Sequence + +import dataproperty as dp +import typepy +from dataproperty import ColumnDataProperty, DataProperty, LineBreakHandling +from mbstrdecoder import MultiByteStrDecoder + +from ...style import Align, Style, get_align_char +from ._text_writer import TextTableWriter + + +class MediaWikiTableWriter(TextTableWriter): + """ + A table writer class for `MediaWiki `__ format. + + :Example: + :ref:`example-mediawiki-table-writer` + """ + + FORMAT_NAME = "mediawiki" + __RE_TABLE_SEQUENCE = re.compile(r"^[\s]+[*|#]+") + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.column_delimiter = "\n" + + self.is_padding = False + self.is_write_header_separator_row = True + self.is_write_value_separator_row = True + self.is_write_opening_row = True + self.is_write_closing_row = True + + self.update_preprocessor(line_break_handling=LineBreakHandling.NOP) + + self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS) + + # experimental: This attribute may change in the future release + self.table_style = kwargs.get("table_style", "") + + def _write_header(self) -> None: + if not self.is_write_header: + return + + if typepy.is_not_null_string(self.table_name): + self._write_line("|+" + MultiByteStrDecoder(self.table_name).unicode_str) + + super()._write_header() + + def _write_value_row( + self, row: int, values: Sequence[str], value_dp_list: Sequence[DataProperty] + ) -> None: + self._write_row( + row, + [ + self.__modify_table_element(value, value_dp) + for value, value_dp, in zip(values, value_dp_list) + ], + ) + + def _get_opening_row_items(self) -> List[str]: + item = '{| class="wikitable"' + if self.table_style: + item += f' style="{self.table_style}"' + + return [item] + + def _get_header_row_separator_items(self) -> List[str]: + return ["|-"] + + def _get_value_row_separator_items(self) -> List[str]: + return self._get_header_row_separator_items() + + def _get_closing_row_items(self) -> List[str]: + return ["|}"] + + def _apply_style_to_header_item( + self, col_dp: ColumnDataProperty, value_dp: DataProperty, style: Style + ) -> str: + value = self._styler.apply(col_dp.dp_to_str(value_dp), style=style) + str_format = "! {{:{:s}{:s}}}".format( + get_align_char(Align.CENTER), str(self._get_padding_len(col_dp, value_dp)) + ) + return str_format.format(value) + + def __modify_table_element(self, value: str, value_dp: DataProperty) -> str: + if value_dp.align is Align.LEFT: + forma_stirng = "| {1:s}" + else: + forma_stirng = '| style="text-align:{0:s}"| {1:s}' + + if self.__RE_TABLE_SEQUENCE.search(value) is not None: + value = "\n" + value.lstrip() + + return forma_stirng.format(value_dp.align.align_string, value) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_rst.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_rst.py new file mode 100644 index 0000000000000000000000000000000000000000..5409d09c4d5b0b21c28cb7a32d28ff31c02ff617 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_rst.py @@ -0,0 +1,241 @@ +import copy +from typing import Any, List + +import dataproperty +import typepy +from mbstrdecoder import MultiByteStrDecoder + +from ...error import EmptyTableDataError +from ...style import ReStructuredTextStyler, StylerInterface +from .._table_writer import AbstractTableWriter +from ._text_writer import IndentationTextTableWriter + + +class RstTableWriter(IndentationTextTableWriter): + """ + A base class of reStructuredText table writer. + """ + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.char_header_row_separator = "=" + self.char_cross_point = "+" + self.char_left_cross_point = "+" + self.char_right_cross_point = "+" + self.char_top_left_cross_point = "+" + self.char_top_right_cross_point = "+" + self.char_bottom_left_cross_point = "+" + self.char_bottom_right_cross_point = "+" + self.char_header_row_cross_point = "+" + self.char_header_row_left_cross_point = "+" + self.char_header_row_right_cross_point = "+" + + self.char_opening_row_cross_point = "+" + self.char_closing_row_cross_point = "+" + + self.indent_string = kwargs.get("indent_string", " ") + self.is_write_header_separator_row = True + self.is_write_value_separator_row = True + self.is_write_opening_row = True + self.is_write_closing_row = True + + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) + + self._init_cross_point_maps() + + def write_table(self, **kwargs: Any) -> None: + with self._logger: + self._write_line(self._get_table_directive()) + + try: + self._verify_property() + except EmptyTableDataError: + self._logger.logger.debug("no tabular data found") + return + + self._write_table(**kwargs) + if self.is_write_null_line_after_table: + self.write_null_line() + + def _get_table_directive(self) -> str: + if typepy.is_null_string(self.table_name): + return ".. table::\n" + + return f".. table:: {MultiByteStrDecoder(self.table_name).unicode_str}\n" + + def _write_table(self, **kwargs: Any) -> None: + self.inc_indent_level() + super()._write_table(**kwargs) + self.dec_indent_level() + + def _create_styler(self, writer: AbstractTableWriter) -> StylerInterface: + return ReStructuredTextStyler(writer) + + +class RstCsvTableWriter(RstTableWriter): + """ + A table class writer for reStructuredText + `CSV table `__ + format. + + :Example: + :ref:`example-rst-csv-table-writer` + """ + + FORMAT_NAME = "rst_csv_table" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.column_delimiter = ", " + self.char_cross_point = "" + self.is_padding = False + self.is_write_header_separator_row = False + self.is_write_value_separator_row = False + self.is_write_closing_row = False + + self._quoting_flags[typepy.Typecode.STRING] = True + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table| with reStructuredText CSV table format. + + :Example: + :ref:`example-rst-csv-table-writer` + + .. note:: + - |None| values are written as an empty string + """ + + IndentationTextTableWriter.write_table(self, **kwargs) + + def _get_opening_row_items(self) -> List[str]: + directive = ".. csv-table::" + + if typepy.is_null_string(self.table_name): + return [directive] + + return [f"{directive} {MultiByteStrDecoder(self.table_name).unicode_str}"] + + def _write_opening_row(self) -> None: + self.dec_indent_level() + super()._write_opening_row() + self.inc_indent_level() + + def _write_header(self) -> None: + if not self.is_write_header: + return + + if typepy.is_not_empty_sequence(self.headers): + self._write_line( + ':header: "{:s}"'.format( + '", "'.join(MultiByteStrDecoder(header).unicode_str for header in self.headers) + ) + ) + + self._write_line( + ":widths: " + ", ".join(str(col_dp.ascii_char_width) for col_dp in self._column_dp_list) + ) + self._write_line() + + def _get_value_row_separator_items(self) -> List[str]: + return [] + + def _get_closing_row_items(self) -> List[str]: + return [] + + +class RstGridTableWriter(RstTableWriter): + """ + A table writer class for reStructuredText + `Grid Tables `__ + format. + + :Example: + :ref:`example-rst-grid-table-writer` + + .. py:method:: write_table + + |write_table| with reStructuredText grid tables format. + + :Example: + :ref:`example-rst-grid-table-writer` + + .. note:: + - |None| values are written as an empty string + """ + + FORMAT_NAME = "rst_grid_table" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return False + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.char_left_side_row = "|" + self.char_right_side_row = "|" + + +class RstSimpleTableWriter(RstTableWriter): + """ + A table writer class for reStructuredText + `Simple Tables + `__ + format. + + :Example: + :ref:`example-rst-simple-table-writer` + + .. py:method:: write_table + + |write_table| with reStructuredText simple tables format. + + :Example: + :ref:`example-rst-simple-table-writer` + + .. note:: + - |None| values are written as an empty string + """ + + FORMAT_NAME = "rst_simple_table" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return False + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.column_delimiter = " " + self.char_cross_point = " " + self.char_opening_row_cross_point = " " + self.char_closing_row_cross_point = " " + self.char_header_row_cross_point = " " + self.char_header_row_left_cross_point = " " + self.char_header_row_right_cross_point = " " + + self.char_opening_row = "=" + self.char_closing_row = "=" + + self.is_write_value_separator_row = False + + self._init_cross_point_maps() diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_spacealigned.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_spacealigned.py new file mode 100644 index 0000000000000000000000000000000000000000..2f5827ba8c5b3a080f3be1df6619d13ba364575c --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_spacealigned.py @@ -0,0 +1,39 @@ +import copy +from typing import Any + +import dataproperty + +from ._csv import CsvTableWriter + + +class SpaceAlignedTableWriter(CsvTableWriter): + """ + A table writer class for space-separated values (SSV) format. + + :Example: + :ref:`example-space-aligned-table-writer` + + .. py:method:: write_table + + |write_table| with SSV format. + + :Example: + :ref:`example-space-aligned-table-writer` + """ + + FORMAT_NAME = "space_aligned" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.column_delimiter = " " + self.char_cross_point = " " + + self.is_padding = True + self.is_formatting_float = kwargs.get("is_formatting_float", True) + + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_text_writer.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_text_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..88f90921ea1391d654f576c5252ae27fa9ec7c77 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_text_writer.py @@ -0,0 +1,646 @@ +import enum +import io +import sys +from itertools import chain +from typing import IO, Any, List, Optional, Sequence, Union, cast + +import typepy +from dataproperty import ColumnDataProperty, DataProperty, LineBreakHandling + +from ...error import EmptyTableDataError +from ...style import Cell, ColSeparatorStyleFilterFunc, Style, StylerInterface, TextStyler +from .._common import HEADER_ROW +from .._table_writer import AbstractTableWriter +from ._interface import IndentationInterface, TextWriterInterface + + +@enum.unique +class RowType(enum.Enum): + OPENING = "opening" + HEADER_SEPARATOR = "header separator" + MIDDLE = "middle" + CLOSING = "closing" + + +class TextTableWriter(AbstractTableWriter, TextWriterInterface): + """ + A base class for table writer with text formats. + + .. figure:: ss/table_char.png + :scale: 60% + :alt: table_char + + Character attributes that compose a table + + .. py:attribute:: column_delimiter + :type: str + + A column delimiter of a table. + + .. py:attribute:: char_left_side_row + :type: str + + A character of a left side of a row. + + .. py:attribute:: char_right_side_row + :type: str + + A character of a right side of a row. + + .. py:attribute:: char_cross_point + :type: str + + A character of the crossing point of column delimiter and row + delimiter. + + .. py:attribute:: char_opening_row + :type: str + + A character of the first line of a table. + + .. py:attribute:: char_header_row_separator + :type: str + + A character of a separator line of the header and + the body of the table. + + .. py:attribute:: char_value_row_separator + :type: str + + A character of a row separator line of the table. + + .. py:attribute:: char_closing_row + :type: str + + A character of the last line of a table. + + .. py:attribute:: is_write_header_separator_row + :type: bool + + Write a header separator line of the table if the value is |True|. + + .. py:attribute:: is_write_value_separator_row + :type: bool + + Write row separator line(s) of the table if the value is |True|. + + .. py:attribute:: is_write_opening_row + :type: bool + + Write an opening line of the table if the value is |True|. + + .. py:attribute:: is_write_closing_row + :type: bool + + Write a closing line of the table if the value is |True|. + + .. py:attribute:: is_write_null_line_after_table + :type: bool + + Write a blank line of after writing a table if the value is |True|. + + .. py:attribute:: margin + :type: int + + Margin size for each cells + + """ + + def __update_template(self) -> None: + self.__value_cell_margin_format = self.__make_margin_format(" ") + self.__opening_row_cell_format = self.__make_margin_format(self.char_opening_row) + self._header_row_separator_cell_format = self.__make_margin_format( + self.char_header_row_separator + ) + self.__value_row_separator_cell_format = self.__make_margin_format( + self.char_value_row_separator + ) + self.__closing_row_cell_format = self.__make_margin_format(self.char_closing_row) + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.stream = sys.stdout + + self._set_chars("") + + self.column_delimiter = "|" + + self.char_opening_row = "-" + self.char_opening_row_cross_point = "-" + + self.char_header_row_separator = "-" + self.char_header_row_cross_point = "-" + + self.char_value_row_separator = "-" + + self.char_closing_row = "-" + self.char_closing_row_cross_point = "-" + + self._margin = kwargs.get("margin", 0) + + self._dp_extractor.preprocessor.line_break_handling = LineBreakHandling.REPLACE + self.is_write_null_line_after_table = kwargs.get("is_write_null_line_after_table", False) + + self._init_cross_point_maps() + + self._col_separator_style_filters: List[ColSeparatorStyleFilterFunc] = [] + + if "theme" in kwargs: + self.set_theme(kwargs["theme"]) + + def __repr__(self) -> str: + return self.dumps() + + @property + def margin(self) -> int: + return self._margin + + @margin.setter + def margin(self, value: int) -> None: + if value < 0: + raise ValueError("margin value must be zero or greater") + + if self._margin == value: + return + + self._margin = value + self._clear_preprocess() + + def _init_cross_point_maps(self) -> None: + self.__cross_point_maps = { + RowType.OPENING: self.char_opening_row_cross_point, + RowType.HEADER_SEPARATOR: self.char_header_row_cross_point, + RowType.MIDDLE: self.char_cross_point, + RowType.CLOSING: self.char_closing_row_cross_point, + } + self.__left_cross_point_maps = { + RowType.OPENING: self.char_top_left_cross_point, + RowType.HEADER_SEPARATOR: self.char_header_row_left_cross_point, + RowType.MIDDLE: self.char_left_cross_point, + RowType.CLOSING: self.char_bottom_left_cross_point, + } + self.__right_cross_point_maps = { + RowType.OPENING: self.char_top_right_cross_point, + RowType.HEADER_SEPARATOR: self.char_header_row_right_cross_point, + RowType.MIDDLE: self.char_right_cross_point, + RowType.CLOSING: self.char_bottom_right_cross_point, + } + + def add_col_separator_style_filter(self, style_filter: ColSeparatorStyleFilterFunc) -> None: + """Add a style filter function for columns to the writer. + + Args: + style_filter: + A function that called for each cell in the table to apply a style + to table cells. + The function will be required to implement the following Protocol: + + .. code-block:: python + + class ColSeparatorStyleFilterFunc(Protocol): + def __call__( + self, left_cell: Optional[Cell], right_cell: Optional[Cell], **kwargs: Any + ) -> Optional[Style]: + ... + + If more than one style filter function is added to the writer, + it will be called from the last one added. + These style functions should return |None| when not needed to apply styles. + If all of the style functions returned |None|, + :py:attr:`~.default_style` will be applied. + + You can pass keyword arguments to style filter functions via + :py:attr:`~.style_filter_kwargs`. In default, the attribute includes: + + - ``writer``: the writer instance that the caller of a ``style_filter function`` + """ + + self._col_separator_style_filters.insert(0, style_filter) + self._clear_preprocess() + + def clear_theme(self) -> None: + """Remove all of the style filters.""" + + super().clear_theme() + + if not self._col_separator_style_filters: + return + + self._col_separator_style_filters = [] + self._clear_preprocess() + + def write_null_line(self) -> None: + """ + Write a null line to the |stream|. + """ + + self._write_line() + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table|. + + .. note:: + - |None| values are written as an empty string. + """ + + try: + super().write_table(**kwargs) + except EmptyTableDataError: + raise + + if self.is_write_null_line_after_table: + self.write_null_line() + + def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None: + """Write data to the output with tabular format. + + During the executing this method, + :py:attr:`~pytablewriter.writer._table_writer.AbstractTableWriter.enable_ansi_escape` + attribute will be temporarily set to |False|. + + Args: + output: + The value must either an output stream or a path to an output file. + + close_after_write: + Close the output after write. + Defaults to |True|. + """ + + try: + output.write # type: ignore + self.stream = output + except AttributeError: + self.stream = open(output, "w", encoding="utf-8") # type: ignore + + try: + stash = self.enable_ansi_escape + self.enable_ansi_escape = False + self.write_table(**kwargs) + finally: + if close_after_write: + self.stream.close() # type: ignore + self.stream = sys.stdout + + self.enable_ansi_escape = stash + + def dumps(self, **kwargs: Any) -> str: + """Get rendered tabular text from the table data. + + Only available for text format table writers. + + Args: + **kwargs: + Optional arguments that the writer takes. + + Returns: + str: Rendered tabular text. + """ + + old_stream = self.stream + + try: + self.stream = io.StringIO() + self.write_table(**kwargs) + tabular_text = self.stream.getvalue() + finally: + self.stream = old_stream + + return tabular_text + + def _set_chars(self, c: str) -> None: + self.char_left_side_row = c + self.char_right_side_row = c + + self.char_cross_point = c + self.char_left_cross_point = c + self.char_right_cross_point = c + self.char_top_left_cross_point = c + self.char_top_right_cross_point = c + self.char_bottom_left_cross_point = c + self.char_bottom_right_cross_point = c + + self.char_opening_row = c + self.char_opening_row_cross_point = c + + self.char_header_row_separator = c + self.char_header_row_cross_point = c + self.char_header_row_left_cross_point = c + self.char_header_row_right_cross_point = c + + self.char_value_row_separator = c + + self.char_closing_row = c + self.char_closing_row_cross_point = c + + self._init_cross_point_maps() + + def _create_styler(self, writer: AbstractTableWriter) -> StylerInterface: + return TextStyler(writer) + + def _write_table_iter(self, **kwargs: Any) -> None: + super()._write_table_iter() + if self.is_write_null_line_after_table: + self.write_null_line() + + def _write_table(self, **kwargs: Any) -> None: + self._preprocess() + self._write_opening_row() + + try: + self._write_header() + self.__write_header_row_separator() + except ValueError: + pass + + is_first_value_row = True + for row, (values, value_dp_list) in enumerate( + zip(self._table_value_matrix, self._table_value_dp_matrix) + ): + try: + if is_first_value_row: + is_first_value_row = False + else: + if self.is_write_value_separator_row: + self._write_value_row_separator() + + self._write_value_row(row, cast(List[str], values), value_dp_list) + except TypeError: + continue + + self._write_closing_row() + + def _get_opening_row_items(self) -> List[str]: + return self.__get_row_separator_items(self.__opening_row_cell_format, self.char_opening_row) + + def _get_header_row_separator_items(self) -> List[str]: + return self.__get_row_separator_items( + self._header_row_separator_cell_format, self.char_header_row_separator + ) + + def _get_value_row_separator_items(self) -> List[str]: + return self.__get_row_separator_items( + self.__value_row_separator_cell_format, self.char_value_row_separator + ) + + def _get_closing_row_items(self) -> List[str]: + return self.__get_row_separator_items(self.__closing_row_cell_format, self.char_closing_row) + + def __get_row_separator_items(self, margin_format: str, separator_char: str) -> List[str]: + return [ + margin_format.format(separator_char * self._get_padding_len(col_dp)) + for col_dp in self._column_dp_list + ] + + def _to_header_item(self, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + return self.__value_cell_margin_format.format(super()._to_header_item(col_dp, value_dp)) + + def _apply_style_to_row_item( + self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty, style: Style + ) -> str: + return self.__value_cell_margin_format.format( + super()._apply_style_to_row_item(row_idx, col_dp, value_dp, style) + ) + + def _write_raw_string(self, unicode_text: str) -> None: + self.stream.write(unicode_text) + + def _write_raw_line(self, unicode_text: str = "") -> None: + self._write_raw_string(unicode_text + "\n") + + def _write(self, text: str) -> None: + self._write_raw_string(text) + + def _write_line(self, text: str = "") -> None: + self._write_raw_line(text) + + def _fetch_col_separator_style( + self, left_cell: Optional[Cell], right_cell: Optional[Cell], default_style: Style + ) -> Style: + for style_filter in self._col_separator_style_filters: + style = style_filter(left_cell, right_cell, **self.style_filter_kwargs) + if style: + return style + + return default_style + + def __to_column_delimiter( + self, + row: int, + left_col_dp: Optional[ColumnDataProperty], + right_col_dp: Optional[ColumnDataProperty], + col_delimiter: str, + ) -> str: + left_cell = None + if left_col_dp: + left_cell = Cell( + row=row, + col=left_col_dp.column_index, + value=col_delimiter, + default_style=self._get_col_style(left_col_dp.column_index), + ) + + right_cell = None + if right_col_dp: + right_cell = Cell( + row=row, + col=right_col_dp.column_index, + value=col_delimiter, + default_style=self._get_col_style(right_col_dp.column_index), + ) + + style = self._fetch_col_separator_style( + left_cell=left_cell, + right_cell=right_cell, + default_style=self.default_style, + ) + + return self._styler.apply_terminal_style(col_delimiter, style=style) + + def _write_row(self, row: int, values: Sequence[str]) -> None: + if typepy.is_empty_sequence(values): + return + + col_delimiters = ( + [ + self.__to_column_delimiter( + row, + None, + self._column_dp_list[0], + self.char_left_side_row, + ) + ] + + [ + self.__to_column_delimiter( + row, + self._column_dp_list[col_idx], + self._column_dp_list[col_idx + 1], + self.column_delimiter, + ) + for col_idx in range(len(self._column_dp_list) - 1) + ] + + [ + self.__to_column_delimiter( + row, + self._column_dp_list[-1], + None, + self.char_right_side_row, + ) + ] + ) + + row_items = [""] * (len(col_delimiters) + len(values)) + row_items[::2] = col_delimiters + row_items[1::2] = list(values) + + self._write_line("".join(chain.from_iterable(row_items))) + + def _write_header(self) -> None: + if not self.is_write_header: + return + + if typepy.is_empty_sequence(self._table_headers): + raise ValueError("header is empty") + + self._write_row(HEADER_ROW, self._table_headers) + + def _write_value_row( + self, row: int, values: Sequence[str], value_dp_list: Sequence[DataProperty] + ) -> None: + self._write_row(row, values) + + def __write_separator_row( + self, values: Sequence[str], row_type: RowType = RowType.MIDDLE + ) -> None: + if typepy.is_empty_sequence(values): + return + + cross_point = self.__cross_point_maps[row_type] + left_cross_point = self.__left_cross_point_maps[row_type] + right_cross_point = self.__right_cross_point_maps[row_type] + + left_cross_point = left_cross_point if left_cross_point else cross_point + right_cross_point = right_cross_point if right_cross_point else cross_point + if typepy.is_null_string(self.char_left_side_row): + left_cross_point = "" + if typepy.is_null_string(self.char_right_side_row): + right_cross_point = "" + + self._write_line(left_cross_point + cross_point.join(values) + right_cross_point) + + def _write_opening_row(self) -> None: + if not self.is_write_opening_row: + return + + self.__write_separator_row(self._get_opening_row_items(), row_type=RowType.OPENING) + + def __write_header_row_separator(self) -> None: + if any([not self.is_write_header, not self.is_write_header_separator_row]): + return + + self.__write_separator_row( + self._get_header_row_separator_items(), row_type=RowType.HEADER_SEPARATOR + ) + + def _write_value_row_separator(self) -> None: + """ + Write row separator of the table which matched to the table type + regardless of the value of the + :py:attr:`.is_write_value_separator_row`. + """ + + self.__write_separator_row(self._get_value_row_separator_items()) + + def _write_closing_row(self) -> None: + if not self.is_write_closing_row: + return + + self.__write_separator_row(self._get_closing_row_items(), row_type=RowType.CLOSING) + + def __make_margin_format(self, margin_char: str) -> str: + margin_str = margin_char * self._margin + + return margin_str + "{:s}" + margin_str + + def _preprocess_table_property(self) -> None: + super()._preprocess_table_property() + + self.__update_template() + self._init_cross_point_maps() + + +class IndentationTextTableWriter(TextTableWriter, IndentationInterface): + """A base class for table writer with indentation text formats. + + Args: + indent_level (int): Indentation level. Defaults to ``0``. + + .. py:attribute:: indent_string + + Indentation string for each level. + """ + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.set_indent_level(kwargs.get("indent_level", 0)) + self.indent_string = kwargs.get("indent_string", "") + + def set_indent_level(self, indent_level: int) -> None: + """Set the indentation level. + + Args: + indent_level (int): New indentation level. + """ + + self._indent_level = indent_level + + def inc_indent_level(self) -> None: + """Increment the indentation level.""" + + self._indent_level += 1 + + def dec_indent_level(self) -> None: + """Decrement the indentation level.""" + + self._indent_level -= 1 + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table|. + + Args: + indent (Optional[int]): + Indent level of an output. + Interpretation of indent level value differ format to format. + Some writer classes may ignore this value. + + .. note:: + - |None| values are written as an empty string. + """ + + indent = kwargs.pop("indent", None) + + if indent is not None: + self._logger.logger.debug(f"indent: {indent}") + self.set_indent_level(int(indent)) + + try: + super().write_table(**kwargs) + except EmptyTableDataError: + self._logger.logger.debug("no tabular data found") + return + + def _get_indent_string(self) -> str: + return self.indent_string * self._indent_level + + def _write(self, text: str) -> None: + self._write_raw_string(self._get_indent_string() + text) + + def _write_line(self, text: str = "") -> None: + if typepy.is_not_null_string(text): + self._write_raw_line(self._get_indent_string() + text) + else: + self._write_raw_line("") diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_toml.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_toml.py new file mode 100644 index 0000000000000000000000000000000000000000..b63538e431e6e4436f7e49fc6a98e692f904dda5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_toml.py @@ -0,0 +1,83 @@ +import warnings +from decimal import Decimal +from typing import Any + +import typepy + +from .._common import import_error_msg_template +from ._common import serialize_dp +from ._text_writer import TextTableWriter + + +class TomlTableWriter(TextTableWriter): + """ + A table writer class for + `TOML `__ data format. + + :Example: + :ref:`example-toml-table-writer` + """ + + FORMAT_NAME = "toml" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.is_formatting_float = False + + self._is_require_table_name = True + self._is_require_header = True + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table| with + `TOML `__ format. + + :raises pytablewriter.EmptyTableNameError: + If the |headers| is empty. + :Example: + :ref:`example-toml-table-writer` + """ + + try: + import toml + + class TomlTableEncoder(toml.encoder.TomlEncoder): + def __init__(self, _dict=dict, preserve=False): # type: ignore + super().__init__(_dict=_dict, preserve=preserve) + + self.dump_funcs[str] = str + self.dump_funcs[Decimal] = toml.encoder._dump_float # type: ignore + + except ImportError: + warnings.warn(import_error_msg_template.format("toml")) + raise + + with self._logger: + self._verify_property() + self._preprocess() + + body = [] + for value_dp_list in self._table_value_dp_matrix: + row = {} + + for header, value in zip( + self.headers, + [serialize_dp(value_dp) for value_dp in value_dp_list], + ): + if typepy.is_null_string(value): + continue + + row[header] = value + + body.append(row) + + self.stream.write(toml.dumps({self.table_name: body}, encoder=TomlTableEncoder())) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_tsv.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_tsv.py new file mode 100644 index 0000000000000000000000000000000000000000..9e26679ae5f7ca791c56425bf910cf667a8b28c0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_tsv.py @@ -0,0 +1,23 @@ +from typing import Any + +from ._csv import CsvTableWriter + + +class TsvTableWriter(CsvTableWriter): + """ + A table writer class for tab separated values (TSV) format. + + :Example: + :ref:`example-tsv-table-writer` + """ + + FORMAT_NAME = "tsv" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.column_delimiter = "\t" diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_unicode.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_unicode.py new file mode 100644 index 0000000000000000000000000000000000000000..f080919960fa23f27e054f80cb29ac0116ecdfb8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_unicode.py @@ -0,0 +1,120 @@ +import copy +from typing import Any + +import dataproperty as dp + +from ._text_writer import IndentationTextTableWriter + + +class UnicodeTableWriter(IndentationTextTableWriter): + """ + A table writer class using Unicode characters. + + :Example: + :ref:`example-unicode-table-writer` + """ + + FORMAT_NAME = "unicode" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.column_delimiter = "│" + self.char_left_side_row = "│" + self.char_right_side_row = "│" + + self.char_cross_point = "┼" + self.char_left_cross_point = "├" + self.char_right_cross_point = "┤" + self.char_header_row_cross_point = "┼" + self.char_header_row_left_cross_point = "├" + self.char_header_row_right_cross_point = "┤" + self.char_top_left_cross_point = "┌" + self.char_top_right_cross_point = "┐" + self.char_bottom_left_cross_point = "└" + self.char_bottom_right_cross_point = "┘" + + self.char_opening_row = "─" + self.char_opening_row_cross_point = "┬" + + self.char_header_row_separator = "─" + self.char_value_row_separator = "─" + + self.char_closing_row = "─" + self.char_closing_row_cross_point = "┴" + + self.indent_string = kwargs.get("indent_string", " ") + self.is_write_header_separator_row = True + self.is_write_value_separator_row = True + self.is_write_opening_row = True + self.is_write_closing_row = True + + self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS) + + self._init_cross_point_maps() + + +class BoldUnicodeTableWriter(IndentationTextTableWriter): + """ + A table writer class using bold Unicode characters. + + :Example: + :ref:`example-unicode-table-writer` + """ + + FORMAT_NAME = "bold_unicode" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.table_name = "" + + self.column_delimiter = "┃" + self.char_left_side_row = "┃" + self.char_right_side_row = "┃" + + self.char_cross_point = "╋" + self.char_left_cross_point = "┣" + self.char_right_cross_point = "┫" + self.char_header_row_cross_point = "╋" + self.char_header_row_left_cross_point = "┣" + self.char_header_row_right_cross_point = "┫" + self.char_top_left_cross_point = "┏" + self.char_top_right_cross_point = "┓" + self.char_bottom_left_cross_point = "┗" + self.char_bottom_right_cross_point = "┛" + + self.char_opening_row = "━" + self.char_opening_row_cross_point = "┳" + + self.char_header_row_separator = "━" + self.char_value_row_separator = "━" + + self.char_closing_row = "━" + self.char_closing_row_cross_point = "┻" + + self.indent_string = kwargs.get("indent_string", " ") + self.is_write_header_separator_row = True + self.is_write_value_separator_row = True + self.is_write_opening_row = True + self.is_write_closing_row = True + + self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS) + + self._init_cross_point_maps() diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_yaml.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..6d814505efcdfb4123259f31d8aa3c93cb985e5e --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/_yaml.py @@ -0,0 +1,71 @@ +import copy +import warnings +from typing import Any, Dict, List, Union + +import dataproperty + +from .._common import import_error_msg_template +from ._common import serialize_dp +from ._text_writer import TextTableWriter + + +class YamlTableWriter(TextTableWriter): + """ + A table writer class for `YAML `__ format. + + :Example: + :ref:`example-yaml-table-writer` + """ + + FORMAT_NAME = "yaml" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.is_padding = False + + self._dp_extractor.float_type = float + self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return False + + def write_table(self, **kwargs: Any) -> None: + """ + |write_table| with + YAML format. + + :Example: + :ref:`example-yaml-table-writer` + """ + + try: + import yaml + except ImportError: + warnings.warn(import_error_msg_template.format("yaml")) + raise + + with self._logger: + self._verify_property() + self._preprocess() + + if self.headers: + matrix: List[Union[Dict[str, Any], List[Any]]] = [ + dict(zip(self.headers, [serialize_dp(value_dp) for value_dp in value_dp_list])) + for value_dp_list in self._table_value_dp_matrix + ] + else: + matrix = [ + [serialize_dp(value_dp) for value_dp in value_dp_list] + for value_dp_list in self._table_value_dp_matrix + ] + + if self.table_name: + self._write(yaml.safe_dump({self.table_name: matrix}, default_flow_style=False)) + else: + self._write(yaml.safe_dump(matrix, default_flow_style=False)) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2786cbe335d1a1d8bd3bd7fdaa794ec977332e6f --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__init__.py @@ -0,0 +1,12 @@ +from ._javascript import JavaScriptTableWriter +from ._numpy import NumpyTableWriter +from ._pandas import PandasDataFrameWriter +from ._python import PythonCodeTableWriter + + +__all__ = ( + "JavaScriptTableWriter", + "NumpyTableWriter", + "PandasDataFrameWriter", + "PythonCodeTableWriter", +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b380b92f4c2987b521a0f06b868eb3fb9d9f375e Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_javascript.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_javascript.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38694a87c2151bff52178e8355a5c9ac6ca1daf6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_javascript.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_numpy.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_numpy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e2f257a6f26d3f23d063feaf7165695a5b553b8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_numpy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_pandas.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_pandas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4cadd17148c5ac09c7b8350b2374abf267f92be Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_pandas.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_python.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_python.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4089027aa777251927e8a5cd98462e2a47ad2c41 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_python.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_sourcecode.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_sourcecode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ba288808e6e19099e0aedec6c5baea676334f6f Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/__pycache__/_sourcecode.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_javascript.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_javascript.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc90ccdd2977bcfa45d60cbf5a403d0d42536c7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_javascript.py @@ -0,0 +1,137 @@ +import io +from datetime import datetime +from typing import Any, List + +from dataproperty import ColumnDataProperty, DataProperty, DefaultValue +from typepy import StrictLevel, Typecode + +from ...._converter import strip_quote +from ...._function import quote_datetime_formatter +from ....sanitizer import sanitize_js_var_name +from .._common import bool_to_str +from ._sourcecode import SourceCodeTableWriter + + +def js_datetime_formatter(value: datetime) -> str: + try: + return f'new Date("{value.strftime(DefaultValue.DATETIME_FORMAT):s}")' + except ValueError: + # the datetime strftime() methods require year >= 1900 + return f'new Date("{value}")' + + +class JavaScriptTableWriter(SourceCodeTableWriter): + """ + A table writer for class JavaScript format. + + :Example: + :ref:`example-js-table-writer` + + .. py:attribute:: variable_declaration + :type: str + :value: "const" + + JavaScript variable declarations type. + The value must be either ``"var"``, ``"let"`` or ``"const"``. + + .. py:method:: write_table + + |write_table| with JavaScript format. + The tabular data are written as a nested list variable definition. + + :raises pytablewriter.EmptyTableNameError: + If the |table_name| is empty. + :Example: + :ref:`example-js-table-writer` + + .. note:: + Specific values in the tabular data are converted when writing: + + - |None|: written as ``null`` + - |inf|: written as ``Infinity`` + - |nan|: written as ``NaN`` + - |datetime| instances determined by |is_datetime_instance_formatting| attribute: + - |True|: written as `dateutil.parser `__ + - |False|: written as |str| + + .. seealso:: + :ref:`example-type-hint-js` + """ + + FORMAT_NAME = "javascript" + __VALID_VAR_DECLARATION = ("var", "let", "const") + __NONE_VALUE_DP = DataProperty("null") + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + @property + def variable_declaration(self) -> str: + return self.__variable_declaration + + @variable_declaration.setter + def variable_declaration(self, value: str) -> None: + value = value.strip().casefold() + if value not in self.__VALID_VAR_DECLARATION: + raise ValueError("declaration must be either var, let or const") + + self.__variable_declaration = value + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.variable_declaration = "const" + self._dp_extractor.type_value_map = { + # Typecode.NONE: "null", + Typecode.INFINITY: "Infinity", + Typecode.NAN: "NaN", + } + self._dp_extractor.update_strict_level_map({Typecode.BOOL: StrictLevel.MAX}) + self.register_trans_func(bool_to_str) + + def get_variable_name(self, value: str) -> str: + return sanitize_js_var_name(value, "_").casefold() + + def _write_table(self, **kwargs: Any) -> None: + if self.is_datetime_instance_formatting: + self._dp_extractor.datetime_formatter = js_datetime_formatter + else: + self._dp_extractor.datetime_formatter = quote_datetime_formatter + + org_stream = self.stream + self.stream = io.StringIO() + + self.inc_indent_level() + super()._write_table(**kwargs) + self.dec_indent_level() + js_matrix_var_def_text = self.stream.getvalue().rstrip("\n") + js_matrix_var_def_text = strip_quote(js_matrix_var_def_text, "true") + js_matrix_var_def_text = strip_quote(js_matrix_var_def_text, "false") + if self.is_write_closing_row: + js_matrix_var_def_line_list = js_matrix_var_def_text.splitlines() + js_matrix_var_def_line_list[-2] = js_matrix_var_def_line_list[-2].rstrip(",") + js_matrix_var_def_text = "\n".join(js_matrix_var_def_line_list) + + self.stream.close() + self.stream = org_stream + + self.dec_indent_level() + self._write_line(js_matrix_var_def_text) + self.inc_indent_level() + + def _get_opening_row_items(self) -> List[str]: + return [f"{self.variable_declaration:s} {self.variable_name:s} = ["] + + def _get_closing_row_items(self) -> List[str]: + return ["];"] + + def _to_row_item(self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str: + if value_dp.data is None: + value_dp = self.__NONE_VALUE_DP + + return super()._to_row_item(row_idx, col_dp, value_dp) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_numpy.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..4a4741bcabf1397950a8c18010834f576a096667 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_numpy.py @@ -0,0 +1,66 @@ +from typing import Any, List + +import typepy + +from ._python import PythonCodeTableWriter + + +class NumpyTableWriter(PythonCodeTableWriter): + """ + A table writer class for ``NumPy`` source code format. + + :Example: + :ref:`example-numpy-table-writer` + + .. py:method:: write_table + + |write_table| with ``NumPy`` format. + The tabular data are written as a variable definition of + ``numpy.array``. + + :raises pytablewriter.EmptyTableNameError: + If the |table_name| is empty. + :Example: + :ref:`example-numpy-table-writer` + + .. note:: + Specific values in the tabular data are converted when writing: + + - |None|: written as ``None`` + - |inf|: written as ``numpy.inf`` + - |nan|: written as ``numpy.nan`` + - |datetime| instances determined by |is_datetime_instance_formatting| attribute: + - |True|: written as `dateutil.parser `__ + - |False|: written as |str| + + .. seealso:: + :ref:`example-type-hint-python` + """ + + FORMAT_NAME = "numpy" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.import_numpy_as = "np" + self._dp_extractor.type_value_map[typepy.Typecode.INFINITY] = "{:s}.inf".format( + self.import_numpy_as + ) + self._dp_extractor.type_value_map[typepy.Typecode.NAN] = "{:s}.nan".format( + self.import_numpy_as + ) + + def _get_opening_row_items(self) -> List[str]: + array_def = f"{self.import_numpy_as:s}.array([" + + if typepy.is_not_null_string(self.table_name): + return [f"{self.variable_name} = {array_def}"] + + return [array_def] + + def _get_closing_row_items(self) -> List[str]: + return ["])"] diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_pandas.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..bfddee7374a835c7f3a083ae47b4354994b41c79 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_pandas.py @@ -0,0 +1,86 @@ +from typing import Any, List + +import typepy +from mbstrdecoder import MultiByteStrDecoder + +from ....error import EmptyTableNameError +from ._numpy import NumpyTableWriter + + +class PandasDataFrameWriter(NumpyTableWriter): + """ + A writer class for Pandas DataFrame format. + + :Example: + :ref:`example-pandas-dataframe-writer` + + .. py:attribute:: import_pandas_as + :type: str + :value: "pd" + + Specify ``pandas`` module import name of an output source code. + + .. py:attribute:: import_numpy_as + :type: str + :value: "np" + + Specify ``numpy`` module import name of an output source code. + + .. py:method:: write_table + + |write_table| with Pandas DataFrame format. + The tabular data are written as a ``pandas.DataFrame`` class + instance definition. + + :raises pytablewriter.EmptyTableNameError: + If the |table_name| is empty. + + :Example: + :ref:`example-pandas-dataframe-writer` + + .. note:: + Specific values in the tabular data are converted when writing: + + - |None|: written as ``None`` + - |inf|: written as ``numpy.inf`` + - |nan|: written as ``numpy.nan`` + - |datetime| instances determined by |is_datetime_instance_formatting| attribute: + - |True|: written as `dateutil.parser `__ + - |False|: written as |str| + + .. seealso:: + :ref:`example-type-hint-python` + """ + + FORMAT_NAME = "pandas" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.import_pandas_as = "pd" + self.is_write_header = False + + def _get_opening_row_items(self) -> List[str]: + return [f"{self.variable_name} = {self.import_pandas_as}.DataFrame(["] + + def _get_closing_row_items(self) -> List[str]: + if typepy.is_not_empty_sequence(self.headers): + return [ + "], columns=[{}])".format( + ", ".join( + f'"{MultiByteStrDecoder(header).unicode_str}"' for header in self.headers + ) + ) + ] + + return ["])"] + + def _verify_property(self) -> None: + super()._verify_property() + + if typepy.is_null_string(self.table_name): + raise EmptyTableNameError("table_name must be a string of one or more characters") diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_python.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_python.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1e25ee832da123e2d89004e87eda6658fbc4f0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_python.py @@ -0,0 +1,81 @@ +from typing import Any, List + +import typepy + +from ...._function import dateutil_datetime_formatter, quote_datetime_formatter +from ....sanitizer import sanitize_python_var_name +from ._sourcecode import SourceCodeTableWriter + + +class PythonCodeTableWriter(SourceCodeTableWriter): + """ + A table writer class for Python source code format. + + :Example: + :ref:`example-python-code-table-writer` + + .. py:method:: write_table + + |write_table| with Python format. + The tabular data are written as a nested list variable definition + for Python format. + + :raises pytablewriter.EmptyTableNameError: + If the |table_name| is empty. + :Example: + :ref:`example-python-code-table-writer` + + .. note:: + Specific values in the tabular data are converted when writing: + + - |None|: written as ``None`` + - |inf|: written as ``float("inf")`` + - |nan|: written as ``float("nan")`` + - |datetime| instances determined by |is_datetime_instance_formatting| attribute: + - |True|: written as `dateutil.parser `__ + - |False|: written as |str| + + .. seealso:: + :ref:`example-type-hint-python` + """ + + FORMAT_NAME = "python" + + @property + def format_name(self) -> str: + return self.FORMAT_NAME + + @property + def support_split_write(self) -> bool: + return True + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self._dp_extractor.type_value_map = { + typepy.Typecode.NONE: None, + typepy.Typecode.INFINITY: 'float("inf")', + typepy.Typecode.NAN: 'float("nan")', + } + + def get_variable_name(self, value: str) -> str: + return sanitize_python_var_name(self.table_name, "_").lower() + + def _write_table(self, **kwargs: Any) -> None: + if self.is_datetime_instance_formatting: + self._dp_extractor.datetime_formatter = dateutil_datetime_formatter + else: + self._dp_extractor.datetime_formatter = quote_datetime_formatter + + self.inc_indent_level() + super()._write_table(**kwargs) + self.dec_indent_level() + + def _get_opening_row_items(self) -> List[str]: + if typepy.is_not_null_string(self.table_name): + return [self.variable_name + " = ["] + + return ["["] + + def _get_closing_row_items(self) -> List[str]: + return ["]"] diff --git a/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_sourcecode.py b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_sourcecode.py new file mode 100644 index 0000000000000000000000000000000000000000..721a656a2acf6c129ddba80084edf43d2e7ec140 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/writer/text/sourcecode/_sourcecode.py @@ -0,0 +1,79 @@ +import abc +from typing import Any, List + +import typepy + +from .._text_writer import IndentationTextTableWriter + + +class SourceCodeTableWriter(IndentationTextTableWriter): + """ + Base class of table writer with a source code (variable definition) format. + + .. py:attribute:: is_datetime_instance_formatting + :type: bool + + Write |datetime| values in the table as definition of |datetime| class + instances coincide with specific language if this value is |True|. + Write as |str| if this value is |False|. + """ + + @abc.abstractmethod + def get_variable_name(self, value: str) -> str: # pragma: no cover + pass + + @property + def variable_name(self) -> str: + """ + str: Return a valid variable name that converted from the |table_name|. + """ + + return self.get_variable_name(self.table_name) + + @property + def margin(self) -> int: + return self._margin + + @margin.setter + def margin(self, value: int) -> None: + # margin setting must be ignored + return + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + self.indent_string = kwargs.get("indent_string", " ") + self.column_delimiter = ", " + self._margin = 0 + + self.char_left_side_row = "[" + self.char_right_side_row = "]," + self.char_cross_point = "" + self.char_opening_row_cross_point = "" + self.char_closing_row_cross_point = "" + + self.is_padding = False + self.is_write_header_separator_row = False + self.is_write_opening_row = True + self.is_write_closing_row = True + + self.is_formatting_float = False + self.is_datetime_instance_formatting = True + + self._quoting_flags[typepy.Typecode.DATETIME] = False + self._is_require_table_name = True + + self._init_cross_point_maps() + + def _get_value_row_separator_items(self) -> List[str]: + return [] + + def _write_opening_row(self) -> None: + self.dec_indent_level() + super()._write_opening_row() + self.inc_indent_level() + + def _write_closing_row(self) -> None: + self.dec_indent_level() + super()._write_closing_row() + self.inc_indent_level()