-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwidget.js
367 lines (336 loc) · 10.3 KB
/
widget.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/* jshint browser: true, jquery: true */
/* globals $, mw, OO */
// ==UserScript==
// @name Wikipedia ChatGPT section summaries
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Experiment to use ChatGPT to summarize page sections.
// @author Aleksei
// @author tonythomas01
// @author Tgr
// @license GPL-3.0-or-later
// @match https://*.wikipedia.org/*
// @icon https://doc.wikimedia.org/oojs-ui/master/demos/dist/themes/wikimediaui/images/icons/robot.svg
// @grant none
// ==/UserScript==
function initializeSectionSummarizer() {
const summarizerSections = getSections();
window.summarizerSections = summarizerSections;
if (summarizerSections.length === 0) {
console.error("Section Summarizer could not find suitable sections");
} else {
injectSummaryWidgets(summarizerSections, 300);
}
}
function injectSummaryWidgets(sections, minChars = 0) {
sections.forEach(function (section) {
if (section.contentPlainLength > minChars) {
const widget = document.createElement("div");
widget.className = "section-summary-widget";
widget.innerHTML = [
'<div class="section-summary-widget__collapsed"></div>',
'<div class="section-summary-widget__loading">',
" <div>Summarizing the section...</div>",
"</div>",
'<div class="section-summary-widget__completed">',
' <div class="section-summary-widget__summary"></div>',
' <div class="section-summary-widget__disclaimer">',
" This summary was generated by AI and can contain errors.",
" </div>",
"</div>",
'<div class="section-summary-widget__error"></div>',
].join("");
section.firstContentElement.parentNode.insertBefore(
widget,
section.firstContentElement
);
const collapsedSection = widget.querySelector(
".section-summary-widget__collapsed"
);
const summarizeButton = new OO.ui.ButtonWidget({
label: "Summarize",
title: "Click to summarize the section",
icon: "robot",
framed: false,
});
summarizeButton.on("click", function (event) {
const sectionHeadingFromDOM = summarizeButton.$element
.parent()
.parent()
.prev(".mw-heading");
widget.classList.remove("collapsed");
widget.classList.add("loading");
const summaryDiv = widget.querySelector(
".section-summary-widget__summary"
);
const updateSummary = (newSummary) => {
summaryDiv.textContent = newSummary;
widget.classList.remove("loading");
widget.classList.add("completed");
};
summarizeSection(section, updateSummary, sectionHeadingFromDOM)
.then(function (summary) {
// This part is not needed anymore since we update the summary in the updateSummary function
})
.catch(function (error) {
const errorDiv = widget.querySelector(
".section-summary-widget__error"
);
errorDiv.textContent = "Error: " + error;
widget.classList.remove("loading");
widget.classList.add("error");
});
});
// Append button to collapsedSection
$(collapsedSection).append(summarizeButton.$element);
widget.classList.add("collapsed");
}
});
}
var discussionToolsInfo;
function getSectionData($heading) {
var dataPromise;
if (discussionToolsInfo) {
dataPromise = $.Deferred().resolve(discussionToolsInfo);
} else {
dataPromise = mw.loader
.using(["mediawiki.api"])
.then(function () {
return new mw.Api().get({
action: "discussiontoolspageinfo",
page: mw.config.get("wgPageName"),
prop: "threaditemshtml",
format: "json",
formatversion: 2,
});
})
.then(function (data) {
discussionToolsInfo = data;
return data;
});
}
var sectionId = $heading.find(".mw-headline").data("mw-thread-id");
var sectionContent = [];
var processReplies = function (reply) {
if (reply.type === "comment") {
sectionContent.push({
type: "comment",
level: reply.level,
author: reply.author,
text: getCommentTextFromHtml(reply.html),
});
for (var i = 0; i < reply.replies.length; i++) {
processReplies(reply.replies[i]);
}
} else if (reply.type === "heading") {
sectionContent.push({
type: "heading",
level: reply.level,
headingLevel: reply.headingLevel,
text: getCommentTextFromHtml(reply.html),
});
for (var i = 0; i < reply.replies.length; i++) {
processReplies(reply.replies[i]);
}
} else {
console.log("Unexpected type: " + reply.type, reply);
}
};
return dataPromise.then(function (data) {
for (
var i = 0;
i < data.discussiontoolspageinfo.threaditemshtml.length;
i++
) {
var section = data.discussiontoolspageinfo.threaditemshtml[i];
if (section.id === sectionId) {
sectionContent.push({
type: "heading",
level: 0,
headingLevel: section.level,
text: getCommentTextFromHtml(section.html),
});
for (var j = 0; j < section.replies.length; j++) {
processReplies(section.replies[j]);
}
}
}
return sectionContent;
});
}
/**
* @param {string} html
* @return {string}
*/
function getCommentTextFromHtml(html) {
return $.parseHTML("<div>" + html + "</div>")
.map((el) => el.innerText || "")
.join("");
}
/**
* @param {jQuery} $heading
* @return {jQuery.Promise<string>}
*/
function getSectionText($heading) {
return getSectionData($heading).then(function (data) {
var sectionText = "";
for (var i = 0; i < data.length; i++) {
var item = data[i];
if (item.type === "heading") {
sectionText +=
"\t".repeat(item.level) +
"=".repeat(item.headingLevel) +
item.text +
"=".repeat(item.headingLevel) +
"\n\n";
} else if (item.type === "comment") {
sectionText += (item.author + ": " + item.text).replace(
/^|\n/g,
"$&" + "\t".repeat(item.level)
);
}
sectionText += "\n\n";
}
return sectionText;
});
}
function summarizeSection(section, updateSummary, sectionHeadingFromDOM) {
return new Promise(function (resolve, reject) {
const openAiKey = getOpenAiKey();
if (!openAiKey) {
reject("OpenAI API key not found or invalid");
return;
}
const namespace = mw.config.get("wgCanonicalNamespace");
if (namespace === "Talk") {
// Use @Tgrs solution to parse things from the API instead.
getSectionText(sectionHeadingFromDOM).then(function (sectionText) {
const fixedPromptForChatGPT =
"Summarize the following discussion section in less than 100 words. Username is followed by what they" +
"wrote. Indentation is used to denote threaded replies. Use the usernames in the summary as well. \n";
fetchSummaryUsingOpenAi(
fixedPromptForChatGPT,
openAiKey,
sectionText,
updateSummary,
function (error, summary) {
if (error) {
reject(error);
} else {
resolve(summary);
}
}
);
});
} else {
const sectionContent =
"## " + section.title + "\n\n" + section.contentPlain;
const fixedPromptForChatGPT =
"Summarize the following section in less than 50 words: ";
fetchSummaryUsingOpenAi(
fixedPromptForChatGPT,
openAiKey,
sectionContent,
updateSummary,
function (error, summary) {
if (error) {
reject(error);
} else {
resolve(summary);
}
}
);
}
});
}
async function fetchSummaryUsingOpenAi(
fixedPromptForChatGPT,
openAiKey,
sectionText,
updateSummary,
callback
) {
const prompt = fixedPromptForChatGPT + sectionText;
console.log("prompt", prompt);
try {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openAiKey}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{
role: "user",
content: prompt,
},
],
stream: true,
temperature: 0,
}),
});
if (response.status !== 200) {
const errorText = await response.text();
console.error("Error:", errorText);
callback(
new Error(`API responded with status ${response.status}: ${errorText}`)
);
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let summary = "";
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
buffer += decoder.decode(value, { stream: true });
let start = 0;
let end = buffer.indexOf("\n");
while (end !== -1) {
const line = buffer
.slice(start, end)
.replace(/^data: /, "")
.trim();
if (line !== "" && line !== "[DONE]") {
const parsedLine = JSON.parse(line);
const { choices } = parsedLine;
const { delta } = choices[0];
const { content } = delta;
if (content) {
summary += content;
updateSummary(summary); // Update the summary content in the widget
}
}
start = end + 1;
end = buffer.indexOf("\n", start);
}
buffer = buffer.slice(start);
}
callback(null, summary);
} catch (error) {
console.error("Error:", error);
callback(error);
}
}
function getOpenAiKey() {
let openAiKey = localStorage.getItem("openAiKey");
if (!openAiKey) {
const userInput = prompt(
'Please enter your OpenAI API key (it should start with "sk-"):'
);
if (userInput && userInput.startsWith("sk-")) {
openAiKey = userInput;
localStorage.setItem("openAiKey", openAiKey);
} else {
console.error("Invalid OpenAI API key provided.");
return null;
}
}
return openAiKey;
}
function openSettings() {}