Spaces:
Running on Zero
Running on Zero
Advance one continuous shot per spoken direction
Browse files- README.md +6 -2
- app.py +55 -39
- assets/desk.html +1 -1
- assets/monitor.html +2 -1
- assets/playback.js +34 -67
- assets/studio.css +6 -2
- assets/studio.js +56 -26
- engine.py +28 -0
- render.py +64 -54
- takes.py +88 -26
README.md
CHANGED
|
@@ -23,9 +23,13 @@ models:
|
|
| 23 |
|
| 24 |
# FastFrames Voice
|
| 25 |
|
| 26 |
-
A private research prototype for directing a continuous generated shot with short spoken cues. Version 0.
|
| 27 |
|
| 28 |
-
Start the microphone,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
## Running the Space
|
| 31 |
|
|
|
|
| 23 |
|
| 24 |
# FastFrames Voice
|
| 25 |
|
| 26 |
+
A private research prototype for directing a continuous generated shot with short spoken cues. Version 0.2.0.
|
| 27 |
|
| 28 |
+
Start the microphone, describe a scene and pause briefly. Each accepted direction generates one silent segment at 832 × 480 and 16 fps. The opening segment contains 61 frames (3.8125 s) and subsequent segments contain 64 (4 s). The last generated image stays in the monitor while you think or while the next cue is being interpreted. End session joins completed segments into a downloadable MP4. Microphone mute discards unsubmitted audio and stops capture. Unmute continues the same take. Inline playback is requested on iPhone, with a tap-to-play button if autoplay is blocked.
|
| 29 |
+
|
| 30 |
+
Fluid Speech Pro transcribes on CPU. Qwen updates the shot description using the last completed direction. FastFrames-S receives one ZeroGPU allocation per segment, with a 60-second maximum runtime for computation and checkpoint I/O. Between directions, the session keeps its exact occupied attention cache, decoder history, frame indices and random generator state on the Space's temporary filesystem. The previous checkpoint is replaced only after the next segment is complete. Ending the take releases the checkpoint. Closing the page or starting another take removes its session workspace. The recordings and resumable state are temporary and do not survive a Space restart.
|
| 31 |
+
|
| 32 |
+
API clients use the same Gradio session throughout. Call `begin`, then `voice_direction` with the take ID, increasing sequence number and base64 mono 16 kHz PCM WAV. For each accepted cue, call `live_take` with its take ID and revision. Its first video output contains the new MP4 when the phase is `segment`. Wait for completion before the next cue. `end_take` closes the shot, then `export_take` returns the full recording. A failed render can be retried with the same revision or replaced by a new direction.
|
| 33 |
|
| 34 |
## Running the Space
|
| 35 |
|
app.py
CHANGED
|
@@ -4,7 +4,6 @@ import json
|
|
| 4 |
import logging
|
| 5 |
import shutil
|
| 6 |
import tempfile
|
| 7 |
-
import time
|
| 8 |
from pathlib import Path
|
| 9 |
|
| 10 |
import gradio as gr
|
|
@@ -34,7 +33,7 @@ def phrase(raw: str, request: gr.Request):
|
|
| 34 |
p,key = payload(raw,request)
|
| 35 |
tag = p["take"]
|
| 36 |
seq = p.get("seq")
|
| 37 |
-
if not isinstance(seq,int) or not 1<=seq<
|
| 38 |
yield msg(tag,"ignored",seq=seq)
|
| 39 |
return
|
| 40 |
try:
|
|
@@ -44,7 +43,7 @@ def phrase(raw: str, request: gr.Request):
|
|
| 44 |
yield msg(tag,"empty",seq=seq)
|
| 45 |
return
|
| 46 |
old = takes.get(key)
|
| 47 |
-
if old.get("phase")
|
| 48 |
yield msg(tag,"ignored",seq=seq)
|
| 49 |
return
|
| 50 |
yield msg(tag,"interpreting",seq=seq,heard=heard)
|
|
@@ -57,62 +56,78 @@ def phrase(raw: str, request: gr.Request):
|
|
| 57 |
except Exception:
|
| 58 |
LOG.exception("voice processing failed for %s",key[:8])
|
| 59 |
yield msg(tag,"speech_error",seq=seq)
|
|
|
|
|
|
|
| 60 |
|
| 61 |
def stop(raw: str, request: gr.Request):
|
| 62 |
p,key = payload(raw,request)
|
| 63 |
-
takes.close(key)
|
| 64 |
-
return msg(p["take"],"stopping")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
def live(raw: str, request: gr.Request):
|
| 67 |
p,key = payload(raw,request)
|
| 68 |
tag = p["take"]
|
|
|
|
|
|
|
| 69 |
skip = gr.skip
|
| 70 |
-
if not takes.claim(key):
|
| 71 |
-
yield skip(),skip(),msg(tag,"
|
| 72 |
return
|
| 73 |
-
segments = []
|
| 74 |
-
folder = Path(tempfile.mkdtemp(prefix="voice-segments-"))
|
| 75 |
stream = None
|
|
|
|
|
|
|
| 76 |
try:
|
| 77 |
if not render.GPU_AVAILABLE:
|
| 78 |
-
|
|
|
|
|
|
|
| 79 |
return
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
for
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
if segments:
|
| 95 |
-
yield skip(),skip(),msg(tag,"finalizing")
|
| 96 |
-
result = render.finalize(segments,folder)
|
| 97 |
-
yield skip(),result,msg(tag,"finished")
|
| 98 |
-
else:
|
| 99 |
-
yield skip(),skip(),msg(tag,"closed")
|
| 100 |
except Exception as exc:
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
| 105 |
finally:
|
| 106 |
-
takes.close(key)
|
| 107 |
if stream is not None and hasattr(stream,"close"):
|
| 108 |
with contextlib.suppress(Exception):
|
| 109 |
stream.close()
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
def unload(request: gr.Request):
|
| 114 |
if request.session_hash:
|
| 115 |
-
takes.
|
| 116 |
|
| 117 |
CSS=asset("studio.css")
|
| 118 |
BUS_JS="watch('value', () => { if (props.value) window.dispatchEvent(new CustomEvent('ffv-signal', {detail: props.value})); });"
|
|
@@ -121,7 +136,7 @@ with gr.Blocks(title="FastFrames Voice",fill_width=True,delete_cache=(600,1800))
|
|
| 121 |
gr.HTML(asset("header.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-header")
|
| 122 |
with gr.Column(elem_id="monitor"):
|
| 123 |
gr.HTML(asset("monitor.html"),apply_default_css=False,padding=False,container=False,elem_id="cover")
|
| 124 |
-
feed=gr.Video(label="
|
| 125 |
show_label=False,container=False,buttons=[],elem_id="live-feed")
|
| 126 |
replay=gr.Video(label="Last take",interactive=False,show_label=False,container=False,
|
| 127 |
buttons=["download"],elem_id="last-take")
|
|
@@ -137,6 +152,7 @@ with gr.Blocks(title="FastFrames Voice",fill_width=True,delete_cache=(600,1800))
|
|
| 137 |
desk.phrase(phrase,[desk],cpu_bus,api_name="voice_direction",concurrency_limit=3,show_progress="hidden")
|
| 138 |
desk.roll(live,[desk],[feed,replay,gpu_bus],api_name="live_take",concurrency_limit=2,show_progress="hidden")
|
| 139 |
desk.halt(stop,[desk],control_bus,queue=False,api_name="end_take",show_progress="hidden")
|
|
|
|
| 140 |
demo.unload(unload)
|
| 141 |
demo.queue(max_size=24)
|
| 142 |
if __name__=="__main__":
|
|
|
|
| 4 |
import logging
|
| 5 |
import shutil
|
| 6 |
import tempfile
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
import gradio as gr
|
|
|
|
| 33 |
p,key = payload(raw,request)
|
| 34 |
tag = p["take"]
|
| 35 |
seq = p.get("seq")
|
| 36 |
+
if not isinstance(seq,int) or not 1<=seq<2**31 or not takes.reserve(key,seq):
|
| 37 |
yield msg(tag,"ignored",seq=seq)
|
| 38 |
return
|
| 39 |
try:
|
|
|
|
| 43 |
yield msg(tag,"empty",seq=seq)
|
| 44 |
return
|
| 45 |
old = takes.get(key)
|
| 46 |
+
if old.get("phase") != "interpreting":
|
| 47 |
yield msg(tag,"ignored",seq=seq)
|
| 48 |
return
|
| 49 |
yield msg(tag,"interpreting",seq=seq,heard=heard)
|
|
|
|
| 56 |
except Exception:
|
| 57 |
LOG.exception("voice processing failed for %s",key[:8])
|
| 58 |
yield msg(tag,"speech_error",seq=seq)
|
| 59 |
+
finally:
|
| 60 |
+
takes.release_phrase(key,seq)
|
| 61 |
|
| 62 |
def stop(raw: str, request: gr.Request):
|
| 63 |
p,key = payload(raw,request)
|
| 64 |
+
count = takes.close(key)
|
| 65 |
+
return msg(p["take"], "stopping" if count else "closed", rendered=count)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def export_take(raw: str, request: gr.Request):
|
| 69 |
+
p,key = payload(raw,request)
|
| 70 |
+
if takes.get(key).get("phase") != "stopped":
|
| 71 |
+
return gr.skip(),msg(p["take"],"export_error")
|
| 72 |
+
try:
|
| 73 |
+
path = render.finalize(takes.ROOT / key)
|
| 74 |
+
return path,msg(p["take"],"finished")
|
| 75 |
+
except Exception:
|
| 76 |
+
LOG.exception("export failed for %s",key[:8])
|
| 77 |
+
return gr.skip(),msg(p["take"],"export_error")
|
| 78 |
+
|
| 79 |
|
| 80 |
def live(raw: str, request: gr.Request):
|
| 81 |
p,key = payload(raw,request)
|
| 82 |
tag = p["take"]
|
| 83 |
+
row = takes.get(key)
|
| 84 |
+
rev = p.get("rev", row.get("rev",0))
|
| 85 |
skip = gr.skip
|
| 86 |
+
if not takes.claim(key, rev):
|
| 87 |
+
yield skip(),skip(),msg(tag,"ignored_roll",rev=rev)
|
| 88 |
return
|
|
|
|
|
|
|
| 89 |
stream = None
|
| 90 |
+
stage = None
|
| 91 |
+
release_claim = True
|
| 92 |
try:
|
| 93 |
if not render.GPU_AVAILABLE:
|
| 94 |
+
takes.fail(key,rev)
|
| 95 |
+
release_claim = False
|
| 96 |
+
yield skip(),skip(),msg(tag,"hardware",rev=rev)
|
| 97 |
return
|
| 98 |
+
stage = Path(tempfile.mkdtemp(prefix="pending-",dir=takes.ROOT))
|
| 99 |
+
yield skip(),skip(),msg(tag,"queued",rev=rev)
|
| 100 |
+
stream = render.generate(key,rev,row["rendered"],row["next_prompt"],str(stage))
|
| 101 |
+
for phase in stream:
|
| 102 |
+
yield skip(),skip(),msg(tag,phase,rev=rev)
|
| 103 |
+
if not takes.active(key,rev):
|
| 104 |
+
return
|
| 105 |
+
yield skip(),skip(),msg(tag,"encoding",rev=rev)
|
| 106 |
+
filename = f"cue-{key[:12]}-{rev}.mp4"
|
| 107 |
+
still = render.encode(stage,filename)
|
| 108 |
+
if takes.publish(key,rev,stage):
|
| 109 |
+
release_claim = False
|
| 110 |
+
folder = takes.completed(key,rev)
|
| 111 |
+
yield str(folder / filename),skip(),msg(tag,"segment",rev=rev,file=filename,still=still)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
except Exception as exc:
|
| 113 |
+
if takes.fail(key,rev):
|
| 114 |
+
release_claim = False
|
| 115 |
+
LOG.exception("cue failed %s rev=%d",key[:8],rev)
|
| 116 |
+
reason = "quota" if "quota" in str(exc).lower() else "gpu_error"
|
| 117 |
+
yield skip(),skip(),msg(tag,reason,rev=rev)
|
| 118 |
finally:
|
|
|
|
| 119 |
if stream is not None and hasattr(stream,"close"):
|
| 120 |
with contextlib.suppress(Exception):
|
| 121 |
stream.close()
|
| 122 |
+
if release_claim:
|
| 123 |
+
takes.fail(key,rev)
|
| 124 |
+
if stage is not None:
|
| 125 |
+
shutil.rmtree(stage,ignore_errors=True)
|
| 126 |
+
|
| 127 |
|
| 128 |
def unload(request: gr.Request):
|
| 129 |
if request.session_hash:
|
| 130 |
+
takes.forget(request.session_hash)
|
| 131 |
|
| 132 |
CSS=asset("studio.css")
|
| 133 |
BUS_JS="watch('value', () => { if (props.value) window.dispatchEvent(new CustomEvent('ffv-signal', {detail: props.value})); });"
|
|
|
|
| 136 |
gr.HTML(asset("header.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-header")
|
| 137 |
with gr.Column(elem_id="monitor"):
|
| 138 |
gr.HTML(asset("monitor.html"),apply_default_css=False,padding=False,container=False,elem_id="cover")
|
| 139 |
+
feed=gr.Video(label="Current segment",streaming=False,autoplay=False,interactive=False,
|
| 140 |
show_label=False,container=False,buttons=[],elem_id="live-feed")
|
| 141 |
replay=gr.Video(label="Last take",interactive=False,show_label=False,container=False,
|
| 142 |
buttons=["download"],elem_id="last-take")
|
|
|
|
| 152 |
desk.phrase(phrase,[desk],cpu_bus,api_name="voice_direction",concurrency_limit=3,show_progress="hidden")
|
| 153 |
desk.roll(live,[desk],[feed,replay,gpu_bus],api_name="live_take",concurrency_limit=2,show_progress="hidden")
|
| 154 |
desk.halt(stop,[desk],control_bus,queue=False,api_name="end_take",show_progress="hidden")
|
| 155 |
+
desk.export_take(export_take,[desk],[replay,control_bus],api_name="export_take",concurrency_limit=2,show_progress="hidden")
|
| 156 |
demo.unload(unload)
|
| 157 |
demo.queue(max_size=24)
|
| 158 |
if __name__=="__main__":
|
assets/desk.html
CHANGED
|
@@ -8,4 +8,4 @@
|
|
| 8 |
<div class="readout"><span class="label" data-tr="heard">Heard</span><p id="heard-text">—</p></div>
|
| 9 |
<div class="readout"><span class="label" data-tr="direction">Interpreted direction</span><p id="focus-text">—</p></div>
|
| 10 |
</section>
|
| 11 |
-
<div class="status-row"><p class="stage-status" role="status" aria-live="polite"><span id="status-dot"></span><span id="stage-text">Microphone off</span></p><button type="button" id="play-inline" data-tr="playVideo" hidden>Play
|
|
|
|
| 8 |
<div class="readout"><span class="label" data-tr="heard">Heard</span><p id="heard-text">—</p></div>
|
| 9 |
<div class="readout"><span class="label" data-tr="direction">Interpreted direction</span><p id="focus-text">—</p></div>
|
| 10 |
</section>
|
| 11 |
+
<div class="status-row"><p class="stage-status" role="status" aria-live="polite"><span id="status-dot"></span><span id="stage-text">Microphone off</span></p><button type="button" id="play-inline" data-tr="playVideo" hidden>Play segment</button><button type="button" id="retry-cue" data-tr="retryCue" hidden>Retry</button><span class="take-limit" data-tr="limit">≈ 4 s per cue</span></div>
|
assets/monitor.html
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
<div class="viewfinder">
|
| 2 |
<img src="./gradio_api/file=assets/preview.jpg" alt="" class="still">
|
| 3 |
-
<div class="cover-copy"><span class="label" data-tr="preview">Preview frame</span><strong data-tr="intro">Describe your opening shot.</strong><span data-tr="help">
|
| 4 |
</div>
|
|
|
|
|
|
| 1 |
<div class="viewfinder">
|
| 2 |
<img src="./gradio_api/file=assets/preview.jpg" alt="" class="still">
|
| 3 |
+
<div class="cover-copy"><span class="label" data-tr="preview">Preview frame</span><strong data-tr="intro">Describe your opening shot.</strong><span data-tr="help">Speak, then pause. Each direction adds about four seconds to the shot.</span></div>
|
| 4 |
</div>
|
| 5 |
+
<img id="held-frame" alt="">
|
assets/playback.js
CHANGED
|
@@ -1,90 +1,57 @@
|
|
| 1 |
-
/* Gradio
|
| 2 |
-
function inlinePlayback(monitor, playButton) {
|
| 3 |
-
let
|
| 4 |
-
let live = null;
|
| 5 |
-
let attempted = false;
|
| 6 |
-
let attemptId = 0;
|
| 7 |
-
|
| 8 |
function configure(video) {
|
| 9 |
if (!video.playsInline) video.playsInline = true;
|
| 10 |
-
if (!video.hasAttribute("playsinline")) video.setAttribute("playsinline", "");
|
| 11 |
if (!video.hasAttribute("webkit-playsinline")) video.setAttribute("webkit-playsinline", "");
|
| 12 |
if (video.closest("#live-feed")) {
|
| 13 |
if (!video.defaultMuted) video.defaultMuted = true;
|
| 14 |
if (!video.muted) video.muted = true;
|
| 15 |
}
|
| 16 |
}
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
attempted = false;
|
| 20 |
-
attemptId++;
|
| 21 |
-
playButton.hidden = true;
|
| 22 |
}
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
if (!
|
| 26 |
-
configure(
|
| 27 |
attempted = true;
|
| 28 |
-
const id = ++attemptId;
|
| 29 |
playButton.hidden = true;
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
if (
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
playButton.hidden = false;
|
| 36 |
-
}
|
| 37 |
});
|
| 38 |
}
|
| 39 |
-
|
| 40 |
function sync() {
|
| 41 |
-
for (const
|
| 42 |
-
configure(
|
| 43 |
-
|
| 44 |
-
const next = monitor.querySelector("#live-feed video");
|
| 45 |
-
if (next !== live) {
|
| 46 |
-
live = next;
|
| 47 |
-
reset();
|
| 48 |
-
}
|
| 49 |
-
if (mode === "live" && live && !attempted && live.readyState >= 2) {
|
| 50 |
-
playLive();
|
| 51 |
}
|
| 52 |
}
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
if
|
| 59 |
-
if
|
| 60 |
-
if
|
| 61 |
-
attempted = true;
|
| 62 |
-
playButton.hidden = true;
|
| 63 |
-
}
|
| 64 |
sync();
|
| 65 |
}
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
const observer = new MutationObserver(sync);
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
childList: true, subtree: true, attributes: true,
|
| 73 |
-
attributeFilter: ["playsinline", "webkit-playsinline", "muted"]
|
| 74 |
-
});
|
| 75 |
-
playButton.addEventListener("click", playLive);
|
| 76 |
sync();
|
| 77 |
-
|
| 78 |
return {
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
mode = next;
|
| 82 |
-
sync();
|
| 83 |
-
},
|
| 84 |
-
dispose() {
|
| 85 |
-
observer.disconnect();
|
| 86 |
-
events.forEach(name => monitor.removeEventListener(name, onMedia, true));
|
| 87 |
-
playButton.removeEventListener("click", playLive);
|
| 88 |
-
}
|
| 89 |
};
|
| 90 |
}
|
|
|
|
| 1 |
+
/* Gradio supplies the MP4. Match the requested file before playing a new cue. */
|
| 2 |
+
function inlinePlayback(monitor, playButton, onStart, onEnd, onError) {
|
| 3 |
+
let target = "", attempted = false, version = 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
function configure(video) {
|
| 5 |
if (!video.playsInline) video.playsInline = true;
|
|
|
|
| 6 |
if (!video.hasAttribute("webkit-playsinline")) video.setAttribute("webkit-playsinline", "");
|
| 7 |
if (video.closest("#live-feed")) {
|
| 8 |
if (!video.defaultMuted) video.defaultMuted = true;
|
| 9 |
if (!video.muted) video.muted = true;
|
| 10 |
}
|
| 11 |
}
|
| 12 |
+
function matches(video) {
|
| 13 |
+
return !!target && video.closest("#live-feed") && video.currentSrc.split("?")[0].endsWith("/"+target);
|
|
|
|
|
|
|
|
|
|
| 14 |
}
|
| 15 |
+
function play() {
|
| 16 |
+
const v = monitor.querySelector("#live-feed video");
|
| 17 |
+
if (!v || !matches(v)) return;
|
| 18 |
+
configure(v);
|
| 19 |
attempted = true;
|
|
|
|
| 20 |
playButton.hidden = true;
|
| 21 |
+
const id = version;
|
| 22 |
+
v.play().catch(error => {
|
| 23 |
+
if (id !== version) return;
|
| 24 |
+
attempted = false;
|
| 25 |
+
if (error.name !== "AbortError") playButton.hidden = false;
|
|
|
|
|
|
|
| 26 |
});
|
| 27 |
}
|
|
|
|
| 28 |
function sync() {
|
| 29 |
+
for (const v of monitor.querySelectorAll("#live-feed video, #last-take video")) {
|
| 30 |
+
configure(v);
|
| 31 |
+
if (matches(v) && !attempted && playButton.hidden && v.readyState >= 2) play();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
}
|
| 34 |
+
function media(e) {
|
| 35 |
+
const v = e.target;
|
| 36 |
+
if (!(v instanceof HTMLVideoElement)) return;
|
| 37 |
+
configure(v);
|
| 38 |
+
if (!matches(v)) return;
|
| 39 |
+
if(e.type === "error"){ clear(); onError(); return; }
|
| 40 |
+
if(e.type === "playing"){playButton.hidden = true; onStart();}
|
| 41 |
+
if(e.type === "ended"){ clear(); onEnd(); return; }
|
|
|
|
|
|
|
|
|
|
| 42 |
sync();
|
| 43 |
}
|
| 44 |
+
function clear() {
|
| 45 |
+
target = ""; attempted = false; version++; playButton.hidden = true;
|
| 46 |
+
}
|
| 47 |
+
const events = ["loadedmetadata","loadeddata","canplay","playing","ended","volumechange","error"];
|
| 48 |
+
events.forEach(k=>monitor.addEventListener(k,media,true));
|
| 49 |
const observer = new MutationObserver(sync);
|
| 50 |
+
observer.observe(monitor,{childList:true,subtree:true,attributes:true,attributeFilter:["playsinline","muted","webkit-playsinline","src"]});
|
| 51 |
+
playButton.addEventListener("click",play);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
sync();
|
|
|
|
| 53 |
return {
|
| 54 |
+
segment(file){clear();target=file;sync();}, clear,
|
| 55 |
+
dispose(){clear();observer.disconnect();events.forEach(k=>monitor.removeEventListener(k,media,true));playButton.removeEventListener("click",play);}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
};
|
| 57 |
}
|
assets/studio.css
CHANGED
|
@@ -50,5 +50,9 @@
|
|
| 50 |
|
| 51 |
#mic-key .mic-slash {display:none}
|
| 52 |
#mic-key[data-mic-state=muted] .mic-slash {display:block;stroke-width:2.6}
|
| 53 |
-
#studio #play-inline {min-height:44px;margin-left:auto;padding:0 12px;border:1px solid #666e6b;border-radius:5px;background:#222726;color:#f4f4f0}
|
| 54 |
-
#studio #play-inline[hidden] {display:none!important}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
#mic-key .mic-slash {display:none}
|
| 52 |
#mic-key[data-mic-state=muted] .mic-slash {display:block;stroke-width:2.6}
|
| 53 |
+
#studio :is(#play-inline,#retry-cue) {min-height:44px;margin-left:auto;padding:0 12px;border:1px solid #666e6b;border-radius:5px;background:#222726;color:#f4f4f0}
|
| 54 |
+
#studio :is(#play-inline,#retry-cue)[hidden] {display:none!important}
|
| 55 |
+
|
| 56 |
+
#held-frame{display:none;position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#080909}
|
| 57 |
+
#monitor[data-mode=hold] #held-frame{display:block}
|
| 58 |
+
#monitor[data-mode=hold] .viewfinder{display:none}
|
assets/studio.js
CHANGED
|
@@ -2,24 +2,32 @@ const root = element.getRootNode();
|
|
| 2 |
const by = id => root.getElementById(id) || document.getElementById(id);
|
| 3 |
const deskEl = by("voice-desk");
|
| 4 |
const mic = by("mic-key"), end = by("end-take"), monitor = by("monitor");
|
| 5 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
const meter = by("mic-level").getContext("2d");
|
| 7 |
const langButtons = [by("lang-en"), by("lang-fr")];
|
| 8 |
const copy = {
|
| 9 |
end:["End session","Terminer"],intro:["Describe your opening shot.","Décris ton premier plan."],
|
| 10 |
-
preview:["Preview frame","Aperçu"],help:["
|
| 11 |
-
heard:["Heard","Transcription"],direction:["Interpreted direction","Consigne interprétée"],limit:["
|
| 12 |
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"],
|
| 13 |
-
muted:["Mic muted","Micro coupé"],playVideo:["Play
|
| 14 |
permission:["Opening microphone…","Ouverture du micro…"],armed:["Listening for your opening shot","À l’écoute du premier plan"],
|
| 15 |
transcribing:["Transcribing…","Transcription…"],interpreting:["Interpreting direction…","Interprétation de la consigne…"],
|
| 16 |
queued:["Requesting GPU…","Demande de GPU…"],allocated:["GPU allocated · preparing frames","GPU alloué · préparation des images"],
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
stopping:["Ending session…","Fin de session…"],finalizing:["Preparing recording…","Préparation de la vidéo…"],
|
| 19 |
finished:["Take ready · replay or download","Prise prête · lecture et téléchargement"],closed:["Session ended","Session terminée"],
|
| 20 |
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"],
|
| 21 |
mic_error:["Microphone unavailable · check browser permission and try again","Micro indisponible · vérifie l’autorisation du navigateur et réessaie"],
|
| 22 |
-
quota:["GPU quota unavailable · try again later","Quota GPU indisponible · réessaie plus tard"],gpu_error:["
|
| 23 |
hardware:["Video requires ZeroGPU · microphone test complete","La vidéo nécessite ZeroGPU · essai micro terminé"],
|
| 24 |
codec:["H.264 playback is unavailable in this browser","Ce navigateur ne peut pas lire la vidéo H.264"],
|
| 25 |
connection:["Session connection interrupted · try again","Connexion interrompue · réessaie"],
|
|
@@ -29,7 +37,7 @@ let lang = "en"; try { lang = localStorage.getItem("ffv-lang")==="fr"?"fr":"en";
|
|
| 29 |
const tr = k => (copy[k] || [k,k])[lang==="fr"?1:0];
|
| 30 |
let take = null, status = "idle", mode = "idle", focus="", prompt="", lastHeard="";
|
| 31 |
let stream=null, ctx=null, node=null, opening=false, stopped=false, micEpoch=0;
|
| 32 |
-
let ready=false, busy=false,
|
| 33 |
let queue=[], pre=[], blocks=[], voice=false, quiet=0, loud=0, baseline=.003, watchdog=0;
|
| 34 |
function label(){
|
| 35 |
root.querySelectorAll("[data-tr]").forEach(e=>e.textContent=tr(e.dataset.tr));
|
|
@@ -37,6 +45,7 @@ function label(){
|
|
| 37 |
by("mic-word").textContent=tr(!take?"start":stream?"on":"off");
|
| 38 |
const muted = Boolean(take && !stream && !opening && !stopped);
|
| 39 |
mic.dataset.micState = muted ? "muted" : stream ? "listening" : "idle";
|
|
|
|
| 40 |
mic.disabled=opening||stopped;
|
| 41 |
end.disabled=(!take&&!opening)||stopped;
|
| 42 |
const stage = opening ? tr("permission") : tr(status);
|
|
@@ -44,11 +53,11 @@ function label(){
|
|
| 44 |
? (status === "armed" ? tr("muted") : tr("muted")+" · "+stage) : stage;
|
| 45 |
by("heard-text").textContent=lastHeard||"—";
|
| 46 |
by("focus-text").textContent=focus?focus.split("+").map(tr).join(" + ")+" · "+prompt:"—";
|
| 47 |
-
if(deskEl)deskEl.dataset.busy=String(!!take&&
|
| 48 |
}
|
| 49 |
function setStatus(k){status=k;label();}
|
| 50 |
function emit(name,data){ props.value=JSON.stringify(data); trigger(name); }
|
| 51 |
-
function setMode(m){mode=m;monitor.dataset.mode=m;
|
| 52 |
function clearPhrase(){pre=[];blocks=[];voice=false;quiet=0;loud=0;baseline=.003;}
|
| 53 |
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);}}
|
| 54 |
function release(){
|
|
@@ -59,7 +68,7 @@ function release(){
|
|
| 59 |
clearPhrase();draw();label();
|
| 60 |
}
|
| 61 |
function finish(k){
|
| 62 |
-
clearTimeout(watchdog); release();queue=[];take=null;ready=false;busy=false;
|
| 63 |
if(k==="finished")saved=true;
|
| 64 |
setMode(saved?"saved":"cover");setStatus(k);
|
| 65 |
}
|
|
@@ -74,7 +83,7 @@ function pack(chunks,rate){
|
|
| 74 |
let sum=0;for(let j=lo;j<hi;j++)sum+=indata[j];v.setInt16(44+2*i,Math.round(Math.min(1,Math.max(-1,sum/(hi-lo)))*32767),true);}
|
| 75 |
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);
|
| 76 |
}
|
| 77 |
-
function pump(){if(!take||!ready||busy||stopped||!queue.length)return;busy=true;
|
| 78 |
emit("phrase",{take,seq:++seq,audio:queue.shift()});setStatus("transcribing");
|
| 79 |
}
|
| 80 |
function flush(){
|
|
@@ -123,18 +132,18 @@ async function openMic(){
|
|
| 123 |
const zero=ctx.createGain();zero.gain.value=0;src.connect(node);node.connect(zero);zero.connect(ctx.destination);
|
| 124 |
capture.getAudioTracks()[0].addEventListener("ended",()=>{if(capture===stream){release();setStatus("mic_error");}});
|
| 125 |
if(!take){
|
| 126 |
-
take=crypto.randomUUID();seq=applied=visionRev=0;focus=prompt=lastHeard="";ready=busy=
|
| 127 |
setStatus("armed");
|
| 128 |
emit("begin",{take});
|
| 129 |
watchdog=setTimeout(()=>{if(take&&!ready)finish("connection");},20000);
|
| 130 |
}
|
| 131 |
-
if (status==="mic_error") setStatus(
|
| 132 |
}catch(err){if(epoch===micEpoch){release();setStatus("mic_error");}}
|
| 133 |
finally{if(epoch===micEpoch){opening=false;label();}}
|
| 134 |
}
|
| 135 |
function endSession(){
|
| 136 |
if(opening&&!take){release();setStatus("idle");return;}
|
| 137 |
-
if(!take||stopped)return;stopped=true;queue=[];release();setStatus("stopping");emit("halt",{take});
|
| 138 |
clearTimeout(watchdog);watchdog=setTimeout(()=>{if(stopped)finish("connection");},40000);
|
| 139 |
}
|
| 140 |
mic.addEventListener("click",()=>{
|
|
@@ -148,23 +157,44 @@ mic.addEventListener("click",()=>{
|
|
| 148 |
});
|
| 149 |
end.addEventListener("click",endSession);
|
| 150 |
langButtons.forEach((b,i)=>b.addEventListener("click",()=>{lang=i?"fr":"en";try{localStorage.setItem("ffv-lang",lang);}catch{}label();}));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
window.addEventListener("ffv-signal",e=>{
|
| 152 |
-
let d;try{d=JSON.parse(e.detail);}catch{return;}
|
| 153 |
-
if(d.
|
| 154 |
-
if(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
if(stopped)return;
|
| 156 |
if(d.phase==="armed"){clearTimeout(watchdog);ready=true;setStatus("armed");pump();return;}
|
| 157 |
-
if(d.phase==="interpreting"){lastHeard=d.heard;setStatus(
|
| 158 |
if(d.phase==="accepted"){
|
| 159 |
-
if(d.rev<=visionRev)return;
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
}
|
| 164 |
-
if(["ignored","empty","speech_error"].includes(d.phase)){busy=false;setStatus(d.phase==="ignored"?"armed":d.phase);pump();return;}
|
| 165 |
-
if(d.phase==="allocated")allocated=true;
|
| 166 |
-
if(d.phase==="frames"){applied=d.rev;setMode("live");if(!busy)setStatus("live");return;}
|
| 167 |
-
if(d.phase==="finalizing"){release();stopped=true;}
|
| 168 |
setStatus(d.phase);
|
| 169 |
});
|
| 170 |
window.addEventListener("pagehide",event=>{if(take)endSession();release();if(!event.persisted)playback.dispose();});
|
|
|
|
| 2 |
const by = id => root.getElementById(id) || document.getElementById(id);
|
| 3 |
const deskEl = by("voice-desk");
|
| 4 |
const mic = by("mic-key"), end = by("end-take"), monitor = by("monitor");
|
| 5 |
+
const retry = by("retry-cue");
|
| 6 |
+
const hold = by("held-frame");
|
| 7 |
+
const playback = inlinePlayback(monitor, by("play-inline"),
|
| 8 |
+
()=>{if(take&&!stopped){setMode("live");setStatus("playing");}},
|
| 9 |
+
()=>completePlayback("holding"), ()=>completePlayback("play_error"));
|
| 10 |
const meter = by("mic-level").getContext("2d");
|
| 11 |
const langButtons = [by("lang-en"), by("lang-fr")];
|
| 12 |
const copy = {
|
| 13 |
end:["End session","Terminer"],intro:["Describe your opening shot.","Décris ton premier plan."],
|
| 14 |
+
preview:["Preview frame","Aperçu"],help:["Speak, then pause. Each direction adds about four seconds to the shot.","Parle, puis marque une pause. Chaque consigne ajoute environ quatre secondes au plan."],
|
| 15 |
+
heard:["Heard","Transcription"],direction:["Interpreted direction","Consigne interprétée"],limit:["≈ 4 s per cue","≈ 4 s par consigne"],
|
| 16 |
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"],
|
| 17 |
+
muted:["Mic muted","Micro coupé"],playVideo:["Play segment","Lire la portion"],retryCue:["Retry","Réessayer"],
|
| 18 |
permission:["Opening microphone…","Ouverture du micro…"],armed:["Listening for your opening shot","À l’écoute du premier plan"],
|
| 19 |
transcribing:["Transcribing…","Transcription…"],interpreting:["Interpreting direction…","Interprétation de la consigne…"],
|
| 20 |
queued:["Requesting GPU…","Demande de GPU…"],allocated:["GPU allocated · preparing frames","GPU alloué · préparation des images"],
|
| 21 |
+
restoring:["Restoring the shot…","Reprise du plan…"],generating:["Generating the next segment…","Génération de la portion…"],
|
| 22 |
+
saving:["Saving shot continuity…","Sauvegarde du plan…"],encoding:["Preparing playback…","Préparation de la lecture…"],
|
| 23 |
+
playing:["Playing segment","Lecture de la portion"],holding:["Frame held · give the next direction","Image en pause · donne la prochaine consigne"],
|
| 24 |
+
loading:["Loading segment…","Chargement de la portion…"],play_error:["Playback unavailable · final frame shown","Lecture indisponible · dernière image affichée"],
|
| 25 |
+
export_error:["Couldn’t export the take · retry","Échec de l’export · réessaie"],
|
| 26 |
stopping:["Ending session…","Fin de session…"],finalizing:["Preparing recording…","Préparation de la vidéo…"],
|
| 27 |
finished:["Take ready · replay or download","Prise prête · lecture et téléchargement"],closed:["Session ended","Session terminée"],
|
| 28 |
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"],
|
| 29 |
mic_error:["Microphone unavailable · check browser permission and try again","Micro indisponible · vérifie l’autorisation du navigateur et réessaie"],
|
| 30 |
+
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"],
|
| 31 |
hardware:["Video requires ZeroGPU · microphone test complete","La vidéo nécessite ZeroGPU · essai micro terminé"],
|
| 32 |
codec:["H.264 playback is unavailable in this browser","Ce navigateur ne peut pas lire la vidéo H.264"],
|
| 33 |
connection:["Session connection interrupted · try again","Connexion interrompue · réessaie"],
|
|
|
|
| 37 |
const tr = k => (copy[k] || [k,k])[lang==="fr"?1:0];
|
| 38 |
let take = null, status = "idle", mode = "idle", focus="", prompt="", lastHeard="";
|
| 39 |
let stream=null, ctx=null, node=null, opening=false, stopped=false, micEpoch=0;
|
| 40 |
+
let ready=false, busy=false, saved=false, seq=0, applied=0, visionRev=0, retryKind="", pendingStill="";
|
| 41 |
let queue=[], pre=[], blocks=[], voice=false, quiet=0, loud=0, baseline=.003, watchdog=0;
|
| 42 |
function label(){
|
| 43 |
root.querySelectorAll("[data-tr]").forEach(e=>e.textContent=tr(e.dataset.tr));
|
|
|
|
| 45 |
by("mic-word").textContent=tr(!take?"start":stream?"on":"off");
|
| 46 |
const muted = Boolean(take && !stream && !opening && !stopped);
|
| 47 |
mic.dataset.micState = muted ? "muted" : stream ? "listening" : "idle";
|
| 48 |
+
retry.hidden=!retryKind;
|
| 49 |
mic.disabled=opening||stopped;
|
| 50 |
end.disabled=(!take&&!opening)||stopped;
|
| 51 |
const stage = opening ? tr("permission") : tr(status);
|
|
|
|
| 53 |
? (status === "armed" ? tr("muted") : tr("muted")+" · "+stage) : stage;
|
| 54 |
by("heard-text").textContent=lastHeard||"—";
|
| 55 |
by("focus-text").textContent=focus?focus.split("+").map(tr).join(" + ")+" · "+prompt:"—";
|
| 56 |
+
if(deskEl)deskEl.dataset.busy=String(!!take&&(busy||stopped)&&!retryKind);
|
| 57 |
}
|
| 58 |
function setStatus(k){status=k;label();}
|
| 59 |
function emit(name,data){ props.value=JSON.stringify(data); trigger(name); }
|
| 60 |
+
function setMode(m){mode=m;monitor.dataset.mode=m;}
|
| 61 |
function clearPhrase(){pre=[];blocks=[];voice=false;quiet=0;loud=0;baseline=.003;}
|
| 62 |
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);}}
|
| 63 |
function release(){
|
|
|
|
| 68 |
clearPhrase();draw();label();
|
| 69 |
}
|
| 70 |
function finish(k){
|
| 71 |
+
clearTimeout(watchdog); release();queue=[];take=null;ready=false;busy=false;retryKind="";stopped=false;playback.clear();
|
| 72 |
if(k==="finished")saved=true;
|
| 73 |
setMode(saved?"saved":"cover");setStatus(k);
|
| 74 |
}
|
|
|
|
| 83 |
let sum=0;for(let j=lo;j<hi;j++)sum+=indata[j];v.setInt16(44+2*i,Math.round(Math.min(1,Math.max(-1,sum/(hi-lo)))*32767),true);}
|
| 84 |
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);
|
| 85 |
}
|
| 86 |
+
function pump(){if(!take||!ready||busy||stopped||!queue.length)return;busy=true;retryKind="";
|
| 87 |
emit("phrase",{take,seq:++seq,audio:queue.shift()});setStatus("transcribing");
|
| 88 |
}
|
| 89 |
function flush(){
|
|
|
|
| 132 |
const zero=ctx.createGain();zero.gain.value=0;src.connect(node);node.connect(zero);zero.connect(ctx.destination);
|
| 133 |
capture.getAudioTracks()[0].addEventListener("ended",()=>{if(capture===stream){release();setStatus("mic_error");}});
|
| 134 |
if(!take){
|
| 135 |
+
take=crypto.randomUUID();seq=applied=visionRev=0;focus=prompt=lastHeard="";ready=busy=stopped=false;queue=[];retryKind="";playback.clear();
|
| 136 |
setStatus("armed");
|
| 137 |
emit("begin",{take});
|
| 138 |
watchdog=setTimeout(()=>{if(take&&!ready)finish("connection");},20000);
|
| 139 |
}
|
| 140 |
+
if (status==="mic_error") setStatus(applied?"holding":"armed");
|
| 141 |
}catch(err){if(epoch===micEpoch){release();setStatus("mic_error");}}
|
| 142 |
finally{if(epoch===micEpoch){opening=false;label();}}
|
| 143 |
}
|
| 144 |
function endSession(){
|
| 145 |
if(opening&&!take){release();setStatus("idle");return;}
|
| 146 |
+
if(!take||stopped)return;stopped=true;retryKind="";queue=[];playback.clear();release();setStatus("stopping");emit("halt",{take});
|
| 147 |
clearTimeout(watchdog);watchdog=setTimeout(()=>{if(stopped)finish("connection");},40000);
|
| 148 |
}
|
| 149 |
mic.addEventListener("click",()=>{
|
|
|
|
| 157 |
});
|
| 158 |
end.addEventListener("click",endSession);
|
| 159 |
langButtons.forEach((b,i)=>b.addEventListener("click",()=>{lang=i?"fr":"en";try{localStorage.setItem("ffv-lang",lang);}catch{}label();}));
|
| 160 |
+
function completePlayback(statusKey){
|
| 161 |
+
if(!take || stopped) return;
|
| 162 |
+
hold.src=pendingStill;setMode("hold");busy=false;setStatus(statusKey);pump();
|
| 163 |
+
}
|
| 164 |
+
retry.addEventListener("click",()=>{
|
| 165 |
+
const action=retryKind;retryKind="";
|
| 166 |
+
if(action==="export"){setStatus("finalizing");emit("export_take",{take});return;}
|
| 167 |
+
if(action==="render" && take && !stopped){
|
| 168 |
+
busy=true;setStatus("queued");emit("roll",{take,rev:visionRev});
|
| 169 |
+
}
|
| 170 |
+
});
|
| 171 |
window.addEventListener("ffv-signal",e=>{
|
| 172 |
+
let d;try{d=JSON.parse(e.detail);}catch{return;}
|
| 173 |
+
if(!take||d.take!==take)return;
|
| 174 |
+
if(d.phase==="closed"||d.phase==="finished"){finish(d.phase);return;}
|
| 175 |
+
if(d.phase==="stopping"){
|
| 176 |
+
clearTimeout(watchdog);setStatus("finalizing");emit("export_take",{take});return;
|
| 177 |
+
}
|
| 178 |
+
if(d.phase==="export_error"){clearTimeout(watchdog);retryKind="export";setStatus(d.phase);return;}
|
| 179 |
if(stopped)return;
|
| 180 |
if(d.phase==="armed"){clearTimeout(watchdog);ready=true;setStatus("armed");pump();return;}
|
| 181 |
+
if(d.phase==="interpreting"){lastHeard=d.heard;setStatus(d.phase);return;}
|
| 182 |
if(d.phase==="accepted"){
|
| 183 |
+
if(d.rev<=visionRev)return;
|
| 184 |
+
visionRev=d.rev;lastHeard=d.heard;prompt=d.summary;focus=d.focus;
|
| 185 |
+
setStatus("queued");emit("roll",{take,rev:d.rev});return;
|
| 186 |
+
}
|
| 187 |
+
if(["ignored","empty","speech_error"].includes(d.phase)){
|
| 188 |
+
busy=false;setStatus(d.phase==="ignored"?(applied?"holding":"armed"):d.phase);pump();return;
|
| 189 |
+
}
|
| 190 |
+
if(d.phase==="ignored_roll" || (d.rev && d.rev!==visionRev))return;
|
| 191 |
+
if(["gpu_error","quota","hardware"].includes(d.phase)){
|
| 192 |
+
busy=false;retryKind="render";setStatus(d.phase);return;
|
| 193 |
+
}
|
| 194 |
+
if(d.phase==="segment"){
|
| 195 |
+
if(d.rev<=applied)return;
|
| 196 |
+
applied=d.rev;pendingStill=d.still;setStatus("loading");playback.segment(d.file);return;
|
| 197 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
setStatus(d.phase);
|
| 199 |
});
|
| 200 |
window.addEventListener("pagehide",event=>{if(take)endSession();release();if(!event.persisted)playback.dispose();});
|
engine.py
CHANGED
|
@@ -114,3 +114,31 @@ class LiveRollout:
|
|
| 114 |
|
| 115 |
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
+
def save(self, folder, check_active):
|
| 118 |
+
"""Keep only occupied KV slots, decoder history and exact RNG state on CPU."""
|
| 119 |
+
folder.mkdir()
|
| 120 |
+
end = self.used * TOKENS
|
| 121 |
+
for index, layer in enumerate(self.kv):
|
| 122 |
+
check_active()
|
| 123 |
+
tensors = {name: value[:, :end].contiguous().cpu() for name, value in layer.items()}
|
| 124 |
+
torch.save(tensors, folder / f"layer-{index}.pt")
|
| 125 |
+
torch.save({
|
| 126 |
+
"used": self.used, "total": self.total, "decoded": self.decoded, "rolls": self.rolls,
|
| 127 |
+
"rng": self.gen.get_state().cpu(),
|
| 128 |
+
"features": [value.cpu() for value in list(self.features)[-DECODER_CONTEXT:]],
|
| 129 |
+
"modulation": [value.cpu() for value in list(self.modulation)[-DECODER_CONTEXT:]],
|
| 130 |
+
}, folder / "history.pt")
|
| 131 |
+
|
| 132 |
+
def restore(self, folder, check_active):
|
| 133 |
+
history = torch.load(folder / "history.pt", map_location="cpu", weights_only=True)
|
| 134 |
+
self.used, self.total = history["used"], history["total"]
|
| 135 |
+
self.decoded, self.rolls = history["decoded"], history["rolls"]
|
| 136 |
+
self.gen.set_state(history["rng"])
|
| 137 |
+
self.features.extend(value.to(PIPE.device) for value in history["features"])
|
| 138 |
+
self.modulation.extend(value.to(PIPE.device) for value in history["modulation"])
|
| 139 |
+
end = self.used * TOKENS
|
| 140 |
+
for index, layer in enumerate(self.kv):
|
| 141 |
+
check_active()
|
| 142 |
+
tensors = torch.load(folder / f"layer-{index}.pt", mmap=True, weights_only=True, map_location="cpu")
|
| 143 |
+
for name, value in tensors.items():
|
| 144 |
+
layer[name][:, :end].copy_(value)
|
render.py
CHANGED
|
@@ -1,13 +1,15 @@
|
|
| 1 |
-
"""
|
|
|
|
| 2 |
import logging
|
| 3 |
import random
|
| 4 |
import subprocess
|
| 5 |
-
import tempfile
|
| 6 |
import time
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
import spaces
|
| 10 |
import torch
|
|
|
|
| 11 |
|
| 12 |
import takes
|
| 13 |
|
|
@@ -19,60 +21,68 @@ GPU_AVAILABLE = torch.cuda.is_available()
|
|
| 19 |
if GPU_AVAILABLE:
|
| 20 |
import engine as en
|
| 21 |
|
| 22 |
-
def encode_chunk(frames, path):
|
| 23 |
-
subprocess.run(["ffmpeg","-nostdin","-loglevel","error","-y","-f","rawvideo","-pix_fmt","rgb24",
|
| 24 |
-
"-s","832x480","-framerate","16","-i","pipe:0","-an","-c:v","libx264","-threads","2",
|
| 25 |
-
"-preset","ultrafast","-tune","zerolatency","-pix_fmt","yuv420p","-f","mpegts",str(path)],
|
| 26 |
-
input=frames.tobytes(), check=True, timeout=8)
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
manifest.write_text("".join(f"file '{p.name}'\n" for p in paths))
|
| 31 |
-
result = folder / "FastFrames-Voice.mp4"
|
| 32 |
-
subprocess.run(["ffmpeg","-nostdin","-loglevel","error","-y","-f","concat","-safe","1","-i",str(manifest),
|
| 33 |
-
"-c:v","copy","-an","-movflags","+faststart",str(result)],check=True,timeout=10)
|
| 34 |
-
if not result.is_file() or not result.stat().st_size:
|
| 35 |
-
raise RuntimeError("Empty recording")
|
| 36 |
-
return str(result)
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
started = time.monotonic()
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
play_start = None
|
| 48 |
try:
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
yield
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
with
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
if play_start is None:
|
| 73 |
-
play_start = time.monotonic()
|
| 74 |
-
frames_sent += len(frames)
|
| 75 |
-
chunk += 1
|
| 76 |
-
yield ("chunk", str(path), rev)
|
| 77 |
finally:
|
| 78 |
-
LOG.info("worker exit %s
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Advance a single rollout for 16 latent frames per spoken direction."""
|
| 2 |
+
import base64
|
| 3 |
import logging
|
| 4 |
import random
|
| 5 |
import subprocess
|
|
|
|
| 6 |
import time
|
| 7 |
+
import tempfile
|
| 8 |
from pathlib import Path
|
| 9 |
|
| 10 |
import spaces
|
| 11 |
import torch
|
| 12 |
+
from PIL import Image
|
| 13 |
|
| 14 |
import takes
|
| 15 |
|
|
|
|
| 21 |
if GPU_AVAILABLE:
|
| 22 |
import engine as en
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
class CueCancelled(Exception):
|
| 26 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
|
| 29 |
+
@spaces.GPU(duration=60, size="xlarge")
|
| 30 |
+
def generate(key, rev, previous, prompt, stage_name):
|
| 31 |
+
"""A fresh GPU allocation for each cue. The CPU owns the committed checkpoint."""
|
| 32 |
started = time.monotonic()
|
| 33 |
+
stage = Path(stage_name)
|
| 34 |
+
def check_active():
|
| 35 |
+
if not takes.active(key, rev):
|
| 36 |
+
raise CueCancelled()
|
| 37 |
+
|
|
|
|
| 38 |
try:
|
| 39 |
+
check_active()
|
| 40 |
+
LOG.info("cue enter %s rev=%d previous=%d", key[:8], rev, previous)
|
| 41 |
+
yield "allocated"
|
| 42 |
+
with torch.inference_mode():
|
| 43 |
+
kv = en.allocate_kv_cache(en.PIPE.dit, en.CAP, en.TOKENS, device=en.PIPE.device)
|
| 44 |
+
rollout = en.LiveRollout(random.SystemRandom().randrange(2**31), kv)
|
| 45 |
+
if previous:
|
| 46 |
+
yield "restoring"
|
| 47 |
+
rollout.restore(takes.completed(key, previous) / "state", check_active)
|
| 48 |
+
first = rollout.total
|
| 49 |
+
text = en.PIPE.dit.text_cache(en.PIPE.encode_prompt(prompt))
|
| 50 |
+
yield "generating"
|
| 51 |
+
with (stage / "pixels.rgb").open("wb") as out:
|
| 52 |
+
for step in range(16):
|
| 53 |
+
check_active()
|
| 54 |
+
rollout.step(text)
|
| 55 |
+
if (step + 1) % en.CHUNK == 0:
|
| 56 |
+
frames = rollout.decode_pending().cpu().numpy()
|
| 57 |
+
out.write(frames.tobytes())
|
| 58 |
+
Image.fromarray(frames[-1]).save(stage / "hold.jpg", quality=92)
|
| 59 |
+
yield "saving"
|
| 60 |
+
rollout.save(stage / "state", check_active)
|
| 61 |
+
LOG.info("cue checkpoint %s rev=%d latent=%d..%d rolls=%d",key[:8],rev,first,rollout.total,rollout.rolls)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
finally:
|
| 63 |
+
LOG.info("cue worker exit %s rev=%d elapsed=%.2f",key[:8],rev,time.monotonic()-started)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def encode(stage, filename):
|
| 67 |
+
subprocess.run(["ffmpeg","-nostdin","-v","error","-y","-f","rawvideo","-pixel_format","rgb24",
|
| 68 |
+
"-video_size","832x480","-framerate","16","-i",str(stage / "pixels.rgb"),"-an",
|
| 69 |
+
"-c:v","libx264","-pix_fmt","yuv420p","-threads","2","-preset","ultrafast","-tune","zerolatency",
|
| 70 |
+
"-movflags","+faststart",str(stage / filename)],check=True,timeout=30)
|
| 71 |
+
(stage / "pixels.rgb").unlink()
|
| 72 |
+
return "data:image/jpeg;base64," + base64.b64encode((stage / "hold.jpg").read_bytes()).decode("ascii")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def finalize(folder):
|
| 76 |
+
clips = sorted(folder.glob("step-*/cue-*.mp4"))
|
| 77 |
+
if not clips:
|
| 78 |
+
raise ValueError("No completed cue")
|
| 79 |
+
output = folder / "FastFrames-Voice.mp4"
|
| 80 |
+
with tempfile.TemporaryDirectory(dir=folder) as name:
|
| 81 |
+
work = Path(name)
|
| 82 |
+
manifest = work / "clips.txt"
|
| 83 |
+
manifest.write_text("".join(f"file '{clip}'\n" for clip in clips))
|
| 84 |
+
result = work / output.name
|
| 85 |
+
subprocess.run(["ffmpeg","-nostdin","-v","error","-y","-f","concat","-safe","0","-i",str(manifest),
|
| 86 |
+
"-c:v","copy","-an","-movflags","+faststart",str(result)],check=True,timeout=60)
|
| 87 |
+
result.replace(output)
|
| 88 |
+
return str(output)
|
takes.py
CHANGED
|
@@ -1,61 +1,123 @@
|
|
| 1 |
-
"""
|
| 2 |
import hashlib
|
| 3 |
import re
|
|
|
|
| 4 |
import sqlite3
|
| 5 |
import tempfile
|
| 6 |
-
import time
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
ROOT = Path(tempfile.mkdtemp(prefix="ff-voice-"))
|
| 10 |
DB = ROOT / "takes.sqlite3"
|
| 11 |
|
|
|
|
| 12 |
def connection():
|
| 13 |
-
db = sqlite3.connect(DB, timeout=
|
| 14 |
db.row_factory = sqlite3.Row
|
| 15 |
return db
|
| 16 |
|
|
|
|
| 17 |
with connection() as db:
|
| 18 |
db.execute("""CREATE TABLE takes (
|
| 19 |
-
id TEXT PRIMARY KEY, owner TEXT NOT NULL,
|
| 20 |
seq INTEGER DEFAULT 0, rev INTEGER DEFAULT 0, rendered INTEGER DEFAULT 0,
|
| 21 |
-
prompt TEXT DEFAULT '', last TEXT DEFAULT '', focus TEXT DEFAULT ''
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
def identify(owner,
|
| 24 |
-
if not owner or not isinstance(
|
| 25 |
raise ValueError("take")
|
| 26 |
-
return hashlib.sha256((owner + ":" +
|
| 27 |
|
| 28 |
-
def start(key, owner):
|
| 29 |
-
with connection() as db:
|
| 30 |
-
db.execute("BEGIN IMMEDIATE")
|
| 31 |
-
db.execute("DELETE FROM takes WHERE born < ?", (time.time()-1800,))
|
| 32 |
-
if db.execute("SELECT 1 FROM takes WHERE id=?", (key,)).fetchone():
|
| 33 |
-
raise ValueError("duplicate")
|
| 34 |
-
db.execute("UPDATE takes SET phase='stopped' WHERE owner=? AND phase IN ('armed','queued','live')",(owner,))
|
| 35 |
-
db.execute("INSERT INTO takes (id, owner, born, phase) VALUES (?,?,?,'armed')",(key,owner,time.time()))
|
| 36 |
|
| 37 |
def get(key):
|
| 38 |
with connection() as db:
|
| 39 |
row = db.execute("SELECT * FROM takes WHERE id=?", (key,)).fetchone()
|
| 40 |
return dict(row) if row else {}
|
| 41 |
|
|
|
|
| 42 |
def update(sql, args):
|
| 43 |
with connection() as db:
|
| 44 |
return db.execute(sql, args).rowcount == 1
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
def reserve(key, seq):
|
| 47 |
-
return update("UPDATE takes SET seq=? WHERE id=? AND seq<? AND phase IN ('armed','
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
def commit(key, seq, heard, focus, prompt):
|
| 50 |
-
return update("""UPDATE takes SET rev=rev+1,
|
| 51 |
-
|
| 52 |
-
WHERE id=? AND seq=? AND phase IN ('armed','queued','live')""",(prompt,heard,focus,key,seq))
|
| 53 |
|
| 54 |
-
def claim(key):
|
| 55 |
-
return update("UPDATE takes SET phase='live' WHERE id=? AND phase='queued'",(key,))
|
| 56 |
|
| 57 |
-
def
|
| 58 |
-
update("UPDATE takes SET phase='
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
def
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Session ownership and atomic publication of each voice-directed segment."""
|
| 2 |
import hashlib
|
| 3 |
import re
|
| 4 |
+
import shutil
|
| 5 |
import sqlite3
|
| 6 |
import tempfile
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
ROOT = Path(tempfile.mkdtemp(prefix="ff-voice-"))
|
| 10 |
DB = ROOT / "takes.sqlite3"
|
| 11 |
|
| 12 |
+
|
| 13 |
def connection():
|
| 14 |
+
db = sqlite3.connect(DB, timeout=10)
|
| 15 |
db.row_factory = sqlite3.Row
|
| 16 |
return db
|
| 17 |
|
| 18 |
+
|
| 19 |
with connection() as db:
|
| 20 |
db.execute("""CREATE TABLE takes (
|
| 21 |
+
id TEXT PRIMARY KEY, owner TEXT NOT NULL, phase TEXT NOT NULL,
|
| 22 |
seq INTEGER DEFAULT 0, rev INTEGER DEFAULT 0, rendered INTEGER DEFAULT 0,
|
| 23 |
+
prompt TEXT DEFAULT '', last TEXT DEFAULT '', focus TEXT DEFAULT '',
|
| 24 |
+
next_prompt TEXT DEFAULT '', next_last TEXT DEFAULT '', next_focus TEXT DEFAULT '')""")
|
| 25 |
+
|
| 26 |
|
| 27 |
+
def identify(owner, tag):
|
| 28 |
+
if not owner or not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9-]{16,64}", tag):
|
| 29 |
raise ValueError("take")
|
| 30 |
+
return hashlib.sha256((owner + ":" + tag).encode()).hexdigest()
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
def get(key):
|
| 34 |
with connection() as db:
|
| 35 |
row = db.execute("SELECT * FROM takes WHERE id=?", (key,)).fetchone()
|
| 36 |
return dict(row) if row else {}
|
| 37 |
|
| 38 |
+
|
| 39 |
def update(sql, args):
|
| 40 |
with connection() as db:
|
| 41 |
return db.execute(sql, args).rowcount == 1
|
| 42 |
|
| 43 |
+
|
| 44 |
+
def remove_owner(db, owner):
|
| 45 |
+
old = db.execute("SELECT id FROM takes WHERE owner=?", (owner,)).fetchall()
|
| 46 |
+
db.execute("DELETE FROM takes WHERE owner=?", (owner,))
|
| 47 |
+
return [ROOT / row["id"] for row in old]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def forget(owner):
|
| 51 |
+
with connection() as db:
|
| 52 |
+
db.execute("BEGIN IMMEDIATE")
|
| 53 |
+
old = remove_owner(db, owner)
|
| 54 |
+
for path in old:
|
| 55 |
+
shutil.rmtree(path, ignore_errors=True)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def start(key, owner):
|
| 59 |
+
with connection() as db:
|
| 60 |
+
db.execute("BEGIN IMMEDIATE")
|
| 61 |
+
if db.execute("SELECT 1 FROM takes WHERE id=?", (key,)).fetchone():
|
| 62 |
+
raise ValueError("Duplicate take")
|
| 63 |
+
old = remove_owner(db, owner)
|
| 64 |
+
db.execute("INSERT INTO takes(id,owner,phase) VALUES(?,?,'armed')",(key,owner))
|
| 65 |
+
(ROOT / key).mkdir()
|
| 66 |
+
for path in old:
|
| 67 |
+
shutil.rmtree(path, ignore_errors=True)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
def reserve(key, seq):
|
| 71 |
+
return update("UPDATE takes SET seq=?,phase='interpreting' WHERE id=? AND seq<? AND phase IN ('armed','retry')",
|
| 72 |
+
(seq,key,seq))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def release_phrase(key, seq):
|
| 76 |
+
update("UPDATE takes SET phase='armed' WHERE id=? AND phase='interpreting' AND seq=?", (key,seq))
|
| 77 |
+
|
| 78 |
|
| 79 |
def commit(key, seq, heard, focus, prompt):
|
| 80 |
+
return update("""UPDATE takes SET rev=rev+1,next_prompt=?,next_last=?,next_focus=?,phase='queued'
|
| 81 |
+
WHERE id=? AND seq=? AND phase='interpreting'""", (prompt,heard,focus,key,seq))
|
|
|
|
| 82 |
|
|
|
|
|
|
|
| 83 |
|
| 84 |
+
def claim(key, rev):
|
| 85 |
+
return update("UPDATE takes SET phase='live' WHERE id=? AND rev=? AND phase IN ('queued','retry')", (key,rev))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def active(key, rev):
|
| 89 |
+
row = get(key)
|
| 90 |
+
return row.get("phase") == "live" and row["rev"] == rev
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def completed(key, rev):
|
| 94 |
+
return ROOT / key / f"step-{rev:08d}"
|
| 95 |
+
|
| 96 |
|
| 97 |
+
def publish(key, rev, stage):
|
| 98 |
+
with connection() as db:
|
| 99 |
+
db.execute("BEGIN IMMEDIATE")
|
| 100 |
+
row = db.execute("SELECT rendered FROM takes WHERE id=? AND rev=? AND phase='live'",(key,rev)).fetchone()
|
| 101 |
+
if not row:
|
| 102 |
+
return False
|
| 103 |
+
stage.rename(completed(key, rev))
|
| 104 |
+
db.execute("""UPDATE takes SET rendered=rev,phase='armed',prompt=next_prompt,
|
| 105 |
+
last=next_last,focus=next_focus WHERE id=?""",(key,))
|
| 106 |
+
if row["rendered"]:
|
| 107 |
+
shutil.rmtree(completed(key, row["rendered"]) / "state", ignore_errors=True)
|
| 108 |
+
return True
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def fail(key, rev):
|
| 112 |
+
return update("UPDATE takes SET phase='retry' WHERE id=? AND phase='live' AND rev=?", (key,rev))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def close(key):
|
| 116 |
+
with connection() as db:
|
| 117 |
+
db.execute("BEGIN IMMEDIATE")
|
| 118 |
+
db.execute("UPDATE takes SET phase='stopped' WHERE id=?", (key,))
|
| 119 |
+
row = db.execute("SELECT rendered FROM takes WHERE id=?", (key,)).fetchone()
|
| 120 |
+
rendered = row["rendered"] if row else 0
|
| 121 |
+
if rendered:
|
| 122 |
+
shutil.rmtree(completed(key, rendered) / "state", ignore_errors=True)
|
| 123 |
+
return rendered
|