Replicate チュートリアル: AIモデルを実行して画像を作成する

Replicateのチュートリアルへようこそ!🚀

Replicateは、シンプルなAPIでクラウド上でAIモデルを実行できるプラットフォームです。画像や動画モデルのホスティングと実行に特に強く、GPU管理やモデルデプロイの技術的な複雑さを気にせず、魅力的なビジュアルコンテンツを生成したいクリエイターにとって最適なプラットフォームです。

このノートブックでは、Replicateの重要な概念をカバーし、最初の画像生成モデルの実行までをウォークスルーします。最先端のAIモデルを使用して、テキスト説明からプロ品質の画像を生成するのがいかに簡単かを確認できます。

Replicateの仕組み

Replicateはシンプルな原則で動作します:特定のモデルを実行するためのAPIリクエストを送信し、残りはReplicateが処理します。プロセスの概要は以下の通りです:

  1. モデルの選択: Replicateは、コミュニティによって作成された膨大な公開モデルライブラリをホストしています。画像生成、動画作成、スタイル転送、画像強化などのモデルを閲覧して選択できます。

  2. APIリクエスト: ここで使用するPythonクライアントのようなクライアントライブラリを使用して、Replicate APIにリクエストを送信します。このリクエストには、実行したいモデルと必要な入力が含まれます。

  3. Prediction: Replicateは入力でモデルを実行し、「prediction」を作成します。長時間実行されるモデル(画像や動画生成で一般的)の場合、APIをポーリングしてpredictionのステータスを確認できます。

  4. 出力の取得: predictionが完了すると、画像、動画、テキスト、またはその他のファイルとして出力を取得できます。Replicateは、大きなメディアファイルの処理と、生成されたコンテンツの信頼性の高いURLの提供に優れています。

セットアップ

まず、必要なPythonライブラリをインストールしましょう。Replicate APIとの対話にはreplicateを、APIキーの管理にはpython-dotenvを使用します。

# %pip install replicate python-dotenv -q

APIキー

Replicate APIを使用するにはAPIキーが必要です。Replicateアカウント設定から取得できます。

セキュリティのため、APIキーは.envファイルに保存するのがベストプラクティスです。このノートブックと同じディレクトリに.envという名前のファイルを作成し、以下の行を追加してください:

REPLICATE_API_TOKEN="your_api_key_here"

では、.envファイルからAPIキーを読み込み、環境変数として設定します。

import os
from dotenv import load_dotenv

load_dotenv()

# The replicate library automatically looks for the REPLICATE_API_TOKEN environment variable.
# So, you don't need to explicitly pass it to the client.
True

モデルの実行

セットアップが完了したら、モデルを実行しましょう!テキストプロンプトから画像を生成するために、Stable Diffusionモデルを使用します。

import replicate

# Run the Stable Diffusion model to generate an image
print("Generating image with Stable Diffusion...")
output = replicate.run(
    "stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf",
    input={"prompt": "a photograph of an astronaut riding a horse"}
)
# Convert the output to a list and extract the URL string
output_list = list(output)
if output_list and len(output_list) > 0:
    # Convert FileOutput to string URL
    image_url = str(output_list[0])
    print(f"Generated image URL: {image_url}")
else:
    print("No image was generated.")
    image_url = None
Generated image URL: https://replicate.delivery/yhqm/w7g9AEduCgZZI1kWKic6GvcF0Upd0eZz2vTI4Dzh0HWuLjkKA/out-0.png

replicate.run()関数はモデルの出力を返します。この場合、生成された画像へのURLです。画像を表示しましょう。

# Display image with custom size
from IPython.display import Image, display

if image_url:
    print("Displaying generated image with custom size:")
    display(Image(url=image_url, width=400, height=300))
else:
    print("No image available to display. Please run the previous cell first.")
Displaying generated image with custom size:

長時間実行されるモデルのPrediction取得

一部のモデルの実行には時間がかかることがあります。そのような場合は、replicate.predictions.create()とprediction.wait()を使用して、モデルを実行し結果を待つことができます。

prediction = replicate.predictions.create(
    version="db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf",
    input={"prompt": "a 19th-century portrait of a robot in a suit"}
)

# Wait for the prediction to complete
prediction.wait()

# Print the output
print(prediction.output)
['https://replicate.delivery/yhqm/MfxCBc67zJXtIyHjfb3DGaguYNrpbpH3PYMGumhAxRXjcGJVA/out-0.png']
from IPython.display import Image

# Display the prediction result
if prediction.output and len(prediction.output) > 0:
    # Convert FileOutput to string URL
    prediction_image_url = str(prediction.output[0])
    print(f"Prediction image URL: {prediction_image_url}")
    display(Image(url=prediction_image_url, width=400, height=300))
else:
    print("No prediction output available.")
Prediction image URL: https://replicate.delivery/yhqm/MfxCBc67zJXtIyHjfb3DGaguYNrpbpH3PYMGumhAxRXjcGJVA/out-0.png

まとめ

おめでとうございます!Replicateを使用してAIモデルを実行する基本を学びました。以下ができるようになりました:

  • 環境をセットアップし、APIキーを安全に管理する。
  • モデルを実行して出力を取得する。
  • 長時間実行されるpredictionを処理する。

ここからは、Replicateウェブサイトの膨大なモデルライブラリを探索し、独自のプロジェクトに統合できます。