File size: 18,812 Bytes
745eaaf
f54e7d4
226c7c9
745eaaf
226c7c9
745eaaf
f54e7d4
 
6d7fc1c
 
 
4953ce6
817cd1e
f54e7d4
e22a639
745eaaf
 
f54e7d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745eaaf
 
f54e7d4
e22a639
 
 
 
32a4d55
e22a639
 
 
 
 
 
226c7c9
32a4d55
e22a639
f54e7d4
 
 
 
 
 
e22a639
f54e7d4
17d970d
f54e7d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17d970d
f54e7d4
 
 
 
 
 
 
 
 
 
 
17d970d
 
f54e7d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17d970d
f54e7d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745eaaf
 
 
 
 
 
 
 
 
 
 
 
6d7fc1c
f54e7d4
16293fe
f54e7d4
 
 
 
 
 
74308ee
f54e7d4
 
745eaaf
 
 
 
f54e7d4
 
 
 
 
226c7c9
 
745eaaf
 
5559672
 
817cd1e
226c7c9
817cd1e
 
f54e7d4
 
 
 
 
16293fe
17c2360
f54e7d4
 
 
 
 
 
 
 
817cd1e
 
745eaaf
817cd1e
 
74308ee
 
17d970d
817cd1e
 
226c7c9
 
f54e7d4
817cd1e
4953ce6
817cd1e
f54e7d4
745eaaf
 
 
f54e7d4
 
 
 
 
 
 
 
 
 
 
16293fe
f54e7d4
 
 
 
 
 
6d7fc1c
 
f54e7d4
 
 
 
 
 
6d7fc1c
 
f54e7d4
 
 
 
6d7fc1c
f54e7d4
 
74308ee
f54e7d4
 
 
 
745eaaf
f54e7d4
 
 
17d970d
 
 
 
 
 
 
 
74308ee
17d970d
f54e7d4
 
 
 
 
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import datetime
import os
import sys
import tempfile
import time
import zipfile
from typing import List, Tuple

import gradio as gr
import spaces

from gpu_info import stop_watcher, watch_gpu_memory

PWD = os.path.dirname(__file__)
CHECKPOINTS_PATH = "/data/checkpoints"
LOG_DIR = os.path.join(PWD, "logs")
os.makedirs(LOG_DIR, exist_ok=True)

try:
    import os

    from huggingface_hub import login

    # Try to login with token from environment variable
    hf_token = os.environ["HF_TOKEN"]
    if hf_token:
        login(token=hf_token)
        print("✅ Authenticated with Hugging Face")
    else:
        print("No HF_TOKEN found, trying without authentication...")
except Exception as e:
    print(f"Authentication failed: {e}")

# download checkpoints
from download_checkpoints import main as download_checkpoints

os.makedirs(CHECKPOINTS_PATH, exist_ok=True)
download_checkpoints(hf_token="", output_dir=CHECKPOINTS_PATH, model="7b_av")


from test_environment import main as check_environment
from test_environment import setup_environment

setup_environment()

# setup env
os.environ["CUDA_HOME"] = "/usr/local/cuda"
os.environ["LD_LIBRARY_PATH"] = "$CUDA_HOME/lib:$CUDA_HOME/lib64:$LD_LIBRARY_PATH"
os.environ["PATH"] = "$CUDA_HOME/bin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:$PATH"

if not check_environment():
    sys.exit(1)

os.environ["TOKENIZERS_PARALLELISM"] = "false"  # Workaround to suppress MP warning

import copy
import json
import random
from io import BytesIO

import torch

from cosmos_transfer1.checkpoints import (
    BASE_7B_CHECKPOINT_AV_SAMPLE_PATH,
    BASE_7B_CHECKPOINT_PATH,
    EDGE2WORLD_CONTROLNET_DISTILLED_CHECKPOINT_PATH,
)
from cosmos_transfer1.diffusion.inference.inference_utils import (
    validate_controlnet_specs,
)
from cosmos_transfer1.diffusion.inference.preprocessors import Preprocessors
from cosmos_transfer1.diffusion.inference.world_generation_pipeline import (
    DiffusionControl2WorldGenerationPipeline,
    DistilledControl2WorldGenerationPipeline,
)
from cosmos_transfer1.utils import log, misc
from cosmos_transfer1.utils.io import read_prompts_from_file, save_video
from helper import parse_arguments

torch.enable_grad(False)
torch.serialization.add_safe_globals([BytesIO])


def inference(cfg, control_inputs, chunking) -> Tuple[List[str], List[str]]:
    video_paths = []
    prompt_paths = []

    control_inputs = validate_controlnet_specs(cfg, control_inputs)
    misc.set_random_seed(cfg.seed)

    device_rank = 0
    process_group = None
    if cfg.num_gpus > 1:
        from megatron.core import parallel_state

        from cosmos_transfer1.utils import distributed

        distributed.init()
        parallel_state.initialize_model_parallel(context_parallel_size=cfg.num_gpus)
        process_group = parallel_state.get_context_parallel_group()

        device_rank = distributed.get_rank(process_group)

    preprocessors = Preprocessors()

    if cfg.use_distilled:
        assert not cfg.is_av_sample
        checkpoint = EDGE2WORLD_CONTROLNET_DISTILLED_CHECKPOINT_PATH
        pipeline = DistilledControl2WorldGenerationPipeline(
            checkpoint_dir=cfg.checkpoint_dir,
            checkpoint_name=checkpoint,
            offload_network=cfg.offload_diffusion_transformer,
            offload_text_encoder_model=cfg.offload_text_encoder_model,
            offload_guardrail_models=cfg.offload_guardrail_models,
            guidance=cfg.guidance,
            num_steps=cfg.num_steps,
            fps=cfg.fps,
            seed=cfg.seed,
            num_input_frames=cfg.num_input_frames,
            control_inputs=control_inputs,
            sigma_max=cfg.sigma_max,
            blur_strength=cfg.blur_strength,
            canny_threshold=cfg.canny_threshold,
            upsample_prompt=cfg.upsample_prompt,
            offload_prompt_upsampler=cfg.offload_prompt_upsampler,
            process_group=process_group,
        )
    else:
        checkpoint = BASE_7B_CHECKPOINT_AV_SAMPLE_PATH if cfg.is_av_sample else BASE_7B_CHECKPOINT_PATH

        # Initialize transfer generation model pipeline
        pipeline = DiffusionControl2WorldGenerationPipeline(
            checkpoint_dir=cfg.checkpoint_dir,
            checkpoint_name=checkpoint,
            offload_network=cfg.offload_diffusion_transformer,
            offload_text_encoder_model=cfg.offload_text_encoder_model,
            offload_guardrail_models=cfg.offload_guardrail_models,
            guidance=cfg.guidance,
            num_steps=cfg.num_steps,
            fps=cfg.fps,
            seed=cfg.seed,
            num_input_frames=cfg.num_input_frames,
            control_inputs=control_inputs,
            sigma_max=cfg.sigma_max,
            blur_strength=cfg.blur_strength,
            canny_threshold=cfg.canny_threshold,
            upsample_prompt=cfg.upsample_prompt,
            offload_prompt_upsampler=cfg.offload_prompt_upsampler,
            process_group=process_group,
            chunking=chunking,
        )

    if cfg.batch_input_path:
        log.info(f"Reading batch inputs from path: {cfg.batch_input_path}")
        prompts = read_prompts_from_file(cfg.batch_input_path)
    else:
        # Single prompt case
        prompts = [{"prompt": cfg.prompt, "visual_input": cfg.input_video_path}]

    batch_size = cfg.batch_size if hasattr(cfg, "batch_size") else 1
    if any("upscale" in control_input for control_input in control_inputs) and batch_size > 1:
        batch_size = 1
        log.info("Setting batch_size=1 as upscale does not support batch generation")
    os.makedirs(cfg.video_save_folder, exist_ok=True)
    for batch_start in range(0, len(prompts), batch_size):
        # Get current batch
        batch_prompts = prompts[batch_start : batch_start + batch_size]
        actual_batch_size = len(batch_prompts)
        # Extract batch data
        batch_prompt_texts = [p.get("prompt", None) for p in batch_prompts]
        batch_video_paths = [p.get("visual_input", None) for p in batch_prompts]

        batch_control_inputs = []
        for i, input_dict in enumerate(batch_prompts):
            current_prompt = input_dict.get("prompt", None)
            current_video_path = input_dict.get("visual_input", None)

            if cfg.batch_input_path:
                video_save_subfolder = os.path.join(cfg.video_save_folder, f"video_{batch_start+i}")
                os.makedirs(video_save_subfolder, exist_ok=True)
            else:
                video_save_subfolder = cfg.video_save_folder

            current_control_inputs = copy.deepcopy(control_inputs)
            if "control_overrides" in input_dict:
                for hint_key, override in input_dict["control_overrides"].items():
                    if hint_key in current_control_inputs:
                        current_control_inputs[hint_key].update(override)
                    else:
                        log.warning(f"Ignoring unknown control key in override: {hint_key}")

            # if control inputs are not provided, run respective preprocessor (for seg and depth)
            log.info("running preprocessor")
            preprocessors(
                current_video_path,
                current_prompt,
                current_control_inputs,
                video_save_subfolder,
                cfg.regional_prompts if hasattr(cfg, "regional_prompts") else None,
            )
            batch_control_inputs.append(current_control_inputs)

        regional_prompts = []
        region_definitions = []
        if hasattr(cfg, "regional_prompts") and cfg.regional_prompts:
            log.info(f"regional_prompts: {cfg.regional_prompts}")
            for regional_prompt in cfg.regional_prompts:
                regional_prompts.append(regional_prompt["prompt"])
                if "region_definitions_path" in regional_prompt:
                    log.info(f"region_definitions_path: {regional_prompt['region_definitions_path']}")
                    region_definition_path = regional_prompt["region_definitions_path"]
                    if isinstance(region_definition_path, str) and region_definition_path.endswith(".json"):
                        with open(region_definition_path, "r") as f:
                            region_definitions_json = json.load(f)
                        region_definitions.extend(region_definitions_json)
                    else:
                        region_definitions.append(region_definition_path)

        if hasattr(pipeline, "regional_prompts"):
            pipeline.regional_prompts = regional_prompts
        if hasattr(pipeline, "region_definitions"):
            pipeline.region_definitions = region_definitions

        # Generate videos in batch
        batch_outputs = pipeline.generate(
            prompt=batch_prompt_texts,
            video_path=batch_video_paths,
            negative_prompt=cfg.negative_prompt,
            control_inputs=batch_control_inputs,
            save_folder=video_save_subfolder,
            batch_size=actual_batch_size,
        )
        if batch_outputs is None:
            log.critical("Guardrail blocked generation for entire batch.")
            continue

        videos, final_prompts = batch_outputs
        for i, (video, prompt) in enumerate(zip(videos, final_prompts)):
            if cfg.batch_input_path:
                video_save_subfolder = os.path.join(cfg.video_save_folder, f"video_{batch_start+i}")
                video_save_path = os.path.join(video_save_subfolder, "output.mp4")
                prompt_save_path = os.path.join(video_save_subfolder, "prompt.txt")
            else:
                video_save_path = os.path.join(cfg.video_save_folder, f"{cfg.video_save_name}.mp4")
                prompt_save_path = os.path.join(cfg.video_save_folder, f"{cfg.video_save_name}.txt")
            # Save video and prompt
            if device_rank == 0:
                os.makedirs(os.path.dirname(video_save_path), exist_ok=True)
                save_video(
                    video=video,
                    fps=cfg.fps,
                    H=video.shape[1],
                    W=video.shape[2],
                    video_save_quality=5,
                    video_save_path=video_save_path,
                )
                video_paths.append(video_save_path)

                # Save prompt to text file alongside video
                with open(prompt_save_path, "wb") as f:
                    f.write(prompt.encode("utf-8"))

                prompt_paths.append(prompt_save_path)

                log.info(f"Saved video to {video_save_path}")
                log.info(f"Saved prompt to {prompt_save_path}")

    # clean up properly
    if cfg.num_gpus > 1:
        parallel_state.destroy_model_parallel()
        import torch.distributed as dist

        dist.destroy_process_group()

    return video_paths, prompt_paths


def create_zip_for_download(filename, files_to_zip):
    temp_dir = tempfile.mkdtemp()
    zip_path = os.path.join(temp_dir, f"{os.path.splitext(filename)[0]}.zip")

    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
        for file_path in files_to_zip:
            arcname = os.path.basename(file_path)
            zipf.write(file_path, arcname)

    return zip_path


@spaces.GPU()
def generate_video(
    rgb_video_path,
    hdmap_video_input,
    lidar_video_input,
    prompt,
    negative_prompt="The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality.",  # noqa: E501
    seed=42,
    randomize_seed=False,
    chunking=None,
    progress=gr.Progress(track_tqdm=True),
):
    _dt = datetime.datetime.now(tz=datetime.timezone(datetime.timedelta(hours=8))).strftime("%Y-%m-%d_%H.%M.%S")
    logfile_path = os.path.join(LOG_DIR, f"{_dt}.log")
    log_handler = log.init_dev_loguru_file(logfile_path)

    if randomize_seed:
        actual_seed = random.randint(0, 1000000)
    else:
        actual_seed = seed

    log.info(f"actual_seed: {actual_seed}")

    if rgb_video_path is None or not os.path.isfile(rgb_video_path):
        log.warning(f"File `{rgb_video_path}` does not exist")
        rgb_video_path = ""

    # add timer to calculate the generation time
    start_time = time.time()

    # parse generation configs
    args, control_inputs = parse_arguments(
        controlnet_specs_in={
            "hdmap": {"control_weight": 0.3, "input_control": hdmap_video_input},
            "lidar": {"control_weight": 0.7, "input_control": lidar_video_input},
        },
        input_video_path=rgb_video_path,
        checkpoint_dir=CHECKPOINTS_PATH,
        prompt=prompt,
        negative_prompt=negative_prompt,
        sigma_max=80,
        offload_text_encoder_model=True,
        is_av_sample=True,
        num_gpus=1,
        seed=seed,
    )

    # watch gpu memory
    watcher = watch_gpu_memory(10, lambda x: log.debug(f"GPU memory usage: {x} (MiB)"))

    # start inference
    if chunking <= 0:
        chunking = None
    videos, prompts = inference(args, control_inputs, chunking)

    # print the generation time
    end_time = time.time()
    log.info(f"Time taken: {end_time - start_time} s")

    # stop the watcher
    stop_watcher()

    video = videos[0]

    log.logger.remove(log_handler)
    return video, create_zip_for_download(filename=logfile_path, files_to_zip=[video, logfile_path]), actual_seed


# Define the Gradio Blocks interface
with gr.Blocks() as demo:
    gr.Markdown(
        """
        # Cosmos-Transfer1-7B-Sample-AV
        """
    )
    with gr.Row():
        with gr.Column():
            rgb_video_input = gr.Video(label="Input RGB Video", format="mp4")
            hdmap_input = gr.Video(label="Input HD Map Video", format="mp4")
            lidar_input = gr.Video(label="Input LiDAR Video", format="mp4")

            prompt_input = gr.Textbox(
                label="Prompt",
                lines=5,
                # value="A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, its bristles moving in circular motions to lift stubborn grease and food residue. The dish, once covered in remnants of a hearty meal, gradually reveals its original glossy surface. Suds form and bubble around the scrubber, creating a satisfying visual of cleanliness in progress. The sound of scrubbing fills the air, accompanied by the gentle clinking of the dish against the sink. As the scrubber continues its task, the dish transforms, gleaming under the bright kitchen lights, symbolizing the triumph of cleanliness over mess.",  # noqa: E501
                value="The video is captured from a camera mounted on a car. The camera is facing forward. The video showcases a scenic golden-hour drive through a suburban area, bathed in the warm, golden hues of the setting sun. The dashboard camera captures the play of light and shadow as the sun’s rays filter through the trees, casting elongated patterns onto the road. The streetlights remain off, as the golden glow of the late afternoon sun provides ample illumination. The two-lane road appears to shimmer under the soft light, while the concrete barrier on the left side of the road reflects subtle warm tones. The stone wall on the right, adorned with lush greenery, stands out vibrantly under the golden light, with the palm trees swaying gently in the evening breeze. Several parked vehicles, including white sedans and vans, are seen on the left side of the road, their surfaces reflecting the amber hues of the sunset. The trees, now highlighted in a golden halo, cast intricate shadows onto the pavement. Further ahead, houses with red-tiled roofs glow warmly in the fading light, standing out against the sky, which transitions from deep orange to soft pastel blue. As the vehicle continues, a white sedan is seen driving in the same lane, while a black sedan and a white van move further ahead. The road markings are crisp, and the entire setting radiates a peaceful, almost cinematic beauty. The golden light, combined with the quiet suburban landscape, creates an atmosphere of tranquility and warmth, making for a mesmerizing and soothing drive.",  # noqa: E501
                placeholder="Enter your descriptive prompt here...",
            )

            negative_prompt_input = gr.Textbox(
                label="Negative Prompt",
                lines=3,
                # value="The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality.",  # noqa: E501
                value="The video captures a game playing, with bad crappy graphics and cartoonish frames. It represents a recording of old outdated games. The lighting looks very fake. The textures are very raw and basic. The geometries are very primitive. The images are very pixelated and of poor CG quality. There are many subtitles in the footage. Overall, the video is unrealistic at all.",  # noqa: E501
                placeholder="Enter what you DON'T want to see in the image...",
            )

            with gr.Row():
                randomize_seed_checkbox = gr.Checkbox(label="Randomize Seed", value=False)
                seed_input = gr.Slider(minimum=0, maximum=1000000, value=1, step=1, label="Seed")

            chunking_input = gr.Slider(minimum=0, maximum=121, value=4, step=1, label="Chunking size")
            generate_button = gr.Button("Generate Image")

        with gr.Column():
            output_video = gr.Video(label="Generated Video", format="mp4")
            output_file = gr.File(label="Download Results")

    generate_button.click(
        fn=generate_video,
        inputs=[
            rgb_video_input,
            hdmap_input,
            lidar_input,
            prompt_input,
            negative_prompt_input,
            seed_input,
            randomize_seed_checkbox,
            chunking_input,
        ],
        outputs=[output_video, output_file, seed_input],
    )

if __name__ == "__main__":
    demo.launch()