🌊 WaveSpeed AI: 高性能マルチモーダル生成

WaveSpeed AIのチュートリアルへようこそ。WaveSpeedは、Flux、Wan、Kling、LTXなどの最先端(SOTA)生成モデルを統一された高速APIの背後に集約した、加速に特化した開発者プラットフォームです。

このノートブックで学ぶこと:

  1. 環境の構成: APIキーを安全に読み込みます。
  2. 画像生成(テキストから画像): Fluxモデルを使用して、超高速かつ高品質な画像生成を行います。
  3. 画像の動画化(画像から動画): Wan 2.1またはKlingを使用して、静止画を動画に変換します。
  4. 高度なスタイルの適用: LoRA(Low-Rank Adaptation)を使用して出力をカスタマイズします。

📚 前提条件

始めましょう!

1. セットアップとインストール

まず、WaveSpeed Python SDKと環境変数を管理するユーティリティをインストールする必要があります。また、生成されたメディアをダウンロードして表示するのに役立つrequestsもインストールします。

#!pip install wavespeed python-dotenv requests -q

2. 認証

セキュリティは最も重要です。APIキーをハードコードする代わりに、.envファイルから読み込みます。

必要なアクション:

  1. このノートブックと同じディレクトリに.envという名前のファイルを作成します。
  2. 以下の行を追加します:
    WAVESPEED_API_KEY=ws-xxxxxxxxxxxxxxxxxxxxxxxx
    
  3. 下のセルを実行して読み込みます。
import os
import wavespeed
from dotenv import load_dotenv
from wavespeed import Client

# Load environment variables from .env file
load_dotenv()

api_key = os.getenv("WAVESPEED_API_KEY")
client = Client(api_key=api_key)

if not api_key:
    raise ValueError("API Key not found! Please check your .env file.")

print("✅ API Key loaded successfully.")
✅ API Key loaded successfully.

3. テキストから画像の生成(Flux)

まず、WaveSpeedでFluxモデルを実行して、テキストプロンプトから画像を生成します。

Fluxのパラメータ:

  • prompt: 生成したい画像を説明するテキスト。
  • aspect_ratio: 出力画像のアスペクト比(例:"16:9"、"1:1")。
  • guidance_scale: プロンプトへの忠実度を制御します。
  • num_inference_steps: ノイズから最終画像へ変換する反復回数。
from IPython.display import Image, display
import requests

def download_and_display(url, filename="output.png"):
    """Helper to download and display the generated media."""
    response = requests.get(url)
    if response.status_code == 200:
        with open(filename, 'wb') as f:
            f.write(response.content)
        display(Image(filename=filename, width=600))
        print(f"Saved to {filename}")
    else:
        print(f"Failed to download media: {response.status_code}")

# ------------------------------
# Generate an Image
# ------------------------------

print("🎨 Generating image with Flux...")

try:
    # Note: Model IDs may change. Check wavespeed.ai/models for the latest list.
    # Common IDs: 'wavespeed-ai/flux-dev', 'black-forest-labs/flux-1-dev'
    result = client.run(
        "wavespeed-ai/flux-dev", 
        {
            "prompt": "A cyberpunk street food vendor in Tokyo, neon lights, rain reflections, highly detailed, 8k",
            "aspect_ratio": "16:9",
            "guidance_scale": 3.5, # This controls how strictly the AI adheres to your text prompt; wiht lower value, the AI takes more artistic liberties.
            "num_inference_steps": 20 # This is the number of "passes" the AI makes to clear up the image from noise to a final picture; with lower value, faster generation, but the image might look blurry
        }
    )

    # The output is usually a list of URLs
    image_url = result["outputs"][0]["url"] if isinstance(result["outputs"][0], dict) else result["outputs"][0]
    print(f"Generated URL: {image_url}")
    
    download_and_display(image_url, "flux_result.png")

except Exception as e:
    print(f"Error generating image: {e}")
🎨 Generating image with Flux...
Generated URL: https://d2p7pge43lyniu.cloudfront.net/output/dddc6db7-5fd6-4f50-aad8-98cbee95fb89-u2_a2ee2cb6-a272-4465-9933-6bf95edafe0a.jpeg
Generated URL: https://d2p7pge43lyniu.cloudfront.net/output/dddc6db7-5fd6-4f50-aad8-98cbee95fb89-u2_a2ee2cb6-a272-4465-9933-6bf95edafe0a.jpeg
Saved to flux_result.png

4. 画像から動画の生成(Wan/Kling)

WaveSpeedの最も強力な機能の1つは、Wan 2.1やKlingのような動画生成モデルを高速化することです。これらのモデルは、入力画像(先ほど作成した画像など)を受け取り、プロンプトに基づいてアニメーション化します。

注: 動画生成は画像より時間がかかります(通常30秒〜2分)。SDKは待機処理を代行します。

from IPython.display import Video

# We will use the image URL generated in the previous step.
# If you skipped that step, replace this with any public image URL.
input_image_url = image_url 

print("🎥 Generating video from image... (This may take a minute)")

try:
    # Using Wan 2.1 (Example ID - verify exact ID on the platform)
    # Other popular options: 'kwaivgi/kling-v2.6-i2v'
    video_result = client.run(
        "wan-ai/wan-2.1-i2v-720p", 
        {
            "image_url": input_image_url,
            "prompt": "The vendor cooks food, steam rising, neon lights flickering, cinematic slow motion",
            "negative_prompt": "distortion, blurry, shaking camera",
            "duration": 5  # Duration in seconds (depends on model capabilities)
        }
    )

    video_output_url = video_result["outputs"][0]["url"] if isinstance(video_result["outputs"][0], dict) else video_result["outputs"][0]
    print(f"Video URL: {video_output_url}")

    # Display Video
    display(Video(url=video_output_url, width=600))

except Exception as e:
    print(f"Error generating video: {e}")

5. 高度な機能: LoRA(Low-Rank Adaptation)の使用

WaveSpeedは、LoRAをサポートしており、モデル全体を再訓練することなく、特定のアーティスティックスタイルやキャラクターを生成に適用できます。Hugging FaceやCivitaiでホストされているLoRAを指定できます。

この例では、Flux生成に「Papercut」スタイルのLoRAを適用します。

print("🎨 Generating stylized image with LoRA...")

try:
    lora_result = wavespeed.run(
        "wavespeed-ai/flux-dev",
        {
            "prompt": "A cute robot holding a flower, papercut style, intricate details",
            # LoRA configuration syntax depends on the specific model support
            # WaveSpeed often allows passing a 'loras' list or embedding it in the prompt for some models.
            "loras": [
                {
                    "path": "TheMisto/Misto-Flux-Papercut", # Example HF path
                    "scale": 0.8  # Strength of the LoRA
                }
            ],
            "aspect_ratio": "1:1",
            "guidance_scale": 4.0
        }
    )

    lora_url = lora_result["outputs"][0]["url"] if isinstance(lora_result["outputs"][0], dict) else lora_result["outputs"][0]
    download_and_display(lora_url, "lora_result.png")

except Exception as e:
    print(f"Error with LoRA generation: {e}")

6. 非同期タスク(本番環境向け)

Webアプリケーションを構築する場合、動画の待機中にコードをブロックしたくありません。WaveSpeedはWebhookをサポートしていますが、ローカルではSDKがrun_asyncパターンをサポートしている場合や、標準的なPythonの並行性を使用できます。

以下は、複数のプロンプトを処理するバッチリクエストをどのように構成するかの概念的な例です。

import concurrent.futures

prompts = [
    "A futuristic city on Mars",
    "An underwater civilization"
]

def generate_batch(prompt):
    print(f"Starting: {prompt}...")
    res = wavespeed.run("wavespeed-ai/flux-dev", {"prompt": prompt})
    return res["outputs"][0]

# Run in parallel threads
# Note: Ensure your API tier supports concurrent requests
try:
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        results = list(executor.map(generate_batch, prompts))
    
    print("Batch generation complete!")
    for i, url in enumerate(results):
        print(f"Result {i+1}: {url}")
except Exception as e:
    print(f"Batch processing error: {e}")

📝 まとめ

WaveSpeed AI APIの探索に成功しました!

まとめ:

  • シンプルさ: 複数のモデルに対して1つのrun()関数。
  • 速度: FluxとWanの最適化された推論。
  • 柔軟性: LoRAや画像から動画へのワークフローの簡単な統合。

次のステップ:

  • Model Catalogで新しい追加モデル(Sora 2やVeoなど)を探索。
  • StreamlitやFastAPIアプリに統合。
  • ビジュアルワークフローを好む場合は、ComfyUI Nodeをチェック。