File size: 6,309 Bytes
81fd211
265f7ee
bcd33b0
1d797bd
 
 
bcd33b0
1d797bd
 
 
 
bcd33b0
1d797bd
265f7ee
1d797bd
 
 
0d86e63
 
 
1d797bd
 
 
 
 
bcd33b0
 
1d797bd
bcd33b0
8ef249c
 
 
 
 
 
 
 
 
 
 
4e162b1
 
 
 
 
 
bcd33b0
1d797bd
bcd33b0
 
 
 
 
1d797bd
bcd33b0
4e162b1
bcd33b0
 
4e162b1
 
 
bcd33b0
 
 
 
4e162b1
bcd33b0
265f7ee
 
 
 
 
81fd211
 
 
2207496
81fd211
bcd33b0
 
81fd211
bcd33b0
81fd211
 
 
bcd33b0
2207496
 
 
 
 
265f7ee
81fd211
 
265f7ee
 
 
 
 
bcd33b0
1d797bd
bcd33b0
 
 
2207496
 
 
 
 
 
 
 
 
 
 
 
 
bcd33b0
 
 
 
 
2207496
 
 
bcd33b0
38ff112
bcd33b0
 
 
e9aaef0
 
bcd33b0
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""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)