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: Even without an internet connection, ChatGPTHelper ensures your chat history remains available.

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

  1. // ==UserScript==
  2. // @name ChatGPTHelper
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.5
  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: Even without an internet connection, ChatGPTHelper ensures your chat history remains available.
  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.  
  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.  
  126. dataList.forEach(data => {
  127. var newDiv = document.createElement('div');
  128. newDiv.textContent = data;
  129. targetDiv.appendChild(newDiv);
  130. });
  131. }
  132.  
  133. function makeAGroup(name, keys, elementfilter, clickcallback){
  134. const div = document.createElement('div');
  135. const ul = document.createElement('ul');
  136. ul.style.overflowY = 'auto';
  137. ul.style.maxHeight = '500px';
  138. var eid = "myUl" + name
  139. ul.id = eid; // Setting an ID to the ul element
  140. var h2 = document.createElement('h2');
  141. h2.innerText = name;
  142. h2.style.color = 'white';
  143. h2.style.textAlign = "center";
  144. div.append(h2);
  145. for (let i = 0; i < keys.length; i++) {
  146. const li = document.createElement('li');
  147. if(!keys[i].startsWith(elementfilter)){
  148. continue;
  149. }
  150. li.innerHTML = keys[i].substring(elementfilter.length, keys[i].length).replace(/\n/g, '<br>');;
  151. li.style.color = 'white';
  152. // Apply CSS styles for the rounded rectangle
  153. li.style.border = '1px solid white'; // Add a border
  154. li.style.borderRadius = '10px'; // Adjust the horizontal and vertical radii to create rounded corners
  155. li.style.padding = '5px'; // Add some padding to make it visually appealing
  156. li.style.position = 'relative';
  157. li.addEventListener('mouseenter', function() {
  158. li.style.backgroundColor = 'grey'; // Change to your desired background color
  159. });
  160.  
  161. li.addEventListener('mouseleave', function() {
  162. li.style.backgroundColor = ''; // Reset to the original background color
  163. });
  164. li.addEventListener('click', (event) => {clickcallback(event, keys[i]);});
  165.  
  166. // add close
  167. // Create close button
  168. const closeButton = document.createElement('span');
  169. closeButton.textContent = '✖';
  170. closeButton.style.position = 'absolute';
  171. closeButton.style.top = '5px';
  172. closeButton.style.right = '5px';
  173. closeButton.style.color = 'white';
  174. closeButton.style.cursor = 'pointer'; // Set cursor to pointer to indicate it's clickable
  175.  
  176. // Add event listener for the close button
  177. closeButton.addEventListener('click', async (event) => {
  178. // Your callback function here
  179. event.stopPropagation();
  180. remove(keys[i], function (){});
  181. await sleep(500);
  182. InitPanel();
  183. });
  184.  
  185. // Add close button to li
  186. li.appendChild(closeButton);
  187. ul.appendChild(li);
  188. }
  189. div.append(ul);
  190. return div;
  191. }
  192.  
  193.  
  194. async function InitPanel() {
  195.  
  196. getAllRedisKeys(function(error, data) {
  197. if (error) {
  198. redisError();
  199. console.error('An error occurred:', error);
  200. return;
  201. }
  202.  
  203. const ol = document.querySelectorAll('ol')[2];
  204. var div = document.querySelectorAll('div.flex-shrink-0.overflow-x-hidden')[0];
  205. const ulExisting = document.getElementById('myUlHistory');
  206. if (ulExisting) {
  207. div.removeChild(ulExisting, function (){});
  208. }
  209. if (data.KEYS.length == 0){
  210. redisError();
  211. }
  212. var ul = makeAGroup("History", data.KEYS.sort().reverse(), HistoryPrefix, function(event, key) {
  213. //console.log('Item clicked:', data.KEYS[i]);
  214. // Load data after saving
  215. load(key, function(err, data) {
  216. if (err) return console.error(err);
  217. var myList = JSON.parse(data.GET);
  218. if (Array.isArray(myList)){
  219. for (let i = 0; i < myList.length; i++) {
  220. if (i % 2 == 0) {
  221. myList[i] = "👨: " + myList[i].replace(/\n/g, '<br>');
  222. } else {
  223. myList[i] = "🤖: " + myList[i].replace(/\n/g, '<br>');
  224. }
  225. }
  226. showHistoryLog(myList.join("<br>"));
  227. }
  228. });
  229. });
  230. div.prepend(ul);
  231.  
  232. /*---Prompt---*/
  233. var ulPrompt = document.getElementById('myUlPrompt');
  234. if (ulPrompt) {
  235. div.removeChild(ulPrompt);
  236. }
  237. var prompt = makeAGroup("Prompt", data.KEYS.sort().reverse(), PromptPrefix, function(event, key) {
  238. //console.log('Item clicked:', data.KEYS[i]);
  239. // Load data after saving
  240. load(key, function(err, data) {
  241. if (err) return console.error(err);
  242. var prompt = JSON.parse(data.GET);
  243. var textarea = document.getElementById('prompt-textarea');
  244. textarea.value = prompt;
  245. });
  246. });
  247. div.prepend(prompt);
  248. if (!ulPrompt) {
  249. var button = document.createElement('button');
  250. button.innerText = 'Save Message As Prompt';
  251. button.style.color = 'white';
  252. button.style.position = 'relative';
  253. button.style.textAlign = 'center';
  254. button.style.border = '1px solid white';
  255. button.style.backgroundColor = '#268BD2';
  256. var bottomdiv = document.querySelectorAll('div.relative.pb-3.pt-2.text-center.text-xs.text-gray-600')[0];
  257. bottomdiv.appendChild(button);
  258.  
  259. button.addEventListener('click', function() {
  260. var textarea = document.getElementById('prompt-textarea');
  261. save(PromptPrefix, textarea.textContent, function(err, response) {
  262. if (err) return console.error(err);
  263. });
  264. InitPanel();
  265. });
  266. }
  267.  
  268.  
  269. });
  270. /*Remote Offical*/
  271. await sleep(2000);
  272. const olElements = document.querySelectorAll('ol');
  273. olElements.forEach(ol => {
  274. // First remove all existing children
  275. while (ol.firstChild) {
  276. ol.removeChild(ol.firstChild);
  277. }
  278. });
  279.  
  280. }
  281.  
  282. function redisError(){
  283. var div = document.querySelectorAll('div.flex-shrink-0.overflow-x-hidden')[0];
  284. const ul = document.createElement('ul');
  285. div.prepend(ul);
  286. const li = document.createElement('li');
  287. li.textContent = "There is no record. Please verify if webdis AND redis-server has been started! Just run `webdis.sh start` to start.";
  288. li.style.color = 'white';
  289. ul.appendChild(li);
  290. }
  291.  
  292. function showHistoryLog(text) {
  293. // Check if the div with a specific id already exists
  294. var existingDiv = document.getElementById('historyLog');
  295.  
  296. if (existingDiv) {
  297. // If the div exists, update the messageSpan's HTML content
  298. var messageSpan = existingDiv.querySelector('.message-span');
  299. if (messageSpan) {
  300. messageSpan.innerHTML = text;
  301. }
  302. existingDiv.style.display = '';
  303. } else {
  304. // If the div doesn't exist, create a new div and append it to the body
  305. var hoverBox = document.createElement('div');
  306. hoverBox.id = 'historyLog'; // Set a unique id for the div
  307. hoverBox.style.position = 'fixed';
  308. hoverBox.style.top = '50%';
  309. hoverBox.style.left = '50%';
  310. hoverBox.style.transform = 'translate(-50%, -50%)';
  311. hoverBox.style.zIndex = '10000';
  312. hoverBox.style.padding = '10px';
  313. hoverBox.style.width = '1000px';
  314. hoverBox.style.height = '800px';
  315. hoverBox.style.backgroundColor = 'white';
  316. hoverBox.style.border = '1px solid black';
  317. hoverBox.style.borderRadius = '5px';
  318. hoverBox.style.boxShadow = '0px 0px 10px rgba(0, 0, 0, 0.5)';
  319. hoverBox.style.overflow = 'hidden'; // Hide content overflow
  320.  
  321. // Create a container div for the content and close button
  322. var contentContainer = document.createElement('div');
  323. contentContainer.style.overflowY = 'auto'; // Make content scrollable
  324. //contentContainer.style.resize = 'both'; // Enable resizing
  325. contentContainer.style.height = 'calc(100% - 40px)'; // Adjust height for close button
  326.  
  327. // Create a span element to hold the message
  328. var messageSpan = document.createElement('span');
  329. messageSpan.innerHTML = text;
  330. messageSpan.className = 'message-span'; // Add a class for easy selection
  331. messageSpan.style.display = 'block';
  332. messageSpan.style.marginTop = '20px';
  333.  
  334. // Create a button element to close the hover box
  335. var closeButton = document.createElement('button');
  336. closeButton.textContent = '✖';
  337. closeButton.style.position = 'absolute';
  338. closeButton.style.top = '10px';
  339. closeButton.style.right = '10px';
  340. closeButton.addEventListener('click', function () {
  341. hoverBox.style.display = 'none';
  342. });
  343.  
  344. // Add the message span and close button to the content container
  345. contentContainer.appendChild(messageSpan);
  346. contentContainer.appendChild(closeButton);
  347.  
  348. // Add the content container to the hover box
  349. hoverBox.appendChild(contentContainer);
  350.  
  351. document.addEventListener('click', function (event) {
  352. if (!hoverBox.contains(event.target) && event.target !== hoverBox) {
  353. hoverBox.style.display = 'none';
  354. }
  355. });
  356.  
  357. // Add the hover box to the body of the document
  358. document.body.appendChild(hoverBox);
  359. }
  360. }
  361.  
  362.  
  363.  
  364.  
  365.  
  366.  
  367.  
  368. InitPanel();
  369.  
  370.  
  371.  
  372.  
  373. document.addEventListener('keydown', async function(event) {
  374. if (event.key === 'Enter' || (event.metaKey && event.key === 'r')) {
  375. // Usage examples
  376. while(true){
  377. var thisdialog = getCurrentDialogContent();
  378. save(HistoryPrefix, thisdialog, function(err, response) {
  379. if (err) return console.error(err);
  380. console.log('Save response:', response);
  381. if(!thisInHistory){
  382. InitPanel();
  383. thisInHistory = true;
  384. }
  385. });
  386. const divElement = document.querySelector('div.flex.items-center.md\\:items-end');
  387. if (divElement == undefined || divElement.textContent == undefined || divElement.textContent != 'Stop generating'){
  388. break;
  389. }
  390. await sleep(2000);
  391. }
  392. }
  393. if (event.key === 'Escape') {
  394. var existingDiv = document.getElementById('historyLog');
  395. if (existingDiv) {
  396. existingDiv.style.display = 'none';
  397. }
  398. }
  399. });
  400.  
  401.  
  402.  
  403.  
  404. })();