File size: 12,703 Bytes
d9b105f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""planner - build what you want, not only what you spell out (12.0; the Pokemon satellite's shape pointed at building: read the
world's real rules, chain backward from the goal, name the blocker).

  world     the files in the sandbox, read: for a table, its columns, which hold numbers, a few values of each
  goal      what you want, read for its parts: the result's form (a page, served, a count, a total, an average, the largest,
            a list), the thing it is about (a column, by its name or a word for it), conditions ("whose amount is above
            average", "where city is leeds", "over 20"), the source ("from sales.csv", or the one table that has those columns)
  need      backward: the form needs a value of some kind; each kind is given by a step that needs another kind; the chain
            stops at a file in the sandbox. Each link records why it is there.
  steps     the chain, forward, written in make's own words; make builds, runs, repairs and checks it as always
A part of the goal no link can give is named (the column that is not in any file, the condition it cannot read), never guessed.
No language model."""
import csv
import io
import re
from pathlib import Path

NUMW = r"(-?\d+(?:\.\d+)?)"


def stem(w):
    w = w.lower()
    for s in ("ies", "es", "s"):
        if len(w) > len(s) + 2 and w.endswith(s):
            return w[: -len(s)] + ("y" if s == "ies" else "")
    return w


def read_world(sandbox):
    """the tables in the sandbox: {file: {"cols": [...], "numeric": set, "values": {col: [few]}}}"""
    world = {}
    for p in sorted(Path(sandbox).glob("*")):
        if p.suffix.lower() not in (".csv", ".tsv") or not p.is_file():
            continue
        text = p.read_text(errors="ignore")
        rows = list(csv.DictReader(io.StringIO(text), delimiter="\t" if p.suffix.lower() == ".tsv" else ","))
        if not rows:
            continue
        cols = list(rows[0].keys())
        numeric = set()
        for c in cols:
            vals = [str(r.get(c, "")).strip() for r in rows if str(r.get(c, "")).strip()]
            if vals and all(re.fullmatch(r"[$£€]?-?[\d,]*\.?\d+%?", v) for v in vals):
                numeric.add(c)
        world[p.name] = {"cols": cols, "numeric": numeric, "values": {c: [r.get(c) for r in rows[:50]] for c in cols}}
    return world


def forms(word):
    """the word and its singular readings (names -> name, nam; cities -> city; boxes -> box)"""
    w = word.lower()
    out = {w, stem(w)}
    if w.endswith("s") and len(w) > 3:
        out.add(w[:-1])
    return out


def find_col(word, info):
    """a column the word names: its header, the header's stem, or a header the word is part of (plurals read both ways:
    sealed want v1 p03/p10 - 'names' was cut to 'nam' and missed the column 'name')"""
    ws = forms(word)
    for c in info["cols"]:
        k = re.sub(r"[^a-z0-9]+", " ", c.lower()).strip()
        if ws & (forms(k) | {f for x in k.split() for f in forms(x)}):
            return c
    return None


def find_value_col(word, info):
    """a column one of whose values is the word (\"leeds\" -> city)"""
    for c, vals in info["values"].items():
        if any(str(v).strip().lower() == word.lower() for v in vals):
            return c
    return None


def plan(goal, sandbox):
    """-> (steps text for make, [why ...]) or (None, [the blocker])"""
    g = goal.strip().rstrip(".")
    # Amendment 13: a written comparison is read, never dropped ("amount > 10" was planned as no filter at all)
    g = re.sub(r"\s*>=\s*", " at least ", g)
    g = re.sub(r"\s*<=\s*", " at most ", g)
    g = re.sub(r"\s*>\s*", " over ", g)
    g = re.sub(r"\s*<\s*", " under ", g)
    lo = g.lower()
    world = read_world(sandbox)
    if not world:
        return None, ["there is no table (csv) in the sandbox to build this from; write or fetch one there first"]
    m = re.search(r"\b(?:from|in|of|using)\s+([\w.-]+\.(?:csv|tsv))\b", g, re.I)
    words = re.findall(r"[a-z][a-z0-9_]+", lo)
    if m and m.group(1) in world:
        src = m.group(1)
    elif m:
        return None, ["there is no %s in the sandbox" % m.group(1)]
    else:   # the table the goal is about: its name, its columns and its values, as the goal names them
        def table_score(f, i):
            s = sum(2 for w in words if find_col(w, i)) + sum(1 for w in words if find_value_col(w, i))
            return s + (2 if any(stem(w) == stem(Path(f).stem) for w in words) else 0)
        score = {f: table_score(f, i) for f, i in world.items()}
        src = max(score, key=score.get)
        if not score[src]:
            return None, ["none of the tables in the sandbox (%s) has a name, column or value your goal names" % ", ".join(world)]
    info = world[src]
    why = ["read the world: %s has columns %s (numbers: %s)" % (src, ", ".join(info["cols"]), ", ".join(sorted(info["numeric"])) or "none")]

    # the result's form
    form = "print"
    if re.search(r"\b(page|html|report|web ?page)\b", lo):
        form = "page"
    if re.search(r"\b(serve|server|host|api|endpoint)\b", lo):
        form = "serve" if form != "page" else "page+serve"
    # what is asked of the values, read with the conditions taken out ("whose amount is above average" asks for no average)
    # and with a word that is a column of the table left as the column ("the average total": total is the column)
    cond_rx = (r"\b(?:whose|where|with|that have|having)\s+(?:the\s+)?[a-z][a-z ]*?\s+(?:is|are|was|were)?\s*(?:above|below|over|"
               r"under|more than|less than|greater than|at least|at most)\s+(?:the\s+)?(?:average|mean|median|-?\d+(?:\.\d+)?)")
    asked = re.sub(cond_rx, " ", lo)
    colword = lambda w: find_col(w, info) is not None
    agg = None
    for pat, a in ((r"\bhow many\b|\bcount of\b|\bnumber of\b", "count"), (r"\baverage\b|\bmean\b", "average"),
                   (r"\bmedian\b", "median"), (r"\b(largest|biggest|highest|max(?:imum)?)\b", "max"),
                   (r"\b(smallest|lowest|min(?:imum)?)\b", "min"), (r"\bsum\b|\badd up\b", "sum"), (r"\btotal\b", "sum")):
        mm = re.search(pat, asked)
        if mm and not (mm.group(0) == "total" and colword("total")):   # "total" that is a column names the column
            agg = a
            break

    # conditions, read before the subject so their words are not taken for it
    conds, used = [], set()
    for cm in re.finditer(r"\b(?:whose|where|with|that have|having)\s+(?:the\s+)?([a-z][a-z ]*?)\s+(?:is|are|was|were)?\s*"
                          r"(above|below|over|under|more than|less than|greater than|at least|at most)\s+(?:the\s+)?(average|mean|median|" + NUMW + r")",
                          lo):
        col = find_col(cm.group(1).split()[-1], info)
        if not col:
            return None, why + ["the condition names %r, which is not a column of %s (%s)" % (cm.group(1), src, ", ".join(info["cols"]))]
        if col not in info["numeric"]:
            return None, why + ["%s is compared as a number, but %s holds text" % (cm.group(1), col)]
        op = ("at least" if cm.group(2) == "at least" else "at most" if cm.group(2) == "at most" else       # Amendment 13:
              "greater than" if cm.group(2) in ("above", "over", "more than", "greater than") else "less than")  # not made strict
        conds.append("keep rows whose %s is %s %s" % (col, op, cm.group(3)))
        used |= set(cm.group(0).split())
        why.append("the goal wants only rows whose %s is %s %s: a filter on the parsed rows" % (col, op, cm.group(3)))
    for cm in re.finditer(r"\b(?:where|whose|in|for)\s+(?:the\s+)?([a-z]+)\s+(?:is|=)\s+([a-z0-9]+)\b", lo):
        if cm.group(0) in " ".join(conds):
            continue
        col = find_col(cm.group(1), info)
        if col and col not in info["numeric"]:
            conds.append("keep rows whose %s is %s" % (col, cm.group(2)))
            used |= set(cm.group(0).split())
            why.append("the goal wants only rows whose %s is %s" % (col, cm.group(2)))
    for w in words:                                            # a bare value names its column ("in leeds" -> city is leeds)
        if w in used:
            continue
        c = find_value_col(w, info)
        if c and not find_col(w, info) and not any(("whose %s is" % c) in x for x in conds):
            conds.append("keep rows whose %s is %s" % (c, w))
            why.append("%r is a value of %s: keep the rows that have it" % (w, c))

    # the subject: the column the result is about (the first column the goal names outside its conditions)
    subject = None
    for w in words:
        if w in used:
            continue
        c = find_col(w, info)
        if c:
            subject = c
            break
    if agg in ("sum", "average", "max", "min", "median") and (subject is None or subject not in info["numeric"]):
        nums = [c for c in info["numeric"] if any(find_col(w, {"cols": [c]}) for w in words)] or sorted(info["numeric"])
        if not nums:
            return None, why + ["the goal asks for a %s, and %s has no column of numbers" % (agg, src)]
        subject = nums[0]

    # every word of the goal must be accounted for: a part it names, a word of form or of what is asked, or a plain function word.
    # A word no link uses is the blocker, named - never planned around (the satellite's rule: name what blocks, do not guess)
    known = set(words) & ({"a", "an", "the", "of", "in", "on", "for", "from", "to", "with", "and", "or", "all", "me", "my", "show",
                           "list", "give", "get", "find", "what", "which", "who", "is", "are", "was", "were", "there", "that",
                           "this", "these", "those", "please", "want", "make", "build", "each", "every", "their", "its", "by",
                           "page", "html", "report", "web", "webpage", "serve", "server", "host", "api", "endpoint", "served",
                           "how", "many", "much", "count", "number", "total", "sum", "add", "up", "average", "mean", "median",
                           "largest", "biggest", "highest", "max", "maximum", "smallest", "lowest", "min", "minimum", "whose",
                           "where", "having", "have", "above", "below", "over", "under", "more", "less", "than", "greater",
                           "least", "most", "at", "it", "them", "do", "does", "using", "csv", "tsv", "rows", "row", "values",
                           "value", "ones", "items", "entries", "column", "columns", "table", "file", "field"})
    for w in words:
        if (w in known or w in used or find_col(w, info) or find_value_col(w, info) or stem(w) == stem(Path(src).stem)
                or re.fullmatch(r"\d+", w) or w in Path(src).name.lower()):
            continue
        return None, why + ["I cannot read %r in your goal: it is not a column of %s (%s), not one of its values, and not something I "
                            "know how to do; say it with a column's name (for example: whose %s is more than 2)" % (
                                w, src, ", ".join(info["cols"]), sorted(info["numeric"])[0] if info["numeric"] else info["cols"][0])]

    # need, backward: form <- value <- (aggregate <- numbers <- column) | column | rows <- filters <- rows <- parse <- read
    chain = []
    if form in ("page", "page+serve"):
        chain.append(("make a page called %s" % re.sub(r"[^a-z0-9]+", "_", (subject or "result").lower()).strip("_"),
                      "a page needs a value to show"))
    if form in ("serve", "page+serve"):
        chain.append(("serve it on port 8790", "serving needs a value to answer with"))
    if form == "print" or agg:
        chain.append(("print it", "the result is shown"))
    if agg == "count":
        chain.append(("count them", "how many = the number of items"))
    elif agg:
        chain.append(({"sum": "sum them", "average": "average them", "max": "find the maximum", "min": "find the minimum",
                       "median": "compute the median"}[agg], "a %s needs numbers" % agg))
        chain.append(("convert to numbers", "numbers need the column's values read as numbers"))
    if subject and (agg != "count" or form != "print" or True):
        if not (agg == "count" and not subject):
            chain.append(("take the %s column" % subject, "the result is about %s: its column of the rows" % subject))
    for c in reversed(conds):
        chain.append((c, "only some rows are wanted"))
    chain.append(("parse it as csv", "rows need the table parsed"))
    chain.append(("read %s" % src, "the table is %s, in the sandbox" % src))
    steps = [s for s, _ in reversed(chain)]
    why += ["%s  <- because %s" % (s, w) for s, w in reversed(chain)]
    return ", ".join(steps), why