Sinccon / app /verify.py
Shaptoli's picture
Deploy Sincc.on Math Bot to Hugging Face Spaces
32af06c
Raw History Blame Contribute Delete
9.27 kB
import re
import sympy as sp
from sympy import FiniteSet, Interval, Union, Intersection, EmptySet, S, And, Or, simplify, solveset
from sympy.parsing.sympy_parser import (
parse_expr,
standard_transformations,
implicit_multiplication_application,
)
TR = standard_transformations + (implicit_multiplication_application,)
SYMPY_LOCALS = {
"oo": S.Infinity,
"Reals": S.Reals,
"EmptySet": S.EmptySet,
"Interval": Interval,
"FiniteSet": FiniteSet,
"Union": Union,
"Intersection": Intersection,
"And": And,
"Or": Or,
"sqrt": sp.sqrt,
"pi": sp.pi,
"E": sp.E,
"e": sp.E,
}
SUP_MAP = {
"⁰": "**0", "¹": "**1", "²": "**2", "³": "**3", "⁴": "**4",
"⁡": "**5", "⁢": "**6", "⁷": "**7", "⁸": "**8", "⁹": "**9",
}
SUB_MAP = str.maketrans("β‚€β‚β‚‚β‚ƒβ‚„β‚…β‚†β‚‡β‚ˆβ‚‰", "0123456789")
def _clean_math_str(s: str) -> str:
s = str(s).strip()
s = re.sub(r"^(?:javob|answer|result)\s*[:=]\s*", "", s, flags=re.IGNORECASE)
# Oxiridagi oddiy o'zbekcha birliklarni tozalash (masalan: "2 soat", "15 sm")
s = re.sub(r"\s+(?:soat|daqiqa|minut|sekund|kun|oy|yil|ta|nafar|dona|sm|cm|dm|mm|km|m|kg|gr|g|litr|l|gradus|birlik)\.?$", "", s, flags=re.IGNORECASE)
s = s.translate(SUB_MAP)
for k, v in SUP_MAP.items():
s = s.replace(k, v)
repls = {
"^": "**", "βˆ’": "-", "–": "-", "β€”": "-", "Γ—": "*", "Β·": "*", "Γ·": "/",
"Ο€": "pi", "∞": "oo", "≀": "<=", "β‰₯": ">=", "β‰ ": "!=",
}
for k, v in repls.items():
s = s.replace(k, v)
# 2√7 -> 2*sqrt(7), √x -> sqrt(x), √(...) -> sqrt(...)
s = re.sub(r"√\s*([A-Za-z0-9]+)", r" sqrt(\1)", s)
s = s.replace("√", "sqrt")
s = re.sub(r"(?<=[A-Za-z0-9\)])\s*sqrt\(", "*sqrt(", s)
return s.strip()
def _parse_expr_safe(expr_str: str):
return parse_expr(expr_str.strip(), local_dict=SYMPY_LOCALS, transformations=TR)
def _split_top_level_comma(text: str, sep_chars=(",", ";")) -> list[str]:
parts, buf, depth = [], [], 0
for ch in text:
if ch in "([{":
depth += 1
elif ch in ")]}" and depth > 0:
depth -= 1
if depth == 0 and ch in sep_chars:
parts.append("".join(buf).strip())
buf = []
else:
buf.append(ch)
if buf:
parts.append("".join(buf).strip())
return parts
def _parse_interval_notation(piece: str):
p = piece.strip()
if len(p) < 5 or p[0] not in "([" or p[-1] not in ")]":
return None
if any(op in p for op in ("<", ">", "=")):
return None
inner_parts = _split_top_level_comma(p[1:-1], sep_chars=(";", ","))
if len(inner_parts) != 2:
return None
left = _parse_expr_safe(inner_parts[0])
right = _parse_expr_safe(inner_parts[1])
return Interval(left, right, left_open=(p[0] == "("), right_open=(p[-1] == ")"))
def _single_rel_to_set(rel_str: str):
# Chained inequality e.g. -3 < a <= 5
ops_pattern = r"(<=|>=|<|>)"
tokens = re.split(ops_pattern, rel_str)
if len(tokens) == 3:
lhs = _parse_expr_safe(tokens[0])
op = tokens[1]
rhs = _parse_expr_safe(tokens[2])
rel_map = {
"<": lhs < rhs,
"<=": lhs <= rhs,
">": lhs > rhs,
">=": lhs >= rhs,
}
rel = rel_map[op]
syms = sorted(rel.free_symbols, key=lambda x: str(x))
if len(syms) != 1:
return None
return solveset(rel, syms[0], S.Reals)
if len(tokens) > 3 and len(tokens) % 2 == 1:
acc = S.Reals
sym = None
for i in range(0, len(tokens) - 2, 2):
sub_set = _single_rel_to_set(f"{tokens[i]} {tokens[i+1]} {tokens[i+2]}")
if sub_set is None:
return None
acc = Intersection(acc, sub_set)
return acc
return None
def _parse_as_set(raw: str):
s = _clean_math_str(raw)
if "∈" in s:
s = s.split("∈", 1)[1].strip()
elif re.match(r"^[A-Za-z]\d*\s+in\s+", s):
s = re.sub(r"^[A-Za-z]\d*\s+in\s+", "", s, count=1).strip()
# Replace set union symbols cleanly
s = s.replace("βˆͺ", " | ")
# Direct SymPy object syntax like Interval.open(...), Union(...), And(...), Or(...)
if any(k in s for k in ("Interval", "Union", "Intersection", "EmptySet", "FiniteSet", "Reals", "And(", "Or(")):
try:
obj = parse_expr(s, local_dict=SYMPY_LOCALS)
if isinstance(obj, sp.Set):
return obj
if isinstance(obj, (sp.Boolean, sp.Relational)):
syms = sorted(obj.free_symbols, key=lambda x: str(x))
if len(syms) == 1:
return solveset(obj, syms[0], S.Reals)
return obj.as_set()
except Exception:
pass
# Handle union separators: 'yoki', 'or', '|' (outside parentheses)
union_parts = re.split(r"\s+(?:yoki|or)\s+|\s*\|\s*", s, flags=re.IGNORECASE)
if len(union_parts) > 1:
sets = []
for up in union_parts:
sub = _parse_as_set(up)
if sub is None:
return None
sets.append(sub)
res = S.EmptySet
for st in sets:
res = Union(res, st)
return res
# Handle intersection separators: 'va', 'and', '&'
inter_parts = re.split(r"\s+(?:va|and)\s+|\s*&\s*", s, flags=re.IGNORECASE)
if len(inter_parts) > 1:
res = S.Reals
for ip in inter_parts:
sub = _parse_as_set(ip.strip("() ") if ip.strip().startswith("(") and ip.strip().endswith(")") and any(op in ip for op in ("<", ">")) else ip)
if sub is None:
return None
res = Intersection(res, sub)
return res
s_unwrapped = s.strip()
if s_unwrapped.startswith("(") and s_unwrapped.endswith(")") and any(op in s_unwrapped for op in ("<", ">")):
s_unwrapped = s_unwrapped[1:-1].strip()
iv = _parse_interval_notation(s_unwrapped)
if iv is not None:
return iv
if any(op in s_unwrapped for op in ("<=", ">=", "<", ">")):
rel_set = _single_rel_to_set(s_unwrapped)
if rel_set is not None:
return rel_set
return None
def _looks_like_set_or_ineq(s: str) -> bool:
low = str(s).lower()
if any(k in low for k in ("<", ">", "≀", "β‰₯", "∈", "interval", "union", "emptyset", "reals", "βˆͺ", "oo", "∞", "and(", "or(")):
return True
cleaned = s.strip()
if len(cleaned) >= 5 and cleaned[0] in "([" and cleaned[-1] in ")]" and ("," in cleaned or ";" in cleaned):
if cleaned[0] == "[" and cleaned[-1] == "]":
# Distinguish root list [2, 3] vs interval only when infinity or ; or mixed brackets present
return ";" in cleaned or "oo" in low or "∞" in low
return True
return False
def _norm(s: str):
s = _clean_math_str(s)
if any(sep in s.lower() for sep in [" va ", " or ", " yoki ", ";"]) or re.search(r"\b[a-z]\d*\s*=", s.lower()):
cleaned = re.sub(r"\b[a-z]\d*\s*=\s*", "", s, flags=re.IGNORECASE)
parts = re.split(r"\s*(?:va|or|yoki|;|,)\s*", cleaned, flags=re.IGNORECASE)
vals = set()
for p in parts:
p = p.strip().strip("[](){}")
if p:
vals.add(simplify(_parse_expr_safe(p)))
if vals:
return vals
v = _parse_expr_safe(s)
if isinstance(v, (list, tuple, set, FiniteSet)):
return {simplify(x) for x in v}
return simplify(v)
def _sets_equal(s1: sp.Set, s2: sp.Set) -> bool:
if s1 == s2:
return True
try:
d1 = s1 - s2
d2 = s2 - s1
if bool(d1.is_empty) and bool(d2.is_empty):
return True
except Exception:
pass
try:
if isinstance(s1, Interval) and isinstance(s2, Interval):
return (
s1.left_open == s2.left_open
and s1.right_open == s2.right_open
and simplify(s1.start - s2.start) == 0
and simplify(s1.end - s2.end) == 0
)
except Exception:
pass
return False
def same_answer(a: str, b: str) -> bool:
if a is None or b is None:
return False
sa = str(a).strip().lower().replace(" ", "")
sb = str(b).strip().lower().replace(" ", "")
if sa and sa == sb:
return True
if _looks_like_set_or_ineq(str(a)) or _looks_like_set_or_ineq(str(b)):
try:
set_a = _parse_as_set(str(a))
set_b = _parse_as_set(str(b))
if set_a is not None and set_b is not None:
return _sets_equal(set_a, set_b)
except Exception:
pass
try:
x, y = _norm(str(a)), _norm(str(b))
if isinstance(x, set) and isinstance(y, set):
return x == y
if isinstance(x, set) and len(x) == 1 and not isinstance(y, set):
return simplify(next(iter(x)) - y) == 0
if isinstance(y, set) and len(y) == 1 and not isinstance(x, set):
return simplify(x - next(iter(y))) == 0
if isinstance(x, set) or isinstance(y, set):
return False
return simplify(x - y) == 0
except Exception:
return False