diff --git a/public/index.html b/public/index.html index 2148a52e5..360a698d2 100644 --- a/public/index.html +++ b/public/index.html @@ -1,14 +1,17 @@ + - - - - - - - - + + + + + + + + @@ -32,4925 +35,90 @@ //console.log(encode("dsfs").length); // [258, 18798, 995] - - -Tavern.AI + Tavern.AI +
-
- +
+
-

text

+
+

text

+
-

Initialization

+
+

Initialization

+
- -
-
- -
- -
-

- Advanced Defininitions -
- -
- - -
-
-

Personality summary

A brief description of the personality ?
- -
- -
-

Scenario

-
Circumstances and context of the dialogue ?
- + +
+
+
-
-

Talkativeness

-
How often does the character speak randomly. Affects group chats only!
- -
- Shy - Normal - Chatty -
+
+

- Advanced Defininitions
- -
-
-

Examples of dialogue

-
Forms a personality more clearly ?
-
- -
- - + +
+ + +
+
+

Personality summary

+
A brief description of the personality ?
+ +
+ +
+

Scenario

+
Circumstances and context of the dialogue ?
+ +
+ +
+

Talkativeness

+
How often does the character speak randomly. Affects group chats only! +
+ +
+ Shy + Normal + Chatty +
+
+ +
+
+

Examples of dialogue

+
Forms a personality more clearly ?
+
+ +
+ +
@@ -4964,8 +132,10 @@ (?)
 
-
- + +
@@ -5006,7 +176,7 @@

Insertion Order

Higher order number entries will be inserted first.
- +
- +
- +
  @@ -5061,44 +235,52 @@
- +
- - -
- ? -
- + + +
+ ? +
+
- +
- +
- -
- - + +
- TavernAI is being developed with love and care on a voluntary basis. If you like the project and want to support it, your donation would make a huge impact! Thank you!
+ TavernAI is being developed with love and care on a voluntary basis. If you like the project and + want to support it, your donation would make a huge impact! Thank you! +
-

Ethereum or USDT

- +
+

Ethereum or USDT

+
+
0x975E5C91042ce8168B3d37b17F99949c5eFB3Dfe
@@ -5106,91 +288,105 @@
-
-
- -
- -
-
+
+
+ +
+ +
+
-
+
- -
+ +
@@ -5532,7 +795,7 @@
-
+
@@ -5541,36 +804,35 @@ - - - + + +
-
- -
+
+ +
- - - - + + \ No newline at end of file diff --git a/public/script.js b/public/script.js new file mode 100644 index 000000000..edb9cc63d --- /dev/null +++ b/public/script.js @@ -0,0 +1,4847 @@ +// API OBJECT FOR EXTERNAL WIRING +window['TavernAI'] = {}; + +import { encode, decode } from "../scripts/gpt-2-3-tokenizer/mod.js"; +$(document).ready(function () { + const VERSION = '1.2.8'; + var converter = new showdown.Converter({ emoji: 'true' }); + var bg_menu_toggle = false; + const systemUserName = 'TavernAI'; + const systemCharName = 'Chloe'; + var default_user_name = "You"; + var name1 = default_user_name; + var name2 = "Chloe"; + // might want to migrate this to 'system message' code + var chat = [{ name: 'Chloe', is_user: false, is_name: true, create_date: 0, mes: '\n*You went inside. The air smelled of fried meat, tobacco and a hint of wine. A dim light was cast by candles, and a fire crackled in the fireplace. It seems to be a very pleasant place. Behind the wooden bar is an elf waitress, she is smiling. Her ears are very pointy, and there is a twinkle in her eye. She wears glasses and a white apron. As soon as she noticed you, she immediately came right up close to you.*\n\n' + ' "Hello there! How is your evening going?"

\n' + '\n' }]; + var safetychat = [{ name: 'Chloe', is_user: false, is_name: true, create_date: 0, mes: '\n*You deleted a character/chat and arrived back here for safety reasons! Pick another character!*\n\n' }]; + var chat_create_date = 0; + + //RossAscends: Added function to format dates used in files and chat timestamps to a humanized format. + //Mostly I wanted this to be for file names, but couldn't figure out exactly where the filename save code was as everything seemed to be connected. + //During testing, this performs the same as previous date.now() structure. + //It also does not break old characters/chats, as the code just uses whatever timestamp exists in the chat. + //New chats made with characters will use this new formatting. + //Useable variable is (( humanizedISO8601Datetime )) + + function humanizedISO8601DateTime() { + let baseDate = new Date(Date.now()); + let humanYear = baseDate.getFullYear(); + let humanMonth = (baseDate.getMonth() + 1); + let humanDate = baseDate.getDate(); + let humanHour = (baseDate.getHours() < 10 ? '0' : '') + baseDate.getHours(); + let humanMinute = (baseDate.getMinutes() < 10 ? '0' : '') + baseDate.getMinutes(); + let humanSecond = (baseDate.getSeconds() < 10 ? '0' : '') + baseDate.getSeconds(); + let humanMillisecond = (baseDate.getMilliseconds() < 10 ? '0' : '') + baseDate.getMilliseconds(); + let HumanizedDateTime = (humanYear + "-" + humanMonth + "-" + humanDate + " @" + humanHour + "h " + humanMinute + "m " + humanSecond + "s " + humanMillisecond + "ms"); + return HumanizedDateTime; + }; + + let prev_selected_char = null; + var default_ch_mes = "Hello"; + var count_view_mes = 0; + var mesStr = ''; + var generatedPromtCache = ''; + var characters = []; + let groups = []; + let selected_group = null; + let is_group_automode_enabled = false; + var this_chid; + var active_character; + var backgrounds = []; + var default_avatar = 'img/fluffy.png'; + var is_colab = false; + var is_checked_colab = false; + var is_mes_reload_avatar = false; + let collapse_newlines = false; + + const system_message_types = { + HELP: 'help', + WELCOME: 'welcome', + GROUP: 'group', + EMPTY: 'empty', + GENERIC: 'generic', + }; + + const system_messages = { + 'help': { + "name": systemUserName, + "force_avatar": "img/five.png", + "is_user": false, + "is_system": true, + "is_name": true, + "mes": "Hi there! The following chat formatting commands are supported:

Need more help? Visit our wiki – TavernAI Wiki!

" + }, + 'group': { + "name": systemUserName, + "force_avatar": "img/five.png", + "is_user": false, + "is_system": true, + "is_name": true, + "mes": "Group chat created. Say 'Hi' to lovely people!" + }, + 'empty': { + "name": systemUserName, + "force_avatar": "img/five.png", + "is_user": false, + "is_system": true, + "is_name": true, + "mes": 'No one hears you. **Hint:** add more members to the group!' + }, + 'generic': { + "name": systemUserName, + "force_avatar": "img/five.png", + "is_user": false, + "is_system": true, + "is_name": true, + "mes": "Generic system message. User `text` parameter to override the contents", + }, + }; + + const world_info_position = { + 'before': 0, + 'after': 1, + } + const talkativeness_default = 0.5; + const storage_keys = { + 'collapse_newlines': 'TavernAI_collapse_newlines', + }; + + var is_advanced_char_open = false; + var is_world_edit_open = false; + + var menu_type = '';//what is selected in the menu + var selected_button = '';//which button pressed + //create pole save + var create_save_name = ''; + var create_save_description = ''; + var create_save_personality = ''; + var create_save_first_message = ''; + var create_save_avatar = ''; + var create_save_scenario = ''; + var create_save_mes_example = ''; + var create_save_talkativeness = talkativeness_default; + + var timerSaveEdit; + var timerWorldSave; + var timerGroupSave; + var durationSaveEdit = 200; + //animation right menu + var animation_rm_duration = 200; + var animation_rm_easing = ""; + + var popup_type = ""; + var bg_file_for_del = ''; + var online_status = 'no_connection'; + + var api_server = ""; + var api_server_textgenerationwebui = ""; + //var interval_timer = setInterval(getStatus, 2000); + var interval_timer_novel = setInterval(getStatusNovel, 3000); + const groupAutoModeInterval = setInterval(groupChatAutoModeWorker, 5000); + var is_get_status = false; + var is_get_status_novel = false; + var is_api_button_press = false; + var is_api_button_press_novel = false; + + var is_send_press = false;//Send generation + let is_group_generating = false; // Group generation flag + var add_mes_without_animation = false; + + var this_del_mes = 0; + + var this_edit_mes_text = ''; + var this_edit_mes_chname = ''; + var this_edit_mes_id; + + const delay = ms => new Promise(res => setTimeout(res, ms)); + //settings + var settings; + var koboldai_settings; + var koboldai_setting_names; + var preset_settings = 'gui'; + var user_avatar = 'you.png'; + var temp = 0.5; + var world_info = null; + var world_names; + var world_info_data = null; + var world_info_depth = 2; + var world_info_budget = 128; + var imported_world_name = ''; + var amount_gen = 80; //default max length of AI generated responses + var max_context = 2048; + var rep_pen = 1; + var rep_pen_size = 100; + + var textgenerationwebui_settings = { + temp: 0.5, + top_p: 0.9, + top_k: 0, + typical_p: 1, + rep_pen: 1.1, + rep_pen_size: 0, + penalty_alpha: 0, + } + + var is_pygmalion = false; + var tokens_already_generated = 0; + var message_already_generated = ''; + var if_typing_text = false; + const tokens_cycle_count = 30; + var cycle_count_generation = 0; + + var anchor_order = 0; + var style_anchor = true; + var character_anchor = true; + let extension_prompts = {}; + var auto_connect = false; + var auto_load_chat = false; + + var main_api = 'kobold'; + //novel settings + var temp_novel = 0.5; + var rep_pen_novel = 1; + var rep_pen_size_novel = 100; + + var api_key_novel = ""; + var novel_tier; + var model_novel = "euterpe-v2"; + var novelai_settings; + var novelai_setting_names; + var preset_settings_novel = 'Classic-Krake'; + + //css + var bg1_toggle = true; // inits the BG as BG1 + var css_mes_bg = $('
').css('background'); + var css_send_form_display = $('
').css('display'); + + var colab_ini_step = 1; + + setInterval(function () { + switch (colab_ini_step) { + case 0: + $('#colab_popup_text').html('

Initialization

'); + colab_ini_step = 1; + break + case 1: + $('#colab_popup_text').html('

Initialization.

'); + colab_ini_step = 2; + break + case 2: + $('#colab_popup_text').html('

Initialization..

'); + colab_ini_step = 3; + break + case 3: + $('#colab_popup_text').html('

Initialization...

'); + colab_ini_step = 0; + break + } + }, 500); + ///////////// + + var token; + $.ajaxPrefilter((options, originalOptions, xhr) => { + xhr.setRequestHeader("X-CSRF-Token", token); + }); + + + $.get("/csrf-token") + .then(data => { + token = data.token; + getCharacters(); + getSettings("def"); + getLastVersion(); + //getCharacters(); + printMessages(); + getBackgrounds(); + getUserAvatars(); + autoloadchat(); + autoconnect(); + }); + + function flushSettings() { + $('#settings_perset').empty(); + $('#world_info').empty(); + $('#settings_perset').append(''); + $('#world_info').append(''); + } + + //RossAscends: a smaller load-up function to be used instead of refreshing the page in cases like deleting a character and changing username + function QuickRefresh() { + flushSettings(); + clearChat(); + //characters.length = 0 //if this could be enabled it would allow the GetCharacters function to detect files added or removed from the char dir on each panel load + //console.log('quickRefresh() -- active_character -- '+active_character); + //console.log('quickRefresh() -- this_chid -- '+this_chid); + getSettings("def"); + getCharacters(); + getUserAvatars(); + //console.log(chat); + printMessages(); + + if (!this_chid || this_chid === 'invalid-safety-id') { + $("#rm_button_selected_ch").css("class", "deselected-right-tab"); + $("#rm_button_selected_ch").children("h2").text(''); + } + + if (NavToggle.checked === false) { + document.getElementById('nav-toggle').click(); + }; + } + + $('#character_search_bar').on('input', function () { + const searchValue = $(this).val().trim().toLowerCase(); + + if (!searchValue) { + $("#rm_print_characters_block .character_select").show(); + } else { + $("#rm_print_characters_block .character_select").each(function () { + $(this).children('.ch_name').text().toLowerCase().includes(searchValue) + ? $(this).show() + : $(this).hide(); + }); + } + }); + + + //RossAscends: a utility function for counting characters, even works for unsaved characters. + function CountCharTokens() { + $('#result_info').html(''); + if (selected_button == 'create') { + var count_tokens = encode(JSON.stringify(create_save_description + create_save_personality + create_save_scenario + create_save_mes_example)).length; + console.log('This unsaved character has ' + count_tokens + ' tokens in the defs.'); + } else { + var count_tokens = encode(JSON.stringify(characters[this_chid].description + characters[this_chid].personality + characters[this_chid].scenario + characters[this_chid].mes_example)).length; + console.log(characters[this_chid].name + ' has ' + count_tokens + ' tokens in the defs.'); + } + + if (count_tokens < 1024) { + $('#result_info').html(count_tokens + " Tokens"); + } else { + $('#result_info').html("" + count_tokens + " Tokens(TOO MANY TOKENS)"); + } + } + + $('#characloud_url').click(function () { + window.open('https://boosty.to/tavernai', '_blank'); + }); + function checkOnlineStatus() { + //console.log(online_status); + if (online_status == 'no_connection') { + $("#send_textarea").attr('placeholder', "Not connected to API!"); //Input bar placeholder tells users they are not connected + $("#send_form").css("background-color", "rgba(100,0,0,0.7)"); //entire input form area is red when not connected + $("#send_but").css("display", "none"); //send button is hidden when not connected + + $("#online_status_indicator2").css("background-color", "red"); + $("#online_status_text2").html("No connection..."); + $("#online_status_indicator3").css("background-color", "red"); + $("#online_status_text3").html("No connection..."); + is_get_status = false; + is_get_status_novel = false; + } else { + $("#send_textarea").attr('placeholder', 'Type a message...'); //on connect, placeholder tells user to type message + $("#send_form").css("background-color", "rgba(0,0,0,0.7)"); //on connect, form BG changes to transprent black + $("#send_but").css("display", "inline"); //on connect, send button shows up + + $("#online_status_indicator2").css("background-color", "green"); + $("#online_status_text2").html(online_status); + $("#online_status_indicator3").css("background-color", "green"); + $("#online_status_text3").html(online_status); + $("#online_status_indicator4").css("background-color", "green"); + $("#online_status_text4").html(online_status); + } + } + async function getLastVersion() { + + jQuery.ajax({ + type: 'POST', // + url: '/getlastversion', // + data: JSON.stringify({ + '': '' + }), + beforeSend: function () { + + + }, + cache: false, + dataType: "json", + contentType: "application/json", + //processData: false, + success: function (data) { + var getVersion = data.version; + if (getVersion !== 'error' && getVersion != undefined) { + if (compareVersions(getVersion, VERSION) === 1) { + $('#verson').append(' (v.' + getVersion + ')'); + } + } + + }, + error: function (jqXHR, exception) { + console.log(exception); + console.log(jqXHR); + + } + }); + + } + async function getStatus() { + if (is_get_status) { + jQuery.ajax({ + type: 'POST', // + url: '/getstatus', // + data: JSON.stringify({ + api_server: (main_api == "kobold" ? api_server : api_server_textgenerationwebui), + main_api: main_api, + }), + beforeSend: function () { + if (is_api_button_press) { + //$("#api_loading").css("display", 'inline-block'); + //$("#api_button").css("display", 'none'); + } + //$('#create_button').attr('value','Creating...'); // + + }, + cache: false, + dataType: "json", + crossDomain: true, + contentType: "application/json", + //processData: false, + success: function (data) { + online_status = data.result; + if (online_status == undefined) { + online_status = 'no_connection'; + } + if (online_status.toLowerCase().indexOf('pygmalion') != -1) { + is_pygmalion = true; + online_status += " (Pyg. formatting on)"; + } else { + is_pygmalion = false; + } + + //console.log(online_status); + resultCheckStatus(); + if (online_status !== 'no_connection') { + var checkStatusNow = setTimeout(getStatus, 3000);//getStatus(); + } + }, + error: function (jqXHR, exception) { + console.log(exception); + console.log(jqXHR); + online_status = 'no_connection'; + + resultCheckStatus(); + } + }); + } else { + if (is_get_status_novel != true) { + online_status = 'no_connection'; + } + } + } + function resultCheckStatus() { + is_api_button_press = false; + checkOnlineStatus(); + $("#api_loading").css("display", 'none'); + $("#api_button").css("display", 'inline-block'); + $("#api_loading_textgenerationwebui").css("display", 'none'); + $("#api_button_textgenerationwebui").css("display", 'inline-block'); + } + + async function getSoftPromptsList() { + if (!api_server) { + return; + } + + const response = await fetch('/getsoftprompts', { + method: 'POST', + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ api_server: api_server }), + }); + + if (response.ok) { + const data = await response.json(); + updateSoftPromptsList(data.soft_prompts); + } + } + + function clearSoftPromptsList() { + $('#softprompt option[value!=""]').each(function () { + $(this).remove(); + }); + } + + function updateSoftPromptsList(soft_prompts) { + // Delete SPs removed from Kobold + $('#softprompt option').each(function () { + const value = $(this).attr('value'); + + if (value == '') { + return; + } + + const prompt = soft_prompts.find(x => x.name === value); + if (!prompt) { + $(this).remove(); + } + }); + + // Add SPs added to Kobold + soft_prompts.forEach((prompt) => { + if ($(`#softprompt option[value="${prompt.name}"]`).length === 0) { + $('#softprompt').append(``); + + if (prompt.selected) { + $('#softprompt').val(prompt.name); + } + } + }); + + // No SP selected or no SPs + if (soft_prompts.length === 0 || !(soft_prompts.some(x => x.selected))) { + $('#softprompt').val(''); + } + } + + function printCharacters() { + //console.log('printCharacters() entered'); + + $("#rm_print_characters_block").empty(); + //console.log('printCharacters() -- sees '+characters.length+' characters.'); + characters.forEach(function (item, i, arr) { + + var this_avatar = default_avatar; + if (item.avatar != 'none') { + this_avatar = "characters/" + item.avatar + "?" + Date.now(); + + } //RossAscends: changed 'prepend' to 'append' to make alphabetical sorting display correctly. + $("#rm_print_characters_block").append('
' + item.name + '
'); + //console.log('printcharacters() -- printing -- ChID '+i+' ('+item.name+')'); + }); + printGroups(); + + } + + function printGroups() { + for (let group of groups) { + const template = $('#group_list_template .group_select').clone(); + template.data('id', group.id); + template.find('.ch_name').html(group.name); + $('#rm_print_characters_block').prepend(template); + updateGroupAvatar(group); + } + } + + function updateGroupAvatar(group) { + $('#rm_print_characters_block .group_select').each(function () { + if ($(this).data('id') == group.id) { + const avatar = getGroupAvatar(group); + if (avatar) { + $(this).find('.avatar').replaceWith(avatar); + } + } + }) + } + + function getGroupAvatar(group) { + const memberAvatars = []; + if (group && Array.isArray(group.members) && group.members.length) { + for (const member of group.members) { + const charIndex = characters.findIndex(x => x.name === member); + if (charIndex !== -1 && characters[charIndex].avatar !== 'none') { + const this_avatar = `characters/${characters[charIndex].avatar}#${Date.now()}`; + memberAvatars.push(this_avatar); + } + if (memberAvatars.length === 4) { + break; + } + } + } + + // Cohee: there's probably a smarter way to do this.. + if (memberAvatars.length === 1) { + const groupAvatar = $('#group_avatars_template .collage_1').clone(); + groupAvatar.find('.img_1').attr('src', memberAvatars[0]); + return groupAvatar; + } + + if (memberAvatars.length === 2) { + const groupAvatar = $('#group_avatars_template .collage_2').clone(); + groupAvatar.find('.img_1').attr('src', memberAvatars[0]); + groupAvatar.find('.img_2').attr('src', memberAvatars[1]); + return groupAvatar; + } + + if (memberAvatars.length === 3) { + const groupAvatar = $('#group_avatars_template .collage_3').clone(); + groupAvatar.find('.img_1').attr('src', memberAvatars[0]); + groupAvatar.find('.img_2').attr('src', memberAvatars[1]); + groupAvatar.find('.img_3').attr('src', memberAvatars[2]); + return groupAvatar; + } + + if (memberAvatars.length === 4) { + const groupAvatar = $('#group_avatars_template .collage_4').clone(); + groupAvatar.find('.img_1').attr('src', memberAvatars[0]); + groupAvatar.find('.img_2').attr('src', memberAvatars[1]); + groupAvatar.find('.img_3').attr('src', memberAvatars[2]); + groupAvatar.find('.img_4').attr('src', memberAvatars[3]); + return groupAvatar; + } + + // default avatar + const groupAvatar = $('#group_avatars_template .collage_1').clone(); + groupAvatar.find('.img_1').attr('src', group.avatar_url); + return groupAvatar; + } + + async function getCharacters() { + await getGroups(); + + //console.log('getCharacters() -- entered'); + //console.log(characters); + var response = await fetch("/getcharacters", { //RossAscends: changed from const + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token + }, + body: JSON.stringify({ + "": "" + }) + }); + if (response.ok === true) { + + var getData = ''; //RossAscends: reset to force array to update to account for deleted character. + var getData = await response.json(); //RossAscends: changed from const + //console.log(getData); + + //var aa = JSON.parse(getData[0]); + + var load_ch_count = Object.getOwnPropertyNames(getData); //RossAscends: change from const to create dynamic character load amounts. + var charCount = load_ch_count.length; + //console.log('/getcharacters -- expecting to load '+charCount+' characters.') + for (var i = 0; i < load_ch_count.length; i++) { + characters[i] = []; + characters[i] = getData[i]; + //console.log('/getcharacters -- loaded character #'+(i+1)+' ('+characters[i].name+')'); + } + //RossAscends: updated character sorting to be alphabetical + characters.sort(function (a, b) { + //console.log('sorting characters: '+a.name+' vs '+b.name); + if (a.name < b.name) { + return -1 + } + if (a.name > b.name) { + return 1; + } + return 0; + + }); + //console.log(characters); + + //characters.reverse(); + //console.log('/getcharacters -- this_chid -- '+this_chid); + if (this_chid != undefined && this_chid != 'invalid-safety-id') { + $("#avatar_url_pole").val(characters[this_chid].avatar); + } + + + //console.log('/getcharacters -- sending '+i+' characters to /printcharacters'); + printCharacters(); + //console.log(propOwn.length); + //return JSON.parse(getData[0]); + //const getData = await response.json(); + //var getMessage = getData.results[0].text; + } + } + async function getBackgrounds() { + + const response = await fetch("/getbackgrounds", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token + }, + body: JSON.stringify({ + "": "" + }) + + }); + if (response.ok === true) { + const getData = await response.json(); + //background = getData; + //console.log(getData.length); + for (var i = 0; i < getData.length; i++) { + //console.log(1); + $("#bg_menu_content").append("
"); + } + //var aa = JSON.parse(getData[0]); + //const load_ch_coint = Object.getOwnPropertyNames(getData); + + + } + } + async function isColab() { + is_checked_colab = true; + const response = await fetch("/iscolab", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token + }, + body: JSON.stringify({ + "": "" + }) + + }); + if (response.ok === true) { + const getData = await response.json(); + if (getData.colaburl != false) { + $('#colab_shadow_popup').css('display', 'none'); + is_colab = true; + let url = String(getData.colaburl).split("flare.com")[0] + "flare.com"; + url = String(url).split("loca.lt")[0] + "loca.lt"; + $('#api_url_text').val(url); + setTimeout(function () { + $('#api_button').click(); + }, 2000); + } + + + } + } + async function setBackground(bg) { + /* + const response = await fetch("/setbackground", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + "bg": bg + }) + + }); + if (response.ok === true) { + //const getData = await response.json(); + //background = getData; + + //var aa = JSON.parse(getData[0]); + //const load_ch_coint = Object.getOwnPropertyNames(getData); + }*/ + //console.log(bg); + jQuery.ajax({ + type: 'POST', // + url: '/setbackground', // + data: JSON.stringify({ + bg: bg + }), + beforeSend: function () { + //$('#create_button').attr('value','Creating...'); // + }, + cache: false, + dataType: "json", + contentType: "application/json", + //processData: false, + success: function (html) { + //setBackground(html); + //$('body').css('background-image', 'linear-gradient(rgba(19,21,44,0.75), rgba(19,21,44,0.75)), url('+e.target.result+')'); + //$("#form_bg_download").after("
"); + }, + error: function (jqXHR, exception) { + console.log(exception); + console.log(jqXHR); + } + }); + } + async function delBackground(bg) { + const response = await fetch("/delbackground", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token + }, + body: JSON.stringify({ + "bg": bg + }) + + }); + if (response.ok === true) { + //const getData = await response.json(); + //background = getData; + + //var aa = JSON.parse(getData[0]); + //const load_ch_coint = Object.getOwnPropertyNames(getData); + + + } + } + function printMessages() { + //console.log(chat); + //console.log('printMessages() -- printing messages for -- '+this_chid+' '+active_character+' '+characters[this_chid]); + chat.forEach(function (item, i, arr) { + addOneMessage(item); + }); + } + function clearChat() { + count_view_mes = 0; + extension_prompts = {}; + $('#chat').html(''); + } + function messageFormating(mes, ch_name, isSystem, forceAvatar) { + if (this_chid != undefined && !isSystem) mes = mes.replaceAll("<", "<").replaceAll(">", ">");//for Chloe + if (this_chid === undefined) { + mes = mes.replace(/\*\*(.+?)\*\*/g, '$1').replace(/\*(.+?)\*/g, '$1').replace(/\n/g, '
'); + + } else if (!isSystem) { + mes = converter.makeHtml(mes); + mes = mes.replace(/{([^}]+)}/g, ''); + mes = mes.replace(/\n/g, '
'); + mes = mes.trim(); + } + + if (forceAvatar) { + mes = mes.replaceAll(ch_name + ":", ""); + } + + if (ch_name !== name1) { + mes = mes.replaceAll(name2 + ":", ""); + } + return mes; + } + function appendImageToMessage(mes, messageElement) { + if (mes.extra?.image) { + const image = document.createElement('img'); + image.src = mes.extra?.image; + image.classList.add('img_extra'); + messageElement.find('.mes_text').prepend(image); + } + } + function addOneMessage(mes) { + //var message = mes['mes']; + //message = mes['mes'].replace(/^\s+/g, ''); + //console.log(message.indexOf(name1+":")); + var messageText = mes['mes']; + var characterName = name1; + var avatarImg = "User Avatars/" + user_avatar; + const isSystem = mes.is_system; + generatedPromtCache = ''; + //thisText = thisText.split("\n").join("
"); + var avatarImg = "User Avatars/" + user_avatar; + if (!mes['is_user']) { + if (mes.force_avatar) { + avatarImg = mes.force_avatar; + } + else if (this_chid == undefined || this_chid == "invalid-safety-id") { + avatarImg = "img/chloe.png"; + } + else { + if (characters[this_chid].avatar != 'none') { + avatarImg = "characters/" + characters[this_chid].avatar; + if (is_mes_reload_avatar !== false) { + avatarImg += "?" + is_mes_reload_avatar; + //console.log(avatarImg); + } + } else { + avatarImg = "img/fluffy.png"; + } + } + + characterName = mes.is_system || mes.force_avatar ? mes.name : name2; + } + + //Formating + //messageText = messageText.replace(/\*\*(.+?)\*\*/g, '$1').replace(/\*(.+?)\*/g, '$1').replace(/\n/g, '
'); + //if(characterName != name1){ + //messageText = messageText.replaceAll(name2+":", ""); + //} + //console.log(messageText); + if (count_view_mes == 0) { + messageText = messageText.replace(/{{user}}/gi, name1); + messageText = messageText.replace(/{{char}}/gi, name2); + messageText = messageText.replace(//gi, name1); + messageText = messageText.replace(//gi, name2); + } + messageText = messageFormating(messageText, characterName, isSystem, mes.force_avatar); + const bias = messageFormating(mes.extra?.bias ?? ''); + + $("#chat").append("
" + characterName + "
" + `
${bias}
`); + + const newMessage = $(`#chat [mesid="${count_view_mes}"]`); + newMessage.data('isSystem', isSystem); + + appendImageToMessage(mes, newMessage); + + if (isSystem) { + newMessage.find('.mes_edit').hide(); + } + + if (!if_typing_text) { + //console.log(messageText); + $("#chat").children().filter('[mesid="' + count_view_mes + '"]').children('.mes_block').children('.mes_text').append(messageText); + } else { + typeWriter($("#chat").children().filter('[mesid="' + count_view_mes + '"]').children('.mes_block').children('.mes_text'), messageText, 50, 0); + } + count_view_mes++; + if (!add_mes_without_animation) { + $('#chat').children().last().css("opacity", 1.0); + $('#chat').children().last().transition({ + opacity: 1.0, + duration: 700, + easing: "", + complete: function () { } + }); + } else { + add_mes_without_animation = false; + } + var $textchat = $('#chat'); + $textchat.scrollTop($textchat[0].scrollHeight); + } + function typeWriter(target, text, speed, i) { + if (i < text.length) { + //target.append(text.charAt(i)); + target.html(target.html() + text.charAt(i)); + i++; + setTimeout(() => typeWriter(target, text, speed, i), speed); + } + } + function newMesPattern(name) { //Patern which denotes a new message + name = name + ':'; + return name; + } + + function substituteParams(content) { + content = content.replace(/{{user}}/gi, name1); + content = content.replace(/{{char}}/gi, name2); + content = content.replace(//gi, name1); + content = content.replace(//gi, name2); + return content; + } + + function checkWorldInfo(chat) { + if (world_info_data.entries.length == 0) { + return ''; + } + + const messagesToLookBack = world_info_depth * 2; + let textToScan = chat.slice(0, messagesToLookBack).join('').toLowerCase(); + let worldInfoBefore = ''; + let worldInfoAfter = ''; + let needsToScan = true; + let allActivatedEntries = new Set(); + + const sortedEntries = Object.keys(world_info_data.entries).map(x => world_info_data.entries[x]).sort((a, b) => b.order - a.order); + while (needsToScan) { + let activatedNow = new Set(); + + for (let entry of sortedEntries) { + if (allActivatedEntries.has(entry.uid)) { + continue; + } + + if (entry.constant) { + activatedNow.add(entry.uid); + } + + if (Array.isArray(entry.key) && entry.key.length) { + primary: for (let key of entry.key) { + if (key && textToScan.includes(key.trim().toLowerCase())) { + if (entry.selective && Array.isArray(entry.keysecondary) && entry.keysecondary.length) { + secondary: for (let keysecondary of entry.keysecondary) { + if (keysecondary && textToScan.includes(keysecondary.trim().toLowerCase())) { + activatedNow.add(entry.uid); + break secondary; + } + } + } else { + activatedNow.add(entry.uid); + break primary; + } + } + } + } + } + + needsToScan = activatedNow.size > 0; + const newEntries = [...activatedNow] + .map(x => world_info_data.entries[x]) + .sort((a, b) => sortedEntries.indexOf(a) - sortedEntries.indexOf(b)); + + for (const entry of newEntries) { + if (entry.position === world_info_position.after) { + worldInfoAfter = `${substituteParams(entry.content)}\n${worldInfoAfter}`; + } + else { + worldInfoBefore = `${substituteParams(entry.content)}\n${worldInfoBefore}`; + } + + if (encode(worldInfoBefore + worldInfoAfter).length >= world_info_budget) { + needsToScan = false; + break; + } + } + + if (needsToScan) { + textToScan = newEntries.map(x => x.content).join('\n').toLowerCase() + textToScan; + } + + allActivatedEntries = new Set([...allActivatedEntries, ...activatedNow]); + } + + return { worldInfoBefore, worldInfoAfter }; + } + + function isHelpRequest(message) { + const helpTokens = ['/?', '/help']; + return helpTokens.includes(message.trim().toLowerCase()); + } + + function sendSystemMessage(type, text) { + const systemMessage = system_messages[type]; + + if (!systemMessage) { + return; + } + + const newMessage = { ...systemMessage, 'send_date': humanizedISO8601DateTime() }; + + if (text) { + newMessage.mes = text; + } + + chat.push(newMessage); + addOneMessage(newMessage); + is_send_press = false; + } + + function extractMessageBias(message) { + if (!message) { + return null; + } + + const found = []; + const rxp = /{([^}]+)}/g; + let curMatch; + + while (curMatch = rxp.exec(message)) { + found.push(curMatch[1].trim()); + } + + if (!found.length) { + return ''; + } + + return ` ${found.join(' ')} `; + } + + $("#send_but").click(function () { + //$( "#send_but" ).css({"background": "url('img/load.gif')","background-size": "100%, 100%", "background-position": "center center"}); + if (is_send_press == false) { + is_send_press = true; + + Generate(); + } + }); + async function Generate(type, automatic_trigger) {//encode("dsfs").length + tokens_already_generated = 0; + message_already_generated = name2 + ': '; + + if (isHelpRequest($("#send_textarea").val())) { + sendSystemMessage(system_message_types.HELP); + $("#send_textarea").val('').trigger('input'); + return; + } + + if (selected_group && !is_group_generating) { + generateGroupWrapper(false); + return; + } + + if (online_status != 'no_connection' && this_chid != undefined && this_chid !== 'invalid-safety-id') { + if (type !== 'regenerate') { + var textareaText = $("#send_textarea").val(); + //console.log('Not a Regenerate call, so posting normall with input of: ' +textareaText); + $("#send_textarea").val('').trigger('input'); + + } else { + //console.log('Regenerate call detected') + var textareaText = ""; + if (chat[chat.length - 1]['is_user']) {//If last message from You + + } else { + //console.log('about to remove last msg') + chat.length = chat.length - 1; + count_view_mes -= 1; + //console.log('removing last msg') + $('#chat').children().last().remove(); + } + } + + $("#send_but").css("display", "none"); + $("#loading_mes").css("display", "inline-block"); + + let promptBias = null; + let messageBias = extractMessageBias(textareaText); + + // gets bias of the latest message where it was applied + for (let mes of chat) { + if (mes && mes.is_user && mes.extra && mes.extra.bias) { + promptBias = mes.extra.bias; + } + } + + // bias from the latest message is top priority + promptBias = messageBias ?? promptBias ?? ''; + + var storyString = ""; + var userSendString = ""; + var finalPromt = ""; + + var postAnchorChar = "talks a lot with descriptions";//'Talk a lot with description what is going on around';// in asterisks + var postAnchorStyle = "Writing style: very long messages";//"[Genre: roleplay chat][Tone: very long messages with descriptions]"; + + + var anchorTop = ''; + var anchorBottom = ''; + var topAnchorDepth = 8; + + if (character_anchor && !is_pygmalion) { + if (anchor_order === 0) { + anchorTop = name2 + " " + postAnchorChar; + } else { + anchorBottom = "[" + name2 + " " + postAnchorChar + "]"; + } + } + if (style_anchor && !is_pygmalion) { + if (anchor_order === 1) { + anchorTop = postAnchorStyle; + } else { + anchorBottom = "[" + postAnchorStyle + "]"; + } + } + + //********************************* + //PRE FORMATING STRING + //********************************* + if (textareaText != "" && !automatic_trigger) { + chat[chat.length] = {}; + chat[chat.length - 1]['name'] = name1; + chat[chat.length - 1]['is_user'] = true; + chat[chat.length - 1]['is_name'] = true; + chat[chat.length - 1]['send_date'] = humanizedISO8601DateTime(); + chat[chat.length - 1]['mes'] = textareaText; + chat[chat.length - 1]['extra'] = {}; + + if (messageBias) { + chat[chat.length - 1]['extra']['bias'] = messageBias; + } + + addOneMessage(chat[chat.length - 1]); + } + var chatString = ''; + var arrMes = []; + var mesSend = []; + var charDescription = $.trim(characters[this_chid].description); + var charPersonality = $.trim(characters[this_chid].personality); + var Scenario = $.trim(characters[this_chid].scenario); + var mesExamples = $.trim(characters[this_chid].mes_example); + var checkMesExample = $.trim(mesExamples.replace(//gi, ''));//for check length without tag + if (checkMesExample.length == 0) mesExamples = ''; + var mesExamplesArray = []; + //***Base replace*** + if (mesExamples !== undefined) { + if (mesExamples.length > 0) { + if (is_pygmalion) { + mesExamples = mesExamples.replace(/{{user}}:/gi, 'You:'); + mesExamples = mesExamples.replace(/:/gi, 'You:'); + } + mesExamples = mesExamples.replace(/{{user}}/gi, name1); + mesExamples = mesExamples.replace(/{{char}}/gi, name2); + mesExamples = mesExamples.replace(//gi, name1); + mesExamples = mesExamples.replace(//gi, name2); + //mesExamples = mesExamples.replaceAll('', '[An example of how '+name2+' responds]'); + let blocks = mesExamples.split(//gi); + mesExamplesArray = blocks.slice(1).map(block => `\n${block.trim()}\n`); + } + } + if (charDescription !== undefined) { + if (charDescription.length > 0) { + charDescription = charDescription.replace(/{{user}}/gi, name1); + charDescription = charDescription.replace(/{{char}}/gi, name2); + charDescription = charDescription.replace(//gi, name1); + charDescription = charDescription.replace(//gi, name2); + } + } + if (charPersonality !== undefined) { + if (charPersonality.length > 0) { + charPersonality = charPersonality.replace(/{{user}}/gi, name1); + charPersonality = charPersonality.replace(/{{char}}/gi, name2); + charPersonality = charPersonality.replace(//gi, name1); + charPersonality = charPersonality.replace(//gi, name2); + } + } + if (Scenario !== undefined) { + if (Scenario.length > 0) { + Scenario = Scenario.replace(/{{user}}/gi, name1); + Scenario = Scenario.replace(/{{char}}/gi, name2); + Scenario = Scenario.replace(//gi, name1); + Scenario = Scenario.replace(//gi, name2); + } + } + + + if (is_pygmalion) { + if (charDescription.length > 0) { + storyString = name2 + "'s Persona: " + charDescription + "\n"; + } + if (charPersonality.length > 0) { + storyString += 'Personality: ' + charPersonality + '\n'; + } + if (Scenario.length > 0) { + storyString += 'Scenario: ' + Scenario + '\n'; + } + } else { + if (charDescription !== undefined) { + if (charPersonality.length > 0) { + charPersonality = name2 + "'s personality: " + charPersonality;//"["+name2+"'s personality: "+charPersonality+"]"; + } + } + if (charDescription !== undefined) { + if ($.trim(charDescription).length > 0) { + if (charDescription.slice(-1) !== ']' || charDescription.substr(0, 1) !== '[') { + //charDescription = '['+charDescription+']'; + } + storyString += charDescription + '\n'; + } + } + + if (count_view_mes < topAnchorDepth) { + storyString += charPersonality + '\n'; + } + + + } + + var count_exm_add = 0; + var chat2 = []; + var j = 0; + for (var i = chat.length - 1; i >= 0; i--) { + if (j == 0) { + chat[j]['mes'] = chat[j]['mes'].replace(/{{user}}/gi, name1); + chat[j]['mes'] = chat[j]['mes'].replace(/{{char}}/gi, name2); + chat[j]['mes'] = chat[j]['mes'].replace(//gi, name1); + chat[j]['mes'] = chat[j]['mes'].replace(//gi, name2); + } + let this_mes_ch_name = ''; + if (chat[j]['is_user']) { + this_mes_ch_name = name1; + } else { + this_mes_ch_name = name2; + } + if (chat[j]['is_name']) { + chat2[i] = this_mes_ch_name + ': ' + chat[j]['mes'] + '\n'; + } else { + chat2[i] = chat[j]['mes'] + '\n'; + } + // system messages produce no text + if (chat[j]['is_system']) { + chat2[i] = ''; + } + // replace bias markup + chat2[i] = (chat2[i] ?? '').replace(/{([^}]+)}/g, ''); + j++; + } + //chat2 = chat2.reverse(); + var this_max_context = 1487; + if (main_api == 'kobold') this_max_context = max_context; + if (main_api == 'novel') { + if (novel_tier === 1) { + this_max_context = 1024; + } else { + this_max_context = 2048 - 60;//fix for fat tokens + if (model_novel == 'krake-v2') { + this_max_context -= 160; + } + } + } + + let worldInfoString = '', worldInfoBefore = '', worldInfoAfter = ''; + + if (world_info && world_info_data) { + const activatedWorldInfo = checkWorldInfo(chat2); + worldInfoBefore = activatedWorldInfo.worldInfoBefore; + worldInfoAfter = activatedWorldInfo.worldInfoAfter; + worldInfoString = worldInfoBefore + worldInfoAfter; + } + + let extension_prompt = Object.keys(extension_prompts).sort().map(x => extension_prompts[x]).filter(x => x).join('\n'); + if (extension_prompt.length && !extension_prompt.endsWith('\n')) { + extension_prompt += '\n'; + } + + var i = 0; + + for (var item of chat2) {//console.log(encode("dsfs").length); + chatString = item + chatString; + if (encode(JSON.stringify(worldInfoString + storyString + chatString + anchorTop + anchorBottom + charPersonality + promptBias + extension_prompt)).length + 120 < this_max_context) { //(The number of tokens in the entire promt) need fix, it must count correctly (added +120, so that the description of the character does not hide) + + + //if (is_pygmalion && i == chat2.length-1) item='\n'+item; + arrMes[arrMes.length] = item; + } else { + i = chat.length - 1; + } + await delay(1); //For disable slow down (encode gpt-2 need fix) + //console.log(i+' '+chat.length); + count_exm_add = 0; + if (i == chat.length - 1) { + //arrMes[arrMes.length-1] = '\n'+arrMes[arrMes.length-1]; + let mesExmString = ''; + for (let iii = 0; iii < mesExamplesArray.length; iii++) {//mesExamplesArray It need to make from end to start + mesExmString = mesExmString + mesExamplesArray[iii]; + if (encode(JSON.stringify(worldInfoString + storyString + mesExmString + chatString + anchorTop + anchorBottom + charPersonality + promptBias + extension_prompt)).length + 120 < this_max_context) { //example of dialogs + if (!is_pygmalion) { + mesExamplesArray[iii] = mesExamplesArray[iii].replace(//i, 'This is how ' + name2 + ' should talk');//An example of how '+name2+' responds + } + count_exm_add++; + await delay(1); + + //arrMes[arrMes.length] = item; + } else { + + iii = mesExamplesArray.length; + } + + } + + if (!is_pygmalion) { + if (Scenario !== undefined) { + if (Scenario.length > 0) { + storyString += 'Circumstances and context of the dialogue: ' + Scenario + '\n'; + } + } + //storyString+='\nThen the roleplay chat between '+name1+' and '+name2+' begins.\n'; + } + runGenerate(); + return; + } + i++; + + + } + + function runGenerate(cycleGenerationPromt = '') { + + + generatedPromtCache += cycleGenerationPromt; + if (generatedPromtCache.length == 0) { + chatString = ""; + arrMes = arrMes.reverse(); + var is_add_personality = false; + arrMes.forEach(function (item, i, arr) {//For added anchors and others + + if (i >= arrMes.length - 1 && $.trim(item).substr(0, (name1 + ":").length) != name1 + ":") { + if (textareaText == "") { + item = item.substr(0, item.length - 1); + } + } + if (i === arrMes.length - topAnchorDepth && count_view_mes >= topAnchorDepth && !is_add_personality) { + + is_add_personality = true; + //chatString = chatString.substr(0,chatString.length-1); + //anchorAndPersonality = "[Genre: roleplay chat][Tone: very long messages with descriptions]"; + if ((anchorTop != "" || charPersonality != "") && !is_pygmalion) { + if (anchorTop != "") charPersonality += ' '; + item += "[" + charPersonality + anchorTop + ']\n'; + } + } + if (i >= arrMes.length - 1 && count_view_mes > 8 && $.trim(item).substr(0, (name1 + ":").length) == name1 + ":" && !is_pygmalion) {//For add anchor in end + item = item.substr(0, item.length - 1); + //chatString+=postAnchor+"\n";//"[Writing style: very long messages]\n"; + item = item + anchorBottom + "\n"; + } + if (is_pygmalion) { + if (i >= arrMes.length - 1 && $.trim(item).substr(0, (name1 + ":").length) == name1 + ":") {//for add name2 when user sent + item = item + name2 + ":"; + } + if (i >= arrMes.length - 1 && $.trim(item).substr(0, (name1 + ":").length) != name1 + ":") {//for add name2 when continue + if (textareaText == "") { + item = item + '\n' + name2 + ":"; + } + } + if ($.trim(item).indexOf(name1) === 0) { + item = item.replace(name1 + ':', 'You:'); + } + } + mesSend[mesSend.length] = item; + //chatString = chatString+item; + }); + } + //finalPromt +=chatString; + //console.log(storyString); + + //console.log(encode(characters[this_chid].description+chatString).length); + //console.log(encode(JSON.stringify(characters[this_chid].description+chatString)).length); + if (type == 'force_name2') { + finalPromt += name2 + ':'; + } + //console.log(JSON.stringify(storyString)); + //Send story string + var mesSendString = ''; + var mesExmString = ''; + + function setPromtString() { + mesSendString = ''; + mesExmString = ''; + for (let j = 0; j < count_exm_add; j++) { + mesExmString += mesExamplesArray[j]; + } + for (let j = 0; j < mesSend.length; j++) { + mesSendString += mesSend[j]; + } + } + + function checkPromtSize() { + setPromtString(); + let thisPromtContextSize = encode(JSON.stringify(worldInfoString + storyString + mesExmString + mesSendString + anchorTop + anchorBottom + charPersonality + generatedPromtCache + promptBias + extension_prompt)).length + 120; + + if (thisPromtContextSize > this_max_context) { //if the prepared prompt is larger than the max context size... + + if (count_exm_add > 0) { // ..and we have example mesages.. + //console.log('Context size: '+thisPromtContextSize+' -- too big, removing example message'); + //mesExamplesArray.length = mesExamplesArray.length-1; + count_exm_add--; // remove the example messages... + checkPromtSize(); // and try agin... + } else if (mesSend.length > 0) { // if the chat history is longer than 0 + //console.log('Context size: '+thisPromtContextSize+' -- too big, removing oldest chat message'); + mesSend.shift(); // remove the first (oldest) chat entry.. + checkPromtSize(); // and check size again.. + } else { + //end + } + } + } + + + + if (generatedPromtCache.length > 0) { + //console.log('Generated Prompt Cache length: '+generatedPromtCache.length); + checkPromtSize(); + } else { + setPromtString(); + } + + if (!is_pygmalion) { + mesSendString = '\nThen the roleplay chat between ' + name1 + ' and ' + name2 + ' begins.\n' + mesSendString; + } else { + mesSendString = '\n' + mesSendString; + //mesSendString = mesSendString; //This edit simply removes the first "" that is prepended to all context prompts + } + finalPromt = worldInfoBefore + storyString + worldInfoAfter + extension_prompt + mesExmString + mesSendString + generatedPromtCache + promptBias; + finalPromt = finalPromt.replace(/\r/gm, ''); + + //if we aren't using the kobold GUI settings... + if (main_api == 'textgenerationwebui' || main_api == 'kobold' && preset_settings != 'gui') { + var this_settings = koboldai_settings[koboldai_setting_names[preset_settings]]; + + var this_amount_gen = parseInt(amount_gen); // how many tokens the AI will be requested to generate + if (is_pygmalion) { // if we are using a pygmalion model... + if (tokens_already_generated === 0) { // if nothing has been generated yet.. + if (parseInt(amount_gen) >= 50) { // if the max gen setting is > 50...( + this_amount_gen = 50; // then only try to make 50 this cycle.. + } + else { + this_amount_gen = parseInt(amount_gen); // otherwise, make as much as the max amount request. + } + } + else { // if we already recieved some generated text... + if (parseInt(amount_gen) - tokens_already_generated < tokens_cycle_count) { // if the remaining tokens to be made is less than next potential cycle count + this_amount_gen = parseInt(amount_gen) - tokens_already_generated; // subtract already generated amount from the desired max gen amount + } + else { + this_amount_gen = tokens_cycle_count; // otherwise make the standard cycle amont (frist 50, and 30 after that) + } + } + } + } + + var generate_data; + if (main_api == 'kobold') { + var generate_data = { prompt: finalPromt, gui_settings: true, max_length: amount_gen, temperature: temp, max_context_length: max_context }; + if (preset_settings != 'gui') { + + generate_data = { + prompt: finalPromt, + gui_settings: false, + sampler_order: this_settings.sampler_order, + max_context_length: parseInt(max_context),//this_settings.max_length, + max_length: this_amount_gen,//parseInt(amount_gen), + rep_pen: parseFloat(rep_pen), + rep_pen_range: parseInt(rep_pen_size), + rep_pen_slope: this_settings.rep_pen_slope, + temperature: parseFloat(temp), + tfs: this_settings.tfs, + top_a: this_settings.top_a, + top_k: this_settings.top_k, + top_p: this_settings.top_p, + typical: this_settings.typical, + s1: this_settings.sampler_order[0], + s2: this_settings.sampler_order[1], + s3: this_settings.sampler_order[2], + s4: this_settings.sampler_order[3], + s5: this_settings.sampler_order[4], + s6: this_settings.sampler_order[5], + s7: this_settings.sampler_order[6], + use_world_info: false, + }; + } + } + + if (main_api == 'textgenerationwebui') { + const doSample = textgenerationwebui_settings.penalty_alpha == 0; + var generate_data = { + data: [ + finalPromt, + this_amount_gen, // min_length + doSample, // do_sample + textgenerationwebui_settings.temp, // temperature + textgenerationwebui_settings.top_p, // top_p + textgenerationwebui_settings.typical_p, // typical_p + textgenerationwebui_settings.rep_pen, // repetition_penalty + textgenerationwebui_settings.top_k, // top_k + 0, // min_length + textgenerationwebui_settings.rep_pen_size, // no_repeat_ngram_size + 1, // num_beams + textgenerationwebui_settings.penalty_alpha, // penalty_alpha + 1, // length_penalty + false, // early_stopping + name1, // name1 + name2, // name2 + "", // Context + true, // stop at newline + max_context, // Maximum prompt size in tokens + 1, // num attempts + ] + }; + } + + if (main_api == 'novel') { + var this_settings = novelai_settings[novelai_setting_names[preset_settings_novel]]; + generate_data = { + "input": finalPromt, + "model": model_novel, + "use_string": true, + "temperature": parseFloat(temp_novel), + "max_length": this_settings.max_length, + "min_length": this_settings.min_length, + "tail_free_sampling": this_settings.tail_free_sampling, + "repetition_penalty": parseFloat(rep_pen_novel), + "repetition_penalty_range": parseInt(rep_pen_size_novel), + "repetition_penalty_frequency": this_settings.repetition_penalty_frequency, + "repetition_penalty_presence": this_settings.repetition_penalty_presence, + //"stop_sequences": {{187}}, + //bad_words_ids = {{50256}, {0}, {1}}; + //generate_until_sentence = true; + "use_cache": false, + //use_string = true; + "return_full_text": false, + "prefix": "vanilla", + "order": this_settings.order + }; + } + var generate_url = ''; + if (main_api == 'kobold') { + generate_url = '/generate'; + } else if (main_api == 'textgenerationwebui') { + generate_url = '/generate_textgenerationwebui'; + } else if (main_api == 'novel') { + generate_url = '/generate_novelai'; + } + jQuery.ajax({ + type: 'POST', // + url: generate_url, // + data: JSON.stringify(generate_data), + beforeSend: function () { + //$('#create_button').attr('value','Creating...'); + }, + cache: false, + dataType: "json", + contentType: "application/json", + success: function (data) { + tokens_already_generated += this_amount_gen; // add new gen amt to any prev gen counter.. + + + //console.log('Tokens requested in total: '+tokens_already_generated); + //$("#send_textarea").focus(); + //$("#send_textarea").removeAttr('disabled'); + is_send_press = false; + if (!data.error) { + //const getData = await response.json(); + var getMessage = ""; + if (main_api == 'kobold') { + getMessage = data.results[0].text; + } else if (main_api == 'textgenerationwebui') { + getMessage = data.data[0]; + if (getMessage == null) { + runGenerate(""); + return; + } + getMessage = getMessage.substring(finalPromt.length); + } else if (main_api == 'novel') { + getMessage = data.output; + } + + if (collapse_newlines) { + getMessage = getMessage.replaceAll(/\n+/g, "\n"); + } + + //Pygmalion run again // to make it continue generating so long as it's under max_amount and hasn't signaled + // an end to the character's response via typing "You:" or adding "" + if (is_pygmalion) { + if_typing_text = false; + message_already_generated += getMessage; + promptBias = ''; + //console.log('AI Response so far: '+message_already_generated); + if (message_already_generated.indexOf('You:') === -1 && //if there is no 'You:' in the response msg + message_already_generated.indexOf('<|endoftext|>') === -1 && //if there is no stamp in the response msg + tokens_already_generated < parseInt(amount_gen) && //if the gen'd msg is less than the max response length.. + getMessage.length > 0) { //if we actually have gen'd text at all... + runGenerate(getMessage); //generate again with the 'GetMessage' argument.. + return; + } + + getMessage = message_already_generated; + + } + //Formating + getMessage = $.trim(getMessage); + if (is_pygmalion) { + getMessage = getMessage.replace(new RegExp('', "g"), name1); + getMessage = getMessage.replace(new RegExp('', "g"), name2); + getMessage = getMessage.replace(new RegExp('You:', "g"), name1 + ':'); + } + if (getMessage.indexOf(name1 + ":") != -1) { + getMessage = getMessage.substr(0, getMessage.indexOf(name1 + ":")); + + } + if (getMessage.indexOf('<|endoftext|>') != -1) { + getMessage = getMessage.substr(0, getMessage.indexOf('<|endoftext|>')); + + } + // clean-up group message from excessive generations + if (type == 'group_chat' && selected_group) { + const group = groups.find(x => x.id == selected_group); + + if (group && Array.isArray(group.members) && group.members) { + for (let member of group.members) { + // Skip current speaker. + if (member === name2) { + continue; + } + + const indexOfMember = getMessage.indexOf(member + ":"); + if (indexOfMember != -1) { + getMessage = getMessage.substr(0, indexOfMember); + } + } + } + } + let this_mes_is_name = true; + if (getMessage.indexOf(name2 + ":") === 0) { + getMessage = getMessage.replace(name2 + ':', ''); + getMessage = getMessage.trimStart(); + } else { + this_mes_is_name = false; + } + if (type === 'force_name2') this_mes_is_name = true; + //getMessage = getMessage.replace(/^\s+/g, ''); + if (getMessage.length > 0) { + chat[chat.length] = {}; + chat[chat.length - 1]['name'] = name2; + chat[chat.length - 1]['is_user'] = false; + chat[chat.length - 1]['is_name'] = this_mes_is_name; + chat[chat.length - 1]['send_date'] = humanizedISO8601DateTime(); + getMessage = $.trim(getMessage); + chat[chat.length - 1]['mes'] = getMessage; + + if (type === 'group_chat') { + let avatarImg = 'img/fluffy.png'; + if (characters[this_chid].avatar != 'none') { + avatarImg = `characters/${characters[this_chid].avatar}?${Date.now()}`; + } + chat[chat.length - 1]['is_name'] = true; + chat[chat.length - 1]['force_avatar'] = avatarImg; + } + + addOneMessage(chat[chat.length - 1]); + $("#send_but").css("display", "inline"); + $("#loading_mes").css("display", "none"); + + if (type == 'group_chat' && selected_group) { + saveGroupChat(selected_group); + } else { + saveChat(); + } + //console.log('/savechat called by /Generate'); + //let final_message_length = encode(JSON.stringify(getMessage)).length; + //console.log('AI Response: +'+getMessage+ '('+final_message_length+' tokens)'); + } else { + Generate('force_name2'); + } + } else { + $("#send_but").css("display", "inline"); + $("#loading_mes").css("display", "none"); + } + }, + error: function (jqXHR, exception) { + + $("#send_textarea").removeAttr('disabled'); + is_send_press = false; + $("#send_but").css("display", "inline"); + $("#loading_mes").css("display", "none"); + console.log(exception); + console.log(jqXHR); + } + }); + } + } else { + if (this_chid == undefined || this_chid == 'invalid-safety-id') { + //send ch sel + popup_type = 'char_not_selected'; + callPopup('

Сharacter is not selected

'); + } + is_send_press = false; + } + } + async function saveChat() { + chat.forEach(function (item, i) { + if (item['is_user']) { + var str = item['mes'].replace(name1 + ':', default_user_name + ':'); + chat[i]['mes'] = str; + chat[i]['name'] = default_user_name; + } + }); + var save_chat = [{ user_name: default_user_name, character_name: name2, create_date: chat_create_date }, ...chat]; + jQuery.ajax({ + type: 'POST', + url: '/savechat', + data: JSON.stringify({ ch_name: characters[this_chid].name, file_name: characters[this_chid].chat, chat: save_chat, avatar_url: characters[this_chid].avatar }), + beforeSend: function () { + //$('#create_button').attr('value','Creating...'); + }, + cache: false, + dataType: "json", + contentType: "application/json", + success: function (data) { + + }, + error: function (jqXHR, exception) { + + console.log(exception); + console.log(jqXHR); + } + }); + } + async function getChat() { + console.log('/getchat -- entered for -- ' + characters[this_chid].name); + jQuery.ajax({ + type: 'POST', + url: '/getchat', + data: JSON.stringify({ ch_name: characters[this_chid].name, file_name: characters[this_chid].chat, avatar_url: characters[this_chid].avatar }), + beforeSend: function () { + //$('#create_button').attr('value','Creating...'); + }, + cache: false, + dataType: "json", + contentType: "application/json", + success: function (data) { + //console.log(data); + //chat.length = 0; + if (data[0] !== undefined) { + for (let key in data) { + chat.push(data[key]); + } + //chat = data; + chat_create_date = chat[0]['create_date']; + //console.log('/getchat saw chat_create_date: '+chat_create_date); + chat.shift(); + + } else { + chat_create_date = humanizedISO8601DateTime(); + } + //console.log(chat); + getChatResult(); + saveChat(); + }, + error: function (jqXHR, exception) { + getChatResult(); + console.log(exception); + console.log(jqXHR); + } + }); + } + function getChatResult() { + name2 = characters[this_chid].name; + if (chat.length > 1) { + + chat.forEach(function (item, i) { + if (item['is_user']) { + var str = item['mes'].replace(default_user_name + ':', name1 + ':'); + chat[i]['mes'] = str; + chat[i]['name'] = name1; + } + }); + + + } else { + //console.log(characters[this_chid].first_mes); + chat[0] = {}; + chat[0]['name'] = name2; + chat[0]['is_user'] = false; + chat[0]['is_name'] = true; + chat[0]['send_date'] = humanizedISO8601DateTime(); + if (characters[this_chid].first_mes != "") { + chat[0]['mes'] = characters[this_chid].first_mes; + } else { + chat[0]['mes'] = default_ch_mes; + } + } + printMessages(); + select_selected_character(this_chid); + } + + //hotkey to send input with enter (shift+enter generates a new line in the chat input box) + //this is not ideal for touch device users with virtual keyboards. + //ideally we would detect if the user is using a virtual keyboard, and disable this shortcut for them. + //because mobile users' hands are always near the screen, tapping the send button is better for them, and enter should always make a new line. + //note: CAI seems to have this handled. PC: shift+enter = new line, enter = send. iOS: shift+enter AND enter both make new lines, and only the send button sends. + //maybe a way to simulate this would be to disable the eventListener for people iOS. + + $("#send_textarea").keydown(function (e) { + if (!e.shiftKey && !e.ctrlKey && e.key == "Enter" && is_send_press == false) { + is_send_press = true; + e.preventDefault(); + Generate(); + } + }); + + //RossAscends: Additional hotkeys + document.addEventListener('keydown', (event) => { + + if (event.ctrlKey && event.key == "Enter") { // Ctrl+Enter for Regeneration Last Response + + if (is_send_press == false) { + is_send_press = true; + Generate('regenerate'); + } + } else if (event.ctrlKey && event.key == "ArrowUp") { //Ctrl+UpArrow for Connect to last server + + document.getElementById('api_button').click(); + + } + }); + + //menu buttons setup + var selected_button_style = {}; + var deselected_button_style = {}; + + $("#rm_button_create").css("class", "deselected-right-tab"); + $("#rm_button_characters").css("class", "deselected-right-tab"); + + $("#rm_button_settings").click(function () { + selected_button = 'settings'; + menu_type = 'settings'; + $("#rm_characters_block").css("display", "none"); + $("#rm_api_block").css("display", "grid"); + $('#rm_api_block').css('opacity', 0.0); + $('#rm_api_block').transition({ + opacity: 1.0, + duration: animation_rm_duration, + easing: animation_rm_easing, + complete: function () { } + }); + + $("#rm_ch_create_block").css("display", "none"); + $("#rm_info_block").css("display", "none"); + $("#rm_group_chats_block").css("display", "none"); + $("#rm_button_characters").css("class", "deselected-right-tab"); + $("#rm_button_settings").css("class", "selected-right-tab"); + $("#rm_button_selected_ch").css("class", "deselected-right-tab"); + }); + $("#rm_button_characters").click(function () { + selected_button = 'characters'; + select_rm_characters(); + }); + $("#rm_button_back").click(function () { + selected_button = 'characters'; + select_rm_characters(); + }); + $("#rm_button_create").click(function () { + selected_button = 'create'; + select_rm_create(); + }); + $("#rm_button_selected_ch").click(function () { + selected_button = 'character_edit'; + select_selected_character(this_chid); + }); + $(document).on('click', '.group_select', async function () { + const id = $(this).data('id'); + selected_button = 'group_chats'; + + if (!is_send_press && !is_group_generating) { + if (selected_group !== id) { + selected_group = id; + this_chid = undefined; + this_edit_mes_id = undefined; + clearChat(); + chat.length = 0; + await getGroupChat(id); + } + + select_group_chats(id); + } + }); + $("#rm_button_group_chats").click(function () { + selected_button = 'group_chats'; + select_group_chats(); + }); + $("#rm_button_back_from_group").click(function () { + selected_button = 'characters'; + select_rm_characters(); + }); + $('#rm_group_filter').on('input', function () { + const searchValue = $(this).val().trim().toLowerCase(); + + if (!searchValue) { + $("#rm_group_add_members .group_member").show(); + } else { + $("#rm_group_add_members .group_member").each(function () { + $(this).children('.ch_name').text().toLowerCase().includes(searchValue) + ? $(this).show() + : $(this).hide(); + }); + } + }); + $('#rm_group_submit').click(async function () { + let name = $('#rm_group_chat_name').val(); + const members = $('#rm_group_members .group_member').map((_, x) => $(x).data('id')).toArray(); + + if (!name) { + name = `Chat with ${members.join(', ')}`; + } + + // placeholder + const avatar_url = '/img/five.png'; + + const createGroupResponse = await fetch('/creategroup', { + method: 'POST', + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ name: name, members: members, avatar_url: avatar_url }), + }); + + if (createGroupResponse.ok) { + const createGroupData = await createGroupResponse.json(); + const id = createGroupData.id; + + await getCharacters(); + $('#rm_info_avatar').html(''); + var avatar = $('#avatar_div_div').clone(); + avatar.find('img').attr('src', avatar_url); + $('#rm_info_avatar').append(avatar); + $('#rm_info_block').transition({ opacity: 0, duration: 0 }); + select_rm_info("Group chat created"); + $('#rm_info_block').transition({ opacity: 1.0, duration: 2000 }); + } + }); + async function generateGroupWrapper(by_auto_mode) { + if (online_status === 'no_connection') { + is_group_generating = false; + is_send_press = false; + return; + } + + const group = groups.find(x => x.id === selected_group); + + if (!group || !Array.isArray(group.members) || !group.members.length) { + sendSystemMessage(system_message_types.EMPTY); + return; + } + + try { + is_group_generating = true; + this_chid = undefined; + name2 = ''; + const userInput = $("#send_textarea").val(); + + let typingIndicator = $('#chat .typing_indicator'); + + if (typingIndicator.length === 0) { + typingIndicator = $('#typing_indicator_template .typing_indicator').clone(); + typingIndicator.hide(); + $('#chat').append(typingIndicator); + } + + let messagesBefore = chat.length; + let activationText = ''; + if (userInput && userInput.length && !by_auto_mode) { + activationText = userInput; + messagesBefore++; + } else { + const lastMessage = chat[chat.length - 1]; + if (lastMessage && !lastMessage.is_system) { + activationText = lastMessage.mes; + } + } + + const activatedMembers = activateMembers(group.members, activationText); + // now the real generation begins: cycle through every character + for (const chId of activatedMembers) { + this_chid = chId; + name2 = characters[chId].name; + + await Generate('group_chat', by_auto_mode); + + // update indicator and scroll down + typingIndicator.find('.typing_indicator_name').text(characters[chId].name); + $('#chat').append(typingIndicator); + typingIndicator.show(250, function () { + typingIndicator.get(0).scrollIntoView({ behavior: 'smooth' }); + }); + + while (true) { + // check if message generated already + if (chat.length == messagesBefore) { + await delay(10); + } else { + messagesBefore++; + break; + } + } + + // hide and reapply the indicator to the bottom of the list + typingIndicator.hide(250); + $('#chat').append(typingIndicator); + } + + } finally { + is_group_generating = false; + is_send_press = false; + this_chid = undefined; + } + } + function activateMembers(members, input) { + let activatedNames = []; + + // find mentions + if (input && input.length) { + for (let inputWord of extractAllWords(input)) { + for (let member of members) { + if (extractAllWords(member).includes(inputWord)) { + activatedNames.push(member); + break; + } + } + } + } + + // activation by talkativeness (in shuffled order) + const shuffledMembers = shuffle([...members]); + for (let member of shuffledMembers) { + const character = characters.find(x => x.name === member); + + if (!character) { + continue; + } + + const rollValue = Math.random(); + let talkativeness = Number(character.talkativeness); + talkativeness = Number.isNaN(talkativeness) ? talkativeness_default : talkativeness; + if (talkativeness >= rollValue) { + activatedNames.push(member); + } + } + + // pick 1 at random if no one was activated + if (activatedNames.length === 0) { + const randomIndex = Math.floor(Math.random() * members.length); + activatedNames.push(members[randomIndex]); + } + + // de-duplicate array of names + activatedNames = activatedNames.filter(onlyUnique); + + // map to character ids + const memberIds = activatedNames.map(x => characters.findIndex(y => y.name === x)).filter(x => x !== -1); + return memberIds; + } + function extractAllWords(value) { + const words = []; + + if (!value) { + return words; + } + + const matches = value.matchAll(/\b\w+\b/gmi); + for (let match of matches) { + words.push(match[0].toLowerCase()); + } + return words; + } + async function getGroupChat(id) { + const response = await fetch('/getgroupchat', { + method: 'POST', + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ id: id }), + }); + + if (response.ok) { + const data = await response.json(); + if (Array.isArray(data) && data.length) { + for (let key of data) { + chat.push(key); + } + printMessages(); + } + else { + sendSystemMessage(system_message_types.GROUP); + const group = groups.find(x => x.id === id); + if (group && Array.isArray(group.members)) { + for (let name of group.members) { + const character = characters.find(x => x.name === name); + + if (!character) { + continue; + } + + const mes = {}; + mes['is_user'] = false; + mes['is_system'] = false; + mes['name'] = character.name; + mes['is_name'] = true; + mes['send_date'] = humanizedISO8601DateTime(); + mes['mes'] = character.first_mes ? substituteParams(character.first_mes.trim()) : mes['mes'] = default_ch_mes; + mes['force_avatar'] = character.avatar != 'none' ? `characters/${character.avatar}?${Date.now()}` : 'img/fluffy.png'; + chat.push(mes); + addOneMessage(mes); + } + } + } + + await saveGroupChat(id); + } + } + async function saveGroupChat(id) { + const response = await fetch('/savegroupchat', { + method: 'POST', + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ id: id, chat: [...chat] }) + }); + } + async function getGroups() { + const response = await fetch('/getgroups', { + method: 'POST', + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + }); + + if (response.ok) { + const data = await response.json(); + groups = data.sort((a, b) => a.id - b.id); + } + } + async function deleteGroup(id) { + const response = await fetch('/deletegroup', { + method: 'POST', + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ id: id }), + }); + + if (response.ok) { + active_character = 'invalid-safety-id'; //unsets the chid in settings (this prevents AutoLoadChat from trying to load the wrong ChID + this_chid = 'invalid-safety-id'; //unsets expected chid before reloading (related to getCharacters/printCharacters from using old arrays) + selected_group = null; + characters.length = 0; // resets the characters array, forcing getcharacters to reset + name2 = "Chloe"; // replaces deleted charcter name with Chloe, since she wil be displayed next. + chat = [...safetychat]; // sets up chloe to tell user about having deleted a character + + QuickRefresh(); + $('#rm_info_avatar').html(''); + $('#rm_info_block').transition({ opacity: 0, duration: 0 }); + select_rm_info("Group deleted!"); + $('#rm_info_block').transition({ opacity: 1.0, duration: 2000 }); + } + + } + async function editGroup(id, immediately) { + const group = groups.find(x => x.id == id); + + if (!group) { + return; + } + + async function _save() { + const response = await fetch('/editgroup', { + method: 'POST', + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify(group), + }); + } + + if (immediately) { + return await _save(); + } + + clearTimeout(timerGroupSave); + timerGroupSave = setTimeout(async () => await _save(), durationSaveEdit); + } + async function groupChatAutoModeWorker() { + if (!is_group_automode_enabled || online_status === 'no_connection') { + return; + } + + if (!selected_group || is_send_press || is_group_generating) { + return; + } + + const group = groups.find(x => x.id === selected_group); + + if (!group || !Array.isArray(group.members) || !group.members.length) { + return; + } + + await generateGroupWrapper(true); + } + + function select_group_chats(chat_id) { + menu_type = 'group_chats'; + const group = chat_id && groups.find(x => x.id == chat_id); + const groupName = group?.name ?? ''; + + $('#rm_group_chat_name').val(groupName); + $('#rm_group_chat_name').off(); + $('#rm_group_chat_name').on('input', async function () { + if (chat_id) { + group.name = $(this).val(); + await editGroup(chat_id); + } + }); + $('#rm_group_filter').val('').trigger('input'); + $("#rm_group_chats_block").css("display", "flex"); + $('#rm_group_chats_block').css('opacity', 0.0); + $('#rm_group_chats_block').transition({ + opacity: 1.0, + duration: animation_rm_duration, + easing: animation_rm_easing, + complete: function () { } + }); + + $("#rm_ch_create_block").css("display", "none"); + $("#rm_characters_block").css("display", "none"); + + async function memberClickHandler(event) { + event.stopPropagation(); + const id = $(this).data('id'); + const isDelete = !!($(this).closest('#rm_group_members').length); + const template = $(this).clone(); + template.data('id', id); + template.click(memberClickHandler); + + if (isDelete) { + template.find('.plus').show(); + template.find('.minus').hide(); + $('#rm_group_add_members').prepend(template); + } else { + template.find('.plus').hide(); + template.find('.minus').show(); + $('#rm_group_members').prepend(template); + } + + if (group) { + if (isDelete) { + const index = group.members.findIndex(x => x === id); + if (index !== -1) { + group.members.splice(index, 1); + } + } else { + group.members.push(id); + } + await editGroup(chat_id); + updateGroupAvatar(group); + } + + $(this).remove(); + const groupHasMembers = !!$('#rm_group_members').children().length; + $("#rm_group_submit").prop('disabled', !groupHasMembers); + } + + // render characters list + $('#rm_group_add_members').empty(); + $('#rm_group_members').empty(); + for (let character of characters) { + const avatar = character.avatar != 'none' ? `characters/${character.avatar}#${Date.now()}` : default_avatar; + const template = $('#group_member_template .group_member').clone(); + template.data('id', character.name); + template.find('.avatar img').attr('src', avatar); + template.find('.ch_name').html(character.name); + template.click(memberClickHandler); + + if (group && Array.isArray(group.members) && group.members.includes(character.name)) { + template.find('.plus').hide(); + template.find('.minus').show(); + $('#rm_group_members').append(template); + } else { + template.find('.plus').show(); + template.find('.minus').hide(); + $('#rm_group_add_members').append(template); + } + } + + const groupHasMembers = !!$('#rm_group_members').children().length; + $("#rm_group_submit").prop('disabled', !groupHasMembers); + + // bottom buttons + if (chat_id) { + $('#rm_group_submit').hide(); + $('#rm_group_delete').show(); + } else { + $('#rm_group_submit').show(); + $('#rm_group_delete').hide(); + } + + $('#rm_group_delete').off(); + $('#rm_group_delete').on('click', function () { + popup_type = 'del_group'; + $('#dialogue_popup').data('group_id', chat_id); + callPopup('

Delete the group?

'); + }); + + // top bar + if (group) { + var display_name = groupName; + $("#rm_button_selected_ch").children("h2").css(deselected_button_style); + $("#rm_button_selected_ch").children("h2").text(''); + } + } + $('#rm_group_automode').on('input', function () { + const value = $(this).prop('checked'); + is_group_automode_enabled = value; + }); + function select_rm_create() { + menu_type = 'create'; + + //console.log('select_rm_Create() -- selected button: '+selected_button); + if (selected_button == 'create') { + if (create_save_avatar != '') { + $("#add_avatar_button").get(0).files = create_save_avatar; + read_avatar_load($("#add_avatar_button").get(0)); + } + } + + $("#rm_characters_block").css("display", "none"); + $("#rm_api_block").css("display", "none"); + $("#rm_ch_create_block").css("display", "block"); + $("#rm_group_chats_block").css("display", "none"); + + $('#rm_ch_create_block').css('opacity', 0.0); + $('#rm_ch_create_block').transition({ + opacity: 1.0, + duration: animation_rm_duration, + easing: animation_rm_easing, + complete: function () { } + }); + $("#rm_info_block").css("display", "none"); + + $("#delete_button_div").css("display", "none"); + $("#delete_button").css("display", "none"); + $("#export_button").css("display", "none"); + $("#create_button").css("display", "block"); + $("#create_button").attr("value", "Create"); + //RossAscends: commented this out as part of the auto-loading token counter + //$('#result_info').html(' '); + $("#rm_button_characters").css("class", "deselected-right-tab"); + $("#rm_button_settings").css("class", "deselected-right-tab"); + $("#rm_button_selected_ch").css("class", "deselected-right-tab"); + + //create text poles + $("#rm_button_back").css("display", "inline-block"); + $("#character_import_button").css("display", "inline-block"); + $("#character_popup_text_h3").text('Create character'); + $("#character_name_pole").val(create_save_name); + $("#description_textarea").val(create_save_description); + $("#personality_textarea").val(create_save_personality); + $("#firstmessage_textarea").val(create_save_first_message); + $("#talkativeness_slider").val(create_save_talkativeness); + $("#scenario_pole").val(create_save_scenario); + if ($.trim(create_save_mes_example).length == 0) { + $("#mes_example_textarea").val(''); + } else { + $("#mes_example_textarea").val(create_save_mes_example); + } + $("#avatar_div").css("display", "grid"); + $("#avatar_load_preview").attr('src', default_avatar); + $("#name_div").css("display", "block"); + + $("#form_create").attr("actiontype", "createcharacter"); + CountCharTokens(); + } + function select_rm_characters() { + QuickRefresh(true); + + if (prev_selected_char) { + let newChId = characters.findIndex(x => x.name == prev_selected_char); + $(`.character_select[chid="${newChId}"]`).trigger('click'); + prev_selected_char = null; + } + + menu_type = 'characters'; + $("#rm_characters_block").css("display", "block"); + $('#rm_characters_block').css('opacity', 0.0); + $('#rm_characters_block').transition({ + opacity: 1.0, + duration: animation_rm_duration, + easing: animation_rm_easing, + complete: function () { } + }); + + $("#rm_api_block").css("display", "none"); + $("#rm_ch_create_block").css("display", "none"); + $("#rm_info_block").css("display", "none"); + $("#rm_group_chats_block").css("display", "none"); + + $("#rm_button_characters").css("class", "selected-right-tab"); + $("#rm_button_settings").css("class", "deselected-right-tab"); + $("#rm_button_selected_ch").css("class", "deselected-right-tab"); + } + function select_rm_info(text, charId = null) { + $("#rm_characters_block").css("display", "none"); + $("#rm_api_block").css("display", "none"); + $("#rm_ch_create_block").css("display", "none"); + $("#rm_group_chats_block").css("display", "none"); + $("#rm_info_block").css("display", "flex"); + + $("#rm_info_text").html('

' + text + '

'); + + $("#rm_button_characters").css("class", "deselected-right-tab"); + $("#rm_button_settings").css("class", "deselected-right-tab"); + $("#rm_button_selected_ch").css("class", "deselected-right-tab"); + + prev_selected_char = charId; + } + function select_selected_character(chid) { //character select + //console.log('select_selected_character() -- starting with input of -- '+chid+' (name:'+characters[chid].name+')'); + select_rm_create(); + menu_type = 'character_edit'; + $("#delete_button").css("display", "block"); + $("#export_button").css("display", "block"); + $("#rm_button_selected_ch").css("class", "selected-right-tab"); + var display_name = characters[chid].name; + + + $("#rm_button_selected_ch").children("h2").text(display_name); + + //create text poles + $("#rm_button_back").css("display", "none"); + //$("#character_import_button").css("display", "none"); + $("#create_button").attr("value", "Save"); + $("#create_button").css("display", "none"); + var i = 0; + while ($("#rm_button_selected_ch").width() > 170 && i < 100) { + display_name = display_name.slice(0, display_name.length - 2); + //console.log(display_name); + $("#rm_button_selected_ch").children("h2").text($.trim(display_name) + '...'); + i++; + } + $("#add_avatar_button").val(''); + + $('#character_popup_text_h3').text(characters[chid].name); + $("#character_name_pole").val(characters[chid].name); + $("#description_textarea").val(characters[chid].description); + $("#personality_textarea").val(characters[chid].personality); + $("#firstmessage_textarea").val(characters[chid].first_mes); + $("#scenario_pole").val(characters[chid].scenario); + $("#talkativeness_slider").val(characters[chid].talkativeness ?? talkativeness_default); + $("#mes_example_textarea").val(characters[chid].mes_example); + $("#selected_chat_pole").val(characters[chid].chat); + $("#create_date_pole").val(characters[chid].create_date); + $("#avatar_url_pole").val(characters[chid].avatar); + $("#chat_import_avatar_url").val(characters[chid].avatar); + $("#chat_import_character_name").val(characters[chid].name); + //$("#avatar_div").css("display", "none"); + var this_avatar = default_avatar; + if (characters[chid].avatar != 'none') { + this_avatar = "characters/" + characters[chid].avatar; + } + $("#avatar_load_preview").attr('src', this_avatar + "?" + Date.now()); + $("#name_div").css("display", "none"); + + $("#form_create").attr("actiontype", "editcharacter"); + active_character = chid; + //console.log('select_selected_character() -- active_character -- '+chid+'(ChID of '+display_name+')'); + saveSettings(); + //console.log('select_selected_character() -- called saveSettings() to save -- active_character -- '+active_character+'(ChID of '+display_name+')'); + + } + $(document).on('click', '.character_select', function () { + if (this_chid !== $(this).attr("chid")) { //if clicked on a different character from what was currently selected + if (!is_send_press) { + selected_group = null; + is_group_generating = false; + this_edit_mes_id = undefined; + selected_button = 'character_edit'; + this_chid = $(this).attr("chid"); + active_character = this_chid; + clearChat(); + chat.length = 0; + getChat(); + + //console.log('Clicked on '+characters[this_chid].name+' Active_Character set to: '+active_character+' (ChID:'+this_chid+')'); + } + } else { //if clicked on character that was already selected + selected_button = 'character_edit'; + select_selected_character(this_chid); + } + $('#character_search_bar').val('').trigger('input'); + }); + var scroll_holder = 0; + var is_use_scroll_holder = false; + $(document).on('input', '.edit_textarea', function () { + scroll_holder = $("#chat").scrollTop(); + $(this).height(0).height(this.scrollHeight); + is_use_scroll_holder = true; + }); + $("#chat").on("scroll", function () { + if (is_use_scroll_holder) { + $("#chat").scrollTop(scroll_holder); + is_use_scroll_holder = false; + } + + }); + $(document).on('click', '.del_checkbox', function () { //when a 'delete message' checkbox is clicked + $('.del_checkbox').each(function () { + $(this).prop("checked", false); + $(this).parent().css('background', css_mes_bg); + }); + $(this).parent().css('background', "#600"); //sets the bg of the mes selected for deletion + var i = $(this).parent().attr('mesid'); //checks the message ID in the chat + this_del_mes = i; + while (i < chat.length) { //as long as the current message ID is less than the total chat length + $(".mes[mesid='" + i + "']").css('background', "#600"); //sets the bg of the all msgs BELOW the selected .mes + $(".mes[mesid='" + i + "']").children('.del_checkbox').prop("checked", true); + i++; + //console.log(i); + } + + }); + $(document).on('click', '#user_avatar_block .avatar', function () { + user_avatar = $(this).attr("imgfile"); + $('.mes').each(function () { + if ($(this).attr('ch_name') == name1) { + $(this).children('.avatar').children('img').attr('src', 'User Avatars/' + user_avatar); + } + }); + saveSettings(); + highlightSelectedAvatar(); + }); + $(document).on('click', '#user_avatar_block .avatar_upload', function () { + $('#avatar_upload_file').click(); + }); + $('#avatar_upload_file').on('change', function (e) { + const file = e.target.files[0]; + + if (!file) { + return; + } + + const formData = new FormData($("#form_upload_avatar").get(0)); + + jQuery.ajax({ + type: 'POST', + url: '/uploaduseravatar', + data: formData, + beforeSend: () => { }, + cache: false, + contentType: false, + processData: false, + success: function (data) { + if (data.path) { + appendUserAvatar(data.path); + } + }, + error: (jqXHR, exception) => { }, + }); + + // Will allow to select the same file twice in a row + $('#form_upload_avatar').trigger("reset"); + }); + $('#logo_block').click(function (event) { + if (!bg_menu_toggle) { + $('#bg_menu_button').transition({ perspective: '100px', rotate3d: '1,1,0,180deg' }); + $('#bg_menu_content').transition({ + opacity: 1.0, height: '90vh', + duration: 340, + easing: 'in', + complete: function () { bg_menu_toggle = true; $('#bg_menu_content').css("overflow-y", "auto"); } + }); + } else { + $('#bg_menu_button').transition({ perspective: '100px', rotate3d: '1,1,0,360deg' }); + $('#bg_menu_content').css("overflow-y", "hidden"); + $('#bg_menu_content').transition({ + + opacity: 0.0, height: '0px', + duration: 340, + easing: 'in', + complete: function () { bg_menu_toggle = false; } + }); + } + }); + $(document).on('click', '.bg_example_img', function () { //when user clicks on a BG thumbnail... + var this_bgfile = $(this).attr("bgfile"); // this_bgfile = whatever they clicked + + if (bg1_toggle == true) { //if bg1 is toggled true (initially set as true in first JS vars) + bg1_toggle = false; // then toggle it false + var number_bg = 2; // sets a variable for bg2 + var target_opacity = 1.0; // target opacity is 100% + } else { //if bg1 is FALSE + bg1_toggle = true; // make it true + var number_bg = 1; // set variable to bg1.. + var target_opacity = 0.0; // set target opacity to 0 + } + $('#bg2').stop(); // first, stop whatever BG transition was happening before + $('#bg2').transition({ // start a new BG transition routine + opacity: target_opacity, // set opacity to previously set variable + duration: 1300, //animation_rm_duration, + easing: "linear", + complete: function () { // why does the BG transition completion make the #options (right nav) invisible? + $("#options").css('display', 'none'); + } + }); + $('#bg' + number_bg).css('background-image', 'url("backgrounds/' + this_bgfile + '")'); + setBackground(this_bgfile); + + }); + $(document).on('click', '.bg_example_cross', function () { + bg_file_for_del = $(this); + //$(this).parent().remove(); + //delBackground(this_bgfile); + popup_type = 'del_bg'; + callPopup('

Delete the background?

'); + + }); + $("#advanced_div").click(function () { + if (!is_advanced_char_open) { + is_advanced_char_open = true; + $('#character_popup').css('display', 'grid'); + $('#character_popup').css('opacity', 0.0); + $('#character_popup').transition({ opacity: 1.0, duration: animation_rm_duration, easing: animation_rm_easing }); + } else { + is_advanced_char_open = false; + $('#character_popup').css('display', 'none'); + } + }); + $("#character_cross").click(function () { + is_advanced_char_open = false; + $('#character_popup').css('display', 'none'); + }); + $("#character_popup_ok").click(function () { + is_advanced_char_open = false; + $('#character_popup').css('display', 'none'); + }); + $("#dialogue_popup_ok").click(function () { + $("#shadow_popup").css('display', 'none'); + $("#shadow_popup").css('opacity:', 0.0); + if (popup_type == 'del_bg') { + delBackground(bg_file_for_del.attr("bgfile")); + bg_file_for_del.parent().remove(); + } + if (popup_type == 'del_ch') { + console.log('Deleting character -- ChID: ' + this_chid + ' -- Name: ' + characters[this_chid].name); + var msg = jQuery('#form_create').serialize(); // ID form + jQuery.ajax({ + method: 'POST', + url: '/deletecharacter', + beforeSend: function () { + select_rm_info("Character deleted"); + //$('#create_button').attr('value','Deleting...'); + }, + data: msg, + cache: false, + success: function (html) { + //RossAscends: setting active character to null in order to avoid array errors. + //this allows for dynamic refresh of character list after deleting a character. + $('#character_cross').click(); + active_character = 'invalid-safety-id'; //unsets the chid in settings (this prevents AutoLoadChat from trying to load the wrong ChID + this_chid = 'invalid-safety-id'; //unsets expected chid before reloading (related to getCharacters/printCharacters from using old arrays) + characters.length = 0; // resets the characters array, forcing getcharacters to reset + name2 = "Chloe"; // replaces deleted charcter name with Chloe, since she wil be displayed next. + chat = [...safetychat]; // sets up chloe to tell user about having deleted a character + saveSettings(); // saving settings to keep changes to variables + QuickRefresh(); // call quick refresh of Char list, clears chat, and loads Chloe 'post-char-delete' message. + //location.reload(); // this is Humi's original code + //getCharacters(); + //$('#create_button_div').html(html); + } + }); + } + if (popup_type === 'world_imported' && imported_world_name) { + world_names.forEach((item, i) => { + if (item === imported_world_name) { + $('#world_info').val(i).change(); + } + }) + imported_world_name = ''; + } + if (popup_type === 'del_world' && world_info) { + deleteWorldInfo(world_info); + } + if (popup_type === 'del_group') { + const groupId = $('#dialogue_popup').data('group_id'); + + if (groupId) { + deleteGroup(groupId); + } + } + //Make a new chat for selected character + if (popup_type == 'new_chat' && this_chid != undefined && menu_type != "create") {//Fix it; New chat doesn't create while open create character menu + clearChat(); + chat.length = 0; + characters[this_chid].chat = (name2 + ' - ' + humanizedISO8601DateTime()); //RossAscends: added character name to new chat filenames and replaced Date.now() with humanizedISO8601DateTime; + $("#selected_chat_pole").val(characters[this_chid].chat); + timerSaveEdit = setTimeout(() => { $("#create_button").click(); }, durationSaveEdit); + getChat(); + + } + }); + $("#dialogue_popup_cancel").click(function () { + $("#shadow_popup").css('display', 'none'); + $("#shadow_popup").css('opacity:', 0.0); + popup_type = ''; + }); + function callPopup(text) { + $("#dialogue_popup_cancel").css("display", "inline-block"); + switch (popup_type) { + case 'text': + case 'char_not_selected': + + $("#dialogue_popup_ok").text("Ok"); + $("#dialogue_popup_cancel").css("display", "none"); + break; + + case 'world_imported': + case 'new_chat': + + + $("#dialogue_popup_ok").text("Yes"); + break; + case 'del_world': + case 'del_group': + default: + + $("#dialogue_popup_ok").text("Delete"); + + } + $("#dialogue_popup_text").html(text); + $("#shadow_popup").css('display', 'block'); + $('#shadow_popup').transition({ opacity: 1.0, duration: animation_rm_duration, easing: animation_rm_easing }); + } + function read_bg_load(input) { + if (input.files && input.files[0]) { + var reader = new FileReader(); + + reader.onload = function (e) { + $('#bg_load_preview') + .attr('src', e.target.result) + .width(103) + .height(83); + + var formData = new FormData($("#form_bg_download").get(0)); + + //console.log(formData); + jQuery.ajax({ + type: 'POST', + url: '/downloadbackground', + data: formData, + beforeSend: function () { + //$('#create_button').attr('value','Creating...'); + }, + cache: false, + contentType: false, + processData: false, + success: function (html) { + setBackground(html); + if (bg1_toggle == true) { // this is a repeat of the background setting function for when user uploads a new BG image + bg1_toggle = false; // should make the Bg setting a modular function to be called in both cases + var number_bg = 2; + var target_opacity = 1.0; + } else { + bg1_toggle = true; + var number_bg = 1; + var target_opacity = 0.0; + } + $('#bg2').transition({ + opacity: target_opacity, + duration: 1300,//animation_rm_duration, + easing: "linear", + complete: function () { + $("#options").css('display', 'none'); + } + }); + $('#bg' + number_bg).css('background-image', 'url(' + e.target.result + ')'); + $("#form_bg_download").after("
"); + }, + error: function (jqXHR, exception) { + console.log(exception); + console.log(jqXHR); + } + }); + + }; + + reader.readAsDataURL(input.files[0]); + } + } + $("#add_bg_button").change(function () { + read_bg_load(this); + + }); + function read_avatar_load(input) { + + if (input.files && input.files[0]) { + var reader = new FileReader(); + if (selected_button == 'create') { + + create_save_avatar = input.files; + } + reader.onload = function (e) { + + if (selected_button == 'character_edit') { + + timerSaveEdit = setTimeout(() => { $("#create_button").click(); }, durationSaveEdit); + } + $('#avatar_load_preview') + .attr('src', e.target.result); + //.width(103) + //.height(83); + //console.log(e.target.result.name); + + }; + + reader.readAsDataURL(input.files[0]); + } + } + $("#add_avatar_button").change(function () { + + is_mes_reload_avatar = Date.now(); + read_avatar_load(this); + }); + $("#form_create").submit(function (e) { + + $('#rm_info_avatar').html(''); + var formData = new FormData($("#form_create").get(0)); + if ($("#form_create").attr("actiontype") == "createcharacter") { + + if ($("#character_name_pole").val().length > 0) { //if the character name text area isn't empty (only posible when creating a new character) + //console.log('/createcharacter entered'); + jQuery.ajax({ + type: 'POST', + url: '/createcharacter', + data: formData, + beforeSend: function () { + $('#create_button').attr('disabled', true); + $('#create_button').attr('value', 'Creating...'); + }, + cache: false, + contentType: false, + processData: false, + success: async function (html) { + $('#character_cross').click(); //closes the advanced character editing popup + $("#character_name_pole").val(''); + create_save_name = ''; + $("#description_textarea").val(''); + create_save_description = ''; + $("#personality_textarea").val(''); + create_save_personality = ''; + $("#firstmessage_textarea").val(''); + create_save_first_message = ''; + $("#talkativeness_slider").val(talkativeness_default); + create_save_talkativeness = talkativeness_default; + + $("#character_popup_text_h3").text('Create character'); + + $("#scenario_pole").val(''); + create_save_scenario = ''; + $("#mes_example_textarea").val(''); + create_save_mes_example = ''; + + create_save_avatar = ''; + + $('#create_button').removeAttr("disabled"); + $("#add_avatar_button").replaceWith($("#add_avatar_button").val('').clone(true)); + + $('#create_button').attr('value', 'Create'); + if (true) { + let oldSelectedChar = null; + if (this_chid != undefined && this_chid != 'invalid-safety-id') { + oldSelectedChar = characters[this_chid].name; + } + + await getCharacters(); + + $('#rm_info_block').transition({ opacity: 0, duration: 0 }); + var $prev_img = $('#avatar_div_div').clone(); + $('#rm_info_avatar').append($prev_img); + select_rm_info("Character created", oldSelectedChar); + + $('#rm_info_block').transition({ opacity: 1.0, duration: 2000 }); + } else { + $('#result_info').html(html); + } + }, + error: function (jqXHR, exception) { + //alert('ERROR: '+xhr.status+ ' Status Text: '+xhr.statusText+' '+xhr.responseText); + $('#create_button').removeAttr("disabled"); + } + }); + } else { + $('#result_info').html("Name not entered"); + } + } else { + //console.log('/editcharacter -- entered.'); + //console.log('Avatar Button Value:'+$("#add_avatar_button").val()); + jQuery.ajax({ + type: 'POST', + url: '/editcharacter', + data: formData, + beforeSend: function () { + $('#create_button').attr('disabled', true); + $('#create_button').attr('value', 'Save'); + }, + cache: false, + contentType: false, + processData: false, + success: function (html) { + $('.mes').each(function () { + if ($(this).attr('ch_name') != name1) { + $(this).children('.avatar').children('img').attr('src', $('#avatar_load_preview').attr('src')); + } + }); + if (chat.length === 1) { + var this_ch_mes = default_ch_mes; + if ($('#firstmessage_textarea').val() != "") { + this_ch_mes = $('#firstmessage_textarea').val(); + } + if (this_ch_mes != $.trim($("#chat").children('.mes').children('.mes_block').children('.mes_text').text())) { + clearChat(); + chat.length = 0; + chat[0] = {}; + chat[0]['name'] = name2; + chat[0]['is_user'] = false; + chat[0]['is_name'] = true; + chat[0]['mes'] = this_ch_mes; + add_mes_without_animation = true; + addOneMessage(chat[0]); + } + } + $('#create_button').removeAttr("disabled"); + getCharacters(); + + $("#add_avatar_button").replaceWith($("#add_avatar_button").val('').clone(true)); + $('#create_button').attr('value', 'Save'); + //console.log('/editcharacters -- this_chid -- '+this_chid); + if (this_chid != undefined && this_chid != 'invalid-safety-id') { //added check to avoid trying to load tokens in case of character deletion + CountCharTokens(); + } + }, + error: function (jqXHR, exception) { + $('#create_button').removeAttr("disabled"); + $('#result_info').html("Error: no connection"); + } + }); + } + + }); + $("#delete_button").click(function () { + popup_type = 'del_ch'; + callPopup('

Delete the character?

Page will reload and you will be returned to Chloe.'); + }); + $("#rm_info_button").click(function () { + $('#rm_info_avatar').html(''); + select_rm_characters(); + }); + //@@@@@@@@@@@@@@@@@@@@@@@@ + //character text poles creating and editing save + $('#character_name_pole').on('change keyup paste', function () { + if (menu_type == 'create') { + create_save_name = $('#character_name_pole').val(); + } + + }); + $('#description_textarea').on('keyup paste cut', function () {//change keyup paste cut + + if (menu_type == 'create') { + create_save_description = $('#description_textarea').val(); + CountCharTokens(); + } else { + timerSaveEdit = setTimeout(() => { $("#create_button").click(); }, durationSaveEdit); + } + + }); + $('#personality_textarea').on('keyup paste cut', function () { + if (menu_type == 'create') { + + create_save_personality = $('#personality_textarea').val(); + CountCharTokens(); + } else { + timerSaveEdit = setTimeout(() => { $("#create_button").click(); }, durationSaveEdit); + } + }); + $('#scenario_pole').on('keyup paste cut', function () { + if (menu_type == 'create') { + create_save_scenario = $('#scenario_pole').val(); + CountCharTokens(); + } else { + timerSaveEdit = setTimeout(() => { $("#create_button").click(); }, durationSaveEdit); + } + }); + $('#mes_example_textarea').on('keyup paste cut', function () { + if (menu_type == 'create') { + + create_save_mes_example = $('#mes_example_textarea').val(); + CountCharTokens(); + } else { + timerSaveEdit = setTimeout(() => { $("#create_button").click(); }, durationSaveEdit); + } + }); + $('#firstmessage_textarea').on('keyup paste cut', function () { + + if (menu_type == 'create') { + create_save_first_message = $('#firstmessage_textarea').val(); + CountCharTokens(); + } else { + timerSaveEdit = setTimeout(() => { $("#create_button").click(); }, durationSaveEdit); + } + }); + $('#talkativeness_slider').on('input', function () { + if (menu_type == 'create') { + create_save_talkativeness = $('#talkativeness_slider').val(); + } else { + timerSaveEdit = setTimeout(() => { + $('#create_button').click(); + }, durationSaveEdit); + } + }); + $("#api_button").click(function () { + if ($('#api_url_text').val() != '') { + $("#api_loading").css("display", 'inline-block'); + $("#api_button").css("display", 'none'); + api_server = $('#api_url_text').val(); + api_server = $.trim(api_server); + //console.log("1: "+api_server); + if (api_server.substr(api_server.length - 1, 1) == "/") { + api_server = api_server.substr(0, api_server.length - 1); + } + if (!(api_server.substr(api_server.length - 3, 3) == "api" || api_server.substr(api_server.length - 4, 4) == "api/")) { + api_server = api_server + "/api"; + } + //console.log("2: "+api_server); + main_api = "kobold"; + saveSettings(); + is_get_status = true; + is_api_button_press = true; + getStatus(); + clearSoftPromptsList(); + getSoftPromptsList(); + } + }); + + + $("#api_button_textgenerationwebui").click(function () { + if ($('#textgenerationwebui_api_url_text').val() != '') { + $("#api_loading_textgenerationwebui").css("display", 'inline-block'); + $("#api_button_textgenerationwebui").css("display", 'none'); + api_server_textgenerationwebui = $('#textgenerationwebui_api_url_text').val(); + api_server_textgenerationwebui = $.trim(api_server_textgenerationwebui); + if (api_server_textgenerationwebui.substr(api_server_textgenerationwebui.length - 1, 1) == "/") { + api_server_textgenerationwebui = api_server_textgenerationwebui.substr(0, api_server_textgenerationwebui.length - 1); + } + //console.log("2: "+api_server_textgenerationwebui); + main_api = "textgenerationwebui"; + saveSettings(); + is_get_status = true; + is_api_button_press = true; + getStatus(); + } + }); + + + $("body").click(function () { + if ($("#options").css('opacity') == 1.0) { + $('#options').transition({ + opacity: 0.0, + duration: 100,//animation_rm_duration, + easing: animation_rm_easing, + complete: function () { + $("#options").css('display', 'none'); + } + }) + + } + }); + + // RossAscends: Added functionality that will close the RightNav panel click outside of it or related panels (adv editing popup, or dialog popups) + + var NavToggle = document.getElementById("nav-toggle"); + var PanelPin = document.getElementById("rm_button_panel_pin"); + $('document').ready(function () { + $("html").click(function (e) { + if (NavToggle.checked === true && PanelPin.checked === false) { + if ($(e.target).attr('id') !== "nav-toggle") { + if (document.querySelector('#right-nav-panel').contains(e.target) === false) { + if (document.querySelector('#character_popup').contains(e.target) === false) { + if (document.querySelector('#dialogue_popup').contains(e.target) === false) { + document.getElementById('nav-toggle').click(); + } + } + } + } + }; + }); + }); + + $("#options_button").click(function () { // this is the options button click function, shows the options menu if closed + if ($("#options").css('display') === 'none' && $("#options").css('opacity') == 0.0) { + $("#options").css('display', 'block'); + $('#options').transition({ + opacity: 1.0, // the manual setting of CSS via JS is what allows the click-away feature to work + duration: 100, + easing: animation_rm_easing, + complete: function () { + + } + }); + } + }); + function openNavToggle() { + if (!$('#nav-toggle').prop('checked')) { + $('#nav-toggle').trigger('click'); + } + } + $("#option_select_chat").click(function () { + if (selected_group) { + // will open a chat selection screen + openNavToggle(); + $("#rm_button_characters").trigger('click'); + return; + } + if (this_chid != undefined && !is_send_press) { + getAllCharaChats(); + $('#shadow_select_chat_popup').css('display', 'block'); + $('#shadow_select_chat_popup').css('opacity', 0.0); + $('#shadow_select_chat_popup').transition({ opacity: 1.0, duration: animation_rm_duration, easing: animation_rm_easing }); + } + }); + $("#option_start_new_chat").click(function () { + if (selected_group) { + // will open a group creation screen + openNavToggle(); + $("#rm_button_group_chats").trigger('click'); + return; + } + if (this_chid != undefined && !is_send_press) { + popup_type = 'new_chat'; + callPopup('

Start new chat?

'); + } + }); + $("#option_regenerate").click(function () { + if (is_send_press == false) { + is_send_press = true; + Generate('regenerate'); + } + }); + // this function hides the input form, and shows the delete/cancel buttons for deleting messages from chat + $("#option_delete_mes").click(function () { + if (this_chid != undefined && !is_send_press || (selected_group && !is_group_generating)) { + $('#dialogue_del_mes').css('display', 'block'); + $('#send_form').css('display', 'none'); + $('.del_checkbox').each(function () { + if ($(this).parent().attr('mesid') != 0) { + $(this).css("display", "block"); + $(this).parent().children('.for_checkbox').css('display', 'none'); + } + }); + } + }); + //functionality for the cancel delete messages button, reverts to normal display of input form + $("#dialogue_del_mes_cancel").click(function () { + $('#dialogue_del_mes').css('display', 'none'); + $('#send_form').css('display', css_send_form_display); + $('.del_checkbox').each(function () { + $(this).css("display", "none"); + $(this).parent().children('.for_checkbox').css('display', 'block'); + $(this).parent().css('background', css_mes_bg); + $(this).prop("checked", false); + + }); + this_del_mes = 0; + + }); + //confirms message delation with the "ok" button + $("#dialogue_del_mes_ok").click(function () { + $('#dialogue_del_mes').css('display', 'none'); + $('#send_form').css('display', css_send_form_display); + $('.del_checkbox').each(function () { + $(this).css("display", "none"); + $(this).parent().children('.for_checkbox').css('display', 'block'); + $(this).parent().css('background', css_mes_bg); + $(this).prop("checked", false); + + + }); + if (this_del_mes != 0) { + $(".mes[mesid='" + this_del_mes + "']").nextAll('div').remove(); + $(".mes[mesid='" + this_del_mes + "']").remove(); + chat.length = this_del_mes; + count_view_mes = this_del_mes; + if (selected_group) { + saveGroupChat(selected_group); + } else { + saveChat(); + } + var $textchat = $('#chat'); + $textchat.scrollTop($textchat[0].scrollHeight); + } + this_del_mes = 0; + + + }); + + $("#world_info").change(async function () { + const selectedWorld = $('#world_info').find(":selected").val(); + world_info = null; + world_info_data = null; + + if (selectedWorld !== 'None') { + const worldIndex = Number(selectedWorld); + world_info = !isNaN(worldIndex) ? world_names[worldIndex] : null; + await loadWorldInfoData(); + } + + hideWorldEditor(); + saveSettings(); + }); + + $("#settings_perset").change(function () { + + if ($('#settings_perset').find(":selected").val() != 'gui') { + preset_settings = $('#settings_perset').find(":selected").text(); + temp = koboldai_settings[koboldai_setting_names[preset_settings]].temp; + amount_gen = koboldai_settings[koboldai_setting_names[preset_settings]].genamt; + rep_pen = koboldai_settings[koboldai_setting_names[preset_settings]].rep_pen; + rep_pen_size = koboldai_settings[koboldai_setting_names[preset_settings]].rep_pen_range; + max_context = koboldai_settings[koboldai_setting_names[preset_settings]].max_length; + $('#temp').val(temp); + $('#temp_counter').html(temp); + + $('#amount_gen').val(amount_gen); + $('#amount_gen_counter').html(amount_gen); + + $('#max_context').val(max_context); + $('#max_context_counter').html(max_context + " Tokens"); + + $('#rep_pen').val(rep_pen); + $('#rep_pen_counter').html(rep_pen); + + $('#rep_pen_size').val(rep_pen_size); + $('#rep_pen_size_counter').html(rep_pen_size + " Tokens"); + + $("#range_block").children().prop("disabled", false); + $("#range_block").css('opacity', 1.0); + $("#amount_gen_block").children().prop("disabled", false); + $("#amount_gen_block").css('opacity', 1.0); + + } else { + //$('.button').disableSelection(); + preset_settings = 'gui'; + $("#range_block").children().prop("disabled", true); + $("#range_block").css('opacity', 0.5); + $("#amount_gen_block").children().prop("disabled", true); + $("#amount_gen_block").css('opacity', 0.45); + } + saveSettings(); + }); + $("#settings_perset_novel").change(function () { + + preset_settings_novel = $('#settings_perset_novel').find(":selected").text(); + temp_novel = novelai_settings[novelai_setting_names[preset_settings_novel]].temperature; + //amount_gen = koboldai_settings[koboldai_setting_names[preset_settings]].genamt; + rep_pen_novel = novelai_settings[novelai_setting_names[preset_settings_novel]].repetition_penalty; + rep_pen_size_novel = novelai_settings[novelai_setting_names[preset_settings_novel]].repetition_penalty_range; + $('#temp_novel').val(temp_novel); + $('#temp_counter_novel').html(temp_novel); + + //$('#amount_gen').val(amount_gen); + //$('#amount_gen_counter').html(amount_gen); + + $('#rep_pen_novel').val(rep_pen_novel); + $('#rep_pen_counter_novel').html(rep_pen_novel); + + $('#rep_pen_size_novel').val(rep_pen_size_novel); + $('#rep_pen_size_counter_novel').html(rep_pen_size_novel + " Tokens"); + + //$("#range_block").children().prop("disabled", false); + //$("#range_block").css('opacity',1.0); + saveSettings(); + }); + $("#main_api").change(function () { + is_pygmalion = false; + is_get_status = false; + is_get_status_novel = false; + online_status = 'no_connection'; + clearSoftPromptsList(); + checkOnlineStatus(); + changeMainAPI(); + saveSettings(); + }); + $('#softprompt').change(async function () { + if (!api_server) { + return; + } + + const selected = $('#softprompt').find(':selected').val(); + const response = await fetch('/setsoftprompt', { + method: 'POST', + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ name: selected, api_server: api_server }), + }); + + if (!response.ok) { + console.error("Couldn't change soft prompt"); + } + }); + function changeMainAPI() { + if ($('#main_api').find(":selected").val() == 'kobold') { + $('#kobold_api').css("display", "block"); + $('#novel_api').css("display", "none"); + $('#textgenerationwebui_api').css("display", "none"); + main_api = 'kobold'; + $('#max_context_block').css('display', 'block'); + $('#amount_gen_block').css('display', 'block'); + $('#softprompt_block').css('display', 'block'); + $('#settings_perset').trigger('change'); + } + if ($('#main_api').find(":selected").val() == 'textgenerationwebui') { + $('#kobold_api').css("display", "none"); + $('#novel_api').css("display", "none"); + $('#textgenerationwebui_api').css("display", "block"); + main_api = 'textgenerationwebui'; + $('#max_context_block').css('display', 'block'); + $('#amount_gen_block').css('display', 'block'); + $('#softprompt_block').css('display', 'block'); + $("#amount_gen_block").children().prop("disabled", false); + $("#amount_gen_block").css('opacity', 1.0); + } + + if ($('#main_api').find(":selected").val() == 'novel') { + $('#kobold_api').css("display", "none"); + $('#novel_api').css("display", "block"); + $('#textgenerationwebui_api').css("display", "none"); + main_api = 'novel'; + $('#max_context_block').css('display', 'none'); + $('#amount_gen_block').css('display', 'none'); + $('#softprompt_block').css('display', 'none'); + } + } + async function getUserAvatars() { + $("#user_avatar_block").html(""); //RossAscends: necessary to avoid doubling avatars each QuickRefresh. + $('#user_avatar_block').append('
+
'); + const response = await fetch("/getuseravatars", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token + }, + body: JSON.stringify({ + "": "" + }) + + }); + if (response.ok === true) { + const getData = await response.json(); + //background = getData; + //console.log(getData.length); + + for (var i = 0; i < getData.length; i++) { + //console.log(1); + appendUserAvatar(getData[i]); + } + //var aa = JSON.parse(getData[0]); + //const load_ch_coint = Object.getOwnPropertyNames(getData); + + + } + } + + function highlightSelectedAvatar() { + $("#user_avatar_block").find('.avatar').removeClass('selected'); + $("#user_avatar_block").find(`.avatar[imgfile='${user_avatar}']`).addClass('selected'); + } + + function appendUserAvatar(name) { + const block = $("#user_avatar_block").append('
'); + highlightSelectedAvatar(); + } + + for (var i of ["temp", "rep_pen", "rep_pen_size", "top_k", "top_p", "typical_p", "penalty_alpha"]) { + $('#' + i + '_textgenerationwebui').attr('x-setting-id', i); + $(document).on('input', '#' + i + '_textgenerationwebui', function () { + var i = $(this).attr('x-setting-id'); + var val = $(this).val(); + if (isInt(val)) { + $('#' + i + '_counter_textgenerationwebui').html($(this).val() + ".00"); + } else { + $('#' + i + '_counter_textgenerationwebui').html($(this).val()); + } + textgenerationwebui_settings[i] = parseFloat(val); + setTimeout(saveSettings, 500); + }); + } + + $(document).on('input', '#temp', function () { + temp = $(this).val(); + if (isInt(temp)) { + $('#temp_counter').html($(this).val() + ".00"); + } else { + $('#temp_counter').html($(this).val()); + } + var tempTimer = setTimeout(saveSettings, 500); + }); + $(document).on('input', '#amount_gen', function () { + amount_gen = $(this).val(); + $('#amount_gen_counter').html($(this).val()); + var amountTimer = setTimeout(saveSettings, 500); + }); + $(document).on('input', '#max_context', function () { + max_context = parseInt($(this).val()); + $('#max_context_counter').html($(this).val() + ' Tokens'); + var max_contextTimer = setTimeout(saveSettings, 500); + }); + $(document).on('input', '#world_info_depth', function () { + world_info_depth = Number($(this).val()); + $('#world_info_depth_counter').html(`${$(this).val()} Messages`); + setTimeout(saveSettings, 500); + }); + $(document).on('input', '#world_info_budget', function () { + world_info_budget = Number($(this).val()); + $('#world_info_budget_counter').html(`${$(this).val()} Tokens`); + setTimeout(saveSettings, 500); + }) + $('#style_anchor').change(function () { + style_anchor = !!$('#style_anchor').prop('checked'); + saveSettings(); + }); + $('#character_anchor').change(function () { + character_anchor = !!$('#character_anchor').prop('checked'); + saveSettings(); + }); + $('#auto-connect-checkbox').change(function () { + auto_connect = !!$('#auto-connect-checkbox').prop('checked'); + saveSettings(); + }); + $('#auto-load-chat-checkbox').change(function () { + auto_load_chat = !!$('#auto-load-chat-checkbox').prop('checked'); + saveSettings(); + }); + $('#collapse-newlines-checkbox').change(function () { + collapse_newlines = !!$('#collapse-newlines-checkbox').prop('checked'); + saveSettings(); + }); + $(document).on('input', '#rep_pen', function () { + rep_pen = $(this).val(); + if (isInt(rep_pen)) { + $('#rep_pen_counter').html($(this).val() + ".00"); + } else { + $('#rep_pen_counter').html($(this).val()); + } + var repPenTimer = setTimeout(saveSettings, 500); + }); + $(document).on('input', '#rep_pen_size', function () { + rep_pen_size = $(this).val(); + $('#rep_pen_size_counter').html($(this).val() + " Tokens"); + var repPenSizeTimer = setTimeout(saveSettings, 500); + }); + //Novel + $(document).on('input', '#temp_novel', function () { + temp_novel = $(this).val(); + + if (isInt(temp_novel)) { + $('#temp_counter_novel').html($(this).val() + ".00"); + } else { + $('#temp_counter_novel').html($(this).val()); + } + var tempTimer_novel = setTimeout(saveSettings, 500); + }); + $(document).on('input', '#rep_pen_novel', function () { + rep_pen_novel = $(this).val(); + if (isInt(rep_pen_novel)) { + $('#rep_pen_counter_novel').html($(this).val() + ".00"); + } else { + $('#rep_pen_counter_novel').html($(this).val()); + } + var repPenTimer_novel = setTimeout(saveSettings, 500); + }); + $(document).on('input', '#rep_pen_size_novel', function () { + rep_pen_size_novel = $(this).val(); + $('#rep_pen_size_counter_novel').html($(this).val() + " Tokens"); + var repPenSizeTimer_novel = setTimeout(saveSettings, 500); + }); + //***************SETTINGS****************// + /////////////////////////////////////////// + async function getSettings(type) {//timer + + //console.log('getSettings() pinging server for settings request'); + jQuery.ajax({ + type: 'POST', + url: '/getsettings', + data: JSON.stringify({}), + beforeSend: function () { + + + }, + cache: false, + dataType: "json", + contentType: "application/json", + //processData: false, + success: function (data) { + if (data.result != 'file not find' && data.settings) { + settings = JSON.parse(data.settings); + if (settings.username !== undefined) { + if (settings.username !== '') { + name1 = settings.username; + $('#your_name').val(name1); + } + } + + //Load which API we are using + if (settings.main_api != undefined) { + main_api = settings.main_api; + $("#main_api option[value=" + main_api + "]").attr('selected', 'true'); + changeMainAPI(); + } + //load Novel API KEY is exists + if (settings.api_key_novel != undefined) { + api_key_novel = settings.api_key_novel; + $("#api_key_novel").val(api_key_novel); + } + //load the rest of the Novel settings without any checks + model_novel = settings.model_novel; + $("#model_novel_select option[value=" + model_novel + "]").attr('selected', 'true'); + + novelai_setting_names = data.novelai_setting_names; + novelai_settings = data.novelai_settings; + novelai_settings.forEach(function (item, i, arr) { + novelai_settings[i] = JSON.parse(item); + }); + var arr_holder = {}; + + $("#settings_perset_novel").empty; + + novelai_setting_names.forEach(function (item, i, arr) { + arr_holder[item] = i; + $('#settings_perset_novel').append(''); + + }); + novelai_setting_names = {}; + novelai_setting_names = arr_holder; + + preset_settings_novel = settings.preset_settings_novel; + $("#settings_perset_novel option[value=" + novelai_setting_names[preset_settings_novel] + "]").attr('selected', 'true'); + + //Load KoboldAI settings + koboldai_setting_names = data.koboldai_setting_names; + koboldai_settings = data.koboldai_settings; + koboldai_settings.forEach(function (item, i, arr) { + koboldai_settings[i] = JSON.parse(item); + }); + var arr_holder = {}; + + $("#settings_perset").empty(); //RossAscends: uncommented this to prevent settings selector from doubling preset list on QuickRefresh + $("#settings_perset").append(''); //adding in the GUI settings, since it is not loaded dynamically + + koboldai_setting_names.forEach(function (item, i, arr) { + arr_holder[item] = i; + $('#settings_perset').append(''); + //console.log('loading preset #'+i+' -- '+item); + + }); + koboldai_setting_names = {}; + koboldai_setting_names = arr_holder; + preset_settings = settings.preset_settings; + + //Load AI model config settings (temp, context length, anchors, and anchor order) + + textgenerationwebui_settings = settings.textgenerationwebui_settings || textgenerationwebui_settings; + + temp = settings.temp; + amount_gen = settings.amount_gen; + if (settings.max_context !== undefined) max_context = parseInt(settings.max_context); + if (settings.anchor_order !== undefined) anchor_order = parseInt(settings.anchor_order); + if (settings.style_anchor !== undefined) style_anchor = !!settings.style_anchor; + if (settings.character_anchor !== undefined) character_anchor = !!settings.character_anchor; + if (settings.world_info_depth !== undefined) world_info_depth = Number(settings.world_info_depth); + if (settings.world_info_budget !== undefined) world_info_budget = Number(settings.world_info_budget); + + //load poweruser options + if (settings.auto_connect !== undefined) auto_connect = !!settings.auto_connect; + if (settings.auto_load_chat !== undefined) auto_load_chat = !!settings.auto_load_chat; + + rep_pen = settings.rep_pen; + rep_pen_size = settings.rep_pen_size; + + var addZeros = ""; + if (isInt(temp)) addZeros = ".00"; + $('#temp').val(temp); + $('#temp_counter').html(temp + addZeros); + + $('#style_anchor').prop('checked', style_anchor); + $('#character_anchor').prop('checked', character_anchor); + $("#anchor_order option[value=" + anchor_order + "]").attr('selected', 'true'); + + $('#auto-connect-checkbox').prop('checked', auto_connect); + $('#auto-load-chat-checkbox').prop('checked', auto_load_chat); + + $('#max_context').val(max_context); + $('#max_context_counter').html(max_context + ' Tokens'); + + $('#amount_gen').val(amount_gen); + $('#amount_gen_counter').html(amount_gen + ' Tokens'); + + $('#world_info_depth_counter').html(`${world_info_depth} Messages`); + $('#world_info_depth').val(world_info_depth); + + $('#world_info_budget_counter').html(`${world_info_budget} Tokens`); + $('#world_info_budget').val(world_info_budget); + + addZeros = ""; + if (isInt(rep_pen)) addZeros = ".00"; + $('#rep_pen').val(rep_pen); + $('#rep_pen_counter').html(rep_pen + addZeros); + + $('#rep_pen_size').val(rep_pen_size); + $('#rep_pen_size_counter').html(rep_pen_size + " Tokens"); + + //Novel + temp_novel = settings.temp_novel; + rep_pen_novel = settings.rep_pen_novel; + rep_pen_size_novel = settings.rep_pen_size_novel; + + addZeros = ""; + if (isInt(temp_novel)) addZeros = ".00"; + $('#temp_novel').val(temp_novel); + $('#temp_counter_novel').html(temp_novel + addZeros); + + addZeros = ""; + if (isInt(rep_pen_novel)) addZeros = ".00"; + $('#rep_pen_novel').val(rep_pen_novel); + $('#rep_pen_counter_novel').html(rep_pen_novel + addZeros); + + $('#rep_pen_size_novel').val(rep_pen_size_novel); + $('#rep_pen_size_counter_novel').html(rep_pen_size_novel + " Tokens"); + + //Enable GUI deference settings if GUI is selected for Kobold + if (preset_settings == 'gui') { + $("#settings_perset option[value=gui]").attr('selected', 'true').trigger('change'); + $("#range_block").children().prop("disabled", true); + $("#range_block").css('opacity', 0.5); + + $("#amount_gen_block").children().prop("disabled", true); + $("#amount_gen_block").css('opacity', 0.45); + } else { + if (typeof koboldai_setting_names[preset_settings] !== 'undefined') { + + $("#settings_perset option[value=" + koboldai_setting_names[preset_settings] + "]").attr('selected', 'true').trigger('change'); + } else { + $("#range_block").children().prop("disabled", true); + $("#range_block").css('opacity', 0.5); + $("#amount_gen_block").children().prop("disabled", true); + $("#amount_gen_block").css('opacity', 0.45); + + preset_settings = 'gui'; + $("#settings_perset option[value=gui]").attr('selected', 'true').trigger('change'); + } + } + + //Load User's Name and Avatar + + user_avatar = settings.user_avatar; + $('.mes').each(function () { + if ($(this).attr('ch_name') == name1) { + $(this).children('.avatar').children('img').attr('src', 'User Avatars/' + user_avatar); + } + }); + + //Load the API server URL from settings + api_server = settings.api_server; + $('#api_url_text').val(api_server); + + // world info settings + world_names = data.world_names?.length ? data.world_names : []; + + if (settings.world_info != undefined) { + if (world_names.includes(settings.world_info)) { + world_info = settings.world_info; + } + } + + world_names.forEach((item, i) => { + $('#world_info').append(``); + // preselect world if saved + if (item == world_info) { + $('#world_info').val(i).change(); + } + }); + // end world info settings + + if (data.enable_extensions) { + const src = 'scripts/extensions.js'; + if ($(`script[src="${src}"]`).length === 0) { + const script = document.createElement('script'); + script.type = 'text/javascript'; + script.src = src; + $('body').append(script); + } + } + + //get the character to auto-load + if (settings.active_character !== undefined) { + if (settings.active_character !== '') { + active_character = settings.active_character; + } + } + + api_server_textgenerationwebui = settings.api_server_textgenerationwebui; + $("#textgenerationwebui_api_url_text").val(api_server_textgenerationwebui); + + + for (var i of ["temp", "rep_pen", "rep_pen_size", "top_k", "top_p", "typical_p", "penalty_alpha"]) { + $("#" + i + "_textgenerationwebui") + .val(textgenerationwebui_settings[i]); + $("#" + i + "_counter_textgenerationwebui") + .html(textgenerationwebui_settings[i]); + } + } + if (!is_checked_colab) isColab(); + }, + error: function (jqXHR, exception) { + console.log(exception); + console.log(jqXHR); + + } + }); + + collapse_newlines = localStorage.getItem(storage_keys.collapse_newlines) == 'true'; + $('#collapse-newlines-checkbox').prop('checked', collapse_newlines); + } + + async function saveSettings(type) { + //console.log('saveSettings() -- pinging server to save settings.'); + jQuery.ajax({ + type: 'POST', + url: '/savesettings', + data: JSON.stringify({ + username: name1, + api_server: api_server, + api_server_textgenerationwebui: api_server_textgenerationwebui, + preset_settings: preset_settings, + preset_settings_novel: preset_settings_novel, + user_avatar: user_avatar, + temp: temp, + amount_gen: amount_gen, + max_context: max_context, + anchor_order: anchor_order, + style_anchor: style_anchor, + character_anchor: character_anchor, + auto_connect: auto_connect, + auto_load_chat: auto_load_chat, + main_api: main_api, + api_key_novel: api_key_novel, + rep_pen: rep_pen, + rep_pen_size: rep_pen_size, + model_novel: model_novel, + temp_novel: temp_novel, + rep_pen_novel: rep_pen_novel, + rep_pen_size_novel: rep_pen_size_novel, + world_info: world_info, + world_info_depth: world_info_depth, + world_info_budget: world_info_budget, + active_character: active_character, + textgenerationwebui_settings: textgenerationwebui_settings, + }), + beforeSend: function () { + //console.log('saveSettings() -- active_character -- '+active_character); + + }, + cache: false, + dataType: "json", + contentType: "application/json", + //processData: false, + success: function (data) { + //online_status = data.result; + if (type === 'change_name') { + QuickRefresh(); //RossAscends: No more page reload on username change + //location.reload(); + } + + }, + error: function (jqXHR, exception) { + console.log(exception); + console.log(jqXHR); + + } + }); + + localStorage.setItem(storage_keys.collapse_newlines, collapse_newlines); + } + $('#donation').click(function () { + $('#shadow_tips_popup').css('display', 'block'); + $('#shadow_tips_popup').transition({ + opacity: 1.0, + duration: 100, + easing: animation_rm_easing, + complete: function () { + + } + }); + }); + $('#tips_cross').click(function () { + + $('#shadow_tips_popup').transition({ + opacity: 0.0, + duration: 100, + easing: animation_rm_easing, + complete: function () { + $('#shadow_tips_popup').css('display', 'none'); + } + }); + }); + $('#select_chat_cross').click(function () { + + + $('#shadow_select_chat_popup').css('display', 'none'); + $('#load_select_chat_div').css('display', 'block'); + }); + function isInt(value) { + return !isNaN(value) && + parseInt(Number(value)) == value && + !isNaN(parseInt(value, 10)); + } + //******************** + //***Message Editor*** + $(document).on('click', '.mes_edit', function () { + if (this_chid !== undefined || selected_group) { + const message = $(this).closest('.mes'); + + if (message.data('isSystem')) { + return; + } + + let chatScrollPosition = $("#chat").scrollTop(); + if (this_edit_mes_id !== undefined) { + let mes_edited = $('#chat').children().filter('[mesid="' + this_edit_mes_id + '"]').children('.mes_block').children('.ch_name').children('.mes_edit_done'); + messageEditDone(mes_edited); + } + $(this).parent().parent().children('.mes_text').empty(); + $(this).css('display', 'none'); + $(this).parent().children('.mes_edit_done').css('display', 'inline-block'); + $(this).parent().children('.mes_edit_done').css('opacity', 0.0); + $(this).parent().children('.mes_edit_cancel').css('display', 'inline-block'); + $(this).parent().children('.mes_edit_cancel').css('opacity', 0.0); + $(this).parent().children('.mes_edit_done').transition({ + opacity: 1.0, + duration: 600, + easing: "", + complete: function () { } + }); + $(this).parent().children('.mes_edit_cancel').transition({ + opacity: 1.0, + duration: 600, + easing: "", + complete: function () { } + }); + var edit_mes_id = $(this).parent().parent().parent().attr('mesid'); + this_edit_mes_id = edit_mes_id; + + var text = chat[edit_mes_id]['mes']; + if (chat[edit_mes_id]['is_user']) { + this_edit_mes_chname = name1; + } + else if (chat[edit_mes_id]['forced_avatar']) { + this_edit_mes_chname = chat[edit_mes_id]['name']; + } + else { + this_edit_mes_chname = name2; + } + text = text.trim(); + $(this).parent().parent().children('.mes_text').append(''); + let edit_textarea = $(this).parent().parent().children('.mes_text').children('.edit_textarea'); + edit_textarea.css('opacity', 0.0); + edit_textarea.transition({ + opacity: 1.0, + duration: 0, + easing: "", + complete: function () { } + }); + edit_textarea.height(0); + edit_textarea.height(edit_textarea[0].scrollHeight); + edit_textarea.focus(); + edit_textarea[0].setSelectionRange(edit_textarea.val().length, edit_textarea.val().length); + if (this_edit_mes_id == count_view_mes - 1) { + $("#chat").scrollTop(chatScrollPosition); + } + } + }); + $(document).on('click', '.mes_edit_cancel', function () { + //var text = $(this).parent().parent().children('.mes_text').children('.edit_textarea').val(); + var text = chat[this_edit_mes_id]['mes']; + + $(this).parent().parent().children('.mes_text').empty(); + $(this).css('display', 'none'); + $(this).parent().children('.mes_edit_done').css('display', 'none'); + $(this).parent().children('.mes_edit').css('display', 'inline-block'); + $(this).parent().parent().children('.mes_text').append(messageFormating(text, this_edit_mes_chname)); + appendImageToMessage(chat[this_edit_mes_id], $(this).closest('.mes')); + this_edit_mes_id = undefined; + }); + $(document).on('click', '.mes_edit_done', function () { + messageEditDone($(this)); + }); + function messageEditDone(div) { + + var text = div.parent().parent().children('.mes_text').children('.edit_textarea').val(); + //var text = chat[this_edit_mes_id]; + text = text.trim(); + const bias = extractMessageBias(text); + chat[this_edit_mes_id]['mes'] = text; + + // editing old messages + if (!chat[this_edit_mes_id]['extra']) { + chat[this_edit_mes_id]['extra'] = {}; + } + + chat[this_edit_mes_id]['extra']['bias'] = bias ?? null; + + div.parent().parent().children('.mes_text').empty(); + div.css('display', 'none'); + div.parent().children('.mes_edit_cancel').css('display', 'none'); + div.parent().children('.mes_edit').css('display', 'inline-block'); + div.parent().parent().children('.mes_text').append(messageFormating(text, this_edit_mes_chname)); + div.parent().parent().children('.mes_bias').empty(); + div.parent().parent().children('.mes_bias').append(messageFormating(bias)); + appendImageToMessage(chat[this_edit_mes_id], div.closest('.mes')); + this_edit_mes_id = undefined; + if (selected_group) { + saveGroupChat(selected_group); + } + else { + saveChat(); + } + } + $("#your_name_button").click(function () { + if (!is_send_press) { + name1 = $("#your_name").val(); + if (name1 === undefined || name1 == '') name1 = default_user_name; + //console.log(name1); + saveSettings('change_name'); + + } + }); + //Select chat + async function getAllCharaChats() { + //console.log('getAllCharaChats() pinging server for character chat history.'); + $('#select_chat_div').html(''); + //console.log(characters[this_chid].chat); + jQuery.ajax({ + type: 'POST', + url: '/getallchatsofcharacter', + data: JSON.stringify({ avatar_url: characters[this_chid].avatar }), + beforeSend: function () { + //$('#create_button').attr('value','Creating...'); + }, + cache: false, + dataType: "json", + contentType: "application/json", + success: function (data) { + $('#load_select_chat_div').css('display', 'none'); + let dataArr = Object.values(data); + data = dataArr.sort((a, b) => a['file_name'].localeCompare(b['file_name'])); + data = data.reverse(); + + for (const key in data) { + let strlen = 300; + let mes = data[key]['mes']; + if (mes !== undefined) { + if (mes.length > strlen) { + mes = '...' + mes.substring(mes.length - strlen); + } + $('#select_chat_div').append('
' + data[key]['file_name'] + '
' + mes + '
'); + if (characters[this_chid]['chat'] == data[key]['file_name'].replace('.jsonl', '')) { + //children().last() + $('#select_chat_div').children(':nth-last-child(1)').attr('highlight', true); + } + } + } + //
+ + //
+ //console.log(data); + //chat.length = 0; + + //chat = data; + //getChatResult(); + //saveChat(); + //console.log('getAllCharaChats() -- Finished successfully'); + }, + error: function (jqXHR, exception) { + //getChatResult(); + //console.log('getAllCharaChats() -- Failed'); + console.log(exception); + console.log(jqXHR); + + } + }); + } + //************************************************************ + //************************Novel.AI**************************** + //************************************************************ + async function getStatusNovel() { + if (is_get_status_novel) { + + var data = { key: api_key_novel }; + + + jQuery.ajax({ + type: 'POST', // + url: '/getstatus_novelai', // + data: JSON.stringify(data), + beforeSend: function () { + //$('#create_button').attr('value','Creating...'); + }, + cache: false, + dataType: "json", + contentType: "application/json", + success: function (data) { + + + if (data.error != true) { + //var settings2 = JSON.parse(data); + //const getData = await response.json(); + novel_tier = data.tier; + if (novel_tier == undefined) { + online_status = 'no_connection'; + } + if (novel_tier === 0) { + online_status = "Paper"; + } + if (novel_tier === 1) { + online_status = "Tablet"; + } + if (novel_tier === 2) { + online_status = "Scroll"; + } + if (novel_tier === 3) { + online_status = "Opus"; + } + } + resultCheckStatusNovel(); + }, + error: function (jqXHR, exception) { + online_status = 'no_connection'; + console.log(exception); + console.log(jqXHR); + resultCheckStatusNovel(); + } + }); + } else { + if (is_get_status != true) { + online_status = 'no_connection'; + } + } + } + $("#api_button_novel").click(function () { + if ($('#api_key_novel').val() != '') { + $("#api_loading_novel").css("display", 'inline-block'); + $("#api_button_novel").css("display", 'none'); + api_key_novel = $('#api_key_novel').val(); + api_key_novel = $.trim(api_key_novel); + //console.log("1: "+api_server); + saveSettings(); + is_get_status_novel = true; + is_api_button_press_novel = true; + } + }); + function resultCheckStatusNovel() { + is_api_button_press_novel = false; + checkOnlineStatus(); + $("#api_loading_novel").css("display", 'none'); + $("#api_button_novel").css("display", 'inline-block'); + } + $("#model_novel_select").change(function () { + model_novel = $('#model_novel_select').find(":selected").val(); + saveSettings(); + }); + $("#anchor_order").change(function () { + anchor_order = parseInt($('#anchor_order').find(":selected").val()); + saveSettings(); + }); + function compareVersions(v1, v2) { + const v1parts = v1.split('.'); + const v2parts = v2.split('.'); + + for (let i = 0; i < v1parts.length; ++i) { + if (v2parts.length === i) { + return 1; + } + + if (v1parts[i] === v2parts[i]) { + continue; + } + if (v1parts[i] > v2parts[i]) { + return 1; + } + else { + return -1; + } + } + + if (v1parts.length != v2parts.length) { + return -1; + } + + return 0; + } + //**************************CHARACTER IMPORT EXPORT*************************// + $("#character_import_button").click(function () { + $("#character_import_file").click(); + }); + $("#character_import_file").on("change", function (e) { + $('#rm_info_avatar').html(''); + var file = e.target.files[0]; + //console.log(1); + if (!file) { + return; + } + var ext = file.name.match(/\.(\w+)$/); + if (!ext || (ext[1].toLowerCase() != "json" && ext[1].toLowerCase() != "png")) { + return; + } + + var format = ext[1].toLowerCase(); + $("#character_import_file_type").val(format); + //console.log(format); + var formData = new FormData($("#form_import").get(0)); + + jQuery.ajax({ + type: 'POST', + url: '/importcharacter', + data: formData, + beforeSend: function () { + //$('#create_button').attr('disabled',true); + //$('#create_button').attr('value','Creating...'); + }, + cache: false, + contentType: false, + processData: false, + success: async function (data) { + if (data.file_name !== undefined) { + + $('#rm_info_block').transition({ opacity: 0, duration: 0 }); + var $prev_img = $('#avatar_div_div').clone(); + $prev_img.children('img').attr('src', 'characters/' + data.file_name + '.png'); + $('#rm_info_avatar').append($prev_img); + + let oldSelectedChar = null; + if (this_chid != undefined && this_chid != 'invalid-safety-id') { + oldSelectedChar = characters[this_chid].name; + } + + await getCharacters(); + select_rm_info("Character created", oldSelectedChar); + $('#rm_info_block').transition({ opacity: 1, duration: 1000 }); + } + }, + error: function (jqXHR, exception) { + $('#create_button').removeAttr("disabled"); + } + }); + }); + $('#export_button').click(function () { + var link = document.createElement('a'); + link.href = 'characters/' + characters[this_chid].avatar; + link.download = characters[this_chid].avatar; + document.body.appendChild(link); + link.click(); + }); + //**************************CHAT IMPORT EXPORT*************************// + $("#chat_import_button").click(function () { + $("#chat_import_file").click(); + }); + $("#chat_import_file").on("change", function (e) { + var file = e.target.files[0]; + //console.log(1); + if (!file) { + return; + } + var ext = file.name.match(/\.(\w+)$/); + if (!ext || (ext[1].toLowerCase() != "json" && ext[1].toLowerCase() != "jsonl")) { + return; + } + + var format = ext[1].toLowerCase(); + $("#chat_import_file_type").val(format); + //console.log(format); + var formData = new FormData($("#form_import_chat").get(0)); + //console.log('/importchat entered with: '+formData); + jQuery.ajax({ + type: 'POST', + url: '/importchat', + data: formData, + beforeSend: function () { + $('#select_chat_div').html(''); + $('#load_select_chat_div').css('display', 'block'); + //$('#create_button').attr('value','Creating...'); + }, + cache: false, + contentType: false, + processData: false, + success: function (data) { + //console.log(data); + if (data.res) { + getAllCharaChats(); + + + } + }, + error: function (jqXHR, exception) { + $('#create_button').removeAttr("disabled"); + } + }); + }); + $(document).on('click', '.select_chat_block', function () { + let file_name = $(this).attr("file_name").replace('.jsonl', ''); + //console.log(characters[this_chid]['chat']); + characters[this_chid]['chat'] = file_name; + clearChat(); + chat.length = 0; + getChat(); + $('#selected_chat_pole').val(file_name); + $("#create_button").click(); + $('#shadow_select_chat_popup').css('display', 'none'); + $('#load_select_chat_div').css('display', 'block'); + + }); + + //**************************WORLD INFO IMPORT EXPORT*************************// + $("#world_import_button").click(function () { + $("#world_import_file").click(); + }); + + $("#world_import_file").on("change", function (e) { + var file = e.target.files[0]; + + if (!file) { + return; + } + + const ext = file.name.match(/\.(\w+)$/); + if (!ext || (ext[1].toLowerCase() !== "json")) { + return; + } + + var formData = new FormData($("#form_world_import").get(0)); + + jQuery.ajax({ + type: 'POST', + url: '/importworldinfo', + data: formData, + beforeSend: () => { }, + cache: false, + contentType: false, + processData: false, + success: function (data) { + if (data.name) { + imported_world_name = data.name; + updateWorldInfoList(imported_world_name); + } + }, + error: (jqXHR, exception) => { }, + }); + + // Will allow to select the same file twice in a row + $('#form_world_import').trigger("reset"); + }); + + async function updateWorldInfoList(importedWorldName) { + var result = await fetch('/getsettings', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + "X-CSRF-Token": token, + }, + body: JSON.stringify({}) + }); + + if (result.ok) { + var data = await result.json(); + world_names = data.world_names?.length ? data.world_names : []; + $('#world_info').find('option[value!="None"]').remove(); + + world_names.forEach((item, i) => { + $('#world_info').append(``); + }); + + if (importedWorldName) { + const indexOf = world_names.indexOf(world_info); + $('#world_info').val(indexOf); + + popup_type = 'world_imported'; + callPopup('

World imported successfully! Select it now?

'); + } + } + } + + function download(content, fileName, contentType) { + var a = document.createElement("a"); + var file = new Blob([content], { type: contentType }); + a.href = URL.createObjectURL(file); + a.download = fileName; + a.click(); + } + + // World Info Editor + async function showWorldEditor() { + if (!world_info) { + popup_type = 'default'; + callPopup('

Select a world info first!

'); + return; + } + + is_world_edit_open = true; + $('#world_popup_name').val(world_info); + $('#world_popup').css('display', 'flex'); + await loadWorldInfoData(); + displayWorldEntries(world_info_data); + } + + async function loadWorldInfoData() { + if (!world_info) { + return; + } + + const response = await fetch("/getworldinfo", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ name: world_info }) + }); + + if (response.ok) { + world_info_data = await response.json(); + } + } + + function hideWorldEditor() { + is_world_edit_open = false; + $('#world_popup').css('display', 'none'); + } + + function displayWorldEntries(data) { + $('#world_popup_entries_list').empty(); + + if (!data || !('entries' in data)) { + return; + } + + for (const entryUid in data.entries) { + const entry = data.entries[entryUid]; + appendWorldEntry(entry); + } + } + + function appendWorldEntry(entry) { + const template = $('#entry_edit_template .world_entry').clone(); + template.data('uid', entry.uid); + + // key + const keyInput = template.find('textarea[name="key"]'); + keyInput.data('uid', entry.uid); + keyInput.on('input', function () { + const uid = $(this).data('uid'); + const value = $(this).val(); + $(this).css("height", ""); //reset the height + $(this).css("height", $(this).prop('scrollHeight') + "px"); + world_info_data.entries[uid].key = value.split(',').map(x => x.trim()).filter(x => x); + saveWorldInfo(); + }); + keyInput.val(entry.key.join(',')).trigger('input'); + keyInput.css("height", ""); //reset the height + keyInput.css("height", $(this).prop('scrollHeight') + "px"); + + // keysecondary + const keySecondaryInput = template.find('textarea[name="keysecondary"]'); + keySecondaryInput.data('uid', entry.uid); + keySecondaryInput.on('input', function () { + const uid = $(this).data('uid'); + const value = $(this).val(); + $(this).css("height", ""); //reset the height + $(this).css("height", $(this).prop('scrollHeight') + "px"); + world_info_data.entries[uid].keysecondary = value.split(',').map(x => x.trim()).filter(x => x); + saveWorldInfo(); + }); + keySecondaryInput.val(entry.keysecondary.join(',')).trigger('input'); + keySecondaryInput.css("height", ""); //reset the height + keySecondaryInput.css("height", $(this).prop('scrollHeight') + "px"); + + // comment + const commentInput = template.find('textarea[name="comment"]'); + commentInput.data('uid', entry.uid); + commentInput.on('input', function () { + const uid = $(this).data('uid'); + const value = $(this).val(); + $(this).css("height", ""); //reset the height + $(this).css("height", $(this).prop('scrollHeight') + "px"); + world_info_data.entries[uid].comment = value; + saveWorldInfo(); + }); + commentInput.val(entry.comment).trigger('input'); + commentInput.css("height", ""); //reset the height + commentInput.css("height", $(this).prop('scrollHeight') + "px"); + + // content + const contentInput = template.find('textarea[name="content"]'); + contentInput.data('uid', entry.uid); + contentInput.on('input', function () { + const uid = $(this).data('uid'); + const value = $(this).val(); + world_info_data.entries[uid].content = value; + $(this).css("height", ""); //reset the height + $(this).css("height", $(this).prop('scrollHeight') + "px"); + saveWorldInfo(); + + // count tokens + const numberOfTokens = encode(value).length; + $(this).closest('.world_entry').find('.world_entry_form_token_counter').html(numberOfTokens); + }); + contentInput.val(entry.content).trigger('input'); + contentInput.css("height", ""); //reset the height + contentInput.css("height", $(this).prop('scrollHeight') + "px"); + + // selective + const selectiveInput = template.find('input[name="selective"]'); + selectiveInput.data('uid', entry.uid); + selectiveInput.on('input', function () { + const uid = $(this).data('uid'); + const value = $(this).prop('checked'); + world_info_data.entries[uid].selective = value; + saveWorldInfo(); + + const keysecondary = $(this).closest('.world_entry').find('.keysecondary'); + value ? keysecondary.show() : keysecondary.hide(); + }); + selectiveInput.prop('checked', entry.selective).trigger('input'); + selectiveInput.siblings('.checkbox_fancy').click(function () { + $(this).siblings('input').click(); + }); + + + // constant + const constantInput = template.find('input[name="constant"]'); + constantInput.data('uid', entry.uid); + constantInput.on('input', function () { + const uid = $(this).data('uid'); + const value = $(this).prop('checked'); + world_info_data.entries[uid].constant = value; + saveWorldInfo(); + }); + constantInput.prop('checked', entry.constant).trigger('input'); + constantInput.siblings('.checkbox_fancy').click(function () { + $(this).siblings('input').click(); + }); + + // order + const orderInput = template.find('input[name="order"]'); + orderInput.data('uid', entry.uid); + orderInput.on('input', function () { + const uid = $(this).data('uid'); + const value = Number($(this).val()); + + world_info_data.entries[uid].order = !isNaN(value) ? value : 0; + saveWorldInfo(); + }); + orderInput.val(entry.order).trigger('input'); + + // position + if (entry.position === undefined) { + entry.position = 0; + } + + const positionInput = template.find('input[name="position"]'); + positionInput.data('uid', entry.uid); + positionInput.on('input', function () { + const uid = $(this).data('uid'); + const value = Number($(this).val()); + world_info_data.entries[uid].position = !isNaN(value) ? value : 0; + saveWorldInfo(); + }) + template.find(`input[name="position"][value=${entry.position}]`).prop('checked', true).trigger('input'); + + // display uid + template.find('.world_entry_form_uid_value').html(entry.uid); + + // delete button + const deleteButton = template.find('input.delete_entry_button'); + deleteButton.data('uid', entry.uid); + deleteButton.on('click', function () { + const uid = $(this).data('uid'); + deleteWorldInfoEntry(uid); + $(this).closest('.world_entry').remove(); + saveWorldInfo(); + }); + + template.appendTo('#world_popup_entries_list'); + return template; + } + + async function deleteWorldInfoEntry(uid) { + if (!world_info_data || !('entries' in world_info_data)) { + return; + } + + delete world_info_data.entries[uid]; + } + + function createWorldInfoEntry() { + const newEntryTemplate = { + key: [], + keysecondary: [], + comment: '', + content: '', + constant: false, + selective: false, + order: 100, + position: 0, + }; + const newUid = getFreeWorldEntryUid(); + + if (!Number.isInteger(newUid)) { + console.error("Couldn't assign UID to a new entry"); + return; + } + + const newEntry = { uid: newUid, ...newEntryTemplate }; + world_info_data.entries[newUid] = newEntry; + + const entryTemplate = appendWorldEntry(newEntry); + entryTemplate.get(0).scrollIntoView({ behavior: 'smooth' }); + } + + async function saveWorldInfo(immediately) { + if (!world_info || !world_info_data) { + return; + } + + async function _save() { + const response = await fetch("/editworldinfo", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ name: world_info, data: world_info_data }) + }); + } + + if (immediately) { + return await _save(); + } + + clearTimeout(timerWorldSave); + timerWorldSave = setTimeout(async () => await _save(), durationSaveEdit); + } + + async function renameWorldInfo() { + const oldName = world_info; + const newName = $('#world_popup_name').val(); + + if (oldName === newName) { + return; + } + + world_info = newName; + await saveWorldInfo(true); + await deleteWorldInfo(oldName, newName); + } + + async function deleteWorldInfo(worldInfoName, selectWorldName) { + if (!world_names.includes(worldInfoName)) { + return; + } + + const response = await fetch("/deleteworldinfo", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify({ name: worldInfoName }) + }); + + if (response.ok) { + await updateWorldInfoList(); + + const selectedIndex = world_names.indexOf(selectWorldName); + if (selectedIndex !== -1) { + $('#world_info').val(selectedIndex).change(); + } + else { + $('#world_info').val('None').change(); + } + + hideWorldEditor(); + } + } + + function getFreeWorldEntryUid() { + if (!world_info_data || !('entries' in world_info_data)) { + return null; + } + + const MAX_UID = 1_000_000; // <- should be safe enough :) + for (let uid = 0; uid < MAX_UID; uid++) { + if (uid in world_info_data.entries) { + continue; + } + return uid; + } + + return null; + } + + function getFreeWorldName() { + const MAX_FREE_NAME = 100_000; + for (let index = 1; index < MAX_FREE_NAME; index++) { + const newName = `New World (${index})`; + if (world_names.includes(newName)) { + continue; + } + return newName; + } + + return undefined; + } + + async function createNewWorldInfo() { + const worldInfoTemplate = { entries: {} }; + const worldInfoName = getFreeWorldName(); + + if (!worldInfoName) { + return; + } + + world_info = worldInfoName; + world_info_data = { ...worldInfoTemplate }; + await saveWorldInfo(true); + await updateWorldInfoList(); + + const selectedIndex = world_names.indexOf(worldInfoName); + if (selectedIndex !== -1) { + $('#world_info').val(selectedIndex).change(); + } + else { + $('#world_info').val('None').change(); + } + } + + $('#world_info_edit_button').click(() => { + is_world_edit_open ? hideWorldEditor() : showWorldEditor(); + }); + + $('#world_popup_export').click(() => { + if (world_info && world_info_data) { + const jsonValue = JSON.stringify(world_info_data); + const fileName = `${world_info}.json`; + download(jsonValue, fileName, 'application/json'); + } + }); + + $('#world_popup_delete').click(() => { + popup_type = 'del_world'; + callPopup('

Delete the World Info?

'); + }); + + $('#world_popup_new').click(() => { + createWorldInfoEntry(); + }); + + $('#world_cross').click(() => { + hideWorldEditor(); + }); + + $('#world_popup_name_button').click(() => { + renameWorldInfo(); + }); + + $('#world_create_button').click(() => { + createNewWorldInfo(); + }); + + /// UTILS + function onlyUnique(value, index, array) { + return array.indexOf(value) === index; + } + + function shuffle(array) { + let currentIndex = array.length, randomIndex; + + while (currentIndex != 0) { + randomIndex = Math.floor(Math.random() * currentIndex); + currentIndex--; + [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]; + } + return array; + } + + function setExtensionPrompt(key, value) { + extension_prompts[key] = value; + } + + window['TavernAI'].getContext = function () { + return { + chat: chat, + characters: characters, + groups: groups, + worldInfo: world_info_data, + name1: name1, + name2: name2, + characterId: this_chid, + groupId: selected_group, + chatId: (this_chid && characters[this_chid] && characters[this_chid].chat), + onlineStatus: online_status, + addOneMessage: addOneMessage, + generate: Generate, + encode: encode, + extensionPrompts: extension_prompts, + setExtensionPrompt: setExtensionPrompt, + saveChat: saveChat, + sendSystemMessage: sendSystemMessage, + }; + }; + + //RossAscends: auto-load last character function (fires when active_character is defined and auto_load_chat is true) + function autoloadchat() { + console.log('starting autoloadchat routine'); + jQuery.ajax({ + type: 'POST', + url: '/getsettings', + data: JSON.stringify({}), + beforeSend: function () { + }, + cache: false, + dataType: "json", + contentType: "application/json", + success: function (data) { + if (data.result != 'file not find') { + settings = JSON.parse(data.settings); + //get the character to auto-load + if (settings.active_character !== undefined) { + if (settings.active_character !== '') { + active_character = settings.active_character; + } + } + } + console.log('active_character = ' + active_character); + console.log('auto_load_chat = ' + auto_load_chat); + + if (active_character !== undefined && auto_load_chat == true) { + $('#CharID' + active_character).click(); //will auto-select and load chat of last selected character is auto_load_chat is true + } + }, + error: function (jqXHR, exception) { + console.log(exception); + console.log(jqXHR); + + } + }); + + } + //RossAscends: auto-connect to last API function (fires when API URL exists in settings and auto_connect is true) + function autoconnect() { + console.log('starting autoconnect routine'); + jQuery.ajax({ + type: 'POST', + url: '/getsettings', + data: JSON.stringify({}), + beforeSend: function () { + }, + cache: false, + dataType: "json", + contentType: "application/json", + //processData: false, + success: function (data) { + if (data.result != 'file not find') { + settings = JSON.parse(data.settings); + + //Load the API server URL from settings + api_server = settings.api_server; + api_server_textgenerationwebui = settings.api_server_textgenerationwebui; + api_key_novel = settings.api_key_novel; + $('#api_url_text').val(api_server); + $('#textgenerationwebui_api_url_text').val(api_server_textgenerationwebui); + $('#api_key_novel').val(api_key_novel); + } + + console.log('api_server = ' + api_server); + console.log('api_server_textgenerationwebui = ' + api_server_textgenerationwebui); + console.log('api_key_novel = ' + api_key_novel); + console.log('auto_connect = ' + auto_connect); + changeMainAPI(); + + if (main_api === 'kobold' && api_server && auto_connect) { + $('#api_button').click(); + } + + if (main_api === 'textgenerationwebui' && api_server_textgenerationwebui && auto_connect) { + $('#api_button_textgenerationwebui').click(); + } + + if (main_api === 'novel' && api_key_novel && auto_connect) { + $('#api_button_novel').click(); + } + }, + error: function (jqXHR, exception) { + console.log(exception); + console.log(jqXHR); + + } + }); + } +}); diff --git a/public/style.css b/public/style.css index 1a0d0509d..4b3616839 100644 --- a/public/style.css +++ b/public/style.css @@ -1,64 +1,65 @@ @charset "UTF-8"; :root { - --transparent: rgba(0,0,0,0); - - --black30a: rgba(0,0,0,0.3); - --black50a: rgba(0,0,0,0.5); - --black70a: rgba(0,0,0,0.7); - --black100: rgba(0,0,0,1); - - --white30a: rgba(255,255,255,0.3); - --white50a: rgba(255,255,255,0.5); - --white70a: rgba(255,255,255,0.7); - --white100: rgba(255,255,255,1); - - --grey10: rgb(25,25,25); - --grey30: rgb(75,75,75); - --grey50: rgb(125,125,125); - --grey70: rgb(175,175,175); - - --fullred: rgba(255,0,0,1); - --crimson70a: rgba(100,0,0,0.7); - --cobalt30a: rgba(100,100,255,0.3); - --sienna: rgb(210,100,40); - --orangered: rgb(255,90,0); - --greyCAIbg: rgb(36,36,37); - --ivory: rgba(229,224,216,1); + --transparent: rgba(0, 0, 0, 0); + + --black30a: rgba(0, 0, 0, 0.3); + --black50a: rgba(0, 0, 0, 0.5); + --black70a: rgba(0, 0, 0, 0.7); + --black100: rgba(0, 0, 0, 1); + + --white30a: rgba(255, 255, 255, 0.3); + --white50a: rgba(255, 255, 255, 0.5); + --white70a: rgba(255, 255, 255, 0.7); + --white100: rgba(255, 255, 255, 1); + + --grey10: rgb(25, 25, 25); + --grey30: rgb(75, 75, 75); + --grey50: rgb(125, 125, 125); + --grey70: rgb(175, 175, 175); + + --fullred: rgba(255, 0, 0, 1); + --crimson70a: rgba(100, 0, 0, 0.7); + --cobalt30a: rgba(100, 100, 255, 0.3); + --sienna: rgb(210, 100, 40); + --orangered: rgb(255, 90, 0); + --greyCAIbg: rgb(36, 36, 37); + --ivory: rgba(229, 224, 216, 1); } * { - box-sizing: border-box; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - -moz-appearance:initial; + box-sizing: border-box; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -moz-appearance: initial; } body { margin: 0; - padding:0; - width: 100%; + padding: 0; + width: 100%; height: 100%; background-color: var(--greyCAIbg); background-repeat: no-repeat; background-attachment: fixed; background-size: cover; - font-family: "Noto Sans", "Noto Color Emoji", sans-serif; - font-size:15px; /*1rem*/ - color: var(--ivory); - + font-family: "Noto Sans", "Noto Color Emoji", sans-serif; + font-size: 15px; + /*1rem*/ + color: var(--ivory); + } -@media screen and (max-width: 450px) { +@media screen and (max-width: 450px) { body { - margin-left: auto; - margin-right: auto; - overflow-x: hidden; + margin-left: auto; + margin-right: auto; + overflow-x: hidden; } } ::-webkit-scrollbar { - width: 0.6em; + width: 0.6em; } ::-webkit-scrollbar-track { @@ -69,26 +70,28 @@ body { ::-webkit-scrollbar-thumb { background: var(--white70a); -webkit-box-shadow: inset 0 0 2px var(--black30a); - box-shadow: inset 0 0 5px black; + box-shadow: inset 0 0 5px black; border-radius: 5px; } @supports (height: 100dvh) { - body { - height: 100dvh; - } + body { + height: 100dvh; + } } .mes_text p { - margin-top:0; + margin-top: 0; margin-bottom: 10px; } + .mes_text li tt { min-width: 80px; display: inline-block; color: grey !important; text-align: right; } + .mes_bias { display: block; font-size: 0.9rem; @@ -97,11 +100,19 @@ body { } /*.mes_text br {display:none;}*/ -.mes_text i, .mes_text em {color: var(--grey70);} -.mes_text strong, .mes_text h2, .mes_text h1 {font-weight: bold;} +.mes_text i, +.mes_text em { + color: var(--grey70); +} + +.mes_text strong, +.mes_text h2, +.mes_text h1 { + font-weight: bold; +} code { - padding: 5px; + padding: 5px; font-family: Consolas, monospace; color: var(--white50a); white-space: pre-wrap; @@ -112,7 +123,7 @@ code { display: inline-block; } -#bg1{ +#bg1 { background: url(backgrounds/tavern.png); background-repeat: no-repeat; background-attachment: fixed; @@ -123,8 +134,9 @@ code { height: 100%; z-index: -2; } -#bg2{ - background: url(backgrounds/tavern.png); + +#bg2 { + background: url(backgrounds/tavern.png); background-repeat: no-repeat; background-attachment: fixed; filter: blur(2px); @@ -134,33 +146,33 @@ code { width: 100%; height: 100%; z-index: -1; -} +} /*TOPPER margin*/ -#top-bar{ - width:100vw; - display: inline-block; - height:40px; - position:fixed; - color:var(--black30a); - border-bottom:1px solid var(--black70a); - box-shadow:0 2px 20px 0 var(--black70a); - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); - z-index:2001; +#top-bar { + width: 100vw; + display: inline-block; + height: 40px; + position: fixed; + color: var(--black30a); + border-bottom: 1px solid var(--black70a); + box-shadow: 0 2px 20px 0 var(--black70a); + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); + z-index: 2001; } #sheld { display: grid; grid-template-rows: auto min-content; height: calc(100svh); - + /*overflow: auto;*/ overflow-x: hidden; /*overflow-y: hidden;*/ - max-width:800px; + max-width: 800px; margin-left: auto; margin-right: auto; @@ -169,22 +181,22 @@ code { #chat { overflow-x: hidden; overflow-y: scroll; - margin-top:40px; - border-bottom:1px solid var(--black30a); - border-left:1px solid var(--black30a); - border-right:1px solid var(--black30a); - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); - /*border-radius: 0 0 40px 40px;*/ - text-shadow: #000 0 0 3px; - + margin-top: 40px; + border-bottom: 1px solid var(--black30a); + border-left: 1px solid var(--black30a); + border-right: 1px solid var(--black30a); + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); + /*border-radius: 0 0 40px 40px;*/ + text-shadow: #000 0 0 3px; + } #form_sheld { - white-space:nowrap; - width:100%; - margin: 1px auto 10px auto; + white-space: nowrap; + width: 100%; + margin: 1px auto 10px auto; } #send_form { @@ -196,7 +208,7 @@ code { border: 1px solid var(--black30a); border-radius: 0 0 20px 20px; - background-color:var(--crimson70a); + background-color: var(--crimson70a); } #send_but_sheld { @@ -206,28 +218,29 @@ code { position: relative; background-position: center; } -#send_but{ + +#send_but { width: 40px; height: 40px; - margin: 0; + margin: 0; display: none; - padding:1px; + padding: 1px; background: url('img/send3.png') no-repeat; background-size: 26px auto; background-position: center center; - outline: none; - - border: none; - cursor: pointer; - transition: 0.3s; - filter:brightness(0.5); + outline: none; + + border: none; + cursor: pointer; + transition: 0.3s; + filter: brightness(0.5); } #send_but:hover { - filter:brightness(150%); - } + filter: brightness(150%); +} -#loading_mes{ +#loading_mes { display: none; width: 40px; height: 40px; @@ -239,7 +252,7 @@ code { } #options_button { - position: relative; + position: relative; display: inline; color: var(--white50a); cursor: pointer; @@ -249,73 +262,81 @@ code { -webkit-transition: color .25s ease-in-out; -moz-transition: color .25s ease-in-out; transition: color .25s ease-in-out; - padding-left: 10px; + padding-left: 10px; padding-top: 0; - + } #options_button:after { - content: '\2630'; /*uses a unicode symbol for hamburger menu icon */ + content: '\2630'; + /*uses a unicode symbol for hamburger menu icon */ text-decoration: none; - font-size: 1.5rem; - + font-size: 1.5rem; + } #options_button:hover { color: var(--white100); } -#options{ +#options { opacity: 0.0; display: none; - bottom: 200px; /*sets vertical position of the options menu to the left of input bar */ + bottom: 200px; + /*sets vertical position of the options menu to the left of input bar */ position: relative; - z-index:1990; - + z-index: 1990; + } .options-content { - overflow: hidden; - display: block; - position: absolute; - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); - border: 1px solid #666; - border-radius: 15px; - box-shadow:00 5px #000; - text-shadow: #000 0 0 3px; - min-width: 200px; - z-index: 2000; + overflow: hidden; + display: block; + position: absolute; + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); + border: 1px solid #666; + border-radius: 15px; + box-shadow: 00 5px #000; + text-shadow: #000 0 0 3px; + min-width: 200px; + z-index: 2000; } /* Ссылки внутри выпадающего блока */ .options-content hr { - margin:0; - padding:0; - border-top: 1px solid var(--white30a); + margin: 0; + padding: 0; + border-top: 1px solid var(--white30a); } -#right-nav-panel hr, #personality_div hr { + +#right-nav-panel hr, +#personality_div hr { background-image: linear-gradient(90deg, var(--transparent), var(--white30a), var(--transparent)); } + .options-content a { - color: var(--ivory, white); - padding: 12px 16px; - text-decoration: none; - display: block; + color: var(--ivory, white); + padding: 12px 16px; + text-decoration: none; + display: block; } .options-content img { /* opacity: 0.5; */ margin-right: 10px; height: 1.25rem; - vertical-align: middle; + vertical-align: middle; +} + +.options-content span { + vertical-align: middle; } -.options-content span {vertical-align:middle;} /* Изменяем цвет ссылки при наведении */ .options-content a:hover { - background-color: var(--white30a); + background-color: var(--white30a); } @@ -327,22 +348,23 @@ code { width: 100%; color: var(--ivory, white); } + .avatar { width: 50px; height: 50px; - border-style:none; + border-style: none; } .avatar img { - width: 100%; + width: 100%; height: 100%; object-fit: cover; object-position: center center; border-radius: 50%; - border: 1px solid var(--black30a); - box-shadow: 0 0 5px var(--black50a); - - + border: 1px solid var(--black30a); + box-shadow: 0 0 5px var(--black50a); + + } .avatar.selected img { @@ -351,26 +373,28 @@ code { outline-width: 2px; } -.mes_block{ - - padding-top:0; +.mes_block { + + padding-top: 0; padding-left: 10px; } -.ch_name{ - - font-weight:bolder; + +.ch_name { + + font-weight: bolder; } -.mes_text{ - font-weight:400; - line-height:1.25rem; + +.mes_text { + font-weight: 400; + line-height: 1.25rem; padding-right: 40px; - padding-left: 5px; - padding-top:5px; - padding-bottom:5px; + padding-left: 5px; + padding-top: 5px; + padding-bottom: 5px; max-width: 720px; word-wrap: break-word; animation: typing 3.5s steps(40, end), blink-caret .75s step-end infinite; - + } .mes_text::after { @@ -387,12 +411,12 @@ code { } br { - display: block; - margin: 3px 0; + display: block; + margin: 3px 0; } -textarea{ - width: 100%; +textarea { + width: 100%; resize: vertical; display: block; background-color: var(--black30a); @@ -405,7 +429,7 @@ textarea{ padding: 5px 10px; } -#send_textarea{ +#send_textarea { font-size: 1rem; line-height: 1.5rem; min-height: calc(1.5em + 0.75rem + 2px); @@ -414,113 +438,117 @@ textarea{ height: 40px; resize: vertical; display: block; - background-color: rgba(255,0,0,0); - border:0; + background-color: rgba(255, 0, 0, 0); + border: 0; box-shadow: none; - padding:6px 0 6px 0; - font-family: "Noto Sans", "Noto Color Emoji", sans-serif; + padding: 6px 0 6px 0; + font-family: "Noto Sans", "Noto Color Emoji", sans-serif; margin: 0; - text-shadow: #000 0 0 3px; + text-shadow: #000 0 0 3px; } -#send_textarea::placeholder{color:var(--white70a)} +#send_textarea::placeholder { + color: var(--white70a) +} #rm_ch_create_block textarea { font-size: 15px; - min-height:200px; + min-height: 200px; } -.margin-bot-10px {margin-bottom:10px;} +.margin-bot-10px { + margin-bottom: 10px; +} + +#description_textarea { -#description_textarea{ - height: -webkit-fill-available; - + } -#character_name_pole{ +#character_name_pole {} + +#firstmessage_textarea { - -} -#firstmessage_textarea{ - height: -webkit-fill-available; } -.text_pole{ - background-color: var(--black30a); +.text_pole { + background-color: var(--black30a); color: var(--white70a); - border:1px solid var(--white30a); - border-radius:10px; + border: 1px solid var(--white30a); + border-radius: 10px; font-family: "Noto Sans", "Noto Color Emoji", sans-serif; font-size: 15px; padding: 7px; - width:100%; - margin: 5px 0; + width: 100%; + margin: 5px 0; } -.right_menu{ - max-height: 90vh; - padding: 0 20px; +.right_menu { + max-height: 90vh; + padding: 0 20px; } + .right_menu h3 { - margin:0; - padding:10px 0; + margin: 0; + padding: 10px 0; } + .right_menu h4 { - margin:0; - padding:5px 0; + margin: 0; + padding: 5px 0; } + .right_menu h5 { color: var(--white50a); - margin:0; - padding-bottom:5px; - font-size:0.75rem; + margin: 0; + padding-bottom: 5px; + font-size: 0.75rem; } -input:focus, textarea:focus, select:focus{ +input:focus, +textarea:focus, +select:focus { outline: none; } -input::file-selector-button { - -} +input::file-selector-button {} input[type="file"] { display: none; } -input[type=submit] { -} +input[type=submit] {} -#right-nav-panel-tabs{ - margin-top:10px; - margin-bottom:10px; - width: calc(100% - 70px); - margin-left:20px; - margin-right:30px; +#right-nav-panel-tabs { + margin-top: 10px; + margin-bottom: 10px; + width: calc(100% - 70px); + margin-left: 20px; + margin-right: 30px; } /* ##################################################################### */ /* Right Panel's Upper Tabs */ /* ##################################################################### */ -.right_menu_button{ - display:inline-block; - cursor:pointer; - vertical-align:middle; +.right_menu_button { + display: inline-block; + cursor: pointer; + vertical-align: middle; text-align: center; padding-right: 20px; - font-size:1.5rem; + font-size: 1.5rem; margin-top: 0; - filter: grayscale(1) brightness(75%); - -webkit-transition: all 0.5s ease-in-out; - transition: all 0.5s ease-in-out; + filter: grayscale(1) brightness(75%); + -webkit-transition: all 0.5s ease-in-out; + transition: all 0.5s ease-in-out; } .right_menu_button:hover { - filter: brightness(150%) grayscale(1); + filter: brightness(150%) grayscale(1); } #rm_button_panel_pin_div { @@ -531,16 +559,16 @@ input[type=submit] { float: right; } -#rm_button_panel_pin { - padding:0; - margin:0; +#rm_button_panel_pin { + padding: 0; + margin: 0; cursor: pointer; height: 0; width: 0; z-index: 3001; } - -#rm_button_panel_pin:hover::after { + +#rm_button_panel_pin:hover::after { filter: grayscale(1) brightness(150%); } @@ -563,7 +591,8 @@ input[type=submit] { } #rm_button_panel_pin:checked::after { - content: '\01F512'; /*closed lock emoji*/ + content: '\01F512'; + /*closed lock emoji*/ line-height: 20px; font-size: 15px; } @@ -571,12 +600,12 @@ input[type=submit] { /* ####################################################################### */ -#characloud_url{ +#characloud_url { opacity: 0.3; } #characloud_url img { - width: 25px; + width: 25px; } #rm_print_characters_block { @@ -585,9 +614,9 @@ input[type=submit] { overflow-y: auto; } -#rm_ch_create_block{ +#rm_ch_create_block { display: none; - overflow-y: auto; + overflow-y: auto; } /* ################################################################*/ @@ -600,35 +629,37 @@ select { background-color: var(--black30a); font-size: 15px; border: 1px solid var(--white30a); - border-radius:10px; - width:100%; + border-radius: 10px; + width: 100%; } -select option { /* works to highlight selected/active option */ - background-color: var(--white50a); - color: var(--black70a); - +select option { + /* works to highlight selected/active option */ + background-color: var(--white50a); + color: var(--black70a); + } -select option:not(:checked) { /* works to color unselected items */ - background-color: var(--black70a); - color: var(--white70a); +select option:not(:checked) { + /* works to color unselected items */ + background-color: var(--black70a); + color: var(--white70a); } /*#######################################################################*/ -#rm_api_block{ - display: none; +#rm_api_block { + display: none; padding-bottom: 5px; overflow-y: auto; - grid-template-rows: auto; - grid-gap: 10px; + grid-template-rows: auto; + grid-gap: 10px; } -.API-logo{ +.API-logo { margin: 0 auto; width: min-content; - opacity: 0.5; + opacity: 0.5; } .oobabooga_logo { @@ -636,34 +667,41 @@ select option:not(:checked) { /* works to color unselected items */ text-align: center; } -#api_url_text, #textgenerationwebui_api_url_text{ +#api_url_text, +#textgenerationwebui_api_url_text { /*margin-right: 4px;*/ - display:block; + display: block; } -#api_button, #api_button_novel, #api_button_textgenerationwebui { -} +#api_button, +#api_button_novel, +#api_button_textgenerationwebui {} #textgenerationwebui_api pre { display: inline; } -#api_button:hover, #api_button_novel:hover{background-color:green;} +#api_button:hover, +#api_button_novel:hover { + background-color: green; +} -#api_loading, #api_loading_textgenerationwebui{ +#api_loading, +#api_loading_textgenerationwebui { width: 25px; height: 25px; display: none; - + } -#api_loading_novel{ + +#api_loading_novel { width: 25px; height: 25px; display: none; - + } -#rm_characters_block{ +#rm_characters_block { display: block; /* visibility: hidden; */ } @@ -723,57 +761,62 @@ input[type=search]:focus::-webkit-search-cancel-button { pointer-events: all; } -.character_select{ +.character_select { padding: 5px; border-radius: 10px; - cursor:pointer; + cursor: pointer; display: grid; grid-template-columns: 67px auto; } -.character_select .ch_name{ +.character_select .ch_name { margin-left: 10px; margin-top: 5px; - transform: translateY(25%); + transform: translateY(25%); } -.character_select:hover{ + +.character_select:hover { background-color: var(--white50a); } -#avatar_url_div{ + +#avatar_url_div { display: none; } -#selected_chat_div{ + +#selected_chat_div { display: none; } -#create_date_div{ + +#create_date_div { display: none; } -#last_mes_div{ + +#last_mes_div { display: none; } /*LEFT SIDE BG MENU*/ -#logo_block{ - margin-top: 10px; - height:26px; - z-index:2000; +#logo_block { + margin-top: 10px; + height: 26px; + z-index: 2000; } -#bg_menu{ - margin-top:0; +#bg_menu { + margin-top: 0; margin-left: 2px; - cursor:pointer; + cursor: pointer; position: absolute; z-index: 2050; - -webkit-user-select: none; - -webkit-touch-callout: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; + -webkit-user-select: none; + -webkit-touch-callout: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; } -#site_logo{ +#site_logo { opacity: 0.4; display: inline-block; width: 130px; @@ -783,7 +826,7 @@ input[type=search]:focus::-webkit-search-cancel-button { } #update-notification { - height: min-content; + height: min-content; font-size: 0.75rem; line-height: 0.75rem; color: orange; @@ -794,60 +837,64 @@ input[type=search]:focus::-webkit-search-cancel-button { } #update-notification a { - color:orange; - text-decoration:none; + color: orange; + text-decoration: none; } -#bg_menu_button{ + +#bg_menu_button { display: inline-block; opacity: 0.4; - transition: 0.5s; + transition: 0.5s; cursor: pointer; width: 20px; text-align: center; height: 20px; color: var(--white50a); - + } -#bg_menu_button img{ - width: 20px; - height: 20px; - margin-bottom: 6px; + +#bg_menu_button img { + width: 20px; + height: 20px; + margin-bottom: 6px; } -#bg_menu_content{ + +#bg_menu_content { margin-top: 5px; - margin-left:0; + margin-left: 0; opacity: 0.0; - cursor:auto; + cursor: auto; display: block; width: 122px; - height:0; - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); + height: 0; + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); overflow: hidden; } .bg_example { -width: 103px; + width: 103px; height: 83px; border-style: none; padding: 6px; /* padding-bottom: 20px; */ position: relative; margin-left: 3px; - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(1px); + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(1px); } .bg_example_img { - cursor: pointer; + cursor: pointer; width: 100%; height: 100%; object-fit: cover; object-position: center center; border-radius: 10px; } + .bg_example_cross { width: 12px; height: 12px; @@ -861,65 +908,60 @@ width: 103px; border-radius: 2px; padding: 1px; } + .bg_example_but_load { margin-left: 3px; - - width: 103px; - height: 83px; - border-style: none; - padding:6px; - padding-bottom:20px; - + + width: 103px; + height: 83px; + border-style: none; + padding: 6px; + padding-bottom: 20px; + } .bg_example_but_load img { - cursor: pointer; - width: 91px; - height: 57px; - object-fit: cover; - object-position: center center; - border-radius: 10px; - opacity: 0.1; + cursor: pointer; + width: 91px; + height: 57px; + object-fit: cover; + object-position: center center; + border-radius: 10px; + opacity: 0.1; } -#add_bg_button{ +#add_bg_button { margin-bottom: 2px; } #form_create { - display: grid; + display: grid; height: 90vh; - grid-template-rows: [avatar] min-content - [hr] min-content - [descriptionHeader] min-content - [description] auto - [firstmessageHeader] min-content - [firstMessage] auto - [hidden] min-content - [advanced] min-content - [tokenCounter] min-content - [formButtons] min-content; + grid-template-rows: [avatar] min-content [hr] min-content [descriptionHeader] min-content [description] auto [firstmessageHeader] min-content [firstMessage] auto [hidden] min-content [advanced] min-content [tokenCounter] min-content [formButtons] min-content; } -.avatar_div{ - /*margin-top: 16px;*/ +.avatar_div { + /*margin-top: 16px;*/ vertical-align: middle; display: grid; grid-template-columns: min-content min-content; - align-items:center; - grid-gap:10px; + align-items: center; + grid-gap: 10px; } -.avatar_div .avatar{ + +.avatar_div .avatar { margin-left: 4px; margin-right: 10px; display: inline-block; } -#first_message_div{} +#first_message_div {} -#advanced_div{width:100%;} +#advanced_div { + width: 100%; +} -.form_create_bottom_buttons_block{ +.form_create_bottom_buttons_block { display: grid; width: min-content; grid-template-columns: repeat(3, min-content); @@ -928,7 +970,7 @@ width: 103px; margin: 0px auto; } -#rm_info_block{ +#rm_info_block { display: none; width: 100%; height: 80%; @@ -936,42 +978,49 @@ width: 103px; flex-direction: column; } -#rm_info_panel{ + +#rm_info_panel { font-size: 20px; display: block; text-align: center; } -#rm_info_button{ - width: min-content; + +#rm_info_button { + width: min-content; margin: 0 auto; } -#rm_info_avatar{ + +#rm_info_avatar { width: 69px; text-align: center; margin-left: auto; margin-right: auto; } -#delete_button{background-color: var(--crimson70a);} -#result_info{ +#delete_button { + background-color: var(--crimson70a); +} + +#result_info { margin-left: 10px; color: var(--white30a); } .input-file { - display: block; + display: block; } -#form_bg_download{ +#form_bg_download { margin-bottom: 2px; - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); } + /* Focus */ -#colab_popup{ - - width:300px; +#colab_popup { + + width: 300px; height: 150px; position: absolute; z-index: 2060; @@ -983,14 +1032,15 @@ width: 103px; margin-top: 36vh; box-shadow: 0 0 2px var(--black50a); padding: 4px; - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); border-radius: 10px; } -#dialogue_popup{ - - width:300px; + +#dialogue_popup { + + width: 300px; position: absolute; z-index: 2060; margin-left: auto; @@ -1001,65 +1051,73 @@ width: 103px; margin-top: 36vh; box-shadow: 0 0 5px 5px var(--fullred); padding: 4px; - background-color: var(--black30a); + background-color: var(--black30a); border-radius: 10px; } -#dialogue_popup_ok{ + +#dialogue_popup_ok { display: inline-block; margin-right: 20px; background-color: var(--crimson70a); cursor: pointer; } -#dialogue_popup_cancel{ + +#dialogue_popup_cancel { display: inline-block; margin-left: 20px; cursor: pointer; } -#dialogue_del_mes{ + +#dialogue_del_mes { width: 100%; margin-left: auto; margin-right: auto; margin-top: 4px; text-align: center; - padding:0; + padding: 0; height: min-content; } -#dialogue_del_mes_ok{ /*changes background of OK button in the deletion menu*/ + +#dialogue_del_mes_ok { + /*changes background of OK button in the deletion menu*/ display: inline-block; background-color: var(--crimson70a); cursor: pointer; } -#dialogue_del_mes_cancel{ + +#dialogue_del_mes_cancel { display: inline-block; cursor: pointer; } -.menu_button{ + +.menu_button { font-weight: bold; color: var(--white70); background-color: var(--black50a); - border: 1px solid var(--white30a); - border-radius: 10px; - padding: 10px; - width: min-content; - cursor: pointer; - margin:10px 0; - transition: 0.3s; - font-size:15px; + border: 1px solid var(--white30a); + border-radius: 10px; + padding: 10px; + width: min-content; + cursor: pointer; + margin: 10px 0; + transition: 0.3s; + font-size: 15px; } -.menu_button:hover{ - background-color: var(--white30a); +.menu_button:hover { + background-color: var(--white30a); } -#dialogue_del_mes .menu_button{ +#dialogue_del_mes .menu_button { font-size: 1.25rem; margin-left: 25px; margin-right: 25px; } -#shadow_popup{ - backdrop-filter: blur(10px); - -webkit-backdrop-filter: blur(10px); + +#shadow_popup { + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); display: none; opacity: 0.0; position: absolute; @@ -1067,10 +1125,11 @@ width: 103px; height: 100vh; z-index: 2095; } -#colab_shadow_popup{ - - backdrop-filter: blur(10px); - -webkit-backdrop-filter: blur(10px); + +#colab_shadow_popup { + + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); display: none; opacity: 1.0; position: absolute; @@ -1078,46 +1137,55 @@ width: 103px; height: 100vh; z-index: 2298; } -#bgtest{ + +#bgtest { display: none; - width:100vw; + width: 100vw; height: 100vh; position: absolute; z-index: -100; background-color: red; } -#online_status2, #online_status4{ +#online_status2, +#online_status4 { opacity: 0.5; margin-top: 2px; - + margin-bottom: 15px; } -#online_status_indicator2, #online_status_indicator4{ + +#online_status_indicator2, +#online_status_indicator4 { border-radius: 7px; width: 14px; height: 14px; background-color: red; display: inline-block; } -#online_status_text2, #online_status_text4{ + +#online_status_text2, +#online_status_text4 { margin-left: 4px; display: inline-block; } -#online_status3{ + +#online_status3 { opacity: 0.5; margin-top: 2px; - + margin-bottom: 30px; } -#online_status_indicator3{ + +#online_status_indicator3 { border-radius: 7px; width: 14px; height: 14px; background-color: red; display: inline-block; } -#online_status_text3{ + +#online_status_text3 { margin-left: 4px; display: inline-block; } @@ -1140,14 +1208,16 @@ width: 103px; align-items: center; } -#world_import_button, #world_create_button { +#world_import_button, +#world_create_button { cursor: pointer; display: inline-block; padding: 0; margin: 0; } -#world_import_button h4, #world_create_button h4 { +#world_import_button h4, +#world_create_button h4 { margin-top: auto; margin-bottom: auto; margin-left: 1rem; @@ -1156,10 +1226,10 @@ width: 103px; #world_popup { display: none; - background-color: rgba(0,0,0,0.3); - backdrop-filter: blur(50px); - -webkit-backdrop-filter: blur(50px); - max-width:800px; + background-color: rgba(0, 0, 0, 0.3); + backdrop-filter: blur(50px); + -webkit-backdrop-filter: blur(50px); + max-width: 800px; height: calc(100% - 40px); position: absolute; margin-left: auto; @@ -1167,9 +1237,9 @@ width: 103px; left: 0; right: 0; margin-top: 40px; - box-shadow: 0 0 2px rgba(0,0,0,0.5); + box-shadow: 0 0 2px rgba(0, 0, 0, 0.5); padding: 4px; - /*border: 1px solid #333333;*/ + /*border: 1px solid #333333;*/ flex-direction: column; z-index: 2064; } @@ -1186,7 +1256,7 @@ width: 103px; #world_popup_bottom_holder div { cursor: pointer; width: fit-content; - user-select: none; + user-select: none; opacity: 0.8; } @@ -1198,7 +1268,8 @@ width: 103px; margin-left: 1rem; } -#world_info_depth_block input[type="range"], #world_info_budget_block input[type="range"] { +#world_info_depth_block input[type="range"], +#world_info_budget_block input[type="range"] { margin-left: 10px; } @@ -1261,7 +1332,7 @@ width: 103px; font-weight: bolder; width: 100%; height: 100%; - display: flex; + display: flex; justify-content: center; align-items: center; opacity: 0.8; @@ -1278,7 +1349,7 @@ width: 103px; flex-direction: row; } -.world_entry_thin_controls > div { +.world_entry_thin_controls>div { flex: 1; } @@ -1356,11 +1427,15 @@ width: 103px; margin-right: 0.5rem; } -#world_popup h4 a, #world_popup h5 a, #world_popup h3 a { +#world_popup h4 a, +#world_popup h5 a, +#world_popup h3 a { color: #936f4a; } -#world_popup h5 a:hover, #world_popup h4 a:hover, #world_popup h4 a:hover a { +#world_popup h5 a:hover, +#world_popup h4 a:hover, +#world_popup h4 a:hover a { color: #998e6b; } @@ -1372,20 +1447,20 @@ width: 103px; /* --------------------------------------------------------------------------------------*/ /* checkboxes default to being hidden unless called by the delete mesasges option menu button, which uses JS to force them to be display:block*/ -.del_checkbox{ +.del_checkbox { display: none; opacity: 0.7; - margin-top:12px; - margin-right:12px; + margin-top: 12px; + margin-right: 12px; } /*this hides the replacement for input form until Delete Messages mode is called*/ -#dialogue_del_mes{ +#dialogue_del_mes { display: none; } /*this is the default-shown div that is shown when message-deletion mode is NOT on, and hidden when JS calls message deletion mode*/ -.for_checkbox{ +.for_checkbox { display: block; } @@ -1406,62 +1481,65 @@ input[type='checkbox']:not(#nav-toggle):not(#rm_button_panel_pin) { /* the checkbox starts with a size 0 background of a checkmark */ input[type='checkbox']:not(#nav-toggle):not(#rm_button_panel_pin)::after { - content: ''; - color: var(--white100); - position: absolute; - top: 4px; - right: 4px; - bottom: 4px; - left: 4px; - background-color: var(--transparent); - background-size: contain; - background-position: center center; - background-repeat: no-repeat; - border-radius: 2px; - -webkit-transform: scale(0); - transform: scale(0); - -webkit-transition: 0.25s ease-in-out; - transition: 0.25s ease-in-out; - background-image: url("data:image/svg+xml;base64,PCEtLSBHZW5lcmF0ZWQgYnkgSWNvTW9vbi5pbyAtLT4KPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjQ0OCIgaGVpZ2h0PSI0NDgiIHZpZXdCb3g9IjAgMCA0NDggNDQ4Ij4KPHRpdGxlPjwvdGl0bGU+CjxnIGlkPSJpY29tb29uLWlnbm9yZSI+CjwvZz4KPHBhdGggZD0iTTQxNy43NSAxNDEuNWMwIDYuMjUtMi41IDEyLjUtNyAxN2wtMjE1IDIxNWMtNC41IDQuNS0xMC43NSA3LTE3IDdzLTEyLjUtMi41LTE3LTdsLTEyNC41LTEyNC41Yy00LjUtNC41LTctMTAuNzUtNy0xN3MyLjUtMTIuNSA3LTE3bDM0LTM0YzQuNS00LjUgMTAuNzUtNyAxNy03czEyLjUgMi41IDE3IDdsNzMuNSA3My43NSAxNjQtMTY0LjI1YzQuNS00LjUgMTAuNzUtNyAxNy03czEyLjUgMi41IDE3IDdsMzQgMzRjNC41IDQuNSA3IDEwLjc1IDcgMTd6Ij48L3BhdGg+Cjwvc3ZnPgo="); + content: ''; + color: var(--white100); + position: absolute; + top: 4px; + right: 4px; + bottom: 4px; + left: 4px; + background-color: var(--transparent); + background-size: contain; + background-position: center center; + background-repeat: no-repeat; + border-radius: 2px; + -webkit-transform: scale(0); + transform: scale(0); + -webkit-transition: 0.25s ease-in-out; + transition: 0.25s ease-in-out; + background-image: url("data:image/svg+xml;base64,PCEtLSBHZW5lcmF0ZWQgYnkgSWNvTW9vbi5pbyAtLT4KPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjQ0OCIgaGVpZ2h0PSI0NDgiIHZpZXdCb3g9IjAgMCA0NDggNDQ4Ij4KPHRpdGxlPjwvdGl0bGU+CjxnIGlkPSJpY29tb29uLWlnbm9yZSI+CjwvZz4KPHBhdGggZD0iTTQxNy43NSAxNDEuNWMwIDYuMjUtMi41IDEyLjUtNyAxN2wtMjE1IDIxNWMtNC41IDQuNS0xMC43NSA3LTE3IDdzLTEyLjUtMi41LTE3LTdsLTEyNC41LTEyNC41Yy00LjUtNC41LTctMTAuNzUtNy0xN3MyLjUtMTIuNSA3LTE3bDM0LTM0YzQuNS00LjUgMTAuNzUtNyAxNy03czEyLjUgMi41IDE3IDdsNzMuNSA3My43NSAxNjQtMTY0LjI1YzQuNS00LjUgMTAuNzUtNyAxNy03czEyLjUgMi41IDE3IDdsMzQgMzRjNC41IDQuNSA3IDEwLjc1IDcgMTd6Ij48L3BhdGg+Cjwvc3ZnPgo="); } /* when the checkbox is checked, the background image is grown to normal size to fill the background of the 'checkbox'*/ input[type='checkbox']:not(#nav-toggle):not(#rm_button_panel_pin):checked::after { - -webkit-transform: scale(1); - transform: scale(1); + -webkit-transform: scale(1); + transform: scale(1); } + /*---------------------------------------------------------------------------------------------------------*/ -#title_api{ - -} +#title_api {} -.option_select_right_menu{ - width:284px; +.option_select_right_menu { + width: 284px; margin-bottom: 35px; color: var(--white70a); - background-color: var(--black30a); + background-color: var(--black30a); } -#user_avatar_block{ + +#user_avatar_block { display: grid; grid-gap: 10px; - grid-template-columns: repeat( auto-fit, minmax(60px, 1fr) ); + grid-template-columns: repeat(auto-fit, minmax(60px, 1fr)); grid-template-rows: min-content; } -#user_avatar_block .avatar{ + +#user_avatar_block .avatar { cursor: pointer; width: 60px; height: 60px; } -#user_avatar_block .avatar img{ - width: 60px; + +#user_avatar_block .avatar img { + width: 60px; height: 60px; } + #user_avatar_block .avatar_upload { cursor: pointer; width: 60px; height: 60px; - background:rgba(100, 100, 100, 0.5); + background: rgba(100, 100, 100, 0.5); backdrop-filter: blur(10px) brightness(0.3); border-radius: 100%; display: flex; @@ -1469,62 +1547,97 @@ input[type='checkbox']:not(#nav-toggle):not(#rm_button_panel_pin):checked::after align-items: center; font-size: 3rem; } + #form_upload_avatar { display: none !important; } -#temp{ + +#temp { margin-left: 10px; margin-bottom: 20px; } -#temp_counter{ - margin-bottom:0; + +#temp_counter { + margin-bottom: 0; } -#amount_gen{ + +#amount_gen { margin-left: 10px; margin-bottom: 20px; } -#amount_gen_counter{ - margin-bottom:0; + +#amount_gen_counter { + margin-bottom: 0; } -#max_context{ + +#max_context { margin-left: 10px; margin-bottom: 20px; } -#max_context_counter{ - margin-bottom:0; + +#max_context_counter { + margin-bottom: 0; } -#range_block input{ + +#range_block input { margin-left: 10px; margin-bottom: 20px; } -#range_block_novel input{ + +#range_block_novel input { margin-left: 10px; margin-bottom: 20px; } + /* range sliders */ -#range_block, #range_block_novel {margin-top: 10px;} -#range_block input, #range_block_novel input{margin-bottom: 20px;} -#temp, #amount_gen, #max_context {margin-bottom: 20px;} -#temp_counter, #amount_gen_counter, #max_context_counter {margin-bottom:0;} -.range-block-counter {width: min-content; margin:0 auto;} -.range-block-range{margin: 0 auto; width: 100%;} +#range_block, +#range_block_novel { + margin-top: 10px; +} + +#range_block input, +#range_block_novel input { + margin-bottom: 20px; +} + +#temp, +#amount_gen, +#max_context { + margin-bottom: 20px; +} + +#temp_counter, +#amount_gen_counter, +#max_context_counter { + margin-bottom: 0; +} + +.range-block-counter { + width: min-content; + margin: 0 auto; +} + +.range-block-range { + margin: 0 auto; + width: 100%; +} input[type="range"] { - -webkit-appearance: none; - margin: 0 auto; - width: 100%; - height: 7px; - background: var(--white50a); - border-radius: 15px; - background-size: 70% 100%; - background-repeat: no-repeat; + -webkit-appearance: none; + margin: 0 auto; + width: 100%; + height: 7px; + background: var(--white50a); + border-radius: 15px; + background-size: 70% 100%; + background-repeat: no-repeat; } /*Notes '?' links*/ -.note-link-span { - color: var(--sienna); +.note-link-span { + color: var(--sienna); border: 1px solid var(--sienna); border-radius: 10px; line-height: 15px; @@ -1534,19 +1647,20 @@ input[type="range"] { padding-left: 6px; padding-top: 1px; display: inline-block; - opacity: 0.7; - margin: 0 5px; + opacity: 0.7; + margin: 0 5px; } -.note-link-span:hover { - color: var(--white100); - background-color:var(--orangered); - opacity:1;} +.note-link-span:hover { + color: var(--white100); + background-color: var(--orangered); + opacity: 1; +} -#tips_popup{ - - width:500px; +#tips_popup { + + width: 500px; height: 600px; position: absolute; z-index: 2060; @@ -1559,13 +1673,14 @@ input[type="range"] { margin-top: 15vh; box-shadow: 5px 5px var(--black30a); padding: 4px; - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); border-radius: 10px; - padding-top: 30px; + padding-top: 30px; } -#shadow_tips_popup{ + +#shadow_tips_popup { display: none; opacity: 0.0; position: absolute; @@ -1574,77 +1689,91 @@ input[type="range"] { z-index: 2055; background-color: var(--black70a); } -.mes_edit{ - float:right; - color: var(--white30a); - cursor:pointer; + +.mes_edit { + float: right; + color: var(--white30a); + cursor: pointer; margin-right: 4px; - transition: 0.3s ease-in-out; - height:20px; - width:20px; + transition: 0.3s ease-in-out; + height: 20px; + width: 20px; } -.mes_edit:after {content: "\270e";} /*unicode pencil*/ +.mes_edit:after { + content: "\270e"; +} -.mes_edit:hover{color:var(--white100);} +/*unicode pencil*/ + +.mes_edit:hover { + color: var(--white100); +} -.mes_edit_done{ +.mes_edit_done { display: none; - float:right; - right:8px; - cursor:pointer; + float: right; + right: 8px; + cursor: pointer; margin-right: 15px; - opacity:0.5; + opacity: 0.5; } -.mes_edit_done img{ + +.mes_edit_done img { width: 23px; height: 23px; } -.mes_edit_cancel{ + +.mes_edit_cancel { display: none; - float:right; + float: right; margin-right: 4px; - cursor:pointer; - opacity:0.5; + cursor: pointer; + opacity: 0.5; } -.mes_edit_cancel img{ +.mes_edit_cancel img { width: 23px; height: 23px; } -.edit_textarea{ - padding:5px; - margin:0; + +.edit_textarea { + padding: 5px; + margin: 0; outline: none; - background-color: var(--black50a); - font-size: 15px; - line-height:1.25rem; + background-color: var(--black50a); + font-size: 15px; + line-height: 1.25rem; } -#anchor_order{ - width:284px; - +#anchor_order { + width: 284px; + margin-bottom: 15px; color: var(--white70a); - background-color: var(--black50a); + background-color: var(--black50a); } -#anchor_checkbox, #power-user-option-checkboxes{ + +#anchor_checkbox, +#power-user-option-checkboxes { display: flex; flex-direction: column; row-gap: 5px; } -#anchor_checkbox label, #power-user-option-checkboxes label { + +#anchor_checkbox label, +#power-user-option-checkboxes label { display: flex; flex-direction: row; column-gap: 10px; align-items: center; } -#shadow_character_popup{ - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); +#shadow_character_popup { + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); display: none; opacity: 1.0; position: absolute; @@ -1652,13 +1781,14 @@ input[type="range"] { height: 100vh; z-index: 2058; } -#character_popup{ - display: none; + +#character_popup { + display: none; background-color: var(--black30a); backdrop-filter: blur(50px); -webkit-backdrop-filter: blur(30px); grid-template-rows: 50px 100px 100px 100px auto; - grid-gap: 10px; + grid-gap: 10px; max-width: 800px; height: calc(100vh - 50px); position: absolute; @@ -1670,81 +1800,82 @@ input[type="range"] { margin-top: 40px; box-shadow: 0 0 20px var(--black70a); padding-left: 30px; - padding-right: 30px; - padding-top: 20px; + padding-right: 30px; + padding-top: 20px; padding-bottom: 30px; border: 1px solid var(--black30a); border-radius: 0 0 20px 20px; } -#character_popup h3{ - margin-top:0; - margin-bottom:0; - margin-left:0; - display: inline; +#character_popup h3 { + margin-top: 0; + margin-bottom: 0; + margin-left: 0; + display: inline; } -#character_popup h4{ - margin-top:0; - margin-bottom:0; - margin-left:0; +#character_popup h4 { + margin-top: 0; + margin-bottom: 0; + margin-left: 0; } -#character_popup h5{ - margin-top:0; + +#character_popup h5 { + margin-top: 0; margin-bottom: 3px; - margin-left:0; + margin-left: 0; color: var(--grey50); } -#character_popup_text{ - display: grid; +#character_popup_text { + display: grid; grid-template-columns: 50px auto; grid-gap: 20px; - align-items: center; - width: 100%; + align-items: center; + width: 100%; } -#personality_div{ - - + +#personality_div {} + +#personality_textarea { + width: 100%; + } -#personality_textarea{ - width: 100%; - -} -#scenario_div{ - - -} -#mes_example_div{ + +#scenario_div {} + +#mes_example_div { height: 100%; display: grid; grid-template-rows: min-content auto; } -#scenario_pole{ + +#scenario_pole { width: 100%; - margin-left:0; -} -#mes_example_textarea{ - width: 100%; - max-height: 100%; - margin-left:0; + margin-left: 0; } -#character_popup_ok{ +#mes_example_textarea { + width: 100%; + max-height: 100%; + margin-left: 0; +} + +#character_popup_ok { cursor: pointer; display: none; height: 40px; margin-top: 15px; margin-left: 36px; - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); width: 110px; text-align: center; } -#shadow_select_chat_popup{ +#shadow_select_chat_popup { display: none; opacity: 1.0; position: absolute; @@ -1752,10 +1883,10 @@ input[type="range"] { height: 100vh; z-index: 2059; backdrop-filter: blur(10px); - -webkit-backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); } -#select_chat_popup{ +#select_chat_popup { display: block; grid-template-rows: 50px 100px 100px auto 45px; max-width: 800px; @@ -1775,83 +1906,90 @@ input[type="range"] { overflow-y: scroll; } -#export_div{ - cursor:pointer; +#export_div { + cursor: pointer; } -#load_select_chat_div{ + +#load_select_chat_div { position: absolute; bottom: 154px; left: 174px; } -#load_select_chat_div img{ + +#load_select_chat_div img { width: 80px; height: 80px; } -#select_chat_div{ + +#select_chat_div { margin-left: 5px; margin-top: 30px; overflow-x: hidden; overflow-y: scroll; - + height: min-content; - max-height:100%; + max-height: 100%; } -#select_chat_div hr{ - margin:0; + +#select_chat_div hr { + margin: 0; } #select_chat_import { - display:grid; - grid-template-columns: min-content auto; - align-items: center; - grid-gap: 10px; - margin-left: 15px; - margin-top: 15px; + display: grid; + grid-template-columns: min-content auto; + align-items: center; + grid-gap: 10px; + margin-left: 15px; + margin-top: 15px; } -.select_chat_block{ -border-radius: 5px; +.select_chat_block { + border-radius: 5px; margin-right: 10px; margin-bottom: 10px; border: 1px solid var(--white30a); padding: 10px; display: grid; - grid-template-columns: min-content auto; + grid-template-columns: min-content auto; grid-template-rows: auto auto; grid-gap: 10px; } + .select_chat_block:hover { background-color: var(--white30a); } -.select_chat_block[highlight]{ + +.select_chat_block[highlight] { background-color: var(--cobalt30a); } -.select_chat_block .avatar{ +.select_chat_block .avatar { grid-row: span 2; } -.select_chat_block_filename{ - opacity:0.5; +.select_chat_block_filename { + opacity: 0.5; } -.select_chat_block_mes{ + +.select_chat_block_mes { margin-right: 6px; - font-size:0.75rem; + font-size: 0.75rem; } .select_chat_block .avatar { - /*height:30px; + /*height:30px; width:30px;*/ - } +} -#advanced_book_logo{ +#advanced_book_logo { width: 35px; height: 35px; display: inline-block; } -#export_character_div{ +#export_character_div { display: grid; grid-template-columns: 340px auto; } @@ -1866,110 +2004,132 @@ border-radius: 5px; align-items: center; width: 100%; } -#rm_button_group_chats{ + +#rm_button_group_chats { cursor: pointer; display: inline-block; } -#rm_button_group_chats h2{ + +#rm_button_group_chats h2 { margin-top: auto; margin-bottom: auto; font-size: 16px; color: rgb(188, 193, 200, 1); border: 1px solid #333; - background-color: rgba(0,0,0,0.3); - padding:6px; + background-color: rgba(0, 0, 0, 0.3); + padding: 6px; border-radius: 10px; } + #rm_group_chats_block { display: none; height: 100%; flex-direction: column; align-items: flex-start; } + #rm_group_chat_name { width: 90%; } + #rm_group_buttons { display: flex; flex-direction: row; width: 100%; align-items: flex-end; } + #rm_group_buttons .checkbox { display: flex; } + #rm_group_buttons .checkbox h4 { display: inline-block; } -#rm_group_buttons > input { + +#rm_group_buttons>input { font-size: 16px; cursor: pointer; user-select: none; } -#rm_group_buttons > input:disabled { + +#rm_group_buttons>input:disabled { filter: brightness(0.3); cursor: unset; } -#rm_group_members, #rm_group_add_members { + +#rm_group_members, +#rm_group_add_members { margin-top: 0.25rem; margin-bottom: 0.25rem; width: 100%; flex: 1; overflow: auto; } + #rm_group_buttons_expander { flex-grow: 1; } + #rm_group_delete { color: rgb(190, 0, 0); } + #rm_group_members:empty { width: 100%; } + #rm_group_members:empty::before { content: 'Group is empty'; font-size: 1rem; font-weight: bolder; width: 100%; height: 100%; - display: flex; + display: flex; justify-content: center; align-items: center; opacity: 0.8; } + #rm_group_add_members:empty { width: 100%; } + #rm_group_add_members_header { display: flex; flex-direction: row; align-items: center; width: 100%; } + #rm_group_add_members_header input { flex-grow: 1; width: 100%; margin-left: 1rem; } + #rm_group_add_members:empty::before { content: 'No characters available'; font-size: 1rem; font-weight: bolder; width: 100%; height: 100%; - display: flex; + display: flex; justify-content: center; align-items: center; opacity: 0.8; } + .group_member_icon { width: 25px; height: 25px; margin: 0 10px; } + .group_member_icon img { filter: invert(1); } + .group_member { display: flex; flex-direction: row; @@ -1977,21 +2137,26 @@ border-radius: 5px; width: 100%; padding: 5px; border-radius: 10px; - cursor:pointer; + cursor: pointer; } + .group_member .ch_name { flex-grow: 1; margin-left: 10px; } -.group_member:hover{ + +.group_member:hover { background-color: #ffffff11; } + #group_member_template { display: none !important; } + #group_list_template { display: none !important; } + .group_select { display: flex; flex-direction: row; @@ -2000,17 +2165,21 @@ border-radius: 5px; border-radius: 10px; cursor: pointer; } + .group_select:hover { background-color: #ffffff11; } + .group_select .group_icon { width: 20px; height: 20px; margin: 0 10px; } + .group_select .ch_name { flex-grow: 1; } + .group_select .group_icon img { filter: invert(1); } @@ -2024,27 +2193,31 @@ border-radius: 5px; bottom: 10px; margin: 10px; opacity: 0.6; - text-shadow: 2px 2px 2px rgba(0,0,0,0.6); + text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.6); } .typing_indicator:after { display: inline-block; vertical-align: bottom; - animation: ellipsis steps(4,end) 1500ms infinite; - content: ""; /* ascii code for the ellipsis character */ + animation: ellipsis steps(4, end) 1500ms infinite; + content: ""; + /* ascii code for the ellipsis character */ width: 0px; } - + @keyframes ellipsis { 0% { content: "" } + 25% { content: "." } + 50% { content: ".." } + 75% { content: "..." } @@ -2148,7 +2321,7 @@ border-radius: 5px; } span.warning { - color:rgb(190, 0, 0); + color: rgb(190, 0, 0); font-weight: bolder; } @@ -2177,9 +2350,11 @@ span.warning { #talkativeness_hint span:nth-child(1) { text-align: left; } + #talkativeness_hint span:nth-child(2) { text-align: center; } + #talkativeness_hint span:nth-child(3) { text-align: right; } @@ -2188,7 +2363,7 @@ span.warning { p { margin-bottom: 16px; - margin-top:0; + margin-top: 0; } hr { @@ -2200,15 +2375,15 @@ hr { h1 { font-size: 2rem; line-height: 32px; - margin-bottom: 22px; + margin-bottom: 22px; font-weight: 300; } h2 { font-size: 1.5rem; line-height: 1.5rem; - margin-top: 5px; - margin-bottom: 22px; + margin-top: 5px; + margin-bottom: 22px; font-weight: 300; } @@ -2216,7 +2391,7 @@ h2 { margin-top: 0; margin-bottom: 0; font-size: 1.25rem; - } +} a { color: orange; @@ -2228,46 +2403,46 @@ a { /* Right nav panel and nav-toggle */ /* ############################################################# */ -#right-nav-panel{ +#right-nav-panel { width: 450px; height: 100%; position: fixed; top: 0; bottom: 0; margin: 0; - right: -450px; - padding:0; - -webkit-transition: right 0.14s ease-in-out 0.02s; - -moz-transition: right 0.14s ease-in-out 0.02s; - transition: right 0.14s ease-in-out 0.02s; - backdrop-filter: blur(10px); - background-color: var(--black70a); - -webkit-backdrop-filter: blur(10px); + right: -450px; + padding: 0; + -webkit-transition: right 0.14s ease-in-out 0.02s; + -moz-transition: right 0.14s ease-in-out 0.02s; + transition: right 0.14s ease-in-out 0.02s; + backdrop-filter: blur(10px); + background-color: var(--black70a); + -webkit-backdrop-filter: blur(10px); z-index: 2050; - white-space:nowrap; - border-left: 1px solid var(--black30a); + white-space: nowrap; + border-left: 1px solid var(--black30a); } -@media screen and (max-width: 450px) { - #right-nav-panel{ - width: 100%; - box-shadow: none; +@media screen and (max-width: 450px) { + #right-nav-panel { + width: 100%; + box-shadow: none; } } -#nav-toggle { +#nav-toggle { position: absolute; right: 13px; top: 12px; - padding:0; - margin:0; + padding: 0; + margin: 0; cursor: pointer; height: 0; width: 0; z-index: 3001; } - -#nav-toggle:hover::after { + +#nav-toggle:hover::after { color: var(--ivory); } @@ -2288,7 +2463,7 @@ a { background: var(--black30a); color: var(--white50a); -webkit-transition: all 0.275s; - transition: all 0.275s; + transition: all 0.275s; } #nav-toggle:checked::after { @@ -2298,8 +2473,8 @@ a { } /* this is what causes the panel movement */ -#nav-toggle:checked ~ #right-nav-panel{ - right:0; +#nav-toggle:checked~#right-nav-panel { + right: 0; box-shadow: -5px 0 20px 0 var(--black70a); overflow-y: auto; } @@ -2312,7 +2487,7 @@ a { border-radius: 10px; } -.mes img.img_extra ~ * { +.mes img.img_extra~* { display: none; } diff --git a/server.js b/server.js index 18ec95fe8..27a7a13da 100644 --- a/server.js +++ b/server.js @@ -5,12 +5,12 @@ const readline = require('readline'); const open = require('open'); var rimraf = require("rimraf"); -const multer = require("multer"); +const multer = require("multer"); const https = require('https'); //const PNG = require('pngjs').PNG; -const extract = require('png-chunks-extract'); -const encode = require('png-chunks-encode'); -const PNGtext = require('png-chunk-text'); +const extract = require('png-chunks-extract'); +const encode = require('png-chunks-encode'); +const PNGtext = require('png-chunk-text'); const sharp = require('sharp'); sharp.cache(false); @@ -50,37 +50,37 @@ var response_getstatus_novel; var response_getlastversion; var api_key_novel; - //RossAscends: Added function to format dates used in files and chat timestamps to a humanized format. - //Mostly I wanted this to be for file names, but couldn't figure out exactly where the filename save code was as everything seemed to be connected. - //During testing, this performs the same as previous date.now() structure. - //It also does not break old characters/chats, as the code just uses whatever timestamp exists in the chat. - //New chats made with characters will use this new formatting. - //Useable variable is (( humanizedISO8601Datetime )) - - - - function humanizedISO8601DateTime() { - let baseDate = new Date(Date.now()); - let humanYear = baseDate.getFullYear(); - let humanMonth = (baseDate.getMonth()+1); - let humanDate = baseDate.getDate(); - let humanHour = (baseDate.getHours() < 10? '0' : '') + baseDate.getHours(); - let humanMinute = (baseDate.getMinutes() < 10? '0' : '') + baseDate.getMinutes(); - let humanSecond = (baseDate.getSeconds() < 10? '0' : '') + baseDate.getSeconds(); - let humanMillisecond = (baseDate.getMilliseconds() < 10? '0' : '') + baseDate.getMilliseconds(); - let HumanizedDateTime = (humanYear+"-"+humanMonth+"-"+humanDate+" @"+humanHour+"h "+humanMinute+"m "+humanSecond+"s "+humanMillisecond+"ms"); - return HumanizedDateTime; - }; +//RossAscends: Added function to format dates used in files and chat timestamps to a humanized format. +//Mostly I wanted this to be for file names, but couldn't figure out exactly where the filename save code was as everything seemed to be connected. +//During testing, this performs the same as previous date.now() structure. +//It also does not break old characters/chats, as the code just uses whatever timestamp exists in the chat. +//New chats made with characters will use this new formatting. +//Useable variable is (( humanizedISO8601Datetime )) + + + +function humanizedISO8601DateTime() { + let baseDate = new Date(Date.now()); + let humanYear = baseDate.getFullYear(); + let humanMonth = (baseDate.getMonth() + 1); + let humanDate = baseDate.getDate(); + let humanHour = (baseDate.getHours() < 10 ? '0' : '') + baseDate.getHours(); + let humanMinute = (baseDate.getMinutes() < 10 ? '0' : '') + baseDate.getMinutes(); + let humanSecond = (baseDate.getSeconds() < 10 ? '0' : '') + baseDate.getSeconds(); + let humanMillisecond = (baseDate.getMilliseconds() < 10 ? '0' : '') + baseDate.getMilliseconds(); + let HumanizedDateTime = (humanYear + "-" + humanMonth + "-" + humanDate + " @" + humanHour + "h " + humanMinute + "m " + humanSecond + "s " + humanMillisecond + "ms"); + return HumanizedDateTime; +}; var is_colab = false; var charactersPath = 'public/characters/'; var chatsPath = 'public/chats/'; -if (is_colab && process.env.googledrive == 2){ +if (is_colab && process.env.googledrive == 2) { charactersPath = '/content/drive/MyDrive/TavernAI/characters/'; chatsPath = '/content/drive/MyDrive/TavernAI/chats/'; } -const jsonParser = express.json({limit: '100mb'}); -const urlencodedParser = express.urlencoded({extended: true, limit: '100mb'}); +const jsonParser = express.json({ limit: '100mb' }); +const urlencodedParser = express.urlencoded({ extended: true, limit: '100mb' }); const baseRequestArgs = { headers: { "Content-Type": "application/json" } }; const directories = { worlds: 'public/worlds/', @@ -96,21 +96,21 @@ const CSRF_SECRET = crypto.randomBytes(8).toString('hex'); const COOKIES_SECRET = crypto.randomBytes(8).toString('hex'); const { invalidCsrfTokenError, generateToken, doubleCsrfProtection } = doubleCsrf({ - getSecret: () => CSRF_SECRET, - cookieName: "X-CSRF-Token", - cookieOptions: { - httpOnly: true, - sameSite: "strict", - secure: false - }, - size: 64, - getTokenFromRequest: (req) => req.headers["x-csrf-token"] + getSecret: () => CSRF_SECRET, + cookieName: "X-CSRF-Token", + cookieOptions: { + httpOnly: true, + sameSite: "strict", + secure: false + }, + size: 64, + getTokenFromRequest: (req) => req.headers["x-csrf-token"] }); app.get("/csrf-token", (req, res) => { - res.json({ - "token": generateToken(res) - }); + res.json({ + "token": generateToken(res) + }); }); app.use(cookieParser(COOKIES_SECRET)); @@ -119,8 +119,8 @@ app.use(doubleCsrfProtection); // CORS Settings // const cors = require('cors'); const CORS = cors({ - origin: 'null', - methods: ['OPTIONS'] + origin: 'null', + methods: ['OPTIONS'] }); app.use(CORS); @@ -130,76 +130,75 @@ app.use(function (req, res, next) { //Security let ip = ipaddr.parse(clientIp); // Check if the IP address is IPv4-mapped IPv6 address if (ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { - const ipv4 = ip.toIPv4Address().toString(); - clientIp = ipv4; + const ipv4 = ip.toIPv4Address().toString(); + clientIp = ipv4; } else { - clientIp = ip; - clientIp = clientIp.toString(); + clientIp = ip; + clientIp = clientIp.toString(); } - - //clientIp = req.connection.remoteAddress.split(':').pop(); + + //clientIp = req.connection.remoteAddress.split(':').pop(); if (whitelistMode === true && !whitelist.includes(clientIp)) { - console.log('Forbidden: Connection attempt from '+ clientIp+'. If you are attempting to connect, please add your IP address in whitelist or disable whitelist mode in config.conf in root of TavernAI folder.\n'); - return res.status(403).send('Forbidden: Connection attempt from '+ clientIp+'. If you are attempting to connect, please add your IP address in whitelist or disable whitelist mode in config.conf in root of TavernAI folder.'); + console.log('Forbidden: Connection attempt from ' + clientIp + '. If you are attempting to connect, please add your IP address in whitelist or disable whitelist mode in config.conf in root of TavernAI folder.\n'); + return res.status(403).send('Forbidden: Connection attempt from ' + clientIp + '. If you are attempting to connect, please add your IP address in whitelist or disable whitelist mode in config.conf in root of TavernAI folder.'); } next(); }); app.use((req, res, next) => { - if (req.url.startsWith('/characters/') && is_colab && process.env.googledrive == 2) { - - const filePath = path.join(charactersPath, decodeURIComponent(req.url.substr('/characters'.length))); - fs.access(filePath, fs.constants.R_OK, (err) => { - if (!err) { - res.sendFile(filePath); - } else { - res.send('Character not found: '+filePath); - //next(); - } - }); - } else { - next(); - } + if (req.url.startsWith('/characters/') && is_colab && process.env.googledrive == 2) { + + const filePath = path.join(charactersPath, decodeURIComponent(req.url.substr('/characters'.length))); + fs.access(filePath, fs.constants.R_OK, (err) => { + if (!err) { + res.sendFile(filePath); + } else { + res.send('Character not found: ' + filePath); + //next(); + } + }); + } else { + next(); + } }); + app.use(express.static(__dirname + "/public", { refresh: true })); - - - app.use('/backgrounds', (req, res) => { - const filePath = decodeURIComponent(path.join(process.cwd(), 'public/backgrounds', req.url.replace(/%20/g, ' '))); - fs.readFile(filePath, (err, data) => { - if (err) { - res.status(404).send('File not found'); - return; - } - //res.contentType('image/jpeg'); - res.send(data); - }); + const filePath = decodeURIComponent(path.join(process.cwd(), 'public/backgrounds', req.url.replace(/%20/g, ' '))); + fs.readFile(filePath, (err, data) => { + if (err) { + res.status(404).send('File not found'); + return; + } + //res.contentType('image/jpeg'); + res.send(data); + }); }); + app.use('/characters', (req, res) => { - const filePath = decodeURIComponent(path.join(process.cwd(), charactersPath, req.url.replace(/%20/g, ' '))); - fs.readFile(filePath, (err, data) => { - if (err) { - res.status(404).send('File not found'); - return; - } - //res.contentType('image/jpeg'); - res.send(data); - }); + const filePath = decodeURIComponent(path.join(process.cwd(), charactersPath, req.url.replace(/%20/g, ' '))); + fs.readFile(filePath, (err, data) => { + if (err) { + res.status(404).send('File not found'); + return; + } + //res.contentType('image/jpeg'); + res.send(data); + }); }); -app.use(multer({dest:"uploads"}).single("avatar")); -app.get("/", function(request, response){ -    response.sendFile(__dirname + "/public/index.html");  -    //response.send("

Главная страница

"); +app.use(multer({ dest: "uploads" }).single("avatar")); +app.get("/", function (request, response) { + response.sendFile(__dirname + "/public/index.html"); + //response.send("

Главная страница

"); }); -app.get("/notes/*", function(request, response){ -    response.sendFile(__dirname + "/public"+request.url+".html");  -    //response.send("

Главная страница

"); +app.get("/notes/*", function (request, response) { + response.sendFile(__dirname + "/public" + request.url + ".html"); + //response.send("

Главная страница

"); }); -app.post("/getlastversion", jsonParser, function(request, response_getlastversion = response){ - if(!request.body) return response_getlastversion.sendStatus(400); - +app.post("/getlastversion", jsonParser, function (request, response_getlastversion = response) { + if (!request.body) return response_getlastversion.sendStatus(400); + const repo = 'TavernAI/TavernAI'; let req; req = https.request({ @@ -207,63 +206,65 @@ app.post("/getlastversion", jsonParser, function(request, response_getlastversio path: `/${repo}/releases/latest`, method: 'HEAD' }, (res) => { - if(res.statusCode === 302) { + if (res.statusCode === 302) { const glocation = res.headers.location; - const versionStartIndex = glocation.lastIndexOf('@')+1; + const versionStartIndex = glocation.lastIndexOf('@') + 1; const version = glocation.substring(versionStartIndex); //console.log(version); - response_getlastversion.send({version: version}); - }else{ - response_getlastversion.send({version: 'error'}); + response_getlastversion.send({ version: version }); + } else { + response_getlastversion.send({ version: 'error' }); } }); - + req.on('error', (error) => { console.error(error); - response_getlastversion.send({version: 'error'}); + response_getlastversion.send({ version: 'error' }); }); req.end(); - }); + //**************Kobold api -app.post("/generate", jsonParser, function(request, response_generate = response){ - if(!request.body) return response_generate.sendStatus(400); -    //console.log(request.body.prompt); +app.post("/generate", jsonParser, function (request, response_generate = response) { + if (!request.body) return response_generate.sendStatus(400); + //console.log(request.body.prompt); //const dataJson = JSON.parse(request.body); request_promt = request.body.prompt; //console.log(request.body); - var this_settings = { prompt: request_promt, - use_story:false, - use_memory:false, - use_authors_note:false, - use_world_info:false, - max_context_length: request.body.max_context_length - //temperature: request.body.temperature, - //max_length: request.body.max_length - }; - - if(request.body.gui_settings == false){ - var sampler_order = [request.body.s1,request.body.s2,request.body.s3,request.body.s4,request.body.s5,request.body.s6,request.body.s7]; - this_settings = { prompt: request_promt, - use_story:false, - use_memory:false, - use_authors_note:false, - use_world_info:false, - max_context_length: request.body.max_context_length, - max_length: request.body.max_length, - rep_pen: request.body.rep_pen, - rep_pen_range: request.body.rep_pen_range, - rep_pen_slope: request.body.rep_pen_slope, - temperature: request.body.temperature, - tfs: request.body.tfs, - top_a: request.body.top_a, - top_k: request.body.top_k, - top_p: request.body.top_p, - typical: request.body.typical, - sampler_order: sampler_order - }; + var this_settings = { + prompt: request_promt, + use_story: false, + use_memory: false, + use_authors_note: false, + use_world_info: false, + max_context_length: request.body.max_context_length + //temperature: request.body.temperature, + //max_length: request.body.max_length + }; + + if (request.body.gui_settings == false) { + var sampler_order = [request.body.s1, request.body.s2, request.body.s3, request.body.s4, request.body.s5, request.body.s6, request.body.s7]; + this_settings = { + prompt: request_promt, + use_story: false, + use_memory: false, + use_authors_note: false, + use_world_info: false, + max_context_length: request.body.max_context_length, + max_length: request.body.max_length, + rep_pen: request.body.rep_pen, + rep_pen_range: request.body.rep_pen_range, + rep_pen_slope: request.body.rep_pen_slope, + temperature: request.body.temperature, + tfs: request.body.tfs, + top_a: request.body.top_a, + top_k: request.body.top_k, + top_p: request.body.top_p, + typical: request.body.typical, + sampler_order: sampler_order + }; } console.log(this_settings); @@ -271,113 +272,113 @@ app.post("/generate", jsonParser, function(request, response_generate = response data: this_settings, headers: { "Content-Type": "application/json" } }; - client.post(api_server+"/v1/generate",args, function (data, response) { - if(response.statusCode == 200){ + client.post(api_server + "/v1/generate", args, function (data, response) { + if (response.statusCode == 200) { console.log(data); response_generate.send(data); } - if(response.statusCode == 422){ + if (response.statusCode == 422) { console.log('Validation error'); - response_generate.send({error: true}); + response_generate.send({ error: true }); } - if(response.statusCode == 501 || response.statusCode == 503 || response.statusCode == 507){ + if (response.statusCode == 501 || response.statusCode == 503 || response.statusCode == 507) { console.log(data); - response_generate.send({error: true}); + response_generate.send({ error: true }); } }).on('error', function (err) { console.log(err); - //console.log('something went wrong on the request', err.request.options); - response_generate.send({error: true}); + //console.log('something went wrong on the request', err.request.options); + response_generate.send({ error: true }); }); }); //************** Text generation web UI -app.post("/generate_textgenerationwebui", jsonParser, function(request, response_generate = response){ - if(!request.body) return response_generate.sendStatus(400); +app.post("/generate_textgenerationwebui", jsonParser, function (request, response_generate = response) { + if (!request.body) return response_generate.sendStatus(400); console.log(request.body); var args = { data: request.body, headers: { "Content-Type": "application/json" } }; - client.post(api_server+"/run/textgen",args, function (data, response) { + client.post(api_server + "/run/textgen", args, function (data, response) { console.log("####", data); - if(response.statusCode == 200){ + if (response.statusCode == 200) { console.log(data); response_generate.send(data); } - if(response.statusCode == 422){ + if (response.statusCode == 422) { console.log('Validation error'); - response_generate.send({error: true}); + response_generate.send({ error: true }); } - if(response.statusCode == 501 || response.statusCode == 503 || response.statusCode == 507){ + if (response.statusCode == 501 || response.statusCode == 503 || response.statusCode == 507) { console.log(data); - response_generate.send({error: true}); + response_generate.send({ error: true }); } }).on('error', function (err) { console.log(err); - //console.log('something went wrong on the request', err.request.options); - response_generate.send({error: true}); + //console.log('something went wrong on the request', err.request.options); + response_generate.send({ error: true }); }); }); -app.post("/savechat", jsonParser, function(request, response){ -//console.log(humanizedISO8601DateTime()+':/savechat/ entered'); +app.post("/savechat", jsonParser, function (request, response) { + //console.log(humanizedISO8601DateTime()+':/savechat/ entered'); //console.log(request.data); //console.log(request.body.bg); - //const data = request.body; + //const data = request.body; //console.log(request); //console.log(request.body.chat); //var bg = "body {background-image: linear-gradient(rgba(19,21,44,0.75), rgba(19,21,44,0.75)), url(../backgrounds/"+request.body.bg+");}"; - var dir_name = String(request.body.avatar_url).replace('.png',''); -//console.log(humanizedISO8601DateTime()+':/savechat sees '+dir_name+' as the character name (derived from avatar PNG filename)'); + var dir_name = String(request.body.avatar_url).replace('.png', ''); + //console.log(humanizedISO8601DateTime()+':/savechat sees '+dir_name+' as the character name (derived from avatar PNG filename)'); let chat_data = request.body.chat; let jsonlData = chat_data.map(JSON.stringify).join('\n'); -//console.log(humanizedISO8601DateTime()+':/savechat saving a chat named '+request.body.file_name+'.jsonl'); - fs.writeFile(chatsPath+dir_name+"/"+request.body.file_name+'.jsonl', jsonlData, 'utf8', function(err) { - if(err) { + //console.log(humanizedISO8601DateTime()+':/savechat saving a chat named '+request.body.file_name+'.jsonl'); + fs.writeFile(chatsPath + dir_name + "/" + request.body.file_name + '.jsonl', jsonlData, 'utf8', function (err) { + if (err) { response.send(err); return console.log(err); //response.send(err); - }else{ + } else { //response.redirect("/"); - response.send({result: "ok"}); + response.send({ result: "ok" }); } }); - + }); -app.post("/getchat", jsonParser, function(request, response){ +app.post("/getchat", jsonParser, function (request, response) { //console.log(request.data); //console.log(request.body.bg); - //const data = request.body; + //const data = request.body; //console.log(request); //console.log(request.body.chat); //var bg = "body {background-image: linear-gradient(rgba(19,21,44,0.75), rgba(19,21,44,0.75)), url(../backgrounds/"+request.body.bg+");}"; -//console.log(humanizedISO8601DateTime()+':/getchat entered'); - var dir_name = String(request.body.avatar_url).replace('.png',''); + //console.log(humanizedISO8601DateTime()+':/getchat entered'); + var dir_name = String(request.body.avatar_url).replace('.png', ''); - fs.stat(chatsPath+dir_name, function(err, stat) { - - if(stat === undefined){ //if no chat dir for the character is found, make one with the character name + fs.stat(chatsPath + dir_name, function (err, stat) { - fs.mkdirSync(chatsPath+dir_name); + if (stat === undefined) { //if no chat dir for the character is found, make one with the character name + + fs.mkdirSync(chatsPath + dir_name); response.send({}); return; - }else{ - - if(err === null){ //if there is a dir, then read the requested file from the JSON call - - fs.stat(chatsPath+dir_name+"/"+request.body.file_name+".jsonl", function(err, stat) { - + } else { + + if (err === null) { //if there is a dir, then read the requested file from the JSON call + + fs.stat(chatsPath + dir_name + "/" + request.body.file_name + ".jsonl", function (err, stat) { + if (err === null) { //if no error (the file exists), read the file -//console.log(humanizedISO8601DateTime()+':/getchat tries to access: '+chatsPath+dir_name+'/'+request.body.file_name+'.jsonl'); - if(stat !== undefined){ - fs.readFile(chatsPath+dir_name+"/"+request.body.file_name+".jsonl", 'utf8', (err, data) => { + //console.log(humanizedISO8601DateTime()+':/getchat tries to access: '+chatsPath+dir_name+'/'+request.body.file_name+'.jsonl'); + if (stat !== undefined) { + fs.readFile(chatsPath + dir_name + "/" + request.body.file_name + ".jsonl", 'utf8', (err, data) => { if (err) { - console.error(err); - response.send(err); - return; + console.error(err); + response.send(err); + return; } //console.log(data); const lines = data.split('\n'); @@ -385,17 +386,17 @@ app.post("/getchat", jsonParser, function(request, response){ // Iterate through the array of strings and parse each line as JSON const jsonData = lines.map(JSON.parse); response.send(jsonData); - //console.log('read the requested file') + //console.log('read the requested file') }); } - }else{ + } else { response.send({}); //return console.log(err); return; } }); - }else{ + } else { console.error(err); response.send({}); return; @@ -403,46 +404,46 @@ app.post("/getchat", jsonParser, function(request, response){ } }); - + }); -app.post("/getstatus", jsonParser, function(request, response_getstatus = response){ - if(!request.body) return response_getstatus.sendStatus(400); +app.post("/getstatus", jsonParser, function (request, response_getstatus = response) { + if (!request.body) return response_getstatus.sendStatus(400); api_server = request.body.api_server; main_api = request.body.main_api; - if(api_server.indexOf('localhost') != -1){ - api_server = api_server.replace('localhost','127.0.0.1'); + if (api_server.indexOf('localhost') != -1) { + api_server = api_server.replace('localhost', '127.0.0.1'); } var args = { headers: { "Content-Type": "application/json" } }; - var url = api_server+"/v1/model"; + var url = api_server + "/v1/model"; if (main_api == "textgenerationwebui") { url = api_server; args = {} } - client.get(url,args, function (data, response) { - if(response.statusCode == 200){ + client.get(url, args, function (data, response) { + if (response.statusCode == 200) { if (main_api == "textgenerationwebui") { // console.log(body); try { var body = data.toString(); - var response = body.match(/gradio_config[ =]*(\{.*\});/)[1]; + var response = body.match(/gradio_config[ =]*(\{.*\});/)[1]; if (!response) - throw "no_connection"; - data = {result: JSON.parse(response).components.filter( (x) => x.props.label == "Model" )[0].props.value}; + throw "no_connection"; + data = { result: JSON.parse(response).components.filter((x) => x.props.label == "Model")[0].props.value }; if (!data) - throw "no_connection"; + throw "no_connection"; } catch { - data = {result: "no_connection"}; + data = { result: "no_connection" }; } } else { - if(data.result != "ReadOnly"){ + if (data.result != "ReadOnly") { //response_getstatus.send(data.result); - }else{ + } else { data.result = "no_connection"; } } - }else{ + } else { data.result = "no_connection"; } response_getstatus.send(data); @@ -453,11 +454,11 @@ app.post("/getstatus", jsonParser, function(request, response_getstatus = respon }).on('error', function (err) { //console.log(url); //console.log('something went wrong on the request', err.request.options); - response_getstatus.send({result: "no_connection"}); + response_getstatus.send({ result: "no_connection" }); }); }); -const formatApiUrl = (url) => (url.indexOf('localhost') !== -1) +const formatApiUrl = (url) => (url.indexOf('localhost') !== -1) ? url.replace('localhost', '127.0.0.1') : url; @@ -480,7 +481,7 @@ app.post('/getsoftprompts', jsonParser, async function (request, response) { return response.send({ soft_prompts }); }); -app.post("/setsoftprompt", jsonParser, async function(request, response) { +app.post("/setsoftprompt", jsonParser, async function (request, response) { if (!request.body || !request.body.api_server) { return response.sendStatus(400); } @@ -500,81 +501,81 @@ app.post("/setsoftprompt", jsonParser, async function(request, response) { return response.sendStatus(200); }); -function checkServer(){ +function checkServer() { //console.log('Check run###################################################'); api_server = 'http://127.0.0.1:5000'; var args = { headers: { "Content-Type": "application/json" } }; - client.get(api_server+"/v1/model",args, function (data, response) { + client.get(api_server + "/v1/model", args, function (data, response) { console.log(data.result); //console.log('###################################################'); console.log(data); }).on('error', function (err) { console.log(err); //console.log(''); - //console.log('something went wrong on the request', err.request.options); + //console.log('something went wrong on the request', err.request.options); //console.log('errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr'); }); } //***************** Main functions -function charaFormatData(data){ - var char = {"name": data.ch_name, "description": data.description, "personality": data.personality, "first_mes": data.first_mes, "avatar": 'none', "chat": data.ch_name+' - '+humanizedISO8601DateTime(), "mes_example": data.mes_example, "scenario": data.scenario, "create_date": humanizedISO8601DateTime(), "talkativeness": data.talkativeness}; +function charaFormatData(data) { + var char = { "name": data.ch_name, "description": data.description, "personality": data.personality, "first_mes": data.first_mes, "avatar": 'none', "chat": data.ch_name + ' - ' + humanizedISO8601DateTime(), "mes_example": data.mes_example, "scenario": data.scenario, "create_date": humanizedISO8601DateTime(), "talkativeness": data.talkativeness }; return char; } -app.post("/createcharacter", urlencodedParser, function(request, response){ - - - - //var sameNameChar = fs.existsSync(charactersPath+request.body.ch_name+'.png'); - //if (sameNameChar == true) return response.sendStatus(500); - if(!request.body) return response.sendStatus(400); - console.log('/createcharacter -- looking for -- '+(charactersPath+request.body.ch_name+'.png')); - console.log('Does this file already exists? '+fs.existsSync(charactersPath+request.body.ch_name+'.png')); - if (!fs.existsSync(charactersPath+request.body.ch_name+'.png')){ - if(!fs.existsSync(chatsPath+request.body.ch_name) )fs.mkdirSync(chatsPath+request.body.ch_name); +app.post("/createcharacter", urlencodedParser, function (request, response) { + + + + //var sameNameChar = fs.existsSync(charactersPath+request.body.ch_name+'.png'); + //if (sameNameChar == true) return response.sendStatus(500); + if (!request.body) return response.sendStatus(400); + console.log('/createcharacter -- looking for -- ' + (charactersPath + request.body.ch_name + '.png')); + console.log('Does this file already exists? ' + fs.existsSync(charactersPath + request.body.ch_name + '.png')); + if (!fs.existsSync(charactersPath + request.body.ch_name + '.png')) { + if (!fs.existsSync(chatsPath + request.body.ch_name)) fs.mkdirSync(chatsPath + request.body.ch_name); let filedata = request.file; -     //console.log(filedata.mimetype); + //console.log(filedata.mimetype); var fileType = ".png"; var img_file = "ai"; var img_path = "public/img/"; var char = charaFormatData(request.body);//{"name": request.body.ch_name, "description": request.body.description, "personality": request.body.personality, "first_mes": request.body.first_mes, "avatar": 'none', "chat": Date.now(), "last_mes": '', "mes_example": ''}; char = JSON.stringify(char); -     if(!filedata){ + if (!filedata) { charaWrite('./public/img/fluffy.png', char, request.body.ch_name, response); - }else{ - + } else { + img_path = "./uploads/"; img_file = filedata.filename if (filedata.mimetype == "image/jpeg") fileType = ".jpeg"; if (filedata.mimetype == "image/png") fileType = ".png"; if (filedata.mimetype == "image/gif") fileType = ".gif"; if (filedata.mimetype == "image/bmp") fileType = ".bmp"; - charaWrite(img_path+img_file, char, request.body.ch_name, response); + charaWrite(img_path + img_file, char, request.body.ch_name, response); } //console.log("The file was saved."); - }else{ - console.error("Error: Cannot save file. A character with that name already exists."); + } else { + console.error("Error: Cannot save file. A character with that name already exists."); response.send("Error: A character with that name already exists."); - //response.send({error: true}); + //response.send({error: true}); } -    //console.log(request.body); -    //response.send(request.body.ch_name); + //console.log(request.body); + //response.send(request.body.ch_name); //response.redirect("https://metanit.com") }); -app.post("/editcharacter", urlencodedParser, async function(request, response){ - if(!request.body) return response.sendStatus(400); +app.post("/editcharacter", urlencodedParser, async function (request, response) { + if (!request.body) return response.sendStatus(400); let filedata = request.file; -    //console.log(filedata.mimetype); + //console.log(filedata.mimetype); var fileType = ".png"; var img_file = "ai"; var img_path = charactersPath; - + var char = charaFormatData(request.body);//{"name": request.body.ch_name, "description": request.body.description, "personality": request.body.personality, "first_mes": request.body.first_mes, "avatar": request.body.avatar_url, "chat": request.body.chat, "last_mes": request.body.last_mes, "mes_example": ''}; char.chat = request.body.chat; char.create_date = request.body.create_date; @@ -599,20 +600,20 @@ app.post("/editcharacter", urlencodedParser, async function(request, response){ return response.send(400); } }); -app.post("/deletecharacter", urlencodedParser, function(request, response){ - if(!request.body) return response.sendStatus(400); - rimraf(charactersPath+request.body.avatar_url, (err) => { - if(err) { +app.post("/deletecharacter", urlencodedParser, function (request, response) { + if (!request.body) return response.sendStatus(400); + rimraf(charactersPath + request.body.avatar_url, (err) => { + if (err) { response.send(err); return console.log(err); - }else{ + } else { //response.redirect("/"); let dir_name = request.body.avatar_url; - rimraf(chatsPath+dir_name.replace('.png',''), (err) => { - if(err) { + rimraf(chatsPath + dir_name.replace('.png', ''), (err) => { + if (err) { response.send(err); return console.log(err); - }else{ + } else { //response.redirect("/"); response.send('ok'); @@ -622,7 +623,7 @@ app.post("/deletecharacter", urlencodedParser, function(request, response){ }); }); -async function charaWrite(img_url, data, target_img, response = undefined, mes = 'ok'){ +async function charaWrite(img_url, data, target_img, response = undefined, mes = 'ok') { try { // Load the image in any format sharp.cache(false); @@ -634,8 +635,8 @@ async function charaWrite(img_url, data, target_img, response = undefined, mes = //const resizedImage = pngImage.resize(100, 100); // Get the chunks - var chunks = extract(image); -  var tEXtChunks = chunks.filter(chunk => chunk.create_date === 'tEXt'); + var chunks = extract(image); + var tEXtChunks = chunks.filter(chunk => chunk.create_date === 'tEXt'); // Remove all existing tEXt chunks for (var tEXtChunk of tEXtChunks) { @@ -646,30 +647,30 @@ async function charaWrite(img_url, data, target_img, response = undefined, mes = chunks.splice(-1, 0, PNGtext.encode('chara', base64EncodedData)); //chunks.splice(-1, 0, text.encode('lorem', 'ipsum')); - fs.writeFileSync(charactersPath+target_img+'.png', new Buffer.from(encode(chunks))); - if(response !== undefined) response.send(mes); - + fs.writeFileSync(charactersPath + target_img + '.png', new Buffer.from(encode(chunks))); + if (response !== undefined) response.send(mes); + } catch (err) { console.log(err); - if(response !== undefined) response.send(err); + if (response !== undefined) response.send(err); } } - - -function charaRead(img_url){ + + +function charaRead(img_url) { sharp.cache(false); - const buffer = fs.readFileSync(img_url); - const chunks = extract(buffer); -   - const textChunks = chunks.filter(function (chunk) { -   return chunk.name === 'tEXt'; - }).map(function (chunk) { + const buffer = fs.readFileSync(img_url); + const chunks = extract(buffer); + + const textChunks = chunks.filter(function (chunk) { + return chunk.name === 'tEXt'; + }).map(function (chunk) { //console.log(text.decode(chunk.data)); -   return PNGtext.decode(chunk.data); + return PNGtext.decode(chunk.data); }); var base64DecodedData = Buffer.from(textChunks[0].text, 'base64').toString('utf8'); return base64DecodedData;//textChunks[0].text; @@ -677,11 +678,11 @@ function charaRead(img_url){ //console.log(textChunks[0].text);    // 'world' } -app.post("/getcharacters", jsonParser, function(request, response){ +app.post("/getcharacters", jsonParser, function (request, response) { fs.readdir(charactersPath, (err, files) => { if (err) { - console.error(err); - return; + console.error(err); + return; } const pngFiles = files.filter(file => file.endsWith('.png')); @@ -691,7 +692,7 @@ app.post("/getcharacters", jsonParser, function(request, response){ var i = 0; pngFiles.forEach(item => { //console.log(item); - var img_data = charaRead(charactersPath+item); + var img_data = charaRead(charactersPath + item); try { let jsonObject = JSON.parse(img_data); jsonObject.avatar = item; @@ -715,66 +716,66 @@ app.post("/getcharacters", jsonParser, function(request, response){ //characters = {}; //character_i = 0; //getCharacterFile(directories, response,0); - + }); -app.post("/getbackgrounds", jsonParser, function(request, response){ +app.post("/getbackgrounds", jsonParser, function (request, response) { var images = getImages("public/backgrounds"); - if(is_colab === true){ + if (is_colab === true) { images = ['tavern.png']; } response.send(JSON.stringify(images)); - + }); -app.post("/iscolab", jsonParser, function(request, response){ +app.post("/iscolab", jsonParser, function (request, response) { let send_data = false; - if(process.env.colaburl !== undefined){ + if (process.env.colaburl !== undefined) { send_data = String(process.env.colaburl).trim(); } - response.send({colaburl:send_data}); - + response.send({ colaburl: send_data }); + }); -app.post("/getuseravatars", jsonParser, function(request, response){ +app.post("/getuseravatars", jsonParser, function (request, response) { var images = getImages("public/User Avatars"); response.send(JSON.stringify(images)); - + }); -app.post("/setbackground", jsonParser, function(request, response){ +app.post("/setbackground", jsonParser, function (request, response) { //console.log(request.data); //console.log(request.body.bg); - //const data = request.body; + //const data = request.body; //console.log(request); //console.log(1); - var bg = "#bg1 {background-image: url(../backgrounds/"+request.body.bg+");}"; - fs.writeFile('public/css/bg_load.css', bg, 'utf8', function(err) { - if(err) { + var bg = "#bg1 {background-image: url(../backgrounds/" + request.body.bg + ");}"; + fs.writeFile('public/css/bg_load.css', bg, 'utf8', function (err) { + if (err) { response.send(err); return console.log(err); - }else{ + } else { //response.redirect("/"); - response.send({result:'ok'}); + response.send({ result: 'ok' }); } }); - + }); -app.post("/delbackground", jsonParser, function(request, response){ - if(!request.body) return response.sendStatus(400); - rimraf('public/backgrounds/'+request.body.bg, (err) => { - if(err) { +app.post("/delbackground", jsonParser, function (request, response) { + if (!request.body) return response.sendStatus(400); + rimraf('public/backgrounds/' + request.body.bg, (err) => { + if (err) { response.send(err); return console.log(err); - }else{ + } else { //response.redirect("/"); response.send('ok'); } }); - + }); -app.post("/downloadbackground", urlencodedParser, function(request, response){ +app.post("/downloadbackground", urlencodedParser, function (request, response) { response_dw_bg = response; - if(!request.body) return response.sendStatus(400); + if (!request.body) return response.sendStatus(400); let filedata = request.file; -    //console.log(filedata.mimetype); + //console.log(filedata.mimetype); var fileType = ".png"; var img_file = "ai"; var img_path = "public/img/"; @@ -785,13 +786,13 @@ app.post("/downloadbackground", urlencodedParser, function(request, response){ if (filedata.mimetype == "image/png") fileType = ".png"; if (filedata.mimetype == "image/gif") fileType = ".gif"; if (filedata.mimetype == "image/bmp") fileType = ".bmp"; - fs.copyFile(img_path+img_file, 'public/backgrounds/'+img_file+fileType, (err) => { - if(err) { - + fs.copyFile(img_path + img_file, 'public/backgrounds/' + img_file + fileType, (err) => { + if (err) { + return console.log(err); - }else{ + } else { //console.log(img_file+fileType); - response_dw_bg.send(img_file+fileType); + response_dw_bg.send(img_file + fileType); } //console.log('The image was copied from temp directory.'); }); @@ -799,39 +800,39 @@ app.post("/downloadbackground", urlencodedParser, function(request, response){ }); -app.post("/savesettings", jsonParser, function(request, response){ +app.post("/savesettings", jsonParser, function (request, response) { - fs.writeFile('public/settings.json', JSON.stringify(request.body), 'utf8', function(err) { - if(err) { + fs.writeFile('public/settings.json', JSON.stringify(request.body), 'utf8', function (err) { + if (err) { response.send(err); return console.log(err); //response.send(err); - }else{ + } else { //response.redirect("/"); - response.send({result: "ok"}); + response.send({ result: "ok" }); } }); - + }); app.post('/getsettings', jsonParser, (request, response) => { //Wintermute's code const koboldai_settings = []; const koboldai_setting_names = []; const novelai_settings = []; const novelai_setting_names = []; - const settings = fs.readFileSync('public/settings.json', 'utf8', (err, data) => { - if (err) return response.sendStatus(500); + const settings = fs.readFileSync('public/settings.json', 'utf8', (err, data) => { + if (err) return response.sendStatus(500); return data; }); - //Kobold + //Kobold const files = fs - .readdirSync('public/KoboldAI Settings') - .sort( - (a, b) => - new Date(fs.statSync(`public/KoboldAI Settings/${b}`).mtime) - - new Date(fs.statSync(`public/KoboldAI Settings/${a}`).mtime) - ); + .readdirSync('public/KoboldAI Settings') + .sort( + (a, b) => + new Date(fs.statSync(`public/KoboldAI Settings/${b}`).mtime) - + new Date(fs.statSync(`public/KoboldAI Settings/${a}`).mtime) + ); const worldFiles = fs .readdirSync(directories.worlds) @@ -841,8 +842,8 @@ app.post('/getsettings', jsonParser, (request, response) => { //Wintermute's cod files.forEach(item => { const file = fs.readFileSync( - `public/KoboldAI Settings/${item}`, - 'utf8', + `public/KoboldAI Settings/${item}`, + 'utf8', (err, data) => { if (err) return response.sendStatus(500) @@ -852,31 +853,31 @@ app.post('/getsettings', jsonParser, (request, response) => { //Wintermute's cod koboldai_settings.push(file); koboldai_setting_names.push(item.replace(/\.[^/.]+$/, '')); }); - - //Novel - const files2 = fs - .readdirSync('public/NovelAI Settings') - .sort( - (a, b) => - new Date(fs.statSync(`public/NovelAI Settings/${b}`).mtime) - - new Date(fs.statSync(`public/NovelAI Settings/${a}`).mtime) - ); - - files2.forEach(item => { - const file2 = fs.readFileSync( - `public/NovelAI Settings/${item}`, - 'utf8', - (err, data) => { - if (err) return response.sendStatus(500); - return data; - } - ); + //Novel + const files2 = fs + .readdirSync('public/NovelAI Settings') + .sort( + (a, b) => + new Date(fs.statSync(`public/NovelAI Settings/${b}`).mtime) - + new Date(fs.statSync(`public/NovelAI Settings/${a}`).mtime) + ); + + files2.forEach(item => { + const file2 = fs.readFileSync( + `public/NovelAI Settings/${item}`, + 'utf8', + (err, data) => { + if (err) return response.sendStatus(500); + + return data; + } + ); novelai_settings.push(file2); novelai_setting_names.push(item.replace(/\.[^/.]+$/, '')); }); - + response.send({ settings, koboldai_settings, @@ -933,15 +934,15 @@ function readWorldInfoFile(worldInfoName) { return worldInfo; } -function getCharacterFile(directories,response,i){ //old need del - if(directories.length > i){ - - fs.stat(charactersPath+directories[i]+'/'+directories[i]+".json", function(err, stat) { +function getCharacterFile(directories, response, i) { //old need del + if (directories.length > i) { + + fs.stat(charactersPath + directories[i] + '/' + directories[i] + ".json", function (err, stat) { if (err == null) { - fs.readFile(charactersPath+directories[i]+'/'+directories[i]+".json", 'utf8', (err, data) => { + fs.readFile(charactersPath + directories[i] + '/' + directories[i] + ".json", 'utf8', (err, data) => { if (err) { - console.error(err); - return; + console.error(err); + return; } //console.log(data); @@ -949,143 +950,143 @@ function getCharacterFile(directories,response,i){ //old need del characters[character_i] = data; i++; character_i++; - getCharacterFile(directories,response,i); + getCharacterFile(directories, response, i); }); - }else{ + } else { i++; - getCharacterFile(directories,response,i); + getCharacterFile(directories, response, i); } }); - - }else{ + + } else { response.send(JSON.stringify(characters)); } } function getImages(path) { return fs.readdirSync(path).sort(function (a, b) { -return new Date(fs.statSync(path + '/' + a).mtime) - new Date(fs.statSync(path + '/' + b).mtime); -}).reverse(); + return new Date(fs.statSync(path + '/' + a).mtime) - new Date(fs.statSync(path + '/' + b).mtime); + }).reverse(); } function getKoboldSettingFiles(path) { return fs.readdirSync(path).sort(function (a, b) { -return new Date(fs.statSync(path + '/' + a).mtime) - new Date(fs.statSync(path + '/' + b).mtime); -}).reverse(); + return new Date(fs.statSync(path + '/' + a).mtime) - new Date(fs.statSync(path + '/' + b).mtime); + }).reverse(); } function getDirectories(path) { - return fs.readdirSync(path).sort(function (a, b) { -return new Date(fs.statSync(path + '/' + a).mtime) - new Date(fs.statSync(path + '/' + b).mtime); -}).reverse(); + return fs.readdirSync(path).sort(function (a, b) { + return new Date(fs.statSync(path + '/' + a).mtime) - new Date(fs.statSync(path + '/' + b).mtime); + }).reverse(); } //***********Novel.ai API -app.post("/getstatus_novelai", jsonParser, function(request, response_getstatus_novel =response){ - - if(!request.body) return response_getstatus_novel.sendStatus(400); -    api_key_novel = request.body.key; +app.post("/getstatus_novelai", jsonParser, function (request, response_getstatus_novel = response) { + + if (!request.body) return response_getstatus_novel.sendStatus(400); + api_key_novel = request.body.key; var data = {}; var args = { data: data, - - headers: { "Content-Type": "application/json", "Authorization": "Bearer "+api_key_novel} + + headers: { "Content-Type": "application/json", "Authorization": "Bearer " + api_key_novel } }; - client.get(api_novelai+"/user/subscription",args, function (data, response) { - if(response.statusCode == 200){ + client.get(api_novelai + "/user/subscription", args, function (data, response) { + if (response.statusCode == 200) { //console.log(data); response_getstatus_novel.send(data);//data); } - if(response.statusCode == 401){ + if (response.statusCode == 401) { console.log('Access Token is incorrect.'); - response_getstatus_novel.send({error: true}); + response_getstatus_novel.send({ error: true }); } - if(response.statusCode == 500 || response.statusCode == 501 || response.statusCode == 501 || response.statusCode == 503 || response.statusCode == 507){ + if (response.statusCode == 500 || response.statusCode == 501 || response.statusCode == 501 || response.statusCode == 503 || response.statusCode == 507) { console.log(data); - response_getstatus_novel.send({error: true}); + response_getstatus_novel.send({ error: true }); } }).on('error', function (err) { //console.log(''); - //console.log('something went wrong on the request', err.request.options); - response_getstatus_novel.send({error: true}); + //console.log('something went wrong on the request', err.request.options); + response_getstatus_novel.send({ error: true }); }); }); -app.post("/generate_novelai", jsonParser, function(request, response_generate_novel = response){ - if(!request.body) return response_generate_novel.sendStatus(400); +app.post("/generate_novelai", jsonParser, function (request, response_generate_novel = response) { + if (!request.body) return response_generate_novel.sendStatus(400); console.log(request.body); var data = { - "input": request.body.input, - "model": request.body.model, - "parameters": { - "use_string": request.body.use_string, - "temperature": request.body.temperature, - "max_length": request.body.max_length, - "min_length": request.body.min_length, - "tail_free_sampling": request.body.tail_free_sampling, - "repetition_penalty": request.body.repetition_penalty, - "repetition_penalty_range": request.body.repetition_penalty_range, - "repetition_penalty_frequency": request.body.repetition_penalty_frequency, - "repetition_penalty_presence": request.body.repetition_penalty_presence, - //"stop_sequences": {{187}}, - //bad_words_ids = {{50256}, {0}, {1}}; - //generate_until_sentence = true; - "use_cache": request.body.use_cache, - //use_string = true; - "return_full_text": request.body.return_full_text, - "prefix": request.body.prefix, - "order": request.body.order - } + "input": request.body.input, + "model": request.body.model, + "parameters": { + "use_string": request.body.use_string, + "temperature": request.body.temperature, + "max_length": request.body.max_length, + "min_length": request.body.min_length, + "tail_free_sampling": request.body.tail_free_sampling, + "repetition_penalty": request.body.repetition_penalty, + "repetition_penalty_range": request.body.repetition_penalty_range, + "repetition_penalty_frequency": request.body.repetition_penalty_frequency, + "repetition_penalty_presence": request.body.repetition_penalty_presence, + //"stop_sequences": {{187}}, + //bad_words_ids = {{50256}, {0}, {1}}; + //generate_until_sentence = true; + "use_cache": request.body.use_cache, + //use_string = true; + "return_full_text": request.body.return_full_text, + "prefix": request.body.prefix, + "order": request.body.order + } }; - + var args = { data: data, - - headers: { "Content-Type": "application/json", "Authorization": "Bearer "+api_key_novel} + + headers: { "Content-Type": "application/json", "Authorization": "Bearer " + api_key_novel } }; - client.post(api_novelai+"/ai/generate",args, function (data, response) { - if(response.statusCode == 201){ + client.post(api_novelai + "/ai/generate", args, function (data, response) { + if (response.statusCode == 201) { console.log(data); response_generate_novel.send(data); } - if(response.statusCode == 400){ + if (response.statusCode == 400) { console.log('Validation error'); - response_generate_novel.send({error: true}); + response_generate_novel.send({ error: true }); } - if(response.statusCode == 401){ + if (response.statusCode == 401) { console.log('Access Token is incorrect'); - response_generate_novel.send({error: true}); + response_generate_novel.send({ error: true }); } - if(response.statusCode == 402){ + if (response.statusCode == 402) { console.log('An active subscription is required to access this endpoint'); - response_generate_novel.send({error: true}); + response_generate_novel.send({ error: true }); } - if(response.statusCode == 500 || response.statusCode == 409){ + if (response.statusCode == 500 || response.statusCode == 409) { console.log(data); - response_generate_novel.send({error: true}); + response_generate_novel.send({ error: true }); } }).on('error', function (err) { //console.log(''); - //console.log('something went wrong on the request', err.request.options); - response_getstatus.send({error: true}); + //console.log('something went wrong on the request', err.request.options); + response_getstatus.send({ error: true }); }); }); -app.post("/getallchatsofcharacter", jsonParser, function(request, response){ - if(!request.body) return response.sendStatus(400); +app.post("/getallchatsofcharacter", jsonParser, function (request, response) { + if (!request.body) return response.sendStatus(400); - var char_dir = (request.body.avatar_url).replace('.png','') - fs.readdir(chatsPath+char_dir, (err, files) => { + var char_dir = (request.body.avatar_url).replace('.png', '') + fs.readdir(chatsPath + char_dir, (err, files) => { if (err) { - console.log('found error in history loading'); - console.error(err); - response.send({error: true}); - return; + console.log('found error in history loading'); + console.error(err); + response.send({ error: true }); + return; } // filter for JSON files - console.log('looking for JSONL files'); + console.log('looking for JSONL files'); const jsonFiles = files.filter(file => path.extname(file) === '.jsonl'); // sort the files by name @@ -1093,229 +1094,230 @@ app.post("/getallchatsofcharacter", jsonParser, function(request, response){ // print the sorted file names var chatData = {}; let ii = jsonFiles.length; //this is the number of files belonging to the character - if (ii !== 0) { - //console.log('found '+ii+' chat logs to load'); - for(let i = jsonFiles.length-1; i >= 0; i--){ - const file = jsonFiles[i]; - const fileStream = fs.createReadStream(chatsPath+char_dir+'/'+file); - const rl = readline.createInterface({ - input: fileStream, - crlfDelay: Infinity - }); + if (ii !== 0) { + //console.log('found '+ii+' chat logs to load'); + for (let i = jsonFiles.length - 1; i >= 0; i--) { + const file = jsonFiles[i]; + const fileStream = fs.createReadStream(chatsPath + char_dir + '/' + file); + const rl = readline.createInterface({ + input: fileStream, + crlfDelay: Infinity + }); - let lastLine; - rl.on('line', (line) => { - lastLine = line; - }); - rl.on('close', () => { - if(lastLine){ - let jsonData = JSON.parse(lastLine); - if(jsonData.name !== undefined){ - chatData[i] = {}; - chatData[i]['file_name'] = file; - chatData[i]['mes'] = jsonData['mes']; - ii--; - if(ii === 0){ - console.log('ii count went to zero, responding with chatData'); - response.send(chatData); - } - }else{ - console.log('just returning from getallchatsofcharacter'); - return; - } - } - console.log('successfully closing getallchatsofcharacter'); - rl.close(); - }); - }; - }else{ - //console.log('Found No Chats. Exiting Load Routine.'); - response.send({error: true}); - }; - })}); -function getPngName(file){ + let lastLine; + rl.on('line', (line) => { + lastLine = line; + }); + rl.on('close', () => { + if (lastLine) { + let jsonData = JSON.parse(lastLine); + if (jsonData.name !== undefined) { + chatData[i] = {}; + chatData[i]['file_name'] = file; + chatData[i]['mes'] = jsonData['mes']; + ii--; + if (ii === 0) { + console.log('ii count went to zero, responding with chatData'); + response.send(chatData); + } + } else { + console.log('just returning from getallchatsofcharacter'); + return; + } + } + console.log('successfully closing getallchatsofcharacter'); + rl.close(); + }); + }; + } else { + //console.log('Found No Chats. Exiting Load Routine.'); + response.send({ error: true }); + }; + }) +}); +function getPngName(file) { let i = 1; let base_name = file; - while (fs.existsSync(charactersPath+file+'.png')) { - file = base_name+i; + while (fs.existsSync(charactersPath + file + '.png')) { + file = base_name + i; i++; } return file; } -app.post("/importcharacter", urlencodedParser, async function(request, response){ +app.post("/importcharacter", urlencodedParser, async function (request, response) { - if(!request.body) return response.sendStatus(400); + if (!request.body) return response.sendStatus(400); - let png_name = ''; - let filedata = request.file; -     //console.log(filedata.filename); - var format = request.body.file_type; - //console.log(format); -     if(filedata){ - if(format == 'json'){ - fs.readFile('./uploads/'+filedata.filename, 'utf8', async (err, data) => { - if (err){ - console.log(err); - response.send({error:true}); - } - const jsonData = JSON.parse(data); - - if(jsonData.name !== undefined){ - png_name = getPngName(jsonData.name); - let char = {"name": jsonData.name, "description": jsonData.description ?? '', "personality": jsonData.personality ?? '', "first_mes": jsonData.first_mes ?? '', "avatar": 'none', "chat": humanizedISO8601DateTime(), "mes_example": jsonData.mes_example ?? '', "scenario": jsonData.scenario ?? '', "create_date": humanizedISO8601DateTime(), "talkativeness": jsonData.talkativeness ?? 0.5}; - char = JSON.stringify(char); - charaWrite('./public/img/fluffy.png', char, png_name, response, {file_name: png_name}); - }else if(jsonData.char_name !== undefined){//json Pygmalion notepad - png_name = getPngName(jsonData.char_name); - let char = {"name": jsonData.char_name, "description": jsonData.char_persona ?? '', "personality": '', "first_mes": jsonData.char_greeting ?? '', "avatar": 'none', "chat": humanizedISO8601DateTime(), "mes_example": jsonData.example_dialogue ?? '', "scenario": jsonData.world_scenario ?? '', "create_date": humanizedISO8601DateTime(), "talkativeness": jsonData.talkativeness ?? 0.5}; - char = JSON.stringify(char); - charaWrite('./public/img/fluffy.png', char, png_name, response, {file_name: png_name}); - }else{ - console.log('Incorrect character format .json'); - response.send({error:true}); - } - }); - }else{ - try{ - - var img_data = charaRead('./uploads/'+filedata.filename); - let jsonData = JSON.parse(img_data); - png_name = getPngName(jsonData.name); - - if(jsonData.name !== undefined){ - let char = {"name": jsonData.name, "description": jsonData.description ?? '', "personality": jsonData.personality ?? '', "first_mes": jsonData.first_mes ?? '', "avatar": 'none', "chat": humanizedISO8601DateTime(), "mes_example": jsonData.mes_example ?? '', "scenario": jsonData.scenario ?? '', "create_date": humanizedISO8601DateTime(), "talkativeness": jsonData.talkativeness ?? 0.5}; - char = JSON.stringify(char); - await charaWrite('./uploads/'+filedata.filename, char, png_name, response, {file_name: png_name}); - /* - fs.copyFile('./uploads/'+filedata.filename, charactersPath+png_name+'.png', (err) => { - if(err) { - response.send({error:true}); - return console.log(err); - }else{ - //console.log(img_file+fileType); - response.send({file_name: png_name}); - } - //console.log('The image was copied from temp directory.'); - });*/ - } - }catch(err){ + let png_name = ''; + let filedata = request.file; + //console.log(filedata.filename); + var format = request.body.file_type; + //console.log(format); + if (filedata) { + if (format == 'json') { + fs.readFile('./uploads/' + filedata.filename, 'utf8', async (err, data) => { + if (err) { console.log(err); - response.send({error:true}); + response.send({ error: true }); } + const jsonData = JSON.parse(data); + + if (jsonData.name !== undefined) { + png_name = getPngName(jsonData.name); + let char = { "name": jsonData.name, "description": jsonData.description ?? '', "personality": jsonData.personality ?? '', "first_mes": jsonData.first_mes ?? '', "avatar": 'none', "chat": humanizedISO8601DateTime(), "mes_example": jsonData.mes_example ?? '', "scenario": jsonData.scenario ?? '', "create_date": humanizedISO8601DateTime(), "talkativeness": jsonData.talkativeness ?? 0.5 }; + char = JSON.stringify(char); + charaWrite('./public/img/fluffy.png', char, png_name, response, { file_name: png_name }); + } else if (jsonData.char_name !== undefined) {//json Pygmalion notepad + png_name = getPngName(jsonData.char_name); + let char = { "name": jsonData.char_name, "description": jsonData.char_persona ?? '', "personality": '', "first_mes": jsonData.char_greeting ?? '', "avatar": 'none', "chat": humanizedISO8601DateTime(), "mes_example": jsonData.example_dialogue ?? '', "scenario": jsonData.world_scenario ?? '', "create_date": humanizedISO8601DateTime(), "talkativeness": jsonData.talkativeness ?? 0.5 }; + char = JSON.stringify(char); + charaWrite('./public/img/fluffy.png', char, png_name, response, { file_name: png_name }); + } else { + console.log('Incorrect character format .json'); + response.send({ error: true }); + } + }); + } else { + try { + + var img_data = charaRead('./uploads/' + filedata.filename); + let jsonData = JSON.parse(img_data); + png_name = getPngName(jsonData.name); + + if (jsonData.name !== undefined) { + let char = { "name": jsonData.name, "description": jsonData.description ?? '', "personality": jsonData.personality ?? '', "first_mes": jsonData.first_mes ?? '', "avatar": 'none', "chat": humanizedISO8601DateTime(), "mes_example": jsonData.mes_example ?? '', "scenario": jsonData.scenario ?? '', "create_date": humanizedISO8601DateTime(), "talkativeness": jsonData.talkativeness ?? 0.5 }; + char = JSON.stringify(char); + await charaWrite('./uploads/' + filedata.filename, char, png_name, response, { file_name: png_name }); + /* + fs.copyFile('./uploads/'+filedata.filename, charactersPath+png_name+'.png', (err) => { + if(err) { + response.send({error:true}); + return console.log(err); + }else{ + //console.log(img_file+fileType); + response.send({file_name: png_name}); + } + //console.log('The image was copied from temp directory.'); + });*/ + } + } catch (err) { + console.log(err); + response.send({ error: true }); } - //charaWrite(img_path+img_file, char, request.body.ch_name, response); } - //console.log("The file was saved."); + //charaWrite(img_path+img_file, char, request.body.ch_name, response); + } + //console.log("The file was saved."); -    //console.log(request.body); -    //response.send(request.body.ch_name); + //console.log(request.body); + //response.send(request.body.ch_name); //response.redirect("https://metanit.com") }); -app.post("/importchat", urlencodedParser, function(request, response){ -//console.log(humanizedISO8601DateTime()+':/importchat begun'); - if(!request.body) return response.sendStatus(400); +app.post("/importchat", urlencodedParser, function (request, response) { + //console.log(humanizedISO8601DateTime()+':/importchat begun'); + if (!request.body) return response.sendStatus(400); - var format = request.body.file_type; - let filedata = request.file; - let avatar_url = (request.body.avatar_url).replace('.png', ''); - let ch_name = request.body.character_name; -     //console.log(filedata.filename); - //var format = request.body.file_type; - //console.log(format); - //console.log(1); -     if(filedata){ + var format = request.body.file_type; + let filedata = request.file; + let avatar_url = (request.body.avatar_url).replace('.png', ''); + let ch_name = request.body.character_name; + //console.log(filedata.filename); + //var format = request.body.file_type; + //console.log(format); + //console.log(1); + if (filedata) { - if(format === 'json'){ - fs.readFile('./uploads/'+filedata.filename, 'utf8', (err, data) => { + if (format === 'json') { + fs.readFile('./uploads/' + filedata.filename, 'utf8', (err, data) => { - if (err){ - console.log(err); - response.send({error:true}); - } + if (err) { + console.log(err); + response.send({ error: true }); + } - const jsonData = JSON.parse(data); - var new_chat = []; - if(jsonData.histories !== undefined){ -//console.log('/importchat confirms JSON histories are defined'); - let i = 0; + const jsonData = JSON.parse(data); + var new_chat = []; + if (jsonData.histories !== undefined) { + //console.log('/importchat confirms JSON histories are defined'); + let i = 0; + new_chat[i] = {}; + new_chat[0]['user_name'] = 'You'; + new_chat[0]['character_name'] = ch_name; + new_chat[0]['create_date'] = humanizedISO8601DateTime() //Date.now(); + i++; + jsonData.histories.histories[0].msgs.forEach(function (item) { new_chat[i] = {}; - new_chat[0]['user_name'] = 'You'; - new_chat[0]['character_name'] = ch_name; - new_chat[0]['create_date'] = humanizedISO8601DateTime() //Date.now(); + if (item.src.is_human == true) { + new_chat[i]['name'] = 'You'; + } else { + new_chat[i]['name'] = ch_name; + } + new_chat[i]['is_user'] = item.src.is_human; + new_chat[i]['is_name'] = true; + new_chat[i]['send_date'] = humanizedISO8601DateTime() //Date.now(); + new_chat[i]['mes'] = item.text; i++; - jsonData.histories.histories[0].msgs.forEach(function(item) { - new_chat[i] = {}; - if(item.src.is_human == true){ - new_chat[i]['name'] = 'You'; - }else{ - new_chat[i]['name'] = ch_name; - } - new_chat[i]['is_user'] = item.src.is_human; - new_chat[i]['is_name'] = true; - new_chat[i]['send_date'] = humanizedISO8601DateTime() //Date.now(); - new_chat[i]['mes'] = item.text; - i++; - }); - const chatJsonlData = new_chat.map(JSON.stringify).join('\n'); -//console.log('/importchat saving a file: '+ch_name+' - '+humanizedISO8601DateTime()+' imported.jsonl'); - fs.writeFile(chatsPath+avatar_url+'/'+ch_name+' - '+humanizedISO8601DateTime()+' imported.jsonl', chatJsonlData, 'utf8', function(err) { //added ch_name and replaced Date.now() with humanizedISO8601DateTime - - if(err) { - response.send(err); - return console.log(err); - //response.send(err); - }else{ - //response.redirect("/"); - response.send({res:true}); - } - }); - - }else{ - response.send({error:true}); - return; - } + }); + const chatJsonlData = new_chat.map(JSON.stringify).join('\n'); + //console.log('/importchat saving a file: '+ch_name+' - '+humanizedISO8601DateTime()+' imported.jsonl'); + fs.writeFile(chatsPath + avatar_url + '/' + ch_name + ' - ' + humanizedISO8601DateTime() + ' imported.jsonl', chatJsonlData, 'utf8', function (err) { //added ch_name and replaced Date.now() with humanizedISO8601DateTime - }); - } - if(format === 'jsonl'){ -//console.log(humanizedISO8601DateTime()+':imported chat format is JSONL'); - const fileStream = fs.createReadStream('./uploads/'+filedata.filename); - const rl = readline.createInterface({ - input: fileStream, - crlfDelay: Infinity - }); - - rl.once('line', (line) => { - let jsonData = JSON.parse(line); - - if(jsonData.user_name !== undefined){ -//console.log(humanizedISO8601DateTime()+':/importchat copying chat as '+ch_name+' - '+humanizedISO8601DateTime()+'.jsonl'); - fs.copyFile('./uploads/'+filedata.filename, chatsPath+avatar_url+'/'+ch_name+' - '+humanizedISO8601DateTime()+'.jsonl', (err) => { //added character name and replaced Date.now() with humanizedISO8601DateTime - if(err) { - response.send({error:true}); - return console.log(err); - }else{ - response.send({res:true}); - return; - } - }); - }else{ - //response.send({error:true}); - return; - } - rl.close(); - }); - } + if (err) { + response.send(err); + return console.log(err); + //response.send(err); + } else { + //response.redirect("/"); + response.send({ res: true }); + } + }); + } else { + response.send({ error: true }); + return; + } + + }); } + if (format === 'jsonl') { + //console.log(humanizedISO8601DateTime()+':imported chat format is JSONL'); + const fileStream = fs.createReadStream('./uploads/' + filedata.filename); + const rl = readline.createInterface({ + input: fileStream, + crlfDelay: Infinity + }); + + rl.once('line', (line) => { + let jsonData = JSON.parse(line); + + if (jsonData.user_name !== undefined) { + //console.log(humanizedISO8601DateTime()+':/importchat copying chat as '+ch_name+' - '+humanizedISO8601DateTime()+'.jsonl'); + fs.copyFile('./uploads/' + filedata.filename, chatsPath + avatar_url + '/' + ch_name + ' - ' + humanizedISO8601DateTime() + '.jsonl', (err) => { //added character name and replaced Date.now() with humanizedISO8601DateTime + if (err) { + response.send({ error: true }); + return console.log(err); + } else { + response.send({ res: true }); + return; + } + }); + } else { + //response.send({error:true}); + return; + } + rl.close(); + }); + } + + } }); app.post('/importworldinfo', urlencodedParser, (request, response) => { - if(!request.file) return response.sendStatus(400); + if (!request.file) return response.sendStatus(400); const filename = request.file.originalname; @@ -1372,7 +1374,7 @@ app.post('/editworldinfo', jsonParser, (request, response) => { }); app.post('/uploaduseravatar', urlencodedParser, async (request, response) => { - if(!request.file) return response.sendStatus(400); + if (!request.file) return response.sendStatus(400); try { const pathToUpload = path.join('./uploads/' + request.file.filename); @@ -1395,7 +1397,7 @@ app.post('/getgroups', jsonParser, (_, response) => { } const files = fs.readdirSync(directories.groups); - files.forEach(function(file) { + files.forEach(function (file) { const fileContents = fs.readFileSync(path.join(directories.groups, file), 'utf8'); const group = JSON.parse(fileContents); groups.push(group); @@ -1432,7 +1434,7 @@ app.post('/editgroup', jsonParser, (request, response) => { const fileData = JSON.stringify(request.body); fs.writeFileSync(pathToFile, fileData); - return response.send({ok: true}); + return response.send({ ok: true }); }); app.post('/getgroupchat', jsonParser, (request, response) => { @@ -1446,7 +1448,7 @@ app.post('/getgroupchat', jsonParser, (request, response) => { if (fs.existsSync(pathToFile)) { const data = fs.readFileSync(pathToFile, 'utf8'); const lines = data.split('\n'); - + // Iterate through the array of strings and parse each line as JSON const jsonData = lines.map(JSON.parse); return response.send(jsonData); @@ -1470,7 +1472,7 @@ app.post('/savegroupchat', jsonParser, (request, response) => { let chat_data = request.body.chat; let jsonlData = chat_data.map(JSON.stringify).join('\n'); fs.writeFileSync(pathToFile, jsonlData, 'utf8'); - return response.send({ok: true}); + return response.send({ ok: true }); }); app.post('/deletegroup', jsonParser, async (request, response) => { @@ -1490,7 +1492,7 @@ app.post('/deletegroup', jsonParser, async (request, response) => { fs.rmSync(pathToChat); } - return response.send({ok: true}); + return response.send({ ok: true }); }); // ** REST CLIENT ASYNC WRAPPERS ** @@ -1539,15 +1541,15 @@ function getAsync(url, args) { } // ** END ** -app.listen(server_port, function() { - if(process.env.colab !== undefined){ - if(process.env.colab == 2){ +app.listen(server_port, function () { + if (process.env.colab !== undefined) { + if (process.env.colab == 2) { is_colab = true; } } console.log('Launching...'); - if(autorun) open('http:127.0.0.1:'+server_port); - console.log('TavernAI started: http://127.0.0.1:'+server_port); + if (autorun) open('http:127.0.0.1:' + server_port); + console.log('TavernAI started: http://127.0.0.1:' + server_port); if (fs.existsSync('public/characters/update.txt') && !is_colab) { convertStage1(); } @@ -1562,12 +1564,12 @@ var character_ib = 0; var directoriesB = {}; -function convertStage1(){ +function convertStage1() { //if (!fs.existsSync('public/charactersBackup')) { - //fs.mkdirSync('public/charactersBackup'); - //copyFolder('public/characters/', 'public/charactersBackup'); + //fs.mkdirSync('public/charactersBackup'); + //copyFolder('public/characters/', 'public/charactersBackup'); //} - + var directories = getDirectories2("public/characters"); //console.log(directories[0]); charactersB = {}; @@ -1575,12 +1577,12 @@ function convertStage1(){ var folderForDel = {}; getCharacterFile2(directories, 0); } -function convertStage2(){ +function convertStage2() { //directoriesB = JSON.parse(directoriesB); //console.log(directoriesB); var mes = true; for (const key in directoriesB) { - if(mes){ + if (mes) { console.log('***'); console.log('The update of the character format has begun...'); console.log('***'); @@ -1589,25 +1591,25 @@ function convertStage2(){ //console.log(`${key}: ${directoriesB[key]}`); //console.log(JSON.parse(charactersB[key])); //console.log(directoriesB[key]); - + var char = JSON.parse(charactersB[key]); char.create_date = humanizedISO8601DateTime(); charactersB[key] = JSON.stringify(char); var avatar = 'public/img/fluffy.png'; - if(char.avatar !== 'none'){ - avatar = 'public/characters/'+char.name+'/avatars/'+char.avatar; + if (char.avatar !== 'none') { + avatar = 'public/characters/' + char.name + '/avatars/' + char.avatar; } - + charaWrite(avatar, charactersB[key], directoriesB[key]); - - const files = fs.readdirSync('public/characters/'+directoriesB[key]+'/chats'); - if (!fs.existsSync(chatsPath+char.name)) { - fs.mkdirSync(chatsPath+char.name); + + const files = fs.readdirSync('public/characters/' + directoriesB[key] + '/chats'); + if (!fs.existsSync(chatsPath + char.name)) { + fs.mkdirSync(chatsPath + char.name); } - files.forEach(function(file) { + files.forEach(function (file) { // Read the contents of the file - - const fileContents = fs.readFileSync('public/characters/'+directoriesB[key]+'/chats/' + file, 'utf8'); + + const fileContents = fs.readFileSync('public/characters/' + directoriesB[key] + '/chats/' + file, 'utf8'); // Iterate through the array of strings and parse each line as JSON @@ -1615,23 +1617,23 @@ function convertStage2(){ let new_chat_data = []; let this_chat_user_name = 'You'; let is_pass_0 = false; - if(chat_data[0].indexOf('') !== -1){ + if (chat_data[0].indexOf('') !== -1) { this_chat_user_name = chat_data[0].substr(''.length, chat_data[0].length); is_pass_0 = true; } let i = 0; let ii = 0; - new_chat_data[i] = {user_name:'You', character_name:char.name, create_date: humanizedISO8601DateTime()}; + new_chat_data[i] = { user_name: 'You', character_name: char.name, create_date: humanizedISO8601DateTime() }; i++; ii++; - chat_data.forEach(function(mes) { - if(!(i === 1 && is_pass_0)){ - if(mes.indexOf('') === -1 && mes.indexOf('') === -1){ + chat_data.forEach(function (mes) { + if (!(i === 1 && is_pass_0)) { + if (mes.indexOf('') === -1 && mes.indexOf('') === -1) { new_chat_data[ii] = {}; let is_name = false; - if(mes.trim().indexOf(this_chat_user_name+':') !== 0){ - if(mes.trim().indexOf(char.name+':') === 0){ - mes = mes.replace(char.name+':',''); + if (mes.trim().indexOf(this_chat_user_name + ':') !== 0) { + if (mes.trim().indexOf(char.name + ':') === 0) { + mes = mes.replace(char.name + ':', ''); is_name = true; } new_chat_data[ii]['name'] = char.name; @@ -1639,8 +1641,8 @@ function convertStage2(){ new_chat_data[ii]['is_name'] = is_name; new_chat_data[ii]['send_date'] = humanizedISO8601DateTime(); //Date.now(); - }else{ - mes = mes.replace(this_chat_user_name+':',''); + } else { + mes = mes.replace(this_chat_user_name + ':', ''); new_chat_data[ii]['name'] = 'You'; new_chat_data[ii]['is_user'] = true; new_chat_data[ii]['is_name'] = true; @@ -1652,31 +1654,31 @@ function convertStage2(){ } } i++; - + }); const jsonlData = new_chat_data.map(JSON.stringify).join('\n'); // Write the contents to the destination folder -//console.log('convertstage2 writing a file: '+chatsPath+char.name+'/' + file+'l'); - fs.writeFileSync(chatsPath+char.name+'/' + file+'l', jsonlData); + //console.log('convertstage2 writing a file: '+chatsPath+char.name+'/' + file+'l'); + fs.writeFileSync(chatsPath + char.name + '/' + file + 'l', jsonlData); }); //fs.rmSync('public/characters/'+directoriesB[key],{ recursive: true }); - console.log(char.name+' update!'); + console.log(char.name + ' update!'); } //removeFolders('public/characters'); fs.unlinkSync('public/characters/update.txt'); - if(mes == false){ + if (mes == false) { console.log('***'); console.log('Сharacter format update completed successfully!'); console.log('***'); console.log('Now you can delete these folders, they are no longer used by TavernAI:'); } for (const key in directoriesB) { - console.log('public/characters/'+directoriesB[key]); + console.log('public/characters/' + directoriesB[key]); } } function removeFolders(folder) { const files = fs.readdirSync(folder); - files.forEach(function(file) { + files.forEach(function (file) { const filePath = folder + '/' + file; const stat = fs.statSync(filePath); if (stat.isDirectory()) { @@ -1688,7 +1690,7 @@ function removeFolders(folder) { function copyFolder(src, dest) { const files = fs.readdirSync(src); - files.forEach(function(file) { + files.forEach(function (file) { const filePath = src + '/' + file; const stat = fs.statSync(filePath); if (stat.isFile()) { @@ -1702,40 +1704,40 @@ function copyFolder(src, dest) { function getDirectories2(path) { - return fs.readdirSync(path) - .filter(function (file) { - return fs.statSync(path + '/' + file).isDirectory(); - }) - .sort(function (a, b) { - return new Date(fs.statSync(path + '/' + a).mtime) - new Date(fs.statSync(path + '/' + b).mtime); - }) - .reverse(); + return fs.readdirSync(path) + .filter(function (file) { + return fs.statSync(path + '/' + file).isDirectory(); + }) + .sort(function (a, b) { + return new Date(fs.statSync(path + '/' + a).mtime) - new Date(fs.statSync(path + '/' + b).mtime); + }) + .reverse(); } -function getCharacterFile2(directories,i){ - if(directories.length > i){ - fs.stat('public/characters/'+directories[i]+'/'+directories[i]+".json", function(err, stat) { - if (err == null) { - fs.readFile('public/characters/'+directories[i]+'/'+directories[i]+".json", 'utf8', (err, data) => { - if (err) { - console.error(err); - return; - } - //console.log(data); - if (!fs.existsSync('public/characters/'+directories[i]+'.png')) { - charactersB[character_ib] = {}; - charactersB[character_ib] = data; - directoriesB[character_ib] = directories[i]; - character_ib++; - } - i++; - getCharacterFile2(directories,i); - }); - }else{ +function getCharacterFile2(directories, i) { + if (directories.length > i) { + fs.stat('public/characters/' + directories[i] + '/' + directories[i] + ".json", function (err, stat) { + if (err == null) { + fs.readFile('public/characters/' + directories[i] + '/' + directories[i] + ".json", 'utf8', (err, data) => { + if (err) { + console.error(err); + return; + } + //console.log(data); + if (!fs.existsSync('public/characters/' + directories[i] + '.png')) { + charactersB[character_ib] = {}; + charactersB[character_ib] = data; + directoriesB[character_ib] = directories[i]; + character_ib++; + } i++; - getCharacterFile2(directories,i); - } - }); - }else{ + getCharacterFile2(directories, i); + }); + } else { + i++; + getCharacterFile2(directories, i); + } + }); + } else { convertStage2(); } }