margin-data-storyteller 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.
- data_storyteller/__init__.py +8 -0
- data_storyteller/agent.py +150 -0
- data_storyteller/cleaning.py +510 -0
- data_storyteller/columns.py +627 -0
- data_storyteller/facts/__init__.py +11 -0
- data_storyteller/facts/base.py +333 -0
- data_storyteller/facts/breakdown.py +230 -0
- data_storyteller/facts/engine.py +342 -0
- data_storyteller/facts/relations.py +438 -0
- data_storyteller/facts/verify.py +71 -0
- data_storyteller/ingest.py +246 -0
- data_storyteller/layout.py +174 -0
- data_storyteller/models.py +308 -0
- data_storyteller/names.py +20 -0
- data_storyteller/profile.py +363 -0
- data_storyteller/py.typed +0 -0
- data_storyteller/report.py +251 -0
- data_storyteller/setup.py +252 -0
- data_storyteller/story/__init__.py +6 -0
- data_storyteller/story/charts.py +223 -0
- data_storyteller/story/plan.py +224 -0
- data_storyteller/story/template.py +102 -0
- data_storyteller/story/tokens.py +98 -0
- data_storyteller/story/validate.py +205 -0
- data_storyteller/story/write.py +201 -0
- data_storyteller/values.py +335 -0
- margin_data_storyteller-0.1.0.dist-info/METADATA +183 -0
- margin_data_storyteller-0.1.0.dist-info/RECORD +31 -0
- margin_data_storyteller-0.1.0.dist-info/WHEEL +4 -0
- margin_data_storyteller-0.1.0.dist-info/entry_points.txt +2 -0
- margin_data_storyteller-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Data Storyteller."""
|
|
2
|
+
|
|
3
|
+
from data_storyteller.agent import DataStorytellerAgent
|
|
4
|
+
from data_storyteller.models import DataStorytellerInput, DataStorytellerOutput
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
|
|
8
|
+
__all__ = ["DataStorytellerAgent", "DataStorytellerInput", "DataStorytellerOutput", "__version__"]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Data Storyteller: cleans a table, explains every change, and sets up the story in it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from margin_core import AgentResult, Answer, BaseAgent, Choice, Question, RunContext
|
|
10
|
+
from margin_core.models import ResultStatus
|
|
11
|
+
|
|
12
|
+
from data_storyteller.models import DataStorytellerInput, DataStorytellerOutput
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from data_storyteller.ingest import Source
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DataStorytellerAgent(BaseAgent):
|
|
19
|
+
id = "data-storyteller"
|
|
20
|
+
name = "Data Storyteller"
|
|
21
|
+
description = (
|
|
22
|
+
"Cleans a table of data, shows every change it made, and tells the story in it with charts."
|
|
23
|
+
)
|
|
24
|
+
version = "0.1.0"
|
|
25
|
+
InputModel = DataStorytellerInput
|
|
26
|
+
OutputModel = DataStorytellerOutput
|
|
27
|
+
primary_input = "dataset"
|
|
28
|
+
uses_llm = True # to write the story; cleaning and facts never call a model
|
|
29
|
+
|
|
30
|
+
async def run(self, input: DataStorytellerInput, ctx: RunContext) -> AgentResult:
|
|
31
|
+
# imported here, not at the top: listing agents (margin list, GET /agents) should not
|
|
32
|
+
# load pandas, scipy and duckdb
|
|
33
|
+
from data_storyteller import cleaning, facts, report, setup, story
|
|
34
|
+
from data_storyteller.ingest import read_source
|
|
35
|
+
from data_storyteller.profile import profile
|
|
36
|
+
|
|
37
|
+
ctx.report_progress("read", f"Reading {Path(input.dataset).name}", 0.05)
|
|
38
|
+
source = await asyncio.to_thread(read_source, input.dataset)
|
|
39
|
+
table = await self._choose_table(source, input, ctx)
|
|
40
|
+
|
|
41
|
+
ctx.check_cancelled()
|
|
42
|
+
ctx.report_progress("inspect", "Checking every column", 0.2)
|
|
43
|
+
plan = await asyncio.to_thread(cleaning.plan, source.tables[table])
|
|
44
|
+
questions = list(plan.questions)
|
|
45
|
+
if input.stop_after == "story":
|
|
46
|
+
provisional = cleaning.apply(
|
|
47
|
+
plan, {q.id: Answer.of(q, q.default, "default") for q in questions}
|
|
48
|
+
)
|
|
49
|
+
questions += setup.questions(profile(provisional))
|
|
50
|
+
|
|
51
|
+
answers: dict[str, Answer] = {}
|
|
52
|
+
if questions:
|
|
53
|
+
answers = await ctx.ask(
|
|
54
|
+
questions,
|
|
55
|
+
title="Check the data",
|
|
56
|
+
detail="Nothing has changed yet. These parts of the file can be read more than "
|
|
57
|
+
"one way; the suggested answer is marked.",
|
|
58
|
+
preset=input.answers,
|
|
59
|
+
assume_defaults=input.assume_defaults,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
ctx.check_cancelled()
|
|
63
|
+
ctx.report_progress("clean", "Cleaning", 0.6)
|
|
64
|
+
clean = await asyncio.to_thread(cleaning.apply, plan, answers)
|
|
65
|
+
ctx.report_progress("profile", "Describing the columns", 0.8)
|
|
66
|
+
columns = profile(clean)
|
|
67
|
+
data = report.output(source, table, clean, columns)
|
|
68
|
+
|
|
69
|
+
status: ResultStatus = "ok"
|
|
70
|
+
warnings: list[str] = []
|
|
71
|
+
if input.stop_after == "story":
|
|
72
|
+
data.setup, problems = setup.resolve(columns, answers)
|
|
73
|
+
warnings += problems
|
|
74
|
+
ctx.check_cancelled()
|
|
75
|
+
ctx.report_progress("facts", "Computing the facts, then checking each one", 0.75)
|
|
76
|
+
found = await asyncio.to_thread(facts.compute, clean.frame, columns, data.setup)
|
|
77
|
+
data.facts = await asyncio.to_thread(facts.verify, clean.frame, found)
|
|
78
|
+
|
|
79
|
+
# checkpoint 2: what the story tells, and context only the person has
|
|
80
|
+
chosen = await ctx.ask(
|
|
81
|
+
story.questions(data.facts, data.setup.north_star),
|
|
82
|
+
title="Choose the story",
|
|
83
|
+
detail="These are the facts worth telling, each checked twice. Pick what the "
|
|
84
|
+
"story should cover.",
|
|
85
|
+
preset=input.answers,
|
|
86
|
+
assume_defaults=input.assume_defaults,
|
|
87
|
+
)
|
|
88
|
+
answers |= chosen
|
|
89
|
+
plan_ = story.build(data.facts, data.setup.north_star, chosen)
|
|
90
|
+
ctx.check_cancelled()
|
|
91
|
+
ctx.report_progress("story", "Writing the story", 0.85)
|
|
92
|
+
rows = f"{len(clean.frame):,} rows, one {data.setup.grain.removeprefix('one ')} each"
|
|
93
|
+
data.story = await story.write(
|
|
94
|
+
ctx.llm,
|
|
95
|
+
plan_,
|
|
96
|
+
data.facts,
|
|
97
|
+
about=f"Data: {source.path.name}, {rows}. Main number: "
|
|
98
|
+
f"{data.setup.north_star or 'the number of rows'}.",
|
|
99
|
+
title=f"What {source.path.name} shows",
|
|
100
|
+
columns=[c.name for c in columns],
|
|
101
|
+
warn=ctx.warn,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
if input.output_dir:
|
|
105
|
+
ctx.report_progress("write", f"Writing to {input.output_dir}", 0.9)
|
|
106
|
+
data.files = await asyncio.to_thread(
|
|
107
|
+
report.write, input.output_dir, data, clean, answers
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
ctx.report_progress("done", "Finished", 1.0)
|
|
111
|
+
assumed = sum(a.source == "default" for a in answers.values())
|
|
112
|
+
return self.make_result(
|
|
113
|
+
summary=report.summary(data, assumed),
|
|
114
|
+
output=data,
|
|
115
|
+
findings=report.findings(data, answers),
|
|
116
|
+
warnings=warnings,
|
|
117
|
+
status=status,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
async def _choose_table(
|
|
121
|
+
self, source: Source, input: DataStorytellerInput, ctx: RunContext
|
|
122
|
+
) -> str:
|
|
123
|
+
names = list(source.tables)
|
|
124
|
+
if input.table is not None:
|
|
125
|
+
if input.table not in source.tables:
|
|
126
|
+
raise ValueError(
|
|
127
|
+
f"{source.path.name} has no table {input.table!r}; it has {', '.join(names)}"
|
|
128
|
+
)
|
|
129
|
+
return input.table
|
|
130
|
+
if len(names) == 1:
|
|
131
|
+
return names[0]
|
|
132
|
+
largest = max(names, key=lambda n: len(source.tables[n].rows))
|
|
133
|
+
answers = await ctx.ask(
|
|
134
|
+
[
|
|
135
|
+
Question(
|
|
136
|
+
id="table",
|
|
137
|
+
prompt=f"{source.path.name} has {len(names)} tables. "
|
|
138
|
+
"Which one should be cleaned?",
|
|
139
|
+
choices=[
|
|
140
|
+
Choice(value=n, label=n, detail=f"{len(source.tables[n].rows):,} rows")
|
|
141
|
+
for n in names
|
|
142
|
+
],
|
|
143
|
+
default=largest,
|
|
144
|
+
)
|
|
145
|
+
],
|
|
146
|
+
title="Choose the table",
|
|
147
|
+
preset=input.answers,
|
|
148
|
+
assume_defaults=input.assume_defaults,
|
|
149
|
+
)
|
|
150
|
+
return str(answers["table"].value)
|
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
"""Cleaning a whole table: plan it, ask what is unclear, apply it, and check the result.
|
|
2
|
+
|
|
3
|
+
Planning reads the layout and every column, then looks for whole-row problems (empty rows,
|
|
4
|
+
total rows, duplicates) on a first, provisional clean. Applying repeats the clean with the
|
|
5
|
+
answers. The check at the end compares the raw table with the result, independently of
|
|
6
|
+
the steps: every value present in the file is either in the result or was left empty by
|
|
7
|
+
a step that says so, and every removed row is removed by exactly one step.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import pandas as pd
|
|
17
|
+
from margin_core import Answer, Choice, Evidence, Question
|
|
18
|
+
|
|
19
|
+
from data_storyteller.columns import (
|
|
20
|
+
MAX_EXAMPLES,
|
|
21
|
+
ColumnPlan,
|
|
22
|
+
ColumnResult,
|
|
23
|
+
Kind,
|
|
24
|
+
StepRecord,
|
|
25
|
+
decided,
|
|
26
|
+
show,
|
|
27
|
+
)
|
|
28
|
+
from data_storyteller.ingest import RawTable
|
|
29
|
+
from data_storyteller.layout import Layout, find_layout, is_empty
|
|
30
|
+
from data_storyteller.names import id_like
|
|
31
|
+
|
|
32
|
+
TOTAL_LABEL = re.compile(
|
|
33
|
+
r"^\s*(grand\s+total|sub-?\s?total|totals?|sum|الإجمالي|إجمالي|المجموع)\b", re.IGNORECASE
|
|
34
|
+
)
|
|
35
|
+
SUBTOTAL_LABEL = re.compile(r"^\s*sub-?\s?total", re.IGNORECASE)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class CleaningCheckError(Exception):
|
|
39
|
+
"""The result does not account for every value in the file (a bug, never expected)."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Plan:
|
|
44
|
+
table: RawTable
|
|
45
|
+
layout: Layout
|
|
46
|
+
rows: list[int] # file row number of each data row
|
|
47
|
+
columns: list[ColumnPlan]
|
|
48
|
+
questions: list[Question] = field(default_factory=list)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Clean:
|
|
53
|
+
"""The cleaned table and everything needed to explain it."""
|
|
54
|
+
|
|
55
|
+
frame: pd.DataFrame
|
|
56
|
+
rows: list[int] # file row number of each remaining row
|
|
57
|
+
kinds: dict[str, Kind]
|
|
58
|
+
units: dict[str, str]
|
|
59
|
+
sources: dict[str, str] # column -> its name in the file ("" for added columns)
|
|
60
|
+
steps: list[StepRecord]
|
|
61
|
+
notes: dict[str, list[str]]
|
|
62
|
+
rows_in: int
|
|
63
|
+
header_row: int | None
|
|
64
|
+
title_text: list[str]
|
|
65
|
+
check: list[str] # what the final check verified
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def plan(table: RawTable) -> Plan:
|
|
69
|
+
layout = find_layout(table.rows, table.header)
|
|
70
|
+
data = table.rows[layout.first_data_row :]
|
|
71
|
+
offset = 2 if table.header is not None else layout.first_data_row + 1
|
|
72
|
+
rows = [offset + i for i in range(len(data))]
|
|
73
|
+
columns = [
|
|
74
|
+
ColumnPlan.plan(name, [r[j] if j < len(r) else None for r in data], rows)
|
|
75
|
+
for j, name in enumerate(layout.names)
|
|
76
|
+
]
|
|
77
|
+
result = Plan(table, layout, rows, columns)
|
|
78
|
+
|
|
79
|
+
if layout.group_row is not None:
|
|
80
|
+
pairs = list(zip(layout.combined_names, layout.names, strict=True))
|
|
81
|
+
differ = [(c, n) for c, n in pairs if c != n][:3]
|
|
82
|
+
upper, lower = layout.group_row + 1, (layout.header_row or 0) + 1
|
|
83
|
+
result.questions.append(
|
|
84
|
+
Question(
|
|
85
|
+
id="header",
|
|
86
|
+
prompt="The column names are split over two rows. How should they be named?",
|
|
87
|
+
detail=f"Row {upper} groups the names on row {lower}.",
|
|
88
|
+
section="Layout",
|
|
89
|
+
choices=[
|
|
90
|
+
Choice(
|
|
91
|
+
value="combined",
|
|
92
|
+
label="Combine both rows",
|
|
93
|
+
detail=", ".join(c for c, _ in differ),
|
|
94
|
+
),
|
|
95
|
+
Choice(
|
|
96
|
+
value="lower",
|
|
97
|
+
label=f"Use row {lower} only",
|
|
98
|
+
detail=", ".join(n for _, n in differ),
|
|
99
|
+
),
|
|
100
|
+
],
|
|
101
|
+
default="combined",
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
for col in columns:
|
|
105
|
+
result.questions.extend(col.questions)
|
|
106
|
+
|
|
107
|
+
# whole-row problems, found on a provisional clean with the suggested answers
|
|
108
|
+
provisional = _apply_columns(result, _defaults(result.questions))
|
|
109
|
+
frame, kinds = provisional
|
|
110
|
+
totals = find_totals(frame, kinds)
|
|
111
|
+
unsure = [i for i, confident in totals if not confident]
|
|
112
|
+
if unsure:
|
|
113
|
+
result.questions.append(
|
|
114
|
+
Question(
|
|
115
|
+
id="total_rows",
|
|
116
|
+
prompt=f"Remove {_rows_text([rows[i] for i in unsure])}? They look like totals.",
|
|
117
|
+
detail="A total row counted as data would double every sum.",
|
|
118
|
+
section="Rows",
|
|
119
|
+
choices=[
|
|
120
|
+
Choice(value="remove", label="Remove them"),
|
|
121
|
+
Choice(value="keep", label="Keep them as data"),
|
|
122
|
+
],
|
|
123
|
+
default="remove",
|
|
124
|
+
evidence=[
|
|
125
|
+
Evidence(kind="row", location=f"row {rows[i]}", detail=_row_text(frame, i))
|
|
126
|
+
for i in unsure[:MAX_EXAMPLES]
|
|
127
|
+
],
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
duplicates = find_duplicates(frame.drop(index=[i for i, _ in totals]))
|
|
131
|
+
if duplicates and not has_id(frame):
|
|
132
|
+
copies = [i for i, _ in duplicates]
|
|
133
|
+
result.questions.append(
|
|
134
|
+
Question(
|
|
135
|
+
id="duplicates",
|
|
136
|
+
prompt=f"Remove {len(copies):,} repeated row{'s' if len(copies) != 1 else ''}?",
|
|
137
|
+
detail=(
|
|
138
|
+
"These rows are exact copies of earlier rows. With no id column, they "
|
|
139
|
+
"could be two real, identical records."
|
|
140
|
+
),
|
|
141
|
+
section="Rows",
|
|
142
|
+
choices=[
|
|
143
|
+
Choice(value="remove", label="Remove the copies"),
|
|
144
|
+
Choice(value="keep", label="Keep them; they are separate records"),
|
|
145
|
+
],
|
|
146
|
+
default="remove",
|
|
147
|
+
evidence=[
|
|
148
|
+
Evidence(
|
|
149
|
+
kind="row",
|
|
150
|
+
location=f"row {rows[i]}",
|
|
151
|
+
detail=f"Same as row {rows[first]}: {_row_text(frame, i)}",
|
|
152
|
+
)
|
|
153
|
+
for i, first in duplicates[:MAX_EXAMPLES]
|
|
154
|
+
],
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
return result
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _defaults(questions: list[Question]) -> dict[str, Answer]:
|
|
161
|
+
return {q.id: Answer.of(q, q.default, "default") for q in questions}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _rows_text(rows: list[int]) -> str:
|
|
165
|
+
if len(rows) == 1:
|
|
166
|
+
return f"row {rows[0]}"
|
|
167
|
+
return f"rows {', '.join(map(str, rows[:-1]))} and {rows[-1]}"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _row_text(frame: pd.DataFrame, i: int) -> str:
|
|
171
|
+
cells = [f"{c}={show(v)}" for c, v in frame.loc[i].items() if v is not None and not pd.isna(v)]
|
|
172
|
+
text = ", ".join(cells[:8])
|
|
173
|
+
return text + (", …" if len(cells) > 8 else "")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _apply_columns(p: Plan, answers: dict[str, Answer]) -> tuple[pd.DataFrame, dict[str, Kind]]:
|
|
177
|
+
assembled = _assemble(p, [c.apply(answers) for c in p.columns], answers)
|
|
178
|
+
return assembled.frame, assembled.kinds
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass
|
|
182
|
+
class _Assembled:
|
|
183
|
+
frame: pd.DataFrame
|
|
184
|
+
kinds: dict[str, Kind]
|
|
185
|
+
sources: dict[str, str] # column -> its name in the file ("" for added columns)
|
|
186
|
+
names: list[str] # the final name of each planned column, in plan order
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _assemble(p: Plan, results: list[ColumnResult], answers: dict[str, Answer]) -> _Assembled:
|
|
190
|
+
names = p.layout.names
|
|
191
|
+
if "header" in answers and answers["header"].value == "combined":
|
|
192
|
+
names = p.layout.combined_names
|
|
193
|
+
data: dict[str, Any] = {}
|
|
194
|
+
kinds: dict[str, Kind] = {}
|
|
195
|
+
sources: dict[str, str] = {}
|
|
196
|
+
for name, written, result in zip(names, p.layout.source_names, results, strict=True):
|
|
197
|
+
data[name] = _series(result.values, result.kind)
|
|
198
|
+
kinds[name], sources[name] = result.kind, written or name
|
|
199
|
+
for extra, values in result.extra.items():
|
|
200
|
+
data[extra] = _series(values, "text")
|
|
201
|
+
kinds[extra], sources[extra] = "text", ""
|
|
202
|
+
frame = pd.DataFrame(data, index=range(len(p.rows)))
|
|
203
|
+
return _Assembled(frame, kinds, sources, list(names))
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _series(values: list[Any], kind: Kind) -> pd.Series:
|
|
207
|
+
if kind == "number":
|
|
208
|
+
if all(v is None or isinstance(v, int) for v in values):
|
|
209
|
+
return pd.Series(values, dtype="Int64")
|
|
210
|
+
return pd.Series([float("nan") if v is None else v for v in values], dtype="float64")
|
|
211
|
+
if kind == "date":
|
|
212
|
+
return pd.to_datetime(pd.Series(values, dtype="object"))
|
|
213
|
+
return pd.Series(values, dtype="object")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def find_totals(frame: pd.DataFrame, kinds: dict[str, Kind]) -> list[tuple[int, bool]]:
|
|
217
|
+
"""Rows that look like totals: (index, confident). Confident means labelled as a total
|
|
218
|
+
and every number in it equals the sum of the rows it would total.
|
|
219
|
+
|
|
220
|
+
Only the last rows, and rows labelled as subtotals, can be totals, so only those are
|
|
221
|
+
looked at: the rest of a large table is never walked row by row.
|
|
222
|
+
"""
|
|
223
|
+
if len(frame) < 3:
|
|
224
|
+
return []
|
|
225
|
+
ids = [c for c in frame.columns if id_like(str(c))]
|
|
226
|
+
numeric = [c for c, k in kinds.items() if k == "number" and c in frame and c not in ids]
|
|
227
|
+
texts = [c for c, k in kinds.items() if k == "text" and c in frame]
|
|
228
|
+
filled = frame.index[frame.notna().any(axis=1)].tolist()
|
|
229
|
+
candidates = set(filled[-3:])
|
|
230
|
+
for c in texts:
|
|
231
|
+
written = frame[c].dropna().astype(str)
|
|
232
|
+
candidates |= set(written.index[written.str.match(SUBTOTAL_LABEL)].tolist())
|
|
233
|
+
found: list[tuple[int, bool]] = []
|
|
234
|
+
for i in sorted(candidates):
|
|
235
|
+
if any(pd.notna(frame.at[i, c]) for c in ids):
|
|
236
|
+
continue # a row with a record id is a record
|
|
237
|
+
labels = [str(frame.at[i, c]) for c in texts if pd.notna(frame.at[i, c])]
|
|
238
|
+
labelled = any(TOTAL_LABEL.match(t) for t in labels)
|
|
239
|
+
last = i in filled[-3:]
|
|
240
|
+
subtotal = any(SUBTOTAL_LABEL.match(t) for t in labels)
|
|
241
|
+
# unlabelled: only the last row, only where the label cells exist and are blank
|
|
242
|
+
unlabelled = i == filled[-1] and bool(texts) and not labels
|
|
243
|
+
if not (labelled and (last or subtotal)) and not unlabelled:
|
|
244
|
+
continue
|
|
245
|
+
others = frame.drop(index=[i, *[j for j, _ in found]])
|
|
246
|
+
sums = [
|
|
247
|
+
_close(frame.at[i, c], others[c].sum()) for c in numeric if pd.notna(frame.at[i, c])
|
|
248
|
+
]
|
|
249
|
+
if not sums:
|
|
250
|
+
continue
|
|
251
|
+
if labelled:
|
|
252
|
+
found.append((i, all(sums) and not subtotal))
|
|
253
|
+
elif all(sums) and len(sums) >= 1:
|
|
254
|
+
found.append((i, False)) # an unlabelled last row equal to the sums above
|
|
255
|
+
return found
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _close(a: Any, b: Any) -> bool:
|
|
259
|
+
x, y = float(a), float(b)
|
|
260
|
+
return abs(x - y) <= 1e-9 * max(1.0, abs(x), abs(y)) + 0.005
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def find_duplicates(frame: pd.DataFrame) -> list[tuple[int, int]]:
|
|
264
|
+
"""(copy, first occurrence) for every row that repeats an earlier row exactly."""
|
|
265
|
+
if frame.empty:
|
|
266
|
+
return []
|
|
267
|
+
columns = [[None if pd.isna(v) else v for v in frame[c].tolist()] for c in frame.columns]
|
|
268
|
+
first: dict[tuple[Any, ...], int] = {}
|
|
269
|
+
pairs = []
|
|
270
|
+
for i, key in zip(frame.index, zip(*columns, strict=True), strict=True):
|
|
271
|
+
if key in first:
|
|
272
|
+
pairs.append((int(i), first[key]))
|
|
273
|
+
else:
|
|
274
|
+
first[key] = int(i)
|
|
275
|
+
return pairs
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def has_id(frame: pd.DataFrame) -> bool:
|
|
279
|
+
"""Whether a column looks like a record id: named like one, and unique once exact
|
|
280
|
+
copies of rows are left out."""
|
|
281
|
+
frame = frame.drop(index=[i for i, _ in find_duplicates(frame)])
|
|
282
|
+
for column in frame.columns:
|
|
283
|
+
if id_like(str(column)):
|
|
284
|
+
values = frame[column].dropna()
|
|
285
|
+
if len(values) and values.nunique() >= 0.9 * len(values):
|
|
286
|
+
return True
|
|
287
|
+
return False
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
# ---- applying ---------------------------------------------------------------------------
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def apply(p: Plan, answers: dict[str, Answer]) -> Clean:
|
|
294
|
+
results = [c.apply(answers) for c in p.columns]
|
|
295
|
+
assembled = _assemble(p, results, answers)
|
|
296
|
+
frame, kinds, sources = assembled.frame, assembled.kinds, assembled.sources
|
|
297
|
+
final = dict(zip(p.layout.names, assembled.names, strict=True)) # plan name -> final name
|
|
298
|
+
units = {final[c.name]: r.unit for c, r in zip(p.columns, results, strict=True) if r.unit}
|
|
299
|
+
notes = {final[c.name]: r.notes for c, r in zip(p.columns, results, strict=True) if r.notes}
|
|
300
|
+
steps: list[StepRecord] = _layout_steps(p, answers)
|
|
301
|
+
for result in results:
|
|
302
|
+
for step in result.steps:
|
|
303
|
+
step.column = final.get(step.column or "", step.column)
|
|
304
|
+
steps.extend(result.steps)
|
|
305
|
+
|
|
306
|
+
# empty columns: nothing left in them
|
|
307
|
+
empty = [c for c in frame.columns if frame[c].isna().all()]
|
|
308
|
+
if empty:
|
|
309
|
+
steps.append(
|
|
310
|
+
StepRecord(
|
|
311
|
+
id="empty_columns",
|
|
312
|
+
kind="empty_columns",
|
|
313
|
+
summary=f"Dropped {len(empty)} empty column{'s' if len(empty) != 1 else ''}: "
|
|
314
|
+
+ ", ".join(empty[:10])
|
|
315
|
+
+ (", …" if len(empty) > 10 else ""),
|
|
316
|
+
)
|
|
317
|
+
)
|
|
318
|
+
frame = frame.drop(columns=empty)
|
|
319
|
+
for c in empty:
|
|
320
|
+
kinds.pop(c)
|
|
321
|
+
|
|
322
|
+
removed: set[int] = set()
|
|
323
|
+
|
|
324
|
+
blank = [int(i) for i in frame.index[frame.isna().all(axis=1)]]
|
|
325
|
+
if blank:
|
|
326
|
+
removed |= set(blank)
|
|
327
|
+
steps.append(
|
|
328
|
+
StepRecord(
|
|
329
|
+
id="empty_rows",
|
|
330
|
+
kind="empty_rows",
|
|
331
|
+
summary=f"Removed {len(blank):,} empty row{'s' if len(blank) != 1 else ''}",
|
|
332
|
+
removed_rows=set(blank),
|
|
333
|
+
examples=[(p.rows[i], "", None) for i in blank[:MAX_EXAMPLES]],
|
|
334
|
+
)
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
live = frame.drop(index=sorted(removed))
|
|
338
|
+
totals = find_totals(live, kinds)
|
|
339
|
+
remove_totals = "total_rows" not in answers or answers["total_rows"].value == "remove"
|
|
340
|
+
confident = [i for i, sure in totals if sure]
|
|
341
|
+
unsure = [i for i, sure in totals if not sure]
|
|
342
|
+
for chosen, by in ((confident, "rule"), (unsure if remove_totals else [], None)):
|
|
343
|
+
if not chosen:
|
|
344
|
+
continue
|
|
345
|
+
removed |= set(chosen)
|
|
346
|
+
steps.append(
|
|
347
|
+
StepRecord(
|
|
348
|
+
id="total_rows" if by is None else "total_rows:labelled",
|
|
349
|
+
kind="total_rows",
|
|
350
|
+
summary=f"Removed {_rows_text([p.rows[i] for i in chosen])}: "
|
|
351
|
+
+ (
|
|
352
|
+
"labelled as a total, and each number equals the sum of the rows above"
|
|
353
|
+
if by == "rule"
|
|
354
|
+
else "rows of totals"
|
|
355
|
+
),
|
|
356
|
+
decided_by="rule" if by == "rule" else decided(answers, ["total_rows"]),
|
|
357
|
+
question_ids=[] if by == "rule" else ["total_rows"],
|
|
358
|
+
removed_rows=set(chosen),
|
|
359
|
+
examples=[(p.rows[i], _row_text(frame, i), None) for i in chosen[:MAX_EXAMPLES]],
|
|
360
|
+
)
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
live = frame.drop(index=sorted(removed))
|
|
364
|
+
duplicates = find_duplicates(live)
|
|
365
|
+
keep_copies = "duplicates" in answers and answers["duplicates"].value == "keep"
|
|
366
|
+
if duplicates and not keep_copies:
|
|
367
|
+
copies = {i for i, _ in duplicates}
|
|
368
|
+
removed |= copies
|
|
369
|
+
asked = "duplicates" in answers
|
|
370
|
+
steps.append(
|
|
371
|
+
StepRecord(
|
|
372
|
+
id="duplicates",
|
|
373
|
+
kind="duplicates",
|
|
374
|
+
summary=f"Removed {len(copies):,} row{'s' if len(copies) != 1 else ''} that "
|
|
375
|
+
+ ("repeat" if len(copies) != 1 else "repeats")
|
|
376
|
+
+ " an earlier row exactly"
|
|
377
|
+
+ ("" if asked else ", id included, so they are copies"),
|
|
378
|
+
decided_by=decided(answers, ["duplicates"]) if asked else "rule",
|
|
379
|
+
question_ids=["duplicates"] if asked else [],
|
|
380
|
+
removed_rows=copies,
|
|
381
|
+
examples=[
|
|
382
|
+
(p.rows[i], f"same as row {p.rows[j]}", None)
|
|
383
|
+
for i, j in duplicates[:MAX_EXAMPLES]
|
|
384
|
+
],
|
|
385
|
+
)
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
kept = [i for i in range(len(p.rows)) if i not in removed]
|
|
389
|
+
out = frame.loc[kept].reset_index(drop=True)
|
|
390
|
+
clean = Clean(
|
|
391
|
+
frame=out,
|
|
392
|
+
rows=[p.rows[i] for i in kept],
|
|
393
|
+
kinds=kinds,
|
|
394
|
+
units={c: u for c, u in units.items() if c in out.columns},
|
|
395
|
+
sources={c: sources[c] for c in out.columns},
|
|
396
|
+
steps=steps,
|
|
397
|
+
notes=notes,
|
|
398
|
+
rows_in=len(p.rows),
|
|
399
|
+
header_row=None if p.layout.header_row is None else p.layout.header_row + 1,
|
|
400
|
+
title_text=p.layout.title_text,
|
|
401
|
+
check=[],
|
|
402
|
+
)
|
|
403
|
+
clean.check = verify(p, clean, results, assembled.names, kept, removed)
|
|
404
|
+
return clean
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _layout_steps(p: Plan, answers: dict[str, Answer]) -> list[StepRecord]:
|
|
408
|
+
layout = p.layout
|
|
409
|
+
steps = []
|
|
410
|
+
if layout.title_rows:
|
|
411
|
+
titles = "; ".join(f'"{t}"' for t in layout.title_text)
|
|
412
|
+
steps.append(
|
|
413
|
+
StepRecord(
|
|
414
|
+
id="title_rows",
|
|
415
|
+
kind="header",
|
|
416
|
+
summary=f"Skipped {_rows_text([i + 1 for i in layout.title_rows])} above the "
|
|
417
|
+
f"column names: {titles}",
|
|
418
|
+
)
|
|
419
|
+
)
|
|
420
|
+
if p.table.header is None and layout.header_row is None:
|
|
421
|
+
steps.append(
|
|
422
|
+
StepRecord(
|
|
423
|
+
id="header",
|
|
424
|
+
kind="header",
|
|
425
|
+
summary="The file has no row of column names; the columns were named "
|
|
426
|
+
"column_1, column_2, …",
|
|
427
|
+
)
|
|
428
|
+
)
|
|
429
|
+
elif layout.group_row is not None:
|
|
430
|
+
upper, lower = layout.group_row + 1, (layout.header_row or 0) + 1
|
|
431
|
+
combined = answers["header"].value == "combined"
|
|
432
|
+
steps.append(
|
|
433
|
+
StepRecord(
|
|
434
|
+
id="header",
|
|
435
|
+
kind="header",
|
|
436
|
+
summary=(
|
|
437
|
+
f"Combined the column names on rows {upper} and {lower}"
|
|
438
|
+
if combined
|
|
439
|
+
else f"Used the column names on row {lower}"
|
|
440
|
+
),
|
|
441
|
+
decided_by=decided(answers, ["header"]),
|
|
442
|
+
question_ids=["header"],
|
|
443
|
+
)
|
|
444
|
+
)
|
|
445
|
+
renamed = layout.renamed
|
|
446
|
+
if "header" in answers and answers["header"].value == "combined":
|
|
447
|
+
renamed = layout.combined_renamed
|
|
448
|
+
if renamed:
|
|
449
|
+
steps.append(
|
|
450
|
+
StepRecord(
|
|
451
|
+
id="names",
|
|
452
|
+
kind="names",
|
|
453
|
+
summary="Renamed "
|
|
454
|
+
+ "; ".join(
|
|
455
|
+
f'"{was}" to "{now}" ({why})' if was else f"an unnamed column to {now}"
|
|
456
|
+
for was, now, why in renamed[:10]
|
|
457
|
+
),
|
|
458
|
+
cells_changed=len(renamed),
|
|
459
|
+
)
|
|
460
|
+
)
|
|
461
|
+
return steps
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def verify(
|
|
465
|
+
p: Plan,
|
|
466
|
+
clean: Clean,
|
|
467
|
+
results: list[ColumnResult],
|
|
468
|
+
names: list[str],
|
|
469
|
+
kept: list[int],
|
|
470
|
+
removed: set[int],
|
|
471
|
+
) -> list[str]:
|
|
472
|
+
"""Check the result against the raw table; raise :class:`CleaningCheckError` if any
|
|
473
|
+
value is unaccounted for. Returns what was checked, for the report."""
|
|
474
|
+
problems = []
|
|
475
|
+
counted: set[int] = set()
|
|
476
|
+
for step in clean.steps:
|
|
477
|
+
if counted & step.removed_rows:
|
|
478
|
+
problems.append(f"rows removed twice: {sorted(counted & step.removed_rows)[:5]}")
|
|
479
|
+
counted |= step.removed_rows
|
|
480
|
+
if counted != removed:
|
|
481
|
+
problems.append("a removed row is not explained by any step")
|
|
482
|
+
if len(clean.frame) != clean.rows_in - len(removed):
|
|
483
|
+
problems.append(f"{clean.rows_in} rows in, {len(removed)} removed, {len(clean.frame)} out")
|
|
484
|
+
|
|
485
|
+
kept_set = set(kept)
|
|
486
|
+
values_checked = 0
|
|
487
|
+
for col, result, name in zip(p.columns, results, names, strict=True):
|
|
488
|
+
emptied = set().union(*(s.emptied for s in result.steps)) & kept_set
|
|
489
|
+
raw_present = sum(1 for i in kept if not is_empty(col.raw[i]))
|
|
490
|
+
# a column dropped as empty has nothing left in the result
|
|
491
|
+
present = int(clean.frame[name].notna().sum()) if name in clean.frame else 0
|
|
492
|
+
values_checked += raw_present
|
|
493
|
+
if raw_present - present != len(emptied):
|
|
494
|
+
problems.append(
|
|
495
|
+
f"{col.name}: {raw_present} values in the file, {present} in the result, "
|
|
496
|
+
f"but {len(emptied)} explained"
|
|
497
|
+
)
|
|
498
|
+
if problems:
|
|
499
|
+
raise CleaningCheckError("The cleaning check failed: " + "; ".join(problems))
|
|
500
|
+
emptied_total = sum(len(s.emptied & kept_set) for s in clean.steps)
|
|
501
|
+
return [
|
|
502
|
+
f"{_n(clean.rows_in, 'row')} in, {len(removed):,} removed by the steps above, "
|
|
503
|
+
f"{len(clean.frame):,} out",
|
|
504
|
+
f"{_n(values_checked, 'value')} in the file: {values_checked - emptied_total:,} kept, "
|
|
505
|
+
f"{emptied_total:,} left empty by the steps above, none lost",
|
|
506
|
+
]
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _n(count: int, word: str) -> str:
|
|
510
|
+
return f"{count:,} {word}{'' if count == 1 else 's'}"
|