OpenAI Token Counter for Selected Text

Automatically count tokens of selected text

目前為 2024-01-10 提交的版本,檢視 最新版本

// ==UserScript==
// @name         OpenAI Token Counter for Selected Text
// @namespace    http://tampermonkey.net/
// @version      1.1
// @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.display = 'none';
    popup.style.position = 'fixed';
    popup.style.right = '20px';
    popup.style.bottom = '60px';
    popup.style.backgroundColor = '#333';
    popup.style.color = '#fff';
    popup.style.padding = '10px';
    popup.style.borderRadius = '5px';
    popup.style.zIndex = '1001';
    document.body.appendChild(popup);

    // 显示token计数结果的函数
    function showTokenCount(tokens) {
        popup.textContent = `Token count: ${tokens.length}`;
        popup.style.display = 'block';
        setTimeout(() => { popup.style.display = 'none'; }, 3000); // 3秒后隐藏
    }

    // 计算并显示选中文本的token数量
    function countAndShowTokens() {
        const text = window.getSelection().toString();
        if (text) {
            const tokens = GPTTokenizer_cl100k_base.encode(text);
            showTokenCount(tokens);
        } else {
            popup.style.display = 'none'; // 如果没有选中文本,则不显示弹窗
        }
    }

    // 为文档添加事件监听器以检测文本选择
    document.addEventListener('selectionchange', function() {
        countAndShowTokens(); // 当文本被选中时调用该函数
    });
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址