-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontent.js
208 lines (183 loc) · 6.15 KB
/
content.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
// Constants
const SUMMARIZE_BUTTON_CLASS = 'linkedin-summarizer-button';
const POST_SELECTOR = '.update-components-update-v2__commentary';
const MIN_POST_LENGTH = 300;
const HOSTED_API_URL = 'https://ujfosx6cdgcqun7gzkk2cs2d2m0kcpbf.lambda-url.ap-south-1.on.aws/api/v1/summarize';
const LOCAL_API_URL = 'http://localhost:9090/api/v1/summarize';
const API_URL = HOSTED_API_URL;
// Main function to initialize the extension
function initExtension() {
addSummarizeButtonsToExistingPosts();
observePageChanges();
observeNewPosts();
}
// Function to add summarize buttons to existing posts
function addSummarizeButtonsToExistingPosts() {
const posts = document.querySelectorAll(POST_SELECTOR);
posts.forEach(addSummarizeButtonIfNeeded);
}
// Function to add a summarize button to a post if it meets the criteria
function addSummarizeButtonIfNeeded(postElement) {
if (postElement.innerText.length > MIN_POST_LENGTH && !postElement.querySelector(`.${SUMMARIZE_BUTTON_CLASS}`)) {
addSummarizeButton(postElement);
}
}
// Function to create and add a summarize button to a post
function addSummarizeButton(postElement) {
const button = createSummarizeButton();
const summaryElement = document.createElement('div');
summaryElement.className = 'summary-element';
summaryElement.style.cssText = `
background-color: #f3f6f8;
padding: 10px;
border-radius: 5px;
margin-top: 10px;
display: none; // Initially hidden
`;
button.addEventListener('click', async () => {
button.disabled = true;
button.innerHTML = '✨ Summarizing...';
if (postElement.innerText === '' || postElement.innerText === undefined) {
button.textContent = 'Post is empty';
button.disabled = false;
console.log(postElement);
return;
}
try {
summaryElement.style.display = 'block'; // Show the summary element
postElement.appendChild(summaryElement);
await summarize(postElement.innerText, summaryElement);
button.remove();
} catch (error) {
console.error('Summarization failed:', error);
button.textContent = 'Summarization failed';
button.disabled = false;
summaryElement.remove();
}
});
postElement.appendChild(document.createElement('br'));
postElement.appendChild(button);
}
// Function to create a summarize button
function createSummarizeButton() {
const button = document.createElement('button');
button.innerHTML = '✨ Summarize';
button.className = SUMMARIZE_BUTTON_CLASS;
button.style.cssText = `
background-color: white;
color: #0073b1;
border: 2px solid #0073b1;
padding: 6px 12px;
font-size: 14px;
font-weight: bold;
cursor: pointer;
border-radius: 5px;
margin: 10px 0px;
transition: background-color 0.3s;
`;
return button;
}
// Function to display the summary
function displaySummary(element, summary) {
const formattedSummary = summary
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
.replace(/\n/g, '<br>');
element.innerHTML = formattedSummary
element.style.cssText = `
background-color: #f3f6f8;
padding: 10px;
border-radius: 5px;
margin-top: 10px;
`;
}
// Function to observe page changes
function observePageChanges() {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList' && isSignificantDOMChange(mutation.target)) {
setTimeout(addSummarizeButtonsToExistingPosts, 1000);
}
});
});
observer.observe(document.body, { childList: true, subtree: true });
}
// Function to check if a DOM change is significant
function isSignificantDOMChange(target) {
return target.tagName === 'BODY' || target.id === 'main' || target.id === 'content';
}
// Function to observe new posts
function observeNewPosts() {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList') {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const posts = node.querySelectorAll(POST_SELECTOR);
posts.forEach(addSummarizeButtonIfNeeded);
}
});
}
});
});
observer.observe(document.body, { childList: true, subtree: true });
}
// Function to summarize text using Hugging Face API
async function summarize(text, summaryElement) {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
post: text,
preferredLanguage: "english"
}),
});
if (!response.ok) {
console.log(response);
throw new Error(`API request failed with status ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let summary = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.slice(6));
if (data.content) {
summary += data.content;
// Update the UI with the current summary
updateSummaryUI(summaryElement, summary);
} else if (data.done) {
console.log('Stream ended');
} else if (data.error) {
console.error('Error:', data.error);
throw new Error(data.error);
}
}
}
}
return summary || 'Summary not available.';
}
// Function to update the summary UI as it's being generated
function updateSummaryUI(summaryElement, currentSummary) {
const formattedSummary = currentSummary
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
.replace(/\n/g, '<br>');
summaryElement.innerHTML = formattedSummary;
}
// Initialize the extension
initExtension();
// Listen for messages from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "activateExtension") {
console.log("Activation message received from popup");
initExtension();
sendResponse({status: "activated"});
return true; // Indicates that the response will be sent asynchronously
}
});