feat: add math engine and puzzle services

This commit is contained in:
2026-08-09 01:52:20 +08:00
parent 6bcff55c4f
commit b99a22fc06
21 changed files with 1011 additions and 1 deletions
+1
View File
@@ -5,3 +5,4 @@ DJANGO_ALLOWED_HOSTS=localhost,127.0.0.1
DATABASE_URL=mysql://hulumath:hulumath@127.0.0.1:3307/hulumath DATABASE_URL=mysql://hulumath:hulumath@127.0.0.1:3307/hulumath
REDIS_URL=redis://localhost:6379/0 REDIS_URL=redis://localhost:6379/0
CORS_ALLOWED_ORIGINS=http://localhost:3000 CORS_ALLOWED_ORIGINS=http://localhost:3000
CALCULATOR_RATE=30/minute
+1
View File
@@ -14,6 +14,7 @@ CORS_ALLOWED_ORIGINS=https://math.example.com
CSRF_TRUSTED_ORIGINS=https://math.example.com CSRF_TRUSTED_ORIGINS=https://math.example.com
API_ANON_RATE=120/minute API_ANON_RATE=120/minute
API_USER_RATE=600/minute API_USER_RATE=600/minute
CALCULATOR_RATE=30/minute
SECURE_HSTS_SECONDS=31536000 SECURE_HSTS_SECONDS=31536000
# 仅供部署脚本直接访问 127.0.0.1:8000 时设置 Host 头。 # 仅供部署脚本直接访问 127.0.0.1:8000 时设置 Host 头。
+1
View File
@@ -18,5 +18,6 @@ test:
.venv/bin/python -m pytest -q .venv/bin/python -m pytest -q
check: check:
.venv/bin/ruff check backend scripts
cd backend && ../.venv/bin/python manage.py check cd backend && ../.venv/bin/python manage.py check
cd backend && ../.venv/bin/python manage.py makemigrations --check --dry-run cd backend && ../.venv/bin/python manage.py makemigrations --check --dry-run
+2
View File
@@ -38,6 +38,7 @@ INSTALLED_APPS = [
"latex_lab", "latex_lab",
"content", "content",
"engagement", "engagement",
"toolbox",
"common", "common",
] ]
@@ -142,6 +143,7 @@ REST_FRAMEWORK = {
"DEFAULT_THROTTLE_RATES": { "DEFAULT_THROTTLE_RATES": {
"anon": os.getenv("API_ANON_RATE", "120/minute"), "anon": os.getenv("API_ANON_RATE", "120/minute"),
"user": os.getenv("API_USER_RATE", "600/minute"), "user": os.getenv("API_USER_RATE", "600/minute"),
"calculator": os.getenv("CALCULATOR_RATE", "30/minute"),
}, },
} }
+1
View File
@@ -17,4 +17,5 @@ urlpatterns = [
path("api/v1/latex/", include("latex_lab.urls")), path("api/v1/latex/", include("latex_lab.urls")),
path("api/v1/content/", include("content.urls")), path("api/v1/content/", include("content.urls")),
path("api/v1/progression/", include("progression.urls")), path("api/v1/progression/", include("progression.urls")),
path("api/v1/toolbox/", include("toolbox.urls")),
] ]
+19
View File
@@ -7,6 +7,7 @@ from .models import (
ContestAttempt, ContestAttempt,
ContestQuestion, ContestQuestion,
LeaderboardSnapshot, LeaderboardSnapshot,
MathGameAttempt,
Question, Question,
QuestionVersion, QuestionVersion,
RatingHistory, RatingHistory,
@@ -64,3 +65,21 @@ admin.site.register(ContestAnswer)
admin.site.register(RealtimeMatch) admin.site.register(RealtimeMatch)
admin.site.register(RatingHistory) admin.site.register(RatingHistory)
admin.site.register(LeaderboardSnapshot) admin.site.register(LeaderboardSnapshot)
@admin.register(MathGameAttempt)
class MathGameAttemptAdmin(admin.ModelAdmin):
list_display = (
"id",
"user",
"kind",
"difficulty",
"status",
"score",
"hints_used",
"started_at",
)
list_filter = ("kind", "difficulty", "status")
search_fields = ("user__username", "user__nickname")
readonly_fields = ("puzzle", "solution", "submission", "started_at", "submitted_at")
ordering = ("-started_at",)
+220
View File
@@ -0,0 +1,220 @@
import ast
import secrets
from collections import Counter
from fractions import Fraction
from django.db import transaction
from django.utils import timezone
from rest_framework.exceptions import ValidationError
from .models import MathGameAttempt
SUDOKU_PUZZLES = {
MathGameAttempt.Difficulty.EASY: [
(
"530070000600195000098000060800060003400803001700020006060000280000419005000080079",
"534678912672195348198342567859761423426853791713924856961537284287419635345286179",
),
],
MathGameAttempt.Difficulty.STANDARD: [
(
"000260701680070090190004500820100040004602900050003028009300074040050036703018000",
"435269781682571493197834562826195347374682915951743628519326874248957136763418259",
),
],
MathGameAttempt.Difficulty.HARD: [
(
"000000010400000000020000000000050407008000300001090000300400200050100000000806000",
"693784512487512936125963874932651487568247391741398625319475268856129743274836159",
),
],
}
TWENTY_FOUR_PUZZLES = {
MathGameAttempt.Difficulty.EASY: [(3, 3, 8, 8), (1, 3, 4, 6), (4, 4, 10, 10)],
MathGameAttempt.Difficulty.STANDARD: [(2, 3, 4, 9), (3, 5, 7, 13), (4, 7, 8, 8)],
MathGameAttempt.Difficulty.HARD: [(1, 5, 5, 5), (3, 3, 7, 7), (5, 5, 7, 11)],
}
def _grid_from_text(value):
return [[int(value[row * 9 + column]) for column in range(9)] for row in range(9)]
def game_payload(attempt):
return {
"attempt_id": attempt.id,
"kind": attempt.kind,
"difficulty": attempt.difficulty,
"status": attempt.status,
"puzzle": attempt.puzzle,
"score": attempt.score,
"duration_ms": attempt.duration_ms,
"hints_used": attempt.hints_used,
"started_at": attempt.started_at,
}
def start_game(user, kind, difficulty):
if kind not in MathGameAttempt.Kind.values:
raise ValidationError({"kind": "不支持的数学玩法"})
if difficulty not in MathGameAttempt.Difficulty.values:
raise ValidationError({"difficulty": "不支持的难度"})
if kind == MathGameAttempt.Kind.SUDOKU:
puzzle_text, solution_text = secrets.choice(SUDOKU_PUZZLES[difficulty])
puzzle = {"grid": _grid_from_text(puzzle_text), "hints": []}
solution = {"grid": _grid_from_text(solution_text)}
else:
numbers = list(secrets.choice(TWENTY_FOUR_PUZZLES[difficulty]))
secrets.SystemRandom().shuffle(numbers)
puzzle = {"numbers": numbers}
solution = {"target": 24}
attempt = MathGameAttempt.objects.create(
user=user,
kind=kind,
difficulty=difficulty,
puzzle=puzzle,
solution=solution,
)
return game_payload(attempt)
def _validate_twenty_four_expression(source, numbers):
source = str(source or "").strip()
if not source or len(source) > 120:
raise ValidationError({"expression": "请输入不超过 120 个字符的表达式"})
try:
tree = ast.parse(source, mode="eval")
except SyntaxError as exc:
raise ValidationError({"expression": "表达式语法无效"}) from exc
used = []
def evaluate(node):
if isinstance(node, ast.Constant) and isinstance(node.value, int):
used.append(node.value)
return Fraction(node.value)
if isinstance(node, ast.BinOp) and isinstance(
node.op,
(ast.Add, ast.Sub, ast.Mult, ast.Div),
):
left = evaluate(node.left)
right = evaluate(node.right)
if isinstance(node.op, ast.Add):
return left + right
if isinstance(node.op, ast.Sub):
return left - right
if isinstance(node.op, ast.Mult):
return left * right
if right == 0:
raise ValidationError({"expression": "不能除以零"})
return left / right
raise ValidationError({"expression": "只允许题目数字、括号和 + - * /"})
result = evaluate(tree.body)
if Counter(used) != Counter(numbers):
raise ValidationError({"expression": "必须且只能使用题目给出的四个数字各一次"})
if result != 24:
raise ValidationError({"expression": f"当前结果是 {result},还没有得到 24"})
return source
def _validate_sudoku_grid(raw_grid, puzzle, solution):
if (
not isinstance(raw_grid, list)
or len(raw_grid) != 9
or any(not isinstance(row, list) or len(row) != 9 for row in raw_grid)
):
raise ValidationError({"grid": "数独答案必须是 9×9 网格"})
try:
grid = [[int(value) for value in row] for row in raw_grid]
except (TypeError, ValueError) as exc:
raise ValidationError({"grid": "每个格子必须填写 1 到 9"}) from exc
if any(value < 1 or value > 9 for row in grid for value in row):
raise ValidationError({"grid": "每个格子必须填写 1 到 9"})
givens = puzzle["grid"]
for row in range(9):
for column in range(9):
if givens[row][column] and grid[row][column] != givens[row][column]:
raise ValidationError({"grid": "不能修改题目给出的数字"})
if grid != solution["grid"]:
raise ValidationError({"grid": "答案尚未满足全部行、列和九宫格"})
return grid
@transaction.atomic
def submit_game(user, attempt_id, submission, submission_key):
attempt = MathGameAttempt.objects.select_for_update().get(id=attempt_id, user=user)
if attempt.status == MathGameAttempt.Status.COMPLETED:
if submission_key and attempt.submission_key == submission_key:
return game_payload(attempt)
raise ValidationError("这局游戏已经完成")
if not submission_key:
raise ValidationError({"Idempotency-Key": "提交必须提供幂等键"})
if attempt.kind == MathGameAttempt.Kind.SUDOKU:
normalized = {
"grid": _validate_sudoku_grid(
submission.get("grid"),
attempt.puzzle,
attempt.solution,
)
}
else:
normalized = {
"expression": _validate_twenty_four_expression(
submission.get("expression"),
attempt.puzzle["numbers"],
)
}
now = timezone.now()
duration_ms = max(0, int((now - attempt.started_at).total_seconds() * 1000))
base_score = 1800 if attempt.kind == MathGameAttempt.Kind.SUDOKU else 1000
time_penalty = duration_ms // (2000 if attempt.kind == MathGameAttempt.Kind.SUDOKU else 1000)
attempt.submission = normalized
attempt.status = MathGameAttempt.Status.COMPLETED
attempt.duration_ms = duration_ms
attempt.score = max(100, base_score - time_penalty - attempt.hints_used * 150)
attempt.submission_key = submission_key
attempt.submitted_at = now
attempt.save(
update_fields=[
"submission",
"status",
"duration_ms",
"score",
"submission_key",
"submitted_at",
]
)
return game_payload(attempt)
@transaction.atomic
def request_sudoku_hint(user, attempt_id):
attempt = MathGameAttempt.objects.select_for_update().get(id=attempt_id, user=user)
if attempt.kind != MathGameAttempt.Kind.SUDOKU:
raise ValidationError("只有数独支持提示")
if attempt.status != MathGameAttempt.Status.ACTIVE:
raise ValidationError("这局游戏已经结束")
hints = list(attempt.puzzle.get("hints", []))
if len(hints) >= 3:
raise ValidationError("每局最多使用 3 次提示")
candidates = [
(row, column)
for row in range(9)
for column in range(9)
if attempt.puzzle["grid"][row][column] == 0
and not any(item["row"] == row and item["column"] == column for item in hints)
]
row, column = secrets.choice(candidates)
hint = {
"row": row,
"column": column,
"value": attempt.solution["grid"][row][column],
}
hints.append(hint)
attempt.puzzle = {**attempt.puzzle, "hints": hints}
attempt.hints_used = len(hints)
attempt.save(update_fields=["puzzle", "hints_used"])
return {**hint, "hints_used": attempt.hints_used}
@@ -0,0 +1,44 @@
# Generated by Django 4.2.23 on 2026-08-08 17:26
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contest', '0002_realtimematch_matchmaking_lookup_idx'),
]
operations = [
migrations.CreateModel(
name='MathGameAttempt',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('kind', models.CharField(choices=[('sudoku', '数独'), ('twenty_four', '24 点')], max_length=20)),
('difficulty', models.CharField(choices=[('easy', '入门'), ('standard', '标准'), ('hard', '进阶')], default='standard', max_length=16)),
('puzzle', models.JSONField(default=dict)),
('solution', models.JSONField(default=dict)),
('submission', models.JSONField(blank=True, default=dict)),
('status', models.CharField(choices=[('active', '进行中'), ('completed', '已完成'), ('failed', '未通过')], default='active', max_length=16)),
('score', models.PositiveIntegerField(default=0)),
('duration_ms', models.PositiveIntegerField(default=0)),
('hints_used', models.PositiveSmallIntegerField(default=0)),
('submission_key', models.CharField(blank=True, max_length=80, null=True)),
('started_at', models.DateTimeField(auto_now_add=True)),
('submitted_at', models.DateTimeField(blank=True, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='math_game_attempts', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-started_at'],
'indexes': [models.Index(fields=['kind', 'status', '-score', 'duration_ms'], name='math_game_ranking_idx')],
},
),
migrations.AddConstraint(
model_name='mathgameattempt',
constraint=models.UniqueConstraint(fields=('user', 'submission_key'), name='unique_user_math_game_submission'),
),
]
+54
View File
@@ -192,3 +192,57 @@ class CheatFlag(models.Model):
evidence = models.JSONField(default=dict) evidence = models.JSONField(default=dict)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN) status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN)
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
class MathGameAttempt(models.Model):
class Kind(models.TextChoices):
SUDOKU = "sudoku", "数独"
TWENTY_FOUR = "twenty_four", "24 点"
class Difficulty(models.TextChoices):
EASY = "easy", "入门"
STANDARD = "standard", "标准"
HARD = "hard", "进阶"
class Status(models.TextChoices):
ACTIVE = "active", "进行中"
COMPLETED = "completed", "已完成"
FAILED = "failed", "未通过"
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="math_game_attempts",
)
kind = models.CharField(max_length=20, choices=Kind.choices)
difficulty = models.CharField(
max_length=16,
choices=Difficulty.choices,
default=Difficulty.STANDARD,
)
puzzle = models.JSONField(default=dict)
solution = models.JSONField(default=dict)
submission = models.JSONField(default=dict, blank=True)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE)
score = models.PositiveIntegerField(default=0)
duration_ms = models.PositiveIntegerField(default=0)
hints_used = models.PositiveSmallIntegerField(default=0)
submission_key = models.CharField(max_length=80, null=True, blank=True)
started_at = models.DateTimeField(auto_now_add=True)
submitted_at = models.DateTimeField(null=True, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=("user", "submission_key"),
name="unique_user_math_game_submission",
)
]
indexes = [
models.Index(
fields=("kind", "status", "-score", "duration_ms"),
name="math_game_ranking_idx",
)
]
ordering = ["-started_at"]
+121
View File
@@ -0,0 +1,121 @@
import pytest
from rest_framework.exceptions import ValidationError
from accounts.models import User
from contest.game_services import (
SUDOKU_PUZZLES,
request_sudoku_hint,
start_game,
submit_game,
)
from contest.models import MathGameAttempt
@pytest.fixture
def game_user(db):
return User.objects.create_user(
username="game_user",
password="StrongPass_2026",
nickname="游戏玩家",
)
@pytest.mark.django_db
def test_twenty_four_服务端校验数字使用与幂等提交(game_user):
attempt = MathGameAttempt.objects.create(
user=game_user,
kind=MathGameAttempt.Kind.TWENTY_FOUR,
puzzle={"numbers": [1, 3, 4, 6]},
solution={"target": 24},
)
result = submit_game(
game_user,
attempt.id,
{"expression": "6 / (1 - 3 / 4)"},
"game-submit-1",
)
replay = submit_game(
game_user,
attempt.id,
{"expression": "1 + 3 + 4 + 6"},
"game-submit-1",
)
assert result["status"] == MathGameAttempt.Status.COMPLETED
assert result["score"] >= 100
assert replay["score"] == result["score"]
@pytest.mark.django_db
def test_twenty_four_拒绝额外数字和非四则表达式(game_user):
attempt = MathGameAttempt.objects.create(
user=game_user,
kind=MathGameAttempt.Kind.TWENTY_FOUR,
puzzle={"numbers": [1, 3, 4, 6]},
solution={"target": 24},
)
with pytest.raises(ValidationError, match="四个数字"):
submit_game(
game_user,
attempt.id,
{"expression": "6 / (1 - 3 / 4) + 24 - 24"},
"invalid-extra-number",
)
with pytest.raises(ValidationError, match="只允许"):
submit_game(
game_user,
attempt.id,
{"expression": "pow(2, 3) * 3"},
"invalid-function",
)
@pytest.mark.django_db
def test_sudoku_提示受限并由服务端校验完整答案(game_user):
payload = start_game(
game_user,
MathGameAttempt.Kind.SUDOKU,
MathGameAttempt.Difficulty.EASY,
)
attempt = MathGameAttempt.objects.get(id=payload["attempt_id"])
hint = request_sudoku_hint(game_user, attempt.id)
solution_text = SUDOKU_PUZZLES[MathGameAttempt.Difficulty.EASY][0][1]
solution = [
[int(solution_text[row * 9 + column]) for column in range(9)]
for row in range(9)
]
result = submit_game(
game_user,
attempt.id,
{"grid": solution},
"sudoku-submit-1",
)
assert hint["value"] == solution[hint["row"]][hint["column"]]
assert result["status"] == MathGameAttempt.Status.COMPLETED
assert result["hints_used"] == 1
@pytest.mark.django_db
def test_math_game_api_目录公开但开局需要登录(client, game_user):
catalog = client.get("/api/v1/contests/games/")
anonymous_start = client.post(
"/api/v1/contests/games/twenty_four/start/",
{"difficulty": "easy"},
content_type="application/json",
)
client.force_login(game_user)
authenticated_start = client.post(
"/api/v1/contests/games/twenty_four/start/",
{"difficulty": "easy"},
content_type="application/json",
)
assert catalog.status_code == 200
assert {item["kind"] for item in catalog.json()} == {"sudoku", "twenty_four"}
assert anonymous_start.status_code in {401, 403}
assert authenticated_start.status_code == 201
assert "solution" not in authenticated_start.json()
+18
View File
@@ -7,6 +7,11 @@ from .views import (
LeaderboardView, LeaderboardView,
MatchmakingView, MatchmakingView,
MatchStateView, MatchStateView,
MathGameCatalogView,
MathGameHistoryView,
MathGameStartView,
MathGameSubmitView,
SudokuHintView,
) )
urlpatterns = [ urlpatterns = [
@@ -16,4 +21,17 @@ urlpatterns = [
path("<slug:slug>/leaderboard/", LeaderboardView.as_view(), name="leaderboard"), path("<slug:slug>/leaderboard/", LeaderboardView.as_view(), name="leaderboard"),
path("attempts/<uuid:attempt_id>/submit/", AttemptSubmitView.as_view(), name="attempt-submit"), path("attempts/<uuid:attempt_id>/submit/", AttemptSubmitView.as_view(), name="attempt-submit"),
path("matches/<uuid:match_id>/", MatchStateView.as_view(), name="match-state"), path("matches/<uuid:match_id>/", MatchStateView.as_view(), name="match-state"),
path("games/", MathGameCatalogView.as_view(), name="math-game-catalog"),
path("games/history/", MathGameHistoryView.as_view(), name="math-game-history"),
path("games/<str:kind>/start/", MathGameStartView.as_view(), name="math-game-start"),
path(
"games/attempts/<uuid:attempt_id>/submit/",
MathGameSubmitView.as_view(),
name="math-game-submit",
),
path(
"games/attempts/<uuid:attempt_id>/hint/",
SudokuHintView.as_view(),
name="sudoku-hint",
),
] ]
+58 -1
View File
@@ -3,7 +3,8 @@ from rest_framework import permissions, status
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.views import APIView from rest_framework.views import APIView
from .models import Contest, ContestAttempt, RealtimeMatch from .game_services import game_payload, request_sudoku_hint, start_game, submit_game
from .models import Contest, ContestAttempt, MathGameAttempt, RealtimeMatch
from .services import ( from .services import (
find_match, find_match,
match_payload, match_payload,
@@ -98,3 +99,59 @@ class LeaderboardView(APIView):
for index, attempt in enumerate(attempts, start=1) for index, attempt in enumerate(attempts, start=1)
] ]
) )
class MathGameCatalogView(APIView):
permission_classes = [permissions.AllowAny]
def get(self, request):
return Response(
[
{
"kind": MathGameAttempt.Kind.TWENTY_FOUR,
"title": "24 点",
"summary": "四个数字各用一次,只用四则运算得到 24。",
"ability": "connection",
"estimated_minutes": 3,
},
{
"kind": MathGameAttempt.Kind.SUDOKU,
"title": "数独",
"summary": "在行、列和九宫格约束中完成 9×9 数字推理。",
"ability": "detection",
"estimated_minutes": 8,
},
]
)
class MathGameStartView(APIView):
def post(self, request, kind):
payload = start_game(
request.user,
kind,
request.data.get("difficulty", MathGameAttempt.Difficulty.STANDARD),
)
return Response(payload, status=status.HTTP_201_CREATED)
class MathGameSubmitView(APIView):
def post(self, request, attempt_id):
payload = submit_game(
request.user,
attempt_id,
request.data,
request.headers.get("Idempotency-Key"),
)
return Response(payload)
class SudokuHintView(APIView):
def post(self, request, attempt_id):
return Response(request_sudoku_hint(request.user, attempt_id))
class MathGameHistoryView(APIView):
def get(self, request):
attempts = MathGameAttempt.objects.filter(user=request.user)[:20]
return Response([game_payload(attempt) for attempt in attempts])
+12
View File
@@ -40,5 +40,17 @@ class ProgressionProfileView(APIView):
} }
for item in request.user.cards.select_related("card") for item in request.user.cards.select_related("card")
], ],
"recent_games": [
{
"kind": attempt.kind,
"label": attempt.get_kind_display(),
"difficulty": attempt.get_difficulty_display(),
"status": attempt.status,
"score": attempt.score,
"duration_ms": attempt.duration_ms,
"started_at": attempt.started_at,
}
for attempt in request.user.math_game_attempts.all()[:10]
],
} }
) )
+1
View File
@@ -0,0 +1 @@
+7
View File
@@ -0,0 +1,7 @@
from django.apps import AppConfig
class ToolboxConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "toolbox"
verbose_name = "数学工具箱"
+333
View File
@@ -0,0 +1,333 @@
import ast
import math
from statistics import mean, median, pstdev, pvariance
import sympy as sp
from rest_framework.exceptions import ValidationError
MAX_EXPRESSION_LENGTH = 500
MAX_AST_NODES = 120
MAX_MATRIX_CELLS = 36
SYMBOLS = {name: sp.Symbol(name, real=True) for name in ("x", "y", "z", "a", "b", "t", "n")}
CONSTANTS = {"pi": sp.pi, "e": sp.E, "E": sp.E, "i": sp.I, "I": sp.I}
FUNCTIONS = {
"sin": sp.sin,
"cos": sp.cos,
"tan": sp.tan,
"asin": sp.asin,
"acos": sp.acos,
"atan": sp.atan,
"sinh": sp.sinh,
"cosh": sp.cosh,
"tanh": sp.tanh,
"sqrt": sp.sqrt,
"exp": sp.exp,
"ln": sp.log,
"log": sp.log,
"abs": sp.Abs,
"factorial": sp.factorial,
"binomial": sp.binomial,
"gcd": sp.gcd,
"lcm": sp.lcm,
"floor": sp.floor,
"ceil": sp.ceiling,
}
FUNCTION_ARITY = {
"factorial": (1, 1),
"binomial": (2, 2),
"gcd": (2, 2),
"lcm": (2, 2),
}
UNIT_FACTORS = {
"mm": ("length", 0.001),
"cm": ("length", 0.01),
"m": ("length", 1.0),
"km": ("length", 1000.0),
"in": ("length", 0.0254),
"ft": ("length", 0.3048),
"g": ("mass", 0.001),
"kg": ("mass", 1.0),
"lb": ("mass", 0.45359237),
"s": ("time", 1.0),
"min": ("time", 60.0),
"h": ("time", 3600.0),
"rad": ("angle", 1.0),
"deg": ("angle", math.pi / 180),
}
class SafeExpressionParser:
def __init__(self, source):
source = str(source or "").strip()
if not source:
raise ValidationError({"expression": "请输入数学表达式"})
if len(source) > MAX_EXPRESSION_LENGTH:
raise ValidationError({"expression": "表达式不能超过 500 个字符"})
source = (
source.replace("π", "pi")
.replace("×", "*")
.replace("÷", "/")
.replace("", "-")
.replace("^", "**")
)
try:
self.tree = ast.parse(source, mode="eval")
except SyntaxError as exc:
raise ValidationError({"expression": "表达式语法无效"}) from exc
if sum(1 for _ in ast.walk(self.tree)) > MAX_AST_NODES:
raise ValidationError({"expression": "表达式过于复杂"})
def parse(self):
return self._convert(self.tree.body)
def _convert(self, node):
if isinstance(node, ast.Constant):
if isinstance(node.value, bool) or not isinstance(node.value, (int, float)):
raise ValidationError({"expression": "只允许数值常量"})
if isinstance(node.value, int) and len(str(abs(node.value))) > 50:
raise ValidationError({"expression": "整数位数过多"})
return sp.Integer(node.value) if isinstance(node.value, int) else sp.Float(node.value)
if isinstance(node, ast.Name):
if node.id in SYMBOLS:
return SYMBOLS[node.id]
if node.id in CONSTANTS:
return CONSTANTS[node.id]
raise ValidationError({"expression": f"不支持变量或常量 {node.id}"})
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
value = self._convert(node.operand)
return value if isinstance(node.op, ast.UAdd) else -value
if isinstance(node, ast.BinOp):
left = self._convert(node.left)
right = self._convert(node.right)
if isinstance(node.op, ast.Add):
return left + right
if isinstance(node.op, ast.Sub):
return left - right
if isinstance(node.op, ast.Mult):
return left * right
if isinstance(node.op, ast.Div):
return left / right
if isinstance(node.op, ast.Mod):
return sp.Mod(left, right)
if isinstance(node.op, ast.Pow):
if right.is_number and abs(float(right)) > 100:
raise ValidationError({"expression": "幂指数绝对值不能超过 100"})
return left**right
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
function = FUNCTIONS.get(node.func.id)
if function is None:
raise ValidationError({"expression": f"不支持函数 {node.func.id}"})
minimum, maximum = FUNCTION_ARITY.get(node.func.id, (1, 2))
if node.keywords or not minimum <= len(node.args) <= maximum:
raise ValidationError({"expression": f"{node.func.id} 的参数数量无效"})
try:
return function(*(self._convert(item) for item in node.args))
except (TypeError, ValueError) as exc:
raise ValidationError({"expression": f"{node.func.id} 的参数无效"}) from exc
raise ValidationError({"expression": "表达式包含不允许的语法"})
def parse_expression(source):
return SafeExpressionParser(source).parse()
def parse_equation(source):
source = str(source or "")
if source.count("=") > 1:
raise ValidationError({"expression": "方程只能包含一个等号"})
if "=" not in source:
return parse_expression(source)
left, right = source.split("=", 1)
return sp.Eq(parse_expression(left), parse_expression(right))
def serialize_math(value):
if isinstance(value, dict):
return {
str(serialize_math(key)["exact"]): serialize_math(item)
for key, item in value.items()
}
if isinstance(value, (list, tuple)):
return [serialize_math(item) for item in value]
if isinstance(value, sp.MatrixBase):
return {
"exact": str(value.tolist()),
"decimal": str(value.evalf(12).tolist()),
"latex": sp.latex(value),
}
exact = str(value)
try:
decimal = str(sp.N(value, 12))
except Exception:
decimal = exact
return {"exact": exact, "decimal": decimal, "latex": sp.latex(value)}
def parse_matrix(source):
rows = [row.strip() for row in str(source or "").split(";") if row.strip()]
if not rows:
raise ValidationError({"expression": "矩阵格式示例:1,2;3,4"})
parsed = [[parse_expression(cell.strip()) for cell in row.split(",")] for row in rows]
width = len(parsed[0])
if width == 0 or any(len(row) != width for row in parsed):
raise ValidationError({"expression": "矩阵每行列数必须一致"})
if len(parsed) * width > MAX_MATRIX_CELLS:
raise ValidationError({"expression": "矩阵最多支持 36 个元素"})
return sp.Matrix(parsed)
def parse_number_list(source):
try:
values = [float(item.strip()) for item in str(source or "").split(",") if item.strip()]
except ValueError as exc:
raise ValidationError({"expression": "统计数据必须是逗号分隔的数字"}) from exc
if not 1 <= len(values) <= 500:
raise ValidationError({"expression": "统计数据数量必须在 1 到 500 之间"})
if not all(math.isfinite(item) for item in values):
raise ValidationError({"expression": "统计数据必须是有限数值"})
return values
def calculate(payload):
operation = str(payload.get("operation", "calculate"))
source = payload.get("expression", "")
variable_name = str(payload.get("variable", "x"))
variable = SYMBOLS.get(variable_name)
if variable is None:
raise ValidationError({"variable": "变量仅支持 x、y、z、a、b、t、n"})
if operation == "statistics":
values = parse_number_list(source)
result = {
"count": len(values),
"mean": mean(values),
"median": median(values),
"variance": pvariance(values),
"standard_deviation": pstdev(values),
"minimum": min(values),
"maximum": max(values),
}
return {
"operation": operation,
"result": result,
"steps": ["读取数据", "计算集中趋势", "计算离散程度"],
}
if operation == "base":
try:
from_base = int(payload.get("from_base", 10))
to_base = int(payload.get("to_base", 2))
if not 2 <= from_base <= 36 or not 2 <= to_base <= 36:
raise ValueError
number = int(str(source).strip(), from_base)
except ValueError as exc:
raise ValidationError({"expression": "进制必须为 2 到 36,且输入应合法"}) from exc
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sign = "-" if number < 0 else ""
remaining = abs(number)
converted = "0"
if remaining:
pieces = []
while remaining:
remaining, index = divmod(remaining, to_base)
pieces.append(digits[index])
converted = "".join(reversed(pieces))
return {
"operation": operation,
"result": {"exact": f"{sign}{converted}", "decimal": str(number), "latex": sign + converted},
"steps": [f"{from_base} 进制读取", f"转换为 {to_base} 进制"],
}
if operation == "unit":
try:
value = float(str(source).strip())
from_unit = str(payload.get("from_unit", "m"))
to_unit = str(payload.get("to_unit", "cm"))
source_unit = UNIT_FACTORS[from_unit]
target_unit = UNIT_FACTORS[to_unit]
if source_unit[0] != target_unit[0] or not math.isfinite(value):
raise ValueError
except (KeyError, ValueError) as exc:
raise ValidationError({"expression": "单位不兼容或数值无效"}) from exc
converted = value * source_unit[1] / target_unit[1]
return {
"operation": operation,
"result": {
"exact": f"{converted:.12g} {to_unit}",
"decimal": f"{converted:.12g}",
"latex": f"{converted:.12g}\\,{to_unit}",
},
"steps": [f"{from_unit} 换算为标准单位", f"转换为 {to_unit}"],
}
if operation.startswith("matrix_"):
matrix = parse_matrix(source)
if operation == "matrix_det":
if not matrix.is_square:
raise ValidationError({"expression": "行列式要求方阵"})
result = matrix.det()
steps = ["读取矩阵", "按行列式规则计算"]
elif operation == "matrix_inverse":
if not matrix.is_square or matrix.det() == 0:
raise ValidationError({"expression": "矩阵不可逆"})
result = matrix.inv()
steps = ["读取矩阵", "验证行列式非零", "计算逆矩阵"]
elif operation == "matrix_rref":
result = matrix.rref()[0]
steps = ["读取矩阵", "执行初等行变换", "得到行最简形"]
elif operation == "matrix_transpose":
result = matrix.T
steps = ["读取矩阵", "交换行列"]
else:
raise ValidationError({"operation": "不支持的矩阵操作"})
return {"operation": operation, "result": serialize_math(result), "steps": steps}
expression = parse_equation(source) if operation == "solve" else parse_expression(source)
steps = ["解析受限数学表达式"]
if operation == "calculate":
result = sp.simplify(expression)
steps.append("化简并保留精确值")
elif operation == "simplify":
result = sp.trigsimp(sp.cancel(expression))
steps.append("约分并进行代数/三角化简")
elif operation == "expand":
result = sp.expand(expression)
steps.append("展开乘积与幂")
elif operation == "factor":
result = sp.factor(expression)
steps.append("提取因式并分解")
elif operation == "solve":
result = sp.solve(expression, variable)
if len(result) > 50:
raise ValidationError({"expression": "解的数量过多"})
steps.extend([f"{variable_name} 为未知量", "求解方程"])
elif operation == "derivative":
order = int(payload.get("order", 1))
if not 1 <= order <= 5:
raise ValidationError({"order": "导数阶数必须在 1 到 5 之间"})
result = sp.diff(expression, variable, order)
steps.append(f"{variable_name}{order} 阶导数")
elif operation == "integral":
lower = str(payload.get("lower", "")).strip()
upper = str(payload.get("upper", "")).strip()
if lower or upper:
if not lower or not upper:
raise ValidationError({"bounds": "定积分必须同时填写上下限"})
result = sp.integrate(
expression,
(variable, parse_expression(lower), parse_expression(upper)),
)
steps.append(f"{variable_name} 计算定积分")
else:
result = sp.integrate(expression, variable)
steps.append(f"{variable_name} 计算不定积分")
elif operation == "limit":
point = parse_expression(payload.get("point", "0"))
direction = str(payload.get("direction", "+-"))
if direction not in {"+", "-", "+-"}:
raise ValidationError({"direction": "极限方向必须为 +、- 或 +-"})
result = sp.limit(expression, variable, point, dir=direction)
steps.append(f"{variable_name} 趋近 {point}")
else:
raise ValidationError({"operation": "不支持的计算类型"})
return {"operation": operation, "result": serialize_math(result), "steps": steps}
+63
View File
@@ -0,0 +1,63 @@
import pytest
from rest_framework.exceptions import ValidationError
from toolbox.engine import calculate, parse_expression
def test_calculate_精确计算与微积分():
exact = calculate({"operation": "calculate", "expression": "sqrt(2) + 1/3"})
derivative = calculate(
{"operation": "derivative", "expression": "sin(x) + x^3", "variable": "x"}
)
integral = calculate(
{
"operation": "integral",
"expression": "x^2",
"variable": "x",
"lower": "0",
"upper": "3",
}
)
assert exact["result"]["exact"] == "1/3 + sqrt(2)"
assert derivative["result"]["exact"] == "3*x**2 + cos(x)"
assert integral["result"]["exact"] == "9"
def test_calculate_方程矩阵统计与进制():
solved = calculate({"operation": "solve", "expression": "x^2 - 5*x + 6 = 0"})
determinant = calculate({"operation": "matrix_det", "expression": "1,2;3,4"})
statistics = calculate({"operation": "statistics", "expression": "1,2,3,4"})
converted = calculate(
{"operation": "base", "expression": "FF", "from_base": 16, "to_base": 2}
)
units = calculate(
{
"operation": "unit",
"expression": "1.75",
"from_unit": "m",
"to_unit": "cm",
}
)
combinations = calculate({"operation": "calculate", "expression": "binomial(10, 3)"})
assert [item["exact"] for item in solved["result"]] == ["2", "3"]
assert determinant["result"]["exact"] == "-2"
assert statistics["result"]["mean"] == 2.5
assert converted["result"]["exact"] == "11111111"
assert units["result"]["exact"] == "175 cm"
assert combinations["result"]["exact"] == "120"
@pytest.mark.parametrize(
"source",
[
"__import__('os').system('id')",
"open('/etc/passwd')",
"x.__class__",
"[x for x in range(10)]",
],
)
def test_parse_expression_拒绝非数学语法(source):
with pytest.raises(ValidationError):
parse_expression(source)
+25
View File
@@ -0,0 +1,25 @@
import pytest
@pytest.mark.django_db
def test_calculator_api_公开访问并返回精确值(client):
response = client.post(
"/api/v1/toolbox/calculate/",
{"operation": "factor", "expression": "x^2 - 1"},
content_type="application/json",
)
assert response.status_code == 200
assert response.json()["result"]["exact"] == "(x - 1)*(x + 1)"
@pytest.mark.django_db
def test_calculator_api_危险表达式返回四百(client):
response = client.post(
"/api/v1/toolbox/calculate/",
{"operation": "calculate", "expression": "__import__('os').system('id')"},
content_type="application/json",
)
assert response.status_code == 400
assert "error" in response.json()
+7
View File
@@ -0,0 +1,7 @@
from django.urls import path
from .views import CalculatorView
urlpatterns = [
path("calculate/", CalculatorView.as_view(), name="toolbox-calculate"),
]
+22
View File
@@ -0,0 +1,22 @@
from rest_framework import permissions
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.throttling import ScopedRateThrottle
from rest_framework.views import APIView
from .engine import calculate
class CalculatorView(APIView):
permission_classes = [permissions.AllowAny]
throttle_classes = [ScopedRateThrottle]
throttle_scope = "calculator"
def post(self, request):
try:
payload = calculate(request.data)
except ValidationError:
raise
except (ArithmeticError, NotImplementedError, TypeError, ValueError) as exc:
raise ValidationError({"expression": "该计算暂时无法完成,请缩小表达式范围"}) from exc
return Response(payload)
+1
View File
@@ -8,3 +8,4 @@ mysqlclient==2.2.7
whitenoise==6.7.0 whitenoise==6.7.0
gunicorn==23.0.0 gunicorn==23.0.0
uvicorn[standard]==0.30.6 uvicorn[standard]==0.30.6
sympy==1.13.3