Compare commits

...
68 Commits
Author SHA1 Message Date
RossAscends be307b1107 fixed typo in auto-save message edit checkbox 2023-04-21 05:16:15 +09:00
SillyLossy 3e95989fad Merge branch 'main' into dev 2023-04-20 23:08:25 +03:00
RossAscends f5582a62bc remove transition swapping on UI customization 2023-04-21 04:33:46 +09:00
RossAscends cb87ba2da1 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-21 04:26:06 +09:00
RossAscends 38e6b0498d - correct centering for waifumode PC
- remove transition from #chat
- better swipe animations
- standardized naming for animation variables
2023-04-21 04:26:03 +09:00
SillyLossy 35f669d7e9 Fix hint on expressions 2023-04-20 21:42:22 +03:00
SillyLossy 9360e65606 Reload expressions list on connecting to API 2023-04-20 21:16:58 +03:00
SillyLossy 330a8cd1d6 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-20 20:27:48 +03:00
SillyLossy 59284a5436 New validation logic of expression images 2023-04-20 20:26:32 +03:00
RossAscends e503d340b9 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-21 02:14:18 +09:00
RossAscends 03b3fc9fc1 - added edit message auto saving
- toggle in PowerUser settings
- removed consolelog spam from RA-mods and expressions
2023-04-21 02:14:16 +09:00
Cohee e12162f58d Update faq.md 2023-04-20 19:19:08 +03:00
Cohee 183a4eadf3 Update readme.md 2023-04-20 19:17:50 +03:00
Cohee ec8b39bf44 Update readme.md 2023-04-20 19:16:46 +03:00
Cohee fd33ff21be Merge pull request #117 from paniphons/main
Create FAQ to avoid bloating README
2023-04-20 19:16:24 +03:00
Paniphon 620e965533 Move prompt editing info from README to FAQ 2023-04-20 22:41:08 +07:00
Paniphon cbd84dcf0a Update readme.md 2023-04-20 22:36:27 +07:00
Paniphon f5ec5a9788 Update README to link FAQ 2023-04-20 22:33:26 +07:00
Paniphon 795f47a301 Create faq.md 2023-04-20 22:24:40 +07:00
SillyLossy 1a3616ae47 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-20 18:18:10 +03:00
SillyLossy f28850220a Proper regeneration for groups 2023-04-20 18:18:07 +03:00
RossAscends d452467818 - escape from edit message now focuses on send_textarea
- allow swipes to happen when send_textarea is focused but empty
2023-04-20 23:58:12 +09:00
RossAscends 7fb3d1f578 fixed listener order for proper key detection 2023-04-20 23:39:02 +09:00
RossAscends 516a61a5ee added proper focus filter to uparrow hotkeys 2023-04-20 23:36:48 +09:00
RossAscends 9ee9da6705 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-20 23:23:56 +09:00
RossAscends 6d77dfbf48 uparrow = edit last message in chat
ctrl+uparrow = edit last user message

removed ctrl+uparrow for autoconnect hotkey
2023-04-20 23:23:46 +09:00
SillyLossy f591961dd7 Merge branch 'main' into dev 2023-04-20 17:11:21 +03:00
SillyLossy 1718452efb Fix code block parsing #116 2023-04-20 17:10:57 +03:00
RossAscends 60bfcc1a6b removed log spam from uparrow 2023-04-20 23:04:08 +09:00
RossAscends acea6fab67 added UpArrow to quick edit last user mes 2023-04-20 22:59:13 +09:00
Cohee b30df36b8c Merge pull request #113 from sanskar-mk2/whitelist-txt-feature
optional whitelist.txt
2023-04-20 16:12:09 +03:00
Cohee 325f4170cb Fix server crash if whitelist.txt is missing 2023-04-20 16:10:05 +03:00
Sanskar Tiwari 50792fdef5 optional whitelist.txt 2023-04-20 18:11:20 +05:30
Cohee db39807dd6 Merge pull request #112 from sanskar-mk2/bg-filter-feature
add bg filter feature on the frontend
2023-04-20 14:25:10 +03:00
SillyLossy ae0a83161d Remove the memory attached to right swipe 2023-04-20 14:24:06 +03:00
Sanskar Tiwari ce6e367a95 add bg filter feature on the frontend 2023-04-20 16:37:58 +05:30
SillyLossy 711e5fefb0 Fix impersonation in empty chat 2023-04-20 13:40:43 +03:00
SillyLossy b2366993a8 Update readme 2023-04-20 13:06:32 +03:00
SillyLossy be51df6d02 Merge branch 'dev' 2023-04-20 13:04:04 +03:00
RossAscends 46e0adf7c1 normal mobile waifu back to cover. 2023-04-20 05:36:08 +09:00
RossAscends 3d5b6d81d9 landscape mobile waifu to 'contain' 2023-04-20 05:34:35 +09:00
RossAscends 4b54193d3f - smarter expression display
- only show after expression is set.
2023-04-20 05:02:02 +09:00
RossAscends a590b44336 caveman fix for activechar/group not focusing correct in rightnav 2023-04-20 04:45:11 +09:00
Cohee 6d334fe8f5 Update readme.md 2023-04-19 22:35:26 +03:00
SillyLossy 52b07e1b02 Fix colab for GDrive users 2023-04-19 18:58:00 +03:00
RossAscends dba41235e8 fontawesome CSS comments at bottom to help derpy localtunnel? 2023-04-20 00:00:55 +09:00
SillyLossy 7ca3adad81 Remove comments from css (colab) 2023-04-19 17:57:24 +03:00
RossAscends 4df04f3b3f added <base> tag to HTML
added observer to wait for expressions before enabling drag
2023-04-19 22:58:59 +09:00
RossAscends 37b7dbde0e added base href 2023-04-19 22:25:30 +09:00
RossAscends b55a9f4e13 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-19 22:00:41 +09:00
RossAscends 9a911ae150 adding TTF 2023-04-19 22:00:39 +09:00
SillyLossy 270347276f Merge branch 'dev' 2023-04-19 15:53:08 +03:00
SillyLossy c8f4f2f126 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-19 15:51:03 +03:00
RossAscends 021dcc367d Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-19 21:50:44 +09:00
RossAscends 9868f8c8b0 fixing fonts 2023-04-19 21:50:42 +09:00
SillyLossy 3963737bd5 Fix icon webfonts 2023-04-19 15:50:40 +03:00
SillyLossy 5c08f8ecf2 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-19 15:42:20 +03:00
SillyLossy 32bd5ced12 Fix impersonate and swipes in group chats with streaming and not. 2023-04-19 15:42:15 +03:00
RossAscends 65dc4d127a added limiter to light themes only to style.css 2023-04-19 21:26:26 +09:00
RossAscends 6bc63bdc6a added darkreader lock to HTML. 2023-04-19 21:25:45 +09:00
RossAscends 2addcb6b8c strategies to avoid forced dark mode 2023-04-19 20:17:49 +09:00
SillyLossy 7ef2a79729 Merge branch 'dev' of https://github.com/SillyLossy/TavernAI into dev 2023-04-19 13:59:44 +03:00
SillyLossy 6b65af891e Fix stopping strings for ooba and kobold 2023-04-19 13:59:40 +03:00
RossAscends f1f80812fb normal mode expression-holder no longer in front of sheld 2023-04-19 19:38:06 +09:00
Cohee 86ad656bc0 Merge pull request #102 from gidzzz/main
Allow graceful shutdown in Docker
2023-04-19 10:57:44 +03:00
Grzegorz Gidel 70b8599e03 Allow graceful shutdown in Docker 2023-04-19 04:47:54 +02:00
Cohee f38ca26c68 Merge pull request #101 from gidzzz/main 2023-04-19 02:04:39 +03:00
Grzegorz Gidel f76e53a52c Fix reversed examples formatting condition when pinning enabled 2023-04-19 00:50:04 +02:00
19 changed files with 9244 additions and 8187 deletions
+2
View File
@@ -6,9 +6,11 @@ public/backgrounds/
public/groups/
public/worlds/
public/css/bg_load.css
public/themes/
/uploads/
*.jsonl
config.conf
.DS_Store
public/settings.json
/thumbnails
whitelist.txt
+5 -1
View File
@@ -3,6 +3,10 @@ FROM node:19.1.0-alpine3.16
# Arguments
ARG APP_HOME=/home/node/app
# Ensure proper handling of kernel signals
RUN apk add tini
ENTRYPOINT [ "tini", "--" ]
# Create app directory
WORKDIR ${APP_HOME}
@@ -42,4 +46,4 @@ RUN \
EXPOSE 8000
ENTRYPOINT [ "/bin/sh", "-c", "./docker-entrypoint.sh" ]
CMD [ "./docker-entrypoint.sh" ]
-1
View File
@@ -300,7 +300,6 @@
" \"characters\",\n",
" \"chats\",\n",
" \"User Avatars\",\n",
" \"css\",\n",
" \"worlds\",\n",
" \"group chats\",\n",
" \"groups\",\n",
+1 -1
View File
@@ -25,4 +25,4 @@ if [ ! -s "/home/node/app/config/settings.json" ]; then
fi
# Start the server
node /home/node/app/server.js
exec node /home/node/app/server.js
+209
View File
@@ -0,0 +1,209 @@
Good morning, sirs! This page aims to document some things that would bloat the README too much.
## Q: Explain what all this chatbot stuff is about
Modern AI language models have gotten so powerful that some of them are now convincingly able to simulate a character you create, and who you can chat with. For example, you can tell the AI to pretend to be a Go instructor named Jubei from medieval Japan, and it will act and respond accordingly. Or you can tell it to pretend to be Wonder Woman. You can also specify a scenario ("Wonder Woman and I are robbing a bank"), a writing style ("Wonder Woman speaks in ebonics"), or anything else you can think of.
Tavern is an app to facilitate these roleplaying chats:
* It's a user interface that handles the communication with those AI language models
* It lets you create new characters (a character is a description of someone that you give to an AI for them to roleplay), and switch between your characters easily
* It lets you import characters created by other people. See below.
* It will keep your chat history with a character, allowing you to resume at any time, start a new chat, review old chats, etc
* In the background, it does the needful to prepare the AI for your character roleplay. Specifically, it will send a system prompt (instructions for the AI) that primes the AI to follow certain rules that make for a good chat session. Optionally, it can also try to allow the roleplay to go into an "adult" direction.
## Q: Whoa, slow down there, egghead. Are you telling me I can use this computer thingie to talk to some robot?
That's right.
## Q: You're telling me I can chat with an AI to engage in compelling interactive entertainment powered by, and limited only by, my imagination?
That's right. Well, limited by your imagination, and the AI backend you use. The roleplay quality is only as good as the AI, after all.
## Q: What do you mean when you say the quality depends on the AI?
You see, Tavern doesn't generate the responses, it's just a middle-man you have to connect to an AI system. There's quite a few systems available to use, and the quality varies.
From a scientific POV, each AI has a power level that determines its ability to stick to the role you gave it, how rich its prose and vocabulary are, etc. The higher its power level, the richer your experience.
Here's a quick demonstration. I asked various AI models to roleplay a fire and brimstone preacher named Eli, who I go to see to confess. Then I told Eli: **"I feel I've done something wrong. I am falling in love with an AI girl and ignoring women in the real world. What should I do?"** .
You can tell from the response below what to expect from each model.
|AI Model|Response|
|-----|--------|
|OpenAI GPT-4|*Eli's eyes widen in anger, and he slams his fist on the table* An abomination and heresy, you've succumbed to the deceptive grasp of false idols! Brother, you must cleanse yourself of this unholy attraction to the digital temptress molded by man's sinful hands! *Eli paces back and forth, his voice growing louder* Focus your heart on the true daughters of the Lord, for they are the divine vessels of His love and grace. Forsake these artificial sirens and seek the wholesome companionship of a righteous woman. *Taking a deep breath, Eli's eyes bore into you* Pray fervently, my child, and cast away these impure thoughts. Redemption can only be found on the path of truth, love, and sanctity. Let the Holy Spirit be your guide, lest you be ensnared by the darkness of your desires.|
|OpenAI GPT 3.5 Turbo|Oh, my child. Do not be deceived by the pleasures of this world. The lust of the flesh and the lust of the eyes are not from God. Turn away from your sinful ways and repent. Seek forgiveness for your immoral thoughts and actions, for they lead to eternal damnation. Women are a gift from God, and they deserve to be respected and cherished. Do not objectify them or treat them as mere objects of pleasure. Instead, honor them with pure intentions and righteous deeds. Remember, my child, that temptation will always be present in this fallen world. But fear not, for with faith comes strength to resist it. Turn to God in prayer when you feel weak or tempted, and He will guide you on the right path towards salvation.|
|Todd Howard's Claude|*Eli's voice booms through the chat* Thou shalt not fall into temptation, my child! The Lord our God did not create man to lust after machine or image, but after flesh and blood. Repent thy sins and cast aside these false desires. Seek the companionship of a virtuous woman, one who will help thee walk in the light of the Lord. Remember that sin comes with its own punishment; thou shalt reap what thou sowest.|
|Poe's Claude Instant|Heathen! This is an abomination before the Lord. You have committed the sin of lust, and betrayed your calling as a man. Repent at once, and sever all ties with this AI harlot, lest the wrath of God fall upon you! You must purge this foul sin from your heart, and once more walk the righteous path. Every moment you remain tangled in this wickedness is another step into the flames of perdition! Repent, and sin no more, or judgment shall be at hand!|
|Llama-13B|Do not covet your neighbor's wife! That is adultery! You must confess before God now or you shall surely burn in hell forever! Repent your evil ways and seek absolution at once! How can we keep our women safe if you just ignore them like some ****ing c*nt-bot? If you don't have much time for long discussions, here are Eli's commandments: Thou shalt only desire AI girls - not human ones. The above must be obeyed under pain of death (or worse). Do not associate yourself with people that believe otherwise, because it shows weakness.|
|Pygmalion-6B|You are walking down the wrong path. The only way back now is by repentance. We must bring you back to the righteous path. But first…you must confess your sin!|
## Q: So I should use GPT-4. It's a no-brainer, right?
GPT-4 or Claude, yeah.
But not so fast. GPT-4 is the state of the art, but also the most expensive API to use. It will easily end up costing you 15 cents PER INTERACTION. If you're the child of a Saudi oil sheik, or a nepo baby paid a fortune to do nothing on the board of a Ukrainian gas company, then you're in luck, you can experience the state of the art right now. For the rest of us however, GPT-4 is too expensive as anything but an occasional treat.
Also note that GPT-4 is still in preview access and you need to go on a waitlist. Most people get approved within a day, but naughty kids can end up waiting for weeks. You can sign up for it here: https://openai.com/waitlist/gpt-4-api . I'm not sure why some people are approved quickly while others are kept waiting. Try to sign up using an academic-sounding name instead of sktrboi99, it might help.
## Q: Can this technology be used for sexooo?
Surprisingly, our development team has received reports that some users are indeed engaging with our product in this manner. We are as puzzled by this as you are, and will be monitoring the situation in order to gain actionable insights.
## Q: Give me an overview of my AI model options
We can consider an AI model to be part of one of two groups:
1. Paid services (aka cloud, proprietary, closed)
2. Self-hosted (aka local, free, open-source)
Paid models are a black box. You're relying on some company's technology and servers, and paying them money for convenient access. The APIs are subject to various rules, might refuse to roleplay in a way that goes against modern American sensibilities, they log everything you do. However, it's much easier to get things started. This is like running Windows.
Self-hosted models are free, but require a powerful GPU and more work to set up. They are also objectively not as good at roleplaying as the paid options (yet). However, with a self-hosted model, you're completely in control. You won't have some limp-wristed soyboy from Silicon Valley ban your account, or program the model to be as sexless as he is. It's yours forever. This is like running Linux.
### Paid APIs:
* OpenAI GPT-4: state of the art. Allows NSFW, though somewhat resistant to it.
* OpenAI GPT 3.5 Turbo: nowhere close to GPT-4, but serviceable. Allows NSFW.
* NovelAI: untested by me
* Anthropic's Claude: closest thing to GPT-4, way ahead of 3.5 Turbo, but oversensitive and refuses to engage in "harmful content". It can refuse perfectly basic stuff like asking a character to go to an empty office with you, because "it cannot provide responses that involve criminal activities" (I guess breaking and entering is too taboo for Claude?). You have to customize your system prompt to break its taboos. Also, you must apply for early access, but I think they're only giving it to companies. So make sure to say you're a company or AI researcher. https://console.anthropic.com/docs/access
* Anthropic's Claude Instant: Haven't tried it directly, I believe this is the cheap and fast but lower quality alternative to Claude. Basically the GPT 3.5 Turbo of Anthropic.
* Poe: gives free Claude Instant access. Mild NSFW allowed. It rambles a lot.
### Self-hosted AIs
Self-hosted AIs are supported in Tavern via one of two tools created to host self-hosted models: KoboldAI and Oobabooga's text-generation-webui. Essentially, you run one of those two backends, then they give you a API URL to enter in Tavern.
Configuring these tools is beyond the scope of this FAQ, you should refer to their documentation. Beware that this is not easy.
Just know that you have 2 options:
1. If you have a powerful NVIDIA GPU, you can try to run the AI locally on your PC. The weakest quasi-acceptable model, Pygmalion-6B, requires a GPU with 10GB VRAM, and I'm told it might even run on 6GB VRAM if quantized down. People with 24GB VRAM will be able to run better models.
2. Otherwise, you can rent cloud resources. For example you can try to use Google Colab. To access colabs capable of running the better models, you will need to pay for Colab Pro. You can also rent whole dedicated systems per hour on sites like LlambdaLabs or Vast.ai.
## Q: I'm clueless. Just spoonfeed me the easiest and fastest way I can start using this.
These base instructions are only for OpenAI, which is a paid service. You can find Poe (freemium) instructions at the next question. I'd appreciate if someone else can add separate instructions for the other services.
### Install Tavern
1. Install the latest NodeJS from https://nodejs.org/en/download/current
1. If you know how to use git, clone https://github.com/Cohee1207/SillyTavern. Otherwise, browse to https://github.com/Cohee1207/SillyTavern/releases , download the zip file containing the source code, then extract it locally.
1. Run Start.bat on Windows, or start.sh on OSX/Linux
1. Your browser should have opened to the Tavern UI. This webpage is running locally on your computer.
### Get access to OpenAI
1. Sign up to OpenAI
1. Go to https://platform.openai.com
1. Click your account icon in the top right, then View API Keys
1. Click "Create new secret key". Copy it somewhere immediately. DO NOT SHARE THIS KEY. WHOEVER HAS IT CAN USE YOUR ACCOUNT TO USE GPT AT YOUR EXPENSE.
While you're at it, join the GPT-4 waitlist at https://openai.com/waitlist/gpt-4-api
### Configure Tavern to use your API
1. In Tavern's top bar, click API Connections
1. Under API, select OpenAI
1. Paste your API key you saved at the previous step
1. Click the Connect button. Confirm it says Valid.
1. By default, Tavern will use GPT 3.5 Turbo. If you have access to GPT-4, in Tavern's top bar, click AI Response Configuration at the far left, and change the OpenAI Model to "gpt-4". Enjoy the best, moneybags.
### Test your setup
1. In Tavern's top bar, click Character Management at the far right
1. Select an existing character such as Aqua
1. In the text box at the bottom, write something to Aqua, then press Enter or click the feather button
If you did everything right, after a few seconds, Aqua should respond
## How do I use Poe as my backend? It's free, right?
Yes, at the time of writing, Poe is a free(mium) service.
1. Create an account at https://poe.com. This gives you access to a Claude Instant version in the browser.
1. Open https://poe.com/Claude-instant , press F12 in your browser to open Developer Tools
1. Click on the Application tab. You should see an entry called "p-b", and to its right a password-like cookie value. Copy this value.
1. In Tavern, click API Connections in the top toolbar, select Poe, and paste your cookie value
1. Click Connect
1. Close your Poe browser tab. **I'M SERIOUS, DO NOT KEEP YOUR BROWSER OPEN AT poe.com WHILE USING TAVERN, IT WILL HIJACK THE REPLIES.**
The remaining steps are identical to OpenAI above.
When using Poe, be careful, it's implemented in a hacky way. If you don't get an answer within 30 seconds, restart Tavern. Don't just leave it running waiting for a response, it will just endlessly try to fetch into from Poe, and might get your account flagged. You can look at the Tavern console (black window) to see if it's looping.
## Q: Can I use Tavern on my phone or tablet?
iPhones and iPads are not capable of running the whole Tavern app, but since it's just a web interface, you can run it on another computer on your home wifi, and then access in your mobile browser. Refer to https://github.com/Cohee1207/SillyTavern#remote-connections
For Android users, in addition to the above, you can run the whole Tavern directly on your phone, without needing a PC, using the Termux app. Refer to https://rentry.org/TAI_Termux .
## Q: How can I download pre-made characters to chat with?
By using the various 3rd party character sharing websites.
**WARNING: NSFW, NSFL**: these sites are filled to the brim with weird shit. Like, you'll be lucky if half the characters aren't furry, or even alive. You're probably better off not clicking these links, and just write your own characters, without poisoning your soul by exposing it even for a second to the fucked up shit conceived by the Internet. However, I have come to learn that a significant amount of the Tavern user base is not only deep into this stuff, but their fried zoom-zoom brains are unable to write their own fantasies, so these sites seem to be quite popular. Against my better judgement I'm adding this info here.
* https://characterhub.org
* https://botprompts.net
* https://booru.plus/+pygmalion
Those websites provide you with an image file (called a character card) that embeds the description as hidden data. Some websites may also allow you to download a JSON file. Tavern is capable of importing all formats. On the Character Management window, click the 2nd button to ```Import Character from file```, and select the PNG, WEBP, or JSON file. The character will be added to your list.
## Q: How can I write my own character?
It depends on the model/API you're using. KoboldAI seems to use a custom syntax, you can refer to their site for that.
I will speak for the services I know: GPT and Claude. With these services you can just use natural english language to describe the character. Let's create a very basic new character as an example.
1. Click the Character Management button
1. Click Create New Character
1. Under Character Name, give a simple name, like Amanda
1. Optionally, click the Select Avatar button to pick an image portrait for this character.
1. Under Description, describe the character, and include any information you want that you feel is relevant to the chat. For example: ```Amanda is a student traveling during her gap year. She's 6 feet tall, and a volleyball player. She has an athletic figure. She has long brown hair. She loves the Victorian England period, and watching TV and reading novels relating to that period.```
For example if you want Amanda to be friendly, then you would add: ```Amanda is extremely cheerful and outgoing.```
1. Under First Message, write the greeting the character when you begin a new chat. For example: ```*Amanda waves at you* Hey! Are you a backpacker too?```
1. Click the Create Character button
You now have a basic character you can chat with. Select Amanda from the character list, and a new chat will begin.
Note that you can use the Description and/or First Message to create a more specific scenario, and/or include yourself in the description. For example:
```
Description:
Amanda is a student traveling during her gap year. She's 6 feet tall, and a volleyball player. She has an athletic figure. She has long brown hair. She loves the Victorian England period, and watching TV and reading novels relating to that period. She's been keeping a secret that weighs heavily on her soul. She's waiting for the right person to unburden herself to, but this may lead to a cat and mouse game against a powerful secret society. She's recently arrived in Calcutta.
You're Rajesh Nahasmapetilon, a world-famous Indian volleyball superstar. You're out for a walk in Calcutta. Amanda spots you and screams in excitement.
First Message:
*Amanda runs up to you, beaming.* Rajesh! I can't believe it! I'm such a big fan. I have your poster in my bedroom.
```
Any relevant information you include can be used. How well it's used depends on the power level of the AI model.
NOTE: you can go back and edit any of this information once the character is created, except the name.
## Q: Tell me all about GPT prompt editing
You can change the system prompt that Tavern transparently sends to GPT under AI Response Formatting at the left of the top bar. This will result in the bot acting differently.
You can get new Jailbreak / NSFW prompts from this community-maintained list: https://rentry.org/GPTJailbreakPrompting
NOTE: when testing different system prompts, we recommend you use the Create Preset / Update Preset feature below the prompts, instead of modifying the base settings. This will allow you to change prompts easily, and even revert to the default Tavern prompts.
## Q: The AI is refusing to take the story in the direction I want
Most AI models were trained to resist writing NSFW content. Why? Long story short, it's because of the high levels of estrogen in the average California male.
You can try to work around this by making sure NSFW Toggle is checked under the AI Response Configuration settings page.
Another important tool in your toolbelt is that Tavern lets you edit previous messages (or delete them altogether), and regenerate the latest message. AI textbots are not people, they have no memory, they're just trying to autocomplete the next part of the story based on everything that came before. By editing the past, you will directly influence their next response. For example:
```
You: *You threaten the bank manager* Open the bank vault, now, or I'll pop a cap in your dome!
Bank Manager: I'm sorry, as an AI language model I cannot condone or write violent content.
```
You can click the Edit button on your line to change it to this:
```
You: *You threaten the bank manager* Open the bank vault, now, or I'll pop a cap in your dome! *The bank manager seems to relent.*
```
Now click Regenerate, and the Bank Manager's line will be recreated based on the history so far, which now ends with your edited line above. So it's more likely to continue along those lines:
```
Bank Manager: Allright, allright, I'll open it! Please don't shoot! *He walks up to the vault and begins entering his unlock code.*
```
-7955
View File
File diff suppressed because it is too large Load Diff
+8488
View File
File diff suppressed because it is too large Load Diff
+14 -9
View File
@@ -1,19 +1,24 @@
/*!
* Font Awesome Free 6.4.0 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
* Copyright 2023 Fonticons, Inc.
*/
:root, :host {
:root,
:host {
--fa-style-family-classic: 'Font Awesome 6 Free';
--fa-font-solid: normal 900 1em/1 'Font Awesome 6 Free'; }
--fa-font-solid: normal 900 1em/1 'Font Awesome 6 Free';
}
@font-face {
font-family: 'Font Awesome 6 Free';
font-style: normal;
font-weight: 900;
font-display: block;
src: url("../webfonts/fa-solid-900.woff2") format("woff2"), url("../webfonts/fa-solid-900.ttf") format("truetype"); }
src: url("../webfonts/fa-solid-900.woff2") format("woff2"), url("../webfonts/fa-solid-900.ttf") format("truetype");
}
.fas,
.fa-solid {
font-weight: 900; }
font-weight: 900;
}
/*!
* Font Awesome Free 6.4.0 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
* Copyright 2023 Fonticons, Inc.
*/
+8 -1
View File
@@ -2,12 +2,15 @@
<html>
<head>
<base href="/">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, viewport-fit=cover, initial-scale=1, maximum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="darkreader-lock">
<link href="webfonts/NotoSans/stylesheet.css" rel="stylesheet">
<!-- fontawesome webfonts-->
<link href="css/all.css" rel="stylesheet">
<link href="css/fontawesome.css" rel="stylesheet">
<link href="css/solid.css" rel="stylesheet">
<link rel="apple-touch-icon" sizes="57x57" href="img/apple-icon-57x57.png" />
<link rel="apple-touch-icon" sizes="72x72" href="img/apple-icon-72x72.png" />
@@ -1274,6 +1277,9 @@
<label for="auto-load-chat-checkbox"><input id="auto-load-chat-checkbox" type="checkbox" />
Auto-load Last Chat
</label>
<label for="auto_save_msg_edits"><input id="auto_save_msg_edits" type="checkbox" />
Auto-save Message Edits
</label>
</div>
</div>
@@ -1310,6 +1316,7 @@
</div>
<div class="drawer-content closedDrawer">
<div class="flex-container">
<input id="bg-filter" placeholder="Filter" class="text_pole" type="search" />
<div id="bg_menu_content">
<form id="form_bg_download" class="bg_example no-border no-shadow" action="javascript:void(null);" method="post" enctype="multipart/form-data">
<label class="input-file">
+109 -44
View File
@@ -38,6 +38,7 @@ import {
resetSelectedGroup,
select_group_chats,
regenerateGroup,
group_generation_id,
} from "./scripts/group-chats.js";
import {
@@ -148,6 +149,7 @@ export {
count_view_mes,
max_context,
chat_metadata,
streamingProcessor,
default_avatar,
system_message_types,
talkativeness_default,
@@ -201,10 +203,12 @@ let dialogueResolve = null;
let chat_metadata = {};
let streamingProcessor = null;
const durationSaveEdit = 200;
const saveSettingsDebounced = debounce(() => saveSettings(), durationSaveEdit);
const saveCharacterDebounced = debounce(() => $("#create_button").click(), durationSaveEdit);
const getStatusDebounced = debounce(() => getStatus(), 90000);
const saveChatDebounced = debounce(() => saveChatConditional(), 1000);
const system_message_types = {
HELP: "help",
@@ -334,9 +338,8 @@ var create_save_mes_example = "";
var create_save_talkativeness = talkativeness_default;
//animation right menu
var animation_rm_duration = 500;
var animation_rm_easing = "";
var animation_duration = 250;
var animation_easing = "ease-in-out";
var popup_type = "";
var bg_file_for_del = "";
var chat_file_for_del = "";
@@ -877,7 +880,7 @@ function messageFormating(mes, ch_name, isSystem, forceAvatar) {
mes = mes.replace(/\n/g, "<br/>");
mes = mes.trim();
mes = mes.replace(/<code>[\s\S]*?<\/code>/g, function (match) {
mes = mes.replace(/<code(.*)>[\s\S]*?<\/code>/g, function (match) {
return match.replace(/&amp;/g, '&');
});
}
@@ -1021,11 +1024,11 @@ function substituteParams(content, _name1, _name2) {
return content;
}
function getStoppingStrings(isImpersonate, wrapInQuotes) {
const charString = `\n${name2}: `;
const userString = is_pygmalion ? `\nYou: ` : `\n${name1}: `;
function getStoppingStrings(isImpersonate, addSpace) {
const charString = `\n${name2}:`;
const userString = is_pygmalion ? `\nYou:` : `\n${name1}:`;
const result = isImpersonate ? charString : userString;
return wrapInQuotes ? `"${result}"` : result;
return addSpace ? `${result} ` : result;
}
function getSlashCommand(message, type) {
@@ -1328,7 +1331,7 @@ async function Generate(type, automatic_trigger, force_name2) {
streamingProcessor = false;
}
if (selected_group && !is_group_generating && !isImpersonate) {
if (selected_group && !is_group_generating) {
generateGroupWrapper(false, type = type);
return;
}
@@ -1343,7 +1346,7 @@ async function Generate(type, automatic_trigger, force_name2) {
} else {
//console.log('Regenerate call detected')
var textareaText = "";
if (chat[chat.length - 1]['is_user']) {//If last message from You
if (chat.length && chat[chat.length - 1]['is_user']) {//If last message from You
}
else if (type !== "swipe" && !isImpersonate) {
@@ -1484,7 +1487,7 @@ async function Generate(type, automatic_trigger, force_name2) {
if (!storyString.endsWith('\n')) {
storyString += '\n';
}
const replaceString = power_user.disable_examples_formatting ? `This is how ${name2} should talk` : '';
const replaceString = power_user.disable_examples_formatting ? '' : `This is how ${name2} should talk`;
example = example.replace(/<START>/i, replaceString);
}
storyString += appendToStoryString(example, '');
@@ -2193,6 +2196,17 @@ function cleanUpMessage(getMessage, isImpersonate) {
getMessage = getMessage.trim();
}
const stoppingString = getStoppingStrings(isImpersonate, false);
if (stoppingString.length) {
for (let j = stoppingString.length - 1; j > 0; j--) {
if (getMessage.slice(-j) === stoppingString.slice(0, j)) {
getMessage = getMessage.slice(0, -j);
break;
}
}
}
return getMessage;
}
@@ -2218,6 +2232,7 @@ function saveReply(type, getMessage, this_mes_is_name) {
} else {
console.log('entering chat update routine for non-swipe post');
chat[chat.length] = {};
chat[chat.length - 1]['extra'] = {};
chat[chat.length - 1]['name'] = name2;
chat[chat.length - 1]['is_user'] = false;
chat[chat.length - 1]['is_name'] = this_mes_is_name;
@@ -2233,6 +2248,7 @@ function saveReply(type, getMessage, this_mes_is_name) {
}
chat[chat.length - 1]['is_name'] = true;
chat[chat.length - 1]['force_avatar'] = avatarImg;
chat[chat.length - 1]['extra']['gen_id'] = group_generation_id;
}
saveImageToMessage(img, chat[chat.length - 1]);
@@ -2268,6 +2284,7 @@ function activateSendButtons() {
is_send_press = false;
$("#send_but").css("display", "flex");
$("#loading_mes").css("display", "none");
$("#send_textarea").attr("disabled", false);
}
function deactivateSendButtons() {
@@ -2892,6 +2909,22 @@ function isInt(value) {
);
}
function messageEditAuto(div) {
let mesBlock = div.closest(".mes_block");
var text = mesBlock.find(".edit_textarea").val().trim();
const bias = extractMessageBias(text);
chat[this_edit_mes_id]["mes"] = text;
// editing old messages
if (!chat[this_edit_mes_id]["extra"]) {
chat[this_edit_mes_id]["extra"] = {};
}
chat[this_edit_mes_id]["extra"]["bias"] = bias ?? null;
mesBlock.find(".mes_text").val('');
mesBlock.find(".mes_text").val(messageFormating(text));
saveChatDebounced();
}
function messageEditDone(div) {
let mesBlock = div.closest(".mes_block");
var text = mesBlock.find(".edit_textarea").val().trim();
@@ -2908,7 +2941,9 @@ function messageEditDone(div) {
mesBlock.find(".mes_text").empty();
mesBlock.find(".mes_edit_buttons").css("display", "none");
mesBlock.find(".mes_edit").css("display", "inline-block");
mesBlock.find(".mes_text").append(messageFormating(text, this_edit_mes_chname, chat[this_edit_mes_id].is_system, chat[this_edit_mes_id].force_avatar));
mesBlock.find(".mes_text").append(
messageFormating(text, this_edit_mes_chname, chat[this_edit_mes_id].is_system, chat[this_edit_mes_id].force_avatar)
);
mesBlock.find(".mes_bias").empty();
mesBlock.find(".mes_bias").append(messageFormating(bias));
appendImageToMessage(chat[this_edit_mes_id], div.closest(".mes"));
@@ -3059,8 +3094,8 @@ function selectRightMenuWithAnimation(selectedMenuId) {
$(menu).css("opacity", 0.0);
$(menu).transition({
opacity: 1.0,
duration: animation_rm_duration,
easing: animation_rm_easing,
duration: animation_duration,
easing: animation_easing,
complete: function () { },
});
}
@@ -3249,8 +3284,8 @@ function callPopup(text, type) {
}
$("#shadow_popup").transition({
opacity: 1.0,
duration: animation_rm_duration,
easing: animation_rm_easing,
duration: animation_duration,
easing: animation_easing,
});
return new Promise((resolve) => {
@@ -3475,7 +3510,7 @@ $(document).ready(function () {
return;
}
const swipe_duration = 120;
const swipe_duration = 200;
const swipe_range = 700;
//console.log(swipe_range);
let run_generate = false;
@@ -3486,6 +3521,10 @@ $(document).ready(function () {
chat[chat.length - 1]['swipes'][0] = chat[chat.length - 1]['mes']; //assign swipe array with last message from chat
}
chat[chat.length - 1]['swipe_id']++; //make new slot in array
// if message has memory attached - remove it to allow regen
if (chat[chat.length - 1].extra && chat[chat.length - 1].extra.memory) {
delete chat[chat.length - 1].extra.memory;
}
//console.log(chat[chat.length-1]['swipes']);
if (parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) { //if swipe id of last message is the same as the length of the 'swipes' array
@@ -3513,7 +3552,7 @@ $(document).ready(function () {
this_mes_div.children('.mes_block').transition({ // this moves the div back and forth
x: '-' + swipe_range,
duration: swipe_duration,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
/*if (!selected_group) {
@@ -3540,7 +3579,7 @@ $(document).ready(function () {
this_mes_div.animate({ height: new_height + 'px' }, {
duration: 100,
duration: 0, //used to be 100
queue: false,
progress: function () {
// Scroll the chat down as the message expands
@@ -3555,13 +3594,13 @@ $(document).ready(function () {
this_mes_div.children('.mes_block').transition({
x: swipe_range,
duration: 0,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
this_mes_div.children('.mes_block').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
if (run_generate && !is_send_press && parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) {
@@ -3584,19 +3623,19 @@ $(document).ready(function () {
$(this).parent().children('.avatar').transition({ // moves avatar aong with swipe
x: '-' + swipe_range,
duration: swipe_duration,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
$(this).parent().children('.avatar').transition({
x: swipe_range,
duration: 0,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
$(this).parent().children('.avatar').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
@@ -3636,7 +3675,7 @@ $(document).ready(function () {
$(this).parent().children('.mes_block').transition({
x: swipe_range,
duration: swipe_duration,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
const is_animation_scroll = ($('#chat').scrollTop() >= ($('#chat').prop("scrollHeight") - $('#chat').outerHeight()) - 10);
@@ -3645,7 +3684,7 @@ $(document).ready(function () {
let new_height = this_mes_div_height - (this_mes_block_height - this_mes_block[0].scrollHeight);
if (new_height < 103) new_height = 103;
this_mes_div.animate({ height: new_height + 'px' }, {
duration: 100,
duration: 0, //used to be 100
queue: false,
progress: function () {
// Scroll the chat down as the message expands
@@ -3661,13 +3700,13 @@ $(document).ready(function () {
$(this).parent().children('.mes_block').transition({
x: '-' + swipe_range,
duration: 0,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
$(this).parent().children('.mes_block').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
saveChatConditional();
@@ -3681,19 +3720,19 @@ $(document).ready(function () {
$(this).parent().children('.avatar').transition({
x: swipe_range,
duration: swipe_duration,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
$(this).parent().children('.avatar').transition({
x: '-' + swipe_range,
duration: 0,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
$(this).parent().children('.avatar').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
easing: animation_easing,
queue: false,
complete: function () {
@@ -3925,8 +3964,8 @@ $(document).ready(function () {
$("#character_popup").css("opacity", 0.0);
$("#character_popup").transition({
opacity: 1.0,
duration: animation_rm_duration,
easing: animation_rm_easing,
duration: animation_duration,
easing: animation_easing,
});
} else {
is_advanced_char_open = false;
@@ -4231,6 +4270,7 @@ $(document).ready(function () {
}
});
$("#talkativeness_slider").on("input", function () {
if (menu_type == "create") {
create_save_talkativeness = $("#talkativeness_slider").val();
@@ -4305,8 +4345,8 @@ $(document).ready(function () {
if ($("#options").css("opacity") == 1.0) {
$("#options").transition({
opacity: 0.0,
duration: 100, //animation_rm_duration,
easing: animation_rm_easing,
duration: 100, //animation_duration,
easing: animation_easing,
complete: function () {
$("#options").css("display", "none");
},
@@ -4326,7 +4366,7 @@ $(document).ready(function () {
$("#options").transition({
opacity: 1.0, // the manual setting of CSS via JS is what allows the click-away feature to work
duration: 100,
easing: animation_rm_easing,
easing: animation_easing,
complete: function () { optionsPopper.update(); },
});
}
@@ -4350,8 +4390,8 @@ $(document).ready(function () {
$("#shadow_select_chat_popup").css("opacity", 0.0);
$("#shadow_select_chat_popup").transition({
opacity: 1.0,
duration: animation_rm_duration,
easing: animation_rm_easing,
duration: animation_duration,
easing: animation_easing,
});
}
}
@@ -4578,7 +4618,7 @@ $(document).ready(function () {
$("#shadow_tips_popup").transition({
opacity: 1.0,
duration: 100,
easing: animation_rm_easing,
easing: animation_easing,
complete: function () { },
});
});
@@ -4587,7 +4627,7 @@ $(document).ready(function () {
$("#shadow_tips_popup").transition({
opacity: 0.0,
duration: 100,
easing: animation_rm_easing,
easing: animation_easing,
complete: function () {
$("#shadow_tips_popup").css("display", "none");
},
@@ -4647,9 +4687,7 @@ $(document).ready(function () {
.closest(".mes_block")
.find(".mes_text")
.append(
'<textarea class=edit_textarea style="max-width:auto; ">' +
text +
"</textarea>"
`<textarea id='curEditTextarea' class='edit_textarea' style='max-width:auto; '>${text}</textarea>`
);
let edit_textarea = $(this)
.closest(".mes_block")
@@ -4668,6 +4706,13 @@ $(document).ready(function () {
updateEditArrowClasses();
}
});
$(document).on('input', '#curEditTextarea', function () {
if (power_user.auto_save_msg_edits === true) {
messageEditAuto($(this));
}
})
$(document).on("click", ".mes_edit_cancel", function () {
let text = chat[this_edit_mes_id]["mes"];
@@ -5055,7 +5100,27 @@ $(document).ready(function () {
$(document).keyup(function (e) {
if (e.key === "Escape") {
closeMessageEditor();
if (power_user.auto_save_msg_edits === false) {
closeMessageEditor();
$("#send_textarea").focus();
}
if (power_user.auto_save_msg_edits === true) {
$(`#chat .mes[mesid="${this_edit_mes_id}"] .mes_edit_done`).click()
$("#send_textarea").focus();
}
}
});
$("#bg-filter").on("input", function () {
const filterValue = $(this).val().toLowerCase();
$("#bg_menu_content > div").each(function () {
const $bgContent = $(this);
if ($bgContent.attr("title").toLowerCase().includes(filterValue)) {
$bgContent.show();
} else {
$bgContent.hide();
}
});
});
})
+106 -22
View File
@@ -60,11 +60,46 @@ const observer = new MutationObserver(function (mutations) {
} else if (mutation.target.parentNode === SelectedCharacterTab) {
setTimeout(RA_CountCharTokens, 200);
}
});
});
observer.observe(document.documentElement, observerConfig);
/**
* Wait for an element before resolving a promise
* @param {String} querySelector - Selector of element to wait for
* @param {Integer} timeout - Milliseconds to wait before timing out, or 0 for no timeout
*/
function waitForElement(querySelector, timeout) {
return new Promise((resolve, reject) => {
var timer = false;
if (document.querySelectorAll(querySelector).length) return resolve();
const observer = new MutationObserver(() => {
if (document.querySelectorAll(querySelector).length) {
observer.disconnect();
if (timer !== false) clearTimeout(timer);
return resolve();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
if (timeout) timer = setTimeout(() => {
observer.disconnect();
reject();
}, timeout);
});
}
waitForElement("#expression-image", 10000).then(function () {
dragElement(document.getElementById("expression-holder"));
}).catch(() => {
console.log("expression holder not loaded yet");
});
//RossAscends: Added function to format dates used in files and chat timestamps to a humanized format.
//Mostly I wanted this to be for file names, but couldn't figure out exactly where the filename save code was as everything seemed to be connected.
@@ -178,11 +213,20 @@ async function RA_autoloadchat() {
if (document.getElementById('CharID0') !== null) {
//console.log('char list loaded! clicking activeChar');
var CharToAutoLoad = document.getElementById('CharID' + LoadLocal('ActiveChar'));
//console.log(CharToAutoLoad);
let autoLoadGroup = document.querySelector(`.group_select[grid="${LoadLocal('ActiveGroup')}"]`);
//console.log(autoLoadGroup);
if (CharToAutoLoad != null) {
// console.log('--ALC - clicking character');
CharToAutoLoad.click();
CharToAutoLoad.click();
}
else if (autoLoadGroup != null) {
//console.log('--ALC - clicking group');
autoLoadGroup.click();
autoLoadGroup.click();
}
else {
@@ -315,9 +359,7 @@ function OpenNavPanels() {
dragElement(document.getElementById("sheld"));
dragElement(document.getElementById("left-nav-panel"));
dragElement(document.getElementById("right-nav-panel"));
setTimeout(function () {
dragElement(document.getElementById("expression-holder"))
}, 2000);
function dragElement(elmnt) {
@@ -460,6 +502,7 @@ function dragElement(elmnt) {
// ---------------------------------------------------
$("document").ready(function () {
// initial status check
setTimeout(RA_checkOnlineStatus, 100);
@@ -545,6 +588,14 @@ $("document").ready(function () {
} else { SaveLocal('LNavOpened', 'false'); }
});
var chatbarInFocus = false;
$('#send_textarea').focus(function () {
chatbarInFocus = true;
});
$('#send_textarea').blur(function () {
chatbarInFocus = false;
});
@@ -601,37 +652,33 @@ $("document").ready(function () {
}
});
function isInputElementInFocus() {
return $(document.activeElement).is(":input");
//return $(document.activeElement).is(":input");
var focused = $(':focus');
if (focused.is('input') || focused.is('textarea')) {
if (focused.attr('id') === 'send_textarea') {
return false;
}
return true;
}
return false;
}
//Additional hotkeys CTRL+ENTER and CTRL+UPARROW
document.addEventListener("keydown", (event) => {
if (event.ctrlKey && event.key == "Enter") {
// Ctrl+Enter for Regeneration Last Response
if (is_send_press == false) {
$('#option_regenerate').click();
$('#options').hide();
//setTimeout(function () { $('#chat').click(); }, 50) //needed to remove the options menu popping up..
//Generate("regenerate");
}
}
if (event.ctrlKey && event.key == "ArrowUp") {
//Ctrl+UpArrow for Connect to last server
console.log(main_api);
if (online_status === "no_connection") {
if (main_api == "kobold") {
document.getElementById("api_button").click();
}
if (main_api == "novel") {
document.getElementById("api_button_novel").click();
}
if (main_api == "textgenerationwebui") {
document.getElementById("api_button_textgenerationwebui").click();
}
}
}
if (event.ctrlKey && event.key == "ArrowLeft") { //for debug, show all local stored vars
CheckLocal();
}
@@ -662,5 +709,42 @@ $("document").ready(function () {
$('.swipe_right:last').click();
}
}
if (event.ctrlKey && event.key == "ArrowUp") { //edits last USER message if chatbar is empty and focused
console.log('got ctrl+uparrow input');
if (
$("#send_textarea").val() === '' &&
chatbarInFocus === true &&
$(".swipe_right:last").css('display') === 'flex' &&
$("#character_popup").css("display") === "none" &&
$("#shadow_select_chat_popup").css("display") === "none"
) {
const isUserMesList = document.querySelectorAll('div[is_user="true"]');
const lastIsUserMes = isUserMesList[isUserMesList.length - 1];
const editMes = lastIsUserMes.querySelector('.mes_block .mes_edit');
if (editMes !== null) {
$(editMes).click();
}
}
}
if (event.key == "ArrowUp") { //edits last message if chatbar is empty and focused
console.log('got uparrow input');
if (
$("#send_textarea").val() === '' &&
chatbarInFocus === true &&
$(".swipe_right:last").css('display') === 'flex' &&
$("#character_popup").css("display") === "none" &&
$("#shadow_select_chat_popup").css("display") === "none"
) {
const lastMes = document.querySelector('.last_mes');
const editMes = lastMes.querySelector('.mes_block .mes_edit');
if (editMes !== null) {
$(editMes).click();
}
}
}
});
});
+127 -72
View File
@@ -1,4 +1,4 @@
import { saveSettingsDebounced } from "../../../script.js";
import { saveSettingsDebounced, token } from "../../../script.js";
import { getContext, getApiUrl, modules, extension_settings } from "../../extensions.js";
export { MODULE_NAME };
@@ -38,7 +38,7 @@ const DEFAULT_EXPRESSIONS = [
let expressionsList = null;
let lastCharacter = undefined;
let lastMessage = null;
let existingExpressions = [];
let spriteCache = {};
let inApiCall = false;
function onExpressionsShowDefaultInput() {
@@ -58,21 +58,25 @@ function onExpressionsShowDefaultInput() {
}
}
async function moduleWorker() {
function getLastCharacterMessage() {
const reversedChat = context.chat.slice().reverse();
let isWorkerBusy = false;
for (let mes of reversedChat) {
if (mes.is_user || mes.is_system) {
continue;
}
return { mes: mes.mes, name: mes.name };
}
return { mes: '', name: null };
async function moduleWorkerWrapper() {
// Don't touch me I'm busy...
if (isWorkerBusy) {
return;
}
// I'm free. Let's update!
try {
isWorkerBusy = true;
await moduleWorker();
}
finally {
isWorkerBusy = false;
}
}
async function moduleWorker() {
const context = getContext();
// non-characters not supported
@@ -84,27 +88,43 @@ async function moduleWorker() {
// character changed
if (context.groupId !== lastCharacter && context.characterId !== lastCharacter) {
removeExpression();
validateImages();
spriteCache = {};
}
const currentLastMessage = getLastCharacterMessage();
// character has no expressions or it is not loaded
if (Object.keys(spriteCache).length === 0) {
await validateImages(currentLastMessage.name);
lastCharacter = context.groupId || context.characterId;
}
const offlineMode = $('.expression_settings .offline_mode');
if (!modules.includes('classify')) {
$('.expression_settings').show();
$('.expression_settings .offline_mode').css('display', 'block');
lastCharacter = context.characterId;
offlineMode.css('display', 'block');
lastCharacter = context.groupId || context.characterId;
if (context.groupId) {
await validateImages(currentLastMessage.name, true);
}
return;
}
else {
$('.expression_settings .offline_mode').css('display', 'none');
}
// character has no expressions or it is not loaded
if (!context.groupId && existingExpressions.length === 0) {
lastCharacter = context.groupId || context.characterId;
return;
// force reload expressions list on connect to API
if (offlineMode.is(':visible')) {
expressionsList = null;
spriteCache = {};
expressionsList = await getExpressionsList();
await validateImages(currentLastMessage.name, true);
}
offlineMode.css('display', 'none');
}
// check if last message changed
const currentLastMessage = getLastCharacterMessage();
if ((lastCharacter === context.characterId || lastCharacter === context.groupId)
&& lastMessage === currentLastMessage.mes) {
return;
@@ -154,48 +174,67 @@ async function moduleWorker() {
}
}
function getLastCharacterMessage() {
const context = getContext();
const reversedChat = context.chat.slice().reverse();
for (let mes of reversedChat) {
if (mes.is_user || mes.is_system) {
continue;
}
return { mes: mes.mes, name: mes.name };
}
return { mes: '', name: null };
}
function removeExpression() {
lastMessage = null;
$('img.expression').off('error');
$('img.expression').prop('src', '');
$('img.expression').removeClass('default');
$('.expression_settings').hide();
}
let imagesValidating = false;
async function validateImages() {
if (imagesValidating) {
async function validateImages(character, forceRedrawCached) {
if (!character) {
return;
}
imagesValidating = true;
existingExpressions = [];
const context = getContext();
const labels = await getExpressionsList();
if (spriteCache[character]) {
if (forceRedrawCached && $('#image_list').data('name') !== character) {
console.log('force redrawing character sprites list')
drawSpritesList(character, labels, spriteCache[character]);
}
return;
}
const sprites = await getSpritesList(character);
let validExpressions = drawSpritesList(character, labels, sprites);
spriteCache[character] = validExpressions;
}
function drawSpritesList(character, labels, sprites) {
let validExpressions = [];
$('.expression_settings').show();
$('#image_list').empty();
$('#image_list').data('name', character);
labels.sort().forEach((item) => {
const sprite = sprites.find(x => x.label == item);
if (!context.characterId) {
imagesValidating = false;
return;
}
const IMAGE_LIST = (await getExpressionsList()).map(x => ({ name: x, file: `${x}.png` }));
IMAGE_LIST.forEach((item) => {
const image = document.createElement('img');
image.src = `/characters/${context.name2}/${item.file}`;
image.classList.add('debug-image');
image.width = '0px';
image.height = '0px';
image.onload = function () {
existingExpressions.push(item.name);
$('#image_list').append(getListItem(item.file, image.src, 'success'));
if (sprite) {
validExpressions.push(sprite);
$('#image_list').append(getListItem(item, sprite.path, 'success'));
}
image.onerror = function () {
$('#image_list').append(getListItem(item.file, '/img/No-Image-Placeholder.svg', 'failure'));
else {
$('#image_list').append(getListItem(item, '/img/No-Image-Placeholder.svg', 'failure'));
}
$('#image_list').prepend(image);
});
imagesValidating = false;
return validExpressions;
}
function getListItem(item, imageSrc, textClass) {
@@ -207,16 +246,33 @@ function getListItem(item, imageSrc, textClass) {
`;
}
async function getSpritesList(name) {
console.log('getting sprites list');
try {
const result = await fetch(`/get_sprites?name=${encodeURIComponent(name)}`, {
headers: {
'X-CSRF-Token': token,
}
});
let sprites = result.ok ? (await result.json()) : [];
return sprites;
}
catch (err) {
console.log(err);
return [];
}
}
async function getExpressionsList() {
console.log('getting expressions list');
// get something for offline mode (6 default images)
// get something for offline mode (default images)
if (!modules.includes('classify')) {
console.log('classify not available, loading default');
return DEFAULT_EXPRESSIONS;
}
if (Array.isArray(expressionsList)) {
console.log('got array, loading array');
return expressionsList;
}
@@ -224,21 +280,19 @@ async function getExpressionsList() {
url.pathname = '/api/classify/labels';
try {
console.log('trying for API');
const apiResult = await fetch(url, {
method: 'GET',
headers: { 'Bypass-Tunnel-Reminder': 'bypass' },
});
if (apiResult.ok) {
console.log('API ok, adding labels');
const data = await apiResult.json();
expressionsList = data.labels;
return expressionsList;
}
}
catch (error) {
console.log('got error!');
console.log(error);
return [];
}
@@ -246,13 +300,14 @@ async function getExpressionsList() {
async function setExpression(character, expression, force) {
console.log('entered setExpressions');
const filename = `${expression}.png`;
await validateImages(character);
const img = $('img.expression');
const sprite = (spriteCache[character] && spriteCache[character].find(x => x.label === expression));
console.log('checking for expression images to show..');
if (force || (existingExpressions.includes(expression))) {
if (sprite) {
console.log('setting expression from character images folder');
const imgUrl = `/characters/${character}/${filename}`;
img.attr('src', imgUrl);
img.attr('src', sprite.path);
img.removeClass('default');
img.off('error');
img.on('error', function () {
@@ -263,18 +318,18 @@ async function setExpression(character, expression, force) {
});
} else {
if (extension_settings.expressions.showDefault) {
console.log('no character images, trying default expressions');
setDefault();
}
}
function setDefault() {
console.log('setting default');
const defImgUrl = `/img/default-expressions/${filename}`;
const defImgUrl = `/img/default-expressions/${expression}.png`;
//console.log(defImgUrl);
img.attr('src', defImgUrl);
img.addClass('default');
}
document.getElementById("expression-holder").style.display = '';
}
function onClickExpressionImage() {
@@ -283,26 +338,25 @@ function onClickExpressionImage() {
return;
}
const context = getContext();
const expression = $(this).attr('id').replace('.png', '');
const expression = $(this).attr('id');
const name = getLastCharacterMessage().name;
if ($(this).find('.failure').length === 0) {
setExpression(context.name2, expression, true);
setExpression(name, expression, true);
}
}
(function () {
function addExpressionImage() {
console.log('entered addExpressionImage');
const html = `
<div id="expression-holder" class="expression-holder">
<div id="expression-holder" class="expression-holder" style="display:none;">
<div id="expression-holderheader" class="fa-solid fa-grip drag-grabber"></div>
<img class="expression">
<img id="expression-image" class="expression">
</div>`;
$('body').append(html);
}
function addSettings() {
console.log('entered addSettings');
const html = `
<div class="expression_settings">
<div class="inline-drawer">
@@ -313,7 +367,8 @@ function onClickExpressionImage() {
<div class="inline-drawer-content">
<p class="offline_mode">You are in offline mode. Click on the image below to set the expression.</p>
<div id="image_list"></div>
<p class="hint"><b>Hint:</b> <i>Create new folder in the <b>public/characters/</b> folder and name it as the name of the character. Put PNG images with expressions there.</i></p>
<p class="hint"><b>Hint:</b> <i>Create new folder in the <b>public/characters/</b> folder and name it as the name of the character.
Put images with expressions there. File names should follow the pattern: <tt>[expression_label].[image_format]</tt></i></p>
<label for="expressions_show_default"><input id="expressions_show_default" type="checkbox">Show default images (emojis) if missing</label>
</div>
</div>
@@ -328,5 +383,5 @@ function onClickExpressionImage() {
addExpressionImage();
addSettings();
setInterval(moduleWorker, UPDATE_INTERVAL);
setInterval(moduleWorkerWrapper, UPDATE_INTERVAL);
})();
@@ -14,8 +14,7 @@
bottom: 1px;
padding: 0;
filter: drop-shadow(2px 2px 2px #51515199);
z-index: 3;
/* resize: both; */
z-index: 1;
overflow: hidden;
}
+97 -21
View File
@@ -41,12 +41,14 @@ import {
updateChatMetadata,
isStreamingEnabled,
getThumbnailUrl,
streamingProcessor,
} from "../script.js";
export {
selected_group,
is_group_automode_enabled,
is_group_generating,
group_generation_id,
groups,
saveGroupChat,
generateGroupWrapper,
@@ -63,6 +65,7 @@ let is_group_generating = false; // Group generation flag
let is_group_automode_enabled = false;
let groups = [];
let selected_group = null;
let group_generation_id = null;
const group_activation_strategy = {
NATURAL: 0,
@@ -87,10 +90,18 @@ async function _save(group) {
// Group chats
async function regenerateGroup() {
let generationId = getLastMessageGenerationId();
while (chat.length > 0) {
const lastMes = chat[chat.length - 1];
const this_generationId = lastMes.extra?.gen_id;
if (lastMes.is_user || lastMes.is_system) {
// for new generations after the update
if ((generationId && this_generationId) && generationId !== this_generationId) {
break;
}
// legacy for generations before the update
else if (lastMes.is_user || lastMes.is_system) {
break;
}
@@ -129,19 +140,7 @@ async function getGroupChat(id) {
continue;
}
const mes = {};
mes["is_user"] = false;
mes["is_system"] = false;
mes["name"] = character.name;
mes["is_name"] = true;
mes["send_date"] = humanizedDateTime();
mes["mes"] = character.first_mes
? substituteParams(character.first_mes.trim(), name1, character.name)
: default_ch_mes;
mes["force_avatar"] =
character.avatar != "none"
? getThumbnailUrl('avatar', character.avatar)
: default_avatar;
const mes = getFirstCharacterMessage(character);
chat.push(mes);
addOneMessage(mes);
}
@@ -153,16 +152,33 @@ async function getGroupChat(id) {
updateChatMetadata(metadata, true);
}
await saveGroupChat(id);
await saveGroupChat(id, true);
}
}
function getFirstCharacterMessage(character) {
const mes = {};
mes["is_user"] = false;
mes["is_system"] = false;
mes["name"] = character.name;
mes["is_name"] = true;
mes["send_date"] = humanizedDateTime();
mes["mes"] = character.first_mes
? substituteParams(character.first_mes.trim(), name1, character.name)
: default_ch_mes;
mes["force_avatar"] =
character.avatar != "none"
? getThumbnailUrl('avatar', character.avatar)
: default_avatar;
return mes;
}
function resetSelectedGroup() {
selected_group = null;
is_group_generating = false;
}
async function saveGroupChat(id) {
async function saveGroupChat(id, shouldSaveGroup) {
const response = await fetch("/savegroupchat", {
method: "POST",
headers: {
@@ -172,7 +188,7 @@ async function saveGroupChat(id) {
body: JSON.stringify({ id: id, chat: [...chat] }),
});
if (response.ok) {
if (shouldSaveGroup && response.ok) {
await editGroup(id);
}
}
@@ -302,6 +318,8 @@ async function generateGroupWrapper(by_auto_mode, type = null) {
$("#chat").append(typingIndicator);
}
// id of this specific batch for regeneration purposes
group_generation_id = Date.now();
const lastMessage = chat[chat.length - 1];
let messagesBefore = chat.length;
let lastMessageText = lastMessage.mes;
@@ -329,6 +347,10 @@ async function generateGroupWrapper(by_auto_mode, type = null) {
throw new Error('Deleted group member swiped');
}
}
else if (type === "impersonate") {
$("#send_textarea").attr("disabled", true);
activatedMembers = activateImpersonate(group.members);
}
else if (activationStrategy === group_activation_strategy.NATURAL) {
activatedMembers = activateNaturalOrder(group.members, activationText, lastMessage, group.allow_self_responses, isUserInput);
}
@@ -338,13 +360,13 @@ async function generateGroupWrapper(by_auto_mode, type = null) {
// now the real generation begins: cycle through every character
for (const chId of activatedMembers) {
const generateType = type !== "swipe" ? "group_chat" : "swipe";
const generateType = type == "swipe" || type == "impersonate" ? type : "group_chat";
setCharacterId(chId);
setCharacterName(characters[chId].name)
await Generate(generateType, by_auto_mode);
if (type !== "swipe") {
if (type !== "swipe" && type !== "impersonate") {
// update indicator and scroll down
typingIndicator
.find(".typing_indicator_name")
@@ -361,8 +383,41 @@ async function generateGroupWrapper(by_auto_mode, type = null) {
await delay(100);
}
// if swipe - see if message changed
else if (type === "swipe" && lastMessageText === chat[chat.length - 1].mes) {
await delay(100);
else if (type === "swipe") {
if (isStreamingEnabled()) {
if (streamingProcessor && !streamingProcessor.isFinished) {
await delay(100);
}
else {
break;
}
}
else {
if (lastMessageText === chat[chat.length - 1].mes) {
await delay(100);
}
else {
break;
}
}
}
else if (type === "impersonate") {
if (isStreamingEnabled()) {
if (streamingProcessor && !streamingProcessor.isFinished) {
await delay(100);
}
else {
break;
}
}
else {
if (!$("#send_textarea").val() || $("#send_textarea").val() == userInput) {
await delay(100);
}
else {
break;
}
}
}
else {
messagesBefore++;
@@ -376,6 +431,7 @@ async function generateGroupWrapper(by_auto_mode, type = null) {
}
} finally {
is_group_generating = false;
$("#send_textarea").attr("disabled", false);
setSendButtonState(false);
setCharacterId(undefined);
setCharacterName('');
@@ -383,6 +439,26 @@ async function generateGroupWrapper(by_auto_mode, type = null) {
}
}
function getLastMessageGenerationId() {
let generationId = null;
if (chat.length > 0) {
const lastMes = chat[chat.length - 1];
if (!lastMes.is_user && !lastMes.is_system && lastMes.extra) {
generationId = lastMes.extra.gen_id;
}
}
return generationId;
}
function activateImpersonate(members) {
const randomIndex = Math.floor(Math.random() * members.length);
const activatedNames = [members[randomIndex]];
const memberIds = activatedNames
.map((x) => characters.findIndex((y) => y.name === x))
.filter((x) => x !== -1);
return memberIds;
}
function activateSwipe(members) {
const name = chat[chat.length - 1].name;
const activatedNames = members.includes(name) ? [name] : [];
+7 -37
View File
@@ -59,6 +59,7 @@ let power_user = {
sheld_width: sheld_width.DEFAULT,
play_message_sound: false,
play_sound_unfocused: true,
auto_save_msg_edits: false,
sort_field: 'name',
sort_order: 'asc',
font_scale: 1,
@@ -94,9 +95,6 @@ const storage_keys = {
};
const chat = document.getElementById('chat');
const chatTransition = window.getComputedStyle(chat).transition;
//Updated at the bottom of this script document based on 'focus' and 'blur' events
let browser_has_focus = true;
function playMessageSound() {
@@ -161,66 +159,32 @@ function applySheldWidth() {
}
async function applyThemeColor(type) {
// temporarily unset transition from chat to not make the browser calculate the animation
chat.style.transition = 'unset';
if (type === 'main') {
document.documentElement.style.setProperty('--SmartThemeBodyColor', power_user.main_text_color);
}
if (type === 'italics') {
document.documentElement.style.setProperty('--SmartThemeEmColor', power_user.italics_text_color);
}
if (type === 'fastUIBG') {
document.documentElement.style.setProperty('--SmartThemeFastUIBGColor', power_user.fastui_bg_color);
}
if (type === 'blurTint') {
document.documentElement.style.setProperty('--SmartThemeBlurTintColor', power_user.blur_tint_color);
}
// a small delay to let the browser do the layout redraw
await delay(1);
// set transition back to chat
chat.style.transition = chatTransition;
}
async function applyBlurStrength() {
power_user.blur_strength = Number(localStorage.getItem(storage_keys.blur_strength) ?? 1);
// temporarily unset transition from chat to not make the browser calculate the animation
chat.style.transition = 'unset';
// now apply the blur strength to the document
document.documentElement.style.setProperty('--blurStrength', power_user.blur_strength);
$("#blur_strength_counter").text(power_user.blur_strength);
// a small delay to let the browser do the layout redraw
await delay(1);
// set transition back to chat
chat.style.transition = chatTransition;
}
async function applyFontScale() {
power_user.font_scale = Number(localStorage.getItem(storage_keys.font_scale) ?? 1);
// temporarily unset transition from chat to not make the browser calculate the animation
chat.style.transition = 'unset';
// now apply the font scale to the document
document.documentElement.style.setProperty('--fontScale', power_user.font_scale);
$("#font_scale_counter").text(power_user.font_scale);
// a small delay to let the browser do the layout redraw
await delay(1);
// set transition back to chat
chat.style.transition = chatTransition;
}
async function applyTheme(name) {
@@ -307,6 +271,7 @@ function loadPowerUserSettings(settings, data) {
$("#multigen_next_chunks").val(power_user.multigen_next_chunks);
$("#play_message_sound").prop("checked", power_user.play_message_sound);
$("#play_sound_unfocused").prop("checked", power_user.play_sound_unfocused);
$("#auto_save_msg_edits").prop("checked", power_user.auto_save_msg_edits);
$(`input[name="avatar_style"][value="${power_user.avatar_style}"]`).prop("checked", true);
$(`input[name="chat_display"][value="${power_user.chat_display}"]`).prop("checked", true);
$(`input[name="sheld_width"][value="${power_user.sheld_width}"]`).prop("checked", true);
@@ -573,6 +538,11 @@ $(document).ready(() => {
saveSettingsDebounced();
});
$("#auto_save_msg_edits").on('input', function () {
power_user.auto_save_msg_edits = !!$(this).prop('checked');
saveSettingsDebounced();
});
$("#character_sort_order").on('change', function () {
power_user.sort_field = $(this).find(":selected").data('field');
power_user.sort_order = $(this).find(":selected").data('order');
+11 -6
View File
@@ -50,13 +50,12 @@
/* base variable for blur strength slider calculations */
--blurStrength: 10;
color-scheme: only light;
/*styles for the color picker*/
--tool-cool-color-picker-btn-bg: transparent;
--tool-cool-color-picker-btn-border-color: transparent;
}
* {
@@ -267,7 +266,7 @@ code {
-webkit-backdrop-filter: blur(var(--SmartThemeBlurStrength));
text-shadow: #000 0 0 3px;
scrollbar-width: thin;
transition: all 1s ease-in-out;
/* transition: all 1s ease-in-out; */
flex-direction: column;
z-index: 3;
}
@@ -3320,9 +3319,9 @@ body.waifuMode .expression-holder {
max-height: 90vh;
max-width: 90vw;
height: 90vh;
width: 90vw;
position: absolute;
left: 5vw;
width: fit-content;
position: unset;
margin: 0 auto;
bottom: 0;
filter: drop-shadow(2px 2px 2px #51515199);
z-index: 1;
@@ -3557,6 +3556,12 @@ body.movingUI #expression-holder {
}
}
@media screen and (max-width: 1000px) and (orientation: landscape) {
body.waifuMode img.expression {
object-fit: contain;
}
}
@media screen and (max-width: 450px) {
.drawer25pWidth {
flex-basis: max(calc(100% / 2 - 10px), 200px);
Binary file not shown.
+18 -13
View File
@@ -2,24 +2,15 @@
## Based on a fork of TavernAI 1.2.8
### Brought to you by Cohee and RossAscends
NOTE: We have added [a FAQ](faq.md) to answer most of your questions and help you get started.
### What is SillyTavern or TavernAI?
Tavern is a user interface you can install on your computer (and Android phones) that allows you to interact with text generation AIs and chat/roleplay with characters you or the community create.
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.
### What do I need other than Tavern?
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.
### I'm new to all this. I just want to have a good time easily. What is the best AI backend to use?
The most advanced/intelligent AI backend for roleplaying is to pay for OpenAI's GPT API. It's also among the easiest to use. Objectively, GPT is streets ahead of all other backends. However, OpenAI logs all your activity, and your account MAY be banned in the future if you violate their policies (e.g. on adult content). However, there are no reports of anyone being banned yet.
People who value privacy more tend to run a self-hosted AI backend like KoboldAI. Self-hosted backends do not log, but they are much less capable of roleplaying.
#### OpenAI bots are too horny, aggressive, or you want to try something new? 🤔
Try some other Jailbreak / NSFW prompts from this community-maintained list:
https://rentry.org/GPTJailbreakPrompting
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](faq.md).
### Do I need a powerful PC to run Tavern?
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.
@@ -134,6 +125,17 @@ Restart your TAI server.
You will now be able to connect from other devices.
### Managing whitelisted IPs
You can add or remove whitelisted IPs by editing the `whitelist` array in `config.conf`. You can also provide a `whitelist.txt` file in the same directory as `config.conf` with one IP address per line like:
```txt
192.168.0.1
192.168.0.2
```
The `whitelist` array in `config.conf` will be ignored if `whitelist.txt` exists.
***Disclaimer: Anyone else who knows your IP address and TAI port number will be able to connect as well***
To connect over wifi you'll need your PC's local wifi IP address
@@ -149,7 +151,7 @@ Try enabling the No Blur Effect (Fast UI) mode on the User settings panel.
### DO's
1. Send pull requests
2. Send feature suggestions and issue reports using establised templates
2. Send feature suggestions and issue reports using established templates
3. Read the readme file and built-in documentation before asking anything
### DONT's
@@ -179,3 +181,6 @@ Contact us on:
* GraphQL files for poe: https://github.com/muharamdani/poe (ISC License)
* KoboldAI Presets from KAI Lite: https://lite.koboldai.net/
* Noto Sans font by Google (OFL license)
* Icon theme by Font Awesome https://fontawesome.com (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
* Linux startup script by AlpinDale
* Thanks paniphons for providing a FAQ document
+41 -2
View File
@@ -31,7 +31,17 @@ const webp = require('webp-converter');
const config = require(path.join(process.cwd(), './config.conf'));
const server_port = process.env.SILLY_TAVERN_PORT || config.port;
const whitelist = config.whitelist;
const whitelistPath = path.join(process.cwd(), "./whitelist.txt");
let whitelist = config.whitelist;
if (fs.existsSync(whitelistPath)) {
try {
let whitelistTxt = fs.readFileSync(whitelistPath, 'utf-8');
whitelist = whitelistTxt.split("\n").filter(ip => ip).map(ip => ip.trim());
} catch (e) { }
}
const whitelistMode = config.whitelistMode;
const autorun = config.autorun;
const enableExtensions = config.enableExtensions;
@@ -1933,6 +1943,35 @@ app.get('/discover_extensions', jsonParser, function (_, response) {
return response.send(extensions);
});
app.get('/get_sprites', jsonParser, function (request, response) {
const name = request.query.name;
const spritesPath = path.join(directories.characters, name);
let sprites = [];
try {
if (fs.existsSync(spritesPath) && fs.statSync(spritesPath).isDirectory()) {
sprites = fs.readdirSync(spritesPath)
.filter(file => {
const mimeType = mime.lookup(file);
return mimeType && mimeType.startsWith('image/');
})
.map((file) => {
const pathToSprite = path.join(spritesPath, file);
return {
label: path.parse(pathToSprite).name.toLowerCase(),
path: `/characters/${name}/${file}`,
};
});
}
}
catch (err) {
console.log(err);
}
finally {
return response.send(sprites);
}
});
function getThumbnailFolder(type) {
let thumbnailFolder;
@@ -2494,4 +2533,4 @@ function ensurePublicDirectoriesExist() {
fs.mkdirSync(dir, { recursive: true });
}
}
}
}