/** * Utility for parsing, segmenting, and reconstructing Markdown (.md) files. * Preserves section headers, lists, links, bold/italic markup, and spacing. */ /** * Splits a Markdown document into section-level translatable chunks. * Groups content by major headers (###) or logical section blocks. * Reduces 280 tiny fragments down to ~15 complete section chunks! */ export function parseMarkdownToSegments(mdContent) { if (!mdContent || typeof mdContent !== 'string') { return { segments: [], structureMap: [] }; } const normalized = mdContent.replace(/\r\n/g, '\n').trim(); if (!normalized) return { segments: [], structureMap: [] }; // Split by section headers (### or ## or #) const lines = normalized.split('\n'); const sections = []; let currentSection = { header: '', bodyLines: [] }; lines.forEach(line => { const headerMatch = line.match(/^(#{1,6}\s+.*)/); if (headerMatch) { if (currentSection.header || currentSection.bodyLines.length > 0) { sections.push(currentSection); } currentSection = { header: line.trim(), bodyLines: [] }; } else { currentSection.bodyLines.push(line); } }); if (currentSection.header || currentSection.bodyLines.length > 0) { sections.push(currentSection); } // Build segments and structureMap from sections const segments = []; const structureMap = []; sections.forEach((sec, idx) => { const fullText = [sec.header, sec.bodyLines.join('\n')].filter(Boolean).join('\n\n').trim(); if (!fullText) return; const segId = `md_section_${idx + 1}`; segments.push({ id: segId, original: fullText, type: 'section', headerTitle: sec.header ? sec.header.replace(/[\*#]/g, '').trim() : `Section ${idx + 1}` }); structureMap.push({ id: segId, type: 'section' }); }); return { segments, structureMap }; } /** * Generates an optimized, token-efficient Knowledge Base context for a specific segment. */ export function extractSmartMarkdownContext(currentSegmentIndex, segments) { if (!segments || segments.length === 0) return ''; const currentSeg = segments[currentSegmentIndex]; if (!currentSeg) return ''; const topHeaders = segments .slice(0, 6) .map(s => s.headerTitle || '') .filter(Boolean) .join(' | '); const prevTitle = segments[currentSegmentIndex - 1]?.headerTitle || ''; const nextTitle = segments[currentSegmentIndex + 1]?.headerTitle || ''; return `Document Knowledge Base Topics: [${topHeaders}] Current Section: "${currentSeg.headerTitle || 'General FAQ'}" Context Neighbors: "${prevTitle ? 'Prev: ' + prevTitle : ''} ${nextTitle ? '| Next: ' + nextTitle : ''}"`; } /** * Automatically compacts user-provided custom Knowledge Base text if it's long. */ export function compactUserContext(text, maxChars = 1200) { if (!text || typeof text !== 'string') return ''; const trimmed = text.trim(); if (trimmed.length <= maxChars) return trimmed; const lines = trimmed.split('\n').map(l => l.trim()).filter(Boolean); const keyLines = lines.filter(line => { const l = line.toLowerCase(); return l.includes('brand') || l.includes('brend') || l.includes('rule') || l.includes('qayda') || l.includes('term') || l.includes('sözlü') || l.includes('ton') || l.includes('voice') || l.includes('do not') || l.includes('etmə') || l.includes('always') || l.includes('həmişə') || l.includes('never') || l.includes('qətiyyən') || l.includes(':') || l.includes('->'); }); if (keyLines.length >= 2 && keyLines.join('\n').length <= maxChars) { return `[COMPACT KNOWLEDGE SUMMARY]:\n${keyLines.join('\n')}`; } return `${trimmed.slice(0, maxChars)}...\n[User context automatically compacted from ${trimmed.length} characters to ${maxChars}]`; } /** * Reconstructs a Markdown document from translated section chunks. */ export function reconstructMarkdown(structureMap, translatedSegmentsMap) { const reconstructedSections = []; structureMap.forEach(item => { const segData = translatedSegmentsMap[item.id]; if (segData) { const translatedText = segData.claude || segData.translation || segData.original; reconstructedSections.push(translatedText.trim()); } }); return reconstructedSections.join('\n\n'); }