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.13
  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. var generateButton = null;
  21.  
  22.  
  23. function load(key, callback) {
  24. key = encodeURIComponent(key);
  25. GM_xmlhttpRequest({
  26. method: "GET",
  27. url: `${WEBREDIS_ENDPOINT}/GET/${key}`,
  28. onload: function(response) {
  29. callback(null, JSON.parse(response.responseText));
  30. },
  31. onerror: function(error) {
  32. callback(error, null);
  33. }
  34. });
  35. }
  36.  
  37. function save(nameprefix, data, callback) {
  38. var strdata;
  39. var dname;
  40. var redisname;
  41. var date = new Date();
  42. var currentTimestamp = date.toLocaleString().substring(0, 19);
  43. if (Array.isArray(data)) {// history
  44. strdata = JSON.stringify(data.map(function(element) {
  45. return element.innerHTML;
  46. }));
  47. dname = data[0].innerText.substring(0, 100).trim();
  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, 100).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.fontSize = '10pt';
  163. //p.style.whiteSpace = 'pre-line';
  164. //p.style.wordWrap = 'break-word';
  165. p.style.wordBreak = 'break-all';
  166. li.innerHTML = `<p style="color: grey; font-size: 5pt;">${parts[0]}</p>`;
  167. li.appendChild(p);
  168. li.style.color = '#dddddd';
  169. // Apply CSS styles for the rounded rectangle
  170. li.style.border = '1px solid #333333'; // Add a border
  171. li.style.borderRadius = '10px'; // Adjust the horizontal and vertical radii to create rounded corners
  172. li.style.padding = '10px'; // Add some padding to make it visually appealing
  173. li.style.position = 'relative';
  174. li.style.marginBottom = '4px';
  175. li.addEventListener('mouseenter', function() {
  176. li.style.backgroundColor = 'rgba(100, 100, 100, 0.8)'; // Change to your desired background color
  177. });
  178.  
  179. li.addEventListener('mouseleave', function() {
  180. li.style.backgroundColor = ''; // Reset to the original background color
  181. });
  182. li.addEventListener('click', (event) => {clickcallback(event, keys[i]);});
  183.  
  184. // add close
  185. // Create close button
  186. var closeButton = document.createElement('span');
  187. 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>';
  188. closeButton.style.position = 'absolute';
  189. closeButton.style.top = '6px';
  190. closeButton.style.right = '5px';
  191. closeButton.style.color = 'white';
  192. closeButton.style.cursor = 'pointer'; // Set cursor to pointer to indicate it's clickable
  193.  
  194. // Add event listener for the close button
  195. closeButton.addEventListener('click', async (event) => {
  196. // Your callback function here
  197. event.stopPropagation();
  198. remove(keys[i], function (){});
  199. await sleep(500);
  200. InitPanel();
  201. });
  202.  
  203. // Add close button to li
  204. li.appendChild(closeButton);
  205. ul.appendChild(li);
  206. }
  207. div.append(ul);
  208. return div;
  209. }
  210.  
  211.  
  212. async function InitPanel() {
  213.  
  214. getAllRedisKeys(function(error, data) {
  215. if (error) {
  216. redisError();
  217. console.error('An error occurred:', error);
  218. return;
  219. }
  220.  
  221. const ol = document.querySelectorAll('ol')[2];
  222. var div = document.querySelectorAll('div.flex-shrink-0.overflow-x-hidden')[0];
  223. const ulExisting = document.getElementById('myUlHistory');
  224. if (ulExisting) {
  225. div.removeChild(ulExisting, function (){});
  226. }
  227. if (data.KEYS.length == 0){
  228. redisError();
  229. }
  230. var ul = makeAGroup("History", data.KEYS.sort().reverse(), HistoryPrefix, function(event, key) {
  231. //console.log('Item clicked:', data.KEYS[i]);
  232. // Load data after saving
  233. load(key, function(err, data) {
  234. if (err) return console.error(err);
  235. var myList = JSON.parse(data.GET);
  236. if (Array.isArray(myList)){
  237. for (let i = 0; i < myList.length; i++) {
  238. if (i % 2 == 0) {
  239. myList[i] = "👨: " + myList[i].replace(/\n/g, '<br>');
  240. } else {
  241. myList[i] = "🤖: " + myList[i].replace(/\n/g, '<br>');
  242. }
  243. }
  244. showHistoryLog(myList.join("<br>"));
  245. }
  246. });
  247. });
  248. div.prepend(ul);
  249.  
  250. /*---Prompt---*/
  251. var ulPrompt = document.getElementById('myUlPrompt');
  252. if (ulPrompt) {
  253. div.removeChild(ulPrompt);
  254. }
  255. var prompt = makeAGroup("Prompt", data.KEYS.sort().reverse(), PromptPrefix, function(event, key) {
  256. //console.log('Item clicked:', data.KEYS[i]);
  257. // Load data after saving
  258. load(key, function(err, data) {
  259. if (err) return console.error(err);
  260. var prompt = JSON.parse(data.GET);
  261. var textarea = document.getElementById('prompt-textarea');
  262. textarea.value = prompt;
  263. var event = new Event('input', { bubbles: true });
  264. textarea.dispatchEvent(event);
  265. textarea.focus();
  266. textarea.setSelectionRange(textarea.value.length, textarea.value.length);
  267. textarea.scrollTop = textarea.scrollHeight;
  268. console.log("in chaning", prompt, textarea);
  269. });
  270. });
  271. div.prepend(prompt);
  272. if (!ulPrompt) {
  273. var textarea = document.getElementById('prompt-textarea');
  274. var button = document.createElement('button');
  275. 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>';
  276. //button.style.color = 'white';
  277. button.style.position = 'absolute';
  278. button.style.right = '60px';
  279. button.style.top = '20px';
  280. button.style.textAlign = 'center';
  281. //button.style.border = '1px solid grey';
  282. button.style.marginLeft = '10px';
  283. //button.style.backgroundColor = '#268BD2';
  284. //var bottomdiv = document.querySelectorAll('div.relative.pb-3.pt-2.text-center.text-xs.text-gray-600')[0];
  285. //bottomdiv.appendChild(button);
  286. button.title = 'Save the message as a prompt';
  287.  
  288. textarea.parentNode.appendChild(button);
  289.  
  290. button.addEventListener('click', function() {
  291. var textarea = document.getElementById('prompt-textarea');
  292. save(PromptPrefix, textarea.textContent, function(err, response) {
  293. if (err) return console.error(err);
  294. });
  295.  
  296. InitPanel();
  297. });
  298. }
  299.  
  300.  
  301. });
  302. /*Remote Offical*/
  303. await sleep(2000);
  304. const olElements = document.querySelectorAll('ol');
  305. olElements.forEach(ol => {
  306. // First remove all existing children
  307. while (ol.firstChild) {
  308. ol.removeChild(ol.firstChild);
  309. }
  310. });
  311.  
  312. }
  313.  
  314. function redisError(){
  315. var div = document.querySelectorAll('div.flex-shrink-0.overflow-x-hidden')[0];
  316. const ul = document.createElement('ul');
  317. div.prepend(ul);
  318. const li = document.createElement('li');
  319. li.textContent = "There is no record. Please verify if webdis AND redis-server has been started! Just run `webdis.sh start` to start.";
  320. li.style.color = 'white';
  321. ul.appendChild(li);
  322. }
  323.  
  324. function showHistoryLog(text) {
  325. // Check if the div with a specific id already exists
  326. var existingDiv = document.getElementById('historyLog');
  327.  
  328. if (existingDiv) {
  329. // If the div exists, update the messageSpan's HTML content
  330. var messageSpan = existingDiv.querySelector('.message-span');
  331. if (messageSpan) {
  332. messageSpan.innerHTML = text;
  333. }
  334. existingDiv.style.display = '';
  335. } else {
  336. // If the div doesn't exist, create a new div and append it to the body
  337. var hoverBox = document.createElement('div');
  338. hoverBox.id = 'historyLog'; // Set a unique id for the div
  339. hoverBox.style.position = 'fixed';
  340. hoverBox.style.top = '50%';
  341. hoverBox.style.left = '50%';
  342. hoverBox.style.transform = 'translate(-50%, -50%)';
  343. hoverBox.style.zIndex = '10000';
  344. hoverBox.style.padding = '10px';
  345. hoverBox.style.width = '1000px';
  346. hoverBox.style.height = '800px';
  347. hoverBox.style.backgroundColor = 'white';
  348. hoverBox.style.border = '1px solid black';
  349. hoverBox.style.borderRadius = '5px';
  350. hoverBox.style.boxShadow = '0px 0px 10px rgba(0, 0, 0, 0.5)';
  351. hoverBox.style.overflow = 'hidden'; // Hide content overflow
  352.  
  353. // Create a container div for the content and close button
  354. var contentContainer = document.createElement('div');
  355. contentContainer.style.overflowY = 'auto'; // Make content scrollable
  356. //contentContainer.style.resize = 'both'; // Enable resizing
  357. contentContainer.style.height = 'calc(100% - 40px)'; // Adjust height for close button
  358.  
  359. // Create a span element to hold the message
  360. var messageSpan = document.createElement('span');
  361. messageSpan.innerHTML = text;
  362. messageSpan.className = 'message-span'; // Add a class for easy selection
  363. messageSpan.style.display = 'block';
  364. messageSpan.style.marginTop = '20px';
  365.  
  366. // Create a button element to close the hover box
  367. var closeButton = document.createElement('button');
  368. closeButton.textContent = '✖';
  369. closeButton.style.position = 'absolute';
  370. closeButton.style.top = '10px';
  371. closeButton.style.right = '10px';
  372. closeButton.addEventListener('click', function () {
  373. hoverBox.style.display = 'none';
  374. });
  375.  
  376. // Add the message span and close button to the content container
  377. contentContainer.appendChild(messageSpan);
  378. contentContainer.appendChild(closeButton);
  379.  
  380. // Add the content container to the hover box
  381. hoverBox.appendChild(contentContainer);
  382.  
  383. document.addEventListener('click', function (event) {
  384. if (!hoverBox.contains(event.target) && event.target !== hoverBox) {
  385. hoverBox.style.display = 'none';
  386. event.stopPropagation();
  387. }
  388. });
  389.  
  390. // Add the hover box to the body of the document
  391. document.body.appendChild(hoverBox);
  392. }
  393. }
  394.  
  395. async function saveHistory(){
  396. while(true){
  397. var thisdialog = getCurrentDialogContent();
  398. save(HistoryPrefix, thisdialog, function(err, response) {
  399. if (err) return console.error(err);
  400. console.log('Save response:', response);
  401. if(!thisInHistory){
  402. InitPanel();
  403. thisInHistory = true;
  404. }
  405. });
  406. const divElement = document.querySelector('div.flex.items-center.md\\:items-end');
  407. if (divElement == undefined || divElement.textContent == undefined || divElement.textContent != 'Stop generating'){
  408. break;
  409. }
  410. if (divElement != undefined && generateButton == null){
  411. generateButton = divElement;
  412. generateButton.addEventListener('click', () => {
  413. saveHistory();
  414. });
  415. }
  416. await sleep(2000);
  417. }
  418. }
  419.  
  420.  
  421.  
  422.  
  423.  
  424.  
  425. InitPanel();
  426.  
  427.  
  428.  
  429.  
  430. document.addEventListener('keydown', function(event) {
  431. if (event.key === 'Enter' || (event.metaKey && event.key === 'r')) {
  432. // Usage examples
  433. saveHistory();
  434. }
  435. if (event.key === 'Escape') {
  436. var existingDiv = document.getElementById('historyLog');
  437. if (existingDiv) {
  438. existingDiv.style.display = 'none';
  439. }
  440. }
  441. });
  442.  
  443.  
  444.  
  445.  
  446.  
  447.  
  448. })();