csvx-py 0.1.0a1__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.
csvx/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """csvx-py: reference Python tooling for the CSVX draft."""
2
+ from .model import Cell, ConversionReport, Document, Sheet
3
+ from .parser import CsvxError, parse, render
4
+ from .xlsx import ConversionError, csvx_to_xlsx, read_xlsx, write_xlsx, xlsx_to_csvx
5
+
6
+ __all__ = ["Cell", "ConversionError", "ConversionReport", "CsvxError", "Document", "Sheet",
7
+ "csvx_to_xlsx", "parse", "read_xlsx", "render", "write_xlsx", "xlsx_to_csvx"]
csvx/cli.py ADDED
@@ -0,0 +1,47 @@
1
+ """Command-line interface for csvx-py."""
2
+ from __future__ import annotations
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+ from .parser import CsvxError, parse, render
8
+ from .xlsx import ConversionError, csvx_to_xlsx, xlsx_to_csvx
9
+
10
+
11
+ def _report(report, path: str | None) -> None:
12
+ if path: Path(path).write_text(json.dumps(report.as_dict(), indent=2) + "\n", encoding="utf-8")
13
+ for issue in report.warnings:
14
+ where = "/".join(x for x in (issue.sheet, issue.cell) if x)
15
+ print(f"csvx: warning: {where + ': ' if where else ''}{issue.feature}: {issue.message}", file=sys.stderr)
16
+
17
+
18
+ def main(argv: list[str] | None = None) -> int:
19
+ parser = argparse.ArgumentParser(prog="csvx", description="CSVX format tools")
20
+ sub = parser.add_subparsers(dest="command", required=True)
21
+ convert = sub.add_parser("convert", help="convert based on input/output extensions")
22
+ convert.add_argument("input"); convert.add_argument("-o", "--output", required=True)
23
+ convert.add_argument("--strict", action="store_true"); convert.add_argument("--report")
24
+ convert.add_argument("--dimension", choices=["content", "worksheet", "compact", "fidelity"], default="content",
25
+ help="content trims trailing style-only extent; worksheet preserves reported extent")
26
+ convert.add_argument("--materialize-dimensions", action="store_true")
27
+ check = sub.add_parser("check", help="parse and validate CSVX")
28
+ check.add_argument("input")
29
+ fmt = sub.add_parser("format", help="write canonical CSVX")
30
+ fmt.add_argument("input"); fmt.add_argument("-o", "--output", required=True)
31
+ args = parser.parse_args(argv)
32
+ try:
33
+ if args.command == "convert":
34
+ source, target = Path(args.input).suffix.lower(), Path(args.output).suffix.lower()
35
+ options = {"strict": args.strict, "dimension": args.dimension, "materialize_dimensions": args.materialize_dimensions}
36
+ if source == ".xlsx" and target == ".csvx": report = xlsx_to_csvx(args.input, args.output, **options)
37
+ elif source == ".csvx" and target == ".xlsx": report = csvx_to_xlsx(args.input, args.output, **options)
38
+ else: raise ConversionError("supported pairs: .xlsx → .csvx and .csvx → .xlsx")
39
+ _report(report, args.report); return 0
40
+ document = parse(Path(args.input).read_text(encoding="utf-8"), strict=True)
41
+ if args.command == "format": Path(args.output).write_text(render(document), encoding="utf-8")
42
+ else: print(f"OK: {len(document.sheets)} sheet(s)")
43
+ return 0
44
+ except (CsvxError, ConversionError, OSError) as error:
45
+ print(f"csvx: error: {error}", file=sys.stderr); return 2
46
+
47
+ if __name__ == "__main__": raise SystemExit(main())
csvx/model.py ADDED
@@ -0,0 +1,70 @@
1
+ """Public CSVX document model."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import Any
6
+
7
+
8
+ @dataclass(slots=True)
9
+ class Cell:
10
+ value: str | None = None
11
+ dtype: str | None = None
12
+ formula: str | None = None
13
+ annotation: str | None = None
14
+ styles: list[str] = field(default_factory=list)
15
+ comment: str | None = None
16
+ quoted: bool = False
17
+
18
+
19
+ @dataclass(slots=True)
20
+ class Sheet:
21
+ name: str
22
+ header: list[Cell] | None = None
23
+ rows: list[list[Cell]] = field(default_factory=list)
24
+ table: dict[str, Any] = field(default_factory=dict)
25
+ columns: list[dict[str, Any]] = field(default_factory=list)
26
+
27
+ @property
28
+ def width(self) -> int:
29
+ if self.header is not None:
30
+ return len(self.header)
31
+ if self.columns:
32
+ return len(self.columns)
33
+ return max((len(row) for row in self.rows), default=0)
34
+
35
+
36
+ @dataclass(slots=True)
37
+ class Document:
38
+ frontmatter: dict[str, Any] = field(default_factory=dict)
39
+ sheets: list[Sheet] = field(default_factory=list)
40
+ warnings: list[str] = field(default_factory=list)
41
+
42
+
43
+ @dataclass(slots=True)
44
+ class ConversionIssue:
45
+ feature: str
46
+ message: str
47
+ sheet: str | None = None
48
+ cell: str | None = None
49
+ action: str = "dropped"
50
+
51
+
52
+ @dataclass(slots=True)
53
+ class ConversionReport:
54
+ warnings: list[ConversionIssue] = field(default_factory=list)
55
+ losses: list[ConversionIssue] = field(default_factory=list)
56
+ sheets_converted: int = 0
57
+
58
+ def add(self, feature: str, message: str, *, sheet: str | None = None,
59
+ cell: str | None = None, action: str = "dropped") -> None:
60
+ self.warnings.append(ConversionIssue(feature, message, sheet, cell, action))
61
+ if action in {"dropped", "changed"}:
62
+ self.losses.append(self.warnings[-1])
63
+
64
+ def as_dict(self) -> dict[str, Any]:
65
+ def issue(x: ConversionIssue) -> dict[str, Any]:
66
+ return {"feature": x.feature, "message": x.message, "sheet": x.sheet,
67
+ "cell": x.cell, "action": x.action}
68
+ return {"sheets_converted": self.sheets_converted,
69
+ "warnings": [issue(x) for x in self.warnings],
70
+ "losses": [issue(x) for x in self.losses]}
csvx/parser.py ADDED
@@ -0,0 +1,356 @@
1
+ """CSVX parser and canonical renderer for the current draft syntax."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ import yaml
9
+
10
+ from .model import Cell, Document, Sheet
11
+
12
+ DEFAULTS = {"delimiter": "|", "quote": '"', "continuation": "+",
13
+ "line_comment": "#", "escape": "\\", "formula_language": "ooxml",
14
+ "annotation_format": "yaml"}
15
+ TABLE_DEFAULTS = {"header": True, "null_policy": "null", "allow_ragged": False,
16
+ "default_dtype": "string", "type_propagation": "column"}
17
+ TYPE_RE = re.compile(r":([A-Za-z_][\w.-]*)(?:\(([^()]*)\))?:")
18
+
19
+
20
+ class CsvxError(ValueError):
21
+ pass
22
+
23
+
24
+ @dataclass(slots=True)
25
+ class RawField:
26
+ text: str
27
+ quoted: bool
28
+ continuation: bool
29
+
30
+
31
+ def _frontmatter(text: str) -> tuple[dict[str, Any], str]:
32
+ if text.startswith("--- "):
33
+ line, _, body = text.partition("\n")
34
+ if not line.endswith(" ---"):
35
+ raise CsvxError("invalid one-line frontmatter")
36
+ data = yaml.safe_load(line[4:-4]) or {}
37
+ if not isinstance(data, dict):
38
+ raise CsvxError("frontmatter must be a mapping")
39
+ return data, body
40
+ if not text.startswith("---\n"):
41
+ return {}, text
42
+ end = text.find("\n---\n", 4)
43
+ if end < 0:
44
+ raise CsvxError("unclosed frontmatter")
45
+ data = yaml.safe_load(text[4:end]) or {}
46
+ if not isinstance(data, dict):
47
+ raise CsvxError("frontmatter must be a mapping")
48
+ return data, text[end + 5:]
49
+
50
+
51
+ def _config(frontmatter: dict[str, Any], strict: bool) -> dict[str, Any]:
52
+ conf = dict(DEFAULTS)
53
+ legacy = frontmatter.get("dialect")
54
+ flat = set(DEFAULTS) & set(frontmatter)
55
+ if legacy is not None:
56
+ if flat:
57
+ raise CsvxError("cannot mix deprecated 'dialect' and flat syntax keys")
58
+ if not isinstance(legacy, dict):
59
+ raise CsvxError("legacy dialect must be a mapping")
60
+ csv, csvx = legacy.get("csv", {}), legacy.get("csvx", {})
61
+ if not isinstance(csv, dict) or not isinstance(csvx, dict):
62
+ raise CsvxError("legacy dialect.csv and dialect.csvx must be mappings")
63
+ conf.update({k: csv[k] for k in ("delimiter", "quote") if k in csv})
64
+ conf.update({k: csvx[k] for k in ("continuation", "line_comment", "escape") if k in csvx})
65
+ formulas = {"xlsx": "ooxml", "ods": "openformula", "sheets": "google-sheets"}
66
+ if "formula_dialect" in csvx:
67
+ conf["formula_language"] = formulas.get(csvx["formula_dialect"], csvx["formula_dialect"])
68
+ if "code_format" in csvx:
69
+ conf["annotation_format"] = csvx["code_format"]
70
+ else:
71
+ conf.update({k: frontmatter[k] for k in DEFAULTS if k in frontmatter})
72
+ for key in ("delimiter", "quote", "continuation", "escape"):
73
+ if not isinstance(conf[key], str) or len(conf[key]) != 1:
74
+ raise CsvxError(f"{key} must be one character")
75
+ if conf["quote"] not in {'"', "'"}:
76
+ raise CsvxError("quote must be double or single quote")
77
+ if conf["formula_language"] not in {"ooxml", "openformula", "google-sheets", "none"}:
78
+ raise CsvxError("unknown formula_language")
79
+ if conf["annotation_format"] not in {"yaml", "json"}:
80
+ raise CsvxError("annotation_format must be yaml or json")
81
+ return conf
82
+
83
+
84
+ def _flatten_legacy_frontmatter(frontmatter: dict[str, Any]) -> dict[str, Any]:
85
+ """Return canonical flat frontmatter after _config has validated legacy input."""
86
+ if "dialect" not in frontmatter:
87
+ return frontmatter
88
+ result = dict(frontmatter)
89
+ legacy = result.pop("dialect")
90
+ csv, csvx = legacy.get("csv", {}), legacy.get("csvx", {})
91
+ for key in ("delimiter", "quote"):
92
+ if key in csv:
93
+ result[key] = csv[key]
94
+ for key in ("continuation", "line_comment", "escape"):
95
+ if key in csvx:
96
+ result[key] = csvx[key]
97
+ formulas = {"xlsx": "ooxml", "ods": "openformula", "sheets": "google-sheets"}
98
+ if "formula_dialect" in csvx:
99
+ result["formula_language"] = formulas.get(csvx["formula_dialect"], csvx["formula_dialect"])
100
+ if "code_format" in csvx:
101
+ result["annotation_format"] = csvx["code_format"]
102
+ return result
103
+
104
+
105
+ def _split_fields(line: str, conf: dict[str, Any]) -> list[RawField]:
106
+ delim, quote, marker = conf["delimiter"], conf["quote"], conf["continuation"]
107
+ fields: list[RawField] = []
108
+ i = 0
109
+ while True:
110
+ start = i
111
+ quoted = i < len(line) and line[i] == quote
112
+ if quoted:
113
+ i += 1
114
+ protected = False
115
+ while i < len(line):
116
+ char = line[i]
117
+ if char == "\\":
118
+ i += 2
119
+ continue
120
+ if char == "`":
121
+ protected = not protected
122
+ i += 1
123
+ continue
124
+ if char == quote and not protected:
125
+ if i + 1 < len(line) and line[i + 1] == quote:
126
+ i += 2
127
+ continue
128
+ i += 1
129
+ break
130
+ i += 1
131
+ else:
132
+ raise CsvxError("unterminated wrapped field")
133
+ raw = line[start + 1:i - 1]
134
+ raw = raw.replace(quote * 2, quote)
135
+ tail = ""
136
+ while i < len(line) and line[i] != delim:
137
+ tail += line[i]
138
+ i += 1
139
+ if tail.strip() not in {"", marker}:
140
+ raise CsvxError("content after closing wrapper")
141
+ continuation = tail.strip() == marker
142
+ else:
143
+ while i < len(line) and line[i] != delim:
144
+ i += 1
145
+ raw = line[start:i]
146
+ continuation = raw.rstrip().endswith(marker) and not raw.rstrip().endswith("\\" + marker)
147
+ if continuation:
148
+ raw = raw.rstrip()[:-1]
149
+ fields.append(RawField(raw, quoted, continuation))
150
+ if i >= len(line):
151
+ return fields
152
+ i += 1
153
+
154
+
155
+ def _close(text: str, start: int, close: str) -> int:
156
+ i = start
157
+ while True:
158
+ i = text.find(close, i)
159
+ if i < 0:
160
+ return -1
161
+ if i == 0 or text[i - 1] != "\\":
162
+ return i
163
+ i += 1
164
+
165
+
166
+ def _annotation_close(text: str, start: int) -> int:
167
+ depth, i = 0, start + 2
168
+ while i < len(text) - 1:
169
+ if text[i] == "\\":
170
+ i += 2; continue
171
+ if text[i] == "{": depth += 1
172
+ elif text[i] == "}":
173
+ if depth: depth -= 1
174
+ elif text[i + 1] == "}": return i
175
+ i += 1
176
+ return -1
177
+
178
+
179
+ def _cell(raw: str, quoted: bool, conf: dict[str, Any]) -> Cell:
180
+ value, pos = [], 0
181
+ while pos < len(raw):
182
+ if raw[pos] == "\\" and pos + 1 < len(raw):
183
+ value.append(raw[pos + 1]); pos += 2; continue
184
+ if raw[pos] == "`" or raw.startswith("{{", pos) or raw.startswith("[[", pos) or raw.startswith("/*", pos) or TYPE_RE.match(raw, pos):
185
+ break
186
+ value.append(raw[pos]); pos += 1
187
+ cell = Cell(value="".join(value).rstrip() or None, quoted=quoted)
188
+ while pos < len(raw):
189
+ while pos < len(raw) and raw[pos].isspace(): pos += 1
190
+ if pos >= len(raw): break
191
+ if raw[pos] == "`":
192
+ end = _close(raw, pos + 1, "`")
193
+ if end < 0: raise CsvxError("unclosed formula")
194
+ cell.formula = raw[pos + 1:end].replace("\\`", "`"); pos = end + 1
195
+ elif raw.startswith("{{", pos):
196
+ end = _annotation_close(raw, pos)
197
+ if end < 0: raise CsvxError("unclosed annotation")
198
+ cell.annotation = raw[pos + 2:end].replace("\\}", "}"); pos = end + 2
199
+ elif raw.startswith("[[", pos):
200
+ end = _close(raw, pos + 2, "]]" )
201
+ if end < 0: raise CsvxError("unclosed style")
202
+ cell.styles.append(raw[pos + 2:end].replace("\\]", "]")); pos = end + 2
203
+ elif raw.startswith("/*", pos):
204
+ end = _close(raw, pos + 2, "*/")
205
+ if end < 0: raise CsvxError("unclosed comment")
206
+ cell.comment = raw[pos + 2:end].replace("\\*", "*"); pos = end + 2
207
+ else:
208
+ match = TYPE_RE.match(raw, pos)
209
+ if not match: raise CsvxError(f"unexpected inclusion content near {raw[pos:pos+12]!r}")
210
+ cell.dtype = match.group(1) + (f"({match.group(2)})" if match.group(2) is not None else "")
211
+ pos = match.end()
212
+ if cell.dtype == "null": cell.value = None
213
+ elif cell.dtype == "empty": cell.value = ""
214
+ elif cell.value is None and quoted: cell.value = ""
215
+ return cell
216
+
217
+
218
+ def _parse_sheet(lines: list[str], name: str, table: dict[str, Any], columns: list[dict[str, Any]], conf: dict[str, Any]) -> Sheet:
219
+ active = [line for line in lines if line.strip() and not (conf["line_comment"] and line.lstrip().startswith(conf["line_comment"] + " "))]
220
+ sheet = Sheet(name, table=table, columns=columns)
221
+ if not active: return sheet
222
+ header_enabled = table.get("header", True)
223
+ first = _split_fields(active[0], conf)
224
+ width = len(first) if header_enabled else (table.get("cols") or len(first))
225
+ start = 1 if header_enabled else 0
226
+ if header_enabled:
227
+ if any(x.continuation for x in first): raise CsvxError("header cannot continue")
228
+ sheet.header = [_cell(x.text, x.quoted, conf) for x in first]
229
+ pending: list[int] = []
230
+ slots: list[list[RawField]] = []
231
+ for line in active[start:]:
232
+ fields = _split_fields(line, conf)
233
+ if not pending:
234
+ if len(fields) > width: raise CsvxError(f"row in {name} exceeds width {width}")
235
+ slots = [[field] for field in fields]
236
+ # Missing trailing cells become pending placeholders when a row
237
+ # uses a staircase; later physical lines fill them left-to-right.
238
+ slots.extend([] for _ in range(len(fields), width))
239
+ pending = [i for i, field in enumerate(fields) if field.continuation] + list(range(len(fields), width))
240
+ else:
241
+ if len(fields) > len(pending): raise CsvxError(f"too many continuation fields in {name}")
242
+ old = pending
243
+ for index, field in enumerate(fields):
244
+ slots[old[index]].append(field)
245
+ pending = [old[i] for i, field in enumerate(fields) if field.continuation] + old[len(fields):]
246
+ if not pending:
247
+ if len(slots) != width and not table.get("allow_ragged", False):
248
+ raise CsvxError(f"row in {name} has {len(slots)} fields; expected {width}")
249
+ row = []
250
+ for segment_list in slots:
251
+ first_seg = segment_list[0]
252
+ parts = [x.text for x in segment_list]
253
+ if len(parts) > 1 and not first_seg.quoted and parts[0] == "": parts.pop(0)
254
+ row.append(_cell("\n".join(parts), first_seg.quoted, conf))
255
+ sheet.rows.append(row)
256
+ slots = []
257
+ if pending: raise CsvxError(f"unresolved continuation in {name}")
258
+ return sheet
259
+
260
+
261
+ def parse(text: str, *, strict: bool = True) -> Document:
262
+ text = text.lstrip("\ufeff").replace("\r\n", "\n").replace("\r", "\n")
263
+ frontmatter, body = _frontmatter(text)
264
+ legacy_frontmatter = "dialect" in frontmatter
265
+ conf = _config(frontmatter, strict)
266
+ frontmatter = _flatten_legacy_frontmatter(frontmatter)
267
+ chunks, current = [], []
268
+ for line in body.split("\n"):
269
+ if line == "---": chunks.append(current); current = []
270
+ else: current.append(line)
271
+ chunks.append(current)
272
+ declarations = frontmatter.get("sheets", []) or []
273
+ if not isinstance(declarations, list): raise CsvxError("sheets must be a list")
274
+ doc = Document(frontmatter=frontmatter)
275
+ if legacy_frontmatter:
276
+ doc.warnings.append("deprecated nested dialect frontmatter was normalized to flat keys")
277
+ for index, chunk in enumerate(chunks):
278
+ override = declarations[index] if index < len(declarations) else {}
279
+ if not isinstance(override, dict): raise CsvxError("sheet entry must be a mapping")
280
+ forbidden = set(DEFAULTS) | {"dialect"}
281
+ if forbidden & set(override): raise CsvxError("syntax settings cannot be overridden per sheet")
282
+ table = {**TABLE_DEFAULTS, **(frontmatter.get("table") or {}), **(override.get("table") or {})}
283
+ columns = override.get("columns", override.get("features", frontmatter.get("columns", frontmatter.get("features", [])))) or []
284
+ doc.sheets.append(_parse_sheet(chunk, override.get("name", f"Sheet{index + 1}"), table, columns, conf))
285
+ return doc
286
+
287
+
288
+ def _escape_value(value: str, conf: dict[str, Any]) -> str:
289
+ """Escape only syntax collisions in a literal value."""
290
+ esc = conf["escape"]
291
+ value = value.replace(esc, esc + esc)
292
+ value = value.replace("`", esc + "`").replace("{{", esc + "{{")
293
+ value = value.replace("[[", esc + "[[").replace("/*", "/" + esc + "*")
294
+ value = TYPE_RE.sub(lambda match: esc + match.group(0), value)
295
+ marker = conf["line_comment"]
296
+ if marker and value.startswith(marker + " "):
297
+ value = esc + value
298
+ return value
299
+
300
+
301
+ def _field(cell: Cell, value: str, conf: dict[str, Any], *, inclusions: bool,
302
+ continuation: bool) -> str:
303
+ text = _escape_value(value, conf)
304
+ if inclusions:
305
+ def add(part: str) -> None:
306
+ nonlocal text
307
+ text += (" " if text else "") + part
308
+ if cell.dtype: add(f":{cell.dtype}:")
309
+ if cell.formula is not None:
310
+ add("`" + cell.formula.replace("`", "\\`") + "`")
311
+ if cell.annotation is not None: add("{{" + cell.annotation + "}}")
312
+ for style in cell.styles: add(f"[[{style}]]")
313
+ if cell.comment is not None: add(f"/*{cell.comment}*/")
314
+ q = conf["quote"]
315
+ empty_string = not text and cell.value == "" and inclusions
316
+ wrapped = (empty_string or text == "---" or text.rstrip().endswith(conf["continuation"]) or
317
+ any(c in text for c in (conf["delimiter"], q)) or text[:1].isspace() or text[-1:].isspace())
318
+ if wrapped:
319
+ protected, out = False, []
320
+ for char in text:
321
+ if char == "`": protected = not protected
322
+ out.append(char if protected or char != q else q + q)
323
+ return q + "".join(out) + q + (conf["continuation"] if continuation else "")
324
+ return text + (conf["continuation"] if continuation else "")
325
+
326
+
327
+ def _render_row(row: list[Cell], conf: dict[str, Any]) -> list[str]:
328
+ segments = [("" if cell.value is None else cell.value).split("\n") for cell in row]
329
+ positions = [0] * len(row)
330
+ pending = list(range(len(row)))
331
+ lines: list[str] = []
332
+ first = True
333
+ while pending:
334
+ fields, next_pending = [], []
335
+ for index in pending:
336
+ cell, part = row[index], segments[index][positions[index]]
337
+ more = positions[index] + 1 < len(segments[index])
338
+ fields.append(_field(cell, part, conf, inclusions=first, continuation=more))
339
+ if more:
340
+ positions[index] += 1
341
+ next_pending.append(index)
342
+ lines.append(conf["delimiter"].join(fields))
343
+ pending, first = next_pending, False
344
+ return lines
345
+
346
+
347
+ def render(document: Document) -> str:
348
+ conf = _config(document.frontmatter, True)
349
+ out: list[str] = []
350
+ if document.frontmatter:
351
+ out.extend(["---", yaml.safe_dump(document.frontmatter, allow_unicode=True, sort_keys=False).rstrip(), "---"])
352
+ for number, sheet in enumerate(document.sheets):
353
+ if number: out.append("---")
354
+ if sheet.header is not None: out.extend(_render_row(sheet.header, conf))
355
+ for row in sheet.rows: out.extend(_render_row(row, conf))
356
+ return "\n".join(out) + "\n"
csvx/xlsx.py ADDED
@@ -0,0 +1,165 @@
1
+ """XLSX adapters. They never evaluate formulas."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import date, datetime, time
5
+ from collections import Counter
6
+ from pathlib import Path
7
+ from typing import Literal
8
+ from zipfile import BadZipFile, is_zipfile
9
+
10
+ from openpyxl import Workbook, load_workbook
11
+ from openpyxl.utils.exceptions import InvalidFileException
12
+ from openpyxl.comments import Comment
13
+
14
+ from .model import Cell, ConversionReport, Document, Sheet
15
+ from .parser import parse, render
16
+
17
+
18
+ class ConversionError(RuntimeError):
19
+ pass
20
+
21
+
22
+ def _issue(report: ConversionReport, strict: bool, feature: str, message: str, sheet: str,
23
+ cell: str | None = None, action: str = "dropped") -> None:
24
+ report.add(feature, message, sheet=sheet, cell=cell, action=action)
25
+ if strict:
26
+ raise ConversionError(f"{sheet}{'!' + cell if cell else ''}: {message}")
27
+
28
+
29
+ def _dtype(value: object) -> str | None:
30
+ if isinstance(value, bool): return "bool"
31
+ if isinstance(value, int): return "int"
32
+ if isinstance(value, float): return "float"
33
+ if isinstance(value, datetime): return "datetime"
34
+ if isinstance(value, date): return "date"
35
+ if isinstance(value, time): return "time"
36
+ return None
37
+
38
+
39
+ def read_xlsx(path: str | Path, *, strict: bool = False,
40
+ dimension: Literal["content", "worksheet", "compact", "fidelity"] = "content") -> tuple[Document, ConversionReport]:
41
+ """Read exposed XLSX values/formulas/comments without formula evaluation."""
42
+ path = Path(path)
43
+ if path.suffix.lower() not in {".xlsx", ".xlsm"}: raise ConversionError("only .xlsx is supported")
44
+ if path.suffix.lower() == ".xlsm": raise ConversionError("macro-enabled workbooks are unsupported")
45
+ if not is_zipfile(path):
46
+ raise ConversionError(f"{path.name} has an .xlsx extension but is not an XLSX ZIP archive; it may be CSV text")
47
+ try:
48
+ formulas = load_workbook(path, data_only=False, read_only=False)
49
+ cached = load_workbook(path, data_only=True, read_only=False)
50
+ except (BadZipFile, InvalidFileException) as error:
51
+ raise ConversionError(f"cannot read XLSX workbook: {error}") from error
52
+ report, sheets = ConversionReport(), []
53
+ declarations = []
54
+ for ws, cached_ws in zip(formulas.worksheets, cached.worksheets):
55
+ if ws.merged_cells.ranges: _issue(report, strict, "merged_cells", "merged cells are not yet converted", ws.title)
56
+ if ws.conditional_formatting: _issue(report, strict, "conditional_formatting", "conditional formatting is not yet converted", ws.title)
57
+ if ws.data_validations.dataValidation: _issue(report, strict, "data_validation", "data validation is not yet converted", ws.title)
58
+ max_row, max_col = ws.max_row, ws.max_column
59
+ # Content mode keeps A1-relative positions and interior gaps, but
60
+ # trims a style-only tail. The legacy compact/fidelity names remain
61
+ # accepted during this pre-alpha transition.
62
+ if dimension in {"content", "compact"}:
63
+ occupied = [(c.row, c.column) for row in ws.iter_rows() for c in row
64
+ if c.value is not None or c.comment or c.hyperlink]
65
+ max_row = max((r for r, _ in occupied), default=1)
66
+ max_col = max((c for _, c in occupied), default=1)
67
+ table = {"header": True}
68
+ sheet = Sheet(ws.title, table=table)
69
+ style_counts: Counter[int] = Counter()
70
+ for row_index in range(1, max_row + 1):
71
+ row: list[Cell] = []
72
+ for col_index in range(1, max_col + 1):
73
+ cell, cached_cell = ws.cell(row_index, col_index), cached_ws.cell(row_index, col_index)
74
+ formula = cell.value if cell.data_type == "f" else None
75
+ value = cached_cell.value if formula else cell.value
76
+ if formula and value is not None: value = str(value)
77
+ elif value is not None and not isinstance(value, str): value = str(value)
78
+ output = Cell(value=value, formula=formula, dtype=_dtype(cell.value if not formula else cached_cell.value))
79
+ if cell.comment: output.comment = cell.comment.text
80
+ if cell.hyperlink: output.annotation = f"link: '{cell.hyperlink.target}'"
81
+ if cell.style_id and cell.style_id != 0:
82
+ style_counts[cell.style_id] += 1
83
+ row.append(output)
84
+ if row_index == 1: sheet.header = row
85
+ else: sheet.rows.append(row)
86
+ if style_counts:
87
+ _issue(report, strict, "cell_style", f"{sum(style_counts.values())} styled cells across {len(style_counts)} style records are not yet converted", ws.title)
88
+ sheets.append(sheet)
89
+ declarations.append({"name": ws.title})
90
+ report.sheets_converted += 1
91
+ # A non-default single-sheet name is workbook data and needs frontmatter;
92
+ # `Sheet1` is the CSVX implicit default and can remain body-only.
93
+ frontmatter = {"sheets": declarations} if len(sheets) > 1 or sheets[0].name != "Sheet1" else {}
94
+ return Document(frontmatter=frontmatter, sheets=sheets), report
95
+
96
+
97
+ def _xlsx_value(source: Cell, report: ConversionReport, strict: bool, sheet: str, coordinate: str) -> object:
98
+ """Coerce only unambiguous CSVX registry values for XLSX output."""
99
+ if source.value is None:
100
+ return None
101
+ dtype = (source.dtype or "").split("(", 1)[0]
102
+ try:
103
+ if dtype == "int": return int(source.value)
104
+ if dtype == "float": return float(source.value)
105
+ if dtype == "bool": return source.value.lower() in {"true", "1", "yes", "on"}
106
+ if dtype == "date": return date.fromisoformat(source.value)
107
+ if dtype == "datetime": return datetime.fromisoformat(source.value)
108
+ if dtype == "time": return time.fromisoformat(source.value)
109
+ except ValueError:
110
+ _issue(report, strict, "typed_value", f"cannot coerce {dtype} value; writing text", sheet, coordinate, action="changed")
111
+ return source.value
112
+
113
+
114
+ def write_xlsx(document: Document, path: str | Path, *, strict: bool = False,
115
+ materialize_dimensions: bool = False) -> ConversionReport:
116
+ """Write values, formula text, comments, and basic date/number types to XLSX."""
117
+ report, workbook = ConversionReport(), Workbook()
118
+ workbook.remove(workbook.active)
119
+ workbook.calculation.fullCalcOnLoad = True
120
+ workbook.calculation.forceFullCalc = True
121
+ for sheet in document.sheets:
122
+ ws = workbook.create_sheet(sheet.name)
123
+ cached_formula_count = 0
124
+ rows = ([sheet.header] if sheet.header is not None else []) + sheet.rows
125
+ for r, row in enumerate(rows, 1):
126
+ for c, source in enumerate(row, 1):
127
+ target = ws.cell(r, c)
128
+ if source.formula is not None:
129
+ if not source.formula.startswith("="):
130
+ _issue(report, strict, "formula", "formula does not begin with '='", sheet.name, target.coordinate)
131
+ target.value = source.formula
132
+ if source.value is not None:
133
+ cached_formula_count += 1
134
+ else:
135
+ target.value = _xlsx_value(source, report, strict, sheet.name, target.coordinate)
136
+ if source.comment: target.comment = Comment(source.comment, "CSVX")
137
+ if source.annotation:
138
+ try:
139
+ annotation = __import__("yaml").safe_load(source.annotation)
140
+ if isinstance(annotation, dict) and isinstance(annotation.get("link") or annotation.get("url"), str):
141
+ target.hyperlink = annotation.get("link") or annotation.get("url")
142
+ else: _issue(report, strict, "annotation", "annotation is not mapped to XLSX", sheet.name, target.coordinate)
143
+ except Exception:
144
+ _issue(report, strict, "annotation", "annotation is not valid YAML", sheet.name, target.coordinate)
145
+ if source.styles: _issue(report, strict, "cell_style", "styles are not yet converted", sheet.name, target.coordinate)
146
+ if cached_formula_count:
147
+ _issue(report, strict, "formula_cache", f"{cached_formula_count} cached formula values are not written; workbook will recalculate", sheet.name, action="changed")
148
+ if materialize_dimensions:
149
+ rows_n, cols_n = sheet.table.get("rows"), sheet.table.get("cols")
150
+ offset = 1 if sheet.header is not None else 0
151
+ if isinstance(rows_n, int) and isinstance(cols_n, int): ws.cell(rows_n + offset, cols_n)
152
+ report.sheets_converted += 1
153
+ workbook.save(path)
154
+ return report
155
+
156
+
157
+ def xlsx_to_csvx(input_path: str | Path, output_path: str | Path, **options: object) -> ConversionReport:
158
+ document, report = read_xlsx(input_path, strict=bool(options.get("strict", False)), dimension=options.get("dimension", "content"))
159
+ Path(output_path).write_text(render(document), encoding="utf-8")
160
+ return report
161
+
162
+
163
+ def csvx_to_xlsx(input_path: str | Path, output_path: str | Path, **options: object) -> ConversionReport:
164
+ document = parse(Path(input_path).read_text(encoding="utf-8"), strict=bool(options.get("strict", False)))
165
+ return write_xlsx(document, output_path, strict=bool(options.get("strict", False)), materialize_dimensions=bool(options.get("materialize_dimensions", False)))
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.5
2
+ Name: csvx-py
3
+ Version: 0.1.0a1
4
+ Summary: Reference Python parser and XLSX converter for CSVX
5
+ Project-URL: Homepage, https://github.com/ljcamargo/csvx
6
+ Project-URL: Repository, https://github.com/ljcamargo/csvx
7
+ Author-email: Luis J Camargo <cam.aedes@gmail.com>
8
+ Maintainer-email: Luis J Camargo <cam.aedes@gmail.com>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: converter,csv,csvx,spreadsheet,xlsx
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: openpyxl>=3.1
18
+ Requires-Dist: pyyaml>=6.0
19
+ Provides-Extra: dev
20
+ Requires-Dist: jsonschema>=4; extra == 'dev'
21
+ Requires-Dist: pytest>=8; extra == 'dev'
22
+ Requires-Dist: ruff>=0.6; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # csvx-py
26
+
27
+ Pre-alpha Python reference parser, canonical renderer, and XLSX converter for
28
+ the [CSVX draft](https://github.com/ljcamargo/csvx/blob/main/SPEC.md). The distribution name is `csvx-py`; the Python
29
+ package and command are both `csvx`.
30
+
31
+ ## Install from this repository
32
+
33
+ Install the published alpha package with:
34
+
35
+ ```bash
36
+ python -m pip install "csvx-py"
37
+ ```
38
+
39
+ For development from the repository:
40
+
41
+ ```bash
42
+ cd tools/csvx-py
43
+ python -m pip install -e ".[dev]"
44
+ ```
45
+
46
+ ## CLI
47
+
48
+ ```bash
49
+ # Validate or canonicalize CSVX
50
+ csvx check workbook.csvx
51
+ csvx format workbook.csvx -o canonical.csvx
52
+
53
+ # Convert by file extension and retain a machine-readable loss report
54
+ csvx convert workbook.xlsx -o workbook.csvx --report import-report.json
55
+ csvx convert workbook.csvx -o rebuilt.xlsx --report export-report.json
56
+ ```
57
+
58
+ XLSX import defaults to `--dimension content`: it preserves A1-relative
59
+ positions and interior gaps but trims trailing rows or columns that contain
60
+ only styles. Use `--dimension worksheet` to preserve the worksheet's reported
61
+ extent. `--strict` rejects any conversion that would report a loss.
62
+
63
+ ## Current fidelity boundary
64
+
65
+ The converter preserves sheet names, cell values, exposed formula text,
66
+ comments, hyperlinks (`{{link: ...}}`), positional blank gaps, and exposed
67
+ formula caches when importing. It never evaluates formulas. XLSX export asks
68
+ the spreadsheet application to recalculate formulas because cached results
69
+ cannot reliably be written with the current library.
70
+
71
+ Styles, merges, data validation, conditional formatting, charts, drawings,
72
+ macros, and annotations other than links are not converted yet. Recognized
73
+ unsupported features are aggregated in lenient-mode reports and rejected by
74
+ strict mode. This pre-alpha converter does not yet detect every possible OOXML
75
+ feature, so strict mode is not a complete fidelity guarantee.
76
+
77
+ Reviewed real-workbook conversion examples and their reports live in
78
+ [`tests/samples/`](https://github.com/ljcamargo/csvx/tree/main/tests/samples). Run the package checks with:
79
+
80
+ ```bash
81
+ python -m ruff check src tests
82
+ python -m pytest
83
+ ```
84
+
85
+ Code is Apache-2.0; see the repository [license](https://github.com/ljcamargo/csvx/blob/main/tools/csvx-py/LICENSE).
@@ -0,0 +1,10 @@
1
+ csvx/__init__.py,sha256=9Cb7ngKCHkIUHZVbO7lMEc9y9tXtolwjXyXIoMSku9g,431
2
+ csvx/cli.py,sha256=VRshzTlCqVwYqdLKneujwOhM_GvO0solckX3fuomSQQ,2750
3
+ csvx/model.py,sha256=fr9wrfNO3pSddljgNSEZO9pHlFldQKlhmuh8eu3r-Fk,2240
4
+ csvx/parser.py,sha256=4oP7-yL-vTQyYuS9SMyIAnn2yP5v2zZKYYs8OzwMa5g,15608
5
+ csvx/xlsx.py,sha256=oLyp0Hm984Lj5IaeCWk7XDrhF2JHIBbKyD5iH_yXSps,9359
6
+ csvx_py-0.1.0a1.dist-info/METADATA,sha256=DN503-JL6lRKQFO2MRGnwCmN8PRJMZN79p0ILQ08e8M,3109
7
+ csvx_py-0.1.0a1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
+ csvx_py-0.1.0a1.dist-info/entry_points.txt,sha256=xdLbhoq7bLkNweUGjSBUh8GO5CF6yqdHpn41SN-IArY,39
9
+ csvx_py-0.1.0a1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ csvx_py-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ csvx = csvx.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.