CUDAWebAPP / index.php
KazukiIz's picture
Update index.php
f34351e verified
raw
history blame
3.71 kB
<!DOCTYPE html>
<html>
<head>
<title>CodeLlamaによる問題生成テストサイト</title>
</head>
<body>
<h1>CodeLlamaによる問題生成テストサイト</h1>
<?php
// Hugging Face APIトークンとAPIエンドポイント
$apiToken = getenv('YOUR_HUGGING_FACE_API_TOKEN');
$modelName = 'elyza/ELYZA-japanese-CodeLlama-7b-instruct'; // 使用するモデル名【変更可能】
// APIエンドポイント
$url = "https://api-inference.huggingface.co/models/$modelName";
// フォームがPOSTメソッドで送信されると処理を実行(&空じゃないかチェック)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['inputs'])) {
$inputs = $_POST['inputs'];
// cURLを使用してリクエストを送信
// cURLセッションを初期化
$ch = curl_init($url);
// cURLでSSL証明書の検証をスキップする【一時的に】
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
if(curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
// cURLの状態確認
if ($ch) {
echo "cURLは使えます。";
curl_close($ch);
} else {
echo "Failed to initialize cURL.";
}
// APIのURLを設定
curl_setopt($ch, CURLOPT_URL, $url);
// API応答を文字列で返す設定
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// POSTリクエストを指定
curl_setopt($ch, CURLOPT_POST, true);
// HTTPヘッダー(APIトークン、コンテンツタイプを指定)
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiToken,
'Content-Type: application/json'
]);
// 【後で変更】フォーム入力とプロンプトのテンプレートを、一部を変数化し、組み合わせる
echo "APIに送信する文章\n";
// APIに送信するデータをJSON形式で指定
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
"inputs" => $inputs,
// 生成テキストの最大長
"max_tokens" => 10000,
// パラメータ類
"temperature" => 0.3 // 応答のランダム性
]));
// cURLリクエストを実行、APIの応答を変数responseに取得
echo $response = curl_exec($ch);
ini_set('max_execution_time', '300'); // 最大実行時間の設定(5分)
// cURLエラーが発生した場合のチェック
if (curl_errno($ch)) {
echo "<div class='response'>Error: " . curl_error($ch) . "</div>";
} else {
// 【JSON形式のAPI応答を連想配列に変換(?)】
$result = json_decode($response, true);
// 整形用処理
$response = str_replace('[{"generated_text":"', PHP_EOL, $response);
$response = str_replace('"}]', PHP_EOL, $response);
$response = str_replace('\n', PHP_EOL, $response);
$response = str_replace('\r', PHP_EOL, $response);
$response = str_replace('\t', PHP_EOL, $response);
}
// cURLセッションを終了し、リソースを開放
curl_close($ch);
}
?>
<!-- 問題を表示する部分 -->
<h2>生成文章(問題文の表示ウィンドウにする予定)</h2>
<?php
echo "<textarea id=\"response\" readonly rows=\"30\" cols=\"80\" style=\"font-size: 20px;\">" . htmlspecialchars($response) . "</textarea>";
?>
<!-- 出力推定問題における回答フォームの部分 -->
<div class="container">
<form method="POST">
<label for="inputs">APIに送信する文章:</label>
<textarea id="inputs" name="inputs" rows="20" cols="40" style="font-size: 25px;"required></textarea>
<button type="submit">Submit</button>
</form>
</body>
</html>