#
# Apache License, Version 2.0("라이선스")에 따라 라이선스가 부여됩니다.
# 이 파일은 라이선스에 따라만 사용할 수 있습니다.
# 라이선스 사본은 다음에서 가져올 수 있습니다
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 적용 가능한 법률에 의해 요구되거나 서면으로 합의되지 않는 한, 소프트웨어
# 라이선스에 따라 배포되는 본 소프트웨어는 "있는 그대로"
# 명시적이든 묵시적이든 어떠한 종류의 보증이나 조건도 없이 제공됩니다.
# 권한을 관리하는 특정 언어에 대한 라이선스를 참조하세요
# 라이선스 하의 제한 사항.
-->

# EasyAnimate
Alibaba PAI의 [EasyAnimate](https://github.com/aigc-apps/EasyAnimate).

GitHub 페이지의 설명: *EasyAnimate는 transformer 아키텍처 기반의 파이프라인으로, AI 이미지 및 비디오 생성과 Diffusion Transformer의 베이스라인 모델 및 Lora 모델 학습을 위해 설계되었습니다. 사전 학습된 EasyAnimate 모델로부터의 직접 예측을 지원하여, 다양한 해상도의 약 6초 길이, 8fps의 비디오를 생성할 수 있습니다(EasyAnimateV5.1, 1~49프레임). 또한, 사용자는 특정 스타일 변환을 위한 자체 베이스라인 및 Lora 모델을 학습할 수 있습니다.*

이 파이프라인은 [bubbliiiing](https://github.com/bubbliiiing)이(가) 기여했습니다. 원본 코드베이스는 [여기](https://huggingface.co/alibaba-pai)에서 찾을 수 있습니다. 원본 가중치는 [hf.co/alibaba-pai](https://huggingface.co/alibaba-pai)에서 찾을 수 있습니다.

텍스트-투-비디오와 비디오-투-비디오를 위한 공식 EasyAnimate 체크포인트가 두 가지 있습니다.

| checkpoints | 권장 추론 dtype |
|:---:|:---:|
| [`alibaba-pai/EasyAnimateV5.1-12b-zh`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh) | torch.float16 |
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-InP`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-InP) | torch.float16 |

이미지-비디오 및 비디오-비디오 변환을 위한 공식 EasyAnimate 체크포인트가 하나 있습니다.

| checkpoints | 권장 추론 dtype |
|:---:|:---:|
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-InP`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-InP) | torch.float16 |

control-to-video를 위한 공식 EasyAnimate 체크포인트가 두 가지 있습니다.

| checkpoints | 권장 추론 dtype |
|:---:|:---:|
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-Control`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-Control) | torch.float16 |
| [`alibaba-pai/EasyAnimateV5.1-12b-zh-Control-Camera`](https://huggingface.co/alibaba-pai/EasyAnimateV5.1-12b-zh-Control-Camera) | torch.float16 |

EasyAnimateV5.1 시리즈의 경우:
- 텍스트-투-비디오(T2V)와 이미지-투-비디오(I2V)는 여러 해상도를 지원합니다. 너비와 높이는 256에서 1024까지 다양할 수 있습니다.
- T2V 및 I2V 모델 모두 1~49프레임 생성을 지원하며, 이 값에서 가장 좋은 성능을 발휘합니다. 8 FPS로 비디오를 내보내는 것을 권장합니다.

## 양자화

Quantization은 모델 가중치를 더 낮은 정밀도의 데이터 타입으로 저장하여 매우 큰 모델의 메모리 요구 사항을 줄이는 데 도움이 됩니다. 그러나 quantization은 비디오 모델에 따라 비디오 품질에 다양한 영향을 미칠 수 있습니다.

지원되는 양자화 백엔드와 사용 사례에 맞는 양자화 백엔드 선택에 대해 자세히 알아보려면 [Quantization](../../quantization/overview) 개요를 참조하세요. 아래 예제는 bitsandbytes로 양자화된 [EasyAnimatePipeline](/docs/diffusers/main/ko/api/pipelines/easyanimate#diffusers.EasyAnimatePipeline)을 추론에 로드하는 방법을 보여줍니다.

```py
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, EasyAnimateTransformer3DModel, EasyAnimatePipeline
from diffusers.utils import export_to_video

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = EasyAnimateTransformer3DModel.from_pretrained(
    "alibaba-pai/EasyAnimateV5.1-12b-zh",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.float16,
)

pipeline = EasyAnimatePipeline.from_pretrained(
    "alibaba-pai/EasyAnimateV5.1-12b-zh",
    transformer=transformer_8bit,
    dtype=torch.float16,
    device_map="balanced",
)

prompt = "A cat walks on the grass, realistic style."
negative_prompt = "bad detailed"
video = pipeline(prompt=prompt, negative_prompt=negative_prompt, num_frames=49, num_inference_steps=30).frames[0]
export_to_video(video, "cat.mp4", fps=8)
```

## EasyAnimatePipeline[[diffusers.EasyAnimatePipeline]]

#### diffusers.EasyAnimatePipeline[[diffusers.EasyAnimatePipeline]]

```python
diffusers.EasyAnimatePipeline(vae: AutoencoderKLMagvit, text_encoder: transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLForConditionalGeneration | transformers.models.bert.modeling_bert.BertModel, tokenizer: transformers.models.qwen2.tokenization_qwen2.Qwen2Tokenizer | transformers.models.bert.tokenization_bert.BertTokenizer, transformer: EasyAnimateTransformer3DModel, scheduler: FlowMatchEulerDiscreteScheduler)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L186)

**매개변수:**

vae ([AutoencoderKLMagvit](/docs/diffusers/main/ko/api/models/autoencoderkl_magvit#diffusers.AutoencoderKLMagvit)) : 비디오를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.

text_encoder (`~transformers.Qwen2VLForConditionalGeneration`, `~transformers.BertModel` | None) : EasyAnimate는 V5.1에서 [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct)을 사용합니다.

tokenizer (`~transformers.Qwen2Tokenizer`, `~transformers.BertTokenizer` | None) : 텍스트를 토큰화할 `Qwen2Tokenizer` 또는 `BertTokenizer`.

transformer ([EasyAnimateTransformer3DModel](/docs/diffusers/main/ko/api/models/easyanimate_transformer3d#diffusers.EasyAnimateTransformer3DModel)) : EasyAnimate Team이 설계한 EasyAnimate 모델입니다.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : EasyAnimate와 함께 사용하여 인코딩된 이미지 라텐트의 노이즈를 제거하는 데 사용되는 스케줄러입니다.

EasyAnimate를 사용한 텍스트-비디오 생성을 위한 Pipeline

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

EasyAnimate는 V5.1에서 하나의 텍스트 인코더인 [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct)를 사용합니다.

#### __호출__[[diffusers.EasyAnimatePipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, num_frames: int | None = 49, height: int | None = 512, width: int | None = 512, num_inference_steps: int | None = 50, guidance_scale: float | None = 5.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float | None = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, timesteps: list[int] | None = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], guidance_rescale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L524)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 또는 비디오 생성을 안내하는 텍스트 프롬프트입니다. 제공되지 않으면 `prompt_embeds`를 대신 사용합니다.

num_frames (`int`, *선택 사항*) : 생성된 비디오의 길이(프레임 단위).

height (`int`, *선택 사항*) : 생성된 이미지의 픽셀 단위 높이.

width (`int`, *선택 사항*) : 생성된 이미지의 픽셀 단위 너비.

num_inference_steps (`int`, *선택 사항*, 기본값 50) : 생성 과정의 디노이징 단계 수입니다. 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만 추론 속도가 느려집니다.

guidance_scale (`float`, *선택 사항*, 기본값 5.0) : 모델이 출력을 프롬프트와 일치하도록 유도합니다. 값이 높을수록 이미지 품질이 저하될 수 있습니다.

negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 생성에서 제외할 내용을 나타내는 프롬프트입니다. 지정되지 않으면 `negative_prompt_embeds`를 사용합니다.

num_images_per_prompt (`int`, *선택 사항*, 기본값 1) : 각 프롬프트에 대해 생성할 이미지의 수.

eta (`float`, *선택 사항*, 기본값 0.0) : DDIM 스케줄링에 적용됩니다. 관련 문헌의 eta 파라미터로 제어됩니다.

generator (`torch.Generator` 또는 `list[torch.Generator]`, *선택 사항*) : 이미지 생성의 재현성을 보장하기 위한 생성기입니다.

latents (`torch.Tensor`, *선택 사항*) : 생성을 조건부화하기 위한 사전 정의된 잠재 텐서.

prompt_embeds (`torch.Tensor`, *선택 사항*) : 프롬프트의 텍스트 임베딩입니다. 더 높은 유연성을 위해 프롬프트 문자열 입력을 덮어씁니다.

negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 부정 프롬프트의 임베딩입니다. 정의된 경우 문자열 입력을 덮어씁니다.

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 주요 프롬프트 임베딩에 대한 어텐션 마스크입니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택 사항*) : negative prompt 임베딩에 사용할 attention mask입니다.

output_type (`str`, *선택 사항*, 기본값 "latent") : 생성된 출력의 형식입니다. PIL 이미지 또는 NumPy 배열 중 하나입니다.

return_dict (`bool`, *선택 사항*, 기본값 `True`) : `True`인 경우 구조화된 출력을 반환합니다. 그렇지 않으면 간단한 튜플을 반환합니다.

callback_on_step_end (`Callable`, *선택 사항*) : 각 디노이징 단계의 끝에서 호출되는 함수.

callback_on_step_end_tensor_inputs (`list[str]`, *선택 사항*) : 콜백 함수 호출에 포함될 텐서 이름.

guidance_rescale (`float`, *선택 사항*, 기본값 0.0) : guidance scale에 따라 노이즈 레벨을 조정합니다.

timesteps (`list[int]`, *선택 사항*) : 노이즈 제거 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우, `num_inference_steps`에 대한 스케줄러의 기본 스케줄이 사용됩니다.

**반환값:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 또는 `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

제공된 프롬프트를 기반으로 EasyAnimate 파이프라인을 사용하여 이미지 또는 비디오를 생성합니다.

예:
```python
>>> import torch
>>> from diffusers import EasyAnimatePipeline
>>> from diffusers.utils import export_to_video

>>> # Models: "alibaba-pai/EasyAnimateV5.1-12b-zh"
>>> pipe = EasyAnimatePipeline.from_pretrained(
...     "alibaba-pai/EasyAnimateV5.1-7b-zh-diffusers", torch_dtype=torch.float16
... ).to("cuda")
>>> prompt = (
...     "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
...     "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
...     "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
...     "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
...     "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
...     "atmosphere of this unique musical performance."
... )
>>> sample_size = (512, 512)
>>> video = pipe(
...     prompt=prompt,
...     guidance_scale=6,
...     negative_prompt="bad detailed",
...     height=sample_size[0],
...     width=sample_size[1],
...     num_inference_steps=50,
... ).frames[0]
>>> export_to_video(video, "output.mp4", fps=8)
```

#### encode_prompt[[diffusers.EasyAnimatePipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None, max_sequence_length: int = 256)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py#L241)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트

device : (`torch.device`): torch 디바이스

dtype (`torch.dtype`) : torch dtype

num_images_per_prompt (`int`) : 프롬프트당 생성할 이미지 수

do_classifier_free_guidance (`bool`) : classifier free guidance를 사용할지 여부

negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).

prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.

negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 프롬프트에 사용할 어텐션 마스크입니다. `prompt_embeds`를 직접 전달하는 경우 필수입니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택*) : negative prompt에 사용할 attention mask입니다. `negative_prompt_embeds`가 직접 전달될 때 필수입니다.

max_sequence_length (`int`, *선택 사항*) : 프롬프트에 사용할 최대 시퀀스 길이.

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

## EasyAnimatePipelineOutput[[diffusers.pipelines.easyanimate.pipeline_output.EasyAnimatePipelineOutput]]

#### diffusers.pipelines.easyanimate.pipeline_output.EasyAnimatePipelineOutput[[diffusers.pipelines.easyanimate.pipeline_output.EasyAnimatePipelineOutput]]

```python
diffusers.pipelines.easyanimate.pipeline_output.EasyAnimatePipelineOutput(frames: Tensor)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/easyanimate/pipeline_output.py#L9)

**매개변수:**

frames (`torch.Tensor`, `np.ndarray`, 또는 list[list[PIL.Image.Image]]) : 비디오 출력 목록 - `batch_size,` 길이의 중첩 목록일 수 있으며, 각 하위 목록에는 `num_frames.` 길이의 노이즈 제거된 PIL 이미지 시퀀스가 포함됩니다. 또한 `(batch_size, num_frames, channels, height, width)` 형상의 NumPy 배열 또는 Torch 텐서일 수도 있습니다.

EasyAnimate 파이프라인의 출력 클래스입니다.

