Spaces:
Running on Zero
Running on Zero
File size: 7,572 Bytes
49d5bc8 | 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 | # -*- coding: utf-8 -*-
"""Core logic of the demo (no Gradio import, so it can be tested alone). Model package v0.4: left brain = v0.3 pipeline #83
(unchanged) + spiral/ (word-problem reader + program brain, see spiral_tab.py)."""
import concurrent.futures as cf
import importlib
import json
import os
import sys
import time
from fractions import Fraction
REPO = "Bigbearbo/handwired-left-brain-1"
REVISION = "v0.4"
MAX_LEN = 300
TIMEOUT_S = 20 # normal questions
TIMEOUT_BIG_S = 240 # big-number mode: a big product took 30-55 s per question on the author's CPU (ladder tiers, then segment core)
PKG = None
BUILD_SECONDS = None
_lb = []
_pool = cf.ThreadPoolExecutor(max_workers=1) # one worker: the network code is not thread-safe
OFFICIAL7 = ["arithmetic__add_or_sub", "arithmetic__mul", "arithmetic__div", "arithmetic__mixed", "numbers__gcd",
"numbers__div_remainder", "algebra__linear_1d"]
# First-level modules used as examples: the fast ones (others, e.g. polynomial roots, can pass the time limit)
FAST_T1 = ["comparison__pair", "comparison__sort", "numbers__lcm", "numbers__is_factor", "numbers__base_conversion",
"numbers__place_value", "arithmetic__add_sub_multiple", "arithmetic__mul_div_multiple", "algebra__linear_2d",
"algebra__sequence_next_term"]
def get_pkg():
"""Local package via LOCAL_PKG, else download the model package (tag v0.4) from the Hub."""
global PKG
if PKG:
return PKG
PKG = os.environ.get("LOCAL_PKG")
if not PKG:
import tempfile
from huggingface_hub import snapshot_download
# local_dir = real files, not the cache's symlinks: spiral/ code uses Path(__file__).resolve(), which would
# follow a cache symlink into blobs/ and lose its folder layout (FileNotFoundError on the first Space run)
PKG = snapshot_download(REPO, revision=REVISION,
local_dir=os.path.join(tempfile.gettempdir(), "handwired-left-brain-1-" + REVISION))
return PKG
def init():
"""Load the package and wire pipeline #83 once; BUILD_SECONDS records the time."""
global BUILD_SECONDS
if _lb:
return BUILD_SECONDS
t0 = time.time()
pkg = get_pkg()
if pkg not in sys.path:
sys.path.insert(0, pkg)
lb = importlib.import_module("lb")
lb.init()
_lb.append(lb)
BUILD_SECONDS = round(time.time() - t0, 1)
return BUILD_SECONDS
def warm_up(extra=()):
"""Run the example questions (and extra ones) once so their networks are built at startup, not on a click."""
global BUILD_SECONDS
t0 = time.time()
init()
for _, q in get_examples():
_solve_inner(q)
for q in extra:
_solve_inner(q)
BUILD_SECONDS = round(time.time() - t0, 1)
return BUILD_SECONDS
def _items(name):
d = json.load(open(os.path.join(get_pkg(), "data", name), encoding="utf-8"))
return d.get("items") or d.get("題")
def get_examples(per_module=1):
"""Example questions: official 7 modules (train-easy file) + the fast first-level modules (level-1 file)."""
got, out = {}, []
srcs = [("official_train_easy_1400.json", OFFICIAL7), ("level1_train_easy_2000.json", FAST_T1)]
for name, mods in srcs:
for d in _items(name):
m = d.get("dataset_module") or d.get("模組")
if m in mods and len(got.setdefault(m, [])) < per_module and 12 <= len(d["question"]) <= 90:
got[m].append(d["question"])
out.append((m, d["question"]))
return out
def _dec(v, k):
n = abs(v.numerator) * 10 ** k // v.denominator
s = str(n).rjust(k + 1, "0")
return ("-" if v < 0 else "") + s[:-k] + "." + s[-k:]
def _fmt(v):
"""Fraction -> 'a/b' (plus the exact decimal when the denominator is 2^i 5^j)."""
v = Fraction(v)
if v.denominator == 1:
return str(v.numerator)
den, k2, k5 = v.denominator, 0, 0
while den % 2 == 0:
den //= 2
k2 += 1
while den % 5 == 0:
den //= 5
k5 += 1
s = f"{v.numerator}/{v.denominator}"
if den == 1:
s += f" (= {_dec(v, max(k2, k5))})"
return s
def _official(v):
v = Fraction(v)
return str(v.numerator) if v.denominator == 1 else f"{v.numerator}/{v.denominator}"
def _result(question, answer="", status="", route="", tokens="", seconds=0.0, verdict=None, raw=""):
return {"question": question, "answer": answer, "raw": raw, "status": status, "route": route,
"tokens": tokens, "seconds": round(seconds, 3), "verdict": verdict}
def _solve_inner(question, gold=None):
lb = _lb[0]
g = None if gold is None else (gold if isinstance(gold, str) else _official(gold))
r = lb.solve(question, gold=g)
raw = ans = r["answer"]
try:
if ans:
ans = _fmt(Fraction(ans))
except (ValueError, ZeroDivisionError):
pass # non-numeric answers (True, "a", "2, 3, 23", "21*w + 16") stay as text
route = r["route"] + (f" [{r['module']}]" if r["module"] else "")
return _result(question, answer=ans, raw=raw, status=r["status"], route=route, tokens=r["tokens"],
seconds=r["seconds"], verdict=r["verdict"])
def solve(question, gold=None, big=False, limit=None):
"""Returns a dict: answer, raw, status, route, tokens, seconds, verdict (never raises).
gold: reference answer (Fraction or official string); with it the pipeline also grades the answer.
limit: time limit in s (default TIMEOUT_S, or TIMEOUT_BIG_S in big mode); the UI raises it for slow types."""
t0 = time.time()
q = (question or "").strip()
if not q:
return _result(q, status="Refused: empty input.")
if len(q) > MAX_LEN:
return _result(q[:40] + "...", status=f"Refused: input longer than {MAX_LEN} characters.")
lim = limit or (TIMEOUT_BIG_S if big else TIMEOUT_S)
try:
init()
return _pool.submit(_solve_inner, q, gold).result(timeout=lim)
except cf.TimeoutError:
return _result(q, status=f"Refused: timed out after {lim} s.", seconds=time.time() - t0)
except Exception as e:
return _result(q, status="Refused: internal error (" + type(e).__name__ + ").", seconds=time.time() - t0)
# ---------------------------------------------------------------- word-problem tab (spiral/): reader + program brain + left brain
WP_TIMEOUT_S = 60
def _lb_for_wp(question):
"""One integer operation for the word-problem tab, answered by the hand-wired left brain (runs in the worker)."""
return _solve_inner(question)
def _wp_run(fn, text):
import spiral_tab
spiral_tab.init(get_pkg())
return fn(text, _lb_for_wp)
def solve_word_problem(text, info=False):
"""English word problem (info=False) or English-style information sentences (info=True) -> dict (never raises)."""
import spiral_tab
try:
init()
fn = spiral_tab.solve_info if info else spiral_tab.solve_question
return _pool.submit(_wp_run, fn, text).result(timeout=WP_TIMEOUT_S)
except cf.TimeoutError:
r = spiral_tab._empty(text)
r["status"] = f"Refused: timed out after {WP_TIMEOUT_S} s."
return r
except Exception as e:
r = spiral_tab._empty(text)
r["status"] = "Refused: internal error (" + type(e).__name__ + ")."
return r
|