Learners submit answers to one published placement set; the API scores auto-gradable questions, maps percent to CEFR, and updates knowledge_level. Co-authored-by: Cursor <cursoragent@cursor.com>
406 lines
12 KiB
Go
406 lines
12 KiB
Go
package domain
|
||
|
||
import (
|
||
"fmt"
|
||
"sort"
|
||
"strings"
|
||
)
|
||
|
||
// CEFR placement levels returned by the initial assessment.
|
||
var InitialAssessmentCEFRLevels = []string{"A1", "A2", "B1", "B2", "C1", "C2"}
|
||
|
||
// DefaultInitialAssessmentThresholds are seeded when the table is empty / on first install.
|
||
func DefaultInitialAssessmentThresholds() []InitialAssessmentLevelThreshold {
|
||
return []InitialAssessmentLevelThreshold{
|
||
{Level: "A1", MinPercent: 0, DisplayOrder: 1},
|
||
{Level: "A2", MinPercent: 17, DisplayOrder: 2},
|
||
{Level: "B1", MinPercent: 34, DisplayOrder: 3},
|
||
{Level: "B2", MinPercent: 51, DisplayOrder: 4},
|
||
{Level: "C1", MinPercent: 68, DisplayOrder: 5},
|
||
{Level: "C2", MinPercent: 85, DisplayOrder: 6},
|
||
}
|
||
}
|
||
|
||
type InitialAssessmentLevelThreshold struct {
|
||
Level string `json:"level"`
|
||
MinPercent int `json:"min_percent"`
|
||
DisplayOrder int `json:"display_order"`
|
||
}
|
||
|
||
type PlacementAnswerInput struct {
|
||
QuestionID int64 `json:"question_id"`
|
||
SelectedOptionIDs []int64 `json:"selected_option_ids,omitempty"`
|
||
TextAnswer *string `json:"text_answer,omitempty"`
|
||
DynamicAnswers []PlacementDynamicAnswerInput `json:"dynamic_answers,omitempty"`
|
||
}
|
||
|
||
type PlacementDynamicAnswerInput struct {
|
||
ElementID string `json:"element_id"`
|
||
SelectedOptionIDs []string `json:"selected_option_ids,omitempty"`
|
||
TextAnswer *string `json:"text_answer,omitempty"`
|
||
}
|
||
|
||
type PlacementQuestionResult struct {
|
||
QuestionID int64 `json:"question_id"`
|
||
QuestionType string `json:"question_type"`
|
||
Gradable bool `json:"gradable"`
|
||
Correct bool `json:"correct"`
|
||
PointsEarned int32 `json:"points_earned"`
|
||
PointsMax int32 `json:"points_max"`
|
||
Skipped bool `json:"skipped"`
|
||
}
|
||
|
||
type PlacementAssessmentResult struct {
|
||
QuestionSetID int64 `json:"question_set_id"`
|
||
ScorePercent float64 `json:"score_percent"`
|
||
Level string `json:"level"`
|
||
PointsEarned int32 `json:"points_earned"`
|
||
PointsMax int32 `json:"points_max"`
|
||
GradableQuestions int `json:"gradable_questions"`
|
||
CorrectQuestions int `json:"correct_questions"`
|
||
SkippedUngradableQuestions int `json:"skipped_ungradable_questions"`
|
||
Questions []PlacementQuestionResult `json:"questions"`
|
||
KnowledgeLevel string `json:"knowledge_level"`
|
||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||
}
|
||
|
||
func NormalizeCEFRLevel(level string) (string, error) {
|
||
normalized := strings.ToUpper(strings.TrimSpace(level))
|
||
for _, allowed := range InitialAssessmentCEFRLevels {
|
||
if normalized == allowed {
|
||
return normalized, nil
|
||
}
|
||
}
|
||
return "", fmt.Errorf("level must be one of: %s", strings.Join(InitialAssessmentCEFRLevels, ", "))
|
||
}
|
||
|
||
// ValidateInitialAssessmentThresholds ensures every CEFR level is present once,
|
||
// mins are ordered ascending, and A1 starts at 0.
|
||
func ValidateInitialAssessmentThresholds(rows []InitialAssessmentLevelThreshold) error {
|
||
if len(rows) != len(InitialAssessmentCEFRLevels) {
|
||
return fmt.Errorf("expected exactly %d thresholds (A1–C2)", len(InitialAssessmentCEFRLevels))
|
||
}
|
||
|
||
byLevel := make(map[string]InitialAssessmentLevelThreshold, len(rows))
|
||
for _, row := range rows {
|
||
level, err := NormalizeCEFRLevel(row.Level)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if _, exists := byLevel[level]; exists {
|
||
return fmt.Errorf("duplicate threshold for level %s", level)
|
||
}
|
||
if row.MinPercent < 0 || row.MinPercent > 100 {
|
||
return fmt.Errorf("min_percent for %s must be between 0 and 100", level)
|
||
}
|
||
byLevel[level] = InitialAssessmentLevelThreshold{
|
||
Level: level,
|
||
MinPercent: row.MinPercent,
|
||
DisplayOrder: row.DisplayOrder,
|
||
}
|
||
}
|
||
|
||
ordered := make([]InitialAssessmentLevelThreshold, 0, len(InitialAssessmentCEFRLevels))
|
||
for i, level := range InitialAssessmentCEFRLevels {
|
||
row, ok := byLevel[level]
|
||
if !ok {
|
||
return fmt.Errorf("missing threshold for level %s", level)
|
||
}
|
||
if row.DisplayOrder <= 0 {
|
||
row.DisplayOrder = i + 1
|
||
}
|
||
ordered = append(ordered, row)
|
||
}
|
||
|
||
if ordered[0].MinPercent != 0 {
|
||
return fmt.Errorf("A1 min_percent must be 0")
|
||
}
|
||
for i := 1; i < len(ordered); i++ {
|
||
if ordered[i].MinPercent <= ordered[i-1].MinPercent {
|
||
return fmt.Errorf("%s min_percent must be greater than %s", ordered[i].Level, ordered[i-1].Level)
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// ResolveCEFRLevelFromScore returns the highest level whose min_percent <= scorePercent.
|
||
func ResolveCEFRLevelFromScore(scorePercent float64, thresholds []InitialAssessmentLevelThreshold) (string, error) {
|
||
if len(thresholds) == 0 {
|
||
thresholds = DefaultInitialAssessmentThresholds()
|
||
}
|
||
if err := ValidateInitialAssessmentThresholds(thresholds); err != nil {
|
||
// tolerate legacy/unsorted rows by sorting and filling defaults for missing
|
||
thresholds = mergeThresholdDefaults(thresholds)
|
||
if err := ValidateInitialAssessmentThresholds(thresholds); err != nil {
|
||
return "", err
|
||
}
|
||
}
|
||
|
||
sorted := append([]InitialAssessmentLevelThreshold(nil), thresholds...)
|
||
sort.Slice(sorted, func(i, j int) bool {
|
||
return sorted[i].MinPercent < sorted[j].MinPercent
|
||
})
|
||
|
||
level := sorted[0].Level
|
||
for _, row := range sorted {
|
||
if scorePercent+1e-9 >= float64(row.MinPercent) {
|
||
level = row.Level
|
||
}
|
||
}
|
||
return level, nil
|
||
}
|
||
|
||
func mergeThresholdDefaults(rows []InitialAssessmentLevelThreshold) []InitialAssessmentLevelThreshold {
|
||
byLevel := make(map[string]InitialAssessmentLevelThreshold)
|
||
for _, d := range DefaultInitialAssessmentThresholds() {
|
||
byLevel[d.Level] = d
|
||
}
|
||
for _, row := range rows {
|
||
level, err := NormalizeCEFRLevel(row.Level)
|
||
if err != nil {
|
||
continue
|
||
}
|
||
row.Level = level
|
||
byLevel[level] = row
|
||
}
|
||
out := make([]InitialAssessmentLevelThreshold, 0, len(InitialAssessmentCEFRLevels))
|
||
for i, level := range InitialAssessmentCEFRLevels {
|
||
row := byLevel[level]
|
||
if row.DisplayOrder <= 0 {
|
||
row.DisplayOrder = i + 1
|
||
}
|
||
out = append(out, row)
|
||
}
|
||
return out
|
||
}
|
||
|
||
// GradePlacementAnswers scores published placement questions against submitted answers.
|
||
// Auto-gradable: MCQ, TRUE_FALSE, SHORT_ANSWER, and DYNAMIC multiple-choice / option slots.
|
||
// AUDIO and other dynamic kinds are skipped (not counted in score denominator).
|
||
func GradePlacementAnswers(
|
||
questions []QuestionWithDetails,
|
||
answers []PlacementAnswerInput,
|
||
) PlacementAssessmentResult {
|
||
byID := make(map[int64]PlacementAnswerInput, len(answers))
|
||
for _, a := range answers {
|
||
byID[a.QuestionID] = a
|
||
}
|
||
|
||
result := PlacementAssessmentResult{
|
||
Questions: make([]PlacementQuestionResult, 0, len(questions)),
|
||
}
|
||
|
||
for _, q := range questions {
|
||
points := q.Points
|
||
if points <= 0 {
|
||
points = 1
|
||
}
|
||
qr := PlacementQuestionResult{
|
||
QuestionID: q.ID,
|
||
QuestionType: q.QuestionType,
|
||
PointsMax: points,
|
||
}
|
||
ans, answered := byID[q.ID]
|
||
|
||
gradable, correct := gradeOnePlacementQuestion(q, ans, answered)
|
||
qr.Gradable = gradable
|
||
if !gradable {
|
||
qr.Skipped = true
|
||
result.SkippedUngradableQuestions++
|
||
result.Questions = append(result.Questions, qr)
|
||
continue
|
||
}
|
||
|
||
result.GradableQuestions++
|
||
result.PointsMax += points
|
||
qr.Correct = correct
|
||
if correct {
|
||
qr.PointsEarned = points
|
||
result.PointsEarned += points
|
||
result.CorrectQuestions++
|
||
}
|
||
if !answered {
|
||
qr.Skipped = true
|
||
}
|
||
result.Questions = append(result.Questions, qr)
|
||
}
|
||
|
||
if result.PointsMax > 0 {
|
||
result.ScorePercent = (float64(result.PointsEarned) / float64(result.PointsMax)) * 100
|
||
}
|
||
return result
|
||
}
|
||
|
||
func gradeOnePlacementQuestion(q QuestionWithDetails, ans PlacementAnswerInput, answered bool) (gradable bool, correct bool) {
|
||
qType := strings.ToUpper(strings.TrimSpace(q.QuestionType))
|
||
switch qType {
|
||
case "MCQ", "TRUE_FALSE":
|
||
return true, answered && gradeSelectedOptionIDs(q.Options, ans.SelectedOptionIDs)
|
||
case "SHORT_ANSWER":
|
||
text := ""
|
||
if ans.TextAnswer != nil {
|
||
text = *ans.TextAnswer
|
||
}
|
||
return true, answered && gradeShortAnswer(q.ShortAnswers, text)
|
||
case "DYNAMIC":
|
||
return gradeDynamicPlacementQuestion(q, ans, answered)
|
||
default:
|
||
// AUDIO and unknown types are not auto-graded in v1.
|
||
return false, false
|
||
}
|
||
}
|
||
|
||
func gradeSelectedOptionIDs(options []QuestionOption, selected []int64) bool {
|
||
correctIDs := make(map[int64]struct{})
|
||
for _, opt := range options {
|
||
if opt.IsCorrect {
|
||
correctIDs[opt.ID] = struct{}{}
|
||
}
|
||
}
|
||
if len(correctIDs) == 0 {
|
||
return false
|
||
}
|
||
if len(selected) != len(correctIDs) {
|
||
return false
|
||
}
|
||
seen := make(map[int64]struct{}, len(selected))
|
||
for _, id := range selected {
|
||
if _, ok := correctIDs[id]; !ok {
|
||
return false
|
||
}
|
||
seen[id] = struct{}{}
|
||
}
|
||
return len(seen) == len(correctIDs)
|
||
}
|
||
|
||
func gradeShortAnswer(acceptable []QuestionShortAnswer, given string) bool {
|
||
given = strings.TrimSpace(given)
|
||
if given == "" || len(acceptable) == 0 {
|
||
return false
|
||
}
|
||
for _, sa := range acceptable {
|
||
want := strings.TrimSpace(sa.AcceptableAnswer)
|
||
match := strings.ToUpper(strings.TrimSpace(sa.MatchType))
|
||
switch match {
|
||
case string(MatchTypeContains):
|
||
if strings.Contains(strings.ToLower(given), strings.ToLower(want)) {
|
||
return true
|
||
}
|
||
case string(MatchTypeCaseInsensitive), "":
|
||
if strings.EqualFold(given, want) {
|
||
return true
|
||
}
|
||
default: // EXACT
|
||
if given == want {
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func gradeDynamicPlacementQuestion(q QuestionWithDetails, ans PlacementAnswerInput, answered bool) (gradable bool, correct bool) {
|
||
if q.DynamicPayload == nil {
|
||
return false, false
|
||
}
|
||
|
||
type slotSpec struct {
|
||
kind string
|
||
correct []string
|
||
short []string
|
||
match string
|
||
}
|
||
|
||
slots := make(map[string]slotSpec)
|
||
collect := func(els []DynamicElementInstance) {
|
||
for _, el := range els {
|
||
id := strings.TrimSpace(el.ID)
|
||
kind := strings.TrimSpace(el.Kind)
|
||
if id == "" {
|
||
continue
|
||
}
|
||
if isMultipleChoiceComponentKind(kind) {
|
||
correctOpts := extractCorrectDynamicOptionIDs(el.Value)
|
||
if len(correctOpts) == 0 {
|
||
continue
|
||
}
|
||
slots[id] = slotSpec{kind: kind, correct: correctOpts}
|
||
}
|
||
}
|
||
}
|
||
collect(q.DynamicPayload.Stimulus)
|
||
collect(q.DynamicPayload.Response)
|
||
|
||
if len(slots) == 0 {
|
||
return false, false
|
||
}
|
||
|
||
if !answered {
|
||
return true, false
|
||
}
|
||
|
||
byElement := make(map[string]PlacementDynamicAnswerInput, len(ans.DynamicAnswers))
|
||
for _, da := range ans.DynamicAnswers {
|
||
byElement[strings.TrimSpace(da.ElementID)] = da
|
||
}
|
||
|
||
for id, spec := range slots {
|
||
da, ok := byElement[id]
|
||
if !ok {
|
||
return true, false
|
||
}
|
||
if isMultipleChoiceComponentKind(spec.kind) {
|
||
if !sameStringSet(spec.correct, da.SelectedOptionIDs) {
|
||
return true, false
|
||
}
|
||
}
|
||
}
|
||
return true, true
|
||
}
|
||
|
||
func extractCorrectDynamicOptionIDs(value interface{}) []string {
|
||
m, ok := value.(map[string]interface{})
|
||
if !ok {
|
||
return nil
|
||
}
|
||
rawOpts, ok := m["options"].([]interface{})
|
||
if !ok {
|
||
return nil
|
||
}
|
||
var out []string
|
||
for _, o := range rawOpts {
|
||
om, ok := o.(map[string]interface{})
|
||
if !ok {
|
||
continue
|
||
}
|
||
if c, _ := om["is_correct"].(bool); !c {
|
||
continue
|
||
}
|
||
id, _ := om["id"].(string)
|
||
id = strings.TrimSpace(id)
|
||
if id != "" {
|
||
out = append(out, id)
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
func sameStringSet(want, got []string) bool {
|
||
if len(want) != len(got) {
|
||
return false
|
||
}
|
||
set := make(map[string]struct{}, len(want))
|
||
for _, w := range want {
|
||
set[strings.TrimSpace(w)] = struct{}{}
|
||
}
|
||
if len(set) != len(want) {
|
||
return false
|
||
}
|
||
for _, g := range got {
|
||
if _, ok := set[strings.TrimSpace(g)]; !ok {
|
||
return false
|
||
}
|
||
}
|
||
return true
|
||
}
|