本日はAIわく、Blender枠です。
〇環境
・Windows11PC
・Blender4.1
〇APIキーの取得とBlender内での使用
APIキーに関しては先日の気を確認ください
Blenderでこのキーを使用するためには次のようなコードを使用します。
今回は翻訳を行います。
api_key = "" #APIキーを入力
api_url = "https://api.openai.com/v1/chat/completions"
def translate_to_english(text):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"model": "gpt-4o-mini", # 最新のgpt-4o-miniモデルを使用
"messages": [{"role": "user", "content": f"Translate the following Japanese text to English, providing only the words: {text}"}], # 単語のみを返すように
"max_tokens": 100
}
response = requests.post(api_url, headers=headers, json=data)
# レスポンスの内容をデバッグ出力
print(f"API Response: {response.status_code} - {response.text}")
if response.status_code == 200:
response_json = response.json()
translated_text = response_json['choices'][0]['message']['content'].strip()
print(f"Translated text: {translated_text}") # 翻訳後のメッセージ
return translated_text
else:
print(f"Error in translation API: {response.status_code}")
return text # エラーが発生した場合は元の名前を返す
このコードを実行することでレスポンスとして投げた日本語が英語で返されて、ログに出力されます。
コードを見てわかるように基本的にChatGPT同様に指示メッセージを投げており、その一部に日本語名を含ませているという形になります。
また、import requestsやimport jsonが必要となります。
これによってtranslate_to_english()の引数に与えた日本語が英語にされ返されます。
本日は以上です。