|
| 1 | +""" |
| 2 | + Copyright 2025 Google LLC |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | + """ |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +from absl import app |
| 19 | +from typing import Sequence |
| 20 | +from maxdiffusion.pipelines.ltx_video.ltx_video_pipeline import LTXVideoPipeline |
| 21 | +from maxdiffusion.pipelines.ltx_video.ltx_video_pipeline import LTXMultiScalePipeline |
| 22 | +from maxdiffusion import pyconfig, max_logging |
| 23 | +import imageio |
| 24 | +from datetime import datetime |
| 25 | +import os |
| 26 | +import time |
| 27 | +from pathlib import Path |
| 28 | + |
| 29 | + |
| 30 | +def calculate_padding( |
| 31 | + source_height: int, source_width: int, target_height: int, target_width: int |
| 32 | +) -> tuple[int, int, int, int]: |
| 33 | + |
| 34 | + # Calculate total padding needed |
| 35 | + pad_height = target_height - source_height |
| 36 | + pad_width = target_width - source_width |
| 37 | + |
| 38 | + # Calculate padding for each side |
| 39 | + pad_top = pad_height // 2 |
| 40 | + pad_bottom = pad_height - pad_top # Handles odd padding |
| 41 | + pad_left = pad_width // 2 |
| 42 | + pad_right = pad_width - pad_left # Handles odd padding |
| 43 | + padding = (pad_left, pad_right, pad_top, pad_bottom) |
| 44 | + return padding |
| 45 | + |
| 46 | + |
| 47 | +def convert_prompt_to_filename(text: str, max_len: int = 20) -> str: |
| 48 | + # Remove non-letters and convert to lowercase |
| 49 | + clean_text = "".join(char.lower() for char in text if char.isalpha() or char.isspace()) |
| 50 | + |
| 51 | + # Split into words |
| 52 | + words = clean_text.split() |
| 53 | + |
| 54 | + # Build result string keeping track of length |
| 55 | + result = [] |
| 56 | + current_length = 0 |
| 57 | + |
| 58 | + for word in words: |
| 59 | + # Add word length plus 1 for underscore (except for first word) |
| 60 | + new_length = current_length + len(word) |
| 61 | + |
| 62 | + if new_length <= max_len: |
| 63 | + result.append(word) |
| 64 | + current_length += len(word) |
| 65 | + else: |
| 66 | + break |
| 67 | + |
| 68 | + return "-".join(result) |
| 69 | + |
| 70 | + |
| 71 | +def get_unique_filename( |
| 72 | + base: str, |
| 73 | + ext: str, |
| 74 | + prompt: str, |
| 75 | + resolution: tuple[int, int, int], |
| 76 | + dir: Path, |
| 77 | + endswith=None, |
| 78 | + index_range=1000, |
| 79 | +) -> Path: |
| 80 | + base_filename = f"{base}_{convert_prompt_to_filename(prompt, max_len=30)}_{resolution[0]}x{resolution[1]}x{resolution[2]}" |
| 81 | + for i in range(index_range): |
| 82 | + filename = dir / f"{base_filename}_{i}{endswith if endswith else ''}{ext}" |
| 83 | + if not os.path.exists(filename): |
| 84 | + return filename |
| 85 | + raise FileExistsError(f"Could not find a unique filename after {index_range} attempts.") |
| 86 | + |
| 87 | + |
| 88 | +def run(config): |
| 89 | + height_padded = ((config.height - 1) // 32 + 1) * 32 |
| 90 | + width_padded = ((config.width - 1) // 32 + 1) * 32 |
| 91 | + num_frames_padded = ((config.num_frames - 2) // 8 + 1) * 8 + 1 |
| 92 | + padding = calculate_padding(config.height, config.width, height_padded, width_padded) |
| 93 | + prompt_enhancement_words_threshold = config.prompt_enhancement_words_threshold |
| 94 | + prompt_word_count = len(config.prompt.split()) |
| 95 | + enhance_prompt = prompt_enhancement_words_threshold > 0 and prompt_word_count < prompt_enhancement_words_threshold |
| 96 | + |
| 97 | + pipeline = LTXVideoPipeline.from_pretrained(config, enhance_prompt=enhance_prompt) |
| 98 | + if config.pipeline_type == "multi-scale": |
| 99 | + pipeline = LTXMultiScalePipeline(pipeline) |
| 100 | + s0 = time.perf_counter() |
| 101 | + images = pipeline( |
| 102 | + height=height_padded, |
| 103 | + width=width_padded, |
| 104 | + num_frames=num_frames_padded, |
| 105 | + is_video=True, |
| 106 | + output_type="pt", |
| 107 | + config=config, |
| 108 | + enhance_prompt=enhance_prompt, |
| 109 | + seed=config.seed, |
| 110 | + ) |
| 111 | + max_logging.log(f"Compile time: {time.perf_counter() - s0:.1f}s.") |
| 112 | + |
| 113 | + (pad_left, pad_right, pad_top, pad_bottom) = padding |
| 114 | + pad_bottom = -pad_bottom |
| 115 | + pad_right = -pad_right |
| 116 | + if pad_bottom == 0: |
| 117 | + pad_bottom = images.shape[3] |
| 118 | + if pad_right == 0: |
| 119 | + pad_right = images.shape[4] |
| 120 | + images = images[:, :, : config.num_frames, pad_top:pad_bottom, pad_left:pad_right] |
| 121 | + output_dir = Path(f"outputs/{datetime.today().strftime('%Y-%m-%d')}") |
| 122 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 123 | + |
| 124 | + for i in range(images.shape[0]): |
| 125 | + # Gathering from B, C, F, H, W to C, F, H, W and then permuting to F, H, W, C |
| 126 | + video_np = images[i].permute(1, 2, 3, 0).detach().float().numpy() |
| 127 | + # Unnormalizing images to [0, 255] range |
| 128 | + video_np = (video_np * 255).astype(np.uint8) |
| 129 | + fps = config.frame_rate |
| 130 | + height, width = video_np.shape[1:3] |
| 131 | + # In case a single image is generated |
| 132 | + if video_np.shape[0] == 1: |
| 133 | + output_filename = get_unique_filename( |
| 134 | + f"image_output_{i}", |
| 135 | + ".png", |
| 136 | + prompt=config.prompt, |
| 137 | + resolution=(height, width, config.num_frames), |
| 138 | + dir=output_dir, |
| 139 | + ) |
| 140 | + imageio.imwrite(output_filename, video_np[0]) |
| 141 | + else: |
| 142 | + output_filename = get_unique_filename( |
| 143 | + f"video_output_{i}", |
| 144 | + ".mp4", |
| 145 | + prompt=config.prompt, |
| 146 | + resolution=(height, width, config.num_frames), |
| 147 | + dir=output_dir, |
| 148 | + ) |
| 149 | + # Write video |
| 150 | + with imageio.get_writer(output_filename, fps=fps) as video: |
| 151 | + for frame in video_np: |
| 152 | + video.append_data(frame) |
| 153 | + |
| 154 | + |
| 155 | +def main(argv: Sequence[str]) -> None: |
| 156 | + pyconfig.initialize(argv) |
| 157 | + run(pyconfig.config) |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == "__main__": |
| 161 | + app.run(main) |
0 commit comments