【PHP WordPress】ChatGPTと画像や音声ファイルをやり取り
AIをアプリやチャットbotに実装を検討している人もいると思いますが、実際のところ費用的に難しく、既存のサイトに導入できないか考えている人もいると思います。
その中でもWordPressは世界的に利用されており、サイトにAIを導入できないか考えていると思います。
まずはヘッダー。API連携するのに必要なデータです。
$header = array(
'Authorization: Bearer ' . $API_KEY,
'Content-type: application/json',
);
次に画像生成のパラメータ
$text = "ごはん";
$params = json_encode(
array(
'model' => "dall-e-3",
'prompt' => $text,
'size' => "1024x1024",
'quality' => "standard",
'n' => 1
)
);
$curl = curl_init('https://api.openai.com/v1/images/generations');
テキスト生成の場合のパラメータ
$text = "ごはん";
$params = json_encode(
array(
'model' => "tts-1-hd",
'voice' => "alloy",
'input' => $text,
'speed' => 1,
'response_format' => "mp3"
)
);
$curl = curl_init('https://api.openai.com/v1/audio/speech');
ヘッダーとパラメータをセットし、API連携
$options = array(
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_BINARYTRANSFER => true,
);
curl_setopt_array($curl,$options);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
ChatGPTが生成した画像をWordPressのメディアライブラリに保存して、そのフルパスを返す。
if (200 == $httpcode) {
$json_array = json_decode($response, true);
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
$url = $json_array['data'][0]['url'];
$ch1 = curl_init($url);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, 0);
$data = curl_exec($ch1);
curl_close($ch1);
$ext = pathinfo($url, PATHINFO_EXTENSION);
if (empty($ext)) {
$ext = 'jpeg';
}
$tempPath = tempnam(sys_get_temp_dir(), 'image') . '.' . $ext;
file_put_contents($tempPath, $data);
$file = array(
'name' => basename(parse_url($url, PHP_URL_PATH)),
'tmp_name' => $tempPath
);
$id = media_handle_sideload($file, 0);
if (is_wp_error($id)) {
@unlink($file['tmp_name']);
$return_value = $id;
$type = "text";
}
$src = wp_get_attachment_url($id);
return = $src;
}else{
return = "メンテナンス中";
}
ChatGPTが生成した音声ファイルをWordPressのメディアライブラリに保存して、そのフルパスを返す。
if (200 == $httpcode) {
$json_array = json_decode($response, true);
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
$temp_file = tempnam(sys_get_temp_dir(),'tts');
file_put_contents($temp_file, $response);
$file = array(
'name' => basename($temp_file) . '.mp3',
'type' => 'audio/mpeg',
'tmp_name' => $temp_file,
'error' => 0,
'size' => filesize($temp_file),
);
$id = media_handle_sideload($file, 0);
unlink($temp_file);
$src = wp_get_attachment_url($id);
return = $src;
}else{
return = "メンテナンス中";
}
ここから先は
0字
メンバーシップ加入で、全ての記事が閲覧できます。