"""Render one tree two ways: to_typst() (deterministic) and to_english() (randomised). Because both strings come from the same tree, every (English, Typst) pair is correct by construction. The English side has to be *unambiguous*: if two different trees could produce the same sentence, the model is taught to guess. The conventions that keep it unambiguous are: * "tail" position: a sub-expression is in tail position when nothing follows it inside its parent. Only there may a phrase run on to the end ("e to the minus x squared", "the quantity x plus 1"). * Anything that is not "simple" (see is_simple) is wrapped when it is an operand: "(x plus 1)", "open paren x plus 1 close paren", or, in tail position only, "the quantity x plus 1". * An exponent is spoken bare only if it is a number, a variable, or "minus " in tail position (guide Appendix A, Q1: "e to the minus x squared" = e^(-x^2)). Every other exponent is delimited. * Functions and roots take one simple argument: "sine of x squared" = sin(x^2); sin(x)^2 is said "sine squared of x" or "(sine of x) squared". * Big operators (integral, sum, limit) only appear at the top of a tree, and their body runs until "dx" (integrals), "equals", or the end of the sentence. """ from __future__ import annotations import random import re from .ast import BIG_OPS, GREEK, Add, Eq, Frac, Func, Integral, Lim, Mul, Neg, Node, Num, Pow, Sqrt, Sub, Sum, Var # ------------------------------------------------------------------------------------------ # Typst # ------------------------------------------------------------------------------------------ def level(n: Node) -> int: """How tightly a node binds in Typst output (higher = tighter).""" if isinstance(n, Eq): return 0 if isinstance(n, (Add, Sub)): return 1 if isinstance(n, BIG_OPS): return 2 if isinstance(n, Neg): return 3 if isinstance(n, Mul): return 4 return 9 # atoms: Var, Num, Pow, Frac, Sqrt, Func def paren(n: Node, cond: bool) -> str: s = to_typst(n) return f"({s})" if cond else s def group(n: Node) -> str: """Sub/superscripts: Typst needs parens around anything longer than one atom (they are not shown).""" return paren(n, not isinstance(n, (Var, Num))) def to_typst(n: Node) -> str: match n: case Var(name): return name case Num(v): return str(v) case Neg(a): return f"-{paren(a, level(a) <= 3)}" case Add(a, b): return f"{to_typst(a)} + {paren(b, level(b) <= 1 or isinstance(b, Neg))}" case Sub(a, b): return f"{to_typst(a)} - {paren(b, level(b) <= 1 or isinstance(b, Neg))}" case Mul(a, b): left = paren(a, level(a) < 3) right = paren(b, level(b) <= 3 and not isinstance(b, BIG_OPS)) sep = " dot " if left[-1].isdigit() and right[0].isdigit() else " " # "2 dot 3", not "2 3" return f"{left}{sep}{right}" case Pow(b, e): # parens around the base *are* visible, so only add them when needed return f"{paren(b, not isinstance(b, (Var, Num, Func, Sqrt)))}^{group(e)}" case Frac(a, b): return f"frac({to_typst(a)}, {to_typst(b)})" case Sqrt(a): return f"sqrt({to_typst(a)})" case Func(name, a): return f"{name}({to_typst(a)})" case Integral(body, v, lo, hi): bounds = "" if lo is None else f"_{group(lo)}^{group(hi)}" return f"integral{bounds} {paren(body, level(body) <= 1)} dif {v}" case Sum(body, v, lo, hi): return f"sum_({v} = {to_typst(lo)})^{group(hi)} {paren(body, level(body) <= 1)}" case Lim(body, v, to): return f"lim_({v} -> {to_typst(to)}) {paren(body, level(body) <= 1)}" case Eq(a, b): return f"{to_typst(a)} = {to_typst(b)}" raise NotImplementedError(n) # ------------------------------------------------------------------------------------------ # English # ------------------------------------------------------------------------------------------ ONES = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] ORDINALS = {4: "fourth", 5: "fifth", 6: "sixth", 7: "seventh", 8: "eighth", 9: "ninth", 10: "tenth"} FUNC_WORDS = { "sin": ["sine", "sin"], "cos": ["cosine", "cos"], "tan": ["tangent", "tan"], "ln": ["ln", "natural log", "the natural log", "the natural logarithm"], "log": ["log", "the log", "the logarithm"], "exp": ["exp", "the exponential"], } def number_words(v: int) -> str: if v < 20: return ONES[v] if v < 100: t, o = divmod(v, 10) return TENS[t] + ("" if o == 0 else " " + ONES[o]) if v == 100: return "one hundred" return str(v) def is_simple(n: Node) -> bool: """Can be said as an operand without wrapping it in parentheses.""" if isinstance(n, (Var, Num, Func, Sqrt)): return True return isinstance(n, Pow) and isinstance(n.base, (Var, Num)) and isinstance(n.exp, (Var, Num)) class English: def __init__(self, rng: random.Random): self.rng = rng def c(self, *options: str) -> str: return self.rng.choice(options) def p(self, prob: float) -> bool: return self.rng.random() < prob def wrap(self, n: Node, tail: bool) -> str: """Say n so that a listener knows where it ends.""" if is_simple(n): return self.say(n, tail) s = self.say(n, tail=True) # the brackets delimit it, so inside it may run on options = [f"({s})", f"open paren {s} close paren"] if tail: # "the quantity" has no closing word, so it must run to the end options += [f"the quantity {s}"] * 2 return self.c(*options) def say(self, n: Node, tail: bool = True) -> str: match n: case Var("infinity"): return "infinity" case Var(name): return name case Num(v): return number_words(v) if v <= 100 and self.p(0.3) else str(v) case Neg(a): inner = self.say(a, tail) if is_simple(a) else self.wrap(a, tail) return f"{self.c('minus', 'negative')} {inner}" case Add(a, b) | Sub(a, b): left = self.say(a, tail=False) right = self.wrap(b, tail) if level(b) <= 1 or isinstance(b, Neg) else self.say(b, tail) op = self.c("plus", "plus", "add") if isinstance(n, Add) else "minus" if op == "add": op = "plus" return f"{left} {op} {right}" case Mul(a, b): left = self.say(a, tail=False) if level(a) >= 3 else self.wrap(a, tail=False) right = self.wrap(b, tail) if level(b) <= 3 else self.say(b, tail) if isinstance(a, Num) and isinstance(b, (Var, Pow, Func, Sqrt)) and self.p(0.6): if isinstance(b, Var) and len(b.name) == 1 and left.isdigit() and self.p(0.5): return f"{left}{right}" # "2x" return f"{left} {right}" # "2 x", "3 sine of x" if isinstance(a, Var) and isinstance(b, Var) and self.p(0.4): return f"{left} {right}" # "x y" return self.c(f"{left} times {right}", f"{left} times {right}", f"{left} multiplied by {right}") case Pow(b, e): return self.say_pow(b, e, tail) case Frac(Num(1), Num(2)) if self.p(0.4): return self.c("one half", "a half") case Frac(a, b): num = self.wrap(a, tail=False) den = self.wrap(b, tail) return self.c( f"{num} over {den}", f"{num} over {den}", f"{num} divided by {den}", f"the fraction {num} over {den}", ) case Sqrt(a): arg = self.say(a, tail) if is_simple(a) else self.wrap(a, tail) return self.c(f"the square root of {arg}", f"square root of {arg}", f"root {arg}", f"sqrt of {arg}") case Func(name, a): word = self.rng.choice(FUNC_WORDS[name]) if not is_simple(a): return f"{word} of {self.wrap(a, tail)}" arg = self.say(a, tail) if word in ("sin", "cos", "tan", "ln", "log", "exp") and self.p(0.5): return f"{word} {arg}" return f"{word} of {arg}" case Integral(body, v, lo, hi): b = self.say(body, tail=True) # "dx" closes the body d = self.c(f"d{v}", f"d{v}", f"d {v}", f"with respect to {v}") if lo is None: return self.c( f"the integral of {b} {d}", f"integral of {b} {d}", f"integral {b} {d}", f"the indefinite integral of {b} {d}", ) lo_s, hi_s = self.say(lo, False), self.say(hi, False) return self.c( f"the integral from {lo_s} to {hi_s} of {b} {d}", f"the integral from {lo_s} to {hi_s} of {b} {d}", f"integral from {lo_s} to {hi_s} of {b} {d}", f"integral {lo_s} to {hi_s} {b} {d}", f"the definite integral from {lo_s} to {hi_s} of {b} {d}", f"the integral of {b} from {lo_s} to {hi_s} {d}", ) case Sum(body, v, lo, hi): b = self.say(body, tail) lo_s, hi_s = self.say(lo, False), self.say(hi, False) eq = self.c("equals", "equals", "=", "from") return self.c( f"the sum from {v} {eq} {lo_s} to {hi_s} of {b}", f"the sum from {v} {eq} {lo_s} to {hi_s} of {b}", f"sum from {v} {eq} {lo_s} to {hi_s} of {b}", f"sum {v} {eq} {lo_s} to {hi_s} {b}", f"the sum over {v} from {lo_s} to {hi_s} of {b}", ) case Lim(body, v, to): b = self.say(body, tail) to_s = self.say(to, False) verb = self.c("approaches", "approaches", "goes to", "tends to") return self.c( f"the limit as {v} {verb} {to_s} of {b}", f"the limit as {v} {verb} {to_s} of {b}", f"limit as {v} {verb} {to_s} of {b}", f"lim {v} {verb} {to_s} of {b}", ) case Eq(a, b): return f"{self.say(a, False)} {self.c('equals', 'equals', 'is equal to', 'is')} {self.say(b, tail)}" raise NotImplementedError(n) def say_pow(self, b: Node, e: Node, tail: bool) -> str: if isinstance(b, Func) and e in (Num(2), Num(3)) and is_simple(b.arg) and self.p(0.5): word = self.rng.choice(FUNC_WORDS[b.name][:2]) return f"{word} {'squared' if e == Num(2) else 'cubed'} of {self.say(b.arg, tail)}" # sine squared of x if isinstance(b, (Var, Num)): base = self.say(b, False) else: # bracket the base, even for functions: "sine of x squared" means sin(x^2) inner = self.say(b, True) base = self.c(f"({inner})", f"open paren {inner} close paren") if e == Num(2): return self.c(f"{base} squared", f"{base} squared", f"{base} to the power of 2", f"{base} to the second") if e == Num(3): return self.c(f"{base} cubed", f"{base} cubed", f"{base} to the power of 3", f"{base} to the third") if isinstance(e, Num): options = [f"{base} to the power of {self.say(e)}", f"{base} to the {self.say(e)}"] if e.value in ORDINALS: options.append(f"{base} to the {ORDINALS[e.value]}") return self.c(*options) if isinstance(e, Var): options = [f"{base} to the {e.name}", f"{base} to the power of {e.name}"] if len(e.name) == 1: options.append(f"{base} to the {e.name}th") return self.c(*options) if tail and isinstance(e, Neg) and is_simple(e.arg): # e to the minus x squared ex = self.say(e, True) return self.c(f"{base} to the {ex}", f"{base} to the power of {ex}") ex = self.say(e, True) return self.c( f"{base} to the ({ex})", f"{base} to the power of ({ex})", f"{base} to the open paren {ex} close paren" ) PREFIXES = ["write ", "what is ", "typeset ", "please write "] def add_noise(s: str, rng: random.Random) -> str: """Surface variation people produce: a dropped 'the', capitals, a polite prefix.""" if rng.random() < 0.3: s = re.sub(r"(^|\bof )the ", lambda m: m.group(1) if rng.random() < 0.5 else m.group(0), s) if rng.random() < 0.08: s = rng.choice(PREFIXES) + s first = s.split(" ", 1)[0] if rng.random() < 0.15 and len(first) >= 3 and first.isalpha() and first not in GREEK: # never "Y" for y s = s[:1].upper() + s[1:] return s def to_english(n: Node, rng: random.Random, noise: bool = True) -> str: s = re.sub(r"\s+", " ", English(rng).say(n, tail=True)).strip() return add_noise(s, rng) if noise else s