statstudio 0.1.0__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.
- statstudio/__init__.py +9 -0
- statstudio/__main__.py +3 -0
- statstudio/app.py +83 -0
- statstudio/cli.py +116 -0
- statstudio/core/__init__.py +3 -0
- statstudio/core/archive.py +27 -0
- statstudio/core/commands.py +67 -0
- statstudio/core/formula_catalog.py +74 -0
- statstudio/core/formulas.py +605 -0
- statstudio/core/joins.py +123 -0
- statstudio/core/project.py +358 -0
- statstudio/core/runtime.py +321 -0
- statstudio/core/scripting.py +594 -0
- statstudio/core/table.py +796 -0
- statstudio/core/transform.py +450 -0
- statstudio/feature_help.py +595 -0
- statstudio/io/__init__.py +3 -0
- statstudio/io/docx.py +201 -0
- statstudio/io/export.py +99 -0
- statstudio/io/file_import.py +199 -0
- statstudio/io/odbc.py +334 -0
- statstudio/io/sample_data.py +164 -0
- statstudio/io/table_io.py +118 -0
- statstudio/plots/__init__.py +19 -0
- statstudio/plots/advanced.py +651 -0
- statstudio/plots/basic.py +957 -0
- statstudio/plots/bayesian_plots.py +94 -0
- statstudio/plots/common.py +334 -0
- statstudio/plots/diagnostics.py +214 -0
- statstudio/plots/doe_plots.py +235 -0
- statstudio/plots/plotly_builders.py +719 -0
- statstudio/plots/predictive_plots.py +72 -0
- statstudio/plots/registry.py +251 -0
- statstudio/plugins.py +111 -0
- statstudio/resources/help_topics.json +13195 -0
- statstudio/resources/logo.ico +0 -0
- statstudio/resources/logo.png +0 -0
- statstudio/resources/statstudio.svg +8 -0
- statstudio/stats/__init__.py +42 -0
- statstudio/stats/bayesian.py +1094 -0
- statstudio/stats/bayesian_optimization.py +590 -0
- statstudio/stats/common.py +140 -0
- statstudio/stats/correlation.py +135 -0
- statstudio/stats/custom_doe.py +1714 -0
- statstudio/stats/descriptive.py +200 -0
- statstudio/stats/desirability.py +132 -0
- statstudio/stats/distributions.py +331 -0
- statstudio/stats/doe.py +1070 -0
- statstudio/stats/hypothesis.py +1305 -0
- statstudio/stats/multivariate.py +307 -0
- statstudio/stats/optimal_doe.py +264 -0
- statstudio/stats/power.py +194 -0
- statstudio/stats/predictive.py +605 -0
- statstudio/stats/profiler.py +379 -0
- statstudio/stats/quality.py +1218 -0
- statstudio/stats/regression.py +1600 -0
- statstudio/stats/results.py +235 -0
- statstudio/stats/simulator.py +95 -0
- statstudio/stats/survival.py +637 -0
- statstudio/stats/timeseries.py +643 -0
- statstudio/stats/tolerance.py +154 -0
- statstudio/ui/__init__.py +0 -0
- statstudio/ui/analysis_hub.py +271 -0
- statstudio/ui/command_catalog.py +460 -0
- statstudio/ui/command_palette.py +55 -0
- statstudio/ui/console.py +239 -0
- statstudio/ui/dialogs/__init__.py +0 -0
- statstudio/ui/dialogs/advanced_dialogs.py +392 -0
- statstudio/ui/dialogs/base.py +537 -0
- statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
- statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
- statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
- statstudio/ui/dialogs/doe_dialogs.py +220 -0
- statstudio/ui/dialogs/extended_dialogs.py +665 -0
- statstudio/ui/dialogs/graph_builder.py +139 -0
- statstudio/ui/dialogs/help_dialog.py +207 -0
- statstudio/ui/dialogs/help_topics.py +280 -0
- statstudio/ui/dialogs/lazy.py +184 -0
- statstudio/ui/dialogs/odbc_dialog.py +311 -0
- statstudio/ui/dialogs/plot_dialog.py +1385 -0
- statstudio/ui/dialogs/report_composer.py +218 -0
- statstudio/ui/dialogs/script_dialogs.py +267 -0
- statstudio/ui/dialogs/stats_dialogs.py +1688 -0
- statstudio/ui/dialogs/table_dialogs.py +997 -0
- statstudio/ui/dialogs/window.py +58 -0
- statstudio/ui/docks/__init__.py +0 -0
- statstudio/ui/formula_editor.py +121 -0
- statstudio/ui/icons.py +257 -0
- statstudio/ui/jobs.py +179 -0
- statstudio/ui/main_window.py +3934 -0
- statstudio/ui/plot_interaction.py +178 -0
- statstudio/ui/profiler_widget.py +437 -0
- statstudio/ui/recent.py +82 -0
- statstudio/ui/reports/__init__.py +0 -0
- statstudio/ui/reports/report_view.py +1632 -0
- statstudio/ui/script_jobs.py +35 -0
- statstudio/ui/scripts_panel.py +271 -0
- statstudio/ui/table_document.py +233 -0
- statstudio/ui/table_model.py +285 -0
- statstudio/ui/table_view.py +285 -0
- statstudio/ui/theme.py +645 -0
- statstudio/ui/welcome.py +453 -0
- statstudio/ui/window_controls.py +53 -0
- statstudio/ui/workers.py +53 -0
- statstudio-0.1.0.dist-info/METADATA +261 -0
- statstudio-0.1.0.dist-info/RECORD +110 -0
- statstudio-0.1.0.dist-info/WHEEL +5 -0
- statstudio-0.1.0.dist-info/entry_points.txt +5 -0
- statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
- statstudio-0.1.0.dist-info/top_level.txt +1 -0
statstudio/io/docx.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import os
|
|
5
|
+
import struct
|
|
6
|
+
import tempfile
|
|
7
|
+
import zipfile
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Iterable
|
|
11
|
+
from xml.sax.saxutils import escape
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
_CONTENT_TYPES = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
17
|
+
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
|
18
|
+
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
|
19
|
+
<Default Extension="xml" ContentType="application/xml"/>
|
|
20
|
+
<Default Extension="png" ContentType="image/png"/>
|
|
21
|
+
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
|
|
22
|
+
</Types>"""
|
|
23
|
+
|
|
24
|
+
_ROOT_RELS = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
25
|
+
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
26
|
+
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
|
|
27
|
+
</Relationships>"""
|
|
28
|
+
|
|
29
|
+
_DOC_HEADER = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
30
|
+
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
|
31
|
+
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
|
|
32
|
+
xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
|
|
33
|
+
xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
|
|
34
|
+
xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
|
|
35
|
+
<w:body>"""
|
|
36
|
+
|
|
37
|
+
_DOC_FOOTER = """<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1134" w:right="1134" w:bottom="1134" w:left="1134"/></w:sectPr></w:body></w:document>"""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _paragraph(text: str, bold: bool = False, size: int | None = None) -> str:
|
|
41
|
+
run_props = ""
|
|
42
|
+
if bold or size:
|
|
43
|
+
pieces = []
|
|
44
|
+
if bold:
|
|
45
|
+
pieces.append("<w:b/>")
|
|
46
|
+
if size:
|
|
47
|
+
pieces.append(f'<w:sz w:val="{size}"/>')
|
|
48
|
+
run_props = f"<w:rPr>{''.join(pieces)}</w:rPr>"
|
|
49
|
+
return f"<w:p><w:r>{run_props}<w:t xml:space=\"preserve\">{escape(str(text))}</w:t></w:r></w:p>"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _table(frame: pd.DataFrame, max_rows: int = 500) -> str:
|
|
53
|
+
if frame is None or frame.empty:
|
|
54
|
+
return _paragraph("(no rows)")
|
|
55
|
+
display = frame.head(max_rows)
|
|
56
|
+
truncated = len(frame) > max_rows
|
|
57
|
+
border = '<w:tblBorders><w:top w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/><w:left w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/><w:bottom w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/><w:right w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/><w:insideH w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/><w:insideV w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/></w:tblBorders>'
|
|
58
|
+
rows = []
|
|
59
|
+
header = "".join(f"<w:tc><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>{escape(str(c))}</w:t></w:r></w:p></w:tc>" for c in display.columns)
|
|
60
|
+
rows.append(f"<w:tr>{header}</w:tr>")
|
|
61
|
+
for _, row in display.iterrows():
|
|
62
|
+
cells = []
|
|
63
|
+
for value in row:
|
|
64
|
+
text = "" if pd.isna(value) else (f"{value:.6g}" if isinstance(value, (float, np.floating)) else str(value))
|
|
65
|
+
cells.append(f"<w:tc><w:p><w:r><w:t xml:space=\"preserve\">{escape(text)}</w:t></w:r></w:p></w:tc>")
|
|
66
|
+
rows.append(f"<w:tr>{''.join(cells)}</w:tr>")
|
|
67
|
+
table_xml = f"<w:tbl><w:tblPr>{border}</w:tblPr>{''.join(rows)}</w:tbl>"
|
|
68
|
+
if truncated:
|
|
69
|
+
table_xml += _paragraph(f"Showing the first {max_rows} of {len(frame)} rows; the on-screen report shows the same limit.")
|
|
70
|
+
return table_xml
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _image_paragraph(rel_id: str, width_emu: int, height_emu: int, index: int) -> str:
|
|
74
|
+
return (
|
|
75
|
+
'<w:p><w:r><w:drawing>'
|
|
76
|
+
f'<wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="{width_emu}" cy="{height_emu}"/>'
|
|
77
|
+
f'<wp:docPr id="{index}" name="Picture {index}"/>'
|
|
78
|
+
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">'
|
|
79
|
+
'<pic:pic><pic:nvPicPr>'
|
|
80
|
+
f'<pic:cNvPr id="{index}" name="image{index}.png"/><pic:cNvPicPr/></pic:nvPicPr>'
|
|
81
|
+
f'<pic:blipFill><a:blip r:embed="{rel_id}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>'
|
|
82
|
+
f'<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="{width_emu}" cy="{height_emu}"/></a:xfrm>'
|
|
83
|
+
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>'
|
|
84
|
+
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
_PNG_DPI = 130
|
|
89
|
+
_EMU_PER_INCH = 914400
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _png_dimensions(data: bytes) -> tuple[int, int]:
|
|
93
|
+
if len(data) >= 24 and data[:8] == b"\x89PNG\r\n\x1a\n":
|
|
94
|
+
return struct.unpack(">II", data[16:24])
|
|
95
|
+
return 0, 0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _image_size(data: bytes) -> tuple[int, int]:
|
|
99
|
+
pixels_x, pixels_y = _png_dimensions(data)
|
|
100
|
+
if not pixels_x or not pixels_y:
|
|
101
|
+
return 0, 0
|
|
102
|
+
return int(pixels_x * _EMU_PER_INCH / _PNG_DPI), int(pixels_y * _EMU_PER_INCH / _PNG_DPI)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _figures_to_png(figures: Iterable[Any]) -> list[tuple[bytes, int, int]]:
|
|
106
|
+
images = []
|
|
107
|
+
for figure in figures:
|
|
108
|
+
try:
|
|
109
|
+
buffer = io.BytesIO()
|
|
110
|
+
figure.savefig(buffer, format="png", dpi=_PNG_DPI, bbox_inches="tight")
|
|
111
|
+
data = buffer.getvalue()
|
|
112
|
+
width, height = _image_size(data)
|
|
113
|
+
images.append((data, width, height))
|
|
114
|
+
except Exception:
|
|
115
|
+
images.append((b"", 0, 0))
|
|
116
|
+
return images
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def write_docx(
|
|
120
|
+
path: str | Path,
|
|
121
|
+
title: str,
|
|
122
|
+
blocks: list[tuple[str, Any]],
|
|
123
|
+
figures: Iterable[Any] = (),
|
|
124
|
+
author: str = "",
|
|
125
|
+
subtitle: str = "",
|
|
126
|
+
) -> Path:
|
|
127
|
+
path = Path(path)
|
|
128
|
+
if path.suffix.lower() != ".docx":
|
|
129
|
+
path = path.with_suffix(".docx")
|
|
130
|
+
images = _figures_to_png(figures)
|
|
131
|
+
body: list[str] = []
|
|
132
|
+
body.append(_paragraph(title, bold=True, size=36))
|
|
133
|
+
if subtitle:
|
|
134
|
+
body.append(_paragraph(subtitle, size=24))
|
|
135
|
+
if author:
|
|
136
|
+
body.append(_paragraph(f"Author: {author}"))
|
|
137
|
+
body.append(_paragraph(f"Generated {datetime.now().strftime('%Y-%m-%d %H:%M')}"))
|
|
138
|
+
image_index = 0
|
|
139
|
+
image_rels = []
|
|
140
|
+
for kind, payload in blocks:
|
|
141
|
+
if kind == "heading":
|
|
142
|
+
body.append(_paragraph(payload, bold=True, size=28))
|
|
143
|
+
elif kind == "paragraph":
|
|
144
|
+
body.append(_paragraph(payload))
|
|
145
|
+
elif kind == "table":
|
|
146
|
+
body.append(_table(payload))
|
|
147
|
+
body.append(_paragraph(""))
|
|
148
|
+
elif kind in {"image", "image_data"}:
|
|
149
|
+
if kind == "image":
|
|
150
|
+
data, width, height = images[image_index] if image_index < len(images) else (b"", 0, 0)
|
|
151
|
+
else:
|
|
152
|
+
data = payload
|
|
153
|
+
width, height = _image_size(data)
|
|
154
|
+
if data and width and height:
|
|
155
|
+
rel_id = f"rId{10 + image_index}"
|
|
156
|
+
max_width = 5486400
|
|
157
|
+
if width > max_width:
|
|
158
|
+
height = int(height * max_width / width)
|
|
159
|
+
width = max_width
|
|
160
|
+
body.append(_image_paragraph(rel_id, width, height, image_index + 1))
|
|
161
|
+
image_rels.append((rel_id, f"media/image{image_index + 1}.png", data))
|
|
162
|
+
else:
|
|
163
|
+
body.append(_paragraph("[Plot unavailable]"))
|
|
164
|
+
image_index += 1
|
|
165
|
+
# Any remaining figures are appended at the end.
|
|
166
|
+
while image_index < len(images):
|
|
167
|
+
data, width, height = images[image_index]
|
|
168
|
+
if not data or not width or not height:
|
|
169
|
+
image_index += 1
|
|
170
|
+
continue
|
|
171
|
+
rel_id = f"rId{10 + image_index}"
|
|
172
|
+
max_width = 5486400
|
|
173
|
+
if width > max_width:
|
|
174
|
+
height = int(height * max_width / width)
|
|
175
|
+
width = max_width
|
|
176
|
+
body.append(_image_paragraph(rel_id, width, height, image_index + 1))
|
|
177
|
+
image_rels.append((rel_id, f"media/image{image_index + 1}.png", data))
|
|
178
|
+
image_index += 1
|
|
179
|
+
document = _DOC_HEADER + "".join(body) + _DOC_FOOTER
|
|
180
|
+
rels = ['<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">']
|
|
181
|
+
for rel_id, target, _ in image_rels:
|
|
182
|
+
rels.append(f'<Relationship Id="{rel_id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="{target}"/>')
|
|
183
|
+
rels.append("</Relationships>")
|
|
184
|
+
fd, temp_name = tempfile.mkstemp(prefix=f".{path.stem}-", suffix=".docx", dir=path.parent)
|
|
185
|
+
os.close(fd)
|
|
186
|
+
temp_path = Path(temp_name)
|
|
187
|
+
try:
|
|
188
|
+
with zipfile.ZipFile(temp_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
|
189
|
+
archive.writestr("[Content_Types].xml", _CONTENT_TYPES)
|
|
190
|
+
archive.writestr("_rels/.rels", _ROOT_RELS)
|
|
191
|
+
archive.writestr("word/document.xml", document)
|
|
192
|
+
archive.writestr("word/_rels/document.xml.rels", "".join(rels))
|
|
193
|
+
for _, target, data in image_rels:
|
|
194
|
+
archive.writestr(f"word/{target}", data)
|
|
195
|
+
os.replace(temp_path, path)
|
|
196
|
+
finally:
|
|
197
|
+
try:
|
|
198
|
+
temp_path.unlink(missing_ok=True)
|
|
199
|
+
except OSError:
|
|
200
|
+
pass
|
|
201
|
+
return path
|
statstudio/io/export.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import tempfile
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Callable
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from statstudio.core.table import DataTable
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ExportError(ValueError):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def atomic_write(path: str | Path, writer: Callable[[Path], None]) -> Path:
|
|
18
|
+
"""Write through a sibling temporary file so failures preserve the old export."""
|
|
19
|
+
path = Path(path)
|
|
20
|
+
fd, temp_name = tempfile.mkstemp(
|
|
21
|
+
prefix=f".{path.stem}-",
|
|
22
|
+
suffix=path.suffix,
|
|
23
|
+
dir=path.parent,
|
|
24
|
+
)
|
|
25
|
+
os.close(fd)
|
|
26
|
+
temp_path = Path(temp_name)
|
|
27
|
+
try:
|
|
28
|
+
writer(temp_path)
|
|
29
|
+
os.replace(temp_path, path)
|
|
30
|
+
finally:
|
|
31
|
+
try:
|
|
32
|
+
temp_path.unlink(missing_ok=True)
|
|
33
|
+
except OSError:
|
|
34
|
+
pass
|
|
35
|
+
return path
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def export_table(
|
|
39
|
+
table: DataTable,
|
|
40
|
+
path: str | Path,
|
|
41
|
+
*,
|
|
42
|
+
include_excluded: bool = True,
|
|
43
|
+
sheet_name: str = "Data",
|
|
44
|
+
) -> Path:
|
|
45
|
+
path = Path(path)
|
|
46
|
+
suffix = path.suffix.lower()
|
|
47
|
+
frame = table.visible_df(include_excluded=include_excluded)
|
|
48
|
+
if suffix in {".csv", ".tsv", ".txt"}:
|
|
49
|
+
separator = "\t" if suffix == ".tsv" else ","
|
|
50
|
+
|
|
51
|
+
def write(target: Path) -> None:
|
|
52
|
+
frame.to_csv(target, index=False, sep=separator)
|
|
53
|
+
|
|
54
|
+
elif suffix in {".xlsx", ".xlsm"}:
|
|
55
|
+
|
|
56
|
+
def write(target: Path) -> None:
|
|
57
|
+
frame.to_excel(target, index=False, sheet_name=sheet_name[:31] or "Data")
|
|
58
|
+
|
|
59
|
+
elif suffix in {".parquet", ".pq"}:
|
|
60
|
+
|
|
61
|
+
def write(target: Path) -> None:
|
|
62
|
+
frame.to_parquet(target, index=False)
|
|
63
|
+
|
|
64
|
+
elif suffix == ".json":
|
|
65
|
+
|
|
66
|
+
def write(target: Path) -> None:
|
|
67
|
+
frame.to_json(target, orient="records", indent=2, date_format="iso")
|
|
68
|
+
|
|
69
|
+
else:
|
|
70
|
+
raise ExportError(f"Unsupported export type: {suffix or 'unknown'}")
|
|
71
|
+
return atomic_write(path, write)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def export_dataframe(frame: pd.DataFrame, path: str | Path) -> Path:
|
|
75
|
+
path = Path(path)
|
|
76
|
+
suffix = path.suffix.lower()
|
|
77
|
+
if suffix in {".csv", ".tsv", ".txt"}:
|
|
78
|
+
|
|
79
|
+
def write(target: Path) -> None:
|
|
80
|
+
frame.to_csv(target, index=False, sep="\t" if suffix == ".tsv" else ",")
|
|
81
|
+
|
|
82
|
+
elif suffix in {".xlsx", ".xlsm"}:
|
|
83
|
+
|
|
84
|
+
def write(target: Path) -> None:
|
|
85
|
+
frame.to_excel(target, index=False)
|
|
86
|
+
|
|
87
|
+
elif suffix in {".parquet", ".pq"}:
|
|
88
|
+
|
|
89
|
+
def write(target: Path) -> None:
|
|
90
|
+
frame.to_parquet(target, index=False)
|
|
91
|
+
|
|
92
|
+
elif suffix == ".json":
|
|
93
|
+
|
|
94
|
+
def write(target: Path) -> None:
|
|
95
|
+
frame.to_json(target, orient="records", indent=2, date_format="iso")
|
|
96
|
+
|
|
97
|
+
else:
|
|
98
|
+
raise ExportError(f"Unsupported export type: {suffix or 'unknown'}")
|
|
99
|
+
return atomic_write(path, write)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass, replace
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from statstudio.core.table import DataTable
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FileImportError(ValueError):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class CSVOptions:
|
|
19
|
+
delimiter: str | None = None
|
|
20
|
+
encoding: str | None = None
|
|
21
|
+
header: int | None = 0
|
|
22
|
+
decimal: str = "."
|
|
23
|
+
thousands: str | None = None
|
|
24
|
+
na_values: list[str] | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _clean_frame(frame: pd.DataFrame) -> pd.DataFrame:
|
|
28
|
+
frame = frame.copy()
|
|
29
|
+
names: list[str] = []
|
|
30
|
+
used: set[str] = set()
|
|
31
|
+
for index, column in enumerate(frame.columns):
|
|
32
|
+
name = str(column).strip()
|
|
33
|
+
if not name or name.lower().startswith("unnamed:"):
|
|
34
|
+
name = f"Column {index + 1}"
|
|
35
|
+
if name in used:
|
|
36
|
+
base = name
|
|
37
|
+
suffix = 2
|
|
38
|
+
while f"{base}_{suffix}" in used:
|
|
39
|
+
suffix += 1
|
|
40
|
+
name = f"{base}_{suffix}"
|
|
41
|
+
used.add(name)
|
|
42
|
+
names.append(name)
|
|
43
|
+
frame.columns = names
|
|
44
|
+
return frame
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _trim_empty_edges(frame: pd.DataFrame) -> pd.DataFrame:
|
|
48
|
+
"""Drop fully empty trailing rows and columns from clipboard-style data."""
|
|
49
|
+
if frame.empty:
|
|
50
|
+
return frame
|
|
51
|
+
while len(frame.columns) and frame.iloc[:, -1].isna().all():
|
|
52
|
+
frame = frame.iloc[:, :-1]
|
|
53
|
+
while len(frame.index) and frame.iloc[-1].isna().all():
|
|
54
|
+
frame = frame.iloc[:-1]
|
|
55
|
+
return frame
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _convert_date_columns(frame: pd.DataFrame) -> pd.DataFrame:
|
|
59
|
+
"""Best-effort date detection for text columns."""
|
|
60
|
+
for column in frame.columns:
|
|
61
|
+
series = frame[column]
|
|
62
|
+
if series.dtype != object:
|
|
63
|
+
continue
|
|
64
|
+
non_missing = series.dropna()
|
|
65
|
+
if non_missing.empty:
|
|
66
|
+
continue
|
|
67
|
+
sample = non_missing.head(200).astype(str)
|
|
68
|
+
date_shape = (
|
|
69
|
+
r"\d{1,4}[-/]\d{1,2}[-/]\d{1,4}"
|
|
70
|
+
r"|\d{1,2}[-/][A-Za-z]{3,}[-/]\d{2,4}"
|
|
71
|
+
)
|
|
72
|
+
if not sample.str.contains(r"[-/]", regex=True).all():
|
|
73
|
+
continue
|
|
74
|
+
if not sample.str.contains(date_shape, regex=True).all():
|
|
75
|
+
continue
|
|
76
|
+
parsed = pd.to_datetime(series, errors="coerce")
|
|
77
|
+
if parsed.notna().sum() == len(non_missing):
|
|
78
|
+
frame[column] = parsed
|
|
79
|
+
return frame
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _read_csv(path: Path, options: CSVOptions) -> pd.DataFrame:
|
|
83
|
+
encodings = [options.encoding] if options.encoding else ["utf-8", "utf-8-sig", "latin-1"]
|
|
84
|
+
last_error: Exception | None = None
|
|
85
|
+
for encoding in encodings:
|
|
86
|
+
if encoding is None:
|
|
87
|
+
continue
|
|
88
|
+
try:
|
|
89
|
+
kwargs: dict[str, Any] = {
|
|
90
|
+
"encoding": encoding,
|
|
91
|
+
"decimal": options.decimal,
|
|
92
|
+
"thousands": options.thousands,
|
|
93
|
+
}
|
|
94
|
+
if options.delimiter:
|
|
95
|
+
kwargs["sep"] = options.delimiter
|
|
96
|
+
else:
|
|
97
|
+
kwargs["sep"] = None
|
|
98
|
+
kwargs["engine"] = "python"
|
|
99
|
+
if options.header is None:
|
|
100
|
+
kwargs["header"] = None
|
|
101
|
+
kwargs["names"] = None
|
|
102
|
+
else:
|
|
103
|
+
kwargs["header"] = options.header
|
|
104
|
+
if options.na_values:
|
|
105
|
+
kwargs["na_values"] = options.na_values
|
|
106
|
+
if options.header is None:
|
|
107
|
+
frame = pd.read_csv(path, **kwargs)
|
|
108
|
+
frame.columns = [f"Column {i + 1}" for i in range(frame.shape[1])]
|
|
109
|
+
else:
|
|
110
|
+
frame = pd.read_csv(path, **kwargs)
|
|
111
|
+
return _convert_date_columns(frame)
|
|
112
|
+
except Exception as exc: # pragma: no cover - encoding fallbacks
|
|
113
|
+
last_error = exc
|
|
114
|
+
continue
|
|
115
|
+
raise FileImportError(f"Could not read {path.name}: {last_error}")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def read_file(path: str | Path, options: CSVOptions | None = None, sheet_name: str | int = 0) -> DataTable:
|
|
119
|
+
path = Path(path)
|
|
120
|
+
suffix = path.suffix.lower()
|
|
121
|
+
if suffix in {".csv", ".tsv", ".txt"}:
|
|
122
|
+
if suffix == ".tsv" and (options is None or not options.delimiter):
|
|
123
|
+
options = replace(options, delimiter="\t") if options else CSVOptions(delimiter="\t")
|
|
124
|
+
frame = _read_csv(path, options or CSVOptions())
|
|
125
|
+
elif suffix in {".xlsx", ".xlsm", ".xls"}:
|
|
126
|
+
frame = pd.read_excel(path, sheet_name=sheet_name)
|
|
127
|
+
elif suffix in {".parquet", ".pq"}:
|
|
128
|
+
frame = pd.read_parquet(path)
|
|
129
|
+
elif suffix in {".json", ".jsonl"}:
|
|
130
|
+
frame = pd.read_json(path, lines=suffix == ".jsonl")
|
|
131
|
+
elif suffix == ".dta":
|
|
132
|
+
frame = pd.read_stata(path)
|
|
133
|
+
for candidate in ("index", ""):
|
|
134
|
+
if candidate in frame.columns and pd.api.types.is_integer_dtype(frame[candidate]):
|
|
135
|
+
if frame[candidate].tolist() == list(range(len(frame))):
|
|
136
|
+
frame = frame.drop(columns=[candidate])
|
|
137
|
+
elif suffix == ".sav":
|
|
138
|
+
try:
|
|
139
|
+
frame = pd.read_spss(path)
|
|
140
|
+
except Exception as exc:
|
|
141
|
+
raise FileImportError("Reading SPSS files requires the 'pyreadstat' package.") from exc
|
|
142
|
+
elif suffix in {".sas7bdat", ".xpt"}:
|
|
143
|
+
frame = pd.read_sas(path)
|
|
144
|
+
else:
|
|
145
|
+
raise FileImportError(f"Unsupported file type: {suffix or 'unknown'}")
|
|
146
|
+
frame = _clean_frame(frame)
|
|
147
|
+
table = DataTable(frame, name=path.stem, source=str(path))
|
|
148
|
+
table.metadata["import"] = {"path": str(path), "suffix": suffix}
|
|
149
|
+
return table
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def parse_clipboard_frame(text: str, delimiter: str | None = None, header: bool = True) -> pd.DataFrame:
|
|
153
|
+
if not text or not text.strip():
|
|
154
|
+
raise FileImportError("The clipboard is empty.")
|
|
155
|
+
kwargs: dict[str, Any] = {"sep": delimiter, "engine": "python"}
|
|
156
|
+
if delimiter is None:
|
|
157
|
+
kwargs["sep"] = None
|
|
158
|
+
if header:
|
|
159
|
+
kwargs["header"] = 0
|
|
160
|
+
else:
|
|
161
|
+
kwargs["header"] = None
|
|
162
|
+
try:
|
|
163
|
+
frame = pd.read_csv(pd.io.common.StringIO(text), **kwargs)
|
|
164
|
+
except Exception as exc:
|
|
165
|
+
raise FileImportError(f"Could not parse clipboard data: {exc}") from exc
|
|
166
|
+
if not header:
|
|
167
|
+
frame.columns = [f"Column {i + 1}" for i in range(frame.shape[1])]
|
|
168
|
+
return _clean_frame(_trim_empty_edges(frame))
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def read_clipboard() -> DataTable:
|
|
172
|
+
frame = pd.read_clipboard()
|
|
173
|
+
return DataTable(_clean_frame(frame), name="Clipboard", source="Clipboard")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def excel_sheet_names(path: str | Path) -> list[str]:
|
|
177
|
+
try:
|
|
178
|
+
excel = pd.ExcelFile(path)
|
|
179
|
+
return list(excel.sheet_names)
|
|
180
|
+
except Exception:
|
|
181
|
+
return []
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def guess_delimiter(path: str | Path) -> str:
|
|
185
|
+
path = Path(path)
|
|
186
|
+
try:
|
|
187
|
+
sample = path.read_text(encoding="utf-8", errors="replace")[:8192]
|
|
188
|
+
except Exception:
|
|
189
|
+
return ","
|
|
190
|
+
counts = {sep: sample.count(sep) for sep in [",", "\t", ";", "|"]}
|
|
191
|
+
return max(counts, key=counts.get) if any(counts.values()) else ","
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def safe_column_names(columns: list[str]) -> list[str]:
|
|
195
|
+
result = []
|
|
196
|
+
for column in columns:
|
|
197
|
+
cleaned = re.sub(r"\s+", " ", str(column)).strip()
|
|
198
|
+
result.append(cleaned or "Column")
|
|
199
|
+
return result
|