Add deterministic numeric-consistency checker (flags prose number slips)
Browse files- app.py +15 -3
- core/numcheck.py +122 -0
- pipeline/prompts.py +91 -7
- shared/i18n.py +1 -0
app.py
CHANGED
|
@@ -26,7 +26,7 @@ for _p in (str(_ROOT), str(_MONOREPO)):
|
|
| 26 |
import gradio as gr # noqa: E402
|
| 27 |
|
| 28 |
from shared import i18n # noqa: E402 (visuals are local; only i18n is shared)
|
| 29 |
-
from core import export, infer, render # noqa: E402
|
| 30 |
|
| 31 |
LOGO_PATH = _ROOT / "assets" / "logo.svg"
|
| 32 |
_LOGO_SVG = LOGO_PATH.read_text(encoding="utf-8")
|
|
@@ -163,6 +163,11 @@ body.cf-forging #cf-header .cf-logo{ filter:drop-shadow(0 6px 22px rgba(255,138,
|
|
| 163 |
.cf-pass{ background:rgba(74,222,128,.14); border-color:rgba(74,222,128,.5); color:#bbf7d0; }
|
| 164 |
.cf-fail{ background:rgba(248,113,113,.13); border-color:rgba(248,113,113,.45); color:#fecaca; }
|
| 165 |
.cf-demo{ font-style:italic; opacity:.85; margin-top:6px; font-size:.85rem; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
.cf-hint{ font-size:.82rem; opacity:.65; margin:4px 2px; }
|
| 167 |
|
| 168 |
/* ---------- empty state (illustrated) ---------- */
|
|
@@ -254,7 +259,8 @@ def _empty_state(lang: str) -> str:
|
|
| 254 |
'<p>' + i18n.t("cf.result_empty", lang) + '</p></div>')
|
| 255 |
|
| 256 |
|
| 257 |
-
def _chips_html(flags: dict, lang: str, demo: bool, reason: str | None = None
|
|
|
|
| 258 |
labels = {
|
| 259 |
"schema": i18n.t("cf.q_schema", lang),
|
| 260 |
"noleak": i18n.t("cf.q_noleak", lang),
|
|
@@ -271,6 +277,10 @@ def _chips_html(flags: dict, lang: str, demo: bool, reason: str | None = None) -
|
|
| 271 |
+ '">' + mark + ' ' + labels[key] + '</span>')
|
| 272 |
head = '<div class="cf-chips">' + "".join(chips) + '</div>'
|
| 273 |
head += '<div class="cf-demo">⚠ ' + i18n.t("cf.disclaimer", lang) + '</div>'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
if demo:
|
| 275 |
note = "cf.busy_note" if reason == "busy" else "cf.demo_note"
|
| 276 |
head += '<div class="cf-demo">' + i18n.t(note, lang) + '</div>'
|
|
@@ -309,7 +319,9 @@ def forge(domain, topic, level, case_lang, theory, ui_lang_label):
|
|
| 309 |
return
|
| 310 |
|
| 311 |
flags = render.quality_flags(obj, res.get("errors", []), res.get("warnings", []))
|
| 312 |
-
|
|
|
|
|
|
|
| 313 |
case_md = render.render_case(obj)
|
| 314 |
note_md = render.render_note(obj)
|
| 315 |
title = obj.get("title", "case")
|
|
|
|
| 26 |
import gradio as gr # noqa: E402
|
| 27 |
|
| 28 |
from shared import i18n # noqa: E402 (visuals are local; only i18n is shared)
|
| 29 |
+
from core import export, infer, numcheck, render # noqa: E402
|
| 30 |
|
| 31 |
LOGO_PATH = _ROOT / "assets" / "logo.svg"
|
| 32 |
_LOGO_SVG = LOGO_PATH.read_text(encoding="utf-8")
|
|
|
|
| 163 |
.cf-pass{ background:rgba(74,222,128,.14); border-color:rgba(74,222,128,.5); color:#bbf7d0; }
|
| 164 |
.cf-fail{ background:rgba(248,113,113,.13); border-color:rgba(248,113,113,.45); color:#fecaca; }
|
| 165 |
.cf-demo{ font-style:italic; opacity:.85; margin-top:6px; font-size:.85rem; }
|
| 166 |
+
.cf-numwarn{ margin-top:8px; padding:8px 12px; border-radius:10px; font-size:.84rem;
|
| 167 |
+
background:rgba(255,193,7,.10); border:1px solid rgba(255,193,7,.40); color:#ffe2a6; }
|
| 168 |
+
.cf-numwarn b{ color:#ffd479; }
|
| 169 |
+
.cf-numwarn ul{ margin:4px 0 0; padding-left:18px; }
|
| 170 |
+
.cf-numwarn li{ margin:2px 0; }
|
| 171 |
.cf-hint{ font-size:.82rem; opacity:.65; margin:4px 2px; }
|
| 172 |
|
| 173 |
/* ---------- empty state (illustrated) ---------- */
|
|
|
|
| 259 |
'<p>' + i18n.t("cf.result_empty", lang) + '</p></div>')
|
| 260 |
|
| 261 |
|
| 262 |
+
def _chips_html(flags: dict, lang: str, demo: bool, reason: str | None = None,
|
| 263 |
+
num_warns: list | None = None) -> str:
|
| 264 |
labels = {
|
| 265 |
"schema": i18n.t("cf.q_schema", lang),
|
| 266 |
"noleak": i18n.t("cf.q_noleak", lang),
|
|
|
|
| 277 |
+ '">' + mark + ' ' + labels[key] + '</span>')
|
| 278 |
head = '<div class="cf-chips">' + "".join(chips) + '</div>'
|
| 279 |
head += '<div class="cf-demo">⚠ ' + i18n.t("cf.disclaimer", lang) + '</div>'
|
| 280 |
+
if num_warns:
|
| 281 |
+
items = "".join("<li>" + w + "</li>" for w in num_warns)
|
| 282 |
+
head += ('<div class="cf-numwarn"><b>⚠ ' + i18n.t("cf.numcheck_title", lang)
|
| 283 |
+
+ '</b><ul>' + items + '</ul></div>')
|
| 284 |
if demo:
|
| 285 |
note = "cf.busy_note" if reason == "busy" else "cf.demo_note"
|
| 286 |
head += '<div class="cf-demo">' + i18n.t(note, lang) + '</div>'
|
|
|
|
| 319 |
return
|
| 320 |
|
| 321 |
flags = render.quality_flags(obj, res.get("errors", []), res.get("warnings", []))
|
| 322 |
+
clang_obj = obj.get("language", "pt")
|
| 323 |
+
num_warns = [] if res.get("demo") else numcheck.check(obj, clang_obj)
|
| 324 |
+
chips = _chips_html(flags, lang, res.get("demo", False), res.get("reason"), num_warns)
|
| 325 |
case_md = render.render_case(obj)
|
| 326 |
note_md = render.render_note(obj)
|
| 327 |
title = obj.get("title", "case")
|
core/numcheck.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic numeric-consistency checker (no LLM, instant, free).
|
| 2 |
+
|
| 3 |
+
A ≤4B model generating freehand still slips on prose numbers (e.g. "gera R$375k/dia"
|
| 4 |
+
when 5.000 rides × R$25 = R$125k). The teacher/code-audit fixes the TRAINING corpus,
|
| 5 |
+
but the live student isn't audited at inference (that would 3× latency + burn ZeroGPU
|
| 6 |
+
quota). So instead the Space runs this cheap pattern-checker over the generated case and
|
| 7 |
+
**flags** likely inconsistencies for the author to verify — fitting the authoring/review
|
| 8 |
+
model. It WARNS, never silently "fixes" prose.
|
| 9 |
+
|
| 10 |
+
Conservative by design: only flags when it confidently extracts a relationship.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import re
|
| 16 |
+
|
| 17 |
+
_UNIT = r"(?:corridas?|viagens?|unidades?|clientes?|pedidos?|atendimentos?|" \
|
| 18 |
+
r"rides?|trips?|units?|customers?|orders?)"
|
| 19 |
+
_PERDAY = r"(?:por dia|/\s*dia|ao dia|di[aá]ri[ao]s?|per day|/\s*day|daily|por m[eê]s|/\s*m[eê]s|monthly|per month)"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _num(text: str) -> float | None:
|
| 23 |
+
"""Parse a pt-BR/en number, honoring mil/milhão (and thousands/decimal seps)."""
|
| 24 |
+
t = text.lower()
|
| 25 |
+
mult = 1.0
|
| 26 |
+
if "milh" in t or "million" in t or "mi " in t:
|
| 27 |
+
mult = 1_000_000.0
|
| 28 |
+
elif "mil" in t or "thousand" in t:
|
| 29 |
+
mult = 1_000.0
|
| 30 |
+
m = re.search(r"\d[\d.,]*", t)
|
| 31 |
+
if not m:
|
| 32 |
+
return None
|
| 33 |
+
n = m.group(0)
|
| 34 |
+
if "," in n and "." in n: # pt-BR: '.' thousands, ',' decimal
|
| 35 |
+
n = n.replace(".", "").replace(",", ".")
|
| 36 |
+
elif "," in n: # only comma → decimal sep
|
| 37 |
+
n = n.replace(",", ".")
|
| 38 |
+
else: # only dots → thousands sep (375.000)
|
| 39 |
+
if re.search(r"\.\d{3}\b", n):
|
| 40 |
+
n = n.replace(".", "")
|
| 41 |
+
try:
|
| 42 |
+
return float(n) * mult
|
| 43 |
+
except ValueError:
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _money(seg: str):
|
| 48 |
+
"""First R$/$ amount in a fragment (carrying mil/milhão words after it)."""
|
| 49 |
+
m = re.search(r"(?:R\$|\$)\s*([\d.,]+(?:\s*(?:mil|milh[õo]es?|milh[ãa]o|million|thousand))?)", seg, re.I)
|
| 50 |
+
return _num(m.group(1)) if m else None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _close(a: float, b: float, tol: float = 0.05) -> bool:
|
| 54 |
+
if a is None or b is None:
|
| 55 |
+
return True
|
| 56 |
+
big = max(abs(a), abs(b), 1.0)
|
| 57 |
+
return abs(a - b) / big <= tol
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _fmt(v: float) -> str:
|
| 61 |
+
v = round(v)
|
| 62 |
+
return f"{v:,.0f}".replace(",", ".")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _sentences(text: str) -> list[str]:
|
| 66 |
+
return re.split(r"(?<=[.;:])\s+|\n", text)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def check(obj: dict, lang: str = "pt") -> list[str]:
|
| 70 |
+
"""Return author-facing warnings about likely numeric inconsistencies."""
|
| 71 |
+
if not obj:
|
| 72 |
+
return []
|
| 73 |
+
c = obj.get("case") or {}
|
| 74 |
+
data = c.get("data") or []
|
| 75 |
+
text = " ".join([c.get("context", "")] + [str(d) for d in data]
|
| 76 |
+
+ [str(e.get("content", "")) for e in (c.get("exhibits") or [])])
|
| 77 |
+
warns: list[str] = []
|
| 78 |
+
|
| 79 |
+
# --- 1) daily/monthly revenue ≈ quantity × unit price -------------------
|
| 80 |
+
# quantity per period (prefer "média"/"total"/largest)
|
| 81 |
+
qtys = [_num(m.group(0)) for m in
|
| 82 |
+
re.finditer(rf"\d[\d.,]*\s*{_UNIT}[^.]*?{_PERDAY}", text, re.I)]
|
| 83 |
+
qtys = [q for q in qtys if q]
|
| 84 |
+
unit_price = None
|
| 85 |
+
mp = re.search(rf"(?:R\$|\$)\s*([\d.,]+)\s*(?:por|/|each|per)\s*{_UNIT}", text, re.I)
|
| 86 |
+
if mp:
|
| 87 |
+
unit_price = _num(mp.group(1))
|
| 88 |
+
# the revenue sentence: has "receita/gera/faturamento" + a per-period amount
|
| 89 |
+
rev = None
|
| 90 |
+
for s in _sentences(text):
|
| 91 |
+
if re.search(r"receita|fatur|gera|revenue|generat|bring", s, re.I) and re.search(_PERDAY, s, re.I):
|
| 92 |
+
rev = _money(s)
|
| 93 |
+
if rev:
|
| 94 |
+
break
|
| 95 |
+
if qtys and unit_price and rev:
|
| 96 |
+
q = max(qtys)
|
| 97 |
+
if not _close(q * unit_price, rev):
|
| 98 |
+
warns.append(
|
| 99 |
+
(f"receita ({_fmt(rev)}) não bate com {_fmt(q)} × {_fmt(unit_price)} = "
|
| 100 |
+
f"{_fmt(q * unit_price)}" if lang == "pt" else
|
| 101 |
+
f"revenue ({_fmt(rev)}) doesn't match {_fmt(q)} × {_fmt(unit_price)} = "
|
| 102 |
+
f"{_fmt(q * unit_price)}"))
|
| 103 |
+
|
| 104 |
+
# --- 2) cost + profit ≈ price ------------------------------------------
|
| 105 |
+
def _find(label_re):
|
| 106 |
+
m = re.search(rf"(?:{label_re})[^.]*?(?:R\$|\$)\s*([\d.,]+)", text, re.I)
|
| 107 |
+
return _num(m.group(1)) if m else None
|
| 108 |
+
|
| 109 |
+
custo = _find(r"custo|cost")
|
| 110 |
+
lucro = _find(r"lucro|margem de lucro|profit")
|
| 111 |
+
preco = _find(r"pre[çc]o|price")
|
| 112 |
+
if custo and lucro and preco and not _close(custo + lucro, preco):
|
| 113 |
+
warns.append(
|
| 114 |
+
(f"custo ({_fmt(custo)}) + lucro ({_fmt(lucro)}) = {_fmt(custo + lucro)} "
|
| 115 |
+
f"≠ preço ({_fmt(preco)})" if lang == "pt" else
|
| 116 |
+
f"cost ({_fmt(custo)}) + profit ({_fmt(lucro)}) = {_fmt(custo + lucro)} "
|
| 117 |
+
f"≠ price ({_fmt(preco)})"))
|
| 118 |
+
|
| 119 |
+
return warns
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
__all__ = ["check"]
|
pipeline/prompts.py
CHANGED
|
@@ -43,7 +43,7 @@ Responda APENAS com um objeto JSON, sem markdown, sem comentários, exatamente n
|
|
| 43 |
"decision_point":"<a pergunta concreta que o protagonista PRECISA decidir>",
|
| 44 |
"context": "<organização, setor e atores envolvidos>",
|
| 45 |
"data": ["<fato quantitativo ilustrativo, em unidade consistente, SEM citação fabricada>", "... (>=3)"],
|
| 46 |
-
"exhibits": [{"title": "<anexo opcional>", "content": "<
|
| 47 |
"alternatives": ["<argumento p/ um caminho>", "<argumento p/ outro>", "... (>=2)"],
|
| 48 |
"closing": "<revisita o dilema NO ponto de decisão — NUNCA revela a escolha>",
|
| 49 |
"references": ["<referência APA>"]
|
|
@@ -86,14 +86,19 @@ Regras invioláveis:
|
|
| 86 |
origem, use rótulo genérico e honesto ("dados internos", "estimativa da equipe"), sem
|
| 87 |
relatório/ano/instituição fabricados. Em "data_sources", afirme que os números são
|
| 88 |
ILUSTRATIVOS/FICTÍCIOS para fins de ensino.
|
| 89 |
-
5.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
Use nomes variados e plausíveis (evite repetir sobrenomes).
|
| 91 |
-
|
| 92 |
CORRETAMENTE. Confira a aritmética — o professor vai ensinar isso como gabarito.
|
| 93 |
-
|
| 94 |
-
|
| 95 |
Não copie nenhuma organização real específica.
|
| 96 |
-
|
| 97 |
|
| 98 |
|
| 99 |
_SEED_EXTRACTION = """\
|
|
@@ -223,5 +228,84 @@ def build_audit_prompt(pair_obj: dict) -> list[dict]:
|
|
| 223 |
]
|
| 224 |
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
__all__ = ["Seed", "build_generation_prompt", "build_minimal_prompt",
|
| 227 |
-
"build_seed_extraction_prompt", "build_audit_prompt"
|
|
|
|
|
|
|
|
|
| 43 |
"decision_point":"<a pergunta concreta que o protagonista PRECISA decidir>",
|
| 44 |
"context": "<organização, setor e atores envolvidos>",
|
| 45 |
"data": ["<fato quantitativo ilustrativo, em unidade consistente, SEM citação fabricada>", "... (>=3)"],
|
| 46 |
+
"exhibits": [{"title": "<anexo opcional>", "content": "<SÓ dados dados/premissas — sem coluna de projeção computada>"}],
|
| 47 |
"alternatives": ["<argumento p/ um caminho>", "<argumento p/ outro>", "... (>=2)"],
|
| 48 |
"closing": "<revisita o dilema NO ponto de decisão — NUNCA revela a escolha>",
|
| 49 |
"references": ["<referência APA>"]
|
|
|
|
| 86 |
origem, use rótulo genérico e honesto ("dados internos", "estimativa da equipe"), sem
|
| 87 |
relatório/ano/instituição fabricados. Em "data_sources", afirme que os números são
|
| 88 |
ILUSTRATIVOS/FICTÍCIOS para fins de ensino.
|
| 89 |
+
5. EXHIBITS = SÓ DADO DADO (valores atuais, premissas, elasticidades). NUNCA monte
|
| 90 |
+
tabela de PROJEÇÃO computada (proibido coluna tipo "impacto de X%", "faturamento
|
| 91 |
+
estimado", "demanda projetada" derivada de elasticidade). Se precisar mostrar uma
|
| 92 |
+
conta, faça UM exemplo trabalhado, passo a passo, na "analysis" da nota — nunca uma
|
| 93 |
+
tabela que encadeia cálculos. Sem linhas repetidas/padding.
|
| 94 |
+
6. O PROTAGONISTA (com nome) aparece JÁ no "hook"/"context" — nunca surge só no fechamento.
|
| 95 |
Use nomes variados e plausíveis (evite repetir sobrenomes).
|
| 96 |
+
7. A "analysis" da nota, se mostrar contas, usa EXATAMENTE os números do caso e os resolve
|
| 97 |
CORRETAMENTE. Confira a aritmética — o professor vai ensinar isso como gabarito.
|
| 98 |
+
8. As "discussion_questions" cobrem os objetivos — pelo menos uma por objetivo.
|
| 99 |
+
9. O caso é FICÇÃO PLAUSÍVEL e ORIGINAL: invente empresa, pessoas e números coerentes.
|
| 100 |
Não copie nenhuma organização real específica.
|
| 101 |
+
10. Escreva todo o conteúdo em {lang_name}. Tom narrativo, concreto, sem moralizar."""
|
| 102 |
|
| 103 |
|
| 104 |
_SEED_EXTRACTION = """\
|
|
|
|
| 228 |
]
|
| 229 |
|
| 230 |
|
| 231 |
+
# ---------------------------------------------------------------------------
|
| 232 |
+
# Code-sandbox numeric auditor (teacher writes Python; code does the arithmetic).
|
| 233 |
+
# Two rounds: (1) write a script that recomputes derived numbers from the stated
|
| 234 |
+
# inputs → execute in a tiny arithmetic-only sandbox → (2) rewrite the JSON to match.
|
| 235 |
+
# ---------------------------------------------------------------------------
|
| 236 |
+
|
| 237 |
+
_CODE_AUDIT_SYS = (
|
| 238 |
+
"Você é um editor quantitativo meticuloso. Você NUNCA faz aritmética de cabeça: "
|
| 239 |
+
"você escreve Python que recalcula os números a partir dos inputs declarados."
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
_CODE_FORMULAS = """\
|
| 243 |
+
Relações-chave (use exatamente):
|
| 244 |
+
- Elasticidade-preço e: uma variação de P% no preço gera (e*P)% na quantidade. Se o caso
|
| 245 |
+
declarar um "impacto na demanda" mas DER a elasticidade, RECALCULE o impacto da elasticidade.
|
| 246 |
+
- Receita = preço x quantidade. Um corte de X% no preço multiplica a receita por
|
| 247 |
+
(1 - X/100) * (1 + variacao_quantidade). NUNCA esqueça o fator do corte de preço.
|
| 248 |
+
- Payback (meses) = investimento_inicial / ganho_mensal, só se ganho_mensal > 0
|
| 249 |
+
(economia ou lucro extra; nunca sobre um custo que AUMENTA).
|
| 250 |
+
- Percentuais/margens/somas/totais: recalcule com precisão."""
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def build_audit_script_prompt(pair_obj: dict) -> list[dict]:
|
| 254 |
+
"""Round 1: teacher writes a Python script that recomputes the derived numbers."""
|
| 255 |
+
import json as _json
|
| 256 |
+
case_json = _json.dumps(pair_obj, ensure_ascii=False)
|
| 257 |
+
return [
|
| 258 |
+
{"role": "system", "content": _CODE_AUDIT_SYS},
|
| 259 |
+
{"role": "user", "content":
|
| 260 |
+
"Aqui está um caso de ensino em JSON. Identifique TODO número DERIVADO "
|
| 261 |
+
"(percentuais, payback, receita/demanda projetada, totais, margens) e escreva "
|
| 262 |
+
"um script Python que calcule o valor CORRETO de cada um a partir dos números "
|
| 263 |
+
"de input declarados.\n\n" + _CODE_FORMULAS + "\n\n"
|
| 264 |
+
"Defina `result` = dict {rótulo curto -> valor numérico correto}. Use SOMENTE "
|
| 265 |
+
"aritmética e números literais — sem imports, sem I/O, sem loops. Responda "
|
| 266 |
+
"APENAS com o bloco de código Python.\n\nCASO:\n" + case_json},
|
| 267 |
+
]
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def build_numeric_rewrite_prompt(pair_obj: dict, computed: dict) -> list[dict]:
|
| 271 |
+
"""Round 2: rewrite the JSON so every number matches the code-computed values."""
|
| 272 |
+
import json as _json
|
| 273 |
+
return [
|
| 274 |
+
{"role": "system", "content":
|
| 275 |
+
"Você corrige números em casos de ensino. Responde só com o JSON inteiro."},
|
| 276 |
+
{"role": "user", "content":
|
| 277 |
+
"Reescreva o JSON do caso para que TODO número fique consistente com estes "
|
| 278 |
+
"valores corretos já computados:\n" + _json.dumps(computed, ensure_ascii=False)
|
| 279 |
+
+ "\n\nMude só os números errados; preserve a prosa e a estrutura; tabela e texto "
|
| 280 |
+
"usam o MESMO valor. Responda APENAS com o JSON.\n\nCASO:\n"
|
| 281 |
+
+ _json.dumps(pair_obj, ensure_ascii=False)},
|
| 282 |
+
]
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def extract_code(text: str) -> str:
|
| 286 |
+
"""Pull the Python block out of a round-1 reply (tolerates fences/<think>)."""
|
| 287 |
+
import re
|
| 288 |
+
text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)
|
| 289 |
+
m = re.search(r"```(?:python)?\s*(.*?)```", text, flags=re.DOTALL)
|
| 290 |
+
return (m.group(1) if m else text).strip()
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def run_numeric_sandbox(code: str) -> dict:
|
| 294 |
+
"""Execute the teacher's arithmetic-only script; return its `result` dict.
|
| 295 |
+
|
| 296 |
+
Restricted: no imports and only a handful of safe builtins, so the executed
|
| 297 |
+
code can do arithmetic but nothing else.
|
| 298 |
+
"""
|
| 299 |
+
safe = {"round": round, "abs": abs, "min": min, "max": max,
|
| 300 |
+
"sum": sum, "len": len, "float": float, "int": int}
|
| 301 |
+
glb = {"__builtins__": safe}
|
| 302 |
+
loc: dict = {}
|
| 303 |
+
exec(code, glb, loc) # noqa: S102 — sandboxed arithmetic only
|
| 304 |
+
res = loc.get("result")
|
| 305 |
+
return res if isinstance(res, dict) else {}
|
| 306 |
+
|
| 307 |
+
|
| 308 |
__all__ = ["Seed", "build_generation_prompt", "build_minimal_prompt",
|
| 309 |
+
"build_seed_extraction_prompt", "build_audit_prompt",
|
| 310 |
+
"build_audit_script_prompt", "build_numeric_rewrite_prompt",
|
| 311 |
+
"extract_code", "run_numeric_sandbox"]
|
shared/i18n.py
CHANGED
|
@@ -107,6 +107,7 @@ _T = {
|
|
| 107 |
"en": "⚡ The GPU is busy or the free quota was reached — showing a sample meanwhile. Try forging again in a moment.",
|
| 108 |
"pt": "⚡ A GPU está ocupada ou a cota grátis acabou — exibindo uma amostra. Tente forjar de novo em instantes.",
|
| 109 |
},
|
|
|
|
| 110 |
"cf.disclaimer": {
|
| 111 |
"en": "Figures are illustrative/fictional — verify them before classroom use.",
|
| 112 |
"pt": "Números são ilustrativos/fictícios — confira antes de usar em aula.",
|
|
|
|
| 107 |
"en": "⚡ The GPU is busy or the free quota was reached — showing a sample meanwhile. Try forging again in a moment.",
|
| 108 |
"pt": "⚡ A GPU está ocupada ou a cota grátis acabou — exibindo uma amostra. Tente forjar de novo em instantes.",
|
| 109 |
},
|
| 110 |
+
"cf.numcheck_title": {"en": "Numbers to double-check", "pt": "Números pra conferir"},
|
| 111 |
"cf.disclaimer": {
|
| 112 |
"en": "Figures are illustrative/fictional — verify them before classroom use.",
|
| 113 |
"pt": "Números são ilustrativos/fictícios — confira antes de usar em aula.",
|