revert: откат до v48 — убраны v49-v53 (close/race/onopen костыли)

This commit is contained in:
“Naeel”
2026-05-22 17:32:11 +04:00
parent f4957437db
commit 3442e5d031
+24 -51
View File
@@ -53,7 +53,7 @@ let mediaRecorder, audioChunks = [], userAudioBlob = null, ttsText = '';
let isRecording = false, isAnalyzing = false, micAnalyser = null, micAnimId = null; let isRecording = false, isAnalyzing = false, micAnalyser = null, micAnimId = null;
let recordStartTime = 0, recordDuration = 0; let recordStartTime = 0, recordDuration = 0;
// ---------- Версия ---------- // ---------- Версия ----------
const VERSION = 'v53'; const VERSION = 'v48';
document.getElementById('ver').textContent = VERSION; document.getElementById('ver').textContent = VERSION;
// ---------- Перевод на русский (Groq) ---------- // ---------- Перевод на русский (Groq) ----------
@@ -221,28 +221,19 @@ async function doCompare(blob, originalText, duration) {
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1); const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
setStatus('Анализ... ' + elapsed + 'с'); setStatus('Анализ... ' + elapsed + 'с');
}, 150); }, 150);
let whisperResult, phon;
// Шаг 1: транскрипция (быстро, ~0.5с)
let whisperResult = { text: '', error: null };
try { whisperResult = await transcribe(blob); }
catch(e) { console.log('[COMPARE] transcribe failed:', e); }
// Шаг 2: фонетика (может виснуть на decodeAudioData, таймаут 10с)
let phon = { pitchHz: 0, pitchStability: 0, voiceClarity: 0, phonScore: 0 };
try { try {
phon = await Promise.race([ [whisperResult, phon] = await Promise.all([
phoneticAnalysis(blob), transcribe(blob),
new Promise(r => setTimeout(() => r({ pitchHz: 0, pitchStability: 0, voiceClarity: 0, phonScore: 0 }), 10000)) phoneticAnalysis(blob)
]); ]);
} catch(e) { console.log('[COMPARE] phonetics failed:', e); } } catch(e) {
clearInterval(timerId); clearInterval(timerId);
isAnalyzing = false; isAnalyzing = false;
setStatus('Ошибка анализа.');
if (whisperResult.error && !whisperResult.text) {
setStatus('Ошибка: ' + (whisperResult.error || 'сеть'));
return ''; return '';
} }
clearInterval(timerId);
const phonEmoji = phon.phonScore >= 85 ? '🟢' : phon.phonScore >= 60 ? '🟡' : '🔴'; const phonEmoji = phon.phonScore >= 85 ? '🟢' : phon.phonScore >= 60 ? '🟡' : '🔴';
let recHTML = '', diffHTML = ''; let recHTML = '', diffHTML = '';
@@ -273,6 +264,7 @@ async function doCompare(blob, originalText, duration) {
'</div>'; '</div>';
setStatus('Готово.'); setStatus('Готово.');
isAnalyzing = false;
return whisperResult.text || ''; return whisperResult.text || '';
} }
@@ -620,13 +612,10 @@ async function transcribe(blob) {
if (!GROQ_API_KEY) return { text: '', error: 'no_key' }; if (!GROQ_API_KEY) return { text: '', error: 'no_key' };
const tStart = performance.now(); const tStart = performance.now();
// Кодируем blob в base64 (только текстовые WS-фреймы — DPI не режет)
const base64 = await new Promise((resolve, reject) => { const base64 = await new Promise((resolve, reject) => {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = () => { reader.onload = () => resolve(reader.result.split(',')[1]);
const b64 = reader.result;
if (typeof b64 !== 'string') reject(new Error('not string'));
else resolve(b64.split(',')[1] || b64);
};
reader.onerror = reject; reader.onerror = reject;
reader.readAsDataURL(blob); reader.readAsDataURL(blob);
}); });
@@ -634,44 +623,28 @@ async function transcribe(blob) {
console.log('[WS] b64=' + (base64.length/1024).toFixed(1) + 'KB'); console.log('[WS] b64=' + (base64.length/1024).toFixed(1) + 'KB');
return new Promise((resolve) => { return new Promise((resolve) => {
let settled = false; try {
const done = (r) => { if (settled) return; settled = true; resolve(r); };
const payload = JSON.stringify({ token: GROQ_API_KEY, audio_b64: base64, mime: blob.type || 'audio/webm' });
const ws = new WebSocket('wss://proxy.kube5s.ru/ws'); const ws = new WebSocket('wss://proxy.kube5s.ru/ws');
const timeout = setTimeout(() => { console.log('[WS] timeout'); try { ws.close(); } catch(e){} done({ text: '', error: 'timeout' }); }, 15000); const timeout = setTimeout(() => {
console.log('[WS] timeout'); ws.close(); resolve({ text: '', error: 'timeout' });
}, 60000);
const trySend = () => { ws.onopen = () => {
if (settled) return; ws.send(JSON.stringify({ token: GROQ_API_KEY, audio_b64: base64, mime: blob.type || 'audio/webm' }));
const st = ws.readyState; console.log('[WS] sent');
if (st === WebSocket.OPEN) {
try { ws.send(payload); console.log('[WS] sent'); } catch(e) { console.log('[WS] send err:', e); clearTimeout(timeout); done({ text: '', error: 'network' }); }
return;
}
if (st === WebSocket.CONNECTING) { setTimeout(trySend, 20); return; }
console.log('[WS] aborted, state=' + st);
clearTimeout(timeout);
done({ text: '', error: 'network' });
}; };
ws.onopen = trySend;
trySend();
ws.onmessage = (e) => { ws.onmessage = (e) => {
clearTimeout(timeout); clearTimeout(timeout); ws.close();
try { ws.close(); } catch(ex) {}
try {
const data = JSON.parse(e.data); const data = JSON.parse(e.data);
console.log('[WS] ← ' + ((performance.now()-tStart)/1000).toFixed(2) + 's → ' + (data.text||'(empty)')); console.log('[WS] ← ' + ((performance.now()-tStart)/1000).toFixed(2) + 's → ' + (data.text||'(empty)'));
done(data.error ? { text: '', error: data.error } : { text: data.text || '', error: null }); resolve(data.error ? { text: '', error: data.error } : { text: data.text || '', error: null });
} catch(ex) {
console.log('[WS] parse err:', ex);
done({ text: '', error: 'parse' });
}
}; };
ws.onerror = () => { console.log('[WS] error'); clearTimeout(timeout); done({ text: '', error: 'network' }); }; ws.onerror = () => { clearTimeout(timeout); resolve({ text: '', error: 'network' }); };
ws.onclose = (e) => { console.log('[WS] close code=' + e.code); /* не резолвим — клиент сам закрывает после onmessage */ }; } catch (err) {
resolve({ text: '', error: 'network' });
}
}); });
} }