Feature: Auto Swipe

This commit is contained in:
Aisu Wata
2023-05-13 22:15:47 -03:00
parent c06de1e6bd
commit 1b2e113a34
4 changed files with 248 additions and 160 deletions

View File

@ -1661,6 +1661,20 @@
<option value="1">Always enabled</option> <option value="1">Always enabled</option>
</select> </select>
</div> </div>
<h4>Auto-swipe</h4>
<label for="auto_swipe">
<input id="auto_swipe" type="checkbox" />
Auto-swipe enabled
</label>
<div>Minimum generated message length</div>
<input id="auto_swipe_minimum_length" name="auto_swipe_minimum_length" type="number" min="0" step="1" value="0" class="text_pole">
<div>Blacklisted words</div>
<div class="auto_swipe">
<input id="auto_swipe_blacklist" name="auto_swipe_blacklist" placeholder="ethical, guidelines, harmful, illegal, comfortable, generating" class="text_pole" maxlength="500" value="" autocomplete="off">
<div>Blacklisted word count to swipe</div>
<input id="auto_swipe_blacklist_threshold" name="auto_swipe_blacklist_threshold" type="number" min="0" step="1" value="1" class="text_pole">
</div>
</div> </div>
</div> </div>

View File

@ -1184,7 +1184,6 @@ function substituteParams(content, _name1, _name2) {
_name1 = _name1 ?? name1; _name1 = _name1 ?? name1;
_name2 = _name2 ?? name2; _name2 = _name2 ?? name2;
if (!content) { if (!content) {
console.warn("No content on substituteParams")
return '' return ''
} }
@ -1469,13 +1468,46 @@ class StreamingProcessor {
this.hideStopButton(this.messageId); this.hideStopButton(this.messageId);
this.onProgressStreaming(messageId, text); this.onProgressStreaming(messageId, text);
addCopyToCodeBlocks($(`#chat .mes[mesid="${messageId}"]`)); addCopyToCodeBlocks($(`#chat .mes[mesid="${messageId}"]`));
playMessageSound();
saveChatConditional(); saveChatConditional();
activateSendButtons(); activateSendButtons();
showSwipeButtons(); showSwipeButtons();
setGenerationProgress(0); setGenerationProgress(0);
$('.mes_buttons:last').show(); $('.mes_buttons:last').show();
generatedPromtCache = ''; generatedPromtCache = '';
console.log("Generated text size:", text.length, text)
if (power_user.auto_swipe) {
function containsBlacklistedWords(str, blacklist, threshold) {
const regex = new RegExp(`\\b(${blacklist.join('|')})\\b`, 'gi');
const matches = str.match(regex) || [];
return matches.length >= threshold;
}
const generatedTextFiltered = (text) => {
if (text) {
if (power_user.auto_swipe_minimum_length) {
if (text.length < power_user.auto_swipe_minimum_length && text.length !== 0) {
console.log("Generated text size too small")
return true
}
}
if (power_user.auto_swipe_blacklist_threshold) {
if (containsBlacklistedWords(text, power_user.auto_swipe_blacklist, power_user.auto_swipe_blacklist_threshold)) {
console.log("Generated text has blacklisted words")
return true
}
}
}
return false
}
if (generatedTextFiltered(text)) {
swipe_right()
return
}
}
playMessageSound();
} }
onErrorStreaming() { onErrorStreaming() {
@ -1630,8 +1662,6 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
let anchorTop = ''; let anchorTop = '';
let anchorBottom = ''; let anchorBottom = '';
if (!is_pygmalion) { if (!is_pygmalion) {
console.log('saw not pyg');
let postAnchorChar = character_anchor ? name2 + " Elaborate speaker" : ""; let postAnchorChar = character_anchor ? name2 + " Elaborate speaker" : "";
let postAnchorStyle = style_anchor ? "Writing style: very long messages" : ""; let postAnchorStyle = style_anchor ? "Writing style: very long messages" : "";
if (anchor_order === 0) { if (anchor_order === 0) {
@ -4005,7 +4035,162 @@ window["SillyTavern"].getContext = function () {
}; };
}; };
// when we click swipe right button
const swipe_right = () => {
if (chat.length - 1 === Number(this_edit_mes_id)) {
closeMessageEditor();
}
if (isHordeGenerationNotAllowed()) {
return;
}
const swipe_duration = 200;
const swipe_range = 700;
//console.log(swipe_range);
let run_generate = false;
let run_swipe_right = false;
if (chat[chat.length - 1]['swipe_id'] === undefined) { // if there is no swipe-message in the last spot of the chat array
chat[chat.length - 1]['swipe_id'] = 0; // set it to id 0
chat[chat.length - 1]['swipes'] = []; // empty the array
chat[chat.length - 1]['swipes'][0] = chat[chat.length - 1]['mes']; //assign swipe array with last message from chat
}
chat[chat.length - 1]['swipe_id']++; //make new slot in array
// if message has memory attached - remove it to allow regen
if (chat[chat.length - 1].extra && chat[chat.length - 1].extra.memory) {
delete chat[chat.length - 1].extra.memory;
}
//console.log(chat[chat.length-1]['swipes']);
if (parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) { //if swipe id of last message is the same as the length of the 'swipes' array
delete chat[chat.length - 1].gen_started;
delete chat[chat.length - 1].gen_finished;
run_generate = true;
} else if (parseInt(chat[chat.length - 1]['swipe_id']) < chat[chat.length - 1]['swipes'].length) { //otherwise, if the id is less than the number of swipes
chat[chat.length - 1]['mes'] = chat[chat.length - 1]['swipes'][chat[chat.length - 1]['swipe_id']]; //load the last mes box with the latest generation
run_swipe_right = true; //then prepare to do normal right swipe to show next message
}
const currentMessage = $("#chat").children().filter(`[mesid="${count_view_mes - 1}"]`);
let this_div = currentMessage.children('.swipe_right');
let this_mes_div = this_div.parent();
if (chat[chat.length - 1]['swipe_id'] > chat[chat.length - 1]['swipes'].length) { //if we swipe right while generating (the swipe ID is greater than what we are viewing now)
chat[chat.length - 1]['swipe_id'] = chat[chat.length - 1]['swipes'].length; //show that message slot (will be '...' while generating)
}
if (run_generate) { //hide swipe arrows while generating
this_div.css('display', 'none');
}
// handles animated transitions when swipe right, specifically height transitions between messages
if (run_generate || run_swipe_right) {
let this_mes_block = this_mes_div.children('.mes_block').children('.mes_text');
const this_mes_div_height = this_mes_div[0].scrollHeight;
const this_mes_block_height = this_mes_block[0].scrollHeight;
this_mes_div.children('.swipe_left').css('display', 'flex');
this_mes_div.children('.mes_block').transition({ // this moves the div back and forth
x: '-' + swipe_range,
duration: swipe_duration,
easing: animation_easing,
queue: false,
complete: function () {
/*if (!selected_group) {
var typingIndicator = $("#typing_indicator_template .typing_indicator").clone();
typingIndicator.find(".typing_indicator_name").text(characters[this_chid].name);
} */
/* $("#chat").append(typingIndicator); */
const is_animation_scroll = ($('#chat').scrollTop() >= ($('#chat').prop("scrollHeight") - $('#chat').outerHeight()) - 10);
//console.log(parseInt(chat[chat.length-1]['swipe_id']));
//console.log(chat[chat.length-1]['swipes'].length);
if (run_generate && parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) {
//console.log('showing ""..."');
/* if (!selected_group) {
} else { */
$("#chat")
.find('[mesid="' + (count_view_mes - 1) + '"]')
.find('.mes_text')
.html('...'); //shows "..." while generating
$("#chat")
.find('[mesid="' + (count_view_mes - 1) + '"]')
.find('.mes_timer')
.html(''); // resets the timer
/* } */
} else {
//console.log('showing previously generated swipe candidate, or "..."');
//console.log('onclick right swipe calling addOneMessage');
addOneMessage(chat[chat.length - 1], { type: 'swipe' });
}
let new_height = this_mes_div_height - (this_mes_block_height - this_mes_block[0].scrollHeight);
if (new_height < 103) new_height = 103;
this_mes_div.animate({ height: new_height + 'px' }, {
duration: 0, //used to be 100
queue: false,
progress: function () {
// Scroll the chat down as the message expands
if (is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
},
complete: function () {
this_mes_div.css('height', 'auto');
// Scroll the chat down to the bottom once the animation is complete
if (is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
}
});
this_mes_div.children('.mes_block').transition({
x: swipe_range,
duration: 0,
easing: animation_easing,
queue: false,
complete: function () {
this_mes_div.children('.mes_block').transition({
x: '0px',
duration: swipe_duration,
easing: animation_easing,
queue: false,
complete: function () {
if (run_generate && !is_send_press && parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) {
console.log('caught here 2');
is_send_press = true;
$('.mes_buttons:last').hide();
Generate('swipe');
} else {
if (parseInt(chat[chat.length - 1]['swipe_id']) !== chat[chat.length - 1]['swipes'].length) {
saveChatConditional();
}
}
}
});
}
});
}
});
this_mes_div.children('.avatar').transition({ // moves avatar along with swipe
x: '-' + swipe_range,
duration: swipe_duration,
easing: animation_easing,
queue: false,
complete: function () {
this_mes_div.children('.avatar').transition({
x: swipe_range,
duration: 0,
easing: animation_easing,
queue: false,
complete: function () {
this_mes_div.children('.avatar').transition({
x: '0px',
duration: swipe_duration,
easing: animation_easing,
queue: false,
complete: function () {
}
});
}
});
}
});
}
}
$(document).ready(function () { $(document).ready(function () {
@ -4052,160 +4237,7 @@ $(document).ready(function () {
///// SWIPE BUTTON CLICKS /////// ///// SWIPE BUTTON CLICKS ///////
$(document).on('click', '.swipe_right', function () { //when we click swipe right button $(document).on('click', '.swipe_right', swipe_right);
if (chat.length - 1 === Number(this_edit_mes_id)) {
closeMessageEditor();
}
if (isHordeGenerationNotAllowed()) {
return;
}
const swipe_duration = 200;
const swipe_range = 700;
//console.log(swipe_range);
let run_generate = false;
let run_swipe_right = false;
if (chat[chat.length - 1]['swipe_id'] === undefined) { // if there is no swipe-message in the last spot of the chat array
chat[chat.length - 1]['swipe_id'] = 0; // set it to id 0
chat[chat.length - 1]['swipes'] = []; // empty the array
chat[chat.length - 1]['swipes'][0] = chat[chat.length - 1]['mes']; //assign swipe array with last message from chat
}
chat[chat.length - 1]['swipe_id']++; //make new slot in array
// if message has memory attached - remove it to allow regen
if (chat[chat.length - 1].extra && chat[chat.length - 1].extra.memory) {
delete chat[chat.length - 1].extra.memory;
}
//console.log(chat[chat.length-1]['swipes']);
if (parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) { //if swipe id of last message is the same as the length of the 'swipes' array
delete chat[chat.length - 1].gen_started;
delete chat[chat.length - 1].gen_finished;
run_generate = true;
} else if (parseInt(chat[chat.length - 1]['swipe_id']) < chat[chat.length - 1]['swipes'].length) { //otherwise, if the id is less than the number of swipes
chat[chat.length - 1]['mes'] = chat[chat.length - 1]['swipes'][chat[chat.length - 1]['swipe_id']]; //load the last mes box with the latest generation
run_swipe_right = true; //then prepare to do normal right swipe to show next message
}
if (chat[chat.length - 1]['swipe_id'] > chat[chat.length - 1]['swipes'].length) { //if we swipe right while generating (the swipe ID is greater than what we are viewing now)
chat[chat.length - 1]['swipe_id'] = chat[chat.length - 1]['swipes'].length; //show that message slot (will be '...' while generating)
}
if (run_generate) { //hide swipe arrows while generating
$(this).css('display', 'none');
}
if (run_generate || run_swipe_right) { // handles animated transitions when swipe right, specifically height transitions between messages
let this_mes_div = $(this).parent();
let this_mes_block = $(this).parent().children('.mes_block').children('.mes_text');
const this_mes_div_height = this_mes_div[0].scrollHeight;
const this_mes_block_height = this_mes_block[0].scrollHeight;
this_mes_div.children('.swipe_left').css('display', 'flex');
this_mes_div.children('.mes_block').transition({ // this moves the div back and forth
x: '-' + swipe_range,
duration: swipe_duration,
easing: animation_easing,
queue: false,
complete: function () {
/*if (!selected_group) {
var typingIndicator = $("#typing_indicator_template .typing_indicator").clone();
typingIndicator.find(".typing_indicator_name").text(characters[this_chid].name);
} */
/* $("#chat").append(typingIndicator); */
const is_animation_scroll = ($('#chat').scrollTop() >= ($('#chat').prop("scrollHeight") - $('#chat').outerHeight()) - 10);
//console.log(parseInt(chat[chat.length-1]['swipe_id']));
//console.log(chat[chat.length-1]['swipes'].length);
if (run_generate && parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) {
//console.log('showing ""..."');
/* if (!selected_group) {
} else { */
$("#chat")
.find('[mesid="' + (count_view_mes - 1) + '"]')
.find('.mes_text')
.html('...'); //shows "..." while generating
$("#chat")
.find('[mesid="' + (count_view_mes - 1) + '"]')
.find('.mes_timer')
.html(''); // resets the timer
/* } */
} else {
//console.log('showing previously generated swipe candidate, or "..."');
//console.log('onclick right swipe calling addOneMessage');
addOneMessage(chat[chat.length - 1], { type: 'swipe' });
}
let new_height = this_mes_div_height - (this_mes_block_height - this_mes_block[0].scrollHeight);
if (new_height < 103) new_height = 103;
this_mes_div.animate({ height: new_height + 'px' }, {
duration: 0, //used to be 100
queue: false,
progress: function () {
// Scroll the chat down as the message expands
if (is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
},
complete: function () {
this_mes_div.css('height', 'auto');
// Scroll the chat down to the bottom once the animation is complete
if (is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
}
});
this_mes_div.children('.mes_block').transition({
x: swipe_range,
duration: 0,
easing: animation_easing,
queue: false,
complete: function () {
this_mes_div.children('.mes_block').transition({
x: '0px',
duration: swipe_duration,
easing: animation_easing,
queue: false,
complete: function () {
if (run_generate && !is_send_press && parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) {
console.log('caught here 2');
is_send_press = true;
$('.mes_buttons:last').hide();
Generate('swipe');
} else {
if (parseInt(chat[chat.length - 1]['swipe_id']) !== chat[chat.length - 1]['swipes'].length) {
saveChatConditional();
}
}
}
});
}
});
}
});
$(this).parent().children('.avatar').transition({ // moves avatar aong with swipe
x: '-' + swipe_range,
duration: swipe_duration,
easing: animation_easing,
queue: false,
complete: function () {
$(this).parent().children('.avatar').transition({
x: swipe_range,
duration: 0,
easing: animation_easing,
queue: false,
complete: function () {
$(this).parent().children('.avatar').transition({
x: '0px',
duration: swipe_duration,
easing: animation_easing,
queue: false,
complete: function () {
}
});
}
});
}
});
}
});
$(document).on('click', '.swipe_left', function () { // when we swipe left..but no generation. $(document).on('click', '.swipe_left', function () { // when we swipe left..but no generation.
if (chat.length - 1 === Number(this_edit_mes_id)) { if (chat.length - 1 === Number(this_edit_mes_id)) {

View File

@ -310,7 +310,7 @@ async function prepareOpenAIMessages(name2, storyString, worldInfoBefore, worldI
let whole_prompt = getSystemPrompt(nsfw_toggle_prompt, enhance_definitions_prompt, wiBefore, storyString, wiAfter, extensionPrompt, isImpersonate); let whole_prompt = getSystemPrompt(nsfw_toggle_prompt, enhance_definitions_prompt, wiBefore, storyString, wiAfter, extensionPrompt, isImpersonate);
// Join by a space and replace placeholders with real user/char names // Join by a space and replace placeholders with real user/char names
storyString = substituteParams(whole_prompt.join(" ")).replace(/\r/gm, '').trim(); storyString = substituteParams(whole_prompt.join("\n")).replace(/\r/gm, '').trim();
let prompt_msg = { "role": "system", "content": storyString } let prompt_msg = { "role": "system", "content": storyString }
let examples_tosend = []; let examples_tosend = [];
@ -469,7 +469,7 @@ function getSystemPrompt(nsfw_toggle_prompt, enhance_definitions_prompt, wiBefor
whole_prompt = [nsfw_toggle_prompt, oai_settings.main_prompt, enhance_definitions_prompt + "\n\n" + wiBefore, storyString, wiAfter, extensionPrompt]; whole_prompt = [nsfw_toggle_prompt, oai_settings.main_prompt, enhance_definitions_prompt + "\n\n" + wiBefore, storyString, wiAfter, extensionPrompt];
} }
else { else {
whole_prompt = [oai_settings.main_prompt, nsfw_toggle_prompt, enhance_definitions_prompt + "\n\n" + wiBefore, storyString, wiAfter, extensionPrompt]; whole_prompt = [oai_settings.main_prompt, nsfw_toggle_prompt, enhance_definitions_prompt, "\n", wiBefore, storyString, wiAfter, extensionPrompt].filter(elem => elem);
} }
} }
return whole_prompt; return whole_prompt;

View File

@ -106,6 +106,10 @@ let power_user = {
noShadows: false, noShadows: false,
theme: 'Default (Dark)', theme: 'Default (Dark)',
auto_swipe: false,
auto_swipe_minimum_length: 0,
auto_swipe_blacklist: ["ethical", "guidelines", "harmful", "illegal", "comfortable", "generating"],
auto_swipe_blacklist_threshold: 2,
auto_scroll_chat_to_bottom: true, auto_scroll_chat_to_bottom: true,
auto_fix_generated_markdown: true, auto_fix_generated_markdown: true,
send_on_enter: send_on_enter_options.AUTO, send_on_enter: send_on_enter_options.AUTO,
@ -476,6 +480,11 @@ function loadPowerUserSettings(settings, data) {
power_user.font_scale = Number(localStorage.getItem(storage_keys.font_scale) ?? 1); power_user.font_scale = Number(localStorage.getItem(storage_keys.font_scale) ?? 1);
power_user.blur_strength = Number(localStorage.getItem(storage_keys.blur_strength) ?? 10); power_user.blur_strength = Number(localStorage.getItem(storage_keys.blur_strength) ?? 10);
$('#auto_swipe').prop("checked", power_user.auto_swipe);
$('#auto_swipe_minimum_length').val(power_user.auto_swipe_minimum_length);
$('#auto_swipe_blacklist').val(power_user.auto_swipe_blacklist.join(", "));
$('#auto_swipe_blacklist_threshold').val(power_user.auto_swipe_blacklist_threshold);
$('#auto_fix_generated_markdown').prop("checked", power_user.auto_fix_generated_markdown); $('#auto_fix_generated_markdown').prop("checked", power_user.auto_fix_generated_markdown);
$('#auto_scroll_chat_to_bottom').prop("checked", power_user.auto_scroll_chat_to_bottom); $('#auto_scroll_chat_to_bottom').prop("checked", power_user.auto_scroll_chat_to_bottom);
$(`#tokenizer option[value="${power_user.tokenizer}"]`).attr('selected', true); $(`#tokenizer option[value="${power_user.tokenizer}"]`).attr('selected', true);
@ -999,6 +1008,39 @@ $(document).ready(() => {
saveSettingsDebounced(); saveSettingsDebounced();
}); });
$('#auto_swipe').on('input', function () {
power_user.auto_swipe = !!$(this).prop('checked');
console.log("power_user.auto_swipe", power_user.auto_swipe)
saveSettingsDebounced();
});
$('#auto_swipe_blacklist').on('input', function () {
power_user.auto_swipe_blacklist = $(this).val()
.split(",")
.map(str => str.trim())
.filter(str => str);
console.log("power_user.auto_swipe_blacklist", power_user.auto_swipe_blacklist)
saveSettingsDebounced();
});
$('#auto_swipe_minimum_length').on('input', function () {
const number = parseInt($(this).val());
if (!isNaN(number)) {
power_user.auto_swipe_minimum_length = number;
console.log("power_user.auto_swipe_minimum_length", power_user.auto_swipe_minimum_length)
saveSettingsDebounced();
}
});
$('#auto_swipe_blacklist_threshold').on('input', function () {
const number = parseInt($(this).val());
if (!isNaN(number)) {
power_user.auto_swipe_blacklist_threshold = number;
console.log("power_user.auto_swipe_blacklist_threshold", power_user.auto_swipe_blacklist_threshold)
saveSettingsDebounced();
}
});
$('#auto_fix_generated_markdown').on('input', function () { $('#auto_fix_generated_markdown').on('input', function () {
power_user.auto_fix_generated_markdown = !!$(this).prop('checked'); power_user.auto_fix_generated_markdown = !!$(this).prop('checked');
reloadCurrentChat(); reloadCurrentChat();