// ---------- Сравнение текстов (Левенштейн) и doCompare ---------- function normalize(text) { return text.toLowerCase().replace(/[.,!?;:«»"'’]/g, '').trim(); } function levenshtein(a, b) { const m = a.length, n = b.length; const dp = Array.from({length: m+1}, (_,i) => [i]); for (let j=0; j<=n; j++) dp[0][j] = j; for (let i=1; i<=m; i++) for (let j=1; j<=n; j++) dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]); return dp[m][n]; } function wordSimilarity(a, b) { const maxLen = Math.max(a.length, b.length); if (maxLen === 0) return 1; return 1 - levenshtein(a, b) / maxLen; } function compareTexts(original, transcribed) { const a = normalize(original).split(/\s+/); const b = normalize(transcribed).split(/\s+/); let totalScore = 0; const result = a.map(word => { let best = 0, bestMatch = ''; for (const t of b) { const sim = wordSimilarity(word, t); if (sim > best) { best = sim; bestMatch = t; } } totalScore += best; const quality = best >= 0.8 ? 'ok' : best >= 0.5 ? 'near' : 'bad'; return { word, quality, bestMatch, score: Math.round(best*100) }; }); const score = Math.round((totalScore / a.length) * 100); return { score, words: result }; } function renderDiff(words) { return words.map(({ word, quality, bestMatch, score }) => { const color = quality === 'ok' ? 'green' : quality === 'near' ? '#e6a800' : 'red'; const tip = quality !== 'ok' ? ` → ${bestMatch} (${score}%)` : ''; return `${word}${tip}`; }).join(' '); } async function doCompare(blob, originalText, duration) { if (isAnalyzing) return ''; isAnalyzing = true; const startTime = Date.now(); const timerId = setInterval(() => { const elapsed = ((Date.now() - startTime) / 1000).toFixed(1); setStatus('Анализ... ' + elapsed + 'с'); }, 150); let whisperResult; try { whisperResult = await transcribe(blob); } catch(e) { clearInterval(timerId); isAnalyzing = false; setStatus('Ошибка анализа.'); return ''; } clearInterval(timerId); let recHTML = '', diffHTML = ''; if (whisperResult.text) { const _transcribed = whisperResult.text; const { score, words } = compareTexts(originalText, whisperResult.text); const recEmoji = score >= 90 ? '🟢' : score >= 70 ? '🟡' : '🔴'; recHTML = recEmoji + ' Распознание: ' + score + '% | 🗣 ' + whisperResult.text + ''; diffHTML = '