优化:按分析章节整合图表解读与完整报告导出
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
|
||||
import { parseAnalysisVisuals, visualPeriodSummary, visualScopeSummary, type AnalysisVisual } from './analysisVisualsModel.ts';
|
||||
|
||||
export type NarrativeKind = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category' | 'defect' | 'trend' | 'composition' | 'crosscheck' | 'action' | 'other';
|
||||
export interface NarrativeSection {
|
||||
id: string;
|
||||
title: string;
|
||||
kind: NarrativeKind;
|
||||
markdown: string;
|
||||
narrative: string;
|
||||
tables: string[];
|
||||
visuals: AnalysisVisual[];
|
||||
evidenceRefs: string[];
|
||||
}
|
||||
export interface AnalysisNarrativeModel {
|
||||
sections: NarrativeSection[];
|
||||
evidence: Array<{ ref: string; label: string; context: string }>;
|
||||
evidenceLabels: Record<string, string>;
|
||||
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<Record<NarrativeKind, string>> = { 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 };
|
||||
}
|
||||
|
||||
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, unknown>): 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<string, unknown>): 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 = ''): AnalysisNarrativeModel {
|
||||
const safe = sanitizeAnalysisDisplayText(answer).replaceAll('\r\n', '\n').replaceAll('\r', '\n');
|
||||
const visuals = 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([...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, evidence, evidenceLabels, period, scope, title };
|
||||
}
|
||||
Reference in New Issue
Block a user