feat(training): 完善安全培训题库与考试交互
修复 PDF 导入判断和填空题解析,支持文本题判分、回顾改答及安全培训三级流程校验。
This commit is contained in:
1 parent
ec4ed9b67d
commit
e62e4961d4
19 files changed
+721
-48
No files matched your search
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from io import BytesIO
|
||||
import re
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
from openpyxl import Workbook
|
||||
@@ -158,6 +159,40 @@ def _normalize_safety_progress(value: Any, safety_stage: str) -> dict[str, Any]:
|
||||
return normalized
|
||||
|
||||
|
||||
def _is_safety_learning_complete(safety_progress: dict[str, Any], training_type: str) -> bool:
|
||||
"""
|
||||
按已发布安全培训配置校验三级资料是否均已完成。
|
||||
|
||||
用途:安全培训请求进入考试或结算阶段时,服务端不能信任前端阶段字段,必须以每项配置资料的完成记录为准。
|
||||
参数约束:仅安全培训生效;未配置资料的级别视为无须学习,所有已配置资料必须在 resource_progress 中标记 completed=True。
|
||||
"""
|
||||
if training_type != "safety":
|
||||
return True
|
||||
published = get_published_config("safety")
|
||||
learning_resources = [
|
||||
resource for resource in (published or {}).get("resources") or []
|
||||
if resource.get("resource_type") != "inline_questions"
|
||||
and resource.get("training_level") in SAFETY_LEVEL_KEYS
|
||||
]
|
||||
resource_progress = safety_progress.get("resource_progress") or {}
|
||||
return all(
|
||||
isinstance(resource_progress.get(str(resource.get("id"))), dict)
|
||||
and bool(resource_progress[str(resource["id"])].get("completed"))
|
||||
for resource in learning_resources
|
||||
)
|
||||
|
||||
|
||||
def _assert_safety_exam_prerequisites(stage: str, safety_progress: dict[str, Any], training_type: str) -> None:
|
||||
"""
|
||||
拦截未完成三级学习的安全培训考试与结算请求。
|
||||
|
||||
用途:当客户端尝试保存 exam/result 阶段时阻止绕过学习流程,确保考试状态只能在三级资料完成后产生。
|
||||
参数约束:仅 stage 为 exam 或 result 且 training_type 为 safety 时校验失败并抛出统一 ValidationError。
|
||||
"""
|
||||
if training_type == "safety" and stage in {"exam", "result"} and not _is_safety_learning_complete(safety_progress, training_type):
|
||||
raise ValidationError("Complete all company, department, and team safety training materials before starting or submitting the exam")
|
||||
|
||||
|
||||
def _parse_iso_date(value: Any) -> Optional[date]:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
@@ -184,7 +219,9 @@ def _normalize_answer_details(value: Any) -> list[dict]:
|
||||
{
|
||||
"question_id": str(item.get("question_id") or item.get("questionId") or ""),
|
||||
"selected_option_id": str(item.get("selected_option_id") or item.get("selectedOptionId") or ""),
|
||||
"answer_text": str(item.get("answer_text") or item.get("answerText") or ""),
|
||||
"correct": bool(item.get("correct", False)),
|
||||
"score_ratio": float(item.get("score_ratio") or item.get("scoreRatio") or 0),
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
@@ -217,8 +254,36 @@ def _normalize_question_bank(value: Any) -> list[dict[str, Any]]:
|
||||
prompt = str(raw.get("prompt") or "").strip()
|
||||
answer = str(raw.get("answer") or "").strip()
|
||||
question_id = str(raw.get("id") or "").strip() or f"q{index + 1}"
|
||||
if not prompt or not answer:
|
||||
question_type = str(raw.get("type") or "single").strip().lower()
|
||||
question_type = {
|
||||
"choice": "single",
|
||||
"select": "single",
|
||||
"bool": "boolean",
|
||||
"judgment": "boolean",
|
||||
"judge": "boolean",
|
||||
"判断": "boolean",
|
||||
"判断题": "boolean",
|
||||
"3": "boolean",
|
||||
"blank": "fill",
|
||||
"fill_blank": "fill",
|
||||
"qa": "essay",
|
||||
"question_answer": "essay",
|
||||
"short_answer": "essay",
|
||||
"问答": "essay",
|
||||
"问答题": "essay",
|
||||
"简答": "essay",
|
||||
"简答题": "essay",
|
||||
"4": "essay",
|
||||
}.get(question_type, question_type)
|
||||
if question_type not in {"single", "boolean", "fill", "essay"} or not prompt:
|
||||
continue
|
||||
if question_type in {"single", "boolean"} and not answer:
|
||||
continue
|
||||
try:
|
||||
score_ratio = float(raw.get("score_ratio") or raw.get("scoreRatio") or 1)
|
||||
except (TypeError, ValueError):
|
||||
score_ratio = 1.0
|
||||
score_ratio = max(0.0, score_ratio)
|
||||
|
||||
options: list[dict[str, str]] = []
|
||||
raw_options = raw.get("options")
|
||||
@@ -244,9 +309,10 @@ def _normalize_question_bank(value: Any) -> list[dict[str, Any]]:
|
||||
normalized.append(
|
||||
{
|
||||
"id": question_id,
|
||||
"type": "boolean" if str(raw.get("type") or "").strip() == "boolean" else "single",
|
||||
"type": question_type,
|
||||
"prompt": prompt,
|
||||
"answer": answer,
|
||||
"score_ratio": score_ratio,
|
||||
"options": options,
|
||||
"explanation": str(raw.get("explanation") or "").strip(),
|
||||
}
|
||||
@@ -302,6 +368,19 @@ def _resolve_training_runtime_config(agent_id: Any, training_type: str) -> tuple
|
||||
return pass_score, question_bank
|
||||
|
||||
|
||||
def _normalize_text_answer(value: Any) -> str:
|
||||
"""
|
||||
规范文本题答案以进行无格式差异的自动判定。
|
||||
|
||||
用途:填空和问答题有标准答案时忽略空白与大小写,避免录入格式造成误判。
|
||||
Args:
|
||||
value: 学员作答或题库标准答案。
|
||||
Returns:
|
||||
删除全部空白并转换为小写后的文本。
|
||||
"""
|
||||
return re.sub(r"[\s\u3000、,,;;。..!!??::()()【】\[\]{}\"'“”‘’\-—_]+", "", str(value or "")).casefold()
|
||||
|
||||
|
||||
def _grade_answer_details(answer_details: list[dict], question_bank: list[dict[str, Any]], pass_score: int) -> tuple[list[dict], int, bool]:
|
||||
"""
|
||||
基于后端题库对答题记录重新判卷。
|
||||
@@ -318,27 +397,44 @@ def _grade_answer_details(answer_details: list[dict], question_bank: list[dict[s
|
||||
|
||||
question_lookup = {str(item["id"]): item for item in question_bank}
|
||||
normalized: list[dict] = []
|
||||
correct_count = 0
|
||||
total_score_ratio = sum(float(question.get("score_ratio") or 0) for question in question_bank)
|
||||
earned_score_ratio = 0.0
|
||||
for index, item in enumerate(answer_details):
|
||||
question_id = str(item.get("question_id") or item.get("questionId") or "").strip()
|
||||
selected_option_id = str(item.get("selected_option_id") or item.get("selectedOptionId") or "").strip()
|
||||
answer_text = str(item.get("answer_text") or item.get("answerText") or "")
|
||||
if not question_id:
|
||||
raise ValidationError("answer_details item must include question_id", details={"field": "answer_details", "index": index})
|
||||
question = question_lookup.get(question_id)
|
||||
if not question:
|
||||
raise ValidationError("answer_details question_id is invalid", details={"field": "answer_details", "index": index, "question_id": question_id})
|
||||
is_correct = selected_option_id == str(question["answer"])
|
||||
if is_correct:
|
||||
correct_count += 1
|
||||
question_type = str(question["type"])
|
||||
if question_type in {"fill", "essay"}:
|
||||
normalized_answer = _normalize_text_answer(answer_text)
|
||||
normalized_standard_answer = _normalize_text_answer(question["answer"])
|
||||
if normalized_standard_answer:
|
||||
earned_ratio = 1.0 if normalized_answer == normalized_standard_answer else 0.0
|
||||
elif not normalized_answer:
|
||||
earned_ratio = 0.0
|
||||
else:
|
||||
earned_ratio = 1.0 if len(answer_text.strip()) > 20 else 0.8
|
||||
is_correct = earned_ratio == 1.0
|
||||
else:
|
||||
earned_ratio = 1.0 if selected_option_id == str(question["answer"]) else 0.0
|
||||
is_correct = bool(earned_ratio)
|
||||
question_score_ratio = float(question.get("score_ratio") or 0)
|
||||
earned_score_ratio += question_score_ratio * earned_ratio
|
||||
normalized.append(
|
||||
{
|
||||
"question_id": question_id,
|
||||
"selected_option_id": selected_option_id,
|
||||
"answer_text": answer_text,
|
||||
"correct": is_correct,
|
||||
"score_ratio": earned_ratio,
|
||||
}
|
||||
)
|
||||
|
||||
score = round((correct_count / len(question_bank)) * 100) if question_bank else 0
|
||||
score = round((earned_score_ratio / total_score_ratio) * 100) if total_score_ratio > 0 else 0
|
||||
return normalized, score, score >= pass_score
|
||||
|
||||
|
||||
@@ -441,6 +537,7 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
|
||||
payload.get("safety_progress") or payload.get("safetyProgress"),
|
||||
safety_stage,
|
||||
)
|
||||
_assert_safety_exam_prerequisites(stage, safety_progress, training_type)
|
||||
|
||||
record = get_user_training_record(user.id, training_type)
|
||||
if not record:
|
||||
|
||||
Reference in new issue
Block a user