/** * Content Analyzer - Extracts Structure from Raw Content * * Uses expert methodologies to analyze content and extract: * - SCQA structure (Barbara Minto) * - Sparkline narrative arc (Nancy Duarte) * - Key messages (Rule of Three) * - Sections with headers, bullets, metrics * - Presentation type detection * * Fully integrated with KnowledgeGateway for expert principles. */ import { getKnowledgeGateway, KnowledgeGateway, PresentationType } from '../kb/KnowledgeGateway.js'; export interface ContentSection { header: string; level: number; content: string; bullets: string[]; metrics: Array<{ value: string; label: string; context?: string }>; } export interface ContentAnalysis { detectedType: PresentationType; title: string; sections: ContentSection[]; keyMessages: string[]; dataPoints: Array<{ value: string; label: string; context?: string }>; scqa: { situation: string; complication: string; question: string; answer: string; }; sparkline: { whatIs: string[]; whatCouldBe: string[]; callToAdventure: string; }; // Required by types/index.ts titles: string[]; starMoments: string[]; estimatedSlideCount: number; } export class ContentAnalyzer { private kb!: KnowledgeGateway; // Signal words for SCQA detection private readonly situationSignals = [ 'currently', 'today', 'at present', 'historically', 'traditionally', 'as of', 'our', 'the market', 'industry', 'context', 'background' ]; private readonly complicationSignals = [ 'however', 'but', 'unfortunately', 'challenge', 'problem', 'issue', 'risk', 'threat', 'concern', 'difficulty', 'obstacle', 'barrier', 'yet', 'although', 'despite', 'while', 'crisis', 'gap', 'broken' ]; private readonly answerSignals = [ 'therefore', 'thus', 'recommend', 'propose', 'suggest', 'solution', 'answer', 'strategy', 'approach', 'plan', 'we should', 'must', 'need to', 'the answer', 'introducing', 'presenting', 'platform' ]; // CTA signals - used to filter these OUT of answer detection private readonly ctaSignals = [ 'contact', 'call us', 'email', 'schedule', 'sign up', 'register', 'next steps', 'get started', 'reach out', 'visit', 'follow' ]; // Type detection signals private readonly typeSignals: Record = { ted_keynote: ['inspire', 'vision', 'imagine', 'dream', 'transform', 'story', 'journey'], sales_pitch: ['buy', 'purchase', 'pricing', 'offer', 'deal', 'discount', 'roi', 'value'], consulting_deck: ['recommend', 'analysis', 'assessment', 'strategy', 'findings', 'options', 'mece'], investment_banking: ['valuation', 'dcf', 'multiple', 'enterprise value', 'ebitda', 'ipo', 'm&a'], investor_pitch: ['investment', 'funding', 'series', 'traction', 'market size', 'tam', 'runway'], technical_presentation: ['architecture', 'api', 'system', 'implementation', 'code', 'database', 'deploy'], all_hands: ['team', 'quarter', 'update', 'progress', 'celebrate', 'recognize', 'company'] }; async initialize(): Promise { this.kb = await getKnowledgeGateway(); } /** * Analyze content and extract structural elements. */ async analyze(content: string, contentType: string): Promise { await this.initialize(); // Parse and normalize content const text = this.parseContent(content, contentType); // Extract title from first header const title = this.extractTitle(text); // Detect presentation type const detectedType = this.detectPresentationType(text); console.log(` ✓ Detected type: ${detectedType}`); // Extract sections const sections = this.extractSections(text); console.log(` ✓ Found ${sections.length} sections`); // Extract SCQA structure const scqa = this.extractSCQA(text); // Extract Sparkline elements const sparkline = this.extractSparkline(text); // Extract key messages (max 3 - Rule of Three from Carmine Gallo) const keyMessages = this.extractKeyMessages(text); // Extract data points (metrics, numbers, percentages) const dataPoints = this.extractDataPoints(text); console.log(` ✓ Found ${dataPoints.length} data points`); // Extract titles from sections const titles = sections.map(s => s.header).filter(h => h.length > 0); // Extract STAR moments (bold statements, key insights) const starMoments = this.extractStarMoments(text); // Estimate slide count based on sections and content const estimatedSlideCount = Math.max(5, sections.length + 3); // sections + title + situation + thank you return { detectedType, title, sections, keyMessages, dataPoints, scqa: { situation: scqa.situation || '', complication: scqa.complication || '', question: scqa.question || '', answer: scqa.answer || '' }, sparkline: { whatIs: sparkline.callToAction ? [sparkline.callToAction] : [], whatCouldBe: keyMessages, callToAdventure: sparkline.callToAction || '' }, titles, starMoments, estimatedSlideCount }; } /** * Parse content based on type */ private parseContent(content: string, contentType: string): string { if (contentType === 'markdown' || content.includes('#') || content.includes('- ')) { return content; } return content; } /** * Extract the main title from content */ private extractTitle(text: string): string { // Look for H1 header const h1Match = text.match(/^#\s+(.+)$/m); if (h1Match && h1Match[1]) { return h1Match[1].replace(/\*\*/g, '').trim(); } // Look for first significant line const lines = text.split('\n').filter(l => l.trim().length > 0); if (lines.length > 0 && lines[0]) { return lines[0].replace(/^#+\s*/, '').replace(/\*\*/g, '').trim().slice(0, 80); } return 'Presentation'; } /** * Detect presentation type from content signals */ private detectPresentationType(text: string): PresentationType { const lowerText = text.toLowerCase(); const scores: Record = { ted_keynote: 0, sales_pitch: 0, consulting_deck: 0, investment_banking: 0, investor_pitch: 0, technical_presentation: 0, all_hands: 0 }; for (const [type, signals] of Object.entries(this.typeSignals)) { for (const signal of signals) { if (lowerText.includes(signal)) { scores[type as PresentationType]++; } } } // Find highest scoring type let maxScore = 0; let detectedType: PresentationType = 'consulting_deck'; // Default for (const [type, score] of Object.entries(scores)) { if (score > maxScore) { maxScore = score; detectedType = type as PresentationType; } } return detectedType; } /** * Extract sections from content (headers, bullets, content) */ private extractSections(text: string): ContentSection[] { const sections: ContentSection[] = []; const lines = text.split('\n'); let currentSection: ContentSection | null = null; let contentLines: string[] = []; for (const line of lines) { const trimmedLine = line.trim(); // Check for header const headerMatch = trimmedLine.match(/^(#{1,6})\s+(.+)$/); if (headerMatch) { // Save previous section if (currentSection) { currentSection.content = contentLines.join('\n').trim(); if (currentSection.header || currentSection.content || currentSection.bullets.length > 0) { sections.push(currentSection); } } // Start new section currentSection = { header: (headerMatch[2] || '').replace(/\*\*/g, '').trim(), level: (headerMatch[1] || '').length, content: '', bullets: [], metrics: [] }; contentLines = []; continue; } // Check for bullet const bulletMatch = trimmedLine.match(/^[-*+]\s+(.+)$/); if (bulletMatch && bulletMatch[1] && currentSection) { currentSection.bullets.push(bulletMatch[1]); continue; } // Check for numbered item const numberedMatch = trimmedLine.match(/^\d+\.\s+(.+)$/); if (numberedMatch && numberedMatch[1] && currentSection) { currentSection.bullets.push(numberedMatch[1]); continue; } // Check for metrics (numbers with context) const metricMatch = trimmedLine.match(/\$?([\d,]+\.?\d*)[%]?\s*[-–—:]\s*(.+)/); if (metricMatch && metricMatch[1] && metricMatch[2] && currentSection) { currentSection.metrics.push({ value: metricMatch[1], label: metricMatch[2].slice(0, 50) }); continue; } // Check for table row (extract metrics) if (trimmedLine.includes('|') && currentSection) { const cells = trimmedLine.split('|').map(c => c.trim()).filter(c => c && !c.match(/^-+$/)); if (cells.length >= 2) { const value = cells.find(c => c.match(/^\$?[\d,]+\.?\d*[%]?$/)); const label = cells.find(c => !c.match(/^\$?[\d,]+\.?\d*[%]?$/) && c.length > 2); if (value && label) { currentSection.metrics.push({ value, label: label.slice(0, 50) }); } } continue; } // Regular content if (trimmedLine && currentSection) { contentLines.push(trimmedLine); } } // Save last section if (currentSection) { currentSection.content = contentLines.join('\n').trim(); if (currentSection.header || currentSection.content || currentSection.bullets.length > 0) { sections.push(currentSection); } } return sections; } /** * Extract SCQA structure (Barbara Minto) */ private extractSCQA(text: string): { situation: string; complication: string; question: string; answer: string } { const paragraphs = text.split(/\n\n+/).filter(p => p.trim()); let situation = ''; let complication = ''; let question = ''; let answer = ''; // Find situation for (const para of paragraphs.slice(0, 3)) { if (this.containsSignals(para.toLowerCase(), this.situationSignals)) { situation = this.extractFirstSentence(para); break; } } // Find complication for (const para of paragraphs) { if (this.containsSignals(para.toLowerCase(), this.complicationSignals)) { complication = this.extractFirstSentence(para); break; } } // Find answer/solution - look in middle 60% of document, avoid CTAs at end const middleStart = Math.floor(paragraphs.length * 0.2); const middleEnd = Math.floor(paragraphs.length * 0.8); for (const para of paragraphs.slice(middleStart, middleEnd)) { const lowerPara = para.toLowerCase(); // Must have answer signal but NOT be a CTA if (this.containsSignals(lowerPara, this.answerSignals) && !this.containsSignals(lowerPara, this.ctaSignals)) { answer = this.extractFirstSentence(para); break; } } // Fallback: use first and last paragraphs if (!situation && paragraphs.length > 0 && paragraphs[0]) { situation = this.extractFirstSentence(paragraphs[0]); } // Don't use last paragraph as fallback - it's usually a CTA if (!answer && paragraphs.length > 2) { // Try to find a recommendation in the first half for (const para of paragraphs.slice(1, Math.floor(paragraphs.length * 0.5))) { const lowerPara = para.toLowerCase(); if (lowerPara.includes('recommend') || lowerPara.includes('strategy') || lowerPara.includes('solution') || lowerPara.includes('approach')) { answer = this.extractFirstSentence(para); break; } } } // Generate implicit question from complication if (complication && !question) { question = `How do we address: ${complication.slice(0, 80)}?`; } return { situation, complication, question, answer }; } /** * Extract STAR moments (Something They'll Always Remember) * Per Nancy Duarte: These should be memorable, COMPLETE thoughts with impact * * CRITICAL REQUIREMENTS: * - Must be complete sentences with subject + verb structure * - Must have 5+ words minimum (no fragments!) * - Must be 30+ characters * - Must contain a verb * - NOT fragments like "significant growth" or "cloud-first strategy" * - NOT headers or topic labels */ private extractStarMoments(text: string): string[] { const starMoments: string[] = []; const usedPhrases = new Set(); // Fragment patterns to reject (common marketing fragments) const fragmentPatterns = [ /^[a-z]+-[a-z]+\s+(strategy|approach|solution|platform|architecture)$/i, // "cloud-first strategy" /^(significant|substantial|dramatic|rapid|strong)\s+(growth|increase|decline|change)$/i, // "significant growth" /^(digital|cloud|data|ai)\s+(transformation|strategy|platform|solution)$/i, // "digital transformation" /^(our|your|the|a)\s+\w+\s*$/i, // "our solution", "the platform" /^[a-z]+\s+[a-z]+$/i, // Any two-word phrase ]; // Verb patterns that indicate complete sentences const verbPatterns = /\b(is|are|was|were|will|can|could|should|must|has|have|had|does|do|provides?|enables?|allows?|offers?|delivers?|creates?|achieves?|exceeds?|results?|generates?|grows?|increases?|decreases?|transforms?|improves?|reduces?)\b/i; // Look for bold statements that are COMPLETE SENTENCES const boldMatches = text.match(/\*\*([^*]+)\*\*/g); if (boldMatches) { for (const match of boldMatches) { const cleaned = match.replace(/\*\*/g, '').trim(); const lowerCleaned = cleaned.toLowerCase(); const wordCount = cleaned.split(/\s+/).length; const normalized = cleaned.toLowerCase().slice(0, 30); // STRICT requirements for STAR moments: const hasVerb = verbPatterns.test(cleaned); const isLongEnough = wordCount >= 5 && cleaned.length >= 30; const isNotFragment = !fragmentPatterns.some(p => p.test(cleaned)); const isNotHeader = !/^(The |Our |Your |Next |Key |Overview|Introduction|Conclusion|Summary|Background)/i.test(cleaned); const isNotCTA = !this.containsSignals(lowerCleaned, this.ctaSignals); const hasMetricContext = /\d+[%xX]|\$[\d,]+/.test(cleaned) && wordCount >= 5; if ((hasVerb || hasMetricContext) && isLongEnough && isNotFragment && isNotHeader && isNotCTA && wordCount <= 25 && !usedPhrases.has(normalized)) { starMoments.push(cleaned); usedPhrases.add(normalized); if (starMoments.length >= 3) break; } } } // Look for sentences with dramatic metrics (must be complete sentences) if (starMoments.length < 3) { // CRITICAL: Clean markdown headers BEFORE sentence matching // Otherwise sentences span headers because headers have no periods const cleanedText = text .replace(/^#+\s+.+$/gm, '') // Remove header lines .replace(/\*\*/g, '') // Remove bold markers .replace(/\|/g, ' ') // Remove table pipes .replace(/-{3,}/g, '') // Remove separator lines .replace(/\n{2,}/g, '\n') // Normalize line breaks .trim(); const sentences = cleanedText.match(/[^.!?]+[.!?]/g) || []; for (const sentence of sentences) { const cleaned = sentence.trim(); const normalized = cleaned.toLowerCase().slice(0, 30); const wordCount = cleaned.split(/\s+/).length; // High-impact metrics with complete sentence structure const hasHighImpact = /(\d{2,3}%|\d+x|billion|million|\$[\d,]+\s*(million|billion)?)/i.test(cleaned); const hasVerb = verbPatterns.test(cleaned); if (hasHighImpact && hasVerb && wordCount >= 6 && wordCount <= 25 && cleaned.length >= 40 && cleaned.length <= 200 && !usedPhrases.has(normalized) && !this.containsSignals(cleaned.toLowerCase(), this.ctaSignals)) { starMoments.push(cleaned); usedPhrases.add(normalized); if (starMoments.length >= 3) break; } } } return starMoments.slice(0, 3); } /** * Extract Sparkline elements (Nancy Duarte) */ private extractSparkline(text: string): { callToAction: string } { const paragraphs = text.split(/\n\n+/).filter(p => p.trim()); // Look for call to action near the end let callToAction = ''; const ctaSignals = ['next steps', 'call to action', 'take action', 'start now', 'join us', 'contact']; for (const para of paragraphs.slice(-3)) { if (this.containsSignals(para.toLowerCase(), ctaSignals)) { callToAction = this.extractFirstSentence(para); break; } } return { callToAction }; } /** * Extract key messages - the actual insights from the content * Per Carmine Gallo: Rule of Three - max 3 key messages * Per Barbara Minto: Messages should be actionable conclusions, not topics */ private extractKeyMessages(text: string): string[] { const messages: string[] = []; const usedPhrases = new Set(); // Clean text for extraction let cleanText = text .replace(/^#+\s+.+$/gm, '') // Remove headers .replace(/\[.+?\]/g, '') // Remove markdown links .replace(/\*\*/g, ''); // Remove bold markers // CRITICAL: Protect decimal numbers from sentence splitting // Replace periods in numbers with a placeholder cleanText = cleanText.replace(/(\d)\.(\d)/g, '$1$2'); // Split into sentences const rawSentences = cleanText.match(/[^.!?]+[.!?]/g) || []; // Restore decimal points const sentences = rawSentences.map(s => s.replace(//g, '.')); // Key message signals - sentences that contain insights const insightSignals = [ 'we recommend', 'we suggest', 'our strategy', 'the solution', 'key finding', 'result', 'achieve', 'improve', 'increase', 'decrease', 'expect', 'roi', 'benefit', 'opportunity', 'transform' ]; // First pass: find sentences with recommendation/insight language for (const sentence of sentences) { const cleaned = sentence.trim(); const normalized = cleaned.toLowerCase().slice(0, 30); if (cleaned.length > 30 && cleaned.length < 150 && !usedPhrases.has(normalized) && !this.containsSignals(cleaned.toLowerCase(), this.ctaSignals)) { if (this.containsSignals(cleaned.toLowerCase(), insightSignals)) { messages.push(cleaned); usedPhrases.add(normalized); if (messages.length >= 3) break; } } } // Second pass: if not enough, get sentences with metrics if (messages.length < 3) { for (const sentence of sentences) { const cleaned = sentence.trim(); const normalized = cleaned.toLowerCase().slice(0, 30); if (cleaned.length > 25 && cleaned.length < 150 && !usedPhrases.has(normalized) && /\d+[%xX]|\$[\d,]+/.test(cleaned)) { messages.push(cleaned); usedPhrases.add(normalized); if (messages.length >= 3) break; } } } // Third pass: get substantive sentences (not just labels) if (messages.length < 2) { for (const sentence of sentences) { const cleaned = sentence.trim(); const wordCount = cleaned.split(/\s+/).length; const normalized = cleaned.toLowerCase().slice(0, 30); // Must be a real sentence with verb-like structure if (wordCount >= 6 && wordCount <= 25 && !usedPhrases.has(normalized) && /\b(is|are|will|can|should|must|has|have|provides?|enables?|allows?)\b/.test(cleaned.toLowerCase())) { messages.push(cleaned); usedPhrases.add(normalized); if (messages.length >= 3) break; } } } return messages.slice(0, 3); } /** * Extract data points (metrics with values) * IMPROVED: Smarter label extraction that understands markdown tables */ private extractDataPoints(text: string): Array<{ value: string; label: string; context?: string }> { const dataPoints: Array<{ value: string; label: string; context?: string }> = []; const usedValues = new Set(); // First: Parse markdown tables properly const tableLines = text.split('\n').filter(line => line.includes('|')); if (tableLines.length >= 3) { const dataRows = tableLines.filter(line => !line.match(/^[\s|:-]+$/)); if (dataRows.length >= 2) { for (const row of dataRows.slice(1)) { const cells = row.split('|').map(c => c.trim()).filter(c => c.length > 0); if (cells.length >= 2) { const valueCell = cells.find(c => /^\$?[\d,]+\.?\d*[MBK%]?$/.test(c.replace(/[,$]/g, ''))); const labelCell = cells[0]; if (valueCell && labelCell && !usedValues.has(valueCell)) { usedValues.add(valueCell); dataPoints.push({ value: valueCell, label: labelCell.slice(0, 40) }); } } } } } // Second: Match inline metrics with preceding context const lines = text.split('\n'); for (const line of lines) { if (line.includes('|')) continue; // Skip table rows // Match patterns like "revenue increasing by 45%" const percentMatch = line.match(/(\w+(?:\s+\w+){0,4})\s+(?:by\s+)?(\d+(?:\.\d+)?%)/i); if (percentMatch && percentMatch[2] && percentMatch[1] && !usedValues.has(percentMatch[2])) { usedValues.add(percentMatch[2]); dataPoints.push({ value: percentMatch[2], label: percentMatch[1].slice(0, 40) }); } // Match patterns like "$2.5 million annually" const dollarMatch = line.match(/\$(\d+(?:\.\d+)?)\s*(million|billion|M|B|K)?/i); if (dollarMatch && dataPoints.length < 6) { const fullValue = '$' + dollarMatch[1] + (dollarMatch[2] ? ' ' + dollarMatch[2] : ''); if (!usedValues.has(fullValue)) { usedValues.add(fullValue); const label = this.extractLabelFromLine(line, fullValue); dataPoints.push({ value: fullValue, label }); } } } return dataPoints.slice(0, 4); } /** * Extract a meaningful label from a line containing a metric */ private extractLabelFromLine(line: string, value: string): string { const cleaned = line.replace(/\*\*/g, '').replace(/\|/g, ' ').trim(); const beforeValue = cleaned.split(value)[0] || ''; const words = beforeValue.split(/\s+/).filter(w => w.length > 2); return words.slice(-4).join(' ').slice(0, 40) || 'Value'; } /** * Check if text contains any of the signals */ private containsSignals(text: string, signals: string[]): boolean { return signals.some(signal => text.includes(signal)); } /** * Extract first meaningful sentence from text * CRITICAL: Must strip headers, CTA text, and fragments */ private extractFirstSentence(text: string): string { // Remove all markdown headers (lines starting with #) let cleaned = text .replace(/^#+\s+.+$/gm, '') // Full header lines .replace(/\*\*/g, '') // Bold markers .replace(/\|/g, ' ') // Table pipes .replace(/-{3,}/g, '') // Separator lines .replace(/\n{2,}/g, '\n') // Multiple newlines .trim(); // Remove common section header patterns that might remain cleaned = cleaned .replace(/^(Overview|Introduction|The Problem|Our Solution|Next Steps|Conclusion|Summary|Background|Context|Recommendation)\s*:?\s*/i, '') .trim(); // Split into sentences and find the first substantive one const sentences = cleaned.match(/[^.!?]+[.!?]/g) || []; for (const sentence of sentences) { const trimmed = sentence.trim(); // Must be 20+ chars and have verb-like structure if (trimmed.length >= 20 && /\b(is|are|was|were|will|can|should|must|has|have|had|provides?|enables?|allows?|offers?|delivers?|creates?|includes?|involves?|requires?|experiencing)\b/i.test(trimmed) && !this.containsSignals(trimmed.toLowerCase(), this.ctaSignals)) { return trimmed.slice(0, 150); } } // Fallback: take first 150 chars if nothing else works const fallback = cleaned.slice(0, 150); return fallback.length >= 20 ? fallback : ''; } } /** * Initialize and return a ContentAnalyzer instance */ export async function initContentAnalyzer(): Promise { const analyzer = new ContentAnalyzer(); await analyzer.initialize(); return analyzer; }