스타일 리스트
스타일 종류 | 결과값 설명 | 비고 |
---|---|---|
도시락 | ||
홈레스토랑 | ||
집들이 요리 | 여러 명이 먹을 수 있도록 대용량으로 만들 수 있는 | |
헬스식단 | 단백질 위주, 건강 식단으로 보여줌 | |
현재는 안해도 괜찮음. 추후에 다시 고민하는 것으로
→ 현재 시점에서는 그냥 선호도 기록만 (as of August 7, 2023)
업데이트 코드:
function processInputDict(inputDict){
let countries = ["Korean","Italian","Chinese","Japanese","Indian","French","Mexican","Thai","Spanish","Greek","Vietnamese"];
let p = Array(countries.length).fill(0.5 / (countries.length - 1));
p[0] = 0.5;
let sum = p.reduce((a, b) => a + b, 0);
p = p.map(x => x / sum); // Normalize the probabilities
// If no country is chosen, generate one (or two if creative)
if (inputDict["countryStyle"].length === 0) {
let chosenCountries = [];
if (inputDict["creativity"].includes("creative")) {
// Choose two countries randomly, based on the probabilities
while (chosenCountries.length < 2) {
let index = Math.floor(Math.random() * countries.length);
if (!chosenCountries.includes(countries[index])) {
chosenCountries.push(countries[index]);
}
}
} else {
// Choose one country randomly, based on the probabilities
let index = Math.floor(Math.random() * countries.length);
chosenCountries.push(countries[index]);
}
inputDict["countryStyle"] = chosenCountries;
}
};
function getPrompts(inputDict,personalTokens,korean=true){
// Create the prompts
let prompt1 = `Give a ${inputDict["creativity"]} ${inputDict["countryStyle"].join(" and ")} style recipe`;
if (inputDict["includeIngredients"].length > 0) {
prompt1 += `including ${inputDict["includeIngredients"].join(", ")}`;
}
if (inputDict["excludeIngredients"].length > 0) {
if (inputDict["includeIngredients"].length > 0) {
prompt1 += " but ";
}
prompt1 += `without ${inputDict["excludeIngredients"].join(", ")}`;
}
if (inputDict["countryStyle"].length > 1) {
prompt1 += `. Make sure the ${inputDict["countryStyle"].length} styles are all clear.`;
}
let prompt2 = "Any other considerations? ";
let prompt3 = "";
if (inputDict["personalTokens"].length === 0 && inputDict["style"].length === 0) {
prompt3 = "Nothing else.";
} else {
if (inputDict["style"].length !== 0){
prompt3 = `Try to make it ${inputDict["style"].join(", ")}. `;
}
if (inputDict["personalTokens"].length !== 0) {
prompt3 += `This person usually likes ${inputDict["personalTokens"].join(", ")} food.`;
}
}
let prompt4 = "In what format do you want the answer?";
let prompt5 = "Give the title of the dish"+(korean ? " in Korean":"")+", skip a line, give the list of ingredients"+(korean ? " in Korean":"")+", skip a line, give the instructions"+(korean ? " in Korean":"")+", "
prompt5 += "skip a line, give an english prompt under 60 words which can be used to generate an image of this dish, skip a line, suggest 5 words summarizing this dish, ";
prompt5 += "skip a line, suggest three other dish names with the same criterion, just the name"+(korean ? ", in Korean":"")+".";
console.log("PROMPT:")
console.log(prompt1);
console.log(prompt2);
console.log(prompt3);
console.log(prompt4);
console.log(prompt5);
return [prompt1,prompt2,prompt3,prompt4,prompt5];
};
async function runChatGPT(prompts){
const chatCompletion = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompts[0] },
{ role: "assistant", content: prompts[1] },
{ role: "user", content: prompts[2] },
{ role: "assistant", content: prompts[3] },
{ role: "user", content: prompts[4] }],
});
return chatCompletion
}
function parseChatCompletion(chatCompletion){
console.log(chatCompletion.data.choices[0].message["content"]);
let output = chatCompletion.data.choices[0].message["content"].split("\\n\\n");
si=0;
var obj = new Object();
try{
obj.title = output[si+0].trim().split(":")[1];
obj.ingredients = output[si+1].trim();
obj.instructions = output[si+2].trim();
obj.imagePrompt = output[si+3].trim().split(":")[1].trim();
obj.summary = output[si+4].trim().split(":")[1].trim();
obj.otherDishes = output[si+5].trim().split(":")[1].trim().split("\\n");
obj.error = 0;
} catch (error) {
obj.error = 1;
}
return obj
};
async function get_results(inputDict,personalTokens,korean=true,save=false){
processInputDict(inputDict);
prompts=getPrompts(inputDict,personalTokens,korean=korean);
chatCompletion=runChatGPT(prompts);
chatCompletion=await chatCompletion;
output=parseChatCompletion(chatCompletion);
var results = new Object();
results.input=inputDict;
results.prompts=prompts;
results.korean=korean;
results.output=output;//parse_output(chatCompletion);
resultsString = JSON.stringify(results);
//결과 저장
if (save){
const fs = require('fs');
const currentTime = new Date();
const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' };
const currentTimeString = currentTime.toLocaleString('en-US', options).replace(/\\D/g, '');
fs.writeFile('./data/'+currentTimeString+'Kr.json', resultsString, 'utf8', (err) => {
if (err) {
console.error('Error saving JSON:', err);
} else {
console.log('JSON saved successfully.');
}
});
}
return results;
}
/*
#########################
*/
//API 셋업
const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
//인풋 셋업, 창의성은 필수, 나머지는 선택, 퍼스널 토큰은 자동(여기에서는 랜덤으로 3개까지)
let inputDict = {
"creativity": "creative",
"countryStyle": [],
"personalTokens": [],
"style": [],//"healthy", "protein-based", "no-carbs"
"includeIngredients": [],
"excludeIngredients": []
};
//퍼스널 토큰 3개 랜덤으로 뽑기
let personalTokens = ["deep-fried", "stew", "grilled", "spicy", "sweet", "raw", "warm", "comfort", "greasy", "pickled", "high-protein", "soup"];
let chosenTokens = [];
n_token= Math.floor(Math.random() * 3) + 1
while (chosenTokens.length < n_token) {
let index = Math.floor(Math.random() * personalTokens.length);
if (!chosenTokens.includes(personalTokens[index])) {
chosenTokens.push(personalTokens[index]);
}
}
inputDict["personalTokens"] = chosenTokens;
//실행
results=get_results(inputDict,personalTokens,korean=true,save=false);
@Hyun Jun Park 업데이트된 코드입니다.
API랑 엮인 부분은 모두 runChatGPT(prompts)안에 있습니다.