Release 12.0 (full): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 5)
d9b105f verified Download workbench/planner.py from psiloceyeben/oracle7: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/psiloceyeben/oracle7/resolve/main/workbench/planner.py
- Command line
-
hf download hf://psiloceyeben/oracle7/workbench/planner.py
-
curl -L -o planner.py https://huggingface.co/psiloceyeben/oracle7/resolve/main/workbench/planner.py
12.7 kB
| """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 | |