File size: 34,963 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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 | """make - build an algorithm as described (12.0, Ben: "we need it to know how to build one as described").
The description is read as steps (sentences, ";", "then", numbered lines). Each step becomes one typed code move:
- a move of the language itself (what Python can do): read, fetch, split, parse, keep/remove where, count, sort by, top N,
sum, average, max, min, unique, lower/upper, replace, extract numbers/emails/urls/words, hash, field, join, write, print
- or, when no language move fits, a function from your workspace found by meaning (the workspace index), copied into the
program with its file's imports
The value flows from step to step ("it", "them", "the result" = the previous step's value), with its kind tracked (text,
list, number, rows, pairs) so a move applies only where it can. The program is written to the sandbox, run, and checked
against "expect <value>" if you give one. A step no move can build is reported as a named gap with the nearest workspace
functions, never guessed. No language model."""
import ast
import json
import re
import threading
from pathlib import Path
NUM = r"(-?\d+(?:\.\d+)?)"
Q = r"""['"‘“]?([^'"’”]+?)['"’”]?"""
def steps_of(desc):
"""steps: lines, numbered items, sentences, ";", "then", and every comma that opens a new clause (a fragment that only
qualifies the step before it - "descending", "and so on", a number - stays with that step)"""
d = re.sub(r"(?m)^\s*\d+[.)]\s*", "\n", desc.strip())
d = re.sub(r"\bexpect(?:ing)?\b.*$", "", d, flags=re.I | re.S)
parts = re.split(r"\n+|;|(?<=[a-z0-9\"')\]])\.\s+|,?\s+then\s+", d, flags=re.I)
out = []
# sealed v2 (v19): "reverse them" was merged into the step before as a sort qualifier and had no effect. Order words
# qualify only a sort step, and only as a bare qualifier; a clause with its own verb is its own step.
QUAL = re.compile(r"^(?:\d|from |to |by |with |as |in |into |on |of )", re.I)
ORDERQ = re.compile(r"^(?:descending|ascending|largest first|smallest first|in order|alphabetically|reversed|in reverse)$", re.I)
carry = ""
for p in parts:
for frag in re.split(r",\s+", p):
f = re.sub(r"^(?:and|or)\s+", "", frag.strip(" .,"), flags=re.I)
if not f:
continue
if re.fullmatch(r"for\s+(?:each|every)\s+\w+", f, re.I): # "for each line," opens the step that follows
carry = f + ", "
continue
f, carry = carry + f, ""
if out and (QUAL.match(f) or (ORDERQ.match(f) and re.match(r"sort\b", out[-1], re.I))):
out[-1] = out[-1] + ", " + f
else:
out.append(f)
return out
class Prog:
def __init__(self):
self.lines, self.imports, self.extra, self.kind, self.gaps, self.trace = [], set(), [], None, [], []
def emit(self, line, kind, imp=()):
self.lines.append(line)
self.imports.update(imp)
self.kind = kind
def source(self):
"""a program another program can use: run(x) holds the steps; printing goes through _show, which a program that
uses this one turns off; main() runs it on its own"""
head = "\n".join(sorted("import " + i for i in self.imports))
body = "\n".join(" " + (("_show(" + ln[len("print("):]) if ln.startswith("print(") else ln) for ln in self.lines)
return ("%s\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n%s\n\n\ndef run(x=None):\n%s\n return x\n\n\n"
"def main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\n"
% (head, "\n\n".join(self.extra), body or " pass")).lstrip()
NUMP = NUM # 12.0 Amendment 13b: inside a function with inputs, a condition may compare with an input by name
def _cond(text):
"""a keep/remove condition -> a Python test on i"""
t = text.strip()
m = re.search(r"(?:at least|no less than)\s+" + NUMP + r"|>=\s*" + NUMP, t)
if m:
return "float(i) >= %s" % (m.group(1) or m.group(2))
m = re.search(r"(?:at most|no more than)\s+" + NUMP + r"|<=\s*" + NUMP, t)
if m:
return "float(i) <= %s" % (m.group(1) or m.group(2))
m = re.search(r"(?:greater|more|larger|bigger|higher)\s+than\s+" + NUMP + r"|\b(?:over|above)\s+" + NUMP + r"|>\s*" + NUMP, t)
if m:
return "float(i) > %s" % (m.group(1) or m.group(2) or m.group(3))
m = re.search(r"(?:less|smaller|fewer|lower)\s+than\s+" + NUMP + r"|\b(?:under|below)\s+" + NUMP + r"|<\s*" + NUMP, t)
if m:
return "float(i) < %s" % (m.group(1) or m.group(2) or m.group(3))
m = re.search(r"longer\s+than\s+" + NUMP, t)
if m:
return "len(str(i)) > %s" % m.group(1)
m = re.search(r"shorter\s+than\s+" + NUMP, t)
if m:
return "len(str(i)) < %s" % m.group(1)
if re.search(r"\b(?:non-?negative)\b", t):
return "float(i) >= 0"
if re.search(r"\bpositive\b", t):
return "float(i) > 0"
if re.search(r"\bnegative\b", t):
return "float(i) < 0"
if re.search(r"\bnon-?empty\b|\bnot empty\b", t):
return "bool(str(i).strip())"
m = re.search(r"(?:start|begin)s?\s+with\s+" + Q + r"\s*$", t)
if m:
return "str(i).startswith(%r)" % m.group(1)
m = re.search(r"ends?\s+with\s+" + Q + r"\s*$", t)
if m:
return "str(i).endswith(%r)" % m.group(1)
m = re.search(r"(?:contain(?:s|ing)?|with|mention(?:s|ing)?|that have|having)\s+" + Q + r"\s*$", t)
if m:
return "%r in str(i)" % m.group(1)
if re.search(r"\b(empty|blank)\b", t):
return "not str(i).strip()"
if re.search(r"\beven\b", t):
return "float(i) % 2 == 0"
if re.search(r"\bodd\b", t):
return "float(i) % 2 == 1"
return None
def each(step, P):
"""a move applied to each item: "<step> of each <thing>", "<step> for each <thing>", "for each <thing>, <step>"""
s = step.strip()
m = re.match(r"^for\s+(?:each|every)\s+\w+\s*,?\s*(.+)$", s, re.I) or \
re.match(r"^(.+?)\s+(?:of|for|in|from)\s+(?:each|every)\s+\w+$", s, re.I)
if not m or P.kind not in ("list", "rows", "value", None): # sealed v3 (w04): a used program's value may be a list
return False
inner = Prog()
inner.kind = "text"
move(m.group(1), inner, None)
if not inner.lines:
return False
n = len(P.extra) + 1
body = "\n".join(" " + ln for ln in inner.lines)
P.extra.append("def each_%d(x):\n%s\n return x" % (n, body))
P.imports.update(inner.imports)
P.emit("x = [each_%d(i) for i in x]" % n, "list")
return True
KNOWN = set() # programs already made in the sandbox (set by the caller): a later program can use them by name
USE_SRC = '''def _use(name, x):
"""another program made here, used as a step: its run() on this value, its own printing off"""
import importlib, os, sys
here = os.path.dirname(os.path.abspath(__file__))
if here not in sys.path:
sys.path.insert(0, here)
m = importlib.import_module(name)
m._SHOW = False
return m.run(x)'''
ROWS_SRC = '''def _cell(r, k):
"""a row's value under the column as named (case, spaces and spelling forgiven)"""
if k in r:
return r[k]
norm = lambda s: "".join(ch for ch in str(s).lower() if ch.isalnum())
for h in r:
if norm(h) == norm(k):
return r[h]
import difflib
near = difflib.get_close_matches(k, list(r), n=1, cutoff=0.5)
return r[near[0]] if near else None
def _cellnum(r, k):
"""the cell as a number, as people write numbers ($1,200.50, 45%), or None"""
import re as _re
v = _cell(r, k)
if isinstance(v, (int, float)):
return float(v)
m = _re.search(r"-?\\d[\\d,]*(?:\\.\\d+)?|-?\\.\\d+", str(v or ""))
return float(m.group(0).replace(",", "")) if m else None'''
PAGE_SRC = '''def _page(x, name):
"""the value as a page: a table for rows (dicts) and pairs, a list for a list, the value itself otherwise"""
esc = html.escape
if isinstance(x, list) and x and isinstance(x[0], dict):
cols = list(x[0])
body = "<table><tr>%s</tr>%s</table>" % ("".join("<th>%s</th>" % esc(str(c)) for c in cols), "".join(
"<tr>%s</tr>" % "".join("<td>%s</td>" % esc(str(r.get(c, ""))) for c in cols) for r in x))
elif isinstance(x, list) and x and isinstance(x[0], tuple):
body = "<table>%s</table>" % "".join("<tr>%s</tr>" % "".join("<td>%s</td>" % esc(str(v)) for v in p) for p in x)
elif isinstance(x, list):
body = "<ul>%s</ul>" % "".join("<li>%s</li>" % esc(str(v)) for v in x)
else:
body = "<p>%s</p>" % esc(str(x))
style = "body{font-family:system-ui,sans-serif;margin:2rem;color:#222}td,th{border-bottom:1px solid #ddd;padding:4px 10px;text-align:left}"
open(name, "w", encoding="utf-8").write("<!doctype html><meta charset=utf-8><title>%s</title><style>%s</style><h1>%s</h1>%s" % (
esc(name), style, esc(name.rsplit(".", 1)[0]), body))
_show("page written: " + name)'''
SERVE_SRC = '''def _serve(x, port):
"""the value at http://127.0.0.1:<port>/ as JSON, and any page made here at /page. Run once, it asks itself for / and
stops (so a build can be checked); with --serve on the command line it stays up until stopped"""
import glob
pages = sorted(glob.glob("*.html"))
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith("/page") and pages:
body, ctype = open(pages[-1], "rb").read(), "text/html; charset=utf-8"
else:
body, ctype = json.dumps(x, default=str, indent=1).encode(), "application/json"
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), H)
if "--serve" in sys.argv:
print("serving on http://127.0.0.1:%d/ (Ctrl+C stops)" % port)
srv.serve_forever()
return
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
got = urllib.request.urlopen("http://127.0.0.1:%d/" % port, timeout=10).read().decode()
srv.shutdown()
_show("served on http://127.0.0.1:%d/ and answered itself: %s" % (port, got[:300]))
_show("(run it with --serve to keep it up)")'''
def branch(steps, i, P):
""""[for each <thing>,] if <condition>" + the step that follows + an optional "otherwise <step>" = one move that applies
the first step where the condition holds and the second (or nothing) where it does not; per item on a list"""
m = re.match(r"^(for\s+(?:each|every)\s+\w+\s*,\s*)?if\s+(.+?)$", steps[i].strip(), re.I)
if not m or i + 1 >= len(steps):
return 0
cond = _cond(re.sub(r"^(?:it|they|the \w+|that|this)\s+(?:is\s+|are\s+)?", "", m.group(2).strip(), flags=re.I))
if not cond:
return 0
per_item = bool(m.group(1)) or P.kind in ("list", "rows")
then_txt = re.sub(r"^then\s+", "", steps[i + 1].strip(), flags=re.I)
m2 = re.match(r"^(?:otherwise|else)[,\s]+(.+)$", steps[i + 2].strip(), re.I) if i + 2 < len(steps) else None
def inner(text):
q = Prog()
q.kind = "text" if per_item else P.kind
move(text, q, None)
return q
t = inner(then_txt)
if not t.lines:
return 0
e = inner(m2.group(1)) if m2 else None
if m2 and not e.lines:
return 0
n = len(P.extra) + 1
src = "def branch_%d(x):\n i = x\n if %s:\n%s\n" % (n, cond, "\n".join(" " + ln for ln in t.lines))
if e:
src += " else:\n%s\n" % "\n".join(" " + ln for ln in e.lines)
src += " return x"
P.extra.append(src)
P.imports.update(t.imports | (e.imports if e else set()))
P.emit("x = [branch_%d(i) for i in x]" % n if per_item else "x = branch_%d(x)" % n, "list" if per_item else "value")
return 3 if m2 else 2
def move(step, P, prev_names):
s = step.strip()
lo = s.lower()
k = P.kind
m = re.match(r"^(?:use|apply|call|run)\s+(?:the\s+)?(?:program\s+)?([A-Za-z0-9_]+)(\s+(?:on|to)\s+(?:it|them|this|that|the result))?$",
s, re.I)
if m and m.group(1) in KNOWN and m.group(1) not in DEFINED:
if USE_SRC not in P.extra:
P.extra.append(USE_SRC)
return P.emit("x = _use(%r, %s)" % (m.group(1), "x" if m.group(2) else "None"), "value")
# rows kept by a condition on a column: compared with a number, with the column's own average / median, or equal to a value
m = re.match(r"^(?:keep|select|filter|take)\s+(?:only\s+)?(?:the\s+)?rows\s+(?:whose|where)\s+(?:the\s+)?(.+?)\s+(?:is|are)\s+"
r"(greater than|more than|above|over|less than|below|under|at least|at most)\s+(?:the\s+)?(average|mean|median|" + NUM + r")$",
s, re.I)
if m:
col, rel, ref = m.group(1).strip(), m.group(2).lower(), m.group(3).lower()
op = ">" if rel in ("greater than", "more than", "above", "over") else "<" if rel in ("less than", "below", "under") else \
">=" if rel == "at least" else "<="
if ROWS_SRC not in P.extra:
P.extra.append(ROWS_SRC)
if ref in ("average", "mean", "median"):
fn = "statistics.median" if ref == "median" else "statistics.mean"
return P.emit("x = (lambda t: [r for r in x if _cellnum(r, %r) is not None and _cellnum(r, %r) %s t])(%s([v for v in (_cellnum(r, %r) for r in x) if v is not None]))"
% (col, col, op, fn, col), "rows", ["statistics"])
return P.emit("x = [r for r in x if _cellnum(r, %r) is not None and _cellnum(r, %r) %s %s]" % (col, col, op, ref), "rows")
m = re.match(r"^(?:keep|select|filter|take)\s+(?:only\s+)?(?:the\s+)?rows\s+(?:whose|where)\s+(?:the\s+)?(.+?)\s+(?:is|are|=)\s+" + Q + r"$", s, re.I)
if m:
if ROWS_SRC not in P.extra:
P.extra.append(ROWS_SRC)
return P.emit("x = [r for r in x if str(_cell(r, %r)).strip().lower() == %r]" % (m.group(1).strip(), m.group(2).strip().lower()), "rows")
# a function this program defines, called by name: "total it", "use total", "apply total to them", "total"
m = re.match(r"^(?:use|apply|call|run|do)?\s*(?:the\s+)?([A-Za-z_][A-Za-z0-9_]*)(?:\s+(?:on|to|of|for)?\s*(?:it|them|this|that|the result))?$",
s, re.I)
if m and m.group(1) in DEFINED:
return P.emit("x = %s(x)" % m.group(1), "value")
# a page: the value as an HTML page in the sandbox (a table for rows and pairs, a list otherwise)
m = re.match(r"^(?:make|write|save|build|show)\s+(?:it\s+as\s+|them\s+as\s+)?(?:an?\s+)?(?:html\s+)?page"
r"(?:\s+(?:showing|of|for|with)\s+(?:it|them|the result))?(?:\s+(?:called|named|to|as|in)\s+" + Q + r")?$", s, re.I)
if m:
f = m.group(1) or "page.html"
f = f if f.endswith(".html") else f + ".html"
if PAGE_SRC not in P.extra:
P.extra.append(PAGE_SRC)
return P.emit("_page(x, %r)" % f, k, ["html"])
# a server: the value served as JSON at / (and the page at /page if one was made); run once it serves itself a request
# and stops; run with --serve it stays up
m = re.match(r"^(?:serve|host|publish)\s+(?:it|them|the result|the page)?(?:\s+(?:on|at)\s+port\s+(\d+))?$", s, re.I)
if m:
if SERVE_SRC not in P.extra:
P.extra.append(SERVE_SRC)
return P.emit("_serve(x, %s)" % (m.group(1) or "8765"), k, ["json", "http.server", "threading", "urllib.request", "sys"])
m = re.match(r"^(?:take|get|keep|find)\s+(?:the\s+)?(last|first)\s+word$", lo)
if m:
return P.emit("x = (str(x).split() or [''])[%s]" % ("-1" if m.group(1) == "last" else "0"), "text")
m = re.match(r"^(?:take|get|keep)\s+(?:the\s+)?(last|first)\s+" + NUM + r"\s+(?:characters|chars|letters)$", lo)
if m:
n = int(float(m.group(2)))
return P.emit("x = str(x)[-%d:]" % n if m.group(1) == "last" else "x = str(x)[:%d]" % n, "text")
if re.match(r"^(?:take|get|find|compute|measure)\s+(?:the\s+)?(?:length|size)$", lo):
return P.emit("x = len(x)", "num")
if re.match(r"^reverse\b", lo):
return P.emit("x = x[::-1]", k)
m = re.match(r"^(?:read|open|load)\s+(?:the\s+)?(?:file\s+)?" + Q + r"(?:\s+file)?$", s, re.I)
if m:
f = m.group(1)
if f.lower().endswith(".json"):
return P.emit("x = json.load(open(%r))" % f, "rows", ["json"])
return P.emit("x = open(%r, encoding=\"utf-8\", errors=\"ignore\").read()" % f, "text")
m = re.match(r"^(?:fetch|download|get)\s+(?:the\s+page\s+)?(https://\S+)", s, re.I)
if m:
P.extra.append(FETCH_SRC)
return P.emit("x = fetch_text(%r)" % m.group(1).rstrip(".,"), "text", ["re", "urllib.request", "urllib.parse"])
if re.match(r"^(?:split|break|turn|cut)\b.*\blines?\b", lo):
return P.emit("x = [l for l in str(x).splitlines() if l.strip()]", "list")
if re.match(r"^(?:split|break|turn|cut)\b.*\bwords?\b", lo) or re.match(r"^extract\s+(?:the\s+)?words", lo):
return P.emit("x = re.findall(r\"[A-Za-z']+\", str(x))", "list", ["re"])
m = re.match(r"^split\b.*\b(?:on|by)\s+" + Q + r"$", s, re.I)
if m:
sep = {"comma": ",", "commas": ",", "space": " ", "spaces": " ", "tab": "\t", "tabs": "\t"}.get(m.group(1).lower(), m.group(1))
return P.emit("x = [p.strip() for p in str(x).split(%r)]" % sep, "list")
if re.match(r"^(?:make|turn|convert|change)\b.*\blower", lo) or lo.startswith("lowercase"):
return P.emit("x = [str(i).lower() for i in x]" if k == "list" else "x = str(x).lower()", k)
if re.match(r"^(?:make|turn|convert|change)\b.*\bupper", lo) or lo.startswith("uppercase"):
return P.emit("x = [str(i).upper() for i in x]" if k == "list" else "x = str(x).upper()", k)
if re.match(r"^(?:parse|read)\b.*\bcsv\b", lo):
return P.emit("x = list(csv.DictReader(io.StringIO(str(x))))", "rows", ["csv", "io"])
if re.match(r"^(?:parse|read)\b.*\bjson\b", lo):
return P.emit("x = json.loads(str(x))", "rows", ["json"])
m = re.match(r"^(?:take|get|keep|pick|select|use)\s+(?:only\s+)?(?:the\s+)?" + Q + r"\s+(?:column|field|key|value)s?$", s, re.I)
if m:
return P.emit("x = [r[%r] for r in x]" % m.group(1), "list")
if re.match(r"^(?:convert|turn|make)\b.*\bnumbers?\b", lo):
return P.emit("x = [float(i) for i in x]", "list")
m = re.match(r"^extract\s+(?:all\s+)?(?:the\s+)?(numbers|emails?|urls?|links?|dates?|years?)", lo)
if m:
what = m.group(1)
rx = {"numbers": NUM, "email": r"[\w.+-]+@[\w-]+\.[\w.]+", "url": r"https?://[^\s\"'<>]+", "link": r"https?://[^\s\"'<>]+",
"date": r"\d{4}-\d{2}-\d{2}", "year": r"\b(1[5-9]\d\d|20\d\d)\b"}[what.rstrip("s") if what != "numbers" else "numbers"]
conv = "float(n)" if what == "numbers" else "int(n)" if what.startswith("year") else "n"
return P.emit("x = [%s for n in re.findall(%r, str(x))]" % (conv, rx), "list", ["re"])
m = re.match(r"^(keep|filter|select|pick|find|take)\s+(?:only\s+)?(?:the\s+)?(?:\w+\s+)?(?:that|which|where|whose|if|with|"
r"containing|longer|shorter|greater|less|more|starting|ending|over|under|above|below)\b(.*)$", s, re.I)
if m:
c = _cond(s[len(m.group(1)):])
if c:
return P.emit("x = [i for i in x if %s]" % c, "list")
m = re.match(r"^(?:keep|filter|select|pick|take)\s+(?:only\s+)?(?:the\s+)?((?:non-?)?(?:even|odd|positive|negative|non-?negative|"
r"empty|blank|non-?empty))\s+(?:numbers|values|items|ones|entries|lines|words|strings)?\s*(?:in it|from it|of it)?$", s, re.I)
if m: # Amendment 13b: "keep the even numbers" - the kind named before the noun
c = _cond(m.group(1))
if c:
return P.emit("x = [i for i in x if %s]" % c, "list")
m = re.match(r"^(?:remove|drop|exclude|delete|skip)\s+(?:the\s+)?((?:non-?)?(?:even|odd|positive|negative))\s+"
r"(?:numbers|values|items|ones|entries)?\s*$", s, re.I)
if m:
c = _cond(m.group(1))
if c:
return P.emit("x = [i for i in x if not (%s)]" % c, "list")
m = re.match(r"^(?:remove|drop|exclude|delete|skip)\s+(?:the\s+)?(?:\w+\s+)?(?:that|which|where|whose|if|with|containing|"
r"longer|shorter|greater|less|empty|blank|starting|ending)\b(.*)$", s, re.I)
if m or re.match(r"^(?:remove|drop)\s+(?:the\s+)?(?:empty|blank)", lo):
c = _cond(s.split(None, 1)[1] if " " in s else s)
if c:
return P.emit("x = [i for i in x if not (%s)]" % c, "list")
if re.match(r"^(?:remove|drop)\s+(?:the\s+)?duplicates|^(?:dedupe|unique|keep\s+(?:only\s+)?(?:the\s+)?unique|make\s+.*unique)", lo):
return P.emit("x = list(dict.fromkeys(x))", "list")
if re.match(r"^count\b.*\b(?:each|every|how often|occurrences|frequenc)", lo) or re.match(r"^(?:tally|frequency)", lo):
return P.emit("x = collections.Counter(x).most_common()", "pairs", ["collections"])
m = re.match(r"^(?:count|how many)\s+(?:the\s+)?(?:number\s+of\s+)?(words|lines|characters|chars|letters|sentences)\b", lo)
if m and k in ("text", None): # the unit the step names is the unit counted
expr = {"words": "len(str(x).split())", "lines": "len(str(x).splitlines())",
"sentences": "len([p for p in re.split(r'[.!?]+', str(x)) if p.strip()])"}.get(m.group(1), "len(str(x))")
return P.emit("x = " + expr, "num", ["re"] if m.group(1) == "sentences" else [])
if re.match(r"^(?:count|how many)\b", lo):
return P.emit("x = len(x)", "num")
if re.match(r"^sort\b", lo):
rev = bool(re.search(r"\b(desc|descending|largest|biggest|highest|most|reverse|decreasing)", lo))
if k == "pairs":
key = "lambda p: p[1]" if re.search(r"\b(count|frequency|number|times|value)\b", lo) else "lambda p: p[0]"
if re.search(r"\b(count|frequency)\b", lo) and not re.search(r"\b(asc|ascending|least|fewest|increasing)", lo):
rev = True
elif re.search(r"\blength\b", lo):
key = "len"
elif re.search(r"\b(value|number|numerically|size)\b", lo):
key = "float"
else:
m2 = re.search(r"\bby\s+(?:the\s+)?" + Q + r"(?:\s+(?:column|field))?(?:\s+(?:asc|desc)\w*)?$", s, re.I)
key = ("lambda r: r[%r]" % m2.group(1)) if (m2 and k == "rows") else None
return P.emit("x = sorted(x%s%s)" % (", key=%s" % key if key else "", ", reverse=True" if rev else ""), k)
m = re.match(r"^(?:take|keep|get|show|print|return)\s+(?:only\s+)?(?:the\s+)?(?:top|first|last)\s+" + NUM, lo)
if m:
n = int(float(m.group(1)))
line = "x = x[-%d:]" % n if " last " in " %s " % lo else "x = x[:%d]" % n
P.emit(line, k)
if re.match(r"^(?:print|show)", lo):
P.emit("print(x)", k)
return
m = re.search(r"\b(median|mode|standard deviation|stdev|std|variance)\b", lo)
if m and re.match(r"^(?:compute|calculate|find|take|get|work out)?\s*(?:the\s+)?(?:population\s+)?"
r"(median|mode|standard deviation|stdev|std|variance)\b", lo):
fn = {"median": "median", "mode": "mode", "standard deviation": "stdev", "stdev": "stdev", "std": "stdev",
"variance": "variance"}[m.group(1)]
if "population" in lo and fn in ("stdev", "variance"):
fn = "p" + fn
return P.emit("x = statistics.%s([float(i) for i in x]) if %s else None" % (fn, "len(x) > 1" if fn in ("stdev", "variance") else "x"),
"num", ["statistics"])
if re.match(r"^(?:sum|add|total)\b", lo):
return P.emit("x = sum(float(i) for i in x)", "num")
if re.match(r"^(?:average|mean|find the average|compute the average|calculate the average)", lo) or "average" in lo:
return P.emit("x = sum(float(i) for i in x) / len(x) if x else 0.0", "num")
if re.match(r"^(?:find\s+the\s+)?(?:max|maximum|largest|biggest|highest)", lo):
return P.emit("x = max(x, key=lambda p: p[1]) if x and isinstance(x[0], tuple) else max(x)", "num")
if re.match(r"^(?:find\s+the\s+)?(?:min|minimum|smallest|lowest)", lo):
return P.emit("x = min(x, key=lambda p: p[1]) if x and isinstance(x[0], tuple) else min(x)", "num")
m = re.match(r"^replace\s+" + Q + r"\s+with\s+" + Q + r"$", s, re.I)
if m:
a, b = m.group(1), m.group(2)
return P.emit("x = [str(i).replace(%r, %r) for i in x]" % (a, b) if k == "list" else "x = str(x).replace(%r, %r)" % (a, b), k)
if re.match(r"^(?:hash|compute the hash|take the hash)\b", lo) or "sha256" in lo:
m = re.search(r"\b(?:hash|of)\s+" + Q + r"\s+with\b", s, re.I)
if m and "." in m.group(1):
P.emit("x = open(%r, \"rb\").read()" % m.group(1), "bytes")
return P.emit("x = hashlib.sha256(x if isinstance(x, bytes) else str(x).encode()).hexdigest()", "text", ["hashlib"])
m = re.match(r"^join\b.*?(?:with|by|using)\s+" + Q + r"$", s, re.I)
if m or re.match(r"^join\b", lo):
sep = (m.group(1) if m else " ")
sep = {"comma": ", ", "commas": ", ", "newline": "\n", "newlines": "\n", "space": " ", "spaces": " "}.get(sep.lower(), sep)
return P.emit("x = %r.join(str(i) for i in x)" % sep, "text")
m = re.match(r"^(?:write|save|store)\b.*?(?:to|in|into|as)\s+" + Q + r"$", s, re.I)
if m:
f = m.group(1)
if f.endswith(".json"):
return P.emit("json.dump(x, open(%r, \"w\"), indent=1)" % f, k, ["json"])
return P.emit("open(%r, \"w\").write(x if isinstance(x, str) else \"\\n\".join(map(str, x)))" % f, k)
if re.match(r"^(?:print|show|display|output|return)\b", lo):
if k == "pairs":
return P.emit("print(\"\\n\".join(\"%s\\t%s\" % p for p in x))", k)
if k == "list":
return P.emit("print(\"\\n\".join(map(str, x)))", k)
return P.emit("print(x)", k)
return None
FETCH_SRC = '''def fetch_text(url):
"""a page from the verified sources, as text"""
host = urllib.parse.urlparse(url).netloc.lower()
if host not in VERIFIED:
raise ValueError(host + " is not on the verified list")
req = urllib.request.Request(url, headers={"User-Agent": "Oracle7-make/12.0"})
t = urllib.request.urlopen(req, timeout=30).read(5_000_000).decode("utf-8", "ignore")
m = re.search(r'(?s)id="mw-content-text".*', t)
t = m.group(0) if m else t
t = re.sub(r"(?is)<(script|style).*?</\\1>", " ", t)
return re.sub(r"\\s+", " ", re.sub(r"(?s)<[^>]+>", " ", t)).strip()'''
def workspace_move(step, P, find_fn, read_rec):
"""no language move fits: a workspace function that does this step, copied in with its file's imports"""
hits = find_fn(step)
if not hits:
return False, []
best, score = hits[0]
named = getattr(find_fn, "named", None) # the step NAMES a workspace function: exact, no threshold
if named:
# sealed v3 (w04): "of each line" named the workspace function line(). Only the thing the step acts on counts: the
# first word after the verb and its articles (joined with the next word as one name too: standard_deviation).
ws = re.findall(r"[a-z_][a-z0-9_]*", step.lower())
while ws and ws[0] in {"compute", "calculate", "find", "take", "get", "work", "out", "apply", "the", "a", "an", "its",
"their", "then", "and"}:
ws.pop(0)
cands = ([ws[0] + "_" + ws[1]] if len(ws) > 1 else []) + ws[:1]
# sealed v5 (z10): "train a neural network on it" named an unrelated train(). A named function is taken only when
# every other content word of the step is in the function's own name or description.
filler = {"it", "them", "this", "that", "on", "of", "to", "for", "in", "with", "a", "an", "the", "result", "each",
"every", "and", "by", "from", "into", "all", "its", "their"}
rest = [w for w in ws if w not in filler and len(w) > 2]
for w in cands:
rec = named(w) if len(w) > 2 else None
if rec:
own = set(re.findall(r"[a-z]+", (rec["name"] + " " + rec.get("doc", "")).lower().replace("_", " ")))
if all(x in own or x in w.split("_") for x in rest):
best, score = rec, 1.0
break
near = ["%s (%s, %.2f)" % (h["name"], h["path"], s) for h, s in hits[:3]]
required = getattr(find_fn, "required", None) # inputs without a default, read from the function's definition
nreq = required(best) if required else len([a for a in best["args"] if a != "self"])
if score < 0.80 or best["kind"] != "def" or nreq != 1 or "self" in best["args"]:
return False, near
src, imps = read_rec(best)
if not src:
return False, near
P.extra.append(src)
P.imports.update(imps)
P.emit("x = %s(x)" % best["name"], "value")
P.trace.append("workspace: %s from %s" % (best["name"], best["path"]))
return True, near
HEADER = re.compile(r"^\s*(?:function|define|def|to)\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*:\s*(.*)$", re.I | re.S)
PARAMS_RX = re.compile(r"^\s*(?:function|define|def|to)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)", re.I)
FPARAMS = {} # Amendment 13b: a function's inputs as its header names them ("function big_total(xs, limit): ...")
MAINH = re.compile(r"^\s*(?:main|then|finally|the program)\s*:\s*(.*)$", re.I | re.S)
def blocks_of(desc):
"""a program of several functions: "function <name>: <steps>; function <name>: <steps>; main: <steps>". Segments are cut
at ";" and new lines; a segment with a header opens a function; the rest belongs to main. -> [(name or None, text)]"""
body = re.sub(r"\bexpect(?:ing)?\b.*$", "", desc, flags=re.I | re.S)
segs = [s for s in re.split(r";|\n", body) if s.strip()]
if not any(HEADER.match(s) for s in segs):
return [(None, desc)]
out, cur = [], [None, []]
for s in segs:
h, m = HEADER.match(s), MAINH.match(s)
if h:
if cur[1]:
out.append((cur[0], ", ".join(cur[1])))
cur = [h.group(1), [h.group(2)] if h.group(2).strip() else []]
elif m:
if cur[1]:
out.append((cur[0], ", ".join(cur[1])))
cur = [None, [m.group(1)] if m.group(1).strip() else []]
else:
cur[1].append(s)
if cur[1]:
out.append((cur[0], ", ".join(cur[1])))
return out
DEFINED = set()
_COMPOSE_LOCK = threading.RLock()
def compose(desc, find_fn, read_rec):
with _COMPOSE_LOCK:
return _compose(desc, find_fn, read_rec)
def _compose(desc, find_fn, read_rec):
"""one program from a description: its functions first (each composed from its own steps, x in, x out), then main, whose
steps may call them by name ("total it", "use total")"""
global NUMP
FPARAMS.clear()
for seg in re.split(r";|\n", re.sub(r"\bexpect(?:ing)?\b.*$", "", desc, flags=re.I | re.S)):
pm = PARAMS_RX.match(seg)
if pm:
FPARAMS[pm.group(1)] = [a.strip() for a in pm.group(2).split(",") if re.fullmatch(r"\s*[A-Za-z_]\w*\s*", a)]
blocks = blocks_of(desc)
DEFINED.clear()
DEFINED.update(n for n, _ in blocks if n)
fns, gaps, trace, imports = [], [], [], set()
for name, text in blocks:
if not name:
continue
params = FPARAMS.get(name) or []
extra_in = [p for p in params[1:] if p != "x"]
NUMP = (r"(-?\d+(?:\.\d+)?|" + "|".join(re.escape(p) for p in extra_in) + r")") if extra_in else NUM
Q = Prog()
try:
compile_steps(steps_of(text), Q, find_fn, read_rec)
finally:
NUMP = NUM
gaps += ["in %s: %s" % (name, g) for g in Q.gaps]
trace += ["%s: %s" % (name, t) for t in Q.trace]
imports |= Q.imports
body = "\n".join(" " + (("_show(" + ln[len("print("):]) if ln.startswith("print(") else ln) for ln in Q.lines) or " pass"
if params: # the first input is the value the steps start from; the others are named
head = "def %s(%s):\n" % (name, ", ".join(params)) + (" x = %s\n" % params[0] if params[0] != "x" else "")
else:
head = "def %s(x):\n" % name
fns.append((Q.extra, "%s%s\n return x" % (head, body)))
main_text = ", ".join(t for n, t in blocks if not n)
P = Prog()
for extra, src in fns:
for e in extra:
if e not in P.extra:
P.extra.append(e)
P.extra.append(src)
P.imports |= imports
P.trace += trace
if main_text.strip():
compile_steps(steps_of(main_text), P, find_fn, read_rec)
P.gaps = gaps + P.gaps
return finish(P)
def compile_steps(steps, P, find_fn, read_rec):
j = 0
while j < len(steps):
st, i = steps[j], j + 1
n0 = len(P.lines)
try:
used = branch(steps, j, P)
except Exception as e: # noqa: BLE001
used = 0
P.gaps.append("step %d (%s): the branch raised %s" % (i, st, e))
if used:
P.trace.append("step %d-%d: %s -> %s" % (i, i + used - 1, " / ".join(steps[j:j + used]), P.lines[-1]))
j += used
continue
j += 1
try:
if not each(st, P):
move(st, P, None)
except Exception as e: # noqa: BLE001
P.gaps.append("step %d (%s): the move raised %s" % (i, st, e))
continue
if len(P.lines) > n0:
P.trace.append("step %d: %s -> %s" % (i, st, P.lines[-1]))
continue
ok, near = workspace_move(st, P, find_fn, read_rec)
if not ok:
P.gaps.append("step %d (%s): no move of the language does this and no workspace function fits it%s" % (
i, st, ("; nearest: " + "; ".join(near)) if near else ""))
return P
def finish(P):
if P.lines and not any(ln.startswith(("print(", "x = _serve(", "_serve(")) for ln in P.lines):
P.emit("print(x)" if P.kind not in ("list", "pairs") else
("print(\"\\n\".join(map(str, x)))" if P.kind == "list" else "print(\"\\n\".join(\"%s\\t%s\" % p for p in x))"), P.kind)
if "fetch_text" in "\n".join(P.extra):
P.extra.insert(0, "VERIFIED = %r" % VERIFIED_LIST)
src = P.source()
ast.parse(src)
return src, P
VERIFIED_LIST = []
def expected_of(desc):
m = re.search(r"\bexpect(?:ing)?\s*:?\s*(.+)$", desc, re.I | re.S)
return m.group(1).strip().strip("'\"") if m else None
|