""" services/shipping_notice/attachment_selection.py 用途:基于 Intake 快览事实生成可审计的附件选择计划。 依赖:ShippingOrderIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。 逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划; 合格业务附件全量入选批次 1(有多少单解析多少单),仅字节预算超限转 Review; 数量类预算字段仅作快照记录,不再截断,扩批链路不再产出。 """ from __future__ import annotations import re from collections import defaultdict from typing import Any from app.models import ShippingOrderIntake _PO_HINT_RE = re.compile(r'\b(?:PO[-_ ]*)?([A-Z]{0,4}\d{5,})\b', re.IGNORECASE) _TOKEN_RE = re.compile(r'[A-Z0-9]{4,}', re.IGNORECASE) _IMAGE_MIME_PREFIX = 'image/' _READY_REASON = 'ready_for_extraction' _EXCLUDED_CATALOG_REASONS = { 'archive', 'executable', 'macro_enabled', 'unknown_binary', 'inline_resource', 'signature_or_logo', } _TYPE_WEIGHTS: tuple[tuple[tuple[str, ...], int, str], ...] = ( (('application/pdf',), 160, 'type_pdf'), (( 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword', ), 80, 'type_word'), (( 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel', 'text/csv', ), 90, 'type_spreadsheet'), (('message/rfc822',), 70, 'type_nested_eml'), ) _NAME_HINTS: tuple[tuple[str, int, str], ...] = ( ('po', 60, 'filename_po_hint'), ('order', 45, 'filename_order_hint'), ('reservation', 40, 'filename_reservation_hint'), ('booking', 35, 'filename_booking_hint'), ('shipping', 20, 'filename_shipping_hint'), ) _NEGATIVE_NAME_HINTS: tuple[tuple[str, int, str], ...] = ( ('copy', -40, 'filename_copy_hint'), ('duplicate', -80, 'filename_duplicate_hint'), ('signature', -180, 'filename_signature_hint'), ('sign', -120, 'filename_sign_hint'), ('logo', -180, 'filename_logo_hint'), ('stamp', -100, 'filename_stamp_hint'), ) def _structured(intake: ShippingOrderIntake) -> dict[str, Any]: """读取 Intake 快览摘要;缺失时返回空对象,调用方决定是否视为不可选。""" return intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {} def _mail_text(structured: dict[str, Any]) -> str: """合并主题与正文白名单快照,供命名线索打分和分组使用。""" email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {} body_text = str(email_meta.get('body_text') or '').strip() subject = str(email_meta.get('subject') or '').strip() html_tables = ' '.join( str(item).strip() for item in (email_meta.get('body_html_tables') or []) if str(item).strip() ) return ' '.join(part for part in (subject, body_text, html_tables) if part).strip() def _po_hints(*values: str) -> list[str]: """提取稳定的订单号线索;用于分组与评分,不输出正文原文。""" found: list[str] = [] for value in values: for item in _PO_HINT_RE.findall(str(value or '')): normalized = str(item or '').strip().upper() if normalized and normalized not in found: found.append(normalized) return found def _mail_tokens(text: str) -> set[str]: """把邮件主题/正文压缩成稳定 token 集合,供附件名做轻量交叉评分。""" return {token.upper() for token in _TOKEN_RE.findall(text or '') if len(token) >= 4} def _score_attachment(*, filename: str, mime_type: str, size: int, mail_text: str) -> tuple[int, list[str], str]: """只基于快览可见事实为单个附件评分,并返回稳定原因码和分组键。""" score = 0 reasons: list[str] = [] normalized_name = filename.lower() normalized_mime = mime_type.lower() tokens = _mail_tokens(mail_text) name_tokens = {token.upper() for token in _TOKEN_RE.findall(filename or '') if len(token) >= 4} for mime_prefixes, weight, reason in _TYPE_WEIGHTS: if any(normalized_mime.startswith(prefix) for prefix in mime_prefixes): score += weight reasons.append(reason) break if size >= 1024 * 20: score += 15 reasons.append('size_non_trivial') if size >= 1024 * 1024: score += 10 reasons.append('size_large_attachment') if 0 < size <= 1024 * 8: score -= 15 reasons.append('size_too_small') for needle, weight, reason in _NAME_HINTS: if needle in normalized_name: score += weight reasons.append(reason) for needle, weight, reason in _NEGATIVE_NAME_HINTS: if needle in normalized_name: score += weight reasons.append(reason) po_hints = _po_hints(filename, mail_text) if po_hints: score += 80 reasons.append('po_hint_detected') overlap = sorted(tokens & name_tokens) if overlap: score += min(30, len(overlap) * 10) reasons.append('mail_filename_token_overlap') group_key = po_hints[0] if po_hints else (overlap[0] if overlap else normalized_name[:48] or 'ungrouped') return score, reasons, group_key def build_attachment_selection_snapshot( *, intakes: list[ShippingOrderIntake], max_initial_attachments: int = 2, max_initial_concurrency: int = 2, expansion_batch_size: int = 2, max_total_attachments: int = 6, max_total_bytes: int | None = None, max_runtime_seconds: int | None = None, ) -> dict[str, Any]: """ 基于当前批次 Intake 快览事实生成可解释的附件选择计划。 AI 触发时机:点击发送后,需要把“当前输入框这批附件”冻结成一份稳定计划时使用。 该函数只能读取快览字段,禁止依赖附件正文、布局坐标、Document、Candidate 或 Provider 输出。 Args: intakes: 当前发送批次的 Intake;必须已经通过上传快览。 max_initial_attachments: 历史兼容字段,仅写入快照作审计记录,不参与选择。 max_initial_concurrency: Worker 最大并发,仅限制执行,不限制 Unit 创建。 expansion_batch_size: 历史兼容字段,仅写入快照作审计记录,不参与选择。 max_total_attachments: 历史兼容字段,仅写入快照作审计记录,不再按数量截断。 max_total_bytes: 唯一生效的选择预算;累计超限的附件以 budget_total_bytes 转 Review。 Returns: 可写入 Run 快照的脱敏计划摘要,包含每个附件的 selected / skipped 结论与原因码。 """ rows: list[dict[str, Any]] = [] duplicate_content_hashes: dict[str, int] = defaultdict(int) for intake in intakes: structured = _structured(intake) mail_text = _mail_text(structured) attachments = structured.get('attachments') if isinstance(structured.get('attachments'), list) else [] for item in attachments: if not isinstance(item, dict): continue filename = str(item.get('filename') or '').strip() mime_type = str(item.get('mime_type') or 'application/octet-stream').strip().lower() content_hash = str(item.get('content_hash') or '').strip().lower() catalog_reason = str(item.get('catalog_reason') or '').strip().lower() or _READY_REASON ready_for_extraction = bool(item.get('ready_for_extraction')) is_inline = bool(item.get('is_inline_resource')) or mime_type.startswith(_IMAGE_MIME_PREFIX) size = max(0, int(item.get('size') or 0)) if is_inline: # 邮件签名和正文内嵌资源不是用户上传的业务附件,不纳入识别范围或数量统计。 continue score, score_reasons, group_key = _score_attachment( filename=filename, mime_type=mime_type, size=size, mail_text=mail_text, ) if content_hash: duplicate_content_hashes[content_hash] += 1 rows.append({ 'intake_no': intake.intake_no, 'attachment_key': str(item.get('attachment_key') or '').strip(), 'filename': filename, 'mime_type': mime_type, 'size': size, 'content_hash': content_hash or None, 'catalog_reason': catalog_reason, 'ready_for_extraction': ready_for_extraction, 'score': score, 'score_reasons': score_reasons, 'group_key': group_key, 'selected': False, 'selection_batch': None, 'planned_selection_batch': None, 'skip_reason_codes': [], }) eligible: list[dict[str, Any]] = [] seen_hashes: set[str] = set() for row in rows: skip_reasons: list[str] = [] catalog_reason = str(row.get('catalog_reason') or _READY_REASON) content_hash = str(row.get('content_hash') or '') if not bool(row.get('ready_for_extraction')): skip_reasons.append(f'catalog_reason:{catalog_reason}') elif catalog_reason in _EXCLUDED_CATALOG_REASONS: skip_reasons.append(f'catalog_reason:{catalog_reason}') elif content_hash and content_hash in seen_hashes: skip_reasons.append('duplicate_content_hash') elif content_hash and duplicate_content_hashes.get(content_hash, 0) > 1: seen_hashes.add(content_hash) if not skip_reasons: if content_hash: seen_hashes.add(content_hash) eligible.append(row) else: row['skip_reason_codes'] = skip_reasons eligible_ordered = sorted(eligible, key=lambda item: (-int(item['score']), str(item['filename']))) byte_budget = max(0, int(max_total_bytes or 0)) planned_bytes = 0 for row in eligible_ordered: size = int(row.get('size') or 0) if byte_budget and planned_bytes + size > byte_budget: row['skip_reason_codes'] = ['budget_total_bytes'] continue # [STEP 1] 合格业务附件全量入选,不设数量截断:有多少单解析多少单。 # 执行节奏由 max_initial_concurrency 与 Worker 运行时预算控制,扩批链路不再产出。 row['selected'] = True row['selection_batch'] = 1 planned_bytes += size group_counts: dict[str, int] = defaultdict(int) for row in rows: group_counts[str(row.get('group_key') or 'ungrouped')] += 1 pending_expansion_batches: dict[int, int] = defaultdict(int) for row in rows: planned_batch = int(row.get('planned_selection_batch') or 0) if planned_batch > 1: pending_expansion_batches[planned_batch] += 1 return { 'selection_version': 'shipping_notice_attachment_selection.v1', 'max_initial_attachments': int(max_initial_attachments), 'max_initial_concurrency': int(max_initial_concurrency), 'expansion_batch_size': int(expansion_batch_size), 'max_total_attachments': int(max_total_attachments), 'max_total_bytes': int(max_total_bytes or 0), 'max_runtime_seconds': int(max_runtime_seconds or 0), 'planned_total_bytes': planned_bytes, 'total_attachment_count': len(rows), 'eligible_attachment_count': len(eligible), 'selected_attachment_count': sum(1 for row in rows if row.get('selected')), 'planned_attachment_count': sum( 1 for row in rows if row.get('selected') or int(row.get('planned_selection_batch') or 0) > 1 ), 'pending_expansion_attachment_count': sum(pending_expansion_batches.values()), 'pending_expansion_batches': { str(batch): count for batch, count in sorted(pending_expansion_batches.items()) }, 'group_count': len(group_counts), 'items': rows, }