Spaces:
Running on Zero
Running on Zero
Download assets/studio.js from fffiloni/fastframes-voice: direct link, hf CLI and curl.
- Browser
- Download file 38.6 kB
-
https://huggingface.co/spaces/fffiloni/fastframes-voice/resolve/main/assets/studio.js
- Command line
-
hf download hf://spaces/fffiloni/fastframes-voice/assets/studio.js
-
curl -L -o studio.js https://huggingface.co/spaces/fffiloni/fastframes-voice/resolve/main/assets/studio.js
38.6 kB
| const root = element.getRootNode(); | |
| const by = id => root.getElementById(id) || document.getElementById(id); | |
| const deskEl = by("voice-desk"); | |
| const mic = by("mic-key"), end = by("end-take"), monitor = by("monitor"); | |
| const retry = by("retry-cue"); | |
| const draft = by("cue-text"), send = by("send-text"), seconds = by("cue-seconds"); | |
| const videoModel = by("video-model"); | |
| const forceRedo = by("redo-last"); | |
| const hold = by("held-frame"); | |
| const playback = inlinePlayback(monitor, by("cue-screen"), | |
| ()=>{ | |
| if(!take || stopped)return; | |
| setMode("live"); | |
| if(livePreview)livePreview.started=true; | |
| if(!livePreview || livePreview.committed)setStatus("playing"); | |
| }, | |
| ()=>endPreview(false), ()=>endPreview(true)); | |
| const media=studioMedia(); | |
| let timeline=null; | |
| const meter = by("mic-level").getContext("2d"); | |
| const langButtons = [by("lang-en"), by("lang-fr")]; | |
| const copy = { | |
| timelineTitle:["Timeline","Montage"],segmentName:["Segment","Segment"],editable:["Editable","Modifiable"], | |
| playClip:["Play segment","Lire le segment"],replaying:["Playback","Relecture"],backToShot:["Back to monitor","Retour au moniteur"], | |
| download:["Download MP4","Télécharger le MP4"],readOnly:["Playback only","Lecture seule"],locked_segment:["Only the latest segment can be edited","Seul le dernier segment peut être modifié"],expired:["Session expired · start a new shot","Session expirée · commence un nouveau plan"],history_error:["Couldn’t load segment playback","Relecture du segment indisponible"], | |
| disk_full:["Temporary storage is full · save this take or retry later","Disque temporaire plein · enregistre ce plan ou réessaie plus tard"], | |
| researchLicense:["Non-commercial research · License","Recherche non commerciale · Licence"], | |
| studioTab:["Studio","Studio"],galleryTab:["Videos","Vidéos"],sessions:["Saved videos","Vidéos enregistrées"], | |
| director:["Director","Régie"],lastDirection:["Last direction","Dernière consigne"], | |
| moreSessions:["Show more","Afficher la suite"],deviceGallery:["This browser","Ce navigateur"],accountGallery:["Your HF account","Ton compte HF"], | |
| watchSession:["Watch","Voir"],noSessions:["Finish a session to see its video here.","Termine une session pour retrouver ta vidéo ici."], | |
| openingVideo:["Loading recording…","Chargement de la vidéo…"],loadingGallery:["Loading videos…","Chargement des vidéos…"], | |
| collection_error:["Couldn’t open saved videos · retry","Vidéos indisponibles · réessaie"], | |
| archiving:["Saving video…","Enregistrement de la vidéo…"], | |
| archive_error:["Recording available · retry saving to Videos","Vidéo disponible · réessaie l’enregistrement dans Vidéos"], | |
| redoLabel:["Redo last segment","Refaire le dernier segment"], | |
| redoSend:["Generate variant","Générer la variante"],redoGenerating:["Generating variant…","Génération de la variante…"], | |
| clarify:["Last segment or the next one?","Sur le dernier segment ou pour la suite ?"], | |
| lastOne:["Last segment","Le dernier segment"],nextOne:["Next segment","La suite"],cancel:["Cancel","Annuler"], | |
| watchOriginal:["Play original","Revoir l’original"],watchVariant:["Play variant","Revoir la variante"], | |
| keepOriginal:["Keep original","Garder l’original"],useVariant:["Use variant","Utiliser la variante"], | |
| review:["Compare the two versions","Compare les deux versions"],deciding:["Saving your choice…","Enregistrement de ton choix…"], | |
| decision_error:["Couldn’t save your choice · try again","Choix non enregistré · réessaie"], | |
| invalid_target:["Pick the latest completed segment","Choisis le dernier segment terminé"],invalid_operation:["Invalid action","Action invalide"], | |
| endSave:["End session and save recording","Terminer la session et enregistrer la vidéo"], | |
| end:["End session","Terminer"],intro:["Describe your opening shot.","Décris ton premier plan."], | |
| preview:["Preview frame","Aperçu"],help:["Speak or type a direction to begin.","Utilise la voix ou le clavier pour commencer."], | |
| videoModel:["Video model","Modèle vidéo"],modelLocked:["Model fixed for this shot","Modèle fixé pour ce plan"],invalid_model:["Choose FastFrames-S or FastFrames-L","Choisis FastFrames-S ou FastFrames-L"], | |
| voiceMode:["Voice","Voix"],textMode:["Text","Texte"],duration:["Next segment","Prochaine portion"], | |
| quietHint:["Speak in a quiet place. Pause for 3 seconds to send.","Parle dans un endroit calme. Une pause de 3 s envoie la consigne."], | |
| pausedHint:["Mic off. Your direction is paused.","Micro coupé. Ta consigne est en pause."], | |
| continueHint:["Continue your direction, then pause for 3 seconds to send.","Continue ta consigne, puis laisse 3 s de silence pour l’envoyer."], | |
| autoPause:["Mic paused · automatic resume","Micro en pause · reprise automatique"], | |
| stayMuted:["Keep muted","Garder coupé"],listenWhenReady:["Listen when ready","Activer à la reprise"], | |
| dictateNext:["Dictate next direction","Dicter la suite"],nextListening:["Listening for your next direction.","À l’écoute de ta prochaine consigne."], | |
| queuedVoice:["Next direction queued.","Prochaine consigne en attente."], | |
| liveHint:["Listening · pause for 3 seconds to send.","À l’écoute · une pause de 3 s envoie la consigne."], | |
| resumeVoice:["Resume","Reprendre"],sendVoice:["Send","Envoyer"],discardVoice:["Discard","Effacer"], | |
| phraseTooLong:["Direction too long. Unmute and try a shorter cue (up to 45 seconds).","Consigne trop longue. Réactive le micro et réessaie en 45 secondes maximum."], | |
| framesReady:["frames available","images disponibles"], | |
| textLabel:["Written direction","Consigne écrite"],textIdle:["Ready for a written direction","En attente d’une consigne écrite"], | |
| cameraCue:["Camera cue","Consigne caméra"], | |
| leaveStudio:["Leaving now discards the current take or unsent direction.","Quitter maintenant abandonne le plan en cours ou la consigne non envoyée."], | |
| stayStudio:["Stay in the studio","Rester dans le studio"],leaveContinue:["Leave and continue","Quitter et continuer"], | |
| cookieRecovery:["This browser blocks sign-in in the embedded studio. Copy this address into the current tab to sign in.","Ce navigateur bloque la connexion dans le studio intégré. Copie cette adresse dans l’onglet courant pour te connecter."], | |
| providerHelp:["With an optional HF account, Inkling can interpret your directions faster via Inference Providers. You can also save films to your private bucket.","Avec un compte HF (facultatif), Inkling peut interpréter tes consignes plus vite via les Inference Providers. Tu peux aussi enregistrer tes films dans ton bucket privé."], | |
| queueDirection:["Queue direction","Mettre en attente"],directionQueued:["Direction queued","Consigne en attente"], | |
| send:["Generate segment","Générer la portion"],starting:["Opening session…","Ouverture de la session…"], | |
| invalid_seconds:["Choose a duration from 1 to 8 s","Choisis une durée de 1 à 8 s"], | |
| invalid_text:["Enter a direction of up to 1,200 characters","Écris une consigne de 1 200 caractères maximum"], | |
| placeholder:["A red fox walks through the snow…","Un renard roux marche dans la neige…"], | |
| nextPlaceholder:["How should the shot change?","Comment le plan doit-il évoluer ?"], | |
| heard:["Heard","Transcription"],direction:["Interpreted direction","Consigne interprétée"], | |
| loopOn:["Loop on","Boucle activée"],loopOff:["Loop off","Boucle désactivée"], | |
| source:["Source Space","Space source"],idle:["Microphone off","Micro coupé"],start:["Start mic","Activer le micro"],on:["Mute mic","Couper le micro"],off:["Unmute mic","Réactiver le micro"], | |
| muted:["Mic muted","Micro coupé"],retryCue:["Retry","Réessayer"], | |
| permission:["Opening microphone…","Ouverture du micro…"],armed:["Listening for your opening shot","À l’écoute du premier plan"], | |
| sent:["Direction sent · waiting","Consigne envoyée · en attente"], | |
| transcribing:["Transcribing…","Transcription…"],interpreting:["Interpreting direction…","Interprétation de la consigne…"], | |
| renderPending:["Segment requested · waiting for the renderer","Segment demandé · en attente du moteur vidéo"], | |
| queued:["Waiting for a GPU…","En attente d’un GPU…"],allocated:["GPU allocated · preparing frames","GPU alloué · préparation des images"], | |
| restoring:["Restoring the shot…","Reprise du plan…"],generating:["Generating video…","Génération vidéo…"], | |
| saving:["Saving shot continuity…","Sauvegarde de la continuité du plan…"],encoding:["Encoding the segment…","Encodage du segment…"], | |
| playing:["Playing segment","Lecture de la portion"],holding:["Ready for the next direction","En attente de ta prochaine consigne"], | |
| loading:["Loading segment…","Chargement de la portion…"],play_error:["Playback unavailable · final frame shown","Lecture indisponible · dernière image affichée"], | |
| export_error:["Couldn’t export the take · retry","Échec de l’export · réessaie"], | |
| stopping:["Ending session…","Fin de session…"],finalizing:["Preparing recording…","Préparation de la vidéo…"], | |
| finished:["Session saved · replay or download","Session enregistrée · lecture et téléchargement"],closed:["Session ended","Session terminée"], | |
| empty:["No speech recognized · try again","Aucune parole reconnue · réessaie"],speech_error:["Couldn’t interpret this phrase · try again","Consigne non comprise · réessaie"], | |
| mic_error:["Microphone unavailable · check browser permission and try again","Micro indisponible · vérifie l’autorisation du navigateur et réessaie"], | |
| quota:["GPU quota unavailable · try again later","Quota GPU indisponible · réessaie plus tard"],gpu_error:["Segment interrupted · retry or give another direction","Portion interrompue · réessaie ou donne une autre consigne"], | |
| hardware:["Video requires ZeroGPU · microphone test complete","La vidéo nécessite ZeroGPU · essai micro terminé"], | |
| connection:["Session connection interrupted · try again","Connexion interrompue · réessaie"], | |
| scene:["Scene","Scène"],camera:["Camera","Caméra"],subject:["Subject","Sujet"],weather:["Weather","Météo"] | |
| }; | |
| let lang = "en"; try { lang = localStorage.getItem("ffv-lang")==="fr"?"fr":"en"; } catch {} | |
| const tr = k => (copy[k] || [k,k])[lang==="fr"?1:0]; | |
| let inputMode = "voice", lastSource = "", interpreter = "", submittedDraft = null; | |
| let take = null, status = "idle", mode = "idle", focus="", prompt="", lastHeard=""; | |
| let stream=null, ctx=null, node=null, opening=false, stopped=false, micEpoch=0, micIssue=""; | |
| let idleAudioContext=null, micSource=null, silentOutput=null; | |
| const workletContexts=new WeakSet(); | |
| let processing=false, listenAfterCue=false, dictatingNext=false; | |
| let ready=false, busy=false, saved=false, seq=0, applied=0, visionRev=0, retryKind="", pendingStill="", lastSegment=null; | |
| let approvedClip=null, variantClip=null, questionId=null, inFlight=null, choosing=false, editOperation="append"; | |
| let queue=[], pre=[], blocks=[], voice=false, quiet=0, loud=0, baseline=.003, watchdog=0; | |
| const endSilence=3, maxSpokenSeconds=45; | |
| let phraseSeconds=0; | |
| let voiceDraft=new Int16Array(0); | |
| let collection=null, livePreview=null; | |
| let loopEnabled=!window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches; | |
| try{const pref=localStorage.getItem("ffv-loop");if(pref!==null)loopEnabled=pref==="on";}catch{} | |
| // Account components can mount after the desk, and Gradio replaces the link on profile load. | |
| const accountLink=()=>by("provider-login").querySelector("a"); | |
| let accountPending=false; | |
| function canUseSessionCookie(){ | |
| try{ | |
| document.cookie="ffv_cookie_probe=1; Max-Age=10; Path=/; SameSite=None; Secure"; | |
| const allowed=document.cookie.split(/;\s*/).includes("ffv_cookie_probe=1"); | |
| document.cookie="ffv_cookie_probe=; Max-Age=0; Path=/; SameSite=None; Secure"; | |
| return allowed; | |
| }catch{return false;} | |
| } | |
| function usePartitionedCookie(){ | |
| try{ | |
| document.cookie="__Host-ffv-embed=1; Max-Age=600; Path=/; Secure; SameSite=None; Partitioned"; | |
| return document.cookie.split(/;\s*/).includes("__Host-ffv-embed=1"); | |
| }catch{return false;} | |
| } | |
| async function openAccount(){ | |
| const link=accountLink(); | |
| if(!link || accountPending)return; | |
| accountPending=true; | |
| by("account-leave").hidden=true; | |
| by("account-storage").hidden=true; | |
| try{ | |
| if(window.self!==window.top && !canUseSessionCookie() && !usePartitionedCookie()){ | |
| if(document.requestStorageAccess)await document.requestStorageAccess(); | |
| if(!canUseSessionCookie())throw new Error("Session cookie unavailable"); | |
| } | |
| window.location.assign(link.href); | |
| }catch{ | |
| const address=by("studio-address"); | |
| address.value=location.origin+"/"; | |
| by("account-storage").hidden=false; | |
| address.focus();address.select(); | |
| }finally{accountPending=false;} | |
| } | |
| by("studio").addEventListener("click",event=>{ | |
| const action=event.target.closest("#provider-login a, #account-stay, #account-continue"); | |
| if(!action)return; | |
| if(action.id==="account-stay"){ | |
| by("account-leave").hidden=true;accountLink()?.focus();return; | |
| } | |
| if(action.id==="account-continue"){openAccount();return;} | |
| if(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button!==0)return; | |
| event.preventDefault(); | |
| if(take || draft.value.trim() || voiceDraft.length){ | |
| by("account-storage").hidden=true; | |
| by("account-leave").hidden=false;by("account-stay").focus(); | |
| }else openAccount(); | |
| }); | |
| function syncLoop(){ | |
| const allowed=loopEnabled && !timeline?.inspecting() && !document.hidden && by("studio").dataset.view!=="gallery"; | |
| playback.setLoop(allowed); | |
| if(playback.isLooping())setMode("live"); | |
| } | |
| by("loop-preview").addEventListener("click",()=>{ | |
| loopEnabled=!loopEnabled; | |
| try{localStorage.setItem("ffv-loop",loopEnabled?"on":"off");}catch{} | |
| syncLoop();label(); | |
| }); | |
| document.addEventListener?.("visibilitychange",()=>{ | |
| if(document.hidden && (listenAfterCue || dictatingNext || opening || stream))pauseMic(); | |
| syncLoop(); | |
| }); | |
| syncLoop(); | |
| const workingStages=new Set(["permission","starting","sent","transcribing","interpreting","renderPending","queued","allocated","restoring","generating","redoGenerating","saving","encoding","loading","deciding","stopping","finalizing","archiving"]); | |
| const errorStages=new Set(["mic_error","phraseTooLong","empty","speech_error","quota","gpu_error","hardware","connection","disk_full","expired","play_error","export_error","archive_error","decision_error","invalid_model","invalid_target","invalid_operation","invalid_seconds","invalid_text","locked_segment","history_error"]); | |
| function drawStage(){ | |
| let stage=status; | |
| if(opening && !busy && !stopped)stage="permission"; | |
| else if(inputMode==="text" && ["armed","idle","mic_error","phraseTooLong"].includes(stage))stage="textIdle"; | |
| else if(stage==="armed" && !stream)stage="muted"; | |
| const text=by("stage-text"), title=tr(stage); | |
| if(text.textContent!==title)text.textContent=title; | |
| by("inference-status").dataset.state=workingStages.has(stage)?"working":errorStages.has(stage)?"error":"idle"; | |
| const generating=stage==="generating" || stage==="redoGenerating"; | |
| const count=by("frame-count"), bar=by("frame-progress"); | |
| const showFrames=Boolean(generating && livePreview?.readyFrames); | |
| count.hidden=bar.hidden=!showFrames; | |
| if(showFrames){ | |
| const {readyFrames,frames}=livePreview; | |
| count.textContent=readyFrames+" / "+frames+" "+tr("framesReady"); | |
| bar.max=frames; | |
| bar.value=readyFrames; | |
| bar.setAttribute("aria-valuetext",count.textContent); | |
| } | |
| } | |
| function label(){ | |
| by("studio").lang=lang; | |
| document.documentElement.lang=lang; | |
| root.querySelectorAll("[data-aria-fr]").forEach(e=>e.setAttribute("aria-label",lang==="fr"?e.dataset.ariaFr:e.dataset.ariaEn)); | |
| root.querySelectorAll("[data-tr]").forEach(e=>e.textContent=tr(e.dataset.tr)); | |
| langButtons.forEach((b,i)=>b.setAttribute("aria-pressed",String(i===(lang==="fr"?1:0)))); | |
| const waitingForWork=Boolean(processing || variantClip || queue.length); | |
| let micWord=voiceDraft.length?"resumeVoice":"off"; | |
| if(waitingForWork)micWord=listenAfterCue?"stayMuted":"listenWhenReady"; | |
| if(!take)micWord="start"; | |
| if(stream)micWord="on"; | |
| if(opening)micWord="cancel"; | |
| by("mic-word").textContent=tr(micWord); | |
| by("mode-voice").setAttribute("aria-pressed",String(inputMode==="voice")); | |
| by("mode-text").setAttribute("aria-pressed",String(inputMode==="text")); | |
| by("voice-control").hidden=inputMode!=="voice"; | |
| const paused=voiceDraft.length>0 && !stream && !stopped; | |
| by("voice-draft-actions").hidden=!paused; | |
| by("send-voice").disabled=opening||stopped||Boolean(variantClip)||queue.length>0||(busy && (editOperation==="redo_last"||Boolean(questionId))); | |
| by("discard-voice").disabled=opening; | |
| by("dictate-next").hidden=!canDictateNext() || Boolean(stream||opening); | |
| let hint=stream?"liveHint":"quietHint"; | |
| if(waitingForWork&&!stream)hint=listenAfterCue?"autoPause":"muted"; | |
| if(voiceDraft.length)hint=stream?"continueHint":"pausedHint"; | |
| if(dictatingNext&&stream)hint="nextListening"; | |
| by("voice-hint").textContent=tr(micIssue||hint); | |
| by("voice-queued").hidden=!queue.some(c=>c.samples); | |
| by("text-control").hidden=inputMode!=="text"; | |
| deskEl.dataset.input=inputMode; | |
| deskEl.dataset.active=String(Boolean(take)); | |
| draft.placeholder=tr(take&&applied?"nextPlaceholder":"placeholder"); | |
| deskEl.dataset.review=String(Boolean(variantClip)); | |
| deskEl.dataset.hasClip=String(Boolean(approvedClip)); | |
| by("loop-preview").hidden=!(take && !stopped && (lastSegment||livePreview?.ended)); | |
| by("loop-preview").textContent=tr(loopEnabled?"loopOn":"loopOff"); | |
| by("loop-preview").setAttribute("aria-pressed",String(loopEnabled)); | |
| collection?.controls(); | |
| videoModel.disabled=Boolean(take); | |
| by("model-choice").title=take?tr("modelLocked"):""; | |
| forceRedo.disabled=!take||!approvedClip||busy||stopped||Boolean(questionId||variantClip); | |
| by("next-length").hidden=forceRedo.checked; | |
| by("fixed-length").hidden=!forceRedo.checked; | |
| by("fixed-length").textContent=approvedClip ? approvedClip.seconds+" s" : ""; | |
| by("clarify-control").hidden=!questionId||stopped; | |
| by("review-control").hidden=!variantClip||stopped; | |
| for(const id of ["answer-redo","answer-append","cancel-answer"])by(id).disabled=busy; | |
| for(const id of ["keep-original","use-variant","watch-original","watch-variant"])by(id).disabled=choosing; | |
| by("watch-variant").setAttribute("aria-pressed",String(Boolean(variantClip&&lastSegment===variantClip))); | |
| by("watch-original").setAttribute("aria-pressed",String(Boolean(variantClip&&lastSegment===approvedClip))); | |
| const waiting=busy && queue.some(cue=>cue.text!==undefined); | |
| const canQueue=busy && livePreview && !livePreview.failed && editOperation==="append" && !queue.length && !questionId; | |
| send.textContent=tr(waiting?"directionQueued":canQueue?"queueDirection":forceRedo.checked?"redoSend":"send"); | |
| send.disabled=(busy&&!canQueue)||stopped||Boolean(variantClip)||submittedDraft!==null||!draft.value.trim(); | |
| by("input-label").textContent=tr((lastSource||inputMode)==="text"?"textLabel":"heard"); | |
| by("interpreter").textContent=interpreter==="Camera cue"?tr("cameraCue"):interpreter; | |
| const muted = Boolean(inputMode==="voice" && take && !stream && !opening && !stopped); | |
| mic.dataset.micState = muted ? "muted" : stream ? "listening" : "idle"; | |
| retry.hidden=!retryKind; | |
| mic.disabled=stopped; | |
| end.disabled=(!take&&!opening)||stopped; | |
| end.title=tr("endSave"); | |
| end.setAttribute("aria-label",tr("endSave")); | |
| drawStage(); | |
| by("heard-text").textContent=lastHeard||"—"; | |
| by("focus-text").textContent=focus?focus.split("+").map(tr).join(" + ")+" · "+prompt:"—"; | |
| timeline?.update(); | |
| if(deskEl)deskEl.dataset.busy=String(!!take&&(busy||stopped)&&!retryKind); | |
| } | |
| function setStatus(k){status=k;label();} | |
| function emit(name,data){ props.value=JSON.stringify({...data,media_key:media.key}); trigger(name); } | |
| function setMode(m){mode=m;monitor.dataset.mode=m;} | |
| function clearPhrase(){pre=[];blocks=[];voice=false;quiet=0;loud=0;phraseSeconds=0;baseline=.003;} | |
| function draw(level=0){meter.clearRect(0,0,88,32);for(let i=0;i<12;i++){meter.fillStyle=level>i/12?"#ffb354":"#515854";const h=5+i*1.8;meter.fillRect(i*7,16-h/2,4,h);}} | |
| function release(keepAudioContext=false){ | |
| micEpoch++;opening=false; | |
| if(micSource){micSource.disconnect();micSource=null;} | |
| if(node){if(node.port)node.port.onmessage=null;else node.onaudioprocess=null;node.disconnect();node=null;} | |
| if(silentOutput){silentOutput.disconnect();silentOutput=null;} | |
| if(stream){stream.getTracks().forEach(t=>t.stop());stream=null;} | |
| if(ctx){idleAudioContext=ctx;ctx=null;} | |
| if(!keepAudioContext && idleAudioContext){idleAudioContext.close().catch(()=>{});idleAudioContext=null;} | |
| clearPhrase();draw();label(); | |
| } | |
| function pauseMic(){ | |
| listenAfterCue=false;dictatingNext=false; | |
| retainSpeech(); | |
| release(); | |
| } | |
| function pauseForWork(){ | |
| dictatingNext=false; | |
| if(stream||opening){retainSpeech();release(listenAfterCue);} | |
| } | |
| function canDictateNext(){ | |
| return processing && take && !stopped && inputMode==="voice" && !queue.length && !variantClip && !questionId | |
| && (inFlight ? inFlight.operation!=="redo_last" && !inFlight.answer : editOperation==="append"); | |
| } | |
| function resumeIfReady(){ | |
| if(listenAfterCue && !processing && !queue.length && !variantClip && take && ready && !stopped && | |
| !(questionId && voiceDraft.length) && inputMode==="voice" && !document.hidden && | |
| by("studio").dataset.view!=="gallery" && !stream && !opening)openMic(); | |
| } | |
| function holdNextDirection(){ | |
| // A failed or ambiguous preceding cue gives a pre-dictated direction back to its author. | |
| const pending=queue.find(c=>c.samples); | |
| if(dictatingNext || pending){ | |
| pauseMic(); | |
| if(pending){voiceDraft=pending.samples;queue=queue.filter(c=>c!==pending);} | |
| } | |
| } | |
| function resetEditing(){ | |
| processing=false;dictatingNext=false; | |
| livePreview=null; | |
| voiceDraft=new Int16Array(0); | |
| approvedClip=variantClip=questionId=inFlight=null;choosing=false;editOperation="append";forceRedo.checked=false; | |
| } | |
| function finish(k){ | |
| listenAfterCue=false; | |
| resetEditing(); | |
| clearTimeout(watchdog); submittedDraft=null;release();queue=[];take=null;ready=false;busy=false;retryKind="";stopped=false;playback.clear(); | |
| if(k==="finished")saved=true; | |
| setMode(saved?"saved":"cover");setStatus(k); | |
| } | |
| function speechSamples(chunks,rate,trimTail){ | |
| const size=chunks.reduce((sum,c)=>sum+c.length,0), indata=new Float32Array(size); | |
| let offset=0;for(const c of chunks){indata.set(c,offset);offset+=c.length;} | |
| const pcm=new Int16Array(Math.floor((size-trimTail)*16000/rate)); | |
| for(let i=0;i<pcm.length;i++){const lo=Math.floor(i*rate/16000),hi=Math.min(size,Math.max(lo+1,Math.floor((i+1)*rate/16000))); | |
| let sum=0;for(let j=lo;j<hi;j++)sum+=indata[j];pcm[i]=Math.round(Math.min(1,Math.max(-1,sum/(hi-lo)))*32767);} | |
| return pcm; | |
| } | |
| function pack(pcm){ | |
| const n=pcm.length,data=new ArrayBuffer(44+n*2),v=new DataView(data); | |
| const str=(at,s)=>{for(let i=0;i<s.length;i++)v.setUint8(at+i,s.charCodeAt(i));}; | |
| str(0,"RIFF");v.setUint32(4,36+n*2,true);str(8,"WAVE");str(12,"fmt ");v.setUint32(16,16,true);v.setUint16(20,1,true);v.setUint16(22,1,true); | |
| v.setUint32(24,16000,true);v.setUint32(28,32000,true);v.setUint16(32,2,true);v.setUint16(34,16,true);str(36,"data");v.setUint32(40,n*2,true); | |
| for(let i=0;i<n;i++)v.setInt16(44+2*i,pcm[i],true); | |
| const u=new Uint8Array(data);let s="";for(let at=0;at<u.length;at+=8192)s+=String.fromCharCode(...u.subarray(at,at+8192));return btoa(s); | |
| } | |
| function cueOptions(){ | |
| const forced=forceRedo.checked && !forceRedo.disabled; | |
| if(forced)forceRedo.checked=false; | |
| return {seconds:Number(seconds.value),operation:forced?"redo_last":"auto", | |
| ...(forced?{target_rev:applied}:{}),...(questionId?{reply_to:questionId}:{})}; | |
| } | |
| forceRedo.addEventListener("change",label); | |
| function pump(){if(!take||!ready||busy||stopped||variantClip||!queue.length)return;timeline?.close();busy=true;retryKind=""; | |
| const {samples,...cue}=queue.shift(), written=cue.text!==undefined; | |
| processing=true;pauseForWork(); | |
| inFlight=cue;setStatus("sent"); | |
| emit(written?"written":"phrase",{take,seq:++seq,...cue,...(samples?{audio:pack(samples)}:{})}); | |
| } | |
| function retainSpeech(){ | |
| if(!voice || !blocks.length || !ctx || loud<=.16)return false; | |
| // Keep the word ending. Normalize here because reopening the mic can change its sample rate. | |
| const trimTail=Math.floor(Math.max(0,quiet-.2)*ctx.sampleRate); | |
| const samples=speechSamples(blocks,ctx.sampleRate,trimTail); | |
| if(voiceDraft.length){ | |
| const joined=new Int16Array(voiceDraft.length+samples.length); | |
| joined.set(voiceDraft);joined.set(samples,voiceDraft.length);voiceDraft=joined; | |
| }else voiceDraft=samples; | |
| return true; | |
| } | |
| function submitVoice(){ | |
| if(!voiceDraft.length || !take || stopped || variantClip || queue.length)return; | |
| queue.push({samples:voiceDraft,...cueOptions()}); | |
| voiceDraft=new Int16Array(0); | |
| pauseForWork(); | |
| label();pump(); | |
| } | |
| function flush(){ | |
| const fresh=retainSpeech(); | |
| clearPhrase(); | |
| if(fresh)submitVoice(); | |
| } | |
| function sample(a){ | |
| if(!ctx||!take||stopped||variantClip||queue.length||(processing&&!dictatingNext))return; | |
| const dt=a.length/ctx.sampleRate;let sum=0;for(const x of a)sum+=x*x; | |
| const rms=Math.sqrt(sum/a.length);draw(Math.min(1,rms*9)); | |
| const sound=rms>Math.max(.008,baseline*3.2); | |
| if(!voice){pre.push(a);if(pre.length*dt>.24)pre.shift(); | |
| if(!sound){baseline=.98*baseline+.02*Math.min(rms,.015);return;} | |
| blocks=pre;pre=[];voice=true;quiet=0;loud=dt;phraseSeconds=dt;return;} | |
| phraseSeconds+=dt; | |
| if(sound && voiceDraft.length/16000+phraseSeconds>maxSpokenSeconds){micFailed("phraseTooLong");return;} | |
| blocks.push(a);if(sound){quiet=0;loud+=dt;}else{quiet+=dt;} | |
| if(quiet>=endSilence)flush(); | |
| } | |
| function startTake(){ | |
| timeline?.reset();media.clear("last-take"); | |
| resetEditing();lastSegment=null;pendingStill="";saved=false;setMode("cover"); | |
| take=crypto.randomUUID();seq=applied=visionRev=0;focus=prompt=lastHeard=lastSource=interpreter=""; | |
| ready=busy=stopped=false;queue=[];retryKind="";playback.clear(); | |
| setStatus("starting");emit("begin",{take,model:videoModel.value}); | |
| watchdog=setTimeout(()=>{if(take&&!ready)finish("connection");},20000); | |
| } | |
| function chooseInput(next){ | |
| inputMode=next; | |
| if(next==="text")pauseMic(); | |
| label(); | |
| if(next==="text")draft.focus(); | |
| } | |
| function sendWritten(){ | |
| if(send.disabled||stopped||inputMode!=="text")return; | |
| const text=draft.value.trim(); | |
| if(!text)return; | |
| if(!take)startTake(); | |
| submittedDraft=draft.value; | |
| queue.push({text,...cueOptions()}); | |
| label();pump(); | |
| } | |
| by("mode-voice").addEventListener("click",()=>chooseInput("voice")); | |
| by("mode-text").addEventListener("click",()=>chooseInput("text")); | |
| send.addEventListener("click",sendWritten); | |
| draft.addEventListener("input",label); | |
| draft.addEventListener("keydown",e=>{ | |
| if(e.key==="Enter"&&!e.shiftKey&&!e.isComposing){e.preventDefault();sendWritten();} | |
| }); | |
| async function openMic(){ | |
| if(opening||stream||stopped||inputMode!=="voice"||document.hidden)return; | |
| micIssue="";opening=true;const epoch=++micEpoch; | |
| label(); | |
| try{ | |
| const capture=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:true,noiseSuppression:true},video:false}); | |
| if(epoch!==micEpoch){capture.getTracks().forEach(t=>t.stop());return;} | |
| // Reuse the user-activated audio context on mobile, with a fresh input track for every capture. | |
| stream=capture;const activeContext=idleAudioContext||new AudioContext();idleAudioContext=null;ctx=activeContext; | |
| let resumeTimer; | |
| try{ | |
| await Promise.race([activeContext.resume(),new Promise((_,reject)=>{resumeTimer=setTimeout(()=>reject(new Error("Audio input paused")),4000);})]); | |
| }finally{clearTimeout(resumeTimer);} | |
| if(epoch!==micEpoch)return; | |
| const moduleSource = /* WORKLET_MODULE */ ""; | |
| let moduleURL,timer; | |
| try{ | |
| if(!workletContexts.has(activeContext)){ | |
| moduleURL=URL.createObjectURL(new Blob([moduleSource],{type:"text/javascript"})); | |
| await Promise.race([activeContext.audioWorklet.addModule(moduleURL),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("worklet timeout")),2500);})]); | |
| workletContexts.add(activeContext); | |
| } | |
| if(epoch!==micEpoch)return; | |
| node=new AudioWorkletNode(activeContext,"ffv-capture"); | |
| node.port.onmessage=e=>{if(epoch===micEpoch)sample(e.data);}; | |
| }catch{ | |
| if(epoch!==micEpoch)return; | |
| node=activeContext.createScriptProcessor(1024,1,1); | |
| node.onaudioprocess=e=>{if(epoch===micEpoch)sample(new Float32Array(e.inputBuffer.getChannelData(0)));}; | |
| }finally{clearTimeout(timer);if(moduleURL)URL.revokeObjectURL(moduleURL);} | |
| micSource=ctx.createMediaStreamSource(capture); | |
| silentOutput=ctx.createGain();silentOutput.gain.value=0;micSource.connect(node);node.connect(silentOutput);silentOutput.connect(ctx.destination); | |
| capture.getAudioTracks()[0].addEventListener("ended",()=>{if(capture===stream)micFailed();}); | |
| if(!take)startTake(); | |
| if (status==="mic_error" || status==="phraseTooLong") setStatus(applied?"holding":"armed"); | |
| }catch(err){if(epoch===micEpoch)micFailed();} | |
| finally{if(epoch===micEpoch){opening=false;label();}} | |
| } | |
| function micFailed(reason="mic_error"){ | |
| listenAfterCue=false;dictatingNext=false; | |
| micIssue=reason; | |
| if(reason==="mic_error")pauseMic();else release(); | |
| if(!busy && !stopped)setStatus(reason); | |
| } | |
| function endSession(){ | |
| listenAfterCue=false;dictatingNext=false;processing=false; | |
| if(opening&&!take){release();setStatus("idle");return;} | |
| if(!take||stopped)return;timeline?.close();stopped=true;retryKind="";queue=[];voiceDraft=new Int16Array(0);playback.clear();release();setStatus("stopping");emit("halt",{take}); | |
| clearTimeout(watchdog);watchdog=setTimeout(()=>{if(stopped)finish("connection");},40000); | |
| } | |
| mic.addEventListener("click",()=>{ | |
| if(stream||opening){pauseMic();return;} | |
| if(processing||variantClip||queue.length){ | |
| if(listenAfterCue)pauseMic(); | |
| else{listenAfterCue=true;micIssue="";label();} | |
| return; | |
| } | |
| listenAfterCue=true;openMic(); | |
| }); | |
| by("dictate-next").addEventListener("click",()=>{ | |
| if(!canDictateNext()||opening||stream)return; | |
| dictatingNext=true;openMic(); | |
| }); | |
| by("send-voice").addEventListener("click",()=>{ | |
| if(stream||opening||by("send-voice").disabled)return; | |
| submitVoice();mic.focus(); | |
| }); | |
| by("discard-voice").addEventListener("click",()=>{ | |
| if(stream||opening)return; | |
| voiceDraft=new Int16Array(0);label();mic.focus(); | |
| }); | |
| end.addEventListener("click",endSession); | |
| langButtons.forEach((b,i)=>b.addEventListener("click",()=>{lang=i?"fr":"en";try{localStorage.setItem("ffv-lang",lang);}catch{}label();collection?.drawItems();})); | |
| function displayClip(clip){ | |
| lastSegment=clip;pendingStill=clip.still; | |
| ({lastHeard,focus,prompt,interpreter,lastSource}=clip); | |
| busy=true;setStatus("loading");playback.segment(clip); | |
| } | |
| function decision(choice){ | |
| if(!variantClip||choosing||stopped)return; | |
| choosing=true;playback.clear();setMode("hold");hold.src=pendingStill; | |
| busy=true;retryKind="";setStatus("deciding");emit("choose",{take,rev:variantClip.rev,choice}); | |
| } | |
| by("keep-original").addEventListener("click",()=>decision("original")); | |
| by("use-variant").addEventListener("click",()=>decision("variant")); | |
| by("watch-original").addEventListener("click",()=>{if(variantClip&&!choosing)displayClip(approvedClip);}); | |
| by("watch-variant").addEventListener("click",()=>{if(variantClip&&!choosing)displayClip(variantClip);}); | |
| for(const [id,answer] of [["answer-redo","redo_last"],["answer-append","append"],["cancel-answer","cancel"]]){ | |
| by(id).addEventListener("click",()=>{ | |
| if(!questionId||busy||stopped)return; | |
| queue.push({text:"",answer,reply_to:questionId});pump(); | |
| }); | |
| } | |
| function endPreview(failed){ | |
| if(livePreview){ | |
| livePreview.ended=true; | |
| livePreview.failed=failed; | |
| if(!livePreview.committed)return; | |
| livePreview=null; | |
| } | |
| if(failed)retryKind="playback"; | |
| completePlayback(failed?"play_error":"holding"); | |
| } | |
| function completePlayback(statusKey){ | |
| if(!take || stopped) return; | |
| hold.src=pendingStill;if(!playback.isLooping())setMode("hold");busy=false;setStatus(variantClip&&statusKey==="holding"?"review":statusKey);pump(); | |
| } | |
| retry.addEventListener("click",()=>{ | |
| const action=retryKind;retryKind=""; | |
| if(action==="playback" && lastSegment && !stopped){busy=true;setStatus("loading");playback.segment(lastSegment);return;} | |
| if(action==="export"){setStatus("finalizing");emit("export_take",{take,device:collection?.device});return;} | |
| if(action==="render" && take && !stopped){ | |
| processing=true;busy=true;pauseForWork();setStatus("renderPending");emit("roll",{take,stream_preview:true,rev:visionRev}); | |
| } | |
| }); | |
| window.addEventListener("ffv-signal",e=>{ | |
| let d;try{d=JSON.parse(e.detail);}catch{return;} | |
| if(collection?.signal(d))return; | |
| if(!take||d.take!==take)return; | |
| if(d.phase==="expired"){timeline.reset();finish("expired");return;} | |
| if(d.phase==="invalid_model"){finish("invalid_model");return;} | |
| if(d.media && ["archiving","archive_error","finished"].includes(d.phase)){ | |
| media.show("last-take",d.media).catch(()=>setStatus("history_error")); | |
| } | |
| if(d.phase==="closed"||d.phase==="finished"){finish(d.phase);return;} | |
| if(d.phase==="stopping"){ | |
| clearTimeout(watchdog);setStatus("finalizing");emit("export_take",{take,device:collection?.device});return; | |
| } | |
| if(d.phase==="archiving"){setMode("saved");setStatus("archiving");return;} | |
| if(d.phase==="archive_error"){clearTimeout(watchdog);retryKind="export";setMode("saved");setStatus(d.phase);return;} | |
| if(d.phase==="export_error"){clearTimeout(watchdog);retryKind="export";setStatus(d.phase);return;} | |
| if(stopped)return; | |
| if(d.phase==="armed"){clearTimeout(watchdog);ready=true;setStatus("armed");pump();return;} | |
| if(d.phase==="interpreting"){lastSource=d.source;lastHeard=d.heard;setStatus(d.phase);return;} | |
| if(d.phase==="clarify"||d.phase==="accepted"){ | |
| if(d.phase==="accepted"&&d.rev<=visionRev)return; | |
| if(draft.value===submittedDraft)draft.value=""; | |
| submittedDraft=null;inFlight=null; | |
| interpreter=d.interpreter||"";lastSource=d.source; | |
| lastHeard=d.heard;prompt=d.summary;focus=d.focus; | |
| if(d.phase==="clarify"){ | |
| holdNextDirection();processing=false;questionId=d.question;queue=[];clearPhrase();busy=false;setStatus("clarify");resumeIfReady();return; | |
| } | |
| questionId=null;editOperation=d.operation||"append"; | |
| if(editOperation==="redo_last"){holdNextDirection();pauseForWork();queue=[];clearPhrase();} | |
| visionRev=d.rev; | |
| setStatus("renderPending");emit("roll",{take,stream_preview:true,rev:d.rev});return; | |
| } | |
| if(d.phase==="question_cancelled"){ | |
| processing=false;questionId=null;submittedDraft=null;inFlight=null;busy=false;setStatus("holding");pump();resumeIfReady();return; | |
| } | |
| if(d.phase==="decided"&&variantClip&&d.rev===variantClip.rev){ | |
| if(d.choice==="variant"){approvedClip=variantClip;timeline.add(approvedClip,true);} | |
| variantClip=null;choosing=false;editOperation="append";retryKind=""; | |
| lastSegment=approvedClip;applied=approvedClip.rev;pendingStill=approvedClip.still; | |
| ({lastHeard,focus,prompt,interpreter,lastSource}=approvedClip); | |
| hold.src=pendingStill;setMode("hold");playback.repeatClip(approvedClip);syncLoop();busy=false;setStatus("holding");pump();resumeIfReady();return; | |
| } | |
| if(d.phase==="decision_error"){choosing=false;busy=false;setStatus("decision_error");return;} | |
| if(["ignored","empty","speech_error","locked_segment","invalid_text","invalid_seconds","invalid_target","invalid_operation"].includes(d.phase)){ | |
| if(inFlight?.operation==="redo_last"&&inFlight.target_rev===applied)forceRedo.checked=true; | |
| holdNextDirection();pauseMic();processing=false;submittedDraft=null;inFlight=null;busy=false;setStatus(d.phase==="ignored"?(applied?"holding":"armed"):d.phase);pump();return; | |
| } | |
| if(d.phase==="ignored_roll" || (d.rev && d.rev!==visionRev))return; | |
| if(d.phase==="preview"){ | |
| const first=!livePreview || livePreview.path!==d.preview; | |
| if(first){ | |
| livePreview={path:d.preview,ended:false,failed:false,committed:false}; | |
| } | |
| // The server publishes complete eight-frame strips after decoding and writing them. | |
| livePreview.frames=d.frames; | |
| livePreview.readyFrames=Math.min(d.frames,Math.max(livePreview.readyFrames||0,d.ready*8)); | |
| const generating=editOperation==="redo_last"?"redoGenerating":"generating"; | |
| if(first || status!==generating)setStatus(generating);else drawStage(); | |
| if(!livePreview.ended)playback.extend(d,d.ready); | |
| return; | |
| } | |
| if(["gpu_error","quota","hardware","disk_full"].includes(d.phase)){ | |
| holdNextDirection();pauseMic();processing=false; | |
| // A written direction queued against a failed segment stays in the editor. | |
| if(queue.some(cue=>cue.text!==undefined)){ | |
| queue=queue.filter(cue=>cue.text===undefined);submittedDraft=null; | |
| } | |
| if(livePreview){ | |
| playback.clear();livePreview=null; | |
| if(approvedClip){hold.src=approvedClip.still;setMode("hold");playback.repeatClip(approvedClip);syncLoop();}else setMode("cover"); | |
| } | |
| busy=false;retryKind="render";setStatus(d.phase);return; | |
| } | |
| if(d.phase==="segment"||d.phase==="variant"){ | |
| if(d.rev<=applied||variantClip?.rev===d.rev)return; | |
| processing=false; | |
| const clip={thumb:d.thumb,media:d.media,preview:d.preview,frames:d.frames,still:d.still,rev:d.rev,seconds:d.seconds,lastHeard,prompt,focus,interpreter,lastSource}; | |
| if(d.phase==="variant")variantClip=clip; | |
| else {approvedClip=clip;applied=d.rev;timeline.add(clip);} | |
| if(livePreview && !livePreview.failed){ | |
| lastSegment=clip;pendingStill=clip.still;livePreview.committed=true; | |
| // A slow client can miss intermediate Gradio events. The final publication confirms all strips. | |
| if(livePreview.ended)endPreview(false); | |
| else { | |
| setStatus(livePreview.started?"playing":"loading"); | |
| playback.extend({...clip,preview:livePreview.path},Math.ceil(clip.frames/8)); | |
| } | |
| }else{livePreview=null;displayClip(clip);} | |
| label();resumeIfReady(); | |
| return; | |
| } | |
| setStatus(d.phase==="generating"&&editOperation==="redo_last"?"redoGenerating":d.phase); | |
| }); | |
| window.addEventListener("pagehide",event=>{if(take)endSession();release();if(!event.persisted)playback.dispose();}); | |
| timeline=shotTimeline(); | |
| const keepAlive=setInterval(()=>{if(take&&ready&&!busy&&!stopped)emit("heartbeat",{take});},60000); | |
| window.addEventListener("pagehide",e=>{if(!e.persisted)clearInterval(keepAlive);}); | |
| collection=sessionCollection();draw();setMode("cover");label(); | |