fffiloni commited on
Commit
b364797
·
verified ·
1 Parent(s): 2207496

Save only the finished MP4 and remove session restore

Browse files
Files changed (10) hide show
  1. README.md +4 -4
  2. app.py +6 -18
  3. assets/collection.js +14 -24
  4. assets/gallery.html +1 -1
  5. assets/header.html +1 -1
  6. assets/studio.css +2 -2
  7. assets/studio.js +9 -18
  8. gallery.py +82 -104
  9. personal_bucket.py +11 -8
  10. takes.py +2 -31
README.md CHANGED
@@ -28,21 +28,21 @@ models:
28
 
29
  # FastFrames Voice
30
 
31
- A private research prototype for directing a continuous generated shot with spoken or written cues. Version 0.6.0. The monitor fills the studio above a horizontal desk for the microphone, transcript and interpreted direction. Open Sessions in the header to browse recordings.
32
 
33
  Select Voice and start the microphone, or select Text, write a direction and press Generate segment (Enter to send, Shift+Enter for a new line). Text mode releases the microphone. Switching inputs preserves the shot. Each accepted direction generates one silent segment at 832 × 480 and 16 fps. Choose 1–8 whole seconds (default 4) before submitting each direction. Each second contains 16 frames. The opening generates one extra latent and trims one leading decoded frame after the model’s three startup frames to deliver an exact whole-second clip. The last segment loops locally while you think or the next cue is being prepared. Toggle Loop on the monitor to freeze it. Reduced-motion preferences disable looping by default. Repeats never enter the exported recording. End session joins completed segments into a downloadable MP4. Microphone mute discards unsubmitted audio and stops capture. Unmute continues the same take. The monitor plays the generated frames on an inline canvas, including on iPhone. The studio publishes JPEG strips of eight frames as the generator produces them. Inline playback starts at the first available strip, before the checkpoint and final MP4 are ready. The next generation waits for the previous revision to commit. API clients can request the same preview events with stream_preview set to true on live_take. The complete take uses a native MP4 player with inline playback and download.
34
 
35
  After a clip is complete, voice and text directions can continue the shot or redo its last segment. Check **Redo last segment** to force a variant for one instruction. A redo uses the duration and the starting state of the original (the same initial seed for the opening). The next-segment duration selector is preserved. With an ambiguous cue, answer “last segment” or “next segment” by voice, text or button; the studio keeps the original direction while waiting. Review both versions, then choose **Keep original** or **Use variant**. Ending during review exports the original. Only chosen clips enter the recording and future continuity.
36
 
37
- Fluid Speech Pro transcribes voice on CPU. Typed directions bypass speech recognition. Inkling 2 Mini updates the last completed shot via Hugging Face Inference Providers when a provider credential is available. Only the text of the current direction, previous direction, target and visual prompt are sent to the HF router. Use the Hugging Face sign-in button below the studio title before starting a take to use your inference credits, or set a server-side HF_INFERENCE_TOKEN secret scoped to Inference Providers. Qwen runs locally when no credential is present or the provider call fails. The interpreted direction identifies the model used. 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 latest clip and its immediate predecessor retain their checkpoints. A pending variant has its own temporary checkpoint until the user chooses a version. Ending a studio session saves the recording, chosen clips, original seed, text conditioning and the last two continuity checkpoints to the signed-in user’s private HF bucket or, for browser-only sessions, to the Space’s private attached bucket. The Sessions view lists finalized recordings, plays/downloads the MP4, and restores a local working copy for continuing or redoing the last clip. Each finished continuation is a new saved session. The original stays available. Unsubmitted variants and microphone audio are excluded. Closing a tab before a save completes may lose the unsaved work.
38
 
39
- Anonymous sessions belong to a private browser key in local storage. Clearing site data or using a different browser loses that key. When signed in through the in-app HF button, new sessions belong to the HF account and can be reopened on another device. For new signed-in recordings, the app uses the visitor’s OAuth token and the contribute-repos scope to create a private bucket named fastframes-voice-studio under their account. This is separate from the Space operator’s bucket. It stores videos, thumbnails, directions and continuity files. The Space keeps a small per-account index of dates, archive IDs and file checksums so it can verify restored content. Files removed or edited outside the app may no longer be restorable. Recordings saved before version 0.6.0 are still read from their original location. If authorization, storage quota or upload fails, the recording remains available in the take for export or retry. Earlier prototype exports without stored checkpoints cannot be restored.
40
 
41
  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. 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.
42
 
43
  ## Running the Space
44
 
45
- 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. Large continuity snapshots consume storage proportional to the occupied attention cache. The session index is published only after all checkpoint and media files have been copied. A failed archive leaves the MP4 available and exposes a save retry. For the saved_sessions API send action list, watch or resume, plus a 64-character random hexadecimal device key or a signed-in profile. Watch and resume require an archive ID; resume also needs a fresh take 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.
46
 
47
  ## Credits and licenses
48
 
 
28
 
29
  # FastFrames Voice
30
 
31
+ A private research prototype for directing a continuous generated shot with spoken or written cues. Version 0.7.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.
32
 
33
  Select Voice and start the microphone, or select Text, write a direction and press Generate segment (Enter to send, Shift+Enter for a new line). Text mode releases the microphone. Switching inputs preserves the shot. Each accepted direction generates one silent segment at 832 × 480 and 16 fps. Choose 1–8 whole seconds (default 4) before submitting each direction. Each second contains 16 frames. The opening generates one extra latent and trims one leading decoded frame after the model’s three startup frames to deliver an exact whole-second clip. The last segment loops locally while you think or the next cue is being prepared. Toggle Loop on the monitor to freeze it. Reduced-motion preferences disable looping by default. Repeats never enter the exported recording. End session joins completed segments into a downloadable MP4. Microphone mute discards unsubmitted audio and stops capture. Unmute continues the same take. The monitor plays the generated frames on an inline canvas, including on iPhone. The studio publishes JPEG strips of eight frames as the generator produces them. Inline playback starts at the first available strip, before the checkpoint and final MP4 are ready. The next generation waits for the previous revision to commit. API clients can request the same preview events with stream_preview set to true on live_take. The complete take uses a native MP4 player with inline playback and download.
34
 
35
  After a clip is complete, voice and text directions can continue the shot or redo its last segment. Check **Redo last segment** to force a variant for one instruction. A redo uses the duration and the starting state of the original (the same initial seed for the opening). The next-segment duration selector is preserved. With an ambiguous cue, answer “last segment” or “next segment” by voice, text or button; the studio keeps the original direction while waiting. Review both versions, then choose **Keep original** or **Use variant**. Ending during review exports the original. Only chosen clips enter the recording and future continuity.
36
 
37
+ Fluid Speech Pro transcribes voice on CPU. Typed directions bypass speech recognition. Inkling 2 Mini updates the last completed shot via Hugging Face Inference Providers when a provider credential is available. Only the text of the current direction, previous direction, target and visual prompt are sent to the HF router. Use the Hugging Face sign-in button below the studio title before starting a take to use your inference credits, or set a server-side HF_INFERENCE_TOKEN secret scoped to Inference Providers. Qwen runs locally when no credential is present or the provider call fails. The interpreted direction identifies the model used. 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 latest clip and its immediate predecessor retain their checkpoints. A pending variant has its own temporary checkpoint until the user chooses a version. Ending a session releases the temporary continuity caches. The gallery saves one final MP4 per recording. The in-studio controls can still continue a shot or redo its last segment until the session ends.
38
 
39
+ For signed-in visitors, the app uses the OAuth contribute-repos scope to write the final MP4 to their private fastframes-voice-studio bucket. Browser-only recordings use the Space’s attached private bucket and a device key from local storage. The Space keeps a small private index with the recording ID, save date, duration, segment count and, for personal uploads, file integrity information. Gallery posters are decoded from the opening frame on demand. New recordings use the save date as their label. Previously saved sessions can still be watched and downloaded from their original location. A failed upload can be retried using the completed local MP4.
40
 
41
  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. 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.
42
 
43
  ## Running the Space
44
 
45
+ 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.
46
 
47
  ## Credits and licenses
48
 
app.py CHANGED
@@ -147,7 +147,7 @@ def decide_variant(raw: str, request: gr.Request):
147
 
148
  def stop(raw: str, request: gr.Request):
149
  p,key = payload(raw,request)
150
- count = takes.close(key,preserve=True)
151
  return msg(p["take"], "stopping" if count else "closed", rendered=count)
152
 
153
 
@@ -175,7 +175,6 @@ def export_take(raw: str, request: gr.Request, profile: gr.OAuthProfile | None,
175
  LOG.exception("gallery save failed for %s",key[:8])
176
  yield str(movie),msg(p["take"],"archive_error")
177
  return
178
- takes.retire(key,row)
179
  yield str(movie),msg(p["take"],"finished",archive=archive)
180
 
181
 
@@ -192,21 +191,10 @@ def saved_sessions(raw: str, request: gr.Request, profile: gr.OAuthProfile | Non
192
  entries,total=gallery.entries(who,p.get("offset",0),personal)
193
  yield gr.skip(),status("collection",items=entries,total=total,account=bool(profile))
194
  return
195
- with gallery.opened(who,p.get("archive"),personal,p.get("action")=="watch") as folder:
196
- if p.get("action")=="watch":
197
  yield gallery.viewing_copy(folder,request.session_hash),status("viewing",archive=folder.name)
198
- return
199
- if p.get("action")=="resume":
200
- tag=p["take"]
201
- key=takes.identify(request.session_hash,tag)
202
- yield gr.skip(),status("reopening")
203
- data=gallery.restore(folder,key,request.session_hash)
204
- rev=data["rendered"]
205
- yield gr.skip(),status("reopened",session=tag,rev=rev,version=data["rev"],
206
- seconds=data["last_seconds"],title=data["title"],prompt=data["prompt"],focus=data["focus"],
207
- heard=data["last"],still=gallery.jpeg(takes.completed(key,rev)/"hold.jpg"),
208
- preview=str(takes.PREVIEWS/key/str(rev)))
209
- return
210
  raise ValueError("Invalid gallery action")
211
  except Exception:
212
  LOG.exception("gallery action failed: %s",p.get("action"))
@@ -293,7 +281,7 @@ with gr.Blocks(title="FastFrames Voice",fill_width=True,delete_cache=(600,1800))
293
  gr.HTML(asset("header.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-header")
294
  with gr.Row(elem_id="provider-account"):
295
  gr.LoginButton(elem_id="provider-login", size="sm", variant="secondary")
296
- gr.HTML('<span data-tr="providerHelp">Use Inkling and save sessions to your private HF bucket. Video checkpoints can use several GB.</span>',
297
  elem_id="provider-help", container=False, padding=False, apply_default_css=False)
298
  with gr.Column(elem_id="work-area"):
299
  with gr.Column(elem_id="monitor"):
@@ -306,7 +294,7 @@ with gr.Blocks(title="FastFrames Voice",fill_width=True,delete_cache=(600,1800))
306
  container=False,elem_id="voice-desk")
307
  with gr.Column(elem_id="collection"):
308
  gr.HTML(asset("gallery.html"),container=False,padding=False,apply_default_css=False,elem_id="gallery-panel")
309
- gallery_video=gr.Video(label="Saved session",interactive=False,buttons=["download"],elem_id="gallery-video")
310
  gr.HTML(asset("credits.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-credits")
311
  def bus(name):
312
  return gr.HTML(value="",html_template="<span></span>",js_on_load=BUS_JS,elem_id=name,container=False)
 
147
 
148
  def stop(raw: str, request: gr.Request):
149
  p,key = payload(raw,request)
150
+ count = takes.close(key)
151
  return msg(p["take"], "stopping" if count else "closed", rendered=count)
152
 
153
 
 
175
  LOG.exception("gallery save failed for %s",key[:8])
176
  yield str(movie),msg(p["take"],"archive_error")
177
  return
 
178
  yield str(movie),msg(p["take"],"finished",archive=archive)
179
 
180
 
 
191
  entries,total=gallery.entries(who,p.get("offset",0),personal)
192
  yield gr.skip(),status("collection",items=entries,total=total,account=bool(profile))
193
  return
194
+ if p.get("action") == "watch":
195
+ with gallery.opened(who, p.get("archive"), personal) as folder:
196
  yield gallery.viewing_copy(folder,request.session_hash),status("viewing",archive=folder.name)
197
+ return
 
 
 
 
 
 
 
 
 
 
 
198
  raise ValueError("Invalid gallery action")
199
  except Exception:
200
  LOG.exception("gallery action failed: %s",p.get("action"))
 
281
  gr.HTML(asset("header.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-header")
282
  with gr.Row(elem_id="provider-account"):
283
  gr.LoginButton(elem_id="provider-login", size="sm", variant="secondary")
284
+ gr.HTML('<span data-tr="providerHelp">Use Inkling and save finished videos to your private HF bucket.</span>',
285
  elem_id="provider-help", container=False, padding=False, apply_default_css=False)
286
  with gr.Column(elem_id="work-area"):
287
  with gr.Column(elem_id="monitor"):
 
294
  container=False,elem_id="voice-desk")
295
  with gr.Column(elem_id="collection"):
296
  gr.HTML(asset("gallery.html"),container=False,padding=False,apply_default_css=False,elem_id="gallery-panel")
297
+ gallery_video=gr.Video(label="Saved video",interactive=False,buttons=["download"],elem_id="gallery-video")
298
  gr.HTML(asset("credits.html"),apply_default_css=False,padding=False,container=False,elem_id="studio-credits")
299
  def bus(name):
300
  return gr.HTML(value="",html_template="<span></span>",js_on_load=BUS_JS,elem_id=name,container=False)
assets/collection.js CHANGED
@@ -11,7 +11,6 @@ function sessionCollection(){
11
  by("studio").dataset.view=view;
12
  by("nav-studio").setAttribute("aria-pressed",String(view==="studio"));
13
  by("nav-gallery").setAttribute("aria-pressed",String(view==="gallery"));
14
- by("nav-studio").disabled=pending?.action==="resume";
15
  by("nav-gallery").disabled=Boolean(stopped||busy||opening);
16
  const statusEl=by("collection-status");
17
  if(!statusEl)return;
@@ -23,7 +22,7 @@ function sessionCollection(){
23
  by("gallery-retry").hidden=state!=="collection_error";
24
  by("collection").dataset.watch=String(Boolean(selected));
25
  for(const button of by("saved-grid").querySelectorAll("button")){
26
- button.disabled=Boolean(pending)||(button.dataset.action==="resume"&&Boolean(take));
27
  }
28
  }
29
  function drawItems(){
@@ -32,23 +31,22 @@ function sessionCollection(){
32
  const fmt=new Intl.DateTimeFormat(lang==="fr"?"fr-FR":"en-GB",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});
33
  for(const item of items){
34
  const card=document.createElement("article");
35
- const image=document.createElement("img");image.src=item.thumb;image.alt="";image.loading="lazy";
36
- const title=document.createElement("h3");title.textContent=item.title;
37
- const meta=document.createElement("p");meta.textContent=fmt.format(new Date(item.date))+" · "+item.seconds+" s · "+item.count+(item.count===1?" segment":" segments");
38
- const actions=document.createElement("div");
39
- for(const [action,word] of [["watch","watchSession"],["resume","resumeSession"]]){
40
- const button=document.createElement("button");button.type="button";
41
- button.dataset.action=action;button.dataset.archive=item.id;button.textContent=tr(word);
42
- button.setAttribute("aria-label",tr(word)+" · "+item.title);actions.append(button);
43
- }
44
- card.append(image,title,meta,actions);grid.append(card);
45
  }
46
  controls();
47
  }
48
  function call(action,extra={}){
49
  if(pending)return;
50
  record={action,...extra};pending={action,id:crypto.randomUUID()};
51
- state=action==="resume"?"reopening":action==="watch"?"openingVideo":"loadingGallery";
52
  if(action==="watch")selected="";
53
  controls();
54
  emit("collection",{action,device,request:pending.id,...extra});
@@ -57,7 +55,6 @@ function sessionCollection(){
57
  requestAnimationFrame(()=>window.scrollTo({top:0,behavior:"instant"}));
58
  }
59
  function tab(next){
60
- if(pending?.action==="resume")return;
61
  view=next;
62
  if(next==="gallery"){
63
  if(stream||opening){queue=queue.filter(c=>c.audio===undefined);release();}
@@ -75,28 +72,21 @@ function sessionCollection(){
75
  if(button.id==="nav-gallery")tab("gallery");
76
  if(button.id==="gallery-more")call("list",{offset:items.length});
77
  if(button.id==="gallery-retry"&&record){const {action,...extra}=record;call(action,extra);}
78
- if(button.dataset.archive){
79
- const action=button.dataset.action;
80
- if(action==="resume"&&take)return;
81
- call(action,{archive:button.dataset.archive,...(action==="resume"?{take:crypto.randomUUID()}:{})});
82
- }
83
  });
84
  function signal(d){
85
- if(!["collection","viewing","reopening","reopened","collection_error"].includes(d.phase))return false;
86
  if(!pending||d.request!==pending.id)return true;
87
- if(d.phase==="reopening"){state="reopening";controls();return true;}
88
  pending=null;state="";
89
  if(d.phase==="collection"){
90
  items=record.offset?[...items,...d.items]:d.items;total=d.total;account=d.account;
91
- state=items.length?(take?"activeSession":""):"noSessions";drawItems();
92
  }else if(d.phase==="viewing"){
93
  selected=d.archive;
94
  const player=by("gallery-video");
95
  const inline=()=>{const v=player?.querySelector("video");if(v){v.playsInline=true;v.setAttribute("webkit-playsinline","");}};
96
  inline();player?.addEventListener("loadedmetadata",inline,{once:true,capture:true});
97
  controls();player?.scrollIntoView({block:"nearest"});
98
- }else if(d.phase==="reopened"){
99
- selected="";view="studio";controls();resumeSession(d);topOfView();
100
  }else{state="collection_error";controls();}
101
  return true;
102
  }
 
11
  by("studio").dataset.view=view;
12
  by("nav-studio").setAttribute("aria-pressed",String(view==="studio"));
13
  by("nav-gallery").setAttribute("aria-pressed",String(view==="gallery"));
 
14
  by("nav-gallery").disabled=Boolean(stopped||busy||opening);
15
  const statusEl=by("collection-status");
16
  if(!statusEl)return;
 
22
  by("gallery-retry").hidden=state!=="collection_error";
23
  by("collection").dataset.watch=String(Boolean(selected));
24
  for(const button of by("saved-grid").querySelectorAll("button")){
25
+ button.disabled=Boolean(pending);
26
  }
27
  }
28
  function drawItems(){
 
31
  const fmt=new Intl.DateTimeFormat(lang==="fr"?"fr-FR":"en-GB",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});
32
  for(const item of items){
33
  const card=document.createElement("article");
34
+ if(item.thumb){const image=document.createElement("img");image.src=item.thumb;image.alt="";image.loading="lazy";card.append(image);}
35
+ const date=fmt.format(new Date(item.date));
36
+ const title=document.createElement("h3");title.textContent=item.title||date;
37
+ const meta=document.createElement("p");
38
+ meta.textContent=(item.title?date+" · ":"")+item.seconds+" s · "+item.count+(item.count===1?" segment":" segments");
39
+ const button=document.createElement("button");button.type="button";
40
+ button.dataset.archive=item.id;button.textContent=tr("watchSession");
41
+ button.setAttribute("aria-label",tr("watchSession")+" · "+title.textContent);
42
+ card.append(title,meta,button);grid.append(card);
 
43
  }
44
  controls();
45
  }
46
  function call(action,extra={}){
47
  if(pending)return;
48
  record={action,...extra};pending={action,id:crypto.randomUUID()};
49
+ state=action==="watch"?"openingVideo":"loadingGallery";
50
  if(action==="watch")selected="";
51
  controls();
52
  emit("collection",{action,device,request:pending.id,...extra});
 
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();}
 
72
  if(button.id==="nav-gallery")tab("gallery");
73
  if(button.id==="gallery-more")call("list",{offset:items.length});
74
  if(button.id==="gallery-retry"&&record){const {action,...extra}=record;call(action,extra);}
75
+ if(button.dataset.archive)call("watch",{archive:button.dataset.archive});
 
 
 
 
76
  });
77
  function signal(d){
78
+ if(!["collection","viewing","collection_error"].includes(d.phase))return false;
79
  if(!pending||d.request!==pending.id)return true;
 
80
  pending=null;state="";
81
  if(d.phase==="collection"){
82
  items=record.offset?[...items,...d.items]:d.items;total=d.total;account=d.account;
83
+ state=items.length?"":"noSessions";drawItems();
84
  }else if(d.phase==="viewing"){
85
  selected=d.archive;
86
  const player=by("gallery-video");
87
  const inline=()=>{const v=player?.querySelector("video");if(v){v.playsInline=true;v.setAttribute("webkit-playsinline","");}};
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;
92
  }
assets/gallery.html CHANGED
@@ -1,5 +1,5 @@
1
  <section class="sessions">
2
- <div class="collection-heading"><h2 data-tr="sessions">Saved sessions</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>
 
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>
assets/header.html CHANGED
@@ -4,7 +4,7 @@
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">Sessions</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>
 
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>
assets/studio.css CHANGED
@@ -131,9 +131,9 @@ html:has(#huggingface-space-header){scroll-padding-top:60px}
131
  #saved-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,230px),1fr));gap:20px;padding:16px 0 4px}
132
  #saved-grid article{min-width:0}#saved-grid img{width:100%;aspect-ratio:832/480;object-fit:contain;background:#0c100e;border-radius:5px}
133
  #studio #saved-grid h3{margin:8px 0 2px;font:600 17px/1.18 Barlow,Arial,sans-serif;overflow-wrap:anywhere}
134
- #saved-grid p{margin:3px 0 8px}#saved-grid article>div{display:flex;gap:7px}
135
  #collection button{min-height:44px;color:#eeeae2;background:#283029;border:1px solid #59645b;border-radius:5px;padding:0 12px}
136
- #collection button:disabled{opacity:.5;cursor:default}#collection button[data-action=resume]{border-color:#ae834d}#gallery-more{margin-top:12px}
137
  @media(max-width:720px){
138
  #studio .mast-actions{gap:4px}.mast .langs{padding-right:4px}
139
  #studio .mast nav button{padding:0 4px}
 
131
  #saved-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,230px),1fr));gap:20px;padding:16px 0 4px}
132
  #saved-grid article{min-width:0}#saved-grid img{width:100%;aspect-ratio:832/480;object-fit:contain;background:#0c100e;border-radius:5px}
133
  #studio #saved-grid h3{margin:8px 0 2px;font:600 17px/1.18 Barlow,Arial,sans-serif;overflow-wrap:anywhere}
134
+ #saved-grid p{margin:3px 0 8px}
135
  #collection button{min-height:44px;color:#eeeae2;background:#283029;border:1px solid #59645b;border-radius:5px;padding:0 12px}
136
+ #collection button:disabled{opacity:.5;cursor:default}#gallery-more{margin-top:12px}
137
  @media(max-width:720px){
138
  #studio .mast-actions{gap:4px}.mast .langs{padding-right:4px}
139
  #studio .mast nav button{padding:0 4px}
assets/studio.js CHANGED
@@ -12,15 +12,14 @@ const playback = inlinePlayback(monitor, by("cue-screen"),
12
  const meter = by("mic-level").getContext("2d");
13
  const langButtons = [by("lang-en"), by("lang-fr")];
14
  const copy = {
15
- studioTab:["Studio","Studio"],galleryTab:["Sessions","Sessions"],sessions:["Saved sessions","Sessions enregistrées"],
16
- director:["Director","Régie"],inputGeneric:["Direction","Consigne"],lastDirection:["Last direction","Dernière consigne"],
17
  moreSessions:["Show more","Afficher la suite"],deviceGallery:["This browser","Ce navigateur"],accountGallery:["Your HF account","Ton compte HF"],
18
- watchSession:["Watch","Voir"],resumeSession:["Resume","Reprendre"],noSessions:["Finish a session to find it here.","Termine une session pour la retrouver ici."],
19
- openingVideo:["Loading recording…","Chargement de la vidéo…"],loadingGallery:["Loading sessions…","Chargement des sessions…"],
20
- activeSession:["Finish the current session to resume a saved one.","Termine la session en cours pour en reprendre une autre."],
21
- collection_error:["Couldn’t open the saved sessions · retry","Accès aux sessions indisponible · réessaie"],
22
- reopening:["Restoring saved session…","Restauration de la session…"],archiving:["Saving recording and continuity…","Enregistrement de la vidéo et du point de reprise…"],
23
- archive_error:["Recording available · retry saving to Sessions","Vidéo disponible · réessaie l’enregistrement dans Sessions"],
24
  redoLabel:["Redo last segment","Refaire le dernier segment"],
25
  redoSend:["Generate variant","Générer la variante"],redoGenerating:["Generating variant…","Génération de la variante…"],
26
  clarify:["Last segment or the next one?","Sur le dernier segment ou pour la suite ?"],
@@ -35,7 +34,7 @@ const copy = {
35
  preview:["Preview frame","Aperçu"],help:["Speak or type a direction to begin.","Utilise la voix ou le clavier pour commencer."],
36
  voiceMode:["Voice","Voix"],textMode:["Text","Texte"],duration:["Next segment","Prochaine portion"],
37
  textLabel:["Written direction","Consigne écrite"],textIdle:["Ready for a written direction","En attente d’une consigne écrite"],
38
- providerHelp:["Use Inkling and save sessions to your private HF bucket. Video checkpoints can use several GB.","Utilise Inkling et enregistre tes sessions dans ton bucket HF privé. Les points de reprise peuvent peser plusieurs Go."],
39
  send:["Generate segment","Générer la portion"],starting:["Opening session…","Ouverture de la session…"],
40
  invalid_seconds:["Choose a duration from 1 to 8 s","Choisis une durée de 1 à 8 s"],
41
  invalid_text:["Enter a direction of up to 1,200 characters","Écris une consigne de 1 200 caractères maximum"],
@@ -115,7 +114,7 @@ function label(){
115
  by("watch-original").setAttribute("aria-pressed",String(Boolean(variantClip&&lastSegment===approvedClip)));
116
  send.textContent=tr(forceRedo.checked?"redoSend":"send");
117
  send.disabled=busy||stopped||Boolean(variantClip)||submittedDraft!==null||!draft.value.trim();
118
- by("input-label").textContent=tr(lastSource==="saved"?"inputGeneric":(lastSource||inputMode)==="text"?"textLabel":"heard");
119
  by("interpreter").textContent=interpreter;
120
  const muted = Boolean(inputMode==="voice" && take && !stream && !opening && !stopped);
121
  mic.dataset.micState = muted ? "muted" : stream ? "listening" : "idle";
@@ -253,14 +252,6 @@ async function openMic(){
253
  }catch(err){if(epoch===micEpoch){release();setStatus("mic_error");}}
254
  finally{if(epoch===micEpoch){opening=false;label();}}
255
  }
256
- function resumeSession(d){
257
- playback.clear();resetEditing();
258
- take=d.session;ready=true;stopped=busy=false;saved=false;seq=0;retryKind="";queue=[];submittedDraft=null;
259
- visionRev=d.version;applied=d.rev;lastHeard=d.heard;focus=d.focus;prompt=d.prompt;interpreter="";
260
- lastSource="saved";pendingStill=d.still;hold.src=d.still;
261
- approvedClip=lastSegment={rev:d.rev,seconds:d.seconds,frames:d.seconds*16,still:d.still,preview:d.preview,lastHeard,focus,prompt,interpreter,lastSource};
262
- setMode("hold");playback.repeatClip(approvedClip);syncLoop();setStatus("holding");
263
- }
264
  function endSession(){
265
  if(opening&&!take){release();setStatus("idle");return;}
266
  if(!take||stopped)return;stopped=true;retryKind="";queue=[];playback.clear();release();setStatus("stopping");emit("halt",{take});
 
12
  const meter = by("mic-level").getContext("2d");
13
  const langButtons = [by("lang-en"), by("lang-fr")];
14
  const copy = {
15
+ studioTab:["Studio","Studio"],galleryTab:["Videos","Vidéos"],sessions:["Saved videos","Vidéos enregistrées"],
16
+ director:["Director","Régie"],lastDirection:["Last direction","Dernière consigne"],
17
  moreSessions:["Show more","Afficher la suite"],deviceGallery:["This browser","Ce navigateur"],accountGallery:["Your HF account","Ton compte HF"],
18
+ watchSession:["Watch","Voir"],noSessions:["Finish a session to see its video here.","Termine une session pour retrouver ta vidéo ici."],
19
+ openingVideo:["Loading recording…","Chargement de la vidéo…"],loadingGallery:["Loading videos…","Chargement des vidéos…"],
20
+ collection_error:["Couldn’t open saved videos · retry","Vidéos indisponibles · réessaie"],
21
+ archiving:["Saving video…","Enregistrement de la vidéo…"],
22
+ archive_error:["Recording available · retry saving to Videos","Vidéo disponible · réessaie l’enregistrement dans Vidéos"],
 
23
  redoLabel:["Redo last segment","Refaire le dernier segment"],
24
  redoSend:["Generate variant","Générer la variante"],redoGenerating:["Generating variant…","Génération de la variante…"],
25
  clarify:["Last segment or the next one?","Sur le dernier segment ou pour la suite ?"],
 
34
  preview:["Preview frame","Aperçu"],help:["Speak or type a direction to begin.","Utilise la voix ou le clavier pour commencer."],
35
  voiceMode:["Voice","Voix"],textMode:["Text","Texte"],duration:["Next segment","Prochaine portion"],
36
  textLabel:["Written direction","Consigne écrite"],textIdle:["Ready for a written direction","En attente d’une consigne écrite"],
37
+ providerHelp:["Use Inkling and save finished videos to your private HF bucket.","Utilise Inkling et enregistre tes vidéos finales dans ton bucket HF privé."],
38
  send:["Generate segment","Générer la portion"],starting:["Opening session…","Ouverture de la session…"],
39
  invalid_seconds:["Choose a duration from 1 to 8 s","Choisis une durée de 1 à 8 s"],
40
  invalid_text:["Enter a direction of up to 1,200 characters","Écris une consigne de 1 200 caractères maximum"],
 
114
  by("watch-original").setAttribute("aria-pressed",String(Boolean(variantClip&&lastSegment===approvedClip)));
115
  send.textContent=tr(forceRedo.checked?"redoSend":"send");
116
  send.disabled=busy||stopped||Boolean(variantClip)||submittedDraft!==null||!draft.value.trim();
117
+ by("input-label").textContent=tr((lastSource||inputMode)==="text"?"textLabel":"heard");
118
  by("interpreter").textContent=interpreter;
119
  const muted = Boolean(inputMode==="voice" && take && !stream && !opening && !stopped);
120
  mic.dataset.micState = muted ? "muted" : stream ? "listening" : "idle";
 
252
  }catch(err){if(epoch===micEpoch){release();setStatus("mic_error");}}
253
  finally{if(epoch===micEpoch){opening=false;label();}}
254
  }
 
 
 
 
 
 
 
 
255
  function endSession(){
256
  if(opening&&!take){release();setStatus("idle");return;}
257
  if(!take||stopped)return;stopped=true;retryKind="";queue=[];playback.clear();release();setStatus("stopping");emit("halt",{take});
gallery.py CHANGED
@@ -1,6 +1,5 @@
1
- """Private, immutable session snapshots on the Space's attached HF bucket."""
2
  from contextlib import contextmanager
3
- import io
4
  import base64
5
  import hashlib
6
  import json
@@ -9,15 +8,16 @@ import re
9
  import shutil
10
  import tempfile
11
  import threading
 
12
  from datetime import datetime, timezone
13
  from pathlib import Path
14
 
15
- from PIL import Image
16
-
17
  import takes
18
 
19
  MOUNT = Path(os.environ.get("GALLERY_ROOT","/data/fastframes-sessions"))
20
- FORMAT = "ff-s-aa099ef-16fps-v1"
 
 
21
  # Gradio may resume a synchronous generator on another worker thread.
22
  LOCKS = [threading.Lock() for _ in range(64)]
23
 
@@ -59,110 +59,111 @@ def find(identities, archive):
59
  raise FileNotFoundError("Saved session unavailable")
60
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def entries(identities, offset=0, personal=None):
63
- if type(offset) is not int or offset<0:
64
  raise ValueError("Invalid gallery page")
65
  records = []
66
  for owner in identities:
67
  for file in (root()/owner).glob("*/manifest.json"):
68
  try:
69
- m=json.loads(file.read_text())
70
- if m["format"]==FORMAT:
71
- records.append((m["saved_at"], file.parent, m))
72
- except (ValueError,KeyError,FileNotFoundError):
73
  continue
74
  if personal is not None:
75
  indexed = {}
76
- for f in (root()/identities[0]).glob("*/receipt.json"):
77
  try:
78
- receipt = json.loads(f.read_text())
79
- indexed[f.parent.name] = (receipt["saved_at"], f.parent, None)
80
- except (ValueError,KeyError,FileNotFoundError):
81
  continue
82
  records.extend(indexed[k] for k in personal.existing(indexed))
83
- records.sort(key=lambda record:record[0],reverse=True)
84
- page=records[offset:offset+12]
85
- items=[]
86
  with tempfile.TemporaryDirectory() as tmp:
87
- downloads=[]
88
- for _, folder, m in page:
89
- if m is None:
90
- signatures=json.loads((folder/"receipt.json").read_text())["files"]
91
- for name in ("thumb.jpg","manifest.json"):
92
- downloads.append((folder.name,name,Path(tmp)/folder.name/name,signatures[name]))
93
- if downloads:
94
- personal.download(downloads)
95
- for date,folder,m in page:
96
- if m is None:
97
- folder=Path(tmp)/folder.name
98
- m=json.loads((folder/"manifest.json").read_text())
99
- items.append(dict(id=folder.name,title=m["title"],date=date,seconds=sum(c["seconds"] for c in m["clips"]),
100
- count=len(m["clips"]),thumb=jpeg(folder/"thumb.jpg")))
101
- return items,len(records)
 
 
 
 
 
 
 
 
 
 
102
 
103
 
104
  def save(key, identities, movie, personal=None):
105
- ident=key[:32]
106
- folder=root()/identities[0]/ident
107
- marker=folder/("receipt.json" if personal else "manifest.json")
108
  if marker.is_file():
109
- try:
110
- if json.loads(marker.read_text()).get("format")==FORMAT:
111
- return ident
112
- except (ValueError,FileNotFoundError):
113
- pass
114
- row=takes.get(key)
115
- if row.get("phase")!="stopped":
116
  raise ValueError("Session still active")
117
- manifest={k:row[k] for k in ("seed","rev","rendered","parent","last_seconds","title","prompt","last","focus")}
118
- clips=takes.clip_list(key)
119
- manifest.update(format=FORMAT,clips=clips,saved_at=datetime.now(timezone.utc).isoformat(timespec="seconds"))
120
- files={"session.mp4":movie}
121
- for clip in clips:
122
- rev=clip["rev"]
123
- src=takes.completed(key,rev)
124
- prefix=f"clip-{rev}/"
125
- files[prefix+"clip.mp4"]=src/f"cue-{key[:12]}-{rev}.mp4"
126
- if rev in (row["rendered"],row["parent"]):
127
- files.update({prefix+"state/"+f.name:f for f in (src/"state").iterdir() if f.is_file()})
128
- if rev==row["rendered"]:
129
- files[prefix+"hold.jpg"]=src/"hold.jpg"
130
- files.update({prefix+"preview/"+f.name:f for f in (takes.PREVIEWS/key/str(rev)).iterdir() if f.is_file()})
131
- with Image.open(src/"hold.jpg") as image:
132
- image.thumbnail((300,174))
133
- out=io.BytesIO()
134
- image.save(out,format="JPEG",quality=82)
135
- files["thumb.jpg"]=out.getvalue()
136
- data=json.dumps(manifest,ensure_ascii=False).encode()
137
- folder.mkdir(parents=True,exist_ok=True)
138
  if personal:
139
- signatures=personal.publish(ident, files, data)
140
- marker.write_text(json.dumps(dict(format=FORMAT,saved_at=manifest["saved_at"],files=signatures)))
 
141
  else:
142
- for name,source in files.items():
143
- dest=folder/name
144
- dest.parent.mkdir(parents=True,exist_ok=True)
145
- if isinstance(source,bytes):
146
- dest.write_bytes(source)
147
- else:
148
- shutil.copyfile(source,dest)
149
- marker.write_bytes(data)
 
150
  return ident
151
 
152
 
153
  @contextmanager
154
- def opened(identities, archive, personal, watch):
155
  if not isinstance(archive,str) or not re.fullmatch("[0-9a-f]{32}",archive):
156
- raise ValueError("Invalid session ID")
157
- receipt=root()/identities[0]/archive/"receipt.json"
158
  if personal is None or not receipt.is_file():
159
- yield find(identities,archive)
160
  return
161
- signatures=json.loads(receipt.read_text())["files"]
162
  with tempfile.TemporaryDirectory(dir=takes.ROOT) as temp:
163
- folder=Path(temp)/archive
164
- names=["session.mp4"] if watch else [n for n in signatures if n not in ("session.mp4","thumb.jpg")]
165
- personal.download([(archive,n,folder/n,signatures[n]) for n in names])
166
  yield folder
167
 
168
 
@@ -177,26 +178,3 @@ def viewing_copy(folder, session_hash):
177
  tmpfile.replace(target)
178
  return str(target)
179
 
180
-
181
- def restore(folder, key, owner):
182
- manifest=json.loads((folder/"manifest.json").read_text())
183
- if manifest.get("format")!=FORMAT:
184
- raise ValueError("Incompatible session format")
185
- with tempfile.TemporaryDirectory(dir=takes.ROOT) as temp:
186
- stage=Path(temp)/"copy"
187
- stage.mkdir()
188
- for clip in manifest["clips"]:
189
- rev=clip["rev"]
190
- if type(rev) is not int or rev<=0:
191
- raise ValueError("Invalid clip revision")
192
- src=folder/f"clip-{rev}"
193
- dest=stage/f"step-{rev:08d}"
194
- dest.mkdir()
195
- shutil.copyfile(src/"clip.mp4",dest/f"cue-{key[:12]}-{rev}.mp4")
196
- if rev in (manifest["parent"],manifest["rendered"]):
197
- shutil.copytree(src/"state",dest/"state",copy_function=shutil.copyfile)
198
- if rev==manifest["rendered"]:
199
- shutil.copyfile(src/"hold.jpg",dest/"hold.jpg")
200
- shutil.copytree(src/"preview",stage/"previews"/str(rev),copy_function=shutil.copyfile)
201
- takes.restore_saved(key,owner,manifest,stage)
202
- return manifest
 
1
+ """Final recordings and their private gallery index."""
2
  from contextlib import contextmanager
 
3
  import base64
4
  import hashlib
5
  import json
 
8
  import shutil
9
  import tempfile
10
  import threading
11
+ import subprocess
12
  from datetime import datetime, timezone
13
  from pathlib import Path
14
 
 
 
15
  import takes
16
 
17
  MOUNT = Path(os.environ.get("GALLERY_ROOT","/data/fastframes-sessions"))
18
+ LEGACY_FORMAT = "ff-s-aa099ef-16fps-v1"
19
+ FORMAT = "final-mp4-v2"
20
+ POSTER_BYTES = 256 * 1024
21
  # Gradio may resume a synchronous generator on another worker thread.
22
  LOCKS = [threading.Lock() for _ in range(64)]
23
 
 
59
  raise FileNotFoundError("Saved session unavailable")
60
 
61
 
62
+ def first_frame(prefix):
63
+ # The exported MP4 has a fast-start header. Only read enough for its first frame.
64
+ process = subprocess.run([
65
+ "ffmpeg", "-nostdin", "-loglevel", "error", "-threads", "1", "-f", "mov", "-i", "pipe:0",
66
+ "-frames:v", "1", "-vf", "scale=300:-2", "-threads", "1", "-f", "image2pipe",
67
+ "-c:v", "mjpeg", "pipe:1",
68
+ ], input=prefix, capture_output=True, timeout=8)
69
+ if not process.stdout or process.returncode:
70
+ return ""
71
+ return "data:image/jpeg;base64," + base64.b64encode(process.stdout).decode("ascii")
72
+
73
+
74
  def entries(identities, offset=0, personal=None):
75
+ if type(offset) is not int or offset < 0:
76
  raise ValueError("Invalid gallery page")
77
  records = []
78
  for owner in identities:
79
  for file in (root()/owner).glob("*/manifest.json"):
80
  try:
81
+ data = json.loads(file.read_text())
82
+ if data["format"] in (LEGACY_FORMAT, FORMAT):
83
+ records.append((data["saved_at"], file.parent, data, False))
84
+ except (ValueError, KeyError, FileNotFoundError):
85
  continue
86
  if personal is not None:
87
  indexed = {}
88
+ for file in (root()/identities[0]).glob("*/receipt.json"):
89
  try:
90
+ data = json.loads(file.read_text())
91
+ indexed[file.parent.name] = (data["saved_at"], file.parent, data, True)
92
+ except (ValueError, KeyError, FileNotFoundError):
93
  continue
94
  records.extend(indexed[k] for k in personal.existing(indexed))
95
+ records.sort(key=lambda record: record[0], reverse=True)
96
+ items = []
 
97
  with tempfile.TemporaryDirectory() as tmp:
98
+ for date, folder, data, remote in records[offset:offset+12]:
99
+ ident = folder.name
100
+ if data["format"] == LEGACY_FORMAT:
101
+ if remote:
102
+ folder = Path(tmp)/ident
103
+ personal.download([(ident, n, folder/n, data["files"][n]) for n in ("manifest.json", "thumb.jpg")])
104
+ data = json.loads((folder/"manifest.json").read_text())
105
+ clips = data["clips"]
106
+ items.append(dict(id=ident, date=date, title=data["title"], thumb=jpeg(folder/"thumb.jpg"),
107
+ count=len(clips), seconds=sum(c["seconds"] for c in clips)))
108
+ continue
109
+ thumb = ""
110
+ try:
111
+ if remote:
112
+ prefix = personal.prefix(ident, POSTER_BYTES)
113
+ if hashlib.sha256(prefix).hexdigest() != data["prefix_sha256"]:
114
+ raise ValueError("Recording changed")
115
+ else:
116
+ with (folder/"session.mp4").open("rb") as movie:
117
+ prefix = movie.read(POSTER_BYTES)
118
+ thumb = first_frame(prefix)
119
+ except (ValueError, OSError, subprocess.SubprocessError):
120
+ pass # The recording can still be opened when a poster is unavailable.
121
+ items.append(dict(id=ident, date=date, title="", thumb=thumb, count=data["count"], seconds=data["seconds"]))
122
+ return items, len(records)
123
 
124
 
125
  def save(key, identities, movie, personal=None):
126
+ ident = key[:32]
127
+ folder = root()/identities[0]/ident
128
+ marker = folder/("receipt.json" if personal else "manifest.json")
129
  if marker.is_file():
130
+ if json.loads(marker.read_text()).get("format") in (LEGACY_FORMAT, FORMAT):
131
+ return ident
132
+ if takes.get(key).get("phase") != "stopped":
 
 
 
 
133
  raise ValueError("Session still active")
134
+ clips = takes.clip_list(key)
135
+ record = dict(format=FORMAT, saved_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
136
+ count=len(clips), seconds=sum(c["seconds"] for c in clips))
137
+ folder.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  if personal:
139
+ with movie.open("rb") as source:
140
+ record["prefix_sha256"] = hashlib.sha256(source.read(POSTER_BYTES)).hexdigest()
141
+ record["files"] = {"session.mp4": personal.publish(ident, movie)}
142
  else:
143
+ shutil.copyfile(movie, folder/"session.mp4")
144
+ # Publish the listing only after the final video is available.
145
+ with tempfile.NamedTemporaryFile(mode="w", dir=folder, delete=False) as tmp:
146
+ json.dump(record, tmp)
147
+ draft = Path(tmp.name)
148
+ try:
149
+ draft.replace(marker)
150
+ finally:
151
+ draft.unlink(missing_ok=True)
152
  return ident
153
 
154
 
155
  @contextmanager
156
+ def opened(identities, archive, personal):
157
  if not isinstance(archive,str) or not re.fullmatch("[0-9a-f]{32}",archive):
158
+ raise ValueError("Invalid recording ID")
159
+ receipt = root()/identities[0]/archive/"receipt.json"
160
  if personal is None or not receipt.is_file():
161
+ yield find(identities, archive)
162
  return
163
+ signature = json.loads(receipt.read_text())["files"]["session.mp4"]
164
  with tempfile.TemporaryDirectory(dir=takes.ROOT) as temp:
165
+ folder = Path(temp)/archive
166
+ personal.download([(archive, "session.mp4", folder/"session.mp4", signature)])
 
167
  yield folder
168
 
169
 
 
178
  tmpfile.replace(target)
179
  return str(target)
180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
personal_bucket.py CHANGED
@@ -28,19 +28,22 @@ class PersonalBucket:
28
  def __init__(self, name, api):
29
  self.name, self.api = name, api
30
 
31
- def publish(self, archive, files, manifest):
32
  self.api.create_bucket(self.name, private=True, exist_ok=True)
33
  if not self.api.bucket_info(self.name).private:
34
  raise PermissionError("A private bucket is required")
35
- prefix = f"sessions/{archive}/"
36
- receipt = {name: fingerprint(source) for name, source in files.items()}
37
- self.api.batch_bucket_files(self.name, add=[(source, prefix + name) for name, source in files.items()])
38
- self.api.batch_bucket_files(self.name, add=[(manifest, prefix + "manifest.json")])
39
- receipt["manifest.json"] = fingerprint(manifest)
40
- return receipt
 
 
 
41
 
42
  def existing(self, archives):
43
- names = [f"sessions/{archive}/manifest.json" for archive in archives]
44
  found = set()
45
  if not names:
46
  return found
 
28
  def __init__(self, name, api):
29
  self.name, self.api = name, api
30
 
31
+ def publish(self, archive, movie):
32
  self.api.create_bucket(self.name, private=True, exist_ok=True)
33
  if not self.api.bucket_info(self.name).private:
34
  raise PermissionError("A private bucket is required")
35
+ signature = fingerprint(movie)
36
+ self.api.batch_bucket_files(self.name, add=[(movie, f"sessions/{archive}/session.mp4")])
37
+ return signature
38
+
39
+ def prefix(self, archive, limit):
40
+ from huggingface_hub import HfFileSystem
41
+ fs = HfFileSystem(token=self.api.token, skip_instance_cache=True)
42
+ path = f"buckets/{self.name}/sessions/{archive}/session.mp4"
43
+ return fs.cat_file(path, start=0, end=limit)
44
 
45
  def existing(self, archives):
46
+ names = [f"sessions/{archive}/session.mp4" for archive in archives]
47
  found = set()
48
  if not names:
49
  return found
takes.py CHANGED
@@ -197,7 +197,7 @@ def fail(key, rev):
197
  return update("UPDATE takes SET phase='retry' WHERE id=? AND phase='live' AND rev=?", (key,rev))
198
 
199
 
200
- def close(key, preserve=False):
201
  with connection() as db:
202
  db.execute("BEGIN IMMEDIATE")
203
  row = db.execute("SELECT * FROM takes WHERE id=?", (key,)).fetchone()
@@ -206,8 +206,7 @@ def close(key, preserve=False):
206
  return 0
207
  if row["phase"] == "review":
208
  discard_revision(key,row["rev"])
209
- if not preserve:
210
- retire(key, row)
211
  return row["rendered"]
212
 
213
 
@@ -220,31 +219,3 @@ def retire(key, row):
220
  def clip_list(key):
221
  with connection() as db:
222
  return [dict(r) for r in db.execute("SELECT rev,seconds FROM clips WHERE take_id=? ORDER BY rev", (key,))]
223
-
224
-
225
- def restore_saved(key, owner, data, stage):
226
- """Install a fully copied snapshot. A failed restore leaves the current take intact."""
227
- with connection() as db:
228
- db.execute("BEGIN IMMEDIATE")
229
- if db.execute("SELECT 1 FROM takes WHERE owner=? AND phase!='stopped'", (owner,)).fetchone():
230
- raise ValueError("Finish the active take first")
231
- if (ROOT/key).exists():
232
- raise ValueError("Duplicate take")
233
- old = remove_owner(db,owner)
234
- out = ROOT/key
235
- try:
236
- stage.rename(out)
237
- (out/"previews").rename(PREVIEWS/key)
238
- db.execute("""INSERT INTO takes(id,owner,phase,seed,rev,rendered,parent,last_seconds,title,prompt,last,focus)
239
- VALUES(?,?,'armed',?,?,?,?,?,?,?,?,?)""",
240
- (key,owner,data["seed"],data["rev"],data["rendered"],data["parent"],
241
- data["last_seconds"],data["title"],data["prompt"],data["last"],data["focus"]))
242
- db.executemany("INSERT INTO clips(take_id,rev,seconds) VALUES(?,?,?)",
243
- [(key,c["rev"],c["seconds"]) for c in data["clips"]])
244
- db.commit()
245
- except Exception:
246
- shutil.rmtree(out, ignore_errors=True)
247
- shutil.rmtree(PREVIEWS/key, ignore_errors=True)
248
- raise
249
- for path in old:
250
- shutil.rmtree(path,ignore_errors=True)
 
197
  return update("UPDATE takes SET phase='retry' WHERE id=? AND phase='live' AND rev=?", (key,rev))
198
 
199
 
200
+ def close(key):
201
  with connection() as db:
202
  db.execute("BEGIN IMMEDIATE")
203
  row = db.execute("SELECT * FROM takes WHERE id=?", (key,)).fetchone()
 
206
  return 0
207
  if row["phase"] == "review":
208
  discard_revision(key,row["rev"])
209
+ retire(key, row)
 
210
  return row["rendered"]
211
 
212
 
 
219
  def clip_list(key):
220
  with connection() as db:
221
  return [dict(r) for r in db.execute("SELECT rev,seconds FROM clips WHERE take_id=? ORDER BY rev", (key,))]