@@ -0,0 +1,29 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from .models import (
|
||||
FormulaDocument,
|
||||
FormulaRevision,
|
||||
HandwritingRecognitionJob,
|
||||
LatexAttempt,
|
||||
LatexCourse,
|
||||
LatexExercise,
|
||||
LatexLesson,
|
||||
)
|
||||
|
||||
|
||||
class LatexLessonInline(admin.StackedInline):
|
||||
model = LatexLesson
|
||||
extra = 1
|
||||
|
||||
|
||||
@admin.register(LatexCourse)
|
||||
class LatexCourseAdmin(admin.ModelAdmin):
|
||||
list_display = ("title", "order", "is_published")
|
||||
inlines = [LatexLessonInline]
|
||||
|
||||
|
||||
admin.site.register(FormulaDocument)
|
||||
admin.site.register(FormulaRevision)
|
||||
admin.site.register(LatexExercise)
|
||||
admin.site.register(LatexAttempt)
|
||||
admin.site.register(HandwritingRecognitionJob)
|
||||
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class LatexLabConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'latex_lab'
|
||||
@@ -0,0 +1,103 @@
|
||||
# Generated by Django 4.2.23 on 2026-08-08 11:15
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='FormulaDocument',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('title', models.CharField(max_length=120)),
|
||||
('source', models.TextField(blank=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='formulas', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ['-updated_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LatexCourse',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('slug', models.SlugField(unique=True)),
|
||||
('title', models.CharField(max_length=120)),
|
||||
('description', models.TextField(blank=True)),
|
||||
('order', models.PositiveIntegerField(default=0)),
|
||||
('is_published', models.BooleanField(default=False)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LatexLesson',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('slug', models.SlugField()),
|
||||
('title', models.CharField(max_length=120)),
|
||||
('content', models.TextField()),
|
||||
('example_source', models.TextField(blank=True)),
|
||||
('order', models.PositiveIntegerField(default=0)),
|
||||
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lessons', to='latex_lab.latexcourse')),
|
||||
],
|
||||
options={
|
||||
'ordering': ['order'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LatexExercise',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('prompt', models.TextField()),
|
||||
('expected_source', models.TextField()),
|
||||
('explanation', models.TextField(blank=True)),
|
||||
('order', models.PositiveIntegerField(default=0)),
|
||||
('lesson', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='exercises', to='latex_lab.latexlesson')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LatexAttempt',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('submitted_source', models.TextField()),
|
||||
('is_correct', models.BooleanField()),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('exercise', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='latex_lab.latexexercise')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='latex_attempts', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='HandwritingRecognitionJob',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('status', models.CharField(choices=[('pending', '等待'), ('complete', '完成'), ('failed', '失败')], default='pending', max_length=16)),
|
||||
('result', models.JSONField(blank=True, default=dict)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='FormulaRevision',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('source', models.TextField()),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('document', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='revisions', to='latex_lab.formuladocument')),
|
||||
],
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='latexlesson',
|
||||
constraint=models.UniqueConstraint(fields=('course', 'slug'), name='unique_course_lesson'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,77 @@
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
|
||||
class FormulaDocument(models.Model):
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="formulas")
|
||||
title = models.CharField(max_length=120)
|
||||
source = models.TextField(blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ["-updated_at"]
|
||||
|
||||
|
||||
class FormulaRevision(models.Model):
|
||||
document = models.ForeignKey(FormulaDocument, on_delete=models.CASCADE, related_name="revisions")
|
||||
source = models.TextField()
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
|
||||
class LatexCourse(models.Model):
|
||||
slug = models.SlugField(unique=True)
|
||||
title = models.CharField(max_length=120)
|
||||
description = models.TextField(blank=True)
|
||||
order = models.PositiveIntegerField(default=0)
|
||||
is_published = models.BooleanField(default=False)
|
||||
|
||||
def __str__(self):
|
||||
return self.title
|
||||
|
||||
|
||||
class LatexLesson(models.Model):
|
||||
course = models.ForeignKey(LatexCourse, on_delete=models.CASCADE, related_name="lessons")
|
||||
slug = models.SlugField()
|
||||
title = models.CharField(max_length=120)
|
||||
content = models.TextField()
|
||||
example_source = models.TextField(blank=True)
|
||||
order = models.PositiveIntegerField(default=0)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=("course", "slug"), name="unique_course_lesson")
|
||||
]
|
||||
ordering = ["order"]
|
||||
|
||||
|
||||
class LatexExercise(models.Model):
|
||||
lesson = models.ForeignKey(LatexLesson, on_delete=models.CASCADE, related_name="exercises")
|
||||
prompt = models.TextField()
|
||||
expected_source = models.TextField()
|
||||
explanation = models.TextField(blank=True)
|
||||
order = models.PositiveIntegerField(default=0)
|
||||
|
||||
|
||||
class LatexAttempt(models.Model):
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="latex_attempts")
|
||||
exercise = models.ForeignKey(LatexExercise, on_delete=models.PROTECT)
|
||||
submitted_source = models.TextField()
|
||||
is_correct = models.BooleanField()
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
|
||||
class HandwritingRecognitionJob(models.Model):
|
||||
class Status(models.TextChoices):
|
||||
PENDING = "pending", "等待"
|
||||
COMPLETE = "complete", "完成"
|
||||
FAILED = "failed", "失败"
|
||||
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)
|
||||
result = models.JSONField(default=dict, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
@@ -0,0 +1,28 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import FormulaDocument, FormulaRevision
|
||||
|
||||
|
||||
class FormulaDocumentSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = FormulaDocument
|
||||
fields = ("id", "title", "source", "created_at", "updated_at")
|
||||
read_only_fields = ("id", "created_at", "updated_at")
|
||||
|
||||
def validate_source(self, value):
|
||||
if len(value) > 50_000:
|
||||
raise serializers.ValidationError("公式源码不能超过 50000 个字符")
|
||||
return value
|
||||
|
||||
def create(self, validated_data):
|
||||
document = FormulaDocument.objects.create(
|
||||
user=self.context["request"].user,
|
||||
**validated_data,
|
||||
)
|
||||
FormulaRevision.objects.create(document=document, source=document.source)
|
||||
return document
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
instance = super().update(instance, validated_data)
|
||||
FormulaRevision.objects.create(document=instance, source=instance.source)
|
||||
return instance
|
||||
@@ -0,0 +1,15 @@
|
||||
from latex_lab.views import ExerciseSubmitView
|
||||
|
||||
|
||||
def test_normalize_忽略公式结构外的空白():
|
||||
left = ExerciseSubmitView.normalize(r"\frac { a } { b }")
|
||||
right = ExerciseSubmitView.normalize(r"\frac{a}{b}")
|
||||
|
||||
assert left == right
|
||||
|
||||
|
||||
def test_normalize_保留_text_命令内部的语义空格():
|
||||
with_space = ExerciseSubmitView.normalize(r"\text{a b}")
|
||||
without_space = ExerciseSubmitView.normalize(r"\text{ab}")
|
||||
|
||||
assert with_space != without_space
|
||||
@@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
@@ -0,0 +1,18 @@
|
||||
from django.urls import include, path
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from .views import CourseListView, ExerciseSubmitView, FormulaDocumentViewSet
|
||||
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register("documents", FormulaDocumentViewSet, basename="formula-document")
|
||||
|
||||
urlpatterns = [
|
||||
path("", include(router.urls)),
|
||||
path("courses/", CourseListView.as_view(), name="latex-course-list"),
|
||||
path(
|
||||
"exercises/<int:exercise_id>/submit/",
|
||||
ExerciseSubmitView.as_view(),
|
||||
name="latex-exercise-submit",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,106 @@
|
||||
from django.shortcuts import get_object_or_404
|
||||
from rest_framework import permissions, status, viewsets
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from .models import LatexAttempt, LatexCourse, LatexExercise
|
||||
from .serializers import FormulaDocumentSerializer
|
||||
|
||||
|
||||
class FormulaDocumentViewSet(viewsets.ModelViewSet):
|
||||
serializer_class = FormulaDocumentSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
return self.request.user.formulas.all()
|
||||
|
||||
|
||||
class CourseListView(APIView):
|
||||
permission_classes = [permissions.AllowAny]
|
||||
|
||||
def get(self, request):
|
||||
courses = LatexCourse.objects.filter(is_published=True).prefetch_related(
|
||||
"lessons__exercises"
|
||||
)
|
||||
return Response(
|
||||
[
|
||||
{
|
||||
"slug": course.slug,
|
||||
"title": course.title,
|
||||
"description": course.description,
|
||||
"lessons": [
|
||||
{
|
||||
"slug": lesson.slug,
|
||||
"title": lesson.title,
|
||||
"content": lesson.content,
|
||||
"example_source": lesson.example_source,
|
||||
"exercise_count": lesson.exercises.count(),
|
||||
}
|
||||
for lesson in course.lessons.all()
|
||||
],
|
||||
}
|
||||
for course in courses
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class ExerciseSubmitView(APIView):
|
||||
@staticmethod
|
||||
def normalize(source):
|
||||
source = source or ""
|
||||
text_commands = (r"\text", r"\mbox", r"\textrm", r"\textsf", r"\texttt")
|
||||
normalized = []
|
||||
index = 0
|
||||
while index < len(source):
|
||||
command = next(
|
||||
(item for item in text_commands if source.startswith(item, index)),
|
||||
None,
|
||||
)
|
||||
if command is None:
|
||||
if not source[index].isspace():
|
||||
normalized.append(source[index])
|
||||
index += 1
|
||||
continue
|
||||
|
||||
command_end = index + len(command)
|
||||
group_start = command_end
|
||||
while group_start < len(source) and source[group_start].isspace():
|
||||
group_start += 1
|
||||
if group_start >= len(source) or source[group_start] != "{":
|
||||
normalized.append(command)
|
||||
index = command_end
|
||||
continue
|
||||
|
||||
depth = 0
|
||||
group_end = group_start
|
||||
while group_end < len(source):
|
||||
if source[group_end] == "{":
|
||||
depth += 1
|
||||
elif source[group_end] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
group_end += 1
|
||||
break
|
||||
group_end += 1
|
||||
normalized.append(command)
|
||||
normalized.append(source[group_start:group_end])
|
||||
index = group_end
|
||||
return "".join(normalized)
|
||||
|
||||
def post(self, request, exercise_id):
|
||||
exercise = get_object_or_404(LatexExercise, id=exercise_id)
|
||||
submitted = str(request.data.get("source", ""))[:50_000]
|
||||
is_correct = self.normalize(submitted) == self.normalize(exercise.expected_source)
|
||||
LatexAttempt.objects.create(
|
||||
user=request.user,
|
||||
exercise=exercise,
|
||||
submitted_source=submitted,
|
||||
is_correct=is_correct,
|
||||
)
|
||||
return Response(
|
||||
{
|
||||
"is_correct": is_correct,
|
||||
"expected_source": exercise.expected_source if not is_correct else None,
|
||||
"explanation": exercise.explanation,
|
||||
},
|
||||
status=status.HTTP_201_CREATED,
|
||||
)
|
||||
Reference in New Issue
Block a user