From 0d8a83e6b6cd8c8458063161589eb0d47abaedec Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 04:01:13 +0300 Subject: [PATCH 01/11] Fix imported char flashing with pagination --- public/script.js | 41 +++++++++++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/public/script.js b/public/script.js index 9522f82eb..6b0895187 100644 --- a/public/script.js +++ b/public/script.js @@ -320,6 +320,7 @@ let safetychat = [ }, ]; let chatSaveTimeout; +let importFlashTimeout; export let isChatSaving = false; let chat_create_date = 0; let firstRun = false; @@ -5708,19 +5709,39 @@ function select_rm_info(type, charId, previousCharId = null) { selectRightMenuWithAnimation('rm_characters_block'); - setTimeout(function () { + // Set a timeout so multiple flashes don't overlap + clearTimeout(importFlashTimeout); + importFlashTimeout = setTimeout(function () { if (type === 'char_import' || type === 'char_create') { - const element = $(`#rm_characters_block [title="${charId}"]`).parent().get(0); - console.log(element); - element.scrollIntoView({ behavior: 'smooth', block: 'start' }); + // Find the page at which the character is located + const charData = getEntitiesList({ doFilter: true }); + const charIndex = charData.findIndex((x) => x?.item?.avatar?.startsWith(charId)); + + if (charIndex === -1) { + console.log(`Could not find character ${charId} in the list`); + return; + } try { - if (element !== undefined || element !== null) { + const perPage = Number(localStorage.getItem('Characters_PerPage')); + const page = Math.floor(charIndex / perPage) + 1; + const selector = `#rm_print_characters_block [title^="${charId}"]`; + $('#rm_print_characters_pagination').pagination('go', page); + + waitUntilCondition(() => document.querySelector(selector) !== null).then(() => { + const element = $(selector).parent().get(0); + + if (!element) { + console.log(`Could not find element for character ${charId}`); + return; + } + + element.scrollIntoView({ behavior: 'smooth', block: 'start' }); $(element).addClass('flash animated'); setTimeout(function () { $(element).removeClass('flash animated'); }, 5000); - } else { console.log('didnt find the element'); } + }); } catch (e) { console.error(e); } @@ -5741,7 +5762,7 @@ function select_rm_info(type, charId, previousCharId = null) { console.error(e); } } - }, 100); + }, 250); if (previousCharId) { const newId = characters.findIndex((x) => x.avatar == previousCharId); @@ -8682,9 +8703,9 @@ $(document).ready(function () { } // Set the height of "autoSetHeight" textareas within the drawer to their scroll height - $(this).closest('.drawer').find('.drawer-content textarea.autoSetHeight').each(function() { + $(this).closest('.drawer').find('.drawer-content textarea.autoSetHeight').each(function () { resetScrollHeight($(this)); - }); + }); } else if (drawerWasOpenAlready) { //to close manually icon.toggleClass('closedIcon openIcon'); @@ -8753,7 +8774,7 @@ $(document).ready(function () { $(this).closest('.inline-drawer').find('.inline-drawer-content').stop().slideToggle(); // Set the height of "autoSetHeight" textareas within the inline-drawer to their scroll height - $(this).closest('.inline-drawer').find('.inline-drawer-content textarea.autoSetHeight').each(function() { + $(this).closest('.inline-drawer').find('.inline-drawer-content textarea.autoSetHeight').each(function () { resetScrollHeight($(this)); }); }); From 813a6403346b266549fc18da47fa1a97e8a86fc1 Mon Sep 17 00:00:00 2001 From: Stefan Daniel Schwarz Date: Sun, 27 Aug 2023 12:13:55 +0200 Subject: [PATCH 02/11] Add model info to model icon as title --- public/script.js | 1 + 1 file changed, 1 insertion(+) diff --git a/public/script.js b/public/script.js index 6b0895187..1e6be48b1 100644 --- a/public/script.js +++ b/public/script.js @@ -1324,6 +1324,7 @@ function insertSVGIcon(mes, extra) { // Add classes for styling and identification image.classList.add('icon-svg', 'timestamp-icon'); image.src = `/img/${modelName}.svg`; + image.title = `${extra?.api ? extra.api + ' - ' : ''}${extra?.model ?? ''}`; image.onload = async function () { // Check if an SVG already exists adjacent to the timestamp From 57985eb08e76e345fc732738563b1832652580d4 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 13:16:42 +0300 Subject: [PATCH 03/11] Fix hint for "Add names" --- public/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/index.html b/public/index.html index 6754f68c0..4dcfe7d45 100644 --- a/public/index.html +++ b/public/index.html @@ -1412,7 +1412,7 @@ Add character names
- Helps the model to associate messages in group chats. Names must only contain letters or numbers without whitespaces. + Send names in the ChatML objects. Helps the model to associate messages with characters.
From 8cb194da0f93ba57db6a6f79b70ae3f9c23a1a84 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 13:17:20 +0300 Subject: [PATCH 04/11] Fix sending empty array as OAI stop strings --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 957557807..7ac683abd 100644 --- a/server.js +++ b/server.js @@ -3515,7 +3515,7 @@ app.post("/generate_openai", jsonParser, function (request, response_generate_op } // Add custom stop sequences - if (Array.isArray(request.body.stop)) { + if (Array.isArray(request.body.stop) && request.body.stop.length > 0) { bodyParams['stop'] = request.body.stop; } From 109ea4008b5b35105a60adce73d33735b0a5d464 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 13:31:14 +0300 Subject: [PATCH 05/11] Improve Horde request error detection --- public/scripts/horde.js | 12 +++++++++--- server.js | 11 +++++++++-- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/public/scripts/horde.js b/public/scripts/horde.js index 57d162d71..1c66e0621 100644 --- a/public/scripts/horde.js +++ b/public/scripts/horde.js @@ -117,12 +117,18 @@ async function generateHorde(prompt, params, signal) { }); if (!response.ok) { - const error = await response.json(); - callPopup(error.message, 'text'); - throw new Error('Horde generation failed: ' + error.message); + toastr.error(response.statusText, 'Horde generation failed'); + throw new Error(`Horde generation failed: ${response.statusText}`); } const responseJson = await response.json(); + + if (responseJson.error) { + const reason = responseJson.error?.message || 'Unknown error'; + toastr.error(reason, 'Horde generation failed'); + throw new Error(`Horde generation failed: ${reason}`); + } + const task_id = responseJson.id; let queue_position_first = null; console.log(`Horde task id = ${task_id}`); diff --git a/server.js b/server.js index 7ac683abd..e28d2acc1 100644 --- a/server.js +++ b/server.js @@ -4202,8 +4202,15 @@ app.post('/generate_horde', jsonParser, async (request, response) => { const data = await postAsync(url, args); return response.send(data); } catch (error) { - console.error(error); - return response.sendStatus(500); + console.log('Horde returned an error:', error.statusText); + + if (typeof error.text === 'function') { + const message = await error.text(); + console.log(message); + return response.send({ error: { message } }); + } else { + return response.send({ error: true }); + } } }); From 8ec9b64be48713edfec5aea66827a42a2b7bee44 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 13:34:29 +0300 Subject: [PATCH 06/11] Fix regeneration calls on empty chat --- public/script.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/public/script.js b/public/script.js index 1e6be48b1..52dfcbbb8 100644 --- a/public/script.js +++ b/public/script.js @@ -2342,10 +2342,10 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, if (chat.length && chat[chat.length - 1]['is_user']) { //do nothing? why does this check exist? } - else if (type !== 'quiet' && type !== "swipe" && !isImpersonate && !dryRun) { + else if (type !== 'quiet' && type !== "swipe" && !isImpersonate && !dryRun && chat.length) { chat.length = chat.length - 1; count_view_mes -= 1; - $('#chat').children().last().hide(500, function () { + $('#chat').children().last().hide(250, function () { $(this).remove(); }); await eventSource.emit(event_types.MESSAGE_DELETED, chat.length); From 9660aaa2c2d49a502af0176cf2cebb4d554dc390 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 18:27:34 +0300 Subject: [PATCH 07/11] Add NovelAI hypebot plugin --- public/index.html | 2 +- public/lib/gpt-3-tokenizer/array-keyed-map.js | 210 -------------- public/lib/gpt-3-tokenizer/gpt3-tokenizer.js | 271 ------------------ .../lib/gpt-3-tokenizer/gpt3-tokenizer.js.map | 1 - public/scripts/extensions/hypebot/index.js | 195 +++++++++++++ .../scripts/extensions/hypebot/manifest.json | 11 + .../scripts/extensions/hypebot/settings.html | 18 ++ public/scripts/extensions/hypebot/style.css | 17 ++ .../scripts/extensions/quick-reply/style.css | 1 + public/scripts/tokenizers.js | 118 ++++++-- public/scripts/utils.js | 11 + public/style.css | 3 + server.js | 116 ++++++-- src/novelai.js | 92 ++++-- 14 files changed, 505 insertions(+), 561 deletions(-) delete mode 100644 public/lib/gpt-3-tokenizer/array-keyed-map.js delete mode 100644 public/lib/gpt-3-tokenizer/gpt3-tokenizer.js delete mode 100644 public/lib/gpt-3-tokenizer/gpt3-tokenizer.js.map create mode 100644 public/scripts/extensions/hypebot/index.js create mode 100644 public/scripts/extensions/hypebot/manifest.json create mode 100644 public/scripts/extensions/hypebot/settings.html create mode 100644 public/scripts/extensions/hypebot/style.css diff --git a/public/index.html b/public/index.html index 4dcfe7d45..ea91c7adc 100644 --- a/public/index.html +++ b/public/index.html @@ -2277,7 +2277,7 @@ + Enabled + + + +
+ + diff --git a/public/scripts/extensions/hypebot/style.css b/public/scripts/extensions/hypebot/style.css new file mode 100644 index 000000000..3a696f4df --- /dev/null +++ b/public/scripts/extensions/hypebot/style.css @@ -0,0 +1,17 @@ +#hypeBotBar { + width: 100%; + max-width: 100%; + padding: 0.5em; + white-space: normal; + font-size: calc(var(--mainFontSize) * 0.85); + order: 20; +} + +.hypebot_nokey { + text-align: center; + font-style: italic; +} + +.hypebot_name { + font-weight: 600; +} diff --git a/public/scripts/extensions/quick-reply/style.css b/public/scripts/extensions/quick-reply/style.css index 4f8f1a7b5..c60a60a21 100644 --- a/public/scripts/extensions/quick-reply/style.css +++ b/public/scripts/extensions/quick-reply/style.css @@ -12,6 +12,7 @@ display: none; max-width: 100%; overflow-x: auto; + order: 10; } #quickReplies { diff --git a/public/scripts/tokenizers.js b/public/scripts/tokenizers.js index 0b5a34668..8c43b8049 100644 --- a/public/scripts/tokenizers.js +++ b/public/scripts/tokenizers.js @@ -1,7 +1,6 @@ import { characters, main_api, nai_settings, online_status, this_chid } from "../script.js"; import { power_user } from "./power-user.js"; import { encode } from "../lib/gpt-2-3-tokenizer/mod.js"; -import { GPT3BrowserTokenizer } from "../lib/gpt-3-tokenizer/gpt3-tokenizer.js"; import { chat_completion_sources, oai_settings } from "./openai.js"; import { groups, selected_group } from "./group-chats.js"; import { getStringHash } from "./utils.js"; @@ -12,7 +11,7 @@ const TOKENIZER_WARNING_KEY = 'tokenizationWarningShown'; export const tokenizers = { NONE: 0, - GPT3: 1, + GPT2: 1, CLASSIC: 2, LLAMA: 3, NERD: 4, @@ -22,7 +21,6 @@ export const tokenizers = { }; const objectStore = new localforage.createInstance({ name: "SillyTavern_ChatCompletions" }); -const gpt3 = new GPT3BrowserTokenizer({ type: 'gpt3' }); let tokenCache = {}; @@ -93,6 +91,35 @@ function getTokenizerBestMatch() { return tokenizers.NONE; } +/** + * Calls the underlying tokenizer model to the token count for a string. + * @param {number} type Tokenizer type. + * @param {string} str String to tokenize. + * @param {number} padding Number of padding tokens. + * @returns {number} Token count. + */ +function callTokenizer(type, str, padding) { + switch (type) { + case tokenizers.NONE: + return guesstimate(str) + padding; + case tokenizers.GPT2: + return countTokensRemote('/tokenize_gpt2', str, padding); + case tokenizers.CLASSIC: + return encode(str).length + padding; + case tokenizers.LLAMA: + return countTokensRemote('/tokenize_llama', str, padding); + case tokenizers.NERD: + return countTokensRemote('/tokenize_nerdstash', str, padding); + case tokenizers.NERD2: + return countTokensRemote('/tokenize_nerdstash_v2', str, padding); + case tokenizers.API: + return countTokensRemote('/tokenize_via_api', str, padding); + default: + console.warn("Unknown tokenizer type", type); + return callTokenizer(tokenizers.NONE, str, padding); + } +} + /** * Gets the token count for a string using the current model tokenizer. * @param {string} str String to tokenize @@ -100,33 +127,6 @@ function getTokenizerBestMatch() { * @returns {number} Token count. */ export function getTokenCount(str, padding = undefined) { - /** - * Calculates the token count for a string. - * @param {number} [type] Tokenizer type. - * @returns {number} Token count. - */ - function calculate(type) { - switch (type) { - case tokenizers.NONE: - return guesstimate(str) + padding; - case tokenizers.GPT3: - return gpt3.encode(str).bpe.length + padding; - case tokenizers.CLASSIC: - return encode(str).length + padding; - case tokenizers.LLAMA: - return countTokensRemote('/tokenize_llama', str, padding); - case tokenizers.NERD: - return countTokensRemote('/tokenize_nerdstash', str, padding); - case tokenizers.NERD2: - return countTokensRemote('/tokenize_nerdstash_v2', str, padding); - case tokenizers.API: - return countTokensRemote('/tokenize_via_api', str, padding); - default: - console.warn("Unknown tokenizer type", type); - return calculate(tokenizers.NONE); - } - } - if (typeof str !== 'string' || !str?.length) { return 0; } @@ -159,7 +159,7 @@ export function getTokenCount(str, padding = undefined) { return cacheObject[cacheKey]; } - const result = calculate(tokenizerType); + const result = callTokenizer(tokenizerType, str, padding); if (isNaN(result)) { console.warn("Token count calculation returned NaN"); @@ -350,6 +350,12 @@ function countTokensRemote(endpoint, str, padding) { return tokenCount + padding; } +/** + * Calls the underlying tokenizer model to encode a string to tokens. + * @param {string} endpoint API endpoint. + * @param {string} str String to tokenize. + * @returns {number[]} Array of token ids. + */ function getTextTokensRemote(endpoint, str) { let ids = []; jQuery.ajax({ @@ -366,8 +372,37 @@ function getTextTokensRemote(endpoint, str) { return ids; } +/** + * Calls the underlying tokenizer model to decode token ids to text. + * @param {string} endpoint API endpoint. + * @param {number[]} ids Array of token ids + */ +function decodeTextTokensRemote(endpoint, ids) { + let text = ''; + jQuery.ajax({ + async: false, + type: 'POST', + url: endpoint, + data: JSON.stringify({ ids: ids }), + dataType: "json", + contentType: "application/json", + success: function (data) { + text = data.text; + } + }); + return text; +} + +/** + * Encodes a string to tokens using the remote server API. + * @param {number} tokenizerType Tokenizer type. + * @param {string} str String to tokenize. + * @returns {number[]} Array of token ids. + */ export function getTextTokens(tokenizerType, str) { switch (tokenizerType) { + case tokenizers.GPT2: + return getTextTokensRemote('/tokenize_gpt2', str); case tokenizers.LLAMA: return getTextTokensRemote('/tokenize_llama', str); case tokenizers.NERD: @@ -380,6 +415,27 @@ export function getTextTokens(tokenizerType, str) { } } +/** + * Decodes token ids to text using the remote server API. + * @param {any} tokenizerType Tokenizer type. + * @param {number[]} ids Array of token ids + */ +export function decodeTextTokens(tokenizerType, ids) { + switch (tokenizerType) { + case tokenizers.GPT2: + return decodeTextTokensRemote('/decode_gpt2', ids); + case tokenizers.LLAMA: + return decodeTextTokensRemote('/decode_llama', ids); + case tokenizers.NERD: + return decodeTextTokensRemote('/decode_nerdstash', ids); + case tokenizers.NERD2: + return decodeTextTokensRemote('/decode_nerdstash_v2', ids); + default: + console.warn("Calling decodeTextTokens with unsupported tokenizer type", tokenizerType); + return ''; + } +} + jQuery(async () => { await loadTokenCache(); }); diff --git a/public/scripts/utils.js b/public/scripts/utils.js index 69d0d1030..aa74ff3dd 100644 --- a/public/scripts/utils.js +++ b/public/scripts/utils.js @@ -45,6 +45,17 @@ export function getSortableDelay() { return isMobile() ? 750 : 50; } +export async function bufferToBase64(buffer) { + // use a FileReader to generate a base64 data URI: + const base64url = await new Promise(resolve => { + const reader = new FileReader() + reader.onload = () => resolve(reader.result) + reader.readAsDataURL(new Blob([buffer])) + }); + // remove the `data:...;base64,` part from the start + return base64url.slice(base64url.indexOf(',') + 1); +} + /** * Rearranges an array in a random order. * @param {any[]} array The array to shuffle. diff --git a/public/style.css b/public/style.css index 3f09e4c76..3bc531046 100644 --- a/public/style.css +++ b/public/style.css @@ -531,6 +531,7 @@ hr { column-gap: 5px; font-size: var(--bottomFormIconSize); overflow: hidden; + order: 1003; } #send_but_sheld>div { @@ -581,6 +582,7 @@ hr { transition: 0.3s; display: flex; align-items: center; + order: 1001; } .font-family-reset { @@ -904,6 +906,7 @@ select { margin: 0; text-shadow: 0px 0px calc(var(--shadowWidth) * 1px) var(--SmartThemeShadowColor); flex: 1; + order: 1002; } .text_pole::placeholder { diff --git a/server.js b/server.js index e28d2acc1..241951c81 100644 --- a/server.js +++ b/server.js @@ -1894,8 +1894,7 @@ app.post("/generate_novelai", jsonParser, async function (request, response_gene const novelai = require('./src/novelai'); const isNewModel = (request.body.model.includes('clio') || request.body.model.includes('kayra')); - const isKrake = request.body.model.includes('krake'); - const badWordsList = (isNewModel ? novelai.badWordsList : (isKrake ? novelai.krakeBadWordsList : novelai.euterpeBadWordsList)).slice(); + const badWordsList = novelai.getBadWordsList(request.body.model); // Add customized bad words for Clio and Kayra if (isNewModel && Array.isArray(request.body.bad_words_ids)) { @@ -1907,7 +1906,7 @@ app.post("/generate_novelai", jsonParser, async function (request, response_gene } // Add default biases for dinkus and asterism - const logit_bias_exp = isNewModel ? novelai.logitBiasExp.slice() : null; + const logit_bias_exp = isNewModel ? novelai.logitBiasExp.slice() : []; if (Array.isArray(logit_bias_exp) && Array.isArray(request.body.logit_bias_exp)) { logit_bias_exp.push(...request.body.logit_bias_exp); @@ -1942,7 +1941,7 @@ app.post("/generate_novelai", jsonParser, async function (request, response_gene "logit_bias_exp": logit_bias_exp, "generate_until_sentence": request.body.generate_until_sentence, "use_cache": request.body.use_cache, - "use_string": true, + "use_string": request.body.use_string ?? true, "return_full_text": request.body.return_full_text, "prefix": request.body.prefix, "order": request.body.order @@ -3845,22 +3844,87 @@ function getPresetSettingsByAPI(apiId) { } } -function createTokenizationHandler(getTokenizerFn) { +function createSentencepieceEncodingHandler(getTokenizerFn) { return async function (request, response) { - if (!request.body) { - return response.sendStatus(400); - } + try { + if (!request.body) { + return response.sendStatus(400); + } - const text = request.body.text || ''; - const tokenizer = getTokenizerFn(); - const { ids, count } = await countSentencepieceTokens(tokenizer, text); - return response.send({ ids, count }); + const text = request.body.text || ''; + const tokenizer = getTokenizerFn(); + const { ids, count } = await countSentencepieceTokens(tokenizer, text); + return response.send({ ids, count }); + } catch (error) { + console.log(error); + return response.send({ ids: [], count: 0 }); + } }; } -app.post("/tokenize_llama", jsonParser, createTokenizationHandler(() => spp_llama)); -app.post("/tokenize_nerdstash", jsonParser, createTokenizationHandler(() => spp_nerd)); -app.post("/tokenize_nerdstash_v2", jsonParser, createTokenizationHandler(() => spp_nerd_v2)); +function createSentencepieceDecodingHandler(getTokenizerFn) { + return async function (request, response) { + try { + if (!request.body) { + return response.sendStatus(400); + } + + const ids = request.body.ids || []; + const tokenizer = getTokenizerFn(); + const text = await tokenizer.decodeIds(ids); + return response.send({ text }); + } catch (error) { + console.log(error); + return response.send({ text: '' }); + } + }; +} + +function createTiktokenEncodingHandler(modelId) { + return async function (request, response) { + try { + if (!request.body) { + return response.sendStatus(400); + } + + const text = request.body.text || ''; + const tokenizer = getTiktokenTokenizer(modelId); + const tokens = Object.values(tokenizer.encode(text)); + return response.send({ ids: tokens, count: tokens.length }); + } catch (error) { + console.log(error); + return response.send({ ids: [], count: 0 }); + } + } +} + +function createTiktokenDecodingHandler(modelId) { + return async function (request, response) { + try { + if (!request.body) { + return response.sendStatus(400); + } + + const ids = request.body.ids || []; + const tokenizer = getTiktokenTokenizer(modelId); + const textBytes = tokenizer.decode(new Uint32Array(ids)); + const text = new TextDecoder().decode(textBytes); + return response.send({ text }); + } catch (error) { + console.log(error); + return response.send({ text: '' }); + } + } +} + +app.post("/tokenize_llama", jsonParser, createSentencepieceEncodingHandler(() => spp_llama)); +app.post("/tokenize_nerdstash", jsonParser, createSentencepieceEncodingHandler(() => spp_nerd)); +app.post("/tokenize_nerdstash_v2", jsonParser, createSentencepieceEncodingHandler(() => spp_nerd_v2)); +app.post("/tokenize_gpt2", jsonParser, createTiktokenEncodingHandler('gpt2')); +app.post("/decode_llama", jsonParser, createSentencepieceDecodingHandler(() => spp_llama)); +app.post("/decode_nerdstash", jsonParser, createSentencepieceDecodingHandler(() => spp_nerd)); +app.post("/decode_nerdstash_v2", jsonParser, createSentencepieceDecodingHandler(() => spp_nerd_v2)); +app.post("/decode_gpt2", jsonParser, createTiktokenDecodingHandler('gpt2')); app.post("/tokenize_via_api", jsonParser, async function (request, response) { if (!request.body) { return response.sendStatus(400); @@ -4350,17 +4414,17 @@ app.post('/libre_translate', jsonParser, async (request, response) => { console.log('Input text: ' + text); try { - const result = await fetch(url, { - method: "POST", - body: JSON.stringify({ - q: text, - source: "auto", - target: lang, - format: "text", - api_key: key - }), - headers: { "Content-Type": "application/json" } - }); + const result = await fetch(url, { + method: "POST", + body: JSON.stringify({ + q: text, + source: "auto", + target: lang, + format: "text", + api_key: key + }), + headers: { "Content-Type": "application/json" } + }); if (!result.ok) { return response.sendStatus(result.status); diff --git a/src/novelai.js b/src/novelai.js index 3a988029a..36dc6fa94 100644 --- a/src/novelai.js +++ b/src/novelai.js @@ -1,18 +1,18 @@ // Ban bracket generation, plus defaults const euterpeBadWordsList = [ - [8162], [17202], [8162], [17202], [8162], [17202], [8162], [17202], [8162], [17202], [46256, 224], [2343, 223, 224], - [46256, 224], [2343, 223, 224], [46256, 224], [2343, 223, 224], [46256, 224], [2343, 223, 224], [46256, 224], - [2343, 223, 224], [58], [60], [90], [92], [685], [1391], [1782], [2361], [3693], [4083], [4357], [4895], [5512], - [5974], [7131], [8183], [8351], [8762], [8964], [8973], [9063], [11208], [11709], [11907], [11919], [12878], [12962], - [13018], [13412], [14631], [14692], [14980], [15090], [15437], [16151], [16410], [16589], [17241], [17414], [17635], - [17816], [17912], [18083], [18161], [18477], [19629], [19779], [19953], [20520], [20598], [20662], [20740], [21476], - [21737], [22133], [22241], [22345], [22935], [23330], [23785], [23834], [23884], [25295], [25597], [25719], [25787], - [25915], [26076], [26358], [26398], [26894], [26933], [27007], [27422], [28013], [29164], [29225], [29342], [29565], - [29795], [30072], [30109], [30138], [30866], [31161], [31478], [32092], [32239], [32509], [33116], [33250], [33761], - [34171], [34758], [34949], [35944], [36338], [36463], [36563], [36786], [36796], [36937], [37250], [37913], [37981], - [38165], [38362], [38381], [38430], [38892], [39850], [39893], [41832], [41888], [42535], [42669], [42785], [42924], - [43839], [44438], [44587], [44926], [45144], [45297], [46110], [46570], [46581], [46956], [47175], [47182], [47527], - [47715], [48600], [48683], [48688], [48874], [48999], [49074], [49082], [49146], [49946], [10221], [4841], [1427], + [8162], [17202], [8162], [17202], [8162], [17202], [8162], [17202], [8162], [17202], [46256, 224], [2343, 223, 224], + [46256, 224], [2343, 223, 224], [46256, 224], [2343, 223, 224], [46256, 224], [2343, 223, 224], [46256, 224], + [2343, 223, 224], [58], [60], [90], [92], [685], [1391], [1782], [2361], [3693], [4083], [4357], [4895], [5512], + [5974], [7131], [8183], [8351], [8762], [8964], [8973], [9063], [11208], [11709], [11907], [11919], [12878], [12962], + [13018], [13412], [14631], [14692], [14980], [15090], [15437], [16151], [16410], [16589], [17241], [17414], [17635], + [17816], [17912], [18083], [18161], [18477], [19629], [19779], [19953], [20520], [20598], [20662], [20740], [21476], + [21737], [22133], [22241], [22345], [22935], [23330], [23785], [23834], [23884], [25295], [25597], [25719], [25787], + [25915], [26076], [26358], [26398], [26894], [26933], [27007], [27422], [28013], [29164], [29225], [29342], [29565], + [29795], [30072], [30109], [30138], [30866], [31161], [31478], [32092], [32239], [32509], [33116], [33250], [33761], + [34171], [34758], [34949], [35944], [36338], [36463], [36563], [36786], [36796], [36937], [37250], [37913], [37981], + [38165], [38362], [38381], [38430], [38892], [39850], [39893], [41832], [41888], [42535], [42669], [42785], [42924], + [43839], [44438], [44587], [44926], [45144], [45297], [46110], [46570], [46581], [46956], [47175], [47182], [47527], + [47715], [48600], [48683], [48688], [48874], [48999], [49074], [49082], [49146], [49946], [10221], [4841], [1427], [2602, 834], [29343], [37405], [35780], [2602], [50256], ] @@ -47,29 +47,79 @@ const krakeBadWordsList = [ // Ban bracket generation, plus defaults const badWordsList = [ - [23], [49209, 23], [23], [49209, 23], [23], [49209, 23], [23], [49209, 23], [23], [49209, 23], [21], [49209, 21], - [21], [49209, 21], [21], [49209, 21], [21], [49209, 21], [21], [49209, 21], [3], [49356], [1431], [31715], [34387], + [23], [49209, 23], [23], [49209, 23], [23], [49209, 23], [23], [49209, 23], [23], [49209, 23], [21], [49209, 21], + [21], [49209, 21], [21], [49209, 21], [21], [49209, 21], [21], [49209, 21], [3], [49356], [1431], [31715], [34387], [20765], [30702], [10691], [49333], [1266], [26523], [41471], [2936], [85, 85], [49332], [7286], [1115] ] +const hypeBotBadWordsList = [ + [58], [60], [90], [92], [685], [1391], [1782], [2361], [3693], [4083], [4357], [4895], + [5512], [5974], [7131], [8183], [8351], [8762], [8964], [8973], [9063], [11208], + [11709], [11907], [11919], [12878], [12962], [13018], [13412], [14631], [14692], + [14980], [15090], [15437], [16151], [16410], [16589], [17241], [17414], [17635], + [17816], [17912], [18083], [18161], [18477], [19629], [19779], [19953], [20520], + [20598], [20662], [20740], [21476], [21737], [22133], [22241], [22345], [22935], + [23330], [23785], [23834], [23884], [25295], [25597], [25719], [25787], [25915], + [26076], [26358], [26398], [26894], [26933], [27007], [27422], [28013], [29164], + [29225], [29342], [29565], [29795], [30072], [30109], [30138], [30866], [31161], + [31478], [32092], [32239], [32509], [33116], [33250], [33761], [34171], [34758], + [34949], [35944], [36338], [36463], [36563], [36786], [36796], [36937], [37250], + [37913], [37981], [38165], [38362], [38381], [38430], [38892], [39850], [39893], + [41832], [41888], [42535], [42669], [42785], [42924], [43839], [44438], [44587], + [44926], [45144], [45297], [46110], [46570], [46581], [46956], [47175], [47182], + [47527], [47715], [48600], [48683], [48688], [48874], [48999], [49074], [49082], + [49146], [49946], [10221], [4841], [1427], [2602, 834], [29343], [37405], [35780], [2602], [50256] +]; + // Used for phrase repetition penalty const repPenaltyAllowList = [ - [49256, 49264, 49231, 49230, 49287, 85, 49255, 49399, 49262, 336, 333, 432, 363, 468, 492, 745, 401, 426, 623, 794, - 1096, 2919, 2072, 7379, 1259, 2110, 620, 526, 487, 16562, 603, 805, 761, 2681, 942, 8917, 653, 3513, 506, 5301, - 562, 5010, 614, 10942, 539, 2976, 462, 5189, 567, 2032, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 588, - 803, 1040, 49209, 4, 5, 6, 7, 8, 9, 10, 11, 12] + [49256, 49264, 49231, 49230, 49287, 85, 49255, 49399, 49262, 336, 333, 432, 363, 468, 492, 745, 401, 426, 623, 794, + 1096, 2919, 2072, 7379, 1259, 2110, 620, 526, 487, 16562, 603, 805, 761, 2681, 942, 8917, 653, 3513, 506, 5301, + 562, 5010, 614, 10942, 539, 2976, 462, 5189, 567, 2032, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 588, + 803, 1040, 49209, 4, 5, 6, 7, 8, 9, 10, 11, 12] ] // Ban the dinkus and asterism const logitBiasExp = [ - { "sequence": [23], "bias": -0.08, "ensure_sequence_finish": false, "generate_once": false }, + { "sequence": [23], "bias": -0.08, "ensure_sequence_finish": false, "generate_once": false }, { "sequence": [21], "bias": -0.08, "ensure_sequence_finish": false, "generate_once": false } ] +const hypeBotLogitBiasExp = [ + { "sequence": [8162], "bias": -0.12, "ensure_sequence_finish": false, "generate_once": false}, + { "sequence": [46256, 224], "bias": -0.12, "ensure_sequence_finish": false, "generate_once": false } +]; + +function getBadWordsList(model) { + let list = [] + + if (model.includes('euterpe')) { + list = euterpeBadWordsList; + } + + if (model.includes('krake')) { + list = krakeBadWordsList; + } + + if (model.includes('hypebot')) { + list = hypeBotBadWordsList; + } + + if (model.includes('clio') || model.includes('kayra')) { + list = badWordsList; + } + + // Clone the list so we don't modify the original + return list.slice(); +} + module.exports = { euterpeBadWordsList, krakeBadWordsList, badWordsList, repPenaltyAllowList, - logitBiasExp + logitBiasExp, + hypeBotBadWordsList, + hypeBotLogitBiasExp, + getBadWordsList, }; From e74bca88f46bb9309aebcaba1783d6fa593990d5 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 18:39:04 +0300 Subject: [PATCH 08/11] Disable OpenRouter fallback by default --- public/scripts/openai.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/public/scripts/openai.js b/public/scripts/openai.js index 88c1d61cf..589615035 100644 --- a/public/scripts/openai.js +++ b/public/scripts/openai.js @@ -176,7 +176,7 @@ const default_settings = { ai21_model: 'j2-ultra', windowai_model: '', openrouter_model: openrouter_website_model, - openrouter_use_fallback: true, + openrouter_use_fallback: false, jailbreak_system: false, reverse_proxy: '', legacy_streaming: false, @@ -220,7 +220,7 @@ const oai_settings = { ai21_model: 'j2-ultra', windowai_model: '', openrouter_model: openrouter_website_model, - openrouter_use_fallback: true, + openrouter_use_fallback: false, jailbreak_system: false, reverse_proxy: '', legacy_streaming: false, From 961b3e1a78b72a8cbef8a89c32a149e1fcf806a9 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 18:57:07 +0300 Subject: [PATCH 09/11] Fix leading space in Novel bias + add additional parsing methods --- public/scripts/nai-settings.js | 66 ++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 6 deletions(-) diff --git a/public/scripts/nai-settings.js b/public/scripts/nai-settings.js index 1c54f4c79..71c45aadc 100644 --- a/public/scripts/nai-settings.js +++ b/public/scripts/nai-settings.js @@ -558,6 +558,10 @@ function createLogitBiasListItem(entry) { $('.novelai_logit_bias_list').prepend(template); } +/** + * Calculates logit bias for Novel AI + * @returns {object[]} Array of logit bias objects + */ function calculateLogitBias() { const bias_preset = nai_settings.logit_bias; @@ -569,12 +573,62 @@ function calculateLogitBias() { const kayra = nai_settings.model_novel.includes('kayra'); const tokenizerType = kayra ? tokenizers.NERD2 : (clio ? tokenizers.NERD : tokenizers.NONE); - return bias_preset.filter(b => b.text?.length > 0).map(bias => ({ - bias: bias.value, - ensure_sequence_finish: false, - generate_once: false, - sequence: getTextTokens(tokenizerType, bias.text) - })); + /** + * Creates a bias object for Novel AI + * @param {number} bias Bias value + * @param {number[]} sequence Sequence of token ids + */ + function getBiasObject(bias, sequence) { + return { + bias: bias, + ensure_sequence_finish: false, + generate_once: false, + sequence: sequence + }; + } + + const result = []; + + for (const entry of bias_preset) { + if (entry.text?.length > 0) { + const text = entry.text.trim(); + + // Skip empty lines + if (text.length === 0) { + continue; + } + + // Verbatim text + if (text.startsWith('{') && text.endsWith('}')) { + const tokens = getTextTokens(tokenizerType, text.slice(1, -1)); + result.push(getBiasObject(entry.value, tokens)); + } + + // Raw token ids, JSON serialized + else if (text.startsWith('[') && text.endsWith(']')) { + try { + const tokens = JSON.parse(text); + + if (Array.isArray(tokens) && tokens.every(t => Number.isInteger(t))) { + result.push(getBiasObject(entry.value, tokens)); + } else { + throw new Error('Not an array of integers'); + } + } catch (err) { + console.log(`Failed to parse logit bias token list: ${text}`, err); + } + } + + // Text with a leading space + else { + const biasText = ` ${text}`; + const tokens = getTextTokens(tokenizerType, biasText); + result.push(getBiasObject(entry.value, tokens)); + } + } + } + + return result; } /** From 8bf679cba278ac7e4337b3ac420441492f96db14 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sun, 27 Aug 2023 19:24:28 +0300 Subject: [PATCH 10/11] #1033 Promt => prompt --- public/script.js | 72 +++++++++++++++++----------------- public/scripts/nai-settings.js | 4 +- 2 files changed, 38 insertions(+), 38 deletions(-) diff --git a/public/script.js b/public/script.js index 52dfcbbb8..66a8f0778 100644 --- a/public/script.js +++ b/public/script.js @@ -327,7 +327,7 @@ let firstRun = false; const default_ch_mes = "Hello"; let count_view_mes = 0; -let generatedPromtCache = ""; +let generatedPromptCache = ""; let generation_started = new Date(); let characters = []; let this_chid; @@ -1445,7 +1445,7 @@ function addOneMessage(mes, { type = "normal", insertAfter = null, scroll = true var avatarImg = getUserAvatar(user_avatar); const isSystem = mes.is_system; const title = mes.title; - generatedPromtCache = ""; + generatedPromptCache = ""; //for non-user mesages if (!mes["is_user"]) { @@ -2119,7 +2119,7 @@ class StreamingProcessor { activateSendButtons(); showSwipeButtons(); setGenerationProgress(0); - generatedPromtCache = ''; + generatedPromptCache = ''; //console.log("Generated text size:", text.length, text) @@ -2621,13 +2621,13 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, const originalType = type; runGenerate(cyclePrompt); - async function runGenerate(cycleGenerationPromt = '') { + async function runGenerate(cycleGenerationPrompt = '') { if (!dryRun) { is_send_press = true; } - generatedPromtCache += cycleGenerationPromt; - if (generatedPromtCache.length == 0 || type === 'continue') { + generatedPromptCache += cycleGenerationPrompt; + if (generatedPromptCache.length == 0 || type === 'continue') { if (main_api === 'openai') { generateOpenAIPromptCache(); } @@ -2657,7 +2657,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, let mesExmString = ''; - function setPromtString() { + function setPromptString() { if (main_api == 'openai') { return; } @@ -2728,26 +2728,26 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, return promptCache; } - function checkPromtSize() { + function checkPromptSize() { console.debug('---checking Prompt size'); - setPromtString(); + setPromptString(); const prompt = [ storyString, mesExmString, mesSend.join(''), - generatedPromtCache, + generatedPromptCache, allAnchors, quiet_prompt, ].join('').replace(/\r/gm, ''); - let thisPromtContextSize = getTokenCount(prompt, power_user.token_padding); + let thisPromptContextSize = getTokenCount(prompt, power_user.token_padding); - if (thisPromtContextSize > this_max_context) { //if the prepared prompt is larger than the max context size... + if (thisPromptContextSize > this_max_context) { //if the prepared prompt is larger than the max context size... if (count_exm_add > 0) { // ..and we have example mesages.. count_exm_add--; // remove the example messages... - checkPromtSize(); // and try agin... + checkPromptSize(); // and try agin... } else if (mesSend.length > 0) { // if the chat history is longer than 0 mesSend.shift(); // remove the first (oldest) chat entry.. - checkPromtSize(); // and check size again.. + checkPromptSize(); // and check size again.. } else { //end console.debug(`---mesSend.length = ${mesSend.length}`); @@ -2755,12 +2755,12 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, } } - if (generatedPromtCache.length > 0 && main_api !== 'openai') { - console.debug('---Generated Prompt Cache length: ' + generatedPromtCache.length); - checkPromtSize(); + if (generatedPromptCache.length > 0 && main_api !== 'openai') { + console.debug('---Generated Prompt Cache length: ' + generatedPromptCache.length); + checkPromptSize(); } else { - console.debug('---calling setPromtString ' + generatedPromtCache.length) - setPromtString(); + console.debug('---calling setPromptString ' + generatedPromptCache.length) + setPromptString(); } // Fetches the combined prompt for both negative and positive prompts @@ -2849,8 +2849,8 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, } // Prune from prompt cache if it exists - if (generatedPromtCache.length !== 0) { - generatedPromtCache = cleanupPromptCache(generatedPromtCache); + if (generatedPromptCache.length !== 0) { + generatedPromptCache = cleanupPromptCache(generatedPromptCache); } // Right now, everything is suffixed with a newline @@ -2867,7 +2867,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, afterScenarioAnchor + mesExmString + mesSendString + - generatedPromtCache; + generatedPromptCache; combinedPrompt = combinedPrompt.replace(/\r/gm, ''); @@ -2980,9 +2980,9 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, afterScenarioAnchor: afterScenarioAnchor, examplesString: examplesString, mesSendString: mesSendString, - generatedPromtCache: generatedPromtCache, + generatedPromptCache: generatedPromptCache, promptBias: promptBias, - finalPromt: finalPrompt, + finalPrompt: finalPrompt, charDescription: charDescription, charPersonality: charPersonality, scenarioText: scenarioText, @@ -3058,7 +3058,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, async function onSuccess(data) { if (data.error == 'dryRun') { - generatedPromtCache = ''; + generatedPromptCache = ''; resolve(); return; } @@ -3108,7 +3108,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, } tokens_already_generated = 0; - generatedPromtCache = ""; + generatedPromptCache = ""; const substringStart = originalType !== 'continue' ? magFirst.length : 0; getMessage = message_already_generated.substring(substringStart); } @@ -3126,7 +3126,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, if (getMessage.length > 0) { if (isImpersonate) { $('#send_textarea').val(getMessage).trigger('input'); - generatedPromtCache = ""; + generatedPromptCache = ""; await eventSource.emit(event_types.IMPERSONATE_READY, getMessage); } else if (type == 'quiet') { @@ -3189,7 +3189,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject, } } } else { - generatedPromtCache = ''; + generatedPromptCache = ''; activateSendButtons(); //console.log('runGenerate calling showSwipeBtns'); showSwipeButtons(); @@ -3402,21 +3402,21 @@ function addChatsSeparator(mesSendString) { } } -function appendZeroDepthAnchor(force_name2, zeroDepthAnchor, finalPromt) { +function appendZeroDepthAnchor(force_name2, zeroDepthAnchor, finalPrompt) { const trimBothEnds = !force_name2 && !is_pygmalion; let trimmedPrompt = (trimBothEnds ? zeroDepthAnchor.trim() : zeroDepthAnchor.trimEnd()); - if (trimBothEnds && !finalPromt.endsWith('\n')) { - finalPromt += '\n'; + if (trimBothEnds && !finalPrompt.endsWith('\n')) { + finalPrompt += '\n'; } - finalPromt += trimmedPrompt; + finalPrompt += trimmedPrompt; if (force_name2 || is_pygmalion) { - finalPromt += ' '; + finalPrompt += ' '; } - return finalPromt; + return finalPrompt; } function getMultigenAmount() { @@ -3553,7 +3553,7 @@ function promptItemize(itemizedPrompts, requestedMesId) { } else { //for non-OAI APIs //console.log('-- Counting non-OAI Tokens'); - var finalPromptTokens = getTokenCount(itemizedPrompts[thisPromptSet].finalPromt); + var finalPromptTokens = getTokenCount(itemizedPrompts[thisPromptSet].finalPrompt); var storyStringTokens = getTokenCount(itemizedPrompts[thisPromptSet].storyString) - worldInfoStringTokens; var examplesStringTokens = getTokenCount(itemizedPrompts[thisPromptSet].examplesString); var mesSendStringTokens = getTokenCount(itemizedPrompts[thisPromptSet].mesSendString) @@ -3570,7 +3570,7 @@ function promptItemize(itemizedPrompts, requestedMesId) { //afterScenarioAnchorTokens + //only counts if AN is set to 'after scenario' //zeroDepthAnchorTokens + //same as above, even if AN not on 0 depth promptBiasTokens; //{{}} - //- thisPrompt_padding; //not sure this way of calculating is correct, but the math results in same value as 'finalPromt' + //- thisPrompt_padding; //not sure this way of calculating is correct, but the math results in same value as 'finalPrompt' } if (this_main_api == 'openai') { diff --git a/public/scripts/nai-settings.js b/public/scripts/nai-settings.js index 71c45aadc..fb7328c10 100644 --- a/public/scripts/nai-settings.js +++ b/public/scripts/nai-settings.js @@ -453,7 +453,7 @@ export function getNovelGenerationData(finalPrompt, this_settings, this_amount_g } // Check if the prefix needs to be overriden to use instruct mode -function selectPrefix(selected_prefix, finalPromt) { +function selectPrefix(selected_prefix, finalPrompt) { let useInstruct = false; const clio = nai_settings.model_novel.includes('clio'); const kayra = nai_settings.model_novel.includes('kayra'); @@ -461,7 +461,7 @@ function selectPrefix(selected_prefix, finalPromt) { if (isNewModel) { // NovelAI claims they scan backwards 1000 characters (not tokens!) to look for instruct brackets. That's really short. - const tail = finalPromt.slice(-1500); + const tail = finalPrompt.slice(-1500); useInstruct = tail.includes("}"); return useInstruct ? "special_instruct" : selected_prefix; } From 1a5dbf26032f78e6695e05be5b6a73532422a251 Mon Sep 17 00:00:00 2001 From: RossAscends <124905043+RossAscends@users.noreply.github.com> Date: Mon, 28 Aug 2023 01:40:40 +0900 Subject: [PATCH 11/11] fix MovingUI to respect resizing topBar --- public/scripts/RossAscends-mods.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/public/scripts/RossAscends-mods.js b/public/scripts/RossAscends-mods.js index bf0548b58..cbf9b6a3f 100644 --- a/public/scripts/RossAscends-mods.js +++ b/public/scripts/RossAscends-mods.js @@ -445,7 +445,7 @@ export function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; var height, width, top, left, right, bottom, maxX, maxY, winHeight, winWidth, - topbar, topbarWidth, topBarFirstX, topBarLastX, sheldWidth; + topbar, topbarWidth, topBarFirstX, topBarLastX, topBarLastY, sheldWidth; var elmntName = elmnt.attr('id'); @@ -493,8 +493,9 @@ export function dragElement(elmnt) { topbar = document.getElementById("top-bar") const topbarstyle = getComputedStyle(topbar) topBarFirstX = parseInt(topbarstyle.marginInline) - topbarWidth = parseInt(topbarstyle.width) + topbarWidth = parseInt(topbarstyle.width); topBarLastX = topBarFirstX + topbarWidth; + topBarLastY = parseInt(topbarstyle.height); /*console.log(` winWidth: ${winWidth}, winHeight: ${winHeight} @@ -540,7 +541,7 @@ export function dragElement(elmnt) { } //prevent resizing from top left into the top bar - if (top < 35 && maxX >= topBarFirstX && left <= topBarFirstX + if (top < topBarLastY && maxX >= topBarFirstX && left <= topBarFirstX ) { console.debug('prevent topbar underlap resize') elmnt.css('width', width - 1 + "px"); @@ -575,7 +576,7 @@ export function dragElement(elmnt) { } //prevent underlap with topbar div - if (top < 35 + if (top < topBarLastY && (maxX >= topBarFirstX && left <= topBarFirstX //elmnt is hitting topbar from left side || left <= topBarLastX && maxX >= topBarLastX //elmnt is hitting topbar from right side || left >= topBarFirstX && maxX <= topBarLastX) //elmnt hitting topbar in the middle