OpenAI Token Counter with Draggable Button

Count tokens of selected text with a draggable button

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

  1. // ==UserScript==
  2. // @name OpenAI Token Counter with Draggable Button
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description Count tokens of selected text with a draggable button
  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 button = document.createElement('button');
  17. button.style.position = 'fixed';
  18. button.style.right = '0px';
  19. button.style.bottom = '50%'; // 初始位置在屏幕垂直中间
  20. button.style.zIndex = '1000';
  21. button.style.width = '25px'; // 小一点的正方形
  22. button.style.height = '25px';
  23. button.style.backgroundColor = '#4CAF50';
  24. button.style.border = 'none';
  25. button.style.cursor = 'pointer';
  26. button.style.borderRadius = '5px';
  27. document.body.appendChild(button);
  28.  
  29. // 创建弹窗
  30. const popup = document.createElement('div');
  31. popup.style.display = 'none';
  32. popup.style.position = 'fixed';
  33. popup.style.right = '20px';
  34. popup.style.bottom = '60px';
  35. popup.style.backgroundColor = '#333';
  36. popup.style.color = '#fff';
  37. popup.style.padding = '10px';
  38. popup.style.borderRadius = '5px';
  39. popup.style.zIndex = '1001';
  40. document.body.appendChild(popup);
  41.  
  42. // 显示计数结果
  43. function showTokenCount(tokens) {
  44. popup.textContent = `Token count: ${tokens.length}`;
  45. popup.style.display = 'block';
  46. setTimeout(() => { popup.style.display = 'none'; }, 3000); // 3秒后隐藏
  47. }
  48.  
  49. // 计算 Token 数量
  50. function countTokens() {
  51. const text = window.getSelection().toString();
  52. if (text) {
  53. const tokens = GPTTokenizer_cl100k_base.encode(text);
  54. showTokenCount(tokens);
  55. }
  56. }
  57.  
  58. // 实现按钮的垂直拖动
  59. let isDragging = false;
  60. button.onmousedown = function(event) {
  61. isDragging = true;
  62. let shiftY = event.clientY - button.getBoundingClientRect().top;
  63.  
  64. document.onmousemove = function(event) {
  65. if (isDragging) {
  66. let newTop = event.clientY - shiftY;
  67. button.style.top = newTop + 'px';
  68. }
  69. };
  70.  
  71. document.onmouseup = function() {
  72. document.onmousemove = null;
  73. document.onmouseup = null;
  74. isDragging = false;
  75. };
  76. };
  77.  
  78. button.ondragstart = function() {
  79. return false;
  80. };
  81.  
  82. // 为按钮添加事件监听器
  83. button.addEventListener('click', countTokens);
  84. })();