import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts'; import { parseAnalysisVisuals, combineStageDefectVisuals, visualPeriodSummary, visualScopeSummary, type AnalysisVisual } from './analysisVisualsModel.ts'; export type NarrativeKind = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category' | 'defect' | 'trend' | 'composition' | 'crosscheck' | 'action' | 'other'; export interface FocusProductRow { product: string; stage?: 'black' | 'bright' | 'all'; scrapDelta: string; rateChange: string; rateLabel: string; basis: string; detail: string; evidenceRefs: string[]; } export interface NarrativeSection { id: string; title: string; kind: NarrativeKind; markdown: string; narrative: string; tables: string[]; visuals: AnalysisVisual[]; evidenceRefs: string[]; focusProducts?: FocusProductRow[]; } export interface AnalysisNarrativeModel { sections: NarrativeSection[]; evidence: Array<{ ref: string; label: string; context: string }>; evidenceLabels: Record; period: string; scope: string; title: string; } const REF = /\bQ[A-F0-9]{8}\b/g; const refs = (text: string) => [...new Set(text.match(REF) || [])]; const TITLES: Partial> = { overview: '核心结论', stage: '阶段变化', department: '产业部变化', group: '业务分组变化', product: '重点规格', category: '正式报废类别变化', defect: '具体缺陷变化', trend: '期间趋势', composition: '报废构成', crosscheck: '交叉核查线索', action: '优先核查方向' }; export function classifyAnalysisSection(title: string): NarrativeKind { if (/已核对|交叉|联系|关联/.test(title)) return 'crosscheck'; if (/行动|建议|下一步|重点关注|优先核查|后续核查/.test(title)) return 'action'; if (/具体缺陷|源字段|来源.*缺陷|缺角|磕边|隐裂/.test(title)) return 'defect'; if (/正式报废|报废大类|报废类别|类别增减/.test(title)) return 'category'; if (/产业部|部门/.test(title)) return 'department'; if (/业务分组|分组|区域/.test(title)) return 'group'; if (/产品|规格/.test(title)) return 'product'; if (/趋势|历史|逐月|月度走势/.test(title)) return 'trend'; if (/构成|占比|柏拉|帕累托/.test(title)) return 'composition'; if (/阶段|黑片|亮片/.test(title)) return 'stage'; if (/总体|综合|总览|结论|摘要|概览/.test(title)) return 'overview'; return 'other'; } /** 保留代码块和完整原表,仅拆分展示位置。 */ export function narrativeParts(markdown: string): { narrative: string; tables: string[] } { const lines = markdown.split('\n'); const prose: string[] = [], tables: string[] = []; let fenced = false; for (let i = 0; i < lines.length; i += 1) { if (/^\s*```/.test(lines[i])) fenced = !fenced; const cells = (lines[i + 1] || '').trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => cell.trim()); if (!fenced && lines[i].includes('|') && cells.length > 0 && cells.every(cell => /^:?-{3,}:?$/.test(cell))) { const table = [lines[i], lines[++i]]; while (i + 1 < lines.length && lines[i + 1].trim() && lines[i + 1].includes('|')) table.push(lines[++i]); let note = i + 1; while (note < lines.length && !lines[note].trim()) note += 1; // 表格的引用和覆盖说明随明细保留,避免在结论和图之间重复出现。 if (/^\s*\[Q[A-F0-9]{8}\]/.test(lines[note] || '')) { table.push('', lines[note]); i = note; } tables.push(table.join('\n')); prose.push(''); } else prose.push(lines[i]); } return { narrative: prose.join('\n').trim(), tables }; } /** Only the deterministic report's exact table contract is eligible for a compact summary. */ function productTableCells(line: string): string[] { const source = line.trim().replace(/^\|/, '').replace(/(? cell.trim().replaceAll('\\|', '|')); } function focusProductCandidates(sections: NarrativeSection[]): Array> { const candidates: Array> = []; const number = /^(?:[+−-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|—)$/; for (const section of sections) { if (section.kind !== 'product' || !/(重点产品|产品率变化线索)/.test(section.title)) continue; const order = section.title.match(/[((]按(报废增量|当前报废重量|合格率降幅),本次返回前\d+[))]/)?.[1]; if (!order) continue; const stage = section.title.startsWith('黑片') ? '黑片' : section.title.startsWith('亮片') ? '亮片' : ''; for (const table of section.tables) { const lines = table.split('\n'); const headers = productTableCells(lines[0] || ''); const rateLabel = headers[2]?.match(/^(综合率|黑片合格率|亮片合格率):比较期→本期 \/ 变化$/)?.[1]; const tableRefs = refs(lines.filter(line => !line.trim().startsWith('|')).join('\n')); if (headers.length !== 4 || headers[0] !== '规格' || headers[1] !== '本期报废 / 增量(kg)' || headers[3] !== '阶段投入:比较期→本期(kg)' || !rateLabel || tableRefs.length !== 1) continue; for (const line of lines.slice(2)) { if (!line.trim().startsWith('|')) break; const cells = productTableCells(line); if (cells.length !== 4 || !cells[0] || !cells[3]) continue; const weights = cells[1].split(/\s*\/\s*/); const rateParts = cells[2].split(';'); if (weights.length !== 2 || !weights.every(value => number.test(value)) || rateParts.length !== 2 || !/^(?:[\d,.]+%|—)→(?:[\d,.]+%|—)$/.test(rateParts[0]) || !/^(?:(?:上升|下降)[\d,.]+个百分点|持平|不可比)$/.test(rateParts[1])) continue; candidates.push({ product: cells[0], stage: stage === '黑片' ? 'black' : stage === '亮片' ? 'bright' : rateLabel === '黑片合格率' ? 'black' : rateLabel === '亮片合格率' ? 'bright' : 'all', scrapDelta: weights[1], rateChange: rateParts[1], rateLabel, basis: `${stage ? `${stage} · ` : ''}按${order}排序${order === '合格率降幅' ? ',仅作率变化线索' : ''}`, evidenceRefs: tableRefs }); } } } return candidates; } /** Move selected, cited product facts near the conclusion without changing their order or numbers. */ function bringFocusProductsForward(sections: NarrativeSection[]): NarrativeSection[] { const candidates = focusProductCandidates(sections); if (!candidates.length) return sections; const focusProducts: FocusProductRow[] = []; const remaining = sections.map(section => { if (section.kind !== 'action') return section; let fenced = false; let moved = false; const lines = section.narrative.split('\n').filter(line => { if (/^\s*```/.test(line)) fenced = !fenced; if (fenced) return true; const detail = line.match(/^\s*[-*+]\s+(.+)$/)?.[1]; if (!detail) return true; const detailRefs = refs(detail); const matches = candidates.filter(row => detail.startsWith(`${row.product}:`) && detailRefs.length === 1 && row.evidenceRefs[0] === detailRefs[0] && detail.includes(`增量${row.scrapDelta} kg`) && detail.includes(row.rateChange)); // A shared reference with more than one possible row is not enough to choose a scope. if (matches.length !== 1) return true; focusProducts.push({ ...matches[0], detail }); moved = true; return false; }); if (!moved) return section; const narrative = lines.join('\n').trim(); const stillHasAction = /^\s*(?:[-*+]\s+|\d+[.)]\s+)/m.test(narrative); return { ...section, narrative, ...(stillHasAction ? {} : { title: '', kind: 'other' as const }) }; }).filter(section => section.narrative || section.tables.length || section.visuals.length); if (!focusProducts.length) return sections; const insertAt = Math.max(0, remaining.findIndex(section => section.kind === 'overview') + 1); remaining.splice(insertAt, 0, { id: 'focus-product-summary', title: '重点产品', kind: 'product', markdown: '', narrative: '', tables: [], visuals: [], evidenceRefs: [...new Set(focusProducts.flatMap(row => row.evidenceRefs))], focusProducts }); return remaining; } function visualKind(visual: AnalysisVisual): NarrativeKind { const key = (visual as AnalysisVisual & { sectionKey?: string }).sectionKey; if (key?.startsWith('category_')) return 'category'; if (key?.startsWith('defect_')) return 'defect'; if (key && key in TITLES) return key as NarrativeKind; if (visual.type === 'waterfall' || visual.metric === 'composite_impact_pp') return 'stage'; if (visual.type === 'donut' || visual.type === 'pareto') return 'composition'; if (['line', 'area', 'heatmap'].includes(visual.type)) return 'trend'; if (visual.metric.startsWith('source_defect')) return /具体缺陷|来源/.test(visual.title) ? 'defect' : 'category'; if (visual.comparisonPeriod && visual.unit === 'ratio' && visual.categories.length === 2) return visual.metric === 'composite_rate' ? 'overview' : 'stage'; const dimension = (visual as AnalysisVisual & { dimension?: string }).dimension; if (dimension === 'department' || dimension === 'group' || dimension === 'product') return dimension; return classifyAnalysisSection(visual.title); } export function isRateComparison(visual: AnalysisVisual): boolean { return visual.chartable && visual.unit === 'ratio' && !!visual.comparisonPeriod && visual.categories.length === 2 && visual.series.length === 1 && ['composite_rate', 'black_rate', 'bright_rate'].includes(visual.metric) && visual.series[0].values.every(value => value !== null); } export function useCompactRateComparison(visual: AnalysisVisual, question = ''): boolean { return isRateComparison(visual) && !/柱状图|柱形图|条形图|横条图/.test(question); } function additionalScopeNames(visual: AnalysisVisual, primaryScope: Record): string[] { return ['department','group','product','category','defect'].filter(key => visual.scope[key] && visual.scope[key] !== primaryScope[key]) .map(key => String(visual.scope[key])); } function sectionScore(section: NarrativeSection, visual: AnalysisVisual, primaryScope: Record): number { const extraNames = additionalScopeNames(visual, primaryScope); const scopedComparison = extraNames.length > 0 && (isRateComparison(visual) || visual.metric === 'composite_impact_pp'); const kind = scopedComparison ? (visual.scope.product ? 'product' : visual.scope.group ? 'group' : visual.scope.department ? 'department' : visualKind(visual)) : visualKind(visual); if (scopedComparison && !extraNames.every(name => section.markdown.includes(name) || section.title.includes(name))) return Number.NEGATIVE_INFINITY; const matchingRef = visual.evidenceRefs.some(ref => section.evidenceRefs.includes(ref)); let score = section.kind === kind ? 30 : 0; if (kind === 'composition' && section.kind === 'category') score = 25; if (matchingRef) score += 18; if (kind === 'other' && matchingRef && visual.categories.length > 1 && visual.categories.filter(category => section.markdown.includes(category.label)).length >= Math.min(2, visual.categories.length)) score += 35; if (/黑片/.test(section.title) && visual.stage === 'black') score += 8; if (/亮片/.test(section.title) && visual.stage === 'bright') score += 8; const blackOnly = /黑片/.test(section.title) && !/亮片/.test(section.title); const brightOnly = /亮片/.test(section.title) && !/黑片/.test(section.title); if ((blackOnly && visual.stage === 'bright') || (brightOnly && visual.stage === 'black')) return Number.NEGATIVE_INFINITY; // 局部交叉核查必须跟随自身依据,不放入全局缺陷章节。 const localNames = ['department', 'group', 'product'].map(key => visual.scope[key]).filter((value): value is string => typeof value === 'string' && !!value); const namesMentioned = localNames.some(name => section.markdown.includes(name) || section.title.includes(name)); if (kind === 'defect' && localNames.length && matchingRef && section.kind === 'crosscheck') score += 35; if (kind === 'defect' && section.kind === 'defect' && localNames.length && !matchingRef && !namesMentioned) return Number.NEGATIVE_INFINITY; // 多表共用引用时,仍不能把类别图放入总体章节。 if (matchingRef && section.kind !== kind && section.kind !== 'other' && section.kind !== 'crosscheck' && !(kind === 'composition' && section.kind === 'category')) score -= 25; return score; } export function buildAnalysisNarrative(answer: string, rawVisuals: unknown, question = '', additionalEvidenceRefs: string[] = []): AnalysisNarrativeModel { const safe = sanitizeAnalysisDisplayText(answer).replaceAll('\r\n', '\n').replaceAll('\r', '\n'); const visuals = combineStageDefectVisuals(parseAnalysisVisuals(rawVisuals).visuals); const scopeDepth = (visual: AnalysisVisual) => ['department','group','product','category','defect'].filter(key => visual.scope[key]).length; const main = [...visuals].filter(visual => visual.metric === 'composite_rate').sort((a,b) => scopeDepth(a)-scopeDepth(b))[0] || visuals[0]; const primaryScope = main?.scope || {}; const chunks: Array<{ title: string; lines: string[] }> = [{ title: '', lines: [] }]; let fenced = false; for (const line of safe.split('\n')) { if (/^\s*```/.test(line)) fenced = !fenced; const heading = !fenced ? line.match(/^\s*#{1,4}\s+(.+?)\s*#*\s*$/) : null; if (heading) chunks.push({ title: heading[1], lines: [] }); else chunks[chunks.length - 1].lines.push(line); } const sections: NarrativeSection[] = chunks.filter(chunk => chunk.title || chunk.lines.join('').trim()).map((chunk, index) => { const markdown = chunk.lines.join('\n').trim(); const kind = chunk.title ? classifyAnalysisSection(chunk.title) : 'overview'; return { id: `section-${index + 1}`, title: chunk.title || (visuals.length ? '核心结论' : ''), kind, markdown, ...narrativeParts(markdown), visuals: [], evidenceRefs: refs(markdown) }; }); const singleNarrativeSection = sections.length === 1 && ['overview', 'other'].includes(sections[0].kind); for (const visual of visuals) { const scored = sections.map((section, index) => { const score = sectionScore(section, visual, primaryScope); return { index, score: Number.isFinite(score) && singleNarrativeSection && index === 0 && visual.evidenceRefs.some(ref => section.evidenceRefs.includes(ref)) ? Math.max(30, score) : score }; }).sort((a, b) => b.score - a.score); if (scored[0]?.score >= 25) sections[scored[0].index].visuals.push(visual); else { const kind = visualKind(visual); const extraNames = additionalScopeNames(visual, primaryScope); const title = `${extraNames.length ? `${extraNames.join(' / ')} · ` : ''}${TITLES[kind] || visual.title}`; const existing = sections.find(section => !section.markdown && section.kind === kind && section.title === title); if (existing) existing.visuals.push(visual); else sections.push({ id: `section-${sections.length + 1}`, title, kind, markdown: '', narrative: '', tables: [], visuals: [visual], evidenceRefs: visual.evidenceRefs }); } } const allRefs = [...new Set([...additionalEvidenceRefs, ...refs(safe), ...visuals.flatMap(visual => visual.evidenceRefs)])]; const evidenceLabels = Object.fromEntries(allRefs.map((ref, index) => [ref, `依据 ${index + 1}`])); const evidence = allRefs.map(ref => { const charts = visuals.filter(visual => visual.evidenceRefs.includes(ref)); const context = [...new Set(charts.map(visual => `${visual.title} · ${visualPeriodSummary(visual)}${visualScopeSummary(visual.scope) ? ` · ${visualScopeSummary(visual.scope)}` : ''}`))].join(';'); return { ref, label: evidenceLabels[ref], context: context || '分析正文引用的数据依据' }; }); const period = main ? visualPeriodSummary(main) : ''; const scope = main ? visualScopeSummary(main.scope) : ''; const cleanQuestion = sanitizeAnalysisDisplayText(question).trim(); const broad = /分析|原因|整体|总体|情况|变化/.test(cleanQuestion); const topic = main?.type === 'pareto' ? '报废类别柏拉图' : main?.type === 'donut' ? '报废类别构成分析' : main && ['area','line'].includes(main.type) ? '质量趋势分析' : main?.metric === 'composite_rate' ? '质量变化分析' : '质量数据分析'; const title = period && (broad || cleanQuestion.length > 40 || /用.*图|展示|查看/.test(cleanQuestion)) ? `${period} ${topic}` : cleanQuestion || '质量分析报告'; return { sections: bringFocusProductsForward(sections), evidence, evidenceLabels, period, scope, title }; }