Automatically count tokens of selected text
当前为
// ==UserScript==
// @name OpenAI Token Counter for Selected Text
// @namespace http://tampermonkey.net/
// @version 1.2
// @description Automatically count tokens of selected text
// @author ChatGPT 4
// @match *://*/*
// @grant none
// @require https://unpkg.com/gpt-tokenizer/dist/cl100k_base.js
// ==/UserScript==
(function() {
'use strict';
// 创建弹窗
const popup = document.createElement('div');
popup.style.position = 'fixed';
popup.style.right = '20px';
popup.style.bottom = '120px';
popup.style.backgroundColor = '#333';
popup.style.color = '#fff';
popup.style.padding = '10px';
popup.style.borderRadius = '5px';
popup.style.zIndex = '1001';
popup.style.display = 'none';
document.body.appendChild(popup);
// 显示token计数结果的函数
function showTokenCount(tokens) {
popup.textContent = `Token count: ${tokens.length}`;
popup.style.display = 'block';
}
// 隐藏弹窗的函数
function hidePopup() {
popup.style.display = 'none';
}
// 计算并显示选中文本的token数量
function countAndShowTokens() {
const text = window.getSelection().toString();
if (text) {
const tokens = GPTTokenizer_cl100k_base.encode(text);
showTokenCount(tokens);
}
}
// 为文档添加事件监听器以检测文本选择
document.addEventListener('selectionchange', function() {
const text = window.getSelection().toString();
if (text.length > 0) {
countAndShowTokens();
} else {
hidePopup();
}
});
})();