fix(training-pdf-import): 修复培训试题PDF导入判断题解析
This commit is contained in:
1 parent
3a22df736e
commit
91758ef2b4
19 files changed
+1767
-12
No files matched your search
@@ -61,3 +61,19 @@ def update_agent_permissions(id: int):
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_service.update_agent_permissions(id, user_ids)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/training-question-bank/import-pdf', methods=['POST'])
|
||||
@require_admin
|
||||
def import_training_question_bank_from_pdf(id: int):
|
||||
"""
|
||||
从已上传的培训试题 PDF 解析题库。
|
||||
|
||||
用途:给 Agent 管理表单提供“从试题 PDF 导入题库”入口,返回结构化题目供前端回填并继续人工微调。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = agent_service.import_training_question_bank_from_pdf(
|
||||
agent_id=id,
|
||||
guide_id=data.get('guide_id'),
|
||||
)
|
||||
return jsonify(payload), 200
|
||||
@@ -57,6 +57,7 @@ class AgentGuide(Base):
|
||||
file_type: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
guide_usage: Mapped[str] = mapped_column(String(50), nullable=False, default='general')
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[int] = mapped_column(Integer, default=1)
|
||||
|
||||
@@ -17,6 +17,7 @@ from app.core.config.settings import Config
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.dify import DifyService
|
||||
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
|
||||
|
||||
|
||||
def serialize_agent(agent: Agent) -> dict:
|
||||
@@ -288,3 +289,15 @@ def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
for user in users_to_remove:
|
||||
user.agents.remove(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def import_training_question_bank_from_pdf(agent_id: int, guide_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
解析指定 Agent 的培训试题 PDF,并返回结构化题库。
|
||||
|
||||
用途:当前端点击“从试题 PDF 导入”时使用;这里只做解析,不直接覆盖 Agent 配置,避免误导入后无法人工复核。
|
||||
"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
return parse_training_question_bank_from_guide(agent_id=agent_id, guide_id=guide_id)
|
||||
@@ -17,6 +17,16 @@ from app.models import AgentGuide
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
|
||||
GUIDE_USAGE_GENERAL = 'general'
|
||||
GUIDE_USAGE_TRAINING_VIDEO = 'training_video'
|
||||
GUIDE_USAGE_TRAINING_EXAM_PDF = 'training_exam_pdf'
|
||||
ALLOWED_GUIDE_USAGES = {
|
||||
GUIDE_USAGE_GENERAL,
|
||||
GUIDE_USAGE_TRAINING_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_EXAM_PDF,
|
||||
}
|
||||
|
||||
|
||||
def _infer_file_type(content_type: str | None) -> str:
|
||||
ct = str(content_type or '')
|
||||
if ct.startswith('video'):
|
||||
@@ -36,6 +46,7 @@ def serialize_guide(guide: AgentGuide) -> dict:
|
||||
'file_path': guide.file_path,
|
||||
'file_url': minio_service.get_public_url(guide.file_path),
|
||||
'file_size': guide.file_size,
|
||||
'guide_usage': guide.guide_usage,
|
||||
'remark': guide.remark,
|
||||
'sort_order': guide.sort_order,
|
||||
'status': guide.status,
|
||||
@@ -43,6 +54,23 @@ def serialize_guide(guide: AgentGuide) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _normalize_guide_usage(raw_usage: Any, *, file_type: str) -> str:
|
||||
"""
|
||||
归一化指南用途并校验与文件类型是否匹配。
|
||||
|
||||
用途:给后台上传/编辑指南时统一约束“培训视频”“培训试题 PDF”等资料用途,避免前端再靠排序或文件名猜测。
|
||||
参数约束:training_video 仅允许 video 文件;training_exam_pdf 仅允许 pdf 文件。
|
||||
"""
|
||||
usage = str(raw_usage or GUIDE_USAGE_GENERAL).strip() or GUIDE_USAGE_GENERAL
|
||||
if usage not in ALLOWED_GUIDE_USAGES:
|
||||
raise ValidationError('Invalid guide usage')
|
||||
if usage == GUIDE_USAGE_TRAINING_VIDEO and file_type != 'video':
|
||||
raise ValidationError('Training video usage requires a video file')
|
||||
if usage == GUIDE_USAGE_TRAINING_EXAM_PDF and file_type != 'pdf':
|
||||
raise ValidationError('Training exam PDF usage requires a PDF file')
|
||||
return usage
|
||||
|
||||
|
||||
def upload_guide_file(file_storage: FileStorage | None) -> dict:
|
||||
"""
|
||||
上传引导文件至 MinIO。
|
||||
@@ -80,12 +108,14 @@ def list_guides(*, agent_id: int | None = None) -> list[dict]:
|
||||
|
||||
def create_guide(data: dict[str, Any], *, created_by_id: int | None) -> dict:
|
||||
"""创建 AgentGuide 记录。"""
|
||||
file_type = str(data['file_type'])
|
||||
guide = AgentGuide(
|
||||
agent_id=data['agent_id'],
|
||||
file_name=data['file_name'],
|
||||
file_type=data['file_type'],
|
||||
file_type=file_type,
|
||||
file_path=data['file_path'],
|
||||
file_size=data.get('file_size'),
|
||||
guide_usage=_normalize_guide_usage(data.get('guide_usage'), file_type=file_type),
|
||||
remark=data.get('remark'),
|
||||
sort_order=data.get('sort_order', 0),
|
||||
status=data.get('status', 1),
|
||||
@@ -109,6 +139,8 @@ def update_guide(guide_id: int, data: dict[str, Any]) -> None:
|
||||
guide.sort_order = data['sort_order']
|
||||
if 'status' in data:
|
||||
guide.status = data['status']
|
||||
if 'guide_usage' in data:
|
||||
guide.guide_usage = _normalize_guide_usage(data.get('guide_usage'), file_type=guide.file_type)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
"""
|
||||
backend/app/services/admin/training_exam_pdf_service.py
|
||||
|
||||
用途:把员工培训试题 PDF 解析成结构化题库,供 Agent extra_config.training_config 回填。
|
||||
依赖:models.AgentGuide、minio_service、pypdf、edkb_system PDF/OCR 技能。
|
||||
逻辑:优先读取已标记为 training_exam_pdf 的指南文件,先抽取 PDF 原生文本;若文本缺失或解析失败,再回退到 OCR 识别,最终把题目、选项、答案与解析返回给管理端表单继续人工校验。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import AgentGuide
|
||||
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
|
||||
from app.services.minio_service import minio_service
|
||||
from edkb_system.contracts import Block, Context
|
||||
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)
|
||||
_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]*题')
|
||||
_BOOLEAN_PROMPT_HINT_PATTERN = re.compile(r'正确还是错误|对还是错|判断题|[\((]\s*[\))]|是否')
|
||||
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s+(.+)$')
|
||||
_BOOLEAN_TOKEN_PATTERN = re.compile(r'正确|错误|对|错|T|F|V|X|√|×', re.IGNORECASE)
|
||||
|
||||
|
||||
def _normalize_line_breaks(text: str) -> str:
|
||||
return str(text or '').replace('\r\n', '\n').replace('\r', '\n')
|
||||
|
||||
|
||||
def _normalize_spaces(text: str) -> str:
|
||||
return re.sub(r'[ \t\u3000]+', ' ', str(text or '')).strip()
|
||||
|
||||
|
||||
def _normalize_answer_token(raw_answer: str) -> str:
|
||||
answer = str(raw_answer or '').strip().upper()
|
||||
if answer in {'A', 'B', 'C', 'D'}:
|
||||
return answer.lower()
|
||||
if answer in {'正确', '对', 'T', 'V', '√', 'TRUE'}:
|
||||
return 'true'
|
||||
if answer in {'错误', '错', 'F', 'X', '×', 'FALSE'}:
|
||||
return 'false'
|
||||
return ''
|
||||
|
||||
|
||||
def _extract_pdf_text(raw_bytes: bytes) -> str:
|
||||
"""
|
||||
从 PDF 原始字节中抽取纯文本。
|
||||
|
||||
用途:为培训试题导入提供统一文本输入,避免每个管理接口重复组装 PdfReader。
|
||||
参数约束:raw_bytes 必须是 PDF 文件内容;若整份文件无可读文本,将由上层决定是否报错。
|
||||
"""
|
||||
reader = PdfReader(io.BytesIO(raw_bytes))
|
||||
page_texts: list[str] = []
|
||||
for page in reader.pages:
|
||||
text = _normalize_spaces(_normalize_line_breaks(page.extract_text() or ''))
|
||||
if text:
|
||||
page_texts.append(text)
|
||||
return '\n'.join(page_texts).strip()
|
||||
|
||||
|
||||
def _blocks_to_text(blocks: list[Block]) -> str:
|
||||
"""
|
||||
把 edkb_system 的段落/OCR 结果统一折叠成纯文本。
|
||||
|
||||
用途:扫描件 PDF 会先被 loader_pdf 切成 paragraph/image/ocr_text block,这里负责收敛成后续题库解析可消费的文本。
|
||||
参数约束:只拼接 paragraph 与 ocr_text,避免把图片元数据等噪音混入题干。
|
||||
"""
|
||||
lines: list[str] = []
|
||||
for block in blocks:
|
||||
if block.type not in {'paragraph', 'ocr_text'}:
|
||||
continue
|
||||
text = _normalize_line_breaks(block.text or '').strip()
|
||||
if not text:
|
||||
continue
|
||||
if block.type == 'ocr_text':
|
||||
if text.startswith('OCR_TEXT:'):
|
||||
text = text[len('OCR_TEXT:') :].strip()
|
||||
text = re.sub(r'(?m)^\s*-\s*', '', text).strip()
|
||||
if text:
|
||||
lines.append(text)
|
||||
return '\n'.join(lines).strip()
|
||||
|
||||
|
||||
def _extract_pdf_text_via_ocr(raw_bytes: bytes) -> tuple[str, list[str]]:
|
||||
"""
|
||||
使用仓库内置 PDF loader + OCR 管线提取扫描件文本。
|
||||
|
||||
用途:当 pypdf 拿不到可读文本,或题目结构解析失败时,回退到这条路径兼容图片型 PDF。
|
||||
参数约束:raw_bytes 必须是完整 PDF 字节;若当前环境未安装 rapidocr 相关依赖,会在 warnings 中返回原因而不是直接抛异常。
|
||||
"""
|
||||
temp_path: Path | None = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file:
|
||||
temp_file.write(raw_bytes)
|
||||
temp_path = Path(temp_file.name)
|
||||
|
||||
context = Context(file_type='pdf')
|
||||
blocks = loader_pdf.run({'file_path': str(temp_path)}, context)
|
||||
if any(block.type == 'image' for block in blocks):
|
||||
blocks = ocr.run(blocks, context)
|
||||
return _blocks_to_text(blocks), list(context.warnings)
|
||||
finally:
|
||||
if temp_path is not None:
|
||||
try:
|
||||
temp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _collect_candidate_lines(text: str) -> list[str]:
|
||||
normalized_text = _normalize_line_breaks(text)
|
||||
lines: list[str] = []
|
||||
for raw_line in normalized_text.split('\n'):
|
||||
line = _normalize_spaces(raw_line)
|
||||
if line:
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
def _is_answer_sheet_line(line: str) -> bool:
|
||||
"""
|
||||
判断当前行是否更像“答案表”而不是题干。
|
||||
|
||||
用途:很多培训试卷会在末尾给出“1.B 2.A 3.正确”这类答案表;这些行不能再被当成题目块切进去,否则会污染上一题或额外生成伪题目。
|
||||
参数约束:仅识别高置信度答案行,避免误伤正常题干。
|
||||
"""
|
||||
normalized_line = _normalize_spaces(line)
|
||||
if not normalized_line:
|
||||
return False
|
||||
if '答案' in normalized_line:
|
||||
return True
|
||||
range_match = _ANSWER_RANGE_PATTERN.match(normalized_line)
|
||||
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):
|
||||
return True
|
||||
matches = list(_ANSWER_PAIR_PATTERN.finditer(normalized_line))
|
||||
return len(matches) >= 2
|
||||
|
||||
|
||||
def _extract_answer_sequence(lines: list[str]) -> list[str]:
|
||||
"""
|
||||
按文本顺序提取整卷答案序列。
|
||||
|
||||
用途:当 PDF 内部“单选题/判断题”分别从 1 重新编号,或答案表使用整卷顺序编号时,单靠题号已无法稳定对齐,这里保留顺序型答案用于按题目出现顺序兜底匹配。
|
||||
参数约束:只从明确的答案行提取,避免把题干中的 A/B/C/D 选项误收进答案序列。
|
||||
"""
|
||||
answers: list[str] = []
|
||||
for line in lines:
|
||||
if not _is_answer_sheet_line(line):
|
||||
continue
|
||||
range_match = _ANSWER_RANGE_PATTERN.match(_normalize_spaces(line))
|
||||
if range_match:
|
||||
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3)):
|
||||
answer = _normalize_answer_token(raw_token)
|
||||
if answer:
|
||||
answers.append(answer)
|
||||
continue
|
||||
for match in _ANSWER_PAIR_PATTERN.finditer(line):
|
||||
answer = _normalize_answer_token(match.group(2))
|
||||
if answer:
|
||||
answers.append(answer)
|
||||
return answers
|
||||
|
||||
|
||||
def _extract_answer_map(lines: list[str]) -> dict[int, str]:
|
||||
"""
|
||||
从“参考答案”区域提取题号与答案映射。
|
||||
|
||||
用途:很多试卷会把题目和答案分成两段展示,这里先把独立答案表收集出来,供后续题目块回填正确答案。
|
||||
参数约束:只解析明显的答案行,避免把题干里的选项误判成答案。
|
||||
"""
|
||||
answer_map: dict[int, str] = {}
|
||||
for line in lines:
|
||||
matches = list(_ANSWER_PAIR_PATTERN.finditer(line))
|
||||
if not _is_answer_sheet_line(line):
|
||||
continue
|
||||
for match in matches:
|
||||
question_no = int(match.group(1))
|
||||
answer = _normalize_answer_token(match.group(2))
|
||||
if answer and question_no not in answer_map:
|
||||
answer_map[question_no] = answer
|
||||
return answer_map
|
||||
|
||||
|
||||
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
|
||||
blocks: list[tuple[int, str]] = []
|
||||
current_no: int | None = None
|
||||
current_lines: list[str] = []
|
||||
|
||||
for line in lines:
|
||||
if _SECTION_HEADING_PATTERN.match(line):
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
current_no = None
|
||||
current_lines = []
|
||||
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()))
|
||||
current_no = int(question_match.group(1))
|
||||
current_lines = [question_match.group(2)]
|
||||
continue
|
||||
if _is_answer_sheet_line(line):
|
||||
continue
|
||||
if current_no is not None:
|
||||
current_lines.append(line)
|
||||
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
return blocks
|
||||
|
||||
|
||||
def _extract_inline_answer(block_text: str) -> str:
|
||||
match = _INLINE_ANSWER_PATTERN.search(block_text)
|
||||
if not match:
|
||||
return ''
|
||||
return _normalize_answer_token(match.group(1))
|
||||
|
||||
|
||||
def _extract_inline_explanation(block_text: str) -> str:
|
||||
match = _INLINE_EXPLANATION_PATTERN.search(block_text)
|
||||
return _normalize_spaces(match.group(1)) if match else ''
|
||||
|
||||
|
||||
def _strip_inline_meta(block_text: str) -> str:
|
||||
cleaned = _INLINE_EXPLANATION_PATTERN.sub('', block_text)
|
||||
cleaned = _INLINE_ANSWER_PATTERN.sub('', cleaned)
|
||||
return _normalize_spaces(cleaned)
|
||||
|
||||
|
||||
def _build_boolean_question(question_no: int, prompt: str, answer: str, explanation: str) -> dict[str, Any] | None:
|
||||
if answer not in {'true', 'false'}:
|
||||
return None
|
||||
return {
|
||||
'id': f'q{question_no}',
|
||||
'type': 'boolean',
|
||||
'prompt': prompt,
|
||||
'answer': answer,
|
||||
'explanation': explanation,
|
||||
}
|
||||
|
||||
|
||||
def _build_answer_candidates(
|
||||
*,
|
||||
inline_answer: str,
|
||||
mapped_answer: str,
|
||||
ordered_answer: str,
|
||||
) -> list[str]:
|
||||
"""
|
||||
组合单题可用的答案候选,并按可信度排序。
|
||||
|
||||
用途:优先使用题干内联答案,其次使用题号映射;若 PDF 存在分节重编号,再退回整卷顺序答案,尽量把判断题补齐。
|
||||
参数约束:返回结果会去重,避免同一答案在多种来源下重复尝试。
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
for raw in (inline_answer, mapped_answer, ordered_answer):
|
||||
value = _normalize_answer_token(raw)
|
||||
if value and value not in candidates:
|
||||
candidates.append(value)
|
||||
return candidates
|
||||
|
||||
|
||||
def _looks_like_boolean_question(prompt: str, option_matches: list[re.Match[str]], answer_candidates: list[str]) -> bool:
|
||||
"""
|
||||
判断题型是否更接近判断题。
|
||||
|
||||
用途:避免答案表错位时把带 A/B/C/D 选项的单选题误判成判断题,同时允许“句子 + ( )”这类常见判断题格式被识别。
|
||||
参数约束:只在没有完整选项结构时才考虑判断题,单选题仍以选项结构为主。
|
||||
"""
|
||||
if len(option_matches) >= 2:
|
||||
return False
|
||||
if any(answer in {'true', 'false'} for answer in answer_candidates):
|
||||
return True
|
||||
return bool(_BOOLEAN_PROMPT_HINT_PATTERN.search(prompt))
|
||||
|
||||
|
||||
def _build_single_choice_question(question_no: int, prompt: str, option_matches: list[re.Match[str]], answer: str, explanation: str) -> dict[str, Any] | None:
|
||||
if len(option_matches) < 2:
|
||||
return None
|
||||
|
||||
options: list[dict[str, str]] = []
|
||||
for index, match in enumerate(option_matches):
|
||||
start = match.end()
|
||||
end = option_matches[index + 1].start() if index + 1 < len(option_matches) else len(prompt)
|
||||
label = _normalize_spaces(prompt[start:end])
|
||||
option_id = match.group(1).lower()
|
||||
if not label:
|
||||
continue
|
||||
options.append({'id': option_id, 'label': f"{match.group(1).upper()}. {label}"})
|
||||
|
||||
if len(options) < 2 or answer not in {item['id'] for item in options}:
|
||||
return None
|
||||
|
||||
prompt_text = _normalize_spaces(prompt[:option_matches[0].start()])
|
||||
if not prompt_text:
|
||||
return None
|
||||
|
||||
return {
|
||||
'id': f'q{question_no}',
|
||||
'type': 'single',
|
||||
'prompt': prompt_text,
|
||||
'answer': answer,
|
||||
'explanation': explanation,
|
||||
'options': options,
|
||||
}
|
||||
|
||||
|
||||
def parse_training_question_bank_text(text: str) -> dict[str, Any]:
|
||||
"""
|
||||
将 PDF 抽出的纯文本解析成培训题库。
|
||||
|
||||
用途:给管理后台的“从试题 PDF 导入题库”提供核心解析逻辑;优先保证答题链路可用,无法确定答案的题目宁可跳过也不乱导入。
|
||||
参数约束:text 应来自同一份试卷文本;若完全无法识别题目或答案,调用方应直接提示人工处理。
|
||||
"""
|
||||
lines = _collect_candidate_lines(text)
|
||||
answer_map = _extract_answer_map(lines)
|
||||
answer_sequence = _extract_answer_sequence(lines)
|
||||
question_blocks = _split_question_blocks(lines)
|
||||
question_bank: list[dict[str, Any]] = []
|
||||
skipped_questions: list[int] = []
|
||||
|
||||
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
|
||||
for index, (question_no, raw_block) in enumerate(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))
|
||||
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 '',
|
||||
)
|
||||
|
||||
if _looks_like_boolean_question(block_text, option_matches, answer_candidates):
|
||||
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
|
||||
|
||||
for answer in answer_candidates:
|
||||
question_payload = _build_single_choice_question(
|
||||
question_no=question_no,
|
||||
prompt=block_text,
|
||||
option_matches=option_matches,
|
||||
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
|
||||
|
||||
skipped_questions.append(question_no)
|
||||
|
||||
if not question_bank:
|
||||
raise ValidationError('未能从试题 PDF 中识别出可用题目,请检查 PDF 是否包含可复制文本与标准答案')
|
||||
|
||||
return {
|
||||
'question_bank': question_bank,
|
||||
'parsed_count': len(question_bank),
|
||||
'skipped_question_numbers': skipped_questions,
|
||||
}
|
||||
|
||||
|
||||
def parse_training_question_bank_from_guide(agent_id: int, guide_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
从指定 Agent 的试题 PDF 指南中解析题库。
|
||||
|
||||
用途:管理后台点击“从已上传试题 PDF 导入”时使用,优先读取显式标记为 training_exam_pdf 的资料。
|
||||
参数约束:guide_id 若传入,必须属于当前 agent 且文件类型为 pdf。
|
||||
"""
|
||||
query = db.session.query(AgentGuide).filter(AgentGuide.agent_id == agent_id)
|
||||
if guide_id is not None:
|
||||
query = query.filter(AgentGuide.id == guide_id)
|
||||
query = query.filter(AgentGuide.file_type == 'pdf')
|
||||
guide = query.order_by(AgentGuide.sort_order.asc(), AgentGuide.id.desc()).first()
|
||||
if not guide:
|
||||
raise NotFoundError('Training exam PDF guide not found')
|
||||
if guide.guide_usage != GUIDE_USAGE_TRAINING_EXAM_PDF:
|
||||
raise ValidationError('Selected guide is not marked as training exam PDF')
|
||||
|
||||
raw_bytes = minio_service.get_file_bytes(guide.file_path)
|
||||
text = _extract_pdf_text(raw_bytes)
|
||||
ocr_text = ''
|
||||
ocr_warnings: list[str] = []
|
||||
extraction_mode = 'pdf_text'
|
||||
|
||||
# [STEP 1] 先尝试 PDF 原生文本,速度快且不会引入 OCR 噪音。
|
||||
if text:
|
||||
try:
|
||||
parsed = parse_training_question_bank_text(text)
|
||||
except ValidationError as primary_error:
|
||||
# [STEP 2] 原生文本存在但结构解析失败时,再尝试 OCR,兼容“页面能选中文本但题号/答案错位”的扫描型 PDF。
|
||||
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
|
||||
if not ocr_text or ocr_text == text:
|
||||
raise primary_error
|
||||
parsed = parse_training_question_bank_text(ocr_text)
|
||||
extraction_mode = 'ocr_fallback'
|
||||
else:
|
||||
# [STEP 2] 完全拿不到 PDF 文本时,直接走 OCR;若 OCR 依旧为空,则给管理端明确报错并带回诊断 warnings。
|
||||
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
|
||||
if not ocr_text:
|
||||
raise ValidationError(
|
||||
'试题 PDF 未提取到可读文本,请检查是否为扫描件或图片 PDF,并确认 OCR 依赖已正确安装',
|
||||
details={'ocr_warnings': ocr_warnings},
|
||||
)
|
||||
parsed = parse_training_question_bank_text(ocr_text)
|
||||
extraction_mode = 'ocr'
|
||||
|
||||
parsed['guide_id'] = guide.id
|
||||
parsed['guide_file_name'] = guide.file_name
|
||||
parsed['extraction_mode'] = extraction_mode
|
||||
parsed['extraction_warnings'] = ocr_warnings
|
||||
return parsed
|
||||
@@ -88,6 +88,25 @@ class MinioService:
|
||||
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
|
||||
return f"{base_url}/{self.bucket_name}/{object_name}"
|
||||
|
||||
def get_file_bytes(self, object_name: str) -> bytes:
|
||||
"""
|
||||
读取对象的原始字节内容。
|
||||
|
||||
用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。
|
||||
参数约束:object_name 必须是已存储的对象名,不接受外部 URL。
|
||||
"""
|
||||
local_path = os.path.join('data/agent-guides', object_name)
|
||||
if os.path.exists(local_path):
|
||||
with open(local_path, 'rb') as file_obj:
|
||||
return file_obj.read()
|
||||
|
||||
response = self.client.get_object(self.bucket_name, object_name)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
|
||||
def delete_file(self, object_name: str):
|
||||
try:
|
||||
self.client.remove_object(self.bucket_name, object_name)
|
||||
|
||||
Reference in new issue
Block a user