OpenAI Token Counter for Selected Text

Automatically count tokens of selected text

当前为 2024-01-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name OpenAI Token Counter for Selected Text
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.1
  5. // @description Automatically count tokens of selected text
  6. // @author ChatGPT 4
  7. // @match *://*/*
  8. // @grant none
  9. // @require https://unpkg.com/gpt-tokenizer/dist/cl100k_base.js
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // 创建弹窗
  16. const popup = document.createElement('div');
  17. popup.style.display = 'none';
  18. popup.style.position = 'fixed';
  19. popup.style.right = '20px';
  20. popup.style.bottom = '60px';
  21. popup.style.backgroundColor = '#333';
  22. popup.style.color = '#fff';
  23. popup.style.padding = '10px';
  24. popup.style.borderRadius = '5px';
  25. popup.style.zIndex = '1001';
  26. document.body.appendChild(popup);
  27.  
  28. // 显示token计数结果的函数
  29. function showTokenCount(tokens) {
  30. popup.textContent = `Token count: ${tokens.length}`;
  31. popup.style.display = 'block';
  32. setTimeout(() => { popup.style.display = 'none'; }, 3000); // 3秒后隐藏
  33. }
  34.  
  35. // 计算并显示选中文本的token数量
  36. function countAndShowTokens() {
  37. const text = window.getSelection().toString();
  38. if (text) {
  39. const tokens = GPTTokenizer_cl100k_base.encode(text);
  40. showTokenCount(tokens);
  41. } else {
  42. popup.style.display = 'none'; // 如果没有选中文本,则不显示弹窗
  43. }
  44. }
  45.  
  46. // 为文档添加事件监听器以检测文本选择
  47. document.addEventListener('selectionchange', function() {
  48. countAndShowTokens(); // 当文本被选中时调用该函数
  49. });
  50. })();