import torch
from diffusers import WanPipeline
from diffusers.utils import export_to_video
import time

MODEL_ID = "Wan2.2/Wan2.2-TI2V-5B-Diffusers"

pipe = WanPipeline.from_pretrained(
  MODEL_ID,
  torch_dtype=torch.bfloat16,
)

# GPUのVRAMが足りないので、CPUオフロードを使う
pipe.enable_model_cpu_offload()
# VAEのメモリー使用量を削減するための設定
pipe.vae.enable_tiling()
pipe.vae.enable_slicing()

# プロンプト
prompt = """
Under a clear blue sky, a young woman is happily running along the sandy beach. Her hair and light clothing flutter in the sea breeze, and the waves gently lapping against the shore. A natural, smooth run, bright sunshine, and a refreshing summer atmosphere. The camera moves smoothly, following the woman beside her. Cinematic imagery, high definition, and natural motion.
"""

# ネガティブプロンプト
negative_prompt = """
Low image quality, blur, noise, flickering, dropped frames, unnatural movements, awkward running, distorted limbs, extra limbs, facial distortion, body distortion, multiple characters, changes in clothing, distorted background, violent camera shake, abrupt scene changes, dark images, cloudy skies, rain, text, logos, watermarks
"""

# 計測開始
start_time = time.perf_counter()

# 動画生成（推論）
with torch.inference_mode():
  result = pipe(
    # プロンプト
    prompt=prompt,
    # ネガティブプロンプト
    negative_prompt=negative_prompt,
    # 解像度
    width=960,
    height=544,
    # 生成する総フレーム数
    num_frames=80,
    # 拡散モデルの反復回数
    num_inference_steps=16,
    # プロンプトへの忠実度
    guidance_scale=4.0,
  )

# 計測終了
elapsed_time = time.perf_counter() - start_time

frames = result.frames[0]

# 保存
export_to_video(
  frames,
  "t2v_test1_output.mp4",
  # フレーム/秒
  fps=16  
)

print("動画生成完了")
print(f"生成にかかった時間: {elapsed_time/60:.2f} 分")