xxxxxxxxxx
61
HUGGINGFACE_API_TOKEN = "";
const LABEL_POSITIVE = "LABEL_1";
const textForm = document.getElementById("textForm");
const textInput = document.getElementById("textInput");
const resultElement = document.getElementById("result");
textForm.onsubmit = function (event) {
event.preventDefault();
const text = textInput.value;
query({ inputs: text, options: { wait_for_model: true } })
.then((response) => handleSentimentResponse(response, text))
.catch((error) => console.error(error));
textInput.value = "";
};
async function query(data) {
try {
const response = await fetch(
"https://api-inference.huggingface.co/models/matthewburke/korean_sentiment",
{
headers: { Authorization: `Bearer ${HUGGINGFACE_API_TOKEN}` },
method: "POST",
body: JSON.stringify(data),
}
);
if (!response.ok)
throw new Error(`[${response.status}] 서버에서 응답을 받지 못했습니다.`);
return await response.json();
} catch (error) {
throw error;
}
}
function handleSentimentResponse(response, text) {
const positiveScore = response[0].find(
(item) => item.label === LABEL_POSITIVE
).score;
const negativeScore = 1 - positiveScore;
const isPositive = positiveScore > negativeScore;
// console.log("text", text);
// console.log("response", response);
// console.log("positiveScore", positiveScore);
// console.log("negativeScore", negativeScore);
// console.log("isPositive", isPositive);
updateUI(text, isPositive, isPositive ? positiveScore : negativeScore);
}
function updateUI(text, isPositive, score) {
const emotion = isPositive ? "긍정" : "부정";
resultElement.innerText = `[${text}] ${emotion}: ${score}`;
resultElement.style.color = isPositive ? "green" : "red";
console.log(resultElement.innerText)
sketchp5.changePotato(text, isPositive, score);
}