translet-test / record.html
bllndebrahim's picture
Upload folder using huggingface_hub
a93af78 verified
Raw History Blame Contribute Delete
19.7 kB
<!doctype html>
<html lang="ckb" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>تۆمارکردنی دەنگ</title>
<link rel="icon" type="image/x-icon" href="lala-icon.ico">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;800&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<style>
:root {
--bg: #f6f5f2; --card: #ffffff; --text: #1d1d1f; --dim: #6b6b70; --line: #e4e2dc;
--accent: #c8102e; --accent-soft: #fde8ea; --ok: #1f8a4c; --ok-soft: #e3f4ea; --warn: #b26a00; --warn-soft: #fff3dc;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #0d0d10; --card: #17171c; --text: #f1f1f3; --dim: #9a9aa3; --line: #2a2a31;
--accent: #ff3b52; --accent-soft: #3a1219; --ok: #3ccf7a; --ok-soft: #102a1b; --warn: #ffb547; --warn-soft: #33250c;
}
}
:root[data-theme="dark"] {
--bg: #0d0d10; --card: #17171c; --text: #f1f1f3; --dim: #9a9aa3; --line: #2a2a31;
--accent: #ff3b52; --accent-soft: #3a1219; --ok: #3ccf7a; --ok-soft: #102a1b; --warn: #ffb547; --warn-soft: #33250c;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font-family: 'Vazirmatn', system-ui, sans-serif; }
.wrap { max-width: 760px; margin: 0 auto; padding: 20px 16px 120px; }
h1 { font-size: 22px; margin: 4px 0 2px; }
.sub { color: var(--dim); font-size: 14px; margin-bottom: 16px; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 18px; padding: 18px; margin-bottom: 14px; }
details summary { cursor: pointer; font-weight: 600; }
details ul { margin: 10px 0 0; padding-right: 20px; line-height: 1.9; color: var(--dim); font-size: 15px; }
.progress-row { display: flex; justify-content: space-between; align-items: center; font-size: 14px; color: var(--dim); margin-bottom: 8px; gap: 8px; flex-wrap: wrap; }
.bar { height: 8px; background: var(--line); border-radius: 99px; overflow: hidden; }
.bar > div { height: 100%; background: var(--ok); width: 0; transition: width .3s; }
.sentence { font-size: clamp(24px, 6vw, 34px); line-height: 1.7; font-weight: 600; text-align: center; min-height: 140px; display: flex; align-items: center; justify-content: center; padding: 18px 6px; }
.num { text-align: center; color: var(--dim); font-size: 14px; }
.status { text-align: center; font-size: 15px; min-height: 26px; margin: 6px 0 12px; }
.status.ok { color: var(--ok); } .status.warn { color: var(--warn); } .status.rec { color: var(--accent); font-weight: 600; }
.meter { height: 10px; background: var(--line); border-radius: 99px; overflow: hidden; margin: 0 auto 16px; max-width: 360px; }
.meter > div { height: 100%; width: 0; background: var(--ok); transition: width .06s; }
.controls { display: flex; justify-content: center; align-items: center; gap: 14px; flex-wrap: wrap; }
button { font-family: inherit; border: 1px solid var(--line); background: var(--card); color: var(--text); border-radius: 14px; padding: 12px 16px; font-size: 16px; cursor: pointer; }
button:disabled { opacity: .4; cursor: not-allowed; }
.rec-btn { width: 92px; height: 92px; border-radius: 50%; background: var(--accent); color: #fff; border: none; font-size: 15px; font-weight: 800; box-shadow: 0 6px 20px rgba(200,16,46,.35); }
.rec-btn.recording { animation: pulse 1.2s infinite; background: #8b0a1f; }
@keyframes pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.07); } }
.done-badge { display: inline-block; background: var(--ok-soft); color: var(--ok); border-radius: 99px; padding: 2px 10px; font-size: 13px; }
.row { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
.primary { background: var(--ok); color: #fff; border: none; font-weight: 700; }
.note { font-size: 13px; color: var(--dim); text-align: center; margin-top: 10px; }
.jump { display: flex; gap: 8px; justify-content: center; align-items: center; margin-top: 10px; font-size: 14px; color: var(--dim); }
.jump input { width: 90px; padding: 8px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); color: var(--text); font-family: inherit; text-align: center; }
</style>
</head>
<body>
<div class="wrap">
<h1>🎤 تۆمارکردنی دەنگی تایبەت</h1>
<div class="sub">هەر ڕستەیەک بە دەنگی خۆت بخوێنەوە. ئەم دەنگانە بۆ دروستکردنی دەنگی تایبەتی ئەپەکە بەکاردێن.</div>
<div class="card">
<details>
<summary>📋 ڕێنمایی (تکایە پێش دەستپێکردن بیخوێنەوە)</summary>
<ul>
<li>لە <b>ژوورێکی بێدەنگ</b> دابنیشە: پەنجەرە دابخە، پانکە و تەلەفزیۆن بکوژێنەوە.</li>
<li>ژووری بچووک کە پەردە و فەرش و قەنەفەی تێدابێت باشترە (دەنگ نادەنەوە).</li>
<li>مۆبایل یان مایک <b>نزیکەی یەک بست</b> لە دەمت دوور بێت.</li>
<li>بە دەنگێکی <b>ئاسایی، ئارام و سروشتی</b> بخوێنەوە، وەک ئەوەی قسە لەگەڵ هاوڕێیەک بکەیت.</li>
<li>هەموو جارێک بە <b>هەمان دەنگ و هەمان خێرایی</b> بخوێنەوە، و هەمان شوێن و هەمان مایک بەکاربهێنە.</li>
<li>ئەگەر هەڵەت کرد، تەنها <b>دووبارە تۆمار</b> بکەرەوە.</li>
<li>پشوو بدە! ڕۆژانە ١٠٠ بۆ ٢٠٠ ڕستە بەسە. پێشکەوتنەکەت پاشەکەوت دەبێت.</li>
<li>لە کۆتایی هەر دانیشتنێکدا، <b>«داگرتنی تۆمارەکان»</b> دابگرە.</li>
</ul>
</details>
</div>
<div class="card">
<div class="progress-row">
<span id="progressText">...</span>
<span id="timeText"></span>
</div>
<div class="bar"><div id="bar"></div></div>
</div>
<div class="card">
<div class="num" id="numText"></div>
<div class="sentence" id="sentence">چاوەڕێ بکە...</div>
<div class="status" id="status"></div>
<div class="meter"><div id="meter"></div></div>
<div class="controls">
<button id="prevBtn" title="پێشوو">→ پێشوو</button>
<button class="rec-btn" id="recBtn">تۆمارکردن</button>
<button id="nextBtn" title="دواتر">دواتر ←</button>
</div>
<div class="row" style="margin-top:14px">
<button id="playBtn" disabled>▶ گوێگرتن</button>
<button id="nextTodoBtn">⏭ ڕستەی تۆمارنەکراو</button>
</div>
<div class="jump">
<span>بڕۆ بۆ ڕستەی ژمارە</span>
<input id="jumpInput" type="number" min="1" inputmode="numeric">
<button id="jumpBtn">بڕۆ</button>
</div>
<div class="note">لەسەر کۆمپیوتەر: <b>Space</b> = تۆمار/وەستان، <b>←</b> = دواتر، <b>→</b> = پێشوو، <b>P</b> = گوێگرتن</div>
</div>
<div class="card">
<div class="row">
<button class="primary" id="exportBtn">⬇ داگرتنی تۆمارەکان (ZIP)</button>
</div>
<div class="note" id="exportNote">تۆمارەکان لە ناو ئەم وێبگەڕەدا پاشەکەوت دەبن. بۆ پاراستن، لە کۆتایی هەر دانیشتنێکدا دایانبگرە.</div>
<div class="note" id="backupNote" style="display:none;color:var(--warn);font-weight:600"></div>
</div>
</div>
<script>
(() => {
const TARGET_RATE = 22050;
const $ = (id) => document.getElementById(id);
let sentences = [];
let idx = 0;
let doneSet = new Set();
let db = null;
let recording = false;
let ctx = null, stream = null, source = null, proc = null, chunks = [], peak = 0;
let currentAudio = null;
// ---------- storage (IndexedDB; the ZIP download is the real backup) ----------
function openDb() {
return new Promise((resolve) => {
try {
const req = indexedDB.open('translet-voice-recording', 1);
req.onupgradeneeded = () => req.result.createObjectStore('clips');
req.onsuccess = () => resolve(req.result);
req.onerror = () => resolve(null);
} catch (_) { resolve(null); }
});
}
function dbOp(mode, fn) {
return new Promise((resolve) => {
if (!db) return resolve(null);
try {
const tx = db.transaction('clips', mode);
const st = tx.objectStore('clips');
const req = fn(st);
req.onsuccess = () => resolve(req.result);
req.onerror = () => resolve(null);
} catch (_) { resolve(null); }
});
}
const saveClip = (i, blob) => dbOp('readwrite', (s) => s.put({ blob, text: sentences[i] }, i));
const getClip = (i) => dbOp('readonly', (s) => s.get(i));
const allKeys = () => dbOp('readonly', (s) => s.getAllKeys());
const memClips = new Map(); // fallback when IndexedDB is unavailable
// ---------- UI ----------
function setStatus(text, cls = '') { const el = $('status'); el.textContent = text; el.className = 'status ' + cls; }
function fmtMin(sec) { const m = Math.round(sec / 60); return m < 60 ? `${m} خولەک` : `${Math.floor(m / 60)} کاتژمێر و ${m % 60} خولەک`; }
function render() {
const s = sentences[idx] || '';
$('sentence').textContent = s;
const isDone = doneSet.has(idx);
$('numText').innerHTML = `ڕستەی ${idx + 1} لە ${sentences.length} ` + (isDone ? '<span class="done-badge">✓ تۆمارکراوە</span>' : '');
$('playBtn').disabled = !isDone;
$('recBtn').textContent = isDone ? 'دووبارە' : 'تۆمارکردن';
$('prevBtn').disabled = idx === 0 || recording;
$('nextBtn').disabled = idx >= sentences.length - 1 || recording;
const n = doneSet.size;
$('progressText').textContent = `${n} لە ${sentences.length} ڕستە تۆمارکراوە`;
$('timeText').textContent = n ? `نزیکەی ${fmtMin(n * 4.5)} دەنگ` : '';
$('bar').style.width = (n / Math.max(1, sentences.length) * 100) + '%';
try { localStorage.setItem('rec_idx', String(idx)); } catch (_) {}
// Remind to download a backup every 25 new recordings
let exported = 0;
try { exported = parseInt(localStorage.getItem('rec_exported') || '0', 10) || 0; } catch (_) {}
const notBackedUp = n - exported;
const bn = $('backupNote');
if (notBackedUp >= 25) {
bn.style.display = 'block';
bn.textContent = `💾 ${notBackedUp} تۆماری نوێت هەیە کە هێشتا دانەگیراون. تکایە ئێستا «داگرتنی تۆمارەکان» دابگرە بۆ پاراستن.`;
} else {
bn.style.display = 'none';
}
}
function go(i) {
if (recording) return;
idx = Math.max(0, Math.min(sentences.length - 1, i));
setStatus('');
render();
}
// ---------- recording ----------
async function startRec() {
try {
stream = await navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false }
});
} catch (e) {
setStatus('⚠️ مایکەکە کار ناکات. تکایە ڕێگە بە مایک بدە.', 'warn');
return;
}
ctx = new (window.AudioContext || window.webkitAudioContext)();
if (ctx.state === 'suspended') await ctx.resume();
source = ctx.createMediaStreamSource(stream);
proc = ctx.createScriptProcessor(4096, 1, 1);
chunks = []; peak = 0;
proc.onaudioprocess = (ev) => {
const d = ev.inputBuffer.getChannelData(0);
chunks.push(new Float32Array(d));
let m = 0;
for (let k = 0; k < d.length; k++) { const a = Math.abs(d[k]); if (a > m) m = a; }
if (m > peak) peak = m;
$('meter').style.width = Math.min(100, m * 140) + '%';
$('meter').style.background = m > 0.97 ? 'var(--accent)' : 'var(--ok)';
};
source.connect(proc);
proc.connect(ctx.destination);
recording = true;
$('recBtn').classList.add('recording');
$('recBtn').textContent = 'وەستان';
setStatus('🔴 تۆمار دەکرێت... ڕستەکە بخوێنەوە، پاشان «وەستان» دابگرە', 'rec');
render();
$('recBtn').textContent = 'وەستان';
}
async function stopRec() {
recording = false;
$('recBtn').classList.remove('recording');
try { proc.disconnect(); source.disconnect(); } catch (_) {}
try { stream.getTracks().forEach((t) => t.stop()); } catch (_) {}
const rate = ctx.sampleRate;
try { await ctx.close(); } catch (_) {}
$('meter').style.width = '0';
const total = chunks.reduce((n, c) => n + c.length, 0);
const pcm = new Float32Array(total);
let off = 0;
for (const c of chunks) { pcm.set(c, off); off += c.length; }
const seconds = total / rate;
if (seconds < 0.8) { setStatus('⚠️ زۆر کورت بوو، دووبارە هەوڵ بدەوە.', 'warn'); render(); return; }
// Was the voice still going at the very end? (stop pressed too early -> last word cut)
// Tuned on the user's real recordings: last 50 ms louder than 15% of the peak = cut
const tailLen = Math.floor(rate * 0.05);
let tailPeak = 0;
for (let k = pcm.length - tailLen; k < pcm.length; k++) { const a = Math.abs(pcm[k]); if (a > tailPeak) tailPeak = a; }
const endCut = tailPeak > peak * 0.15;
if (peak < 0.05) { setStatus('⚠️ دەنگەکە زۆر نزمە. مایکەکە نزیکتر بکەرەوە و دووبارە تۆمار بکە.', 'warn'); render(); return; }
const wav = encodeWav(await resample(pcm, rate, TARGET_RATE), TARGET_RATE);
memClips.set(idx, wav);
await saveClip(idx, wav);
doneSet.add(idx);
if (peak > 0.97) setStatus('⚠️ دەنگەکە زۆر بەرز بوو. کەمێک دوورتر لە مایک قسە بکە و دووبارەی بکەرەوە.', 'warn');
else if (endCut) setStatus('⚠️ زوو «وەستان»ت داگرت، کۆتا وشە بڕا. دووبارەی بکەرەوە و دوای کۆتا وشە نیو چرکە چاوەڕێ بکە.', 'warn');
else setStatus(`✓ پاشەکەوت کرا (${seconds.toFixed(1)} چرکە)`, 'ok');
render();
if (peak <= 0.97 && !endCut && idx < sentences.length - 1) {
setTimeout(() => {
if (recording) return;
go(idx + 1);
setStatus('✓ ڕستەی پێشوو پاشەکەوت کرا. ئێستا ئەمە بخوێنەوە.', 'ok');
}, 700);
}
}
async function resample(pcm, from, to) {
if (from === to) return pcm;
const len = Math.ceil(pcm.length * to / from);
const off = new OfflineAudioContext(1, len, to);
const buf = off.createBuffer(1, pcm.length, from);
buf.copyToChannel(pcm, 0);
const src = off.createBufferSource();
src.buffer = buf; src.connect(off.destination); src.start();
return (await off.startRendering()).getChannelData(0);
}
function encodeWav(samples, rate) {
const buf = new ArrayBuffer(44 + samples.length * 2);
const v = new DataView(buf);
const w = (o, s) => { for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i)); };
w(0, 'RIFF'); v.setUint32(4, 36 + samples.length * 2, true); w(8, 'WAVE'); w(12, 'fmt ');
v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
v.setUint32(24, rate, true); v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true);
w(36, 'data'); v.setUint32(40, samples.length * 2, true);
for (let i = 0; i < samples.length; i++) {
const s = Math.max(-1, Math.min(1, samples[i]));
v.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);
}
return new Blob([buf], { type: 'audio/wav' });
}
async function play() {
const rec = memClips.get(idx) || (await getClip(idx))?.blob;
if (!rec) return;
if (currentAudio) { try { currentAudio.pause(); } catch (_) {} }
currentAudio = new Audio(URL.createObjectURL(rec));
currentAudio.play().catch(() => {});
}
// ---------- export ----------
async function exportZip() {
if (!window.JSZip) { setStatus('⚠️ نەتوانرا ZIP دروست بکرێت. ئینتەرنێتەکەت بپشکنە.', 'warn'); return; }
const keys = [...doneSet].sort((a, b) => a - b);
if (!keys.length) { setStatus('هێشتا هیچ ڕستەیەک تۆمار نەکراوە.', 'warn'); return; }
$('exportBtn').disabled = true;
$('exportNote').textContent = 'ئامادە دەکرێت...';
const zip = new JSZip();
const lines = [];
for (const i of keys) {
const blob = memClips.get(i) || (await getClip(i))?.blob;
if (!blob) continue;
const name = String(i + 1).padStart(4, '0');
zip.file(`wavs/${name}.wav`, blob);
lines.push(`${name}|${sentences[i]}`);
}
zip.file('metadata.csv', lines.join('\n') + '\n');
const out = await zip.generateAsync({ type: 'blob' });
const a = document.createElement('a');
a.href = URL.createObjectURL(out);
a.download = `kurdish_voice_${lines.length}_clips.zip`;
document.body.appendChild(a); a.click(); a.remove();
$('exportBtn').disabled = false;
try { localStorage.setItem('rec_exported', String(lines.length)); } catch (_) {}
render();
$('exportNote').textContent = `✓ ${lines.length} تۆمار داگیرا. فایلەکە بنێرە بۆ کۆمپیوتەرەکەت، بۆ فۆڵدەری translet\\voice_training\\recordings`;
}
// ---------- events ----------
$('recBtn').onclick = () => (recording ? stopRec() : startRec());
$('prevBtn').onclick = () => go(idx - 1);
$('nextBtn').onclick = () => go(idx + 1);
$('playBtn').onclick = play;
$('exportBtn').onclick = exportZip;
$('jumpBtn').onclick = () => { const n = parseInt($('jumpInput').value, 10); if (n) go(n - 1); };
$('nextTodoBtn').onclick = () => {
for (let k = 1; k <= sentences.length; k++) {
const j = (idx + k) % sentences.length;
if (!doneSet.has(j)) return go(j);
}
setStatus('🎉 هەموو ڕستەکان تۆمار کراون!', 'ok');
};
document.addEventListener('keydown', (e) => {
if (e.target.tagName === 'INPUT') return;
if (e.code === 'Space') { e.preventDefault(); $('recBtn').click(); }
else if (e.key === 'ArrowLeft') go(idx + 1);
else if (e.key === 'ArrowRight') go(idx - 1);
else if (e.key.toLowerCase() === 'p') play();
});
// ---------- start ----------
(async () => {
// Ask the browser to keep these recordings and never delete them on its own
try { if (navigator.storage && navigator.storage.persist) await navigator.storage.persist(); } catch (_) {}
db = await openDb();
try {
const r = await fetch('voice_training/sentences.json', { cache: 'no-cache' });
sentences = await r.json();
} catch (_) {
$('sentence').textContent = '⚠️ نەتوانرا ڕستەکان بار بکرێن. ئینتەرنێتەکەت بپشکنە.';
return;
}
const keys = (await allKeys()) || [];
doneSet = new Set(keys);
let saved = 0;
try { saved = parseInt(localStorage.getItem('rec_idx') || '0', 10) || 0; } catch (_) {}
idx = Math.min(saved, sentences.length - 1);
if (!db) setStatus('⚠️ ئەم وێبگەڕە ناتوانێت پاشەکەوت بکات. پێش داخستن تۆمارەکان دابگرە.', 'warn');
render();
})();
})();
</script>
</body>
</html>