"""Advance a single rollout by the duration of each direction.""" from concurrent.futures import ThreadPoolExecutor import base64 import logging import subprocess import time import tempfile from pathlib import Path import spaces import torch from PIL import Image from continuity import WindowWriter import takes LOG = logging.getLogger("studio") LOG.setLevel(logging.INFO) if not logging.getLogger().handlers: logging.basicConfig(level=logging.WARNING) GPU_AVAILABLE = torch.cuda.is_available() if GPU_AVAILABLE: import engine as en class CueCancelled(Exception): pass def temporary_bytes(model, seconds, previous): pipe = en.PIPELINES[model] steps = seconds * 4 + int(not previous) frames = min(pipe.config.num_frames, steps) if previous and not next((previous / "state").glob("*.kv"), None): frames = pipe.config.num_frames kv = frames * pipe.frame_tokens * pipe.dit.dim * len(pipe.dit.blocks) * 2 * 2 pixels = seconds * 16 * 832 * 480 * 3 return kv + 2 * pixels + 512 * 1024**2 def gpu_duration(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=False, model="S"): return 120 if model == "L" else 60 @spaces.GPU(duration=gpu_duration, size="xlarge") def generate(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=False, model="S"): """A fresh GPU allocation for each cue. The CPU owns the committed checkpoint.""" started = time.monotonic() stage = Path(stage_name) def check_active(): if not takes.active(key, rev): raise CueCancelled() try: check_active() LOG.info("cue enter %s rev=%d previous=%d model=%s", key[:8], rev, previous, model) yield "allocated" with torch.inference_mode(): pipe = en.PIPELINES[model] en.configure_backends(pipe.config) rollout = en.LiveRollout(pipe, seed) if previous: yield "restoring" rollout.restore(takes.completed(key, previous) / "state", check_active) first = rollout.total text = pipe.dit.text_cache(pipe.encode_prompt(prompt)) yield "generating" steps = 4 * takes.segment_seconds(seconds) + int(not previous) with ThreadPoolExecutor(max_workers=1, thread_name_prefix="continuity") as pool, (stage / "pixels.rgb").open("wb") as out: writer = WindowWriter(stage / "state", rollout, steps, en.ROLL_STRIDE, en.SINK, pool, check_active) if previous: writer.inherit(takes.completed(key, previous) / "state", en.ROLL_STRIDE, en.SINK) # Four decoder frames per latent. The opening decoder trims three # startup frames. Advance one extra latent and trim the fourth. opening = not previous sent = 0 for step in range(steps): check_active() rollout.step(text) if rollout.total - rollout.decoded == en.CHUNK or step + 1 == steps: frames = rollout.decode_pending().cpu().numpy() if opening: frames = frames[1:] opening = False out.write(frames.tobytes()) strips = out.tell() // (8 * 832 * 480 * 3) if preview and strips > sent: out.flush() sent = strips yield strips writer.capture(rollout.total - 1, rollout.used - 1) if out.tell() != seconds * 16 * 832 * 480 * 3: raise ValueError("Unexpected segment frame count") Image.fromarray(frames[-1]).save(stage / "hold.jpg", quality=92) yield "saving" tail_start = time.monotonic() rollout.save_history(stage / "state", writer.finish()) LOG.info("continuity tail %s rev=%d elapsed=%.3f", key[:8], rev, time.monotonic()-tail_start) LOG.info("cue checkpoint %s rev=%d latent=%d..%d rolls=%d",key[:8],rev,first,rollout.total,rollout.rolls) finally: LOG.info("cue worker exit %s rev=%d elapsed=%.2f",key[:8],rev,time.monotonic()-started) def write_strips(stage, first, end): preview = stage / "preview" preview.mkdir(exist_ok=True) size = 8 * 832 * 480 * 3 with (stage / "pixels.rgb").open("rb") as raw: raw.seek(first * size) for index in range(first,end): data = raw.read(size) if not data or len(data) % (832 * 480 * 3): raise ValueError("Incomplete preview strip") Image.frombytes("RGB",(832,len(data)//(832*3)),data).save(preview/f"{index}.jpg",quality=90) def encode(stage, filename): subprocess.run(["ffmpeg","-nostdin","-v","error","-y","-f","rawvideo","-pixel_format","rgb24", "-video_size","832x480","-framerate","16","-i",str(stage / "pixels.rgb"),"-an", "-c:v","libx264","-pix_fmt","yuv420p","-threads","2","-preset","ultrafast","-tune","zerolatency", "-movflags","+faststart",str(stage / filename)],check=True,timeout=30) total = (stage / "pixels.rgb").stat().st_size // (832 * 480 * 3) if not (stage / "preview").exists(): write_strips(stage, 0, (total+7)//8) (stage / "pixels.rgb").unlink() return total, "data:image/jpeg;base64," + base64.b64encode((stage / "hold.jpg").read_bytes()).decode("ascii") def finalize(folder): clips = [takes.completed(folder.name, rev) / f"cue-{folder.name[:12]}-{rev}.mp4" for rev in takes.timeline(folder.name)] if not clips: raise ValueError("No completed cue") output = folder / "FastFrames-Voice.mp4" with tempfile.TemporaryDirectory(dir=folder) as name: work = Path(name) manifest = work / "clips.txt" manifest.write_text("".join(f"file '{clip}'\n" for clip in clips)) result = work / output.name subprocess.run(["ffmpeg","-nostdin","-v","error","-y","-f","concat","-safe","0","-i",str(manifest), "-c:v","copy","-an","-movflags","+faststart",str(result)],check=True,timeout=60) result.replace(output) return str(output)