From 383d46fe4daeb5bd81b6c3b1c6ca212e0b79e682 Mon Sep 17 00:00:00 2001 From: Yokayo Date: Mon, 26 Aug 2024 01:39:56 +0700 Subject: [PATCH 1/4] Work on tl --- public/index.html | 2 +- public/locales/ru-ru.json | 61 ++++++++++++++++--- public/script.js | 23 +++---- public/scripts/openai.js | 17 +++--- public/scripts/templates/chatRename.html | 6 ++ public/scripts/templates/newChatConfirm.html | 4 ++ .../templates/proxyConnectionWarning.html | 1 + 7 files changed, 82 insertions(+), 32 deletions(-) create mode 100644 public/scripts/templates/chatRename.html create mode 100644 public/scripts/templates/newChatConfirm.html create mode 100644 public/scripts/templates/proxyConnectionWarning.html diff --git a/public/index.html b/public/index.html index 46962677b..3d3cb6a62 100644 --- a/public/index.html +++ b/public/index.html @@ -4120,7 +4120,7 @@ MovingUI  - +
diff --git a/public/locales/ru-ru.json b/public/locales/ru-ru.json index 17a0a406a..3afe4109c 100644 --- a/public/locales/ru-ru.json +++ b/public/locales/ru-ru.json @@ -43,7 +43,7 @@ "Smoothing Factor": "Коэффициент сглаживания", "No Repeat Ngram Size": "Размер no_repeat_ngram", "Min Length": "Мин. длина", - "Alternative server URL (leave empty to use the default value).": "Альтернативный URL сервера (оставьте пустым для стандартного значения)", + "Alternative server URL (leave empty to use the default value).": "URL альтернативного сервера (оставьте пустым для стандартного значения)", "Remove your real OAI API Key from the API panel BEFORE typing anything into this box": "Удалите свой личный OAI API Key из панели API, и ТОЛЬКО ПОСЛЕ ЭТОГО вводите что-то сюда", "We cannot provide support for problems encountered while using an unofficial OpenAI proxy": "Мы не сможем предоставить помощь с проблемами, с которыми вы столкнетесь при использовании неофициальных прокси для OpenAI", "Context Size (tokens)": "Размер контекста (в токенах)", @@ -186,7 +186,7 @@ "Generate only one line per request": "Генерировать одну строку на запрос", "Misc. Settings": "Доп. настройки", "Auto-Continue": "Авто-продолжение", - "Collapse Consecutive Newlines": "Сворачивать последовательные новые строки", + "Collapse Consecutive Newlines": "Сворачивать неск. новых строк в одну", "Allow for Chat Completion APIs": "Разрешить для Chat Completion API", "Target length (tokens)": "Целевая длина (в токенах)", "World Info": "Информация о мире", @@ -373,7 +373,7 @@ "Prefer Character Card Prompt": "Приоритет промпту из карточки персонажа", "Prefer Character Card Jailbreak": "Приоритет джейлбрейку из карточки персонажа", "Press Send to continue": "Кнопка отправки продолжает сообщение", - "Quick 'Continue' button": "Кнопка быстрого продолжения", + "Quick 'Continue' button": "Быстрое продолжение", "Log prompts to console": "Выводить промпты в консоль", "Never resize avatars": "Не менять размер аватарок", "Show avatar filenames": "Показывать названия файлов аватарок", @@ -495,7 +495,7 @@ "(Write a comma-separated list of tags)": "(Список тегов через запятую)", "(A brief description of the personality)": "(Краткое описание личности)", "(Circumstances and context of the interaction)": "(Обстоятельства и контекст этого диалога)", - "(Examples of chat dialog. Begin each example with START on a new line.)": "(Примеры диалога. Начинайте каждый пример с START или новой линией.)", + "(Examples of chat dialog. Begin each example with START on a new line.)": "(Примеры диалога. Начинайте каждый пример с START или новой строкой.)", "Type here...": "Пишите здесь...", "Comma separated (required)": "Через запятую (обязательное поле)", "What this keyword should mean to the AI, sent verbatim": "Что это ключевое слово должно означать для ИИ, отправляется дословно", @@ -552,7 +552,7 @@ "Click to set a new User Name": "Нажмите, чтобы задать новое имя пользователя.", "Click to lock your selected persona to the current chat. Click again to remove the lock.": "Нажмите, чтобы закрепить выбранную персону для текущего чата. Нажмите еще раз, чтобы открепить.", "Click to set user name for all messages": "Нажмите, чтобы задать имя пользователя для всех сообщений.", - "Create a dummy persona": "Создать персону-болванку", + "Create a dummy persona": "Создать пустую персону", "Character Management": "Управление персонажами", "Locked = Character Management panel will stay open": "Закреплено = Панель управление персонажами останется открытой", "Select/Create Characters": "Выбрать/Создать персонажа", @@ -625,7 +625,7 @@ "Automatically select a background based on the chat context": "Автоматический выбор фона в зависимости от контекста чата", "Filter": "Фильтр", "Exclude message from prompts": "Исключить сообщение из промпта", - "Include message in prompts": "Включить сообщение в подсказки", + "Include message in prompts": "Включить сообщение в промпт", "Create checkpoint": "Создать чекпоинт", "Create Branch": "Создать ветку", "Embed file or image": "Вставить файл или изображение", @@ -1661,5 +1661,52 @@ "ext_regex_ai_output_desc": "Сообщения, полученные от API", "ext_regex_sts_desc": "Сообщения, отправленные с помощью команд STscript", "ext_regex_wi_desc": "Содержимое лорбуков и миров. Для работы требует включения флажка \"Только промпт\"!", - "ext_regex_only_format_display_desc": "История чата не изменится, замена будет осуществляться только в отображаемом сообщении (в UI)" + "ext_regex_only_format_display_desc": "История чата не изменится, замена будет осуществляться только в отображаемом сообщении (в UI)", + "Prefer Character Card Instructions": "Приоритет инструкциям из карточек", + "If checked and the character card contains a Post-History Instructions override, use that instead": "Если в карточке персонажа имеется собственная инструкция после истории, в промпт попадёт именно она", + "Auto-select Input Text": "Автовыделение вводимого текста", + "Enable auto-select of input text in some text fields when clicking/selecting them. Applies to popup input textboxes, and possible other custom input fields.": "Автоматически выделять вводимый текст в некоторых текстовых полях при клике/выборе. Работает для вспл. окон и различных кастомных полей ввода.", + "Reset MovingUI panel sizes/locations.": "Сбросить расположение и размеры панелей MovingUI.", + "mui_reset": "Сброс", + "Quick 'Impersonate' button": "Быстрое перевоплощение", + "Show a button in the input area to ask the AI to impersonate your character for a single message": "Показать в поле ввода кнопку, по нажатии на которую ИИ сгенерирует одно сообщение от лица вашего персонажа.", + "Separators as Stop Strings": "Разделители как стоп-строки", + "Names as Stop Strings": "Имена как стоп-строки", + "Add Character and User names to a list of stopping strings.": "Добавлять имена персонажа и пользователя в список стоп-строк.", + "Allow Post-History Instructions": "Разрешить инструкции после истории", + "context_allow_post_history_instructions": "Добавлять в конец промпта инструкции после истории. Работает только при наличии таких инструкций в карточке И при включенной опции ''Приоритет инструкциям из карточек''.\nНЕ РЕКОМЕНДУЕТСЯ ДЛЯ МОДЕЛЕЙ TEXT COMPLETION, МОЖЕТ ПОРТИТЬ ВЫХОДНОЙ ТЕКСТ.", + "First User Prefix": "Первый префикс пользователя", + "Inserted before the first User's message.": "Вставляется перед первым сообщением пользователя.", + "Last User Prefix": "Последний префикс пользователя", + "instruct_last_input_sequence": "Вставляется перед последним сообщением пользователя.", + "Inserted before a User message and as a last prompt line when impersonating.": "Вставляется перед сообщением пользователя в качестве последней строки промпта при перевоплощении.", + "Inserted before a System (added by slash commands or extensions) message.": "Вставляется перед сообщением системы (может быть добавлено слэш-командой или расширением).", + "Load Asset List": "Загрузить список ресурсов", + "Never add character names.": "Не вставлять имя персонажа.", + "Don't add character names unless necessary.": "Вставлять имя персонажа только когда это необходимо.", + "character_names_none": "Не добавлять имена персонажей в качестве префикса. Может повредить качеству ответов в групповых чатах, используйте с осторожностью.", + "Auxiliary": "Вспомогательный", + "Post-History Instructions": "Инструкции после истории", + "Current persona updated": "Текущая персона изменена", + "Your messages will now be sent as ${0}": "Ваши сообщения будут отправляться от лица ${0}", + "Copied!": "Скопировано!", + "Are you sure you want to delete this message?": "Вы точно хотите удалить это сообщение?", + "Delete Message": "Удалить сообщение", + "Delete Swipe": "Удалить свайп", + "Could not get a reply from API. Check your connection settings / API key and try again.": "Не удалось получить ответ от API. Проверьте настройки соединения и API-ключ и повторите попытку.", + "Connecting To Proxy": "Подключение к прокси", + "Are you sure you want to connect to the following proxy URL?": "Вы точно хотите соединиться с прокси по этому адресу?", + "API connection successful!": "Соединение с API установлено!", + "Proxy Saved": "Прокси сохранена", + "Proxy Deleted": "Прокси удалена", + "Could not find proxy with name '${0}'": "Не удалось найти прокси с названием '${0}'", + "Proxy preset '${0}' not found in proxies array.": "Пресет с названием '${0}' не найден в списке прокси.", + "Please wait for the previous request to complete.": "Пожалуйста, дождитесь окончания обработки предыдущего запроса." + "Start new chat?": "Начать новый чат?", + "If necessary, you can later restore this chat file from the /backups folder": "При необходимости этот чат можно будет восстановить из папки /backups", + "Also delete the current chat file": "Также удалить текущий чат", + "chat_rename_1": "Введите новое имя чата:", + "chat_rename_2": "!!Не используйте имя уже существующего файла, это приведёт к ошибке!!", + "chat_rename_3": "Будут разрушены связи между чатами-чекпоинтами.", + "chat_rename_4": "Расширение '.jsonl' дописывать не нужно." } diff --git a/public/script.js b/public/script.js index 15f719857..b19f4218e 100644 --- a/public/script.js +++ b/public/script.js @@ -2191,7 +2191,7 @@ export function addCopyToCodeBlocks(messageElement) { codeBlocks.get(i).appendChild(copyButton); copyButton.addEventListener('pointerup', function (event) { navigator.clipboard.writeText(codeBlocks.get(i).innerText); - toastr.info('Copied!', '', { timeOut: 2000 }); + toastr.info(t`Copied!`, '', { timeOut: 2000 }); }); } } @@ -6309,7 +6309,7 @@ export function setUserName(value) { console.log(`User name changed to ${name1}`); $('#your_name').val(name1); if (power_user.persona_show_notifications) { - toastr.success(`Your messages will now be sent as ${name1}`, 'Current persona updated'); + toastr.success(t`Your messages will now be sent as ${name1}`, t`Current persona updated`); } saveSettingsDebounced(); } @@ -9530,11 +9530,7 @@ jQuery(async function () { const oldFileNameFull = $(this).closest('.select_chat_block_wrapper').find('.select_chat_block_filename').text(); const oldFileName = oldFileNameFull.replace('.jsonl', ''); - const popupText = `

Enter the new name for the chat:

- !!Using an existing filename will produce an error!!
- This will break the link between checkpoint chats.
- No need to add '.jsonl' at the end.
-
`; + const popupText = await renderTemplateAsync('chatRename'); const newName = await callPopup(popupText, 'input', oldFileName); if (!newName || newName == oldFileName) { @@ -9742,12 +9738,7 @@ jQuery(async function () { else if (id == 'option_start_new_chat') { if ((selected_group || this_chid !== undefined) && !is_send_press) { let deleteCurrentChat = false; - const result = await Popup.show.confirm('Start new chat?', ` - `, { + const result = await Popup.show.confirm(t`Start new chat?`, await renderTemplateAsync('newChatConfirm'), { onClose: () => deleteCurrentChat = !!$('#del_chat_checkbox').prop('checked'), }); if (!result) { @@ -10259,10 +10250,10 @@ jQuery(async function () { let deleteOnlySwipe = false; if (power_user.confirm_message_delete && fromSlashCommand !== true) { - const result = await callGenericPopup('Are you sure you want to delete this message?', POPUP_TYPE.CONFIRM, null, { - okButton: canDeleteSwipe ? 'Delete Swipe' : 'Delete Message', + const result = await callGenericPopup(t`Are you sure you want to delete this message?`, POPUP_TYPE.CONFIRM, null, { + okButton: canDeleteSwipe ? t`Delete Swipe` : t`Delete Message`, cancelButton: 'Cancel', - customButtons: canDeleteSwipe ? ['Delete Message'] : null, + customButtons: canDeleteSwipe ? [t`Delete Message`] : null, }); if (!result) { return; diff --git a/public/scripts/openai.js b/public/scripts/openai.js index 0de095b64..a6239b60b 100644 --- a/public/scripts/openai.js +++ b/public/scripts/openai.js @@ -74,6 +74,7 @@ import { ARGUMENT_TYPE, SlashCommandArgument } from './slash-commands/SlashComma import { renderTemplateAsync } from './templates.js'; import { SlashCommandEnumValue } from './slash-commands/SlashCommandEnumValue.js'; import { Popup, POPUP_RESULT } from './popup.js'; +import { t } from './i18n.js'; export { openai_messages_count, @@ -425,7 +426,7 @@ async function validateReverseProxy() { const rememberKey = `Proxy_SkipConfirm_${getStringHash(oai_settings.reverse_proxy)}`; const skipConfirm = localStorage.getItem(rememberKey) === 'true'; - const confirmation = skipConfirm || await Popup.show.confirm('Connecting To Proxy', `Are you sure you want to connect to the following proxy URL?${DOMPurify.sanitize(oai_settings.reverse_proxy)}`); + const confirmation = skipConfirm || await Popup.show.confirm(t`Connecting To Proxy`, await renderTemplateAsync('proxyConnectionWarning', {proxyURL: DOMPurify.sanitize(oai_settings.reverse_proxy)})); if (!confirmation) { toastr.error('Update or remove your reverse proxy settings.'); @@ -4673,17 +4674,17 @@ function toggleChatCompletionForms() { async function testApiConnection() { // Check if the previous request is still in progress if (is_send_press) { - toastr.info('Please wait for the previous request to complete.'); + toastr.info(t`Please wait for the previous request to complete.`); return; } try { const reply = await sendOpenAIRequest('quiet', [{ 'role': 'user', 'content': 'Hi' }]); console.log(reply); - toastr.success('API connection successful!'); + toastr.success(t`API connection successful!`); } catch (err) { - toastr.error('Could not get a reply from API. Check your connection settings / API key and try again.'); + toastr.error(t`Could not get a reply from API. Check your connection settings / API key and try again.`); } } @@ -4837,7 +4838,7 @@ function onProxyPresetChange() { if (selectedPreset) { setProxyPreset(selectedPreset.name, selectedPreset.url, selectedPreset.password); } else { - console.error(`Proxy preset "${value}" not found in proxies array.`); + console.error(t`Proxy preset '${value}' not found in proxies array.`); } saveSettingsDebounced(); } @@ -4849,7 +4850,7 @@ $('#save_proxy').on('click', async function () { setProxyPreset(presetName, reverseProxy, proxyPassword); saveSettingsDebounced(); - toastr.success('Proxy Saved'); + toastr.success(t`Proxy Saved`); if ($('#openai_proxy_preset').val() !== presetName) { const option = document.createElement('option'); option.text = presetName; @@ -4883,9 +4884,9 @@ $('#delete_proxy').on('click', async function () { saveSettingsDebounced(); $('#openai_proxy_preset').val(selected_proxy.name); - toastr.success('Proxy Deleted'); + toastr.success(t`Proxy Deleted`); } else { - toastr.error(`Could not find proxy with name "${presetName}"`); + toastr.error(t`Could not find proxy with name '${presetName}'`); } }); diff --git a/public/scripts/templates/chatRename.html b/public/scripts/templates/chatRename.html new file mode 100644 index 000000000..2ffbd5654 --- /dev/null +++ b/public/scripts/templates/chatRename.html @@ -0,0 +1,6 @@ +

Enter the new name for the chat:

+ + !!Using an existing filename will produce an error!!
+ This will break the link between checkpoint chats.
+ No need to add '.jsonl' at the end.
+
\ No newline at end of file diff --git a/public/scripts/templates/newChatConfirm.html b/public/scripts/templates/newChatConfirm.html new file mode 100644 index 000000000..38436ba8f --- /dev/null +++ b/public/scripts/templates/newChatConfirm.html @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/public/scripts/templates/proxyConnectionWarning.html b/public/scripts/templates/proxyConnectionWarning.html new file mode 100644 index 000000000..4218b5b98 --- /dev/null +++ b/public/scripts/templates/proxyConnectionWarning.html @@ -0,0 +1 @@ +Are you sure you want to connect to the following proxy URL?{{proxyURL}} \ No newline at end of file From 15a6b6100e7703b47186c3fc4b32d278ed71cbf5 Mon Sep 17 00:00:00 2001 From: Yokayo Date: Mon, 26 Aug 2024 02:00:52 +0700 Subject: [PATCH 2/4] Fix syntax error --- public/locales/ru-ru.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/locales/ru-ru.json b/public/locales/ru-ru.json index 3afe4109c..311d41f32 100644 --- a/public/locales/ru-ru.json +++ b/public/locales/ru-ru.json @@ -1701,7 +1701,7 @@ "Proxy Deleted": "Прокси удалена", "Could not find proxy with name '${0}'": "Не удалось найти прокси с названием '${0}'", "Proxy preset '${0}' not found in proxies array.": "Пресет с названием '${0}' не найден в списке прокси.", - "Please wait for the previous request to complete.": "Пожалуйста, дождитесь окончания обработки предыдущего запроса." + "Please wait for the previous request to complete.": "Пожалуйста, дождитесь окончания обработки предыдущего запроса.", "Start new chat?": "Начать новый чат?", "If necessary, you can later restore this chat file from the /backups folder": "При необходимости этот чат можно будет восстановить из папки /backups", "Also delete the current chat file": "Также удалить текущий чат", From e11e7b7d52c10acb3a70f90ea6dd745a6fead150 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Wed, 28 Aug 2024 21:15:20 +0300 Subject: [PATCH 3/4] Translate message copy --- public/script.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/script.js b/public/script.js index 1abc3c98f..15b791a98 100644 --- a/public/script.js +++ b/public/script.js @@ -5080,7 +5080,7 @@ async function promptItemize(itemizedPrompts, requestedMesId) { } navigator.clipboard.writeText(rawPromptValues); - toastr.info('Copied!'); + toastr.info(t`Copied!`); }); popup.dlg.querySelector('#showRawPrompt').addEventListener('click', function () { From c820d5f56a6cea0180954c3473b5fae4116d6bdb Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Wed, 28 Aug 2024 21:20:21 +0300 Subject: [PATCH 4/4] Reformat code --- public/scripts/openai.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/scripts/openai.js b/public/scripts/openai.js index a6239b60b..a6a79acbf 100644 --- a/public/scripts/openai.js +++ b/public/scripts/openai.js @@ -426,7 +426,7 @@ async function validateReverseProxy() { const rememberKey = `Proxy_SkipConfirm_${getStringHash(oai_settings.reverse_proxy)}`; const skipConfirm = localStorage.getItem(rememberKey) === 'true'; - const confirmation = skipConfirm || await Popup.show.confirm(t`Connecting To Proxy`, await renderTemplateAsync('proxyConnectionWarning', {proxyURL: DOMPurify.sanitize(oai_settings.reverse_proxy)})); + const confirmation = skipConfirm || await Popup.show.confirm(t`Connecting To Proxy`, await renderTemplateAsync('proxyConnectionWarning', { proxyURL: DOMPurify.sanitize(oai_settings.reverse_proxy) })); if (!confirmation) { toastr.error('Update or remove your reverse proxy settings.');