Merge branch 'staging' into pollinations

This commit is contained in:
Cohee 2024-04-10 21:14:36 +03:00
commit c90105e9f6
64 changed files with 1871 additions and 815 deletions

View File

@ -69,16 +69,16 @@ body:
required: false required: false
- type: checkboxes - type: checkboxes
id: idiot-check id: user-check
attributes: attributes:
label: Please tick the boxes label: Please tick the boxes
description: Before submitting, please ensure that description: Before submitting, please ensure that you have completed the following checklist
options: options:
- label: You have explained the issue clearly, and included all relevant info - label: I have explained the issue clearly, and I included all relevant info
required: true required: true
- label: You've checked that this [issue hasn't already been raised](https://github.com/SillyTavern/SillyTavern/issues?q=is%3Aissue) - label: I have checked that this [issue hasn't already been raised](https://github.com/SillyTavern/SillyTavern/issues?q=is%3Aissue)
required: true required: true
- label: You've checked the [docs](https://docs.sillytavern.app/) ![important](https://img.shields.io/badge/Important!-F6094E) - label: I have checked the [docs](https://docs.sillytavern.app/) ![important](https://img.shields.io/badge/Important!-F6094E)
required: true required: true
- type: markdown - type: markdown

View File

@ -15,7 +15,7 @@ body:
- 'No' - 'No'
- 'Yes' - 'Yes'
validations: validations:
required: false required: true
# Field 2 - Is it bug-related # Field 2 - Is it bug-related
- type: textarea - type: textarea
@ -67,16 +67,16 @@ body:
validations: validations:
required: true required: true
# Field 7 - Can the user implement # Field 7 - Can the user user test in staging
- type: dropdown - type: dropdown
id: canImplement id: canTestStaging
attributes: attributes:
label: Is this something you would be keen to implement? label: Are you willing to test this on staging/unstable branch if this is implemented?
description: Are you raising this ticket in order to get an issue number for your PR? description: Otherwise you'll need to wait until the next stable release after the feature is developed.
options: options:
- 'No' - 'No'
- 'Maybe' - 'Maybe'
- 'Yes!' - 'Yes'
validations: validations:
required: false required: false

143
.github/readme.md vendored
View File

@ -1,6 +1,8 @@
<a name="readme-top"></a>
English | [中文](readme-zh_cn.md) | [日本語](readme-ja_jp.md) English | [中文](readme-zh_cn.md) | [日本語](readme-ja_jp.md)
![SillyTavern-Banner](https://github.com/SillyTavern/SillyTavern/assets/18619528/c2be4c3f-aada-4f64-87a3-ae35a68b61a4) ![][cover]
Mobile-friendly layout, Multi-API (KoboldAI/CPP, Horde, NovelAI, Ooba, OpenAI, OpenRouter, Claude, Scale), VN-like Waifu Mode, Stable Diffusion, TTS, WorldInfo (lorebooks), customizable UI, auto-translate, and more prompt options than you'd ever want or need + ability to install third-party extensions. Mobile-friendly layout, Multi-API (KoboldAI/CPP, Horde, NovelAI, Ooba, OpenAI, OpenRouter, Claude, Scale), VN-like Waifu Mode, Stable Diffusion, TTS, WorldInfo (lorebooks), customizable UI, auto-translate, and more prompt options than you'd ever want or need + ability to install third-party extensions.
@ -22,6 +24,11 @@ SillyTavern is a user interface you can install on your computer (and Android ph
SillyTavern is a fork of TavernAI 1.2.8 which is under more active development and has added many major features. At this point, they can be thought of as completely independent programs. SillyTavern is a fork of TavernAI 1.2.8 which is under more active development and has added many major features. At this point, they can be thought of as completely independent programs.
## Screenshots
<img width="400" alt="image" src="https://github.com/SillyTavern/SillyTavern/assets/61471128/e902c7a2-45a6-4415-97aa-c59c597669c1">
<img width="400" alt="image" src="https://github.com/SillyTavern/SillyTavern/assets/61471128/f8a79c47-4fe9-4564-9e4a-bf247ed1c961">
### Branches ### Branches
SillyTavern is being developed using a two-branch system to ensure a smooth experience for all users. SillyTavern is being developed using a two-branch system to ensure a smooth experience for all users.
@ -31,36 +38,25 @@ SillyTavern is being developed using a two-branch system to ensure a smooth expe
If you're not familiar with using the git CLI or don't understand what a branch is, don't worry! The release branch is always the preferable option for you. If you're not familiar with using the git CLI or don't understand what a branch is, don't worry! The release branch is always the preferable option for you.
### What do I need other than Tavern? ### What do I need other than SillyTavern?
On its own Tavern is useless, as it's just a user interface. You have to have access to an AI system backend that can act as the roleplay character. There are various supported backends: OpenAPI API (GPT), KoboldAI (either running locally or on Google Colab), and more. You can read more about this in [the FAQ](https://docs.sillytavern.app/usage/faq/). On its own SillyTavern is useless, as it's just a user interface. You have to have access to an AI system backend that can act as the roleplay character. There are various supported backends: OpenAPI API (GPT), KoboldAI (either running locally or on Google Colab), and more. You can read more about this in [the FAQ](https://docs.sillytavern.app/usage/faq/).
### Do I need a powerful PC to run Tavern? ### Do I need a powerful PC to run SillyTavern?
Since Tavern is only a user interface, it has tiny hardware requirements, it will run on anything. It's the AI system backend that needs to be powerful. Since SillyTavern is only a user interface, it has tiny hardware requirements, it will run on anything. It's the AI system backend that needs to be powerful.
## Mobile support
> **Note**
> **This fork can be run natively on Android phones using Termux. Please refer to this guide by ArroganceComplex#2659:**
<https://rentry.org/STAI-Termux>
## Questions or suggestions? ## Questions or suggestions?
### We now have a community Discord server ### We now have a community Discord server
Get support, share favorite characters and prompts: | [![][discord-shield-badge]][discord-link] | [Join our Discord community!](https://discord.gg/sillytavern) Get support, share favorite characters and prompts. |
| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
### [Join](https://discord.gg/sillytavern) Or get in touch with the developers directly:
***
Get in touch with the developers directly:
* Discord: cohee or rossascends * Discord: cohee or rossascends
* Reddit: /u/RossAscends or /u/sillylossy * Reddit: [/u/RossAscends](https://www.reddit.com/user/RossAscends/) or [/u/sillylossy](https://www.reddit.com/user/sillylossy/)
* [Post a GitHub issue](https://github.com/SillyTavern/SillyTavern/issues) * [Post a GitHub issue](https://github.com/SillyTavern/SillyTavern/issues)
## This version includes ## This version includes
@ -124,61 +120,88 @@ A full list of included extensions and tutorials on how to use them can be found
* Customizable page colors for 'main text', 'quoted text', and 'italics text'. * Customizable page colors for 'main text', 'quoted text', and 'italics text'.
* Customizable UI background color and blur amount * Customizable UI background color and blur amount
## Installation # Installation
*NOTE: This software is intended for local install purposes, and has not been thoroughly tested on a colab or other cloud notebook service.* > \[!WARNING]
> * DO NOT INSTALL INTO ANY WINDOWS CONTROLLED FOLDER (Program Files, System32, etc).
> * DO NOT RUN START.BAT WITH ADMIN PERMISSIONS
> * INSTALLATION ON WINDOWS 7 IS IMPOSSIBLE AS IT CAN NOT RUN NODEJS 18.16
> **Warning** ## 🪟 Windows
> DO NOT INSTALL INTO ANY WINDOWS CONTROLLED FOLDER (Program Files, System32, etc).
> DO NOT RUN START.BAT WITH ADMIN PERMISSIONS
### Windows
Installing via Git (recommended for easy updating)
An easy-to-follow guide with pretty pictures:
<https://docs.sillytavern.app/installation/windows/>
## Installing via Git
1. Install [NodeJS](https://nodejs.org/en) (latest LTS version is recommended) 1. Install [NodeJS](https://nodejs.org/en) (latest LTS version is recommended)
2. Install [GitHub Desktop](https://central.github.com/deployments/desktop/desktop/latest/win32) 2. Install [Git for Windows](https://gitforwindows.org/)
3. Open Windows Explorer (`Win+E`) 3. Open Windows Explorer (`Win+E`)
4. Browse to or Create a folder that is not controlled or monitored by Windows. (ex: C:\MySpecialFolder\) 4. Browse to or Create a folder that is not controlled or monitored by Windows. (ex: C:\MySpecialFolder\)
5. Open a Command Prompt inside that folder by clicking in the 'Address Bar' at the top, typing `cmd`, and pressing Enter. 5. Open a Command Prompt inside that folder by clicking in the 'Address Bar' at the top, typing `cmd`, and pressing Enter.
6. Once the black box (Command Prompt) pops up, type ONE of the following into it and press Enter: 6. Once the black box (Command Prompt) pops up, type ONE of the following into it and press Enter:
* for Release Branch: `git clone https://github.com/SillyTavern/SillyTavern -b release` - for Release Branch: `git clone https://github.com/SillyTavern/SillyTavern -b release`
* for Staging Branch: `git clone https://github.com/SillyTavern/SillyTavern -b staging` - for Staging Branch: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
7. Once everything is cloned, double-click `Start.bat` to make NodeJS install its requirements. 7. Once everything is cloned, double-click `Start.bat` to make NodeJS install its requirements.
8. The server will then start, and SillyTavern will pop up in your browser. 8. The server will then start, and SillyTavern will pop up in your browser.
Installing via ZIP download (discouraged) ## Installing via SillyTavern Launcher
1. Install [Git for Windows](https://gitforwindows.org/)
2. Open Windows Explorer (`Win+E`) and make or choose a folder where you wanna install the launcher to
3. Open a Command Prompt inside that folder by clicking in the 'Address Bar' at the top, typing `cmd`, and pressing Enter.
4. When you see a black box, insert the following command: `git clone https://github.com/SillyTavern/SillyTavern-Launcher.git`
5. Double-click on `installer.bat` and choose what you wanna install
6. After installation double-click on `launcher.bat`
## Installing via GitHub Desktop
(This allows git usage **only** in GitHub Desktop, if you want to use `git` on the command line too, you also need to install [Git for Windows](https://gitforwindows.org/))
1. Install [NodeJS](https://nodejs.org/en) (latest LTS version is recommended) 1. Install [NodeJS](https://nodejs.org/en) (latest LTS version is recommended)
2. Download the zip from this GitHub repo. (Get the `Source code (zip)` from [Releases](https://github.com/SillyTavern/SillyTavern/releases/latest)) 2. Install [GitHub Desktop](https://central.github.com/deployments/desktop/desktop/latest/win32)
3. Unzip it into a folder of your choice 3. After installing GitHub Desktop, click on `Clone a repository from the internet....` (Note: You **do NOT need** to create a GitHub account for this step)
4. Run `Start.bat` by double-clicking or in a command line. 4. On the menu, click the URL tab, enter this URL `https://github.com/SillyTavern/SillyTavern`, and click Clone. You can change the Local path to change where SillyTavern is going to be downloaded.
5. Once the server has prepared everything for you, it will open a tab in your browser. 6. To open SillyTavern, use Windows Explorer to browse into the folder where you cloned the repository. By default, the repository will be cloned here: `C:\Users\[Your Windows Username]\Documents\GitHub\SillyTavern`
7. Double-click on the `start.bat` file. (Note: the `.bat` part of the file name might be hidden by your OS, in that case, it will look like a file called "`Start`". This is what you double-click to run SillyTavern)
8. After double-clicking, a large black command console window should open and SillyTavern will begin to install what it needs to operate.
9. After the installation process, if everything is working, the command console window should look like this and a SillyTavern tab should be open in your browser:
10. Connect to any of the [supported APIs](https://docs.sillytavern.app/usage/api-connections/) and start chatting!
### Linux ## 🐧 Linux & 🍎 MacOS
#### Unofficial Debian/Ubuntu PKGBUILD For MacOS / Linux all of these will be done in a Terminal.
> **This installation method is unofficial and not supported by the project. Report any issues to the PKGBUILD maintainer.** 1. Install git and nodeJS (the method for doing this will vary depending on your OS)
> The method is intended for Debian-based distributions (Ubuntu, Mint, etc). 2. Clone the repo
1. Install [makedeb](https://www.makedeb.org/). - for Release Branch: `git clone https://github.com/SillyTavern/SillyTavern -b release`
2. Ensure you have Node.js v18 or higher installed by running `node -v`. If you need to upgrade, you can install a [node.js repo](https://mpr.makedeb.org/packages/nodejs-repo) (you'll might need to edit the version inside the PKGBUILD). As an alternative, install and configure [nvm](https://mpr.makedeb.org/packages/nvm) to manage multiple node.js installations. Finally, you can [install node.js manually](https://nodejs.org/en/download), but you will need to update the PATH variable of your environment. - for Staging Branch: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
3. Now build the [sillytavern package](https://mpr.makedeb.org/packages/sillytavern). The build needs to run with the correct node.js version.
#### Manual 3. `cd SillyTavern` to navigate into the install folder.
4. Run the `start.sh` script with one of these commands:
- `./start.sh`
- `bash start.sh`
## Installing via SillyTavern Launcher
### For Linux users
1. Open your favorite terminal and install git
2. Download Sillytavern Launcher with: `git clone https://github.com/SillyTavern/SillyTavern-Launcher.git`
3. Navigate to the SillyTavern-Launcher with: `cd SillyTavern-Launcher`
4. Start the install launcher with: `chmod +x install.sh && ./install.sh` and choose what you wanna install
5. After installation start the launcher with: `chmod +x launcher.sh && ./launcher.sh`
### For Mac users
1. Open a terminal and install brew with: `/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`
2. Then install git with: `brew install git`
3. Download Sillytavern Launcher with: `git clone https://github.com/SillyTavern/SillyTavern-Launcher.git`
4. Navigate to the SillyTavern-Launcher with: `cd SillyTavern-Launcher`
5. Start the install launcher with: `chmod +x install.sh && ./install.sh` and choose what you wanna install
6. After installation start the launcher with: `chmod +x launcher.sh && ./launcher.sh`
## 📱 Mobile - Installing via termux
> \[!NOTE]
> **SillyTavern can be run natively on Android phones using Termux. Please refer to this guide by ArroganceComplex#2659:**
> * <https://rentry.org/STAI-Termux>
1. Ensure you have Node.js v18 or higher (the latest [LTS version](https://nodejs.org/en/download/) is recommended) installed by running `node -v`.
Alternatively, use the [Node Version Manager](https://github.com/nvm-sh/nvm#installing-and-updating) script to quickly and easily manage your Node installations.
2. Run the `start.sh` script.
3. Enjoy.
## API keys management ## API keys management
@ -222,7 +245,7 @@ or
CIDR masks are also accepted (eg. 10.0.0.0/24). CIDR masks are also accepted (eg. 10.0.0.0/24).
* Save the `whitelist.txt` file. * Save the `whitelist.txt` file.
* Restart your TAI server. * Restart your ST server.
Now devices which have the IP specified in the file will be able to connect. Now devices which have the IP specified in the file will be able to connect.
@ -293,10 +316,7 @@ You can find them archived here:
<https://files.catbox.moe/1xevnc.zip> <https://files.catbox.moe/1xevnc.zip>
## Screenshots
<img width="400" alt="image" src="https://github.com/SillyTavern/SillyTavern/assets/61471128/e902c7a2-45a6-4415-97aa-c59c597669c1">
<img width="400" alt="image" src="https://github.com/SillyTavern/SillyTavern/assets/61471128/f8a79c47-4fe9-4564-9e4a-bf247ed1c961">
## License and credits ## License and credits
@ -327,3 +347,10 @@ GNU Affero General Public License for more details.**
* Korean translation by @doloroushyeonse * Korean translation by @doloroushyeonse
* k_euler_a support for Horde by <https://github.com/Teashrock> * k_euler_a support for Horde by <https://github.com/Teashrock>
* Chinese translation by [@XXpE3](https://github.com/XXpE3), 中文 ISSUES 可以联系 @XXpE3 * Chinese translation by [@XXpE3](https://github.com/XXpE3), 中文 ISSUES 可以联系 @XXpE3
<!-- LINK GROUP -->
[back-to-top]: https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square
[cover]: https://github.com/SillyTavern/SillyTavern/assets/18619528/c2be4c3f-aada-4f64-87a3-ae35a68b61a4
[discord-link]: https://discord.gg/sillytavern
[discord-shield]: https://img.shields.io/discord/1100685673633153084?color=5865F2&label=discord&labelColor=black&logo=discord&logoColor=white&style=flat-square
[discord-shield-badge]: https://img.shields.io/discord/1100685673633153084?color=5865F2&label=discord&labelColor=black&logo=discord&logoColor=white&style=for-the-badge

View File

@ -1,45 +1,78 @@
# This workflow will publish a docker image for every full release to the GitHub package repository # This workflow will publish a docker image for every full release to the GitHub package repository
name: Create Docker Image on Release name: Create Docker Image (Release and Staging)
on: on:
release: release:
# Allow pre-releases # Allow pre-releases
types: [published] types: [published]
schedule:
# Build the staging image everyday at 00:00 UTC
- cron: "0 0 * * *"
env: env:
# This should allow creation of docker images even in forked repositories # This should allow creation of docker images even in forked repositories
# Image name may not contain uppercase characters, so we can not use the repository name IMAGE_NAME: ${{ github.repository }}
# Creates a string like: ghcr.io/SillyTavern/sillytavern REGISTRY: ghcr.io
image_name: ghcr.io/sillytavern/sillytavern
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout # Using the following workaround because currently GitHub Actions
# does not support logical AND/OR operations on triggers
# It's currently not possible to have `branches` under the `schedule` trigger
- name: Checkout the release branch
if: ${{ github.event_name == 'release' }}
uses: actions/checkout@v3 uses: actions/checkout@v3
with:
ref: "release"
# Build docker image using dockerfile and tag it with branch name - name: Checkout the staging branch
# Assumes branch name is the version number if: ${{ github.event_name == 'schedule' }}
- name: Build the Docker image uses: actions/checkout@v3
run: | with:
docker build . --file Dockerfile --tag $image_name:${{ github.ref_name }} ref: "staging"
# Setting up QEMU for multi-arch image build
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Extract metadata (tags, labels) for the image
uses: docker/metadata-action@v5.5.1
id: metadata
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: ${{ github.ref_name }}
# Login into package repository as the person who created the release # Login into package repository as the person who created the release
- name: Login to GitHub Container Registry - name: Log in to the Container registry
uses: docker/login-action@v1 uses: docker/login-action@v3
with: with:
registry: ghcr.io registry: ${{ env.REGISTRY }}
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
# Assumes release is the latest and marks image as such # Build docker image using dockerfile for amd64 and arm64
- name: Docker Tag and Push # Tag it with branch name
# Assumes branch name is the version number
- name: Build and push
uses: docker/build-push-action@v5.3.0
with:
context: .
platforms: linux/amd64,linux/arm64
file: Dockerfile
push: true
tags: ${{ steps.metadata.outputs.tags }}
labels: ${{ steps.metadata.outputs.labels }}
# If the workflow is triggered by a release, marks and push the image as such
- name: Docker tag latest and push
if: ${{ github.event_name == 'release' }}
run: | run: |
docker tag $image_name:${{ github.ref_name }} $image_name:latest docker tag $IMAGE_NAME:${{ github.ref_name }} $IMAGE_NAME:latest
docker push $image_name:${{ github.ref_name }} docker push $IMAGE_NAME:latest
docker push $image_name:latest

1
.gitignore vendored
View File

@ -45,3 +45,4 @@ access.log
/cache/ /cache/
public/css/user.css public/css/user.css
/plugins/ /plugins/
/data

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "Adventure" "name": "Adventure"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "\n\n", "system_suffix": "\n\n",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "Alpaca-Roleplay" "name": "Alpaca-Roleplay"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "Alpaca-Single-Turn" "name": "Alpaca-Single-Turn"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "\n\n", "system_suffix": "\n\n",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "Alpaca" "name": "Alpaca"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "<|im_end|>\n", "system_suffix": "<|im_end|>\n",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "ChatML" "name": "ChatML"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "DreamGen Role-Play V1" "name": "DreamGen Role-Play V1"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "Koala" "name": "Koala"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "Libra-32B" "name": "Libra-32B"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "Lightning 1.1" "name": "Lightning 1.1"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "Let's get started. Please respond based on the information and instructions provided above.", "user_alignment_message": "Let's get started. Please respond based on the information and instructions provided above.",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "Llama 2 Chat" "name": "Llama 2 Chat"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "Metharme" "name": "Metharme"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "Let's get started. Please respond based on the information and instructions provided above.", "user_alignment_message": "Let's get started. Please respond based on the information and instructions provided above.",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "Mistral" "name": "Mistral"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "OpenOrca-OpenChat" "name": "OpenOrca-OpenChat"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "Pygmalion" "name": "Pygmalion"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "Story" "name": "Story"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "\n", "system_suffix": "\n",
"user_alignment_message": "Let's get started. Please respond based on the information and instructions provided above.", "user_alignment_message": "Let's get started. Please respond based on the information and instructions provided above.",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "Synthia" "name": "Synthia"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "Vicuna 1.0" "name": "Vicuna 1.0"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "Vicuna 1.1" "name": "Vicuna 1.1"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": true, "system_same_as_user": true,
"last_system_sequence": "",
"name": "WizardLM-13B" "name": "WizardLM-13B"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "WizardLM" "name": "WizardLM"
} }

View File

@ -19,5 +19,6 @@
"system_suffix": "", "system_suffix": "",
"user_alignment_message": "", "user_alignment_message": "",
"system_same_as_user": false, "system_same_as_user": false,
"last_system_sequence": "",
"name": "simple-proxy-for-tavern" "name": "simple-proxy-for-tavern"
} }

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "sillytavern", "name": "sillytavern",
"version": "1.11.6", "version": "1.11.7",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "sillytavern", "name": "sillytavern",
"version": "1.11.6", "version": "1.11.7",
"hasInstallScript": true, "hasInstallScript": true,
"license": "AGPL-3.0", "license": "AGPL-3.0",
"dependencies": { "dependencies": {

View File

@ -59,7 +59,7 @@
"type": "git", "type": "git",
"url": "https://github.com/SillyTavern/SillyTavern.git" "url": "https://github.com/SillyTavern/SillyTavern.git"
}, },
"version": "1.11.6", "version": "1.11.7",
"scripts": { "scripts": {
"start": "node server.js", "start": "node server.js",
"start-multi": "node server.js --disableCsrf", "start-multi": "node server.js --disableCsrf",

View File

@ -208,6 +208,7 @@
#cfgConfig, #cfgConfig,
#logprobsViewer, #logprobsViewer,
#movingDivs > div { #movingDivs > div {
/* 100vh are fallback units for browsers that don't support svh */
height: calc(100vh - 45px); height: calc(100vh - 45px);
height: calc(100svh - 45px); height: calc(100svh - 45px);
min-width: 100% !important; min-width: 100% !important;
@ -223,6 +224,10 @@
backdrop-filter: blur(calc(var(--SmartThemeBlurStrength) * 2)); backdrop-filter: blur(calc(var(--SmartThemeBlurStrength) * 2));
} }
#right-nav-panel {
padding-right: 15px;
}
#floatingPrompt, #floatingPrompt,
#cfgConfig, #cfgConfig,
#logprobsViewer, #logprobsViewer,

View File

@ -58,6 +58,11 @@
cursor: unset; cursor: unset;
} }
#rm_group_buttons textarea {
margin: 0px;
min-width: 200px;
}
#rm_group_members, #rm_group_members,
#rm_group_add_members { #rm_group_add_members {
margin-top: 0.25rem; margin-top: 0.25rem;

View File

@ -73,6 +73,11 @@
background: none; background: none;
} }
.tag.placeholder-expander {
cursor: alias;
border: 0;
}
.tagListHint { .tagListHint {
align-self: center; align-self: center;
display: flex; display: flex;
@ -94,7 +99,7 @@
#bulkTagsList, #bulkTagsList,
#tagList.tags { #tagList.tags {
margin: 2px 0; margin: 5px 0;
} }
#bulkTagsList, #bulkTagsList,

View File

@ -2404,16 +2404,20 @@
</optgroup> </optgroup>
<optgroup label="GPT-4"> <optgroup label="GPT-4">
<option value="gpt-4">gpt-4</option> <option value="gpt-4">gpt-4</option>
<option value="gpt-4-turbo-preview">gpt-4-turbo-preview</option>
<option value="gpt-4-vision-preview">gpt-4-vision-preview</option>
<option value="gpt-4-0125-preview">gpt-4-0125-preview (2024)</option>
<option value="gpt-4-1106-preview">gpt-4-1106-preview (2023)</option>
<option value="gpt-4-0613">gpt-4-0613 (2023)</option> <option value="gpt-4-0613">gpt-4-0613 (2023)</option>
<option value="gpt-4-0314">gpt-4-0314 (2023)</option> <option value="gpt-4-0314">gpt-4-0314 (2023)</option>
<option value="gpt-4-32k">gpt-4-32k</option> <option value="gpt-4-32k">gpt-4-32k</option>
<option value="gpt-4-32k-0613">gpt-4-32k-0613 (2023)</option> <option value="gpt-4-32k-0613">gpt-4-32k-0613 (2023)</option>
<option value="gpt-4-32k-0314">gpt-4-32k-0314 (2023)</option> <option value="gpt-4-32k-0314">gpt-4-32k-0314 (2023)</option>
</optgroup> </optgroup>
<optgroup label="GPT-4 Turbo">
<option value="gpt-4-turbo">gpt-4-turbo</option>
<option value="gpt-4-turbo-2024-04-09">gpt-4-turbo-2024-04-09</option>
<option value="gpt-4-turbo-preview">gpt-4-turbo-preview</option>
<option value="gpt-4-vision-preview">gpt-4-vision-preview</option>
<option value="gpt-4-0125-preview">gpt-4-0125-preview (2024)</option>
<option value="gpt-4-1106-preview">gpt-4-1106-preview (2023)</option>
</optgroup>
<optgroup label="Other"> <optgroup label="Other">
<option value="text-davinci-003">text-davinci-003</option> <option value="text-davinci-003">text-davinci-003</option>
<option value="text-davinci-002">text-davinci-002</option> <option value="text-davinci-002">text-davinci-002</option>
@ -2729,6 +2733,11 @@
<div class="flex-container"> <div class="flex-container">
<select id="model_custom_select" class="text_pole"></select> <select id="model_custom_select" class="text_pole"></select>
</div> </div>
<h4 data-i18n="Prompt Post-Processing">Prompt Post-Processing</h4>
<select id="custom_prompt_post_processing" class="text_pole" title="Applies additional processing to the prompt before sending it to the API.">
<option value="">None</option>
<option value="claude">Claude</option>
</select>
</form> </form>
<div class="flex-container flex"> <div class="flex-container flex">
<div id="api_button_openai" class="api_button menu_button menu_button_icon" type="submit" data-i18n="Connect">Connect</div> <div id="api_button_openai" class="api_button menu_button menu_button_icon" type="submit" data-i18n="Connect">Connect</div>
@ -2758,15 +2767,17 @@
<div class="drawer-content"> <div class="drawer-content">
<h3 class="margin0" data-i18n="Advanced Formatting"> <h3 class="margin0" data-i18n="Advanced Formatting">
Advanced Formatting Advanced Formatting
<a href="https://docs.sillytavern.app/usage/core-concepts/advancedformatting/" class="notes-link" target="_blank">
<span class="fa-solid fa-circle-question note-link-span"></span>
</a>
</h3> </h3>
<div class="flex-container"> <div class="flex-container">
<div id="PygOverrides"> <div id="PygOverrides">
<div> <div>
<h4 class="standoutHeader title_restorable"> <h4 class="standoutHeader title_restorable">
<span data-i18n="Context Template">Context Template</span> <div>
<span data-i18n="Context Template">Context Template</span>
<a href="https://docs.sillytavern.app/usage/core-concepts/advancedformatting/#context-template" class="notes-link" target="_blank">
<span class="fa-solid fa-circle-question note-link-span"></span>
</a>
</div>
<div class="flex-container"> <div class="flex-container">
<i data-newbie-hidden data-preset-manager-import="context" class="margin0 menu_button fa-solid fa-file-import" title="Import preset" data-i18n="[title]Import preset"></i> <i data-newbie-hidden data-preset-manager-import="context" class="margin0 menu_button fa-solid fa-file-import" title="Import preset" data-i18n="[title]Import preset"></i>
<i data-newbie-hidden data-preset-manager-export="context" class="margin0 menu_button fa-solid fa-file-export" title="Export preset" data-i18n="[title]Export preset"></i> <i data-newbie-hidden data-preset-manager-export="context" class="margin0 menu_button fa-solid fa-file-export" title="Export preset" data-i18n="[title]Export preset"></i>
@ -3034,12 +3045,12 @@
</div> </div>
</div> </div>
<div class="flex-container"> <div class="flex-container">
<div class="flex1" title="Will be inserted at the start of the chat history if it doesn't start with a User message."> <div class="flex1" title="Will be inserted as a last prompt line when using system/neutral generation.">
<label for="instruct_user_alignment_message"> <label for="instruct_last_system_sequence">
<small data-i18n="User Filler Message">User Filler Message</small> <small data-i18n="System Instruction Prefix">System Instruction Prefix</small>
</label> </label>
<div> <div>
<textarea id="instruct_user_alignment_message" class="text_pole textarea_compact autoSetHeight" maxlength="2000" placeholder="&mdash;" rows="1"></textarea> <textarea id="instruct_last_system_sequence" class="text_pole textarea_compact autoSetHeight" maxlength="2000" placeholder="&mdash;" rows="1"></textarea>
</div> </div>
</div> </div>
<div class="flex1" title="If a stop sequence is generated, everything past it will be removed from the output (inclusive)."> <div class="flex1" title="If a stop sequence is generated, everything past it will be removed from the output (inclusive).">
@ -3051,6 +3062,16 @@
</div> </div>
</div> </div>
</div> </div>
<div class="flex-container">
<div class="flex1" title="Will be inserted at the start of the chat history if it doesn't start with a User message.">
<label for="instruct_user_alignment_message">
<small data-i18n="User Filler Message">User Filler Message</small>
</label>
<div>
<textarea id="instruct_user_alignment_message" class="text_pole textarea_compact autoSetHeight" maxlength="2000" placeholder="&mdash;" rows="1"></textarea>
</div>
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -4138,7 +4159,7 @@
<div class="right_menu_button fa-solid fa-list-ul" id="rm_button_characters" title="Select/Create Characters" data-i18n="[title]Select/Create Characters"></div> <div class="right_menu_button fa-solid fa-list-ul" id="rm_button_characters" title="Select/Create Characters" data-i18n="[title]Select/Create Characters"></div>
</div> </div>
<div id="HotSwapWrapper" class="alignitemscenter flex-container margin0auto wide100p"> <div id="HotSwapWrapper" class="alignitemscenter flex-container margin0auto wide100p">
<div class="hotswap avatars_inline flex-container"></div> <div class="hotswap avatars_inline flex-container expander"></div>
</div> </div>
</div> </div>
<hr> <hr>
@ -4175,76 +4196,74 @@
Tokens: <span data-token-counter="character_name_pole" data-token-permanent="true">counting...</span> Tokens: <span data-token-counter="character_name_pole" data-token-permanent="true">counting...</span>
</div> </div>
</div> </div>
<div id="avatar_div" class="avatar_div alignitemsflexstart justifySpaceBetween flexnowrap flexGap5"> <div class="flex-container flexFlowColumn expander flexNoGap">
<label id="avatar_div_div" class="add_avatar avatar" for="add_avatar_button" title="Click to select a new avatar for this character" data-i18n="[title]Click to select a new avatar for this character"> <div id="avatar_div" class="avatar_div alignitemsflexstart justifySpaceBetween flexnowrap">
<img id="avatar_load_preview" src="img/ai4.png" alt="avatar"> <label id="avatar_div_div" class="add_avatar avatar" for="add_avatar_button" title="Click to select a new avatar for this character" data-i18n="[title]Click to select a new avatar for this character">
<input hidden type="file" id="add_avatar_button" name="avatar" accept="image/*"> <img id="avatar_load_preview" src="img/ai4.png" alt="avatar">
</label> <input hidden type="file" id="add_avatar_button" name="avatar" accept="image/*">
<div class="flex-container flexFlowColumn"> </label>
<div class="flex-container flexFlowColumn"> <div class="flex-container" id="avatar_controls">
<div class="flex-container justifyContentFlexEnd flexFlowColumn"> <div class="form_create_bottom_buttons_block">
<div class="form_create_bottom_buttons_block"> <div id="rm_button_back" class="menu_button fa-solid fa-left-long "></div>
<div id="rm_button_back" class="menu_button fa-solid fa-left-long "></div> <!-- <div id="renameCharButton" class="menu_button fa-solid fa-user-pen" title="Rename Character"></div> -->
<!-- <div id="renameCharButton" class="menu_button fa-solid fa-user-pen" title="Rename Character"></div> --> <div id="favorite_button" class="menu_button fa-solid fa-star" title="Add to Favorites" data-i18n="[title]Add to Favorites"></div>
<div id="favorite_button" class="menu_button fa-solid fa-star" title="Add to Favorites" data-i18n="[title]Add to Favorites"></div> <input type="hidden" id="fav_checkbox" name="fav" />
<input type="hidden" id="fav_checkbox" name="fav" /> <div id="advanced_div" class="menu_button fa-solid fa-book " title="Advanced Definitions" data-i18n="[title]Advanced Definition"></div>
<div id="advanced_div" class="menu_button fa-solid fa-book " title="Advanced Definitions" data-i18n="[title]Advanced Definition"></div> <div id="world_button" class="menu_button fa-solid fa-globe" title="Character Lore" data-i18n="[title]Character Lore"></div>
<div id="world_button" class="menu_button fa-solid fa-globe" title="Character Lore" data-i18n="[title]Character Lore"></div> <div class="chat_lorebook_button menu_button fa-solid fa-passport" title="Chat Lore" data-i18n="[title]Chat Lore"></div>
<div class="chat_lorebook_button menu_button fa-solid fa-passport" title="Chat Lore" data-i18n="[title]Chat Lore"></div> <div id="export_button" class="menu_button fa-solid fa-file-export " title="Export and Download" data-i18n="[title]Export and Download"></div>
<div id="export_button" class="menu_button fa-solid fa-file-export " title="Export and Download" data-i18n="[title]Export and Download"></div> <!-- <div id="set_chat_scenario" class="menu_button fa-solid fa-scroll" title="Set a chat scenario override"></div> -->
<!-- <div id="set_chat_scenario" class="menu_button fa-solid fa-scroll" title="Set a chat scenario override"></div> --> <!-- <div id="set_character_world" class="menu_button fa-solid fa-globe" title="Set a character World Info / Lorebook"></div> -->
<!-- <div id="set_character_world" class="menu_button fa-solid fa-globe" title="Set a character World Info / Lorebook"></div> --> <div id="dupe_button" class="menu_button fa-solid fa-clone " title="Duplicate Character" data-i18n="[title]Duplicate Character"></div>
<div id="dupe_button" class="menu_button fa-solid fa-clone " title="Duplicate Character" data-i18n="[title]Duplicate Character"></div> <label for="create_button" id="create_button_label" class="menu_button fa-solid fa-user-check" title="Create Character" data-i18n="[title]Create Character">
<label for="create_button" id="create_button_label" class="menu_button fa-solid fa-user-check" title="Create Character" data-i18n="[title]Create Character"> <input type="submit" id="create_button" name="create_button">
<input type="submit" id="create_button" name="create_button">
</label>
<div id="delete_button" class="menu_button fa-solid fa-skull " title="Delete Character" data-i18n="[title]Delete Character"></div>
</div>
<label class="flex1" for="char-management-dropdown">
<select id="char-management-dropdown">
<option value="default" disabled selected data-i18n="More...">More...</option>
<option id="set_character_world" data-i18n="Link to World Info">
Link to World Info
</option>
<option id="import_character_info" data-i18n="Import Card Lore">
Import Card Lore
</option>
<option id="set_chat_scenario" data-i18n="Scenario Override">
Scenario Override
</option>
<option id="convert_to_persona" data-i18n="Convert to Persona">
Convert to Persona
</option>
<option id="renameCharButton" data-i18n="Rename">
Rename
</option>
<option id="character_source" data-i18n="Link to Source">
Link to Source
</option>
<option id="replace_update" data-i18n="Replace / Update">
Replace / Update
</option>
<!--<option id="dupe_button">
Duplicate
</option>
<option id="export_button">
Export
</option>
<option id="delete_button">
Delete
</option>-->
</select>
</label> </label>
<div id="delete_button" class="menu_button fa-solid fa-skull " title="Delete Character" data-i18n="[title]Delete Character"></div>
</div> </div>
<div id="tags_div"> <label class="flex1 height100p" for="char-management-dropdown">
<div class="tag_controls"> <select id="char-management-dropdown" class="text_pole">
<input id="tagInput" class="text_pole textarea_compact tag_input wide100p margin0" data-i18n="[placeholder]Search / Create Tags" placeholder="Search / Create tags" maxlength="50" /> <option value="default" disabled selected data-i18n="More...">More...</option>
<div class="tags_view menu_button fa-solid fa-tags" title="View all tags" data-i18n="[title]View all tags"></div> <option id="set_character_world" data-i18n="Link to World Info">
</div> Link to World Info
<div id="tagList" class="tags"></div> </option>
</div> <option id="import_character_info" data-i18n="Import Card Lore">
Import Card Lore
</option>
<option id="set_chat_scenario" data-i18n="Scenario Override">
Scenario Override
</option>
<option id="convert_to_persona" data-i18n="Convert to Persona">
Convert to Persona
</option>
<option id="renameCharButton" data-i18n="Rename">
Rename
</option>
<option id="character_source" data-i18n="Link to Source">
Link to Source
</option>
<option id="replace_update" data-i18n="Replace / Update">
Replace / Update
</option>
<!--<option id="dupe_button">
Duplicate
</option>
<option id="export_button">
Export
</option>
<option id="delete_button">
Delete
</option>-->
</select>
</label>
</div> </div>
</div> </div>
<div id="tags_div">
<div class="tag_controls">
<input id="tagInput" class="text_pole textarea_compact tag_input wide100p margin0" data-i18n="[placeholder]Search / Create Tags" placeholder="Search / Create tags" maxlength="50" />
<div class="tags_view menu_button fa-solid fa-tags" title="View all tags" data-i18n="[title]View all tags"></div>
</div>
<div id="tagList" class="tags"></div>
</div>
</div> </div>
</div> </div>
<hr> <hr>
@ -4258,12 +4277,21 @@
</div> </div>
<div id="descriptionWrapper" class="flex-container flexFlowColumn flex1"> <div id="descriptionWrapper" class="flex-container flexFlowColumn flex1">
<hr> <hr>
<div id="description_div" class="flex-container alignitemscenter"> <div id="description_div" class="title_restorable">
<span data-i18n="Character Description">Description</span> <div class="flex-container alignitemscenter">
<i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="description_textarea" title="Expand the editor"></i> <span data-i18n="Character Description">Description</span>
<a href="https://docs.sillytavern.app/usage/core-concepts/characterdesign/#character-description" class="notes-link" target="_blank"> <i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="description_textarea" title="Expand the editor"></i>
<span class="fa-solid fa-circle-question note-link-span"></span> <a href="https://docs.sillytavern.app/usage/core-concepts/characterdesign/#character-description" class="notes-link" target="_blank">
</a> <span class="fa-solid fa-circle-question note-link-span"></span>
</a>
</div>
<div id="character_open_media_overrides" class="menu_button menu_button_icon open_media_overrides" title="Click to allow/forbid the use of external media for this character." data-i18n="[title]Click to allow/forbid the use of external media for this character.">
<i id="character_media_allowed_icon" class="fa-solid fa-fw fa-link"></i>
<i id="character_media_forbidden_icon" class="fa-solid fa-fw fa-link-slash"></i>
<span data-i18n="Ext. Media">
Ext. Media
</span>
</div>
</div> </div>
<textarea id="description_textarea" data-i18n="[placeholder]Describe your character's physical and mental traits here." placeholder="Describe your character's physical and mental traits here." name="description" placeholder=""></textarea> <textarea id="description_textarea" data-i18n="[placeholder]Describe your character's physical and mental traits here." placeholder="Describe your character's physical and mental traits here." name="description" placeholder=""></textarea>
<div class="extension_token_counter"> <div class="extension_token_counter">
@ -4339,30 +4367,54 @@
</div> </div>
<div name="GroupStragegyAndOrder" id="rm_group_buttons" class="flex-container paddingLeftRight5 flex2"> <div name="GroupStragegyAndOrder" id="rm_group_buttons" class="flex-container paddingLeftRight5 flex2">
<div class="flex1 flexGap5"> <div class="flex1 flexGap5">
<div class="flex-container flexnowrap width100p whitespacenowrap"> <label for="rm_group_activation_strategy" class="flexnowrap width100p whitespacenowrap">
<span data-i18n="Group reply strategy">Group reply strategy</span> <span data-i18n="Group reply strategy">Group reply strategy</span>
</div> </label>
<select id="rm_group_activation_strategy"> <select id="rm_group_activation_strategy">
<option value="0" data-i18n="Natural order">Natural order</option> <option value="0" data-i18n="Natural order">Natural order</option>
<option value="1" data-i18n="List order">List order</option> <option value="1" data-i18n="List order">List order</option>
</select> </select>
</div> </div>
<div class="flex1 flexGap5"> <div class="flex1 flexGap5">
<div class="flex-container flexnowrap width100p whitespacenowrap"> <label for="rm_group_generation_mode" class="flexnowrap width100p whitespacenowrap">
<span data-i18n="Group generation handling mode">Group generation handling mode</span> <span data-i18n="Group generation handling mode">Group generation handling mode</span>
</div> </label>
<select id="rm_group_generation_mode"> <select id="rm_group_generation_mode">
<option value="0" data-i18n="Swap character cards">Swap character cards</option> <option value="0" data-i18n="Swap character cards">Swap character cards</option>
<option value="1" data-i18n="Join character cards (exclude muted)">Join character cards (exclude muted)</option> <option value="1" data-i18n="Join character cards (exclude muted)">Join character cards (exclude muted)</option>
<option value="2" data-i18n="Join character cards (include muted)">Join character cards (include muted)</option> <option value="2" data-i18n="Join character cards (include muted)">Join character cards (include muted)</option>
</select> </select>
</div> </div>
<div class="flex1 flexGap5" title="Inserted before each part of the joined fields.">
<label for="rm_group_generation_mode_join_prefix" class="flexnowrap width100p whitespacenowrap">
<span data-i18n="Join Prefix">Join Prefix</span>
<div class="fa-solid fa-circle-info opacity50p"
data-i18n="[title]When 'Join character cards' is selected, all respective fields of the characters are being joined together.&#13;This means that in the story string for example all character descriptions will be joined to one big text.&#13;If you want those fields to be separated, you can define a prefix or suffix here.&#13;&#13;This value supports normal macros and will also replace {{char}} with the relevant char's name and &lt;FIELDNAME&gt; with the name of the part (e.g.: description, personality, scenario, etc.)"
title="When 'Join character cards' is selected, all respective fields of the characters are being joined together.&#13;This means that in the story string for example all character descriptions will be joined to one big text.&#13;If you want those fields to be separated, you can define a prefix or suffix here.&#13;&#13;This value supports normal macros and will also replace {{char}} with the relevant char's name and &lt;FIELDNAME&gt; with the name of the part (e.g.: description, personality, scenario, etc.)">
</div>
</label>
<textarea id="rm_group_generation_mode_join_prefix" class="text_pole wide100p textarea_compact autoSetHeight" maxlength="2000" placeholder="&mdash;" rows="1"></textarea>
</div>
<div class="flex1 flexGap5" title="Inserted after each part of the joined fields.">
<label for="rm_group_generation_mode_join_suffix" class="flexnowrap width100p whitespacenowrap">
<span data-i18n="Join Suffix">Join Suffix</span>
<div class="fa-solid fa-circle-info opacity50p"
data-i18n="[title]When 'Join character cards' is selected, all respective fields of the characters are being joined together.&#13;This means that in the story string for example all character descriptions will be joined to one big text.&#13;If you want those fields to be separated, you can define a prefix or suffix here.&#13;&#13;This value supports normal macros and will also replace {{char}} with the relevant char's name and &lt;FIELDNAME&gt; with the name of the part (e.g.: description, personality, scenario, etc.)"
title="When 'Join character cards' is selected, all respective fields of the characters are being joined together.&#13;This means that in the story string for example all character descriptions will be joined to one big text.&#13;If you want those fields to be separated, you can define a prefix or suffix here.&#13;&#13;This value supports normal macros and will also replace {{char}} with the relevant char's name and &lt;FIELDNAME&gt; with the name of the part (e.g.: description, personality, scenario, etc.)">
</div>
</label>
<textarea id="rm_group_generation_mode_join_suffix" class="text_pole wide100p textarea_compact autoSetHeight" maxlength="2000" placeholder="&mdash;" rows="1"></textarea>
</div>
</div> </div>
<div id="GroupFavDelOkBack" class="flex-container flexGap5 spaceEvenly flex1"> <div id="GroupFavDelOkBack" class="flex-container flexGap5 spaceEvenly flex1">
<div id="rm_button_back_from_group" class="heightFitContent margin0 menu_button fa-solid fa-left-long"></div> <div id="rm_button_back_from_group" class="heightFitContent margin0 menu_button fa-solid fa-left-long"></div>
<div id="rm_group_scenario" class="heightFitContent margin0 menu_button fa-solid fa-scroll" title="Set a group chat scenario" data-i18n="[title]Set a group chat scenario"></div> <div id="rm_group_scenario" class="heightFitContent margin0 menu_button fa-solid fa-scroll" title="Set a group chat scenario" data-i18n="[title]Set a group chat scenario"></div>
<div id="group_favorite_button" class="heightFitContent margin0 menu_button fa-solid fa-star" title="Add to Favorites" data-i18n="[title]Add to Favorites"></div> <div id="group_favorite_button" class="heightFitContent margin0 menu_button fa-solid fa-star" title="Add to Favorites" data-i18n="[title]Add to Favorites"></div>
<input id="rm_group_fav" type="hidden" /> <input id="rm_group_fav" type="hidden" />
<div id="group_open_media_overrides" class="heightFitContent margin0 menu_button menu_button_icon open_media_overrides" title="Click to allow/forbid the use of external media for this group." data-i18n="[title]Click to allow/forbid the use of external media for this group.">
<i id="group_media_allowed_icon" class="fa-solid fa-fw fa-link"></i>
<i id="group_media_forbidden_icon" class="fa-solid fa-fw fa-link-slash"></i>
</div>
<div id="rm_group_submit" class="heightFitContent margin0 menu_button fa-solid fa-check" title="Create" data-i18n="[title]Create"></div> <div id="rm_group_submit" class="heightFitContent margin0 menu_button fa-solid fa-check" title="Create" data-i18n="[title]Create"></div>
<div id="rm_group_restore_avatar" class="heightFitContent margin0 menu_button fa-solid fa-images" title="Restore collage avatar" data-i18n="[title]Restore collage avatar"></div> <div id="rm_group_restore_avatar" class="heightFitContent margin0 menu_button fa-solid fa-images" title="Restore collage avatar" data-i18n="[title]Restore collage avatar"></div>
<div id="rm_group_delete" class="heightFitContent margin0 menu_button fa-solid fa-trash-can" title="Delete" data-i18n="[title]Delete"></div> <div id="rm_group_delete" class="heightFitContent margin0 menu_button fa-solid fa-trash-can" title="Delete" data-i18n="[title]Delete"></div>
@ -4466,6 +4518,22 @@
</div> </div>
</div> </div>
<!-- various fullscreen popups --> <!-- various fullscreen popups -->
<template id="shadow_popup_template">
<div class="shadow_popup">
<div class="dialogue_popup">
<div class="dialogue_popup_holder">
<div class="dialogue_popup_text">
<h3 class="margin0">text</h3>
</div>
<textarea class="dialogue_popup_input text_pole" rows="1"></textarea>
<div class="dialogue_popup_controls">
<div class="dialogue_popup_ok menu_button" data-i18n="Delete">Delete</div>
<div class="dialogue_popup_cancel menu_button" data-i18n="Cancel">Cancel</div>
</div>
</div>
</div>
</div>
</template>
<div id="shadow_popup"> <div id="shadow_popup">
<div id="dialogue_popup"> <div id="dialogue_popup">
<div id="dialogue_popup_holder"> <div id="dialogue_popup_holder">
@ -4815,7 +4883,7 @@
<div class="flex-container alignitemscenter wide100p"> <div class="flex-container alignitemscenter wide100p">
<div class="WIEntryTitleAndStatus flex-container flex1 alignitemscenter"> <div class="WIEntryTitleAndStatus flex-container flex1 alignitemscenter">
<div class="flex-container flex1"> <div class="flex-container flex1">
<textarea class="text_pole autoSetHeight" name="comment" maxlength="5000" data-i18n="[placeholder]Entry Title/Memo" placeholder="Entry Title/Memo"></textarea> <textarea class="text_pole" rows="1" name="comment" maxlength="5000" data-i18n="[placeholder]Entry Title/Memo" placeholder="Entry Title/Memo"></textarea>
</div> </div>
<!-- <span class="world_entry_form_position_value"></span> --> <!-- <span class="world_entry_form_position_value"></span> -->
<select data-i18n="[title]WI Entry Status:🔵 Constant🟢 Normal❌ Disabled" title="WI Entry Status:&#13;🔵 Constant&#13;🟢 Normal&#13;❌ Disabled" name="entryStateSelector" class="text_pole widthNatural margin0"> <select data-i18n="[title]WI Entry Status:🔵 Constant🟢 Normal❌ Disabled" title="WI Entry Status:&#13;🔵 Constant&#13;🟢 Normal&#13;❌ Disabled" name="entryStateSelector" class="text_pole widthNatural margin0">
@ -4931,8 +4999,8 @@
<div class="world_entry_form_control flex1"> <div class="world_entry_form_control flex1">
<label for="content "> <label for="content ">
<small> <small>
<span data-i18n="Content" class="alignitemscenter flex-container flexnowrap wide100p justifySpaceBetween"> <span class="alignitemscenter flex-container flexnowrap wide100p justifySpaceBetween">
<span class="alignitemscenter flex-container flexNoGap"> <span data-i18n="Content" class="alignitemscenter flex-container flexNoGap">
Content Content
</span> </span>
<span> <span>
@ -5370,6 +5438,32 @@
<textarea name="alternate_greetings" data-i18n="[placeholder](This will be the first message from the character that starts every chat)" placeholder="(This will be the first message from the character that starts every chat)" class="text_pole textarea_compact alternate_greeting_text" maxlength="50000" value="" autocomplete="off" rows="16"></textarea> <textarea name="alternate_greetings" data-i18n="[placeholder](This will be the first message from the character that starts every chat)" placeholder="(This will be the first message from the character that starts every chat)" class="text_pole textarea_compact alternate_greeting_text" maxlength="50000" value="" autocomplete="off" rows="16"></textarea>
</div> </div>
</div> </div>
<div id="forbid_media_override_template" class="template_element">
<div class="forbid_media_override flex-container flexFlowColumn">
<h4 data-i18n="Forbid Media Override explanation" class="margin0">
Ability of the current character/group to use external media in chats.
</h4>
<small data-i18n="Forbid Media Override subtitle" class="marginBot5">
Media: images, videos, audio. External: not hosted on the local server.
</small>
<label class="checkbox_label" for="forbid_media_override_global">
<input type="radio" id="forbid_media_override_global" name="forbid_media_override" />
<span>
<span data-i18n="Use global setting">Use global setting</span>
<b class="forbid_media_global_state_forbidden">(forbidden)</b>
<b class="forbid_media_global_state_allowed">(allowed)</b>
</span>
</label>
<label class="checkbox_label" for="forbid_media_override_forbidden">
<input type="radio" id="forbid_media_override_forbidden" name="forbid_media_override" />
<span data-i18n="Always forbidden">Always forbidden</span>
</label>
<label class="checkbox_label" for="forbid_media_override_allowed">
<input type="radio" id="forbid_media_override_allowed" name="forbid_media_override" />
<span data-i18n="Always allowed">Always allowed</span>
</label>
</div>
</div>
<!-- chat and input bar --> <!-- chat and input bar -->
<div id="typing_indicator_template" class="template_element"> <div id="typing_indicator_template" class="template_element">
<div class="typing_indicator"><span class="typing_indicator_name">CHAR</span> is typing</div> <div class="typing_indicator"><span class="typing_indicator_name">CHAR</span> is typing</div>

View File

@ -5,7 +5,7 @@
"novelaipreserts": "Preajustes de NovelAI", "novelaipreserts": "Preajustes de NovelAI",
"default": "Predeterminado", "default": "Predeterminado",
"openaipresets": "Preajustes de OpenAI", "openaipresets": "Preajustes de OpenAI",
"text gen webio(ooba) presets": "Preajustes de generación de texto WebUI(ooba)", "text gen webio(ooba) presets": "Preajustes de Text Gen WebUI(ooba)",
"response legth(tokens)": "Longitud de respuesta (tokens)", "response legth(tokens)": "Longitud de respuesta (tokens)",
"select": "Seleccionar", "select": "Seleccionar",
"context size(tokens)": "Tamaño de contexto (tokens)", "context size(tokens)": "Tamaño de contexto (tokens)",
@ -13,17 +13,17 @@
"Only select models support context sizes greater than 4096 tokens. Increase only if you know what you're doing.": "Solo algunos modelos admiten tamaños de contexto mayores de 4096 tokens. Aumenta solo si sabes lo que estás haciendo.", "Only select models support context sizes greater than 4096 tokens. Increase only if you know what you're doing.": "Solo algunos modelos admiten tamaños de contexto mayores de 4096 tokens. Aumenta solo si sabes lo que estás haciendo.",
"rep.pen": "Penalización de repetición", "rep.pen": "Penalización de repetición",
"WI Entry Status:🔵 Constant🟢 Normal❌ Disabled": "Estado de entrada de WI:🔵 Constante🟢 Normal❌ Desactivado", "WI Entry Status:🔵 Constant🟢 Normal❌ Disabled": "Estado de entrada de WI:🔵 Constante🟢 Normal❌ Desactivado",
"rep.pen range": "Rango de penalización de repetición", "rep.pen range": "rango de penalización de repetición",
"Temperature controls the randomness in token selection": "La temperatura controla la aleatoriedad en la selección de tokens", "Temperature controls the randomness in token selection": "La temperatura controla la aleatoriedad en la selección de tokens",
"temperature": "Temperatura", "temperature": "Temperatura",
"Top K sets a maximum amount of top tokens that can be chosen from": "Top K establece una cantidad máxima de tokens principales que se pueden elegir", "Top K sets a maximum amount of top tokens that can be chosen from": "Top K establece una cantidad máxima de tokens principales que se pueden elegir",
"Top P (a.k.a. nucleus sampling)": "Top P (también conocido como muestreo de núcleo)", "Top P (a.k.a. nucleus sampling)": "Top P (también conocido como muestreo de núcleo)",
"Typical P Sampling prioritizes tokens based on their deviation from the average entropy of the set": "El muestreo P típico prioriza tokens según su desviación de la entropía promedio del conjunto", "Typical P Sampling prioritizes tokens based on their deviation from the average entropy of the set": "El Muestreo P Típico prioriza tokens según su desviación de la entropía promedio del conjunto",
"Min P sets a base minimum probability": "Min P establece una probabilidad mínima base", "Min P sets a base minimum probability": "Min P establece una probabilidad mínima base",
"Top A sets a threshold for token selection based on the square of the highest token probability": "Top A establece un umbral para la selección de tokens basado en el cuadrado de la probabilidad de token más alta", "Top A sets a threshold for token selection based on the square of the highest token probability": "Top A establece un umbral para la selección de tokens basado en el cuadrado de la probabilidad de token más alta",
"Tail-Free Sampling (TFS)": "Muestreo sin cola (TFS)", "Tail-Free Sampling (TFS)": "Muestreo sin cola (TFS)",
"Epsilon cutoff sets a probability floor below which tokens are excluded from being sampled": "El corte epsilon establece un límite de probabilidad por debajo del cual se excluyen los tokens de ser muestreados", "Epsilon cutoff sets a probability floor below which tokens are excluded from being sampled": "El corte Epsilon establece un límite de probabilidad por debajo del cual se excluyen los tokens de ser muestreados",
"Scale Temperature dynamically per token, based on the variation of probabilities": "Escalas de temperatura dinámicamente por token, basado en la variación de probabilidades", "Scale Temperature dynamically per token, based on the variation of probabilities": "Escala la Temperatura dinámicamente por token, basado en la variación de probabilidades",
"Minimum Temp": "Temperatura mínima", "Minimum Temp": "Temperatura mínima",
"Maximum Temp": "Temperatura máxima", "Maximum Temp": "Temperatura máxima",
"Exponent": "Exponente", "Exponent": "Exponente",
@ -33,11 +33,11 @@
"Variability parameter for Mirostat outputs": "Parámetro de variabilidad para las salidas de Mirostat", "Variability parameter for Mirostat outputs": "Parámetro de variabilidad para las salidas de Mirostat",
"Learning rate of Mirostat": "Tasa de aprendizaje de Mirostat", "Learning rate of Mirostat": "Tasa de aprendizaje de Mirostat",
"Strength of the Contrastive Search regularization term. Set to 0 to disable CS": "Fuerza del término de regularización de la Búsqueda Contrastiva. Establece en 0 para deshabilitar CS.", "Strength of the Contrastive Search regularization term. Set to 0 to disable CS": "Fuerza del término de regularización de la Búsqueda Contrastiva. Establece en 0 para deshabilitar CS.",
"Temperature Last": "Última temperatura", "Temperature Last": "Temperatura de Último",
"Use the temperature sampler last": "Usar el muestreador de temperatura al final", "Use the temperature sampler last": "Usar el muestreador de temperatura al final",
"LLaMA / Mistral / Yi models only": "Solo modelos LLaMA / Mistral / Yi", "LLaMA / Mistral / Yi models only": "Solo modelos LLaMA / Mistral / Yi",
"Example: some text [42, 69, 1337]": "Ejemplo: algún texto [42, 69, 1337]", "Example: some text [42, 69, 1337]": "Ejemplo: algún texto [42, 69, 1337]",
"Classifier Free Guidance. More helpful tip coming soon": "Guía libre de clasificadores. Pronto llegará un consejo más útil", "Classifier Free Guidance. More helpful tip coming soon": "Guía Libre de Clasificadores. Pronto llegará un consejo más útil",
"Scale": "Escala", "Scale": "Escala",
"GBNF Grammar": "Gramática GBNF", "GBNF Grammar": "Gramática GBNF",
"Usage Stats": "Estadísticas de uso", "Usage Stats": "Estadísticas de uso",
@ -74,7 +74,7 @@
"Add BOS Token": "Agregar token BOS", "Add BOS Token": "Agregar token BOS",
"Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative": "Agrega el token BOS al principio de las indicaciones. Desactivar esto puede hacer que las respuestas sean más creativas", "Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative": "Agrega el token BOS al principio de las indicaciones. Desactivar esto puede hacer que las respuestas sean más creativas",
"Ban EOS Token": "Prohibir token EOS", "Ban EOS Token": "Prohibir token EOS",
"Ban the eos_token. This forces the model to never end the generation prematurely": "Prohibir el token eos. Esto obliga al modelo a nunca terminar la generación prematuramente", "Ban the eos_token. This forces the model to never end the generation prematurely": "Prohibir el token EOS. Esto obliga al modelo a nunca terminar la generación prematuramente",
"Skip Special Tokens": "Omitir tokens especiales", "Skip Special Tokens": "Omitir tokens especiales",
"Beam search": "Búsqueda de haz", "Beam search": "Búsqueda de haz",
"Number of Beams": "Número de haces", "Number of Beams": "Número de haces",
@ -83,9 +83,9 @@
"Contrastive search": "Búsqueda contrastiva", "Contrastive search": "Búsqueda contrastiva",
"Penalty Alpha": "Alfa de penalización", "Penalty Alpha": "Alfa de penalización",
"Seed": "Semilla", "Seed": "Semilla",
"Epsilon Cutoff": "Corte epsilon", "Epsilon Cutoff": "Corte Epsilon",
"Eta Cutoff": "Corte eta", "Eta Cutoff": "Corte Eta",
"Negative Prompt": "Indicación negativa", "Negative Prompt": "Indicaciónes negativas",
"Mirostat (mode=1 is only for llama.cpp)": "Mirostat (modo=1 es solo para llama.cpp)", "Mirostat (mode=1 is only for llama.cpp)": "Mirostat (modo=1 es solo para llama.cpp)",
"Mirostat is a thermostat for output perplexity": "Mirostat es un termostato para la perplejidad de salida", "Mirostat is a thermostat for output perplexity": "Mirostat es un termostato para la perplejidad de salida",
"Add text here that would make the AI generate things you don't want in your outputs.": "Agrega aquí texto que haría que la IA genere cosas que no quieres en tus salidas.", "Add text here that would make the AI generate things you don't want in your outputs.": "Agrega aquí texto que haría que la IA genere cosas que no quieres en tus salidas.",
@ -102,32 +102,32 @@
"NSFW Encouraged": "NSFW Alentado", "NSFW Encouraged": "NSFW Alentado",
"Tell the AI that NSFW is allowed.": "Indica a la IA que se permite contenido NSFW.", "Tell the AI that NSFW is allowed.": "Indica a la IA que se permite contenido NSFW.",
"NSFW Prioritized": "NSFW Priorizado", "NSFW Prioritized": "NSFW Priorizado",
"NSFW prompt text goes first in the prompt to emphasize its effect.": "El texto de la indicación NSFW va primero en la indicación para enfatizar su efecto.", "NSFW prompt text goes first in the prompt to emphasize its effect.": "El texto de las indicaciones NSFW va primero en la indicación para enfatizar su efecto.",
"Streaming": "Transmisión", "Streaming": "Transmisión (Streaming)",
"Dynamic Temperature": "Temperatura dinámica", "Dynamic Temperature": "Temperatura dinámica",
"Restore current preset": "Restaurar la configuración actual", "Restore current preset": "Restaurar el preajuste actual",
"Neutralize Samplers": "Neutralizar los muestreadores", "Neutralize Samplers": "Neutralizar muestreadores",
"Text Completion presets": "Preajustes de completado de texto", "Text Completion presets": "Preajustes de Completado de Texto",
"Documentation on sampling parameters": "Documentación sobre parámetros de muestreo", "Documentation on sampling parameters": "Documentación sobre parámetros de muestreo",
"Set all samplers to their neutral/disabled state.": "Establecer todos los muestreadores en su estado neutral/desactivado.", "Set all samplers to their neutral/disabled state.": "Establecer todos los muestreadores en su estado neutral/desactivado.",
"Only enable this if your model supports context sizes greater than 4096 tokens": "Habilita esto solo si tu modelo admite tamaños de contexto mayores de 4096 tokens", "Only enable this if your model supports context sizes greater than 4096 tokens": "Habilita esto solo si tu modelo admite tamaños de contexto mayores de 4096 tokens",
"Display the response bit by bit as it is generated": "Mostrar la respuesta poco a poco según se genera", "Display the response bit by bit as it is generated": "Mostrar la respuesta poco a poco según se genera",
"Generate only one line per request (KoboldAI only, ignored by KoboldCpp).": "Generar solo una línea por solicitud (solo KoboldAI, ignorado por KoboldCpp).", "Generate only one line per request (KoboldAI only, ignored by KoboldCpp).": "Generar solo una línea por solicitud (solo KoboldAI, ignorado por KoboldCpp).",
"Ban the End-of-Sequence (EOS) token (with KoboldCpp, and possibly also other tokens with KoboldAI).": "Prohibir el token Fin-de-secuencia (EOS) (con KoboldCpp, y posiblemente también otros tokens con KoboldAI).", "Ban the End-of-Sequence (EOS) token (with KoboldCpp, and possibly also other tokens with KoboldAI).": "Prohibir el token Fin-de-Secuencia (EOS) (con KoboldCpp, y posiblemente también otros tokens con KoboldAI).",
"Good for story writing, but should not be used for chat and instruct mode.": "Bueno para escribir historias, pero no debería usarse para el modo de chat e instrucción.", "Good for story writing, but should not be used for chat and instruct mode.": "Bueno para escribir historias, pero no debería usarse para el modo de chat e instrucción.",
"Enhance Definitions": "Mejorar Definiciones", "Enhance Definitions": "Mejorar Definiciones",
"Use OAI knowledge base to enhance definitions for public figures and known fictional characters": "Utilizar la base de conocimientos de OAI para mejorar las definiciones de figuras públicas y personajes ficticios conocidos", "Use OAI knowledge base to enhance definitions for public figures and known fictional characters": "Utilizar la base de conocimientos de OAI para mejorar las definiciones de figuras públicas y personajes ficticios conocidos",
"Wrap in Quotes": "Envolver entre comillas", "Wrap in Quotes": "Envolver entre comillas",
"Wrap entire user message in quotes before sending.": "Envolver todo el mensaje del usuario entre comillas antes de enviarlo.", "Wrap entire user message in quotes before sending.": "Envolver todo el mensaje del usuario entre comillas antes de enviarlo.",
"Leave off if you use quotes manually for speech.": "Omite esto si usas comillas manualmente para el discurso.", "Leave off if you use quotes manually for speech.": "Omite esto si usas comillas manualmente para diálogo.",
"Main prompt": "Indicación principal", "Main prompt": "Indicaciónes principales",
"The main prompt used to set the model behavior": "La indicación principal utilizada para establecer el comportamiento del modelo", "The main prompt used to set the model behavior": "Las indicaciónes principales utilizadas para establecer el comportamiento del modelo",
"NSFW prompt": "Indicación NSFW", "NSFW prompt": "Indicaciónes NSFW",
"Prompt that is used when the NSFW toggle is on": "Indicación que se utiliza cuando el interruptor NSFW está activado", "Prompt that is used when the NSFW toggle is on": "Indicaciónes que se utilizan cuando el interruptor NSFW está activado",
"Jailbreak prompt": "Indicación de jailbreak", "Jailbreak prompt": "Indicaciónes de jailbreak",
"Prompt that is used when the Jailbreak toggle is on": "Indicación que se utiliza cuando el interruptor Jailbreak está activado", "Prompt that is used when the Jailbreak toggle is on": "Indicaciónes que se utilizan cuando el interruptor Jailbreak está activado",
"Impersonation prompt": "Indicación de suplantación de identidad", "Impersonation prompt": "Indicaciónes de Suplantación",
"Prompt that is used for Impersonation function": "Indicación que se utiliza para la función de suplantación de identidad", "Prompt that is used for Impersonation function": "Indicación que se utiliza para la función de Suplantación",
"Logit Bias": "Sesgo de logit", "Logit Bias": "Sesgo de logit",
"Helps to ban or reenforce the usage of certain words": "Ayuda a prohibir o reforzar el uso de ciertas palabras", "Helps to ban or reenforce the usage of certain words": "Ayuda a prohibir o reforzar el uso de ciertas palabras",
"View / Edit bias preset": "Ver / Editar preajuste de sesgo", "View / Edit bias preset": "Ver / Editar preajuste de sesgo",
@ -136,17 +136,17 @@
"Message to send when auto-jailbreak is on.": "Mensaje para enviar cuando el auto-jailbreak está activado.", "Message to send when auto-jailbreak is on.": "Mensaje para enviar cuando el auto-jailbreak está activado.",
"Jailbreak confirmation reply": "Respuesta de confirmación de jailbreak", "Jailbreak confirmation reply": "Respuesta de confirmación de jailbreak",
"Bot must send this back to confirm jailbreak": "El bot debe enviar esto de vuelta para confirmar el jailbreak", "Bot must send this back to confirm jailbreak": "El bot debe enviar esto de vuelta para confirmar el jailbreak",
"Character Note": "Nota del personaje", "Character Note": "Nota de personaje",
"Influences bot behavior in its responses": "Influye en el comportamiento del bot en sus respuestas", "Influences bot behavior in its responses": "Influye en el comportamiento del bot en sus respuestas",
"Connect": "Conectar", "Connect": "Conectar",
"Test Message": "Mensaje de prueba", "Test Message": "Mensaje de prueba",
"API": "API", "API": "API",
"KoboldAI": "KoboldAI", "KoboldAI": "KoboldAI",
"Use Horde": "Usar Horda", "Use Horde": "Usar Horde",
"API url": "URL de la API", "API url": "URL de la API",
"PygmalionAI/aphrodite-engine": "PygmalionAI/aphrodite-engine (Modo envolvente para API de OpenAI)", "PygmalionAI/aphrodite-engine": "PygmalionAI/aphrodite-engine (Modo envolvente para API de OpenAI)",
"Register a Horde account for faster queue times": "Registra una cuenta de la Horda para tiempos de espera más rápidos", "Register a Horde account for faster queue times": "Registra una cuenta de Horde para tiempos de espera más rápidos",
"Learn how to contribute your idle GPU cycles to the Hord": "Aprende cómo contribuir con tus ciclos de GPU inactivos a la Horda", "Learn how to contribute your idle GPU cycles to the Hord": "Aprende cómo contribuir con tus ciclos de GPU inactivos a Horde",
"Adjust context size to worker capabilities": "Ajusta el tamaño del contexto a las capacidades del trabajador", "Adjust context size to worker capabilities": "Ajusta el tamaño del contexto a las capacidades del trabajador",
"Adjust response length to worker capabilities": "Ajusta la longitud de la respuesta a las capacidades del trabajador", "Adjust response length to worker capabilities": "Ajusta la longitud de la respuesta a las capacidades del trabajador",
"API key": "Clave API", "API key": "Clave API",
@ -168,7 +168,7 @@
"For privacy reasons": "Por razones de privacidad, la clave API se oculta después de actualizar la página", "For privacy reasons": "Por razones de privacidad, la clave API se oculta después de actualizar la página",
"Models": "Modelos", "Models": "Modelos",
"Hold Control / Command key to select multiple models.": "Mantén presionada la tecla Control / Comando para seleccionar varios modelos.", "Hold Control / Command key to select multiple models.": "Mantén presionada la tecla Control / Comando para seleccionar varios modelos.",
"Horde models not loaded": "Modelos de la Horda no cargados", "Horde models not loaded": "Modelos de Horde no cargados",
"Not connected...": "No conectado...", "Not connected...": "No conectado...",
"Novel API key": "Clave API de Novel", "Novel API key": "Clave API de Novel",
"Follow": "Seguir", "Follow": "Seguir",
@ -199,7 +199,7 @@
"OpenAI Model": "Modelo de OpenAI", "OpenAI Model": "Modelo de OpenAI",
"Claude API Key": "Clave API de Claude", "Claude API Key": "Clave API de Claude",
"Get your key from": "Obtén tu clave desde", "Get your key from": "Obtén tu clave desde",
"Anthropic's developer console": "consola de desarrolladores de Anthropic", "Anthropic's developer console": "la consola de desarrolladores de Anthropic",
"Slack and Poe cookies will not work here, do not bother trying.": "Las cookies de Slack y Poe no funcionarán aquí, no te molestes en intentarlo.", "Slack and Poe cookies will not work here, do not bother trying.": "Las cookies de Slack y Poe no funcionarán aquí, no te molestes en intentarlo.",
"Claude Model": "Modelo de Claude", "Claude Model": "Modelo de Claude",
"Scale API Key": "Clave API de Scale", "Scale API Key": "Clave API de Scale",
@ -214,72 +214,72 @@
"OpenRouter API Key": "Clave API de OpenRouter", "OpenRouter API Key": "Clave API de OpenRouter",
"Connect to the API": "Conectar a la API", "Connect to the API": "Conectar a la API",
"OpenRouter Model": "Modelo de OpenRouter", "OpenRouter Model": "Modelo de OpenRouter",
"View Remaining Credits": "Ver créditos restantes", "View Remaining Credits": "Ver Créditos Restantes",
"Click Authorize below or get the key from": "Haz clic en Autorizar a continuación o obtén la clave desde", "Click Authorize below or get the key from": "Haz clic en Autorizar a continuación o obtén la clave desde",
"Auto-connect to Last Server": "Conexión automática al último servidor", "Auto-connect to Last Server": "Conexión automática al último servidor",
"View hidden API keys": "Ver claves API ocultas", "View hidden API keys": "Ver claves API ocultas",
"Advanced Formatting": "Formato avanzado", "Advanced Formatting": "Formato avanzado",
"Context Template": "Plantilla de contexto", "Context Template": "Plantilla de Contexto",
"AutoFormat Overrides": "Anulaciones de AutoFormato", "AutoFormat Overrides": "Anulaciones de AutoFormato",
"Disable description formatting": "Desactivar formato de descripción", "Disable description formatting": "Desactivar formato de descripción",
"Disable personality formatting": "Desactivar formato de personalidad", "Disable personality formatting": "Desactivar formato de personalidad",
"Disable scenario formatting": "Desactivar formato de escenario", "Disable scenario formatting": "Desactivar formato de escenario",
"Disable example chats formatting": "Desactivar formato de chats de ejemplo", "Disable example chats formatting": "Desactivar formato de chats de ejemplo",
"Disable chat start formatting": "Desactivar formato de inicio de chat", "Disable chat start formatting": "Desactivar formato de inicio de chat",
"Custom Chat Separator": "Separador de chat personalizado", "Custom Chat Separator": "Separador de Chat Personalizado",
"Replace Macro in Custom Stopping Strings": "Reemplazar macro en cadenas de detención personalizadas", "Replace Macro in Custom Stopping Strings": "Reemplazar macro en Cadenas de Detención Personalizadas",
"Strip Example Messages from Prompt": "Eliminar mensajes de ejemplo de la solicitud", "Strip Example Messages from Prompt": "Eliminar Mensajes de Ejemplo de las Indicaciones",
"Story String": "Cadena de historia", "Story String": "Cadena de historia",
"Example Separator": "Separador de ejemplo", "Example Separator": "Separador de ejemplo",
"Chat Start": "Inicio de chat", "Chat Start": "Inicio de chat",
"Activation Regex": "Regex de activación", "Activation Regex": "Regex de activación",
"Instruct Mode": "Modo de instrucción", "Instruct Mode": "Modo Instrucción",
"Wrap Sequences with Newline": "Envolver secuencias con nueva línea", "Wrap Sequences with Newline": "Envolver Secuencias con Nueva línea",
"Include Names": "Incluir nombres", "Include Names": "Incluir Nombres",
"Force for Groups and Personas": "Forzar para grupos y personas", "Force for Groups and Personas": "Forzar para Grupos y Personas",
"System Prompt": "Solicitud del sistema", "System Prompt": "Indicaciones del Sistema",
"Instruct Mode Sequences": "Secuencias en modo de instrucción", "Instruct Mode Sequences": "Secuencias en Modo Instrucción",
"Input Sequence": "Secuencia de entrada", "Input Sequence": "Secuencia de Entrada",
"Output Sequence": "Secuencia de salida", "Output Sequence": "Secuencia de Salida",
"First Output Sequence": "Primera secuencia de salida", "First Output Sequence": "Primera Secuencia de Salida",
"Last Output Sequence": "Última secuencia de salida", "Last Output Sequence": "Última Secuencia de Salida",
"System Sequence Prefix": "Prefijo de secuencia del sistema", "System Sequence Prefix": "Prefijo de Secuencia del Sistema",
"System Sequence Suffix": "Sufijo de secuencia del sistema", "System Sequence Suffix": "Sufijo de Secuencia del Sistema",
"Stop Sequence": "Secuencia de parada", "Stop Sequence": "Secuencia de Parada",
"Context Formatting": "Formato de contexto", "Context Formatting": "Formato de Contexto",
"(Saved to Context Template)": "(Guardado en plantilla de contexto)", "(Saved to Context Template)": "(Guardado en Plantilla de Contexto)",
"Tokenizer": "Tokenizador", "Tokenizer": "Tokenizador",
"None / Estimated": "Ninguno / Estimado", "None / Estimated": "Ninguno / Estimado",
"Sentencepiece (LLaMA)": "Sentencepiece (LLaMA)", "Sentencepiece (LLaMA)": "Sentencepiece (LLaMA)",
"Token Padding": "Relleno de token", "Token Padding": "Relleno de token",
"Save preset as": "Guardar preajuste como", "Save preset as": "Guardar preajuste como",
"Always add character's name to prompt": "Siempre agregar el nombre del personaje a la solicitud", "Always add character's name to prompt": "Siempre agregar el nombre del personaje a las indicaciones",
"Use as Stop Strings": "Usar como cadenas de parada", "Use as Stop Strings": "Usar como Cadenas de Parada",
"Bind to Context": "Vincular al contexto", "Bind to Context": "Vincular al Contexto",
"Generate only one line per request": "Generar solo una línea por solicitud", "Generate only one line per request": "Generar solo una línea por solicitud",
"Misc. Settings": "Configuraciones misceláneas", "Misc. Settings": "Configuraciones Misceláneas",
"Auto-Continue": "Autocontinuar", "Auto-Continue": "Autocontinuar",
"Collapse Consecutive Newlines": "Colapsar nuevas líneas consecutivas", "Collapse Consecutive Newlines": "Colapsar Nuevas líneas Consecutivas",
"Allow for Chat Completion APIs": "Permitir APIs de finalización de chat", "Allow for Chat Completion APIs": "Permitir para APIs de Completado de Chat",
"Target length (tokens)": "Longitud objetivo (tokens)", "Target length (tokens)": "Longitud objetivo (tokens)",
"Keep Example Messages in Prompt": "Mantener mensajes de ejemplo en la solicitud", "Keep Example Messages in Prompt": "Mantener Mensajes de Ejemplo en las indicaciones",
"Remove Empty New Lines from Output": "Eliminar nuevas líneas vacías de la salida", "Remove Empty New Lines from Output": "Eliminar Nuevas líneas vacías de la salida",
"Disabled for all models": "Desactivado para todos los modelos", "Disabled for all models": "Desactivado para todos los modelos",
"Automatic (based on model name)": "Automático (basado en el nombre del modelo)", "Automatic (based on model name)": "Automático (basado en el nombre del modelo)",
"Enabled for all models": "Activado para todos los modelos", "Enabled for all models": "Activado para todos los modelos",
"Anchors Order": "Orden de anclajes", "Anchors Order": "Orden de Anclajes",
"Character then Style": "Personaje luego estilo", "Character then Style": "Personaje luego estilo",
"Style then Character": "Estilo luego personaje", "Style then Character": "Estilo luego personaje",
"Character Anchor": "Anclaje de personaje", "Character Anchor": "Anclaje de personaje",
"Style Anchor": "Anclaje de estilo", "Style Anchor": "Anclaje de estilo",
"World Info": "Información del mundo", "World Info": "Información de Mundo (WI)",
"Scan Depth": "Profundidad de escaneo", "Scan Depth": "Profundidad de escaneo",
"Case-Sensitive": "Sensible a mayúsculas y minúsculas", "Case-Sensitive": "Sensible a mayúsculas y minúsculas",
"Match Whole Words": "Coincidir con palabras completas", "Match Whole Words": "Coincidir con palabras completas",
"Use global setting": "Usar configuración global", "Use global setting": "Usar configuración global",
"Yes": "Sí", "Yes": "Sí",
"No": "No", "No": "No",
"Context %": "Contexto %", "Context %": "% de Contexto",
"Budget Cap": "Límite de presupuesto", "Budget Cap": "Límite de presupuesto",
"(0 = disabled)": "(0 = desactivado)", "(0 = disabled)": "(0 = desactivado)",
"depth": "profundidad", "depth": "profundidad",
@ -289,29 +289,29 @@
"None": "Ninguno", "None": "Ninguno",
"User Settings": "Configuraciones de usuario", "User Settings": "Configuraciones de usuario",
"UI Mode": "Modo de IU", "UI Mode": "Modo de IU",
"UI Language": "Idioma", "UI Language": "Idioma de la UI",
"MovingUI Preset": "Preajuste de MovingUI", "MovingUI Preset": "Preajuste de MovingUI",
"UI Customization": "Personalización de la IU", "UI Customization": "Personalización de la IU",
"Avatar Style": "Estilo de avatar", "Avatar Style": "Estilo de Avatar",
"Circle": "Círculo", "Circle": "Círculo",
"Rectangle": "Rectángulo", "Rectangle": "Rectángulo",
"Square": "Cuadrado", "Square": "Cuadrado",
"Chat Style": "Estilo de chat", "Chat Style": "Estilo de Chat",
"Default": "Predeterminado", "Default": "Predeterminado",
"Bubbles": "Burbujas", "Bubbles": "Burbujas",
"No Blur Effect": "Sin efecto de desenfoque", "No Blur Effect": "Sin efecto de desenfoque",
"No Text Shadows": "Sin sombras de texto", "No Text Shadows": "Sin sombras de texto",
"Waifu Mode": "Modo Waifu", "Waifu Mode": "Modo Waifu",
"Message Timer": "Temporizador de mensajes", "Message Timer": "Temporizador de mensajes",
"Model Icon": "Ícono del modelo", "Model Icon": "Ícono del Modelo",
"# of messages (0 = disabled)": "# de mensajes (0 = desactivado)", "# of messages (0 = disabled)": "# de mensajes (0 = desactivado)",
"Advanced Character Search": "Búsqueda avanzada de personajes", "Advanced Character Search": "Búsqueda Avanzada de Personajes",
"Allow {{char}}: in bot messages": "Permitir {{char}}: en mensajes de bot", "Allow {{char}}: in bot messages": "Permitir {{char}}: en mensajes de bot",
"Allow {{user}}: in bot messages": "Permitir {{user}}: en mensajes de bot", "Allow {{user}}: in bot messages": "Permitir {{user}}: en mensajes de bot",
"Show tags in responses": "Mostrar etiquetas en respuestas", "Show tags in responses": "Mostrar etiquetas en respuestas",
"Aux List Field": "Campo de lista auxiliar", "Aux List Field": "Campo de lista auxiliar",
"Lorebook Import Dialog": "Diálogo de importación de libro de historia", "Lorebook Import Dialog": "Diálogo de Importación de Libro de Historia",
"MUI Preset": "Preset MUI", "MUI Preset": "Preajuste MUI",
"If set in the advanced character definitions, this field will be displayed in the characters list.": "Si se establece en las definiciones avanzadas de personajes, este campo se mostrará en la lista de personajes.", "If set in the advanced character definitions, this field will be displayed in the characters list.": "Si se establece en las definiciones avanzadas de personajes, este campo se mostrará en la lista de personajes.",
"Relaxed API URLS": "URLS de API relajadas", "Relaxed API URLS": "URLS de API relajadas",
"Custom CSS": "CSS personalizado", "Custom CSS": "CSS personalizado",
@ -322,7 +322,7 @@
"Relax message trim in Groups": "Relajar recorte de mensajes en Grupos", "Relax message trim in Groups": "Relajar recorte de mensajes en Grupos",
"Characters Hotswap": "Cambio rápido de personajes", "Characters Hotswap": "Cambio rápido de personajes",
"Request token probabilities": "Solicitar probabilidades de tokens", "Request token probabilities": "Solicitar probabilidades de tokens",
"Movable UI Panels": "Paneles de UI móviles", "Movable UI Panels": "Paneles de UI Móviles",
"Reset Panels": "Restablecer paneles", "Reset Panels": "Restablecer paneles",
"UI Colors": "Colores de UI", "UI Colors": "Colores de UI",
"Main Text": "Texto principal", "Main Text": "Texto principal",
@ -331,44 +331,44 @@
"Shadow Color": "Color de sombra", "Shadow Color": "Color de sombra",
"FastUI BG": "Fondo de FastUI", "FastUI BG": "Fondo de FastUI",
"Blur Tint": "Tinte de desenfoque", "Blur Tint": "Tinte de desenfoque",
"Font Scale": "Escala de fuente", "Font Scale": "Tamaño de fuente",
"Blur Strength": "Fuerza de desenfoque", "Blur Strength": "Fuerza de desenfoque",
"Text Shadow Width": "Ancho de sombra de texto", "Text Shadow Width": "Ancho de sombra de texto",
"UI Theme Preset": "Preset de tema de UI", "UI Theme Preset": "Preajuste de tema de UI",
"Power User Options": "Opciones avanzadas de usuario", "Power User Options": "Opciones avanzadas de usuario",
"Swipes": "Deslizamientos", "Swipes": "Deslizamientos",
"Miscellaneous": "Varios", "Miscellaneous": "Varios",
"Theme Toggles": "Conmutadores de tema", "Theme Toggles": "Conmutadores de tema",
"Background Sound Only": "Solo sonido de fondo", "Background Sound Only": "Solo Sonido de Fondo",
"Auto-load Last Chat": "Cargar automáticamente el último chat", "Auto-load Last Chat": "Cargar automáticamente el último chat",
"Auto-save Message Edits": "Guardar automáticamente las ediciones de mensajes", "Auto-save Message Edits": "Guardar automáticamente las Ediciones de Mensajes",
"Auto-fix Markdown": "Auto-corregir Markdown", "Auto-fix Markdown": "Auto-corregir Markdown",
"Allow : in bot messages": "Permitir : en mensajes de bot", "Allow : in bot messages": "Permitir : en mensajes de bot",
"Auto-scroll Chat": "Chat de desplazamiento automático", "Auto-scroll Chat": "Desplazamiento de Chat Automático",
"Render Formulas": "Renderizar fórmulas", "Render Formulas": "Renderizar fórmulas",
"Send on Enter": "Enviar al presionar Enter", "Send on Enter": "Enviar al presionar Enter",
"Always disabled": "Siempre desactivado", "Always disabled": "Siempre desactivado",
"Automatic (desktop)": "Automático (escritorio)", "Automatic (desktop)": "Automático (escritorio)",
"Always enabled": "Siempre activado", "Always enabled": "Siempre activado",
"Debug Menu": "Menú de depuración", "Debug Menu": "Menú de depuración",
"Restore User Input": "Restaurar entrada de usuario", "Restore User Input": "Restaurar Entrada de Usuario",
"Character Handling": "Manipulación de personajes", "Character Handling": "Manipulación de personajes",
"Example Messages Behavior": "Comportamiento de mensajes de ejemplo", "Example Messages Behavior": "Comportamiento de mensajes de ejemplo",
"Gradual push-out": "Empuje gradual", "Gradual push-out": "Expulsión gradual",
"Chat/Message Handling": "Manipulación de chat/mensaje", "Chat/Message Handling": "Manipulación de Chat/Mensaje",
"Always include examples": "Siempre incluir ejemplos", "Always include examples": "Siempre incluir ejemplos",
"Never include examples": "Nunca incluir ejemplos", "Never include examples": "Nunca incluir ejemplos",
"Forbid External Media": "Prohibir medios externos", "Forbid External Media": "Prohibir Medios Externos",
"System Backgrounds": "Fondos del sistema", "System Backgrounds": "Fondos del Sistema",
"Name": "Nombre", "Name": "Nombre",
"Your Avatar": "Tu avatar", "Your Avatar": "Tu avatar",
"Extensions API:": "API de extensiones:", "Extensions API:": "API de Extensiones:",
"SillyTavern-extras": "Extras de SillyTavern", "SillyTavern-extras": "Extras de SillyTavern",
"Auto-connect": "Conexión automática", "Auto-connect": "Conexión automática",
"Active extensions": "Extensiones activas", "Active extensions": "Extensiones Activas",
"Extension settings": "Configuraciones de extensión", "Extension settings": "Configuraciones de Extensión",
"Description": "Descripción", "Description": "Descripción",
"First message": "Primer mensaje", "First message": "Primer Mensaje",
"Group Controls": "Controles de grupo", "Group Controls": "Controles de grupo",
"Group reply strategy": "Estrategia de respuesta de grupo", "Group reply strategy": "Estrategia de respuesta de grupo",
"Natural order": "Orden natural", "Natural order": "Orden natural",
@ -387,19 +387,19 @@
"Circumstances and context of the dialogue": "Circunstancias y contexto del diálogo", "Circumstances and context of the dialogue": "Circunstancias y contexto del diálogo",
"Talkativeness": "Habladuría", "Talkativeness": "Habladuría",
"How often the chracter speaks in": "Con qué frecuencia habla el personaje en", "How often the chracter speaks in": "Con qué frecuencia habla el personaje en",
"group chats!": "chats de grupo!", "group chats!": "chats grupales!",
"Shy": "Tímido", "Shy": "Tímido",
"Normal": "Normal", "Normal": "Normal",
"Chatty": "Charlatán", "Chatty": "Parlanchín",
"Examples of dialogue": "Ejemplos de diálogo", "Examples of dialogue": "Ejemplos de diálogo",
"Forms a personality more clearly": "Forma una personalidad más clara", "Forms a personality more clearly": "Forma una personalidad más clara",
"Save": "Guardar", "Save": "Guardar",
"World Info Editor": "Editor de información del mundo", "World Info Editor": "Editor de Información de Mundo (WI)",
"New summary": "Nuevo resumen", "New summary": "Nuevo resumen",
"Export": "Exportar", "Export": "Exportar",
"Delete World": "Eliminar mundo", "Delete World": "Eliminar mundo",
"Chat History": "Historial de chat", "Chat History": "Historial de chat",
"Group Chat Scenario Override": "Anulación de escenario de chat grupal", "Group Chat Scenario Override": "Anulación de escenario de Chat Grupal",
"All group members will use the following scenario text instead of what is specified in their character cards.": "Todos los miembros del grupo usarán el siguiente texto de escenario en lugar de lo que se especifica en sus tarjetas de personaje.", "All group members will use the following scenario text instead of what is specified in their character cards.": "Todos los miembros del grupo usarán el siguiente texto de escenario en lugar de lo que se especifica en sus tarjetas de personaje.",
"Keywords": "Palabras clave", "Keywords": "Palabras clave",
"Separate with commas": "Separar con comas", "Separate with commas": "Separar con comas",
@ -424,60 +424,60 @@
"Start new chat": "Iniciar nuevo chat", "Start new chat": "Iniciar nuevo chat",
"View past chats": "Ver chats anteriores", "View past chats": "Ver chats anteriores",
"Delete messages": "Eliminar mensajes", "Delete messages": "Eliminar mensajes",
"Impersonate": "Hacerse pasar por", "Impersonate": "Suplantar",
"Regenerate": "Regenerar", "Regenerate": "Regenerar",
"PNG": "PNG", "PNG": "PNG",
"JSON": "JSON", "JSON": "JSON",
"presets": "ajustes preestablecidos", "presets": "preajustes",
"Message Sound": "Sonido de mensaje", "Message Sound": "Sonido de mensaje",
"Author's Note": "Nota del autor", "Author's Note": "Nota del autor",
"Send Jailbreak": "Enviar Jailbreak", "Send Jailbreak": "Enviar Jailbreak",
"Replace empty message": "Reemplazar mensaje vacío", "Replace empty message": "Reemplazar mensaje vacío",
"Send this text instead of nothing when the text box is empty.": "Enviar este texto en lugar de nada cuando el cuadro de texto está vacío.", "Send this text instead of nothing when the text box is empty.": "Enviar este texto en lugar de nada cuando el cuadro de texto está vacío.",
"NSFW avoidance prompt": "Indicación de evitación de NSFW", "NSFW avoidance prompt": "Indicaciones de evitación de NSFW",
"Prompt that is used when the NSFW toggle is off": "Indicación que se usa cuando el interruptor de NSFW está apagado", "Prompt that is used when the NSFW toggle is off": "Indicaciones que se usa cuando el interruptor de NSFW está apagado",
"Advanced prompt bits": "Bits de indicación avanzada", "Advanced prompt bits": "Bits de Indicaciones Avanzadas",
"World Info format": "Formato de información del mundo", "World Info format": "Formato de Información de Mundo (WI)",
"Wraps activated World Info entries before inserting into the prompt. Use {0} to mark a place where the content is inserted.": "Envuelve las entradas de información del mundo activadas antes de insertarlas en la indicación. Use {0} para marcar un lugar donde se inserta el contenido.", "Wraps activated World Info entries before inserting into the prompt. Use {0} to mark a place where the content is inserted.": "Envuelve las entradas de Información de Mundo (WI) activadas antes de insertarlas en las indicaciones. Use {0} para marcar un lugar donde se inserta el contenido.",
"Unrestricted maximum value for the context slider": "Valor máximo sin restricciones para el control deslizante de contexto", "Unrestricted maximum value for the context slider": "Valor máximo sin restricciones para el control deslizante de contexto",
"Chat Completion Source": "Fuente de completado de chat", "Chat Completion Source": "Fuente de Completado de Chat",
"Avoid sending sensitive information to the Horde.": "Evite enviar información sensible a la Horda.", "Avoid sending sensitive information to the Horde.": "Evite enviar información sensible a Horde.",
"Review the Privacy statement": "Revise la declaración de privacidad", "Review the Privacy statement": "Revise la declaración de privacidad",
"Learn how to contribute your idel GPU cycles to the Horde": "Aprende cómo contribuir con tus ciclos de GPU inactivos a la Horda", "Learn how to contribute your idel GPU cycles to the Horde": "Aprende cómo contribuir con tus ciclos de GPU inactivos a Horde",
"Trusted workers only": "Solo trabajadores de confianza", "Trusted workers only": "Solo trabajadores de confianza",
"For privacy reasons, your API key will be hidden after you reload the page.": "Por razones de privacidad, su clave de API se ocultará después de que vuelva a cargar la página.", "For privacy reasons, your API key will be hidden after you reload the page.": "Por razones de privacidad, su clave de API se ocultará después de que vuelva a cargar la página.",
"-- Horde models not loaded --": "-- Modelos de la Horda no cargados --", "-- Horde models not loaded --": "-- Modelos de Horde no cargados --",
"Example: http://127.0.0.1:5000/api ": "Ejemplo: http://127.0.0.1:5000/api", "Example: http://127.0.0.1:5000/api ": "Ejemplo: http://127.0.0.1:5000/api",
"No connection...": "Sin conexión...", "No connection...": "Sin conexión...",
"Get your NovelAI API Key": "Obtenga su clave de API de NovelAI", "Get your NovelAI API Key": "Obtenga su Clave de API de NovelAI",
"KoboldAI Horde": "Horda de KoboldAI", "KoboldAI Horde": "Horde de KoboldAI",
"Text Gen WebUI (ooba)": "Text Gen WebUI (ooba)", "Text Gen WebUI (ooba)": "Text Gen WebUI (ooba)",
"NovelAI": "NovelAI", "NovelAI": "NovelAI",
"Chat Completion (OpenAI, Claude, Window/OpenRouter, Scale)": "Completado de chat (OpenAI, Claude, Window/OpenRouter, Scale)", "Chat Completion (OpenAI, Claude, Window/OpenRouter, Scale)": "Completado de Chat (OpenAI, Claude, Window/OpenRouter, Scale)",
"OpenAI API key": "Clave de API de OpenAI", "OpenAI API key": "Clave de API de OpenAI",
"Trim spaces": "Recortar espacios", "Trim spaces": "Recortar espacios",
"Trim Incomplete Sentences": "Recortar oraciones incompletas", "Trim Incomplete Sentences": "Recortar Oraciones Incompletas",
"Include Newline": "Incluir nueva línea", "Include Newline": "Incluir Nueva línea",
"Non-markdown strings": "Cadenas no Markdown", "Non-markdown strings": "Cadenas no Markdown",
"Replace Macro in Sequences": "Reemplazar macro en secuencias", "Replace Macro in Sequences": "Reemplazar Macro en Secuencias",
"Presets": "Ajustes preestablecidos", "Presets": "Preajustes",
"Separator": "Separador", "Separator": "Separador",
"Start Reply With": "Iniciar respuesta con", "Start Reply With": "Iniciar Respuesta con",
"Show reply prefix in chat": "Mostrar prefijo de respuesta en el chat", "Show reply prefix in chat": "Mostrar prefijo de respuesta en el chat",
"Worlds/Lorebooks": "Mundos/Libros de historia", "Worlds/Lorebooks": "Mundos/Libros de Historia",
"Active World(s)": "Mundo(s) activo(s)", "Active World(s)": "Mundo(s) Activo(s)",
"Activation Settings": "Configuraciones de activación", "Activation Settings": "Configuraciones de activación",
"Character Lore Insertion Strategy": "Estrategia de inserción de lore de personajes", "Character Lore Insertion Strategy": "Estrategia de Inserción de Historia de Dersonajes",
"Sorted Evenly": "Ordenado uniformemente", "Sorted Evenly": "Ordenado uniformemente",
"Active World(s) for all chats": "Mundo(s) activo(s) para todos los chats", "Active World(s) for all chats": "Mundo(s) Activo(s) para todos los chats",
"-- World Info not found --": "-- Información del mundo no encontrada --", "-- World Info not found --": "-- Información de Mundo (WI) no encontrada --",
"--- Pick to Edit ---": "--- Seleccionar para editar ---", "--- Pick to Edit ---": "--- Seleccionar para editar ---",
"or": "o", "or": "o",
"New": "Nuevo", "New": "Nuevo",
"Priority": "Prioridad", "Priority": "Prioridad",
"Custom": "Personalizado", "Custom": "Personalizado",
"Title A-Z": "Título de la A a la Z", "Title A-Z": "Título de A a Z",
"Title Z-A": "Título de la Z a la A", "Title Z-A": "Título de Z a A",
"Tokens ↗": "Tokens ↗", "Tokens ↗": "Tokens ↗",
"Tokens ↘": "Tokens ↘", "Tokens ↘": "Tokens ↘",
"Depth ↗": "Profundidad ↗", "Depth ↗": "Profundidad ↗",
@ -486,26 +486,26 @@
"Order ↘": "Orden ↘", "Order ↘": "Orden ↘",
"UID ↗": "UID ↗", "UID ↗": "UID ↗",
"UID ↘": "UID ↘", "UID ↘": "UID ↘",
"Trigger% ↗": "Desencadenar% ↗", "Trigger% ↗": "Activador% ↗",
"Trigger% ↘": "Desencadenar% ↘", "Trigger% ↘": "Activador% ↘",
"Order:": "Orden:", "Order:": "Orden:",
"Depth:": "Profundidad:", "Depth:": "Profundidad:",
"Character Lore First": "Lore del personaje primero", "Character Lore First": "Historia de Personaje Primero",
"Global Lore First": "Lore global primero", "Global Lore First": "Historia Global Primero",
"Recursive Scan": "Exploración recursiva", "Recursive Scan": "Escaneo Recursiva",
"Case Sensitive": "Sensible a mayúsculas y minúsculas", "Case Sensitive": "Sensible a mayúsculas y minúsculas",
"Match whole words": "Coincidir palabras completas", "Match whole words": "Coincidir palabras completas",
"Alert On Overflow": "Alerta en desbordamiento", "Alert On Overflow": "Alerta en Desbordamiento",
"World/Lore Editor": "Editor de mundo/Lore", "World/Lore Editor": "Editor de Mundo/Historia",
"--- None ---": "--- Ninguno ---", "--- None ---": "--- Ninguno ---",
"Comma separated (ignored if empty)": "Separado por comas (ignorado si está vacío)", "Comma separated (ignored if empty)": "Separado por comas (ignorado si está vacío)",
"Use Probability": "Usar Probabilidad", "Use Probability": "Usar Probabilidad",
"Exclude from recursion": "Excluir de la recursión", "Exclude from recursion": "Excluir de la recursión",
"Entry Title/Memo": "Título/Memo", "Entry Title/Memo": "Título/Memo",
"Position:": "Posición:", "Position:": "Posición:",
"T_Position": "↑Char: antes de definiciones de caracteres\n↓Char: después de definiciones de caracteres\n↑AN: antes de notas del autor\n↓AN: después de notas del autor\n@D: en profundidad", "T_Position": "↑Char: antes de definiciones de personajes\n↓Char: después de definiciones de personajes\n↑AN: antes de notas del autor\n↓AN: después de notas del autor\n@D: en profundidad",
"Before Char Defs": "Antes de Definiciones de Caracteres", "Before Char Defs": "Antes de Def. de Personaje",
"After Char Defs": "Después de Definiciones de Caracteres", "After Char Defs": "Después de Def. de Personaje",
"Before AN": "Antes de AN", "Before AN": "Antes de AN",
"After AN": "Después de AN", "After AN": "Después de AN",
"at Depth": "en Profundidad", "at Depth": "en Profundidad",
@ -521,7 +521,7 @@
"Chat Background": "Fondo de Chat", "Chat Background": "Fondo de Chat",
"UI Background": "Fondo de IU", "UI Background": "Fondo de IU",
"Mad Lab Mode": "Modo Laboratorio Loco", "Mad Lab Mode": "Modo Laboratorio Loco",
"Show Message Token Count": "Mostrar Conteo de Tokens de Mensaje", "Show Message Token Count": "Mostrar Conteo de Tokens en Mensaje",
"Compact Input Area (Mobile)": "Área de Entrada Compacta (Móvil)", "Compact Input Area (Mobile)": "Área de Entrada Compacta (Móvil)",
"Zen Sliders": "Deslizadores Zen", "Zen Sliders": "Deslizadores Zen",
"UI Border": "Borde de IU", "UI Border": "Borde de IU",
@ -534,9 +534,9 @@
"Streaming FPS": "FPS de Transmisión", "Streaming FPS": "FPS de Transmisión",
"Gestures": "Gestos", "Gestures": "Gestos",
"Message IDs": "IDs de Mensaje", "Message IDs": "IDs de Mensaje",
"Prefer Character Card Prompt": "Preferir Tarjeta de Personaje con Indicación", "Prefer Character Card Prompt": "Preferir Indicaciones en Tarjeta de Personaje",
"Prefer Character Card Jailbreak": "Preferir Jailbreak de Tarjeta de Personaje", "Prefer Character Card Jailbreak": "Preferir Jailbreak en Tarjeta de Personaje",
"Press Send to continue": "Presione Enviar para continuar", "Press Send to continue": "Presionar Enviar para continuar",
"Quick 'Continue' button": "Botón 'Continuar' Rápido", "Quick 'Continue' button": "Botón 'Continuar' Rápido",
"Log prompts to console": "Registrar indicaciones en la consola", "Log prompts to console": "Registrar indicaciones en la consola",
"Never resize avatars": "Nunca redimensionar avatares", "Never resize avatars": "Nunca redimensionar avatares",
@ -569,11 +569,11 @@
"Show the number of tokens in each message in the chat log": "Mostrar el número de tokens en cada mensaje en el registro de chat", "Show the number of tokens in each message in the chat log": "Mostrar el número de tokens en cada mensaje en el registro de chat",
"Single-row message input area. Mobile only, no effect on PC": "Área de entrada de mensaje de una sola fila. Solo móvil, sin efecto en PC", "Single-row message input area. Mobile only, no effect on PC": "Área de entrada de mensaje de una sola fila. Solo móvil, sin efecto en PC",
"In the Character Management panel, show quick selection buttons for favorited characters": "En el panel de Gestión de Personajes, mostrar botones de selección rápida para personajes favoritos", "In the Character Management panel, show quick selection buttons for favorited characters": "En el panel de Gestión de Personajes, mostrar botones de selección rápida para personajes favoritos",
"Show tagged character folders in the character list": "Mostrar carpetas de personajes etiquetadas en la lista de personajes", "Show tagged character folders in the character list": "Mostrar carpetas de personajes etiquetados en la lista de personajes",
"Play a sound when a message generation finishes": "Reproducir un sonido cuando finaliza la generación de un mensaje", "Play a sound when a message generation finishes": "Reproducir un sonido cuando finaliza la generación de un mensaje",
"Only play a sound when ST's browser tab is unfocused": "Solo reproducir un sonido cuando la pestaña del navegador de ST no está enfocada", "Only play a sound when ST's browser tab is unfocused": "Solo reproducir un sonido cuando la pestaña del navegador de ST no está enfocada",
"Reduce the formatting requirements on API URLs": "Reducir los requisitos de formato en las URL de API", "Reduce the formatting requirements on API URLs": "Reducir los requisitos de formato en las URL de API",
"Ask to import the World Info/Lorebook for every new character with embedded lorebook. If unchecked, a brief message will be shown instead": "Pedir importar la Información Mundial/Libro de Leyendas para cada nuevo personaje con un lorebook incrustado. Si no está marcado, se mostrará un mensaje breve en su lugar", "Ask to import the World Info/Lorebook for every new character with embedded lorebook. If unchecked, a brief message will be shown instead": "Pedir importar Información de Mundo (WI)/Libro de Historia para cada nuevo personaje con un Libro de Historia incrustado. Si no está marcado, se mostrará un mensaje breve en su lugar",
"Restore unsaved user input on page refresh": "Restaurar la entrada de usuario no guardada al actualizar la página", "Restore unsaved user input on page refresh": "Restaurar la entrada de usuario no guardada al actualizar la página",
"Allow repositioning certain UI elements by dragging them. PC only, no effect on mobile": "Permitir reposicionar ciertos elementos de IU arrastrándolos. Solo PC, sin efecto en móviles", "Allow repositioning certain UI elements by dragging them. PC only, no effect on mobile": "Permitir reposicionar ciertos elementos de IU arrastrándolos. Solo PC, sin efecto en móviles",
"MovingUI preset. Predefined/saved draggable positions": "Preconfiguración MovingUI. Posiciones arrastrables predefinidas/guardadas", "MovingUI preset. Predefined/saved draggable positions": "Preconfiguración MovingUI. Posiciones arrastrables predefinidas/guardadas",
@ -581,7 +581,7 @@
"Apply a custom CSS style to all of the ST GUI": "Aplicar un estilo CSS personalizado a toda la GUI de ST", "Apply a custom CSS style to all of the ST GUI": "Aplicar un estilo CSS personalizado a toda la GUI de ST",
"Use fuzzy matching, and search characters in the list by all data fields, not just by a name substring": "Usar coincidencia difusa y buscar personajes en la lista por todos los campos de datos, no solo por una subcadena de nombre", "Use fuzzy matching, and search characters in the list by all data fields, not just by a name substring": "Usar coincidencia difusa y buscar personajes en la lista por todos los campos de datos, no solo por una subcadena de nombre",
"If checked and the character card contains a prompt override (System Prompt), use that instead": "Si está marcado y la tarjeta de personaje contiene una anulación de indicación (Indicación del sistema), usar eso en su lugar", "If checked and the character card contains a prompt override (System Prompt), use that instead": "Si está marcado y la tarjeta de personaje contiene una anulación de indicación (Indicación del sistema), usar eso en su lugar",
"If checked and the character card contains a jailbreak override (Post History Instruction), use that instead": "Si está marcado y la tarjeta de personaje contiene una anulación de jailbreak (Instrucción de Historial de Publicaciones), usar eso en su lugar", "If checked and the character card contains a jailbreak override (Post History Instruction), use that instead": "Si está marcado y la tarjeta de personaje contiene una anulación de jailbreak (Instrucciones Post Historial), usar eso en su lugar",
"Avoid cropping and resizing imported character images. When off, crop/resize to 400x600": "Evitar recortar y redimensionar imágenes de personajes importadas. Cuando esté desactivado, recortar/redimensionar a 400x600", "Avoid cropping and resizing imported character images. When off, crop/resize to 400x600": "Evitar recortar y redimensionar imágenes de personajes importadas. Cuando esté desactivado, recortar/redimensionar a 400x600",
"Show actual file names on the disk, in the characters list display only": "Mostrar nombres de archivo reales en el disco, solo en la visualización de la lista de personajes", "Show actual file names on the disk, in the characters list display only": "Mostrar nombres de archivo reales en el disco, solo en la visualización de la lista de personajes",
"Prompt to import embedded card tags on character import. Otherwise embedded tags are ignored": "Solicitar importar etiquetas de tarjeta incrustadas al importar un personaje. De lo contrario, las etiquetas incrustadas se ignoran", "Prompt to import embedded card tags on character import. Otherwise embedded tags are ignored": "Solicitar importar etiquetas de tarjeta incrustadas al importar un personaje. De lo contrario, las etiquetas incrustadas se ignoran",
@ -590,7 +590,7 @@
"Show arrow buttons on the last in-chat message to generate alternative AI responses. Both PC and mobile": "Mostrar botones de flecha en el último mensaje del chat para generar respuestas alternativas de la IA. Tanto PC como móvil", "Show arrow buttons on the last in-chat message to generate alternative AI responses. Both PC and mobile": "Mostrar botones de flecha en el último mensaje del chat para generar respuestas alternativas de la IA. Tanto PC como móvil",
"Allow using swiping gestures on the last in-chat message to trigger swipe generation. Mobile only, no effect on PC": "Permitir el uso de gestos de deslizamiento en el último mensaje del chat para activar la generación de deslizamiento. Solo móvil, sin efecto en PC", "Allow using swiping gestures on the last in-chat message to trigger swipe generation. Mobile only, no effect on PC": "Permitir el uso de gestos de deslizamiento en el último mensaje del chat para activar la generación de deslizamiento. Solo móvil, sin efecto en PC",
"Save edits to messages without confirmation as you type": "Guardar ediciones en mensajes sin confirmación mientras escribe", "Save edits to messages without confirmation as you type": "Guardar ediciones en mensajes sin confirmación mientras escribe",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Renderizar notación de ecuaciones LaTeX y AsciiMath en mensajes de chat. Alimentado por KaTeX", "Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Renderizar notación de ecuaciones LaTeX y AsciiMath en mensajes de chat. Impulsado por KaTeX",
"Disalow embedded media from other domains in chat messages": "No permitir medios incrustados de otros dominios en mensajes de chat", "Disalow embedded media from other domains in chat messages": "No permitir medios incrustados de otros dominios en mensajes de chat",
"Skip encoding and characters in message text, allowing a subset of HTML markup as well as Markdown": "Omitir la codificación de los caracteres en el texto del mensaje, permitiendo un subconjunto de marcado HTML, así como Markdown", "Skip encoding and characters in message text, allowing a subset of HTML markup as well as Markdown": "Omitir la codificación de los caracteres en el texto del mensaje, permitiendo un subconjunto de marcado HTML, así como Markdown",
"Allow AI messages in groups to contain lines spoken by other group members": "Permitir que los mensajes de IA en grupos contengan líneas habladas por otros miembros del grupo", "Allow AI messages in groups to contain lines spoken by other group members": "Permitir que los mensajes de IA en grupos contengan líneas habladas por otros miembros del grupo",
@ -599,7 +599,7 @@
"Enable the auto-swipe function. Settings in this section only have an effect when auto-swipe is enabled": "Habilitar la función de deslizamiento automático. La configuración en esta sección solo tiene efecto cuando el deslizamiento automático está habilitado", "Enable the auto-swipe function. Settings in this section only have an effect when auto-swipe is enabled": "Habilitar la función de deslizamiento automático. La configuración en esta sección solo tiene efecto cuando el deslizamiento automático está habilitado",
"If the generated message is shorter than this, trigger an auto-swipe": "Si el mensaje generado es más corto que esto, activar un deslizamiento automático", "If the generated message is shorter than this, trigger an auto-swipe": "Si el mensaje generado es más corto que esto, activar un deslizamiento automático",
"Reload and redraw the currently open chat": "Recargar y volver a dibujar el chat abierto actualmente", "Reload and redraw the currently open chat": "Recargar y volver a dibujar el chat abierto actualmente",
"Auto-Expand Message Actions": "Expansión Automática de Acciones de Mensaje", "Auto-Expand Message Actions": "Expandir Automáticamente de Acciones de Mensaje",
"Not Connected": "No Conectado", "Not Connected": "No Conectado",
"Persona Management": "Gestión de Personas", "Persona Management": "Gestión de Personas",
"Persona Description": "Descripción de Persona", "Persona Description": "Descripción de Persona",
@ -609,16 +609,16 @@
"In Story String / Chat Completion: Before Character Card": "En la Cadena de Historia / Completado de Chat: Antes de la Tarjeta de Personaje", "In Story String / Chat Completion: Before Character Card": "En la Cadena de Historia / Completado de Chat: Antes de la Tarjeta de Personaje",
"In Story String / Chat Completion: After Character Card": "En la Cadena de Historia / Completado de Chat: Después de la Tarjeta de Personaje", "In Story String / Chat Completion: After Character Card": "En la Cadena de Historia / Completado de Chat: Después de la Tarjeta de Personaje",
"In Story String / Prompt Manager": "En la Cadena de Historia / Administrador de Indicaciones", "In Story String / Prompt Manager": "En la Cadena de Historia / Administrador de Indicaciones",
"Top of Author's Note": "Parte Superior de la Nota del Autor", "Top of Author's Note": "Parte Superior de la Nota de Autor",
"Bottom of Author's Note": "Parte Inferior de la Nota del Autor", "Bottom of Author's Note": "Parte Inferior de la Nota de Autor",
"How do I use this?": "¿Cómo uso esto?", "How do I use this?": "¿Cómo uso esto?",
"More...": "Más...", "More...": "Más...",
"Link to World Info": "Enlace a Información del Mundo", "Link to World Info": "Enlazar a Información de Mundo (WI)",
"Import Card Lore": "Importar Lore de Tarjeta", "Import Card Lore": "Importar Historia de Tarjeta",
"Scenario Override": "Anulación de Escenario", "Scenario Override": "Anulación de Escenario",
"Rename": "Renombrar", "Rename": "Renombrar",
"Character Description": "Descripción del Personaje", "Character Description": "Descripción del Personaje",
"Creator's Notes": "Notas del Creador", "Creator's Notes": "Nota del Creador",
"A-Z": "A-Z", "A-Z": "A-Z",
"Z-A": "Z-A", "Z-A": "Z-A",
"Newest": "Más Reciente", "Newest": "Más Reciente",
@ -628,11 +628,11 @@
"Most chats": "Más Chats", "Most chats": "Más Chats",
"Least chats": "Menos Chats", "Least chats": "Menos Chats",
"Back": "Volver", "Back": "Volver",
"Prompt Overrides (For OpenAI/Claude/Scale APIs, Window/OpenRouter, and Instruct mode)": "Sustituciones de Indicaciones (Para APIs de OpenAI/Claude/Scale, Ventana/OpenRouter y Modo Instrucción)", "Prompt Overrides (For OpenAI/Claude/Scale APIs, Window/OpenRouter, and Instruct mode)": "Anulaciones de Indicaciones (Para APIs de OpenAI/Claude/Scale, Window/OpenRouter y Modo Instrucción)",
"Insert {{original}} into either box to include the respective default prompt from system settings.": "Inserte {{original}} en cualquiera de las casillas para incluir la indicación predeterminada respectiva de la configuración del sistema.", "Insert {{original}} into either box to include the respective default prompt from system settings.": "Inserte {{original}} en cualquiera de las casillas para incluir las indicaciones predeterminadas respectivas de la configuración del sistema.",
"Main Prompt": "Indicación Principal", "Main Prompt": "Indicaciones Principales",
"Jailbreak": "Jailbreak", "Jailbreak": "Jailbreak",
"Creator's Metadata (Not sent with the AI prompt)": "Metadatos del Creador (No enviados con la indicación de la IA)", "Creator's Metadata (Not sent with the AI prompt)": "Metadatos del Creador (No enviados con las indicaciones de la IA)",
"Everything here is optional": "Todo aquí es opcional", "Everything here is optional": "Todo aquí es opcional",
"Created by": "Creado por", "Created by": "Creado por",
"Character Version": "Versión del Personaje", "Character Version": "Versión del Personaje",
@ -641,11 +641,11 @@
"Important to set the character's writing style.": "Importante para establecer el estilo de escritura del personaje.", "Important to set the character's writing style.": "Importante para establecer el estilo de escritura del personaje.",
"ATTENTION!": "¡ATENCIÓN!", "ATTENTION!": "¡ATENCIÓN!",
"Samplers Order": "Orden de Muestreadores", "Samplers Order": "Orden de Muestreadores",
"Samplers will be applied in a top-down order. Use with caution.": "Los Muestreadores se aplicarán en un orden de arriba hacia abajo. Úselo con precaución.", "Samplers will be applied in a top-down order. Use with caution.": "Los Muestreadores se aplicarán en un orden de arriba hacia abajo. Úsalo con precaución.",
"Repetition Penalty": "Penalización por Repetición", "Repetition Penalty": "Penalización por Repetición",
"Rep. Pen. Range.": "Rango de Pen. Rep.", "Rep. Pen. Range.": "Rango de Pen. Rep.",
"Rep. Pen. Freq.": "Frec. Pen. Rep.", "Rep. Pen. Freq.": "Frec. de Pen. Rep.",
"Rep. Pen. Presence": "Presencia Pen. Rep.", "Rep. Pen. Presence": "Presencia de Pen. Rep.",
"Enter it in the box below:": "Introdúzcalo en la casilla de abajo:", "Enter it in the box below:": "Introdúzcalo en la casilla de abajo:",
"separate with commas w/o space between": "separe con comas sin espacio entre ellas", "separate with commas w/o space between": "separe con comas sin espacio entre ellas",
"Document": "Documento", "Document": "Documento",
@ -658,7 +658,7 @@
"Editing:": "Editando:", "Editing:": "Editando:",
"AI reply prefix": "Prefijo de Respuesta de IA", "AI reply prefix": "Prefijo de Respuesta de IA",
"Custom Stopping Strings": "Cadenas de Detención Personalizadas", "Custom Stopping Strings": "Cadenas de Detención Personalizadas",
"JSON serialized array of strings": "Arreglo serializado JSON de cadenas", "JSON serialized array of strings": "Arreglo de cadenas serializado en JSON",
"words you dont want generated separated by comma ','": "palabras que no desea generar separadas por coma ','", "words you dont want generated separated by comma ','": "palabras que no desea generar separadas por coma ','",
"Extensions URL": "URL de Extensiones", "Extensions URL": "URL de Extensiones",
"API Key": "Clave de API", "API Key": "Clave de API",
@ -670,10 +670,10 @@
"Chat Name (Optional)": "Nombre del Chat (Opcional)", "Chat Name (Optional)": "Nombre del Chat (Opcional)",
"Filter...": "Filtrar...", "Filter...": "Filtrar...",
"Search...": "Buscar...", "Search...": "Buscar...",
"Any contents here will replace the default Main Prompt used for this character. (v2 spec: system_prompt)": "Cualquier contenido aquí reemplazará la Indicación Principal predeterminada utilizada para este personaje. (v2 especificación: system_prompt)", "Any contents here will replace the default Main Prompt used for this character. (v2 spec: system_prompt)": "Cualquier contenido aquí reemplazará las Indicaciones Principales predeterminada utilizada para este personaje. (especificación v2: system_prompt)",
"Any contents here will replace the default Jailbreak Prompt used for this character. (v2 spec: post_history_instructions)": "Cualquier contenido aquí reemplazará la Indicación de Desbloqueo predeterminada utilizada para este personaje. (v2 especificación: post_history_instructions)", "Any contents here will replace the default Jailbreak Prompt used for this character. (v2 spec: post_history_instructions)": "Cualquier contenido aquí reemplazará las Indicaciones de Jailbreak predeterminada utilizada para este personaje. (especificación v2: post_history_instructions)",
"(Botmaker's name / Contact Info)": "(Nombre del creador del bot / Información de contacto)", "(Botmaker's name / Contact Info)": "(Nombre del creador del bot / Información de contacto)",
"(If you want to track character versions)": "(Si desea rastrear las versiones de los personajes)", "(If you want to track character versions)": "(Si desea rastrear versiones de personajes)",
"(Describe the bot, give use tips, or list the chat models it has been tested on. This will be displayed in the character list.)": "(Describa el bot, dé consejos de uso o enumere los modelos de chat en los que se ha probado. Esto se mostrará en la lista de personajes.)", "(Describe the bot, give use tips, or list the chat models it has been tested on. This will be displayed in the character list.)": "(Describa el bot, dé consejos de uso o enumere los modelos de chat en los que se ha probado. Esto se mostrará en la lista de personajes.)",
"(Write a comma-separated list of tags)": "(Escriba una lista de etiquetas separadas por comas)", "(Write a comma-separated list of tags)": "(Escriba una lista de etiquetas separadas por comas)",
"(A brief description of the personality)": "(Una breve descripción de la personalidad)", "(A brief description of the personality)": "(Una breve descripción de la personalidad)",
@ -694,19 +694,19 @@
"Not connected to API!": "¡No conectado a la API!", "Not connected to API!": "¡No conectado a la API!",
"AI Response Configuration": "Configuración de Respuesta de IA", "AI Response Configuration": "Configuración de Respuesta de IA",
"AI Configuration panel will stay open": "El panel de Configuración de IA permanecerá abierto", "AI Configuration panel will stay open": "El panel de Configuración de IA permanecerá abierto",
"Update current preset": "Actualizar la configuración actual", "Update current preset": "Actualizar el preajuste actual",
"Create new preset": "Crear nueva configuración", "Create new preset": "Crear nuevo preajuste",
"Import preset": "Importar configuración", "Import preset": "Importar preajuste",
"Export preset": "Exportar configuración", "Export preset": "Exportar preajuste",
"Delete the preset": "Eliminar la configuración", "Delete the preset": "Eliminar el preajuste",
"Auto-select this preset for Instruct Mode": "Auto-seleccionar esta configuración para el Modo Instrucción", "Auto-select this preset for Instruct Mode": "Auto-seleccionar este preajuste para el Modo Instrucción",
"Auto-select this preset on API connection": "Auto-seleccionar esta configuración en la conexión de la API", "Auto-select this preset on API connection": "Auto-seleccionar este preajuste en la conexión de la API",
"NSFW block goes first in the resulting prompt": "El bloque NSFW va primero en la indicación resultante", "NSFW block goes first in the resulting prompt": "El bloque NSFW va primero en la indicación resultante",
"Enables OpenAI completion streaming": "Permite la transmisión de completado de OpenAI", "Enables OpenAI completion streaming": "Permite streaming de completado de OpenAI",
"Wrap user messages in quotes before sending": "Envolver los mensajes de usuario entre comillas antes de enviarlos", "Wrap user messages in quotes before sending": "Envolver los mensajes de usuario entre comillas antes de enviarlos",
"Restore default prompt": "Restaurar la indicación predeterminada", "Restore default prompt": "Restaurar las indicaciones predeterminada",
"New preset": "Nueva configuración", "New preset": "Nuevo preajuste",
"Delete preset": "Eliminar configuración", "Delete preset": "Eliminar preajuste",
"Restore default jailbreak": "Restaurar el jailbreak predeterminado", "Restore default jailbreak": "Restaurar el jailbreak predeterminado",
"Restore default reply": "Restaurar la respuesta predeterminada", "Restore default reply": "Restaurar la respuesta predeterminada",
"Restore default note": "Restaurar la nota predeterminada", "Restore default note": "Restaurar la nota predeterminada",
@ -715,21 +715,21 @@
"Clear your API key": "Borrar tu clave de API", "Clear your API key": "Borrar tu clave de API",
"Refresh models": "Actualizar modelos", "Refresh models": "Actualizar modelos",
"Get your OpenRouter API token using OAuth flow. You will be redirected to openrouter.ai": "Obtenga su token de API de OpenRouter utilizando el flujo OAuth. Será redirigido a openrouter.ai", "Get your OpenRouter API token using OAuth flow. You will be redirected to openrouter.ai": "Obtenga su token de API de OpenRouter utilizando el flujo OAuth. Será redirigido a openrouter.ai",
"Verifies your API connection by sending a short test message. Be aware that you'll be credited for it!": "Verifica su conexión de API enviando un breve mensaje de prueba. ¡Tenga en cuenta que se le acreditará por ello!", "Verifies your API connection by sending a short test message. Be aware that you'll be credited for it!": "Verifica su conexión de API enviando un breve mensaje de prueba. ¡Tenga en cuenta que se le cobrará por ello!",
"Create New": "Crear Nuevo", "Create New": "Crear Nuevo",
"Edit": "Editar", "Edit": "Editar",
"Locked = World Editor will stay open": "Bloqueado = El Editor de Mundo permanecerá abierto", "Locked = World Editor will stay open": "Bloqueado = El Editor de Mundo permanecerá abierto",
"Entries can activate other entries by mentioning their keywords": "Las entradas pueden activar otras entradas mencionando sus palabras clave", "Entries can activate other entries by mentioning their keywords": "Las entradas pueden activar otras entradas mencionando sus palabras clave",
"Lookup for the entry keys in the context will respect the case": "La búsqueda de las claves de entrada en el contexto respetará el caso", "Lookup for the entry keys in the context will respect the case": "La búsqueda de las claves de entrada en el contexto respetará mayúsculas y minúsculas",
"If the entry key consists of only one word, it would not be matched as part of other words": "Si la clave de entrada consiste en solo una palabra, no se emparejará como parte de otras palabras", "If the entry key consists of only one word, it would not be matched as part of other words": "Si la clave de entrada consiste en solo una palabra, no se emparejará como parte de otras palabras",
"Open all Entries": "Abrir Todas las Entradas", "Open all Entries": "Abrir Todas las Entradas",
"Close all Entries": "Cerrar Todas las Entradas", "Close all Entries": "Cerrar Todas las Entradas",
"Create": "Crear", "Create": "Crear",
"Import World Info": "Importar Información del Mundo", "Import World Info": "Importar Información de Mundo (WI)",
"Export World Info": "Exportar Información del Mundo", "Export World Info": "Exportar Información de Mundo (WI)",
"Delete World Info": "Eliminar Información del Mundo", "Delete World Info": "Eliminar Información de Mundo (WI)",
"Duplicate World Info": "Duplicar Información del Mundo", "Duplicate World Info": "Duplicar Información de Mundo (WI)",
"Rename World Info": "Renombrar Información del Mundo", "Rename World Info": "Renombrar Información de Mundo (WI)",
"Refresh": "Actualizar", "Refresh": "Actualizar",
"Primary Keywords": "Palabras Clave Primarias", "Primary Keywords": "Palabras Clave Primarias",
"Logic": "Lógica", "Logic": "Lógica",
@ -752,13 +752,13 @@
"Character Management": "Gestión de Personajes", "Character Management": "Gestión de Personajes",
"Locked = Character Management panel will stay open": "Bloqueado = El panel de Gestión de Personajes permanecerá abierto", "Locked = Character Management panel will stay open": "Bloqueado = El panel de Gestión de Personajes permanecerá abierto",
"Select/Create Characters": "Seleccionar/Crear Personajes", "Select/Create Characters": "Seleccionar/Crear Personajes",
"Token counts may be inaccurate and provided just for reference.": "Las cuentas de tokens pueden ser inexactas y se proporcionan solo como referencia.", "Token counts may be inaccurate and provided just for reference.": "El conteo de tokens pueden ser inexacto y se proporcionan solo como referencia.",
"Click to select a new avatar for this character": "Haga clic para seleccionar un nuevo avatar para este personaje", "Click to select a new avatar for this character": "Haga clic para seleccionar un nuevo avatar para este personaje",
"Example: [{{user}} is a 28-year-old Romanian cat girl.]": "Ejemplo: [{{user}} es una chica gata rumana de 28 años.]", "Example: [{{user}} is a 28-year-old Romanian cat girl.]": "Ejemplo: [{{user}} es una chica gata rumana de 28 años.]",
"Toggle grid view": "Alternar vista de cuadrícula", "Toggle grid view": "Alternar vista de cuadrícula",
"Add to Favorites": "Agregar a Favoritos", "Add to Favorites": "Agregar a Favoritos",
"Advanced Definition": "Definición Avanzada", "Advanced Definition": "Definición Avanzada",
"Character Lore": "Trasfondo del personaje", "Character Lore": "Historia (Trasfondo) del personaje",
"Export and Download": "Exportar y descargar", "Export and Download": "Exportar y descargar",
"Duplicate Character": "Duplicar personaje", "Duplicate Character": "Duplicar personaje",
"Create Character": "Crear personaje", "Create Character": "Crear personaje",
@ -769,21 +769,21 @@
"Click to select a new avatar for this group": "Haz clic para seleccionar un nuevo avatar para este grupo", "Click to select a new avatar for this group": "Haz clic para seleccionar un nuevo avatar para este grupo",
"Set a group chat scenario": "Establecer un escenario de chat grupal", "Set a group chat scenario": "Establecer un escenario de chat grupal",
"Restore collage avatar": "Restaurar avatar de collage", "Restore collage avatar": "Restaurar avatar de collage",
"Create New Character": "Crear nuevo personaje", "Create New Character": "Crear Nuevo Personaje",
"Import Character from File": "Importar personaje desde archivo", "Import Character from File": "Importar Personaje desde Archivo",
"Import content from external URL": "Importar contenido desde URL externa", "Import content from external URL": "Importar contenido desde URL externa",
"Create New Chat Group": "Crear nuevo grupo de chat", "Create New Chat Group": "Crear Nuevo Grupo de Chat",
"Characters sorting order": "Orden de clasificación de personajes", "Characters sorting order": "Orden de clasificación de personajes",
"Add chat injection": "Agregar inyección de chat", "Add chat injection": "Agregar inyección de chat",
"Remove injection": "Eliminar inyección", "Remove injection": "Eliminar inyección",
"Remove": "Eliminar", "Remove": "Eliminar",
"Select a World Info file for": "Seleccionar un archivo de Información Mundial para", "Select a World Info file for": "Seleccionar un archivo de Información de Mundo (WI) para",
"Primary Lorebook": "Libro de historias primario", "Primary Lorebook": "Libro de Historia primario",
"A selected World Info will be bound to this character as its own Lorebook.": "Una Información Mundial seleccionada se vinculará a este personaje como su propio Libro de historias.", "A selected World Info will be bound to this character as its own Lorebook.": "Una Información de Mundo (WI) seleccionada se vinculará a este personaje como su propio Libro de Historia.",
"When generating an AI reply, it will be combined with the entries from a global World Info selector.": "Al generar una respuesta de IA, se combinará con las entradas de un selector global de Información Mundial.", "When generating an AI reply, it will be combined with the entries from a global World Info selector.": "Al generar una respuesta de IA, se combinará con las entradas de un selector global de Información Mundial.",
"Exporting a character would also export the selected Lorebook file embedded in the JSON data.": "Exportar un personaje también exportaría el archivo de Libro de historias seleccionado incrustado en los datos JSON.", "Exporting a character would also export the selected Lorebook file embedded in the JSON data.": "Exportar un personaje también exportaría el archivo de Libro de Historia seleccionado incrustado en los datos JSON.",
"Additional Lorebooks": "Libros de historias adicionales", "Additional Lorebooks": "Libros de Historia Adicionales",
"Associate one or more auxillary Lorebooks with this character.": "Asociar uno o más Libros de historias auxiliares con este personaje.", "Associate one or more auxillary Lorebooks with this character.": "Asociar uno o más Libros de Historia auxiliares con este personaje.",
"NOTE: These choices are optional and won't be preserved on character export!": "NOTA: ¡Estas opciones son opcionales y no se conservarán al exportar el personaje!", "NOTE: These choices are optional and won't be preserved on character export!": "NOTA: ¡Estas opciones son opcionales y no se conservarán al exportar el personaje!",
"Rename chat file": "Renombrar archivo de chat", "Rename chat file": "Renombrar archivo de chat",
"Export JSONL chat file": "Exportar archivo de chat JSONL", "Export JSONL chat file": "Exportar archivo de chat JSONL",
@ -815,19 +815,19 @@
"Abort request": "Cancelar solicitud", "Abort request": "Cancelar solicitud",
"Send a message": "Enviar un mensaje", "Send a message": "Enviar un mensaje",
"Ask AI to write your message for you": "Pídele a la IA que escriba tu mensaje por ti", "Ask AI to write your message for you": "Pídele a la IA que escriba tu mensaje por ti",
"Continue the last message": "Continuar con el último mensaje", "Continue the last message": "Continuar el último mensaje",
"Bind user name to that avatar": "Vincular nombre de usuario a ese avatar", "Bind user name to that avatar": "Vincular nombre de usuario a ese avatar",
"Select this as default persona for the new chats.": "Seleccionar esto como persona predeterminada para los nuevos chats.", "Select this as default persona for the new chats.": "Seleccionar esta persona como predeterminada para los nuevos chats.",
"Change persona image": "Cambiar imagen de persona", "Change persona image": "Cambiar imagen de persona",
"Delete persona": "Eliminar persona", "Delete persona": "Eliminar persona",
"Reduced Motion": "Movimiento reducido", "Reduced Motion": "Movimiento reducido",
"Auto-select": "Auto-seleccionar", "Auto-select": "Auto-seleccionar",
"Automatically select a background based on the chat context": "Seleccionar automáticamente un fondo basado en el contexto del chat", "Automatically select a background based on the chat context": "Seleccionar automáticamente un fondo basado en el contexto del chat",
"Filter": "Filtro", "Filter": "Filtro",
"Exclude message from prompts": "Excluir mensaje de indicaciones", "Exclude message from prompts": "Excluir mensaje de las indicaciones",
"Include message in prompts": "Incluir mensaje en indicaciones", "Include message in prompts": "Incluir mensaje en las indicaciones",
"Create checkpoint": "Crear punto de control", "Create checkpoint": "Crear punto de control",
"Create Branch": "Crear rama", "Create Branch": "Crear Rama",
"Embed file or image": "Insertar archivo o imagen", "Embed file or image": "Insertar archivo o imagen",
"UI Theme": "Tema de interfaz de usuario", "UI Theme": "Tema de interfaz de usuario",
"This message is invisible for the AI": "Este mensaje es invisible para la IA", "This message is invisible for the AI": "Este mensaje es invisible para la IA",
@ -837,7 +837,7 @@
"Max Tokens Second": "Máximo de tokens por segundo", "Max Tokens Second": "Máximo de tokens por segundo",
"CFG": "CFG", "CFG": "CFG",
"No items": "Sin elementos", "No items": "Sin elementos",
"Extras API key (optional)": "Clave API de extras (opcional)", "Extras API key (optional)": "Clave API de Extras (opcional)",
"Notify on extension updates": "Notificar sobre actualizaciones de extensión", "Notify on extension updates": "Notificar sobre actualizaciones de extensión",
"Toggle character grid view": "Alternar vista de cuadrícula de personajes", "Toggle character grid view": "Alternar vista de cuadrícula de personajes",
"Bulk edit characters": "Editar personajes masivamente", "Bulk edit characters": "Editar personajes masivamente",
@ -854,7 +854,7 @@
"Most tokens": "Más tokens", "Most tokens": "Más tokens",
"Least tokens": "Menos tokens", "Least tokens": "Menos tokens",
"Random": "Aleatorio", "Random": "Aleatorio",
"Skip Example Dialogues Formatting": "Omitir formato de diálogos de ejemplo", "Skip Example Dialogues Formatting": "Omitir Formato de Diálogos de Ejemplo",
"Import a theme file": "Importar un archivo de tema", "Import a theme file": "Importar un archivo de tema",
"Export a theme file": "Exportar un archivo de tema", "Export a theme file": "Exportar un archivo de tema",
"Unlocked Context Size": "Tamaño de contexto desbloqueado", "Unlocked Context Size": "Tamaño de contexto desbloqueado",
@ -866,33 +866,33 @@
"Utility Prompts": "Indicaciones de utilidad", "Utility Prompts": "Indicaciones de utilidad",
"Add character names": "Agregar nombres de personajes", "Add character names": "Agregar nombres de personajes",
"Send names in the message objects. Helps the model to associate messages with characters.": "Enviar nombres en los objetos de mensaje. Ayuda al modelo a asociar mensajes con personajes.", "Send names in the message objects. Helps the model to associate messages with characters.": "Enviar nombres en los objetos de mensaje. Ayuda al modelo a asociar mensajes con personajes.",
"Continue prefill": "Continuar con prefiltro", "Continue prefill": "Continuar con prellenado",
"Continue sends the last message as assistant role instead of system message with instruction.": "Continuar envía el último mensaje como rol de asistente en lugar de mensaje del sistema con instrucciones.", "Continue sends the last message as assistant role instead of system message with instruction.": "Continuar envía el último mensaje como rol de asistente en lugar de mensaje del sistema con instrucciones.",
"Squash system messages": "Aplastar mensajes del sistema", "Squash system messages": "Aplastar mensajes del sistema",
"Combines consecutive system messages into one (excluding example dialogues). May improve coherence for some models.": "Combina mensajes del sistema consecutivos en uno solo (excluyendo diálogos de ejemplo). Puede mejorar la coherencia para algunos modelos.", "Combines consecutive system messages into one (excluding example dialogues). May improve coherence for some models.": "Combina mensajes del sistema consecutivos en uno solo (excluyendo diálogos de ejemplo). Puede mejorar la coherencia para algunos modelos.",
"Send inline images": "Enviar imágenes en línea", "Send inline images": "Enviar imágenes en línea",
"Assistant Prefill": "Prefiltro de asistente", "Assistant Prefill": "Prellenado de Asistente",
"Start Claude's answer with...": "Iniciar la respuesta de Claude con...", "Start Claude's answer with...": "Iniciar la respuesta de Claude con...",
"Use system prompt (Claude 2.1+ only)": "Usar indicación del sistema (solo Claude 2.1+)", "Use system prompt (Claude 2.1+ only)": "Usar indicación del sistema (solo para Claude 2.1+)",
"Send the system prompt for supported models. If disabled, the user message is added to the beginning of the prompt.": "Enviar la indicación del sistema para los modelos admitidos. Si está desactivado, el mensaje del usuario se agrega al principio de la indicación.", "Send the system prompt for supported models. If disabled, the user message is added to the beginning of the prompt.": "Enviar la indicación del sistema para los modelos admitidos. Si está desactivado, el mensaje del usuario se agrega al principio de las indicaciónes.",
"Prompts": "Indicaciones", "Prompts": "Indicaciones",
"Total Tokens:": "Tokens totales:", "Total Tokens:": "Tokens totales:",
"Insert prompt": "Insertar indicación", "Insert prompt": "Insertar indicaciones",
"Delete prompt": "Eliminar indicación", "Delete prompt": "Eliminar indicaciones",
"Import a prompt list": "Importar una lista de indicaciones", "Import a prompt list": "Importar una lista de indicaciones",
"Export this prompt list": "Exportar esta lista de indicaciones", "Export this prompt list": "Exportar esta lista de indicaciones",
"Reset current character": "Restablecer personaje actual", "Reset current character": "Restablecer personaje actual",
"New prompt": "Nueva indicación", "New prompt": "Nuevas indicaciones",
"Tokens": "Tokens", "Tokens": "Tokens",
"Want to update?": "¿Quieres actualizar?", "Want to update?": "¿Quieres actualizar?",
"How to start chatting?": "¿Cómo empezar a chatear?", "How to start chatting?": "¿Cómo empezar a chatear?",
"Click": "Haz clic ", "Click": "Haz clic ",
"and select a": "y selecciona un", "and select a": "y selecciona una",
"Chat API": " API de chat", "Chat API": " API de chat",
"and pick a character": "y elige un personaje", "and pick a character": "y elige un personaje",
"in the chat bar": "en la barra de chat", "in the chat bar": "en la barra de chat",
"Confused or lost?": "¿Confundido o perdido?", "Confused or lost?": "¿Confundido o perdido?",
"click these icons!": haz clic en estos iconos!", "click these icons!": Haz clic en estos iconos!",
"SillyTavern Documentation Site": "Sitio de documentación de SillyTavern", "SillyTavern Documentation Site": "Sitio de documentación de SillyTavern",
"Extras Installation Guide": "Guía de instalación de extras", "Extras Installation Guide": "Guía de instalación de extras",
"Still have questions?": "¿Todavía tienes preguntas?", "Still have questions?": "¿Todavía tienes preguntas?",
@ -909,10 +909,10 @@
"Medium": "Medio", "Medium": "Medio",
"Aggressive": "Agresivo", "Aggressive": "Agresivo",
"Very aggressive": "Muy agresivo", "Very aggressive": "Muy agresivo",
"Eta cutoff is the main parameter of the special Eta Sampling technique.&#13;In units of 1e-4; a reasonable value is 3.&#13;Set to 0 to disable.&#13;See the paper Truncation Sampling as Language Model Desmoothing by Hewitt et al. (2022) for details.": "El corte de Eta es el parámetro principal de la técnica especial de Muestreo Eta.&#13;En unidades de 1e-4; un valor razonable es 3.&#13;Establecer en 0 para desactivar.&#13;Consulte el documento Truncation Sampling as Language Model Desmoothing de Hewitt et al. (2022) para más detalles.", "Eta cutoff is the main parameter of the special Eta Sampling technique.&#13;In units of 1e-4; a reasonable value is 3.&#13;Set to 0 to disable.&#13;See the paper Truncation Sampling as Language Model Desmoothing by Hewitt et al. (2022) for details.": "El Corte de Eta es el parámetro principal de la técnica especial de Muestreo Eta.&#13;En unidades de 1e-4; un valor razonable es 3.&#13;Establecer en 0 para desactivar.&#13;Consulte el documento Truncation Sampling as Language Model Desmoothing de Hewitt et al. (2022) para más detalles.",
"Learn how to contribute your idle GPU cycles to the Horde": "Aprende cómo contribuir con tus ciclos de GPU inactivos a la Horda", "Learn how to contribute your idle GPU cycles to the Horde": "Aprende cómo contribuir con tus ciclos de GPU inactivos a Horde",
"Use the appropriate tokenizer for Google models via their API. Slower prompt processing, but offers much more accurate token counting.": "Usa el tokenizador apropiado para los modelos de Google a través de su API. Procesamiento de indicaciones más lento, pero ofrece un recuento de tokens mucho más preciso.", "Use the appropriate tokenizer for Google models via their API. Slower prompt processing, but offers much more accurate token counting.": "Usa el tokenizador apropiado para los modelos de Google a través de su API. Procesamiento de indicaciones más lento, pero ofrece un recuento de tokens mucho más preciso.",
"Load koboldcpp order": "Cargar orden koboldcpp", "Load koboldcpp order": "Cargar orden de koboldcpp",
"Use Google Tokenizer": "Usar Tokenizador de Google" "Use Google Tokenizer": "Usar Tokenizador de Google"

View File

@ -208,9 +208,10 @@ import { getBackgrounds, initBackgrounds, loadBackgroundSettings, background_set
import { hideLoader, showLoader } from './scripts/loader.js'; import { hideLoader, showLoader } from './scripts/loader.js';
import { BulkEditOverlay, CharacterContextMenu } from './scripts/BulkEditOverlay.js'; import { BulkEditOverlay, CharacterContextMenu } from './scripts/BulkEditOverlay.js';
import { loadMancerModels, loadOllamaModels, loadTogetherAIModels, loadInfermaticAIModels, loadOpenRouterModels, loadAphroditeModels, loadDreamGenModels } from './scripts/textgen-models.js'; import { loadMancerModels, loadOllamaModels, loadTogetherAIModels, loadInfermaticAIModels, loadOpenRouterModels, loadAphroditeModels, loadDreamGenModels } from './scripts/textgen-models.js';
import { appendFileContent, hasPendingFileAttachment, populateFileAttachment, decodeStyleTags, encodeStyleTags } from './scripts/chats.js'; import { appendFileContent, hasPendingFileAttachment, populateFileAttachment, decodeStyleTags, encodeStyleTags, isExternalMediaAllowed, getCurrentEntityId } from './scripts/chats.js';
import { initPresetManager } from './scripts/preset-manager.js'; import { initPresetManager } from './scripts/preset-manager.js';
import { evaluateMacros } from './scripts/macros.js'; import { evaluateMacros } from './scripts/macros.js';
import { callGenericPopup } from './scripts/popup.js';
//exporting functions and vars for mods //exporting functions and vars for mods
export { export {
@ -324,10 +325,13 @@ DOMPurify.addHook('uponSanitizeElement', (node, _, config) => {
return; return;
} }
if (!power_user.forbid_external_images) { const isMediaAllowed = isExternalMediaAllowed();
if (isMediaAllowed) {
return; return;
} }
let mediaBlocked = false;
switch (node.tagName) { switch (node.tagName) {
case 'AUDIO': case 'AUDIO':
case 'VIDEO': case 'VIDEO':
@ -350,6 +354,7 @@ DOMPurify.addHook('uponSanitizeElement', (node, _, config) => {
if (isExternalUrl(url)) { if (isExternalUrl(url)) {
console.warn('External media blocked', url); console.warn('External media blocked', url);
node.remove(); node.remove();
mediaBlocked = true;
break; break;
} }
} }
@ -357,16 +362,37 @@ DOMPurify.addHook('uponSanitizeElement', (node, _, config) => {
if (src && isExternalUrl(src)) { if (src && isExternalUrl(src)) {
console.warn('External media blocked', src); console.warn('External media blocked', src);
mediaBlocked = true;
node.remove(); node.remove();
} }
if (data && isExternalUrl(data)) { if (data && isExternalUrl(data)) {
console.warn('External media blocked', data); console.warn('External media blocked', data);
mediaBlocked = true;
node.remove(); node.remove();
} }
} }
break; break;
} }
if (mediaBlocked) {
const entityId = getCurrentEntityId();
const warningShownKey = `mediaWarningShown:${entityId}`;
if (localStorage.getItem(warningShownKey) === null) {
const warningToast = toastr.warning(
'Use the "Ext. Media" button to allow it. Click on this message to dismiss.',
'External media has been blocked',
{
timeOut: 0,
preventDuplicates: true,
onclick: () => toastr.clear(warningToast),
},
);
localStorage.setItem(warningShownKey, 'true');
}
}
}); });
// API OBJECT FOR EXTERNAL WIRING // API OBJECT FOR EXTERNAL WIRING
@ -752,7 +778,6 @@ function reloadMarkdownProcessor(render_formulas = false) {
} }
function getCurrentChatId() { function getCurrentChatId() {
console.debug(`selectedGroup:${selected_group}, this_chid:${this_chid}`);
if (selected_group) { if (selected_group) {
return groups.find(x => x.id == selected_group)?.chat_id; return groups.find(x => x.id == selected_group)?.chat_id;
} }
@ -797,7 +822,7 @@ let create_save = {
//animation right menu //animation right menu
export const ANIMATION_DURATION_DEFAULT = 125; export const ANIMATION_DURATION_DEFAULT = 125;
export let animation_duration = ANIMATION_DURATION_DEFAULT; export let animation_duration = ANIMATION_DURATION_DEFAULT;
let animation_easing = 'ease-in-out'; export let animation_easing = 'ease-in-out';
let popup_type = ''; let popup_type = '';
let chat_file_for_del = ''; let chat_file_for_del = '';
let online_status = 'no_connection'; let online_status = 'no_connection';
@ -1693,7 +1718,7 @@ export async function reloadCurrentChat() {
chat.length = 0; chat.length = 0;
if (selected_group) { if (selected_group) {
await getGroupChat(selected_group); await getGroupChat(selected_group, true);
} }
else if (this_chid) { else if (this_chid) {
await getChat(); await getChat();
@ -3442,7 +3467,6 @@ async function Generate(type, { automatic_trigger, force_name2, quiet_prompt, qu
// Add persona description to prompt // Add persona description to prompt
addPersonaDescriptionExtensionPrompt(); addPersonaDescriptionExtensionPrompt();
// Call combined AN into Generate // Call combined AN into Generate
let allAnchors = getAllExtensionPrompts();
const beforeScenarioAnchor = getExtensionPrompt(extension_prompt_types.BEFORE_PROMPT).trimStart(); const beforeScenarioAnchor = getExtensionPrompt(extension_prompt_types.BEFORE_PROMPT).trimStart();
const afterScenarioAnchor = getExtensionPrompt(extension_prompt_types.IN_PROMPT); const afterScenarioAnchor = getExtensionPrompt(extension_prompt_types.IN_PROMPT);
@ -3489,10 +3513,11 @@ async function Generate(type, { automatic_trigger, force_name2, quiet_prompt, qu
function getMessagesTokenCount() { function getMessagesTokenCount() {
const encodeString = [ const encodeString = [
beforeScenarioAnchor,
storyString, storyString,
afterScenarioAnchor,
examplesString, examplesString,
chatString, chatString,
allAnchors,
quiet_prompt, quiet_prompt,
cyclePrompt, cyclePrompt,
userAlignmentMessage, userAlignmentMessage,
@ -3760,12 +3785,13 @@ async function Generate(type, { automatic_trigger, force_name2, quiet_prompt, qu
console.debug('---checking Prompt size'); console.debug('---checking Prompt size');
setPromptString(); setPromptString();
const prompt = [ const prompt = [
beforeScenarioAnchor,
storyString, storyString,
afterScenarioAnchor,
mesExmString, mesExmString,
mesSend.map((e) => `${e.extensionPrompts.join('')}${e.message}`).join(''), mesSend.map((e) => `${e.extensionPrompts.join('')}${e.message}`).join(''),
'\n', '\n',
generatedPromptCache, generatedPromptCache,
allAnchors,
quiet_prompt, quiet_prompt,
].join('').replace(/\r/gm, ''); ].join('').replace(/\r/gm, '');
let thisPromptContextSize = getTokenCount(prompt, power_user.token_padding); let thisPromptContextSize = getTokenCount(prompt, power_user.token_padding);
@ -4001,7 +4027,8 @@ async function Generate(type, { automatic_trigger, force_name2, quiet_prompt, qu
...thisPromptBits[currentArrayEntry], ...thisPromptBits[currentArrayEntry],
rawPrompt: generate_data.prompt || generate_data.input, rawPrompt: generate_data.prompt || generate_data.input,
mesId: getNextMessageId(type), mesId: getNextMessageId(type),
allAnchors: allAnchors, allAnchors: getAllExtensionPrompts(),
chatInjects: injectedIndices?.map(index => arrMes[arrMes.length - index - 1])?.join('') || '',
summarizeString: (extension_prompts['1_memory']?.value || ''), summarizeString: (extension_prompts['1_memory']?.value || ''),
authorsNoteString: (extension_prompts['2_floating_prompt']?.value || ''), authorsNoteString: (extension_prompts['2_floating_prompt']?.value || ''),
smartContextString: (extension_prompts['chromadb']?.value || ''), smartContextString: (extension_prompts['chromadb']?.value || ''),
@ -4548,7 +4575,7 @@ function addChatsPreamble(mesSendString) {
function addChatsSeparator(mesSendString) { function addChatsSeparator(mesSendString) {
if (power_user.context.chat_start) { if (power_user.context.chat_start) {
return substituteParams(power_user.context.chat_start) + '\n' + mesSendString; return substituteParams(power_user.context.chat_start + '\n') + mesSendString;
} }
else { else {
@ -4625,8 +4652,13 @@ function promptItemize(itemizedPrompts, requestedMesId) {
zeroDepthAnchorTokens: getTokenCount(itemizedPrompts[thisPromptSet].zeroDepthAnchor), // TODO: unused zeroDepthAnchorTokens: getTokenCount(itemizedPrompts[thisPromptSet].zeroDepthAnchor), // TODO: unused
thisPrompt_padding: itemizedPrompts[thisPromptSet].padding, thisPrompt_padding: itemizedPrompts[thisPromptSet].padding,
this_main_api: itemizedPrompts[thisPromptSet].main_api, this_main_api: itemizedPrompts[thisPromptSet].main_api,
chatInjects: getTokenCount(itemizedPrompts[thisPromptSet].chatInjects),
}; };
if (params.chatInjects){
params.ActualChatHistoryTokens = params.ActualChatHistoryTokens - params.chatInjects;
}
if (params.this_main_api == 'openai') { if (params.this_main_api == 'openai') {
//for OAI API //for OAI API
//console.log('-- Counting OAI Tokens'); //console.log('-- Counting OAI Tokens');
@ -6900,6 +6932,12 @@ export function select_selected_character(chid) {
$('#form_create').attr('actiontype', 'editcharacter'); $('#form_create').attr('actiontype', 'editcharacter');
$('.form_create_bottom_buttons_block .chat_lorebook_button').show(); $('.form_create_bottom_buttons_block .chat_lorebook_button').show();
const externalMediaState = isExternalMediaAllowed();
$('#character_open_media_overrides').toggle(!selected_group);
$('#character_media_allowed_icon').toggle(externalMediaState);
$('#character_media_forbidden_icon').toggle(!externalMediaState);
saveSettingsDebounced(); saveSettingsDebounced();
} }
@ -6960,6 +6998,7 @@ function select_rm_create() {
$('#form_create').attr('actiontype', 'createcharacter'); $('#form_create').attr('actiontype', 'createcharacter');
$('.form_create_bottom_buttons_block .chat_lorebook_button').hide(); $('.form_create_bottom_buttons_block .chat_lorebook_button').hide();
$('#character_open_media_overrides').hide();
} }
function select_rm_characters() { function select_rm_characters() {
@ -7777,6 +7816,7 @@ window['SillyTavern'].getContext = function () {
registedDebugFunction: registerDebugFunction, registedDebugFunction: registerDebugFunction,
renderExtensionTemplate: renderExtensionTemplate, renderExtensionTemplate: renderExtensionTemplate,
callPopup: callPopup, callPopup: callPopup,
callGenericPopup: callGenericPopup,
mainApi: main_api, mainApi: main_api,
extensionSettings: extension_settings, extensionSettings: extension_settings,
ModuleWorkerWrapper: ModuleWorkerWrapper, ModuleWorkerWrapper: ModuleWorkerWrapper,
@ -9908,14 +9948,14 @@ jQuery(async function () {
$('#character_import_file').click(); $('#character_import_file').click();
}); });
$('#character_import_file').on('change', function (e) { $('#character_import_file').on('change', async function (e) {
$('#rm_info_avatar').html(''); $('#rm_info_avatar').html('');
if (!e.target.files.length) { if (!e.target.files.length) {
return; return;
} }
for (const file of e.target.files) { for (const file of e.target.files) {
importCharacter(file); await importCharacter(file);
} }
}); });

View File

@ -5,6 +5,7 @@ import {
addCopyToCodeBlocks, addCopyToCodeBlocks,
appendMediaToMessage, appendMediaToMessage,
callPopup, callPopup,
characters,
chat, chat,
eventSource, eventSource,
event_types, event_types,
@ -12,9 +13,14 @@ import {
getRequestHeaders, getRequestHeaders,
hideSwipeButtons, hideSwipeButtons,
name2, name2,
reloadCurrentChat,
saveChatDebounced, saveChatDebounced,
saveSettingsDebounced,
showSwipeButtons, showSwipeButtons,
this_chid,
} from '../script.js'; } from '../script.js';
import { selected_group } from './group-chats.js';
import { power_user } from './power-user.js';
import { import {
extractTextFromHTML, extractTextFromHTML,
extractTextFromMarkdown, extractTextFromMarkdown,
@ -416,6 +422,56 @@ export function decodeStyleTags(text) {
}); });
} }
async function openExternalMediaOverridesDialog() {
const entityId = getCurrentEntityId();
if (!entityId) {
toastr.info('No character or group selected');
return;
}
const template = $('#forbid_media_override_template > .forbid_media_override').clone();
template.find('.forbid_media_global_state_forbidden').toggle(power_user.forbid_external_images);
template.find('.forbid_media_global_state_allowed').toggle(!power_user.forbid_external_images);
if (power_user.external_media_allowed_overrides.includes(entityId)) {
template.find('#forbid_media_override_allowed').prop('checked', true);
}
else if (power_user.external_media_forbidden_overrides.includes(entityId)) {
template.find('#forbid_media_override_forbidden').prop('checked', true);
}
else {
template.find('#forbid_media_override_global').prop('checked', true);
}
callPopup(template, 'text', '', { wide: false, large: false });
}
export function getCurrentEntityId() {
if (selected_group) {
return String(selected_group);
}
return characters[this_chid]?.avatar ?? null;
}
export function isExternalMediaAllowed() {
const entityId = getCurrentEntityId();
if (!entityId) {
return !power_user.forbid_external_images;
}
if (power_user.external_media_allowed_overrides.includes(entityId)) {
return true;
}
if (power_user.external_media_forbidden_overrides.includes(entityId)) {
return false;
}
return !power_user.forbid_external_images;
}
jQuery(function () { jQuery(function () {
$(document).on('click', '.mes_hide', async function () { $(document).on('click', '.mes_hide', async function () {
const messageBlock = $(this).closest('.mes'); const messageBlock = $(this).closest('.mes');
@ -511,6 +567,32 @@ jQuery(function () {
$(this).closest('.mes').find('.mes_edit').trigger('click'); $(this).closest('.mes').find('.mes_edit').trigger('click');
}); });
$(document).on('click', '.open_media_overrides', openExternalMediaOverridesDialog);
$(document).on('input', '#forbid_media_override_allowed', function () {
const entityId = getCurrentEntityId();
if (!entityId) return;
power_user.external_media_allowed_overrides.push(entityId);
power_user.external_media_forbidden_overrides = power_user.external_media_forbidden_overrides.filter((v) => v !== entityId);
saveSettingsDebounced();
reloadCurrentChat();
});
$(document).on('input', '#forbid_media_override_forbidden', function () {
const entityId = getCurrentEntityId();
if (!entityId) return;
power_user.external_media_forbidden_overrides.push(entityId);
power_user.external_media_allowed_overrides = power_user.external_media_allowed_overrides.filter((v) => v !== entityId);
saveSettingsDebounced();
reloadCurrentChat();
});
$(document).on('input', '#forbid_media_override_global', function () {
const entityId = getCurrentEntityId();
if (!entityId) return;
power_user.external_media_allowed_overrides = power_user.external_media_allowed_overrides.filter((v) => v !== entityId);
power_user.external_media_forbidden_overrides = power_user.external_media_forbidden_overrides.filter((v) => v !== entityId);
saveSettingsDebounced();
reloadCurrentChat();
});
$('#file_form_input').on('change', onFileAttach); $('#file_form_input').on('change', onFileAttach);
$('#file_form').on('reset', function () { $('#file_form').on('reset', function () {
$('#file_form').addClass('displayNone'); $('#file_form').addClass('displayNone');

View File

@ -103,7 +103,8 @@ function downloadAssetsList(url) {
if (assetType == 'extension') { if (assetType == 'extension') {
assetTypeMenu.append(` assetTypeMenu.append(`
<div class="assets-list-git"> <div class="assets-list-git">
To download extensions from this page, you need to have <a href="https://git-scm.com/downloads" target="_blank">Git</a> installed. To download extensions from this page, you need to have <a href="https://git-scm.com/downloads" target="_blank">Git</a> installed.<br>
Click the <i class="fa-solid fa-sm fa-arrow-up-right-from-square"></i> icon to visit the Extension's repo for tips on how to use it.
</div>`); </div>`);
} }
@ -180,6 +181,7 @@ function downloadAssetsList(url) {
const displayName = DOMPurify.sanitize(asset['name'] || asset['id']); const displayName = DOMPurify.sanitize(asset['name'] || asset['id']);
const description = DOMPurify.sanitize(asset['description'] || ''); const description = DOMPurify.sanitize(asset['description'] || '');
const url = isValidUrl(asset['url']) ? asset['url'] : ''; const url = isValidUrl(asset['url']) ? asset['url'] : '';
const title = assetType === 'extension' ? `Extension repo/guide: ${url}` : 'Preview in browser';
const previewIcon = (assetType === 'extension' || assetType === 'character') ? 'fa-arrow-up-right-from-square' : 'fa-headphones-simple'; const previewIcon = (assetType === 'extension' || assetType === 'character') ? 'fa-arrow-up-right-from-square' : 'fa-headphones-simple';
const assetBlock = $('<i></i>') const assetBlock = $('<i></i>')
@ -187,7 +189,7 @@ function downloadAssetsList(url) {
.append(`<div class="flex-container flexFlowColumn flexNoGap"> .append(`<div class="flex-container flexFlowColumn flexNoGap">
<span class="asset-name flex-container alignitemscenter"> <span class="asset-name flex-container alignitemscenter">
<b>${displayName}</b> <b>${displayName}</b>
<a class="asset_preview" href="${url}" target="_blank" title="Preview in browser"> <a class="asset_preview" href="${url}" target="_blank" title="${title}">
<i class="fa-solid fa-sm ${previewIcon}"></i> <i class="fa-solid fa-sm ${previewIcon}"></i>
</a> </a>
</span> </span>

View File

@ -30,7 +30,7 @@ function migrateSettings() {
if (extension_settings.caption.source === 'openai') { if (extension_settings.caption.source === 'openai') {
extension_settings.caption.source = 'multimodal'; extension_settings.caption.source = 'multimodal';
extension_settings.caption.multimodal_api = 'openai'; extension_settings.caption.multimodal_api = 'openai';
extension_settings.caption.multimodal_model = 'gpt-4-vision-preview'; extension_settings.caption.multimodal_model = 'gpt-4-turbo';
} }
if (!extension_settings.caption.multimodal_api) { if (!extension_settings.caption.multimodal_api) {
@ -38,7 +38,7 @@ function migrateSettings() {
} }
if (!extension_settings.caption.multimodal_model) { if (!extension_settings.caption.multimodal_model) {
extension_settings.caption.multimodal_model = 'gpt-4-vision-preview'; extension_settings.caption.multimodal_model = 'gpt-4-turbo';
} }
if (!extension_settings.caption.prompt) { if (!extension_settings.caption.prompt) {
@ -369,6 +369,7 @@ jQuery(function () {
<label for="caption_multimodal_model">Model</label> <label for="caption_multimodal_model">Model</label>
<select id="caption_multimodal_model" class="flex1 text_pole"> <select id="caption_multimodal_model" class="flex1 text_pole">
<option data-type="openai" value="gpt-4-vision-preview">gpt-4-vision-preview</option> <option data-type="openai" value="gpt-4-vision-preview">gpt-4-vision-preview</option>
<option data-type="openai" value="gpt-4-turbo">gpt-4-turbo</option>
<option data-type="anthropic" value="claude-3-opus-20240229">claude-3-opus-20240229</option> <option data-type="anthropic" value="claude-3-opus-20240229">claude-3-opus-20240229</option>
<option data-type="anthropic" value="claude-3-sonnet-20240229">claude-3-sonnet-20240229</option> <option data-type="anthropic" value="claude-3-sonnet-20240229">claude-3-sonnet-20240229</option>
<option data-type="anthropic" value="claude-3-haiku-20240307">claude-3-haiku-20240307</option> <option data-type="anthropic" value="claude-3-haiku-20240307">claude-3-haiku-20240307</option>

View File

@ -11,7 +11,7 @@ const MODULE_NAME = 'expressions';
const UPDATE_INTERVAL = 2000; const UPDATE_INTERVAL = 2000;
const STREAMING_UPDATE_INTERVAL = 6000; const STREAMING_UPDATE_INTERVAL = 6000;
const TALKINGCHECK_UPDATE_INTERVAL = 500; const TALKINGCHECK_UPDATE_INTERVAL = 500;
const FALLBACK_EXPRESSION = 'joy'; const DEFAULT_FALLBACK_EXPRESSION = 'joy';
const DEFAULT_EXPRESSIONS = [ const DEFAULT_EXPRESSIONS = [
'talkinghead', 'talkinghead',
'admiration', 'admiration',
@ -58,6 +58,14 @@ function isTalkingHeadEnabled() {
return extension_settings.expressions.talkinghead && !extension_settings.expressions.local; return extension_settings.expressions.talkinghead && !extension_settings.expressions.local;
} }
/**
* Returns the fallback expression if explicitly chosen, otherwise the default one
* @returns {string} expression name
*/
function getFallbackExpression() {
return extension_settings.expressions.fallback_expression ?? DEFAULT_FALLBACK_EXPRESSION;
}
/** /**
* Toggles Talkinghead mode on/off. * Toggles Talkinghead mode on/off.
* *
@ -157,7 +165,8 @@ async function visualNovelSetCharacterSprites(container, name, expression) {
const sprites = spriteCache[spriteFolderName]; const sprites = spriteCache[spriteFolderName];
const expressionImage = container.find(`.expression-holder[data-avatar="${avatar}"]`); const expressionImage = container.find(`.expression-holder[data-avatar="${avatar}"]`);
const defaultSpritePath = sprites.find(x => x.label === FALLBACK_EXPRESSION)?.path; const defaultExpression = getFallbackExpression();
const defaultSpritePath = sprites.find(x => x.label === defaultExpression)?.path;
const noSprites = sprites.length === 0; const noSprites = sprites.length === 0;
if (expressionImage.length > 0) { if (expressionImage.length > 0) {
@ -568,7 +577,7 @@ function handleImageChange() {
// This preserves the same expression Talkinghead had at the moment it was switched off. // This preserves the same expression Talkinghead had at the moment it was switched off.
const charName = getContext().name2; const charName = getContext().name2;
const last = lastExpression[charName]; const last = lastExpression[charName];
const targetExpression = last ? last : FALLBACK_EXPRESSION; const targetExpression = last ? last : getFallbackExpression();
setExpression(charName, targetExpression, true); setExpression(charName, targetExpression, true);
} }
} }
@ -691,8 +700,8 @@ async function moduleWorker() {
const force = !!context.groupId; const force = !!context.groupId;
// Character won't be angry on you for swiping // Character won't be angry on you for swiping
if (currentLastMessage.mes == '...' && expressionsList.includes(FALLBACK_EXPRESSION)) { if (currentLastMessage.mes == '...' && expressionsList.includes(getFallbackExpression())) {
expression = FALLBACK_EXPRESSION; expression = getFallbackExpression();
} }
await sendExpressionCall(spriteFolderName, expression, force, vnMode); await sendExpressionCall(spriteFolderName, expression, force, vnMode);
@ -885,6 +894,22 @@ async function setSpriteSetCommand(_, folder) {
moduleWorker(); moduleWorker();
} }
async function classifyCommand(_, text) {
if (!text) {
console.log('No text provided');
return '';
}
if (!modules.includes('classify') && !extension_settings.expressions.local) {
toastr.warning('Text classification is disabled or not available');
return '';
}
const label = getExpressionLabel(text);
console.debug(`Classification result for "${text}": ${label}`);
return label;
}
async function setSpriteSlashCommand(_, spriteId) { async function setSpriteSlashCommand(_, spriteId) {
if (!spriteId) { if (!spriteId) {
console.log('No sprite id provided'); console.log('No sprite id provided');
@ -949,7 +974,7 @@ function sampleClassifyText(text) {
async function getExpressionLabel(text) { async function getExpressionLabel(text) {
// Return if text is undefined, saving a costly fetch request // Return if text is undefined, saving a costly fetch request
if ((!modules.includes('classify') && !extension_settings.expressions.local) || !text) { if ((!modules.includes('classify') && !extension_settings.expressions.local) || !text) {
return FALLBACK_EXPRESSION; return getFallbackExpression();
} }
text = sampleClassifyText(text); text = sampleClassifyText(text);
@ -988,7 +1013,7 @@ async function getExpressionLabel(text) {
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);
return FALLBACK_EXPRESSION; return getFallbackExpression();
} }
} }
@ -1092,6 +1117,11 @@ async function getSpritesList(name) {
} }
} }
async function renderAdditionalExpressionSettings() {
renderCustomExpressions();
await renderFallbackExpressionPicker();
}
function renderCustomExpressions() { function renderCustomExpressions() {
if (!Array.isArray(extension_settings.expressions.custom)) { if (!Array.isArray(extension_settings.expressions.custom)) {
extension_settings.expressions.custom = []; extension_settings.expressions.custom = [];
@ -1112,6 +1142,23 @@ function renderCustomExpressions() {
} }
} }
async function renderFallbackExpressionPicker() {
const expressions = await getExpressionsList();
const defaultPicker = $('#expression_fallback');
defaultPicker.empty();
const fallbackExpression = getFallbackExpression();
for (const expression of expressions) {
const option = document.createElement('option');
option.value = expression;
option.text = expression;
option.selected = expression == fallbackExpression;
defaultPicker.append(option);
}
}
async function getExpressionsList() { async function getExpressionsList() {
// Return cached list if available // Return cached list if available
if (Array.isArray(expressionsList)) { if (Array.isArray(expressionsList)) {
@ -1349,7 +1396,7 @@ async function onClickExpressionAddCustom() {
// Add custom expression into settings // Add custom expression into settings
extension_settings.expressions.custom.push(expressionName); extension_settings.expressions.custom.push(expressionName);
renderCustomExpressions(); await renderAdditionalExpressionSettings();
saveSettingsDebounced(); saveSettingsDebounced();
// Force refresh sprites list // Force refresh sprites list
@ -1376,7 +1423,11 @@ async function onClickExpressionRemoveCustom() {
// Remove custom expression from settings // Remove custom expression from settings
const index = extension_settings.expressions.custom.indexOf(selectedExpression); const index = extension_settings.expressions.custom.indexOf(selectedExpression);
extension_settings.expressions.custom.splice(index, 1); extension_settings.expressions.custom.splice(index, 1);
renderCustomExpressions(); if (selectedExpression == getFallbackExpression()) {
toastr.warning(`Deleted custom expression '${selectedExpression}' that was also selected as the fallback expression.\nFallback expression has been reset to '${DEFAULT_FALLBACK_EXPRESSION}'.`);
extension_settings.expressions.fallback_expression = DEFAULT_FALLBACK_EXPRESSION;
}
await renderAdditionalExpressionSettings();
saveSettingsDebounced(); saveSettingsDebounced();
// Force refresh sprites list // Force refresh sprites list
@ -1385,6 +1436,14 @@ async function onClickExpressionRemoveCustom() {
moduleWorker(); moduleWorker();
} }
function onExpressionFallbackChanged() {
const expression = this.value;
if (expression) {
extension_settings.expressions.fallback_expression = expression;
saveSettingsDebounced();
}
}
async function handleFileUpload(url, formData) { async function handleFileUpload(url, formData) {
try { try {
const data = await jQuery.ajax({ const data = await jQuery.ajax({
@ -1632,7 +1691,7 @@ async function fetchImagesNoCache() {
return await Promise.allSettled(promises); return await Promise.allSettled(promises);
} }
(function () { (async function () {
function addExpressionImage() { function addExpressionImage() {
const html = ` const html = `
<div id="expression-wrapper"> <div id="expression-wrapper">
@ -1652,7 +1711,7 @@ async function fetchImagesNoCache() {
element.hide(); element.hide();
$('body').append(element); $('body').append(element);
} }
function addSettings() { async function addSettings() {
$('#extensions_settings').append(renderExtensionTemplate(MODULE_NAME, 'settings')); $('#extensions_settings').append(renderExtensionTemplate(MODULE_NAME, 'settings'));
$('#expression_override_button').on('click', onClickExpressionOverrideButton); $('#expression_override_button').on('click', onClickExpressionOverrideButton);
$('#expressions_show_default').on('input', onExpressionsShowDefaultInput); $('#expressions_show_default').on('input', onExpressionsShowDefaultInput);
@ -1680,10 +1739,11 @@ async function fetchImagesNoCache() {
} }
}); });
renderCustomExpressions(); await renderAdditionalExpressionSettings();
$('#expression_custom_add').on('click', onClickExpressionAddCustom); $('#expression_custom_add').on('click', onClickExpressionAddCustom);
$('#expression_custom_remove').on('click', onClickExpressionRemoveCustom); $('#expression_custom_remove').on('click', onClickExpressionRemoveCustom);
$('#expression_fallback').on('change', onExpressionFallbackChanged)
} }
// Pause Talkinghead to save resources when the ST tab is not visible or the window is minimized. // Pause Talkinghead to save resources when the ST tab is not visible or the window is minimized.
@ -1716,7 +1776,7 @@ async function fetchImagesNoCache() {
addExpressionImage(); addExpressionImage();
addVisualNovelMode(); addVisualNovelMode();
addSettings(); await addSettings();
const wrapper = new ModuleWorkerWrapper(moduleWorker); const wrapper = new ModuleWorkerWrapper(moduleWorker);
const updateFunction = wrapper.update.bind(wrapper); const updateFunction = wrapper.update.bind(wrapper);
setInterval(updateFunction, UPDATE_INTERVAL); setInterval(updateFunction, UPDATE_INTERVAL);
@ -1758,5 +1818,6 @@ async function fetchImagesNoCache() {
registerSlashCommand('sprite', setSpriteSlashCommand, ['emote'], '<span class="monospace">(spriteId)</span> force sets the sprite for the current character', true, true); registerSlashCommand('sprite', setSpriteSlashCommand, ['emote'], '<span class="monospace">(spriteId)</span> force sets the sprite for the current character', true, true);
registerSlashCommand('spriteoverride', setSpriteSetCommand, ['costume'], '<span class="monospace">(optional folder)</span> sets an override sprite folder for the current character. If the name starts with a slash or a backslash, selects a sub-folder in the character-named folder. Empty value to reset to default.', true, true); registerSlashCommand('spriteoverride', setSpriteSetCommand, ['costume'], '<span class="monospace">(optional folder)</span> sets an override sprite folder for the current character. If the name starts with a slash or a backslash, selects a sub-folder in the character-named folder. Empty value to reset to default.', true, true);
registerSlashCommand('lastsprite', (_, value) => lastExpression[value.trim()] ?? '', [], '<span class="monospace">(charName)</span> Returns the last set sprite / expression for the named character.', true, true); registerSlashCommand('lastsprite', (_, value) => lastExpression[value.trim()] ?? '', [], '<span class="monospace">(charName)</span> Returns the last set sprite / expression for the named character.', true, true);
registerSlashCommand('th', toggleTalkingHeadCommand, ['talkinghead'], ' Character Expressions: toggles <i>Image Type - talkinghead (extras)</i> on/off.'); registerSlashCommand('th', toggleTalkingHeadCommand, ['talkinghead'], ' Character Expressions: toggles <i>Image Type - talkinghead (extras)</i> on/off.', true, true);
registerSlashCommand('classify', classifyCommand, [], '<span class="monospace">(text)</span> performs an emotion classification of the given text and returns a label.', true, true);
})(); })();

View File

@ -18,6 +18,11 @@
<input id="image_type_toggle" type="checkbox"> <input id="image_type_toggle" type="checkbox">
<span>Image Type - talkinghead (extras)</span> <span>Image Type - talkinghead (extras)</span>
</label> </label>
<div class="expression_fallback_block m-b-1 m-t-1">
<label for="expression_fallback">Default / Fallback Expression</label>
<small>Set the default and fallback expression being used when no matching expression is found.</small>
<select id="expression_fallback" class="flex1 margin0" data-i18n="Fallback Expression" placeholder="Fallback Expression"></select>
</div>
<div class="expression_custom_block m-b-1 m-t-1"> <div class="expression_custom_block m-b-1 m-t-1">
<label for="expression_custom">Custom Expressions</label> <label for="expression_custom">Custom Expressions</label>
<small>Can be set manually or with an <tt>/emote</tt> slash command.</small> <small>Can be set manually or with an <tt>/emote</tt> slash command.</small>

View File

@ -16,12 +16,20 @@
<label for="qr--modal-message"> <label for="qr--modal-message">
Message / Command: Message / Command:
</label> </label>
<small> <div class="qr--modal-editorSettings">
<label class="checkbox_label"> <label class="checkbox_label">
<input type="checkbox" id="qr--modal-wrap"> <input type="checkbox" id="qr--modal-wrap">
<span>Word wrap</span> <span>Word wrap</span>
</label> </label>
</small> <label class="checkbox_label">
<span>Tab size:</span>
<input type="number" min="1" max="9" id="qr--modal-tabSize" class="text_pole">
</label>
<label class="checkbox_label">
<input type="checkbox" id="qr--modal-executeShortcut">
<span>Ctrl+Enter to execute</span>
</label>
</div>
<textarea class="monospace" id="qr--modal-message"></textarea> <textarea class="monospace" id="qr--modal-message"></textarea>
</div> </div>
</div> </div>
@ -78,7 +86,7 @@
<input type="checkbox" id="qr--executeOnGroupMemberDraft"> <input type="checkbox" id="qr--executeOnGroupMemberDraft">
<span><i class="fa-solid fa-fw fa-people-group"></i> Execute before group member message</span> <span><i class="fa-solid fa-fw fa-people-group"></i> Execute before group member message</span>
</label> </label>
<div class="flex-container alignItemsBaseline" title="Activate this quick reply when a World Info entry with the same Automation ID is triggered."> <div class="flex-container alignItemsBaseline flexFlowColumn flexNoGap" title="Activate this quick reply when a World Info entry with the same Automation ID is triggered.">
<small>Automation ID</small> <small>Automation ID</small>
<input type="text" id="qr--automationId" class="text_pole flex1" placeholder="( None )"> <input type="text" id="qr--automationId" class="text_pole flex1" placeholder="( None )">
</div> </div>

View File

@ -104,7 +104,7 @@ const loadSets = async () => {
qr.executeOnAi = slot.autoExecute_botMessage ?? false; qr.executeOnAi = slot.autoExecute_botMessage ?? false;
qr.executeOnChatChange = slot.autoExecute_chatLoad ?? false; qr.executeOnChatChange = slot.autoExecute_chatLoad ?? false;
qr.executeOnGroupMemberDraft = slot.autoExecute_groupMemberDraft ?? false; qr.executeOnGroupMemberDraft = slot.autoExecute_groupMemberDraft ?? false;
qr.automationId = slot.automationId ?? false; qr.automationId = slot.automationId ?? '';
qr.contextList = (slot.contextMenu ?? []).map(it=>({ qr.contextList = (slot.contextMenu ?? []).map(it=>({
set: it.preset, set: it.preset,
isChained: it.chain, isChained: it.chain,

View File

@ -1,4 +1,4 @@
import { callPopup } from '../../../../script.js'; import { POPUP_TYPE, Popup } from '../../../popup.js';
import { getSortableDelay } from '../../../utils.js'; import { getSortableDelay } from '../../../utils.js';
import { log, warn } from '../index.js'; import { log, warn } from '../index.js';
import { QuickReplyContextLink } from './QuickReplyContextLink.js'; import { QuickReplyContextLink } from './QuickReplyContextLink.js';
@ -44,6 +44,13 @@ export class QuickReply {
/**@type {HTMLInputElement}*/ settingsDomLabel; /**@type {HTMLInputElement}*/ settingsDomLabel;
/**@type {HTMLTextAreaElement}*/ settingsDomMessage; /**@type {HTMLTextAreaElement}*/ settingsDomMessage;
/**@type {Popup}*/ editorPopup;
/**@type {HTMLElement}*/ editorExecuteBtn;
/**@type {HTMLElement}*/ editorExecuteErrors;
/**@type {HTMLInputElement}*/ editorExecuteHide;
/**@type {Promise}*/ editorExecutePromise;
get hasContext() { get hasContext() {
return this.contextList && this.contextList.length > 0; return this.contextList && this.contextList.length > 0;
@ -192,7 +199,8 @@ export class QuickReply {
/**@type {HTMLElement} */ /**@type {HTMLElement} */
// @ts-ignore // @ts-ignore
const dom = this.template.cloneNode(true); const dom = this.template.cloneNode(true);
const popupResult = callPopup(dom, 'text', undefined, { okButton: 'OK', wide: true, large: true, rows: 1 }); this.editorPopup = new Popup(dom, POPUP_TYPE.TEXT, undefined, { okButton: 'OK', wide: true, large: true, rows: 1 });
const popupResult = this.editorPopup.show();
// basics // basics
/**@type {HTMLInputElement}*/ /**@type {HTMLInputElement}*/
@ -209,7 +217,7 @@ export class QuickReply {
}); });
/**@type {HTMLInputElement}*/ /**@type {HTMLInputElement}*/
const wrap = dom.querySelector('#qr--modal-wrap'); const wrap = dom.querySelector('#qr--modal-wrap');
wrap.checked = JSON.parse(localStorage.getItem('qr--wrap')); wrap.checked = JSON.parse(localStorage.getItem('qr--wrap') ?? 'false');
wrap.addEventListener('click', () => { wrap.addEventListener('click', () => {
localStorage.setItem('qr--wrap', JSON.stringify(wrap.checked)); localStorage.setItem('qr--wrap', JSON.stringify(wrap.checked));
updateWrap(); updateWrap();
@ -221,9 +229,26 @@ export class QuickReply {
message.style.whiteSpace = 'pre'; message.style.whiteSpace = 'pre';
} }
}; };
/**@type {HTMLInputElement}*/
const tabSize = dom.querySelector('#qr--modal-tabSize');
tabSize.value = JSON.parse(localStorage.getItem('qr--tabSize') ?? '4');
const updateTabSize = () => {
message.style.tabSize = tabSize.value;
};
tabSize.addEventListener('change', () => {
localStorage.setItem('qr--tabSize', JSON.stringify(Number(tabSize.value)));
updateTabSize();
});
/**@type {HTMLInputElement}*/
const executeShortcut = dom.querySelector('#qr--modal-executeShortcut');
executeShortcut.checked = JSON.parse(localStorage.getItem('qr--executeShortcut') ?? 'true');
executeShortcut.addEventListener('click', () => {
localStorage.setItem('qr--executeShortcut', JSON.stringify(executeShortcut.checked));
});
/**@type {HTMLTextAreaElement}*/ /**@type {HTMLTextAreaElement}*/
const message = dom.querySelector('#qr--modal-message'); const message = dom.querySelector('#qr--modal-message');
updateWrap(); updateWrap();
updateTabSize();
message.value = this.message; message.value = this.message;
message.addEventListener('input', () => { message.addEventListener('input', () => {
this.updateMessage(message.value); this.updateMessage(message.value);
@ -257,6 +282,12 @@ export class QuickReply {
message.selectionStart = start - 1; message.selectionStart = start - 1;
message.selectionEnd = end - count; message.selectionEnd = end - count;
this.updateMessage(message.value); this.updateMessage(message.value);
} else if (evt.key == 'Enter' && evt.ctrlKey && !evt.shiftKey && !evt.altKey) {
evt.stopPropagation();
evt.preventDefault();
if (executeShortcut.checked) {
this.executeFromEditor();
}
} }
}); });
@ -385,27 +416,15 @@ export class QuickReply {
/**@type {HTMLElement}*/ /**@type {HTMLElement}*/
const executeErrors = dom.querySelector('#qr--modal-executeErrors'); const executeErrors = dom.querySelector('#qr--modal-executeErrors');
this.editorExecuteErrors = executeErrors;
/**@type {HTMLInputElement}*/ /**@type {HTMLInputElement}*/
const executeHide = dom.querySelector('#qr--modal-executeHide'); const executeHide = dom.querySelector('#qr--modal-executeHide');
let executePromise; this.editorExecuteHide = executeHide;
/**@type {HTMLElement}*/ /**@type {HTMLElement}*/
const executeBtn = dom.querySelector('#qr--modal-execute'); const executeBtn = dom.querySelector('#qr--modal-execute');
this.editorExecuteBtn = executeBtn;
executeBtn.addEventListener('click', async()=>{ executeBtn.addEventListener('click', async()=>{
if (executePromise) return; await this.executeFromEditor();
executeBtn.classList.add('qr--busy');
executeErrors.innerHTML = '';
if (executeHide.checked) {
document.querySelector('#shadow_popup').classList.add('qr--hide');
}
try {
executePromise = this.execute();
await executePromise;
} catch (ex) {
executeErrors.textContent = ex.message;
}
executePromise = null;
executeBtn.classList.remove('qr--busy');
document.querySelector('#shadow_popup').classList.remove('qr--hide');
}); });
await popupResult; await popupResult;
@ -414,6 +433,24 @@ export class QuickReply {
} }
} }
async executeFromEditor() {
if (this.editorExecutePromise) return;
this.editorExecuteBtn.classList.add('qr--busy');
this.editorExecuteErrors.innerHTML = '';
if (this.editorExecuteHide.checked) {
this.editorPopup.dom.classList.add('qr--hide');
}
try {
this.editorExecutePromise = this.execute();
await this.editorExecutePromise;
} catch (ex) {
this.editorExecuteErrors.textContent = ex.message;
}
this.editorExecutePromise = null;
this.editorExecuteBtn.classList.remove('qr--busy');
this.editorPopup.dom.classList.remove('qr--hide');
}

View File

@ -216,71 +216,85 @@
align-items: baseline; align-items: baseline;
} }
@media screen and (max-width: 750px) { @media screen and (max-width: 750px) {
body #dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor { body .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor {
flex-direction: column; flex-direction: column;
} }
body #dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels { body .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels {
flex-direction: column; flex-direction: column;
} }
body #dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer > #qr--modal-message { body .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer > #qr--modal-message {
min-height: 90svh; min-height: 90svh;
} }
} }
#dialogue_popup:has(#qr--modalEditor) { .dialogue_popup:has(#qr--modalEditor) {
aspect-ratio: unset; aspect-ratio: unset;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor {
flex: 1 1 auto; flex: 1 1 auto;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
gap: 1em; gap: 1em;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main {
flex: 1 1 auto; flex: 1 1 auto;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels {
flex: 0 0 auto; flex: 0 0 auto;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
gap: 0.5em; gap: 0.5em;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels > label { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels > label {
flex: 1 1 1px; flex: 1 1 1px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels > label > .qr--labelText { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels > label > .qr--labelText {
flex: 1 1 auto; flex: 1 1 auto;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels > label > .qr--labelHint { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels > label > .qr--labelHint {
flex: 1 1 auto; flex: 1 1 auto;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels > label > input { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--labels > label > input {
flex: 0 0 auto; flex: 0 0 auto;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer {
flex: 1 1 auto; flex: 1 1 auto;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer > #qr--modal-message { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer > .qr--modal-editorSettings {
display: flex;
flex-direction: row;
gap: 1em;
color: var(--grey70);
font-size: smaller;
align-items: baseline;
}
.dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer > .qr--modal-editorSettings > .checkbox_label {
white-space: nowrap;
}
.dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer > .qr--modal-editorSettings > .checkbox_label > input {
font-size: inherit;
}
.dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor > #qr--main > .qr--modal-messageContainer > #qr--modal-message {
flex: 1 1 auto; flex: 1 1 auto;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor #qr--modal-execute { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor #qr--modal-execute {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
gap: 0.5em; gap: 0.5em;
} }
#dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor #qr--modal-execute.qr--busy { .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor #qr--modal-execute.qr--busy {
opacity: 0.5; opacity: 0.5;
cursor: wait; cursor: wait;
} }
#shadow_popup.qr--hide { .shadow_popup.qr--hide {
opacity: 0 !important; opacity: 0 !important;
} }

View File

@ -242,7 +242,7 @@
@media screen and (max-width: 750px) { @media screen and (max-width: 750px) {
body #dialogue_popup:has(#qr--modalEditor) #dialogue_popup_text > #qr--modalEditor { body .dialogue_popup:has(#qr--modalEditor) .dialogue_popup_text > #qr--modalEditor {
flex-direction: column; flex-direction: column;
> #qr--main > .qr--labels { > #qr--main > .qr--labels {
flex-direction: column; flex-direction: column;
@ -252,10 +252,10 @@
} }
} }
} }
#dialogue_popup:has(#qr--modalEditor) { .dialogue_popup:has(#qr--modalEditor) {
aspect-ratio: unset; aspect-ratio: unset;
#dialogue_popup_text { .dialogue_popup_text {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@ -293,6 +293,20 @@
flex: 1 1 auto; flex: 1 1 auto;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
> .qr--modal-editorSettings {
display: flex;
flex-direction: row;
gap: 1em;
color: var(--grey70);
font-size: smaller;
align-items: baseline;
> .checkbox_label {
white-space: nowrap;
> input {
font-size: inherit;
}
}
}
> #qr--modal-message { > #qr--modal-message {
flex: 1 1 auto; flex: 1 1 auto;
} }
@ -312,6 +326,6 @@
} }
} }
#shadow_popup.qr--hide { .shadow_popup.qr--hide {
opacity: 0 !important; opacity: 0 !important;
} }

View File

@ -56,7 +56,7 @@ export async function getMultimodalCaption(base64Img, prompt) {
if (!isGoogle) { if (!isGoogle) {
requestBody.api = extension_settings.caption.multimodal_api || 'openai'; requestBody.api = extension_settings.caption.multimodal_api || 'openai';
requestBody.model = extension_settings.caption.multimodal_model || 'gpt-4-vision-preview'; requestBody.model = extension_settings.caption.multimodal_model || 'gpt-4-turbo';
requestBody.reverse_proxy = proxyUrl; requestBody.reverse_proxy = proxyUrl;
requestBody.proxy_password = proxyPassword; requestBody.proxy_password = proxyPassword;
} }
@ -83,7 +83,7 @@ export async function getMultimodalCaption(base64Img, prompt) {
if (isCustom) { if (isCustom) {
requestBody.server_url = oai_settings.custom_url; requestBody.server_url = oai_settings.custom_url;
requestBody.model = oai_settings.custom_model || 'gpt-4-vision-preview'; requestBody.model = oai_settings.custom_model || 'gpt-4-turbo';
requestBody.custom_include_headers = oai_settings.custom_include_headers; requestBody.custom_include_headers = oai_settings.custom_include_headers;
requestBody.custom_include_body = oai_settings.custom_include_body; requestBody.custom_include_body = oai_settings.custom_include_body;
requestBody.custom_exclude_body = oai_settings.custom_exclude_body; requestBody.custom_exclude_body = oai_settings.custom_exclude_body;

View File

@ -2629,7 +2629,7 @@ async function generateComfyImage(prompt, negativePrompt) {
} }
let workflow = (await workflowResponse.json()).replace('"%prompt%"', JSON.stringify(prompt)); let workflow = (await workflowResponse.json()).replace('"%prompt%"', JSON.stringify(prompt));
workflow = workflow.replace('"%negative_prompt%"', JSON.stringify(negativePrompt)); workflow = workflow.replace('"%negative_prompt%"', JSON.stringify(negativePrompt));
workflow = workflow.replace('"%seed%"', JSON.stringify(Math.round(Math.random() * Number.MAX_SAFE_INTEGER))); workflow = workflow.replaceAll('"%seed%"', JSON.stringify(Math.round(Math.random() * Number.MAX_SAFE_INTEGER)));
placeholders.forEach(ph => { placeholders.forEach(ph => {
workflow = workflow.replace(`"%${ph}%"`, JSON.stringify(extension_settings.sd[ph])); workflow = workflow.replace(`"%${ph}%"`, JSON.stringify(extension_settings.sd[ph]));
}); });

View File

@ -19,8 +19,9 @@ const UPDATE_INTERVAL = 1000;
let voiceMapEntries = []; let voiceMapEntries = [];
let voiceMap = {}; // {charName:voiceid, charName2:voiceid2} let voiceMap = {}; // {charName:voiceid, charName2:voiceid2}
let storedvalue = false; let talkingHeadState = false;
let lastChatId = null; let lastChatId = null;
let lastMessage = null;
let lastMessageHash = null; let lastMessageHash = null;
const DEFAULT_VOICE_MARKER = '[Default Voice]'; const DEFAULT_VOICE_MARKER = '[Default Voice]';
@ -67,7 +68,7 @@ export function getPreviewString(lang) {
return previewStrings[lang] ?? fallbackPreview; return previewStrings[lang] ?? fallbackPreview;
} }
let ttsProviders = { const ttsProviders = {
ElevenLabs: ElevenLabsTtsProvider, ElevenLabs: ElevenLabsTtsProvider,
Silero: SileroTtsProvider, Silero: SileroTtsProvider,
XTTSv2: XTTSTtsProvider, XTTSv2: XTTSTtsProvider,
@ -82,7 +83,6 @@ let ttsProviders = {
let ttsProvider; let ttsProvider;
let ttsProviderName; let ttsProviderName;
let ttsLastMessage = null;
async function onNarrateOneMessage() { async function onNarrateOneMessage() {
audioElement.src = '/sounds/silence.mp3'; audioElement.src = '/sounds/silence.mp3';
@ -130,103 +130,13 @@ async function onNarrateText(args, text) {
} }
async function moduleWorker() { async function moduleWorker() {
// Primarily determining when to add new chat to the TTS queue if (!extension_settings.tts.enabled) {
const enabled = $('#tts_enabled').is(':checked');
$('body').toggleClass('tts', enabled);
if (!enabled) {
return; return;
} }
const context = getContext();
const chat = context.chat;
processTtsQueue(); processTtsQueue();
processAudioJobQueue(); processAudioJobQueue();
updateUiAudioPlayState(); updateUiAudioPlayState();
// Auto generation is disabled
if (extension_settings.tts.auto_generation == false) {
return;
}
// no characters or group selected
if (!context.groupId && context.characterId === undefined) {
return;
}
// Chat changed
if (
context.chatId !== lastChatId
) {
currentMessageNumber = context.chat.length ? context.chat.length : 0;
saveLastValues();
// Force to speak on the first message in the new chat
if (context.chat.length === 1) {
lastMessageHash = -1;
}
return;
}
// take the count of messages
let lastMessageNumber = context.chat.length ? context.chat.length : 0;
// There's no new messages
let diff = lastMessageNumber - currentMessageNumber;
let hashNew = getStringHash((chat.length && chat[chat.length - 1].mes) ?? '');
// if messages got deleted, diff will be < 0
if (diff < 0) {
// necessary actions will be taken by the onChatDeleted() handler
return;
}
// if no new messages, or same message, or same message hash, do nothing
if (diff == 0 && hashNew === lastMessageHash) {
return;
}
// If streaming, wait for streaming to finish before processing new messages
if (context.streamingProcessor && !context.streamingProcessor.isFinished) {
return;
}
// clone message object, as things go haywire if message object is altered below (it's passed by reference)
const message = structuredClone(chat[chat.length - 1]);
// if last message within current message, message got extended. only send diff to TTS.
if (ttsLastMessage !== null && message.mes.indexOf(ttsLastMessage) !== -1) {
let tmp = message.mes;
message.mes = message.mes.replace(ttsLastMessage, '');
ttsLastMessage = tmp;
} else {
ttsLastMessage = message.mes;
}
// We're currently swiping. Don't generate voice
if (!message || message.mes === '...' || message.mes === '') {
return;
}
// Don't generate if message doesn't have a display text
if (extension_settings.tts.narrate_translated_only && !(message?.extra?.display_text)) {
return;
}
// Don't generate if message is a user message and user message narration is disabled
if (message.is_user && !extension_settings.tts.narrate_user) {
return;
}
// New messages, add new chat to history
lastMessageHash = hashNew;
currentMessageNumber = lastMessageNumber;
console.debug(
`Adding message from ${message.name} for TTS processing: "${message.mes}"`,
);
ttsJobQueue.push(message);
} }
function talkingAnimation(switchValue) { function talkingAnimation(switchValue) {
@ -238,11 +148,11 @@ function talkingAnimation(switchValue) {
const apiUrl = getApiUrl(); const apiUrl = getApiUrl();
const animationType = switchValue ? 'start' : 'stop'; const animationType = switchValue ? 'start' : 'stop';
if (switchValue !== storedvalue) { if (switchValue !== talkingHeadState) {
try { try {
console.log(animationType + ' Talking Animation'); console.log(animationType + ' Talking Animation');
doExtrasFetch(`${apiUrl}/api/talkinghead/${animationType}_talking`); doExtrasFetch(`${apiUrl}/api/talkinghead/${animationType}_talking`);
storedvalue = switchValue; // Update the storedvalue to the current switchValue talkingHeadState = switchValue;
} catch (error) { } catch (error) {
// Handle the error here or simply ignore it to prevent logging // Handle the error here or simply ignore it to prevent logging
} }
@ -289,7 +199,6 @@ function debugTtsPlayback() {
{ {
'ttsProviderName': ttsProviderName, 'ttsProviderName': ttsProviderName,
'voiceMap': voiceMap, 'voiceMap': voiceMap,
'currentMessageNumber': currentMessageNumber,
'audioPaused': audioPaused, 'audioPaused': audioPaused,
'audioJobQueue': audioJobQueue, 'audioJobQueue': audioJobQueue,
'currentAudioJob': currentAudioJob, 'currentAudioJob': currentAudioJob,
@ -465,6 +374,7 @@ async function processAudioJobQueue() {
playAudioData(currentAudioJob); playAudioData(currentAudioJob);
talkingAnimation(true); talkingAnimation(true);
} catch (error) { } catch (error) {
toastr.error(error.toString());
console.error(error); console.error(error);
audioQueueProcessorReady = true; audioQueueProcessorReady = true;
} }
@ -476,21 +386,12 @@ async function processAudioJobQueue() {
let ttsJobQueue = []; let ttsJobQueue = [];
let currentTtsJob; // Null if nothing is currently being processed let currentTtsJob; // Null if nothing is currently being processed
let currentMessageNumber = 0;
function completeTtsJob() { function completeTtsJob() {
console.info(`Current TTS job for ${currentTtsJob?.name} completed.`); console.info(`Current TTS job for ${currentTtsJob?.name} completed.`);
currentTtsJob = null; currentTtsJob = null;
} }
function saveLastValues() {
const context = getContext();
lastChatId = context.chatId;
lastMessageHash = getStringHash(
(context.chat.length && context.chat[context.chat.length - 1].mes) ?? '',
);
}
async function tts(text, voiceId, char) { async function tts(text, voiceId, char) {
async function processResponse(response) { async function processResponse(response) {
// RVC injection // RVC injection
@ -581,8 +482,9 @@ async function processTtsQueue() {
toastr.error(`Specified voice for ${char} was not found. Check the TTS extension settings.`); toastr.error(`Specified voice for ${char} was not found. Check the TTS extension settings.`);
throw `Unable to attain voiceId for ${char}`; throw `Unable to attain voiceId for ${char}`;
} }
tts(text, voiceId, char); await tts(text, voiceId, char);
} catch (error) { } catch (error) {
toastr.error(error.toString());
console.error(error); console.error(error);
currentTtsJob = null; currentTtsJob = null;
} }
@ -654,6 +556,7 @@ function onRefreshClick() {
initVoiceMap(); initVoiceMap();
updateVoiceMap(); updateVoiceMap();
}).catch(error => { }).catch(error => {
toastr.error(error.toString());
console.error(error); console.error(error);
setTtsStatus(error, false); setTtsStatus(error, false);
}); });
@ -761,26 +664,103 @@ async function onChatChanged() {
await resetTtsPlayback(); await resetTtsPlayback();
const voiceMapInit = initVoiceMap(); const voiceMapInit = initVoiceMap();
await Promise.race([voiceMapInit, delay(1000)]); await Promise.race([voiceMapInit, delay(1000)]);
ttsLastMessage = null; lastMessage = null;
} }
async function onChatDeleted() { async function onMessageEvent(messageId) {
// If TTS is disabled, do nothing
if (!extension_settings.tts.enabled) {
return;
}
// Auto generation is disabled
if (!extension_settings.tts.auto_generation) {
return;
}
const context = getContext();
// no characters or group selected
if (!context.groupId && context.characterId === undefined) {
return;
}
// Chat changed
if (context.chatId !== lastChatId) {
lastChatId = context.chatId;
lastMessageHash = getStringHash(context.chat[messageId]?.mes ?? '');
// Force to speak on the first message in the new chat
if (context.chat.length === 1) {
lastMessageHash = -1;
}
}
// clone message object, as things go haywire if message object is altered below (it's passed by reference)
const message = structuredClone(context.chat[messageId]);
const hashNew = getStringHash(message?.mes ?? '');
// if no new messages, or same message, or same message hash, do nothing
if (hashNew === lastMessageHash) {
return;
}
const isLastMessageInCurrent = () =>
lastMessage &&
typeof lastMessage === 'object' &&
message.swipe_id === lastMessage.swipe_id &&
message.name === lastMessage.name &&
message.is_user === lastMessage.is_user &&
message.mes.indexOf(lastMessage.mes) !== -1;
// if last message within current message, message got extended. only send diff to TTS.
if (isLastMessageInCurrent()) {
const tmp = structuredClone(message);
message.mes = message.mes.replace(lastMessage.mes, '');
lastMessage = tmp;
} else {
lastMessage = structuredClone(message);
}
// We're currently swiping. Don't generate voice
if (!message || message.mes === '...' || message.mes === '') {
return;
}
// Don't generate if message doesn't have a display text
if (extension_settings.tts.narrate_translated_only && !(message?.extra?.display_text)) {
return;
}
// Don't generate if message is a user message and user message narration is disabled
if (message.is_user && !extension_settings.tts.narrate_user) {
return;
}
// New messages, add new chat to history
lastMessageHash = hashNew;
lastChatId = context.chatId;
console.debug(`Adding message from ${message.name} for TTS processing: "${message.mes}"`);
ttsJobQueue.push(message);
}
async function onMessageDeleted() {
const context = getContext(); const context = getContext();
// update internal references to new last message // update internal references to new last message
lastChatId = context.chatId; lastChatId = context.chatId;
currentMessageNumber = context.chat.length ? context.chat.length : 0;
// compare against lastMessageHash. If it's the same, we did not delete the last chat item, so no need to reset tts queue // compare against lastMessageHash. If it's the same, we did not delete the last chat item, so no need to reset tts queue
let messageHash = getStringHash((context.chat.length && context.chat[context.chat.length - 1].mes) ?? ''); const messageHash = getStringHash((context.chat.length && context.chat[context.chat.length - 1].mes) ?? '');
if (messageHash === lastMessageHash) { if (messageHash === lastMessageHash) {
return; return;
} }
lastMessageHash = messageHash; lastMessageHash = messageHash;
ttsLastMessage = (context.chat.length && context.chat[context.chat.length - 1].mes) ?? ''; lastMessage = context.chat.length ? structuredClone(context.chat[context.chat.length - 1]) : null;
// stop any tts playback since message might not exist anymore // stop any tts playback since message might not exist anymore
await resetTtsPlayback(); resetTtsPlayback();
} }
/** /**
@ -1076,8 +1056,10 @@ $(document).ready(function () {
setInterval(wrapper.update.bind(wrapper), UPDATE_INTERVAL); // Init depends on all the things setInterval(wrapper.update.bind(wrapper), UPDATE_INTERVAL); // Init depends on all the things
eventSource.on(event_types.MESSAGE_SWIPED, resetTtsPlayback); eventSource.on(event_types.MESSAGE_SWIPED, resetTtsPlayback);
eventSource.on(event_types.CHAT_CHANGED, onChatChanged); eventSource.on(event_types.CHAT_CHANGED, onChatChanged);
eventSource.on(event_types.MESSAGE_DELETED, onChatDeleted); eventSource.on(event_types.MESSAGE_DELETED, onMessageDeleted);
eventSource.on(event_types.GROUP_UPDATED, onChatChanged); eventSource.on(event_types.GROUP_UPDATED, onChatChanged);
eventSource.on(event_types.MESSAGE_SENT, onMessageEvent);
eventSource.on(event_types.MESSAGE_RECEIVED, onMessageEvent);
registerSlashCommand('speak', onNarrateText, ['narrate', 'tts'], '<span class="monospace">(text)</span> narrate any text using currently selected character\'s voice. Use voice="Character Name" argument to set other voice from the voice map, example: <tt>/speak voice="Donald Duck" Quack!</tt>', true, true); registerSlashCommand('speak', onNarrateText, ['narrate', 'tts'], '<span class="monospace">(text)</span> narrate any text using currently selected character\'s voice. Use voice="Character Name" argument to set other voice from the voice map, example: <tt>/speak voice="Donald Duck" Quack!</tt>', true, true);
document.body.appendChild(audioElement); document.body.appendChild(audioElement);
}); });

View File

@ -9,9 +9,11 @@ import {
saveBase64AsFile, saveBase64AsFile,
PAGINATION_TEMPLATE, PAGINATION_TEMPLATE,
getBase64Async, getBase64Async,
resetScrollHeight,
initScrollHeight,
} from './utils.js'; } from './utils.js';
import { RA_CountCharTokens, humanizedDateTime, dragElement, favsToHotswap, getMessageTimeStamp } from './RossAscends-mods.js'; import { RA_CountCharTokens, humanizedDateTime, dragElement, favsToHotswap, getMessageTimeStamp } from './RossAscends-mods.js';
import { loadMovingUIState, sortEntitiesList } from './power-user.js'; import { power_user, loadMovingUIState, sortEntitiesList } from './power-user.js';
import { import {
chat, chat,
@ -73,6 +75,7 @@ import {
} from '../script.js'; } from '../script.js';
import { printTagList, createTagMapFromList, applyTagsOnCharacterSelect, tag_map } from './tags.js'; import { printTagList, createTagMapFromList, applyTagsOnCharacterSelect, tag_map } from './tags.js';
import { FILTER_TYPES, FilterHelper } from './filters.js'; import { FILTER_TYPES, FilterHelper } from './filters.js';
import { isExternalMediaAllowed } from './chats.js';
export { export {
selected_group, selected_group,
@ -176,7 +179,7 @@ async function loadGroupChat(chatId) {
return []; return [];
} }
export async function getGroupChat(groupId) { export async function getGroupChat(groupId, reload = false) {
const group = groups.find((x) => x.id === groupId); const group = groups.find((x) => x.id === groupId);
const chat_id = group.chat_id; const chat_id = group.chat_id;
const data = await loadGroupChat(chat_id); const data = await loadGroupChat(chat_id);
@ -216,6 +219,10 @@ export async function getGroupChat(groupId) {
updateChatMetadata(metadata, true); updateChatMetadata(metadata, true);
} }
if (reload) {
select_group_chats(groupId, true);
}
await eventSource.emit(event_types.CHAT_CHANGED, getCurrentChatId()); await eventSource.emit(event_types.CHAT_CHANGED, getCurrentChatId());
} }
@ -346,6 +353,46 @@ export function getGroupCharacterCards(groupId, characterId) {
return null; return null;
} }
/**
* Runs the macro engine on a text, with custom <FIELDNAME> replace
* @param {string} value Value to replace
* @param {string} fieldName Name of the field
* @param {string} characterName Name of the character
* @returns {string} Replaced text
* */
function customBaseChatReplace(value, fieldName, characterName) {
if (!value) {
return '';
}
// We should do the custom field name replacement first, and then run it through the normal macro engine with provided names
value = value.replace(/<FIELDNAME>/gi, fieldName);
return baseChatReplace(value.trim(), name1, characterName);
}
/**
* Prepares text with prefix/suffix for a character field
* @param {string} value Value to replace
* @param {string} characterName Name of the character
* @param {string} fieldName Name of the field
* @returns {string} Prepared text
* */
function replaceAndPrepareForJoin(value, characterName, fieldName) {
value = value.trim();
if (!value) {
return '';
}
// Prepare and replace prefixes
const prefix = customBaseChatReplace(group.generation_mode_join_prefix, fieldName, characterName);
const suffix = customBaseChatReplace(group.generation_mode_join_suffix, fieldName, characterName);
const separator = power_user.instruct.wrap ? '\n' : '';
// Also run the macro replacement on the actual content
value = customBaseChatReplace(value, fieldName, characterName);
return `${prefix ? prefix + separator : ''}${value}${suffix ? separator + suffix : ''}`;
}
const scenarioOverride = chat_metadata['scenario']; const scenarioOverride = chat_metadata['scenario'];
let descriptions = []; let descriptions = [];
@ -367,16 +414,16 @@ export function getGroupCharacterCards(groupId, characterId) {
continue; continue;
} }
descriptions.push(baseChatReplace(character.description.trim(), name1, character.name)); descriptions.push(replaceAndPrepareForJoin(character.description, character.name, 'Description'));
personalities.push(baseChatReplace(character.personality.trim(), name1, character.name)); personalities.push(replaceAndPrepareForJoin(character.personality, character.name, 'Personality'));
scenarios.push(baseChatReplace(character.scenario.trim(), name1, character.name)); scenarios.push(replaceAndPrepareForJoin(character.scenario, character.name, 'Scenario'));
mesExamplesArray.push(baseChatReplace(character.mes_example.trim(), name1, character.name)); mesExamplesArray.push(replaceAndPrepareForJoin(character.mes_example, character.name, 'Example Messages'));
} }
const description = descriptions.join('\n'); const description = descriptions.filter(x => x.length).join('\n');
const personality = personalities.join('\n'); const personality = personalities.filter(x => x.length).join('\n');
const scenario = scenarioOverride?.trim() || scenarios.join('\n'); const scenario = scenarioOverride?.trim() || scenarios.filter(x => x.length).join('\n');
const mesExamples = mesExamplesArray.join('\n'); const mesExamples = mesExamplesArray.filter(x => x.length).join('\n');
return { description, personality, scenario, mesExamples }; return { description, personality, scenario, mesExamples };
} }
@ -1088,6 +1135,8 @@ async function onGroupGenerationModeInput(e) {
let _thisGroup = groups.find((x) => x.id == openGroupId); let _thisGroup = groups.find((x) => x.id == openGroupId);
_thisGroup.generation_mode = Number(e.target.value); _thisGroup.generation_mode = Number(e.target.value);
await editGroup(openGroupId, false, false); await editGroup(openGroupId, false, false);
toggleHiddenControls(_thisGroup);
} }
} }
@ -1100,6 +1149,15 @@ async function onGroupAutoModeDelayInput(e) {
} }
} }
async function onGroupGenerationModeTemplateInput(e) {
if (openGroupId) {
let _thisGroup = groups.find((x) => x.id == openGroupId);
const prop = $(e.target).attr('setting');
_thisGroup[prop] = String(e.target.value);
await editGroup(openGroupId, false, false);
}
}
async function onGroupNameInput() { async function onGroupNameInput() {
if (openGroupId) { if (openGroupId) {
let _thisGroup = groups.find((x) => x.id == openGroupId); let _thisGroup = groups.find((x) => x.id == openGroupId);
@ -1265,6 +1323,14 @@ async function onHideMutedSpritesClick(value) {
} }
} }
function toggleHiddenControls(group, generationMode = null) {
const isJoin = [group_generation_mode.APPEND, group_generation_mode.APPEND_DISABLED].includes(generationMode ?? group?.generation_mode);
$('#rm_group_generation_mode_join_prefix').parent().toggle(isJoin);
$('#rm_group_generation_mode_join_suffix').parent().toggle(isJoin);
initScrollHeight($('#rm_group_generation_mode_join_prefix'));
initScrollHeight($('#rm_group_generation_mode_join_suffix'));
}
function select_group_chats(groupId, skipAnimation) { function select_group_chats(groupId, skipAnimation) {
openGroupId = groupId; openGroupId = groupId;
newGroupMembers = []; newGroupMembers = [];
@ -1300,12 +1366,20 @@ function select_group_chats(groupId, skipAnimation) {
$('#rm_group_hidemutedsprites').prop('checked', group && group.hideMutedSprites); $('#rm_group_hidemutedsprites').prop('checked', group && group.hideMutedSprites);
$('#rm_group_automode_delay').val(group?.auto_mode_delay ?? DEFAULT_AUTO_MODE_DELAY); $('#rm_group_automode_delay').val(group?.auto_mode_delay ?? DEFAULT_AUTO_MODE_DELAY);
$('#rm_group_generation_mode_join_prefix').val(group?.generation_mode_join_prefix ?? '').attr('setting', 'generation_mode_join_prefix');
$('#rm_group_generation_mode_join_suffix').val(group?.generation_mode_join_suffix ?? '').attr('setting', 'generation_mode_join_suffix');
toggleHiddenControls(group, generationMode);
// bottom buttons // bottom buttons
if (openGroupId) { if (openGroupId) {
$('#rm_group_submit').hide(); $('#rm_group_submit').hide();
$('#rm_group_delete').show(); $('#rm_group_delete').show();
$('#rm_group_scenario').show(); $('#rm_group_scenario').show();
$('#group-metadata-controls .chat_lorebook_button').removeClass('disabled').prop('disabled', false); $('#group-metadata-controls .chat_lorebook_button').removeClass('disabled').prop('disabled', false);
$('#group_open_media_overrides').show();
const isMediaAllowed = isExternalMediaAllowed();
$('#group_media_allowed_icon').toggle(isMediaAllowed);
$('#group_media_forbidden_icon').toggle(!isMediaAllowed);
} else { } else {
$('#rm_group_submit').show(); $('#rm_group_submit').show();
if ($('#groupAddMemberListToggle .inline-drawer-content').css('display') !== 'block') { if ($('#groupAddMemberListToggle .inline-drawer-content').css('display') !== 'block') {
@ -1314,6 +1388,7 @@ function select_group_chats(groupId, skipAnimation) {
$('#rm_group_delete').hide(); $('#rm_group_delete').hide();
$('#rm_group_scenario').hide(); $('#rm_group_scenario').hide();
$('#group-metadata-controls .chat_lorebook_button').addClass('disabled').prop('disabled', true); $('#group-metadata-controls .chat_lorebook_button').addClass('disabled').prop('disabled', true);
$('#group_open_media_overrides').hide();
} }
updateFavButtonState(group?.fav ?? false); updateFavButtonState(group?.fav ?? false);
@ -1328,6 +1403,11 @@ function select_group_chats(groupId, skipAnimation) {
$('#rm_group_automode_label').hide(); $('#rm_group_automode_label').hide();
} }
// Toggle textbox sizes, as input events have not fired here
$('#rm_group_chats_block .autoSetHeight').each(element => {
resetScrollHeight(element);
});
eventSource.emit('groupSelected', { detail: { id: openGroupId, group: group } }); eventSource.emit('groupSelected', { detail: { id: openGroupId, group: group } });
} }
@ -1786,6 +1866,10 @@ function doCurMemberListPopout() {
} }
jQuery(() => { jQuery(() => {
$(document).on('input', '#rm_group_chats_block .autoSetHeight', function () {
resetScrollHeight($(this));
});
$(document).on('click', '.group_select', function () { $(document).on('click', '.group_select', function () {
const groupId = $(this).attr('chid') || $(this).attr('grid') || $(this).data('id'); const groupId = $(this).attr('chid') || $(this).attr('grid') || $(this).data('id');
openGroupById(groupId); openGroupById(groupId);
@ -1813,6 +1897,8 @@ jQuery(() => {
$('#rm_group_activation_strategy').on('change', onGroupActivationStrategyInput); $('#rm_group_activation_strategy').on('change', onGroupActivationStrategyInput);
$('#rm_group_generation_mode').on('change', onGroupGenerationModeInput); $('#rm_group_generation_mode').on('change', onGroupGenerationModeInput);
$('#rm_group_automode_delay').on('input', onGroupAutoModeDelayInput); $('#rm_group_automode_delay').on('input', onGroupAutoModeDelayInput);
$('#rm_group_generation_mode_join_prefix').on('input', onGroupGenerationModeTemplateInput);
$('#rm_group_generation_mode_join_suffix').on('input', onGroupGenerationModeTemplateInput);
$('#group_avatar_button').on('input', uploadGroupAvatar); $('#group_avatar_button').on('input', uploadGroupAvatar);
$('#rm_group_restore_avatar').on('click', restoreGroupAvatar); $('#rm_group_restore_avatar').on('click', restoreGroupAvatar);
$(document).on('click', '.group_member .right_menu_button', onGroupActionClick); $(document).on('click', '.group_member .right_menu_button', onGroupActionClick);

View File

@ -26,6 +26,7 @@ const controls = [
{ id: 'instruct_output_suffix', property: 'output_suffix', isCheckbox: false }, { id: 'instruct_output_suffix', property: 'output_suffix', isCheckbox: false },
{ id: 'instruct_system_sequence', property: 'system_sequence', isCheckbox: false }, { id: 'instruct_system_sequence', property: 'system_sequence', isCheckbox: false },
{ id: 'instruct_system_suffix', property: 'system_suffix', isCheckbox: false }, { id: 'instruct_system_suffix', property: 'system_suffix', isCheckbox: false },
{ id: 'instruct_last_system_sequence', property: 'last_system_sequence', isCheckbox: false },
{ id: 'instruct_user_alignment_message', property: 'user_alignment_message', isCheckbox: false }, { id: 'instruct_user_alignment_message', property: 'user_alignment_message', isCheckbox: false },
{ id: 'instruct_stop_sequence', property: 'stop_sequence', isCheckbox: false }, { id: 'instruct_stop_sequence', property: 'stop_sequence', isCheckbox: false },
{ id: 'instruct_names', property: 'names', isCheckbox: true }, { id: 'instruct_names', property: 'names', isCheckbox: true },
@ -56,6 +57,7 @@ function migrateInstructModeSettings(settings) {
system_sequence: '', system_sequence: '',
system_suffix: '', system_suffix: '',
user_alignment_message: '', user_alignment_message: '',
last_system_sequence: '',
names_force_groups: true, names_force_groups: true,
skip_examples: false, skip_examples: false,
system_same_as_user: false, system_same_as_user: false,
@ -249,8 +251,9 @@ export function getInstructStoppingSequences() {
const first_output_sequence = power_user.instruct.first_output_sequence?.replace(/{{name}}/gi, name2) || ''; const first_output_sequence = power_user.instruct.first_output_sequence?.replace(/{{name}}/gi, name2) || '';
const last_output_sequence = power_user.instruct.last_output_sequence?.replace(/{{name}}/gi, name2) || ''; const last_output_sequence = power_user.instruct.last_output_sequence?.replace(/{{name}}/gi, name2) || '';
const system_sequence = power_user.instruct.system_sequence?.replace(/{{name}}/gi, 'System') || ''; const system_sequence = power_user.instruct.system_sequence?.replace(/{{name}}/gi, 'System') || '';
const last_system_sequence = power_user.instruct.last_system_sequence?.replace(/{{name}}/gi, 'System') || '';
const combined_sequence = `${stop_sequence}\n${input_sequence}\n${output_sequence}\n${first_output_sequence}\n${last_output_sequence}\n${system_sequence}`; const combined_sequence = `${stop_sequence}\n${input_sequence}\n${output_sequence}\n${first_output_sequence}\n${last_output_sequence}\n${system_sequence}\n${last_system_sequence}`;
combined_sequence.split('\n').filter((line, index, self) => self.indexOf(line) === index).forEach(addInstructSequence); combined_sequence.split('\n').filter((line, index, self) => self.indexOf(line) === index).forEach(addInstructSequence);
} }
@ -369,7 +372,7 @@ export function formatInstructModeSystemPrompt(systemPrompt) {
* @returns {string[]} Formatted example messages string. * @returns {string[]} Formatted example messages string.
*/ */
export function formatInstructModeExamples(mesExamplesArray, name1, name2) { export function formatInstructModeExamples(mesExamplesArray, name1, name2) {
const blockHeading = power_user.context.example_separator ? power_user.context.example_separator + '\n' : ''; const blockHeading = power_user.context.example_separator ? `${substituteParams(power_user.context.example_separator)}\n` : '';
if (power_user.instruct.skip_examples) { if (power_user.instruct.skip_examples) {
return mesExamplesArray.map(x => x.replace(/<START>\n/i, blockHeading)); return mesExamplesArray.map(x => x.replace(/<START>\n/i, blockHeading));
@ -416,10 +419,13 @@ export function formatInstructModeExamples(mesExamplesArray, name1, name2) {
} }
for (const example of blockExamples) { for (const example of blockExamples) {
// If force group/persona names is set, we should override the include names for the user placeholder
const includeThisName = includeNames || (power_user.instruct.names_force_groups && example.name == 'example_user');
const prefix = example.name == 'example_user' ? inputPrefix : outputPrefix; const prefix = example.name == 'example_user' ? inputPrefix : outputPrefix;
const suffix = example.name == 'example_user' ? inputSuffix : outputSuffix; const suffix = example.name == 'example_user' ? inputSuffix : outputSuffix;
const name = example.name == 'example_user' ? name1 : name2; const name = example.name == 'example_user' ? name1 : name2;
const messageContent = includeNames ? `${name}: ${example.content}` : example.content; const messageContent = includeThisName ? `${name}: ${example.content}` : example.content;
const formattedMessage = [prefix, messageContent + suffix].filter(x => x).join(separator); const formattedMessage = [prefix, messageContent + suffix].filter(x => x).join(separator);
formattedExamples.push(formattedMessage); formattedExamples.push(formattedMessage);
} }
@ -452,9 +458,10 @@ export function formatInstructModePrompt(name, isImpersonate, promptBias, name1,
return power_user.instruct.input_sequence; return power_user.instruct.input_sequence;
} }
// Neutral / system prompt // Neutral / system / quiet prompt
// Use a special quiet instruct sequence if defined, or assistant's output sequence otherwise
if (isQuiet && !isQuietToLoud) { if (isQuiet && !isQuietToLoud) {
return power_user.instruct.output_sequence; return power_user.instruct.last_system_sequence || power_user.instruct.output_sequence;
} }
// Quiet in-character prompt // Quiet in-character prompt
@ -511,26 +518,37 @@ function selectMatchingContextTemplate(name) {
/** /**
* Replaces instruct mode macros in the given input string. * Replaces instruct mode macros in the given input string.
* @param {string} input Input string. * @param {string} input Input string.
* @param {Object<string, *>} env - Map of macro names to the values they'll be substituted with. If the param
* values are functions, those functions will be called and their return values are used.
* @returns {string} String with macros replaced. * @returns {string} String with macros replaced.
*/ */
export function replaceInstructMacros(input) { export function replaceInstructMacros(input, env) {
if (!input) { if (!input) {
return ''; return '';
} }
const instructMacros = {
'systemPrompt': (power_user.prefer_character_prompt && env.charPrompt ? env.charPrompt : power_user.instruct.system_prompt),
'instructSystem|instructSystemPrompt': power_user.instruct.system_prompt,
'instructSystemPromptPrefix': power_user.instruct.system_sequence_prefix,
'instructSystemPromptSuffix': power_user.instruct.system_sequence_suffix,
'instructInput|instructUserPrefix': power_user.instruct.input_sequence,
'instructUserSuffix': power_user.instruct.input_suffix,
'instructOutput|instructAssistantPrefix': power_user.instruct.output_sequence,
'instructSeparator|instructAssistantSuffix': power_user.instruct.output_suffix,
'instructSystemPrefix': power_user.instruct.system_sequence,
'instructSystemSuffix': power_user.instruct.system_suffix,
'instructFirstOutput|instructFirstAssistantPrefix': power_user.instruct.first_output_sequence || power_user.instruct.output_sequence,
'instructLastOutput|instructLastAssistantPrefix': power_user.instruct.last_output_sequence || power_user.instruct.output_sequence,
'instructStop': power_user.instruct.stop_sequence,
'instructUserFiller': power_user.instruct.user_alignment_message,
'instructSystemInstructionPrefix': power_user.instruct.last_system_sequence,
};
for (const [placeholder, value] of Object.entries(instructMacros)) {
const regex = new RegExp(`{{(${placeholder})}}`, 'gi');
input = input.replace(regex, power_user.instruct.enabled ? value : '');
}
input = input.replace(/{{(instructSystem|instructSystemPrompt)}}/gi, power_user.instruct.enabled ? power_user.instruct.system_prompt : '');
input = input.replace(/{{instructSystemPromptPrefix}}/gi, power_user.instruct.enabled ? power_user.instruct.system_sequence_prefix : '');
input = input.replace(/{{instructSystemPromptSuffix}}/gi, power_user.instruct.enabled ? power_user.instruct.system_sequence_suffix : '');
input = input.replace(/{{(instructInput|instructUserPrefix)}}/gi, power_user.instruct.enabled ? power_user.instruct.input_sequence : '');
input = input.replace(/{{instructUserSuffix}}/gi, power_user.instruct.enabled ? power_user.instruct.input_suffix : '');
input = input.replace(/{{(instructOutput|instructAssistantPrefix)}}/gi, power_user.instruct.enabled ? power_user.instruct.output_sequence : '');
input = input.replace(/{{(instructSeparator|instructAssistantSuffix)}}/gi, power_user.instruct.enabled ? power_user.instruct.output_suffix : '');
input = input.replace(/{{instructSystemPrefix}}/gi, power_user.instruct.enabled ? power_user.instruct.system_sequence : '');
input = input.replace(/{{instructSystemSuffix}}/gi, power_user.instruct.enabled ? power_user.instruct.system_suffix : '');
input = input.replace(/{{(instructFirstOutput|instructFirstAssistantPrefix)}}/gi, power_user.instruct.enabled ? (power_user.instruct.first_output_sequence || power_user.instruct.output_sequence) : '');
input = input.replace(/{{(instructLastOutput|instructLastAssistantPrefix)}}/gi, power_user.instruct.enabled ? (power_user.instruct.last_output_sequence || power_user.instruct.output_sequence) : '');
input = input.replace(/{{instructStop}}/gi, power_user.instruct.enabled ? power_user.instruct.stop_sequence : '');
input = input.replace(/{{instructUserFiller}}/gi, power_user.instruct.enabled ? power_user.instruct.user_alignment_message : '');
input = input.replace(/{{exampleSeparator}}/gi, power_user.context.example_separator); input = input.replace(/{{exampleSeparator}}/gi, power_user.context.example_separator);
input = input.replace(/{{chatStart}}/gi, power_user.context.chat_start); input = input.replace(/{{chatStart}}/gi, power_user.context.chat_start);

View File

@ -1,4 +1,4 @@
import { chat, main_api, getMaxContextSize, getCurrentChatId } from '../script.js'; import { chat, chat_metadata, main_api, getMaxContextSize, getCurrentChatId } from '../script.js';
import { timestampToMoment, isDigitsOnly, getStringHash } from './utils.js'; import { timestampToMoment, isDigitsOnly, getStringHash } from './utils.js';
import { textgenerationwebui_banned_in_macros } from './textgen-settings.js'; import { textgenerationwebui_banned_in_macros } from './textgen-settings.js';
import { replaceInstructMacros } from './instruct-mode.js'; import { replaceInstructMacros } from './instruct-mode.js';
@ -8,121 +8,121 @@ import { replaceVariableMacros } from './variables.js';
Handlebars.registerHelper('trim', () => '{{trim}}'); Handlebars.registerHelper('trim', () => '{{trim}}');
/** /**
* Returns the ID of the last message in the chat. * Gets a hashed id of the current chat from the metadata.
* @returns {string} The ID of the last message in the chat. * If no metadata exists, creates a new hash and saves it.
* @returns {number} The hashed chat id
*/ */
function getLastMessageId() { function getChatIdHash() {
const index = chat?.length - 1; const cachedIdHash = chat_metadata['chat_id_hash'];
if (!isNaN(index) && index >= 0) { // If chat_id_hash is not already set, calculate it
return String(index); if (!cachedIdHash) {
// Use the main_chat if it's available, otherwise get the current chat ID
const chatId = chat_metadata['main_chat'] ?? getCurrentChatId();
const chatIdHash = getStringHash(chatId);
chat_metadata['chat_id_hash'] = chatIdHash;
return chatIdHash;
} }
return ''; return cachedIdHash;
} }
/** /**
* Returns the ID of the first message included in the context. * Returns the ID of the last message in the chat
* @returns {string} The ID of the first message in the context. *
* Optionally can only choose specific messages, if a filter is provided.
*
* @param {object} param0 - Optional arguments
* @param {boolean} [param0.exclude_swipe_in_propress=true] - Whether a message that is currently being swiped should be ignored
* @param {function(object):boolean} [param0.filter] - A filter applied to the search, ignoring all messages that don't match the criteria. For example to only find user messages, etc.
* @returns {number|null} The message id, or null if none was found
*/
export function getLastMessageId({ exclude_swipe_in_propress = true, filter = null } = {}) {
for (let i = chat?.length - 1; i >= 0; i--) {
let message = chat[i];
// If ignoring swipes and the message is being swiped, continue
// We can check if a message is being swiped by checking whether the current swipe id is not in the list of finished swipes yet
if (exclude_swipe_in_propress && message.swipes && message.swipe_id >= message.swipes.length) {
continue;
}
// Check if no filter is provided, or if the message passes the filter
if (!filter || filter(message)) {
return i;
}
}
return null;
}
/**
* Returns the ID of the first message included in the context
*
* @returns {number|null} The ID of the first message in the context
*/ */
function getFirstIncludedMessageId() { function getFirstIncludedMessageId() {
const index = document.querySelector('.lastInContext')?.getAttribute('mesid'); const index = Number(document.querySelector('.lastInContext')?.getAttribute('mesid'));
if (!isNaN(index) && index >= 0) { if (!isNaN(index) && index >= 0) {
return String(index); return index;
} }
return ''; return null;
} }
/** /**
* Returns the last message in the chat. * Returns the last message in the chat
* @returns {string} The last message in the chat. *
* @returns {string} The last message in the chat
*/ */
function getLastMessage() { function getLastMessage() {
const index = chat?.length - 1; const mid = getLastMessageId();
return chat[mid]?.mes ?? '';
if (!isNaN(index) && index >= 0) {
return chat[index].mes;
}
return '';
} }
/** /**
* Returns the last message from the user. * Returns the last message from the user
* @returns {string} The last message from the user. *
* @returns {string} The last message from the user
*/ */
function getLastUserMessage() { function getLastUserMessage() {
if (!Array.isArray(chat) || chat.length === 0) { const mid = getLastMessageId({ filter: m => m.is_user && !m.is_system });
return ''; return chat[mid]?.mes ?? '';
}
for (let i = chat.length - 1; i >= 0; i--) {
if (chat[i].is_user && !chat[i].is_system) {
return chat[i].mes;
}
}
return '';
} }
/** /**
* Returns the last message from the bot. * Returns the last message from the bot
* @returns {string} The last message from the bot. *
* @returns {string} The last message from the bot
*/ */
function getLastCharMessage() { function getLastCharMessage() {
if (!Array.isArray(chat) || chat.length === 0) { const mid = getLastMessageId({ filter: m => !m.is_user && !m.is_system });
return ''; return chat[mid]?.mes ?? '';
}
for (let i = chat.length - 1; i >= 0; i--) {
if (!chat[i].is_user && !chat[i].is_system) {
return chat[i].mes;
}
}
return '';
} }
/** /**
* Returns the ID of the last swipe. * Returns the 1-based ID (number) of the last swipe
* @returns {string} The 1-based ID of the last swipe *
* @returns {number|null} The 1-based ID of the last swipe
*/ */
function getLastSwipeId() { function getLastSwipeId() {
const index = chat?.length - 1; // For swipe macro, we are accepting using the message that is currently being swiped
const mid = getLastMessageId({ exclude_swipe_in_propress: false });
if (!isNaN(index) && index >= 0) { const swipes = chat[mid]?.swipes;
const swipes = chat[index].swipes; return swipes?.length;
if (!Array.isArray(swipes) || swipes.length === 0) {
return '';
}
return String(swipes.length);
}
return '';
} }
/** /**
* Returns the ID of the current swipe. * Returns the 1-based ID (number) of the current swipe
* @returns {string} The 1-based ID of the current swipe. *
* @returns {number|null} The 1-based ID of the current swipe
*/ */
function getCurrentSwipeId() { function getCurrentSwipeId() {
const index = chat?.length - 1; // For swipe macro, we are accepting using the message that is currently being swiped
const mid = getLastMessageId({ exclude_swipe_in_propress: false });
if (!isNaN(index) && index >= 0) { const swipeId = chat[mid]?.swipe_id;
const swipeId = chat[index].swipe_id; return swipeId ? swipeId + 1 : null;
if (swipeId === undefined || isNaN(swipeId)) {
return '';
}
return String(swipeId + 1);
}
return '';
} }
/** /**
@ -205,7 +205,10 @@ function randomReplace(input, emptyListPlaceholder = '') {
function pickReplace(input, rawContent, emptyListPlaceholder = '') { function pickReplace(input, rawContent, emptyListPlaceholder = '') {
const pickPattern = /{{pick\s?::?([^}]+)}}/gi; const pickPattern = /{{pick\s?::?([^}]+)}}/gi;
const chatIdHash = getStringHash(getCurrentChatId());
// We need to have a consistent chat hash, otherwise we'll lose rolls on chat file rename or branch switches
// No need to save metadata here - branching and renaming will implicitly do the save for us, and until then loading it like this is consistent
const chatIdHash = getChatIdHash();
const rawContentHash = getStringHash(rawContent); const rawContentHash = getStringHash(rawContent);
return input.replace(pickPattern, (match, listString, offset) => { return input.replace(pickPattern, (match, listString, offset) => {
@ -276,10 +279,11 @@ export function evaluateMacros(content, env) {
} }
content = diceRollReplace(content); content = diceRollReplace(content);
content = replaceInstructMacros(content); content = replaceInstructMacros(content, env);
content = replaceVariableMacros(content); content = replaceVariableMacros(content);
content = content.replace(/{{newline}}/gi, '\n'); content = content.replace(/{{newline}}/gi, '\n');
content = content.replace(/\n*{{trim}}\n*/gi, ''); content = content.replace(/\n*{{trim}}\n*/gi, '');
content = content.replace(/{{noop}}/gi, '');
content = content.replace(/{{input}}/gi, () => String($('#send_textarea').val())); content = content.replace(/{{input}}/gi, () => String($('#send_textarea').val()));
// Substitute passed-in variables // Substitute passed-in variables
@ -292,12 +296,12 @@ export function evaluateMacros(content, env) {
content = content.replace(/{{maxPrompt}}/gi, () => String(getMaxContextSize())); content = content.replace(/{{maxPrompt}}/gi, () => String(getMaxContextSize()));
content = content.replace(/{{lastMessage}}/gi, () => getLastMessage()); content = content.replace(/{{lastMessage}}/gi, () => getLastMessage());
content = content.replace(/{{lastMessageId}}/gi, () => getLastMessageId()); content = content.replace(/{{lastMessageId}}/gi, () => String(getLastMessageId() ?? ''));
content = content.replace(/{{lastUserMessage}}/gi, () => getLastUserMessage()); content = content.replace(/{{lastUserMessage}}/gi, () => getLastUserMessage());
content = content.replace(/{{lastCharMessage}}/gi, () => getLastCharMessage()); content = content.replace(/{{lastCharMessage}}/gi, () => getLastCharMessage());
content = content.replace(/{{firstIncludedMessageId}}/gi, () => getFirstIncludedMessageId()); content = content.replace(/{{firstIncludedMessageId}}/gi, () => String(getFirstIncludedMessageId() ?? ''));
content = content.replace(/{{lastSwipeId}}/gi, () => getLastSwipeId()); content = content.replace(/{{lastSwipeId}}/gi, () => String(getLastSwipeId() ?? ''));
content = content.replace(/{{currentSwipeId}}/gi, () => getCurrentSwipeId()); content = content.replace(/{{currentSwipeId}}/gi, () => String(getCurrentSwipeId() ?? ''));
content = content.replace(/\{\{\/\/([\s\S]*?)\}\}/gm, ''); content = content.replace(/\{\{\/\/([\s\S]*?)\}\}/gm, '');

View File

@ -186,6 +186,11 @@ const continue_postfix_types = {
DOUBLE_NEWLINE: '\n\n', DOUBLE_NEWLINE: '\n\n',
}; };
const custom_prompt_post_processing_types = {
NONE: '',
CLAUDE: 'claude',
};
const prefixMap = selected_group ? { const prefixMap = selected_group ? {
assistant: '', assistant: '',
user: '', user: '',
@ -262,6 +267,7 @@ const default_settings = {
continue_prefill: false, continue_prefill: false,
names_behavior: character_names_behavior.NONE, names_behavior: character_names_behavior.NONE,
continue_postfix: continue_postfix_types.SPACE, continue_postfix: continue_postfix_types.SPACE,
custom_prompt_post_processing: custom_prompt_post_processing_types.NONE,
seed: -1, seed: -1,
n: 1, n: 1,
}; };
@ -331,6 +337,7 @@ const oai_settings = {
continue_prefill: false, continue_prefill: false,
names_behavior: character_names_behavior.NONE, names_behavior: character_names_behavior.NONE,
continue_postfix: continue_postfix_types.SPACE, continue_postfix: continue_postfix_types.SPACE,
custom_prompt_post_processing: custom_prompt_post_processing_types.NONE,
seed: -1, seed: -1,
n: 1, n: 1,
}; };
@ -431,15 +438,15 @@ function convertChatCompletionToInstruct(messages, type) {
const exampleMessages = messages.filter(x => x.role === 'system' && (x.name === 'example_user' || x.name === 'example_assistant')); const exampleMessages = messages.filter(x => x.role === 'system' && (x.name === 'example_user' || x.name === 'example_assistant'));
if (exampleMessages.length) { if (exampleMessages.length) {
examplesText = power_user.context.example_separator + '\n'; const blockHeading = power_user.context.example_separator ? (substituteParams(power_user.context.example_separator) + '\n') : '';
examplesText += exampleMessages.map(toString).join('\n'); const examplesArray = exampleMessages.map(m => '<START>\n' + toString(m));
examplesText = formatInstructModeExamples(examplesText, name1, name2); examplesText = blockHeading + formatInstructModeExamples(examplesArray, name1, name2).join('');
} }
const chatMessages = messages.slice(firstChatMessage); const chatMessages = messages.slice(firstChatMessage);
if (chatMessages.length) { if (chatMessages.length) {
chatMessagesText = power_user.context.chat_start + '\n'; chatMessagesText = substituteParams(power_user.context.chat_start) + '\n';
for (const message of chatMessages) { for (const message of chatMessages) {
const name = getPrefix(message); const name = getPrefix(message);
@ -1743,6 +1750,7 @@ async function sendOpenAIRequest(type, messages, signal) {
generate_data['custom_include_body'] = oai_settings.custom_include_body; generate_data['custom_include_body'] = oai_settings.custom_include_body;
generate_data['custom_exclude_body'] = oai_settings.custom_exclude_body; generate_data['custom_exclude_body'] = oai_settings.custom_exclude_body;
generate_data['custom_include_headers'] = oai_settings.custom_include_headers; generate_data['custom_include_headers'] = oai_settings.custom_include_headers;
generate_data['custom_prompt_post_processing'] = oai_settings.custom_prompt_post_processing;
} }
if (isCohere) { if (isCohere) {
@ -2625,6 +2633,7 @@ function loadOpenAISettings(data, settings) {
oai_settings.custom_include_body = settings.custom_include_body ?? default_settings.custom_include_body; oai_settings.custom_include_body = settings.custom_include_body ?? default_settings.custom_include_body;
oai_settings.custom_exclude_body = settings.custom_exclude_body ?? default_settings.custom_exclude_body; oai_settings.custom_exclude_body = settings.custom_exclude_body ?? default_settings.custom_exclude_body;
oai_settings.custom_include_headers = settings.custom_include_headers ?? default_settings.custom_include_headers; oai_settings.custom_include_headers = settings.custom_include_headers ?? default_settings.custom_include_headers;
oai_settings.custom_prompt_post_processing = settings.custom_prompt_post_processing ?? default_settings.custom_prompt_post_processing;
oai_settings.google_model = settings.google_model ?? default_settings.google_model; oai_settings.google_model = settings.google_model ?? default_settings.google_model;
oai_settings.chat_completion_source = settings.chat_completion_source ?? default_settings.chat_completion_source; oai_settings.chat_completion_source = settings.chat_completion_source ?? default_settings.chat_completion_source;
oai_settings.api_url_scale = settings.api_url_scale ?? default_settings.api_url_scale; oai_settings.api_url_scale = settings.api_url_scale ?? default_settings.api_url_scale;
@ -2770,6 +2779,8 @@ function loadOpenAISettings(data, settings) {
$('#chat_completion_source').val(oai_settings.chat_completion_source).trigger('change'); $('#chat_completion_source').val(oai_settings.chat_completion_source).trigger('change');
$('#oai_max_context_unlocked').prop('checked', oai_settings.max_context_unlocked); $('#oai_max_context_unlocked').prop('checked', oai_settings.max_context_unlocked);
$('#custom_prompt_post_processing').val(oai_settings.custom_prompt_post_processing);
$(`#custom_prompt_post_processing option[value="${oai_settings.custom_prompt_post_processing}"]`).attr('selected', true);
} }
function setNamesBehaviorControls() { function setNamesBehaviorControls() {
@ -2924,6 +2935,7 @@ async function saveOpenAIPreset(name, settings, triggerUi = true) {
custom_include_body: settings.custom_include_body, custom_include_body: settings.custom_include_body,
custom_exclude_body: settings.custom_exclude_body, custom_exclude_body: settings.custom_exclude_body,
custom_include_headers: settings.custom_include_headers, custom_include_headers: settings.custom_include_headers,
custom_prompt_post_processing: settings.custom_prompt_post_processing,
google_model: settings.google_model, google_model: settings.google_model,
temperature: settings.temp_openai, temperature: settings.temp_openai,
frequency_penalty: settings.freq_pen_openai, frequency_penalty: settings.freq_pen_openai,
@ -3313,6 +3325,7 @@ function onSettingsPresetChange() {
custom_include_body: ['#custom_include_body', 'custom_include_body', false], custom_include_body: ['#custom_include_body', 'custom_include_body', false],
custom_exclude_body: ['#custom_exclude_body', 'custom_exclude_body', false], custom_exclude_body: ['#custom_exclude_body', 'custom_exclude_body', false],
custom_include_headers: ['#custom_include_headers', 'custom_include_headers', false], custom_include_headers: ['#custom_include_headers', 'custom_include_headers', false],
custom_prompt_post_processing: ['#custom_prompt_post_processing', 'custom_prompt_post_processing', false],
google_model: ['#model_google_select', 'google_model', false], google_model: ['#model_google_select', 'google_model', false],
openai_max_context: ['#openai_max_context', 'openai_max_context', false], openai_max_context: ['#openai_max_context', 'openai_max_context', false],
openai_max_tokens: ['#openai_max_tokens', 'openai_max_tokens', false], openai_max_tokens: ['#openai_max_tokens', 'openai_max_tokens', false],
@ -4025,12 +4038,13 @@ export function isImageInliningSupported() {
'gemini-1.0-pro-vision-latest', 'gemini-1.0-pro-vision-latest',
'gemini-1.5-pro-latest', 'gemini-1.5-pro-latest',
'gemini-pro-vision', 'gemini-pro-vision',
'claude-3' 'claude-3',
'gpt-4-turbo',
]; ];
switch (oai_settings.chat_completion_source) { switch (oai_settings.chat_completion_source) {
case chat_completion_sources.OPENAI: case chat_completion_sources.OPENAI:
return visionSupportedModels.some(model => oai_settings.openai_model.includes(model)); return visionSupportedModels.some(model => oai_settings.openai_model.includes(model) && !oai_settings.openai_model.includes('gpt-4-turbo-preview'));
case chat_completion_sources.MAKERSUITE: case chat_completion_sources.MAKERSUITE:
return visionSupportedModels.some(model => oai_settings.google_model.includes(model)); return visionSupportedModels.some(model => oai_settings.google_model.includes(model));
case chat_completion_sources.CLAUDE: case chat_completion_sources.CLAUDE:
@ -4493,6 +4507,11 @@ $(document).ready(async function () {
saveSettingsDebounced(); saveSettingsDebounced();
}); });
$('#custom_prompt_post_processing').on('change', function () {
oai_settings.custom_prompt_post_processing = String($(this).val());
saveSettingsDebounced();
});
$('#names_behavior').on('input', function () { $('#names_behavior').on('input', function () {
oai_settings.names_behavior = Number($(this).val()); oai_settings.names_behavior = Number($(this).val());
setNamesBehaviorControls(); setNamesBehaviorControls();

225
public/scripts/popup.js Normal file
View File

@ -0,0 +1,225 @@
import { animation_duration, animation_easing } from '../script.js';
import { delay } from './utils.js';
/**@readonly*/
/**@enum {Number}*/
export const POPUP_TYPE = {
'TEXT': 1,
'CONFIRM': 2,
'INPUT': 3,
};
/**@readonly*/
/**@enum {Boolean}*/
export const POPUP_RESULT = {
'AFFIRMATIVE': true,
'NEGATIVE': false,
'CANCELLED': undefined,
};
export class Popup {
/**@type {POPUP_TYPE}*/ type;
/**@type {HTMLElement}*/ dom;
/**@type {HTMLElement}*/ dlg;
/**@type {HTMLElement}*/ text;
/**@type {HTMLTextAreaElement}*/ input;
/**@type {HTMLElement}*/ ok;
/**@type {HTMLElement}*/ cancel;
/**@type {POPUP_RESULT}*/ result;
/**@type {any}*/ value;
/**@type {Promise}*/ promise;
/**@type {Function}*/ resolver;
/**@type {Function}*/ keyListenerBound;
/**
* @typedef {{okButton?: string, cancelButton?: string, rows?: number, wide?: boolean, large?: boolean, allowHorizontalScrolling?: boolean, allowVerticalScrolling?: boolean }} PopupOptions - Options for the popup.
* @param {JQuery<HTMLElement>|string|Element} text - Text to display in the popup.
* @param {POPUP_TYPE} type - One of Popup.TYPE
* @param {string} inputValue - Value to set the input to.
* @param {PopupOptions} options - Options for the popup.
*/
constructor(text, type, inputValue = '', { okButton, cancelButton, rows, wide, large, allowHorizontalScrolling, allowVerticalScrolling } = {}) {
this.type = type;
/**@type {HTMLTemplateElement}*/
const template = document.querySelector('#shadow_popup_template');
// @ts-ignore
this.dom = template.content.cloneNode(true).querySelector('.shadow_popup');
const dlg = this.dom.querySelector('.dialogue_popup');
// @ts-ignore
this.dlg = dlg;
this.text = this.dom.querySelector('.dialogue_popup_text');
this.input = this.dom.querySelector('.dialogue_popup_input');
this.ok = this.dom.querySelector('.dialogue_popup_ok');
this.cancel = this.dom.querySelector('.dialogue_popup_cancel');
if (wide) dlg.classList.add('wide_dialogue_popup');
if (large) dlg.classList.add('large_dialogue_popup');
if (allowHorizontalScrolling) dlg.classList.add('horizontal_scrolling_dialogue_popup');
if (allowVerticalScrolling) dlg.classList.add('vertical_scrolling_dialogue_popup');
this.ok.textContent = okButton ?? 'OK';
this.cancel.textContent = cancelButton ?? 'Cancel';
switch(type) {
case POPUP_TYPE.TEXT: {
this.input.style.display = 'none';
this.cancel.style.display = 'none';
break;
}
case POPUP_TYPE.CONFIRM: {
this.input.style.display = 'none';
this.ok.textContent = okButton ?? 'Yes';
this.cancel.textContent = cancelButton ?? 'No';
break;
}
case POPUP_TYPE.INPUT: {
this.input.style.display = 'block';
this.ok.textContent = okButton ?? 'Save';
break;
}
default: {
// illegal argument
}
}
this.input.value = inputValue;
this.input.rows = rows ?? 1;
this.text.innerHTML = '';
if (text instanceof jQuery) {
$(this.text).append(text);
} else if (text instanceof HTMLElement) {
this.text.append(text);
} else if (typeof text == 'string') {
this.text.innerHTML = text;
} else {
// illegal argument
}
this.ok.addEventListener('click', ()=>this.completeAffirmative());
this.cancel.addEventListener('click', ()=>this.completeNegative());
const keyListener = (evt)=>{
switch (evt.key) {
case 'Escape': {
evt.preventDefault();
evt.stopPropagation();
this.completeCancelled();
window.removeEventListener('keydown', keyListenerBound);
break;
}
}
};
const keyListenerBound = keyListener.bind(this);
window.addEventListener('keydown', keyListenerBound);
}
async show() {
document.body.append(this.dom);
this.dom.style.display = 'block';
switch(this.type) {
case POPUP_TYPE.INPUT: {
this.input.focus();
break;
}
}
$(this.dom).transition({
opacity: 1,
duration: animation_duration,
easing: animation_easing,
});
this.promise = new Promise((resolve) => {
this.resolver = resolve;
});
return this.promise;
}
completeAffirmative() {
switch (this.type) {
case POPUP_TYPE.TEXT:
case POPUP_TYPE.CONFIRM: {
this.value = true;
break;
}
case POPUP_TYPE.INPUT: {
this.value = this.input.value;
break;
}
}
this.result = POPUP_RESULT.AFFIRMATIVE;
this.hide();
}
completeNegative() {
switch (this.type) {
case POPUP_TYPE.TEXT:
case POPUP_TYPE.CONFIRM:
case POPUP_TYPE.INPUT: {
this.value = false;
break;
}
}
this.result = POPUP_RESULT.NEGATIVE;
this.hide();
}
completeCancelled() {
switch (this.type) {
case POPUP_TYPE.TEXT:
case POPUP_TYPE.CONFIRM:
case POPUP_TYPE.INPUT: {
this.value = null;
break;
}
}
this.result = POPUP_RESULT.CANCELLED;
this.hide();
}
hide() {
$(this.dom).transition({
opacity: 0,
duration: animation_duration,
easing: animation_easing,
});
delay(animation_duration).then(()=>{
this.dom.remove();
});
this.resolver(this.value);
}
}
/**
* Displays a blocking popup with a given text and type.
* @param {JQuery<HTMLElement>|string|Element} text - Text to display in the popup.
* @param {POPUP_TYPE} type
* @param {string} inputValue - Value to set the input to.
* @param {PopupOptions} options - Options for the popup.
* @returns
*/
export function callGenericPopup(text, type, inputValue = '', { okButton, cancelButton, rows, wide, large, allowHorizontalScrolling, allowVerticalScrolling } = {}) {
const popup = new Popup(
text,
type,
inputValue,
{ okButton, rows, wide, large, allowHorizontalScrolling, allowVerticalScrolling },
);
return popup.show();
}

View File

@ -204,6 +204,7 @@ let power_user = {
output_suffix: '', output_suffix: '',
system_sequence: '', system_sequence: '',
system_suffix: '', system_suffix: '',
last_system_sequence: '',
first_output_sequence: '', first_output_sequence: '',
last_output_sequence: '', last_output_sequence: '',
system_sequence_prefix: '', system_sequence_prefix: '',
@ -254,6 +255,8 @@ let power_user = {
auto_connect: false, auto_connect: false,
auto_load_chat: false, auto_load_chat: false,
forbid_external_images: false, forbid_external_images: false,
external_media_allowed_overrides: [],
external_media_forbidden_overrides: [],
}; };
let themes = []; let themes = [];
@ -1939,7 +1942,9 @@ export function renderStoryString(params) {
// add a newline to the end of the story string if it doesn't have one // add a newline to the end of the story string if it doesn't have one
if (output.length > 0 && !output.endsWith('\n')) { if (output.length > 0 && !output.endsWith('\n')) {
output += '\n'; if (!power_user.instruct.enabled || power_user.instruct.wrap) {
output += '\n';
}
} }
return output; return output;
@ -2760,22 +2765,35 @@ export function getCustomStoppingStrings(limit = undefined) {
} }
$(document).ready(() => { $(document).ready(() => {
const adjustAutocompleteDebounced = debounce(() => {
$('.ui-autocomplete-input').each(function () {
const isOpen = $(this).autocomplete('widget')[0].style.display !== 'none';
if (isOpen) {
$(this).autocomplete('search');
}
});
});
$(window).on('resize', async () => { const reportZoomLevelDebounced = debounce(() => {
if (isMobile()) {
return;
}
//console.log('Window resized!');
const zoomLevel = Number(window.devicePixelRatio).toFixed(2); const zoomLevel = Number(window.devicePixelRatio).toFixed(2);
const winWidth = window.innerWidth; const winWidth = window.innerWidth;
const winHeight = window.innerHeight; const winHeight = window.innerHeight;
console.debug(`Zoom: ${zoomLevel}, X:${winWidth}, Y:${winHeight}`); console.debug(`Zoom: ${zoomLevel}, X:${winWidth}, Y:${winHeight}`);
});
$(window).on('resize', async () => {
adjustAutocompleteDebounced();
setHotswapsDebounced();
if (isMobile()) {
return;
}
reportZoomLevelDebounced();
if (Object.keys(power_user.movingUIState).length > 0) { if (Object.keys(power_user.movingUIState).length > 0) {
resetMovablePanels('resize'); resetMovablePanels('resize');
} }
// Adjust layout and styling here
setHotswapsDebounced();
}); });
// Settings that go to settings.json // Settings that go to settings.json

View File

@ -106,7 +106,7 @@ function getDelay(s) {
/** /**
* Parses the stream data and returns the parsed data and the chunk to be sent. * Parses the stream data and returns the parsed data and the chunk to be sent.
* @param {object} json The JSON data. * @param {object} json The JSON data.
* @returns {AsyncGenerator<{data: object, chunk: string} | null>} The parsed data and the chunk to be sent. * @returns {AsyncGenerator<{data: object, chunk: string}>} The parsed data and the chunk to be sent.
*/ */
async function* parseStreamData(json) { async function* parseStreamData(json) {
// Claude // Claude
@ -120,6 +120,7 @@ async function* parseStreamData(json) {
}; };
} }
} }
return;
} }
// MakerSuite // MakerSuite
else if (Array.isArray(json.candidates)) { else if (Array.isArray(json.candidates)) {
@ -145,6 +146,7 @@ async function* parseStreamData(json) {
} }
} }
} }
return;
} }
// NovelAI / KoboldCpp Classic // NovelAI / KoboldCpp Classic
else if (typeof json.token === 'string' && json.token.length > 0) { else if (typeof json.token === 'string' && json.token.length > 0) {
@ -155,6 +157,7 @@ async function* parseStreamData(json) {
chunk: str, chunk: str,
}; };
} }
return;
} }
// llama.cpp? // llama.cpp?
else if (typeof json.content === 'string' && json.content.length > 0) { else if (typeof json.content === 'string' && json.content.length > 0) {
@ -165,6 +168,7 @@ async function* parseStreamData(json) {
chunk: str, chunk: str,
}; };
} }
return;
} }
// OpenAI-likes // OpenAI-likes
else if (Array.isArray(json.choices)) { else if (Array.isArray(json.choices)) {
@ -184,6 +188,7 @@ async function* parseStreamData(json) {
chunk: str, chunk: str,
}; };
} }
return;
} }
else if (typeof json.choices[0].delta === 'object') { else if (typeof json.choices[0].delta === 'object') {
if (typeof json.choices[0].delta.text === 'string' && json.choices[0].delta.text.length > 0) { if (typeof json.choices[0].delta.text === 'string' && json.choices[0].delta.text.length > 0) {
@ -197,6 +202,7 @@ async function* parseStreamData(json) {
chunk: str, chunk: str,
}; };
} }
return;
} }
else if (typeof json.choices[0].delta.content === 'string' && json.choices[0].delta.content.length > 0) { else if (typeof json.choices[0].delta.content === 'string' && json.choices[0].delta.content.length > 0) {
for (let j = 0; j < json.choices[0].delta.content.length; j++) { for (let j = 0; j < json.choices[0].delta.content.length; j++) {
@ -209,6 +215,7 @@ async function* parseStreamData(json) {
chunk: str, chunk: str,
}; };
} }
return;
} }
} }
else if (typeof json.choices[0].message === 'object') { else if (typeof json.choices[0].message === 'object') {
@ -223,11 +230,12 @@ async function* parseStreamData(json) {
chunk: str, chunk: str,
}; };
} }
return;
} }
} }
} }
return null; throw new Error('Unknown event data format');
} }
/** /**
@ -243,6 +251,12 @@ export class SmoothEventSourceStream extends EventSourceStream {
const data = event.data; const data = event.data;
try { try {
const hasFocus = document.hasFocus(); const hasFocus = document.hasFocus();
if (data === '[DONE]') {
lastStr = '';
return controller.enqueue(event);
}
const json = JSON.parse(data); const json = JSON.parse(data);
if (!json) { if (!json) {
@ -251,17 +265,13 @@ export class SmoothEventSourceStream extends EventSourceStream {
} }
for await (const parsed of parseStreamData(json)) { for await (const parsed of parseStreamData(json)) {
if (!parsed) {
lastStr = '';
return controller.enqueue(event);
}
hasFocus && await delay(getDelay(lastStr)); hasFocus && await delay(getDelay(lastStr));
controller.enqueue(new MessageEvent(event.type, { data: JSON.stringify(parsed.data) })); controller.enqueue(new MessageEvent(event.type, { data: JSON.stringify(parsed.data) }));
lastStr = parsed.chunk; lastStr = parsed.chunk;
hasFocus && await eventSource.emit(event_types.SMOOTH_STREAM_TOKEN_RECEIVED, parsed.chunk); hasFocus && await eventSource.emit(event_types.SMOOTH_STREAM_TOKEN_RECEIVED, parsed.chunk);
} }
} catch { } catch (error) {
console.error('Smooth Streaming parsing error', error);
controller.enqueue(event); controller.enqueue(event);
} }
}, },

View File

@ -43,6 +43,9 @@ export {
const CHARACTER_FILTER_SELECTOR = '#rm_characters_block .rm_tag_filter'; const CHARACTER_FILTER_SELECTOR = '#rm_characters_block .rm_tag_filter';
const GROUP_FILTER_SELECTOR = '#rm_group_chats_block .rm_tag_filter'; const GROUP_FILTER_SELECTOR = '#rm_group_chats_block .rm_tag_filter';
const TAG_TEMPLATE = $('#tag_template .tag');
const FOLDER_TEMPLATE = $('#bogus_folder_template .bogus_folder_select');
const VIEW_TAG_TEMPLATE = $('#tag_view_template .tag_view_item');
function getFilterHelper(listSelector) { function getFilterHelper(listSelector) {
return $(listSelector).is(GROUP_FILTER_SELECTOR) ? groupCandidatesFilter : entitiesFilter; return $(listSelector).is(GROUP_FILTER_SELECTOR) ? groupCandidatesFilter : entitiesFilter;
@ -115,6 +118,7 @@ const TAG_FOLDER_DEFAULT_TYPE = 'NONE';
* @property {function} [action] - An optional function that gets executed when this tag is an actionable tag and is clicked on. * @property {function} [action] - An optional function that gets executed when this tag is an actionable tag and is clicked on.
* @property {string} [class] - An optional css class added to the control representing this tag when printed. Used for custom tags in the filters. * @property {string} [class] - An optional css class added to the control representing this tag when printed. Used for custom tags in the filters.
* @property {string} [icon] - An optional css class of an icon representing this tag when printed. This will replace the tag name with the icon. Used for custom tags in the filters. * @property {string} [icon] - An optional css class of an icon representing this tag when printed. This will replace the tag name with the icon. Used for custom tags in the filters.
* @property {string} [title] - An optional title for the tooltip of this tag. If there is no tooltip specified, and "icon" is chosen, the tooltip will be the "name" property.
*/ */
/** /**
@ -125,10 +129,17 @@ let tags = [];
/** /**
* A map representing the key of an entity (character avatar, group id, etc) with a corresponding array of tags this entity has assigned. The array might not exist if no tags were assigned yet. * A map representing the key of an entity (character avatar, group id, etc) with a corresponding array of tags this entity has assigned. The array might not exist if no tags were assigned yet.
* @type {Object.<string, string[]?>} * @type {{[identifier: string]: string[]?}}
*/ */
let tag_map = {}; let tag_map = {};
/**
* A cache of all cut-off tag lists that got expanded until the last reload. They will be printed expanded again.
* It contains the key of the entity.
* @type {string[]} ids
*/
let expanded_tags_cache = [];
/** /**
* Applies the basic filter for the current state of the tags and their selection on an entity list. * Applies the basic filter for the current state of the tags and their selection on an entity list.
* @param {Array<Object>} entities List of entities for display, consisting of tags, characters and groups. * @param {Array<Object>} entities List of entities for display, consisting of tags, characters and groups.
@ -271,7 +282,7 @@ function getTagBlock(tag, entities, hidden = 0) {
const tagFolder = TAG_FOLDER_TYPES[tag.folder_type]; const tagFolder = TAG_FOLDER_TYPES[tag.folder_type];
const template = $('#bogus_folder_template .bogus_folder_select').clone(); const template = FOLDER_TEMPLATE.clone();
template.addClass(tagFolder.class); template.addClass(tagFolder.class);
template.attr({ 'tagid': tag.id, 'id': `BogusFolder${tag.id}` }); template.attr({ 'tagid': tag.id, 'id': `BogusFolder${tag.id}` });
template.find('.avatar').css({ 'background-color': tag.color, 'color': tag.color2 }).attr('title', `[Folder] ${tag.name}`); template.find('.avatar').css({ 'background-color': tag.color, 'color': tag.color2 }).attr('title', `[Folder] ${tag.name}`);
@ -385,7 +396,7 @@ function getTagKey() {
* Robust method to find a valid tag key for any entity. * Robust method to find a valid tag key for any entity.
* *
* @param {object|number|string} entityOrKey An entity with id property (character, group, tag), or directly an id or tag key. * @param {object|number|string} entityOrKey An entity with id property (character, group, tag), or directly an id or tag key.
* @returns {string} The tag key that can be found. * @returns {string|undefined} The tag key that can be found.
*/ */
export function getTagKeyForEntity(entityOrKey) { export function getTagKeyForEntity(entityOrKey) {
let x = entityOrKey; let x = entityOrKey;
@ -416,6 +427,33 @@ export function getTagKeyForEntity(entityOrKey) {
return undefined; return undefined;
} }
/**
* Checks for a tag key based on an entity for a given element.
* It checks the given element and upwards parents for a set character id (chid) or group id (grid), and if there is any, returns its unique entity key.
*
* @param {JQuery<HTMLElement>|string} element - The element to search the entity id on
* @returns {string|undefined} The tag key that can be found.
*/
export function getTagKeyForEntityElement(element) {
if (typeof element === 'string') {
element = $(element);
}
// Start with the given element and traverse up the DOM tree
while (element.length && element.parent().length) {
const grid = element.attr('grid');
const chid = element.attr('chid');
if (grid || chid) {
const id = grid || chid;
return getTagKeyForEntity(id);
}
// Move up to the parent element
element = element.parent();
}
return undefined;
}
function addTagToMap(tagId, characterId = null) { function addTagToMap(tagId, characterId = null) {
const key = characterId !== null && characterId !== undefined ? getTagKeyForEntity(characterId) : getTagKey(); const key = characterId !== null && characterId !== undefined ? getTagKeyForEntity(characterId) : getTagKey();
@ -614,15 +652,16 @@ function createNewTag(tagName) {
/** /**
* Prints the list of tags * Prints the list of tags
* *
* @param {JQuery<HTMLElement>} element - The container element where the tags are to be printed. * @param {JQuery<HTMLElement>|string} element - The container element where the tags are to be printed. (Optionally can also be a string selector for the element, which will then be resolved)
* @param {PrintTagListOptions} [options] - Optional parameters for printing the tag list. * @param {PrintTagListOptions} [options] - Optional parameters for printing the tag list.
*/ */
function printTagList(element, { tags = undefined, addTag = undefined, forEntityOrKey = undefined, empty = true, tagActionSelector = undefined, tagOptions = {} } = {}) { function printTagList(element, { tags = undefined, addTag = undefined, forEntityOrKey = undefined, empty = true, tagActionSelector = undefined, tagOptions = {} } = {}) {
const $element = (typeof element === 'string') ? $(element) : element;
const key = forEntityOrKey !== undefined ? getTagKeyForEntity(forEntityOrKey) : getTagKey(); const key = forEntityOrKey !== undefined ? getTagKeyForEntity(forEntityOrKey) : getTagKey();
let printableTags = tags ? (typeof tags === 'function' ? tags() : tags) : getTagsList(key); let printableTags = tags ? (typeof tags === 'function' ? tags() : tags) : getTagsList(key);
if (empty === 'always' || (empty && (printableTags?.length > 0 || key))) { if (empty === 'always' || (empty && (printableTags?.length > 0 || key))) {
$(element).empty(); $element.empty();
} }
if (addTag && (tagOptions.skipExistsCheck || !printableTags.some(x => x.id === addTag.id))) { if (addTag && (tagOptions.skipExistsCheck || !printableTags.some(x => x.id === addTag.id))) {
@ -634,6 +673,16 @@ function printTagList(element, { tags = undefined, addTag = undefined, forEntity
const customAction = typeof tagActionSelector === 'function' ? tagActionSelector : null; const customAction = typeof tagActionSelector === 'function' ? tagActionSelector : null;
// Well, lets check if the tag list was expanded. Based on either a css class, or when any expand was clicked yet, then we search whether this element id matches
const expanded = $element.hasClass('tags-expanded') || (expanded_tags_cache.length && expanded_tags_cache.indexOf(key ?? getTagKeyForEntityElement(element)) >= 0);
// We prepare some stuff. No matter which list we have, there is a maximum value of tags we are going to display
const TAGS_LIMIT = 50;
const MAX_TAGS = !expanded ? TAGS_LIMIT : Number.MAX_SAFE_INTEGER;
let totalPrinted = 0;
let hiddenTags = 0;
const filterActive = (/** @type {Tag} */ tag) => tag.filter_state && !isFilterState(tag.filter_state, FILTER_STATES.UNDEFINED);
for (const tag of printableTags) { for (const tag of printableTags) {
// If we have a custom action selector, we override that tag options for each tag // If we have a custom action selector, we override that tag options for each tag
if (customAction) { if (customAction) {
@ -645,7 +694,40 @@ function printTagList(element, { tags = undefined, addTag = undefined, forEntity
} }
} }
appendTagToList(element, tag, tagOptions); // Check if we should print this tag
if (totalPrinted++ < MAX_TAGS || filterActive(tag)) {
appendTagToList($element, tag, tagOptions);
} else {
hiddenTags++;
}
}
// After the loop, check if we need to add the placeholder.
// The placehold if clicked expands the tags and remembers either via class or cache array which was expanded, so it'll stay expanded until the next reload.
if (hiddenTags > 0) {
const id = 'placeholder_' + uuidv4();
// Add click event
const showHiddenTags = (_, event) => {
const elementKey = key ?? getTagKeyForEntityElement($element);
console.log(`Hidden tags shown for element ${elementKey}`);
// Mark the current char/group as expanded if we were in any. This will be kept in memory until reload
$element.addClass('tags-expanded');
expanded_tags_cache.push(elementKey);
// Do not bubble further, we are just expanding
event.stopPropagation();
printTagList($element, { tags: tags, addTag: addTag, forEntityOrKey: forEntityOrKey, empty: empty, tagActionSelector: tagActionSelector, tagOptions: tagOptions });
};
// Print the placeholder object with its styling and action to show the remaining tags
/** @type {Tag} */
const placeholderTag = { id: id, name: '...', title: `${hiddenTags} tags not displayed.\n\nClick to expand remaining tags.`, color: 'transparent', action: showHiddenTags, class: 'placeholder-expander' };
// It should never be marked as a removable tag, because it's just an expander action
/** @type {TagOptions} */
const placeholderTagOptions = { ...tagOptions, removable: false };
appendTagToList($element, placeholderTag, placeholderTagOptions);
} }
} }
@ -665,7 +747,7 @@ function appendTagToList(listElement, tag, { removable = false, selectable = fal
return; return;
} }
let tagElement = $('#tag_template .tag').clone(); let tagElement = TAG_TEMPLATE.clone();
tagElement.attr('id', tag.id); tagElement.attr('id', tag.id);
//tagElement.css('color', 'var(--SmartThemeBodyColor)'); //tagElement.css('color', 'var(--SmartThemeBodyColor)');
@ -679,13 +761,19 @@ function appendTagToList(listElement, tag, { removable = false, selectable = fal
if (tag.class) { if (tag.class) {
tagElement.addClass(tag.class); tagElement.addClass(tag.class);
} }
if (tag.title) {
tagElement.attr('title', tag.title);
}
if (tag.icon) { if (tag.icon) {
tagElement.find('.tag_name').text('').attr('title', tag.name).addClass(tag.icon); tagElement.find('.tag_name').text('').attr('title', `${tag.name} ${tag.title || ''}`.trim()).addClass(tag.icon);
tagElement.addClass('actionable');
} }
// We could have multiple ways of actions passed in. The manual arguments have precendence in front of a specified tag action
const clickableAction = action ?? tag.action;
// If this is a tag for a general list and its either selectable or actionable, lets mark its current state // If this is a tag for a general list and its either selectable or actionable, lets mark its current state
if ((selectable || action) && isGeneralList) { if ((selectable || clickableAction) && isGeneralList) {
toggleTagThreeState(tagElement, { stateOverride: tag.filter_state ?? DEFAULT_FILTER_STATE }); toggleTagThreeState(tagElement, { stateOverride: tag.filter_state ?? DEFAULT_FILTER_STATE });
} }
@ -693,14 +781,11 @@ function appendTagToList(listElement, tag, { removable = false, selectable = fal
tagElement.on('click', () => onTagFilterClick.bind(tagElement)(listElement)); tagElement.on('click', () => onTagFilterClick.bind(tagElement)(listElement));
} }
if (action) { if (clickableAction) {
const filter = getFilterHelper($(listElement)); const filter = getFilterHelper($(listElement));
tagElement.on('click', () => action.bind(tagElement)(filter)); tagElement.on('click', (e) => clickableAction.bind(tagElement)(filter, e));
tagElement.addClass('actionable'); tagElement.addClass('clickable-action');
} }
/*if (action && tag.id === 2) {
tagElement.addClass('innerActionable hidden');
}*/
$(listElement).append(tagElement); $(listElement).append(tagElement);
} }
@ -765,7 +850,9 @@ function toggleTagThreeState(element, { stateOverride = undefined, simulateClick
element.toggleClass(FILTER_STATES[state].class, state === states[targetStateIndex]); element.toggleClass(FILTER_STATES[state].class, state === states[targetStateIndex]);
}); });
console.debug('toggle three-way filter from', states[currentStateIndex], 'to', states[targetStateIndex], 'on', element); if (states[currentStateIndex] !== states[targetStateIndex]) {
console.debug('toggle three-way filter from', states[currentStateIndex], 'to', states[targetStateIndex], 'on', element);
}
} }
@ -1129,7 +1216,7 @@ function onTagCreateClick() {
function appendViewTagToList(list, tag, everything) { function appendViewTagToList(list, tag, everything) {
const count = everything.filter(x => x == tag.id).length; const count = everything.filter(x => x == tag.id).length;
const template = $('#tag_view_template .tag_view_item').clone(); const template = VIEW_TAG_TEMPLATE.clone();
template.attr('id', tag.id); template.attr('id', tag.id);
template.find('.tag_view_counter_value').text(count); template.find('.tag_view_counter_value').text(count);
template.find('.tag_view_name').text(tag.name); template.find('.tag_view_name').text(tag.name);
@ -1146,16 +1233,18 @@ function appendViewTagToList(list, tag, everything) {
template.find('.tag_as_folder').hide(); template.find('.tag_as_folder').hide();
} }
template.find('.tagColorPickerHolder').html( const primaryColorPicker = $('<toolcool-color-picker></toolcool-color-picker>')
`<toolcool-color-picker id="${colorPickerId}" color="${tag.color}" class="tag-color"></toolcool-color-picker>`, .addClass('tag-color')
); .attr({ id: colorPickerId, color: tag.color });
template.find('.tagColorPicker2Holder').html(
`<toolcool-color-picker id="${colorPicker2Id}" color="${tag.color2}" class="tag-color2"></toolcool-color-picker>`, const secondaryColorPicker = $('<toolcool-color-picker></toolcool-color-picker>')
); .addClass('tag-color2')
.attr({ id: colorPicker2Id, color: tag.color2 });
template.find('.tagColorPickerHolder').append(primaryColorPicker);
template.find('.tagColorPicker2Holder').append(secondaryColorPicker);
template.find('.tag_as_folder').attr('id', tagAsFolderId); template.find('.tag_as_folder').attr('id', tagAsFolderId);
template.find('.tag-color').attr('id', colorPickerId);
template.find('.tag-color2').attr('id', colorPicker2Id);
list.append(template); list.append(template);

View File

@ -4,6 +4,8 @@
<ul> <ul>
<li><tt>&lcub;&lcub;pipe&rcub;&rcub;</tt> only for slash command batching. Replaced with the returned result of the previous command.</li> <li><tt>&lcub;&lcub;pipe&rcub;&rcub;</tt> only for slash command batching. Replaced with the returned result of the previous command.</li>
<li><tt>&lcub;&lcub;newline&rcub;&rcub;</tt> just inserts a newline.</li> <li><tt>&lcub;&lcub;newline&rcub;&rcub;</tt> just inserts a newline.</li>
<li><tt>&lcub;&lcub;trim&rcub;&rcub;</tt> trims newlines surrounding this macro.</li>
<li><tt>&lcub;&lcub;noop&rcub;&rcub;</tt> no operation, just an empty string.</li>
<li><tt>&lcub;&lcub;original&rcub;&rcub;</tt> global prompts defined in API settings. Only valid in Advanced Definitions prompt overrides.</li> <li><tt>&lcub;&lcub;original&rcub;&rcub;</tt> global prompts defined in API settings. Only valid in Advanced Definitions prompt overrides.</li>
<li><tt>&lcub;&lcub;input&rcub;&rcub;</tt> the user input</li> <li><tt>&lcub;&lcub;input&rcub;&rcub;</tt> the user input</li>
<li><tt>&lcub;&lcub;charPrompt&rcub;&rcub;</tt> the Character's Main Prompt override</li> <li><tt>&lcub;&lcub;charPrompt&rcub;&rcub;</tt> the Character's Main Prompt override</li>
@ -49,6 +51,7 @@
<li><tt>&lcub;&lcub;maxPrompt&rcub;&rcub;</tt> max allowed prompt length in tokens = (context size - response length)</li> <li><tt>&lcub;&lcub;maxPrompt&rcub;&rcub;</tt> max allowed prompt length in tokens = (context size - response length)</li>
<li><tt>&lcub;&lcub;exampleSeparator&rcub;&rcub;</tt> context template example dialogues separator</li> <li><tt>&lcub;&lcub;exampleSeparator&rcub;&rcub;</tt> context template example dialogues separator</li>
<li><tt>&lcub;&lcub;chatStart&rcub;&rcub;</tt> context template chat start line</li> <li><tt>&lcub;&lcub;chatStart&rcub;&rcub;</tt> context template chat start line</li>
<li><tt>&lcub;&lcub;systemPrompt&rcub;&rcub;</tt> main system prompt (either character prompt override if chosen, or instructSystemPrompt)</li>
<li><tt>&lcub;&lcub;instructSystemPrompt&rcub;&rcub;</tt> instruct system prompt</li> <li><tt>&lcub;&lcub;instructSystemPrompt&rcub;&rcub;</tt> instruct system prompt</li>
<li><tt>&lcub;&lcub;instructSystemPromptPrefix&rcub;&rcub;</tt> instruct system prompt prefix sequence</li> <li><tt>&lcub;&lcub;instructSystemPromptPrefix&rcub;&rcub;</tt> instruct system prompt prefix sequence</li>
<li><tt>&lcub;&lcub;instructSystemPromptSuffix&rcub;&rcub;</tt> instruct system prompt suffix sequence</li> <li><tt>&lcub;&lcub;instructSystemPromptSuffix&rcub;&rcub;</tt> instruct system prompt suffix sequence</li>
@ -60,6 +63,7 @@
<li><tt>&lcub;&lcub;instructLastAssistantPrefix&rcub;&rcub;</tt> instruct assistant last output sequence</li> <li><tt>&lcub;&lcub;instructLastAssistantPrefix&rcub;&rcub;</tt> instruct assistant last output sequence</li>
<li><tt>&lcub;&lcub;instructSystemPrefix&rcub;&rcub;</tt> instruct system message prefix sequence</li> <li><tt>&lcub;&lcub;instructSystemPrefix&rcub;&rcub;</tt> instruct system message prefix sequence</li>
<li><tt>&lcub;&lcub;instructSystemSuffix&rcub;&rcub;</tt> instruct system message suffix sequence</li> <li><tt>&lcub;&lcub;instructSystemSuffix&rcub;&rcub;</tt> instruct system message suffix sequence</li>
<li><tt>&lcub;&lcub;instructSystemInstructionPrefix&rcub;&rcub;</tt> instruct system instruction prefix</li>
<li><tt>&lcub;&lcub;instructUserFiller&rcub;&rcub;</tt> instruct first user message filler</li> <li><tt>&lcub;&lcub;instructUserFiller&rcub;&rcub;</tt> instruct first user message filler</li>
<li><tt>&lcub;&lcub;instructStop&rcub;&rcub;</tt> instruct stop sequence</li> <li><tt>&lcub;&lcub;instructStop&rcub;&rcub;</tt> instruct stop sequence</li>
</ul> </ul>

View File

@ -568,7 +568,7 @@ jQuery(function () {
const json_schema_string = String($(this).val()); const json_schema_string = String($(this).val());
try { try {
settings.json_schema = JSON.parse(json_schema_string ?? '{}'); settings.json_schema = JSON.parse(json_schema_string || '{}');
} catch { } catch {
// Ignore errors from here // Ignore errors from here
} }

View File

@ -42,6 +42,8 @@ const world_info_logic = {
AND_ALL: 3, AND_ALL: 3,
}; };
const WI_ENTRY_EDIT_TEMPLATE = $('#entry_edit_template .world_entry');
let world_info = {}; let world_info = {};
let selected_world_info = []; let selected_world_info = [];
let world_names; let world_names;
@ -95,6 +97,11 @@ class WorldInfoBuffer {
*/ */
#skew = 0; #skew = 0;
/**
* @type {number} The starting depth of the global scan depth. Incremented by "min activations" feature to not repeat scans. When > 0 it means a complete scan was done up to #startDepth already, and `advanceScanPosition` was called.
*/
#startDepth = 0;
/** /**
* Initialize the buffer with the given messages. * Initialize the buffer with the given messages.
* @param {string[]} messages Array of messages to add to the buffer * @param {string[]} messages Array of messages to add to the buffer
@ -137,7 +144,10 @@ class WorldInfoBuffer {
* @returns {string} A slice of buffer until the given depth (inclusive) * @returns {string} A slice of buffer until the given depth (inclusive)
*/ */
get(entry) { get(entry) {
let depth = entry.scanDepth ?? (world_info_depth + this.#skew); let depth = entry.scanDepth ?? this.getDepth();
if (depth <= this.#startDepth) {
return '';
}
if (depth < 0) { if (depth < 0) {
console.error(`Invalid WI scan depth ${depth}. Must be >= 0`); console.error(`Invalid WI scan depth ${depth}. Must be >= 0`);
@ -149,7 +159,7 @@ class WorldInfoBuffer {
depth = MAX_SCAN_DEPTH; depth = MAX_SCAN_DEPTH;
} }
let result = this.#depthBuffer.slice(0, depth).join('\n'); let result = this.#depthBuffer.slice(this.#startDepth, depth).join('\n');
if (this.#recurseBuffer.length > 0) { if (this.#recurseBuffer.length > 0) {
result += '\n' + this.#recurseBuffer.join('\n'); result += '\n' + this.#recurseBuffer.join('\n');
@ -197,11 +207,19 @@ class WorldInfoBuffer {
} }
/** /**
* Adds an increment to depth skew. * Increments skew and sets startDepth to previous depth.
*/ */
addSkew() { advanceScanPosition() {
this.#startDepth = this.getDepth();
this.#skew++; this.#skew++;
} }
/**
* @returns {number} Settings' depth + current skew.
*/
getDepth() {
return world_info_depth + this.#skew;
}
} }
export function getWorldInfoSettings() { export function getWorldInfoSettings() {
@ -783,6 +801,11 @@ function displayWorldEntries(name, data, navigation = navigation_option.none) {
afterSizeSelectorChange: function (e) { afterSizeSelectorChange: function (e) {
localStorage.setItem(storageKey, e.target.value); localStorage.setItem(storageKey, e.target.value);
}, },
afterPaging: function () {
$('#world_popup_entries_list textarea[name="comment"]').each(function () {
initScrollHeight($(this));
});
},
}); });
if (typeof navigation === 'number' && Number(navigation) >= 0) { if (typeof navigation === 'number' && Number(navigation) >= 0) {
@ -970,7 +993,7 @@ function getWorldEntry(name, data, entry) {
return; return;
} }
const template = $('#entry_edit_template .world_entry').clone(); const template = WI_ENTRY_EDIT_TEMPLATE.clone();
template.data('uid', entry.uid); template.data('uid', entry.uid);
template.attr('uid', entry.uid); template.attr('uid', entry.uid);
@ -982,10 +1005,10 @@ function getWorldEntry(name, data, entry) {
event.stopPropagation(); event.stopPropagation();
}); });
keyInput.on('input', function () { keyInput.on('input', function (_, { skipReset } = {}) {
const uid = $(this).data('uid'); const uid = $(this).data('uid');
const value = String($(this).val()); const value = String($(this).val());
resetScrollHeight(this); !skipReset && resetScrollHeight(this);
data.entries[uid].key = value data.entries[uid].key = value
.split(',') .split(',')
.map((x) => x.trim()) .map((x) => x.trim())
@ -994,7 +1017,7 @@ function getWorldEntry(name, data, entry) {
setOriginalDataValue(data, uid, 'keys', data.entries[uid].key); setOriginalDataValue(data, uid, 'keys', data.entries[uid].key);
saveWorldInfo(name, data); saveWorldInfo(name, data);
}); });
keyInput.val(entry.key.join(', ')).trigger('input'); keyInput.val(entry.key.join(', ')).trigger('input', { skipReset: true });
//initScrollHeight(keyInput); //initScrollHeight(keyInput);
// logic AND/NOT // logic AND/NOT
@ -1008,7 +1031,6 @@ function getWorldEntry(name, data, entry) {
selectiveLogicDropdown.on('input', function () { selectiveLogicDropdown.on('input', function () {
const uid = $(this).data('uid'); const uid = $(this).data('uid');
const value = Number($(this).val()); const value = Number($(this).val());
console.debug(`logic for ${entry.uid} set to ${value}`);
data.entries[uid].selectiveLogic = !isNaN(value) ? value : world_info_logic.AND_ANY; data.entries[uid].selectiveLogic = !isNaN(value) ? value : world_info_logic.AND_ANY;
setOriginalDataValue(data, uid, 'selectiveLogic', data.entries[uid].selectiveLogic); setOriginalDataValue(data, uid, 'selectiveLogic', data.entries[uid].selectiveLogic);
saveWorldInfo(name, data); saveWorldInfo(name, data);
@ -1118,10 +1140,10 @@ function getWorldEntry(name, data, entry) {
// keysecondary // keysecondary
const keySecondaryInput = template.find('textarea[name="keysecondary"]'); const keySecondaryInput = template.find('textarea[name="keysecondary"]');
keySecondaryInput.data('uid', entry.uid); keySecondaryInput.data('uid', entry.uid);
keySecondaryInput.on('input', function () { keySecondaryInput.on('input', function (_, { skipReset } = {}) {
const uid = $(this).data('uid'); const uid = $(this).data('uid');
const value = String($(this).val()); const value = String($(this).val());
resetScrollHeight(this); !skipReset && resetScrollHeight(this);
data.entries[uid].keysecondary = value data.entries[uid].keysecondary = value
.split(',') .split(',')
.map((x) => x.trim()) .map((x) => x.trim())
@ -1131,17 +1153,17 @@ function getWorldEntry(name, data, entry) {
saveWorldInfo(name, data); saveWorldInfo(name, data);
}); });
keySecondaryInput.val(entry.keysecondary.join(', ')).trigger('input'); keySecondaryInput.val(entry.keysecondary.join(', ')).trigger('input', { skipReset: true });
initScrollHeight(keySecondaryInput); //initScrollHeight(keySecondaryInput);
// comment // comment
const commentInput = template.find('textarea[name="comment"]'); const commentInput = template.find('textarea[name="comment"]');
const commentToggle = template.find('input[name="addMemo"]'); const commentToggle = template.find('input[name="addMemo"]');
commentInput.data('uid', entry.uid); commentInput.data('uid', entry.uid);
commentInput.on('input', function () { commentInput.on('input', function (_, { skipReset } = {}) {
const uid = $(this).data('uid'); const uid = $(this).data('uid');
const value = $(this).val(); const value = $(this).val();
resetScrollHeight(this); !skipReset && resetScrollHeight(this);
data.entries[uid].comment = value; data.entries[uid].comment = value;
setOriginalDataValue(data, uid, 'comment', data.entries[uid].comment); setOriginalDataValue(data, uid, 'comment', data.entries[uid].comment);
@ -1160,8 +1182,8 @@ function getWorldEntry(name, data, entry) {
value ? commentContainer.show() : commentContainer.hide(); value ? commentContainer.show() : commentContainer.hide();
}); });
commentInput.val(entry.comment).trigger('input'); commentInput.val(entry.comment).trigger('input', { skipReset: true });
initScrollHeight(commentInput); //initScrollHeight(commentInput);
commentToggle.prop('checked', true /* entry.addMemo */).trigger('input'); commentToggle.prop('checked', true /* entry.addMemo */).trigger('input');
commentToggle.parent().hide(); commentToggle.parent().hide();
@ -1196,6 +1218,8 @@ function getWorldEntry(name, data, entry) {
if (counter.data('first-run')) { if (counter.data('first-run')) {
counter.data('first-run', false); counter.data('first-run', false);
countTokensDebounced(counter, contentInput.val()); countTokensDebounced(counter, contentInput.val());
initScrollHeight(keyInput);
initScrollHeight(keySecondaryInput);
} }
}); });
@ -1362,7 +1386,7 @@ function getWorldEntry(name, data, entry) {
} }
const positionInput = template.find('select[name="position"]'); const positionInput = template.find('select[name="position"]');
initScrollHeight(positionInput); //initScrollHeight(positionInput);
positionInput.data('uid', entry.uid); positionInput.data('uid', entry.uid);
positionInput.on('click', function (event) { positionInput.on('click', function (event) {
// Prevent closing the drawer on clicking the input // Prevent closing the drawer on clicking the input
@ -1419,7 +1443,6 @@ function getWorldEntry(name, data, entry) {
//new tri-state selector for constant/normal/disabled //new tri-state selector for constant/normal/disabled
const entryStateSelector = template.find('select[name="entryStateSelector"]'); const entryStateSelector = template.find('select[name="entryStateSelector"]');
entryStateSelector.data('uid', entry.uid); entryStateSelector.data('uid', entry.uid);
console.log(entry.uid);
entryStateSelector.on('click', function (event) { entryStateSelector.on('click', function (event) {
// Prevent closing the drawer on clicking the input // Prevent closing the drawer on clicking the input
event.stopPropagation(); event.stopPropagation();
@ -1434,7 +1457,6 @@ function getWorldEntry(name, data, entry) {
setOriginalDataValue(data, uid, 'enabled', true); setOriginalDataValue(data, uid, 'enabled', true);
setOriginalDataValue(data, uid, 'constant', true); setOriginalDataValue(data, uid, 'constant', true);
template.removeClass('disabledWIEntry'); template.removeClass('disabledWIEntry');
console.debug('set to constant');
break; break;
case 'normal': case 'normal':
data.entries[uid].constant = false; data.entries[uid].constant = false;
@ -1442,7 +1464,6 @@ function getWorldEntry(name, data, entry) {
setOriginalDataValue(data, uid, 'enabled', true); setOriginalDataValue(data, uid, 'enabled', true);
setOriginalDataValue(data, uid, 'constant', false); setOriginalDataValue(data, uid, 'constant', false);
template.removeClass('disabledWIEntry'); template.removeClass('disabledWIEntry');
console.debug('set to normal');
break; break;
case 'disabled': case 'disabled':
data.entries[uid].constant = false; data.entries[uid].constant = false;
@ -1450,7 +1471,6 @@ function getWorldEntry(name, data, entry) {
setOriginalDataValue(data, uid, 'enabled', false); setOriginalDataValue(data, uid, 'enabled', false);
setOriginalDataValue(data, uid, 'constant', false); setOriginalDataValue(data, uid, 'constant', false);
template.addClass('disabledWIEntry'); template.addClass('disabledWIEntry');
console.debug('set to disabled');
break; break;
} }
saveWorldInfo(name, data); saveWorldInfo(name, data);
@ -1458,19 +1478,13 @@ function getWorldEntry(name, data, entry) {
}); });
const entryState = function () { const entryState = function () {
console.log(`constant: ${entry.constant}, disabled: ${entry.disable}`);
if (entry.constant === true) { if (entry.constant === true) {
console.debug('found constant');
return 'constant'; return 'constant';
} else if (entry.disable === true) { } else if (entry.disable === true) {
console.debug('found disabled');
return 'disabled'; return 'disabled';
} else { } else {
console.debug('found normal');
return 'normal'; return 'normal';
} }
}; };
template template
.find(`select[name="entryStateSelector"] option[value=${entryState()}]`) .find(`select[name="entryStateSelector"] option[value=${entryState()}]`)
@ -1966,15 +1980,12 @@ async function getSortedEntries() {
switch (Number(world_info_character_strategy)) { switch (Number(world_info_character_strategy)) {
case world_info_insertion_strategy.evenly: case world_info_insertion_strategy.evenly:
console.debug('WI using evenly');
entries = [...globalLore, ...characterLore].sort(sortFn); entries = [...globalLore, ...characterLore].sort(sortFn);
break; break;
case world_info_insertion_strategy.character_first: case world_info_insertion_strategy.character_first:
console.debug('WI using char first');
entries = [...characterLore.sort(sortFn), ...globalLore.sort(sortFn)]; entries = [...characterLore.sort(sortFn), ...globalLore.sort(sortFn)];
break; break;
case world_info_insertion_strategy.global_first: case world_info_insertion_strategy.global_first:
console.debug('WI using global first');
entries = [...globalLore.sort(sortFn), ...characterLore.sort(sortFn)]; entries = [...globalLore.sort(sortFn), ...characterLore.sort(sortFn)];
break; break;
default: default:
@ -2009,7 +2020,6 @@ async function checkWorldInfo(chat, maxContext) {
const buffer = new WorldInfoBuffer(chat); const buffer = new WorldInfoBuffer(chat);
// Combine the chat // Combine the chat
let minActivationMsgIndex = world_info_depth; // tracks chat index to satisfy `world_info_min_activations`
// Add the depth or AN if enabled // Add the depth or AN if enabled
// Put this code here since otherwise, the chat reference is modified // Put this code here since otherwise, the chat reference is modified
@ -2102,8 +2112,6 @@ async function checkWorldInfo(chat, maxContext) {
const substituted = substituteParams(key); const substituted = substituteParams(key);
const textToScan = buffer.get(entry); const textToScan = buffer.get(entry);
console.debug(`${entry.uid}: ${substituted}`);
if (substituted && buffer.matchKeys(textToScan, substituted.trim(), entry)) { if (substituted && buffer.matchKeys(textToScan, substituted.trim(), entry)) {
console.debug(`WI UID ${entry.uid} found by primary match: ${substituted}.`); console.debug(`WI UID ${entry.uid} found by primary match: ${substituted}.`);
@ -2160,7 +2168,7 @@ async function checkWorldInfo(chat, maxContext) {
activatedNow.add(entry); activatedNow.add(entry);
break primary; break primary;
} }
} else { console.debug(`No active entries for logic checks for word: ${substituted}.`); } }
} }
} }
} }
@ -2225,15 +2233,14 @@ async function checkWorldInfo(chat, maxContext) {
// world_info_min_activations // world_info_min_activations
if (!needsToScan && !token_budget_overflowed) { if (!needsToScan && !token_budget_overflowed) {
if (world_info_min_activations > 0 && (allActivatedEntries.size < world_info_min_activations)) { if (world_info_min_activations > 0 && (allActivatedEntries.size < world_info_min_activations)) {
let over_max = false; let over_max = (
over_max = (
world_info_min_activations_depth_max > 0 && world_info_min_activations_depth_max > 0 &&
minActivationMsgIndex > world_info_min_activations_depth_max buffer.getDepth() > world_info_min_activations_depth_max
) || (minActivationMsgIndex >= chat.length); ) || (buffer.getDepth() > chat.length);
if (!over_max) { if (!over_max) {
needsToScan = true; needsToScan = true; // loop
minActivationMsgIndex += 1; buffer.advanceScanPosition();
buffer.addSkew();
} }
} }
} }

View File

@ -539,6 +539,7 @@ body.reduced-motion #bg_custom {
margin-right: 5px; margin-right: 5px;
z-index: 2000; z-index: 2000;
min-width: 55px; min-width: 55px;
justify-content: flex-end;
} }
.panelControlBar .drag-grabber { .panelControlBar .drag-grabber {
@ -984,9 +985,7 @@ body.reduced-motion #bg_custom {
} }
.avatars_inline .avatar { .avatars_inline .avatar {
margin-top: calc(var(--avatar-base-border-radius)); margin: calc(var(--avatar-base-border-radius));
margin-left: calc(var(--avatar-base-border-radius));
margin-bottom: calc(var(--avatar-base-border-radius));
} }
.avatars_inline .avatar:last-of-type { .avatars_inline .avatar:last-of-type {
@ -1099,8 +1098,8 @@ select {
@media screen and (min-width: 1001px) { @media screen and (min-width: 1001px) {
#description_textarea { #description_textarea {
height: 30vh; height: 29vh;
height: 30svh; height: 29svh;
} }
#firstmessage_textarea { #firstmessage_textarea {
@ -1187,7 +1186,7 @@ input[type="file"] {
#right-nav-panel-tabs { #right-nav-panel-tabs {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 5px;
overflow: hidden; overflow: hidden;
width: 100%; width: 100%;
} }
@ -1197,7 +1196,7 @@ input[type="file"] {
align-items: center; align-items: center;
flex-wrap: wrap; flex-wrap: wrap;
gap: 10px; gap: 10px;
padding: 0 5px; padding: 0px 10px 0px 5px;
} }
#right-nav-panel-tabs .right_menu_button, #right-nav-panel-tabs .right_menu_button,
@ -1651,6 +1650,7 @@ input[type=search]:focus::-webkit-search-cancel-button {
.missing-avatar.inline_avatar { .missing-avatar.inline_avatar {
padding: unset; padding: unset;
border-radius: var(--avatar-base-border-radius-round); border-radius: var(--avatar-base-border-radius-round);
width: fit-content;
} }
/*applies to char list and mes_text char display name*/ /*applies to char list and mes_text char display name*/
@ -1999,6 +1999,19 @@ grammarly-extension {
justify-content: center; justify-content: center;
align-items: center; align-items: center;
align-self: center !important; align-self: center !important;
width: 100%;
height: 100%;
/* Avoids cutting off the box shadow on the avatar*/
margin: 10px;
}
#avatar_controls {
height: 100%;
width: 100%;
flex-grow: 1;
justify-content: flex-end;
flex-flow: column;
padding: 5px 5px 10px 0;
} }
#description_div, #description_div,
@ -2058,7 +2071,8 @@ grammarly-extension {
/* Focus */ /* Focus */
#bulk_tag_popup, #bulk_tag_popup,
#dialogue_popup { #dialogue_popup,
.dialogue_popup {
width: 500px; width: 500px;
max-width: 90vw; max-width: 90vw;
max-width: 90svw; max-width: 90svw;
@ -2111,7 +2125,8 @@ grammarly-extension {
} }
#bulk_tag_popup_holder, #bulk_tag_popup_holder,
#dialogue_popup_holder { #dialogue_popup_holder,
.dialogue_popup_holder {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 100%; height: 100%;
@ -2119,13 +2134,15 @@ grammarly-extension {
padding: 0 10px; padding: 0 10px;
} }
#dialogue_popup_text { #dialogue_popup_text,
.dialogue_popup_text {
flex-grow: 1; flex-grow: 1;
overflow-y: auto; overflow-y: auto;
height: 100%; height: 100%;
} }
#dialogue_popup_controls { #dialogue_popup_controls,
.dialogue_popup_controls {
display: flex; display: flex;
align-self: center; align-self: center;
gap: 20px; gap: 20px;
@ -2133,14 +2150,16 @@ grammarly-extension {
#bulk_tag_popup_reset, #bulk_tag_popup_reset,
#bulk_tag_popup_remove_mutual, #bulk_tag_popup_remove_mutual,
#dialogue_popup_ok { #dialogue_popup_ok,
.dialogue_popup_ok {
background-color: var(--crimson70a); background-color: var(--crimson70a);
cursor: pointer; cursor: pointer;
} }
#bulk_tag_popup_reset:hover, #bulk_tag_popup_reset:hover,
#bulk_tag_popup_remove_mutual:hover, #bulk_tag_popup_remove_mutual:hover,
#dialogue_popup_ok:hover { #dialogue_popup_ok:hover,
.dialogue_popup_ok:hover {
background-color: var(--crimson-hover); background-color: var(--crimson-hover);
} }
@ -2148,13 +2167,15 @@ grammarly-extension {
max-height: 70vh; max-height: 70vh;
} }
#dialogue_popup_input { #dialogue_popup_input,
.dialogue_popup_input {
margin: 10px 0; margin: 10px 0;
width: 100%; width: 100%;
} }
#bulk_tag_popup_cancel, #bulk_tag_popup_cancel,
#dialogue_popup_cancel { #dialogue_popup_cancel,
.dialogue_popup_cancel {
cursor: pointer; cursor: pointer;
} }
@ -2201,11 +2222,11 @@ grammarly-extension {
font-weight: bold; font-weight: bold;
padding: 5px; padding: 5px;
margin: 0; margin: 0;
height: 26px;
filter: grayscale(0.5); filter: grayscale(0.5);
text-align: center; text-align: center;
font-size: 17px; font-size: 17px;
aspect-ratio: 1 / 1; aspect-ratio: 1 / 1;
flex: 0.075;
} }
.menu_button:hover, .menu_button:hover,
@ -2219,7 +2240,7 @@ grammarly-extension {
margin-right: 25px; margin-right: 25px;
} }
#shadow_popup { #shadow_popup, .shadow_popup {
backdrop-filter: blur(calc(var(--SmartThemeBlurStrength) * 2)); backdrop-filter: blur(calc(var(--SmartThemeBlurStrength) * 2));
-webkit-backdrop-filter: blur(calc(var(--SmartThemeBlurStrength) * 2)); -webkit-backdrop-filter: blur(calc(var(--SmartThemeBlurStrength) * 2));
background-color: var(--black30a); background-color: var(--black30a);
@ -2231,6 +2252,9 @@ grammarly-extension {
height: 100svh; height: 100svh;
z-index: 9999; z-index: 9999;
top: 0; top: 0;
&.shadow_popup {
z-index: 9998;
}
} }
#bgtest { #bgtest {
@ -2621,7 +2645,11 @@ input[type="range"]::-webkit-slider-thumb {
color: var(--SmartThemeBodyColor); color: var(--SmartThemeBodyColor);
} }
#char-management-dropdown, #char-management-dropdown {
height: auto;
margin-bottom: 0;
}
#tagInput { #tagInput {
height: 26px; height: 26px;
margin-bottom: 0; margin-bottom: 0;

View File

@ -341,6 +341,7 @@ redirect('/savequickreply', '/api/quick-replies/save');
// Redirect deprecated image endpoints // Redirect deprecated image endpoints
redirect('/uploadimage', '/api/images/upload'); redirect('/uploadimage', '/api/images/upload');
redirect('/listimgfiles/:folder', '/api/images/list/:folder'); redirect('/listimgfiles/:folder', '/api/images/list/:folder');
redirect('/api/content/import', '/api/content/importURL');
// Redirect deprecated moving UI endpoints // Redirect deprecated moving UI endpoints
redirect('/savemovingui', '/api/moving-ui/save'); redirect('/savemovingui', '/api/moving-ui/save');

View File

@ -15,6 +15,23 @@ const API_CLAUDE = 'https://api.anthropic.com/v1';
const API_MISTRAL = 'https://api.mistral.ai/v1'; const API_MISTRAL = 'https://api.mistral.ai/v1';
const API_COHERE = 'https://api.cohere.ai/v1'; const API_COHERE = 'https://api.cohere.ai/v1';
/**
* Applies a post-processing step to the generated messages.
* @param {object[]} messages Messages to post-process
* @param {string} type Prompt conversion type
* @param {string} charName Character name
* @param {string} userName User name
* @returns
*/
function postProcessPrompt(messages, type, charName, userName) {
switch (type) {
case 'claude':
return convertClaudeMessages(messages, '', false, '', charName, userName).messages;
default:
return messages;
}
}
/** /**
* Ollama strikes back. Special boy #2's steaming routine. * Ollama strikes back. Special boy #2's steaming routine.
* Wrap this abomination into proper SSE stream, again. * Wrap this abomination into proper SSE stream, again.
@ -36,7 +53,13 @@ async function parseCohereStream(jsonStream, request, response) {
} catch (e) { } catch (e) {
break; break;
} }
if (json.event_type === 'text-generation') { if (json.message) {
const message = json.message || 'Unknown error';
const chunk = { error: { message: message } };
response.write(`data: ${JSON.stringify(chunk)}\n\n`);
partialData = '';
break;
} else if (json.event_type === 'text-generation') {
const text = json.text || ''; const text = json.text || '';
const chunk = { choices: [{ text }] }; const chunk = { choices: [{ text }] };
response.write(`data: ${JSON.stringify(chunk)}\n\n`); response.write(`data: ${JSON.stringify(chunk)}\n\n`);
@ -516,6 +539,11 @@ async function sendMistralAIRequest(request, response) {
} }
} }
/**
* Sends a request to Cohere API.
* @param {express.Request} request Express request
* @param {express.Response} response Express response
*/
async function sendCohereRequest(request, response) { async function sendCohereRequest(request, response) {
const apiKey = readSecret(SECRET_KEYS.COHERE); const apiKey = readSecret(SECRET_KEYS.COHERE);
const controller = new AbortController(); const controller = new AbortController();
@ -842,6 +870,15 @@ router.post('/generate', jsonParser, function (request, response) {
mergeObjectWithYaml(bodyParams, request.body.custom_include_body); mergeObjectWithYaml(bodyParams, request.body.custom_include_body);
mergeObjectWithYaml(headers, request.body.custom_include_headers); mergeObjectWithYaml(headers, request.body.custom_include_headers);
if (request.body.custom_prompt_post_processing) {
console.log('Applying custom prompt post-processing of type', request.body.custom_prompt_post_processing);
request.body.messages = postProcessPrompt(
request.body.messages,
request.body.custom_prompt_post_processing,
request.body.char_name,
request.body.user_name);
}
} else { } else {
console.log('This chat completion source is not supported yet.'); console.log('This chat completion source is not supported yet.');
return response.status(400).send({ error: true }); return response.status(400).send({ error: true });

View File

@ -473,6 +473,76 @@ llamacpp.post('/caption-image', jsonParser, async function (request, response) {
} }
}); });
llamacpp.post('/props', jsonParser, async function (request, response) {
try {
if (!request.body.server_url) {
return response.sendStatus(400);
}
console.log('LlamaCpp props request:', request.body);
const baseUrl = trimV1(request.body.server_url);
const fetchResponse = await fetch(`${baseUrl}/props`, {
method: 'GET',
timeout: 0,
});
if (!fetchResponse.ok) {
console.log('LlamaCpp props error:', fetchResponse.status, fetchResponse.statusText);
return response.status(500).send({ error: true });
}
const data = await fetchResponse.json();
console.log('LlamaCpp props response:', data);
return response.send(data);
} catch (error) {
console.error(error);
return response.status(500);
}
});
llamacpp.post('/slots', jsonParser, async function (request, response) {
try {
if (!request.body.server_url) {
return response.sendStatus(400);
}
if (!/^\d+$/.test(request.body.id_slot)) {
return response.sendStatus(400);
}
if (!/^(erase|restore|save)$/.test(request.body.action)) {
return response.sendStatus(400);
}
console.log('LlamaCpp slots request:', request.body);
const baseUrl = trimV1(request.body.server_url);
const fetchResponse = await fetch(`${baseUrl}/slots/${request.body.id_slot}?action=${request.body.action}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
timeout: 0,
body: JSON.stringify({
filename: `${request.body.filename}`,
}),
});
if (!fetchResponse.ok) {
console.log('LlamaCpp slots error:', fetchResponse.status, fetchResponse.statusText);
return response.status(500).send({ error: true });
}
const data = await fetchResponse.json();
console.log('LlamaCpp slots response:', data);
return response.send(data);
} catch (error) {
console.error(error);
return response.status(500);
}
});
router.use('/ollama', ollama); router.use('/ollama', ollama);
router.use('/llamacpp', llamacpp); router.use('/llamacpp', llamacpp);

View File

@ -74,6 +74,8 @@ router.post('/create', jsonParser, (request, response) => {
chat_id: request.body.chat_id ?? id, chat_id: request.body.chat_id ?? id,
chats: request.body.chats ?? [id], chats: request.body.chats ?? [id],
auto_mode_delay: request.body.auto_mode_delay ?? 5, auto_mode_delay: request.body.auto_mode_delay ?? 5,
generation_mode_join_prefix: request.body.generation_mode_join_prefix ?? '',
generation_mode_join_suffix: request.body.generation_mode_join_suffix ?? '',
}; };
const pathToFile = path.join(DIRECTORIES.groups, `${id}.json`); const pathToFile = path.join(DIRECTORIES.groups, `${id}.json`);
const fileData = JSON.stringify(groupMetadata); const fileData = JSON.stringify(groupMetadata);

View File

@ -6,6 +6,7 @@ const { readAllChunks, extractFileFromZipBuffer, forwardFetchResponse } = requir
const { jsonParser } = require('../express-common'); const { jsonParser } = require('../express-common');
const API_NOVELAI = 'https://api.novelai.net'; const API_NOVELAI = 'https://api.novelai.net';
const IMAGE_NOVELAI = 'https://image.novelai.net';
// Ban bracket generation, plus defaults // Ban bracket generation, plus defaults
const badWordsList = [ const badWordsList = [
@ -238,7 +239,7 @@ router.post('/generate-image', jsonParser, async (request, response) => {
try { try {
console.log('NAI Diffusion request:', request.body); console.log('NAI Diffusion request:', request.body);
const generateUrl = `${API_NOVELAI}/ai/generate-image`; const generateUrl = `${IMAGE_NOVELAI}/ai/generate-image`;
const generateResult = await fetch(generateUrl, { const generateResult = await fetch(generateUrl, {
method: 'POST', method: 'POST',
headers: { headers: {