Remove chatgpt

This commit is contained in:
Alexey Koshelev
2024-08-12 15:12:30 +03:00
parent a1007f438a
commit ca99e87db4
39 changed files with 0 additions and 51736 deletions

View File

@ -1,13 +0,0 @@
This plugin uses code from the following 3rd party projects.
1. jQuery - Query is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. (http://jquery.com/)
License: MIT License
License File: jQuery.license
2. GPT-3-Encoder is a Javascript BPE Encoder Decoder for GPT-2 / GPT-3. (https://github.com/latitudegames/GPT-3-Encoder/)
License: MIT
License File: GPT-3-Encoder.license

View File

@ -1,17 +0,0 @@
## Overview
The ChatGPT API can be applied to virtually any task that involves understanding or generating natural language or code.
The plugin uses the [OpenAI](https://openai.com/) engine.
It is called "ChatGPT" in the interface and isn't installed by default in cloud, [self-hosted](https://github.com/ONLYOFFICE/DocumentServer) and [desktop version](https://github.com/ONLYOFFICE/DesktopEditors) of ONLYOFFICE editors.
## How to use
1. Find the plugin in the Plugins tab.
2. Open settings page and enter your OpenAI Api key and click the "Save" button.
3. Start the plugin.
4. Select any text into a document and press right mouse button.
5. Choose some of several options: "Text analysis", "Word analysis", "Translate" or "Generate image from text".
If you need more information about how to use or write your own plugin, please see this https://api.onlyoffice.com/plugin/basic

View File

@ -1,57 +0,0 @@
<!--
(c) Copyright Ascensio System SIA 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>OpenAI</title>
<script type="text/javascript" src="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins.js"></script>
<script type="text/javascript" src="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript" src="scripts/desktop.js"></script>
<script type="text/javascript" src="vendor/GPT-3-Encoder/encoder.js"></script>
<script type="text/javascript" src="scripts/chat.js"></script>
<link rel="stylesheet" href="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins.css">
<link rel="stylesheet" href="./resources/css/styles.css">
</head>
<body style="display: flex;">
<div class="chat_window">
<div class="form-control messages" id="chat"></div>
<div id="tokens_info" class="tokens_info">
<div class="form-control div_title_chat hidden">
<span class="i18n">Maximum 4000 tokens are available.</span>
<br>
<span class="i18n">For work with this model we should save chat history and sent it into a request.</span>
<span class="i18n">But we have a limit on the number of tokens in the request.</span>
<span class="i18n">That's why sometimes you should clear your chat history.</span>
<div class="div_tokens_info">
<button id="clear_history" style="margin-top: 5px;" class="form-control btn-text-default i18n">Clear history</button>
</div>
</div>
<div class="div_tokens_info">
<span class="i18n">Tokens in the request about: </span>
<span id="cur_tokens">0</span>
</div>
<div class="div_tokens_info">
<span class="i18n">Total tokens are used in last request: </span>
<span id="total_tokens">0</span>
</div>
</div>
<textarea id="message" class="form-control" spellcheck="false"></textarea>
</div>
</body>
</html>

View File

@ -1,72 +0,0 @@
{
"name" : "ChatGPT",
"guid" : "asc.{FE8A04AC-D8C2-4DE9-9C03-3DD5E831721E}",
"variations" : [
{
"description" : "ChatGPT",
"url" : "index.html",
"icons" : [ "resources/light/icon.png", "resources/light/icon@2x.png" ],
"icons2": [
{
"style" : "light",
"100%": {
"normal": "resources/light/icon.png"
},
"125%": {
"normal": "resources/light/icon@1.25x.png"
},
"150%": {
"normal": "resources/light/icon@1.5x.png"
},
"175%": {
"normal": "resources/light/icon@1.75x.png"
},
"200%": {
"normal": "resources/light/icon@2x.png"
}
},
{
"style" : "dark",
"100%": {
"normal": "resources/dark/icon.png"
},
"125%": {
"normal": "resources/dark/icon@1.25x.png"
},
"150%": {
"normal": "resources/dark/icon@1.5x.png"
},
"175%": {
"normal": "resources/dark/icon@1.75x.png"
},
"200%": {
"normal": "resources/dark/icon@2x.png"
}
}
],
"isViewer" : false,
"EditorsSupport" : ["word"],
"isVisual" : false,
"isModal" : false,
"isInsideMode" : false,
"isSystem" : true,
"initDataType" : "none",
"isUpdateOleOnResize" : false,
"events": ["onContextMenuShow", "onContextMenuClick"],
"store": {
"background": {
"light" : "linear-gradient(90deg, #F9B6FF 0%, #E370EE 102.01%)",
"dark" : "linear-gradient(90deg, #F9B6FF 0%, #E370EE 102.01%)"
},
"screenshots" : [],
"icons" : {
"light" : "resources/store/icons",
"dark" : "resources/store/icons"
},
"categories": ["specAbilities", "work", "recommended"]
}
}
]
}

View File

@ -1,30 +0,0 @@
<!--
(c) Copyright Ascensio System SIA 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>ChatGPT</title>
<script type="text/javascript" src="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins.js"></script>
<script type="text/javascript" src="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins-ui.js"></script>
<link rel="stylesheet" href="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins.css">
<script type="text/javascript" src="scripts/desktop.js"></script>
<script type="text/javascript" src="vendor/GPT-3-Encoder/encoder.js"></script>
<script type="text/javascript" src="scripts/code.js"></script>
</head>
<body>
</body>
</html>

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 AIDungeon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,20 +0,0 @@
Copyright (c) 2009 John Resig, http://jquery.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,83 +0,0 @@
html, body {
width: 100%;
height: 100%;
margin: 0px !important;
}
.loader {
margin: 0 !important;
position: absolute;
right: 0;
top: 0;
width: 100%;
height: 100% !important;
background-color: rgba(128, 128, 128, 0.5);
}
.form {
margin: 10px;
display: flex;
flex-flow: row;
justify-content: center;
align-items: center;
}
input {
flex: 1;
}
.info {
margin: 10px;
}
.err-message {
color: red;
}
.chat_window {
display: flex;
flex-direction: column;
margin: 5px;
flex: 1;
}
.messages {
flex: 1;
margin-bottom: 10px;
display: flex;
flex-direction: column;
overflow: auto;
}
.span_message {
display: flex;
align-items: center;
justify-content: center;
margin: 5px 10px;
width: fit-content;
height: fit-content;
}
.user_message {
display: flex;
justify-content: end;
}
.tokens_info {
margin: 5px 0;
}
.div_tokens_info {
text-align: end;
}
.div_title_chat {
position: absolute;
z-index: 1;
height: fit-content;
padding: 8px 5px;
right: 5px;
left: 5px;
top: 250px;
overflow-wrap: anywhere;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 645 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 809 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1013 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

View File

@ -1,174 +0,0 @@
/**
*
* (c) Copyright Ascensio System SIA 2020
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
(function(window, undefined) {
const url = 'https://api.openai.com/v1/chat/completions';
const apiKey = localStorage.getItem('OpenAIApiKey');
const maxTokens = 4000;
const settings = {
model: 'gpt-3.5-turbo',
messages: []
};
let interval = null;
let tokenTimeot = null;
let modalTimeout = null;
window.Asc.plugin.init = function() {
document.getElementById('message').onkeydown = function(e) {
if ( (e.ctrlKey || e.metaKey) && e.key === 'Enter') {
let value = e.target.value.trim();
if (value.length) {
createMessage(e.target.value.trim(), 1);
e.target.value = '';
document.getElementById('cur_tokens').innerText = 0;
}
}
};
document.getElementById('message').oninput = function(event) {
if (tokenTimeot) {
clearTimeout(tokenTimeot);
tokenTimeot = null;
}
tokenTimeot = setTimeout(function() {
let text = event.target.value.trim();
let tokens = window.Asc.OpenAIEncode(text);
document.getElementById('cur_tokens').innerText = tokens.length;
}, 250);
};
document.getElementById('tokens_info').addEventListener('mouseenter', function (event) {
event.target.children[0].classList.remove('hidden');
if (modalTimeout) {
clearTimeout(modalTimeout);
modalTimeout = null;
}
});
document.getElementById('tokens_info').addEventListener('mouseleave', function (event) {
modalTimeout = setTimeout(function() {
event.target.children[0].classList.add('hidden');
}, 100)
});
document.getElementById('clear_history').onclick = function() {
document.getElementById('chat').innerHTML = '';
settings.messages = [];
document.getElementById('total_tokens').classList.remove('err-message');
document.getElementById('total_tokens').innerText = 0;
};
};
function createMessage(text, type) {
let chat = document.getElementById('chat');
let message = type ? document.createElement('div') : document.getElementById('loading');
let textMes = document.createElement('span');
textMes.classList.add('form-control', 'span_message');
textMes.innerText = text;
message.appendChild(textMes);
chat.scrollTop = chat.scrollHeight;
chat.appendChild(message);
if (type) {
message.classList.add('user_message');
sendMessage(text);
} else {
message.id = '';
}
};
function sendMessage(text) {
createLoader();
settings.messages.push({role: 'user', content: text});
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + apiKey
},
body: JSON.stringify(settings),
})
.then(function(response) {
return response.json()
})
.then(function(data) {
if (data.error)
throw data.error
let text = data.choices[0].message.content;
settings.messages.push({role: data.choices[0].message.role, content: text});
destroyLoader();
// to to add check for max tokens length
createMessage(text, 0);
document.getElementById('total_tokens').innerText = data.usage.total_tokens;
if (data.usage.total_tokens >= maxTokens)
document.getElementById('total_tokens').classList.add('err-message');
})
.catch(function(error) {
console.error('Error:', error);
destroyLoader();
});
};
function createError(error) {
document.getElementById('err_message').innerText = error.message;
console.error(error);
};
function createLoader() {
let chat = document.getElementById('chat');
let message = document.createElement('div');
let loading = document.createElement('span');
message.id = 'loading';
loading.classList.add('form-control', 'span_message');
loading.innerText='.';
message.appendChild(loading);
chat.appendChild(message);
chat.scrollTop = chat.scrollHeight;
interval = setInterval(() => {
let text = loading.innerText;
text = text.length > 5 ? '.' : text + '.';
loading.innerText = text;
}, 500);
};
function destroyLoader() {
clearInterval(interval);
interval = null;
document.getElementById('loading').innerHTML = '';
return;
};
window.Asc.plugin.onTranslate = function() {
let elements = document.querySelectorAll('.i18n');
elements.forEach(function(element) {
element.innerText = window.Asc.plugin.tr(element.innerText);
});
};
window.Asc.plugin.onThemeChanged = function(theme) {
window.Asc.plugin.onThemeChangedBase(theme);
};
/* EXAMPLE:
window.Asc.plugin.attachEvent("onPluginMessage", function(data) {
console.log(data);
});
window.Asc.plugin.sendToPlugin("onWindowMessage", {});
*/
})(window, undefined);

View File

@ -1,642 +0,0 @@
/**
*
* (c) Copyright Ascensio System SIA 2020
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
(function(window, undefined){
let ApiKey = '';
let bHasKey = false;
const model = 'text-davinci-003';
const maxLen = 4000;
let loadingPhrase = 'Loading...';
let thesaurusCounter = 0;
let settingsWindow = null;
let chatWindow = null;
let imgsize = null;
window.Asc.plugin.init = function() {};
function checkApiKey() {
ApiKey = localStorage.getItem('OpenAIApiKey') || '';
if (!ApiKey.length) {
console.error(new Error('Please enter Api key!'));
bHasKey = false;
} else {
bHasKey = true;
}
};
function getContextMenuItems(options) {
checkApiKey();
let settings = {
guid: window.Asc.plugin.guid,
items: [
{
id : 'ChatGPT',
text : generatText('ChatGPT'),
items : []
}
]
};
if (bHasKey)
{
switch (options.type)
{
case 'Target':
{
settings.items[0].items.push({
id : 'onMeaningT',
text : generatText('Explain text in comment')
});
break;
}
case 'Selection':
{
settings.items[0].items.push(
{
id : 'TextAnalysis',
text : generatText('Text analysis'),
items : [
{
id : 'onSummarize',
text : generatText('Summarize')
},
{
id : 'onKeyWords',
text : generatText('Keywords')
},
]
},
{
id : 'Tex Meaning',
text : generatText('Word analysis'),
items : [
{
id : 'onMeaningS',
text : generatText('Explain text in comment')
},
{
id : 'onMeaningLinkS',
text : generatText('Explain text in hyperlink')
}
]
},
{
id : 'TranslateText',
text : generatText('Translate'),
items : [
{
id : 'onFrenchTr',
text : generatText('Translate to French')
},
{
id : 'onGermanTr',
text : generatText('Translate to German')
}
]
},
{
id : 'OnGenerateImage',
text : generatText('Generate image from text')
}
);
break;
}
case 'Image':
case 'Shape':
{
settings.items[0].items.push({
id : 'onImgVar',
text : generatText('Generate image varion')
});
break;
}
default:
break;
}
settings.items[0].items.push({
id : 'onChat',
text : generatText('Chat'),
separator: true
});
}
settings.items[0].items.push({
id : 'onSettings',
text : generatText('Settings'),
separator: true
});
return settings;
}
window.Asc.plugin.attachEvent('onContextMenuShow', function(options) {
// todo: change key validation
if (!options)
return;
this.executeMethod('AddContextMenuItem', [getContextMenuItems(options)]);
if (bHasKey && options.type === "Target")
{
window.Asc.plugin.executeMethod('GetCurrentWord', null, function(text) {
if (text && text.length > 1) {
thesaurusCounter++;
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 10, true);
}
});
}
});
function generatText(text) {
let lang = window.Asc.plugin.info.lang.substring(0,2);
return {
en: text,
[lang]: window.Asc.plugin.tr(text)
}
};
window.Asc.plugin.attachContextMenuClickEvent('onSettings', function() {
let location = window.location;
let start = location.pathname.lastIndexOf('/') + 1;
let file = location.pathname.substring(start);
// default settings for modal window (I created separate settings, because we have many unnecessary field in plugin variations)
let variation = {
url : location.href.replace(file, 'settings.html'),
description : window.Asc.plugin.tr('Settings'),
isVisual : true,
buttons : [],
isModal : true,
EditorsSupport : ["word"],
buttons : [],
size : [ 592, 100 ]
};
if (!settingsWindow) {
settingsWindow = new window.Asc.PluginWindow();
}
settingsWindow.show(variation);
});
window.Asc.plugin.attachContextMenuClickEvent('onChat', function() {
let location = window.location;
let start = location.pathname.lastIndexOf('/') + 1;
let file = location.pathname.substring(start);
// default settings for modal window (I created separate settings, because we have many unnecessary field in plugin variations)
let variation = {
url : location.href.replace(file, 'chat.html'),
description : window.Asc.plugin.tr('ChatGPT'),
isVisual : true,
buttons : [],
isModal : true,
EditorsSupport : ["word"],
buttons : [],
size : [ 400, 400 ]
};
if (!chatWindow) {
chatWindow = new window.Asc.PluginWindow();
chatWindow.attachEvent("onWindowMessage", function(data){
console.log(data);
});
}
chatWindow.show(variation);
});
window.Asc.plugin.attachContextMenuClickEvent('onMeaningT', function() {
window.Asc.plugin.executeMethod('GetCurrentWord', null, function(text) {
if (text === '') {
console.error('No word in this position.')
} else {
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 9);
}
});
});
window.Asc.plugin.attachContextMenuClickEvent('onSummarize', function() {
window.Asc.plugin.executeMethod('GetSelectedText', null, function(text) {
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 1);
});
});
window.Asc.plugin.attachContextMenuClickEvent('onKeyWords', function() {
window.Asc.plugin.executeMethod('GetSelectedText', null, function(text) {
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 2);
});
});
window.Asc.plugin.attachContextMenuClickEvent('onMeaningS', function() {
window.Asc.plugin.executeMethod('GetSelectedText', null, function(text) {
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 3);
});
});
window.Asc.plugin.attachContextMenuClickEvent('onMeaningLinkS', function() {
window.Asc.plugin.executeMethod('GetSelectedText', null, function(text) {
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 4);
});
});
window.Asc.plugin.attachContextMenuClickEvent('onFrenchTr', function() {
window.Asc.plugin.executeMethod('GetSelectedText', null, function(text) {
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 6);
});
});
window.Asc.plugin.attachContextMenuClickEvent('onGermanTr', function() {
window.Asc.plugin.executeMethod('GetSelectedText', null, function(text) {
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 7);
});
});
window.Asc.plugin.attachContextMenuClickEvent('onRandomImage', function() {
let text = 'Get a random image as html tag.';
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 5);
});
window.Asc.plugin.attachContextMenuClickEvent('OnGenerateImage', function() {
window.Asc.plugin.executeMethod('GetSelectedText', null, function(text) {
let tokens = window.Asc.OpenAIEncode(text);
createSettings(text, tokens, 8);
});
});
window.Asc.plugin.attachContextMenuClickEvent('onThesaurus', function(data) {
window.Asc.plugin.executeMethod('ReplaceCurrentWord', [data]);
});
window.Asc.plugin.attachContextMenuClickEvent('onImgVar', function() {
window.Asc.plugin.executeMethod('GetImageDataFromSelection', null, function(data) {
// todo разобраться с размера картинки
createSettings(data, 0, 11);
});
});
function createSettings(text, tokens, type, isNoBlockedAction) {
let url;
let settings = {
model : model,
max_tokens : maxLen - tokens.length
};
if (settings.max_tokens < 100) {
console.error(new Error('This request is too big!'));
return;
}
window.Asc.plugin.executeMethod('StartAction', [isNoBlockedAction ? 'Information' : 'Block', 'ChatGPT: ' + loadingPhrase]);
switch (type) {
case 1:
settings.prompt = `Summarize this text: '${text}'`;
url = 'https://api.openai.com/v1/completions';
break;
case 2:
settings.prompt = `Get Key words from this text: '${text}'`;
url = 'https://api.openai.com/v1/completions';
break;
case 3:
settings.prompt = `What does it mean '${text}' ?`;
url = 'https://api.openai.com/v1/completions';
break;
case 4:
settings.prompt = `Give a link to the explanation of the word '${text}'`;
url = 'https://api.openai.com/v1/completions';
break;
case 5:
settings.prompt = text;
url = 'https://api.openai.com/v1/completions';
break;
case 6:
settings.prompt = `Translate in to Franch: '${text}'`;
url = 'https://api.openai.com/v1/completions';
break;
case 7:
settings.prompt = `Translate in to German: '${text}'`;
url = 'https://api.openai.com/v1/completions';
break;
case 8:
delete settings.model;
delete settings.max_tokens;
settings.prompt = `Generate image: '${text}'`;
settings.n = 1;
settings.size = '256x256';
settings.response_format = 'b64_json';
imgsize = {width: 256, height: 256};
url = 'https://api.openai.com/v1/images/generations';
break;
case 9:
settings.prompt = `What does it mean '${text}' ?`;
url = 'https://api.openai.com/v1/completions';
break;
case 10:
settings.prompt = `Give synonyms for the word '${text}' as javascript array`;
url = 'https://api.openai.com/v1/completions';
break;
case 11:
imageToBlob(text)
.then(function(obj) {
url = 'https://api.openai.com/v1/images/variations';
console.log(obj);
const formdata = new FormData();
formdata.append('image', obj.blob);
formdata.append('size', obj.size.str);
formdata.append('n', 1);// Number.parseInt(elements.inpTopSl.value));
formdata.append('response_format', "b64_json");
fetchData(formdata, url, type, isNoBlockedAction);
});
break;
}
if (type !== 11)
fetchData(settings, url, type, isNoBlockedAction);
};
function fetchData(settings, url, type, isNoBlockedAction) {
let header = {
'Authorization': 'Bearer ' + ApiKey
};
if (type < 11) {
header['Content-Type'] = 'application/json';
}
fetch(url, {
method: 'POST',
headers: header,
body: (type < 11 ? JSON.stringify(settings) : settings),
})
.then(function(response) {
return response.json()
})
.then(function(data) {
if (data.error)
throw data.error
processResult(data, type, isNoBlockedAction);
})
.catch(function(error) {
console.error(error);
window.Asc.plugin.executeMethod('EndAction', [isNoBlockedAction ? 'Information' : 'Block', 'ChatGPT: ' + loadingPhrase]);
});
};
function processResult(data, type, isNoBlockedAction) {
window.Asc.plugin.executeMethod('EndAction', [isNoBlockedAction ? 'Information' : 'Block', 'ChatGPT: ' + loadingPhrase]);
let text, start, end, img;
Asc.scope = {};
switch (type) {
case 1:
Asc.scope.data = data.choices[0].text.split('\n\n');
window.Asc.plugin.callCommand(function() {
let oDocument = Api.GetDocument();
let sumPar = Api.CreateParagraph();
sumPar.AddText('Summarize selected text: ');
oDocument.Push(sumPar);
for(let ind = 0; ind < Asc.scope.data.length; ind++) {
let text = Asc.scope.data[ind];
if (text.length) {
let oParagraph = Api.CreateParagraph();
oParagraph.AddText(text);
oDocument.Push(oParagraph);
}
}
}, false);
break;
case 2:
Asc.scope.data = data.choices[0].text.split('\n\n');
window.Asc.plugin.callCommand(function() {
let oDocument = Api.GetDocument();
for(let ind = 0; ind < Asc.scope.data.length; ind++) {
let text = Asc.scope.data[ind];
if (text.length) {
let oParagraph = Api.CreateParagraph();
oParagraph.AddText(text);
oDocument.Push(oParagraph);
}
}
}, false);
break;
case 3:
text = data.choices[0].text;
Asc.scope.comment = text.startsWith('\n\n') ? text.substring(2) : text;
window.Asc.plugin.callCommand(function() {
let oDocument = Api.GetDocument();
let oRange = oDocument.GetRangeBySelect();
oRange.AddComment(Asc.scope.comment, 'OpenAI');
}, false);
break;
case 4:
text = data.choices[0].text;
start = text.indexOf('htt');
end = text.indexOf(' ', start);
if (end == -1) {
end = text.length;
}
Asc.scope.link = text.slice(start, end);
if (Asc.scope.link) {
window.Asc.plugin.callCommand(function() {
let oDocument = Api.GetDocument();
let oRange = oDocument.GetRangeBySelect();
oRange.AddHyperlink(Asc.scope.link, 'Meaning of the word');
}, false);
}
break;
case 5:
text = data.choices[0].text;
start = text.indexOf('<img');
end = text.indexOf('/>', start);
if (end == -1) {
end = text.length;
}
let link = text.slice(start, end);
if (link) {
window.Asc.plugin.executeMethod('PasteHtml', [link])
}
break;
case 6:
text = data.choices[0].text.startsWith('\n\n') ? data.choices[0].text.substring(2) : data.choices[0].text;
//window.Asc.plugin.executeMethod('PasteText', [text]);
Asc.scope.comment = text;
window.Asc.plugin.callCommand(function() {
let oDocument = Api.GetDocument();
let oRange = oDocument.GetRangeBySelect();
oRange.AddComment(Asc.scope.comment, 'OpenAI');
}, false);
break;
case 7:
text = data.choices[0].text.startsWith('\n\n') ? data.choices[0].text.substring(2) : data.choices[0].text;
window.Asc.plugin.executeMethod('PasteText', [text]);
break;
case 8:
let url = (data.data && data.data[0]) ? data.data[0].b64_json : null;
if (url) {
Asc.scope.url = /^data\:image\/png\;base64/.test(url) ? url : `data:image/png;base64,${url}`;
window.Asc.plugin.callCommand(function() {
let oDocument = Api.GetDocument();
let oParagraph = Api.CreateParagraph();
let oDrawing = Api.CreateImage(Asc.scope.url, 25.5 * 36000, 25.5 * 36000);
oParagraph.AddDrawing(oDrawing);
oDocument.Push(oParagraph);
}, false);
}
break;
case 9:
text = data.choices[0].text;
Asc.scope.comment = text.startsWith('\n\n') ? text.substring(2) : text;
window.Asc.plugin.callCommand(function() {
var oDocument = Api.GetDocument();
Api.AddComment(oDocument, Asc.scope.comment, 'OpenAI');
}, false);
break;
case 10:
thesaurusCounter--;
if (0 < thesaurusCounter)
return;
text = data.choices[0].text;
let startPos = text.indexOf("[");
let endPos = text.indexOf("]");
if (-1 === startPos || -1 === endPos || startPos > endPos)
return;
text = text.substring(startPos, endPos + 1);
let arrayWords = eval(text);
let items = getContextMenuItems({ type : "Target" });
let itemNew = {
id : "onThesaurusList",
text : generatText("Thesaurus"),
items : []
};
for (let i = 0; i < arrayWords.length; i++)
{
itemNew.items.push({
id : 'onThesaurus',
data : arrayWords[i],
text : arrayWords[i]
}
);
}
items.items[0].items.unshift(itemNew);
window.Asc.plugin.executeMethod('UpdateContextMenuItem', [items]);
break;
case 11:
img = (data.data && data.data[0]) ? data.data[0].b64_json : null;
if (img) {
let sImageSrc = /^data\:image\/png\;base64/.test(img) ? img : `data:image/png;base64,${img}`;
let oImageData = {
"src": sImageSrc,
"width": imgsize.width,
"height": imgsize.height
};
imgsize = null;
window.Asc.plugin.executeMethod ("PutImageDataToSelection", [oImageData]);
}
break;
}
};
window.Asc.plugin.button = function(id, windowId) {
if (!settingsWindow && !chatWindow)
return;
if (windowId) {
switch (id)
{
case -1:
default:
// if we use close, it is unregister this window and we won't be able to receive messages from this window
// window.Asc.plugin.init();
// settingsWindow.close();
// settingsWindow = null;
window.Asc.plugin.executeMethod('CloseWindow', [windowId]);
}
}
};
window.Asc.plugin.onTranslate = function() {
loadingPhrase = window.Asc.plugin.tr(loadingPhrase);
};
function imageToBlob(img) {
return new Promise(function(resolve) {
const image = new Image();
image.onload = function() {
const img_size = {width: image.width, height: image.height};
const canvas_size = normalizeImageSize(img_size);
const draw_size = canvas_size.width > image.width ? img_size : canvas_size;
let canvas = document.createElement('canvas');
canvas.width = canvas_size.width;
canvas.height = canvas_size.height;
canvas.getContext('2d').drawImage(image, 0, 0, draw_size.width, draw_size.height*image.height/image.width);
imgsize = img_size;
canvas.toBlob(function(blob) {resolve({blob, size: canvas_size})}, 'image/png');
};
image.src = img.src;
});
};
function normalizeImageSize (size) {
let width = 0, height = 0;
if ( size.width > 750 || size.height > 750 )
width = height = 1024;
else if ( size.width > 375 || size.height > 350 )
width = height = 512;
else width = height = 256;
return {width: width, height: height, str: `${width}x${height}`}
};
})(window, undefined);

View File

@ -1,46 +0,0 @@
(function(){
function internal_isLocal() {
if (window.navigator && window.navigator.userAgent.toLowerCase().indexOf("ascdesktopeditor") < 0)
return false;
if (window.location && window.location.protocol == "file:")
return true;
if (window.document && window.document.currentScript && 0 == window.document.currentScript.src.indexOf("file:///"))
return true;
return false;
}
if (internal_isLocal())
{
window.fetch = function(url, obj) {
function TextResponse(text) {
this.textResponse = text;
this.text = function() { return this.textResponse; };
this.json = function() { return JSON.parse(this.textResponse); };
};
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(obj.method, url, true);
for (let h in obj.headers)
if (obj.headers.hasOwnProperty(h))
xhr.setRequestHeader(h, obj.headers[h]);
xhr.onload = function ()
{
if (this.status == 200 || this.status == 0)
resolve(new TextResponse(this.response));
};
xhr.onerror = function ()
{
reject(new TextResponse(this.response));
};
xhr.send(obj.body);
});
};
}
})();

View File

@ -1,106 +0,0 @@
/**
*
* (c) Copyright Ascensio System SIA 2020
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
(function(window, undefined) {
let loader = null;
let errMessage = 'Invalid Api key.';
let loadMessage = 'Loading...';
let isInited = false;
window.addEventListener("DOMContentLoaded", init);
window.Asc.plugin.init = init;
function init() {
if (isInited)
return;
isInited = true;
document.getElementById('inp_key').value = localStorage.getItem('OpenAIApiKey') || '';
document.getElementById('btn_save').onclick = function() {
document.getElementById('err_message').innerText = '';
document.getElementById('success_message').classList.add('hidden');
localStorage.removeItem('OpenAIApiKey');
let key = document.getElementById('inp_key').value.trim();
if (key.length) {
createLoader();
// check api key by fetching models
fetch('https://api.openai.com/v1/models', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + key
}
}).
then(function(response) {
if (response.ok) {
localStorage.setItem('OpenAIApiKey', key);
document.getElementById('success_message').classList.remove('hidden');
} else {
createError(new Error(errMessage));
}
})
.catch(function(error) {
createError(error);
})
.finally(function(){
destroyLoader();
});
} else {
createError(new Error(errMessage));
}
}
};
function createError(error) {
document.getElementById('err_message').innerText = error.message;
console.error(error);
};
function createLoader() {
if (!window.Asc.plugin.theme)
window.Asc.plugin.theme = {type: 'light'};
$('#loader-container').removeClass( "hidden" );
loader && (loader.remove ? loader.remove() : $('#loader-container')[0].removeChild(loader));
loader = showLoader($('#loader-container')[0], loadMessage);
};
function destroyLoader() {
$('#loader-container').addClass( "hidden" )
loader && (loader.remove ? loader.remove() : $('#loader-container')[0].removeChild(loader));
loader = null;
};
window.Asc.plugin.button = function(id) {
this.executeCommand("close", "");
};
window.Asc.plugin.onTranslate = function() {
errMessage = window.Asc.plugin.tr(errMessage);
loadMessage = window.Asc.plugin.tr(loadMessage);
let elements = document.querySelectorAll('.i18n');
elements.forEach(function(element) {
element.innerText = window.Asc.plugin.tr(element.innerText);
})
};
/* EXAMPLE:
window.Asc.plugin.attachEvent("onPluginMessage", function(data) {
console.log(data);
});
window.Asc.plugin.sendToPlugin("onWindowMessage", {});
*/
})(window, undefined);

View File

@ -1,45 +0,0 @@
<!--
(c) Copyright Ascensio System SIA 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Settings</title>
<script type="text/javascript" src="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins.js"></script>
<script type="text/javascript" src="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins.css">
<link rel="stylesheet" href="resources/css/styles.css">
<script type="text/javascript" src="scripts/desktop.js"></script>
<script type="text/javascript" src="scripts/settings.js"></script>
</head>
<body>
<div class="info">
<span class="i18n">For using ChatGPT you should get an API key.</span>
<span class="i18n">Go to</span> <a target="_blank" href="https://beta.openai.com/account/api-keys">OpenAI API keys</a><span>.</span>
<span class="i18n">Create API keys and copy in this field.</span>
</div>
<div class="form">
<input id="inp_key" class="form-control" placeholder="Api key">
<button class="btn-text-default i18n" id="btn_save">Save</button>
</div>
<div class="info">
<span id="err_message" class="err-message"></span>
<span id="success_message" class="header hidden i18n">Api key saved successfully.</span>
</div>
<div id="loader-container" class="asc-loader-container loader hidden"></div>
</body>
</html>

View File

@ -1,27 +0,0 @@
{
"For using ChatGPT you should get an API key." : "Pro použití ChatGPT byste měli získat klíč API..",
"Create API keys and copy in this field." : "Vytvořte klíče API a zkopírujte do tohoto pole.",
"Go to" : "Přejít na",
"Loading..." : "Načítání...",
"Api key saved successfully." : "Klíč Api byl úspěšně uložen.",
"Save" : "Uložit",
"Text analysis": "Analýza textu",
"Summarize": "Shrnout",
"Keywords": "Slovo",
"Word analysis": "Slovní analýza",
"Explain text in comment": "Vysvětlení v komentáři",
"Explain text in hyperlink": "Vysvětlení v hypertextovém odkazu",
"Translate": "Přeložit",
"Translate to French": "Přeložit do francouzštiny",
"Translate to German": "Přeložit do němčiny",
"Generate image from text": "Generovat obrázek z textu",
"Settings": "Nastavení",
"Maximum 4000 tokens are available." : "K dispozici je maximálně 4000 žetonů.",
"For work with this model we should save chat history and sent it into a request." : "Pro práci s tímto modelem bychom měli uložit historii chatu a odeslat ji do požadavku.",
"But we have a limit on the number of tokens in the request." : "Ale máme limit na počet žetonů v žádosti.",
"That's why sometimes you should clear your chat history." : "Proto byste někdy měli vymazat historii chatu.",
"Clear history" : "Vymazat historii",
"Tokens in the request about: " : "Tokeny v žádosti o: ",
"Total tokens are used in last request: " : "Celkové tokeny jsou použity v posledním požadavku: ",
"Chat" : "Chata"
}

View File

@ -1,27 +0,0 @@
{
"For using ChatGPT you should get an API key." : "Für die Verwendung von ChatGPT sollten Sie einen API-Schlüssel erhalten.",
"Create API keys and copy in this field." : "Erstellen Sie API-Schlüssel und kopieren Sie sie in dieses Feld.",
"Go to" : "Navigieren Sie zu",
"Loading..." : "Laden...",
"Api key saved successfully." : "API-Schlüssel erfolgreich gespeichert.",
"Save" : "Speichern",
"Text analysis": "Textanalyse",
"Summarize": "Zusammenfassen",
"Keywords": "Einsehen",
"Word analysis": "Wortanalyse",
"Explain text in comment": "Text im Kommentar erklären",
"Explain text in hyperlink": "Text im Hyperlink erklären",
"Translate": "Übersetzen",
"Translate to French": "Ins Französische übersetzen",
"Translate to German": "Ins Deutsche übersetzen",
"Generate image from text": "Bild aus Text generieren",
"Settings": "Einstellungen",
"Maximum 4000 tokens are available." : "Maximal 4000 Token sind verfügbar.",
"For work with this model we should save chat history and sent it into a request." : "Für die Arbeit mit diesem Modell sollten wir den Chatverlauf speichern und in eine Anfrage senden.",
"But we have a limit on the number of tokens in the request." : "Wir haben jedoch eine Begrenzung für die Anzahl der Token in der Anfrage.",
"That's why sometimes you should clear your chat history." : "Deshalb sollten Sie manchmal Ihren Chatverlauf löschen.",
"Clear history" : "Verlauf löschen",
"Tokens in the request about: " : "Token in der Anfrage über: ",
"Total tokens are used in last request: " : "Gesamtzahl der Token, die in der letzten Anforderung verwendet wurden: ",
"Chat" : "Chat"
}

View File

@ -1,27 +0,0 @@
{
"For using ChatGPT you should get an API key." : "Para usar ChatGPT, debe obtener una clave API.",
"Create API keys and copy in this field." : "Cree claves de API y cópielas en este campo.",
"Go to" : "Navegue hasta",
"Loading..." : "Carga...",
"Api key saved successfully." : "Clave de Api guardada correctamente.",
"Save" : "Guardar",
"Text analysis": "Análisis de texto",
"Summarize": "Resumir",
"Keywords": "Palabras Clave",
"Word analysis": "Análisis de palabras",
"Explain text in comment": "Explicar el texto en el comentario",
"Explain text in hyperlink": "Explicar texto en hipervínculo",
"Translate": "Traducir",
"Translate to French": "Traducir al Francés",
"Translate to German": "Traducir al Alemán",
"Generate image from text": "Generar imagen a partir de texto",
"Settings": "Ajustes",
"Maximum 4000 tokens are available." : "Hay un máximo de 4000 fichas disponibles.",
"For work with this model we should save chat history and sent it into a request." : "Para trabajar con este modelo, debemos guardar el historial de chat y enviarlo a una solicitud.",
"But we have a limit on the number of tokens in the request." : "Pero tenemos un límite en el número de tokens en la solicitud.",
"That's why sometimes you should clear your chat history." : "Es por eso que a veces debes borrar tu historial de chat.",
"Clear history" : "Borrar historial",
"Tokens in the request about: " : "Tokens en la solicitud acerca de: ",
"Total tokens are used in last request: " : "Total de tokens utilizados en la última solicitud: ",
"Chat" : "Chat"
}

View File

@ -1,27 +0,0 @@
{
"For using ChatGPT you should get an API key." : "Pour utiliser ChatGPT, vous devriez obtenir une clé API.",
"Create API keys and copy in this field." : "Créez des clés API et copiez-les dans ce champ.",
"Go to" : "Naviguer vers",
"Loading..." : "Chargement...",
"Api key saved successfully." : "Clé API enregistrée avec succès.",
"Save" : "Enregistrer",
"Text analysis": "Analyse de texte",
"Summarize": "Résumer",
"Keywords": "Mot",
"Word analysis": "Analyse des mots",
"Explain text in comment": "Explication en commentaire",
"Explain text in hyperlink": "Expliquer le texte en hyperlien",
"Translate": "Traduire",
"Translate to French": "Traduire en Français",
"Translate to German": "Traduire en Allemand",
"Generate image from text": "Générer une image à partir de texte",
"Settings": "Réglages",
"Maximum 4000 tokens are available." : "Un maximum de 4000 jetons sont disponibles.",
"For work with this model we should save chat history and sent it into a request." : "Pour travailler avec ce modèle, nous devons enregistrer l'historique des discussions et l'envoyer dans une demande.",
"But we have a limit on the number of tokens in the request." : "Mais nous avons une limite sur le nombre de jetons dans la demande.",
"That's why sometimes you should clear your chat history." : "C'est pourquoi vous devez parfois effacer votre historique de discussion.",
"Clear history" : "Effacer l'historique",
"Tokens in the request about: " : "Jetons dans la demande à propos: ",
"Total tokens are used in last request: " : "Le nombre total de jetons est utilisé dans la dernière demande: ",
"Chat" : "Chat"
}

View File

@ -1,7 +0,0 @@
[
"cs-CS",
"de-DE",
"es-ES",
"fr-FR",
"ru-RU"
]

View File

@ -1,27 +0,0 @@
{
"For using ChatGPT you should get an API key." : "Для использования ChatGPT вы должны получить ключ API.",
"Create API keys and copy in this field." : "Создайте ключи API и скопируйте в это поле.",
"Go to" : "Перейти к",
"Loading..." : "Загрузка...",
"Api key saved successfully." : "Api ключ успешно сохранён.",
"Save" : "Сохранить",
"Text analysis" : "Анализ текста",
"Summarize" : "Резюмировать",
"Keywords" : "Ключевые слова",
"Word analysis" : "Анализ слова",
"Explain text in comment" : "Значение слова в комментарий",
"Explain text in hyperlink" : "Ссылка на значение",
"Translate" : "Перевести",
"Translate to French" : "Перевести на Французкий",
"Translate to German" : "Перевести на Немецкий",
"Generate image from text" : "Создать картинку по тексту",
"Settings" : "Настройки",
"Maximum 4000 tokens are available." : "Максимум 4000 токенов доступно.",
"For work with this model we should save chat history and sent it into a request." : "Для работы с этой моделью мы должны сохранять историю диалога и посылать её в запросе.",
"But we have a limit on the number of tokens in the request." : "Но мы имеем ограничение на количество токенов в запросе.",
"That's why sometimes you should clear your chat history." : "Поэтому иногда вам следует очищать историю чата.",
"Clear history" : "Очистить историю",
"Tokens in the request about: " : "Примерное количество токенов в запросе: ",
"Total tokens are used in last request: " : "Всего токенов использовано в последнем запросе: ",
"Chat" : "Чат"
}

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 AIDungeon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,34 +0,0 @@
# GPT-3-Encoder
Javascript BPE Encoder Decoder for GPT-2 / GPT-3
## About
GPT-2 and GPT-3 use byte pair encoding to turn text into a series of integers to feed into the model. This is a javascript implementation of OpenAI's original python encoder/decoder which can be found [here](https://github.com/openai/gpt-2)
## Install with npm
```
npm install gpt-3-encoder
```
## Usage
Compatible with Node >= 12
```js
const {encode, decode} = require('gpt-3-encoder')
const str = 'This is an example sentence to try encoding out on!'
const encoded = encode(str)
console.log('Encoded this string looks like: ', encoded)
console.log('We can look at each token and what it represents')
for(let token of encoded){
console.log({token, string: decode([token])})
}
const decoded = decode(encoded)
console.log('We can decode it back into:\n', decoded)
```

View File

@ -1,211 +0,0 @@
// This file includes code which was modified from https://github.com/openai/gpt-2
let encoder; // = JSON.parse(fs.readFileSync(path.join(__dirname, './encoder.json')));
let bpe_file; // = fs.readFileSync(path.join(__dirname, './vocabulary.bpe'), 'utf-8');
const pat = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;
const cache = new Map;
let decoder = {};
let byte_decoder = {};
let bpe_merges;
let byte_encoder;
let bpe_ranks;
const vocUrl = './vendor/GPT-3-Encoder/vocabulary.bpe';
const encUrl = './vendor/GPT-3-Encoder/encoder.json';
fetchResources(vocUrl);
fetchResources(encUrl);
function fetchResources(url) {
let flag = url.includes('vocabulary.bpe');
fetch(url, {
method: 'GET'
})
.then(function(response) {
return flag ? response.text() : response.json();
})
.then(function(data) {
if (flag) {
bpe_file = data;
} else {
encoder = data;
}
})
.catch(function(error) {
console.error('Error:', error);
}).finally(function(){
init();
});
};
const range = (x, y) => {
const res = Array.from(Array(y).keys()).slice(x);
return res;
};
const ord = x => {
return x.charCodeAt(0);
};
const chr = x => {
return String.fromCharCode(x);
};
const textEncoder = new TextEncoder("utf-8");
const encodeStr = str => {
return Array.from(textEncoder.encode(str)).map(x => x.toString());
};
const textDecoder = new TextDecoder("utf-8")
const decodeStr = arr => {
return textDecoder.decode(new Uint8Array(arr));
};
const dictZip = (x, y) => {
const result = {};
x.map((_, i) => { result[x[i]] = y[i] });
return result;
};
function bytes_to_unicode() {
const bs = range(ord('!'), ord('~') + 1).concat(range(ord('¡'), ord('¬') + 1), range(ord('®'), ord('ÿ') + 1));
let cs = bs.slice();
let n = 0;
for (let b = 0; b < 2 ** 8; b++) {
if (!bs.includes(b)) {
bs.push(b);
cs.push(2 ** 8 + n);
n = n + 1;
}
}
cs = cs.map(x => chr(x));
const result = {};
bs.map((_, i) => { result[bs[i]] = cs[i] });
return result;
};
function get_pairs(word) {
const pairs = new Set();
let prev_char = word[0];
for (let i = 1; i < word.length; i++) {
const char = word[i];
pairs.add([prev_char, char]);
prev_char = char;
}
return pairs;
};
function init() {
if (encoder === undefined || bpe_file === undefined)
return;
Object.keys(encoder).map(x => { decoder[encoder[x]] = x });
let lines = bpe_file.split('\n');
// bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split("\n")[1:-1]]
bpe_merges = lines.slice(1, lines.length - 1).map(x => {
return x.split(/(\s+)/).filter(function(e) { return e.trim().length > 0 });
})
byte_encoder = bytes_to_unicode();
Object.keys(byte_encoder).map(x => { byte_decoder[byte_encoder[x]] = x });
bpe_ranks = dictZip(bpe_merges, range(0, bpe_merges.length));
};
function bpe(token) {
if (cache.has(token)) {
return cache.get(token);
}
let word = token.split('');
let pairs = get_pairs(word);
if (!pairs) {
return token;
}
while (true) {
const minPairs = {};
Array.from(pairs).map(pair => {
const rank = bpe_ranks[pair];
minPairs[(isNaN(rank) ? 10e10 : rank)] = pair;
})
const bigram = minPairs[Math.min(...Object.keys(minPairs).map(x => {
return parseInt(x);
}))]
if (!(bigram in bpe_ranks)) {
break;
}
const first = bigram[0];
const second = bigram[1];
let new_word = [];
let i = 0;
while (i < word.length) {
const j = word.indexOf(first, i);
if (j === -1) {
new_word = new_word.concat(word.slice(i));
break;
}
new_word = new_word.concat(word.slice(i, j));
i = j;
if (word[i] === first && i < word.length - 1 && word[i + 1] === second) {
new_word.push(first + second);
i = i + 2;
} else {
new_word.push(word[i]);
i = i + 1;
}
}
word = new_word;
if (word.length === 1) {
break;
} else {
pairs = get_pairs(word);
}
}
word = word.join(' ');
cache.set(token, word);
return word;
};
function encode(text) {
let bpe_tokens = [];
const matches = Array.from(text.matchAll(pat)).map(x => x[0]);
for (let token of matches) {
token = encodeStr(token).map(x => {
return byte_encoder[x];
}).join('');
const new_tokens = bpe(token).split(' ').map(x => encoder[x]);
bpe_tokens = bpe_tokens.concat(new_tokens);
}
return bpe_tokens;
};
function decode(tokens) {
let text = tokens.map(x => decoder[x]).join('');
text = decodeStr(text.split('').map(x => byte_decoder[x]));
return text;
};
window.Asc.OpenAIEncode = encode;
window.Asc.OpenAIDecode = decode;

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff