|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | + |
| 4 | +from functools import partial |
| 5 | +from typing import Any, List, Literal |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import torch |
| 9 | +from diffusers import DiffusionPipeline |
| 10 | +from diffusers.pipelines.cogvideo.pipeline_output import CogVideoXPipelineOutput |
| 11 | +from PIL import Image |
| 12 | + |
| 13 | +from cogkit.logging import get_logger |
| 14 | +from cogkit.types import GenerationMode |
| 15 | +from cogkit.utils import ( |
| 16 | + guess_generation_mode, |
| 17 | + rand_generator, |
| 18 | +) |
| 19 | + |
| 20 | +from .util import before_generation, guess_frames, guess_resolution |
| 21 | + |
| 22 | +_logger = get_logger(__name__) |
| 23 | + |
| 24 | + |
| 25 | +def _cast_to_pipeline_output(output: Any) -> CogVideoXPipelineOutput: |
| 26 | + if isinstance(output, CogVideoXPipelineOutput): |
| 27 | + return output |
| 28 | + if isinstance(output, tuple): |
| 29 | + return CogVideoXPipelineOutput(frames=output[0]) |
| 30 | + |
| 31 | + err_msg = f"Cannot cast a `{output.__class__.__name__}` to a `CogVideoXPipelineOutput`." |
| 32 | + raise ValueError(err_msg) |
| 33 | + |
| 34 | + |
| 35 | +def generate_video( |
| 36 | + prompt: str, |
| 37 | + pipeline: DiffusionPipeline, |
| 38 | + num_videos_per_prompt: int = 1, |
| 39 | + output_type: Literal["pil", "pt", "np"] = "pil", |
| 40 | + input_image: Image.Image | None = None, |
| 41 | + # * params for model loading |
| 42 | + load_type: Literal["cuda", "cpu_model_offload", "sequential_cpu_offload"] = "cpu_model_offload", |
| 43 | + height: int | None = None, |
| 44 | + width: int | None = None, |
| 45 | + num_frames: int | None = None, |
| 46 | + num_inference_steps: int = 50, |
| 47 | + guidance_scale: float = 6.0, |
| 48 | + seed: int | None = 42, |
| 49 | +) -> tuple[List[Image.Image] | torch.Tensor | np.ndarray, int]: |
| 50 | + """Main function for video generation, supporting both text-to-video and image-to-video generation modes. |
| 51 | +
|
| 52 | + Args: |
| 53 | + - prompt (str): Text prompt describing the desired video content. |
| 54 | + - pipeline (DiffusionPipeline): Pre-loaded diffusion model pipeline. |
| 55 | + - num_videos_per_prompt (int, optional): Number of videos to generate per prompt. Defaults to 1. |
| 56 | + - output_type (Literal, optional): Output type, one of "pil", "pt", or "np". Defaults to "pil". |
| 57 | + - input_image (Image.Image | None, optional): Input image for image-to-video generation. Defaults to None. |
| 58 | + - load_type (Literal, optional): Model loading type, one of "cuda", "cpu_model_offload", or |
| 59 | + "sequential_cpu_offload". Defaults to "cpu_model_offload". |
| 60 | + - height (int | None, optional): Height of output video. If None, will be inferred. Defaults to None. |
| 61 | + - width (int | None, optional): Width of output video. If None, will be inferred. Defaults to None. |
| 62 | + - num_frames (int | None, optional): Number of frames in generated video. If None, will be inferred. |
| 63 | + Defaults to None. |
| 64 | + - num_inference_steps (int, optional): Number of inference steps. Defaults to 50. |
| 65 | + - guidance_scale (float, optional): Classifier guidance scale. Defaults to 6.0. |
| 66 | + - seed (int | None, optional): Random seed for generation. Defaults to 42. |
| 67 | +
|
| 68 | + Returns: |
| 69 | + tuple[torch.Tensor, int]: Returns a tuple containing: |
| 70 | + - Generated video tensor with shape (num_videos, num_frames, height, width, 3) |
| 71 | + - Video frame rate (fps) |
| 72 | +
|
| 73 | + Raises: |
| 74 | + ValueError: When provided generation mode is unknown or output cannot be cast to CogVideoXPipelineOutput. |
| 75 | + AssertionError: When both pipeline and model_id_or_path are None or both are provided. |
| 76 | +
|
| 77 | + Note: |
| 78 | + - Either pipeline or model_id_or_path must be provided, but not both. |
| 79 | + - If lora_model_id_or_path is provided, LoRA weights will be loaded and applied. |
| 80 | + - Height, width, number of frames, and fps will be automatically inferred if not specified. |
| 81 | + """ |
| 82 | + |
| 83 | + task = guess_generation_mode( |
| 84 | + pipeline=pipeline, |
| 85 | + generation_mode=None, |
| 86 | + image=input_image, |
| 87 | + ) |
| 88 | + |
| 89 | + height, width = guess_resolution(pipeline, height, width) |
| 90 | + num_frames, fps = guess_frames(pipeline, num_frames) |
| 91 | + |
| 92 | + _logger.info( |
| 93 | + f"Generation config: height {height}, width {width}, num_frames {num_frames}, fps {fps}." |
| 94 | + ) |
| 95 | + |
| 96 | + before_generation(pipeline, load_type) |
| 97 | + |
| 98 | + pipeline_fn = partial( |
| 99 | + pipeline, |
| 100 | + height=height, |
| 101 | + width=width, |
| 102 | + prompt=prompt, |
| 103 | + num_videos_per_prompt=num_videos_per_prompt, |
| 104 | + num_inference_steps=num_inference_steps, |
| 105 | + num_frames=num_frames, |
| 106 | + use_dynamic_cfg=True, |
| 107 | + guidance_scale=guidance_scale, |
| 108 | + output_type=output_type, |
| 109 | + generator=rand_generator(seed), |
| 110 | + ) |
| 111 | + if task == GenerationMode.TextToVideo: |
| 112 | + pipeline_out = pipeline_fn() |
| 113 | + elif task == GenerationMode.ImageToVideo: |
| 114 | + pipeline_out = pipeline_fn(image=input_image) |
| 115 | + else: |
| 116 | + err_msg = f"Unknown generation mode: {task.value}" |
| 117 | + raise ValueError(err_msg) |
| 118 | + |
| 119 | + batch_video = _cast_to_pipeline_output(pipeline_out).frames |
| 120 | + |
| 121 | + if output_type in ("pt", "np"): |
| 122 | + # Dim of a video: (num_videos, num_frames, 3, height, width) |
| 123 | + assert batch_video.ndim == 5, f"Expected 5D array, got {batch_video[0].ndim}D array" |
| 124 | + assert batch_video.shape[2] == 3, ( |
| 125 | + f"Expected 3 channels, got {batch_video[0].shape[2]} channels" |
| 126 | + ) |
| 127 | + return batch_video, fps |
0 commit comments