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-19 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name ChatGPTHelper
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.12
  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 redisname;
  40. var date = new Date();
  41. var currentTimestamp = date.toLocaleString().substring(0, 19);
  42. if (Array.isArray(data)) {// history
  43. strdata = JSON.stringify(data.map(function(element) {
  44. return element.innerHTML;
  45. }));
  46. dname = data[0].innerText.substring(0, 100).trim();
  47. if (redisHistoryName == ""){
  48. redisHistoryName = encodeURIComponent(nameprefix + currentTimestamp + "\n" + dname);
  49. }
  50. redisname = redisHistoryName
  51. } else {//prompt
  52. strdata = JSON.stringify(data);
  53. dname = data.substring(0, 100).trim();
  54. redisname = encodeURIComponent(nameprefix + currentTimestamp + "\n" + dname);
  55. }
  56. if (strdata && strdata.length < 3){
  57. return;
  58. }
  59.  
  60. console.log(redisname);
  61. GM_xmlhttpRequest({
  62. method: "GET",
  63. url: `${WEBREDIS_ENDPOINT}/SET/${redisname}/${encodeURIComponent(strdata)}`,
  64. onload: function(response) {
  65. console.log(response);
  66. callback(null, response.responseText);
  67. },
  68. onerror: function(error) {
  69. console.log(error);
  70. callback(error, null);
  71. }
  72. });
  73. }
  74.  
  75. function remove(key, callback) {
  76. key = encodeURIComponent(key);
  77. GM_xmlhttpRequest({
  78. method: "GET",
  79. url: `${WEBREDIS_ENDPOINT}/DEL/${key}`,
  80. onload: function(response) {
  81. callback(null, JSON.parse(response.responseText));
  82. },
  83. onerror: function(error) {
  84. callback(error, null);
  85. }
  86. });
  87. }
  88.  
  89.  
  90. function getAllRedisKeys(callback) {
  91. GM_xmlhttpRequest({
  92. method: "GET",
  93. url: `${WEBREDIS_ENDPOINT}/KEYS/*`, // Update this to your actual endpoint
  94. onload: function(response) {
  95. if (response.responseText == undefined){
  96. redisError();
  97. return;
  98. }
  99. callback(null, JSON.parse(response.responseText));
  100. },
  101. onerror: function(error) {
  102. callback(error, null);
  103. }
  104. });
  105. }
  106.  
  107.  
  108. function getCurrentDialogContent() {
  109. // Get all div elements with the specified class
  110. const divsWithSpecificClass = document.querySelectorAll('div.flex.flex-grow.flex-col.gap-3.max-w-full');
  111. // Create an array to store the text content of each div
  112. const divTexts = [];
  113.  
  114. // Loop through the NodeList and get the text content of each div
  115. divsWithSpecificClass.forEach(div => {
  116. var textContent = [];
  117. divTexts.push(div);
  118. });
  119.  
  120. // Return the array of text contents
  121. return divTexts;
  122. }
  123.  
  124. function sleep(ms) {
  125. return new Promise(resolve => setTimeout(resolve, ms));
  126. }
  127.  
  128. function showHistory(dataList) {
  129. var targetDiv = document.querySelector('div.flex-1.overflow-hidden > div > div > div');
  130.  
  131.  
  132. dataList.forEach(data => {
  133. var newDiv = document.createElement('div');
  134. newDiv.textContent = data;
  135. targetDiv.appendChild(newDiv);
  136. });
  137. }
  138.  
  139. function makeAGroup(name, keys, elementfilter, clickcallback){
  140. const div = document.createElement('div');
  141. div.style.padding = "5px"
  142. const ul = document.createElement('ul');
  143. ul.style.overflowY = 'auto';
  144. ul.style.maxHeight = '500px';
  145. var eid = "myUl" + name
  146. div.id = eid; // Setting an ID to the ul element
  147. var h2 = document.createElement('h2');
  148. h2.innerText = name;
  149. h2.style.color = 'white';
  150. h2.style.textAlign = "center";
  151. div.append(h2);
  152. for (let i = 0; i < keys.length; i++) {
  153. const li = document.createElement('li');
  154. if(!keys[i].startsWith(elementfilter)){
  155. continue;
  156. }
  157. var parts = keys[i].substring(elementfilter.length, keys[i].length).split("\n");
  158. var p = document.createElement('p');
  159. p.innerText = parts[1];
  160. p.style.lineHeight = '0.9';
  161. p.style.fontSize = '10pt';
  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 = '#dddddd';
  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(100, 100, 100, 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. var closeButton = document.createElement('span');
  186. closeButton.innerHTML = '<svg width="20" height="20" viewBox="0 0 72 72" xmlns="http://www.w3.org/2000/svg" <g style="fill:none;stroke:#aaa;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;stroke-width:2"><path d="m31 16v-4h10v4"/><path d="m51 25v31c0 2.2091-1.7909 4-4 4h-22c-2.2091 0-4-1.7909-4-4v-31"/><path d="m17 16h38v4h-38z"/><path d="m41 28.25v26.75"/><path d="m31 28.25v26.75"/></g></svg>';
  187. closeButton.style.position = 'absolute';
  188. closeButton.style.top = '6px';
  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. var event = new Event('input', { bubbles: true });
  263. textarea.dispatchEvent(event);
  264. textarea.focus();
  265. textarea.setSelectionRange(textarea.value.length, textarea.value.length);
  266. textarea.scrollTop = textarea.scrollHeight;
  267. console.log("in chaning", prompt, textarea);
  268. });
  269. });
  270. div.prepend(prompt);
  271. if (!ulPrompt) {
  272. var textarea = document.getElementById('prompt-textarea');
  273. var button = document.createElement('button');
  274. button.innerHTML = '<svg height="25" viewBox="0 0 1792 1792" width="25" xmlns="http://www.w3.org/2000/svg" stroke="#bbbbbb"><path d="M512 1536h768v-384h-768v384zm896 0h128v-896q0-14-10-38.5t-20-34.5l-281-281q-10-10-34-20t-39-10v416q0 40-28 68t-68 28h-576q-40 0-68-28t-28-68v-416h-128v1280h128v-416q0-40 28-68t68-28h832q40 0 68 28t28 68v416zm-384-928v-320q0-13-9.5-22.5t-22.5-9.5h-192q-13 0-22.5 9.5t-9.5 22.5v320q0 13 9.5 22.5t22.5 9.5h192q13 0 22.5-9.5t9.5-22.5zm640 32v928q0 40-28 68t-68 28h-1344q-40 0-68-28t-28-68v-1344q0-40 28-68t68-28h928q40 0 88 20t76 48l280 280q28 28 48 76t20 88z" fill="#bbbbbb"/></svg>';
  275. //button.style.color = 'white';
  276. button.style.position = 'absolute';
  277. button.style.right = '60px';
  278. button.style.top = '20px';
  279. button.style.textAlign = 'center';
  280. //button.style.border = '1px solid grey';
  281. button.style.marginLeft = '10px';
  282. //button.style.backgroundColor = '#268BD2';
  283. //var bottomdiv = document.querySelectorAll('div.relative.pb-3.pt-2.text-center.text-xs.text-gray-600')[0];
  284. //bottomdiv.appendChild(button);
  285. button.title = 'Save the message as a prompt';
  286.  
  287. textarea.parentNode.appendChild(button);
  288.  
  289. button.addEventListener('click', function() {
  290. var textarea = document.getElementById('prompt-textarea');
  291. save(PromptPrefix, textarea.textContent, function(err, response) {
  292. if (err) return console.error(err);
  293. });
  294.  
  295. InitPanel();
  296. });
  297. }
  298.  
  299.  
  300. });
  301. /*Remote Offical*/
  302. await sleep(2000);
  303. const olElements = document.querySelectorAll('ol');
  304. olElements.forEach(ol => {
  305. // First remove all existing children
  306. while (ol.firstChild) {
  307. ol.removeChild(ol.firstChild);
  308. }
  309. });
  310.  
  311. }
  312.  
  313. function redisError(){
  314. var div = document.querySelectorAll('div.flex-shrink-0.overflow-x-hidden')[0];
  315. const ul = document.createElement('ul');
  316. div.prepend(ul);
  317. const li = document.createElement('li');
  318. li.textContent = "There is no record. Please verify if webdis AND redis-server has been started! Just run `webdis.sh start` to start.";
  319. li.style.color = 'white';
  320. ul.appendChild(li);
  321. }
  322.  
  323. function showHistoryLog(text) {
  324. // Check if the div with a specific id already exists
  325. var existingDiv = document.getElementById('historyLog');
  326.  
  327. if (existingDiv) {
  328. // If the div exists, update the messageSpan's HTML content
  329. var messageSpan = existingDiv.querySelector('.message-span');
  330. if (messageSpan) {
  331. messageSpan.innerHTML = text;
  332. }
  333. existingDiv.style.display = '';
  334. } else {
  335. // If the div doesn't exist, create a new div and append it to the body
  336. var hoverBox = document.createElement('div');
  337. hoverBox.id = 'historyLog'; // Set a unique id for the div
  338. hoverBox.style.position = 'fixed';
  339. hoverBox.style.top = '50%';
  340. hoverBox.style.left = '50%';
  341. hoverBox.style.transform = 'translate(-50%, -50%)';
  342. hoverBox.style.zIndex = '10000';
  343. hoverBox.style.padding = '10px';
  344. hoverBox.style.width = '1000px';
  345. hoverBox.style.height = '800px';
  346. hoverBox.style.backgroundColor = 'white';
  347. hoverBox.style.border = '1px solid black';
  348. hoverBox.style.borderRadius = '5px';
  349. hoverBox.style.boxShadow = '0px 0px 10px rgba(0, 0, 0, 0.5)';
  350. hoverBox.style.overflow = 'hidden'; // Hide content overflow
  351.  
  352. // Create a container div for the content and close button
  353. var contentContainer = document.createElement('div');
  354. contentContainer.style.overflowY = 'auto'; // Make content scrollable
  355. //contentContainer.style.resize = 'both'; // Enable resizing
  356. contentContainer.style.height = 'calc(100% - 40px)'; // Adjust height for close button
  357.  
  358. // Create a span element to hold the message
  359. var messageSpan = document.createElement('span');
  360. messageSpan.innerHTML = text;
  361. messageSpan.className = 'message-span'; // Add a class for easy selection
  362. messageSpan.style.display = 'block';
  363. messageSpan.style.marginTop = '20px';
  364.  
  365. // Create a button element to close the hover box
  366. var closeButton = document.createElement('button');
  367. closeButton.textContent = '✖';
  368. closeButton.style.position = 'absolute';
  369. closeButton.style.top = '10px';
  370. closeButton.style.right = '10px';
  371. closeButton.addEventListener('click', function () {
  372. hoverBox.style.display = 'none';
  373. });
  374.  
  375. // Add the message span and close button to the content container
  376. contentContainer.appendChild(messageSpan);
  377. contentContainer.appendChild(closeButton);
  378.  
  379. // Add the content container to the hover box
  380. hoverBox.appendChild(contentContainer);
  381.  
  382. document.addEventListener('click', function (event) {
  383. if (!hoverBox.contains(event.target) && event.target !== hoverBox) {
  384. hoverBox.style.display = 'none';
  385. event.stopPropagation();
  386. }
  387. });
  388.  
  389. // Add the hover box to the body of the document
  390. document.body.appendChild(hoverBox);
  391. }
  392. }
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. InitPanel();
  401.  
  402.  
  403.  
  404.  
  405. document.addEventListener('keydown', async function(event) {
  406. if (event.key === 'Enter' || (event.metaKey && event.key === 'r')) {
  407. // Usage examples
  408. while(true){
  409. var thisdialog = getCurrentDialogContent();
  410. save(HistoryPrefix, thisdialog, function(err, response) {
  411. if (err) return console.error(err);
  412. console.log('Save response:', response);
  413. if(!thisInHistory){
  414. InitPanel();
  415. thisInHistory = true;
  416. }
  417. });
  418. const divElement = document.querySelector('div.flex.items-center.md\\:items-end');
  419. if (divElement == undefined || divElement.textContent == undefined || divElement.textContent != 'Stop generating'){
  420. break;
  421. }
  422. await sleep(2000);
  423. }
  424. }
  425. if (event.key === 'Escape') {
  426. var existingDiv = document.getElementById('historyLog');
  427. if (existingDiv) {
  428. existingDiv.style.display = 'none';
  429. }
  430. }
  431. });
  432.  
  433.  
  434.  
  435.  
  436. })();