Greasy Fork镜像 支持简体中文。

OpenAI Token Counter for Selected Text

Automatically count tokens of selected text

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

  1. // ==UserScript==
  2. // @name OpenAI Token Counter for Selected Text
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.3
  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 = '120px';
  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. }
  33.  
  34. // 计算并显示选中文本的token数量
  35. function countAndShowTokens() {
  36. const text = window.getSelection().toString();
  37. if (text) {
  38. const tokens = GPTTokenizer_cl100k_base.encode(text);
  39. showTokenCount(tokens);
  40. checkSelection(); // 检查文本是否仍被选中
  41. } else {
  42. popup.style.display = 'none'; // 如果没有选中文本,则不显示弹窗
  43. }
  44. }
  45.  
  46. // 检查是否还有文本被选中
  47. function checkSelection() {
  48. const checkInterval = 500; // 每500ms检查一次
  49. const interval = setInterval(() => {
  50. const currentSelection = window.getSelection().toString();
  51. if (!currentSelection) {
  52. popup.style.display = 'none';
  53. clearInterval(interval); // 停止检查
  54. }
  55. }, checkInterval);
  56. }
  57.  
  58. // 为文档添加事件监听器以检测文本选择
  59. document.addEventListener('selectionchange', function() {
  60. countAndShowTokens(); // 当文本被选中时调用该函数
  61. });
  62. })();

QingJ © 2025

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