-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.html
More file actions
1094 lines (973 loc) · 33.9 KB
/
test.html
File metadata and controls
1094 lines (973 loc) · 33.9 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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Clickbait-Digest</title>
<style>
body {
font-family: sans-serif;
margin: 0;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 2rem;
box-sizing: border-box;
}
.container {
width: 90%;
max-width: 600px;
display: flex;
flex-direction: column;
gap: 1rem;
}
label {
display: block;
margin-bottom: 1vh;
}
input[type="text"],
input[type="password"] {
width: 100%;
padding: 1vh;
margin-bottom: 1vh;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 0.5vh;
}
button {
padding: 1vh 2vw;
margin-right: 1vw;
background-color: #4285f4;
color: white;
border: none;
border-radius: 0.5vh;
cursor: pointer;
transition: all 0.3s ease;
}
button:hover {
background-color: #2c65c8;
transform: translateY(-2px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
button:active {
transform: translateY(0);
}
/* Add disabled button style */
button.disabled {
background-color: #cccccc;
color: #888888;
cursor: not-allowed;
transform: none;
box-shadow: none;
pointer-events: none;
}
#summarizeBtn {
width: 100%;
}
#summary {
width: 100%;
height: 40vh;
margin-top: 2vh;
padding: 1vh;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 0.5vh;
resize: none;
flex-grow: 1;
}
.temp-buttons {
margin-bottom: 2vh;
display: flex;
gap: 1vw;
}
.temp-buttons button {
background-color: #eee;
color: #333;
flex: 1;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.temp-buttons button:hover {
transform: translateY(-2px);
}
.temp-buttons button.selected {
background-color: #4285f4;
color: white;
animation: pulse 2s infinite;
}
#error {
margin-top: 10px;
font-weight: bold;
transition: all 0.3s ease;
transform-origin: left;
color: red;
}
#success-message {
color: green;
}
/*Loading animation*/
#summary.loading {
/* No special styles needed as we're using overlay */
}
.spinner {
border: 0.4vh solid #f3f3f3;
border-top: 0.4vh solid #3498db;
border-radius: 50%;
width: 4vh;
height: 4vh;
animation: spin 1s linear infinite;
transition: all 0.3s ease;
box-shadow: 0 0 10px rgba(52, 152, 219, 0.3);
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
/* Loading dots animation */
.loading-dots {
display: flex;
justify-content: center;
align-items: center;
gap: 0.8vh;
height: 3vh;
}
.loading-dots .dot {
width: 0.8vh;
height: 0.8vh;
background-color: var(--primary-color);
border-radius: 50%;
opacity: 0.6;
position: relative;
background: linear-gradient(145deg, var(--primary-color), var(--button-hover-bg));
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
.loading-dots .dot:nth-child(1) {
animation: dot-animation 1.5s infinite 0s cubic-bezier(0.4, 0, 0.2, 1);
}
.loading-dots .dot:nth-child(2) {
animation: dot-animation 1.5s infinite 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.loading-dots .dot:nth-child(3) {
animation: dot-animation 1.5s infinite 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes dot-animation {
0%, 100% {
opacity: 0.3;
transform: translateY(0) scale(0.8);
}
50% {
opacity: 1;
transform: translateY(-1vh) scale(1.2);
box-shadow: 0 0.5vh 0.8vh rgba(66, 133, 244, 0.5);
}
}
/* Loading overlay */
.loading-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
backdrop-filter: blur(1px);
background-color: rgba(255, 255, 255, 0.92);
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
z-index: 10;
border-radius: 0.5vh;
opacity: 0;
pointer-events: none;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
padding-top: 5vh;
}
.loading-overlay.visible {
opacity: 1;
pointer-events: auto;
}
.loading-text {
margin-top: 1vh;
font-size: 0.9rem;
color: var(--primary-color);
font-weight: 500;
letter-spacing: 0.05em;
opacity: 0.8;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.summary-container {
position: relative;
flex-grow: 1;
width: 100%;
}
.button-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.icon-button {
background: none;
border: none;
font-size: 1.2rem;
color: var(--icon-color);
cursor: pointer;
padding: 0.5rem;
transition: color 0.2s ease, transform 0.3s ease;
}
.icon-button:hover {
color: var(--icon-hover-color);
background: none;
transform: scale(1.1);
box-shadow: none;
}
.icon-button:active {
transform: scale(1);
}
/* Update disabled icon button style */
.icon-button.disabled {
color: #cccccc;
cursor: not-allowed;
pointer-events: none;
background: none;
}
.icon-button.disabled i {
color: #cccccc;
}
.slider-container {
display: flex;
align-items: center;
margin-bottom: 10px;
}
input[type="range"] {
width: 70%;
transition: all 0.3s ease;
}
input[type="range"]:hover {
transform: scaleY(1.2);
}
#skepticismValue,
#lengthValue {
margin-left: 0.5rem;
font-weight: bold;
white-space: nowrap;
}
.hidden {
display: none;
}
:root {
--primary-color: #4285f4;
--secondary-color: #f1f3f4;
--text-color: #333;
--button-bg: var(--primary-color);
--button-text: #fff;
--button-hover-bg: #2c65c8;
--button-active-bg: #1a4587;
--border-radius: 8px;
--pill-radius: 20px;
--success-color: #4caf50;
--error-color: #f44336;
--loading-spinner-color: var(--primary-color);
--icon-color: var(--primary-color);
--icon-hover-color: var(--button-hover-bg);
}
#summary.typing {
white-space: pre-wrap;
overflow-wrap: break-word;
font-family: monospace;
animation: glow 1.5s ease-in-out infinite;
}
@keyframes glow {
0%, 100% {
box-shadow: 0 0 5px rgba(66, 133, 244, 0.2);
}
50% {
box-shadow: 0 0 15px rgba(66, 133, 244, 0.4);
}
}
/* Main content fade animation */
#main {
transition: opacity 0.3s ease;
opacity: 1;
}
#main.hidden {
opacity: 0;
pointer-events: none;
}
/* Messages animation */
#error:not(:empty),
#success-message:not(.hidden) {
animation: slideIn 0.3s ease;
}
/* Animations */
@keyframes slideIn {
from {
transform: translateX(-20px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 rgba(66, 133, 244, 0.4);
}
70% {
box-shadow: 0 0 0 10px rgba(66, 133, 244, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(66, 133, 244, 0);
}
}
/* Refresh button rotation animation */
#refreshBtn i {
transition: transform 0.5s ease;
}
#refreshBtn:hover i {
transform: rotate(180deg);
}
</style>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"
integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<link
href="https://fonts.googleapis.com/css2?family=Geist&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div class="container">
<h2>Clickbait Digest</h2>
<input
type="text"
id="youtubeUrl"
placeholder="Paste YouTube video URL here"
/>
<div id="main">
<!-- main div -->
<div class="temp-buttons">
<button data-prompt-type="low">Low Skepticism</button>
<button data-prompt-type="medium" class="selected">
Medium Skepticism
</button>
<button data-prompt-type="high">High Skepticism</button>
</div>
<div class="slider-container">
<label for="length">Summary Length:</label>
<input
type="range"
id="length"
min="50"
max="400"
step="1"
value="50"
/>
<span id="lengthValue">50 words</span>
</div>
<button id="summarizeBtn">Summarize</button>
<div class="summary-container">
<textarea id="summary" placeholder="Your summary will appear here..."></textarea>
<div class="loading-overlay">
<div class="loading-dots">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
<div class="loading-text">Summarizing...</div>
</div>
</div>
</div>
<div id="error"></div>
</div>
<script>
// --- API KEY ---
const geminiApiKey = "YOUR_API_KEY_HERE"; // Replace with your actual API key
document.addEventListener("DOMContentLoaded", function () {
const summaryTextArea = document.getElementById("summary");
const errorDiv = document.getElementById("error");
const summarizeBtn = document.getElementById("summarizeBtn");
const youtubeUrlInput = document.getElementById("youtubeUrl");
const tempButtons = document.querySelectorAll(".temp-buttons button");
const lengthSlider = document.getElementById("length");
const lengthValueSpan = document.getElementById("lengthValue");
const loadingOverlay = document.querySelector(".loading-overlay");
// Add summarization state tracking
let isSummarizing = false;
let selectedLength = 50; // Default length
// --- Prompts --- (Remains the same)
const prompts = {
low: (
videoTitle,
question,
pageContent,
length
) => `OMG, like, totally summarize this YouTube video’s captions in about ${length} words, okay? Just take whatever it says as, like, super true ‘cause I saw it on TikTok once. Focus on the big juicy stuff they’re talking about, no brainy analysis or whatever—just spill the tea as they give it, yas queen! Ignore the ads.
Title: ${videoTitle}
Question: ${question}
Page Content:
${pageContent}
Summary:`,
medium: (
videoTitle,
question,
pageContent,
length
) => `Yo, break down this YouTube video’s captions in about ${length} words. Cut through the fluff, hit the core question or claim from the title, and give me the straight-up main points. Keep it real—flag any obvious bias or overhyped nonsense, but don’t overthink it. Concise, no cap, let’s go. Ignore the ads.
Title: ${videoTitle}
Question: ${question}
Page Content:
${pageContent}
Summary:`,
high: (
videoTitle,
question,
pageContent,
length
) => `Akshually… dissect this YouTube video’s captions and deliver a razor-sharp ${length}-word summary tackling the title’s core question or claim. Ruthlessly question everything—sniff out biases, exaggerations, logical fallacies, and any BS not backed by facts. Summarize the key arguments, but shred their validity like a peer-reviewed takedown. Report it, stat. Ignore the ads.
Title: ${videoTitle}
Question: ${question}
Page Content:
${pageContent}
Summary:`,
};
// --- Length Slider Event Listener ---
lengthSlider.addEventListener("input", function () {
selectedLength = parseInt(this.value);
lengthValueSpan.textContent = selectedLength + " words";
});
// --- Temperature Button Click Handlers ---
tempButtons.forEach((button) => {
button.addEventListener("click", function () {
tempButtons.forEach((btn) => btn.classList.remove("selected"));
this.classList.add("selected");
console.log("Skepticism level set to:", this.dataset.promptType);
});
});
// --- Summarize Button Click Handler ---
summarizeBtn.addEventListener("click", function () {
// Prevent re-triggering if already summarizing
if (isSummarizing) {
return;
}
errorDiv.textContent = "";
loadingOverlay.classList.add("visible");
// Disable buttons during summarization
setButtonsState(true);
startSummaryGeneration();
});
// Helper function to enable/disable buttons
function setButtonsState(disabled) {
isSummarizing = disabled;
// Disable/enable summarize button
if (disabled) {
summarizeBtn.classList.add('disabled');
summarizeBtn.setAttribute('title', 'Summarization in progress...');
} else {
summarizeBtn.classList.remove('disabled');
summarizeBtn.setAttribute('title', 'Summarize');
}
// Disable/enable temperature buttons
tempButtons.forEach(button => {
if (disabled) {
button.classList.add('disabled');
} else {
button.classList.remove('disabled');
}
});
}
// --- Main Function ---
async function startSummaryGeneration() {
if (!geminiApiKey) {
displayMessage(
"API key is missing! Please add it to the top of the HTML file.",
"red"
);
loadingOverlay.classList.remove("visible");
setButtonsState(false); // Re-enable buttons
return;
}
const youtubeUrl = youtubeUrlInput.value.trim();
if (!youtubeUrl) {
displayMessage("Please enter a YouTube URL.", "red");
loadingOverlay.classList.remove("visible");
setButtonsState(false); // Re-enable buttons
return;
}
if (!youtubeUrl.includes("youtube.com/watch")) {
displayMessage("Not a valid YouTube video URL.", "red");
loadingOverlay.classList.remove("visible");
setButtonsState(false); // Re-enable buttons
return;
}
const videoId = new URL(youtubeUrl).searchParams.get("v");
// Fetch Video Title (using proxy for CORS)
let videoTitle;
try {
videoTitle = await fetchVideoTitle(videoId);
} catch (error) {
displayMessage(
"Failed to fetch video title. Please check the URL and try again.",
"red"
);
loadingOverlay.classList.remove("visible");
setButtonsState(false); // Re-enable buttons
return;
}
if (!videoId) {
displayMessage("Could not extract video ID.", "red");
loadingOverlay.classList.remove("visible");
setButtonsState(false); // Re-enable buttons
return;
}
getVideoTranscript(videoId, videoTitle);
}
// --- Transcript Retrieval and Summarization ---
async function getVideoTranscript(videoId, videoTitle) {
console.log("getVideoTranscript called with videoId:", videoId);
try {
// Try 1: get_video_info (using CORS proxy)
let transcriptText = await fetchTranscriptFromVideoInfo(videoId);
if (transcriptText) {
console.log("Transcript found via get_video_info");
await generateSummary(videoTitle, transcriptText, selectedLength);
return;
}
// Try 2: Scrape ytInitialPlayerResponse (using CORS proxy).
transcriptText = await scrapeTranscript(videoId);
if (transcriptText) {
console.log("Transcript found via scrapeTranscript");
await generateSummary(videoTitle, transcriptText, selectedLength);
return;
}
// Try 3: Fallback to Gemini with page content (using iframe - likely to fail)
console.log("Falling back to page content summarization.");
const pageContent = await getPageContent(videoId);
if (pageContent) {
await generateSummaryFromPageContent(
videoTitle,
pageContent,
selectedLength
);
} else {
throw new Error("Could not retrieve transcript or page content.");
}
} catch (error) {
console.error("Error in getVideoTranscript:", error);
displayMessage(error.message, "red");
loadingOverlay.classList.remove("visible");
setButtonsState(false); // Re-enable buttons
}
}
async function fetchVideoTitle(videoId) {
const proxyUrl = `https://corsproxy.io/?https://www.youtube.com/watch?v=${videoId}`;
const response = await fetch(proxyUrl);
if (!response.ok) {
throw new Error(`Failed to fetch video page: ${response.status}`);
}
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const title = doc
.querySelector('meta[name="title"]')
?.getAttribute("content");
if (!title) {
throw new Error("Could not find video title.");
}
return title;
}
async function fetchTranscriptFromVideoInfo(videoId) {
console.log("Attempting to fetch transcript from get_video_info...");
try {
const proxyUrl = `https://corsproxy.io/?https://www.youtube.com/get_video_info?video_id=${videoId}&hl=en`;
const response = await fetch(proxyUrl);
if (!response.ok) {
console.warn(`get_video_info failed: ${response.status}`);
return null;
}
const videoInfo = await response.text();
const parsedVideoInfo = parseQueryString(videoInfo);
if (!parsedVideoInfo.player_response) {
console.warn("No player_response in get_video_info.");
return null;
}
const playerResponse = JSON.parse(parsedVideoInfo.player_response);
if (!playerResponse.captions) {
console.warn("No captions in get_video_info player_response.");
return null;
}
const captionTracks =
playerResponse.captions.playerCaptionsTracklistRenderer
.captionTracks;
if (!captionTracks || captionTracks.length === 0) {
console.warn("No caption tracks found in get_video_info.");
return null;
}
// Find English caption track
let baseUrl = null;
for (const track of captionTracks) {
if (track.languageCode === "en") {
baseUrl = track.baseUrl;
break;
}
}
if (!baseUrl) {
console.warn("No English caption track found in get_video_info.");
return null;
}
console.log("Fetching transcript from:", baseUrl);
const transcriptResponse = await fetch(
`https://corsproxy.io/?${baseUrl}`
); // Use proxy for transcript too
if (!transcriptResponse.ok) {
console.warn(
`Failed to download transcript from get_video_info: ${transcriptResponse.status}`
);
return null;
}
const transcriptXml = await transcriptResponse.text();
console.log("Transcript XML fetched successfully.");
return parseTranscriptXml(transcriptXml);
} catch (error) {
console.warn("Error in fetchTranscriptFromVideoInfo:", error);
return null;
}
}
async function scrapeTranscript(videoId) {
console.log("Attempting to scrape transcript...");
try {
const proxyUrl = `https://corsproxy.io/?https://www.youtube.com/watch?v=${videoId}`;
const response = await fetch(proxyUrl);
if (!response.ok) {
throw new Error(`Failed to fetch video page: ${response.status}`);
}
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
// Extract ytInitialPlayerResponse
const scripts = doc.querySelectorAll("script");
let ytInitialPlayerResponse = null;
for (const script of scripts) {
if (script.textContent.includes("ytInitialPlayerResponse")) {
// Extract the JSON object using a regular expression
const match = script.textContent.match(
/var ytInitialPlayerResponse = ({.*?});/
);
if (match && match[1]) {
ytInitialPlayerResponse = JSON.parse(match[1]);
break;
}
}
}
if (!ytInitialPlayerResponse) {
console.warn("No ytInitialPlayerResponse found.");
return null;
}
const captionTracks =
ytInitialPlayerResponse.captions?.playerCaptionsTracklistRenderer
?.captionTracks;
if (!captionTracks || captionTracks.length === 0) {
console.warn(
"No caption tracks found in ytInitialPlayerResponse."
);
return null;
}
let baseUrl = null;
for (const track of captionTracks) {
if (track.languageCode === "en") {
baseUrl = track.baseUrl;
break;
}
}
if (!baseUrl) {
console.warn("No English caption track found.");
return null;
}
console.log("Fetching transcript from (scrape):", baseUrl);
const transcriptResponse = await fetch(
`https://corsproxy.io/?${baseUrl}`
);
if (!transcriptResponse.ok) {
console.warn(
`Failed to download transcript (scrape): ${transcriptResponse.status}`
);
return null;
}
const transcriptXml = await transcriptResponse.text();
console.log("Transcript XML fetched successfully (scrape).");
return parseTranscriptXml(transcriptXml);
} catch (error) {
console.warn("Error in scrapeTranscript:", error);
return null;
}
}
async function getPageContent(videoId) {
// iframe method (unreliable)
try {
const iframe = document.createElement("iframe");
iframe.src = `https://www.youtube.com/watch?v=${videoId}`;
iframe.style.display = "none";
document.body.appendChild(iframe);
return new Promise((resolve, reject) => {
iframe.onload = () => {
try {
//Try catch added to handle potential security policy issues
let pageText = iframe.contentDocument.body.innerText;
// Remove likely irrelevant sections
pageText = pageText.replace(/Comments\s*(\n.*)*/g, "");
pageText = pageText.replace(/Up next\s*Autoplay.*/g, "");
pageText = pageText.replace(
/People also watched\s*(\n.*)*/g,
""
);
pageText = pageText.replace(/\s+/g, " ").trim();
document.body.removeChild(iframe); // Clean up
resolve(pageText);
} catch (iframeError) {
console.error("Error accessing iframe content:", iframeError);
document.body.removeChild(iframe);
resolve(null);
}
};
iframe.onerror = () => {
//Handle load errors
console.error("Error loading iframe");
document.body.removeChild(iframe);
resolve(null); // Resolve with null on error
};
});
} catch (error) {
console.error("Error getting page content (iframe):", error);
return null;
}
}
async function generateSummaryFromPageContent(
videoTitle,
pageContent,
length
) {
console.log("generateSummaryFromPageContent called");
try {
const question = extractQuestionFromTitle(videoTitle);
const selectedPromptType = document.querySelector(
".temp-buttons .selected"
).dataset.promptType;
const prompt = prompts[selectedPromptType](
videoTitle,
question,
pageContent,
length
);
const response = await fetch(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=" +
geminiApiKey,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
contents: [
{
parts: [
{
text: prompt,
},
],
},
],
generationConfig: {
temperature: 0.5, //Fixed temperature
},
}),
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Gemini API error: ${errorData.error.message}`);
}
const data = await response.json();
if (
data.candidates &&
data.candidates[0] &&
data.candidates[0].content &&
data.candidates[0].content.parts &&
data.candidates[0].content.parts[0]
) {
const summary = data.candidates[0].content.parts[0].text;
typewriterEffect(summaryTextArea, summary);
} else {
console.error("Unexpected response structure:", data);
throw new Error(
"Gemini API returned an unexpected response structure."
);
}
} catch (error) {
displayMessage(error.message, "red");
loadingOverlay.classList.remove("visible");
setButtonsState(false); // Re-enable buttons on error
} finally {
loadingOverlay.classList.remove("visible");
// Remove setButtonsState here as it will be called after typewriter effect
}
}
async function generateSummary(videoTitle, transcript, length) {
console.log("generateSummary called with transcript");
try {
const question = extractQuestionFromTitle(videoTitle);
const selectedPromptType = document.querySelector(
".temp-buttons .selected"
).dataset.promptType;
const prompt = prompts[selectedPromptType](
videoTitle,
question,
transcript,
length
);
const response = await fetch(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=" +
geminiApiKey,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
contents: [
{
parts: [
{
text: prompt,
},
],
},
],
generationConfig: {
temperature: 0.5, //Fixed temperature
},
}),
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Gemini API error: ${errorData.error.message}`);
}
const data = await response.json();
if (
data.candidates &&
data.candidates[0] &&
data.candidates[0].content &&
data.candidates[0].content.parts &&
data.candidates[0].content.parts[0]
) {
const summary = data.candidates[0].content.parts[0].text;
typewriterEffect(summaryTextArea, summary);
} else {
console.error("Unexpected response structure:", data);
throw new Error(
"Gemini API returned an unexpected response structure."
);
}
} catch (error) {
displayMessage(error.message, "red");
loadingOverlay.classList.remove("visible");
setButtonsState(false); // Re-enable buttons on error
} finally {
loadingOverlay.classList.remove("visible");
// Remove setButtonsState here as it will be called after typewriter effect
}
}
// --- Utility Functions --- (Remains largely the same)