jutor_write / xx.js
youngtsai's picture
save
53e2fad
raw
history blame
109 kB
JS
<script src="https://kit.fontawesome.com/3f4312642f.js" crossorigin="anonymous"></script> <!--YH Personal Paid Account --> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js"></script> <!-- common template behavior --> <script>
// URL Re-direct window.onload = function() {
var currentUrl = window.location.href; var originalDomain = 'edit-dot-gaewordpress-dot-junyiacademy.appspot.com'; var redirectDomain = 'www.junyiacademy.org/event'
if (currentUrl.includes(originalDomain)) { var modifiedUrl = currentUrl.replace(originalDomain, redirectDomain); window.location.href = modifiedUrl; }
};
// show system-level messages function showSysMsg(text_to_display, type) { const messageDiv = document.getElementById("sys_msg_div"); messageDiv.innerHTML = <p>${text_to_display}</p>;
if (type === "sccuess") { messageDiv.style.display = "flex"; messageDiv.style.background = "#67da6f"; } else if (type === "error") { messageDiv.style.display = "flex"; messageDiv.style.background = "#da6767"; } else { // DO NOTHIG}
// Set the timer to hide the message div after 3 seconds setTimeout(hideMessageDiv, 2500);
// Function to hide the message div function hideMessageDiv() { const messageDiv = document.getElementById('sys_msg_div'); messageDiv.style.display = "none"; } }
function showFireworks() {
const fireworkArea = document.querySelector(".firework-area"); fireworkArea.style.display = "block";
// Function to generate a random number between min and max function getRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
// Function to generate a random color function getRandomColor() { const letters = "789ABCDEF"; let color = "#"; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 10)]; } return color; }
// Function to create a firework div and add it to the fireworks area function createFirework() { const firework = document.createElement("div"); firework.className = "firework"; const size = getRandomNumber(10, 40); firework.style.width = ${size}px; firework.style.height = ${size}px; firework.style.backgroundColor = getRandomColor(); const x = getRandomNumber(0, 60 - size); const y = getRandomNumber(0, 60 - size); firework.style.left = ${x}px; firework.style.top = ${y}px; fireworkArea.appendChild(firework); }
// Create 3 to 5 fireworks elements const numFireworks = getRandomNumber(3, 5); for (let i = 0; i < numFireworks; i++) { createFirework(); }
// Apply the animation to the fireworks elements const fireworks = document.querySelectorAll(".firework"); fireworks.forEach((firework) => { firework.style.animation = fireworksAnimation ${getRandomNumber(1, 2)}s ease-out infinite; });
// Hide the fireworks area after 3 seconds setTimeout(() => { fireworkArea.style.display = "none"; }, 2000); }
// change layout function toggleSidebar() { const sidebar = document.querySelector('.sidebar'); sidebar.classList.toggle('collapsed');
const toggle_btn = document.querySelector('.toggle-btn'); toggle_btn.classList.toggle('collapsed');
const message_div = document.querySelector('.messageContainer'); message_div.classList.toggle('collapsed');
const content = document.querySelector('.content'); content.classList.toggle('collapsed');
const footer = document.querySelector('.footerContainer'); footer.classList.toggle('collapsed');
const footerTrans = document.querySelector('.footerTransitionLayer'); footerTrans.classList.toggle('collapsed'); }
function themeSwitch() { const themeContent = document.querySelector('.content'); const themeSidebar = document.querySelector('.sidebar'); const themeMessageDiv = document.querySelector('.messageContainer'); const themeFooter = document.querySelector('.footerContainer'); const themeFooterTrans = document.querySelector('.footerTransitionLayer'); const themeToggleBtn = document.querySelector('.toggle-btn');
themeContent.classList.toggle('dark-theme'); themeToggleBtn.classList.toggle('dark-theme'); themeSidebar.classList.toggle('dark-theme'); themeMessageDiv.classList.toggle('dark-theme'); themeFooter.classList.toggle('dark-theme'); themeFooterTrans.classList.toggle('dark-theme'); }
// create a toggleList function iniToggleList() { const toggleLists = document.querySelectorAll('.toggle-list'); toggleLists.forEach(list =>{ list.style.display = "none"; });
const toggleHeadings = document.querySelectorAll('.toggle-heading'); toggleHeadings.forEach(heading => { heading.addEventListener('click', function() { const list = this.nextElementSibling; list.style.display = list.style.display === 'none' ? 'block' : 'none'; }); });}
iniToggleList();
// Function to check screen size and collapse sidebar when width < 499px function collapseSidebar() { const sidebar = document.querySelector('.sidebar'); const toggle_btn = document.querySelector('.toggle-btn'); const message_div = document.querySelector('.messageContainer'); const content = document.querySelector('.content'); const footer = document.querySelector('.footerContainer'); const footerTrans = document.querySelector('.footerTransitionLayer');
sidebar.classList.add('collapsed'); toggle_btn.classList.add('collapsed'); message_div.classList.add('collapsed'); content.classList.add('collapsed'); footer.classList.add('collapsed'); footerTrans.classList.add('collapsed'); }
function checkScreenSize() { const screenWidth = window.innerWidth; const content = document.querySelector('.content');
if (screenWidth < 580) { // Your function to collapse the sidebar goes here collapseSidebar();
content.addEventListener('click', collapseSidebar); } else { // Your function to expand the sidebar goes here (if needed) content.removeEventListener('click', collapseSidebar); //sidebar.classList.remove('collapsed'); //toggle_btn.classList.remove('collapsed'); //content.classList.remove('collapsed'); } }
window.addEventListener('resize', checkScreenSize);
checkScreenSize();
function saveHtmltoPDF () { var element = document.getElementById("mainContainer"); // work now, could be optimize
let currentDate = new Date(); let options = { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, year: 'numeric', month: 'long', day: 'numeric' }; let formattedDate = currentDate.toLocaleString(undefined, options);var opt = { margin: 1, filename: ${topic}-${formattedDate}.pdf, image: { type: 'jpeg', quality: 0.95 }, html2canvas: { scale: 1 }, jsPDF: { unit: 'cm', format: 'a4', orientation: 'portrait' } };
// New Promise-based usage: html2pdf().set(opt).from(element).save();}
</script>
<!-- common login & valiadation behavior -->
<script> var userData; var xsrfToken; // visit JY-HP first, to save X-KA-FKey into cookie var currentPage = window.location.href; let user_hashed_id; let gpt_model;
jQuery(document).ready(function () {
jQuery.ajax({ url: 'https://www.junyiacademy.org/', method: 'GET', async: false, cache: false, // disable cache to prevent error with browser history-back }).done(function () { xsrfToken = /fkey=([^;])/.exec(document.cookie) ? /fkey=([^;])/.exec(document.cookie)[1] : null; });
// Check User logged-Status let isLogin;
jQuery.ajax({ url: 'https://www.junyiacademy.org/api/v2/user/tracking-identity', method: 'GET', async: false, cache: false, // disable cache to prevent error with browser history back xhrFields: { withCredentials: true }, headers: { 'X-KA-FKey': xsrfToken }, }).done(function (data) { data = data["data"]; isLogin = data["isLoggedIn"]; });
if (isLogin) { jQuery.ajax({ url: 'https://www.junyiacademy.org/api/v2/user', method: 'GET', async: false, cache: false, // disable cache to prevent error with browser history-back xhrFields: { withCredentials: true }, headers: { 'X-KA-FKey': xsrfToken }, }).done(function (resp) { var data = resp.data; userData = data; // filter phantom user out if (!userData['isPhantom'] && !userData['isPrePhantom']) {
// login sccuessful setLogin(false); setLogout(true);
// remove validation @2024/01/23 // if ( isJYer(userData['userId']) || verifyEmail(userData['keyEmail']) || verifyBadge() || verifyBackupEmail(userData['backupEmails']) || verifyBackupEmail(userData['allEmails']) ){ // validate sccuessful if (true) { setJutorPass(true); initProgram();
} else { // validate fail setJutorPass(false); } } }).fail(function (data) {
// 驗證均一登入時發生錯誤 console.log("驗證均一登入時發生錯誤");
}).always(function () {
// Do Nothing }); } else { // 未登入狀態 setLogin(true); setLogout(false);
}
});
function setLogin(flag) {
const loginControl = document.getElementById("loginControlContainer");
if(flag) { // 設置設置登入轉導 const loginLink = document.getElementById("login"); const junyi_login = "https://www.junyiacademy.org/login?continue="+ currentPage; loginLink.setAttribute('href', junyi_login);
// 設定顯示 loginControl.style.display = "flex";
}else { // 設定隱藏loginControl.style.display = "none"; } }
function setLogout(flag) { const logoutControl = document.getElementById("logoutControlContainer");
if(flag) { // 設定登出均一帳號的程序 jQuery("#logout").click(function (e) { e.preventDefault(); jQuery.ajax({ url: 'https://www.junyiacademy.org/logout?continue='+ currentPage +'"', method: 'GET', async: false, cache: false, // disable cache to prevent error with browser history-back xhrFields: { withCredentials: true }, headers: { 'X-KA-FKey': xsrfToken }, }).done(function () { window.location.replace(currentPage); }); });
// 設定顯示 logoutControl.style.display = "grid";
}else { // 設定隱藏logoutControl.style.display = "none"; }}
function setJutorPass(flag) {
const jutorPassControl = document.getElementById("JutorPassControlContainer"); const mainControl = document.getElementById("mainContainer");
if(flag) { jutorPassControl.style.display = "none"; mainControl.style.display = "flex"; } else { jutorPassControl.style.display = "block"; mainControl.style.display = "none";} }
function isJYer(userId) { var pattern = /(googleid.junyiacademy.org)/; // Regular expression pattern to match "googleid.junyiacademy.org" in para "user_id". return pattern.test(userId);}
// verify specfic pattern to byPass JutorPass Examination function verifyEmail(email) { var pattern = /(jutor01)|(@tsmc.com$)|(@ilc\.edu\.tw$)|(@tmail.ilc.edu.tw$)|(@smail\.ilc\.edu\.tw$)|(@ufispace.com$)|(@app\.mzu\.kh\.edu\.tw$)/; // Regular expression pattern to match "@junyiacademy.org", "@ilc.edu.tw; @tmail.ilc.edu.tw; @smail.ilc.edu.tw" at the end of the email. return pattern.test(email); }
function verifyBackupEmail(email_array) { var flag = false; //console.log(email_array);
if (email_array.length === 0) { // empty array, do nothing } else { for (const email of email_array) { //console.log(email);
if (verifyEmail(email)) { flag = true; // pass validation, when any email is verified as true } } }
return flag; }
function verifyBadge() {
//api/v2/user/badges var flag = false; // default status
jQuery.ajax({ url: 'https://www.junyiacademy.org/api/v2/user/badges', method: 'GET', async: false, cache: false, // disable cache to prevent error with browser history-back xhrFields: { withCredentials: true }, headers: { 'X-KA-FKey': xsrfToken }, }).done(function (data) {
badgeData = data;
badgeCollections = badgeData['data']['badgeCollections'];
const actBadget_set = badgeCollections.find(item => item.typeLabel.includes('挑戰'));
if (actBadget_set){
const jutorBadge = actBadget_set['badges'].find(item => item.description.includes('JutorBeta 通行證'));
// check if the badge exists and is owned if (jutorBadge && jutorBadge.isOwned) { flag = true; // set flag: true }
} }).fail(function (data) { // Do Nothing}).always(function (data) { // Do Nothing });
return flag;}
// localStorage OPS.
function setCurretLevel(user_id){
let currentlevel = localStorage.getItem('Jutor_Write_current_level'+user_id);
// When activating Jutor for the first time, store the date if(current_level){ // data exists, do nothing. user_selected_level = current_level; }else{ // data does not exist, do initiate. current_level = 'lv_intermediate';
localStorage.setItem('JutorWrite_current_level'+user_id, current_level); user_selected_level = current_level; } }
function updateCurretLevel(userid){ let current_level = localStorage.getItem('Jutor_Write_current_level'+user_id);
// When activating Jutor for the first time, store the date if(currentlevel){ // data exists, do update. current_level = user_selected_level; localStorage.setItem('Jutor_Write_current_level'+user_id, current_level);}else{ // data does not exist, do initiate. setCurretLevel(user_id); }
}
function setTotalTypingTime(user_id){
let totaltime = localStorage.getItem('Jutor_Write_total_time'+user_id);
// When activating Jutor for the first time, initiate the total_time if(total_time){ // data exists, do nothing. totalTypingTime = parseInt(total_time); }else{ // data does not exist, do initiate. total_time = 0;
localStorage.setItem('JutorWrite_total_time'+user_id, total_time); totalTypingTime = parseInt(total_time); } }
function updateTotalTypingTime(user_id){
let totaltime = localStorage.getItem('Jutor_Write_total_time'+user_id);
// When activating Jutor for the first time, initiate the totaltime if(total_time){ // data exists, do update. total_time = totalTypingTime; localStorage.setItem('Jutor_Write_total_time'+user_id, total_time); }else{ // data does not exist, do initiate. setTotalTypingTime(user_id); } }
function setTotalPracticeCnt(user_id){
let totalpractice = localStorage.getItem('Jutor_Write_total_pratice'+user_id);
// When activating Jutor for the first time, initiate the total_time if(total_practice){ // data exists, do nothing. totalPracticeCnt = parseInt(total_practice); }else{ // data does not exist, do initiate. total_practice = 0;
localStorage.setItem('JutorWrite_total_pratice'+user_id, total_practice); totalPracticeCnt = parseInt(total_practice); } }
function updateTotalPracticeCnt(user_id){
let totalpractice = localStorage.getItem('Jutor_Write_total_pratice'+user_id);
// When activating Jutor for the first time, initiate the totaltime if(total_practice){ // data exists, do update. total_practice = totalPracticeCnt; localStorage.setItem('Jutor_Write_total_pratice'+user_id, total_practice); }else{ // data does not exist, do initiate. setTotalPracticeCnt(user_id); } }
function initProgram() {
document.getElementById('user_nickname').innerHTML = userData['nickname'];
user_hashed_id = userData['hashed_unique_id'];
// restore the date of joining Jutor setJoinDate(user_hashed_id);
// restore the maximum consecutive login days setMaxConsecutiveLoginDays(user_hashed_id);
// set the default User level iniUserLevel();
function setJoinDate(user_id){
let joinedDate = localStorage.getItem('Jutor_Write_date_joined'+user_id);
// When activating Jutor for the first time, store the date if(joined_Date){ // data exists, do nothing.
}else{ // data does not exist, do initiate. let currentDate = new Date(); let options = { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, year: 'numeric', month: 'long', day: 'numeric' }; let formattedDate = currentDate.toLocaleString(undefined, options);
localStorage.setItem('JutorWrite_date_joined'+user_id, formattedDate); joined_Date = formattedDate; }
document.getElementById('joined_date').innerHTML = joined_Date; }
function setMaxConsecutiveLoginDays(user_id){
let currentDate = new Date(); // No adjustment by local timezone let loginHistory;
let jsonArray = localStorage.getItem('JutorWrite_login_history'+user_id);
if(jsonArray){ // data exists, add current login record loginHistory = JSON.parse(jsonArray); }else{ // data does not exist, do initiate. loginHistory = []; }
loginHistory.push(currentDate);
localStorage.setItem('JutorWrite_login_history'+user_id, JSON.stringify(loginHistory));
function extractDateOnly(var_timestamp){ const timestamp = new Date(var_timestamp); const dateOnly = new Date(timestamp.getFullYear(), timestamp.getMonth(), timestamp.getDate()); return dateOnly; }
// Function to calculate the maximum consecutive login days function calculateMaxConsecutiveLoginDays(loginHistory) { let maxConsecutiveDays = 0; let currentConsecutiveDays = 0;
loginHistory.sort((a, b) => a - b);
for (let i = 0; i < loginHistory.length; i++) { if (i === 0 || (extractDateOnly(loginHistory[i]) - extractDateOnly(loginHistory[i - 1])) === 24 * 60 * 60 * 1000) { currentConsecutiveDays = currentConsecutiveDays + 1; }
if (currentConsecutiveDays > maxConsecutiveDays) { maxConsecutiveDays = currentConsecutiveDays; } }
return maxConsecutiveDays; }
// Calculate and display the maximum consecutive login days const maxConsecutiveDays = calculateMaxConsecutiveLoginDays(loginHistory);
document.getElementById('max_consecutive_days').innerHTML = maxConsecutiveDays; }
function iniUserLevel(){
// localStorage ops - Level setCurretLevel(user_hashed_id); const active_level_elm = document.getElementById(user_selected_level); // set UI btn active_level_elm.className = "clickable active";
// Get all the clickable elements const spans = document.querySelectorAll('.clickable');
// Add event listeners to each span spans.forEach((span, index) => {
//span.style.backgroundColor = "";
span.addEventListener('click', () => { // Change background colors of the spans spans.forEach((s, i) => { if (i === index) { s.className = "clickable active"; } else { s.className = "clickable"; } }); }); });
// localStorage ops - totalTypingTime; setTotalTypingTime(user_hashed_id); const totalTypingTimeDisplay = document.getElementById("total_time_est"); // set UI elements totalTypingTimeDisplay.textContent = formatTime(totalTypingTime);
// localStorage ops - totalPracticeCnt; setTotalPracticeCnt(user_hashed_id); const totalPracticeCntDisplay = document.getElementById("total_paragraph_cnt"); // set UI elements totalPracticeCntDisplay.textContent = totalPracticeCnt;
}
// here goes to other application initiation
ini_btn_disabled(); iniTimerGropus(); // set timers setLevel(user_selected_level); // set default version from localStorage para. }
</script>
<!-- application behavior --> <script>
let user_selected_level; // bounded to localStorage
// beginning-level - 基礎級定義 let desc_lv1 = beginning-level English that is short, easy-to-understand, commonly used in everyday conversations. Aim for clarity and simplicity, keeping in mind that the audience is comprised of beginning-level students;
// intermediate-level - 實力級定義 let desc_lv2 = intermediate-level English that is more specific and as commonly used in formal books and newspapers. These words should expand upon a general idea or topic.;
// advanced-level - 大師級定義 let desc_lv3 = advanced-level English that is equal to CEFR C2 level vocabulary. These words could be complex, possibly with multiple meanings or specialized usage found in academic, technical, or professional contexts.;
let eng_level; let scenario; let topic; let point_1; let point_2; let point_3; let points; let topicSentenceSelected; let correctFlag; let support_sentence_1; let support_sentence_2; let support_sentence_3; let conclusion_sentence; let paragraph; let paragraph_ai_modification; let paragraph_final; let paragraph_final_ai_modification; let CEFR_label_phase1; let evaluation_phase1; let typingInterval; let typingTimeout; let totalTypingTime; // bounded to localStorage let totalPracticeCnt; // bounded to localStorage let newPracticeToken = false; // 作為一次有效寫作的控制
const LearningTips = [ "擴展詞彙量", "學習文法結構", "寫作後自我檢查", "經常練習寫作", "寫日記練習思考", "學習使用同義詞", "避免使用太長句子", "清晰表達主題句", "使用活躍的語態", "避免重複語詞", "使用範例句型參考", "模仿好的寫作風格", "請他人給予意見", "多練習寫作不同類型", "使用適當的過渡句子", "避免過多的修飾語", "使用具體事例支持", "瞭解寫作目的", "維持一致的時態", "使用清晰的段落結構", "學習英文標點符號", "使用適當的語調", "設定寫作目標", "檢查拼寫和語法", "時常回顧和修正", "研讀英文寫作書籍", "參考英文寫作範本", "學習避免冗言贅字", "交換文章互相評論", "學習使用隱喻與比喻", "閱讀英文報紙、雜誌", "練習精練地叙述故事", "適時使用名言佳句", "瞭解不同風格的寫作", "盡量使用主動語態", "避免過度使用被動態", "學習使用修辭手法", "閱讀並模仿經典文學", "學會撰寫論點明確的論文", "學習正確使用時態", "研究句型與結構變化", "使用適當的連接詞", "避免使用俚語或口語", "使用詞典查找合適詞語", "瞭解受眾與文體要求", "避免使用模糊不清的詞語", "學會使用精確的形容詞", "學習使用範疇與例證", ];
let displayInterval;
// Function to show the Tips div function showTipsTransition() {
let start_pos = Math.floor(Math.random() * LearningTips.length); let displayCount = 0; // Initialize the display count let maxTimes = 15; let isFirstDisplay = true;
const divElement = document.getElementById("tip_msg_div"); divElement.style.display = "flex"; const divElementContent = document.getElementById("tip_msg_div_content");
displayNextString(); displayInterval = setInterval(displayNextString, 6000); // Update every 5 seconds
function displayNextString() { if (displayCount < maxTimes) { //const divElement = document.getElementById("outputDiv"); const nextString = getNextString();
if (!isFirstDisplay) { divElement.classList.add("fade-out"); setTimeout(() => { divElementContent.innerHTML = nextString; divElement.classList.remove("fade-out"); divElement.classList.add("fade-in"); displayCount++;
if (displayCount === maxTimes) { clearInterval(displayInterval); } }, 500); // Time for fade-out animation to complete } else { divElementContent.innerHTML = nextString; divElement.classList.add("fade-in"); isFirstDisplay = false; displayCount++; } } }
function getNextString() { const currentString = LearningTips[start_pos]; start_pos = (start_pos + 1) % LearningTips.length; return currentString; }
}
// Function to hide the Tips div function hideTipsTransition() { clearInterval(displayInterval); // Stop const divElement = document.getElementById('tip_msg_div'); divElement.style.display = "none"; }
function iniTimerGropus (){
const timerGroups = document.querySelectorAll('.timer-group');
timerGroups.forEach((group) => {
const startButton = group.querySelector('.start-button');
const timerDisplay = group.querySelector('.timer-display');
let timerInterval; let seconds = 0; let minutes = 0; let isPaused = true;
function updateTimerDisplay() { timerDisplay.textContent = ${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}; }
function startTimer() { timerInterval = setInterval(() => { seconds++; if (seconds === 60) { seconds = 0; minutes++; } if (minutes === 100) { clearInterval(timerInterval); timerDisplay.textContent = '99:59'; } else { updateTimerDisplay(); } }, 1000); }
function pauseTimer() { clearInterval(timerInterval); isPaused = true; }
function toggleTimer() { if (isPaused) { startButton.innerHTML = '<i class="fa-kit fa-regular-timer-circle-pause"></i>暫停:'; startTimer(); isPaused = false; } else { startButton.innerHTML = '<i class="fa-kit fa-regular-timer-circle-play"></i>繼續:'; pauseTimer(); } }
startButton.addEventListener('click', toggleTimer); }); }
function formatTime(seconds) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); const remainingSeconds = seconds % 60;
const formattedHours = String(hours).padStart(2, "0"); const formattedMinutes = String(minutes).padStart(2, "0"); const formattedSeconds = String(remainingSeconds).padStart(2, "0");
return ${formattedHours}:${formattedMinutes}:${formattedSeconds}; }
function ini_btn_disabled() { // Your JavaScript code to execute on page load goes here // For example, disabling buttons with the "disabledButton" class const disabledButtons = document.querySelectorAll(".inactive_btn"); disabledButtons.forEach((button) => { button.disabled = true; }); }
function setLevel(label) {
user_selected_level = label; // update global variable updateCurretLevel(user_hashed_id); // update localStorage ops. - Level
const step_1 = document.getElementById("step_1"); const step_expert = document.getElementById("step_expert");
if (label ==="lv_beginner"){ eng_level = desc_lv1; step_1.style.display = "flex"; step_expert.style.display = "none";
// flow control navigateToStep(1,"undefined"); } else if (label ==="lv_intermediate") { // default // eng_level = desc_lv2; 難度調整,都降為初級 eng_level = desc_lv1; step_1.style.display = "flex"; step_expert.style.display = "none";
// flow control navigateToStep(1,"undefined"); } else if (label ==="lv_advanced") { // expert_mode 與前兩者流程不同 // eng_level = desc_lv3; 難度調整,都降為初級 eng_level = desc_lv1; step_1.style.display = "none"; step_expert.style.display = "flex";
} else { //do nothing;} //console.log("ENG-level: "+eng_level);
// level control adjustElementsByLevel(label);
function adjustElementsByLevel(level) {
const scenario_mode_typein = document.getElementById("userStep1Mode_0"); // 情境設定,手動輸入 const scenario_mode_select = document.getElementById("userStep1Mode_1"); // 情境設定,清單選擇
const topic_mode_typein = document.getElementById("userStep2Mode_0"); // 主題設定,手動輸入 const topic_mode_select = document.getElementById("userStep2Mode_1"); // 主題設定,清單選擇
const points_mode_beginner = document.getElementById("userStep3Mode_0"); // 要點說明,基礎級; const points_mode_intermediate = document.getElementById("userStep3Mode_1"); // 要點說明,實力級;
const point_div_1 = document.getElementById("point_div_1"); // 要點#1 const point_div_2 = document.getElementById("point_div_2"); // 要點#2 const point_div_3 = document.getElementById("point_div_3"); // 要點#3 const supporting_detail_div_1 = document.getElementById("supporting_detail_div_1"); // 支持句#1 const supporting_detail_div_2 = document.getElementById("supporting_detail_div_2"); // 支持句#2 const supporting_detail_div_3 = document.getElementById("supporting_detail_div_3"); // 支持句#3
const div_ai_grammer_spell_check = document.getElementById("ai_grammer_spell_check"); // AI批改-文法 div_ai_grammer_spell_check.style.display = "block";
if (level === "lv_beginner"){
scenario_mode_typein.classList.remove("show"); topic_mode_typein.classList.remove("show"); scenario_mode_select.classList.add("show"); topic_mode_select.classList.add("show");
points_mode_beginner.classList.add("show"); points_mode_intermediate.classList.remove("show"); point_div_1.style.display = "block"; point_div_2.style.display = "none"; point_div_3.style.display = "none"; supporting_detail_div_1.style.display = "block"; supporting_detail_div_2.style.display = "none"; supporting_detail_div_3.style.display = "none";
} else if (level === "lv_intermediate") {
scenario_mode_typein.classList.add("show"); topic_mode_typein.classList.add("show"); scenario_mode_select.classList.remove("show"); topic_mode_select.classList.remove("show");
points_mode_beginner.classList.remove("show"); points_mode_intermediate.classList.add("show"); point_div_1.style.display = "block"; point_div_2.style.display = "block"; point_div_3.style.display = "block"; supporting_detail_div_1.style.display = "block"; supporting_detail_div_2.style.display = "block"; supporting_detail_div_3.style.display = "block";
} else if (level === "lv_advanced") {
scenario_mode_typein.classList.add("show"); topic_mode_typein.classList.add("show"); scenario_mode_select.classList.remove("show"); topic_mode_select.classList.remove("show");
points_mode_beginner.classList.remove("show"); points_mode_intermediate.classList.add("show"); point_div_1.style.display = "block"; point_div_2.style.display = "block"; point_div_3.style.display = "block";supporting_detail_div_1.style.display = "block"; supporting_detail_div_2.style.display = "block"; supporting_detail_div_3.style.display = "block";} }
}
function swtichInStep(currentStep, switchClass) {
showStep(currentStep);
switch_mode(switchClass);
function switch_mode(mode) {
const mode_ClassName = '.' + mode; const mode_show_ClassName = mode_ClassName +'.show'; // CSS settings
const modes = document.querySelectorAll(mode_ClassName); const num_mode = modes.length;
const show_mode = document.querySelectorAll(mode_show_ClassName); // 確認只有一個 show mode const show_mode_id = show_mode[0].id; // 定位目前顯示的mode
var index = Number((showmode_id.split(""))[1]);
index = (index+1) % num_mode; // 計算下一個要顯示的mode邊號
var nextshow_mode_id = (show_mode_id.split(""))[0]+"_"+String(index);
modes.forEach(m => { m.className = mode; });
document.getElementById(next_show_mode_id).className = mode+' show';
} }
function navigateToStep(nextStep, action) {
// 顯示煙火效果 showFireworks();
// 設定 UIUX 顯現的樣式 showStep(nextStep);
// Call your existing functions or perform any other actions specific to the current step
if (nextStep === 1) { // do nothing; } else if (nextStep === 2) { //getTopicsFromInput(); if (action === "select") { const input = document.getElementById("user_input_select"); scenario = input.value; } else if (action === "typein") { const input = document.getElementById("user_input"); scenario = input.value;} else { // do nothing; }
// to-do? re-write to getSelectedScenario()? const user_selected_scenario = document.getElementById("user_selected_scenario"); user_selected_scenario.innerHTML = ${scenario};
// 對於一次有效寫作練習的控制 newPracticeToken = true;
} else if (nextStep === 3) {
if (action === "select") { // do nothing; 由點選 topic btn 的行為,取得topic的值 } else if (action === "typein") { const input = document.getElementById("user_input_topic"); topic = input.value.trim(); console.log("user_topic: "+topic); } else { // do nothing; }
getSelectedTopic();
} else if (nextStep === 4) { getSelectedPoints(); } else if (nextStep === 5) { getSelectedTopicSentence(); } else if (nextStep === 6) { getFullParagraph(); } else if (nextStep === 7) { getFullParagraphFianl();
} else if (nextStep === 8) { showFinalResult(); //getUserReviseOne(); } else if (nextStep === 9) { //getUserReviseTwo(); } else if (nextStep === 10) { //getUserReviseThree(); } else { console.log("Error: out-of-step"); }
}
function showStep(nextStep) { const steps = document.getElementsByClassName("step_Container"); const user_dialogs = document.getElementsByClassName("user_dialog_Container");
for (let i = 0; i < steps.length; i++) { const step = steps[i]; if (i+1 <= nextStep) { step.style.display = "flex"; } else { step.style.display = "none"; }
const user_dialog = user_dialogs[i]; if (i+1 <= nextStep-1 ) { user_dialog.style.display = "flex"; } else { user_dialog.style.display = "none"; } }}
function nextAiModule(current) {
// 顯示煙火效果 showFireworks();
const div_ai_grammer_spell_check = document.getElementById("ai_grammer_spell_check"); // AI批改-文法 const div_ai_paragraph_refine = document.getElementById("ai_paragraph_refine"); // AI批改-整體改善 const div_ai_coherence_flow_refine = document.getElementById("ai_coherence_flow_refine"); // AI批改-連貫性
if (user_selected_level === "lv_beginner") { // 初階 2步驟批改 // if (current === "ai_grammer_spell_check") {
getUserReviseOne(); // 將使用者的修改,存回共用變數
div_ai_grammer_spell_check.style.display = "block"; div_ai_paragraph_refine.style.display = "block"; div_ai_coherence_flow_refine.style.display = "none";
} else if (current === "ai_paragraph_refine") {
getUserReviseTwo(); // 將使用者的修改,存回共用變數
div_ai_grammer_spell_check.style.display = "block"; div_ai_paragraph_refine.style.display = "block"; div_ai_coherence_flow_refine.style.display = "none";
// end, navigate to next step navigateToStep(8);
} else if (current === "ai_coherence_flow_refine") { // non-exist case; } else { // do nothing. }
} else if (user_selected_level === "lv_intermediate") { // 中階 2步驟批改
if (current === "ai_grammer_spell_check") {
getUserReviseOne(); // 將使用者的的修改的修改,存回共用變數
div_ai_grammer_spell_check.style.display = "block"; div_ai_paragraph_refine.style.display = "block"; div_ai_coherence_flow_refine.style.display = "none";
} else if (current === "ai_paragraph_refine") {
getUserReviseTwo(); // 將使用者的修改,存回共用變數
div_ai_grammer_spell_check.style.display = "block"; div_ai_paragraph_refine.style.display = "block"; div_ai_coherence_flow_refine.style.display = "none";
// end, navigate to next step navigateToStep(8);
} else if (current === "ai_coherence_flow_refine") { // non-exist case; } else { // do nothing. }
} else if (user_selected_level === "lv_advanced") { // 高階 3步驟批改
if (current === "ai_grammer_spell_check") { getUserReviseOne(); // 將使用者的的修改的修改,存回共用變數
div_ai_grammer_spell_check.style.display = "block"; div_ai_paragraph_refine.style.display = "block"; div_ai_coherence_flow_refine.style.display = "none";
} else if (current === "ai_paragraph_refine") { getUserReviseTwo(); // 將使用者的修改,存回共用變數
div_ai_grammer_spell_check.style.display = "block"; div_ai_paragraph_refine.style.display = "block"; div_ai_coherence_flow_refine.style.display = "block";
} else if (current === "ai_coherence_flow_refine") { getUserReviseThree(); // 將使用者的修改,存回共用變數
div_ai_grammer_spell_check.style.display = "block"; div_ai_paragraph_refine.style.display = "block"; div_ai_coherence_flow_refine.style.display = "block";
// end, navigate to next step navigateToStep(8);
} else { // do nothing. }
} else { // error. console.log("Error: func_nextAiModule out of scope") } }
function checkEmptyTextareas() {
const totalTypingTimeDisplay = document.getElementById("total_time_est");
// Internal timer, record total time of typingconst startTypingTimer = () => { if (!typingInterval) { // Check if the interval is not already running typingInterval = setInterval(() => { totalTypingTime += 1; totalTypingTimeDisplay.textContent = formatTime(totalTypingTime); updateTotalTypingTime(user_hashed_id); // localStorage ops. }, 1000); } };
const stopTypingTimer = () => { clearInterval(typingInterval); typingInterval = null; };
clearTimeout(typingTimeout); startTypingTimer();
typingTimeout = setTimeout(() => { stopTypingTimer(); }, 1000); // Stop the timer if no typing detected for 1 second
// flow control for expert-mode const expert_full_paragraph_edit = document.getElementById("expert_full_paragraph_edit").value; document.getElementById("word_count_expert_full_paragraph_edit").textContent = countWords(expert_full_paragraph_edit); // update word counts const expert_btn_1 = document.getElementById("expert_btn_1");
if (expert_full_paragraph_edit.trim() === '') { expert_btn_1.disabled = true; // Disable the button expert_btn_1.className = "inactive_btn"; } else { expert_btn_1.disabled = false; // Enable the button expert_btn_1.className = "active_btn"; }
const expert_textarea_full_paragraph_revised_1 = document.getElementById("expert_textarea_full_paragraph_revised_1").value; document.getElementById("word_count_expert_textarea_full_paragraph_revised_1").textContent = countWords(expert_textarea_full_paragraph_revised_1); // update word counts const expert_btn_2 = document.getElementById("expert_btn_ai_grammer_spell_check"); if (expert_textarea_full_paragraph_revised_1.trim() === '') { expert_btn_2.disabled = true; // Disable the button expert_btn_2.className = "inactive_btn"; } else { expert_btn_2.disabled = false; // Enable the button expert_btn_2.className = "active_btn"; }
const expert_textarea_full_paragraph_revised_2 = document.getElementById("expert_textarea_full_paragraph_revised_2").value; document.getElementById("word_count_expert_textarea_full_paragraph_revised_2").textContent = countWords(expert_textarea_full_paragraph_revised_2); // update word counts const expert_btn_3 = document.getElementById("expert_btn_ai_paragraph_refine"); if (expert_textarea_full_paragraph_revised_2.trim() === '') { expert_btn_3.disabled = true; // Disable the button expert_btn_3.className = "inactive_btn"; } else { expert_btn_3.disabled = false; // Enable the button expert_btn_3.className = "active_btn"; }
// flow control for Step1 const user_input_scenario = document.getElementById("user_input").value; document.getElementById("word_count_user_input").textContent = countWords(user_input_scenario); // update word counts const submitButton_1 = document.getElementById("btn_next_1b");
if (user_input_scenario.trim() === '') { submitButton_1.disabled = true; // Disable the button submitButton_1.className = "inactive_btn"; } else { submitButton_1.disabled = false; // Enable the button submitButton_1.className = "active_btn"; }
// flow control for step2 const user_input_topic = document.getElementById("user_input_topic").value; document.getElementById("word_count_user_input_topic").textContent = countWords(user_input_topic); // update word counts
const submitButton_2 = document.getElementById("btn_next_2a");
if (user_input_topic.trim() === '') { submitButton_2.disabled = true; // Disable the button submitButton_2.className = "inactive_btn"; } else { submitButton_2.disabled = false; // Disable the button submitButton_2.className = "active_btn";
/* const topicButtons = document.querySelectorAll('.topic-button'); topicButtons.forEach(button => { button.classList.remove('active'); }); // reset */ }
// flow control for Step3 const user_input_point_1 = document.getElementById("user_input_point_1").value; const user_input_point_2 = document.getElementById("user_input_point_2").value; const user_input_point_3 = document.getElementById("user_input_point_3").value; const submitButton_3 = document.getElementById("btn_next_3");
if (user_input_point_1.trim() === '' && user_input_point_2.trim() === '' && user_input_point_3.trim() === '') { submitButton_3.disabled = true; // Disable the button submitButton_3.className = "inactive_btn"; } else { submitButton_3.disabled = false; // Enable the button submitButton_3.className = "active_btn"; }
// control visibility of support_detail by user_point const supporting_detail_div_1 = document.getElementById("supporting_detail_div_1"); // 支持句#1 const supporting_detail_div_2 = document.getElementById("supporting_detail_div_2"); // 支持句#2 const supporting_detail_div_3 = document.getElementById("supporting_detail_div_3"); // 支持句#3
if (user_input_point_1.trim() === '') { supporting_detail_div_1.style.display = "none"; } else { supporting_detail_div_1.style.display = "block"; }
if (user_input_point_2.trim() === '') { supporting_detail_div_2.style.display = "none"; } else { supporting_detail_div_2.style.display = "block"; }
if (user_input_point_3.trim() === '') { supporting_detail_div_3.style.display = "none"; } else { supporting_detail_div_3.style.display = "block"; }
// flow control for Step5 const user_topic_sentence = document.getElementById("user_topic_sentence").value; document.getElementById("word_count_user_topic_sentence").textContent = countWords(user_topic_sentence); // update word counts
const user_supporting_sentence_1 = document.getElementById("user_supporting_sentence_1").value; document.getElementById("word_count_user_supporting_sentence_1").textContent = countWords(user_supporting_sentence_1); // update word counts
const user_supporting_sentence_2 = document.getElementById("user_supporting_sentence_2").value; document.getElementById("word_count_user_supporting_sentence_2").textContent = countWords(user_supporting_sentence_2); // update word counts
const user_supporting_sentence_3 = document.getElementById("user_supporting_sentence_3").value; document.getElementById("word_count_user_supporting_sentence_3").textContent = countWords(user_supporting_sentence_3); // update word counts
const user_conclusion_sentence = document.getElementById("user_conclusion_sentence").value; document.getElementById("word_count_user_conclusion_sentence").textContent = countWords(user_conclusion_sentence); // update word counts
const submitButton_5 = document.getElementById("btn_next_5");
let flag = false; if (user_supporting_sentence_1.trim() === '' && user_supporting_sentence_2.trim() === '' && user_supporting_sentence_3.trim() === '') { flag = false; } else { flag = true; }
if (user_topic_sentence.trim() === '' || flag === false || user_conclusion_sentence.trim() === '') { submitButton_5.disabled = true; // Disable the button submitButton_5.className = "inactive_btn"; } else { submitButton_5.disabled = false; // Enable the button submitButton_5.className = "active_btn"; }
// flow control for Step6 const user_full_paragraph_edit = document.getElementById("user_full_paragraph_edit").value; document.getElementById("word_count_user_full_paragraph_edit").textContent = countWords(user_full_paragraph_edit); // update word countsconst submitButton_6 = document.getElementById("btn_next_6");
if (user_full_paragraph_edit.trim() === '') { submitButton_6.disabled = true; // Disable the button submitButton_6.className = "inactive_btn"; } else { submitButton_6.disabled = false; // Disable the button submitButton_6.className = "active_btn"; }
// flow control for Step7 (JUTOR 批改) const textarea_full_paragraph_revised_1 = document.getElementById("textarea_full_paragraph_revised_1").value; document.getElementById("word_count_textarea_full_paragraph_revised_1").textContent = countWords(textarea_full_paragraph_revised_1); // update word counts
const submitButton_7 = document.getElementById("btn_ai_grammer_spell_check");
if (textarea_full_paragraph_revised_1.trim() === '') { submitButton_7.disabled = true; // Disable the button submitButton_7.className = "inactive_btn"; } else { submitButton_7.disabled = false; // Disable the button submitButton_7.className = "active_btn"; }
const textarea_full_paragraph_revised_2 = document.getElementById("textarea_full_paragraph_revised_2").value; document.getElementById("word_count_textarea_full_paragraph_revised_2").textContent = countWords(textarea_full_paragraph_revised_2); // update word counts
const submitButton_8 = document.getElementById("btn_ai_paragraph_refine");
if (textarea_full_paragraph_revised_2.trim() === '') { submitButton_8.disabled = true; // Disable the button submitButton_8.className = "inactive_btn"; } else { submitButton_8.disabled = false; // Disable the button submitButton_8.className = "active_btn"; }
const textarea_full_paragraph_revised_3 = document.getElementById("textarea_full_paragraph_revised_3").value; document.getElementById("word_count_textarea_full_paragraph_revised_3").textContent = countWords(textarea_full_paragraph_revised_3); // update word counts
const submitButton_9 = document.getElementById("btn_ai_coherence_flow_refine");
if (textarea_full_paragraph_revised_3.trim() === '') { submitButton_9.disabled = true; // Disable the button submitButton_9.className = "inactive_btn"; } else { submitButton_9.disabled = false; // Disable the button submitButton_9.className = "active_btn"; }
// Step 8 and after }
function countWords(text) { // Trim any leading or trailing white spaces text = text.trim();
// Split the text into words by using one or more spaces as the delimiter const words = text.split(/\s+/);
// Filter out any empty strings (caused by multiple spaces) const nonEmptyWords = words.filter(word => word !== '');
// Return the number of words in the textarea content return nonEmptyWords.length; }
async function getTopicsFromInput() {
const choicesContainer = document.getElementById("ai_topics"); choicesContainer.innerHTML = '';
const submitButton_2 = document.getElementById("btn_next_2b"); submitButton_2.disabled = true; submitButton_2.className = "inactive_btn";
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill. ;
const usr_promt = ` Give me 10 topics relevent to ${scenario}, for a paragraph. Just the topics, no explaination, use simple English language. Make sure the vocabulary you use is at ${eng_level}.
Translate "${scenario}" into English as #eng_scenario.
The response should strictly be in the below JSON format and nothing else:
{ "scenario" : "#eng_scenario", "topics": [ { "topic": "#topic_1" }, { "topic": "#topic_2" }, ... ] }
`;
let aigc = '';
choicesContainer.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在產生 10 個主題...';aigc = await jutorChat (sys_prompt, usr_promt, "gpt-4-1106-preview", choicesContainer); choicesContainer.innerHTML = '';
// clean the return string. Modify @2023/11/07const cleanedJsonString = aigc.replace(/^json|$/g, '').trim();
// dynamically generates the topic buttons based on the topics const data = JSON.parse(cleanedJsonString);
scenario = data.scenario; //console.log("scenario (processed): "+scenario);
const topics = data.topics;
topics.forEach(topic_item => { const buttonElement = document.createElement("button"); buttonElement.classList.add("topic-button"); buttonElement.textContent = topic_item["topic"]; buttonElement.addEventListener("click", selectTopic);
choicesContainer.appendChild(buttonElement); });
function selectTopic(event) { const topicButtons = document.querySelectorAll('.topic-button');
topicButtons.forEach(button => { button.classList.remove('active'); });
event.target.classList.add('active');
const selectedTopic = event.target.textContent;
topic = selectedTopic;
submitButton_2.disabled = false; submitButton_2.className = "active_btn";
// Perform any further actions based on the selected topic // ... } }
function getSelectedTopic() { const output = document.getElementById("user_selected_topic"); //console.log("topic: "+topic); output.innerHTML = ${topic};
const user_span_topic = document.getElementById("span_topic"); user_span_topic.innerHTML = topic;
const user_sapn_scenario = document.getElementById("sapn_scenario"); user_sapn_scenario.innerHTML = scenario;
}
async function getPointsFromTopic() {
const output = document.getElementById("ai_points"); output.innerHTML = '';
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill. ;
/* Return the result in JSON format. */ const usr_promt = ` Give me seven main points (only keywords, no paragraph, explaination or serial number) to develop in a paragraph about "${topic}" in the context of "${scenario}", use simple English language and not too long.Make sure the vocabulary you use is at ${eng_level}.
Return the result in JSON format as:
{ "mainpoints": [ "main_point#1", "mainpoint#2", "mainpoint#3", "mainpoint#4", "mainpoint#5", "mainpoint#6", "mainpoint#7" ] } `; output.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在產生 7 個關鍵字...';
let aigc = '';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", output );
output.innerHTML = '';
// clean the return string. Modify @2023/11/07const cleanedJsonString = aigc.replace(/^json|$/g, '').trim();
// dynamically generates the topic buttons based on the topics const data = JSON.parse(cleanedJsonString);
const main_points = data["main_points"]
main_points.forEach(point_item => { const buttonElement = document.createElement("button"); buttonElement.classList.add("point-button"); buttonElement.textContent = point_item; buttonElement.addEventListener("click", selectPoint);
output.appendChild(buttonElement);
//console.log(spanElement); });
function selectPoint(event) { // const pointSpans = document.querySelectorAll('.point_span'); const pointSpans = document.querySelectorAll('.point-button');
pointSpans.forEach(point => { point.classList.remove('active'); });
event.target.classList.add('active');
const selectedPoint = event.target.textContent;
// Perform any further actions based on the selected topic copyToClipboard(selectedPoint); const msg = '<i class="fa-solid fa-square-check"></i> 已複製'; showSysMsg(msg, "sccuess"); }
}
function copyUserDivContent(input_div) {
const divTextContent = document.getElementById(input_div).textContent;
copyToClipboard(divTextContent); const msg = '<i class="fa-solid fa-square-check"></i> 已複製'; showSysMsg(msg, "sccuess");
}
// Function to copy the provided text to the clipboard function copyToClipboard(text) { const textArea = document.createElement('textarea'); textArea.value = text; document.body.appendChild(textArea); textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); }
function getSelectedPoints() { point_1 = document.getElementById("user_input_point_1").value.trim(); const user_point_1 = document.getElementById("sapn_point_1"); user_point_1.innerHTML = point_1;
point_2 = document.getElementById("user_input_point_2").value.trim(); const user_point_2 = document.getElementById("sapn_point_2"); user_point_2.innerHTML = point_2;
point_3 = document.getElementById("user_input_point_3").value.trim(); const user_point_3 = document.getElementById("sapn_point_3"); user_point_3.innerHTML = point_3;
let pointsArray = [point_1, point_2, point_3].filter(point => point !== "");
points = pointsArray.join("; ");
const output = document.getElementById("user_selected_points"); output.innerHTML = points;
document.getElementById("points_span_in_step4").innerHTML = points; // document.getElementById("points_span_in_step5").innerHTML = points;
// AI生成主題句選項 getTopicSentencesFromPoints();
}
async function getTopicSentencesFromPoints() {
const topicSentenceContainer = document.getElementById("ai_topic_sentences"); topicSentenceContainer.innerHTML = ''; const infoContainer = document.getElementById("ai_topic_sentences_explainaiton"); infoContainer.innerHTML = ''; const submitButton_4 = document.getElementById("btn_next_4"); submitButton_4.disabled = true; submitButton_4.className = "inactive_btn";
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill on a topic about "${topic}" in the context of "${scenario}". ;
const usr_promt = `
Given the #topic "{scenario}", please provide one appropriate topic sentence that aptly introduces the subject for the given scenario. Additionally, provide two topic sentences that, while related to the topic, would be considered inappropriate or less effective for the specified context. Those sentences must includes the three #main-points: "${points}". Use English language and each sentence should not be too long.
For each sentence, explain the reason in Traditional Chinese, Taiwan, 繁體中文.
Make sure the vocabulary you use is at ${eng_level}.
Only return the result in JSON format starting as: { "0": [ { "topic-sentence": "#","appropriate": "Y/N" "reason": "#中文解釋" } ], "1": [ { "topic-sentence": "#","appropriate": "Y/N" "reason": "#中文解釋" } ], "2": [ { "topic-sentence": "#","appropriate": "Y/N" "reason": "#中文解釋" } ] }
`;
let aigc = '';
topicSentenceContainer.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在寫三個主題句... 請等候約 10 秒';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-4-1106-preview", false);
topicSentenceContainer.innerHTML = '';
// clean the return string. Modify @2023/11/07const cleanedJsonString = aigc.replace(/^json|$/g, '').trim();
// dynamically generates the topic-sentence buttons based on the points const jsonData = shuffleJSONObject(cleanedJsonString);
// Extract "topic-sentence" as the value of buttons and add click event listeners const topicSentences = Object.values(jsonData).flatMap((topicArray) => topicArray.map((topic) => topic["topic-sentence"]));
topicSentences.forEach((topicSentence, index) => { const button = document.createElement("button"); button.classList.add("sentence-button"); button.textContent = topicSentence; topicSentenceContainer.appendChild(button);
button.addEventListener("click", () => { // Remove active class from all buttons const buttons = topicSentenceContainer.querySelectorAll("button"); buttons.forEach((btn) => { btn.classList.remove("active"); });
// Add active class to the clicked button button.classList.add("active");
// Retrieve the corresponding topic object based on the original index const topicObject = jsonData[index][0];
// Retrieve the "topic-sentence" and "appropriate" values from the topic object const selectedTopicSentence = topicObject["topic-sentence"]; const selectedAppropriate = topicObject["appropriate"];
// Display appropriate and reason based on the original index of the selected button const reason = topicObject["reason"];
topicSentenceSelected = selectedTopicSentence; correctFlag = selectedAppropriate;
if (correctFlag === "Y") { infoContainer.innerHTML = '<i class="fa-solid fa-circle-check"></i> 合適:' + reason; infoContainer.style.color = "#67da6f";
submitButton_4.disabled = false; submitButton_4.className = "active_btn"; } else { infoContainer.innerHTML = '<i class="fa-solid fa-circle-xmark"></i> 不合適:' + reason; infoContainer.style.color = "#ff7c7c";
submitButton_4.disabled = true; submitButton_4.className = "inactive_btn"; }
}); });
// Function to shuffle a JSON string function shuffleJSONObject(jsonString) { // Convert JSON object to array const array = Object.values(JSON.parse(jsonString));
// Shuffle the array for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; }
// Convert array back to JSON object const shuffledJson = array.reduce((obj, item, index) => { obj[index] = item; return obj; }, {});
return shuffledJson; }
}
function getSelectedTopicSentence() { const output = document.getElementById("user_selected_topic_sentence"); output.innerHTML = topicSentenceSelected;
const textarea_user_topic_sentence = document.getElementById("user_topic_sentence"); textarea_user_topic_sentence.value = topicSentenceSelected; document.getElementById("word_count_user_topic_sentence").textContent = countWords(textarea_user_topic_sentence.value); // update word counts
}
function showTopicSentence(displayDiv) { const output = document.getElementById(displayDiv); const current_topic_sentence = document.getElementById('user_topic_sentence'); output.innerHTML = current_topic_sentence.value;
if (output.style.display === 'none') { output.style.display = 'block'; } else { output.style.display = 'none'; } } function hideTopicSentence(displayDiv) { const output = document.getElementById(displayDiv); output.innerHTML = '';}
async function getAiSupportSentenceFromPoint (point_span, ai_supporting_sentence_div) {
const input_point = document.getElementById(point_span).innerText;
const output = document.getElementById(ai_supporting_sentence_div); output.innerHTML = '';
//check point not null; if(input_point === '') { // do nothing }else { const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill on a topic about "${topic}" in the context of "${scenario}" . ;
/* Return the result in JSON format. */ const usr_promt = `I'm aiming to improve my writing. I have a topic sentence as "${topicSentenceSelected}". Please assist me by "Developing supporting detials" based on the keyword "${input_point}" to write three sentences as an example.
- Make sure any revised vocabulary aligns with the ${eng_level}. - Guidelines for Length and Complexity: Please keep the example concise and straightforward, avoiding overly technical language. Total word-count is around 50.
The response should strictly be in the below JSON format and nothing else:
{ "example": "supporting detials" } `;
output.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在產生支持句...';
let aigc = '';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", output );
output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 逐筆的修訂與解釋 const example_sentence = jsonObject["example"]; output.innerHTML = example_sentence;
} else { // No JSON format string in response output.innerHTML = aigc; }}
}
async function rephraseSupporting (point_span, ai_supporting_sentence_div, type) {
const input_point = document.getElementById(point_span).innerText;
const original_text = document.getElementById(ai_supporting_sentence_div).textContent;
const output = document.getElementById(ai_supporting_sentence_div); const existing_ai_suggestions = output.innerHTML; // 取得既有內容
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill on a topic about "${topic}" in the context of "${scenario}". ;
const usr_promt = `Please assist me by "Rephrasing" the provided paragraph, make it ${type}.
- Paragraph for Rephrasing: [${original_text}]. This paragraph is a supporting-detail that is developed based on the keyword "${input_point}". Must use the keyword in your modification.
- Make sure any revised vocabulary aligns with the ${eng_level}.
The response should strictly be in the below JSON format and nothing else:
{ "modification": "Rephrasing Paragraph" } `;
output.innerHTML += '<BR><i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在改寫支持句...';
let aigc = '';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", output );
//output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 逐筆的修訂與解釋 const example_sentence = jsonObject["modification"]; //output.innerHTML = example_sentence; output.innerHTML = existing_ai_suggestions + '<p>' + example_sentence + '</p>';
} else { // No JSON format string in response output.innerHTML = existing_ai_suggestions + '<p>' + aigc + '</p>'; }
}
async function getAiConclusionSentence () { const output = document.getElementById('ai_conclusion_sentence'); output.innerHTML = '';
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill on a topic about "${topic}" in the context of "${scenario}". ;
/* Return the result in JSON format. */ const usr_promt = `I'm aiming to improve my writing. I have a topic sentence as "${topicSentenceSelected}". Please assist me by "Developing conclusion sentences" based on keywords: "${points}" to finish a paragrpah as an example.
- Make sure any revised vocabulary aligns with the ${eng_level}. - Guidelines for Length and Complexity: Please keep the example concise and straightforward, avoiding overly technical language. Total word-count is around 20.
The response should strictly be in the below JSON format and nothing else:
{ "example": "conclusion sentences" } `;
output.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在產生結論句...';
let aigc = '';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", output );
output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 逐筆的修訂與解釋 const example_sentence = jsonObject["example"]; output.innerHTML = example_sentence;
} else { // No JSON format string in response output.innerHTML = aigc; } }
async function rephraseConclusion ( ai_supporting_sentence_div, type) {
const original_text = document.getElementById(ai_supporting_sentence_div).textContent;
const output = document.getElementById(ai_supporting_sentence_div); const existing_ai_suggestions = output.innerHTML; // 取得既有內容
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill on a topic about "${topic}" in the context of "${scenario}". ;
const usr_promt = `Please assist me by "Rephrasing" the provided paragraph, make it ${type}.
- Paragraph for Rephrasing: [${original_text}]. This paragraph is a conclusion-sentence that is developed based on keywords: "${points}" to finish a paragraph. Must use these keywords in your modification.
- Make sure any revised vocabulary aligns with the ${eng_level}.
The response should strictly be in the below JSON format and nothing else:
{ "modification": "Rephrasing Paragraph" } `;
output.innerHTML += '<p><i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在改寫結論句...</p>';
let aigc = '';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", output );
//output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 逐筆的修訂與解釋 const example_sentence = jsonObject["modification"]; output.innerHTML = existing_ai_suggestions + '<p>' + example_sentence + '</p>';
} else { // No JSON format string in response output.innerHTML = existing_ai_suggestions + '<p>' + aigc + '</p>'; } }
function getFullParagraph() {
// Composite a full pragraph topicSentenceSelected = document.getElementById('user_topic_sentence').value.trim(); support_sentence_1 = document.getElementById("user_supporting_sentence_1").value.trim(); support_sentence_2 = document.getElementById("user_supporting_sentence_2").value.trim();support_sentence_3 = document.getElementById("user_supporting_sentence_3").value.trim(); conclusion_sentence = document.getElementById("user_conclusion_sentence").value.trim();
let sentencesArray = [topicSentenceSelected, support_sentence_1, support_sentence_2, support_sentence_3, conclusion_sentence].filter(sentence => sentence !== "");
paragraph = sentencesArray.join(" ");
const output = document.getElementById("user_full_paragraph"); output.innerHTML = paragraph;
const textarea_user_full_paragraph_edit = document.getElementById("user_full_paragraph_edit"); textarea_user_full_paragraph_edit.value = paragraph; document.getElementById("word_count_user_full_paragraph_edit").textContent = countWords(textarea_user_full_paragraph_edit.value); // update word counts
const btn_next_6 = document.getElementById("btn_next_6"); btn_next_6.disabled = false; btn_next_6.className = "active_btn";
//generateImageFromArticle(); // 以草稿生成圖片 }
function getFullParagraphFianl() {
paragraph_final = document.getElementById("user_full_paragraph_edit").value.trim();
const output = document.getElementById("user_full_paragraph_final"); output.innerHTML = paragraph_final;
// 完成一次寫作練習 if(newPracticeToken) { totalPracticeCnt += 1;
const totalPracticeCntDisplay = document.getElementById("total_paragraph_cnt"); // set UI elements totalPracticeCntDisplay.textContent = totalPracticeCnt;
updateTotalPracticeCnt(user_hashed_id); } newPracticeToken = false; // controller 避免重複計算
// 產生評價 evaluateArticle_content ('content_level','content_explanation'); evaluateArticle_organization ('organization_level', 'organization_explanation'); evaluateArticle_grammar ('GrammarAndUsage_level', 'GrammarAndUsage_explanation'); evaluateArticle_vocabulary ('Vocabulary_level', 'Vocabulary_explanation'); evaluateArticle_coherence ('CoherenceAndCohesion_level', 'CoherenceAndCohesion_explanation');
paragraph_ai_modification = paragraph_final; // 設定 ai 初始值段落修改的初始值}
function expertGetFullParagraphFianl() {
showFireworks();
paragraph_final = document.getElementById("expert_full_paragraph_edit").value.trim();
const nextDiv = document.getElementById("expert_evaluation_div"); nextDiv.style.display = "flex";
const output = document.getElementById("expert_full_paragraph_final"); output.innerHTML = paragraph_final;
// 初始一次寫作練習 newPracticeToken = true; // controller 避免重複計算
// 產生評價 evaluateArticle_topicSentence ('expert_topic_sentence_level','expert_topic_sentence_explanation'); evaluateArticle_content ('expert_content_level','expert_content_explanation'); evaluateArticle_organization ('expert_organization_level', 'expert_organization_explanation'); evaluateArticle_grammar ('expert_GrammarAndUsage_level', 'expert_GrammarAndUsage_explanation'); evaluateArticle_vocabulary ('expert_Vocabulary_level', 'expert_Vocabulary_explanation'); evaluateArticle_coherence ('expert_CoherenceAndCohesion_level', 'expert_CoherenceAndCohesion_explanation');
paragraph_ai_modification = paragraph_final; // 設定 ai 初始值段落修改的初始值
// ai 批改 model_1 const expert_ai_grammer_spell_check = document.getElementById("expert_ai_grammer_spell_check"); expert_ai_grammer_spell_check.style.display = "block";
// ai 批改 model_2 // const expert_ai_paragraph_refine = document.getElementById("expert_ai_paragraph_refine"); // expert_ai_paragraph_refine.style.display = "none";}
async function generateImageFromArticle () {
const imgContianer = document.getElementById("imageContainer"); const imgElement = document.getElementById("textToImage"); imgContianer.style.display = "none";
// use gpt4 to summarize Atricle and generate a prompt for Dalle2 const sys_prompt = ` Based on the summary of the following article as the [context] to create a prompt for Dalle2 to generate an image that: - pick one style [Scratch-Book/vector illustraction/Cubism] that is appropriate for the [context], - Do not use/display/draw English Letters in the image - use only soft/warm colors, minimal contrast, simple lines and shapes, positive/hopeful atmosphere
`;
const usr_promt = ${paragraph} ;
let prompt_for_dalle;
prompt_for_dalle = await jutorChat(sys_prompt, usr_promt, "gpt-4-1106-preview", false);
console.log(prompt_for_dalle);
// use Dalle2 to generate an Image & Display it let imageUrl;
imageUrl = await jutorImage(prompt_for_dalle);
if(imageUrl) { imgElement.src = imageUrl; imgContianer.style.display = "block"; } }
async function evaluateArticle_topicSentence(lv_output_div_id, desc_output_div_id){
const levelDiv = document.getElementById(lv_output_div_id); levelDiv.innerHTML = "" ;
const descDiv = document.getElementById(desc_output_div_id); descDiv.innerHTML = <i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在評估主題句... ;
const sys_prompt = `
`;
const usr_promt = ` ${paragraph_final}
-- 根據上述的文章,找出「主題句(topic sentence)」並進行評分,並且解釋這個主題句合適或不合適。
- 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋
評分結果以 JSON 格式輸出: { "content_level": "#beginner/intermediate/advanced", "topic_sentence": "主題句(topic sentence)", "content_explanation": "#中文解釋"} `;
let aigc; aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", false);
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
content_level = jsonObject["content_level"]; expert_topic_sentence = jsonObject["topic_sentence"]; content_explanation = jsonObject["content_explanation"];
levelDiv.innerHTML = <i class="fa-duotone fa-ranking-star"></i> + content_level; descDiv.innerHTML = <i class="fa-duotone fa-quote-left"></i> +expert_topic_sentence+<br>+content_explanation; } else { // No JSON format string in response levelDiv.innerHTML = ""; descDiv.innerHTML = aigc; }}
async function evaluateArticle_content (lv_output_div_id, desc_output_div_id) {
const levelDiv = document.getElementById(lv_output_div_id); levelDiv.innerHTML = "" ;
const descDiv = document.getElementById(desc_output_div_id); descDiv.innerHTML = <i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在評估段落... ;
const sys_prompt = `
`;
const usr_promt = ` ${paragraph_final}
-- 根據上述的文章,以「內容(content)」層面評分。
- 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋
評分結果以 JSON 格式輸出: { "content_level": "#beginner/intermediate/advanced", "content_explanation": "#中文解釋"} `;
let aigc; aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", false);
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
content_level = jsonObject["content_level"]; content_explanation = jsonObject["content_explanation"];
levelDiv.innerHTML = <i class="fa-duotone fa-ranking-star"></i> + content_level; descDiv.innerHTML = <i class="fa-duotone fa-quote-left"></i> +content_explanation; } else { // No JSON format string in response levelDiv.innerHTML = ""; descDiv.innerHTML = aigc; }
}
async function evaluateArticle_organization (lv_output_div_id, desc_output_div_id) {
const levelDiv = document.getElementById(lv_output_div_id); levelDiv.innerHTML = "" ;
const descDiv = document.getElementById(desc_output_div_id); descDiv.innerHTML = <i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在評估段落... ;
const sys_prompt = `
`;
const usr_promt = ` ${paragraph_final}
-- 根據上述的文章,以「組織(organization)」層面評分。
- 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋
評分結果以 JSON 格式輸出: { "organization_level": "#beginner/intermediate/advanced", "organization_explanation": "#中文解釋" }
`;
let aigc; aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", false);
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
organization_level = jsonObject["organization_level"]; organization_explanation = jsonObject["organization_explanation"];
levelDiv.innerHTML = <i class="fa-duotone fa-ranking-star"></i> +organization_level; descDiv.innerHTML = <i class="fa-duotone fa-quote-left"></i> +organization_explanation;
} else { // No JSON format string in response levelDiv.innerHTML = ""; descDiv.innerHTML = aigc; }
}
async function evaluateArticle_grammar (lv_output_div_id, desc_output_div_id) {
const levelDiv = document.getElementById(lv_output_div_id); levelDiv.innerHTML = "" ;
const descDiv = document.getElementById(desc_output_div_id); descDiv.innerHTML = <i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在評估段落... ;
const sys_prompt = `
`;
const usr_promt = ` ${paragraph_final}
-- 根據上述的文章,以「文法和用法(Grammar and usage)」層面評分。
- 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋
評分結果以 JSON 格式輸出: { "GrammarAndUsage_level": "#beginner/intermediate/advanced", "GrammarAndUsage_explanation": "#中文解釋" }
`;
let aigc; aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", false);
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
GrammarAndUsage_level = jsonObject["GrammarAndUsage_level"]; GrammarAndUsage_explanation = jsonObject["GrammarAndUsage_explanation"];
levelDiv.innerHTML = <i class="fa-duotone fa-ranking-star"></i> +GrammarAndUsage_level; descDiv.innerHTML = <i class="fa-duotone fa-quote-left"></i> +GrammarAndUsage_explanation; } else { // No JSON format string in response levelDiv.innerHTML = ""; descDiv.innerHTML = aigc; }
}
async function evaluateArticle_vocabulary (lv_output_div_id, desc_output_div_id) {
const levelDiv = document.getElementById(lv_output_div_id); levelDiv.innerHTML = "" ;
const descDiv = document.getElementById(desc_output_div_id); descDiv.innerHTML = <i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在評估段落... ;
const sys_prompt = `
`;
const usr_promt = ` ${paragraph_final}
-- 根據上述的文章,以「詞彙(Vocabulary )」層面評分。
- 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋
評分結果以 JSON 格式輸出: { "Vocabulary_level": "#beginner/intermediate/advanced", "Vocabulary_explanation": "#中文解釋" }
`;
let aigc; aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", false);
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
Vocabulary_level = jsonObject["Vocabulary_level"]; Vocabulary_explanation = jsonObject["Vocabulary_explanation"];
levelDiv.innerHTML = <i class="fa-duotone fa-ranking-star"></i> +Vocabulary_level; descDiv.innerHTML = <i class="fa-duotone fa-quote-left"></i> +Vocabulary_explanation; } else { // No JSON format string in response levelDiv.innerHTML = ""; descDiv.innerHTML = aigc; }
}
async function evaluateArticle_coherence (lv_output_div_id, desc_output_div_id) {
const levelDiv = document.getElementById(lv_output_div_id); levelDiv.innerHTML = "" ;
const descDiv = document.getElementById(desc_output_div_id); descDiv.innerHTML = <i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在評估段落... ;
const sys_prompt = `
`;
const usr_promt = ` ${paragraph_final}
-- 根據上述的文章,以「連貫性和連接詞(Coherence and Cohesion)」層面評分。
- 評分等級有三級:beginner, intermediate, advanced. - 以繁體中文解釋
評分結果以 JSON 格式輸出: { "CoherenceAndCohesion_level": "#beginner/intermediate/advanced", "CoherenceAndCohesion_explanation": "#中文解釋"}
`;
let aigc; aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", false);
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
CoherenceAndCohesion_level = jsonObject["CoherenceAndCohesion_level"]; CoherenceAndCohesion_explanation = jsonObject["CoherenceAndCohesion_explanation"];
levelDiv.innerHTML = <i class="fa-duotone fa-ranking-star"></i> +CoherenceAndCohesion_level; descDiv.innerHTML = <i class="fa-duotone fa-quote-left"></i> +CoherenceAndCohesion_explanation;
} else { // No JSON format string in response levelDiv.innerHTML = ""; descDiv.innerHTML = aigc; }
}
async function getAiReviseOne() {
const output = document.getElementById("ai_full_paragraph_revised_1"); output.innerHTML = '';
const user_edit_area = document.getElementById("textarea_full_paragraph_revised_1");
// 修正為存取一個 global variable 儲存現有的全文.user_edit_area.value = paragraph_ai_modification; document.getElementById("word_count_textarea_full_paragraph_revised_1").textContent = countWords(user_edit_area.value); // update words count checkEmptyTextareas();
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill on a topic about "${topic}" in the context of "${scenario}". ;
const usr_promt = ` Generate a JSON response with the following structure:
I'm aiming to improve my writing. Please assist me by "Correcting Grammatical and Spelling Errors" in the provided paragraph. For every correction you make, I'd like an "Explanation" to understand the reasoning behind it.
- Paragraph for Correction: [${paragraph_ai_modification}]
- The sentence to remain unchanged: "${topicSentenceSelected}" - When explaining, use Traditional Chinese (Taiwan, 繁體中文) for clarity. - Make sure any revised vocabulary aligns with the ${eng_level}. - Guidelines for Length and Complexity: Please keep explanations concise and straightforward, avoiding overly technical language.
The response should strictly be in the below JSON format and nothing else:
{ "Corrections and Explanations": [ { "Error": "#error_1", "Correction": "#correction_1", "Explanation": "#explanation_1_in_traditional_chinese" }, { "Error": "#error_2", "Correction": "#correction_2", "Explanation": "#explanation_2_in_traditional_chinese" }, ... ], "Revised Paragraph": "#revised_paragraph" }
`;
let aigc = '';
output.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在進行文法與拼寫檢查... 請等候約 10 秒';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-4-1106-preview", false);
output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 修訂後全文 const revisedParagraph = jsonObject["Revised Paragraph"]; output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-wand-magic-sparkles-circle-check"></i> 已修訂段落:</p><p>${revisedParagraph}</p></div>;
// 逐筆的修訂與解釋 const correctionsAndExplanations = jsonObject["Corrections and Explanations"];
if (correctionsAndExplanations.length > 0) {
let inputText = paragraph_final;
correctionsAndExplanations.forEach((item, index) => { const error = item["Error"]; const correction = item["Correction"]; const explanation = item["Explanation"];
let regex = new RegExp(escapeRegExp(error), 'gi'); // 'gi' for global, case-insensitive match
inputText = inputText.replace(regex, <span class="tooltip"> <span class="highlight">${error}</span> <span class="tooltiptext">${correction}</span> </span> );
output.innerHTML += <div class="feedback_correction_explanation"> <p><i class="fa-solid fa-feather"></i> # ${index + 1}</p> <p>原文:${error}</p> <p>修訂:${correction}</p> <p>解釋:${explanation}</p> </div> ; });
output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-highlighter-circle-question"></i> 待修訂段落:</p><p>${inputText}</p></div>;
} else { output.innerHTML += <div class="feedback_correction_explanation"> <p><i class="fa-solid fa-check-double"></i> 未發現文法或拼字錯誤。</p> </div> ; }
} else { // No JSON format string in response output.innerHTML = aigc; }
}
async function expertGetAiReviseOne() {
const output = document.getElementById("expert_ai_full_paragraph_revised_1"); output.innerHTML = '';
const user_edit_area = document.getElementById("expert_textarea_full_paragraph_revised_1");
// 修正為存取一個 global variable 儲存現有的全文.user_edit_area.value = paragraph_ai_modification;
document.getElementById("word_count_expert_textarea_full_paragraph_revised_1").textContent = countWords(user_edit_area.value); // update words count checkEmptyTextareas();
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill. ;
const usr_promt = ` Generate a JSON response with the following structure:
I'm aiming to improve my writing. Please assist me by "Correcting Grammatical and Spelling Errors" in the provided paragraph. For every correction you make, I'd like an "Explanation" to understand the reasoning behind it.
- Paragraph for Correction: [${paragraph_ai_modification}] - When explaining, use Traditional Chinese (Taiwan, 繁體中文) for clarity. - Make sure any revised vocabulary aligns with the ${eng_level}. - Guidelines for Length and Complexity: Please keep explanations concise and straightforward, avoiding overly technical language.
The response should strictly be in the below JSON format and nothing else:
{ "Corrections and Explanations": [ { "Error": "#error_1", "Correction": "#correction_1", "Explanation": "#explanation_1_in_traditional_chinese" }, { "Error": "#error_2", "Correction": "#correction_2", "Explanation": "#explanation_2_in_traditional_chinese" }, ... ], "Revised Paragraph": "#revised_paragraph" }
`;
let aigc = '';
output.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在進行文法與拼寫檢查... 請等候約 10 秒';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-4-1106-preview", false);
output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 修訂後全文 const revisedParagraph = jsonObject["Revised Paragraph"]; output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-wand-magic-sparkles-circle-check"></i> 已修訂段落:</p><p>${revisedParagraph}</p></div>;
// 逐筆的修訂與解釋 const correctionsAndExplanations = jsonObject["Corrections and Explanations"];
if (correctionsAndExplanations.length > 0) {
let inputText = paragraph_final;
correctionsAndExplanations.forEach((item, index) => { const error = item["Error"]; const correction = item["Correction"]; const explanation = item["Explanation"];
let regex = new RegExp(escapeRegExp(error), 'gi'); // 'gi' for global, case-insensitive match
inputText = inputText.replace(regex, <span class="tooltip"> <span class="highlight">${error}</span> <span class="tooltiptext">${correction}</span> </span> );
output.innerHTML += <div class="feedback_correction_explanation"> <p><i class="fa-solid fa-feather"></i> # ${index + 1}</p> <p>原文:${error}</p> <p>修訂:${correction}</p> <p>解釋:${explanation}</p> </div> ; });
output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-highlighter-circle-question"></i> 待修訂段落:</p><p>${inputText}</p></div>;
} else { output.innerHTML += <div class="feedback_correction_explanation"> <p><i class="fa-solid fa-check-double"></i> 未發現文法或拼字錯誤。</p> </div> ; }
} else { // No JSON format string in response output.innerHTML = aigc; }
}
// Utility function to escape special characters for RegExp. function escapeRegExp(string) { return string.replace(/[.*+-?^${}()|[\]\\]/g, '\\$&'); }
function getUserReviseOne() { // 使用者的修改,再儲存回 paragraph_ai_modification paragraph_ai_modification = document.getElementById("textarea_full_paragraph_revised_1").value;
}
function expertGetUserReviseOne() { // 使用者的修改,再儲存回 paragraph_ai_modification paragraph_ai_modification = document.getElementById("expert_textarea_full_paragraph_revised_1").value;}
function expertNextAiModule () {
showFireworks();
expertGetUserReviseOne();
const expert_ai_paragraph_refine = document.getElementById("expert_ai_paragraph_refine"); expert_ai_paragraph_refine.style.display = "block"; }
async function getAiReviseTwo() {
const output = document.getElementById("ai_full_paragraph_revised_2"); output.innerHTML = '';
const user_edit_area = document.getElementById("textarea_full_paragraph_revised_2"); user_edit_area.value = paragraph_ai_modification; document.getElementById("word_count_textarea_full_paragraph_revised_2").textContent = countWords(user_edit_area.value); // update word counts checkEmptyTextareas();
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill on a topic about "${topic}" in the context of "${scenario}". However, also consider the changes made from "Revised Version 0" to understand the direction and context of the revisions. - Revised Version 0 (for context): [${paragraph_final}] ;
const usr_promt = ` Generate a JSON response with the following structure:
I need assistance with revising a paragraph. Please "Refine" the "Revised Version 1" and immediately "Provide Explanations" for each suggestion you made.
- Revised Version 1 (for correction): [${paragraph_ai_modification}]
- Do not modify the sentence: "${topicSentenceSelected}" - Make sure any revised vocabulary aligns with the ${eng_level}. - Guidelines for Length and Complexity: Please keep explanations concise and straightforward, avoiding overly technical language.
The response should strictly be in the below JSON format and nothing else:
{
"Suggestions and Explanations": [ { "Origin": "#original_text_1", "Suggestion": "#suggestion_1", "Explanation": "#explanation_1" }, { "Origin": "#original_text_2", "Suggestion": "#suggestion_2", "Explanation": "#explanation_2" }, ... ],
"Revised Paragraph": "#revised_paragraph_v2"
}
`;
//console.log(usr_promt);
let aigc = '';
output.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在分析整個段落... 請等候約 10 秒';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-4-1106-preview", false);
output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 修訂後全文 const revisedParagraph = jsonObject["Revised Paragraph"]; output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-wand-magic-sparkles-circle-check"></i> 已修訂段落:</p><p>${revisedParagraph}</p></div>;
// 逐筆的修訂與解釋 const correctionsAndExplanations = jsonObject["Suggestions and Explanations"];
if (correctionsAndExplanations.length > 0) {
let inputText = paragraph_ai_modification;
correctionsAndExplanations.forEach((item, index) => { const origin = item["Origin"]; const correction = item["Suggestion"]; const explanation = item["Explanation"];
let regex = new RegExp(escapeRegExp(origin), 'gi'); // 'gi' for global, case-insensitive match
inputText = inputText.replace(regex, <span class="tooltip"> <span class="highlight">${origin}</span> <span class="tooltiptext">${correction}</span> </span> );
output.innerHTML += <div class="feedback_correction_explanation"> <p><i class="fa-solid fa-feather"></i> # ${index + 1}</p> <p>原文:${origin}</p> <p>建議:${correction}</p> <p>解釋:${explanation}</p> </div> ; });
output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-highlighter-circle-question"></i> 待修訂段落:</p><p>${inputText}</p></div>;
} else { output.innerHTML += <div class="feedback_correction_explanation"> <p><i class="fa-solid fa-check-double"></i> 段落良好,無改善建議。</p> </div> ; }
} else { // No JSON format string in response output.innerHTML = aigc; }
}
async function expertGetAiReviseTwo() {
const output = document.getElementById("expert_ai_full_paragraph_revised_2"); output.innerHTML = '';
const user_edit_area = document.getElementById("expert_textarea_full_paragraph_revised_2"); user_edit_area.value = paragraph_ai_modification; document.getElementById("word_count_expert_textarea_full_paragraph_revised_2").textContent = countWords(user_edit_area.value); // update word counts checkEmptyTextareas();
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill. However, also consider the changes made from "Revised Version 0" to understand the direction and context of the revisions. - Revised Version 0 (for context): [${paragraph_final}] ;
const usr_promt = ` Generate a JSON response with the following structure:
I need assistance with revising a paragraph. Please "Refine" the "Revised Version 1" and immediately "Provide Explanations" for each suggestion you made.
- Revised Version 1 (for correction): [${paragraph_ai_modification}] - Make sure any revised vocabulary aligns with the ${eng_level}. - Guidelines for Length and Complexity: Please keep explanations concise and straightforward, avoiding overly technical language.
The response should strictly be in the below JSON format and nothing else:
{
"Suggestions and Explanations": [ { "Origin": "#original_text_1", "Suggestion": "#suggestion_1", "Explanation": "#explanation_1" }, { "Origin": "#original_text_2", "Suggestion": "#suggestion_2", "Explanation": "#explanation_2" }, ... ],
"Revised Paragraph": "#revised_paragraph_v2"
}
`;
//console.log(usr_promt);
let aigc = '';
output.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在分析整個段落... 請等候約 10 秒';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-4-1106-preview", false);
output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 修訂後全文 const revisedParagraph = jsonObject["Revised Paragraph"]; output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-wand-magic-sparkles-circle-check"></i> 已修訂段落:</p><p>${revisedParagraph}</p></div>;
// 逐筆的修訂與解釋 const correctionsAndExplanations = jsonObject["Suggestions and Explanations"];
if (correctionsAndExplanations.length > 0) {
let inputText = paragraph_ai_modification;
correctionsAndExplanations.forEach((item, index) => { const origin = item["Origin"]; const correction = item["Suggestion"]; const explanation = item["Explanation"];
let regex = new RegExp(escapeRegExp(origin), 'gi'); // 'gi' for global, case-insensitive match
inputText = inputText.replace(regex, <span class="tooltip"> <span class="highlight">${origin}</span> <span class="tooltiptext">${correction}</span> </span> );
output.innerHTML += <div class="feedback_correction_explanation"> <p><i class="fa-solid fa-feather"></i> # ${index + 1}</p> <p>原文:${origin}</p> <p>建議:${correction}</p> <p>解釋:${explanation}</p> </div> ; });
output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-highlighter-circle-question"></i> 待修訂段落:</p><p>${inputText}</p></div>;
} else { output.innerHTML += <div class="feedback_correction_explanation"> <p><i class="fa-solid fa-check-double"></i> 段落良好,無改善建議。</p> </div> ; }
} else { // No JSON format string in response output.innerHTML = aigc; }
}
async function rephraseAiReviseTwo ( paragraph_div, type) {
const original_text = document.getElementById(paragraph_div).textContent;
const output = document.getElementById(paragraph_div); output.innerHTML += '<BR>';
const sys_prompt = You are an English teacher who is practicing with me to improve my English writing skill on a topic about "${topic}" in the context of "${scenario}". ;
const usr_promt = `Please assist me by "Rephrasing" the provided paragraph, make its vocabulary and strcuture more ${type}.
- Paragraph for Rephrasing: [${original_text}]. This paragraph is developed based on keywords: "${points}" to finish a paragraph. Must use these keywords in your modification.
The response should strictly be in the below JSON format and nothing else:
{ "modification": "Rephrasing Paragraph" } `;
let aigc = '';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", output );
//output.innerHTML = ''; //reset
// Fetch the string between {} as the source. const jsonString = parseJsonString(aigc);
// Formatted output if (jsonString) { const jsonObject = JSON.parse(jsonString);
// 修改後段落全文 const full_text = jsonObject["modification"]; output.innerHTML += <div class="feedback_revised_paragraph"><p><i class="fa-kit fa-solid-wand-magic-sparkles-circle-check"></i> 已修訂段落(${type}):</p><p>${full_text}</p></div>;
} else { // No JSON format string in response output.innerHTML += aigc; } }
function parseJsonString(responseString) {
const startIndex = responseString.indexOf('{'); const endIndex = responseString.lastIndexOf('}');
// Extract the content inside the most top pair of '{' and '}' const extractedContent = responseString.slice(startIndex, endIndex + 1);
//console.log(extractedContent);return extractedContent; }
function getUserReviseTwo() { paragraph_ai_modification = document.getElementById("textarea_full_paragraph_revised_2").value; }
function expertGetUserReviseTwo() { paragraph_ai_modification = document.getElementById("expert_textarea_full_paragraph_revised_2").value; }
async function getAiReviseThree() {
const output = document.getElementById("ai_full_paragraph_revised_3"); output.innerHTML = '';
const user_edit_area = document.getElementById("textarea_full_paragraph_revised_3");
// 修正為存取一個 global variable 儲存現有的全文. user_edit_area.innerHTML = paragraph_ai_modification; checkEmptyTextareas();
const sys_prompt = You are an English teacher who is practicing with me to improve my writing skill on a topic about "${topic}" in the context of "${scenario}". ;
const usr_promt = ` I'd like to ensure that my writing has a logical progression and maintains consistency throughout. Please "Check for Coherence and Flow" in the following paragraph. Additionally, I'd greatly value it if you could "Provide Explanations" for any suggestions or alterations you make in Traditional Chinese (Taiwan,繁體中文), so I can better understand and apply the feedback.
[${paragraph_ai_modification}]
Keep the "${topicSentenceSelected}" sentence unchanged.
Make sure the vocabulary you use is at ${eng_level}.
At last, give the whole revised paragraph.
`;
output.innerHTML = '<i class="fa-solid fa-hat-wizard fa-beat"></i> JUTOR 正在分析整個段落...';
let aigc = '';
aigc = await jutorChat(sys_prompt, usr_promt, "gpt-4-1106-preview", output);
output.innerHTML = ''; //reset
// 待處理 aigc 內容 output.innerHTML = aigc;
}
function getUserReviseThree() { paragraph_ai_modification = document.getElementById("textarea_full_paragraph_revised_3").value; //paragraph_revised_3 = document.getElementById("textarea_full_paragraph_revised_3").value; }
function showFinalResult () { const output = document.getElementById("user_full_paragraph_final_revised"); output.innerHTML = paragraph_ai_modification;
jutorTTS (paragraph_ai_modification, 'audio_user_full_paragraph');
paragraph_final_ai_modification = paragraph_ai_modification; //evaluateArticle_phase2(); //已經混合了 AI 建議,已無法確認為使用者的產出,不做評價。 }
function expertShowFinalResult () {
showFireworks();
expertGetUserReviseTwo();
const expert_final_div = document.getElementById("expert_final_div"); expert_final_div.style.display = "flex";
const output = document.getElementById("expert_full_paragraph_final_revised"); output.innerHTML = paragraph_ai_modification;
jutorTTS (paragraph_ai_modification, 'audio_expert_full_paragraph');
paragraph_final_ai_modification = paragraph_ai_modification;
// controller 避免重複計算if(newPracticeToken) { totalPracticeCnt += 1;
const totalPracticeCntDisplay = document.getElementById("total_paragraph_cnt"); // set UI elements totalPracticeCntDisplay.textContent = totalPracticeCnt;
updateTotalPracticeCnt(user_hashed_id); } newPracticeToken = false; // controller 避免重複計算
}
function reviewMode() { // Get a reference to the button and all divs with class "step_Container" const stepContainers = document.querySelectorAll(".step_Container");
// Add a click event listener to the button stepContainers.forEach((div) => { if (div.style.display === "none" || div.style.display === "") { div.style.display = "block"; document.getElementById("user_full_paragraph_final_revised").scrollIntoView({ behavior: "smooth", block: "start" }); // Scroll the specific div into view
} else { div.style.display = "none"; document.getElementById("mainContainer").scrollIntoView({ behavior: "smooth", block: "start" }); // Scroll the specific div into view
} });
}
/* 暫定不納入範圍。已經混合了 AI 建議,已無法確認為使用者的產出,不做評價。 async function evaluateArticle_phase2 () {
// const input = document.getElementById("user_full_paragraph_final_revised"); // 取得文稿的 div-id // const output = document.getElementById(""); // 取得輸出回饋的 div-id
const sys_prompt = ` You are an English teacher who is practicing with me to improve my English writing skill. You will give me feedback according to my article. Please evaluate the article is in which CEFR level, and give simple and clear explanations without technical terms. Explanation is 100 words Max. Use warm and supportive tones.
Response in following JSON format: { "CEFR": "#cefr_level", "Explanation": "#explanation" } `;
const usr_promt = ${paragraph_final_ai_modification}; ;
let aigc; aigc = await jutorChat(sys_prompt, usr_promt, "gpt-3.5-turbo-1106", false); console.log(aigc);
// output.innerHTML = ''; //reset
// 待處理 aigc JSON 內容 // output.innerHTML = aigc;
// CEFR_label_phase2 = aigc.cerf_label; // 儲存在 global variable,後續存在 local storage // evaluation_phase2 = aigc.explanation; // 儲存在 global variable,後續存在 local storage
} */
</script>
<script> /* AI Common Functions */
/*Fetch Open AI api chat
async function jutorChat_tmp(system_prompt, user_prompt, gpt_model, stream_message_obj) { let aigc = ''; // key-name:寫作-preview const response = await fetch(https://api.openai.com/v1/chat/completions, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer KEY' }, body: JSON.stringify({ "messages": [ {"role": "system", "content": ${system_prompt}}, {"role": "user", "content": ${user_prompt}}], "temperature": 0.9, "model": ${gpt_model}, "stream": true, // For streaming responses }), });
// Read the response as a stream of data const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8");
while (true) { const { done, value } = await reader.read(); if (done) { break; } // Massage and parse the chunk of data const chunk = decoder.decode(value); const lines = chunk.split("\n\n"); const parsedLines = lines .map((line) => line.replace(/^data: /, "").trim()) // Remove the "data: " prefix .filter((line) => line !== "" && line !== "[DONE]") // Remove empty lines and "[DONE]" .map((line) => JSON.parse(line)); // Parse the JSON string
for (const parsedLine of parsedLines) { const { choices } = parsedLine; const { delta } = choices[0]; const { content } = delta; // Update the UI with the new content if (content) {
if (stream_message_obj){ stream_message_obj.innerHTML += content;}
aigc += content; } } }
return aigc; } */
/* Module:: Jutor-Chat, 共用模組,Fetch jutor api chat */
async function jutorChat (system_prompt, user_prompt, gpt_model, stream_message_obj) {
hideTipsTransition();showTipsTransition(); //stream_message_obj: Aim for stream mode. Not support yet.
const response = await fetch(/api/v2/jutor/chat, { method: "POST", headers: { "Content-Type": "application/json", 'X-KA-FKey': xsrfToken },body: JSON.stringify({ "endpoint": "https://api.openai.com/v1/chat/completions", "http_method": "POST", "data": { "model": ${gpt_model}, "messages": [ {"role": "system", "content": ${system_prompt}}, {"role": "user", "content": ${user_prompt}}], "temperature": 0.9, "n": 1 } }) });
let aigc;
if (response.ok) {
const json = await response.json(); aigc = json.data.choices[0].message.content.trim();
} else { // Error Handling... console.log("status: "+response.status);
// Create a JSON object to wrap the error message const errorResponse = { jutor_error: "JUTOR 發生了技術錯誤,請稍後再試。" };
// Convert the JSON object to a JSON string const errorMessageJSON = JSON.stringify(errorResponse);aigc = errorMessageJSON;
}
hideTipsTransition(); console.log(aigc); return aigc;
}
async function jutorImage (prompt_for_dalle) { let aigc_image;
await fetch('https://api.openai.com/v1/images/generations', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer sk' }, body: JSON.stringify({ "prompt": ${prompt_for_dalle}, "n": 1, "size": "1024x1024" }) }) .then(response => response.json()) .then(data => { const imageUrl = data.data[0].url;
// Process or display the generated image as needed aigc_image = imageUrl;
}) .catch(error => { console.error('Error:', error); // Handle the error aigc_image = null; });
return aigc_image; }
async function jutorTTS (text, audioPlayer) { const response = await fetch("/api/v2/jutor/tts", { method: "POST", headers: { "Content-Type": "application/json", 'X-KA-FKey': xsrfToken },body: JSON.stringify({ "text": text, //設定文字內容 "lang": "en-US", // 設定語言 "voice_name": "en-US-JaneNeural" }) /*body: JSON.stringify({ "text": text, //設定文字內容 "lang": "zh-TW", // 設定語言 "voice_name": "zh-TW-HsiaoChenNeural" }) */ });
const data = await response.json();
if (data.data.audio_data) { const audio = new Audio("data:audio/wav;base64," + data.data.audio_data); var audioElement = document.getElementById(audioPlayer); audioElement.src = audio.src; //audioElement.play();
} else { console.log(data.error); }
}
/* Module:: Jutor-Chat, 共用模組,Fetch Azure Open AI chat
async function jutorChat (system_prompt, user_prompt, gpt_model, stream_message_obj) {
//stream_message_obj: Aim for stream mode. Not support yet.
let endpoint;
if (gpt_model === "gpt-4-1106-preview") { endpoint = "https://jutor-open-ai.openai.azure.com/openai/deployments/test-GPT4/chat/completions?api-version=2023-03-15-preview"; } else if (gpt_model === "gpt-3.5-turbo-1106") { endpoint = "https://jutor-open-ai.openai.azure.com/openai/deployments/test-GPT3-5-16k/chat/completions?api-version=2023-03-15-preview"; } else { endpoint = "https://jutor-open-ai.openai.azure.com/openai/deployments/test-GPT3-5-16k/chat/completions?api-version=2023-03-15-preview"; // set to gpt-3 for cost; }
const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'api-key': 'KEY' }, body: JSON.stringify({ "messages": [ {"role": "system", "content": ${system_prompt}}, {"role": "user", "content": ${user_prompt}}], "temperature": 0.9, "top_p": 0.95, "frequency_penalty": 0, "presence_penalty": 0, "max_tokens": 800, "stop": null }), });
let aigc;
// Read the response as a stream of data if (response.ok) { const json = await response.json(); aigc = json.choices[0].message.content.trim(); } else { // Error Handling... console.log("status: "+response.status);
// Create a JSON object to wrap the error message const errorResponse = { jutor_error: "Something went wrong. Please try again later." };
// Convert the JSON object to a JSON string const errorMessageJSON = JSON.stringify(errorResponse); aigc = errorMessageJSON;
} return aigc; } */ </script>
OpenAI的提示(prompt),以及系统提示(system prompt)的内容。