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 history still available when offline.

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

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