v1-images-generations API の Python クイックスタートガイド
この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。
最終更新日 2025年01月24日(金)
Table of Contents
Heroku Managed Inference and Agent アドオンは現在パイロット段階です。パイロットの一環として提供される製品は本番環境での使用を目的としたものではなく、ベータサービスとみなされています。また、https://www.salesforce.com/company/legal/agreements.jsp のベータサービス条件が適用されます。
Stability AI Stable Image Ultra (stability-image-ultra
) モデルを使用すると、説明的なテキストプロンプトから高品質かつ精細な画像を生成できます。このガイドでは、Python を使用して v1-images-generations API にアクセスする方法について説明します。
前提条件
リクエストを行う前に、選択したモデルへのアクセスをプロビジョニングします。
まだインストールされていない場合は、Heroku CLI をインストールします。次に、Heroku AI プラグインをインストールします。
heroku plugins:install @heroku/plugin-ai
画像モデルをアプリにアタッチします。
# If you don't have an app yet, you can create one with: heroku create $APP_NAME # specify the name you want for your app (or skip this step to use an existing app you have!) # Create and attach the image model to your app, $APP_NAME. heroku ai:models:create -a $APP_NAME stability-image-ultra --as DIFFUSION
必要な
requests
パッケージをインストールします。pip install requests
Python のサンプルコード
import requests
import json
import os
import base64
import subprocess
import sys
# Global variables for API endpoint, authorization key, and model ID from Heroku config variables
ENV_VARS = {
"DIFFUSION_URL": None,
"DIFFUSION_KEY": None,
"DIFFUSION_MODEL_ID": None
}
# Assert the existence of required environment variables, with helpful messages if they're missing.
for env_var in ENV_VARS.keys():
value = os.environ.get(env_var)
assert value is not None, (
f"Environment variable '{env_var}' is missing. Set it using:\n"
f"export {env_var}=$(heroku config:get -a $APP_NAME {env_var})"
)
ENV_VARS[env_var] = value
def open_image_file(filename):
"""
Opens an image file using the default image viewer based on the operating system.
"""
try:
if sys.platform == "darwin": # macOS
subprocess.run(["open", filename], check=True)
elif sys.platform == "win32": # Windows
subprocess.run(["start", filename], shell=True, check=True)
elif sys.platform == "linux": # Linux
subprocess.run(["xdg-open", filename], check=True)
else:
print("Automatic image opening is not supported on this platform.")
except Exception as e:
print(f"Failed to open image: {e}")
def parse_image_output(response, payload, open_image=False, filename=None):
if response.status_code == 200:
result = response.json()
if payload.get("response_format", "url") == "base64":
# Generate a default filename if none provided, based on the prompt
if not filename:
filename = payload["prompt"][:20].replace(" ", "_").lower() + ".png"
with open(filename, "wb") as f:
f.write(base64.b64decode(result["data"][0]["b64_json"]))
print(f"Image saved as {filename}")
# Open the image if flag is set
if open_image:
open_image_file(filename)
else:
print("Download the image from:", result["data"][0]["url"])
else:
print(f"Request failed: {response.status_code}, {response.text}")
def generate_image(payload, open_image=False, filename=None):
"""
Generates an image using the Stability AI Stable Image Ultra model and saves it to a file.
Parameters:
- payload (dict): dictionary containing parameters for the image generation
- open_image (bool): flag to open the image automatically after generation
- filename (str): name of the saved file (defaults to a truncated version of the prompt)
Returns:
- saves the generated image to a file and optionally opens it
"""
# Set headers using the global API key
HEADERS = {
"Authorization": f"Bearer {ENV_VARS['DIFFUSION_KEY']}",
"Content-Type": "application/json"
}
endpoint_url = ENV_VARS['DIFFUSION_URL'] + "/v1/images/generations"
response = requests.post(endpoint_url, headers=HEADERS, data=json.dumps(payload))
parse_image_output(response=response, payload=payload, open_image=open_image, filename=filename)
# Example payload
payload = {
"model": ENV_VARS["DIFFUSION_MODEL_ID"],
"prompt": "A surreal landscape with glowing mushrooms under a night sky.",
"aspect_ratio": "16:9",
"output_format": "png",
"seed": 123,
"negative_prompt": "crowded, noisy, chaotic"
}
# Generate the image with the given payload
generate_image(payload, open_image=True)