Spaces:
Running
Running
Download index.html from ultrazcode/juru-bahasa: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/spaces/ultrazcode/juru-bahasa/resolve/main/index.html
- Command line
-
hf download hf://spaces/ultrazcode/juru-bahasa/index.html
-
curl -L -o index.html https://huggingface.co/spaces/ultrazcode/juru-bahasa/resolve/main/index.html
15.1 kB
| <html lang="id"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>Juru Bahasa — Inggris ke Indonesia</title> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Newsreader:opsz,wght@6..72,400;6..72,600&family=Public+Sans:wght@400;500;600&display=swap"> | |
| <style> | |
| :root{ | |
| --bg:#f5f0e6;--paper:#fffdf8;--ink:#23201b;--muted:#6f685b;--line:#ddd4c3; | |
| --accent:#b8421f;--accent-ink:#fff;--soft:#efe7d6; | |
| --serif:"Newsreader",Georgia,"Times New Roman",serif; | |
| --sans:"Public Sans","Segoe UI",system-ui,sans-serif; | |
| } | |
| @media (prefers-color-scheme:dark){ | |
| :root{--bg:#1b1915;--paper:#23201b;--ink:#efe9dc;--muted:#a39a88;--line:#3a352c;--accent:#e0714a;--accent-ink:#1b1915;--soft:#2c2822} | |
| } | |
| *{box-sizing:border-box;margin:0} | |
| body{background:var(--bg);color:var(--ink);font:16px/1.55 var(--sans);padding:0 20px 64px} | |
| main{max-width:640px;margin:0 auto} | |
| header{padding:48px 0 28px;border-bottom:1px solid var(--line)} | |
| h1{font:600 34px/1.15 var(--serif);letter-spacing:-.01em} | |
| header p{color:var(--muted);margin-top:8px;max-width:46ch} | |
| .talk{padding:32px 0;border-bottom:1px solid var(--line)} | |
| .row{display:flex;align-items:center;gap:20px} | |
| #mic{flex:none;width:76px;height:76px;border-radius:50%;border:0;background:var(--accent);color:var(--accent-ink); | |
| cursor:pointer;display:grid;place-items:center;transition:background .15s,transform .1s} | |
| #mic:hover{transform:translateY(-1px)} | |
| #mic:focus-visible,input:focus-visible,select:focus-visible,.opt:focus-within{outline:3px solid var(--ink);outline-offset:3px} | |
| #mic svg{width:30px;height:30px} | |
| #mic.rec{background:var(--ink);color:var(--bg)} | |
| #mic .stopicon{display:none} | |
| #mic.rec .micicon{display:none} | |
| #mic.rec .stopicon{display:block} | |
| .say{min-width:0} | |
| #status{font:500 18px/1.3 var(--serif);font-size:20px} | |
| #hint{color:var(--muted);font-size:14px;margin-top:2px} | |
| #meter{display:flex;gap:3px;align-items:flex-end;height:18px;margin-top:10px} | |
| #meter i{width:4px;height:3px;background:var(--line);border-radius:2px;transition:height .06s,background .06s} | |
| #meter i.on{background:var(--accent)} | |
| .opts{display:flex;flex-wrap:wrap;gap:12px 28px;margin-top:26px;font-size:14px;color:var(--muted);align-items:center} | |
| .opts label.opt{display:inline-flex;align-items:center;gap:6px;cursor:pointer} | |
| select{font:inherit;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:6px;padding:5px 8px} | |
| form{display:flex;gap:8px;margin-top:24px} | |
| input[type=text]{flex:1;min-width:0;font:inherit;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:6px;padding:10px 12px} | |
| form button{font:600 15px var(--sans);background:transparent;color:var(--ink);border:1px solid var(--ink);border-radius:6px;padding:0 16px;cursor:pointer} | |
| form button:hover{background:var(--ink);color:var(--bg)} | |
| h2{font:600 13px var(--sans);letter-spacing:.08em;text-transform:uppercase;color:var(--muted);padding:28px 0 4px} | |
| .empty{color:var(--muted);padding:18px 0} | |
| .item{padding:20px 0;border-bottom:1px solid var(--line)} | |
| .item .en{color:var(--muted);font-size:15px} | |
| .item .id{font:400 26px/1.3 var(--serif);margin-top:6px} | |
| .item .meta{display:flex;gap:14px;align-items:center;margin-top:10px;font-size:13px;color:var(--muted)} | |
| .item button{font:500 13px var(--sans);color:var(--ink);background:none;border:0;border-bottom:1px solid var(--ink);padding:0;cursor:pointer} | |
| #toast{position:fixed;left:20px;right:20px;bottom:20px;max-width:520px;margin:0 auto;background:var(--ink);color:var(--bg); | |
| padding:12px 16px;border-radius:6px;font-size:14px;display:none} | |
| footer{color:var(--muted);font-size:13px;padding-top:28px} | |
| @media (prefers-reduced-motion:reduce){*{transition:none}} | |
| </style> | |
| </head> | |
| <body> | |
| <main> | |
| <header> | |
| <h1>Bicara Inggris,<br>dengar Indonesia.</h1> | |
| <p>Ucapkan satu atau dua kalimat. Terjemahannya akan muncul di bawah dan dibacakan dengan suara Indonesia.</p> | |
| </header> | |
| <section class="talk"> | |
| <div class="row"> | |
| <button id="mic" aria-label="Mulai bicara"> | |
| <svg class="micicon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v4"/></svg> | |
| <svg class="stopicon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2"/></svg> | |
| </button> | |
| <div class="say"> | |
| <div id="status" aria-live="polite">Siap mendengarkan</div> | |
| <div id="hint">Tekan tombol, lalu mulai bicara.</div> | |
| <div id="meter" aria-hidden="true"></div> | |
| </div> | |
| </div> | |
| <div class="opts"> | |
| <span>Cara merekam:</span> | |
| <label class="opt"><input type="radio" name="mode" value="auto" checked> Otomatis berhenti saat jeda</label> | |
| <label class="opt"><input type="radio" name="mode" value="manual"> Saya yang menghentikan</label> | |
| <label class="opt">Suara <select id="voice"><option>Memuat…</option></select></label> | |
| </div> | |
| <form id="textform"> | |
| <input id="text" type="text" placeholder="Atau ketik kalimat Inggris di sini" autocomplete="off" aria-label="Kalimat Inggris"> | |
| <button>Terjemahkan</button> | |
| </form> | |
| </section> | |
| <h2>Hasil terjemahan</h2> | |
| <section id="log"><p class="empty">Belum ada. Coba ucapkan: “How are you doing today?”</p></section> | |
| <details style="margin-top:28px;font-size:14px;color:var(--muted)"> | |
| <summary style="cursor:pointer">Pengaturan lanjutan (opsional)</summary> | |
| <p style="margin:10px 0 8px">Terjemahan bawaan memakai layanan gratis MyMemory. Untuk hasil yang lebih natural, tempel API key Groq milik Anda sendiri. Key hanya disimpan di browser ini dan dikirim langsung ke Groq.</p> | |
| <input id="gkey" type="password" placeholder="gsk_..." autocomplete="off" style="width:100%;font:inherit;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:6px;padding:9px 12px"> | |
| </details> | |
| <footer id="engine">Semua proses berjalan di browser Anda. Model pengenalan suara (sekitar 80 MB) diunduh sekali saat pertama dipakai.</footer> | |
| </main> | |
| <div id="toast" role="alert"></div> | |
| <script type="module"> | |
| import { pipeline, env } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.5.1"; | |
| env.allowLocalModels = false; | |
| const $ = s => document.querySelector(s); | |
| const micBtn = $('#mic'), statusEl = $('#status'), hintEl = $('#hint'), meter = $('#meter'); | |
| for (let i = 0; i < 16; i++) meter.appendChild(document.createElement('i')); | |
| const bars = [...meter.children]; | |
| let mode = 'auto', listening = false, busy = false; | |
| let stream, ctx, analyser, recorder, chunks = [], speaking = false, silentSince = 0, speechStart = 0, raf; | |
| const THRESH = 0.03, SILENCE_MS = 900, MIN_MS = 500; | |
| const store = { get: k => { try { return localStorage.getItem(k) || ''; } catch { return ''; } }, | |
| set: (k, v) => { try { localStorage.setItem(k, v); } catch {} } }; | |
| $('#gkey').value = store.get('groq_key'); | |
| $('#gkey').onchange = e => store.set('groq_key', e.target.value.trim()); | |
| /* ---------- Pengenalan suara (Whisper di browser) ---------- */ | |
| let asrPromise; | |
| function loadASR() { | |
| asrPromise ??= pipeline('automatic-speech-recognition', 'Xenova/whisper-base.en', { | |
| progress_callback: p => { if (p.status === 'progress' && !busy) setStatus('Mengunduh model suara… ' + Math.round(p.progress) + '%', 'Hanya sekali, setelah itu tersimpan di browser.'); } | |
| }); | |
| return asrPromise; | |
| } | |
| async function toPCM(blob) { | |
| const ac = new AudioContext(); | |
| const buf = await ac.decodeAudioData(await blob.arrayBuffer()); | |
| ac.close(); | |
| const off = new OfflineAudioContext(1, Math.ceil(buf.duration * 16000), 16000); | |
| const src = off.createBufferSource(); src.buffer = buf; src.connect(off.destination); src.start(); | |
| return (await off.startRendering()).getChannelData(0); | |
| } | |
| /* ---------- Terjemahan ---------- */ | |
| async function translate(text) { | |
| const key = store.get('groq_key'); | |
| if (key) { | |
| try { | |
| const r = await fetch('https://api.groq.com/openai/v1/chat/completions', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + key }, | |
| body: JSON.stringify({ model: 'openai/gpt-oss-20b', temperature: 0.2, max_tokens: 400, messages: [ | |
| { role: 'system', content: 'Kamu penerjemah lisan profesional. Terjemahkan ucapan Bahasa Inggris pengguna ke Bahasa Indonesia yang natural, santai, dan mudah diucapkan. Balas HANYA dengan hasil terjemahan.' }, | |
| { role: 'user', content: text }] }) | |
| }); | |
| if (r.ok) return (await r.json()).choices[0].message.content.trim(); | |
| } catch {} | |
| } | |
| const r = await fetch('https://api.mymemory.translated.net/get?langpair=en|id&q=' + encodeURIComponent(text)); | |
| if (!r.ok) throw new Error('Layanan terjemahan sedang sibuk. Coba lagi sebentar.'); | |
| const j = await r.json(); | |
| const out = j.responseData && j.responseData.translatedText; | |
| if (!out || j.responseStatus != 200) throw new Error('Terjemahan gagal: ' + (j.responseDetails || 'tidak ada hasil')); | |
| return out; | |
| } | |
| /* ---------- Suara (bawaan browser) ---------- */ | |
| let idVoices = []; | |
| function loadVoices() { | |
| idVoices = speechSynthesis.getVoices().filter(v => v.lang.toLowerCase().startsWith('id')); | |
| $('#voice').innerHTML = idVoices.length | |
| ? idVoices.map((v, i) => `<option value="${i}">${v.name.replace(/Microsoft |Google /, '')}</option>`).join('') | |
| : '<option>Suara bawaan</option>'; | |
| } | |
| speechSynthesis.onvoiceschanged = loadVoices; loadVoices(); | |
| function speak(text) { | |
| return new Promise(res => { | |
| speechSynthesis.cancel(); | |
| const u = new SpeechSynthesisUtterance(text); | |
| u.lang = 'id-ID'; | |
| const v = idVoices[+$('#voice').value]; if (v) u.voice = v; | |
| u.onend = u.onerror = res; | |
| speechSynthesis.speak(u); | |
| }); | |
| } | |
| /* ---------- UI ---------- */ | |
| document.querySelectorAll('input[name=mode]').forEach(r => r.onchange = () => { | |
| if (listening) stop(); | |
| mode = r.value; | |
| setStatus('Siap mendengarkan', mode === 'auto' ? 'Tekan tombol, lalu mulai bicara.' : 'Tekan untuk mulai, tekan lagi saat selesai bicara.'); | |
| }); | |
| function setStatus(main, hint = '') { statusEl.textContent = main; hintEl.textContent = hint; } | |
| function toast(msg) { const t = $('#toast'); t.textContent = msg; t.style.display = 'block'; setTimeout(() => t.style.display = 'none', 5000); } | |
| function level(v) { const n = Math.round(Math.min(1, v * 8) * bars.length); bars.forEach((b, i) => { b.classList.toggle('on', i < n); b.style.height = (3 + (i < n ? i : 0)) + 'px'; }); } | |
| micBtn.onclick = () => listening ? stop() : start(); | |
| async function start() { | |
| loadASR(); | |
| try { | |
| stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } }); | |
| } catch { return toast('Browser tidak diberi izin memakai mikrofon. Izinkan dulu lewat ikon gembok di address bar.'); } | |
| ctx = new AudioContext(); analyser = ctx.createAnalyser(); analyser.fftSize = 1024; | |
| ctx.createMediaStreamSource(stream).connect(analyser); | |
| listening = true; micBtn.classList.add('rec'); micBtn.setAttribute('aria-label', 'Berhenti'); | |
| if (mode === 'manual') { beginSegment(); setStatus('Merekam…', 'Tekan lagi kalau sudah selesai bicara.'); } | |
| else setStatus('Mendengarkan…', 'Silakan bicara. Saya berhenti sendiri saat Anda diam.'); | |
| loop(); | |
| } | |
| function stop() { | |
| listening = false; micBtn.classList.remove('rec'); micBtn.setAttribute('aria-label', 'Mulai bicara'); | |
| cancelAnimationFrame(raf); level(0); | |
| if (recorder && recorder.state !== 'inactive') { | |
| if (mode !== 'manual') recorder.onstop = null; | |
| recorder.stop(); | |
| } | |
| stream && stream.getTracks().forEach(t => t.stop()); ctx && ctx.close(); | |
| if (!busy) setStatus('Siap mendengarkan', 'Tekan tombol, lalu mulai bicara.'); | |
| } | |
| function beginSegment() { | |
| chunks = []; | |
| recorder = new MediaRecorder(stream); | |
| recorder.ondataavailable = e => e.data.size && chunks.push(e.data); | |
| recorder.onstop = () => { if (chunks.length) handleAudio(new Blob(chunks, { type: recorder.mimeType })); }; | |
| recorder.start(); | |
| } | |
| function loop() { | |
| const buf = new Float32Array(analyser.fftSize); | |
| analyser.getFloatTimeDomainData(buf); | |
| const rms = Math.sqrt(buf.reduce((s, v) => s + v * v, 0) / buf.length); | |
| level(rms); | |
| const now = performance.now(); | |
| if (mode === 'auto' && !busy) { | |
| if (rms > THRESH) { | |
| silentSince = now; | |
| if (!speaking) { speaking = true; speechStart = now; beginSegment(); setStatus('Merekam…', 'Lanjutkan bicara, jeda sebentar saat selesai.'); } | |
| } else if (speaking && now - silentSince > SILENCE_MS) { | |
| speaking = false; | |
| if (now - speechStart - SILENCE_MS < MIN_MS) { recorder.onstop = null; recorder.stop(); setStatus('Mendengarkan…', 'Silakan bicara.'); } | |
| else recorder.stop(); | |
| } | |
| } | |
| if (listening) raf = requestAnimationFrame(loop); | |
| } | |
| async function handleAudio(blob) { | |
| await run(async () => { | |
| const t0 = performance.now(); | |
| setStatus('Mengenali ucapan…'); | |
| const asr = await loadASR(); | |
| const pcm = await toPCM(blob); | |
| const out = await asr(pcm); | |
| const english = (out.text || '').trim(); | |
| if (!english) throw new Error('Tidak ada ucapan yang terdeteksi.'); | |
| return { english, t0 }; | |
| }); | |
| } | |
| $('#textform').onsubmit = async e => { | |
| e.preventDefault(); | |
| const v = $('#text').value.trim(); if (!v || busy) return; | |
| $('#text').value = ''; | |
| await run(async () => ({ english: v, t0: performance.now() })); | |
| }; | |
| async function run(getEnglish) { | |
| busy = true; | |
| try { | |
| const { english, t0 } = await getEnglish(); | |
| setStatus('Menerjemahkan…'); | |
| const indonesian = await translate(english); | |
| addItem({ english, indonesian, secs: ((performance.now() - t0) / 1000).toFixed(1) }); | |
| setStatus('Memutar terjemahan…'); | |
| await speak(indonesian); | |
| } catch (err) { toast(err.message || String(err)); } | |
| finally { | |
| busy = false; | |
| if (listening) setStatus('Mendengarkan…', 'Silakan bicara.'); | |
| else setStatus('Siap mendengarkan', 'Tekan tombol, lalu mulai bicara.'); | |
| } | |
| } | |
| const esc = s => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); | |
| function addItem(d) { | |
| const log = $('#log'); const em = log.querySelector('.empty'); if (em) em.remove(); | |
| const el = document.createElement('article'); el.className = 'item'; | |
| el.innerHTML = `<div class="en">${esc(d.english)}</div><div class="id">${esc(d.indonesian)}</div> | |
| <div class="meta"><button type="button">Putar ulang</button><span>selesai dalam ${d.secs} detik</span></div>`; | |
| el.querySelector('button').onclick = () => speak(d.indonesian); | |
| log.prepend(el); | |
| } | |
| </script> | |
| </body> | |
| </html> | |