ChatGPTとOpenWeatherMapを使ってみる

OpenAIのChatGPTが話題になっているので使ってみました。特にプログラミングが優秀との事だったので、天気を取得するプログラミングを行ってもらうことにしました。

実際にプログラムでやってみたい事がいろいろとあってChatGPTをいろいろと使ってみたのだけれど、例えばRaspberrypiPicoをはめ込んで使う「Pico RGB Keypad Base」とか、Mastodonのログ(tooto)を収集して時系列に表示するとかいろいろと試したのですが、思うように文章を解釈してくれない。英語で尋ねてみたけど説明を多少追加した程度では思ったようなスクリプトは作ってくれませんでした。
自分の語彙力も含めて、真っ当に動作しそうなスクリプトが天気取得プログラムでした。

■参考サイト
OpenWeatherのAPIを使ってみる
https://dev.classmethod.jp/articles/openweather_-pyowm/


■chatGPT(OpenAI)
https://chat.openai.com/chat
■OpenWeatherMap
https://openweathermap.org/

ChatGPTは使用するのに登録が必要なんだけど、chromeブラウザを使ったところMicrosoftアカウントでログインすることができなかった。ページが固まってしまいました。その為、MicrosoftEdgeを使いました。他の方法でアカウントを作れば行けるのかもしれないが、試していません。

ChatGPTに質問するにあたってWeb上で動かすのでPHPを指定しました。
情報源に関して特に指定しなかった場合にOpenWeatherMapから情報を取得するスクリプトを作ったのでOpenWeatherMapのユーザー登録をしてAPIKyeを取得しました。他にスクレイピングも考えましたが、APIを提供していないサイトから定期的に情報を取得した場合、最悪は悪質な嫌がらせと判断されてアクセスを止められる可能性もあるので、ここは素直にOpenWeatherMapを使うことにしました。

以下がそのスクリプトになります。

<?php

// Replace with your OpenWeatherMap API key
$api_key = "your_api_key_here";

// Define the city you want to retrieve the weather for (in this case, Tokyo)
$city = "Tokyo,JP";

// Define the API endpoint
$endpoint = "http://api.openweathermap.org/data/2.5/weather?q=" . $city . "&appid=" . $api_key;

// Use curl to make a GET request to the API endpoint
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Store the response from the API
$response = curl_exec($ch);

// Decode the JSON response into an array
$weather = json_decode($response, true);

// Extract the values you're interested in from the array
$temperature = $weather["main"]["temp"] - 273.15; // Convert from Kelvin to Celsius
$humidity = $weather["main"]["humidity"];
$condition = $weather["weather"][0]["main"];

// Print the values
echo "Temperature: " . $temperature . "°C\n";
echo "Humidity: " . $humidity . "%\n";
echo "Condition: " . $condition . "\n";

?>

上記のスクリプトを元にして使いやすいように改造しました。

使用する時に5分に一回呼び出すスクリプトに組込む予定なので、OpenWeatherMapに迷惑が掛からないように5時間以内は保存した情報を読み込むことにしました。

保存するテキストを自動で生成するようにして、そこに時間と気象内容を保存しました。

表示が英語だったので、日本語に変更して温度、湿度、天気としました。

形式上はWebで表示させるのでエンコード等、ヘッダー等のタグの形式を整えました。

改造したスクリプトが以下になります。

<?php
###PHPファイル自体のエンコード
define(INTERNAL_ENC    ,"UTF-8");
##出力時のエンコード
define(OUTPUT_ENC      ,"UTF-8");
##エスケープシーケンス除去
ini_set("magic_quotes_gpc", "off");

$filename='weather.txt';

// 時間計算の為のファイル作成
if(!file_exists($filename)) {touch($filename);}
$weather_=@file($filename,FILE_IGNORE_NEW_LINES);
if($weather_==""){$weatherdata_[0]=time()-20000;}

//五時間以上経っていたら
if($weather_[0]+18000 < time() ){

// Replace with your OpenWeatherMap API key
$api_key = "取得したAPI KEY";

// Define the city you want to retrieve the weather for (in this case, Tokyo)
$city = "Tokyo,JP";

// Define the API endpoint
$endpoint = "http://api.openweathermap.org/data/2.5/weather?q=" . $city . "&appid=" . $api_key;

// Use curl to make a GET request to the API endpoint
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Store the response from the API
$response = curl_exec($ch);

// Decode the JSON response into an array
$weather = json_decode($response, true);

// Extract the values you're interested in from the array
$temperature = $weather["main"]["temp"] - 273.15; // Convert from Kelvin to Celsius
$humidity = $weather["main"]["humidity"];
$condition = $weather["weather"][0]["main"];

// Print the values
$weather ="気温: " . $temperature . "℃ ";
$weather = $weather . "湿度: " . $humidity . "% ";
$weather = $weather . "天気: " . $condition;


  $HANDLE = fopen( 'weather.txt', "w");
  flock ($HANDLE, 2);
  rewind ($HANDLE);
  ftruncate ($HANDLE, '0');
  fputs ($HANDLE, time(). "\n" . $weather);
  flock ($HANDLE, 3);
  fclose ($HANDLE);
  @ chmod ('weather.txt',0666);

}else{

$weather = $weather_[1];

}


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML><HEAD>
<META http-equiv="Content-Type" content="text/html; charset=<?=OUTPUT_ENC?>">
<META http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="refresh" content="600">
<title>Tokyo-Weather</title>

</head><body>
<p>
<?php

echo $weather;

?>

</body></html>

■まとめ

今回のお天気スクリプトは、自分で改造したんですけど、chatGPTが全部作ることができるように指示が出せると良いですね。

必要に応じて都市名を変えれば良いので、都市名のファイル名にして必要に応じて都市の天気を呼び出せると便利なのかもしれません。

OpenWeatherMapはまだまだいろいろな機能があるようなので、もう少し違った情報を呼び出せるスクリプトも面白いかもしれません。


投稿日

カテゴリー:

投稿者:

コメント

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です