import torch
from diffusers import WanImageToVideoPipeline
from diffusers.utils import export_to_video
import time
from PIL import Image

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

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

pipe.enable_model_cpu_offload()
pipe.vae.enable_tiling()
pipe.vae.enable_slicing()

# 入力画像
image = Image.open("input.png").convert("RGB")

# プロンプト
prompt = """
The reference image shows a motorcycle and rider continuing deeper into the forest along a trail. The motorcycle follows the unpaved road into the woods, gradually becoming smaller as it recedes into the distance. Features include natural off-road riding movements, realistic suspension movements, slight dust and pebbles kicked up by the rear wheel, cinematic camerawork, stable composition, natural lighting, a detailed forest background, smooth movement, consistent motorcycle shape, the same rider, same clothing, and the same motorcycle color and design as in the reference image.
"""

# ネガティブプロンプト
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(
    # 入力画像
    image=image,
    prompt=prompt,
    negative_prompt=negative_prompt,
    width=960,
    height=544,
    num_frames=81,
    num_inference_steps=30,
    guidance_scale=5.0,
  )

elapsed_time = time.perf_counter() - start_time

frames = result.frames[0]

# 保存
export_to_video(
  frames,
  "i2v_test1_output.mp4",
  fps=16,
)

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