applied-ai-018 commited on
Commit
e20593c
·
verified ·
1 Parent(s): 213ec7c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
  2. ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
  3. ckpts/universal/global_step80/zero/19.attention.dense.weight/fp32.pt +3 -0
  4. venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/__init__.cpython-310.pyc +0 -0
  5. venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_logger.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_null_logger.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/pytablewriter/writer/__init__.py +74 -0
  8. venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/__init__.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_common.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_elasticsearch.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_interface.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_msgfy.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_null.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_table_writer.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/pytablewriter/writer/_common.py +12 -0
  16. venv/lib/python3.10/site-packages/pytablewriter/writer/_elasticsearch.py +204 -0
  17. venv/lib/python3.10/site-packages/pytablewriter/writer/_interface.py +84 -0
  18. venv/lib/python3.10/site-packages/pytablewriter/writer/_msgfy.py +56 -0
  19. venv/lib/python3.10/site-packages/pytablewriter/writer/_null.py +61 -0
  20. venv/lib/python3.10/site-packages/pytablewriter/writer/_table_writer.py +1245 -0
  21. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__init__.py +11 -0
  22. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/__init__.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel_workbook.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_interface.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_pandas.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_sqlite.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel.py +501 -0
  29. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel_workbook.py +139 -0
  30. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_interface.py +58 -0
  31. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_pandas.py +99 -0
  32. venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_sqlite.py +104 -0
  33. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__init__.py +44 -0
  34. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/__init__.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_common.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_css.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_csv.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_interface.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_latex.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_ltsv.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_markdown.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_mediawiki.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_spacealigned.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_text_writer.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_tsv.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_yaml.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/pytablewriter/writer/text/_asciidoc.py +146 -0
  48. venv/lib/python3.10/site-packages/pytablewriter/writer/text/_borderless.py +41 -0
  49. venv/lib/python3.10/site-packages/pytablewriter/writer/text/_common.py +26 -0
  50. venv/lib/python3.10/site-packages/pytablewriter/writer/text/_css.py +157 -0
ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c5b62e6ac763e6b168c91d08d0a8eebe05d5a993d9d871af59777d5793f0d716
3
+ size 33555627
ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2349d88812163b3b6d673cc809aa8dc9b6571f3c2dfc8e4b6625835e2cc2263d
3
+ size 33555533
ckpts/universal/global_step80/zero/19.attention.dense.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf760ef522c939521fe0d8a7dfe4d7bb297517e0c98c217476377b007be61a7a
3
+ size 16778317
venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (286 Bytes). View file
 
venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_logger.cpython-310.pyc ADDED
Binary file (4.09 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/_logger/__pycache__/_null_logger.cpython-310.pyc ADDED
Binary file (1.92 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/__init__.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._elasticsearch import ElasticsearchWriter
2
+ from ._null import NullTableWriter
3
+ from ._table_writer import AbstractTableWriter
4
+ from .binary import (
5
+ ExcelXlsTableWriter,
6
+ ExcelXlsxTableWriter,
7
+ PandasDataFramePickleWriter,
8
+ SqliteTableWriter,
9
+ )
10
+ from .text import (
11
+ AsciiDocTableWriter,
12
+ BoldUnicodeTableWriter,
13
+ BorderlessTableWriter,
14
+ CssTableWriter,
15
+ CsvTableWriter,
16
+ HtmlTableWriter,
17
+ JsonLinesTableWriter,
18
+ JsonTableWriter,
19
+ LatexMatrixWriter,
20
+ LatexTableWriter,
21
+ LtsvTableWriter,
22
+ MarkdownTableWriter,
23
+ MediaWikiTableWriter,
24
+ RstCsvTableWriter,
25
+ RstGridTableWriter,
26
+ RstSimpleTableWriter,
27
+ SpaceAlignedTableWriter,
28
+ TomlTableWriter,
29
+ TsvTableWriter,
30
+ UnicodeTableWriter,
31
+ YamlTableWriter,
32
+ )
33
+ from .text.sourcecode import (
34
+ JavaScriptTableWriter,
35
+ NumpyTableWriter,
36
+ PandasDataFrameWriter,
37
+ PythonCodeTableWriter,
38
+ )
39
+
40
+
41
+ __all__ = (
42
+ "AbstractTableWriter",
43
+ "AsciiDocTableWriter",
44
+ "BoldUnicodeTableWriter",
45
+ "BorderlessTableWriter",
46
+ "CssTableWriter",
47
+ "CsvTableWriter",
48
+ "ElasticsearchWriter",
49
+ "ExcelXlsTableWriter",
50
+ "ExcelXlsxTableWriter",
51
+ "HtmlTableWriter",
52
+ "JavaScriptTableWriter",
53
+ "JsonLinesTableWriter",
54
+ "JsonTableWriter",
55
+ "LatexMatrixWriter",
56
+ "LatexTableWriter",
57
+ "LtsvTableWriter",
58
+ "MarkdownTableWriter",
59
+ "MediaWikiTableWriter",
60
+ "NullTableWriter",
61
+ "NumpyTableWriter",
62
+ "PandasDataFramePickleWriter",
63
+ "PandasDataFrameWriter",
64
+ "PythonCodeTableWriter",
65
+ "RstCsvTableWriter",
66
+ "RstGridTableWriter",
67
+ "RstSimpleTableWriter",
68
+ "SpaceAlignedTableWriter",
69
+ "SqliteTableWriter",
70
+ "TomlTableWriter",
71
+ "TsvTableWriter",
72
+ "UnicodeTableWriter",
73
+ "YamlTableWriter",
74
+ )
venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_common.cpython-310.pyc ADDED
Binary file (414 Bytes). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_elasticsearch.cpython-310.pyc ADDED
Binary file (6.63 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_interface.cpython-310.pyc ADDED
Binary file (3.56 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_msgfy.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_null.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_table_writer.cpython-310.pyc ADDED
Binary file (37.5 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/_common.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from textwrap import dedent
2
+
3
+
4
+ HEADER_ROW = -1
5
+
6
+
7
+ import_error_msg_template = dedent(
8
+ """\
9
+ dependency packages for {0} not found.
10
+ you can install the dependencies with 'pip install pytablewriter[{0}]'
11
+ """
12
+ )
venv/lib/python3.10/site-packages/pytablewriter/writer/_elasticsearch.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. codeauthor:: Tsuyoshi Hombashi <[email protected]>
3
+ """
4
+
5
+
6
+ import copy
7
+ from typing import Any, Dict, Generator
8
+
9
+ import dataproperty
10
+ from dataproperty import ColumnDataProperty
11
+ from typepy import Typecode
12
+
13
+ from ..error import EmptyValueError
14
+ from ._msgfy import to_error_message
15
+ from ._table_writer import AbstractTableWriter
16
+
17
+
18
+ DataType = Dict[str, str]
19
+ Properties = Dict[str, DataType]
20
+
21
+
22
+ def _get_es_datatype(column_dp: ColumnDataProperty) -> DataType:
23
+ if column_dp.typecode in (
24
+ Typecode.NONE,
25
+ Typecode.NULL_STRING,
26
+ Typecode.INFINITY,
27
+ Typecode.NAN,
28
+ ):
29
+ return {"type": "keyword"}
30
+
31
+ if column_dp.typecode == Typecode.STRING:
32
+ return {"type": "text"}
33
+
34
+ if column_dp.typecode == Typecode.DATETIME:
35
+ return {"type": "date", "format": "date_optional_time"}
36
+
37
+ if column_dp.typecode == Typecode.REAL_NUMBER:
38
+ return {"type": "double"}
39
+
40
+ if column_dp.typecode == Typecode.BOOL:
41
+ return {"type": "boolean"}
42
+
43
+ if column_dp.typecode == Typecode.IP_ADDRESS:
44
+ return {"type": "ip"}
45
+
46
+ if column_dp.typecode == Typecode.INTEGER:
47
+ assert column_dp.bit_length is not None
48
+
49
+ if column_dp.bit_length <= 8:
50
+ return {"type": "byte"}
51
+ elif column_dp.bit_length <= 16:
52
+ return {"type": "short"}
53
+ elif column_dp.bit_length <= 32:
54
+ return {"type": "integer"}
55
+ elif column_dp.bit_length <= 64:
56
+ return {"type": "long"}
57
+
58
+ raise ValueError(
59
+ f"too large integer bits: expected<=64bits, actual={column_dp.bit_length:d}bits"
60
+ )
61
+
62
+ raise ValueError(f"unknown typecode: {column_dp.typecode}")
63
+
64
+
65
+ class ElasticsearchWriter(AbstractTableWriter):
66
+ """
67
+ A table writer class for Elasticsearch.
68
+
69
+ :Dependency Packages:
70
+ - `elasticsearch-py <https://github.com/elastic/elasticsearch-py>`__
71
+
72
+ .. py:attribute:: index_name
73
+ :type: str
74
+
75
+ Alias attribute for |table_name|.
76
+
77
+ .. py:attribute:: document_type
78
+ :type: str
79
+ :value: "table"
80
+
81
+ Specify document type for indices.
82
+
83
+ .. py:method:: write_table()
84
+
85
+ Create an index and put documents for each row to Elasticsearch.
86
+
87
+ You need to pass an
88
+ `elasticsearch.Elasticsearch <https://elasticsearch-py.rtfd.io/en/master/api.html#elasticsearch>`__
89
+ instance to |stream| before calling this method.
90
+ |table_name|/:py:attr:`~pytablewriter.ElasticsearchWriter.index_name`
91
+ used as the creating index name,
92
+ invalid characters in the name are replaced with underscores (``'_'``).
93
+ Document data types for documents are automatically detected from the data.
94
+
95
+ :raises ValueError:
96
+ If the |stream| has not elasticsearch.Elasticsearch instance.
97
+ :Example:
98
+ :ref:`example-elasticsearch-table-writer`
99
+ """
100
+
101
+ FORMAT_NAME = "elasticsearch"
102
+
103
+ @property
104
+ def format_name(self) -> str:
105
+ return self.FORMAT_NAME
106
+
107
+ @property
108
+ def support_split_write(self) -> bool:
109
+ return True
110
+
111
+ @property
112
+ def table_name(self) -> str:
113
+ return super().table_name
114
+
115
+ @table_name.setter
116
+ def table_name(self, value: str) -> None:
117
+ from pathvalidate import ErrorReason, ValidationError
118
+
119
+ from ..sanitizer import ElasticsearchIndexNameSanitizer
120
+
121
+ try:
122
+ self._table_name = ElasticsearchIndexNameSanitizer(value).sanitize(replacement_text="_")
123
+ except ValidationError as e:
124
+ if e.reason is ErrorReason.NULL_NAME:
125
+ self._table_name = ""
126
+ else:
127
+ raise
128
+
129
+ @property
130
+ def index_name(self) -> str:
131
+ return self.table_name
132
+
133
+ @index_name.setter
134
+ def index_name(self, value: str) -> None:
135
+ self.table_name = value
136
+
137
+ def __init__(self, **kwargs: Any) -> None:
138
+ super().__init__(**kwargs)
139
+
140
+ self.stream = None
141
+ self.is_padding = False
142
+ self.is_formatting_float = False
143
+ self._is_require_table_name = True
144
+ self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
145
+ self._dp_extractor.type_value_map = copy.deepcopy(dataproperty.DefaultValue.TYPE_VALUE_MAP)
146
+
147
+ self.document_type = "table"
148
+
149
+ def write_null_line(self) -> None:
150
+ pass
151
+
152
+ def _get_mappings(self) -> Dict[str, Dict[str, Dict[str, Properties]]]:
153
+ properties: Properties = {}
154
+
155
+ for header, column_dp in zip(self.headers, self._column_dp_list):
156
+ properties[header] = _get_es_datatype(column_dp)
157
+
158
+ return {"mappings": {self.document_type: {"properties": properties}}}
159
+
160
+ def _get_body(self) -> Generator:
161
+ str_datatype = (Typecode.DATETIME, Typecode.IP_ADDRESS, Typecode.INFINITY, Typecode.NAN)
162
+
163
+ for value_dp_list in self._table_value_dp_matrix:
164
+ values = [
165
+ value_dp.data if value_dp.typecode not in str_datatype else value_dp.to_str()
166
+ for value_dp in value_dp_list
167
+ ]
168
+
169
+ yield dict(zip(self.headers, values))
170
+
171
+ def _write_table(self, **kwargs: Any) -> None:
172
+ import elasticsearch as es
173
+
174
+ if not isinstance(self.stream, es.Elasticsearch):
175
+ raise ValueError("stream must be an elasticsearch.Elasticsearch instance")
176
+
177
+ try:
178
+ self._verify_value_matrix()
179
+ except EmptyValueError:
180
+ self._logger.logger.debug("no tabular data found")
181
+ return
182
+
183
+ self._preprocess()
184
+
185
+ mappings = self._get_mappings()
186
+
187
+ try:
188
+ result = self.stream.indices.create(index=self.index_name, body=mappings)
189
+ self._logger.logger.debug(result)
190
+ except es.TransportError as e:
191
+ if e.error == "index_already_exists_exception":
192
+ # ignore already existing index
193
+ self._logger.logger.debug(to_error_message(e))
194
+ else:
195
+ raise
196
+
197
+ for body in self._get_body():
198
+ try:
199
+ self.stream.index(index=self.index_name, body=body, doc_type=self.document_type)
200
+ except es.exceptions.RequestError as e:
201
+ self._logger.logger.error(f"{to_error_message(e)}, body={body}")
202
+
203
+ def _write_value_row_separator(self) -> None:
204
+ pass
venv/lib/python3.10/site-packages/pytablewriter/writer/_interface.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. codeauthor:: Tsuyoshi Hombashi <[email protected]>
3
+ """
4
+
5
+ import abc
6
+ from typing import IO, Any, Union
7
+
8
+
9
+ class TableWriterInterface(metaclass=abc.ABCMeta):
10
+ """
11
+ Interface class for writing a table.
12
+ """
13
+
14
+ @abc.abstractproperty
15
+ def format_name(self) -> str: # pragma: no cover
16
+ """Format name for the writer.
17
+
18
+ Returns:
19
+ |str|
20
+ """
21
+
22
+ @abc.abstractproperty
23
+ def support_split_write(self) -> bool: # pragma: no cover
24
+ """Indicates whether the writer class supports iterative table writing (``write_table_iter``) method.
25
+
26
+ Returns:
27
+ bool: |True| if the writer supported iterative table writing.
28
+ """
29
+
30
+ @abc.abstractmethod
31
+ def write_table(self, **kwargs: Any) -> None: # pragma: no cover
32
+ """
33
+ |write_table|.
34
+ """
35
+
36
+ def dump(
37
+ self, output: Union[str, IO], close_after_write: bool, **kwargs: Any
38
+ ) -> None: # pragma: no cover
39
+ raise NotImplementedError(f"{self.format_name} writer did not support dump method")
40
+
41
+ def dumps(self) -> str: # pragma: no cover
42
+ raise NotImplementedError(f"{self.format_name} writer did not support dumps method")
43
+
44
+ def write_table_iter(self, **kwargs: Any) -> None: # pragma: no cover
45
+ """
46
+ Write a table with iteration.
47
+ "Iteration" means that divide the table writing into multiple writes.
48
+ This method is helpful, especially for extensive data.
49
+ The following are the premises to execute this method:
50
+
51
+ - set iterator to the |value_matrix|
52
+ - set the number of iterations to the |iteration_length| attribute
53
+
54
+ Call back function (Optional):
55
+ A callback function is called when each iteration of writing a table is completed.
56
+ You can set a callback function via the |write_callback| attribute.
57
+
58
+ Raises:
59
+ pytablewriter.NotSupportedError: If the writer class does not support this method.
60
+
61
+ .. note::
62
+ The following classes do not support this method:
63
+
64
+ - |HtmlTableWriter|
65
+ - |RstGridTableWriter|
66
+ - |RstSimpleTableWriter|
67
+
68
+ ``support_split_write`` attribute return |True| if the class
69
+ is supporting this method.
70
+ """
71
+
72
+ self._write_table_iter(**kwargs)
73
+
74
+ @abc.abstractmethod
75
+ def _write_table_iter(self, **kwargs: Any) -> None: # pragma: no cover
76
+ pass
77
+
78
+ @abc.abstractmethod
79
+ def close(self) -> None: # pragma: no cover
80
+ pass
81
+
82
+ @abc.abstractmethod
83
+ def _write_value_row_separator(self) -> None: # pragma: no cover
84
+ pass
venv/lib/python3.10/site-packages/pytablewriter/writer/_msgfy.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Import from https://github.com/thombashi/msgfy
3
+ """
4
+
5
+ import inspect
6
+ import os.path
7
+ from types import FrameType
8
+ from typing import Optional
9
+
10
+
11
+ DEFAULT_ERROR_MESSAGE_FORMAT = "{exception}: {error_msg}"
12
+ DEFAULT_DEBUG_MESSAGE_FORMAT = "{exception} {file_name}({line_no}) {func_name}: {error_msg}"
13
+
14
+ error_message_format = DEFAULT_ERROR_MESSAGE_FORMAT
15
+ debug_message_format = DEFAULT_DEBUG_MESSAGE_FORMAT
16
+
17
+
18
+ def _to_message(exception_obj: Exception, format_str: str, frame: Optional[FrameType]) -> str:
19
+ if not isinstance(exception_obj, Exception):
20
+ raise ValueError("exception_obj must be an instance of a subclass of the Exception class")
21
+
22
+ if frame is None:
23
+ return str(exception_obj)
24
+
25
+ try:
26
+ return (
27
+ format_str.replace("{exception}", exception_obj.__class__.__name__)
28
+ .replace("{file_name}", os.path.basename(frame.f_code.co_filename))
29
+ .replace("{line_no}", str(frame.f_lineno))
30
+ .replace("{func_name}", frame.f_code.co_name)
31
+ .replace("{error_msg}", str(exception_obj))
32
+ )
33
+ except AttributeError:
34
+ raise ValueError("format_str must be a string")
35
+
36
+
37
+ def to_error_message(exception_obj: Exception, format_str: Optional[str] = None) -> str:
38
+ if not format_str:
39
+ format_str = error_message_format
40
+
41
+ frame = inspect.currentframe()
42
+ if frame is None:
43
+ return str(exception_obj)
44
+
45
+ return _to_message(exception_obj, format_str, frame.f_back)
46
+
47
+
48
+ def to_debug_message(exception_obj: Exception, format_str: Optional[str] = None) -> str:
49
+ if not format_str:
50
+ format_str = debug_message_format
51
+
52
+ frame = inspect.currentframe()
53
+ if frame is None:
54
+ return str(exception_obj)
55
+
56
+ return _to_message(exception_obj, format_str, frame.f_back)
venv/lib/python3.10/site-packages/pytablewriter/writer/_null.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. codeauthor:: Tsuyoshi Hombashi <[email protected]>
3
+ """
4
+
5
+ from typing import IO, Any, Union
6
+
7
+ from ._interface import TableWriterInterface
8
+ from .text._interface import IndentationInterface, TextWriterInterface
9
+
10
+
11
+ class NullTableWriter(IndentationInterface, TextWriterInterface, TableWriterInterface):
12
+ FORMAT_NAME = "null"
13
+
14
+ def __init__(self, **kwargs: Any) -> None:
15
+ self.table_name = kwargs.get("table_name", "")
16
+ self.value_matrix = kwargs.get("value_matrix", [])
17
+ self.is_formatting_float = kwargs.get("is_formatting_float", True)
18
+ self.headers = kwargs.get("headers", [])
19
+ self.type_hints = kwargs.get("type_hints", [])
20
+ self.max_workers = kwargs.get("max_workers", 1)
21
+
22
+ def __repr__(self) -> str:
23
+ return self.dumps()
24
+
25
+ @property
26
+ def format_name(self) -> str:
27
+ return self.FORMAT_NAME
28
+
29
+ @property
30
+ def support_split_write(self) -> bool:
31
+ return True
32
+
33
+ def set_indent_level(self, indent_level: int) -> None:
34
+ pass
35
+
36
+ def inc_indent_level(self) -> None:
37
+ pass
38
+
39
+ def dec_indent_level(self) -> None:
40
+ pass
41
+
42
+ def write_null_line(self) -> None:
43
+ pass
44
+
45
+ def write_table(self, **kwargs: Any) -> None:
46
+ pass
47
+
48
+ def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None:
49
+ pass
50
+
51
+ def dumps(self) -> str:
52
+ return ""
53
+
54
+ def _write_table_iter(self, **kwargs: Any) -> None:
55
+ pass
56
+
57
+ def close(self) -> None:
58
+ pass
59
+
60
+ def _write_value_row_separator(self) -> None:
61
+ pass
venv/lib/python3.10/site-packages/pytablewriter/writer/_table_writer.py ADDED
@@ -0,0 +1,1245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. codeauthor:: Tsuyoshi Hombashi <[email protected]>
3
+ """
4
+
5
+ import abc
6
+ import copy
7
+ import math
8
+ import warnings
9
+ from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence, Union, cast
10
+
11
+ import typepy
12
+ from dataproperty import (
13
+ Align,
14
+ ColumnDataProperty,
15
+ DataProperty,
16
+ DataPropertyExtractor,
17
+ Format,
18
+ MatrixFormatting,
19
+ Preprocessor,
20
+ )
21
+ from dataproperty.typing import TransFunc
22
+ from tabledata import TableData, convert_idx_to_alphabet, to_value_matrix
23
+ from typepy import Typecode, extract_typepy_from_dtype
24
+
25
+ from .._logger import WriterLogger
26
+ from ..error import EmptyTableDataError, EmptyTableNameError, EmptyValueError, NotSupportedError
27
+ from ..style import (
28
+ Cell,
29
+ CheckStyleFilterKeywordArgsFunc,
30
+ ColSeparatorStyleFilterFunc,
31
+ Style,
32
+ StyleFilterFunc,
33
+ StylerInterface,
34
+ ThousandSeparator,
35
+ fetch_theme,
36
+ )
37
+ from ..typehint import Integer, TypeHint
38
+ from ._common import HEADER_ROW
39
+ from ._interface import TableWriterInterface
40
+ from ._msgfy import to_error_message
41
+
42
+
43
+ if TYPE_CHECKING:
44
+ import pandas
45
+ import tablib
46
+
47
+ from .._table_format import TableFormat
48
+
49
+ _ts_to_flag: Dict[ThousandSeparator, int] = {
50
+ ThousandSeparator.NONE: Format.NONE,
51
+ ThousandSeparator.COMMA: Format.THOUSAND_SEPARATOR,
52
+ ThousandSeparator.SPACE: Format.THOUSAND_SEPARATOR,
53
+ ThousandSeparator.UNDERSCORE: Format.THOUSAND_SEPARATOR,
54
+ }
55
+
56
+
57
+ def header_style_filter(cell: Cell, **kwargs: Any) -> Optional[Style]:
58
+ if cell.is_header_row():
59
+ return Style(align=Align.CENTER)
60
+
61
+ return None
62
+
63
+
64
+ DEFAULT_STYLE_FILTERS: List[StyleFilterFunc] = [header_style_filter]
65
+
66
+
67
+ class AbstractTableWriter(TableWriterInterface, metaclass=abc.ABCMeta):
68
+ """
69
+ An abstract base class of table writer classes.
70
+
71
+ Args:
72
+ max_precision (int): Maximum decimal places for real number values.
73
+
74
+ dequote (bool): If |True|, dequote values in :py:attr:`~.value_matrix`.
75
+
76
+ .. py:attribute:: stream
77
+
78
+ Stream to write tables.
79
+ You can use arbitrary streams which support ``write``methods
80
+ such as ``sys.stdout``, file stream, ``StringIO``, and so forth.
81
+ Defaults to ``sys.stdout``.
82
+
83
+ :Example:
84
+ :ref:`example-configure-stream`
85
+
86
+ .. py:attribute:: is_write_header
87
+ :type: bool
88
+
89
+ Write headers of a table if the value is |True|.
90
+
91
+ .. py:attribute:: is_padding
92
+ :type: bool
93
+
94
+ Padding for each item in the table if the value is |True|.
95
+
96
+ .. py:attribute:: iteration_length
97
+ :type: int
98
+
99
+ The number of iterations to write a table.
100
+ This value is used in :py:meth:`.write_table_iter` method.
101
+ (defaults to ``-1``, which means the number of iterations is indefinite)
102
+
103
+ .. py:attribute:: style_filter_kwargs
104
+ :type: Dict[str, Any]
105
+
106
+ Extra keyword arguments for style filter functions.
107
+ These arguments will pass to filter functions added by
108
+ :py:meth:`.add_style_filter` or :py:meth:`.add_col_separator_style_filter`
109
+
110
+ .. py:attribute:: colorize_terminal
111
+ :type: bool
112
+ :value: True
113
+
114
+ [Only available for text format writers] [experimental]
115
+ If |True|, colorize text outputs with |Style|.
116
+
117
+ .. py:attribute:: enable_ansi_escape
118
+ :type: bool
119
+ :value: True
120
+
121
+ [Only available for text format writers]
122
+ If |True|, applies ANSI escape sequences to the terminal's text outputs with |Style|.
123
+
124
+ .. py:attribute:: write_callback
125
+
126
+ The value expected to a function.
127
+ The function is called when each of the iterations of writing a table
128
+ completed. (defaults to |None|)
129
+ For example, a callback function definition is as follows:
130
+
131
+ .. code:: python
132
+
133
+ def callback_example(iter_count: int, iter_length: int) -> None:
134
+ print("{:d}/{:d}".format(iter_count, iter_length))
135
+
136
+ Arguments that passed to the callback are:
137
+
138
+ - first argument: current iteration number (start from ``1``)
139
+ - second argument: a total number of iteration
140
+ """
141
+
142
+ @property
143
+ def margin(self) -> int:
144
+ raise NotImplementedError()
145
+
146
+ @margin.setter
147
+ def margin(self, value: int) -> None:
148
+ raise NotImplementedError()
149
+
150
+ @property
151
+ def value_matrix(self) -> Sequence:
152
+ """Data of a table to be outputted."""
153
+
154
+ return self.__value_matrix_org
155
+
156
+ @value_matrix.setter
157
+ def value_matrix(self, value_matrix: Sequence) -> None:
158
+ self.__set_value_matrix(value_matrix)
159
+ self.__clear_preprocess()
160
+
161
+ @property
162
+ def table_format(self) -> "TableFormat":
163
+ """TableFormat: Get the format of the writer."""
164
+
165
+ from .._table_format import TableFormat
166
+
167
+ table_format = TableFormat.from_name(self.format_name)
168
+ assert table_format
169
+
170
+ return table_format
171
+
172
+ @property
173
+ def stream(self) -> Any:
174
+ return self._stream
175
+
176
+ @stream.setter
177
+ def stream(self, value: Any) -> None:
178
+ self._stream = value
179
+
180
+ @abc.abstractmethod
181
+ def _write_table(self, **kwargs: Any) -> None:
182
+ pass
183
+
184
+ def __init__(self, **kwargs: Any) -> None:
185
+ self._logger = WriterLogger(self)
186
+
187
+ self.table_name = kwargs.get("table_name", "")
188
+ self.value_matrix = kwargs.get("value_matrix", [])
189
+
190
+ self.is_write_header = kwargs.get("is_write_header", True)
191
+ self.is_write_header_separator_row = kwargs.get("is_write_header_separator_row", True)
192
+ self.is_write_value_separator_row = kwargs.get("is_write_value_separator_row", False)
193
+ self.is_write_opening_row = kwargs.get("is_write_opening_row", False)
194
+ self.is_write_closing_row = kwargs.get("is_write_closing_row", False)
195
+
196
+ self._use_default_header = False
197
+
198
+ self._dp_extractor = DataPropertyExtractor(max_precision=kwargs.get("max_precision"))
199
+ self._dp_extractor.min_column_width = 1
200
+ self._dp_extractor.strip_str_header = '"'
201
+ self._dp_extractor.preprocessor = Preprocessor(dequote=kwargs.get("dequote", True))
202
+ self._dp_extractor.type_value_map[Typecode.NONE] = ""
203
+ self._dp_extractor.matrix_formatting = MatrixFormatting.HEADER_ALIGNED
204
+ self._dp_extractor.update_strict_level_map({Typecode.BOOL: 1})
205
+
206
+ self.is_formatting_float = kwargs.get("is_formatting_float", True)
207
+ self.is_padding = kwargs.get("is_padding", True)
208
+
209
+ self.headers = kwargs.get("headers", [])
210
+ self.type_hints = kwargs.get("type_hints", [])
211
+ self._quoting_flags = {
212
+ Typecode.BOOL: False,
213
+ Typecode.DATETIME: True,
214
+ Typecode.DICTIONARY: False,
215
+ Typecode.INFINITY: False,
216
+ Typecode.INTEGER: False,
217
+ Typecode.IP_ADDRESS: True,
218
+ Typecode.LIST: False,
219
+ Typecode.NAN: False,
220
+ Typecode.NONE: False,
221
+ Typecode.NULL_STRING: True,
222
+ Typecode.REAL_NUMBER: False,
223
+ Typecode.STRING: True,
224
+ }
225
+
226
+ self._is_require_table_name = False
227
+ self._is_require_header = False
228
+
229
+ self.iteration_length: int = kwargs.get("iteration_length", -1)
230
+ self.write_callback = kwargs.get(
231
+ "write_callback", lambda _iter_count, _iter_length: None # defaults to NOP callback
232
+ )
233
+ self._iter_count: Optional[int] = None
234
+
235
+ self.__default_style: Style
236
+ self.default_style = kwargs.get("default_style", Style())
237
+
238
+ self.__col_style_list: List[Optional[Style]] = []
239
+ self.column_styles = kwargs.get("column_styles", [])
240
+
241
+ self._style_filters: List[StyleFilterFunc] = copy.deepcopy(DEFAULT_STYLE_FILTERS)
242
+ self._enable_style_filter = True
243
+ self._styler = self._create_styler(self)
244
+ self.style_filter_kwargs: Dict[str, Any] = kwargs.get("style_filter_kwargs", {})
245
+ self._check_style_filter_kwargs_funcs: List[CheckStyleFilterKeywordArgsFunc] = []
246
+ self.__colorize_terminal = kwargs.get("colorize_terminal", True)
247
+ self.__enable_ansi_escape = kwargs.get("enable_ansi_escape", True)
248
+
249
+ self.max_workers = kwargs.get("max_workers", 1)
250
+
251
+ if "dataframe" in kwargs:
252
+ self.from_dataframe(kwargs["dataframe"])
253
+
254
+ self.__clear_preprocess()
255
+
256
+ def _repr_html_(self) -> str:
257
+ from .text._html import HtmlTableWriter
258
+
259
+ writer = HtmlTableWriter(
260
+ table_name=self.table_name,
261
+ headers=self.headers,
262
+ value_matrix=self.value_matrix,
263
+ column_styles=self.column_styles,
264
+ colorize_terminal=self.colorize_terminal,
265
+ enable_ansi_escape=self.enable_ansi_escape,
266
+ )
267
+ writer._dp_extractor = self._dp_extractor
268
+
269
+ return writer.dumps()
270
+
271
+ @property
272
+ def value_preprocessor(self) -> Preprocessor:
273
+ return self._dp_extractor.preprocessor
274
+
275
+ def __clear_preprocess_status(self) -> None:
276
+ self._is_complete_table_dp_preprocess = False
277
+ self._is_complete_table_property_preprocess = False
278
+ self._is_complete_header_preprocess = False
279
+ self._is_complete_value_matrix_preprocess = False
280
+
281
+ def __clear_preprocess_data(self) -> None:
282
+ self._column_dp_list: List[ColumnDataProperty] = []
283
+ self._table_headers: List[str] = []
284
+ self._table_value_matrix: List[Union[List[str], Dict]] = []
285
+ self._table_value_dp_matrix: Sequence[Sequence[DataProperty]] = []
286
+
287
+ @property
288
+ def headers(self) -> Sequence[str]:
289
+ """Sequence[str]: Headers of a table to be outputted."""
290
+
291
+ return self._dp_extractor.headers
292
+
293
+ @headers.setter
294
+ def headers(self, value: Sequence[str]) -> None:
295
+ self._dp_extractor.headers = value
296
+
297
+ @property
298
+ def is_formatting_float(self) -> bool:
299
+ return self._dp_extractor.is_formatting_float
300
+
301
+ @is_formatting_float.setter
302
+ def is_formatting_float(self, value: bool) -> None:
303
+ if self._dp_extractor.is_formatting_float == value:
304
+ return
305
+
306
+ self._dp_extractor.is_formatting_float = value
307
+ self.__clear_preprocess()
308
+
309
+ @property
310
+ def max_workers(self) -> int:
311
+ return self._dp_extractor.max_workers
312
+
313
+ @max_workers.setter
314
+ def max_workers(self, value: Optional[int]) -> None:
315
+ self._dp_extractor.max_workers = value
316
+
317
+ @property
318
+ def tabledata(self) -> TableData:
319
+ """tabledata.TableData: Get tabular data of the writer."""
320
+
321
+ return TableData(
322
+ self.table_name,
323
+ self.headers,
324
+ self.value_matrix,
325
+ max_workers=self.max_workers,
326
+ max_precision=self._dp_extractor.max_precision,
327
+ )
328
+
329
+ @property
330
+ def table_name(self) -> str:
331
+ """str: Name of a table."""
332
+
333
+ return self._table_name
334
+
335
+ @table_name.setter
336
+ def table_name(self, value: str) -> None:
337
+ self._table_name = value
338
+
339
+ @property
340
+ def type_hints(self) -> List[TypeHint]:
341
+ """
342
+ Type hints for each column of the tabular data.
343
+ Writers convert data for each column using the type hints information
344
+ before writing tables when you call ``write_xxx`` methods.
345
+
346
+ Acceptable values are as follows:
347
+
348
+ - |None| (automatically detect column type from values in the column)
349
+ - :py:class:`pytablewriter.typehint.Bool` or ``"bool"``
350
+ - :py:class:`pytablewriter.typehint.DateTime` or ``"datetime"``
351
+ - :py:class:`pytablewriter.typehint.Dictionary` or ``"dict"``
352
+ - :py:class:`pytablewriter.typehint.Infinity` or ``"inf"``
353
+ - :py:class:`pytablewriter.typehint.Integer` or ``"int"``
354
+ - :py:class:`pytablewriter.typehint.IpAddress` or ``"ipaddr"``
355
+ - :py:class:`pytablewriter.typehint.List` or ``"list"``
356
+ - :py:class:`pytablewriter.typehint.Nan` or ``"nan"``
357
+ - :py:class:`pytablewriter.typehint.NoneType` or ``"none"``
358
+ - :py:class:`pytablewriter.typehint.NullString` or ``"nullstr"``
359
+ - :py:class:`pytablewriter.typehint.RealNumber` or ``"realnumber"`` or ``"float"``
360
+ - :py:class:`pytablewriter.typehint.String` or ``"str"``
361
+
362
+ If a type-hint value is not |None|, the writer tries to
363
+ convert data for each data in a column to type-hint class.
364
+ If the type-hint value is |None| or failed to convert data,
365
+ the writer automatically detects column data type from
366
+ the column data.
367
+
368
+ If ``type_hints`` is |None|, the writer automatically detects data types
369
+ for all of the columns and writes a table using detected column types.
370
+
371
+ Defaults to |None|.
372
+
373
+ Examples:
374
+ - :ref:`example-type-hint-js`
375
+ - :ref:`example-type-hint-python`
376
+ """
377
+
378
+ return self._dp_extractor.column_type_hints
379
+
380
+ @type_hints.setter
381
+ def type_hints(self, value: Sequence[Union[str, TypeHint]]) -> None:
382
+ hints = list(value)
383
+ if self.type_hints == hints:
384
+ return
385
+
386
+ self.__set_type_hints(hints)
387
+ self.__clear_preprocess()
388
+
389
+ @property
390
+ def default_style(self) -> Style:
391
+ """Style: Default |Style| of table cells."""
392
+
393
+ return self.__default_style
394
+
395
+ @default_style.setter
396
+ def default_style(self, style: Optional[Style]) -> None:
397
+ if style is None:
398
+ style = Style()
399
+
400
+ if not isinstance(style, Style):
401
+ raise TypeError("default_style must be a Style instance")
402
+
403
+ try:
404
+ if self.__default_style == style:
405
+ return
406
+ except AttributeError:
407
+ # not yet initialized
408
+ pass
409
+
410
+ self.__default_style = style
411
+ self._dp_extractor.default_format_flags = _ts_to_flag[
412
+ self.__default_style.thousand_separator
413
+ ]
414
+ self.__clear_preprocess()
415
+
416
+ @property
417
+ def column_styles(self) -> List[Optional[Style]]:
418
+ """List[Optional[Style]]: |Style| for each column."""
419
+
420
+ return self.__col_style_list
421
+
422
+ @column_styles.setter
423
+ def column_styles(self, value: Sequence[Optional[Style]]) -> None:
424
+ if self.__col_style_list == value:
425
+ return
426
+
427
+ self.__col_style_list = list(value)
428
+
429
+ if self.__col_style_list:
430
+ self._dp_extractor.format_flags_list = [
431
+ _ts_to_flag[self._get_col_style(col_idx).thousand_separator]
432
+ for col_idx in range(len(self.__col_style_list))
433
+ ]
434
+ else:
435
+ self._dp_extractor.format_flags_list = []
436
+
437
+ self.__clear_preprocess()
438
+
439
+ @property
440
+ def colorize_terminal(self) -> bool:
441
+ return self.__colorize_terminal
442
+
443
+ @colorize_terminal.setter
444
+ def colorize_terminal(self, value: bool) -> None:
445
+ if self.__colorize_terminal == value:
446
+ return
447
+
448
+ self.__colorize_terminal = value
449
+ self.__clear_preprocess()
450
+
451
+ @property
452
+ def enable_ansi_escape(self) -> bool:
453
+ return self.__enable_ansi_escape
454
+
455
+ @enable_ansi_escape.setter
456
+ def enable_ansi_escape(self, value: bool) -> None:
457
+ if self.__enable_ansi_escape == value:
458
+ return
459
+
460
+ self.__enable_ansi_escape = value
461
+ self.__clear_preprocess()
462
+
463
+ @property
464
+ def _quoting_flags(self) -> Dict[Typecode, bool]:
465
+ return self._dp_extractor.quoting_flags
466
+
467
+ @_quoting_flags.setter
468
+ def _quoting_flags(self, value: Mapping[Typecode, bool]) -> None:
469
+ self._dp_extractor.quoting_flags = value
470
+ self.__clear_preprocess()
471
+
472
+ def add_style_filter(self, style_filter: StyleFilterFunc) -> None:
473
+ """Add a style filter function to the writer.
474
+
475
+ Args:
476
+ style_filter:
477
+ A function called for each table cell to apply a style to table cells.
478
+ The function will be required to implement the following Protocol:
479
+
480
+ .. code-block:: python
481
+
482
+ class StyleFilterFunc(Protocol):
483
+ def __call__(self, cell: Cell, **kwargs: Any) -> Optional[Style]:
484
+ ...
485
+
486
+ If more than one style filter function is added to the writer,
487
+ it will be called from the last one added.
488
+ These style functions should return |None| when not needed to apply styles.
489
+ If all of the style functions returned |None|,
490
+ :py:attr:`~.default_style` will be used.
491
+
492
+ You can pass keyword arguments to style filter functions via
493
+ :py:attr:`~.style_filter_kwargs`. In default, the attribute includes:
494
+
495
+ - ``writer``: the writer instance that the caller of a ``style_filter function``
496
+ """
497
+
498
+ self._style_filters.insert(0, style_filter)
499
+ self.__clear_preprocess()
500
+
501
+ def add_col_separator_style_filter(self, style_filter: ColSeparatorStyleFilterFunc) -> None:
502
+ self._logger.logger.debug(
503
+ "add_col_separator_style_filter method is only implemented in text format writer classes"
504
+ )
505
+
506
+ def clear_theme(self) -> None:
507
+ """Remove all of the style filters."""
508
+
509
+ if not self._style_filters:
510
+ return
511
+
512
+ self._style_filters = copy.deepcopy(DEFAULT_STYLE_FILTERS)
513
+ self._check_style_filter_kwargs_funcs = []
514
+ self.__clear_preprocess()
515
+
516
+ def enable_style_filter(self) -> None:
517
+ """Enable style filters."""
518
+
519
+ if self._enable_style_filter is True:
520
+ return
521
+
522
+ self._enable_style_filter = True
523
+ self.__clear_preprocess()
524
+
525
+ def disable_style_filter(self, clear_filters: bool = False) -> None:
526
+ """Disable style filters.
527
+
528
+ Args:
529
+ clear_filters (bool):
530
+ If |True|, clear all of the style filters.
531
+ Defaults to |False|.
532
+ """
533
+
534
+ if clear_filters:
535
+ self.clear_theme()
536
+ return
537
+
538
+ if self._enable_style_filter is False:
539
+ return
540
+
541
+ self._enable_style_filter = False
542
+ self.__clear_preprocess()
543
+
544
+ def set_style(self, column: Union[str, int], style: Style) -> None:
545
+ """Set |Style| for a specific column.
546
+
547
+ Args:
548
+ column (|int| or |str|):
549
+ Column specifier. Column index or header name correlated with the column.
550
+ style (|Style|):
551
+ Style value to be set to the column.
552
+
553
+ Raises:
554
+ ValueError: Raised when the column specifier is invalid.
555
+ """
556
+
557
+ column_idx = None
558
+
559
+ while len(self.headers) > len(self.__col_style_list):
560
+ self.__col_style_list.append(None)
561
+
562
+ if isinstance(column, int):
563
+ column_idx = column
564
+ elif isinstance(column, str):
565
+ try:
566
+ column_idx = self.headers.index(column)
567
+ except ValueError:
568
+ pass
569
+
570
+ if column_idx is not None:
571
+ self.__col_style_list[column_idx] = style
572
+ self.__clear_preprocess()
573
+ self._dp_extractor.format_flags_list = [
574
+ _ts_to_flag[self._get_col_style(col_idx).thousand_separator]
575
+ for col_idx in range(len(self.__col_style_list))
576
+ ]
577
+ return
578
+
579
+ raise ValueError(f"column must be an int or string: actual={column}")
580
+
581
+ def set_theme(self, theme: str, **kwargs: Any) -> None:
582
+ """Set style filters for a theme.
583
+
584
+ Args:
585
+ theme (str):
586
+ Name of the theme. pytablewriter theme plugin must be installed
587
+ corresponding to the theme name.
588
+
589
+ Raises:
590
+ RuntimeError: Raised when a theme plugin does not install.
591
+ """
592
+
593
+ try:
594
+ fetched_theme = fetch_theme(theme.strip())
595
+ except RuntimeError as e:
596
+ warnings.warn(f"{e}", UserWarning)
597
+ return
598
+
599
+ if fetched_theme.style_filter:
600
+ self.add_style_filter(fetched_theme.style_filter)
601
+
602
+ if fetched_theme.col_separator_style_filter:
603
+ self.add_col_separator_style_filter(fetched_theme.col_separator_style_filter)
604
+
605
+ if fetched_theme.check_style_filter_kwargs:
606
+ self._check_style_filter_kwargs_funcs.append(fetched_theme.check_style_filter_kwargs)
607
+
608
+ self.style_filter_kwargs.update(**kwargs)
609
+
610
+ def __is_skip_close(self) -> bool:
611
+ try:
612
+ from _pytest.capture import EncodedFile
613
+
614
+ if isinstance(self.stream, EncodedFile):
615
+ # avoid closing streams for pytest
616
+ return True
617
+ except ImportError:
618
+ pass
619
+
620
+ try:
621
+ from _pytest.capture import CaptureIO
622
+
623
+ if isinstance(self.stream, CaptureIO):
624
+ # avoid closing streams for pytest
625
+ return True
626
+ except ImportError:
627
+ try:
628
+ # for pytest 5.4.1 or older versions
629
+ from _pytest.compat import CaptureIO
630
+
631
+ if isinstance(self.stream, CaptureIO):
632
+ # avoid closing streams for pytest
633
+ return True
634
+ except ImportError:
635
+ pass
636
+
637
+ try:
638
+ from ipykernel.iostream import OutStream
639
+
640
+ if isinstance(self.stream, OutStream):
641
+ # avoid closing streams for Jupyter Notebook
642
+ return True
643
+ except ImportError:
644
+ pass
645
+
646
+ return False
647
+
648
+ def close(self) -> None:
649
+ """
650
+ Close the current |stream|.
651
+ """
652
+
653
+ if self.stream is None:
654
+ return
655
+
656
+ try:
657
+ self.stream.isatty()
658
+
659
+ if self.stream.name in ["<stdin>", "<stdout>", "<stderr>"]:
660
+ return
661
+ except AttributeError:
662
+ pass
663
+ except ValueError:
664
+ # raised when executing an operation to a closed stream
665
+ pass
666
+
667
+ if self.__is_skip_close():
668
+ return
669
+
670
+ try:
671
+ self.stream.close()
672
+ except AttributeError:
673
+ self._logger.logger.warning(
674
+ f"the stream has no close method implementation: type={type(self.stream)}"
675
+ )
676
+ finally:
677
+ self._stream = None
678
+
679
+ def from_tabledata(self, value: TableData, is_overwrite_table_name: bool = True) -> None:
680
+ """
681
+ Set tabular attributes to the writer from |TableData|.
682
+ The following attributes are configured:
683
+
684
+ - :py:attr:`~.table_name`.
685
+ - :py:attr:`~.headers`.
686
+ - :py:attr:`~.value_matrix`.
687
+
688
+ |TableData| can be created from various data formats by
689
+ ``pytablereader``. More detailed information can be found in
690
+ https://pytablereader.rtfd.io/en/latest/
691
+
692
+ :param tabledata.TableData value: Input table data.
693
+ """
694
+
695
+ self.__clear_preprocess()
696
+
697
+ if is_overwrite_table_name:
698
+ self.table_name = value.table_name if value.table_name else ""
699
+
700
+ self.headers = value.headers
701
+ self.value_matrix = list(value.rows)
702
+
703
+ if not value.has_value_dp_matrix:
704
+ return
705
+
706
+ self._table_value_dp_matrix = value.value_dp_matrix
707
+ self._column_dp_list = self._dp_extractor.to_column_dp_list(
708
+ self._table_value_dp_matrix, self._column_dp_list
709
+ )
710
+ self.__set_type_hints([col_dp.type_class for col_dp in self._column_dp_list])
711
+
712
+ self._is_complete_table_dp_preprocess = True
713
+
714
+ def from_csv(self, csv_source: str, delimiter: str = ",") -> None:
715
+ """
716
+ Set tabular attributes to the writer from a character-separated values (CSV) data source.
717
+ The following attributes are set to the writer by the method:
718
+
719
+ - :py:attr:`~.headers`.
720
+ - :py:attr:`~.value_matrix`.
721
+
722
+ :py:attr:`~.table_name` also be set if the CSV data source is a file.
723
+ In that case, :py:attr:`~.table_name` is as same as the filename.
724
+
725
+ Args:
726
+ csv_source (str):
727
+ Input CSV data source can be designated CSV text or a CSV file path.
728
+
729
+ delimiter (str):
730
+ Delimiter character of the CSV data source.
731
+ Defaults to ``,``.
732
+
733
+ Examples:
734
+ :ref:`example-from-csv`
735
+
736
+ :Dependency Packages:
737
+ - `pytablereader <https://github.com/thombashi/pytablereader>`__
738
+ """
739
+
740
+ import pytablereader as ptr
741
+
742
+ loader = ptr.CsvTableTextLoader(csv_source, quoting_flags=self._quoting_flags)
743
+ loader.delimiter = delimiter
744
+ try:
745
+ for table_data in loader.load():
746
+ self.from_tabledata(table_data, is_overwrite_table_name=False)
747
+ return
748
+ except ptr.DataError:
749
+ pass
750
+
751
+ loader = ptr.CsvTableFileLoader(csv_source, quoting_flags=self._quoting_flags)
752
+ loader.delimiter = delimiter
753
+ for table_data in loader.load():
754
+ self.from_tabledata(table_data)
755
+
756
+ def from_dataframe(
757
+ self,
758
+ dataframe: "pandas.DataFrame",
759
+ add_index_column: bool = False,
760
+ overwrite_type_hints: bool = True,
761
+ ) -> None:
762
+ """
763
+ Set tabular attributes to the writer from :py:class:`pandas.DataFrame`.
764
+ The following attributes are set by the method:
765
+
766
+ - :py:attr:`~.headers`
767
+ - :py:attr:`~.value_matrix`
768
+ - :py:attr:`~.type_hints`
769
+
770
+ Args:
771
+ dataframe(pandas.DataFrame or |str|):
772
+ Input pandas.DataFrame object or path to a DataFrame pickle.
773
+ add_index_column(bool, optional):
774
+ If |True|, add a column of ``index`` of the ``dataframe``.
775
+ Defaults to |False|.
776
+ overwrite_type_hints(bool):
777
+ If |True|, Overwrite type hints with dtypes within the DataFrame.
778
+
779
+ Example:
780
+ :ref:`example-from-pandas-dataframe`
781
+ """
782
+
783
+ if typepy.String(dataframe).is_type():
784
+ import pandas as pd
785
+
786
+ dataframe = pd.read_pickle(dataframe)
787
+
788
+ self.headers = list(dataframe.columns.values)
789
+
790
+ if not self.type_hints or overwrite_type_hints:
791
+ self.type_hints = [extract_typepy_from_dtype(dtype) for dtype in dataframe.dtypes]
792
+
793
+ if add_index_column:
794
+ self.headers = [" "] + self.headers
795
+ if self.type_hints:
796
+ self.type_hints = [Integer] + self.type_hints
797
+ self.value_matrix = [
798
+ [index] + row
799
+ for index, row in zip(dataframe.index.tolist(), dataframe.values.tolist())
800
+ ]
801
+ else:
802
+ self.value_matrix = dataframe.values.tolist()
803
+
804
+ def from_series(self, series: "pandas.Series", add_index_column: bool = True) -> None:
805
+ """
806
+ Set tabular attributes to the writer from :py:class:`pandas.Series`.
807
+ The following attributes are set by the method:
808
+
809
+ - :py:attr:`~.headers`
810
+ - :py:attr:`~.value_matrix`
811
+ - :py:attr:`~.type_hints`
812
+
813
+ Args:
814
+ series(pandas.Series):
815
+ Input pandas.Series object.
816
+ add_index_column(bool, optional):
817
+ If |True|, add a column of ``index`` of the ``series``.
818
+ Defaults to |True|.
819
+ """
820
+
821
+ if series.name:
822
+ self.headers = [series.name]
823
+ else:
824
+ self.headers = ["value"]
825
+
826
+ self.type_hints = [extract_typepy_from_dtype(series.dtype)]
827
+
828
+ if add_index_column:
829
+ self.headers = [""] + self.headers
830
+ if self.type_hints:
831
+ self.type_hints = [None] + self.type_hints
832
+ self.value_matrix = [
833
+ [index] + [value] for index, value in zip(series.index.tolist(), series.tolist())
834
+ ]
835
+ else:
836
+ self.value_matrix = [[value] for value in series.tolist()]
837
+
838
+ def from_tablib(self, tablib_dataset: "tablib.Dataset") -> None:
839
+ """
840
+ Set tabular attributes to the writer from :py:class:`tablib.Dataset`.
841
+ """
842
+
843
+ self.headers = tablib_dataset.headers
844
+ self.value_matrix = [row for row in tablib_dataset]
845
+
846
+ def from_writer(
847
+ self, writer: "AbstractTableWriter", is_overwrite_table_name: bool = True
848
+ ) -> None:
849
+ """
850
+ Copy attributes from another table writer class instance.
851
+
852
+ Args:
853
+ writer (pytablewriter.writer.AbstractTableWriter):
854
+ Another table writer instance.
855
+ is_overwrite_table_name (bool, optional):
856
+ Overwrite the table name of the writer with the table name of the ``writer``.
857
+ Defaults to |True|.
858
+ """
859
+
860
+ self.__clear_preprocess()
861
+
862
+ if is_overwrite_table_name:
863
+ self.table_name = str(writer.table_name)
864
+
865
+ self.headers = writer.headers
866
+ self.value_matrix = writer.value_matrix
867
+
868
+ self.type_hints = writer.type_hints
869
+ self.column_styles = writer.column_styles
870
+ self._style_filters = writer._style_filters
871
+ self.style_filter_kwargs = writer.style_filter_kwargs
872
+ self.margin = writer.margin
873
+
874
+ self._table_headers = writer._table_headers
875
+ self._table_value_dp_matrix = writer._table_value_dp_matrix
876
+ self._column_dp_list = writer._column_dp_list
877
+ self._table_value_matrix = writer._table_value_matrix
878
+
879
+ self.stream = writer.stream
880
+
881
+ self._is_complete_table_dp_preprocess = writer._is_complete_table_dp_preprocess
882
+ self._is_complete_table_property_preprocess = writer._is_complete_table_property_preprocess
883
+ self._is_complete_header_preprocess = writer._is_complete_header_preprocess
884
+ self._is_complete_value_matrix_preprocess = writer._is_complete_value_matrix_preprocess
885
+
886
+ def register_trans_func(self, trans_func: TransFunc) -> None:
887
+ self._dp_extractor.register_trans_func(trans_func)
888
+ self.__clear_preprocess()
889
+
890
+ def update_preprocessor(self, **kwargs: Any) -> None:
891
+ # TODO: documentation
892
+ # is_escape_formula_injection: for CSV/Excel
893
+
894
+ if not self._dp_extractor.update_preprocessor(**kwargs):
895
+ return
896
+
897
+ self.__clear_preprocess()
898
+
899
+ def write_table(self, **kwargs: Any) -> None:
900
+ """
901
+ |write_table|.
902
+ """
903
+
904
+ with self._logger:
905
+ try:
906
+ self._verify_property()
907
+ except EmptyTableDataError:
908
+ self._logger.logger.debug("no tabular data found")
909
+ return
910
+
911
+ self._write_table(**kwargs)
912
+
913
+ def _write_table_iter(self, **kwargs: Any) -> None:
914
+ if not self.support_split_write:
915
+ raise NotSupportedError("the class not supported the write_table_iter method")
916
+
917
+ self._verify_style_filter_kwargs()
918
+ self._verify_table_name()
919
+ self._verify_stream()
920
+
921
+ if all(
922
+ [typepy.is_empty_sequence(self.headers), typepy.is_empty_sequence(self.value_matrix)]
923
+ ):
924
+ self._logger.logger.debug("no tabular data found")
925
+ return
926
+
927
+ self._verify_header()
928
+
929
+ self._logger.logger.debug(f"_write_table_iter: iteration-length={self.iteration_length:d}")
930
+
931
+ stash_is_write_header = self.is_write_header
932
+ stach_is_write_opening_row = self.is_write_opening_row
933
+ stash_is_write_closing_row = self.is_write_closing_row
934
+
935
+ try:
936
+ self.is_write_closing_row = False
937
+ self._iter_count = 1
938
+
939
+ for work_matrix in self.value_matrix:
940
+ is_final_iter = all(
941
+ [self.iteration_length > 0, self._iter_count >= self.iteration_length]
942
+ )
943
+
944
+ if is_final_iter:
945
+ self.is_write_closing_row = True
946
+
947
+ self.__set_value_matrix(work_matrix)
948
+ self.__clear_preprocess_status()
949
+
950
+ with self._logger:
951
+ self._write_table(**kwargs)
952
+
953
+ if not is_final_iter:
954
+ self._write_value_row_separator()
955
+
956
+ self.is_write_opening_row = False
957
+ self.is_write_header = False
958
+
959
+ self.write_callback(self._iter_count, self.iteration_length)
960
+
961
+ # update typehint for the next iteration
962
+ """
963
+ if self.type_hints is None:
964
+ self.__set_type_hints([
965
+ column_dp.type_class for column_dp in self._column_dp_list
966
+ ])
967
+ """
968
+
969
+ if is_final_iter:
970
+ break
971
+
972
+ self._iter_count += 1
973
+ finally:
974
+ self.is_write_header = stash_is_write_header
975
+ self.is_write_opening_row = stach_is_write_opening_row
976
+ self.is_write_closing_row = stash_is_write_closing_row
977
+ self._iter_count = None
978
+
979
+ def _get_padding_len(
980
+ self, column_dp: ColumnDataProperty, value_dp: Optional[DataProperty] = None
981
+ ) -> int:
982
+ if not self.is_padding:
983
+ return 0
984
+
985
+ try:
986
+ return cast(DataProperty, value_dp).get_padding_len(column_dp.ascii_char_width)
987
+ except AttributeError:
988
+ return column_dp.ascii_char_width
989
+
990
+ def _to_header_item(self, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str:
991
+ style = self._fetch_style(HEADER_ROW, col_dp, value_dp)
992
+ header = self._apply_style_to_header_item(col_dp, value_dp, style)
993
+ header = self._styler.apply_terminal_style(header, style=style)
994
+
995
+ return header
996
+
997
+ def _apply_style_to_header_item(
998
+ self, col_dp: ColumnDataProperty, value_dp: DataProperty, style: Style
999
+ ) -> str:
1000
+ return self._styler.apply_align(
1001
+ self._styler.apply(col_dp.dp_to_str(value_dp), style=style), style=style
1002
+ )
1003
+
1004
+ def _to_row_item(self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> str:
1005
+ style = self._fetch_style(row_idx, col_dp, value_dp)
1006
+ value = self._apply_style_to_row_item(row_idx, col_dp, value_dp, style)
1007
+
1008
+ return self._styler.apply_terminal_style(value, style=style)
1009
+
1010
+ def _apply_style_to_row_item(
1011
+ self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty, style: Style
1012
+ ) -> str:
1013
+ return self._styler.apply_align(
1014
+ self._styler.apply(col_dp.dp_to_str(value_dp), style=style), style=style
1015
+ )
1016
+
1017
+ def _fetch_style_from_filter(
1018
+ self, row_idx: int, col_dp: ColumnDataProperty, value_dp: DataProperty, default_style: Style
1019
+ ) -> Style:
1020
+ if not self._enable_style_filter:
1021
+ return default_style
1022
+
1023
+ self.style_filter_kwargs.update({"writer": self})
1024
+
1025
+ style: Optional[Style] = None
1026
+ for style_filter in self._style_filters:
1027
+ style = style_filter(
1028
+ Cell(
1029
+ row=row_idx,
1030
+ col=col_dp.column_index,
1031
+ value=value_dp.data,
1032
+ default_style=default_style,
1033
+ ),
1034
+ **self.style_filter_kwargs,
1035
+ )
1036
+ if style:
1037
+ break
1038
+
1039
+ if style is None:
1040
+ style = copy.deepcopy(default_style)
1041
+
1042
+ if style.align is None or (style.align == Align.AUTO and row_idx >= 0):
1043
+ style.align = self.__retrieve_align_from_data(col_dp, value_dp)
1044
+
1045
+ if style.padding is None:
1046
+ style.padding = self._get_padding_len(col_dp, value_dp)
1047
+
1048
+ return style
1049
+
1050
+ def _get_col_style(self, col_idx: int) -> Style:
1051
+ try:
1052
+ style = self.column_styles[col_idx]
1053
+ except (TypeError, IndexError, KeyError):
1054
+ pass
1055
+ else:
1056
+ if style:
1057
+ return style
1058
+
1059
+ return self.default_style
1060
+
1061
+ def _get_align(self, col_idx: int, default_align: Align) -> Align:
1062
+ align = self._get_col_style(col_idx).align
1063
+
1064
+ if align is None:
1065
+ return default_align
1066
+
1067
+ if align == Align.AUTO:
1068
+ return default_align
1069
+
1070
+ return align
1071
+
1072
+ def __retrieve_align_from_data(
1073
+ self, col_dp: ColumnDataProperty, value_dp: DataProperty
1074
+ ) -> Align:
1075
+ if col_dp.typecode == Typecode.STRING and (
1076
+ value_dp.typecode in (Typecode.INTEGER, Typecode.REAL_NUMBER)
1077
+ or value_dp.typecode == Typecode.STRING
1078
+ and value_dp.is_include_ansi_escape
1079
+ ):
1080
+ return value_dp.align
1081
+
1082
+ return col_dp.align
1083
+
1084
+ def _verify_property(self) -> None:
1085
+ self._verify_style_filter_kwargs()
1086
+ self._verify_table_name()
1087
+ self._verify_stream()
1088
+
1089
+ if all(
1090
+ [
1091
+ typepy.is_empty_sequence(self.headers),
1092
+ typepy.is_empty_sequence(self.value_matrix),
1093
+ typepy.is_empty_sequence(self._table_value_dp_matrix),
1094
+ ]
1095
+ ):
1096
+ raise EmptyTableDataError()
1097
+
1098
+ self._verify_header()
1099
+ try:
1100
+ self._verify_value_matrix()
1101
+ except EmptyValueError:
1102
+ pass
1103
+
1104
+ def __set_value_matrix(self, value_matrix: Sequence) -> None:
1105
+ self.__value_matrix_org = value_matrix
1106
+
1107
+ def __set_type_hints(self, type_hints: Sequence[Union[str, TypeHint]]) -> None:
1108
+ self._dp_extractor.column_type_hints = type_hints
1109
+
1110
+ def _verify_style_filter_kwargs(self) -> None:
1111
+ for checker in self._check_style_filter_kwargs_funcs:
1112
+ checker(**self.style_filter_kwargs)
1113
+
1114
+ def _verify_table_name(self) -> None:
1115
+ if all([self._is_require_table_name, typepy.is_null_string(self.table_name)]):
1116
+ raise EmptyTableNameError(
1117
+ "table_name must be a string, with at least one or more character."
1118
+ )
1119
+
1120
+ def _verify_stream(self) -> None:
1121
+ if self.stream is None:
1122
+ raise OSError("null output stream")
1123
+
1124
+ def _verify_header(self) -> None:
1125
+ if self._is_require_header and not self._use_default_header:
1126
+ self._validate_empty_header()
1127
+
1128
+ def _validate_empty_header(self) -> None:
1129
+ """
1130
+ Raises:
1131
+ ValueError: If the |headers| is empty.
1132
+ """
1133
+
1134
+ if typepy.is_empty_sequence(self.headers):
1135
+ raise ValueError("headers expected to have one or more header names")
1136
+
1137
+ def _verify_value_matrix(self) -> None:
1138
+ if typepy.is_empty_sequence(self.value_matrix):
1139
+ raise EmptyValueError()
1140
+
1141
+ def _create_styler(self, writer: "AbstractTableWriter") -> StylerInterface:
1142
+ from ..style._styler import NullStyler
1143
+
1144
+ return NullStyler(writer)
1145
+
1146
+ def _preprocess_table_dp(self) -> None:
1147
+ if self._is_complete_table_dp_preprocess:
1148
+ return
1149
+
1150
+ self._logger.logger.debug("_preprocess_table_dp")
1151
+
1152
+ if typepy.is_empty_sequence(self.headers) and self._use_default_header:
1153
+ self.headers = [
1154
+ convert_idx_to_alphabet(col_idx)
1155
+ for col_idx in range(len(self.__value_matrix_org[0]))
1156
+ ]
1157
+
1158
+ try:
1159
+ self._table_value_dp_matrix = self._dp_extractor.to_dp_matrix(
1160
+ to_value_matrix(self.headers, self.__value_matrix_org)
1161
+ )
1162
+ except TypeError as e:
1163
+ self._logger.logger.debug(to_error_message(e))
1164
+ self._table_value_dp_matrix = []
1165
+
1166
+ self._column_dp_list = self._dp_extractor.to_column_dp_list(
1167
+ self._table_value_dp_matrix, self._column_dp_list
1168
+ )
1169
+
1170
+ self._is_complete_table_dp_preprocess = True
1171
+
1172
+ def _fetch_style(self, row: int, col_dp: ColumnDataProperty, value_dp: DataProperty) -> Style:
1173
+ default_style = self._get_col_style(col_dp.column_index)
1174
+ return self._fetch_style_from_filter(row, col_dp, value_dp, default_style)
1175
+
1176
+ def _preprocess_table_property(self) -> None:
1177
+ if self._is_complete_table_property_preprocess:
1178
+ return
1179
+
1180
+ self._logger.logger.debug("_preprocess_table_property")
1181
+
1182
+ if self._iter_count == 1:
1183
+ for column_dp in self._column_dp_list:
1184
+ column_dp.extend_width(int(math.ceil(column_dp.ascii_char_width * 0.25)))
1185
+
1186
+ header_dp_list = self._dp_extractor.to_header_dp_list()
1187
+ if not header_dp_list:
1188
+ return
1189
+
1190
+ for column_dp in self._column_dp_list:
1191
+ style = self._get_col_style(column_dp.column_index)
1192
+ header_style = self._fetch_style(
1193
+ HEADER_ROW, column_dp, header_dp_list[column_dp.column_index]
1194
+ )
1195
+ body_width = self._styler.get_additional_char_width(style)
1196
+ header_width = self._styler.get_additional_char_width(header_style)
1197
+ column_dp.extend_body_width(max(body_width, header_width))
1198
+
1199
+ self._is_complete_table_property_preprocess = True
1200
+
1201
+ def _preprocess_header(self) -> None:
1202
+ if self._is_complete_header_preprocess:
1203
+ return
1204
+
1205
+ self._logger.logger.debug("_preprocess_header")
1206
+
1207
+ self._table_headers = [
1208
+ self._to_header_item(col_dp, header_dp)
1209
+ for col_dp, header_dp in zip(
1210
+ self._column_dp_list, self._dp_extractor.to_header_dp_list()
1211
+ )
1212
+ ]
1213
+
1214
+ self._is_complete_header_preprocess = True
1215
+
1216
+ def _preprocess_value_matrix(self) -> None:
1217
+ if self._is_complete_value_matrix_preprocess:
1218
+ return
1219
+
1220
+ self._logger.logger.debug(
1221
+ f"_preprocess_value_matrix: value-rows={len(self._table_value_dp_matrix)}"
1222
+ )
1223
+
1224
+ self._table_value_matrix = [
1225
+ [
1226
+ self._to_row_item(row_idx, col_dp, value_dp)
1227
+ for col_dp, value_dp in zip(self._column_dp_list, value_dp_list)
1228
+ ]
1229
+ for row_idx, value_dp_list in enumerate(self._table_value_dp_matrix)
1230
+ ]
1231
+
1232
+ self._is_complete_value_matrix_preprocess = True
1233
+
1234
+ def _preprocess(self) -> None:
1235
+ self._preprocess_table_dp()
1236
+ self._preprocess_table_property()
1237
+ self._preprocess_header()
1238
+ self._preprocess_value_matrix()
1239
+
1240
+ def _clear_preprocess(self) -> None:
1241
+ self.__clear_preprocess()
1242
+
1243
+ def __clear_preprocess(self) -> None:
1244
+ self.__clear_preprocess_status()
1245
+ self.__clear_preprocess_data()
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._excel import ExcelXlsTableWriter, ExcelXlsxTableWriter
2
+ from ._pandas import PandasDataFramePickleWriter
3
+ from ._sqlite import SqliteTableWriter
4
+
5
+
6
+ __all__ = (
7
+ "ExcelXlsTableWriter",
8
+ "ExcelXlsxTableWriter",
9
+ "PandasDataFramePickleWriter",
10
+ "SqliteTableWriter",
11
+ )
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (421 Bytes). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel.cpython-310.pyc ADDED
Binary file (16 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_excel_workbook.cpython-310.pyc ADDED
Binary file (4.71 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_interface.cpython-310.pyc ADDED
Binary file (2.87 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_pandas.cpython-310.pyc ADDED
Binary file (3.98 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/__pycache__/_sqlite.cpython-310.pyc ADDED
Binary file (3.74 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import copy
3
+ import warnings
4
+ from typing import IO, TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union, cast
5
+
6
+ import dataproperty
7
+ import typepy
8
+ from dataproperty import DataProperty
9
+ from tabledata import TableData
10
+ from typepy import Integer
11
+
12
+ from .._common import import_error_msg_template
13
+ from ._excel_workbook import ExcelWorkbookInterface, ExcelWorkbookXls, ExcelWorkbookXlsx
14
+ from ._interface import AbstractBinaryTableWriter
15
+
16
+
17
+ if TYPE_CHECKING:
18
+ from xlwt import XFStyle
19
+
20
+
21
+ class ExcelTableWriter(AbstractBinaryTableWriter, metaclass=abc.ABCMeta):
22
+ """
23
+ An abstract class of a table writer for Excel file format.
24
+ """
25
+
26
+ FORMAT_NAME = "excel"
27
+
28
+ @property
29
+ def format_name(self) -> str:
30
+ return self.FORMAT_NAME
31
+
32
+ @property
33
+ def workbook(self) -> Optional[ExcelWorkbookInterface]:
34
+ return self._workbook
35
+
36
+ def __init__(self, **kwargs: Any) -> None:
37
+ super().__init__(**kwargs)
38
+
39
+ self._workbook: Optional[ExcelWorkbookInterface] = None
40
+
41
+ self._dp_extractor.type_value_map = {
42
+ typepy.Typecode.INFINITY: "Inf",
43
+ typepy.Typecode.NAN: "NaN",
44
+ }
45
+
46
+ self._first_header_row = 0
47
+ self._last_header_row = self.first_header_row
48
+ self._first_data_row = self.last_header_row + 1
49
+ self._first_data_col = 0
50
+ self._last_data_row: Optional[int] = None
51
+ self._last_data_col: Optional[int] = None
52
+
53
+ self._current_data_row = self._first_data_row
54
+
55
+ self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
56
+ self._quoting_flags[typepy.Typecode.DATETIME] = True
57
+
58
+ @property
59
+ def first_header_row(self) -> int:
60
+ """int: Index of the first row of the header.
61
+
62
+ .. note:: |excel_attr|
63
+ """
64
+
65
+ return self._first_header_row
66
+
67
+ @property
68
+ def last_header_row(self) -> int:
69
+ """int: Index of the last row of the header.
70
+
71
+ .. note:: |excel_attr|
72
+ """
73
+
74
+ return self._last_header_row
75
+
76
+ @property
77
+ def first_data_row(self) -> int:
78
+ """int: Index of the first row of the data (table body).
79
+
80
+ .. note:: |excel_attr|
81
+ """
82
+
83
+ return self._first_data_row
84
+
85
+ @property
86
+ def last_data_row(self) -> Optional[int]:
87
+ """int: Index of the last row of the data (table body).
88
+
89
+ .. note:: |excel_attr|
90
+ """
91
+
92
+ return self._last_data_row
93
+
94
+ @property
95
+ def first_data_col(self) -> int:
96
+ """int: Index of the first column of the table.
97
+
98
+ .. note:: |excel_attr|
99
+ """
100
+
101
+ return self._first_data_col
102
+
103
+ @property
104
+ def last_data_col(self) -> Optional[int]:
105
+ """int: Index of the last column of the table.
106
+
107
+ .. note:: |excel_attr|
108
+ """
109
+
110
+ return self._last_data_col
111
+
112
+ def is_opened(self) -> bool:
113
+ return self.workbook is not None
114
+
115
+ def open(self, file_path: str) -> None:
116
+ """
117
+ Open an Excel workbook file.
118
+
119
+ :param str file_path: Excel workbook file path to open.
120
+ """
121
+
122
+ if self.workbook and self.workbook.file_path == file_path:
123
+ self._logger.logger.debug(f"workbook already opened: {self.workbook.file_path}")
124
+ return
125
+
126
+ self.close()
127
+ self._open(file_path)
128
+
129
+ @abc.abstractmethod
130
+ def _open(self, workbook_path: str) -> None: # pragma: no cover
131
+ pass
132
+
133
+ def close(self) -> None:
134
+ """
135
+ Close the current workbook.
136
+ """
137
+
138
+ if self.is_opened():
139
+ self.workbook.close() # type: ignore
140
+ self._workbook = None
141
+
142
+ def from_tabledata(self, value: TableData, is_overwrite_table_name: bool = True) -> None:
143
+ """
144
+ Set following attributes from |TableData|
145
+
146
+ - :py:attr:`~.table_name`.
147
+ - :py:attr:`~.headers`.
148
+ - :py:attr:`~.value_matrix`.
149
+
150
+ And create worksheet named from :py:attr:`~.table_name` ABC
151
+ if not existed yet.
152
+
153
+ :param tabledata.TableData value: Input table data.
154
+ """
155
+
156
+ super().from_tabledata(value)
157
+
158
+ if self.is_opened():
159
+ self.make_worksheet(self.table_name)
160
+
161
+ def make_worksheet(self, sheet_name: Optional[str] = None) -> None:
162
+ """Make a worksheet to the current workbook.
163
+
164
+ Args:
165
+ sheet_name (str):
166
+ Name of the worksheet to create. The name will be automatically generated
167
+ (like ``"Sheet1"``) if the ``sheet_name`` is empty.
168
+ """
169
+
170
+ if sheet_name is None:
171
+ sheet_name = self.table_name
172
+ if not sheet_name:
173
+ sheet_name = ""
174
+
175
+ self._stream = self.workbook.add_worksheet(sheet_name) # type: ignore
176
+ self._current_data_row = self._first_data_row
177
+
178
+ def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None:
179
+ """Write a worksheet to the current workbook.
180
+
181
+ Args:
182
+ output (str):
183
+ Path to the workbook file to write.
184
+ close_after_write (bool, optional):
185
+ Close the workbook after write.
186
+ Defaults to |True|.
187
+ """
188
+
189
+ if not isinstance(output, str):
190
+ raise TypeError(f"output must be a str: actual={type(output)}")
191
+
192
+ self.open(output)
193
+ try:
194
+ self.make_worksheet(self.table_name)
195
+ self.write_table(**kwargs)
196
+ finally:
197
+ if close_after_write:
198
+ self.close()
199
+
200
+ @abc.abstractmethod
201
+ def _write_header(self) -> None:
202
+ pass
203
+
204
+ @abc.abstractmethod
205
+ def _write_cell(self, row: int, col: int, value_dp: DataProperty) -> None:
206
+ pass
207
+
208
+ def _write_table(self, **kwargs: Any) -> None:
209
+ self._preprocess_table_dp()
210
+ self._preprocess_table_property()
211
+ self._write_header()
212
+ self._write_value_matrix()
213
+ self._postprocess()
214
+
215
+ def _write_value_matrix(self) -> None:
216
+ for value_dp_list in self._table_value_dp_matrix:
217
+ for col_idx, value_dp in enumerate(value_dp_list):
218
+ self._write_cell(self._current_data_row, col_idx, value_dp)
219
+
220
+ self._current_data_row += 1
221
+
222
+ def _get_last_column(self) -> int:
223
+ if typepy.is_not_empty_sequence(self.headers):
224
+ return len(self.headers) - 1
225
+
226
+ if typepy.is_not_empty_sequence(self.value_matrix):
227
+ return len(self.value_matrix[0]) - 1
228
+
229
+ raise ValueError("data not found")
230
+
231
+ def _postprocess(self) -> None:
232
+ self._last_data_row = self._current_data_row
233
+ self._last_data_col = self._get_last_column()
234
+
235
+
236
+ class ExcelXlsTableWriter(ExcelTableWriter):
237
+ """
238
+ A table writer class for Excel file format: ``.xls`` (older or equal to Office 2003).
239
+
240
+ ``xlwt`` package required to use this class.
241
+
242
+ .. py:method:: write_table()
243
+
244
+ Write a table to the current opened worksheet.
245
+
246
+ :raises IOError: If failed to write data to the worksheet.
247
+
248
+ .. note::
249
+ Specific values in the tabular data are converted when writing:
250
+
251
+ - |None|: written as an empty string
252
+ - |inf|: written as ``Inf``
253
+ - |nan|: written as ``NaN``
254
+ """
255
+
256
+ def __init__(self, **kwargs: Any) -> None:
257
+ super().__init__(**kwargs)
258
+
259
+ self.__col_style_table: Dict[int, Any] = {}
260
+
261
+ def _open(self, workbook_path: str) -> None:
262
+ self._workbook = ExcelWorkbookXls(workbook_path)
263
+
264
+ def _write_header(self) -> None:
265
+ if not self.is_write_header or typepy.is_empty_sequence(self.headers):
266
+ return
267
+
268
+ for col, value in enumerate(self.headers):
269
+ self.stream.write(self.first_header_row, col, value)
270
+
271
+ def _write_cell(self, row: int, col: int, value_dp: DataProperty) -> None:
272
+ if value_dp.typecode in [typepy.Typecode.REAL_NUMBER]:
273
+ try:
274
+ cell_style = self.__get_cell_style(col)
275
+ except ValueError:
276
+ pass
277
+ else:
278
+ self.stream.write(row, col, value_dp.data, cell_style)
279
+ return
280
+
281
+ self.stream.write(row, col, value_dp.data)
282
+
283
+ def _postprocess(self) -> None:
284
+ super()._postprocess()
285
+
286
+ self.__col_style_table = {}
287
+
288
+ def __get_cell_style(self, col: int) -> "XFStyle":
289
+ try:
290
+ import xlwt
291
+ except ImportError:
292
+ warnings.warn(import_error_msg_template.format("excel"))
293
+ raise
294
+
295
+ if col in self.__col_style_table:
296
+ return self.__col_style_table.get(col)
297
+
298
+ try:
299
+ col_dp = self._column_dp_list[col]
300
+ except KeyError:
301
+ return {}
302
+
303
+ if col_dp.typecode not in [typepy.Typecode.REAL_NUMBER]:
304
+ raise ValueError()
305
+
306
+ if not Integer(col_dp.minmax_decimal_places.max_value).is_type():
307
+ raise ValueError()
308
+
309
+ float_digit = col_dp.minmax_decimal_places.max_value
310
+ if float_digit <= 0:
311
+ raise ValueError()
312
+
313
+ num_format_str = "#,{:s}0.{:s}".format("#" * int(float_digit), "0" * int(float_digit))
314
+ cell_style = xlwt.easyxf(num_format_str=num_format_str)
315
+ self.__col_style_table[col] = cell_style
316
+
317
+ return cell_style
318
+
319
+
320
+ class ExcelXlsxTableWriter(ExcelTableWriter):
321
+ """
322
+ A table writer class for Excel file format: ``.xlsx`` (newer or equal to Office 2007).
323
+
324
+ .. py:method:: write_table()
325
+
326
+ Write a table to the current opened worksheet.
327
+
328
+ :raises IOError: If failed to write data to the worksheet.
329
+
330
+ Examples:
331
+ :ref:`example-excel-table-writer`
332
+
333
+ .. note::
334
+ Specific values in the tabular data are converted when writing:
335
+
336
+ - |None|: written as an empty string
337
+ - |inf|: written as ``Inf``
338
+ - |nan|: written as ``NaN``
339
+ """
340
+
341
+ MAX_CELL_WIDTH: ClassVar[int] = 60
342
+
343
+ class TableFormat:
344
+ HEADER = "header"
345
+ CELL = "cell"
346
+ NAN = "nan"
347
+
348
+ class Default:
349
+ FONT_NAME: ClassVar[str] = "MS Gothic"
350
+ FONT_SIZE: ClassVar[int] = 9
351
+
352
+ CELL_FORMAT: Dict[str, Union[int, str, bool]] = {
353
+ "font_name": FONT_NAME,
354
+ "font_size": FONT_SIZE,
355
+ "align": "top",
356
+ "text_wrap": True,
357
+ "top": 1,
358
+ "left": 1,
359
+ "bottom": 1,
360
+ "right": 1,
361
+ }
362
+ HEADER_FORMAT: Dict[str, Union[int, str, bool]] = {
363
+ "font_name": FONT_NAME,
364
+ "font_size": FONT_SIZE,
365
+ "bg_color": "#DFDFFF",
366
+ "bold": True,
367
+ "left": 1,
368
+ "right": 1,
369
+ }
370
+ NAN_FORMAT: Dict[str, Union[int, str, bool]] = {
371
+ "font_name": FONT_NAME,
372
+ "font_size": FONT_SIZE,
373
+ "font_color": "silver",
374
+ "top": 1,
375
+ "left": 1,
376
+ "bottom": 1,
377
+ "right": 1,
378
+ }
379
+
380
+ @property
381
+ def __nan_format_property(self) -> Dict[str, Union[int, str, bool]]:
382
+ return self.format_table.get(self.TableFormat.NAN, self.default_format)
383
+
384
+ @property
385
+ def __cell_format_property(self) -> Dict[str, Union[int, str, bool]]:
386
+ return self.format_table.get(self.TableFormat.CELL, self.default_format)
387
+
388
+ def __init__(self, **kwargs: Any) -> None:
389
+ super().__init__(**kwargs)
390
+
391
+ self.default_format = self.Default.CELL_FORMAT
392
+ self.format_table = {
393
+ self.TableFormat.CELL: self.Default.CELL_FORMAT,
394
+ self.TableFormat.HEADER: self.Default.HEADER_FORMAT,
395
+ self.TableFormat.NAN: self.Default.NAN_FORMAT,
396
+ }
397
+
398
+ self.__col_cell_format_cache: Dict[int, Any] = {}
399
+ self.__col_numprops_table: Dict[int, Dict[str, str]] = {}
400
+
401
+ def _open(self, workbook_path: str) -> None:
402
+ self._workbook = ExcelWorkbookXlsx(workbook_path)
403
+
404
+ def _write_header(self) -> None:
405
+ if not self.is_write_header or typepy.is_empty_sequence(self.headers):
406
+ return
407
+
408
+ header_format_props = self.format_table.get(self.TableFormat.HEADER, self.default_format)
409
+ header_format = self.__add_format(header_format_props)
410
+
411
+ self.stream.write_row(
412
+ row=self.first_header_row, col=0, data=self.headers, cell_format=header_format
413
+ )
414
+ for row in range(self.first_header_row, self.last_header_row):
415
+ self.stream.write_row(
416
+ row=row, col=0, data=[""] * len(self.headers), cell_format=header_format
417
+ )
418
+
419
+ def _write_cell(self, row: int, col: int, value_dp: DataProperty) -> None:
420
+ base_props = dict(self.__cell_format_property)
421
+ format_key = f"{col:d}_{value_dp.typecode.name:s}"
422
+
423
+ if value_dp.typecode in [typepy.Typecode.INTEGER, typepy.Typecode.REAL_NUMBER]:
424
+ num_props = self.__get_number_property(col)
425
+ base_props.update(num_props)
426
+ cell_format = self.__get_cell_format(format_key, base_props)
427
+
428
+ try:
429
+ self.stream.write_number(row, col, float(value_dp.data), cell_format)
430
+ return
431
+ except TypeError:
432
+ pass
433
+
434
+ if value_dp.typecode is typepy.Typecode.NAN:
435
+ base_props = dict(self.__nan_format_property)
436
+
437
+ cell_format = self.__get_cell_format(format_key, base_props)
438
+ self.stream.write(row, col, value_dp.data, cell_format)
439
+
440
+ def __get_number_property(self, col: int) -> Dict[str, str]:
441
+ if col in self.__col_numprops_table:
442
+ return self.__col_numprops_table[col]
443
+
444
+ try:
445
+ col_dp = self._column_dp_list[col]
446
+ except KeyError:
447
+ return {}
448
+
449
+ if col_dp.typecode not in [typepy.Typecode.INTEGER, typepy.Typecode.REAL_NUMBER]:
450
+ return {}
451
+
452
+ num_props = {}
453
+ if Integer(col_dp.minmax_decimal_places.max_value).is_type():
454
+ float_digit = col_dp.minmax_decimal_places.max_value
455
+ if float_digit > 0:
456
+ num_props = {"num_format": "0.{:s}".format("0" * int(float_digit))}
457
+
458
+ self.__col_numprops_table[col] = num_props
459
+
460
+ return num_props
461
+
462
+ def __get_cell_format(self, format_key, cell_props) -> Dict: # type: ignore
463
+ cell_format = self.__col_cell_format_cache.get(format_key)
464
+ if cell_format is not None:
465
+ return cell_format
466
+
467
+ # cache miss
468
+ cell_format = self.__add_format(cell_props)
469
+ self.__col_cell_format_cache[format_key] = cell_format
470
+
471
+ return cell_format
472
+
473
+ def __add_format(self, dict_property): # type: ignore
474
+ assert self.workbook
475
+ return self.workbook.workbook.add_format(dict_property)
476
+
477
+ def __set_cell_width(self) -> None:
478
+ font_size = cast(int, self.__cell_format_property.get("font_size"))
479
+
480
+ if not Integer(font_size).is_type():
481
+ return
482
+
483
+ for col_idx, col_dp in enumerate(self._column_dp_list):
484
+ width = min(col_dp.ascii_char_width, self.MAX_CELL_WIDTH) * (font_size / 10.0) + 2
485
+ self.stream.set_column(col_idx, col_idx, width=width)
486
+
487
+ def _preprocess_table_property(self) -> None:
488
+ super()._preprocess_table_property()
489
+
490
+ self.__set_cell_width()
491
+
492
+ def _postprocess(self) -> None:
493
+ super()._postprocess()
494
+
495
+ self.stream.autofilter(
496
+ self.last_header_row, self.first_data_col, self.last_data_row, self.last_data_col
497
+ )
498
+ self.stream.freeze_panes(self.first_data_row, self.first_data_col)
499
+
500
+ self.__col_cell_format_cache = {}
501
+ self.__col_numprops_table = {}
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_excel_workbook.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import warnings
3
+ from typing import Any, Dict, Optional
4
+
5
+ import typepy
6
+
7
+ from ..._logger import logger
8
+ from ...sanitizer import sanitize_excel_sheet_name
9
+ from .._common import import_error_msg_template
10
+ from .._msgfy import to_error_message
11
+
12
+
13
+ class ExcelWorkbookInterface(metaclass=abc.ABCMeta):
14
+ @abc.abstractproperty
15
+ def workbook(self) -> Any: # pragma: no cover
16
+ pass
17
+
18
+ @abc.abstractproperty
19
+ def file_path(self) -> Optional[str]: # pragma: no cover
20
+ pass
21
+
22
+ @abc.abstractmethod
23
+ def open(self, file_path: str) -> None: # pragma: no cover
24
+ pass
25
+
26
+ @abc.abstractmethod
27
+ def close(self) -> None: # pragma: no cover
28
+ pass
29
+
30
+ @abc.abstractmethod
31
+ def add_worksheet(self, worksheet_name: Optional[str]) -> Any: # pragma: no cover
32
+ pass
33
+
34
+
35
+ class ExcelWorkbook(ExcelWorkbookInterface):
36
+ @property
37
+ def workbook(self) -> Any:
38
+ return self._workbook
39
+
40
+ @property
41
+ def file_path(self) -> Optional[str]:
42
+ return self._file_path
43
+
44
+ def _clear(self) -> None:
45
+ self._workbook = None
46
+ self._file_path: Optional[str] = None
47
+ self._worksheet_table: Dict[str, Any] = {}
48
+
49
+ def __init__(self, file_path: str) -> None:
50
+ self._clear()
51
+ self._file_path = file_path
52
+
53
+ def __del__(self) -> None:
54
+ self.close()
55
+
56
+
57
+ class ExcelWorkbookXls(ExcelWorkbook):
58
+ def __init__(self, file_path: str) -> None:
59
+ super().__init__(file_path)
60
+
61
+ self.open(file_path)
62
+
63
+ def open(self, file_path: str) -> None:
64
+ try:
65
+ import xlwt
66
+ except ImportError:
67
+ warnings.warn(import_error_msg_template.format("excel"))
68
+ raise
69
+
70
+ self._workbook = xlwt.Workbook()
71
+
72
+ def close(self) -> None:
73
+ if self.workbook is None:
74
+ return
75
+
76
+ try:
77
+ self.workbook.save(self._file_path)
78
+ except IndexError as e:
79
+ logger.debug(to_error_message(e))
80
+
81
+ self._clear()
82
+
83
+ def add_worksheet(self, worksheet_name: Optional[str]) -> Any:
84
+ if typepy.is_not_null_string(worksheet_name):
85
+ assert worksheet_name
86
+ worksheet_name = sanitize_excel_sheet_name(worksheet_name)
87
+ if worksheet_name in self._worksheet_table:
88
+ # the work sheet is already exists
89
+ return self._worksheet_table.get(worksheet_name)
90
+ else:
91
+ sheet_id = 1
92
+ while True:
93
+ worksheet_name = f"Sheet{sheet_id:d}"
94
+ if worksheet_name not in self._worksheet_table:
95
+ break
96
+ sheet_id += 1
97
+
98
+ worksheet = self.workbook.add_sheet(worksheet_name)
99
+ self._worksheet_table[worksheet.get_name()] = worksheet
100
+
101
+ return worksheet
102
+
103
+
104
+ class ExcelWorkbookXlsx(ExcelWorkbook):
105
+ def __init__(self, file_path: str) -> None:
106
+ super().__init__(file_path)
107
+
108
+ self.open(file_path)
109
+
110
+ def open(self, file_path: str) -> None:
111
+ try:
112
+ import xlsxwriter
113
+ except ImportError:
114
+ warnings.warn(import_error_msg_template.format("excel"))
115
+ raise
116
+
117
+ self._workbook = xlsxwriter.Workbook(file_path)
118
+
119
+ def close(self) -> None:
120
+ if self.workbook is None:
121
+ return
122
+
123
+ self._workbook.close() # type: ignore
124
+ self._clear()
125
+
126
+ def add_worksheet(self, worksheet_name: Optional[str]) -> Any:
127
+ if typepy.is_not_null_string(worksheet_name):
128
+ assert worksheet_name
129
+ worksheet_name = sanitize_excel_sheet_name(worksheet_name)
130
+ if worksheet_name in self._worksheet_table:
131
+ # the work sheet is already exists
132
+ return self._worksheet_table.get(worksheet_name)
133
+ else:
134
+ worksheet_name = None
135
+
136
+ worksheet = self.workbook.add_worksheet(worksheet_name)
137
+ self._worksheet_table[worksheet.get_name()] = worksheet
138
+
139
+ return worksheet
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_interface.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ from typing import Any
3
+
4
+ from .._table_writer import AbstractTableWriter
5
+
6
+
7
+ class BinaryWriterInterface(metaclass=abc.ABCMeta):
8
+ @abc.abstractmethod
9
+ def is_opened(self) -> bool: # pragma: no cover
10
+ pass
11
+
12
+ @abc.abstractmethod
13
+ def open(self, file_path: str) -> None: # pragma: no cover
14
+ """
15
+ Open a file for output stream.
16
+
17
+ Args:
18
+ file_path (str): path to the file.
19
+ """
20
+
21
+
22
+ class AbstractBinaryTableWriter(AbstractTableWriter, BinaryWriterInterface):
23
+ @property
24
+ def stream(self) -> Any:
25
+ return self._stream
26
+
27
+ @stream.setter
28
+ def stream(self, value: Any) -> None:
29
+ raise RuntimeError(
30
+ "cannot assign a stream to binary format writers. use open method instead."
31
+ )
32
+
33
+ @property
34
+ def support_split_write(self) -> bool:
35
+ return True
36
+
37
+ def __init__(self, **kwargs: Any) -> None:
38
+ super().__init__(**kwargs)
39
+
40
+ self.table_name = kwargs.get("table_name", "")
41
+
42
+ self._stream = None
43
+
44
+ def __del__(self) -> None:
45
+ self.close()
46
+
47
+ def is_opened(self) -> bool:
48
+ return self.stream is not None
49
+
50
+ def dumps(self) -> str:
51
+ raise NotImplementedError("binary format writers did not support dumps method")
52
+
53
+ def _verify_stream(self) -> None:
54
+ if self.stream is None:
55
+ raise OSError("null output stream. required to open(file_path) first.")
56
+
57
+ def _write_value_row_separator(self) -> None:
58
+ pass
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_pandas.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import IO, Any, Optional, Union
2
+
3
+ import tabledata
4
+
5
+ from ...error import EmptyValueError
6
+ from ._interface import AbstractBinaryTableWriter
7
+
8
+
9
+ class PandasDataFramePickleWriter(AbstractBinaryTableWriter):
10
+ """
11
+ A table writer class for pandas DataFrame pickle.
12
+
13
+ .. py:method:: write_table()
14
+
15
+ Write a table to a pandas DataFrame pickle file.
16
+ """
17
+
18
+ FORMAT_NAME = "pandas_pickle"
19
+
20
+ @property
21
+ def format_name(self) -> str:
22
+ return self.FORMAT_NAME
23
+
24
+ @property
25
+ def support_split_write(self) -> bool:
26
+ return False
27
+
28
+ def __init__(self, **kwargs: Any) -> None:
29
+ import copy
30
+
31
+ import dataproperty
32
+
33
+ super().__init__(**kwargs)
34
+
35
+ self.is_padding = False
36
+ self.is_formatting_float = False
37
+ self._use_default_header = True
38
+
39
+ self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
40
+
41
+ self.__filepath: Optional[str] = None
42
+
43
+ def is_opened(self) -> bool:
44
+ return self.__filepath is not None
45
+
46
+ def open(self, file_path: str) -> None:
47
+ self.__filepath = file_path
48
+
49
+ def close(self) -> None:
50
+ super().close()
51
+ self.__filepath = None
52
+
53
+ def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None:
54
+ """Write data to a DataFrame pickle file.
55
+
56
+ Args:
57
+ output (str): Path to an output DataFrame pickle file.
58
+ """
59
+
60
+ if not isinstance(output, str):
61
+ raise TypeError(f"output must be a str: actual={type(output)}")
62
+
63
+ self.open(output)
64
+ try:
65
+ self.write_table(**kwargs)
66
+ finally:
67
+ if close_after_write:
68
+ self.close()
69
+
70
+ def _verify_stream(self) -> None:
71
+ pass
72
+
73
+ def _write_table(self, **kwargs: Any) -> None:
74
+ if not self.is_opened():
75
+ self._logger.logger.error("required to open(file_path) first.")
76
+ return
77
+
78
+ try:
79
+ self._verify_value_matrix()
80
+ except EmptyValueError:
81
+ self._logger.logger.debug("no tabular data found")
82
+ return
83
+
84
+ self._preprocess()
85
+
86
+ table_data = tabledata.TableData(
87
+ self.table_name,
88
+ self.headers,
89
+ [
90
+ [value_dp.data for value_dp in value_dp_list]
91
+ for value_dp_list in self._table_value_dp_matrix
92
+ ],
93
+ type_hints=self.type_hints,
94
+ max_workers=self.max_workers,
95
+ )
96
+ table_data.as_dataframe().to_pickle(self.__filepath)
97
+
98
+ def _write_table_iter(self, **kwargs: Any) -> None:
99
+ self._write_table(**kwargs)
venv/lib/python3.10/site-packages/pytablewriter/writer/binary/_sqlite.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os.path import abspath
2
+ from typing import IO, Any, Union
3
+
4
+ import tabledata
5
+
6
+ from ...error import EmptyValueError
7
+ from ._interface import AbstractBinaryTableWriter
8
+
9
+
10
+ class SqliteTableWriter(AbstractBinaryTableWriter):
11
+ """
12
+ A table writer class for `SQLite <https://www.sqlite.org/index.html>`__ database.
13
+
14
+ .. py:method:: write_table()
15
+
16
+ Write a table to a `SQLite <https://www.sqlite.org/index.html>`__ database.
17
+
18
+ :raises pytablewriter.EmptyTableNameError:
19
+ If the |table_name| is empty.
20
+ :Example:
21
+ :ref:`example-sqlite-table-writer`
22
+ """
23
+
24
+ FORMAT_NAME = "sqlite"
25
+
26
+ @property
27
+ def format_name(self) -> str:
28
+ return self.FORMAT_NAME
29
+
30
+ def __init__(self, **kwargs: Any) -> None:
31
+ import copy
32
+
33
+ import dataproperty
34
+
35
+ super().__init__(**kwargs)
36
+
37
+ self.is_padding = False
38
+ self.is_formatting_float = False
39
+ self._use_default_header = True
40
+
41
+ self._is_require_table_name = True
42
+ self._is_require_header = True
43
+
44
+ self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
45
+
46
+ def open(self, file_path: str) -> None:
47
+ """
48
+ Open a SQLite database file.
49
+
50
+ :param str file_path: SQLite database file path to open.
51
+ """
52
+
53
+ from simplesqlite import SimpleSQLite
54
+
55
+ if self.is_opened():
56
+ if self.stream.database_path == abspath(file_path):
57
+ self._logger.logger.debug(f"database already opened: {self.stream.database_path}")
58
+ return
59
+
60
+ self.close()
61
+
62
+ self._stream = SimpleSQLite(file_path, "w", max_workers=self.max_workers)
63
+
64
+ def dump(self, output: Union[str, IO], close_after_write: bool = True, **kwargs: Any) -> None:
65
+ """Write data to the SQLite database file.
66
+
67
+ Args:
68
+ output (str):
69
+ path to the output SQLite database file.
70
+ close_after_write (bool, optional):
71
+ Close the output after write.
72
+ Defaults to |True|.
73
+ """
74
+
75
+ if not isinstance(output, str):
76
+ raise TypeError(f"output must be a str: actual={type(output)}")
77
+
78
+ self.open(output)
79
+ try:
80
+ self.write_table(**kwargs)
81
+ finally:
82
+ if close_after_write:
83
+ self.close()
84
+
85
+ def _write_table(self, **kwargs: Any) -> None:
86
+ try:
87
+ self._verify_value_matrix()
88
+ except EmptyValueError:
89
+ self._logger.logger.debug("no tabular data found")
90
+ return
91
+
92
+ self._preprocess()
93
+
94
+ table_data = tabledata.TableData(
95
+ self.table_name,
96
+ self.headers,
97
+ [
98
+ [value_dp.data for value_dp in value_dp_list]
99
+ for value_dp_list in self._table_value_dp_matrix
100
+ ],
101
+ type_hints=self.type_hints,
102
+ max_workers=self.max_workers,
103
+ )
104
+ self.stream.create_table_from_tabledata(table_data)
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__init__.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._asciidoc import AsciiDocTableWriter
2
+ from ._borderless import BorderlessTableWriter
3
+ from ._css import CssTableWriter
4
+ from ._csv import CsvTableWriter
5
+ from ._html import HtmlTableWriter
6
+ from ._json import JsonTableWriter
7
+ from ._jsonlines import JsonLinesTableWriter
8
+ from ._latex import LatexMatrixWriter, LatexTableWriter
9
+ from ._ltsv import LtsvTableWriter
10
+ from ._markdown import MarkdownFlavor, MarkdownTableWriter, normalize_md_flavor
11
+ from ._mediawiki import MediaWikiTableWriter
12
+ from ._rst import RstCsvTableWriter, RstGridTableWriter, RstSimpleTableWriter
13
+ from ._spacealigned import SpaceAlignedTableWriter
14
+ from ._toml import TomlTableWriter
15
+ from ._tsv import TsvTableWriter
16
+ from ._unicode import BoldUnicodeTableWriter, UnicodeTableWriter
17
+ from ._yaml import YamlTableWriter
18
+
19
+
20
+ __all__ = (
21
+ "AsciiDocTableWriter",
22
+ "BoldUnicodeTableWriter",
23
+ "BorderlessTableWriter",
24
+ "CssTableWriter",
25
+ "CsvTableWriter",
26
+ "HtmlTableWriter",
27
+ "JsonTableWriter",
28
+ "JsonLinesTableWriter",
29
+ "LatexMatrixWriter",
30
+ "LatexTableWriter",
31
+ "LtsvTableWriter",
32
+ "MarkdownFlavor",
33
+ "MarkdownTableWriter",
34
+ "normalize_md_flavor",
35
+ "MediaWikiTableWriter",
36
+ "RstCsvTableWriter",
37
+ "RstGridTableWriter",
38
+ "RstSimpleTableWriter",
39
+ "SpaceAlignedTableWriter",
40
+ "TomlTableWriter",
41
+ "TsvTableWriter",
42
+ "UnicodeTableWriter",
43
+ "YamlTableWriter",
44
+ )
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.33 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_common.cpython-310.pyc ADDED
Binary file (822 Bytes). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_css.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_csv.cpython-310.pyc ADDED
Binary file (2.51 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_interface.cpython-310.pyc ADDED
Binary file (1.38 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_latex.cpython-310.pyc ADDED
Binary file (7.85 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_ltsv.cpython-310.pyc ADDED
Binary file (2.22 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_markdown.cpython-310.pyc ADDED
Binary file (7.17 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_mediawiki.cpython-310.pyc ADDED
Binary file (4.48 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_spacealigned.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_text_writer.cpython-310.pyc ADDED
Binary file (20.5 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_tsv.cpython-310.pyc ADDED
Binary file (1.02 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_yaml.cpython-310.pyc ADDED
Binary file (2.79 kB). View file
 
venv/lib/python3.10/site-packages/pytablewriter/writer/text/_asciidoc.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Any, List, Sequence
3
+
4
+ import dataproperty as dp
5
+ import typepy
6
+ from dataproperty import ColumnDataProperty, DataProperty, LineBreakHandling
7
+ from mbstrdecoder import MultiByteStrDecoder
8
+
9
+ from ...style import (
10
+ Align,
11
+ FontStyle,
12
+ FontWeight,
13
+ Style,
14
+ StylerInterface,
15
+ TextStyler,
16
+ get_align_char,
17
+ )
18
+ from .._table_writer import AbstractTableWriter
19
+ from ._text_writer import TextTableWriter
20
+
21
+
22
+ class AsciiDocStyler(TextStyler):
23
+ def apply(self, value: str, style: Style) -> str:
24
+ value = super().apply(value, style)
25
+ if not value:
26
+ return value
27
+
28
+ try:
29
+ fg_color = style.fg_color.name.lower() # type: ignore
30
+ except AttributeError:
31
+ fg_color = None
32
+
33
+ try:
34
+ bg_color = style.bg_color.name.lower() # type: ignore
35
+ except AttributeError:
36
+ bg_color = None
37
+
38
+ if fg_color and bg_color:
39
+ value = f"[{fg_color} {bg_color}-background]##{value}##"
40
+ elif fg_color:
41
+ value = f"[{fg_color}]##{value}##"
42
+ elif bg_color:
43
+ value = f"[{bg_color}-background]##{value}##"
44
+
45
+ if style.font_weight == FontWeight.BOLD:
46
+ value = f"*{value}*"
47
+
48
+ if style.font_style == FontStyle.ITALIC:
49
+ value = f"_{value}_"
50
+
51
+ return value
52
+
53
+
54
+ class AsciiDocTableWriter(TextTableWriter):
55
+ """
56
+ A table writer class for `AsciiDoc <https://asciidoc.org/>`__ format.
57
+ """
58
+
59
+ FORMAT_NAME = "asciidoc"
60
+
61
+ @property
62
+ def format_name(self) -> str:
63
+ return self.FORMAT_NAME
64
+
65
+ @property
66
+ def support_split_write(self) -> bool:
67
+ return True
68
+
69
+ def __init__(self, **kwargs: Any) -> None:
70
+ super().__init__(**kwargs)
71
+
72
+ self.column_delimiter = "\n"
73
+
74
+ self.is_padding = False
75
+ self.is_write_header_separator_row = True
76
+ self.is_write_value_separator_row = True
77
+ self.is_write_opening_row = True
78
+ self.is_write_closing_row = True
79
+
80
+ self.update_preprocessor(line_break_handling=LineBreakHandling.NOP)
81
+
82
+ self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS)
83
+
84
+ def _create_styler(self, writer: AbstractTableWriter) -> StylerInterface:
85
+ return AsciiDocStyler(writer)
86
+
87
+ def _write_value_row(
88
+ self, row: int, values: Sequence[str], value_dp_list: Sequence[DataProperty]
89
+ ) -> None:
90
+ self._write_row(
91
+ row,
92
+ [
93
+ self.__modify_row_element(row, col_idx, value, value_dp)
94
+ for col_idx, (value, value_dp), in enumerate(zip(values, value_dp_list))
95
+ ],
96
+ )
97
+
98
+ def _get_opening_row_items(self) -> List[str]:
99
+ cols = ", ".join(
100
+ f"{get_align_char(col_dp.align)}{col_dp.ascii_char_width}"
101
+ for col_dp in self._column_dp_list
102
+ )
103
+ rows = [f'[cols="{cols}", options="header"]']
104
+
105
+ if typepy.is_not_null_string(self.table_name):
106
+ rows.append("." + MultiByteStrDecoder(self.table_name).unicode_str)
107
+
108
+ rows.append("|===")
109
+
110
+ return ["\n".join(rows)]
111
+
112
+ def _get_header_row_separator_items(self) -> List[str]:
113
+ return [""]
114
+
115
+ def _get_value_row_separator_items(self) -> List[str]:
116
+ return self._get_header_row_separator_items()
117
+
118
+ def _get_closing_row_items(self) -> List[str]:
119
+ return ["|==="]
120
+
121
+ def __apply_align(self, value: str, style: Style) -> str:
122
+ return f"{get_align_char(Align.CENTER)}|{value}"
123
+
124
+ def _apply_style_to_header_item(
125
+ self, col_dp: ColumnDataProperty, value_dp: DataProperty, style: Style
126
+ ) -> str:
127
+ value = self._styler.apply(col_dp.dp_to_str(value_dp), style=style)
128
+ return self.__apply_align(value, style)
129
+
130
+ def __modify_row_element(
131
+ self, row_idx: int, col_idx: int, value: str, value_dp: DataProperty
132
+ ) -> str:
133
+ col_dp = self._column_dp_list[col_idx]
134
+ style = self._fetch_style(row_idx, col_dp, value_dp)
135
+ align = col_dp.align
136
+
137
+ if style and style.align and style.align != align:
138
+ forma_stirng = "{0:s}|{1:s}"
139
+ align = style.align
140
+ elif value_dp.align != align:
141
+ forma_stirng = "{0:s}|{1:s}"
142
+ align = value_dp.align
143
+ else:
144
+ forma_stirng = "|{1:s}"
145
+
146
+ return forma_stirng.format(get_align_char(align), value)
venv/lib/python3.10/site-packages/pytablewriter/writer/text/_borderless.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Any
3
+
4
+ import dataproperty as dp
5
+
6
+ from ._text_writer import IndentationTextTableWriter
7
+
8
+
9
+ class BorderlessTableWriter(IndentationTextTableWriter):
10
+ """
11
+ A table writer class for borderless table.
12
+ """
13
+
14
+ FORMAT_NAME = "borderless"
15
+
16
+ @property
17
+ def format_name(self) -> str:
18
+ return self.FORMAT_NAME
19
+
20
+ @property
21
+ def support_split_write(self) -> bool:
22
+ return True
23
+
24
+ def __init__(self, **kwargs: Any) -> None:
25
+ super().__init__(**kwargs)
26
+
27
+ self.table_name = ""
28
+
29
+ self.column_delimiter = ""
30
+ self.char_left_side_row = ""
31
+ self.char_right_side_row = ""
32
+
33
+ self.indent_string = kwargs.get("indent_string", " ")
34
+ self.is_write_header_separator_row = False
35
+ self.is_write_value_separator_row = False
36
+ self.is_write_opening_row = False
37
+ self.is_write_closing_row = False
38
+
39
+ self._quoting_flags = copy.deepcopy(dp.NOT_QUOTING_FLAGS)
40
+
41
+ self._init_cross_point_maps()
venv/lib/python3.10/site-packages/pytablewriter/writer/text/_common.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from decimal import Decimal
2
+ from typing import Any
3
+
4
+ from dataproperty import DataProperty
5
+ from typepy import Typecode
6
+
7
+
8
+ def bool_to_str(value: Any) -> Any:
9
+ if value is True:
10
+ return "true"
11
+ if value is False:
12
+ return "false"
13
+
14
+ return value
15
+
16
+
17
+ def serialize_dp(dp: DataProperty) -> Any:
18
+ if dp.typecode in (Typecode.REAL_NUMBER, Typecode.INFINITY, Typecode.NAN) and isinstance(
19
+ dp.data, Decimal
20
+ ):
21
+ return float(dp.data)
22
+
23
+ if dp.typecode == Typecode.DATETIME:
24
+ return dp.to_str()
25
+
26
+ return dp.data
venv/lib/python3.10/site-packages/pytablewriter/writer/text/_css.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Any, List, cast
3
+
4
+ from dataproperty import NOT_QUOTING_FLAGS, DataProperty
5
+ from pathvalidate import replace_symbol
6
+
7
+ from ...error import EmptyTableDataError
8
+ from ...style import Align, DecorationLine, FontStyle, FontWeight, Style, VerticalAlign
9
+ from .._common import HEADER_ROW
10
+ from ._text_writer import IndentationTextTableWriter
11
+
12
+
13
+ class CssTableWriter(IndentationTextTableWriter):
14
+ """
15
+ A CSS writer class.
16
+ """
17
+
18
+ FORMAT_NAME = "css"
19
+ MARGIN_PIXEL = 6
20
+
21
+ @property
22
+ def format_name(self) -> str:
23
+ return self.FORMAT_NAME
24
+
25
+ @property
26
+ def support_split_write(self) -> bool:
27
+ return False
28
+
29
+ def __init__(self, **kwargs: Any) -> None:
30
+ super().__init__(**kwargs)
31
+
32
+ self.is_padding = False
33
+ self.indent_string = kwargs.get("indent_string", " ")
34
+
35
+ self._dp_extractor.preprocessor.is_escape_html_tag = False
36
+ self._quoting_flags = copy.deepcopy(NOT_QUOTING_FLAGS)
37
+
38
+ def write_table(self, **kwargs: Any) -> None:
39
+ """
40
+ |write_table| with CSS.
41
+ """
42
+
43
+ with self._logger:
44
+ try:
45
+ self._verify_property()
46
+ except EmptyTableDataError:
47
+ self._logger.logger.debug("no tabular data found")
48
+ return
49
+
50
+ self._preprocess()
51
+
52
+ self.__write_css(
53
+ css_class=replace_symbol(self.table_name, replacement_text="-"),
54
+ write_style_tag=kwargs.get("write_style_tag", False),
55
+ )
56
+
57
+ def __extract_css_tags(self, value_dp: DataProperty, style: Style) -> List[str]:
58
+ css_tags: List[str] = []
59
+
60
+ if self._styler.get_font_size(style):
61
+ css_tags.append(cast(str, self._styler.get_font_size(style)))
62
+ if style.font_weight == FontWeight.BOLD:
63
+ css_tags.append("font-weight:bold")
64
+ if style.font_style == FontStyle.ITALIC:
65
+ css_tags.append("font-style:italic")
66
+
67
+ if style.color:
68
+ css_tags.append(f"color: {style.color.color_code}")
69
+
70
+ if style.bg_color:
71
+ css_tags.append(f"background-color: {style.bg_color.color_code}")
72
+
73
+ css_tag = self.__extract_align_tag(value_dp, style)
74
+ if css_tag:
75
+ css_tags.append(css_tag)
76
+
77
+ if style.vertical_align != VerticalAlign.BASELINE:
78
+ css_tags.append(f"vertical-align: {style.vertical_align.align_str}")
79
+
80
+ if style.decoration_line in (DecorationLine.LINE_THROUGH, DecorationLine.STRIKE):
81
+ css_tags.append("text-decoration-line: line-through")
82
+ elif style.decoration_line == DecorationLine.UNDERLINE:
83
+ css_tags.append("text-decoration-line: underline")
84
+
85
+ if self.margin > 0:
86
+ css_tags.append(f"padding: {self.margin * self.MARGIN_PIXEL}px")
87
+
88
+ return css_tags
89
+
90
+ def __extract_align_tag(self, value_dp: DataProperty, style: Style) -> str:
91
+ if style.align == Align.AUTO:
92
+ value = value_dp.align.align_string
93
+ else:
94
+ value = style.align.align_string
95
+
96
+ return f"text-align: {value}"
97
+
98
+ def __write_css_thead(self, css_class: str, base_indent_level: int) -> None:
99
+ for col_dp, header_dp in zip(self._column_dp_list, self._dp_extractor.to_header_dp_list()):
100
+ style = self._fetch_style(HEADER_ROW, col_dp, header_dp)
101
+ css_tags = self.__extract_css_tags(header_dp, style)
102
+
103
+ if not css_tags:
104
+ continue
105
+
106
+ self.set_indent_level(base_indent_level)
107
+ self._write_line(
108
+ ".{css_class} thead th:nth-child({col}) {{".format(
109
+ css_class=css_class, col=col_dp.column_index + 1
110
+ )
111
+ )
112
+
113
+ self.set_indent_level(base_indent_level + 1)
114
+ for css_tag in css_tags:
115
+ self._write_line(f"{css_tag};")
116
+
117
+ self.set_indent_level(base_indent_level)
118
+ self._write_line("}")
119
+
120
+ def __write_css_tbody(self, css_class: str, base_indent_level: int) -> None:
121
+ for row_idx, (values, value_dp_list) in enumerate(
122
+ zip(self._table_value_matrix, self._table_value_dp_matrix)
123
+ ):
124
+ for value, value_dp, col_dp in zip(values, value_dp_list, self._column_dp_list):
125
+ style = self._fetch_style(row_idx, col_dp, value_dp)
126
+ css_tags = self.__extract_css_tags(value_dp, style)
127
+
128
+ if not css_tags:
129
+ continue
130
+
131
+ self.set_indent_level(base_indent_level)
132
+ self._write_line(
133
+ ".{css_class} tbody tr:nth-child({row}) td:nth-child({col}) {{".format(
134
+ css_class=css_class, row=row_idx + 1, col=col_dp.column_index + 1
135
+ )
136
+ )
137
+
138
+ self.set_indent_level(base_indent_level + 1)
139
+ for css_tag in css_tags:
140
+ self._write_line(f"{css_tag};")
141
+
142
+ self.set_indent_level(base_indent_level)
143
+ self._write_line("}")
144
+
145
+ def __write_css(self, css_class: str, write_style_tag: bool = False) -> None:
146
+ base_indent_level = 0
147
+
148
+ if write_style_tag:
149
+ self._write_line('<style type="text/css">')
150
+ base_indent_level = 1
151
+
152
+ self.__write_css_thead(css_class, base_indent_level)
153
+ self.__write_css_tbody(css_class, base_indent_level)
154
+
155
+ if write_style_tag:
156
+ self.set_indent_level(0)
157
+ self._write_line("</style>")