feat(training): 完善安全培训题库与考试交互
修复 PDF 导入判断和填空题解析,支持文本题判分、回顾改答及安全培训三级流程校验。
This commit is contained in:
1 parent
ec4ed9b67d
commit
e62e4961d4
19 files changed
+721
-48
No files matched your search
@@ -27,11 +27,16 @@ from edkb_system.skills import loader_pdf, ocr
|
||||
_QUESTION_START_PATTERN = re.compile(r'^\s*(\d{1,3})\s*[\.\、\.\)]\s*(.+?)\s*$')
|
||||
_OPTION_PATTERN = re.compile(r'([A-D])\s*[\.\、\.\)\::]\s*')
|
||||
_INLINE_ANSWER_PATTERN = re.compile(r'答案\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
|
||||
_PARENTHESIZED_ANSWER_PATTERN = re.compile(r'[\((]\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)\s*[\))]', re.IGNORECASE)
|
||||
_INLINE_EXPLANATION_PATTERN = re.compile(r'解析\s*[::]?\s*(.+)$', re.IGNORECASE)
|
||||
_ANSWER_PAIR_PATTERN = re.compile(r'(?:^|(?<=[\s,,;;]))(\d{1,3})\s*[\.\、\.\)]?\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
|
||||
_SECTION_HEADING_PATTERN = re.compile(r'^[一二三四五六七八九十]+[\.\、\.\)]\s*[^\n]*题')
|
||||
_FILL_SECTION_PATTERN = re.compile(r'填空(?:题)?|填\s*空')
|
||||
_ESSAY_SECTION_PATTERN = re.compile(r'问答题|简答题')
|
||||
_BOOLEAN_SECTION_PATTERN = re.compile(r'判\s*断\s*题?')
|
||||
_BOOLEAN_SECTION_ANSWER_PATTERN = re.compile(r'判\s*断\s*题\s*[::]?\s*(.*)$')
|
||||
_BOOLEAN_PROMPT_HINT_PATTERN = re.compile(r'正确还是错误|对还是错|判断题|[\((]\s*[\))]|是否')
|
||||
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s+(.+)$')
|
||||
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s*[、,,.::]?\s*(.+)$')
|
||||
_BOOLEAN_TOKEN_PATTERN = re.compile(r'正确|错误|对|错|T|F|V|X|√|×', re.IGNORECASE)
|
||||
|
||||
|
||||
@@ -145,7 +150,7 @@ def _is_answer_sheet_line(line: str) -> bool:
|
||||
if range_match:
|
||||
token_matches = _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3))
|
||||
expected_count = int(range_match.group(2)) - int(range_match.group(1)) + 1
|
||||
if len(token_matches) >= max(expected_count - 1, 2):
|
||||
if token_matches:
|
||||
return True
|
||||
matches = list(_ANSWER_PAIR_PATTERN.finditer(normalized_line))
|
||||
return len(matches) >= 2
|
||||
@@ -176,6 +181,20 @@ def _extract_answer_sequence(lines: list[str]) -> list[str]:
|
||||
return answers
|
||||
|
||||
|
||||
def _extract_section_answer_sequence(lines: list[str], section_pattern: re.Pattern[str]) -> list[str]:
|
||||
"""提取带题型标题的答案行,支持“判断题:1-10、√ ×”这类分节答案表。"""
|
||||
answers: list[str] = []
|
||||
for line in lines:
|
||||
if not section_pattern.search(line) or not _is_answer_sheet_line(line):
|
||||
continue
|
||||
range_match = re.search(r'\d{1,3}\s*[-~-—至到]\s*\d{1,3}\s*[、,,.::]?\s*(.*)$', line)
|
||||
token_text = range_match.group(1) if range_match else line
|
||||
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(token_text):
|
||||
answer = _normalize_answer_token(raw_token)
|
||||
if answer:
|
||||
answers.append(answer)
|
||||
return answers
|
||||
|
||||
def _extract_answer_map(lines: list[str]) -> dict[int, str]:
|
||||
"""
|
||||
从“参考答案”区域提取题号与答案映射。
|
||||
@@ -196,24 +215,119 @@ def _extract_answer_map(lines: list[str]) -> dict[int, str]:
|
||||
return answer_map
|
||||
|
||||
|
||||
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
|
||||
blocks: list[tuple[int, str]] = []
|
||||
def _section_type_for_line(line: str) -> str | None:
|
||||
if _FILL_SECTION_PATTERN.search(line):
|
||||
return 'fill'
|
||||
if _ESSAY_SECTION_PATTERN.search(line):
|
||||
return 'essay'
|
||||
if _BOOLEAN_SECTION_PATTERN.search(line):
|
||||
return 'boolean'
|
||||
if re.search(r'选择题|单选题', line):
|
||||
return 'single'
|
||||
return None
|
||||
|
||||
|
||||
def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
|
||||
"""提取 PDF 后半段按小节重复出现的填空标准答案,避免把答案行当作新题目。"""
|
||||
occurrences: dict[str, int] = {}
|
||||
active_type: str | None = None
|
||||
answers: dict[str, list[str]] = {'fill': []}
|
||||
in_answer_sheet = False
|
||||
for line in lines:
|
||||
if _is_answer_section_heading(line):
|
||||
in_answer_sheet = True
|
||||
active_type = None
|
||||
continue
|
||||
section_type = _section_type_for_line(line)
|
||||
if section_type:
|
||||
occurrences[section_type] = occurrences.get(section_type, 0) + 1
|
||||
if occurrences[section_type] > 1:
|
||||
in_answer_sheet = True
|
||||
active_type = section_type if occurrences[section_type] > 1 or in_answer_sheet else None
|
||||
continue
|
||||
if not in_answer_sheet or active_type != 'fill':
|
||||
continue
|
||||
match = _QUESTION_START_PATTERN.match(line)
|
||||
if match:
|
||||
value = _normalize_spaces(match.group(2))
|
||||
if value:
|
||||
answers['fill'].append(value)
|
||||
return answers
|
||||
|
||||
|
||||
def _format_fill_prompt(prompt: str, standard_answer: str) -> str:
|
||||
"""把 PDF 中表示填空位置的空白转换为稳定可见的下划线。"""
|
||||
text = _normalize_spaces(prompt)
|
||||
if not standard_answer:
|
||||
return text
|
||||
answer_parts = [part for part in re.split(r'[、,,;;]+', standard_answer) if part.strip()]
|
||||
expected = max(1, len(answer_parts))
|
||||
candidates = list(re.finditer(r'(?<=[\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff、,,;;。])', text))
|
||||
if not candidates:
|
||||
return f"{text} {' '.join('______' for _ in range(expected))}"
|
||||
positions = {match.start() for match in candidates[:expected]}
|
||||
result: list[str] = []
|
||||
last = 0
|
||||
for match in candidates:
|
||||
result.append(text[last:match.start()])
|
||||
result.append(' ______ ' if match.start() in positions else ' ')
|
||||
last = match.end()
|
||||
result.append(text[last:])
|
||||
formatted = _normalize_spaces(''.join(result))
|
||||
missing_count = expected - formatted.count('______')
|
||||
if missing_count > 0:
|
||||
# PDF 文本抽取会丢失部分空白字符;补足占位符,确保学员能看到与标准答案数量一致的填空位置。
|
||||
formatted = f"{formatted} {' '.join('______' for _ in range(missing_count))}"
|
||||
return formatted
|
||||
|
||||
|
||||
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str, str | None]]:
|
||||
"""
|
||||
按题号及所属小节切分题目块。
|
||||
|
||||
用途:保留“填空题”“判断题”“问答题”小节语义,避免无选项题被当作解析失败而丢弃。
|
||||
参数约束:仅识别明确的题目小节;未命中时返回 None,后续继续按单选/判断规则判别。
|
||||
"""
|
||||
blocks: list[tuple[int, str, str | None]] = []
|
||||
current_no: int | None = None
|
||||
current_lines: list[str] = []
|
||||
current_section_type: str | None = None
|
||||
section_occurrences: dict[str, int] = {}
|
||||
|
||||
for line in lines:
|
||||
if _SECTION_HEADING_PATTERN.match(line):
|
||||
if _is_answer_section_heading(line):
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
|
||||
current_no = None
|
||||
current_lines = []
|
||||
current_section_type = 'answer_sheet'
|
||||
continue
|
||||
section_type = _section_type_for_line(line)
|
||||
if section_type:
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
|
||||
current_no = None
|
||||
current_lines = []
|
||||
section_occurrences[section_type] = section_occurrences.get(section_type, 0) + 1
|
||||
current_section_type = section_type if section_occurrences[section_type] == 1 else f'answer_{section_type}'
|
||||
continue
|
||||
if _is_answer_section_heading(line):
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
|
||||
current_no = None
|
||||
current_lines = []
|
||||
current_section_type = 'answer_sheet'
|
||||
continue
|
||||
if current_section_type == 'answer_sheet' or (current_section_type and current_section_type.startswith('answer_')):
|
||||
continue
|
||||
if _is_answer_sheet_line(line):
|
||||
continue
|
||||
question_match = _QUESTION_START_PATTERN.match(line)
|
||||
if question_match:
|
||||
if _is_answer_sheet_line(line) and '答案' not in line:
|
||||
continue
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
|
||||
current_no = int(question_match.group(1))
|
||||
current_lines = [question_match.group(2)]
|
||||
continue
|
||||
@@ -223,12 +337,22 @@ def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
|
||||
current_lines.append(line)
|
||||
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
|
||||
return blocks
|
||||
|
||||
|
||||
def _is_answer_section_heading(line: str) -> bool:
|
||||
return bool(re.match(r'^(?:参考)?答案(?:解析|及解析)?\s*[::]?$', line))
|
||||
|
||||
|
||||
def _extract_inline_answer(block_text: str) -> str:
|
||||
match = _INLINE_ANSWER_PATTERN.search(block_text)
|
||||
"""
|
||||
从单题文本中提取内联标准答案。
|
||||
|
||||
用途:兼容“答案:B”与“(B)”两种常见试卷标注;后者需排除空括号,避免把答题留白误判为答案。
|
||||
参数约束:仅返回可标准化为单选或判断值的答案,否则返回空字符串。
|
||||
"""
|
||||
match = _INLINE_ANSWER_PATTERN.search(block_text) or _PARENTHESIZED_ANSWER_PATTERN.search(block_text)
|
||||
if not match:
|
||||
return ''
|
||||
return _normalize_answer_token(match.group(1))
|
||||
@@ -257,6 +381,25 @@ def _build_boolean_question(question_no: int, prompt: str, answer: str, explanat
|
||||
}
|
||||
|
||||
|
||||
def _build_text_question(question_no: int, prompt: str, question_type: str, explanation: str, answer: str = '') -> dict[str, Any] | None:
|
||||
"""
|
||||
构造无选项的填空或问答题。
|
||||
|
||||
用途:填空题会携带 PDF 答案区提取到的标准答案用于自动判分;问答题没有固定答案时仍按文本长度规则评分。
|
||||
参数约束:question_type 只能为 fill 或 essay;answer 仅允许来自同一 PDF 的对应填空答案。
|
||||
"""
|
||||
prompt_text = _normalize_spaces(prompt)
|
||||
if not prompt_text or question_type not in {'fill', 'essay'}:
|
||||
return None
|
||||
return {
|
||||
'id': f'q{question_no}',
|
||||
'type': question_type,
|
||||
'prompt': prompt_text,
|
||||
'answer': _normalize_spaces(answer) if question_type == 'fill' else '',
|
||||
'explanation': explanation,
|
||||
}
|
||||
|
||||
|
||||
def _build_answer_candidates(
|
||||
*,
|
||||
inline_answer: str,
|
||||
@@ -332,21 +475,59 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
|
||||
lines = _collect_candidate_lines(text)
|
||||
answer_map = _extract_answer_map(lines)
|
||||
answer_sequence = _extract_answer_sequence(lines)
|
||||
repeated_section_answers = _extract_repeated_section_answers(lines)
|
||||
question_blocks = _split_question_blocks(lines)
|
||||
question_bank: list[dict[str, Any]] = []
|
||||
skipped_questions: list[int] = []
|
||||
fill_answer_index = 0
|
||||
|
||||
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
|
||||
for index, (question_no, raw_block) in enumerate(question_blocks):
|
||||
answer_sequence_index = 0
|
||||
for question_no, raw_block, section_type in question_blocks:
|
||||
inline_answer = _extract_inline_answer(raw_block)
|
||||
explanation = _extract_inline_explanation(raw_block)
|
||||
block_text = _strip_inline_meta(raw_block)
|
||||
option_matches = list(_OPTION_PATTERN.finditer(block_text))
|
||||
consumes_answer = section_type not in {'fill', 'essay'}
|
||||
ordered_answer = answer_sequence[answer_sequence_index] if answer_sequence_index < len(answer_sequence) else ''
|
||||
if consumes_answer:
|
||||
answer_sequence_index += 1
|
||||
answer_candidates = _build_answer_candidates(
|
||||
inline_answer=inline_answer,
|
||||
mapped_answer=answer_map.get(question_no, ''),
|
||||
ordered_answer=answer_sequence[index] if index < len(answer_sequence) else '',
|
||||
ordered_answer=ordered_answer,
|
||||
)
|
||||
if section_type == 'boolean':
|
||||
for answer in answer_candidates:
|
||||
question_payload = _build_boolean_question(
|
||||
question_no=question_no,
|
||||
prompt=block_text,
|
||||
answer=answer,
|
||||
explanation=explanation,
|
||||
)
|
||||
if question_payload:
|
||||
question_payload['id'] = f'q{len(question_bank) + 1}'
|
||||
question_bank.append(question_payload)
|
||||
break
|
||||
else:
|
||||
question_payload = None
|
||||
if question_payload:
|
||||
continue
|
||||
|
||||
if section_type in {'fill', 'essay'}:
|
||||
fill_answer = (
|
||||
repeated_section_answers['fill'][fill_answer_index]
|
||||
if section_type == 'fill' and fill_answer_index < len(repeated_section_answers['fill'])
|
||||
else ''
|
||||
)
|
||||
if section_type == 'fill':
|
||||
fill_answer_index += 1
|
||||
block_text = _format_fill_prompt(block_text, fill_answer)
|
||||
question_payload = _build_text_question(question_no, block_text, section_type, explanation, fill_answer)
|
||||
if question_payload:
|
||||
question_payload['id'] = f'q{len(question_bank) + 1}'
|
||||
question_bank.append(question_payload)
|
||||
continue
|
||||
|
||||
if _looks_like_boolean_question(block_text, option_matches, answer_candidates):
|
||||
for answer in answer_candidates:
|
||||
|
||||
Reference in new issue
Block a user