chatgpt-page-summary-button

🍓 let ChatGPT summary the web page you are reading in one click

目前為 2023-05-29 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name chatgpt-page-summary-button
  3. // @description 🍓 let ChatGPT summary the web page you are reading in one click
  4. // @author mefengl
  5. // @version 0.1.5
  6. // @namespace https://github.com/mefengl
  7. // @require https://cdn.jsdelivr.net/npm/@mozilla/readability@0.4.3/Readability.min.js
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=openai.com
  9. // @license MIT
  10. // @match *://*/*
  11. // @grant GM_setValue
  12. // @grant GM_getValue
  13. // @grant GM_addValueChangeListener
  14.  
  15. // @name:en ChatGPT Page Summary Button
  16. // @description:en 🍓 let ChatGPT summarize the web page you are reading in one click
  17. // @name:zh-CN ChatGPT 页面摘要按钮
  18. // @description:zh-CN 🍓 让 ChatGPT 一键总结您正在阅读的网页
  19. // @name:es Botón de resumen de página de ChatGPT
  20. // @description:es 🍓 permite que ChatGPT resuma la página web que estás leyendo con un solo clic
  21. // @name:hi ChatGPT पृष्ठ सारांश बटन
  22. // @description:hi 🍓 ChatGPT को वेबपेज जो आप पढ़ रहे हैं को एक क्लिक में संक्षेप में देने दें
  23. // @name:ar زر ملخص الصفحة لـ ChatGPT
  24. // @description:ar 🍓 دع ChatGPT يلخص صفحة الويب التي تقرأها بنقرة واحدة
  25. // @name:pt Botão de resumo de página do ChatGPT
  26. // @description:pt 🍓 permita que o ChatGPT resuma a página da web que você está lendo com um clique
  27. // @name:ru Кнопка резюме страницы ChatGPT
  28. // @description:ru 🍓 позволяет ChatGPT кратко описывать веб-страницу, которую вы читаете, одним щелчком мыши
  29. // @name:ja ChatGPTページ要約ボタン
  30. // @description:ja 🍓 ChatGPTで読んでいるWebページをワンクリックで要約
  31. // @name:de ChatGPT-Seitenzusammenfassungs-Button
  32. // @description:de 🍓 Lassen Sie ChatGPT die Webseite, die Sie gerade lesen, mit einem Klick zusammenfassen
  33. // @name:fr Bouton de résumé de page ChatGPT
  34. // @description:fr 🍓 laissez ChatGPT résumer la page Web que vous lisez en un seul clic
  35. // ==/UserScript==
  36. "use strict";
  37. (() => {
  38. var __create = Object.create;
  39. var __defProp = Object.defineProperty;
  40. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  41. var __getOwnPropNames = Object.getOwnPropertyNames;
  42. var __getProtoOf = Object.getPrototypeOf;
  43. var __hasOwnProp = Object.prototype.hasOwnProperty;
  44. var __commonJS = (cb, mod) => function __require() {
  45. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  46. };
  47. var __copyProps = (to, from, except, desc) => {
  48. if (from && typeof from === "object" || typeof from === "function") {
  49. for (let key of __getOwnPropNames(from))
  50. if (!__hasOwnProp.call(to, key) && key !== except)
  51. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  52. }
  53. return to;
  54. };
  55. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  56. // If the importer is in node compatibility mode or this is not an ESM
  57. // file that has been converted to a CommonJS file using a Babel-
  58. // compatible transform (i.e. "__esModule" has not been set), then set
  59. // "default" to the CommonJS "module.exports" for node compatibility.
  60. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  61. mod
  62. ));
  63. var __async = (__this, __arguments, generator) => {
  64. return new Promise((resolve, reject) => {
  65. var fulfilled = (value) => {
  66. try {
  67. step(generator.next(value));
  68. } catch (e) {
  69. reject(e);
  70. }
  71. };
  72. var rejected = (value) => {
  73. try {
  74. step(generator.throw(value));
  75. } catch (e) {
  76. reject(e);
  77. }
  78. };
  79. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  80. step((generator = generator.apply(__this, __arguments)).next());
  81. });
  82. };
  83.  
  84. // ../../packages/chatkit/dist/chatgpt/index.js
  85. var require_chatgpt = __commonJS({
  86. "../../packages/chatkit/dist/chatgpt/index.js"(exports, module) {
  87. "use strict";
  88. var __defProp2 = Object.defineProperty;
  89. var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
  90. var __getOwnPropNames2 = Object.getOwnPropertyNames;
  91. var __hasOwnProp2 = Object.prototype.hasOwnProperty;
  92. var __export = (target, all) => {
  93. for (var name in all)
  94. __defProp2(target, name, { get: all[name], enumerable: true });
  95. };
  96. var __copyProps2 = (to, from, except, desc) => {
  97. if (from && typeof from === "object" || typeof from === "function") {
  98. for (let key of __getOwnPropNames2(from))
  99. if (!__hasOwnProp2.call(to, key) && key !== except)
  100. __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
  101. }
  102. return to;
  103. };
  104. var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
  105. var chatgpt_exports = {};
  106. __export(chatgpt_exports, {
  107. getContinueGeneratingButton: () => getContinueGeneratingButton,
  108. getConversation: () => getConversation,
  109. getHistoryBlockTitle: () => getHistoryBlockTitle,
  110. getHistoryBlocks: () => getHistoryBlocks,
  111. getHistoryBlocksWithTitle: () => getHistoryBlocksWithTitle,
  112. getLastResponse: () => getLastResponse,
  113. getLastResponseElement: () => getLastResponseElement,
  114. getModelSelectButton: () => getModelSelectButton,
  115. getNav: () => getNav,
  116. getNewModelSelectButtons: () => getNewModelSelectButtons,
  117. getRegenerateButton: () => getRegenerateButton,
  118. getStopGeneratingButton: () => getStopGeneratingButton,
  119. getSubmitButton: () => getSubmitButton,
  120. getTextarea: () => getTextarea,
  121. getTextareaValue: () => getTextareaValue,
  122. hasNewModelSelectButtons: () => hasNewModelSelectButtons,
  123. isConversationStarted: () => isConversationStarted,
  124. isGenerating: () => isGenerating,
  125. isHorizontalConversation: () => isHorizontalConversation,
  126. onSend: () => onSend,
  127. regenerate: () => regenerate,
  128. send: () => send,
  129. setHorizontalConversation: () => setHorizontalConversation,
  130. setPromptListener: () => setPromptListener2,
  131. setPureConversation: () => setPureConversation,
  132. setTextarea: () => setTextarea,
  133. waitForIdle: () => waitForIdle
  134. });
  135. module.exports = __toCommonJS(chatgpt_exports);
  136. function getNav() {
  137. return document.querySelector("nav");
  138. }
  139. function getHistoryBlocks() {
  140. const nav = getNav();
  141. if (!nav)
  142. return [];
  143. const result = Array.from(nav.querySelectorAll("ol")).map((ol) => ol.parentElement);
  144. return result;
  145. }
  146. function getHistoryBlockTitle(historyBlock) {
  147. var _a;
  148. return ((_a = historyBlock.querySelector("h3")) == null ? void 0 : _a.textContent) || "";
  149. }
  150. function getHistoryBlocksWithTitle() {
  151. const historyBlocks = getHistoryBlocks();
  152. const result = historyBlocks.map((historyBlock) => ({
  153. block: historyBlock,
  154. title: getHistoryBlockTitle(historyBlock)
  155. }));
  156. return result;
  157. }
  158. function getTextarea() {
  159. const form = document.querySelector("form");
  160. if (!form)
  161. return;
  162. const textareas = form.querySelectorAll("textarea");
  163. const result = textareas[0];
  164. return result;
  165. }
  166. function getSubmitButton() {
  167. const textarea = getTextarea();
  168. if (!textarea)
  169. return;
  170. return textarea.nextElementSibling;
  171. }
  172. function getRegenerateButton() {
  173. const form = document.querySelector("form");
  174. if (!form)
  175. return;
  176. const buttons = form.querySelectorAll("button");
  177. const result = Array.from(buttons).find((button) => {
  178. var _a;
  179. return (_a = button.textContent) == null ? void 0 : _a.trim().toLowerCase().includes("regenerate");
  180. });
  181. return result;
  182. }
  183. function getContinueGeneratingButton() {
  184. const form = document.querySelector("form");
  185. if (!form)
  186. return;
  187. const buttons = form.querySelectorAll("button");
  188. const result = Array.from(buttons).find((button) => {
  189. var _a;
  190. return (_a = button.textContent) == null ? void 0 : _a.trim().toLowerCase().includes("continue generating");
  191. });
  192. return result;
  193. }
  194. function getStopGeneratingButton() {
  195. const form = document.querySelector("form");
  196. if (!form)
  197. return;
  198. const buttons = form.querySelectorAll("button");
  199. const result = Array.from(buttons).find((button) => {
  200. var _a;
  201. return (_a = button.textContent) == null ? void 0 : _a.trim().toLowerCase().includes("stop generating");
  202. });
  203. return result;
  204. }
  205. function getLastResponseElement() {
  206. const responseElements = document.querySelectorAll(".group.w-full");
  207. return responseElements[responseElements.length - 1];
  208. }
  209. function getLastResponse() {
  210. const lastResponseElement = getLastResponseElement();
  211. if (!lastResponseElement)
  212. return;
  213. const lastResponse = lastResponseElement.textContent;
  214. return lastResponse;
  215. }
  216. function getTextareaValue() {
  217. var _a;
  218. return ((_a = getTextarea()) == null ? void 0 : _a.value) || "";
  219. }
  220. function setTextarea(message) {
  221. const textarea = getTextarea();
  222. if (!textarea)
  223. return;
  224. textarea.value = message;
  225. textarea.dispatchEvent(new Event("input"));
  226. }
  227. function send(message) {
  228. setTextarea(message);
  229. const textarea = getTextarea();
  230. if (!textarea)
  231. return;
  232. textarea.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
  233. }
  234. function regenerate() {
  235. const regenerateButton = getRegenerateButton();
  236. if (!regenerateButton)
  237. return;
  238. regenerateButton.click();
  239. }
  240. function onSend(callback) {
  241. const textarea = getTextarea();
  242. if (!textarea)
  243. return;
  244. textarea.addEventListener("keydown", function(event) {
  245. if (event.key === "Enter" && !event.shiftKey) {
  246. callback();
  247. }
  248. });
  249. const sendButton = getSubmitButton();
  250. if (!sendButton)
  251. return;
  252. sendButton.addEventListener("mousedown", callback);
  253. }
  254. function isGenerating() {
  255. var _a, _b;
  256. return ((_b = (_a = getSubmitButton()) == null ? void 0 : _a.firstElementChild) == null ? void 0 : _b.childElementCount) === 3;
  257. }
  258. function waitForIdle() {
  259. return new Promise((resolve) => {
  260. const interval = setInterval(() => {
  261. if (!isGenerating()) {
  262. clearInterval(interval);
  263. resolve();
  264. }
  265. }, 1e3);
  266. });
  267. }
  268. function setPromptListener2(key = "prompt_texts") {
  269. let last_trigger_time = +/* @__PURE__ */ new Date();
  270. if (location.href.includes("chat.openai")) {
  271. GM_addValueChangeListener(key, (name, old_value, new_value) => __async(this, null, function* () {
  272. if (+/* @__PURE__ */ new Date() - last_trigger_time < 500) {
  273. return;
  274. }
  275. last_trigger_time = +/* @__PURE__ */ new Date();
  276. setTimeout(() => __async(this, null, function* () {
  277. const prompt_texts = new_value;
  278. if (prompt_texts.length > 0) {
  279. let firstTime = true;
  280. while (prompt_texts.length > 0) {
  281. if (!firstTime) {
  282. yield new Promise((resolve) => setTimeout(resolve, 2e3));
  283. }
  284. if (!firstTime && isGenerating()) {
  285. continue;
  286. }
  287. firstTime = false;
  288. const prompt_text = prompt_texts.shift() || "";
  289. send(prompt_text);
  290. }
  291. }
  292. }), 0);
  293. GM_setValue(key, []);
  294. }));
  295. }
  296. }
  297. function getConversation() {
  298. var _a, _b;
  299. return (_b = (_a = document.querySelector('div[class^="react-scroll-to-bottom"]')) == null ? void 0 : _a.firstChild) == null ? void 0 : _b.firstChild;
  300. }
  301. function getModelSelectButton() {
  302. const conversation = getConversation();
  303. if (!conversation)
  304. return;
  305. return Array.from(conversation.querySelectorAll("button")).find((button) => {
  306. var _a;
  307. return (_a = button.textContent) == null ? void 0 : _a.trim().toLowerCase().includes("model");
  308. });
  309. }
  310. function getNewModelSelectButtons() {
  311. return Array.from(document.querySelectorAll("[class^='group/button']"));
  312. }
  313. function hasNewModelSelectButtons() {
  314. return getNewModelSelectButtons().length > 0;
  315. }
  316. function isConversationStarted() {
  317. return !getModelSelectButton();
  318. }
  319. function setPureConversation() {
  320. const conversation = getConversation();
  321. if (!conversation)
  322. return;
  323. const firstChild = conversation.firstChild;
  324. if (!firstChild)
  325. return;
  326. const newDiv = document.createElement("div");
  327. conversation.insertBefore(newDiv, firstChild.nextSibling);
  328. }
  329. function isHorizontalConversation() {
  330. const conversation = getConversation();
  331. if (!conversation)
  332. return true;
  333. if (!isConversationStarted())
  334. return true;
  335. return conversation.classList.contains("grid");
  336. }
  337. function setHorizontalConversation() {
  338. if (isHorizontalConversation())
  339. return;
  340. setPureConversation();
  341. const conversation = getConversation();
  342. if (!conversation)
  343. return;
  344. conversation.classList.remove("flex", "flex-col", "items-center");
  345. conversation.classList.add("grid", "grid-cols-2", "place-items-center");
  346. }
  347. }
  348. });
  349.  
  350. // ../../packages/chatkit/chatgpt.js
  351. var require_chatgpt2 = __commonJS({
  352. "../../packages/chatkit/chatgpt.js"(exports, module) {
  353. module.exports = require_chatgpt();
  354. }
  355. });
  356.  
  357. // src/index.ts
  358. var import_chatgpt = __toESM(require_chatgpt2(), 1);
  359.  
  360. // src/createButton/index.ts
  361. function createButton(callback) {
  362. if (window.location.href.includes("chat.openai")) {
  363. return;
  364. }
  365. const hideRight = document.title.match(/[\u4e00-\u9fa5]/) ? "-130px" : "-120px";
  366. const button = document.createElement("button");
  367. button.innerHTML = "\u7F51\u9875\u603B\u7ED3";
  368. button.style.position = "fixed";
  369. button.style.width = "140px";
  370. button.style.top = "180px";
  371. button.style.right = hideRight;
  372. button.style.zIndex = "999999";
  373. button.style.backgroundColor = "#F8BBC6";
  374. button.style.color = "#fff";
  375. button.style.opacity = "0.8";
  376. button.style.border = "none";
  377. button.style.borderRadius = "4px";
  378. button.style.padding = "10px 16px";
  379. button.style.fontSize = "18px";
  380. button.style.cursor = "pointer";
  381. button.style.transition = "right 0.3s";
  382. document.body.appendChild(button);
  383. button.addEventListener("mouseenter", () => {
  384. button.style.right = "-10px";
  385. });
  386. button.addEventListener("mouseleave", () => {
  387. button.style.right = hideRight;
  388. });
  389. document.addEventListener("fullscreenchange", () => {
  390. if (document.fullscreenElement) {
  391. button.style.display = "none";
  392. } else {
  393. button.style.display = "block";
  394. }
  395. });
  396. button.addEventListener("click", callback);
  397. }
  398. var createButton_default = createButton;
  399.  
  400. // src/SimpleArticleSegmentation/index.ts
  401. var MIN_PARAGRAPH_LENGTH = 1600;
  402. var MAX_PARAGRAPH_LENGTH = 1800;
  403. var SimpleArticleSegmentation = class {
  404. constructor(text) {
  405. this.text = text;
  406. }
  407. segment() {
  408. const paragraphs = [];
  409. const sentences = this.text.split(new RegExp("(?<=[.!?])\\s+"));
  410. let paragraph = "";
  411. for (const sentence of sentences) {
  412. if (paragraph.length + sentence.length + 1 <= MAX_PARAGRAPH_LENGTH) {
  413. paragraph += (paragraph.length > 0 ? " " : "") + sentence;
  414. } else {
  415. if (paragraph.length >= MIN_PARAGRAPH_LENGTH) {
  416. paragraphs.push(paragraph);
  417. paragraph = sentence;
  418. } else {
  419. paragraph += " " + sentence;
  420. }
  421. }
  422. }
  423. if (paragraph.length >= MIN_PARAGRAPH_LENGTH) {
  424. paragraphs.push(paragraph);
  425. }
  426. return paragraphs;
  427. }
  428. };
  429. var SimpleArticleSegmentation_default = SimpleArticleSegmentation;
  430.  
  431. // src/getParagraphs/index.ts
  432. function getParagraphs() {
  433. try {
  434. let docClone = document.cloneNode(true);
  435. let article = new Readability(docClone).parse();
  436. if (article && article.textContent) {
  437. const segmenter = new SimpleArticleSegmentation_default(article.textContent);
  438. const paragraphs = segmenter.segment();
  439. for (let i = 0; i < paragraphs.length; i++) {
  440. paragraphs[i] = paragraphs[i].trim();
  441. }
  442. return paragraphs;
  443. } else {
  444. console.warn("Readability.js could not extract any text content from this page.");
  445. return [];
  446. }
  447. } catch (error) {
  448. console.error("An error occurred while using Readability.js:", error);
  449. return [];
  450. }
  451. }
  452. var getParagraphs_default = getParagraphs;
  453.  
  454. // src/index.ts
  455. function initialize() {
  456. return __async(this, null, function* () {
  457. yield new Promise((resolve) => window.addEventListener("load", resolve));
  458. yield new Promise((resolve) => setTimeout(resolve, 1e3));
  459. });
  460. }
  461. function main() {
  462. return __async(this, null, function* () {
  463. yield initialize();
  464. const key = "prompt_texts";
  465. (0, import_chatgpt.setPromptListener)(key);
  466. const summaryWeb = () => __async(this, null, function* () {
  467. const paragraphs = getParagraphs_default();
  468. console.log(paragraphs);
  469. const prompt_texts = paragraphs.map((paragraph) => {
  470. return `"""
  471. ${paragraph}
  472. """
  473. Summarize this paragraph into a bulleted list of the most important information, prefix with emoji. Use Markdown syntax to optimize the display format:`;
  474. });
  475. console.log(prompt_texts);
  476. GM_setValue(key, prompt_texts);
  477. });
  478. createButton_default(summaryWeb);
  479. });
  480. }
  481. (function() {
  482. main();
  483. })();
  484. })();