Summarize with AI

Adds a button or key shortcut to summarize articles, news, and similar content using the OpenAI API (gpt-4o-mini model). The summary is displayed in an overlay with improved styling and loading animation.

当前为 2024-09-27 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Summarize with AI
  3. // @namespace https://github.com/insign/summarize-with-ai
  4. // @version 2024.10.10.1247
  5. // @description Adds a button or key shortcut to summarize articles, news, and similar content using the OpenAI API (gpt-4o-mini model). The summary is displayed in an overlay with improved styling and loading animation.
  6. // @author Hélio
  7. // @license WTFPL
  8. // @match *://*/*
  9. // @grant GM_addStyle
  10. // @grant GM_xmlhttpRequest
  11. // @grant GM_setValue
  12. // @grant GM_getValue
  13. // @connect api.openai.com
  14. // ==/UserScript==
  15.  
  16. (function() {
  17. 'use strict';
  18.  
  19. // Add keydown event listener for 'S' key to trigger summarization
  20. document.addEventListener('keydown', function(e) {
  21. const activeElement = document.activeElement;
  22. const isInput = activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA' || activeElement.isContentEditable);
  23. if (!isInput && (e.key === 's' || e.key === 'S')) {
  24. onSummarizeShortcut();
  25. }
  26. });
  27.  
  28. // Add summarize button if the page is an article
  29. addSummarizeButton();
  30.  
  31. /*** Function Definitions ***/
  32.  
  33. // Function to determine if the page is an article
  34. function isArticlePage() {
  35. // Check for <article> element
  36. if (document.querySelector('article')) {
  37. return true;
  38. }
  39.  
  40. // Check for Open Graph meta tag
  41. const ogType = document.querySelector('meta[property="og:type"]');
  42. if (ogType && ogType.content === 'article') {
  43. return true;
  44. }
  45.  
  46. // Check for news content in the URL
  47. const url = window.location.href;
  48. if (/news|article|story|post/i.test(url)) {
  49. return true;
  50. }
  51.  
  52. // Check for significant text content (e.g., more than 500 words)
  53. const bodyText = document.body.innerText || "";
  54. const wordCount = bodyText.split(/\s+/).length;
  55. if (wordCount > 500) {
  56. return true;
  57. }
  58.  
  59. return false;
  60. }
  61.  
  62. // Function to add the summarize button
  63. function addSummarizeButton() {
  64. if (!isArticlePage()) {
  65. return; // Do not add the button if not an article
  66. }
  67. // Create the button element
  68. const button = document.createElement('div');
  69. button.id = 'summarize-button';
  70. button.innerText = 'S';
  71. document.body.appendChild(button);
  72.  
  73. // Add event listeners
  74. button.addEventListener('click', onSummarizeClick);
  75. button.addEventListener('dblclick', onApiKeyReset);
  76.  
  77. // Add styles
  78. GM_addStyle(`
  79. #summarize-button {
  80. position: fixed;
  81. bottom: 20px;
  82. right: 20px;
  83. width: 50px;
  84. height: 50px;
  85. background-color: #007bff;
  86. color: white;
  87. font-size: 24px;
  88. font-weight: bold;
  89. text-align: center;
  90. line-height: 50px;
  91. border-radius: 50%;
  92. cursor: pointer;
  93. z-index: 10000;
  94. box-shadow: 0 2px 5px rgba(0,0,0,0.3);
  95. }
  96. #summarize-overlay {
  97. position: fixed;
  98. top: 50%;
  99. left: 50%;
  100. transform: translate(-50%, -50%);
  101. background-color: white;
  102. z-index: 10001;
  103. padding: 20px;
  104. box-shadow: 0 0 10px rgba(0,0,0,0.5);
  105. overflow: auto;
  106. font-size: 1.1em;
  107. max-width: 90%;
  108. max-height: 90%;
  109. border-radius: 8px;
  110. }
  111. #summarize-overlay h2 {
  112. margin-top: 0;
  113. font-size: 1.5em;
  114. }
  115. #summarize-close {
  116. position: absolute;
  117. top: 10px;
  118. right: 10px;
  119. cursor: pointer;
  120. font-size: 22px;
  121. }
  122. #summarize-content {
  123. margin-top: 20px;
  124. }
  125. #summarize-error {
  126. position: fixed;
  127. bottom: 20px;
  128. left: 20px;
  129. background-color: rgba(255,0,0,0.8);
  130. color: white;
  131. padding: 10px 20px;
  132. border-radius: 5px;
  133. z-index: 10002;
  134. }
  135. .glow {
  136. font-size: 1.2em;
  137. color: #fff;
  138. text-align: center;
  139. animation: glow 1.5s ease-in-out infinite alternate;
  140. }
  141. @keyframes glow {
  142. from {
  143. text-shadow: 0 0 10px #00e6e6, 0 0 20px #00e6e6, 0 0 30px #00e6e6, 0 0 40px #00e6e6, 0 0 50px #00e6e6, 0 0 60px #00e6e6;
  144. }
  145. to {
  146. text-shadow: 0 0 20px #00ffff, 0 0 30px #00ffff, 0 0 40px #00ffff, 0 0 50px #00ffff, 0 0 60px #00ffff, 0 0 70px #00ffff;
  147. }
  148. }
  149. @media (max-width: 768px) {
  150. #summarize-overlay {
  151. width: 90%;
  152. height: 90%;
  153. }
  154. }
  155. @media (min-width: 769px) {
  156. #summarize-overlay {
  157. width: 60%;
  158. height: 85%;
  159. }
  160. }
  161. `);
  162. }
  163.  
  164. // Handler for clicking the "S" button
  165. function onSummarizeClick() {
  166. const apiKey = getApiKey();
  167. if (!apiKey) {
  168. return;
  169. }
  170.  
  171. // Capture page source
  172. const pageContent = document.documentElement.outerHTML;
  173.  
  174. // Show summary overlay with loading message
  175. showSummaryOverlay('<p class="glow">Generating summary...</p>');
  176.  
  177. // Send content to OpenAI API
  178. summarizeContent(apiKey, pageContent);
  179. }
  180.  
  181. // Handler for the "S" key shortcut
  182. function onSummarizeShortcut() {
  183. const apiKey = getApiKey();
  184. if (!apiKey) {
  185. return;
  186. }
  187.  
  188. if (!isArticlePage()) {
  189. // Show a quick warning
  190. alert('This page may not be an article. Proceeding to summarize anyway.');
  191. }
  192.  
  193. // Capture page source
  194. const pageContent = document.documentElement.outerHTML;
  195.  
  196. // Show summary overlay with loading message
  197. showSummaryOverlay('<p class="glow">Generating summary...</p>');
  198.  
  199. // Send content to OpenAI API
  200. summarizeContent(apiKey, pageContent);
  201. }
  202.  
  203. // Handler for resetting the API key
  204. function onApiKeyReset() {
  205. const newKey = prompt('Please enter your OpenAI API key:', '');
  206. if (newKey) {
  207. GM_setValue('openai_api_key', newKey.trim());
  208. alert('API key updated successfully.');
  209. }
  210. }
  211.  
  212. // Function to get the API key
  213. function getApiKey() {
  214. let apiKey = GM_getValue('openai_api_key');
  215. if (!apiKey) {
  216. apiKey = prompt('Please enter your OpenAI API key:', '');
  217. if (apiKey) {
  218. GM_setValue('openai_api_key', apiKey.trim());
  219. } else {
  220. alert('API key is required to generate a summary.');
  221. return null;
  222. }
  223. }
  224. return apiKey.trim();
  225. }
  226.  
  227. // Function to show the summary overlay
  228. function showSummaryOverlay(initialContent = '') {
  229. // Create the overlay
  230. const overlay = document.createElement('div');
  231. overlay.id = 'summarize-overlay';
  232. overlay.innerHTML = `
  233. <div id="summarize-close">&times;</div>
  234. <div id="summarize-content">${initialContent}</div>
  235. `;
  236. document.body.appendChild(overlay);
  237.  
  238. // Add event listener for close button
  239. document.getElementById('summarize-close').addEventListener('click', closeOverlay);
  240.  
  241. // Add event listener for 'Escape' key to close the overlay
  242. document.addEventListener('keydown', onEscapePress);
  243.  
  244. function onEscapePress(e) {
  245. if (e.key === 'Escape') {
  246. closeOverlay();
  247. }
  248. }
  249.  
  250. function closeOverlay() {
  251. overlay.remove();
  252. document.removeEventListener('keydown', onEscapePress);
  253. }
  254. }
  255.  
  256. // Function to update the summary content
  257. function updateSummaryOverlay(content) {
  258. const contentDiv = document.getElementById('summarize-content');
  259. if (contentDiv) {
  260. contentDiv.innerHTML = content;
  261. }
  262. }
  263.  
  264. // Function to display an error notification
  265. function showErrorNotification(message) {
  266. const errorDiv = document.createElement('div');
  267. errorDiv.id = 'summarize-error';
  268. errorDiv.innerText = message;
  269. document.body.appendChild(errorDiv);
  270.  
  271. // Remove the notification after 4 seconds
  272. setTimeout(() => {
  273. errorDiv.remove();
  274. }, 4000);
  275. }
  276.  
  277. // Function to summarize the content using OpenAI API (non-streaming)
  278. function summarizeContent(apiKey, content) {
  279. const userLanguage = navigator.language || 'en';
  280.  
  281. // Prepare the API request
  282. const apiUrl = 'https://api.openai.com/v1/chat/completions';
  283. const requestData = {
  284. model: 'gpt-4o-mini',
  285. messages: [
  286. {
  287. role: 'system', content: `You are a helpful assistant that summarizes articles based on the HTML content provided. You must generate a concise summary that includes a short introduction, followed by a list of topics, and ends with a short conclusion. For the topics, you must use appropriate emojis as bullet points, and the topics must consist of descriptive titles as brief of its content resuming that topic subject.
  288.  
  289. You must always use HTML tags to structure the summary text. The title must be wrapped in h2 tags, and you must always use the user's language besides the article's original language. The generated HTML must be ready to be injected into the final target, and you must never use markdown.
  290.  
  291. Required structure:
  292. - Use h2 for the summary title
  293. - Use paragraphs for the introduction and conclusion
  294. - Use appropriate emojis for topics
  295. - Do not add text like "Article summary" or "Summary of the article" in the summary, nor "Introduction", "Topics", "Conclusion", etc
  296.  
  297. User language: ${userLanguage}.
  298. Adapt the text to be short, concise, and informative.
  299. `
  300.  
  301. },
  302. { role: 'user', content: `Page content: \n\n${content}` }
  303. ],
  304. max_tokens: 500,
  305. temperature: 0.5,
  306. n: 1,
  307. stream: false
  308. };
  309.  
  310. // Send the request using GM_xmlhttpRequest
  311. GM_xmlhttpRequest({
  312. method: 'POST',
  313. url: apiUrl,
  314. headers: {
  315. 'Content-Type': 'application/json',
  316. 'Authorization': `Bearer ${apiKey}`
  317. },
  318. data: JSON.stringify(requestData),
  319. onload: function(response) {
  320. if (response.status === 200) {
  321. const resData = JSON.parse(response.responseText);
  322. const summary = resData.choices[0].message.content;
  323. updateSummaryOverlay(summary.replaceAll('\n', '<br>'));
  324. } else {
  325. showErrorNotification('Error: Failed to retrieve summary.');
  326. updateSummaryOverlay('<p>Error: Failed to retrieve summary.</p>');
  327. }
  328. },
  329. onerror: function() {
  330. showErrorNotification('Error: Network error.');
  331. updateSummaryOverlay('<p>Error: Network error.</p>');
  332. },
  333. onabort: function() {
  334. showErrorNotification('Request canceled.');
  335. updateSummaryOverlay('<p>Request canceled.</p>');
  336. }
  337. });
  338. }
  339.  
  340. })();