Spaces:
Sleeping
Sleeping
Add a read-only segment timeline and protect temporary studio media
Browse files- README.md +9 -1
- app.py +67 -19
- assets/collection.js +4 -3
- assets/credits.html +1 -1
- assets/desk.html +12 -6
- assets/gallery.html +2 -1
- assets/header.html +3 -3
- assets/media.js +67 -0
- assets/monitor.html +3 -1
- assets/playback.js +1 -2
- assets/studio.css +40 -0
- assets/studio.js +27 -9
- assets/timeline.js +55 -0
- continuity.py +19 -0
- housekeeping.py +67 -0
- media_access.py +84 -0
- render.py +11 -0
- takes.py +8 -3
README.md
CHANGED
|
@@ -29,7 +29,7 @@ models:
|
|
| 29 |
|
| 30 |
# FastFrames Voice
|
| 31 |
|
| 32 |
-
A private research prototype for directing a continuous generated shot with spoken or written cues. Version 0.
|
| 33 |
|
| 34 |
Choose FastFrames-S (default, 1.3B) or FastFrames-L (14B) before starting a shot. Each session uses the same model for its opening, continuations and variants. When the session ends, the model selector becomes available again.
|
| 35 |
|
|
@@ -43,6 +43,14 @@ For signed-in visitors, the app uses the OAuth contribute-repos scope to write t
|
|
| 43 |
|
| 44 |
API clients use the same Gradio session throughout. Call `begin` with the take ID and an optional `model` of `S` or `L` (default `S`), then `voice_direction` with the take ID, increasing sequence number and base64 mono 16 kHz PCM WAV. Alternatively use `text_direction` with `text` (1–1200 characters). Both endpoints accept an optional integer `seconds` from 1 to 8, default 4. API calls without an `operation` retain append behavior. The studio sends `operation: "auto"` by default. Send `operation: "redo_last"` with the last accepted clip’s `target_rev` to override automatic routing. A `clarify` event carries a question ID. Send a higher sequence number with `reply_to` and either a spoken/written answer or an explicit `answer` of `append`, `redo_last` or `cancel`. 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` or `variant`. After a variant, call `choose_variant` with the take ID, revision and a `choice` of `original` or `variant`. 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.
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
## Running the Space
|
| 47 |
|
| 48 |
Use the Hugging Face Gradio SDK and ZeroGPU hardware. Attach a **private read-write HF storage bucket** at /data/fastframes-sessions for durable sessions. For a standalone installation point GALLERY_ROOT to an existing persistent directory. The app publishes the gallery entry after the final video is stored. The saved_sessions API supports list and watch. Supply a 64-character random hexadecimal device key or sign in. Watch requires the archive ID. Send the same device key with export_take for anonymous API archives. The application places the video models on CUDA at startup through the Spaces SDK. Install the system packages in packages.txt, the Python dependencies in requirements.txt and the Spaces runtime for local GPU development. Run python app.py from this directory. The CPU speech path is usable on a CPU host. Allow the browser microphone through HTTPS or localhost. The model revisions are recorded in engine.py and speech.py.
|
|
|
|
| 29 |
|
| 30 |
# FastFrames Voice
|
| 31 |
|
| 32 |
+
A private research prototype for directing a continuous generated shot with spoken or written cues. Version 0.9.0. The monitor fills the studio above a horizontal desk for the microphone, transcript and interpreted direction. Open Videos in the header to watch or download finished recordings.
|
| 33 |
|
| 34 |
Choose FastFrames-S (default, 1.3B) or FastFrames-L (14B) before starting a shot. Each session uses the same model for its opening, continuations and variants. When the session ends, the model selector becomes available again.
|
| 35 |
|
|
|
|
| 43 |
|
| 44 |
API clients use the same Gradio session throughout. Call `begin` with the take ID and an optional `model` of `S` or `L` (default `S`), then `voice_direction` with the take ID, increasing sequence number and base64 mono 16 kHz PCM WAV. Alternatively use `text_direction` with `text` (1–1200 characters). Both endpoints accept an optional integer `seconds` from 1 to 8, default 4. API calls without an `operation` retain append behavior. The studio sends `operation: "auto"` by default. Send `operation: "redo_last"` with the last accepted clip’s `target_rev` to override automatic routing. A `clarify` event carries a question ID. Send a higher sequence number with `reply_to` and either a spoken/written answer or an explicit `answer` of `append`, `redo_last` or `cancel`. 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` or `variant`. After a variant, call `choose_variant` with the take ID, revision and a `choice` of `original` or `variant`. 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.
|
| 45 |
|
| 46 |
+
### Timeline, private media and temporary storage
|
| 47 |
+
|
| 48 |
+
The timeline appears below the desk after the first completed segment. Each thumbnail shows a segment, its start time and its duration. Select one to watch it in the monitor. Starting another direction returns to the current shot. Only the last accepted segment can be redone. Earlier segments are playback-only. Accepting a variant replaces its thumbnail in place. The gallery stores the final film.
|
| 49 |
+
|
| 50 |
+
The segment, export and gallery video outputs contain a media descriptor (`video.url` relative to the Space origin, with a matching `media` URL in the status event). To download with an API client, resolve that URL against the Space and pass the status event's `media_key` in the `X-FastFrames-Key` request header. Keep the same Gradio session. A client may instead choose a random 64-character lower-case hexadecimal `media_key` and include it in every callback. Preview strip URLs use the same credential. Private Spaces additionally require the usual Hub authorization. Media URLs alone grant no access. Browsers use inline native video with range requests where first-party or partitioned cookies are supported, or authenticated fetch and a local object URL otherwise.
|
| 51 |
+
|
| 52 |
+
An open studio refreshes its temporary take while waiting for a direction. A disconnected take expires after 90 minutes of inactivity, checked once a minute. API clients pausing longer can call `keep_alive` with their take. Rendering and interpretation in progress are protected. Renders reserve disk headroom for the selected model and duration before requesting ZeroGPU. When space is insufficient the last valid segment can still be exported.
|
| 53 |
+
|
| 54 |
## Running the Space
|
| 55 |
|
| 56 |
Use the Hugging Face Gradio SDK and ZeroGPU hardware. Attach a **private read-write HF storage bucket** at /data/fastframes-sessions for durable sessions. For a standalone installation point GALLERY_ROOT to an existing persistent directory. The app publishes the gallery entry after the final video is stored. The saved_sessions API supports list and watch. Supply a 64-character random hexadecimal device key or sign in. Watch requires the archive ID. Send the same device key with export_take for anonymous API archives. The application places the video models on CUDA at startup through the Spaces SDK. Install the system packages in packages.txt, the Python dependencies in requirements.txt and the Spaces runtime for local GPU development. Run python app.py from this directory. The CPU speech path is usable on a CPU host. Allow the browser microphone through HTTPS or localhost. The model revisions are recorded in engine.py and speech.py.
|
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
"""FastFrames Voice · Gradio session callbacks and studio layout."""
|
| 2 |
import contextlib
|
|
|
|
| 3 |
import hashlib
|
| 4 |
import json
|
| 5 |
import logging
|
|
@@ -12,7 +13,14 @@ from pathlib import Path
|
|
| 12 |
|
| 13 |
import gradio as gr
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
import gallery
|
|
|
|
|
|
|
| 16 |
import personal_bucket
|
| 17 |
|
| 18 |
import render
|
|
@@ -26,7 +34,11 @@ def asset(name):
|
|
| 26 |
|
| 27 |
def payload(raw, request):
|
| 28 |
p = json.loads(raw)
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def msg(take, phase, **data):
|
| 32 |
return json.dumps({"take":take,"phase":phase,**data},ensure_ascii=False)
|
|
@@ -37,9 +49,15 @@ def begin(raw: str, request: gr.Request):
|
|
| 37 |
if model not in ("S", "L"):
|
| 38 |
return msg(p["take"], "invalid_model")
|
| 39 |
with gallery.lock_for(request.session_hash):
|
| 40 |
-
takes.start(key,request.session_hash,model)
|
| 41 |
return msg(p["take"],"armed",model=model)
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def phrase(raw: str, request: gr.Request, oauth: gr.OAuthToken | None):
|
| 44 |
yield from direction(raw, request, oauth, "voice")
|
| 45 |
|
|
@@ -169,16 +187,21 @@ def export_take(raw: str, request: gr.Request, profile: gr.OAuthProfile | None,
|
|
| 169 |
LOG.exception("export failed for %s",key[:8])
|
| 170 |
yield gr.skip(),msg(p["take"],"export_error")
|
| 171 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
archive=None
|
| 173 |
if p.get("device") or profile:
|
| 174 |
-
yield
|
| 175 |
try:
|
| 176 |
archive=gallery.save(key,gallery.owners(p.get("device"),profile),movie,personal_bucket.account(profile,oauth))
|
| 177 |
except Exception:
|
| 178 |
LOG.exception("gallery save failed for %s",key[:8])
|
| 179 |
-
yield
|
| 180 |
return
|
| 181 |
-
yield
|
| 182 |
|
| 183 |
|
| 184 |
def saved_sessions(raw: str, request: gr.Request, profile: gr.OAuthProfile | None, oauth: gr.OAuthToken | None):
|
|
@@ -196,7 +219,10 @@ def saved_sessions(raw: str, request: gr.Request, profile: gr.OAuthProfile | Non
|
|
| 196 |
return
|
| 197 |
if p.get("action") == "watch":
|
| 198 |
with gallery.opened(who, p.get("archive"), personal) as folder:
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
| 200 |
return
|
| 201 |
yield gr.skip(),status("collection_error")
|
| 202 |
except Exception:
|
|
@@ -218,20 +244,26 @@ def live(raw: str, request: gr.Request):
|
|
| 218 |
early = None
|
| 219 |
published = False
|
| 220 |
release_claim = True
|
|
|
|
|
|
|
| 221 |
try:
|
| 222 |
if not render.GPU_AVAILABLE:
|
| 223 |
takes.fail(key,rev)
|
| 224 |
release_claim = False
|
| 225 |
yield skip(),skip(),msg(tag,"hardware",rev=rev)
|
| 226 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
stage = Path(tempfile.mkdtemp(prefix="pending-",dir=takes.ROOT))
|
| 228 |
yield skip(),skip(),msg(tag,"queued",rev=rev)
|
| 229 |
-
variant = row["operation"]=="redo_last"
|
| 230 |
-
base = row["parent"] if variant else row["rendered"]
|
| 231 |
if p.get("stream_preview") is True:
|
| 232 |
parent=takes.PREVIEWS/key
|
| 233 |
parent.mkdir(exist_ok=True)
|
| 234 |
early=Path(tempfile.mkdtemp(prefix=f"live-{rev}-",dir=parent))
|
|
|
|
| 235 |
count=0
|
| 236 |
stream = render.generate(key,rev,base,row["next_prompt"],str(stage),row["seconds"],row["seed"],early is not None,row["model"])
|
| 237 |
for phase in stream:
|
|
@@ -240,7 +272,7 @@ def live(raw: str, request: gr.Request):
|
|
| 240 |
for i in range(count,phase):
|
| 241 |
os.link(stage/"preview"/f"{i}.jpg", early/f"{i}.jpg")
|
| 242 |
count=phase
|
| 243 |
-
yield skip(),skip(),msg(tag,"preview",rev=rev,ready=count,preview=
|
| 244 |
else:
|
| 245 |
yield skip(),skip(),msg(tag,phase,rev=rev)
|
| 246 |
if not takes.active(key,rev):
|
|
@@ -248,16 +280,27 @@ def live(raw: str, request: gr.Request):
|
|
| 248 |
yield skip(),skip(),msg(tag,"encoding",rev=rev)
|
| 249 |
filename = f"cue-{key[:12]}-{rev}.mp4"
|
| 250 |
count,still = render.encode(stage,filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
if takes.publish(key,rev,stage):
|
| 252 |
published=True
|
| 253 |
release_claim = False
|
| 254 |
-
|
| 255 |
-
|
|
|
|
| 256 |
except Exception as exc:
|
| 257 |
if takes.fail(key,rev):
|
| 258 |
release_claim = False
|
| 259 |
LOG.exception("cue failed %s rev=%d",key[:8],rev)
|
| 260 |
reason = "quota" if "quota" in str(exc).lower() else "gpu_error"
|
|
|
|
|
|
|
| 261 |
yield skip(),skip(),msg(tag,reason,rev=rev)
|
| 262 |
finally:
|
| 263 |
if stream is not None and hasattr(stream,"close"):
|
|
@@ -269,12 +312,16 @@ def live(raw: str, request: gr.Request):
|
|
| 269 |
shutil.rmtree(early,ignore_errors=True)
|
| 270 |
if stage is not None:
|
| 271 |
shutil.rmtree(stage,ignore_errors=True)
|
|
|
|
|
|
|
| 272 |
|
| 273 |
|
| 274 |
def unload(request: gr.Request):
|
| 275 |
if request.session_hash:
|
| 276 |
with gallery.lock_for(request.session_hash):
|
| 277 |
takes.forget(request.session_hash)
|
|
|
|
|
|
|
| 278 |
shutil.rmtree(takes.ROOT/"viewing"/hashlib.sha256(request.session_hash.encode()).hexdigest(),ignore_errors=True)
|
| 279 |
|
| 280 |
CSS=asset("studio.css")
|
|
@@ -284,20 +331,18 @@ with gr.Blocks(title="FastFrames Voice",fill_width=True,delete_cache=(600,1800))
|
|
| 284 |
gr.HTML(asset("header.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-header")
|
| 285 |
with gr.Row(elem_id="provider-account"):
|
| 286 |
gr.LoginButton(elem_id="provider-login", size="sm", variant="secondary")
|
| 287 |
-
gr.HTML('<span data-tr="providerHelp">
|
| 288 |
elem_id="provider-help", container=False, padding=False, apply_default_css=False)
|
| 289 |
with gr.Column(elem_id="work-area"):
|
| 290 |
with gr.Column(elem_id="monitor"):
|
| 291 |
gr.HTML(asset("monitor.html"),apply_default_css=False,padding=False,container=False,elem_id="cover")
|
| 292 |
-
feed=gr.
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
buttons=["download"],elem_id="last-take")
|
| 296 |
-
desk=gr.HTML(value="",apply_default_css=False,padding=False,html_template=asset("desk.html"),js_on_load=asset("playback.js")+"\n"+asset("collection.js")+"\n"+asset("studio.js").replace('/* WORKLET_MODULE */ ""', json.dumps(asset("capture.js"))),
|
| 297 |
container=False,elem_id="voice-desk")
|
| 298 |
with gr.Column(elem_id="collection"):
|
| 299 |
gr.HTML(asset("gallery.html"),container=False,padding=False,apply_default_css=False,elem_id="gallery-panel")
|
| 300 |
-
gallery_video=gr.
|
| 301 |
gr.HTML(asset("credits.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-credits")
|
| 302 |
def bus(name):
|
| 303 |
return gr.HTML(value="",html_template="<span></span>",js_on_load=BUS_JS,elem_id=name,container=False)
|
|
@@ -306,6 +351,7 @@ with gr.Blocks(title="FastFrames Voice",fill_width=True,delete_cache=(600,1800))
|
|
| 306 |
control_bus=bus("control-signal")
|
| 307 |
library_bus=bus("gallery-signal")
|
| 308 |
desk.begin(begin,[desk],control_bus,queue=False,api_name="begin",show_progress="hidden")
|
|
|
|
| 309 |
desk.phrase(phrase,[desk],cpu_bus,api_name="voice_direction",concurrency_id="directions",concurrency_limit=3,show_progress="hidden")
|
| 310 |
desk.written(written,[desk],cpu_bus,api_name="text_direction",concurrency_id="directions",concurrency_limit=3,show_progress="hidden")
|
| 311 |
desk.roll(live,[desk],[feed,replay,gpu_bus],api_name="live_take",concurrency_limit=2,show_progress="hidden")
|
|
@@ -316,4 +362,6 @@ with gr.Blocks(title="FastFrames Voice",fill_width=True,delete_cache=(600,1800))
|
|
| 316 |
demo.unload(unload)
|
| 317 |
demo.queue(max_size=24)
|
| 318 |
if __name__=="__main__":
|
| 319 |
-
|
|
|
|
|
|
|
|
|
| 1 |
"""FastFrames Voice · Gradio session callbacks and studio layout."""
|
| 2 |
import contextlib
|
| 3 |
+
import errno
|
| 4 |
import hashlib
|
| 5 |
import json
|
| 6 |
import logging
|
|
|
|
| 13 |
|
| 14 |
import gradio as gr
|
| 15 |
|
| 16 |
+
from starlette.middleware import Middleware
|
| 17 |
+
from PIL import Image
|
| 18 |
+
import base64
|
| 19 |
+
import io
|
| 20 |
+
|
| 21 |
import gallery
|
| 22 |
+
import media_access
|
| 23 |
+
import housekeeping
|
| 24 |
import personal_bucket
|
| 25 |
|
| 26 |
import render
|
|
|
|
| 34 |
|
| 35 |
def payload(raw, request):
|
| 36 |
p = json.loads(raw)
|
| 37 |
+
key = takes.identify(request.session_hash, p["take"])
|
| 38 |
+
row = takes.get(key)
|
| 39 |
+
if row.get("media_owner") and row["media_owner"] != media_access.digest(media_access.credential(p,request)):
|
| 40 |
+
raise ValueError("Session unavailable")
|
| 41 |
+
return p, key
|
| 42 |
|
| 43 |
def msg(take, phase, **data):
|
| 44 |
return json.dumps({"take":take,"phase":phase,**data},ensure_ascii=False)
|
|
|
|
| 49 |
if model not in ("S", "L"):
|
| 50 |
return msg(p["take"], "invalid_model")
|
| 51 |
with gallery.lock_for(request.session_hash):
|
| 52 |
+
takes.start(key,request.session_hash,model,media_access.digest(media_access.credential(p,request)))
|
| 53 |
return msg(p["take"],"armed",model=model)
|
| 54 |
|
| 55 |
+
def heartbeat(raw: str, request: gr.Request):
|
| 56 |
+
_,key = payload(raw,request)
|
| 57 |
+
takes.update("UPDATE takes SET touched=unixepoch() WHERE id=?", (key,))
|
| 58 |
+
return gr.skip()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
def phrase(raw: str, request: gr.Request, oauth: gr.OAuthToken | None):
|
| 62 |
yield from direction(raw, request, oauth, "voice")
|
| 63 |
|
|
|
|
| 187 |
LOG.exception("export failed for %s",key[:8])
|
| 188 |
yield gr.skip(),msg(p["take"],"export_error")
|
| 189 |
return
|
| 190 |
+
secret = media_access.credential(p,request)
|
| 191 |
+
url = media_access.register(movie,secret,request.session_hash)
|
| 192 |
+
info = media_access.file_info(url)
|
| 193 |
+
def exported(phase, **details):
|
| 194 |
+
return info,msg(p["take"],phase,media=url,media_key=secret,**details)
|
| 195 |
archive=None
|
| 196 |
if p.get("device") or profile:
|
| 197 |
+
yield exported("archiving")
|
| 198 |
try:
|
| 199 |
archive=gallery.save(key,gallery.owners(p.get("device"),profile),movie,personal_bucket.account(profile,oauth))
|
| 200 |
except Exception:
|
| 201 |
LOG.exception("gallery save failed for %s",key[:8])
|
| 202 |
+
yield exported("archive_error")
|
| 203 |
return
|
| 204 |
+
yield exported("finished",archive=archive)
|
| 205 |
|
| 206 |
|
| 207 |
def saved_sessions(raw: str, request: gr.Request, profile: gr.OAuthProfile | None, oauth: gr.OAuthToken | None):
|
|
|
|
| 219 |
return
|
| 220 |
if p.get("action") == "watch":
|
| 221 |
with gallery.opened(who, p.get("archive"), personal) as folder:
|
| 222 |
+
secret = media_access.credential(p,request)
|
| 223 |
+
movie = gallery.viewing_copy(folder,request.session_hash)
|
| 224 |
+
url = media_access.register(movie,secret,request.session_hash)
|
| 225 |
+
yield media_access.file_info(url),status("viewing",archive=folder.name,media=url,media_key=secret)
|
| 226 |
return
|
| 227 |
yield gr.skip(),status("collection_error")
|
| 228 |
except Exception:
|
|
|
|
| 244 |
early = None
|
| 245 |
published = False
|
| 246 |
release_claim = True
|
| 247 |
+
reserved = False
|
| 248 |
+
secret = media_access.credential(p,request)
|
| 249 |
try:
|
| 250 |
if not render.GPU_AVAILABLE:
|
| 251 |
takes.fail(key,rev)
|
| 252 |
release_claim = False
|
| 253 |
yield skip(),skip(),msg(tag,"hardware",rev=rev)
|
| 254 |
return
|
| 255 |
+
base = row["parent"] if row["operation"]=="redo_last" else row["rendered"]
|
| 256 |
+
needed = render.temporary_bytes(row["model"],row["seconds"],takes.completed(key,base) if base else None)
|
| 257 |
+
reserved = housekeeping.reserve(key,needed)
|
| 258 |
+
if not reserved:
|
| 259 |
+
raise OSError(errno.ENOSPC, "Insufficient temporary storage")
|
| 260 |
stage = Path(tempfile.mkdtemp(prefix="pending-",dir=takes.ROOT))
|
| 261 |
yield skip(),skip(),msg(tag,"queued",rev=rev)
|
|
|
|
|
|
|
| 262 |
if p.get("stream_preview") is True:
|
| 263 |
parent=takes.PREVIEWS/key
|
| 264 |
parent.mkdir(exist_ok=True)
|
| 265 |
early=Path(tempfile.mkdtemp(prefix=f"live-{rev}-",dir=parent))
|
| 266 |
+
strip_url=media_access.register(early,secret,request.session_hash,strips=True)
|
| 267 |
count=0
|
| 268 |
stream = render.generate(key,rev,base,row["next_prompt"],str(stage),row["seconds"],row["seed"],early is not None,row["model"])
|
| 269 |
for phase in stream:
|
|
|
|
| 272 |
for i in range(count,phase):
|
| 273 |
os.link(stage/"preview"/f"{i}.jpg", early/f"{i}.jpg")
|
| 274 |
count=phase
|
| 275 |
+
yield skip(),skip(),msg(tag,"preview",rev=rev,ready=count,preview=strip_url,media_key=secret,frames=row["seconds"]*16)
|
| 276 |
else:
|
| 277 |
yield skip(),skip(),msg(tag,phase,rev=rev)
|
| 278 |
if not takes.active(key,rev):
|
|
|
|
| 280 |
yield skip(),skip(),msg(tag,"encoding",rev=rev)
|
| 281 |
filename = f"cue-{key[:12]}-{rev}.mp4"
|
| 282 |
count,still = render.encode(stage,filename)
|
| 283 |
+
folder = takes.completed(key,rev)
|
| 284 |
+
url = media_access.register(folder / filename,secret,request.session_hash)
|
| 285 |
+
strips = media_access.register(takes.PREVIEWS/key/str(rev),secret,request.session_hash,strips=True)
|
| 286 |
+
with Image.open(stage / "hold.jpg") as image:
|
| 287 |
+
image.thumbnail((184,106))
|
| 288 |
+
thumb = io.BytesIO()
|
| 289 |
+
image.save(thumb,format="JPEG",quality=75)
|
| 290 |
+
thumbnail = "data:image/jpeg;base64,"+base64.b64encode(thumb.getvalue()).decode()
|
| 291 |
if takes.publish(key,rev,stage):
|
| 292 |
published=True
|
| 293 |
release_claim = False
|
| 294 |
+
yield media_access.file_info(url),skip(),msg(tag,"variant" if row["operation"]=="redo_last" else "segment",
|
| 295 |
+
model=row["model"],rev=rev,frames=count,seconds=row["seconds"],media=url,media_key=secret,
|
| 296 |
+
preview=strips,still=still,thumb=thumbnail)
|
| 297 |
except Exception as exc:
|
| 298 |
if takes.fail(key,rev):
|
| 299 |
release_claim = False
|
| 300 |
LOG.exception("cue failed %s rev=%d",key[:8],rev)
|
| 301 |
reason = "quota" if "quota" in str(exc).lower() else "gpu_error"
|
| 302 |
+
if getattr(exc,"errno",None)==errno.ENOSPC or "no space left on device" in str(exc).lower():
|
| 303 |
+
reason = "disk_full"
|
| 304 |
yield skip(),skip(),msg(tag,reason,rev=rev)
|
| 305 |
finally:
|
| 306 |
if stream is not None and hasattr(stream,"close"):
|
|
|
|
| 312 |
shutil.rmtree(early,ignore_errors=True)
|
| 313 |
if stage is not None:
|
| 314 |
shutil.rmtree(stage,ignore_errors=True)
|
| 315 |
+
if reserved:
|
| 316 |
+
housekeeping.release(key)
|
| 317 |
|
| 318 |
|
| 319 |
def unload(request: gr.Request):
|
| 320 |
if request.session_hash:
|
| 321 |
with gallery.lock_for(request.session_hash):
|
| 322 |
takes.forget(request.session_hash)
|
| 323 |
+
with takes.connection() as db:
|
| 324 |
+
db.execute("DELETE FROM media WHERE session=?", (request.session_hash,))
|
| 325 |
shutil.rmtree(takes.ROOT/"viewing"/hashlib.sha256(request.session_hash.encode()).hexdigest(),ignore_errors=True)
|
| 326 |
|
| 327 |
CSS=asset("studio.css")
|
|
|
|
| 331 |
gr.HTML(asset("header.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-header")
|
| 332 |
with gr.Row(elem_id="provider-account"):
|
| 333 |
gr.LoginButton(elem_id="provider-login", size="sm", variant="secondary")
|
| 334 |
+
gr.HTML('<span data-tr="providerHelp">Optional · Sign in for Inkling and to save to your private HF bucket.</span>',
|
| 335 |
elem_id="provider-help", container=False, padding=False, apply_default_css=False)
|
| 336 |
with gr.Column(elem_id="work-area"):
|
| 337 |
with gr.Column(elem_id="monitor"):
|
| 338 |
gr.HTML(asset("monitor.html"),apply_default_css=False,padding=False,container=False,elem_id="cover")
|
| 339 |
+
feed=gr.JSON(visible=False)
|
| 340 |
+
replay=gr.JSON(visible=False)
|
| 341 |
+
desk=gr.HTML(value="",apply_default_css=False,padding=False,html_template=asset("desk.html"),js_on_load=asset("media.js")+"\n"+asset("timeline.js")+"\n"+asset("playback.js")+"\n"+asset("collection.js")+"\n"+asset("studio.js").replace('/* WORKLET_MODULE */ ""', json.dumps(asset("capture.js"))),
|
|
|
|
|
|
|
| 342 |
container=False,elem_id="voice-desk")
|
| 343 |
with gr.Column(elem_id="collection"):
|
| 344 |
gr.HTML(asset("gallery.html"),container=False,padding=False,apply_default_css=False,elem_id="gallery-panel")
|
| 345 |
+
gallery_video=gr.JSON(visible=False)
|
| 346 |
gr.HTML(asset("credits.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-credits")
|
| 347 |
def bus(name):
|
| 348 |
return gr.HTML(value="",html_template="<span></span>",js_on_load=BUS_JS,elem_id=name,container=False)
|
|
|
|
| 351 |
control_bus=bus("control-signal")
|
| 352 |
library_bus=bus("gallery-signal")
|
| 353 |
desk.begin(begin,[desk],control_bus,queue=False,api_name="begin",show_progress="hidden")
|
| 354 |
+
desk.heartbeat(heartbeat,[desk],control_bus,queue=False,api_name="keep_alive",show_progress="hidden")
|
| 355 |
desk.phrase(phrase,[desk],cpu_bus,api_name="voice_direction",concurrency_id="directions",concurrency_limit=3,show_progress="hidden")
|
| 356 |
desk.written(written,[desk],cpu_bus,api_name="text_direction",concurrency_id="directions",concurrency_limit=3,show_progress="hidden")
|
| 357 |
desk.roll(live,[desk],[feed,replay,gpu_bus],api_name="live_take",concurrency_limit=2,show_progress="hidden")
|
|
|
|
| 362 |
demo.unload(unload)
|
| 363 |
demo.queue(max_size=24)
|
| 364 |
if __name__=="__main__":
|
| 365 |
+
housekeeping.start()
|
| 366 |
+
demo.launch(ssr_mode=False,css=CSS,footer_links=[],allowed_paths=[str(ASSETS.resolve())],
|
| 367 |
+
blocked_paths=[str(takes.ROOT),str(gallery.MOUNT)],app_kwargs={"middleware":[Middleware(media_access.PrivateMedia)]})
|
assets/collection.js
CHANGED
|
@@ -55,15 +55,17 @@ function sessionCollection(){
|
|
| 55 |
requestAnimationFrame(()=>window.scrollTo({top:0,behavior:"instant"}));
|
| 56 |
}
|
| 57 |
function tab(next){
|
|
|
|
| 58 |
view=next;
|
| 59 |
if(next==="gallery"){
|
| 60 |
if(stream||opening){queue=queue.filter(c=>c.audio===undefined);release();}
|
| 61 |
call("list");
|
| 62 |
}else{
|
| 63 |
pending=null;selected="";
|
| 64 |
-
|
| 65 |
}
|
| 66 |
controls();syncLoop();topOfView();
|
|
|
|
| 67 |
}
|
| 68 |
window.addEventListener("click",e=>{
|
| 69 |
const button=e.composedPath().find(n=>n?.tagName==="BUTTON");
|
|
@@ -84,8 +86,7 @@ function sessionCollection(){
|
|
| 84 |
}else if(d.phase==="viewing"){
|
| 85 |
selected=d.archive;
|
| 86 |
const player=by("gallery-video");
|
| 87 |
-
|
| 88 |
-
inline();player?.addEventListener("loadedmetadata",inline,{once:true,capture:true});
|
| 89 |
controls();player?.scrollIntoView({block:"nearest"});
|
| 90 |
}else{state="collection_error";controls();}
|
| 91 |
return true;
|
|
|
|
| 55 |
requestAnimationFrame(()=>window.scrollTo({top:0,behavior:"instant"}));
|
| 56 |
}
|
| 57 |
function tab(next){
|
| 58 |
+
timeline?.close();
|
| 59 |
view=next;
|
| 60 |
if(next==="gallery"){
|
| 61 |
if(stream||opening){queue=queue.filter(c=>c.audio===undefined);release();}
|
| 62 |
call("list");
|
| 63 |
}else{
|
| 64 |
pending=null;selected="";
|
| 65 |
+
media.clear("gallery-video");
|
| 66 |
}
|
| 67 |
controls();syncLoop();topOfView();
|
| 68 |
+
by(next==="gallery"?"gallery-title":"studio-title").focus({preventScroll:true});
|
| 69 |
}
|
| 70 |
window.addEventListener("click",e=>{
|
| 71 |
const button=e.composedPath().find(n=>n?.tagName==="BUTTON");
|
|
|
|
| 86 |
}else if(d.phase==="viewing"){
|
| 87 |
selected=d.archive;
|
| 88 |
const player=by("gallery-video");
|
| 89 |
+
media.show("gallery-video",d.media).catch(()=>{if(selected===d.archive){state="collection_error";selected="";controls();}});
|
|
|
|
| 90 |
controls();player?.scrollIntoView({block:"nearest"});
|
| 91 |
}else{state="collection_error";controls();}
|
| 92 |
return true;
|
assets/credits.html
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
<footer class="credit-line"><div><a href="https://huggingface.co/apple/FastFrames-S" target="_blank" rel="noopener">FastFrames-S</a><a href="https://huggingface.co/apple/FastFrames-L" target="_blank" rel="noopener">FastFrames-L <span>· Apple</span></a><a href="https://huggingface.co/FluidVoice-Labs/fluid-speech-pro" target="_blank" rel="noopener">Fluid Speech Pro <span>· FluidVoice</span></a><a href="https://huggingface.co/thinkingmachines/Inkling-2-Mini" target="_blank" rel="noopener">Inkling 2 Mini <span>· Thinking Machines</span></a><a href="https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507" target="_blank" rel="noopener">Qwen</a><a href="https://huggingface.co/spaces/linoyts/fastframes-s-live" target="_blank" rel="noopener"><span data-tr="source">Source Space</span> · linoyts</a></div><a href="https://huggingface.co/fffiloni" target="_blank" rel="noopener">UI/UX · Sylvain Filoni / fffiloni</a></footer>
|
|
|
|
| 1 |
+
<footer class="credit-line"><div><a href="https://huggingface.co/apple/FastFrames-S" target="_blank" rel="noopener">FastFrames-S</a><a href="https://huggingface.co/apple/FastFrames-L" target="_blank" rel="noopener">FastFrames-L <span>· Apple</span></a><a href="https://huggingface.co/FluidVoice-Labs/fluid-speech-pro" target="_blank" rel="noopener">Fluid Speech Pro <span>· FluidVoice</span></a><a href="https://huggingface.co/thinkingmachines/Inkling-2-Mini" target="_blank" rel="noopener">Inkling 2 Mini <span>· Thinking Machines</span></a><a href="https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507" target="_blank" rel="noopener">Qwen</a><a href="https://huggingface.co/spaces/linoyts/fastframes-s-live" target="_blank" rel="noopener"><span data-tr="source">Source Space</span> · linoyts</a><a href="https://huggingface.co/apple/FastFrames-L/blob/main/LICENSE" target="_blank" rel="noopener" data-tr="researchLicense">Non-commercial research · License</a></div><a href="https://huggingface.co/fffiloni" target="_blank" rel="noopener">UI/UX · Sylvain Filoni / fffiloni</a></footer>
|
assets/desk.html
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
<div id="text-control" hidden>
|
| 2 |
<label class="label" for="cue-text" data-tr="textLabel">Written direction</label>
|
| 3 |
<div class="composer"><textarea id="cue-text" rows="2" maxlength="1200"></textarea>
|
| 4 |
<button type="button" id="send-text" disabled data-tr="send">Generate segment</button></div>
|
| 5 |
</div>
|
| 6 |
-
<section class="console" aria-label="Direction">
|
| 7 |
<div id="voice-control" class="control-cell">
|
| 8 |
<button class="mic-key" id="mic-key" data-mic-state="idle">
|
| 9 |
<svg aria-hidden="true" viewBox="0 0 24 24"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v1a7 7 0 0 0 14 0v-1m-7 8v4m-4 0h8"/><path class="mic-slash" d="M3 3l18 18"/></svg><span id="mic-word">Start mic</span>
|
|
@@ -18,16 +23,13 @@
|
|
| 18 |
<div><button type="button" id="answer-redo" data-tr="lastOne">Last segment</button><button type="button" id="answer-append" data-tr="nextOne">Next segment</button><button type="button" id="cancel-answer" data-tr="cancel">Cancel</button></div>
|
| 19 |
</div>
|
| 20 |
<div class="cue-choice" id="review-control" hidden>
|
| 21 |
-
<div role="group" aria-label="Preview"><button type="button" id="watch-original" data-tr="watchOriginal">Play original</button><button type="button" id="watch-variant" data-tr="watchVariant">Play variant</button></div>
|
| 22 |
<div><button type="button" id="keep-original" data-tr="keepOriginal">Keep original</button><button type="button" id="use-variant" data-tr="useVariant">Use variant</button></div>
|
| 23 |
</div>
|
| 24 |
<div class="desk-rail">
|
| 25 |
<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="retry-cue" data-tr="retryCue" hidden>Retry</button></div>
|
| 26 |
<div class="cue-tools">
|
| 27 |
-
|
| 28 |
-
<button type="button" id="mode-voice" aria-pressed="true" data-tr="voiceMode">Voice</button>
|
| 29 |
-
<button type="button" id="mode-text" aria-pressed="false" data-tr="textMode">Text</button>
|
| 30 |
-
</div>
|
| 31 |
<label id="redo-control"><input type="checkbox" id="redo-last" disabled><span data-tr="redoLabel">Redo last segment</span></label>
|
| 32 |
<label class="duration" id="model-choice"><span data-tr="videoModel">Video model</span>
|
| 33 |
<select id="video-model"><option value="S">FastFrames-S</option><option value="L">FastFrames-L · 14B</option></select>
|
|
@@ -38,3 +40,7 @@
|
|
| 38 |
<span id="fixed-length" class="duration" hidden></span>
|
| 39 |
</div>
|
| 40 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<div id="clip-notice" hidden><span id="clip-caption"></span><button type="button" id="back-to-shot" data-tr="backToShot">Back to monitor</button></div>
|
| 2 |
+
<div role="group" aria-label="Direction input" data-aria-en="Direction input" data-aria-fr="Mode de saisie" class="input-switch">
|
| 3 |
+
<button type="button" id="mode-voice" aria-pressed="true" data-tr="voiceMode">Voice</button>
|
| 4 |
+
<button type="button" id="mode-text" aria-pressed="false" data-tr="textMode">Text</button>
|
| 5 |
+
</div>
|
| 6 |
<div id="text-control" hidden>
|
| 7 |
<label class="label" for="cue-text" data-tr="textLabel">Written direction</label>
|
| 8 |
<div class="composer"><textarea id="cue-text" rows="2" maxlength="1200"></textarea>
|
| 9 |
<button type="button" id="send-text" disabled data-tr="send">Generate segment</button></div>
|
| 10 |
</div>
|
| 11 |
+
<section class="console" aria-label="Direction" data-aria-en="Direction" data-aria-fr="Consigne">
|
| 12 |
<div id="voice-control" class="control-cell">
|
| 13 |
<button class="mic-key" id="mic-key" data-mic-state="idle">
|
| 14 |
<svg aria-hidden="true" viewBox="0 0 24 24"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v1a7 7 0 0 0 14 0v-1m-7 8v4m-4 0h8"/><path class="mic-slash" d="M3 3l18 18"/></svg><span id="mic-word">Start mic</span>
|
|
|
|
| 23 |
<div><button type="button" id="answer-redo" data-tr="lastOne">Last segment</button><button type="button" id="answer-append" data-tr="nextOne">Next segment</button><button type="button" id="cancel-answer" data-tr="cancel">Cancel</button></div>
|
| 24 |
</div>
|
| 25 |
<div class="cue-choice" id="review-control" hidden>
|
| 26 |
+
<div role="group" aria-label="Preview" data-aria-en="Preview" data-aria-fr="Aperçu"><button type="button" id="watch-original" data-tr="watchOriginal">Play original</button><button type="button" id="watch-variant" data-tr="watchVariant">Play variant</button></div>
|
| 27 |
<div><button type="button" id="keep-original" data-tr="keepOriginal">Keep original</button><button type="button" id="use-variant" data-tr="useVariant">Use variant</button></div>
|
| 28 |
</div>
|
| 29 |
<div class="desk-rail">
|
| 30 |
<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="retry-cue" data-tr="retryCue" hidden>Retry</button></div>
|
| 31 |
<div class="cue-tools">
|
| 32 |
+
|
|
|
|
|
|
|
|
|
|
| 33 |
<label id="redo-control"><input type="checkbox" id="redo-last" disabled><span data-tr="redoLabel">Redo last segment</span></label>
|
| 34 |
<label class="duration" id="model-choice"><span data-tr="videoModel">Video model</span>
|
| 35 |
<select id="video-model"><option value="S">FastFrames-S</option><option value="L">FastFrames-L · 14B</option></select>
|
|
|
|
| 40 |
<span id="fixed-length" class="duration" hidden></span>
|
| 41 |
</div>
|
| 42 |
</div>
|
| 43 |
+
<section id="timeline" aria-labelledby="timeline-title" hidden>
|
| 44 |
+
<header><h2 id="timeline-title" data-tr="timelineTitle">Timeline</h2><span id="timeline-length"></span></header>
|
| 45 |
+
<div id="clip-list"></div>
|
| 46 |
+
</section>
|
assets/gallery.html
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
<section class="sessions">
|
| 2 |
-
<div class="collection-heading"><h2 data-tr="sessions">Saved videos</h2><span id="gallery-scope"></span></div>
|
| 3 |
<p id="collection-status" role="status" aria-live="polite"></p>
|
| 4 |
<div id="saved-grid"></div>
|
| 5 |
<button type="button" id="gallery-more" data-tr="moreSessions" hidden>Show more</button>
|
| 6 |
<button type="button" id="gallery-retry" data-tr="retryCue" hidden>Retry</button>
|
|
|
|
| 7 |
</section>
|
|
|
|
| 1 |
<section class="sessions">
|
| 2 |
+
<div class="collection-heading"><h2 id="gallery-title" tabindex="-1" data-tr="sessions">Saved videos</h2><span id="gallery-scope"></span></div>
|
| 3 |
<p id="collection-status" role="status" aria-live="polite"></p>
|
| 4 |
<div id="saved-grid"></div>
|
| 5 |
<button type="button" id="gallery-more" data-tr="moreSessions" hidden>Show more</button>
|
| 6 |
<button type="button" id="gallery-retry" data-tr="retryCue" hidden>Retry</button>
|
| 7 |
+
<div id="gallery-video" class="movie-player"><video playsinline controls preload="metadata" aria-label="Saved video" data-aria-en="Saved video" data-aria-fr="Vidéo enregistrée"></video><a download="FastFrames-Voice.mp4" data-tr="download">Download MP4</a></div>
|
| 8 |
</section>
|
assets/header.html
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
<header class="mast">
|
| 2 |
-
<h1><svg aria-hidden="true" viewBox="0 0 32 32"><path d="M3 11V3h8m10 0h8v8m0 10v8h-8m-10 0H3v-8"/></svg>FastFrames Voice</h1>
|
| 3 |
<div class="mast-actions">
|
| 4 |
-
<nav aria-label="Workspace">
|
| 5 |
<button type="button" id="nav-studio" data-tr="studioTab">Studio</button>
|
| 6 |
<button type="button" id="nav-gallery">
|
| 7 |
<svg aria-hidden="true" viewBox="0 0 24 24"><rect x="3" y="7" width="15" height="13" rx="2"/><path d="M7 4h12a2 2 0 0 1 2 2v10"/></svg><span data-tr="galleryTab">Videos</span>
|
| 8 |
</button>
|
| 9 |
</nav>
|
| 10 |
-
<div class="langs" aria-label="Interface language"><button id="lang-en" lang="en" aria-pressed="true">EN</button><span>/</span><button id="lang-fr" lang="fr" aria-pressed="false">FR</button></div>
|
| 11 |
<button id="end-take" class="stop" disabled><span class="stop-icon"></span><span data-tr="end">End session</span></button>
|
| 12 |
</div>
|
| 13 |
</header>
|
|
|
|
| 1 |
<header class="mast">
|
| 2 |
+
<h1 id="studio-title" tabindex="-1"><svg aria-hidden="true" viewBox="0 0 32 32"><path d="M3 11V3h8m10 0h8v8m0 10v8h-8m-10 0H3v-8"/></svg>FastFrames Voice</h1>
|
| 3 |
<div class="mast-actions">
|
| 4 |
+
<nav aria-label="Workspace" data-aria-en="Workspace" data-aria-fr="Navigation du studio">
|
| 5 |
<button type="button" id="nav-studio" data-tr="studioTab">Studio</button>
|
| 6 |
<button type="button" id="nav-gallery">
|
| 7 |
<svg aria-hidden="true" viewBox="0 0 24 24"><rect x="3" y="7" width="15" height="13" rx="2"/><path d="M7 4h12a2 2 0 0 1 2 2v10"/></svg><span data-tr="galleryTab">Videos</span>
|
| 8 |
</button>
|
| 9 |
</nav>
|
| 10 |
+
<div class="langs" aria-label="Interface language" data-aria-en="Interface language" data-aria-fr="Langue de l’interface"><button id="lang-en" lang="en" aria-pressed="true">EN</button><span>/</span><button id="lang-fr" lang="fr" aria-pressed="false">FR</button></div>
|
| 11 |
<button id="end-take" class="stop" disabled><span class="stop-icon"></span><span data-tr="end">End session</span></button>
|
| 12 |
</div>
|
| 13 |
</header>
|
assets/media.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
function studioMedia() {
|
| 2 |
+
// Keep the gallery recovery key independent from the credential for temporary media.
|
| 3 |
+
const storage = "ffv-media-key";
|
| 4 |
+
let key;
|
| 5 |
+
try { key = localStorage.getItem(storage); } catch {}
|
| 6 |
+
if (!/^[a-f0-9]{64}$/.test(key || "")) {
|
| 7 |
+
key = Array.from(crypto.getRandomValues(new Uint8Array(32)), x => x.toString(16).padStart(2,"0")).join("");
|
| 8 |
+
try { localStorage.setItem(storage,key); } catch {}
|
| 9 |
+
}
|
| 10 |
+
const headers = {"X-FastFrames-Key":key};
|
| 11 |
+
let cookieCheck;
|
| 12 |
+
function privateURL(path) {
|
| 13 |
+
const url = new URL(path,document.baseURI);
|
| 14 |
+
if (url.origin !== location.origin || !url.pathname.startsWith("/studio-media/")) throw Error("Invalid media address");
|
| 15 |
+
return url;
|
| 16 |
+
}
|
| 17 |
+
async function nativeAccess() {
|
| 18 |
+
try {
|
| 19 |
+
const set = await fetch(privateURL("/studio-media/bind"),{method:"POST",headers,credentials:"same-origin"});
|
| 20 |
+
if (!set.ok) return false;
|
| 21 |
+
const check = await fetch(privateURL("/studio-media/check"),{method:"HEAD",credentials:"same-origin",cache:"no-store"});
|
| 22 |
+
const bytes = await crypto.subtle.digest("SHA-256",new TextEncoder().encode(key));
|
| 23 |
+
const expected = Array.from(new Uint8Array(bytes), b=>b.toString(16).padStart(2,"0")).join("");
|
| 24 |
+
return check.ok && check.headers.get("X-Media-Owner")===expected;
|
| 25 |
+
} catch { return false; }
|
| 26 |
+
}
|
| 27 |
+
const slots = new Map();
|
| 28 |
+
function clear(id) {
|
| 29 |
+
const state=slots.get(id);
|
| 30 |
+
if (!state) return;
|
| 31 |
+
slots.delete(id);state.controller.abort();
|
| 32 |
+
const el=by(id), video=el.querySelector("video"), link=el.querySelector("a");
|
| 33 |
+
video.pause();video.removeAttribute("src");video.load();
|
| 34 |
+
link?.removeAttribute("href");
|
| 35 |
+
if(state.blob)URL.revokeObjectURL(state.blob);
|
| 36 |
+
}
|
| 37 |
+
async function show(id,path,autoplay=false) {
|
| 38 |
+
const el=by(id), video=el.querySelector("video"), link=el.querySelector("a");
|
| 39 |
+
if(slots.get(id)?.path===path) return slots.get(id).ready;
|
| 40 |
+
clear(id);
|
| 41 |
+
const state={path,controller:new AbortController(),blob:null};
|
| 42 |
+
slots.set(id,state);
|
| 43 |
+
state.ready=(async ()=>{
|
| 44 |
+
const url=privateURL(path);
|
| 45 |
+
cookieCheck ||= nativeAccess();
|
| 46 |
+
let source=url.href;
|
| 47 |
+
if (!(await cookieCheck)) {
|
| 48 |
+
const res=await fetch(url,{headers,signal:state.controller.signal,credentials:"same-origin"});
|
| 49 |
+
if(!res.ok)throw Error("Media unavailable");
|
| 50 |
+
const blob=await res.blob();
|
| 51 |
+
if(slots.get(id)!==state)return;
|
| 52 |
+
source=state.blob=URL.createObjectURL(blob);
|
| 53 |
+
}
|
| 54 |
+
if(slots.get(id)!==state)return;
|
| 55 |
+
video.playsInline=true;video.src=source;
|
| 56 |
+
if(link)link.href=source;
|
| 57 |
+
if(autoplay)video.play().catch(()=>{});
|
| 58 |
+
})();
|
| 59 |
+
try { await state.ready; } catch(error) {
|
| 60 |
+
if(slots.get(id)===state){clear(id);throw error;}
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
function strip(path,signal) {
|
| 64 |
+
return fetch(privateURL(path),{headers,credentials:"same-origin",signal});
|
| 65 |
+
}
|
| 66 |
+
return {key,show,clear,strip};
|
| 67 |
+
}
|
assets/monitor.html
CHANGED
|
@@ -3,5 +3,7 @@
|
|
| 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 or type a direction to begin.</span></div>
|
| 4 |
</div>
|
| 5 |
<img id="held-frame" alt="">
|
| 6 |
-
<canvas id="cue-screen" width="832" height="480" role="img" aria-label="FastFrames video preview"></canvas>
|
| 7 |
<button type="button" id="loop-preview" hidden aria-pressed="false">Loop preview</button>
|
|
|
|
|
|
|
|
|
| 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 or type a direction to begin.</span></div>
|
| 4 |
</div>
|
| 5 |
<img id="held-frame" alt="">
|
| 6 |
+
<canvas id="cue-screen" width="832" height="480" role="img" aria-label="FastFrames video preview" data-aria-en="FastFrames video preview" data-aria-fr="Aperçu vidéo FastFrames"></canvas>
|
| 7 |
<button type="button" id="loop-preview" hidden aria-pressed="false">Loop preview</button>
|
| 8 |
+
<div id="last-take" class="movie-player"><video controls playsinline preload="metadata" aria-label="Finished take" data-aria-en="Finished take" data-aria-fr="Plan terminé"></video><a download="FastFrames-Voice.mp4" data-tr="download">Download MP4</a></div>
|
| 9 |
+
<div id="clip-player" class="movie-player"><video controls playsinline preload="metadata" aria-label="Timeline segment" data-aria-en="Timeline segment" data-aria-fr="Segment du montage"></video></div>
|
assets/playback.js
CHANGED
|
@@ -87,8 +87,7 @@ function inlinePlayback(monitor, canvas, onStart, onEnd, onError) {
|
|
| 87 |
}
|
| 88 |
if(signal.aborted)return null;
|
| 89 |
if(state.blobs[index])return loadStrip(state.blobs[index]);
|
| 90 |
-
const
|
| 91 |
-
const response=await fetch(url,{credentials:"same-origin",signal});
|
| 92 |
if(!response.ok)throw new Error("Could not load segment frames");
|
| 93 |
state.blobs[index]=await response.blob();
|
| 94 |
return loadStrip(state.blobs[index]);
|
|
|
|
| 87 |
}
|
| 88 |
if(signal.aborted)return null;
|
| 89 |
if(state.blobs[index])return loadStrip(state.blobs[index]);
|
| 90 |
+
const response=await media.strip(state.path+"/"+index+".jpg",signal);
|
|
|
|
| 91 |
if(!response.ok)throw new Error("Could not load segment frames");
|
| 92 |
state.blobs[index]=await response.blob();
|
| 93 |
return loadStrip(state.blobs[index]);
|
assets/studio.css
CHANGED
|
@@ -178,3 +178,43 @@ html:has(#huggingface-space-header){scroll-padding-top:60px}
|
|
| 178 |
#studio #loop-preview[hidden]{display:none}
|
| 179 |
|
| 180 |
#studio .desk-rail #video-model{width:auto;max-width:100%;min-height:44px}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
#studio #loop-preview[hidden]{display:none}
|
| 179 |
|
| 180 |
#studio .desk-rail #video-model{width:auto;max-width:100%;min-height:44px}
|
| 181 |
+
|
| 182 |
+
/* Keep the first action in reach while the monitor retains its native proportions. */
|
| 183 |
+
@media(min-width:721px){
|
| 184 |
+
#studio{width:min(1240px,calc(100% - 64px),max(544px,calc((100svh - 372px)*1.7333)));min-width:min(544px,100% - 32px)}
|
| 185 |
+
}
|
| 186 |
+
@media(max-width:720px){
|
| 187 |
+
body div:has(> div > main #studio){padding:0!important}
|
| 188 |
+
#studio{width:calc(100% - 16px);min-width:0}
|
| 189 |
+
#studio .mast #nav-gallery{width:auto}
|
| 190 |
+
#nav-gallery span{position:static;width:auto;height:auto;clip-path:none}
|
| 191 |
+
#studio .mast h1{font-size:clamp(18px,5vw,22px)!important}
|
| 192 |
+
}
|
| 193 |
+
#studio .input-switch{display:inline-flex;gap:2px;margin-top:8px;padding:2px;border:1px solid #515b55}
|
| 194 |
+
#studio .input-switch button{min-height:40px;padding:0 14px}
|
| 195 |
+
#studio .input-switch button[aria-pressed=true]{box-shadow:inset 0 -2px #ffb354}
|
| 196 |
+
#voice-desk[data-review=true] .input-switch{display:none}
|
| 197 |
+
#clip-notice,#timeline header{display:flex;align-items:center;justify-content:space-between;gap:12px}
|
| 198 |
+
#clip-notice{margin-top:5px;color:#f0c58e;font-size:14px}
|
| 199 |
+
#studio #back-to-shot{background:transparent;color:#f3f1eb;border:1px solid #667069;border-radius:5px;min-height:44px;padding:0 12px}
|
| 200 |
+
#monitor #clip-player,#monitor #last-take{display:none;position:absolute;inset:0}
|
| 201 |
+
#monitor[data-mode=saved] #cover{visibility:visible}
|
| 202 |
+
#monitor[data-mode=saved] .viewfinder{display:none}
|
| 203 |
+
#monitor[data-mode=saved] #last-take,#monitor[data-inspect=true] #clip-player{display:block;visibility:visible;opacity:1;pointer-events:auto;z-index:4}
|
| 204 |
+
#monitor[data-inspect=true] #clip-player{z-index:6}
|
| 205 |
+
#monitor[data-inspect=true] #loop-preview{display:none}
|
| 206 |
+
.movie-player video{display:block;width:100%;object-fit:contain;background:#080909}
|
| 207 |
+
#studio .movie-player a{display:inline-flex;align-items:center;min-height:40px;padding:0 12px;color:#fff;background:#202722;border:1px solid #667069;border-radius:5px;text-decoration:none}
|
| 208 |
+
#studio .movie-player a:not([href]){display:none}
|
| 209 |
+
#monitor .movie-player a{position:absolute;top:8px;right:8px}
|
| 210 |
+
#gallery-video a{margin-top:8px}
|
| 211 |
+
#timeline{border-top:1px solid #444c49;margin:9px 0 12px;padding-top:9px;min-width:0}
|
| 212 |
+
#timeline header{margin-bottom:6px}
|
| 213 |
+
#studio #timeline h2{margin:0;font:600 15px/1.2 Barlow,Arial,sans-serif;color:#f0f0e9}
|
| 214 |
+
#timeline-length,.clip-time{color:#b5bdb9;font-variant-numeric:tabular-nums;font-size:12px}
|
| 215 |
+
#clip-list{display:flex;gap:7px;overflow-x:auto;overscroll-behavior-x:contain;padding:3px 3px 7px;scrollbar-width:thin}
|
| 216 |
+
#studio #clip-list button{display:grid;grid-template-columns:1fr;gap:3px;text-align:left;flex:0 0 132px;min-width:0;padding:4px;border:1px solid #49534d;border-radius:4px;background:#1d2320;color:#e8ebe6}
|
| 217 |
+
#clip-list img{display:block;width:100%;height:auto;aspect-ratio:832/480;object-fit:contain;background:#111}
|
| 218 |
+
.clip-title{font-size:13px;font-weight:600}#studio #clip-list button[aria-pressed=true]{border-color:#ffb354}
|
| 219 |
+
#studio #clip-list button:disabled{cursor:default}
|
| 220 |
+
#studio-title:focus-visible,#gallery-title:focus-visible{outline:2px solid #ffb354;outline-offset:3px}
|
assets/studio.js
CHANGED
|
@@ -10,9 +10,16 @@ const hold = by("held-frame");
|
|
| 10 |
const playback = inlinePlayback(monitor, by("cue-screen"),
|
| 11 |
()=>{if(take&&!stopped){setMode("live");setStatus("playing");}},
|
| 12 |
()=>endPreview(false), ()=>endPreview(true));
|
|
|
|
|
|
|
| 13 |
const meter = by("mic-level").getContext("2d");
|
| 14 |
const langButtons = [by("lang-en"), by("lang-fr")];
|
| 15 |
const copy = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
studioTab:["Studio","Studio"],galleryTab:["Videos","Vidéos"],sessions:["Saved videos","Vidéos enregistrées"],
|
| 17 |
director:["Director","Régie"],lastDirection:["Last direction","Dernière consigne"],
|
| 18 |
moreSessions:["Show more","Afficher la suite"],deviceGallery:["This browser","Ce navigateur"],accountGallery:["Your HF account","Ton compte HF"],
|
|
@@ -36,7 +43,7 @@ const copy = {
|
|
| 36 |
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"],
|
| 37 |
voiceMode:["Voice","Voix"],textMode:["Text","Texte"],duration:["Next segment","Prochaine portion"],
|
| 38 |
textLabel:["Written direction","Consigne écrite"],textIdle:["Ready for a written direction","En attente d’une consigne écrite"],
|
| 39 |
-
providerHelp:["
|
| 40 |
queueDirection:["Queue direction","Mettre en attente"],directionQueued:["Direction queued","Consigne en attente"],
|
| 41 |
send:["Generate segment","Générer la portion"],starting:["Opening session…","Ouverture de la session…"],
|
| 42 |
invalid_seconds:["Choose a duration from 1 to 8 s","Choisis une durée de 1 à 8 s"],
|
|
@@ -77,7 +84,7 @@ let collection=null, livePreview=null;
|
|
| 77 |
let loopEnabled=!window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;
|
| 78 |
try{const pref=localStorage.getItem("ffv-loop");if(pref!==null)loopEnabled=pref==="on";}catch{}
|
| 79 |
function syncLoop(){
|
| 80 |
-
const allowed=loopEnabled && !document.hidden && by("studio").dataset.view!=="gallery";
|
| 81 |
playback.setLoop(allowed);
|
| 82 |
if(playback.isLooping())setMode("live");
|
| 83 |
}
|
|
@@ -89,6 +96,10 @@ by("loop-preview").addEventListener("click",()=>{
|
|
| 89 |
document.addEventListener?.("visibilitychange",syncLoop);
|
| 90 |
syncLoop();
|
| 91 |
function label(){
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
root.querySelectorAll("[data-tr]").forEach(e=>e.textContent=tr(e.dataset.tr));
|
| 93 |
langButtons.forEach((b,i)=>b.setAttribute("aria-pressed",String(i===(lang==="fr"?1:0))));
|
| 94 |
by("mic-word").textContent=tr(!take?"start":stream?"on":"off");
|
|
@@ -138,7 +149,7 @@ function label(){
|
|
| 138 |
if(deskEl)deskEl.dataset.busy=String(!!take&&(busy||stopped)&&!retryKind);
|
| 139 |
}
|
| 140 |
function setStatus(k){status=k;label();}
|
| 141 |
-
function emit(name,data){ props.value=JSON.stringify(data); trigger(name); }
|
| 142 |
function setMode(m){mode=m;monitor.dataset.mode=m;}
|
| 143 |
function clearPhrase(){pre=[];blocks=[];voice=false;quiet=0;loud=0;baseline=.003;}
|
| 144 |
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);}}
|
|
@@ -177,7 +188,7 @@ function cueOptions(){
|
|
| 177 |
...(forced?{target_rev:applied}:{}),...(questionId?{reply_to:questionId}:{})};
|
| 178 |
}
|
| 179 |
forceRedo.addEventListener("change",label);
|
| 180 |
-
function pump(){if(!take||!ready||busy||stopped||variantClip||!queue.length)return;busy=true;retryKind="";
|
| 181 |
const cue=queue.shift(), written=cue.text!==undefined;
|
| 182 |
inFlight=cue;setStatus("sent");
|
| 183 |
emit(written?"written":"phrase",{take,seq:++seq,...cue});
|
|
@@ -198,6 +209,7 @@ function sample(a){
|
|
| 198 |
if(quiet>=.75||blocks.length*dt>=13)flush();
|
| 199 |
}
|
| 200 |
function startTake(){
|
|
|
|
| 201 |
resetEditing();lastSegment=null;pendingStill="";saved=false;setMode("cover");
|
| 202 |
take=crypto.randomUUID();seq=applied=visionRev=0;focus=prompt=lastHeard=lastSource=interpreter="";
|
| 203 |
ready=busy=stopped=false;queue=[];retryKind="";playback.clear();
|
|
@@ -261,7 +273,7 @@ async function openMic(){
|
|
| 261 |
}
|
| 262 |
function endSession(){
|
| 263 |
if(opening&&!take){release();setStatus("idle");return;}
|
| 264 |
-
if(!take||stopped)return;stopped=true;retryKind="";queue=[];playback.clear();release();setStatus("stopping");emit("halt",{take});
|
| 265 |
clearTimeout(watchdog);watchdog=setTimeout(()=>{if(stopped)finish("connection");},40000);
|
| 266 |
}
|
| 267 |
mic.addEventListener("click",()=>{
|
|
@@ -325,6 +337,9 @@ window.addEventListener("ffv-signal",e=>{
|
|
| 325 |
if(collection?.signal(d))return;
|
| 326 |
if(!take||d.take!==take)return;
|
| 327 |
if(d.phase==="invalid_model"){finish("invalid_model");return;}
|
|
|
|
|
|
|
|
|
|
| 328 |
if(d.phase==="closed"||d.phase==="finished"){finish(d.phase);return;}
|
| 329 |
if(d.phase==="stopping"){
|
| 330 |
clearTimeout(watchdog);setStatus("finalizing");emit("export_take",{take,device:collection?.device});return;
|
|
@@ -353,7 +368,7 @@ window.addEventListener("ffv-signal",e=>{
|
|
| 353 |
questionId=null;submittedDraft=null;inFlight=null;busy=false;setStatus("holding");pump();return;
|
| 354 |
}
|
| 355 |
if(d.phase==="decided"&&variantClip&&d.rev===variantClip.rev){
|
| 356 |
-
if(d.choice==="variant")approvedClip=variantClip;
|
| 357 |
variantClip=null;choosing=false;editOperation="append";retryKind="";
|
| 358 |
lastSegment=approvedClip;applied=approvedClip.rev;pendingStill=approvedClip.still;
|
| 359 |
({lastHeard,focus,prompt,interpreter,lastSource}=approvedClip);
|
|
@@ -372,7 +387,7 @@ window.addEventListener("ffv-signal",e=>{
|
|
| 372 |
if(!livePreview.ended)playback.extend(d,d.ready);
|
| 373 |
return;
|
| 374 |
}
|
| 375 |
-
if(["gpu_error","quota","hardware"].includes(d.phase)){
|
| 376 |
// A written direction queued against a failed segment stays in the editor.
|
| 377 |
if(queue.some(cue=>cue.text!==undefined)){
|
| 378 |
queue=queue.filter(cue=>cue.text===undefined);submittedDraft=null;
|
|
@@ -385,9 +400,9 @@ window.addEventListener("ffv-signal",e=>{
|
|
| 385 |
}
|
| 386 |
if(d.phase==="segment"||d.phase==="variant"){
|
| 387 |
if(d.rev<=applied||variantClip?.rev===d.rev)return;
|
| 388 |
-
const clip={preview:d.preview,frames:d.frames,still:d.still,rev:d.rev,seconds:d.seconds,lastHeard,prompt,focus,interpreter,lastSource};
|
| 389 |
if(d.phase==="variant")variantClip=clip;
|
| 390 |
-
else {approvedClip=clip;applied=d.rev;}
|
| 391 |
if(livePreview && !livePreview.failed){
|
| 392 |
lastSegment=clip;pendingStill=clip.still;livePreview.committed=true;
|
| 393 |
// A slow client can miss intermediate Gradio events. The final publication confirms all strips.
|
|
@@ -403,4 +418,7 @@ window.addEventListener("ffv-signal",e=>{
|
|
| 403 |
setStatus(d.phase==="generating"&&editOperation==="redo_last"?"redoGenerating":d.phase);
|
| 404 |
});
|
| 405 |
window.addEventListener("pagehide",event=>{if(take)endSession();release();if(!event.persisted)playback.dispose();});
|
|
|
|
|
|
|
|
|
|
| 406 |
collection=sessionCollection();draw();setMode("cover");label();
|
|
|
|
| 10 |
const playback = inlinePlayback(monitor, by("cue-screen"),
|
| 11 |
()=>{if(take&&!stopped){setMode("live");setStatus("playing");}},
|
| 12 |
()=>endPreview(false), ()=>endPreview(true));
|
| 13 |
+
const media=studioMedia();
|
| 14 |
+
let timeline=null;
|
| 15 |
const meter = by("mic-level").getContext("2d");
|
| 16 |
const langButtons = [by("lang-en"), by("lang-fr")];
|
| 17 |
const copy = {
|
| 18 |
+
timelineTitle:["Timeline","Montage"],segmentName:["Segment","Segment"],editable:["Editable","Modifiable"],
|
| 19 |
+
playClip:["Play segment","Lire le segment"],replaying:["Playback","Relecture"],backToShot:["Back to monitor","Retour au moniteur"],
|
| 20 |
+
download:["Download MP4","Télécharger le MP4"],history_error:["Couldn’t load segment playback","Relecture du segment indisponible"],
|
| 21 |
+
disk_full:["Temporary storage is full · save this take or retry later","Disque temporaire plein · enregistre ce plan ou réessaie plus tard"],
|
| 22 |
+
researchLicense:["Non-commercial research · License","Recherche non commerciale · Licence"],
|
| 23 |
studioTab:["Studio","Studio"],galleryTab:["Videos","Vidéos"],sessions:["Saved videos","Vidéos enregistrées"],
|
| 24 |
director:["Director","Régie"],lastDirection:["Last direction","Dernière consigne"],
|
| 25 |
moreSessions:["Show more","Afficher la suite"],deviceGallery:["This browser","Ce navigateur"],accountGallery:["Your HF account","Ton compte HF"],
|
|
|
|
| 43 |
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"],
|
| 44 |
voiceMode:["Voice","Voix"],textMode:["Text","Texte"],duration:["Next segment","Prochaine portion"],
|
| 45 |
textLabel:["Written direction","Consigne écrite"],textIdle:["Ready for a written direction","En attente d’une consigne écrite"],
|
| 46 |
+
providerHelp:["Optional · Sign in for Inkling and to save to your private HF bucket.","Facultatif · Connecte-toi pour utiliser Inkling et enregistrer tes films dans ton bucket HF privé."],
|
| 47 |
queueDirection:["Queue direction","Mettre en attente"],directionQueued:["Direction queued","Consigne en attente"],
|
| 48 |
send:["Generate segment","Générer la portion"],starting:["Opening session…","Ouverture de la session…"],
|
| 49 |
invalid_seconds:["Choose a duration from 1 to 8 s","Choisis une durée de 1 à 8 s"],
|
|
|
|
| 84 |
let loopEnabled=!window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;
|
| 85 |
try{const pref=localStorage.getItem("ffv-loop");if(pref!==null)loopEnabled=pref==="on";}catch{}
|
| 86 |
function syncLoop(){
|
| 87 |
+
const allowed=loopEnabled && !timeline?.inspecting() && !document.hidden && by("studio").dataset.view!=="gallery";
|
| 88 |
playback.setLoop(allowed);
|
| 89 |
if(playback.isLooping())setMode("live");
|
| 90 |
}
|
|
|
|
| 96 |
document.addEventListener?.("visibilitychange",syncLoop);
|
| 97 |
syncLoop();
|
| 98 |
function label(){
|
| 99 |
+
by("studio").lang=lang;
|
| 100 |
+
document.documentElement.lang=lang;
|
| 101 |
+
root.querySelectorAll("[data-aria-fr]").forEach(e=>e.setAttribute("aria-label",lang==="fr"?e.dataset.ariaFr:e.dataset.ariaEn));
|
| 102 |
+
timeline?.update();
|
| 103 |
root.querySelectorAll("[data-tr]").forEach(e=>e.textContent=tr(e.dataset.tr));
|
| 104 |
langButtons.forEach((b,i)=>b.setAttribute("aria-pressed",String(i===(lang==="fr"?1:0))));
|
| 105 |
by("mic-word").textContent=tr(!take?"start":stream?"on":"off");
|
|
|
|
| 149 |
if(deskEl)deskEl.dataset.busy=String(!!take&&(busy||stopped)&&!retryKind);
|
| 150 |
}
|
| 151 |
function setStatus(k){status=k;label();}
|
| 152 |
+
function emit(name,data){ props.value=JSON.stringify({...data,media_key:media.key}); trigger(name); }
|
| 153 |
function setMode(m){mode=m;monitor.dataset.mode=m;}
|
| 154 |
function clearPhrase(){pre=[];blocks=[];voice=false;quiet=0;loud=0;baseline=.003;}
|
| 155 |
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);}}
|
|
|
|
| 188 |
...(forced?{target_rev:applied}:{}),...(questionId?{reply_to:questionId}:{})};
|
| 189 |
}
|
| 190 |
forceRedo.addEventListener("change",label);
|
| 191 |
+
function pump(){if(!take||!ready||busy||stopped||variantClip||!queue.length)return;timeline?.close();busy=true;retryKind="";
|
| 192 |
const cue=queue.shift(), written=cue.text!==undefined;
|
| 193 |
inFlight=cue;setStatus("sent");
|
| 194 |
emit(written?"written":"phrase",{take,seq:++seq,...cue});
|
|
|
|
| 209 |
if(quiet>=.75||blocks.length*dt>=13)flush();
|
| 210 |
}
|
| 211 |
function startTake(){
|
| 212 |
+
timeline?.reset();media.clear("last-take");
|
| 213 |
resetEditing();lastSegment=null;pendingStill="";saved=false;setMode("cover");
|
| 214 |
take=crypto.randomUUID();seq=applied=visionRev=0;focus=prompt=lastHeard=lastSource=interpreter="";
|
| 215 |
ready=busy=stopped=false;queue=[];retryKind="";playback.clear();
|
|
|
|
| 273 |
}
|
| 274 |
function endSession(){
|
| 275 |
if(opening&&!take){release();setStatus("idle");return;}
|
| 276 |
+
if(!take||stopped)return;timeline?.close();stopped=true;retryKind="";queue=[];playback.clear();release();setStatus("stopping");emit("halt",{take});
|
| 277 |
clearTimeout(watchdog);watchdog=setTimeout(()=>{if(stopped)finish("connection");},40000);
|
| 278 |
}
|
| 279 |
mic.addEventListener("click",()=>{
|
|
|
|
| 337 |
if(collection?.signal(d))return;
|
| 338 |
if(!take||d.take!==take)return;
|
| 339 |
if(d.phase==="invalid_model"){finish("invalid_model");return;}
|
| 340 |
+
if(d.media && ["archiving","archive_error","finished"].includes(d.phase)){
|
| 341 |
+
media.show("last-take",d.media).catch(()=>setStatus("history_error"));
|
| 342 |
+
}
|
| 343 |
if(d.phase==="closed"||d.phase==="finished"){finish(d.phase);return;}
|
| 344 |
if(d.phase==="stopping"){
|
| 345 |
clearTimeout(watchdog);setStatus("finalizing");emit("export_take",{take,device:collection?.device});return;
|
|
|
|
| 368 |
questionId=null;submittedDraft=null;inFlight=null;busy=false;setStatus("holding");pump();return;
|
| 369 |
}
|
| 370 |
if(d.phase==="decided"&&variantClip&&d.rev===variantClip.rev){
|
| 371 |
+
if(d.choice==="variant"){approvedClip=variantClip;timeline.add(approvedClip,true);}
|
| 372 |
variantClip=null;choosing=false;editOperation="append";retryKind="";
|
| 373 |
lastSegment=approvedClip;applied=approvedClip.rev;pendingStill=approvedClip.still;
|
| 374 |
({lastHeard,focus,prompt,interpreter,lastSource}=approvedClip);
|
|
|
|
| 387 |
if(!livePreview.ended)playback.extend(d,d.ready);
|
| 388 |
return;
|
| 389 |
}
|
| 390 |
+
if(["gpu_error","quota","hardware","disk_full"].includes(d.phase)){
|
| 391 |
// A written direction queued against a failed segment stays in the editor.
|
| 392 |
if(queue.some(cue=>cue.text!==undefined)){
|
| 393 |
queue=queue.filter(cue=>cue.text===undefined);submittedDraft=null;
|
|
|
|
| 400 |
}
|
| 401 |
if(d.phase==="segment"||d.phase==="variant"){
|
| 402 |
if(d.rev<=applied||variantClip?.rev===d.rev)return;
|
| 403 |
+
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};
|
| 404 |
if(d.phase==="variant")variantClip=clip;
|
| 405 |
+
else {approvedClip=clip;applied=d.rev;timeline.add(clip);}
|
| 406 |
if(livePreview && !livePreview.failed){
|
| 407 |
lastSegment=clip;pendingStill=clip.still;livePreview.committed=true;
|
| 408 |
// A slow client can miss intermediate Gradio events. The final publication confirms all strips.
|
|
|
|
| 418 |
setStatus(d.phase==="generating"&&editOperation==="redo_last"?"redoGenerating":d.phase);
|
| 419 |
});
|
| 420 |
window.addEventListener("pagehide",event=>{if(take)endSession();release();if(!event.persisted)playback.dispose();});
|
| 421 |
+
timeline=shotTimeline();
|
| 422 |
+
const keepAlive=setInterval(()=>{if(take&&ready&&!busy&&!stopped)emit("heartbeat",{take});},60000);
|
| 423 |
+
window.addEventListener("pagehide",e=>{if(!e.persisted)clearInterval(keepAlive);});
|
| 424 |
collection=sessionCollection();draw();setMode("cover");label();
|
assets/timeline.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
function shotTimeline() {
|
| 2 |
+
const el=by("timeline"), list=by("clip-list");
|
| 3 |
+
let clips=[], selected=null;
|
| 4 |
+
const clock=n=>Math.floor(n/60)+":"+String(n%60).padStart(2,"0");
|
| 5 |
+
function close() {
|
| 6 |
+
if(selected===null)return;
|
| 7 |
+
selected=null;media.clear("clip-player");
|
| 8 |
+
monitor.removeAttribute("data-inspect");
|
| 9 |
+
by("clip-notice").hidden=true;
|
| 10 |
+
syncLoop();update();
|
| 11 |
+
}
|
| 12 |
+
function update() {
|
| 13 |
+
el.hidden=!clips.length;
|
| 14 |
+
let offset=0;
|
| 15 |
+
const locked=Boolean(busy||stopped||variantClip);
|
| 16 |
+
for(const [i,clip] of clips.entries()){
|
| 17 |
+
const button=list.children[i], latest=i===clips.length-1 && Boolean(take) && !stopped;
|
| 18 |
+
const title=tr("segmentName")+" "+(i+1);
|
| 19 |
+
button.querySelector(".clip-time").textContent=clock(offset)+" · "+clip.seconds+" s";
|
| 20 |
+
button.querySelector(".clip-title").textContent=latest?title+" · "+tr("editable"):title;
|
| 21 |
+
button.setAttribute("aria-label",tr("playClip")+" "+(i+1)+", "+clock(offset)+", "+clip.seconds+" s"+(latest?", "+tr("editable"):""));
|
| 22 |
+
button.setAttribute("aria-pressed",String(clip.rev===selected));
|
| 23 |
+
button.disabled=locked;offset+=clip.seconds;
|
| 24 |
+
}
|
| 25 |
+
by("timeline-length").textContent=clock(offset);
|
| 26 |
+
if(selected!==null){
|
| 27 |
+
by("clip-caption").textContent=tr("replaying")+" · "+tr("segmentName")+" "+(clips.findIndex(c=>c.rev===selected)+1);
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
function add(clip,replace=false) {
|
| 31 |
+
const entry={rev:clip.rev,seconds:clip.seconds,media:clip.media};
|
| 32 |
+
if(clips.some(c=>c.rev===entry.rev))return;
|
| 33 |
+
if(replace){clips.pop();list.lastElementChild?.remove();}
|
| 34 |
+
clips.push(entry);
|
| 35 |
+
const button=document.createElement("button");
|
| 36 |
+
button.type="button";
|
| 37 |
+
const image=document.createElement("img");image.alt="";image.src=clip.thumb;image.width=128;image.height=74;
|
| 38 |
+
const title=document.createElement("span");title.className="clip-title";
|
| 39 |
+
const time=document.createElement("span");time.className="clip-time";
|
| 40 |
+
button.append(image,title,time);list.append(button);update();
|
| 41 |
+
list.scrollLeft=list.scrollWidth;
|
| 42 |
+
button.addEventListener("click",async()=>{
|
| 43 |
+
if(button.disabled)return;
|
| 44 |
+
selected=entry.rev;monitor.dataset.inspect="true";by("clip-notice").hidden=false;
|
| 45 |
+
playback.setLoop(false);update();
|
| 46 |
+
try {await media.show("clip-player",entry.media,true);}
|
| 47 |
+
catch {if(selected===entry.rev){close();setStatus("history_error");}}
|
| 48 |
+
});
|
| 49 |
+
}
|
| 50 |
+
by("back-to-shot").addEventListener("click",()=>{
|
| 51 |
+
const index=clips.findIndex(c=>c.rev===selected);close();list.children[index]?.focus({preventScroll:true});
|
| 52 |
+
});
|
| 53 |
+
function reset(){close();clips=[];list.replaceChildren();update();}
|
| 54 |
+
return {add,close,reset,update,inspecting:()=>selected!==null};
|
| 55 |
+
}
|
continuity.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""Temporary, lossless FastFrames attention windows. Each frame is written once per branch."""
|
| 2 |
from collections import deque
|
| 3 |
from contextlib import nullcontext
|
|
|
|
| 4 |
import math
|
| 5 |
import os
|
| 6 |
|
|
@@ -29,6 +30,15 @@ def write_frame(path, packed, stream, ready):
|
|
| 29 |
with torch.cuda.stream(stream) if stream is not None else nullcontext():
|
| 30 |
if ready is not None:
|
| 31 |
stream.wait_event(ready)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
mapped = torch.from_file(str(path), shared=True, size=packed.numel(), dtype=packed.dtype)
|
| 33 |
# A blocking copy on the transfer stream completes before the writer releases its inputs.
|
| 34 |
mapped.view_as(packed).copy_(packed)
|
|
@@ -98,6 +108,15 @@ def restore_frames(roll, folder, records, stride, sink, shift, check_active):
|
|
| 98 |
path = frame_file(folder, frame)
|
| 99 |
if path.stat().st_size != size * example.element_size() or not 0 <= records[frame] <= roll.rolls:
|
| 100 |
raise ValueError("Invalid continuity frame")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
mapped = torch.from_file(str(path), shared=False, size=size, dtype=example.dtype)
|
| 102 |
packed = mapped.view(shape).to(roll.pipe.device)
|
| 103 |
keys = packed[0::2]
|
|
|
|
| 1 |
"""Temporary, lossless FastFrames attention windows. Each frame is written once per branch."""
|
| 2 |
from collections import deque
|
| 3 |
from contextlib import nullcontext
|
| 4 |
+
import errno
|
| 5 |
import math
|
| 6 |
import os
|
| 7 |
|
|
|
|
| 30 |
with torch.cuda.stream(stream) if stream is not None else nullcontext():
|
| 31 |
if ready is not None:
|
| 32 |
stream.wait_event(ready)
|
| 33 |
+
# Reserve the extent before mapping so a full filesystem raises a recoverable error.
|
| 34 |
+
with path.open("wb") as output:
|
| 35 |
+
try:
|
| 36 |
+
os.posix_fallocate(output.fileno(), 0, packed.numel() * packed.element_size())
|
| 37 |
+
except OSError as error:
|
| 38 |
+
if error.errno not in (errno.EOPNOTSUPP, errno.ENOSYS):
|
| 39 |
+
raise
|
| 40 |
+
packed.cpu().contiguous().view(torch.uint8).numpy().tofile(output)
|
| 41 |
+
return
|
| 42 |
mapped = torch.from_file(str(path), shared=True, size=packed.numel(), dtype=packed.dtype)
|
| 43 |
# A blocking copy on the transfer stream completes before the writer releases its inputs.
|
| 44 |
mapped.view_as(packed).copy_(packed)
|
|
|
|
| 108 |
path = frame_file(folder, frame)
|
| 109 |
if path.stat().st_size != size * example.element_size() or not 0 <= records[frame] <= roll.rolls:
|
| 110 |
raise ValueError("Invalid continuity frame")
|
| 111 |
+
# Reserve the extent before mapping so a full filesystem raises a recoverable error.
|
| 112 |
+
with path.open("wb") as output:
|
| 113 |
+
try:
|
| 114 |
+
os.posix_fallocate(output.fileno(), 0, packed.numel() * packed.element_size())
|
| 115 |
+
except OSError as error:
|
| 116 |
+
if error.errno not in (errno.EOPNOTSUPP, errno.ENOSYS):
|
| 117 |
+
raise
|
| 118 |
+
packed.cpu().contiguous().view(torch.uint8).numpy().tofile(output)
|
| 119 |
+
return
|
| 120 |
mapped = torch.from_file(str(path), shared=False, size=size, dtype=example.dtype)
|
| 121 |
packed = mapped.view(shape).to(roll.pipe.device)
|
| 122 |
keys = packed[0::2]
|
housekeeping.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reclaim abandoned temporary takes and share disk headroom between renders."""
|
| 2 |
+
import logging
|
| 3 |
+
import shutil
|
| 4 |
+
import threading
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
import gallery
|
| 8 |
+
import takes
|
| 9 |
+
|
| 10 |
+
IDLE_SECONDS = 90 * 60
|
| 11 |
+
MIN_FREE = 512 * 1024**2
|
| 12 |
+
|
| 13 |
+
with takes.connection() as db:
|
| 14 |
+
db.execute("CREATE TABLE reservations (id TEXT PRIMARY KEY, bytes INTEGER NOT NULL)")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def reserve(key, size):
|
| 18 |
+
with takes.connection() as db:
|
| 19 |
+
db.execute("BEGIN IMMEDIATE")
|
| 20 |
+
reserved = db.execute("SELECT coalesce(sum(bytes),0) FROM reservations").fetchone()[0]
|
| 21 |
+
if size + reserved + MIN_FREE > shutil.disk_usage(takes.ROOT).free:
|
| 22 |
+
return False
|
| 23 |
+
db.execute("INSERT INTO reservations VALUES (?,?)", (key,size))
|
| 24 |
+
return True
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def release(key):
|
| 28 |
+
with takes.connection() as db:
|
| 29 |
+
db.execute("DELETE FROM reservations WHERE id=?", (key,))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def sweep():
|
| 33 |
+
cutoff = int(time.time()) - IDLE_SECONDS
|
| 34 |
+
with takes.connection() as db:
|
| 35 |
+
owners = db.execute("""SELECT owner FROM takes WHERE touched<? AND phase NOT IN ('live','interpreting')
|
| 36 |
+
UNION SELECT session FROM media WHERE touched<?""",(cutoff,cutoff)).fetchall()
|
| 37 |
+
for (owner,) in owners:
|
| 38 |
+
with gallery.lock_for(owner), takes.connection() as db:
|
| 39 |
+
db.execute("BEGIN IMMEDIATE")
|
| 40 |
+
row = db.execute("SELECT id,touched,phase FROM takes WHERE owner=?", (owner,)).fetchone()
|
| 41 |
+
if row and (row["touched"] >= cutoff or row["phase"] in ("live","interpreting")):
|
| 42 |
+
continue
|
| 43 |
+
paths = takes.remove_owner(db,owner) if row else []
|
| 44 |
+
expired = db.execute("SELECT path FROM media WHERE session=? AND touched<?",(owner,cutoff)).fetchall()
|
| 45 |
+
db.execute("DELETE FROM media WHERE session=? AND touched<?",(owner,cutoff))
|
| 46 |
+
db.commit()
|
| 47 |
+
for path in paths:
|
| 48 |
+
shutil.rmtree(path,ignore_errors=True)
|
| 49 |
+
for (relative,) in expired:
|
| 50 |
+
if relative.startswith("viewing/"):
|
| 51 |
+
file = takes.ROOT / relative
|
| 52 |
+
file.unlink(missing_ok=True)
|
| 53 |
+
try:
|
| 54 |
+
file.parent.rmdir()
|
| 55 |
+
except OSError:
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def start():
|
| 60 |
+
def periodic():
|
| 61 |
+
while True:
|
| 62 |
+
time.sleep(60)
|
| 63 |
+
try:
|
| 64 |
+
sweep()
|
| 65 |
+
except Exception:
|
| 66 |
+
logging.getLogger("studio").exception("Temporary session cleanup failed")
|
| 67 |
+
threading.Thread(target=periodic,name="temporary-take-cleanup",daemon=True).start()
|
media_access.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serve session media outside Gradio's shared cache."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import hmac
|
| 4 |
+
import re
|
| 5 |
+
import secrets
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from starlette.requests import Request
|
| 9 |
+
from starlette.responses import FileResponse, Response
|
| 10 |
+
|
| 11 |
+
import takes
|
| 12 |
+
|
| 13 |
+
PREFIX = "/studio-media/"
|
| 14 |
+
HEADER = "x-fastframes-key"
|
| 15 |
+
COOKIE = "__Host-ffv-media"
|
| 16 |
+
SECRET = secrets.token_bytes(32)
|
| 17 |
+
KEY = re.compile(r"[0-9a-f]{64}")
|
| 18 |
+
PRIVATE = {"Cache-Control": "private, no-store", "Vary": "Cookie, X-FastFrames-Key",
|
| 19 |
+
"Cross-Origin-Resource-Policy": "same-origin", "X-Content-Type-Options": "nosniff"}
|
| 20 |
+
|
| 21 |
+
with takes.connection() as db:
|
| 22 |
+
db.execute("""CREATE TABLE media (
|
| 23 |
+
id TEXT PRIMARY KEY, owner TEXT NOT NULL, session TEXT NOT NULL, path TEXT NOT NULL,
|
| 24 |
+
strips INTEGER NOT NULL, touched INTEGER NOT NULL DEFAULT (unixepoch()),
|
| 25 |
+
UNIQUE (owner, session, path))""")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def digest(key):
|
| 29 |
+
return hashlib.sha256(key.encode()).hexdigest()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def credential(payload, request):
|
| 33 |
+
value = payload.get("media_key") or (getattr(request,"headers",None) or {}).get(HEADER)
|
| 34 |
+
if value is None:
|
| 35 |
+
return hmac.digest(SECRET, request.session_hash.encode(), "sha256").hex()
|
| 36 |
+
if not isinstance(value, str) or not KEY.fullmatch(value):
|
| 37 |
+
raise ValueError("Invalid media credential")
|
| 38 |
+
return value
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def register(path, key, session, strips=False):
|
| 42 |
+
path = Path(path).resolve().relative_to(takes.ROOT.resolve()).as_posix()
|
| 43 |
+
with takes.connection() as db:
|
| 44 |
+
row = db.execute("""INSERT INTO media(id,owner,session,path,strips) VALUES (?,?,?,?,?)
|
| 45 |
+
ON CONFLICT(owner,session,path) DO UPDATE SET touched=unixepoch() RETURNING id""",
|
| 46 |
+
(secrets.token_hex(18),digest(key),session,path,int(strips))).fetchone()
|
| 47 |
+
return PREFIX + row[0] + ("" if strips else "/clip.mp4")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def file_info(url):
|
| 51 |
+
return {"video":{"path":url,"url":url,"orig_name":"FastFrames-Voice.mp4","mime_type":"video/mp4"},"subtitles":None}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class PrivateMedia:
|
| 55 |
+
def __init__(self, app):
|
| 56 |
+
self.app = app
|
| 57 |
+
|
| 58 |
+
async def __call__(self, scope, receive, send):
|
| 59 |
+
if scope["type"] != "http" or not scope["path"].startswith(PREFIX):
|
| 60 |
+
return await self.app(scope,receive,send)
|
| 61 |
+
request = Request(scope)
|
| 62 |
+
key = request.headers.get(HEADER) or request.cookies.get(COOKIE,"")
|
| 63 |
+
response = Response(status_code=404, headers=PRIVATE)
|
| 64 |
+
path = scope["path"][len(PREFIX):]
|
| 65 |
+
if KEY.fullmatch(key):
|
| 66 |
+
if path == "bind" and request.method == "POST" and request.headers.get(HEADER):
|
| 67 |
+
headers = {**PRIVATE, "Set-Cookie": f"{COOKIE}={key}; Path=/; Secure; HttpOnly; SameSite=None; Partitioned"}
|
| 68 |
+
response = Response(status_code=204, headers=headers)
|
| 69 |
+
elif path == "check" and request.method == "HEAD":
|
| 70 |
+
response = Response(status_code=204,headers={**PRIVATE,"X-Media-Owner":digest(key)})
|
| 71 |
+
elif request.method in ("GET","HEAD"):
|
| 72 |
+
match = re.fullmatch(r"([0-9a-f]{36})/(clip\.mp4|[0-9]{1,3}\.jpg)", path)
|
| 73 |
+
if match:
|
| 74 |
+
with takes.connection() as db:
|
| 75 |
+
row = db.execute("SELECT path,strips FROM media WHERE id=? AND owner=?",
|
| 76 |
+
(match[1],digest(key))).fetchone()
|
| 77 |
+
if row and bool(row["strips"]) == match[2].endswith(".jpg"):
|
| 78 |
+
file = takes.ROOT / row["path"]
|
| 79 |
+
if row["strips"]:
|
| 80 |
+
file = file / match[2]
|
| 81 |
+
if file.is_file():
|
| 82 |
+
response = FileResponse(file, media_type="image/jpeg" if row["strips"] else "video/mp4",
|
| 83 |
+
headers=PRIVATE)
|
| 84 |
+
await response(scope,receive,send)
|
render.py
CHANGED
|
@@ -27,6 +27,17 @@ class CueCancelled(Exception):
|
|
| 27 |
pass
|
| 28 |
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
def gpu_duration(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=False, model="S"):
|
| 31 |
return 120 if model == "L" else 60
|
| 32 |
|
|
|
|
| 27 |
pass
|
| 28 |
|
| 29 |
|
| 30 |
+
def temporary_bytes(model, seconds, previous):
|
| 31 |
+
pipe = en.PIPELINES[model]
|
| 32 |
+
steps = seconds * 4 + int(not previous)
|
| 33 |
+
frames = min(pipe.config.num_frames, steps)
|
| 34 |
+
if previous and not next((previous / "state").glob("*.kv"), None):
|
| 35 |
+
frames = pipe.config.num_frames
|
| 36 |
+
kv = frames * pipe.frame_tokens * pipe.dit.dim * len(pipe.dit.blocks) * 2 * 2
|
| 37 |
+
pixels = seconds * 16 * 832 * 480 * 3
|
| 38 |
+
return kv + 2 * pixels + 512 * 1024**2
|
| 39 |
+
|
| 40 |
+
|
| 41 |
def gpu_duration(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=False, model="S"):
|
| 42 |
return 120 if model == "L" else 60
|
| 43 |
|
takes.py
CHANGED
|
@@ -23,11 +23,13 @@ def connection():
|
|
| 23 |
with connection() as db:
|
| 24 |
db.execute("""CREATE TABLE takes (
|
| 25 |
id TEXT PRIMARY KEY, owner TEXT NOT NULL, phase TEXT NOT NULL, model TEXT NOT NULL,
|
| 26 |
-
seq INTEGER DEFAULT 0, rev INTEGER DEFAULT 0, rendered INTEGER DEFAULT 0,
|
| 27 |
title TEXT DEFAULT '', prompt TEXT DEFAULT '', last TEXT DEFAULT '', focus TEXT DEFAULT '',
|
| 28 |
parent INTEGER DEFAULT 0, seed INTEGER NOT NULL, last_seconds INTEGER DEFAULT 0,
|
| 29 |
decision_rev INTEGER DEFAULT 0, decision TEXT DEFAULT '', operation TEXT DEFAULT 'append', question TEXT DEFAULT '', seconds INTEGER DEFAULT 4, next_prompt TEXT DEFAULT '', next_last TEXT DEFAULT '', next_focus TEXT DEFAULT '')""")
|
| 30 |
|
|
|
|
|
|
|
| 31 |
db.execute("""CREATE TABLE clips (
|
| 32 |
take_id TEXT REFERENCES takes(id) ON DELETE CASCADE, rev INTEGER NOT NULL, seconds INTEGER NOT NULL,
|
| 33 |
PRIMARY KEY(take_id,rev))""")
|
|
@@ -64,15 +66,18 @@ def forget(owner):
|
|
| 64 |
shutil.rmtree(path, ignore_errors=True)
|
| 65 |
|
| 66 |
|
| 67 |
-
def start(key, owner, model="S"):
|
| 68 |
if model not in ("S", "L"):
|
| 69 |
raise ValueError("Invalid video model")
|
| 70 |
with connection() as db:
|
| 71 |
db.execute("BEGIN IMMEDIATE")
|
| 72 |
if db.execute("SELECT 1 FROM takes WHERE id=?", (key,)).fetchone():
|
| 73 |
raise ValueError("Duplicate take")
|
|
|
|
|
|
|
|
|
|
| 74 |
old = remove_owner(db, owner)
|
| 75 |
-
db.execute("INSERT INTO takes(id,owner,phase,seed,model) VALUES(?,?,'armed',?,?)",(key,owner,secrets.randbits(31),model))
|
| 76 |
(ROOT / key).mkdir()
|
| 77 |
for path in old:
|
| 78 |
shutil.rmtree(path, ignore_errors=True)
|
|
|
|
| 23 |
with connection() as db:
|
| 24 |
db.execute("""CREATE TABLE takes (
|
| 25 |
id TEXT PRIMARY KEY, owner TEXT NOT NULL, phase TEXT NOT NULL, model TEXT NOT NULL,
|
| 26 |
+
media_owner TEXT DEFAULT '', touched INTEGER NOT NULL DEFAULT (unixepoch()), seq INTEGER DEFAULT 0, rev INTEGER DEFAULT 0, rendered INTEGER DEFAULT 0,
|
| 27 |
title TEXT DEFAULT '', prompt TEXT DEFAULT '', last TEXT DEFAULT '', focus TEXT DEFAULT '',
|
| 28 |
parent INTEGER DEFAULT 0, seed INTEGER NOT NULL, last_seconds INTEGER DEFAULT 0,
|
| 29 |
decision_rev INTEGER DEFAULT 0, decision TEXT DEFAULT '', operation TEXT DEFAULT 'append', question TEXT DEFAULT '', seconds INTEGER DEFAULT 4, next_prompt TEXT DEFAULT '', next_last TEXT DEFAULT '', next_focus TEXT DEFAULT '')""")
|
| 30 |
|
| 31 |
+
db.execute("""CREATE TRIGGER touch_take AFTER UPDATE OF phase,seq,rev ON takes BEGIN
|
| 32 |
+
UPDATE takes SET touched=unixepoch() WHERE id=NEW.id; END""")
|
| 33 |
db.execute("""CREATE TABLE clips (
|
| 34 |
take_id TEXT REFERENCES takes(id) ON DELETE CASCADE, rev INTEGER NOT NULL, seconds INTEGER NOT NULL,
|
| 35 |
PRIMARY KEY(take_id,rev))""")
|
|
|
|
| 66 |
shutil.rmtree(path, ignore_errors=True)
|
| 67 |
|
| 68 |
|
| 69 |
+
def start(key, owner, model="S", media_owner=""):
|
| 70 |
if model not in ("S", "L"):
|
| 71 |
raise ValueError("Invalid video model")
|
| 72 |
with connection() as db:
|
| 73 |
db.execute("BEGIN IMMEDIATE")
|
| 74 |
if db.execute("SELECT 1 FROM takes WHERE id=?", (key,)).fetchone():
|
| 75 |
raise ValueError("Duplicate take")
|
| 76 |
+
held = db.execute("SELECT media_owner FROM takes WHERE owner=?", (owner,)).fetchone()
|
| 77 |
+
if held and held[0] != media_owner:
|
| 78 |
+
raise ValueError("Session unavailable")
|
| 79 |
old = remove_owner(db, owner)
|
| 80 |
+
db.execute("INSERT INTO takes(id,owner,phase,seed,model,media_owner) VALUES(?,?,'armed',?,?,?)",(key,owner,secrets.randbits(31),model,media_owner))
|
| 81 |
(ROOT / key).mkdir()
|
| 82 |
for path in old:
|
| 83 |
shutil.rmtree(path, ignore_errors=True)
|