diff --git a/backend/app/api/admin/agents.py b/backend/app/api/admin/agents.py index b39b4aa7..16e54e97 100644 --- a/backend/app/api/admin/agents.py +++ b/backend/app/api/admin/agents.py @@ -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//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 diff --git a/backend/app/models/agent.py b/backend/app/models/agent.py index 8f0424c9..472d680f 100644 --- a/backend/app/models/agent.py +++ b/backend/app/models/agent.py @@ -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) diff --git a/backend/app/services/admin/agent_service.py b/backend/app/services/admin/agent_service.py index 9789ee49..a9330525 100644 --- a/backend/app/services/admin/agent_service.py +++ b/backend/app/services/admin/agent_service.py @@ -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) diff --git a/backend/app/services/admin/guide_service.py b/backend/app/services/admin/guide_service.py index 45867c1e..23d4af1d 100644 --- a/backend/app/services/admin/guide_service.py +++ b/backend/app/services/admin/guide_service.py @@ -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() diff --git a/backend/app/services/admin/training_exam_pdf_service.py b/backend/app/services/admin/training_exam_pdf_service.py new file mode 100644 index 00000000..5f0e4cc6 --- /dev/null +++ b/backend/app/services/admin/training_exam_pdf_service.py @@ -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 diff --git a/backend/app/services/minio_service.py b/backend/app/services/minio_service.py index ade0019f..45a919e8 100644 --- a/backend/app/services/minio_service.py +++ b/backend/app/services/minio_service.py @@ -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) diff --git a/backend/tests/services/admin/test_training_exam_pdf_service.py b/backend/tests/services/admin/test_training_exam_pdf_service.py new file mode 100644 index 00000000..db00ee1c --- /dev/null +++ b/backend/tests/services/admin/test_training_exam_pdf_service.py @@ -0,0 +1,209 @@ +""" +tests/services/admin/test_training_exam_pdf_service.py + +用途:验证培训试题 PDF 文本解析逻辑,确保可从常见试卷文本中抽出题目、选项、答案与解析。 +""" +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import Agent, AgentGuide +from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF +from app.services.admin.training_exam_pdf_service import ( + parse_training_question_bank_from_guide, + parse_training_question_bank_text, +) + + +def test_parse_training_question_bank_text_supports_inline_answers(): + text = """ + 一、单选题 + 1. 工资每月几号发放? A. 8号 B. 9号 C. 15号 D. 27号 答案:C 解析:工资固定在每月15号发放。 + 2. 餐厅订餐的系统是? A. OA B. 中米新订餐系统 C. ERP 答案:B + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 2 + assert payload['skipped_question_numbers'] == [] + assert payload['question_bank'][0]['type'] == 'single' + assert payload['question_bank'][0]['answer'] == 'c' + assert payload['question_bank'][0]['options'][2]['label'] == 'C. 15号' + assert payload['question_bank'][0]['explanation'] == '工资固定在每月15号发放。' + + +def test_parse_training_question_bank_text_supports_answer_sheet_mapping(): + text = """ + 1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122 + 2、入职培训未达到90分必须重新考试。 正确还是错误? + + 参考答案: + 1.B 2.正确 + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 2 + assert payload['question_bank'][0]['answer'] == 'b' + assert payload['question_bank'][1]['type'] == 'boolean' + assert payload['question_bank'][1]['answer'] == 'true' + + +def test_parse_training_question_bank_text_supports_global_answer_sequence_for_section_reset_numbering(): + text = """ + 一、单选题 + 1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122 + 2、餐厅订餐系统是? A.OA B.中米新订餐系统 C.ERP D.PLM + + 二、判断题(每题5分) + 1、正常出勤必须打卡。( ) + 2、忘记刷卡需要OA补刷卡单。( ) + + 参考答案: + 1.B 2.B 3.正确 4.正确 + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 4 + assert payload['skipped_question_numbers'] == [] + assert [item['type'] for item in payload['question_bank']] == ['single', 'single', 'boolean', 'boolean'] + assert payload['question_bank'][2]['answer'] == 'true' + assert payload['question_bank'][3]['answer'] == 'true' + + +def test_parse_training_question_bank_text_supports_answer_sheet_with_section_local_numbering(): + text = """ + 一、单选题 + 1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122 + 2、餐厅订餐系统是? A.OA B.中米新订餐系统 C.ERP D.PLM + + 二、判断题 + 1、正常出勤必须打卡。( ) + 2、忘记刷卡需要OA补刷卡单。( ) + + 单选题答案: + 1.B 2.B + 判断题答案: + 1.正确 2.错误 + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 4 + assert payload['skipped_question_numbers'] == [] + assert payload['question_bank'][2]['type'] == 'boolean' + assert payload['question_bank'][2]['answer'] == 'true' + assert payload['question_bank'][3]['answer'] == 'false' + + +def test_parse_training_question_bank_text_supports_boolean_range_answer_sheet(): + text = """ + 一、选择题(每题5分) + 1、工资每月几号发放( ) + A、8号 B、9号 C、15号 D、27号 + 2、餐厅订餐的系统是( ) + A、OA B、中米新订餐系统 C、ERP + + 二、判断题(每题5分) + 1、正常出勤必须打卡,加班需要提前申请提报。( ) + 2、忘记刷卡需要OA开补刷卡单。( ) + 3、每月工资从上月21日至本月20日为止计算。( ) + + 一、单选题(每题10分) + 1、C 2、B + 二、判断题(每题10分) + 1-3 V V × + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 5 + assert payload['skipped_question_numbers'] == [] + assert [item['type'] for item in payload['question_bank']] == ['single', 'single', 'boolean', 'boolean', 'boolean'] + assert [item['answer'] for item in payload['question_bank']] == ['c', 'b', 'true', 'true', 'false'] + + +def test_parse_training_question_bank_text_raises_when_no_usable_questions(): + with pytest.raises(ValidationError, match='未能从试题 PDF 中识别出可用题目'): + parse_training_question_bank_text('这是一份扫描件占位文本,没有题号也没有答案。') + + +def test_parse_training_question_bank_from_guide_falls_back_to_ocr_when_pdf_text_empty(app, monkeypatch): + with app.app_context(): + agent = Agent(name='员工培训', type='api', is_active=True) + db.session.add(agent) + db.session.flush() + guide = AgentGuide( + agent_id=agent.id, + file_name='training.pdf', + file_type='pdf', + file_path='training/training.pdf', + guide_usage=GUIDE_USAGE_TRAINING_EXAM_PDF, + status=1, + ) + db.session.add(guide) + db.session.commit() + + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service.minio_service.get_file_bytes', + lambda _path: b'%PDF-1.4 fake', + ) + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service._extract_pdf_text', + lambda _raw: '', + ) + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service._extract_pdf_text_via_ocr', + lambda _raw: ( + '1. 消防电话是多少? A.110 B.119 C.120 D.122 答案:B', + ['pdf likely scanned; OCR recommended'], + ), + ) + + payload = parse_training_question_bank_from_guide(agent.id, guide.id) + + assert payload['parsed_count'] == 1 + assert payload['extraction_mode'] == 'ocr' + assert payload['extraction_warnings'] == ['pdf likely scanned; OCR recommended'] + assert payload['question_bank'][0]['answer'] == 'b' + + +def test_parse_training_question_bank_from_guide_retries_ocr_when_native_text_parse_fails(app, monkeypatch): + with app.app_context(): + agent = Agent(name='员工培训', type='api', is_active=True) + db.session.add(agent) + db.session.flush() + guide = AgentGuide( + agent_id=agent.id, + file_name='training.pdf', + file_type='pdf', + file_path='training/training.pdf', + guide_usage=GUIDE_USAGE_TRAINING_EXAM_PDF, + status=1, + ) + db.session.add(guide) + db.session.commit() + + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service.minio_service.get_file_bytes', + lambda _path: b'%PDF-1.4 fake', + ) + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service._extract_pdf_text', + lambda _raw: '这是错位文本,题号和答案都缺失', + ) + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service._extract_pdf_text_via_ocr', + lambda _raw: ( + '1. 工资每月几号发放? A.8号 B.9号 C.15号 D.27号 答案:C', + ['pdf page-image mode pages: 1'], + ), + ) + + payload = parse_training_question_bank_from_guide(agent.id, guide.id) + + assert payload['parsed_count'] == 1 + assert payload['extraction_mode'] == 'ocr_fallback' + assert payload['extraction_warnings'] == ['pdf page-image mode pages: 1'] + assert payload['question_bank'][0]['answer'] == 'c' diff --git a/docs/funclist.md b/docs/funclist.md index cef28d3d..6fd3c30d 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -26,11 +26,12 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | | Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 | -| Chat 内 HR 管理面板 | 已实现 | 管理角色可在同一聊天页查看真实培训统计、筛选记录并导出 Excel | -| 培训题库前端内置 | 前端已实现 | 内置 20 道新人试卷题目,支持一题一答、即时反馈、未通过重考 | -| 管理端培训模式配置 | 前端已实现 | Agent 管理表单支持显式开启培训工作区,并可一键套用培训默认配置 | +| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;权限支持角色默认值与前端用户配置共同控制 | +| 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 | +| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 | | 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 | | 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 | +| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) | | 培训业务闭环整改清单 | 已文档化 | 见 [docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) | ## 1. 功能总览 diff --git a/docs/tec.md b/docs/tec.md index 3857433b..616feefa 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -911,6 +911,128 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth; - Web 进程压力下降,系统稳定性提升 - 失败任务可重试,进度展示更清晰 - 整体知识库链路更适合后续扩展为高并发、多批次处理模式 + +--- + +## 19. 新人入职培训 Agent 推荐技术路径 + +### 19.1 推荐结论 + +“新人入职培训 Agent”不建议走纯 Dify 考试编排主链,推荐采用: + +- **主链**:Chat 页面内嵌培训工作区 + 前端受控状态机 + 后端真实记录落库 +- **辅助层**:Dify 承担培训 FAQ、知识点解释、HR 自然语言统计问答(ChatBI) + +该方案更符合培训考试场景对“流程刚性、成绩可信、状态可恢复、结果可审计”的要求。 + +### 19.2 为什么不建议纯 Dify 主导考试 + +- 培训考试需要严格控制“看视频 -> 看总结 -> 一题一答 -> 结算 -> 补考”顺序 +- 题号推进、得分计算、补考次数不适合交给大模型对话变量作为唯一事实源 +- 纯 Dify 方案更适合自然语言问答,不适合作为考试状态机和唯一判卷引擎 +- HR 统计和导出需要稳定的数据事实源,不能依赖对话历史反推 + +### 19.3 推荐架构 + +```text +员工 + -> Chat 页面 + -> 培训工作区(视频 / 总结 / 考试 / 结算) + -> 聊天气泡卡片(视频卡片 / 总结卡片 / 题目卡片 / 结果卡片) + +前端培训工作区 + -> /api/user/training-record + -> /api/user/training-record/progress + +后端 training 域 + -> TrainingRecord 表 + -> training_service + -> HR 列表 / 统计 / Excel 导出 + +Dify + -> 培训 FAQ + -> 知识点解释 + -> HR ChatBI +``` + +### 19.4 培训权限模型 + +- 学员端默认面向所有已登录员工开放,允许查看视频、知识点复盘、考试与个人成绩回显。 +- `HR 管理` 视图与 `/api/admin/training-records*` 接口统一走 `training_hr_manage` 功能权限判断。 +- 权限来源采用“**角色默认值 + 用户显式配置覆盖**”: + - `admin`、`hr` 角色默认拥有 `training_hr_manage` + - 管理后台用户编辑表单可对单个用户显式授予或关闭该权限 +- 前端只根据登录态里的 `feature_permissions.training_hr_manage` 决定是否展示 `HR 管理` 标签;后端仍做强校验,避免仅靠前端隐藏导致越权。 + +### 19.5 培训资料维护 + +- 后台继续复用 `AgentGuide` 资料模型承载培训素材,不单独新建一套上传体系。 +- `guide_usage` 用于标识资料用途: + - `general`:普通应用指南 + - `training_video`:员工培训视频 + - `training_exam_pdf`:员工培训试题 PDF +- 员工培训工作区读取顺序: + 1. 优先读取 `training_video` 指南作为培训视频 + 2. 若未配置,再回退到 Agent `extra_config.training_video_url` + 3. 仍未配置时使用默认演示视频 +- “查看试题 PDF”入口只读取 `training_exam_pdf`,避免把普通指南 PDF 误识别成考试资料。 + +### 19.6 培训内容后台化 + +- 培训工作区的结构化内容统一收敛到 `Agent.extra_config.training_config`,避免继续把题库、复盘要点散落在前端静态文案里。 +- 当前约定字段: + - `pass_score`:及格线,按百分制判定是否通过 + - `summary_points`:知识点复盘数组 + - `summary_checklist`:考前必知数组 + - `question_bank`:结构化题库(`id/type/prompt/answer/explanation/options`) +- 员工培训工作区读取顺序: + 1. 优先读取 `extra_config.training_config` + 2. 若某项未配置,则仅该项回退到前端默认值,保证旧 Agent 不因缺字段而失效 +- 题库题量改为后台可配后,前端分数计算改为“按当前题量折算百分制”,不再硬编码每题 5 分。 +- 管理端支持从已上传并标记为 `training_exam_pdf` 的指南 PDF 解析题库: + 1. 后端按 `guide_id` 读取 PDF 文本 + 2. 若 PDF 原生文本缺失或错位,则回退到 `loader_pdf + rapidocr` 识别扫描件页面 + 3. 识别题号、选项、答案与解析,生成 `question_bank` + 4. 解析结果先回填 Agent 表单,由 HR 复核后再保存,避免误解析直接落库 +- 扫描件 PDF 的 OCR 回退依赖 `backend/requirements-ocr.txt` 中的 rapidocr / onnxruntime 栈;若环境未安装,接口会返回带 `ocr_warnings` 的诊断信息,提示先补齐 OCR 依赖。 + +### 19.4 Dify 职责边界 + +#### 建议由 Dify 负责 + +- 培训制度问答 +- 培训知识点解释 +- 培训 FAQ +- HR 自然语言统计和导出问答 + +#### 不建议由 Dify 负责 + +- 当前题号推进 +- 当前分数累计 +- 最终是否通过的唯一判定 +- 补考次数控制 +- 培训考试记录事实落库 + +### 19.5 推荐实施顺序 + +#### P0 + +- 保留现有培训工作区主链 +- 完善 training 接口测试与前端回归测试 +- 确保培训记录、统计、导出全链路稳定 + +#### P1 + +- 题库、知识点、通过线、欢迎语后台配置化 +- 培训视频素材正式配置化 +- 题库版本化与记录快照化 + +#### P2 + +- 接入 Dify 作为培训 FAQ / HR ChatBI 的辅助层 +- 对外形成“Chat 化体验 + 受控考试主链”的最终形态 + +详细说明见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md)。 # 设备维保助手技术设计补充 ## 数据模型 diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index ea80710b..564c6463 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -1,4 +1,4 @@ -/** +/** * features/admin/api/admin.api.ts * 管理后台 HTTP API:用户、部门、Agent、权限、报表、企业微信、公告等。 */ @@ -131,6 +131,27 @@ export const uploadAdminAgentGuideFile = async (file: File) => { } return response.json(); }; +export const importAdminAgentTrainingQuestionBankFromPdf = (agentId: number, payload: { guide_id?: number | null }) => + requestJson<{ + guide_id: number; + guide_file_name: string; + parsed_count: number; + skipped_question_numbers: number[]; + extraction_mode?: 'pdf_text' | 'ocr' | 'ocr_fallback'; + extraction_warnings?: string[]; + question_bank: Array<{ + id: string; + type: 'single' | 'boolean'; + prompt: string; + answer: string; + explanation: string; + options?: Array<{ id: string; label: string }>; + }>; + }>(`/api/admin/agents/${agentId}/training-question-bank/import-pdf`, { + method: 'POST', + ...jsonAuth(), + body: JSON.stringify(payload), + }); export const testAdminAgent = (id: number) => requestJson(`/api/admin/agents/${id}/test`, { method: 'POST', ...auth() }); export const saveAdminAgentPermissions = (agentId: number, userIds: number[]) => diff --git a/frontend/src/features/admin/modules/agents/AgentsPage.vue b/frontend/src/features/admin/modules/agents/AgentsPage.vue index 9d15a4f9..3e5bb403 100644 --- a/frontend/src/features/admin/modules/agents/AgentsPage.vue +++ b/frontend/src/features/admin/modules/agents/AgentsPage.vue @@ -1,4 +1,4 @@ -/** +/** * features/admin/modules/agents/AgentsPage.vue * * 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。 @@ -29,9 +29,11 @@ const { t } = useI18n(); const { agents, scheduleTasks, + trainingExamPdfGuides, activeUsers, isLoading, isSaving, + isImportingTrainingPdf, isEditing, selectedAgentId, form, @@ -50,6 +52,11 @@ const { submitAgent, addSuggestedQuestion, removeSuggestedQuestion, + addTrainingQuestion, + removeTrainingQuestion, + addTrainingOption, + removeTrainingOption, + importTrainingQuestionBankFromPdf, deleteAgent, openTestModal, runAgentTest, @@ -229,12 +236,19 @@ onMounted(() => { :visible="showFormDialog" :is-editing="isEditing" :is-saving="isSaving" + :is-importing-training-pdf="isImportingTrainingPdf" :form="form" :schedule-tasks="scheduleTasks" + :training-exam-pdf-guides="trainingExamPdfGuides" @close="showFormDialog = false" @save="saveAgentForm" @add-suggested-question="addSuggestedQuestion" @remove-suggested-question="removeSuggestedQuestion" + @add-training-question="addTrainingQuestion" + @remove-training-question="removeTrainingQuestion" + @add-training-option="addTrainingOption" + @remove-training-option="removeTrainingOption" + @import-training-pdf="importTrainingQuestionBankFromPdf" /> -import { Plus, Trash2, X } from 'lucide-vue-next'; +import { FileDown, Plus, Trash2, X } from 'lucide-vue-next'; import { useI18n } from 'vue-i18n'; -import type { AgentFormState } from '@/features/admin/types/agent.types'; +import type { AgentFormState, AgentGuideSummary } from '@/features/admin/types/agent.types'; import type { ScheduleTask } from '@/shared/types/schedule.types'; import AgentToolRunProgressConfig from './AgentToolRunProgressConfig.vue'; @@ -17,8 +17,10 @@ defineProps<{ visible: boolean; isEditing: boolean; isSaving: boolean; + isImportingTrainingPdf: boolean; form: AgentFormState; scheduleTasks: ScheduleTask[]; + trainingExamPdfGuides: AgentGuideSummary[]; }>(); const emit = defineEmits<{ @@ -26,9 +28,40 @@ const emit = defineEmits<{ save: []; addSuggestedQuestion: []; removeSuggestedQuestion: [index: number]; + addTrainingQuestion: []; + removeTrainingQuestion: [index: number]; + addTrainingOption: [questionIndex: number]; + removeTrainingOption: [questionIndex: number, optionIndex: number]; + importTrainingPdf: [guideId?: number | null]; }>(); const { t } = useI18n(); +const optionLabels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); + +/** + * 切换培训题型时同步修正表单结构。 + * 核心逻辑:判断题固定使用 true/false;单选题至少保留两个选项,并把答案回落到首个可用选项。 + */ +const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) => { + const question = form.training_question_bank[index]; + if (!question) return; + if (question.type === 'boolean') { + question.options = []; + question.answer = question.answer === 'false' ? 'false' : 'true'; + return; + } + if (!Array.isArray(question.options)) { + question.options = ['', '']; + } + while (question.options.length < 2) { + question.options.push(''); + } + const validAnswerIds = question.options + .map((item) => String(item || '').trim()) + .filter(Boolean) + .map((_, optionIndex) => String.fromCharCode(97 + optionIndex)); + question.answer = validAnswerIds.includes(question.answer) ? question.answer : (validAnswerIds[0] || 'a'); +};