-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
142 lines (128 loc) · 5.23 KB
/
popup.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
// popup.js
document.getElementById("summarizeButton").addEventListener("click", () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tab = tabs[0];
if (tab.url.includes("youtube.com/watch")) {
// Check if content script has already been injected
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
func: () => window.contentScriptInjected, // Check if already injected
},
(results) => {
if (results[0].result) {
// Content script already injected
console.log("Content script already injected.");
sendGetTranscriptMessage(tab.id);
} else {
// Inject the YouTube Transcript library
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
files: ['youtube-transcript.js'],
},
() => {
// Inject the content script
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
files: ['contentScript.js'],
},
() => {
// Now send the message to the content script to get the transcript
sendGetTranscriptMessage(tab.id);
}
);
}
);
}
}
);
} else {
document.getElementById("summary").innerText = "Please navigate to a YouTube video page.";
}
});
});
// Function to send a message to the content script to get the transcript
function sendGetTranscriptMessage(tabId) {
chrome.tabs.sendMessage(tabId, { action: "getTranscript" }, async (response) => {
if (chrome.runtime.lastError) {
console.error("Error sending message to content script:", chrome.runtime.lastError);
document.getElementById("summary").innerText = "Error: " + chrome.runtime.lastError.message;
return;
}
if (!response) {
console.error("No response received from content script.");
document.getElementById("summary").innerText = "Error: No response from content script.";
return;
}
console.log("Received response from content script:", response);
if (response.error) {
document.getElementById("summary").innerText = "Error: " + response.error;
} else {
const transcript = response.transcript;
document.getElementById("summary").innerText = "Transcript fetched. Generating summary...";
// Fetch the OpenAI API key, custom prompt, and token limit
chrome.storage.sync.get(["openaiApiKey", "customPrompt", "maxTokenLimit"], async (items) => {
const apiKey = items.openaiApiKey;
const prompt = items.customPrompt || "Summarize the following transcript of a YouTube Video:"; // Default prompt if not set
const maxTokens = items.maxTokenLimit || 500; // Default max tokens if not set
if (!apiKey) {
document.getElementById("summary").innerText = "Error: OpenAI API key not set.";
return;
}
try {
// Generate summary using OpenAI API with custom prompt and token limit
const summary = await generateSummary(transcript, apiKey, prompt, maxTokens);
document.getElementById("summary").innerText = summary;
} catch (error) {
console.error("Error summarizing transcript:", error);
document.getElementById("summary").innerText = "Error: " + error.message;
}
});
}
});
}
// Function to summarize the transcript using OpenAI API
async function generateSummary(transcript, apiKey, prompt, maxTokens) {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "gpt-4o", // or "gpt-4" if you have access
messages: [{ role: "user", content: `${prompt}\n\n${transcript}` }],
max_tokens: maxTokens, // Use custom max token limit
temperature: 0.7,
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error.message);
}
const data = await response.json();
return data.choices[0].message.content.trim();
}
// Add copy to clipboard functionality
document.getElementById("copyButton").addEventListener("click", () => {
const summaryText = document.getElementById("summary").innerText;
if (summaryText) {
navigator.clipboard.writeText(summaryText).then(() => {
// Display confirmation message
const confirmationMessage = document.getElementById("copyConfirmation");
confirmationMessage.innerText = "Summary copied to clipboard!";
confirmationMessage.style.display = "block"; // Show the confirmation message
// Hide the message after a few seconds
setTimeout(() => {
confirmationMessage.style.display = "none";
}, 3000);
}).catch((err) => {
console.error("Failed to copy text: ", err);
document.getElementById("copyConfirmation").innerText = "Failed to copy summary to clipboard.";
});
} else {
document.getElementById("copyConfirmation").innerText = "No summary available to copy.";
}
});