Skip to content

Instantly share code, notes, and snippets.

@Recursing
Last active August 5, 2023 15:06
Show Gist options
  • Save Recursing/27107caa5f7bd12e13bf34dfd6fec834 to your computer and use it in GitHub Desktop.
Save Recursing/27107caa5f7bd12e13bf34dfd6fec834 to your computer and use it in GitHub Desktop.
Writes a 10 bullet point summary for posts on https://forum.effectivealtruism.org/ Copy it here: https://mrcoles.com/bookmarklet/ You'll need an API key from OpenAI https://platform.openai.com/account/api-keys
(async function () {
const API_KEY = "YOUR_API_KEY";
const SYSTEM_PROMPT = "Summarize the following article in 10 bullet points:";
async function getSummary(text) {
const API_URL = "https://api.openai.com/v1/chat/completions";
const data = {
model: "gpt-3.5-turbo-16k",
messages: [
{
role: "system",
content: SYSTEM_PROMPT,
},
{
role: "user",
content: text,
},
],
};
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + API_KEY,
},
body: JSON.stringify(data),
});
const json = await response.json();
return json.choices[0].message.content;
}
function getTextChunks(node) {
if (node.nodeType === 3) {
return [node.textContent];
}
if (node.offsetParent === null) {
return [];
}
let nodes = [];
for (const child of node.childNodes) {
nodes = nodes.concat(getTextChunks(child));
}
return nodes;
}
const title = document.querySelector("h1.PostsPageTitle-root")?.textContent;
let body = document.querySelector(".PostsPage-postContent");
if (!body || !title) {
throw Error("No body or title found");
}
let paragraphs = getTextChunks(body);
let chunks = [paragraphs.shift()];
while (paragraphs.length > 0) {
const next_paragraph = paragraphs.shift();
if (chunks.at(-1).length + next_paragraph.length < 45000) {
chunks[chunks.length - 1] += "\n\n" + next_paragraph;
} else {
chunks.push(next_paragraph);
}
}
const queries = chunks.map((chunk) => title + "\n\n" + chunk);
const bodyEl = document.querySelector(".PostsPage-postContent");
const newElement = document.createElement("div");
newElement.style =
"white-space:pre-wrap;border:#333 3px solid;padding:2em;margin-bottom:2em;";
newElement.classList.add("ContentStyles-base");
bodyEl.parentElement.insertBefore(newElement, bodyEl);
newElement.textContent = "Generating summary...";
try {
const summaries = await Promise.all(queries.map(getSummary));
newElement.textContent = summaries.join("----------------------\n\n");
} catch (e) {
newElement.textContent = "Error: " + e + e.message;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment