anyconv-table-basic 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """Basic table conversion module for AnyConv."""
2
+
3
+ from .module import TableModule
4
+
5
+ __all__ = ["TableModule"]
@@ -0,0 +1,51 @@
1
+ spec: "^1.0"
2
+ api: ">=1.0,<2.0"
3
+ id: com.gitlab.raceozr.table-basic
4
+ version: 1.0.1
5
+ title:
6
+ en: "Basic tables"
7
+ ru: "Базовые таблицы"
8
+ description:
9
+ en: "Convert XLSX, ODS, CSV, TSV and JSON tables."
10
+ ru: "Конвертация таблиц XLSX, ODS, CSV, TSV и JSON."
11
+ license: MIT
12
+ homepage: "https://gitlab.com/anyconv/anyconv-modules"
13
+ keywords: [table, xlsx, ods, csv, tsv, json]
14
+ stability: stable
15
+ entrypoint:
16
+ kind: python
17
+ target: "anyconv_table_basic.module:TableModule"
18
+ requires:
19
+ python: ">=3.10"
20
+ packages:
21
+ - "anyconv-core>=1.0,<2.0"
22
+ - "openpyxl>=3.1"
23
+ - "odfpy>=1.4"
24
+
25
+ capabilities:
26
+ - id: table-convert
27
+ op: convert
28
+ since: 1.0.0
29
+ routing: auto
30
+ fidelity: semantic-loss
31
+ determinism: deterministic
32
+ cache: {reuse: false}
33
+ cost: {weight: 8}
34
+ limits: {timeout_s: 60, max_input_bytes: 104857600, max_outputs: 1}
35
+ inputs:
36
+ - name: source
37
+ cardinality: one
38
+ accept:
39
+ formats: [table:xlsx, table:ods, text:csv, text:tsv, data:json]
40
+ outputs:
41
+ - name: result
42
+ cardinality: one
43
+ kind: data
44
+ produce:
45
+ formats: [table:xlsx, table:ods, text:csv, text:tsv, data:json, text:html]
46
+ settings:
47
+ type: object
48
+ additionalProperties: false
49
+ properties:
50
+ sheet: {type: string, default: "", maxLength: 100}
51
+ header: {type: boolean, default: true}
@@ -0,0 +1,280 @@
1
+ """Table conversion for AnyConv."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import html
7
+ import io
8
+ import json
9
+ from importlib.resources import files
10
+ from typing import Any
11
+
12
+ import yaml
13
+ from anyconv.sdk import Availability, CheckContext, Context, OpResult, Request
14
+ from anyconv.sdk.errors import CorruptInput, ModuleUnavailable, OpNotImplemented, UnsupportedType
15
+
16
+ FORMATS = {"table:xlsx", "table:ods", "text:csv", "text:tsv", "data:json", "text:html"}
17
+
18
+
19
+ class TableModule:
20
+ @staticmethod
21
+ def manifest() -> dict[str, Any]:
22
+ return yaml.safe_load(
23
+ files("anyconv_table_basic")
24
+ .joinpath("anyconv.module.yaml")
25
+ .read_text("utf-8")
26
+ )
27
+
28
+ def check(self, ctx: CheckContext) -> Availability:
29
+ missing = []
30
+ for module, label in (("openpyxl", "openpyxl"), ("odf", "odfpy")):
31
+ try:
32
+ __import__(module)
33
+ except ImportError:
34
+ missing.append(f"package:{label}")
35
+ return Availability(
36
+ status="unavailable" if missing else "ready",
37
+ missing=missing,
38
+ )
39
+
40
+ def convert(self, req: Request, ctx: Context) -> OpResult:
41
+ if req.capability_id != "table-convert":
42
+ raise OpNotImplemented(
43
+ f"Неизвестная возможность {req.capability_id!r}",
44
+ details={"capability": req.capability_id},
45
+ )
46
+ source = req.inputs["source"][0]
47
+ source_format = source.typeref.format if source.typeref is not None else None
48
+ target = req.target.format if req.target is not None else None
49
+ if source_format not in FORMATS or target not in FORMATS:
50
+ raise UnsupportedType(
51
+ "Неподдерживаемый табличный формат",
52
+ details={"source": source_format, "target": target},
53
+ )
54
+ columns, rows = _load_table(ctx, source, source_format, req.settings)
55
+ data = _dump_table(columns, rows, target, req.settings)
56
+ with ctx.out_blob("result", format=target) as writer:
57
+ writer.write(data)
58
+ provenance = {
59
+ "source_format": source_format,
60
+ "target_format": target,
61
+ "rows": len(rows),
62
+ "columns": len(columns),
63
+ }
64
+ ctx.emit_provenance(provenance)
65
+ assert writer.output is not None
66
+ return OpResult(outputs={"result": writer.output}, provenance=provenance)
67
+
68
+
69
+ def _load_table(
70
+ ctx: Context,
71
+ source: Any,
72
+ source_format: str,
73
+ settings: dict[str, Any],
74
+ ) -> tuple[list[str], list[list[Any]]]:
75
+ if source_format == "data:json":
76
+ value = _json_value(ctx, source)
77
+ return _from_json(value, bool(settings.get("header", True)))
78
+ raw = ctx.read_input("source")
79
+ if source_format == "table:xlsx":
80
+ rows = _read_xlsx(raw, str(settings.get("sheet", "")))
81
+ elif source_format == "table:ods":
82
+ rows = _read_ods(raw, str(settings.get("sheet", "")))
83
+ else:
84
+ delimiter = "\t" if source_format == "text:tsv" else ","
85
+ try:
86
+ text = raw.decode("utf-8-sig")
87
+ except UnicodeDecodeError as exc:
88
+ raise CorruptInput("Таблица должна быть в UTF-8") from exc
89
+ rows = [row for row in csv.reader(io.StringIO(text), delimiter=delimiter)]
90
+ return _normalize_rows(rows, bool(settings.get("header", True)))
91
+
92
+
93
+ def _read_xlsx(raw: bytes, sheet: str) -> list[list[Any]]:
94
+ try:
95
+ from openpyxl import load_workbook
96
+ except ImportError as exc: # pragma: no cover
97
+ raise ModuleUnavailable("Для XLSX требуется openpyxl") from exc
98
+ try:
99
+ workbook = load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
100
+ try:
101
+ worksheet = workbook[sheet] if sheet in workbook.sheetnames else workbook.worksheets[0]
102
+ return [list(row) for row in worksheet.iter_rows(values_only=True)]
103
+ finally:
104
+ workbook.close()
105
+ except Exception as exc:
106
+ raise CorruptInput("Не удалось прочитать XLSX") from exc
107
+
108
+
109
+ def _read_ods(raw: bytes, sheet: str) -> list[list[Any]]:
110
+ try:
111
+ from odf import teletype
112
+ from odf.opendocument import load
113
+ from odf.table import Table, TableCell, TableRow
114
+ except ImportError as exc: # pragma: no cover
115
+ raise ModuleUnavailable("Для ODS требуется odfpy") from exc
116
+ try:
117
+ document = load(io.BytesIO(raw))
118
+ tables = document.spreadsheet.getElementsByType(Table)
119
+ table = next(
120
+ (item for item in tables if sheet and item.getAttribute("name") == sheet),
121
+ None,
122
+ )
123
+ if table is None:
124
+ table = tables[0]
125
+ rows = []
126
+ for row in table.getElementsByType(TableRow):
127
+ values = []
128
+ for cell in row.getElementsByType(TableCell):
129
+ value = cell.getAttribute("value")
130
+ values.append(value if value is not None else teletype.extractText(cell).strip())
131
+ repeats = int(cell.getAttribute("numbercolumnsrepeated") or 1)
132
+ if repeats > 1:
133
+ values.extend([values[-1]] * (min(repeats, 1000) - 1))
134
+ rows.append(values)
135
+ return rows
136
+ except Exception as exc:
137
+ raise CorruptInput("Не удалось прочитать ODS") from exc
138
+
139
+
140
+ def _json_value(ctx: Context, source: Any) -> Any:
141
+ if isinstance(source.value, (dict, list)):
142
+ return source.value
143
+ try:
144
+ return json.loads(_source_text(ctx, source))
145
+ except json.JSONDecodeError as exc:
146
+ raise CorruptInput("Некорректный JSON таблицы") from exc
147
+
148
+
149
+ def _source_text(ctx: Context, source: Any) -> str:
150
+ if source.kind == "text" and isinstance(source.value, str):
151
+ return source.value
152
+ if isinstance(source.value, str):
153
+ return source.value
154
+ data = ctx.read_input("source")
155
+ try:
156
+ return data.decode("utf-8-sig")
157
+ except UnicodeDecodeError as exc:
158
+ raise CorruptInput("JSON должен быть в UTF-8") from exc
159
+
160
+
161
+ def _from_json(value: Any, header: bool) -> tuple[list[str], list[list[Any]]]:
162
+ if isinstance(value, dict) and isinstance(value.get("rows"), list):
163
+ rows = value["rows"]
164
+ columns = [str(item) for item in value.get("columns") or []]
165
+ if columns:
166
+ return columns, [list(row) if isinstance(row, list) else [row] for row in rows]
167
+ return _normalize_rows(
168
+ [list(row) if isinstance(row, list) else [row] for row in rows],
169
+ header,
170
+ )
171
+ if isinstance(value, list):
172
+ if value and all(isinstance(item, dict) for item in value):
173
+ columns: list[str] = []
174
+ for item in value:
175
+ for key in item:
176
+ if str(key) not in columns:
177
+ columns.append(str(key))
178
+ rows = [[item.get(key, "") for key in columns] for item in value]
179
+ return columns, rows
180
+ return _normalize_rows(
181
+ [list(item) if isinstance(item, list) else [item] for item in value],
182
+ header,
183
+ )
184
+ raise CorruptInput("JSON должен быть списком строк или объектом с rows")
185
+
186
+
187
+ def _normalize_rows(
188
+ rows: list[list[Any]],
189
+ header: bool,
190
+ ) -> tuple[list[str], list[list[Any]]]:
191
+ cleaned = [list(row) for row in rows if any(str(cell).strip() for cell in row)]
192
+ if not cleaned:
193
+ return [], []
194
+ if header:
195
+ columns = [str(cell) for cell in cleaned[0]]
196
+ data = cleaned[1:]
197
+ else:
198
+ width = max(len(row) for row in cleaned)
199
+ columns = [f"column_{index + 1}" for index in range(width)]
200
+ data = cleaned
201
+ return columns, data
202
+
203
+
204
+ def _dump_table(
205
+ columns: list[str],
206
+ rows: list[list[Any]],
207
+ target: str,
208
+ settings: dict[str, Any],
209
+ ) -> bytes:
210
+ if target == "data:json":
211
+ data = [dict(zip(columns, row, strict=False)) for row in rows]
212
+ return (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
213
+ if target in ("text:csv", "text:tsv"):
214
+ buffer = io.StringIO()
215
+ writer = csv.writer(
216
+ buffer,
217
+ delimiter="," if target == "text:csv" else "\t",
218
+ lineterminator="\n",
219
+ )
220
+ if bool(settings.get("header", True)):
221
+ writer.writerow(columns)
222
+ for row in rows:
223
+ writer.writerow(row)
224
+ return buffer.getvalue().encode("utf-8")
225
+ if target == "text:html":
226
+ head = "".join(f"<th>{html.escape(column)}</th>" for column in columns)
227
+ body = "".join(
228
+ "<tr>" + "".join(f"<td>{html.escape(str(cell))}</td>" for cell in row) + "</tr>"
229
+ for row in rows
230
+ )
231
+ return (
232
+ '<!doctype html><html><head><meta charset="utf-8"></head><body><table>'
233
+ f"<thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></body></html>\n"
234
+ ).encode()
235
+ if target == "table:xlsx":
236
+ return _write_xlsx(columns, rows, str(settings.get("sheet", "Sheet1")))
237
+ if target == "table:ods":
238
+ return _write_ods(columns, rows, str(settings.get("sheet", "Sheet1")))
239
+ raise UnsupportedType(f"Неизвестный табличный формат {target!r}")
240
+
241
+
242
+ def _write_xlsx(columns: list[str], rows: list[list[Any]], sheet: str) -> bytes:
243
+ try:
244
+ from openpyxl import Workbook
245
+ except ImportError as exc: # pragma: no cover
246
+ raise ModuleUnavailable("Для XLSX требуется openpyxl") from exc
247
+ workbook = Workbook()
248
+ worksheet = workbook.active
249
+ worksheet.title = sheet or "Sheet1"
250
+ worksheet.append(columns)
251
+ for row in rows:
252
+ worksheet.append(row)
253
+ output = io.BytesIO()
254
+ workbook.save(output)
255
+ return output.getvalue()
256
+
257
+
258
+ def _write_ods(columns: list[str], rows: list[list[Any]], sheet: str) -> bytes:
259
+ try:
260
+ from odf.opendocument import OpenDocumentSpreadsheet
261
+ from odf.table import Table, TableCell, TableRow
262
+ from odf.text import P
263
+ except ImportError as exc: # pragma: no cover
264
+ raise ModuleUnavailable("Для ODS требуется odfpy") from exc
265
+ document = OpenDocumentSpreadsheet()
266
+ table = Table(name=sheet or "Sheet1")
267
+ for values in [columns, *rows]:
268
+ row = TableRow()
269
+ for value in values:
270
+ cell = TableCell(valuetype="string")
271
+ cell.addElement(P(text=str(value)))
272
+ row.addElement(cell)
273
+ table.addElement(row)
274
+ document.spreadsheet.addElement(table)
275
+ output = io.BytesIO()
276
+ document.save(output)
277
+ return output.getvalue()
278
+
279
+
280
+ __all__ = ["TableModule"]
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: anyconv-table-basic
3
+ Version: 1.0.1
4
+ Summary: AnyConv basic XLSX, ODS, CSV, TSV and JSON table conversion module
5
+ Author: AnyConv
6
+ License-Expression: MIT
7
+ Keywords: anyconv,table,xlsx,ods,csv,tsv,json
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: anyconv-core<2.0,>=1.0
12
+ Requires-Dist: openpyxl>=3.1
13
+ Requires-Dist: odfpy>=1.4
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=7; extra == "dev"
16
+ Requires-Dist: ruff>=0.5; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # anyconv-table-basic
20
+
21
+ Конвертация простых таблиц: XLSX, ODS, CSV, TSV, JSON и HTML.
22
+
23
+ ## Возможности
24
+
25
+ - **`table-convert`** — XLSX/ODS/CSV/TSV/JSON → XLSX/ODS/CSV/TSV/JSON/HTML.
26
+ - Настройки `sheet` (имя листа) и `header` (первая строка — заголовки).
27
+
28
+ ## Установка
29
+
30
+ ```bash
31
+ pip install "anyconv-core[all] @ git+https://gitlab.com/anyconv/anyconv-core.git@v1.0.1"
32
+ pip install "git+https://gitlab.com/anyconv/anyconv-modules.git@v1.0.1#subdirectory=modules/table-basic"
33
+ # ?????????? ?? checkout anyconv-modules
34
+ cd modules/table-basic
35
+ pip install -e ".[dev]"
36
+ pytest
37
+ anyconv module validate .
38
+ anyconv module test .
39
+ ```
@@ -0,0 +1,9 @@
1
+ anyconv_table_basic/__init__.py,sha256=Z2JID40N2uZl4LAi2zAX0e-1i3ztWXb3XiTWarZblic,109
2
+ anyconv_table_basic/anyconv.module.yaml,sha256=GtT1w-vRfGf8s1dUoi1mWbRfXKFnKoxwg-GAbqfj0Lg,1394
3
+ anyconv_table_basic/module.py,sha256=oeaiWPzzyqcIEyNmSp9d5xErPVeHXG3gRbaE4EB8Vlw,10691
4
+ anyconv_table_basic-1.0.1.dist-info/licenses/LICENSE,sha256=Wahb1xasoYXZBxdcuh2ETI6eaWi4JazPi9yhb0eFBxU,1077
5
+ anyconv_table_basic-1.0.1.dist-info/METADATA,sha256=yi9vxBMN8Mxz-URm3wi0Ax3JwQGEXz7wCxrMP8gWCAQ,1233
6
+ anyconv_table_basic-1.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ anyconv_table_basic-1.0.1.dist-info/entry_points.txt,sha256=cIO-e0fGajDEgf5TFWE_ke17tCDVfzmMQ1n-Yx9u5wg,71
8
+ anyconv_table_basic-1.0.1.dist-info/top_level.txt,sha256=Q20PmTHHBrRaChHaX0O9Py-h0njYDsUI6ZA-4GEuiTc,20
9
+ anyconv_table_basic-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [anyconv.modules]
2
+ table_basic = anyconv_table_basic.module:TableModule
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AnyConv contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ anyconv_table_basic