ChatGPTHelper

1) Real-Time Local Disk Storage: ChatGPTHelper automatically saves all your chat history and predefined prompts on your local disk as you go. 2) No Official History Required: You won't need to fine-tune it with official history data. Your information remains confidential, never used to train the model. 3) Offline Functionality: ChatGPTHelper makes the histtory still available when offline.

当前为 2023-09-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name ChatGPTHelper
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.4
  5. // @description 1) Real-Time Local Disk Storage: ChatGPTHelper automatically saves all your chat history and predefined prompts on your local disk as you go. 2) No Official History Required: You won't need to fine-tune it with official history data. Your information remains confidential, never used to train the model. 3) Offline Functionality: ChatGPTHelper makes the histtory still available when offline.
  6. // @author maple
  7. // @match https://chat.openai.com/*
  8. // @grant GM_xmlhttpRequest
  9. // @license GPL-3.0-or-later
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. const WEBREDIS_ENDPOINT = "http://127.0.0.1:7379";
  16. var thisInHistory = false;
  17. var HistoryPrefix = "HISTORY";
  18. var PromptPrefix = "USERPROMPT";
  19.  
  20. /*---------------------------------History-------------------------------------*/
  21. function load(key, callback) {
  22. key = encodeURIComponent(key);
  23. GM_xmlhttpRequest({
  24. method: "GET",
  25. url: `${WEBREDIS_ENDPOINT}/GET/${key}`,
  26. onload: function(response) {
  27. callback(null, JSON.parse(response.responseText));
  28. },
  29. onerror: function(error) {
  30. callback(error, null);
  31. }
  32. });
  33. }
  34.  
  35. function save(nameprefix, data, callback) {
  36. var strdata;
  37. var dname;
  38. var currentTimestamp = "";
  39. if (Array.isArray(data)) {// history
  40. strdata = JSON.stringify(data.map(function(element) {
  41. return element.innerHTML;
  42. }));
  43. dname = data[0].innerText.substring(0, 50).trim();
  44. var date = new Date();
  45. currentTimestamp = date.toLocaleString().substring(0, 19);
  46. } else {//prompt
  47. strdata = JSON.stringify(data);
  48. dname = data.substring(0, 50).trim();
  49. }
  50. if (strdata && strdata.length < 3){
  51. return;
  52. }
  53. var redisname = encodeURIComponent(nameprefix + currentTimestamp + "\n" + dname);
  54. console.log(redisname);
  55. GM_xmlhttpRequest({
  56. method: "GET",
  57. url: `${WEBREDIS_ENDPOINT}/SET/${redisname}/${encodeURIComponent(strdata)}`,
  58. onload: function(response) {
  59. console.log(response);
  60. callback(null, response.responseText);
  61. },
  62. onerror: function(error) {
  63. console.log(error);
  64. callback(error, null);
  65. }
  66. });
  67. }
  68.  
  69. function remove(key, callback) {
  70. key = encodeURIComponent(key);
  71. GM_xmlhttpRequest({
  72. method: "GET",
  73. url: `${WEBREDIS_ENDPOINT}/DEL/${key}`,
  74. onload: function(response) {
  75. callback(null, JSON.parse(response.responseText));
  76. },
  77. onerror: function(error) {
  78. callback(error, null);
  79. }
  80. });
  81. }
  82.  
  83.  
  84. function getAllRedisKeys(callback) {
  85. GM_xmlhttpRequest({
  86. method: "GET",
  87. url: `${WEBREDIS_ENDPOINT}/KEYS/*`, // Update this to your actual endpoint
  88. onload: function(response) {
  89. if (response.responseText == undefined){
  90. redisError();
  91. return;
  92. }
  93. callback(null, JSON.parse(response.responseText));
  94. },
  95. onerror: function(error) {
  96. callback(error, null);
  97. }
  98. });
  99. }
  100.  
  101.  
  102. function getCurrentDialogContent() {
  103. // Get all div elements with the specified class
  104. const divsWithSpecificClass = document.querySelectorAll('div.flex.flex-grow.flex-col.gap-3.max-w-full');
  105. // Create an array to store the text content of each div
  106. const divTexts = [];
  107.  
  108. // Loop through the NodeList and get the text content of each div
  109. divsWithSpecificClass.forEach(div => {
  110. var textContent = [];
  111. divTexts.push(div);
  112. });
  113.  
  114. // Return the array of text contents
  115. return divTexts;
  116. }
  117.  
  118. function sleep(ms) {
  119. return new Promise(resolve => setTimeout(resolve, ms));
  120. }
  121.  
  122. function showHistory(dataList) {
  123. var targetDiv = document.querySelector('div.flex-1.overflow-hidden > div > div > div');
  124.  
  125. /*while(targetDiv.firstChild) {
  126. targetDiv.removeChild(targetDiv.firstChild);
  127. }*/
  128.  
  129. dataList.forEach(data => {
  130. var newDiv = document.createElement('div');
  131. newDiv.textContent = data;
  132. targetDiv.appendChild(newDiv);
  133. });
  134. }
  135.  
  136. function makeAGroup(name, keys, elementfilter, clickcallback){
  137. const ul = document.createElement('ul');
  138. ul.style.overflowY = 'auto';
  139. ul.style.maxHeight = '500px';
  140. var eid = "myUl" + name
  141. ul.id = eid; // Setting an ID to the ul element
  142. var h2 = document.createElement('h2');
  143. h2.innerText = name;
  144. h2.style.color = 'white';
  145. h2.style.textAlign = "center";
  146. ul.append(h2);
  147. for (let i = 0; i < keys.length; i++) {
  148. const li = document.createElement('li');
  149. if(!keys[i].startsWith(elementfilter)){
  150. continue;
  151. }
  152. li.innerHTML = keys[i].substring(elementfilter.length, keys[i].length).replace(/\n/g, '<br>');;
  153. li.style.color = 'white';
  154. // Apply CSS styles for the rounded rectangle
  155. li.style.border = '1px solid white'; // Add a border
  156. li.style.borderRadius = '10px'; // Adjust the horizontal and vertical radii to create rounded corners
  157. li.style.padding = '5px'; // Add some padding to make it visually appealing
  158. li.style.position = 'relative';
  159. li.addEventListener('mouseenter', function() {
  160. li.style.backgroundColor = 'grey'; // Change to your desired background color
  161. });
  162.  
  163. li.addEventListener('mouseleave', function() {
  164. li.style.backgroundColor = ''; // Reset to the original background color
  165. });
  166. li.addEventListener('click', (event) => {clickcallback(event, keys[i]);});
  167.  
  168. // add close
  169. // Create close button
  170. const closeButton = document.createElement('span');
  171. closeButton.textContent = '✖';
  172. closeButton.style.position = 'absolute';
  173. closeButton.style.top = '5px';
  174. closeButton.style.right = '5px';
  175. closeButton.style.color = 'white';
  176. closeButton.style.cursor = 'pointer'; // Set cursor to pointer to indicate it's clickable
  177.  
  178. // Add event listener for the close button
  179. closeButton.addEventListener('click', async (event) => {
  180. // Your callback function here
  181. event.stopPropagation();
  182. remove(keys[i], function (){});
  183. await sleep(500);
  184. InitPanel();
  185. });
  186.  
  187. // Add close button to li
  188. li.appendChild(closeButton);
  189. ul.appendChild(li);
  190. }
  191. return ul;
  192. }
  193.  
  194.  
  195. async function InitPanel() {
  196.  
  197.  
  198.  
  199.  
  200. getAllRedisKeys(function(error, data) {
  201. if (error) {
  202. redisError();
  203. console.error('An error occurred:', error);
  204. return;
  205. }
  206.  
  207. const ol = document.querySelectorAll('ol')[2];
  208. var div = document.querySelectorAll('div.flex-shrink-0.overflow-x-hidden')[0];
  209. const ulExisting = document.getElementById('myUlHistory');
  210. if (ulExisting) {
  211. div.removeChild(ulExisting, function (){});
  212. }
  213. if (data.KEYS.length == 0){
  214. redisError();
  215. }
  216. var ul = makeAGroup("History", data.KEYS.sort().reverse(), HistoryPrefix, function(event, key) {
  217. //console.log('Item clicked:', data.KEYS[i]);
  218. // Load data after saving
  219. load(key, function(err, data) {
  220. if (err) return console.error(err);
  221. var myList = JSON.parse(data.GET);
  222. if (Array.isArray(myList)){
  223. for (let i = 0; i < myList.length; i++) {
  224. if (i % 2 == 0) {
  225. myList[i] = "👨: " + myList[i].replace(/\n/g, '<br>');
  226. } else {
  227. myList[i] = "🤖: " + myList[i].replace(/\n/g, '<br>');
  228. }
  229. }
  230. showHistoryLog(myList.join("<br>"));
  231. }
  232. });
  233. });
  234. div.prepend(ul);
  235.  
  236. /*---Prompt---*/
  237. var ulPrompt = document.getElementById('myUlPrompt');
  238. if (ulPrompt) {
  239. div.removeChild(ulPrompt);
  240. }
  241. var prompt = makeAGroup("Prompt", data.KEYS.sort().reverse(), PromptPrefix, function(event, key) {
  242. //console.log('Item clicked:', data.KEYS[i]);
  243. // Load data after saving
  244. load(key, function(err, data) {
  245. if (err) return console.error(err);
  246. var prompt = JSON.parse(data.GET);
  247. var textarea = document.getElementById('prompt-textarea');
  248. textarea.value = prompt;
  249. });
  250. });
  251. div.prepend(prompt);
  252. if (!ulPrompt) {
  253. var button = document.createElement('button');
  254. button.innerText = 'Save Message As Prompt';
  255. button.style.color = 'white';
  256. button.style.position = 'relative';
  257. button.style.textAlign = 'center';
  258. button.style.border = '1px solid white';
  259. button.style.backgroundColor = '#268BD2';
  260. var bottomdiv = document.querySelectorAll('div.relative.pb-3.pt-2.text-center.text-xs.text-gray-600')[0];
  261. bottomdiv.appendChild(button);
  262.  
  263. button.addEventListener('click', function() {
  264. var textarea = document.getElementById('prompt-textarea');
  265. save(PromptPrefix, textarea.textContent, function(err, response) {
  266. if (err) return console.error(err);
  267. });
  268. InitPanel();
  269. });
  270. }
  271.  
  272.  
  273. });
  274. /*Remote Offical*/
  275. await sleep(2000);
  276. const olElements = document.querySelectorAll('ol');
  277. olElements.forEach(ol => {
  278. // First remove all existing children
  279. while (ol.firstChild) {
  280. ol.removeChild(ol.firstChild);
  281. }
  282. });
  283.  
  284. }
  285.  
  286. function redisError(){
  287. var div = document.querySelectorAll('div.flex-shrink-0.overflow-x-hidden')[0];
  288. const ul = document.createElement('ul');
  289. div.prepend(ul);
  290. const li = document.createElement('li');
  291. li.textContent = "There is no record. Please verify if webdis AND redis-server has been started! Just run `webdis.sh start` to start.";
  292. li.style.color = 'white';
  293. ul.appendChild(li);
  294. }
  295.  
  296. function showHistoryLog(text) {
  297. // Check if the div with a specific id already exists
  298. var existingDiv = document.getElementById('historyLog');
  299.  
  300. if (existingDiv) {
  301. // If the div exists, update the messageSpan's HTML content
  302. var messageSpan = existingDiv.querySelector('.message-span');
  303. if (messageSpan) {
  304. messageSpan.innerHTML = text;
  305. }
  306. existingDiv.style.display = '';
  307. } else {
  308. // If the div doesn't exist, create a new div and append it to the body
  309. var hoverBox = document.createElement('div');
  310. hoverBox.id = 'historyLog'; // Set a unique id for the div
  311. hoverBox.style.position = 'fixed';
  312. hoverBox.style.top = '50%';
  313. hoverBox.style.left = '50%';
  314. hoverBox.style.transform = 'translate(-50%, -50%)';
  315. hoverBox.style.zIndex = '10000';
  316. hoverBox.style.padding = '10px';
  317. hoverBox.style.width = '1000px';
  318. hoverBox.style.height = '800px';
  319. hoverBox.style.backgroundColor = 'white';
  320. hoverBox.style.border = '1px solid black';
  321. hoverBox.style.borderRadius = '5px';
  322. hoverBox.style.boxShadow = '0px 0px 10px rgba(0, 0, 0, 0.5)';
  323. hoverBox.style.overflow = 'hidden'; // Hide content overflow
  324.  
  325. // Create a container div for the content and close button
  326. var contentContainer = document.createElement('div');
  327. contentContainer.style.overflowY = 'auto'; // Make content scrollable
  328. //contentContainer.style.resize = 'both'; // Enable resizing
  329. contentContainer.style.height = 'calc(100% - 40px)'; // Adjust height for close button
  330.  
  331. // Create a span element to hold the message
  332. var messageSpan = document.createElement('span');
  333. messageSpan.innerHTML = text;
  334. messageSpan.className = 'message-span'; // Add a class for easy selection
  335. messageSpan.style.display = 'block';
  336. messageSpan.style.marginTop = '20px';
  337.  
  338. // Create a button element to close the hover box
  339. var closeButton = document.createElement('button');
  340. closeButton.textContent = '✖';
  341. closeButton.style.position = 'absolute';
  342. closeButton.style.top = '10px';
  343. closeButton.style.right = '10px';
  344. closeButton.addEventListener('click', function () {
  345. hoverBox.style.display = 'none';
  346. });
  347.  
  348. // Add the message span and close button to the content container
  349. contentContainer.appendChild(messageSpan);
  350. contentContainer.appendChild(closeButton);
  351.  
  352. // Add the content container to the hover box
  353. hoverBox.appendChild(contentContainer);
  354.  
  355. document.addEventListener('click', function (event) {
  356. if (!hoverBox.contains(event.target) && event.target !== hoverBox) {
  357. hoverBox.style.display = 'none';
  358. }
  359. });
  360.  
  361. // Add the hover box to the body of the document
  362. document.body.appendChild(hoverBox);
  363. }
  364. }
  365.  
  366.  
  367.  
  368.  
  369.  
  370.  
  371.  
  372. InitPanel();
  373.  
  374.  
  375.  
  376.  
  377. document.addEventListener('keydown', async function(event) {
  378. if (event.key === 'Enter' || (event.metaKey && event.key === 'r')) {
  379. // Usage examples
  380. while(true){
  381. var thisdialog = getCurrentDialogContent();
  382. save(HistoryPrefix, thisdialog, function(err, response) {
  383. if (err) return console.error(err);
  384. console.log('Save response:', response);
  385. if(!thisInHistory){
  386. InitPanel();
  387. thisInHistory = true;
  388. }
  389. });
  390. const divElement = document.querySelector('div.flex.items-center.md\\:items-end');
  391. if (divElement == undefined || divElement.textContent == undefined || divElement.textContent != 'Stop generating'){
  392. break;
  393. }
  394. await sleep(2000);
  395. }
  396. }
  397. if (event.key === 'Escape') {
  398. var existingDiv = document.getElementById('historyLog');
  399. if (existingDiv) {
  400. existingDiv.style.display = 'none';
  401. }
  402. }
  403. });
  404.  
  405.  
  406.  
  407.  
  408. })();