Regex script: promptOnly checkbox and feature

This commit is contained in:
Aisu Wata 2023-11-02 19:52:33 -03:00
parent d541558f15
commit c94962aa3c
4 changed files with 50 additions and 25 deletions

View File

@ -2441,6 +2441,14 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
reject = () => { }; reject = () => { };
} }
let chat_regexed = chat.map(x => ({
...x,
mes: getRegexedString(x.mes, x.is_user ? regex_placement.USER_INPUT : regex_placement.AI_OUTPUT, {
isPrompt: true,
}),
}))
if (selected_group && !is_group_generating && !dryRun) { if (selected_group && !is_group_generating && !dryRun) {
generateGroupWrapper(false, type, { resolve, reject, quiet_prompt, force_chid, signal: abortController.signal }); generateGroupWrapper(false, type, { resolve, reject, quiet_prompt, force_chid, signal: abortController.signal });
return; return;
@ -2485,34 +2493,34 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
$("#send_textarea").val('').trigger('input'); $("#send_textarea").val('').trigger('input');
} else { } else {
textareaText = ""; textareaText = "";
if (chat.length && chat[chat.length - 1]['is_user']) { if (chat_regexed.length && chat_regexed[chat_regexed.length - 1]['is_user']) {
//do nothing? why does this check exist? //do nothing? why does this check exist?
} }
else if (type !== 'quiet' && type !== "swipe" && !isImpersonate && !dryRun && chat.length) { else if (type !== 'quiet' && type !== "swipe" && !isImpersonate && !dryRun && chat_regexed.length) {
chat.length = chat.length - 1; chat_regexed.length = chat_regexed.length - 1;
count_view_mes -= 1; count_view_mes -= 1;
$('#chat').children().last().hide(250, function () { $('#chat').children().last().hide(250, function () {
$(this).remove(); $(this).remove();
}); });
await eventSource.emit(event_types.MESSAGE_DELETED, chat.length); await eventSource.emit(event_types.MESSAGE_DELETED, chat_regexed.length);
} }
} }
if (!type && !textareaText && power_user.continue_on_send && !selected_group && chat.length && !chat[chat.length - 1]['is_user'] && !chat[chat.length - 1]['is_system']) { if (!type && !textareaText && power_user.continue_on_send && !selected_group && chat_regexed.length && !chat_regexed[chat_regexed.length - 1]['is_user'] && !chat_regexed[chat_regexed.length - 1]['is_system']) {
type = 'continue'; type = 'continue';
} }
const isContinue = type == 'continue'; const isContinue = type == 'continue';
// Rewrite the generation timer to account for the time passed for all the continuations. // Rewrite the generation timer to account for the time passed for all the continuations.
if (isContinue && chat.length) { if (isContinue && chat_regexed.length) {
const prevFinished = chat[chat.length - 1]['gen_finished']; const prevFinished = chat_regexed[chat_regexed.length - 1]['gen_finished'];
const prevStarted = chat[chat.length - 1]['gen_started']; const prevStarted = chat_regexed[chat_regexed.length - 1]['gen_started'];
if (prevFinished && prevStarted) { if (prevFinished && prevStarted) {
const timePassed = prevFinished - prevStarted; const timePassed = prevFinished - prevStarted;
generation_started = new Date(Date.now() - timePassed); generation_started = new Date(Date.now() - timePassed);
chat[chat.length - 1]['gen_started'] = generation_started; chat_regexed[chat_regexed.length - 1]['gen_started'] = generation_started;
} }
} }
@ -2600,12 +2608,12 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
mesExamplesArray = [] mesExamplesArray = []
// First message in fresh 1-on-1 chat reacts to user/character settings changes // First message in fresh 1-on-1 chat reacts to user/character settings changes
if (chat.length) { if (chat_regexed.length) {
chat[0].mes = substituteParams(chat[0].mes); chat_regexed[0].mes = substituteParams(chat_regexed[0].mes);
} }
// Collect messages with usable content // Collect messages with usable content
let coreChat = chat.filter(x => !x.is_system); let coreChat = chat_regexed.filter(x => !x.is_system);
if (type === 'swipe') { if (type === 'swipe') {
coreChat.pop(); coreChat.pop();
} }
@ -2626,7 +2634,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
console.debug('Skipping extension interceptors for dry run'); console.debug('Skipping extension interceptors for dry run');
} }
console.log(`Core/all messages: ${coreChat.length}/${chat.length}`); console.log(`Core/all messages: ${coreChat.length}/${chat_regexed.length}`);
// kingbri MARK: - Make sure the prompt bias isn't the same as the user bias // kingbri MARK: - Make sure the prompt bias isn't the same as the user bias
if ((promptBias && !isUserPromptBias) || power_user.always_force_name2 || main_api == 'novel') { if ((promptBias && !isUserPromptBias) || power_user.always_force_name2 || main_api == 'novel') {

View File

@ -33,7 +33,7 @@
<small data-i18n="Replace With">Replace With</small> <small data-i18n="Replace With">Replace With</small>
</label> </label>
<div> <div>
<textarea <textarea
class="regex_replace_string text_pole wide100p textarea_compact" class="regex_replace_string text_pole wide100p textarea_compact"
placeholder="Use {{match}} to include the matched text from the Find Regex" placeholder="Use {{match}} to include the matched text from the Find Regex"
rows="2" rows="2"
@ -45,7 +45,7 @@
<small data-i18n="Trim Out">Trim Out</small> <small data-i18n="Trim Out">Trim Out</small>
</label> </label>
<div> <div>
<textarea <textarea
class="regex_trim_strings text_pole wide100p textarea_compact" class="regex_trim_strings text_pole wide100p textarea_compact"
placeholder="Globally trims any unwanted parts from a regex match before replacement. Separate each element by an enter." placeholder="Globally trims any unwanted parts from a regex match before replacement. Separate each element by an enter."
rows="3" rows="3"
@ -86,6 +86,10 @@
<input type="checkbox" name="only_format_display" /> <input type="checkbox" name="only_format_display" />
<span data-i18n="Only Format Display">Only Format Display</span> <span data-i18n="Only Format Display">Only Format Display</span>
</label> </label>
<label class="checkbox flex-container" title="Chat history won't change, only as the prompt as the request is sent (on generation)">
<input type="checkbox" name="only_format_prompt"/>
<span data-i18n="Only Format Prompt (?)">Only Format Prompt (?)</span>
</label>
<label class="checkbox flex-container"> <label class="checkbox flex-container">
<input type="checkbox" name="run_on_edit" /> <input type="checkbox" name="run_on_edit" />
<span data-i18n="Run On Edit">Run On Edit</span> <span data-i18n="Run On Edit">Run On Edit</span>

View File

@ -24,12 +24,12 @@ function regexFromString(input) {
try { try {
// Parse input // Parse input
var m = input.match(/(\/?)(.+)\1([a-z]*)/i); var m = input.match(/(\/?)(.+)\1([a-z]*)/i);
// Invalid flags // Invalid flags
if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) { if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) {
return RegExp(input); return RegExp(input);
} }
// Create the regular expression // Create the regular expression
return new RegExp(m[2], m[3]); return new RegExp(m[2], m[3]);
} catch { } catch {
@ -38,19 +38,24 @@ function regexFromString(input) {
} }
// Parent function to fetch a regexed version of a raw string // Parent function to fetch a regexed version of a raw string
function getRegexedString(rawString, placement, { characterOverride, isMarkdown } = {}) { function getRegexedString(rawString, placement, { characterOverride, isMarkdown, isPrompt } = {}) {
let finalString = rawString; let finalString = rawString;
if (extension_settings.disabledExtensions.includes("regex") || !rawString || placement === undefined) { if (extension_settings.disabledExtensions.includes("regex") || !rawString || placement === undefined) {
return finalString; return finalString;
} }
extension_settings.regex.forEach((script) => { extension_settings.regex.forEach((script) => {
if ((script.markdownOnly && !isMarkdown) || (!script.markdownOnly && isMarkdown)) { if (
return; // Script applies to Markdown and input is Markdown
} (script.markdownOnly && isMarkdown) ||
// Script applies to Generate and input is Generate
if (script.placement.includes(placement)) { (script.promptOnly && isPrompt) ||
finalString = runRegexScript(script, finalString, { characterOverride }); // Script applies to all cases when neither "only"s are true, but there's no need to do it when `isMarkdown`, the as source (chat history) should already be changed beforehand
(!script.markdownOnly && !script.promptOnly && !isMarkdown)
) {
if (script.placement.includes(placement)) {
finalString = runRegexScript(script, finalString, { characterOverride });
}
} }
}); });
@ -91,7 +96,7 @@ function runRegexScript(regexScript, rawString, { characterOverride } = {}) {
const subReplaceString = substituteRegexParams( const subReplaceString = substituteRegexParams(
regexScript.replaceString, regexScript.replaceString,
trimCapturedMatch ?? trimFencedMatch, trimCapturedMatch ?? trimFencedMatch,
{ {
characterOverride, characterOverride,
replaceStrategy: regexScript.replaceStrategy ?? regex_replace_strategy.REPLACE replaceStrategy: regexScript.replaceStrategy ?? regex_replace_strategy.REPLACE
} }

View File

@ -113,6 +113,9 @@ async function onRegexEditorOpenClick(existingId) {
editorHtml editorHtml
.find(`input[name="only_format_display"]`) .find(`input[name="only_format_display"]`)
.prop("checked", existingScript.markdownOnly ?? false); .prop("checked", existingScript.markdownOnly ?? false);
editorHtml
.find(`input[name="only_format_prompt"]`)
.prop("checked", existingScript.promptOnly ?? false);
editorHtml editorHtml
.find(`input[name="run_on_edit"]`) .find(`input[name="run_on_edit"]`)
.prop("checked", existingScript.runOnEdit ?? false); .prop("checked", existingScript.runOnEdit ?? false);
@ -165,6 +168,10 @@ async function onRegexEditorOpenClick(existingId) {
editorHtml editorHtml
.find(`input[name="only_format_display"]`) .find(`input[name="only_format_display"]`)
.prop("checked"), .prop("checked"),
promptOnly:
editorHtml
.find(`input[name="only_format_prompt"]`)
.prop("checked"),
runOnEdit: runOnEdit:
editorHtml editorHtml
.find(`input[name="run_on_edit"]`) .find(`input[name="run_on_edit"]`)
@ -197,6 +204,7 @@ function migrateSettings() {
script.placement = script.placement.filter((e) => e !== regex_placement.MD_DISPLAY); script.placement = script.placement.filter((e) => e !== regex_placement.MD_DISPLAY);
script.markdownOnly = true script.markdownOnly = true
script.promptOnly = true
performSave = true; performSave = true;
} }