Spaces:
Running

README / app.js
Zolton
Translate each recorded sentence
8cd89cc
Raw History Blame Contribute Delete
12.1 kB
"use strict";
const $=s=>document.querySelector(s),state={tier:"CPU",gpu:null,wasm:null,profile:{pitch:128,energy:.16},ctx:null};
const els={text:$("#text"),zyntalic:$("#zyntalic"),count:$("#count"),record:$("#record"),speak:$("#speak"),wipe:$("#wipe"),status:$("#status"),wave:$("#wave"),badge:$("#privacyBadge"),metricTier:$("#metricTier"),metricMs:$("#metricMs"),metricProfile:$("#metricProfile")};
function stage(name){const order=["capture","profile","translate","infer","play"],at=order.indexOf(name);document.querySelectorAll(".pipe-step").forEach(e=>{const i=order.indexOf(e.dataset.step);e.classList.toggle("active",i===at);e.classList.toggle("done",i>=0&&i<at)})}
const anchors={i:"za",you:"ti",we:"nava",the:"el",a:"an",and:"ka",is:"esh",are:"esh",to:"ul",of:"or",in:"vi",with:"sha",ideas:"zynera",idea:"zyner",enter:"talvek",then:"sai",transformations:"morvatai",transformation:"morvat",make:"kora",brand:"kuggara",hello:"salvek",world:"orvane"};
function hashWord(word){let h=2166136261;for(const c of word){h^=c.charCodeAt(0);h=Math.imul(h,16777619)}const a=["za","ve","ko","tal","ryn","sha","mor","ki","ul","dra","syn","na"],b=["n","r","s","th","k","m","v","l","z","x"];return a[(h>>>0)%a.length]+a[(h>>>7)%a.length]+b[(h>>>15)%b.length]}
function toZyntalic(input){return input.replace(/[A-Za-z']+/g,w=>{const z=anchors[w.toLowerCase()]||hashWord(w.toLowerCase());return /^[A-Z]/.test(w)?z[0].toUpperCase()+z.slice(1):z}).replace(/\s+([,.;!?])/g,"$1")}
function translateIdea(){const translated=toZyntalic(els.text.value.trim());els.zyntalic.textContent=translated;els.count.textContent=`${els.text.value.length} / 360`;return translated}
function status(s){els.status.textContent=s}function tier(name,ready,selected=false){const e=document.querySelector(`[data-tier="${name}"]`);e.classList.toggle("ready",ready);e.classList.toggle("selected",selected);e.querySelector("b").textContent=selected?"SELECTED":ready?"READY":"UNAVAILABLE"}
async function probe(){let gpu=false,wasm=false;try{if(navigator.gpu){const a=await navigator.gpu.requestAdapter();if(a){state.gpu=await a.requestDevice();gpu=true}}}catch(e){}try{const r=await fetch("rcv-kernel.wasm");const bytes=await r.arrayBuffer();const m=await WebAssembly.instantiate(bytes);state.wasm=m.instance.exports;wasm=true}catch(e){}state.tier=gpu?"WEBGPU":wasm?"WASM":"CPU";tier("WEBGPU",gpu,state.tier==="WEBGPU");tier("WASM",wasm,state.tier==="WASM");tier("CPU",true,state.tier==="CPU");els.metricTier.textContent=state.tier;status(`${state.tier} READY · ALL AUDIO STAYS LOCAL`)}
function db(){return new Promise((ok,no)=>{const q=indexedDB.open("kugguk-rcv",2);q.onupgradeneeded=()=>{if(!q.result.objectStoreNames.contains("clips"))q.result.createObjectStore("clips")};q.onsuccess=()=>ok(q.result);q.onerror=()=>no(q.error)})}
async function put(key,val){const d=await db();return new Promise(ok=>{const t=d.transaction("clips","readwrite");t.objectStore("clips").put(val,key);t.oncomplete=ok})}async function get(key){const d=await db();return new Promise(ok=>{const q=d.transaction("clips").objectStore("clips").get(key);q.onsuccess=()=>ok(q.result)})}
function analyse(buffer){const x=buffer.getChannelData(0),step=Math.max(1,Math.floor(x.length/16000));let sum=0,cross=0,last=x[0];for(let i=0;i<x.length;i+=step){sum+=x[i]*x[i];if(last<=0&&x[i]>0)cross++;last=x[i]}const seconds=x.length/buffer.sampleRate;return{pitch:Math.max(85,Math.min(220,cross/seconds)),energy:Math.max(.08,Math.min(.32,Math.sqrt(sum/(x.length/step))))}}
async function startDictation(){const Recognition=window.SpeechRecognition||window.webkitSpeechRecognition;if(!Recognition)return null;const recognition=new Recognition,options={langs:["en-US"],processLocally:true};let local=false;if("processLocally" in recognition&&typeof Recognition.available==="function"){try{const availability=await Recognition.available(options);if(availability!=="unavailable"){if(availability!=="available"&&typeof Recognition.install==="function"){status("INSTALLING ON-DEVICE ENGLISH DICTATION…");await Recognition.install(options)}const ready=await Recognition.available(options);if(ready==="available"){recognition.processLocally=true;local=true}}}catch(e){}}recognition.lang="en-US";recognition.continuous=true;recognition.interimResults=true;let transcript="";recognition.onresult=e=>{transcript=Array.from(e.results,r=>r[0].transcript).join(" ").trim();if(transcript){els.text.value=transcript;translateIdea()}};recognition.start();return{mode:local?"LOCAL":"BROWSER SERVICE",stop:()=>{try{recognition.stop()}catch(e){}},text:()=>transcript}}
async function record(){if(!navigator.mediaDevices?.getUserMedia)return status("MIC REQUIRES HTTPS OR LOCALHOST");els.record.disabled=true;stage("capture");let stream;try{stream=await navigator.mediaDevices.getUserMedia({audio:true});let dictation=null;try{dictation=await startDictation()}catch(e){}if(dictation){els.text.value="";translateIdea()}const rec=new MediaRecorder(stream),parts=[];rec.ondataavailable=e=>parts.push(e.data);rec.start();status(dictation?`RECORDING + ${dictation.mode} DICTATION · 3`:"RECORDING VOICE PROFILE · 3");for(let n=2;n>0;n--){await new Promise(r=>setTimeout(r,1000));status(`${dictation?`RECORDING + ${dictation.mode} DICTATION`:"RECORDING PROFILE"} · ${n}`)}await new Promise(r=>{setTimeout(()=>rec.stop(),1000);rec.onstop=r});dictation?.stop();await new Promise(r=>setTimeout(r,250));stream.getTracks().forEach(t=>t.stop());const blob=new Blob(parts,{type:rec.mimeType});const ctx=state.ctx||=new AudioContext();const buf=await ctx.decodeAudioData(await blob.arrayBuffer());stage("profile");state.profile=analyse(buf);await put("sample",blob);await put("profile",state.profile);els.badge.textContent=dictation?.mode==="BROWSER SERVICE"?"● PROFILE LOCAL · DICTATION VIA BROWSER":"● PROFILE HELD LOCALLY";els.badge.classList.add("held");els.metricProfile.textContent=`${Math.round(state.profile.pitch)} HZ`;draw(buf.getChannelData(0));const translated=translateIdea();stage("translate");status(dictation?.text()?`TRANSCRIBED + TRANSLATED · ${translated}`:"NO SPEECH RECOGNIZED · TRY AGAIN OR TYPE SOURCE TEXT")}catch(e){stage("capture");status("MICROPHONE NOT AVAILABLE")}finally{stream?.getTracks().forEach(t=>t.stop());els.record.disabled=false}}
function synth(text,sr=32000){const duration=Math.min(14,Math.max(1.2,text.length*.075)),out=new Float32Array(Math.floor(duration*sr)),base=state.profile.pitch,gain=state.profile.energy*2.2;let seed=2166136261;for(const ch of text){seed^=ch.charCodeAt(0);seed=Math.imul(seed,16777619)}for(let i=0;i<out.length;i++){const t=i/sr,k=Math.floor(t/.075),code=text.charCodeAt(k%Math.max(1,text.length))||32;const voiced=/[aeiouy]/i.test(text[k%Math.max(1,text.length)]||"");const f=base*(.78+(code%13)/30);seed=(Math.imul(seed,1664525)+1013904223)|0;const noise=((seed>>>8)/16777216-.5);const env=Math.sin(Math.PI*((t%.075)/.075))**.45;const pulse=Math.sin(2*Math.PI*f*t)+.35*Math.sin(4*Math.PI*f*t)+.14*Math.sin(6*Math.PI*f*t);out[i]=env*gain*(voiced?pulse*.42:noise*.48)}return out}
async function processGPU(input,gain){const d=state.gpu,n=input.length,size=Math.ceil(n*4/4)*4,usage=GPUBufferUsage;const a=d.createBuffer({size,usage:usage.STORAGE|usage.COPY_DST}),b=d.createBuffer({size,usage:usage.STORAGE|usage.COPY_SRC}),r=d.createBuffer({size,usage:usage.COPY_DST|usage.MAP_READ});d.queue.writeBuffer(a,0,input);const mod=d.createShaderModule({code:`struct P{n:u32,g:f32};@group(0)@binding(0)var<storage,read>a:array<f32>;@group(0)@binding(1)var<storage,read_write>b:array<f32>;@group(0)@binding(2)var<uniform>p:P;@compute @workgroup_size(64)fn main(@builtin(global_invocation_id)i:vec3<u32>){if(i.x<p.n){b[i.x]=a[i.x]*p.g;}}`}),p=d.createBuffer({size:8,usage:usage.UNIFORM|usage.COPY_DST});const pars=new ArrayBuffer(8);new Uint32Array(pars)[0]=n;new Float32Array(pars)[1]=gain;d.queue.writeBuffer(p,0,pars);const pipe=d.createComputePipeline({layout:"auto",compute:{module:mod,entryPoint:"main"}}),bind=d.createBindGroup({layout:pipe.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:a}},{binding:1,resource:{buffer:b}},{binding:2,resource:{buffer:p}}]}),enc=d.createCommandEncoder(),pass=enc.beginComputePass();pass.setPipeline(pipe);pass.setBindGroup(0,bind);pass.dispatchWorkgroups(Math.ceil(n/64));pass.end();enc.copyBufferToBuffer(b,0,r,0,size);d.queue.submit([enc.finish()]);await r.mapAsync(GPUMapMode.READ);const out=new Float32Array(r.getMappedRange().slice(0));r.unmap();return out}
function processWasm(input,gain){const w=state.wasm,src=0,dst=8*1024*1024,newMem=new Float32Array(w.memory.buffer);newMem.set(input,src/4);w.process(src,dst,input.length,gain);return new Float32Array(w.memory.buffer.slice(dst,dst+input.byteLength))}function processCPU(input,gain){const out=new Float32Array(input.length);for(let i=0;i<input.length;i++)out[i]=input[i]*gain;return out}
async function installedVoice(){if(!("speechSynthesis" in window))return null;let voices=speechSynthesis.getVoices();if(!voices.length){await new Promise(resolve=>{let settled=false;const done=()=>{if(settled)return;settled=true;speechSynthesis.removeEventListener("voiceschanged",done);resolve()};speechSynthesis.addEventListener("voiceschanged",done);setTimeout(done,800)});voices=speechSynthesis.getVoices()}return voices.find(v=>v.localService&&/^en\b/i.test(v.lang))||voices.find(v=>v.localService)||null}
async function speakWithLocalVoice(text){const voice=await installedVoice();if(!voice)return null;speechSynthesis.cancel();const utterance=new SpeechSynthesisUtterance(text);utterance.voice=voice;utterance.lang=voice.lang;utterance.pitch=Math.max(.7,Math.min(1.35,state.profile.pitch/128));utterance.rate=Math.max(.72,Math.min(1.12,.86+state.profile.energy));utterance.volume=Math.max(.65,Math.min(1,state.profile.energy*4));return new Promise((resolve,reject)=>{utterance.onstart=()=>resolve(voice);utterance.onerror=reject;speechSynthesis.speak(utterance)})}
async function speakProcedural(text){const raw=synth(text);let out,used=state.tier;try{out=used==="WEBGPU"?await processGPU(raw,.92):used==="WASM"?processWasm(raw,.92):processCPU(raw,.92)}catch(e){used="CPU";out=processCPU(raw,.92)}const ctx=state.ctx||=new AudioContext(),buf=ctx.createBuffer(1,out.length,32000);buf.copyToChannel(out,0);const node=ctx.createBufferSource();node.buffer=buf;node.playbackRate.value=.94;node.connect(ctx.destination);node.start();draw(out);return `${used} FALLBACK`}
async function speak(){const text=translateIdea();if(!text)return status("ENTER ENGLISH TEXT FIRST");els.speak.disabled=true;stage("translate");await new Promise(requestAnimationFrame);stage("infer");const start=performance.now();try{const voice=await speakWithLocalVoice(text),used=voice?`LOCAL · ${voice.name}`:await speakProcedural(text),ms=Math.round(performance.now()-start);els.metricTier.textContent=used;els.metricMs.textContent=`${ms} MS`;stage("play");status(voice?`SPEAKING ZYNTALIC · ${voice.name} · ON DEVICE`:`${used} · LOCAL PLAYBACK`)}catch(e){status("LOCAL SPEECH ENGINE COULD NOT START")}finally{els.speak.disabled=false}}
function draw(data){const c=els.wave,x=c.getContext("2d"),w=c.width,h=c.height;x.clearRect(0,0,w,h);x.strokeStyle="#272b28";x.beginPath();x.moveTo(0,h/2);x.lineTo(w,h/2);x.stroke();x.strokeStyle="#d7ff3f";x.beginPath();const step=Math.max(1,Math.floor(data.length/w));for(let i=0;i<w;i++){let peak=0;for(let j=0;j<step;j++)peak=Math.max(peak,Math.abs(data[i*step+j]||0));x.moveTo(i,h/2-peak*h*.42);x.lineTo(i,h/2+peak*h*.42)}x.stroke()}
async function wipe(){const d=await db();const t=d.transaction("clips","readwrite");t.objectStore("clips").clear();state.profile={pitch:128,energy:.16};els.badge.textContent="● NO SAMPLE HELD";els.badge.classList.remove("held");status("LOCAL PROFILE WIPED")}
els.text.addEventListener("input",()=>{translateIdea();stage("translate")});els.record.onclick=record;els.speak.onclick=speak;els.wipe.onclick=wipe;translateIdea();get("profile").then(p=>{if(p){state.profile=p;els.badge.textContent="● PROFILE HELD LOCALLY";els.badge.classList.add("held");els.metricProfile.textContent=`${Math.round(p.pitch)} HZ`}});probe();