-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.js
More file actions
496 lines (436 loc) · 16.4 KB
/
Copy pathreplace.js
File metadata and controls
496 lines (436 loc) · 16.4 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
let questionlist = [];
let geminiCalled = false;
let answered = 0;
let correct = 0;
let On = false;
let FeedObserver = null;
let fileUri = null
let fileData = null
let mimeType = null
let apiKey = null
let source = null;
// fetching API key from local storage
chrome.storage.local.get({ key: null }, (result) => {
apiKey = result.key;
console.log("Initial API key:", apiKey);
});
// function to sop looking at the feed by disconnecting the oserver
function stopFeedObserver() {
if (FeedObserver) {
FeedObserver.disconnect();
FeedObserver = null;
}
}
// fetches initial state of the on/off button
chrome.storage.local.get({ On: false }, (result) => {
On = result.On;
console.log("Initial On/Off State in replace.js:", On);
if (On){
waitForFeed();
}
});
// fetches initial state of the source
chrome.storage.local.get({ source: "subject" }, (result) => {
source = result.source;
console.log("Initial source in replace.js:", source);
});
// fetches initial fileUri
chrome.storage.local.get({ fileData: null }, (result) => {
if (result.fileData && result.fileData.fileUri && result.fileData.filetype){
fileUri = result.fileData.fileUri;
mimeType = result.fileData.filetype;
console.log("Initial fireUri:", fileUri);
console.log("Initial mimeType:", mimeType);
} else {
console.log("No initial file");
}
});
// Listens to any updates of the on/off button from background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "TOGGLE_ON_UPDATE") {
On = message.enabled;
console.log("On/Off Updated (replace.js):", On);
if (On) {
waitForFeed();
}
else {
stopFeedObserver();
}
} else if (message.type === "RESET_ANSWER_STATS") {
answered = message.answer_stats.answered;
correct = message.answer_stats.correct;
} else if (message.type === "UPDATE_SOURCE") {
source = message.source;
console.log("Source Updated (replace.js):", source);
}
});
// Replaces occasional tweets with questions
function replaceTweets() {
if (questionlist.length < 15) {
if (!geminiCalled){
geminiCalled = true;
callGemini({source: source});
}
}
if (questionlist.length < 1) {
return
}
const tweets = Array.from(document.querySelectorAll('article[data-testid="tweet"]')).filter((tweet) => {
const rect = tweet.getBoundingClientRect();
return rect.top > window.innerHeight;
});
if (tweets.length === 0) {
// Debug
console.log('No tweets below viewport found');
return;
}
if (Math.random() > 0.1) return;
const randomIndex = Math.floor(Math.random() * tweets.length);
const randomTweet = tweets[randomIndex];
if (randomTweet.dataset.replaced) return;
randomTweet.dataset.replaced = "true";
const questionData = questionlist.pop()
const questionStartTime = Date.now(); // Track when question is displayed
// Debug
console.log("questions left: ", questionlist.length)
const allAnswers = [...questionData.incorrect_answers, questionData.correct_answers].sort(
() => Math.random() - 0.5
);
const replacementArticle = document.createElement("article");
replacementArticle.style.width = "100%";
replacementArticle.style.padding = "10px";
replacementArticle.style.borderRadius = "8px";
replacementArticle.style.backgroundColor = "black";
replacementArticle.className = "css-175oi2r";
const questionText = document.createElement("h3");
questionText.textContent = questionData.question_text;
questionText.style.marginBottom = "10px";
questionText.style.fontFamily = "'Open Sans', sans-serif";
replacementArticle.appendChild(questionText);
const answersContainer = document.createElement("div");
allAnswers.forEach((answer) => {
const answerButton = document.createElement("button");
answerButton.textContent = answer;
answerButton.style.display = "block";
answerButton.style.marginBottom = "5px";
answerButton.style.padding = "10px";
answerButton.style.border = "1px solid #ccc";
answerButton.style.borderRadius = "5px";
answerButton.style.cursor = "pointer";
answerButton.style.textAlign = "left";
answerButton.style.width = "100%";
answerButton.style.fontFamily = "'Open Sans', sans-serif";
answerButton.addEventListener("click", () => {
answered += 1
const buttons = answersContainer.querySelectorAll("button");
buttons.forEach((btn) => {
if (questionData.correct_answers.includes(btn.textContent)) {
btn.style.backgroundColor = "rgba(0, 128, 0, 0.5)";
btn.style.color = "white";
if (btn === answerButton) {
correct += 1;
// Debug
console.log("Correct answers count:", correct);
}
} else {
btn.style.backgroundColor = "rgba(255, 0, 0, 0.5)";
btn.style.color = "white";
}
btn.disabled = true;
});
explanation.style.display = "block";
// Debug
console.log(correct, " / ", answered)
// Save question/answer data for analysis
const qaData = {
question: questionData.question_text,
answer: questionData.correct_answers[0], // Assuming single correct answer
userAnswer: answerButton.textContent,
isCorrect: questionData.correct_answers.includes(answerButton.textContent),
topic: questionData.topic || 'General',
subject: source === 'subject' ? 'Custom Subject' : (source === 'file' ? 'File Content' : 'Combined'),
difficulty: 'Graduate Level',
timeSpent: Date.now() - questionStartTime,
source: source
};
chrome.runtime.sendMessage({
type: "SAVE_QUESTION_ANSWER",
qaData: qaData
}, (response) => {
if (chrome.runtime.lastError) {
console.error("Error saving QA data:", chrome.runtime.lastError.message);
} else {
console.log("QA data saved successfully:", response);
}
});
chrome.runtime.sendMessage({
type: "UPDATE_ANSWER_STATS",
answer_stats: { correct, answered }
}, (response) => {
// Debug
if (chrome.runtime.lastError) {
console.error("Error sending message to background.js:", chrome.runtime.lastError.message);
} else {
console.log("Response from background.js:", response);
}
});
});
answersContainer.appendChild(answerButton);
});
replacementArticle.appendChild(answersContainer);
const explanation = document.createElement("p");
explanation.innerHTML = `<strong>Explanation:</strong> ${questionData.explanation}`;
explanation.style.display = "none"; // Initially hidden
explanation.style.padding = "10px";
explanation.style.margin = "5px";
explanation.style.fontFamily = "'Open Sans', sans-serif";
replacementArticle.appendChild(explanation);
randomTweet.replaceWith(replacementArticle);
// Debug
console.log('Tweet replaced successfully');
}
// observes updates to the feed and replaces tweets when a change occurs
function observeFeed() {
if (!On) {
console.log("Feature is disabled. Stopping observer.");
return;
}
const feed = document.querySelector('[role="main"]');
if (!feed) {
// Debug
console.log('Feed not found');
return;
}
stopFeedObserver();
FeedObserver = new MutationObserver(() => {
replaceTweets();
});
FeedObserver.observe(feed, {
childList: true,
subtree: true
});
// Debug
console.log('Observer initialized');
}
// Waits for feed to load and then sets up an observer
function waitForFeed() {
const interval = setInterval(() => {
const feed = document.querySelector('[role="main"]');
if (feed) {
clearInterval(interval);
// Debug
console.log('Feed found, starting observer');
observeFeed();
} else {
// Debug
console.log('Waiting for feed...');
}
}, 500);
}
// waitForFeed();
async function uploadFile(file) {
const url = `https://generativelanguage.googleapis.com/upload/v1beta/files?key=${apiKey}`;
const fileBlob = new Blob([file], { type: file.type });
const fileSize = fileBlob.size;
const headers = {
"X-Goog-Upload-Command": "start, upload, finalize",
"X-Goog-Upload-Header-Content-Length": fileSize.toString(),
"X-Goog-Upload-Header-Content-Type": file.type,
"X-Goog-Upload-Protocol": "raw",
"Content-Type": file.type,
};
try {
const response = await fetch(url, {
method: "POST",
headers: headers,
body: fileBlob, // Send raw binary data
});
const rawResponse = await response.text();
console.log("Raw upload response:", rawResponse);
const data = JSON.parse(rawResponse);
console.log("Parsed upload response:", data);
if (!data.file || !data.file.uri) {
throw new Error("Upload did not return a valid file URI.");
}
return data.file.uri;
} catch (error) {
console.error("Error uploading file:", error);
throw error;
}
}
// Testing
//const fileUrl = chrome.runtime.getURL("SWE_Sample_Study_Guide.pdf");
//console.log(fileUrl);
//fetch(fileUrl)
// .then((response) => response.blob())
// .then((blob) => {
// const file = new File([blob], "example.pdf", { type: "application/pdf" });
// callGemini({useFile: true, file: file});
//
// })
//.catch((error) => console.error("Error loading file:", error));
//callGemini({useFile: true});
async function callGemini({ source = "subject" } = {}) {
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=${apiKey}`;
let subject = null;
try {
if (source == "file" && fileUri) {
console.log("using file")
} else if (source == "subject" || source == "subject+file") {
console.log("Retrieving subject from storage...");
subject = await new Promise((resolve) => {
chrome.storage.local.get({ subject: null }, (result) => {
const retrievedSubject = result.subject || "random trivia questions";
console.log("Subject retrieved:", retrievedSubject);
resolve(retrievedSubject);
});
});
}
const requestBody = {
contents: [],
generationConfig: {
temperature: 1,
topK: 40,
topP: 0.95,
maxOutputTokens: 8192,
thinkingConfig: {"thinkingBudget": 0,},
responseMimeType: "application/json",
responseSchema: {
type: "array",
description: "List of questions with their answers and explanations",
items: {
type: "object",
description: "Question and answer data",
properties: {
question_text: {
type: "string",
description: "The text of the question",
nullable: false,
},
correct_answers: {
type: "array",
description: "List of correct answers",
nullable: false,
items: {
type: "string",
},
},
incorrect_answers: {
type: "array",
description: "List of incorrect answers",
nullable: false,
items: {
type: "string",
},
},
topic: {
type: "string",
description: "The specific topic covered by the question",
nullable: false,
},
explanation: {
type: "string",
description: "Explanation of the correct answer",
nullable: false,
},
},
required: [
"question_text",
"correct_answers",
"incorrect_answers",
"topic",
"explanation",
],
},
},
},
};
if (fileUri && source == "file") {
requestBody.contents.push({
role: "user",
parts: [
{
fileData: {
fileUri: fileUri,
mimeType: mimeType,
},
},
],
});
requestBody.contents.push({
role: "user",
parts: [
{
text: `Give me a list of 20 graduate-level questions based on the provided file. Make sure the full response is included and not just the letter. Do not use keywords from the question in the correct answer. The three incorrect options must be highly plausible distractors. They should reflect common misconceptions, closely related but incorrect concepts, or subtle inaccuracies that a graduate student might find challenging. Ensure there always is a correct answer.`,
},
],
});
} else if (subject && source == "subject") {
requestBody.contents.push({
role: "user",
parts: [
{
text: `Give me a list of 20 graduate-level questions with the subject: ${subject}. Make sure the full response is included and not just the letter. Do not use keywords from the question in the correct answer. The three incorrect options must be highly plausible distractors. They should reflect common misconceptions, closely related but incorrect concepts, or subtle inaccuracies that a graduate student might find challenging. Ensure there always is a correct answer.`,
},
],
});
} else if (subject && fileUri && source == "subject+file") {
requestBody.contents.push({
role: "user",
parts: [
{
fileData: {
fileUri: fileUri,
mimeType: mimeType,
},
},
],
});
requestBody.contents.push({
role: "user",
parts: [
{
text: `Give me a list of 20 graduate-level questions based on the provided file and the following subject: ${subject}. Make sure the full response is included and not just the letter. Do not use keywords from the question in the correct answer. The three incorrect options must be highly plausible distractors. They should reflect common misconceptions, closely related but incorrect concepts, or subtle inaccuracies that a graduate student might find challenging. Ensure there always is a correct answer.`,
},
],
});
}
// Log request body for debugging
console.log("Request body:", JSON.stringify(requestBody, null, 2));
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorDetails = await response.json();
console.error("Error details:", errorDetails);
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("Generated Response:", data);
// Process response
if (
data.candidates &&
data.candidates[0] &&
data.candidates[0].content &&
data.candidates[0].content.parts &&
data.candidates[0].content.parts[0]
) {
const jsonString = data.candidates[0].content.parts[0].text;
const parsedData = JSON.parse(jsonString);
console.log("Parsed JSON Object:", parsedData);
questionlist = [...questionlist, ...Object.values(parsedData)];
console.log("Updated question list:", questionlist);
geminiCalled = false;
} else {
console.error("Response does not contain the expected structure.");
geminiCalled = false;
}
} catch (error) {
console.error("Error calling Gemini API:", error);
geminiCalled = false;
}
}