-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
2660 lines (2304 loc) · 101 KB
/
main.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
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
//MODULES AND IMPORTS
const nodemailer = require("nodemailer");
const fs = require("fs");
const path = require("path");
const util = require('util');
const { parse: parseUrl, format } = require('url');
const { exec } = require('child_process');
const cheerio = require('cheerio');
const sanitizeHtml = require('sanitize-html');
const { decode } = require('html-entities');
const { XMLParser } = require('fast-xml-parser');
const axios = require("axios");
const { OpenAI } = require("openai");
const puppeteer = require('puppeteer');
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const { RateLimiter } = require('limiter');
const os = require('os');
const { parseISO, parse, differenceInHours, isValid, subMinutes } = require('date-fns');
const { es, enUS } = require('date-fns/locale');
let { terms, websites } = require("./terminos");
const config = require("./config.json");
const { getMainTopics } = require("./text_analysis/topics_extractor");
const { findValidChromiumPath } = require("./browser/browserPath");
//IMPORTANT CONSTANTS AND SETTINGS
const openai = new OpenAI({ apiKey: config.openai.api_key });
const LANGUAGE = config.text_analysis.language;
const MAX_TOKENS_PER_CALL = config.openai.max_tokens_per_call;
const IGNORE_REDUNDANCY = config.text_analysis.ignore_redundancy;
const MAX_RETRIES_PER_FETCH = 3; //to be managed by user configuration
const INITIAL_DELAY = 500; //to be managed by user configuration
const MINUTES_TO_CLOSE = 15 * 60000;
let BROWSER_PATH;
const STRING_PLACEHOLDER = "placeholder";
const FAILED_SUMMARY_MSSG = "No se pudo generar un resumen";
const EMPTY_STRING = "";
const CRAWLED_RESULTS_JSON = "crawled_results.json";
const CRAWL_COMPLETE_FLAG = "crawl_complete.flag";
const SAFE_TO_REBOOT_FLAG = "safe_to_reboot.flag";
const CRAWL_COMPLETE_TEXT = "Crawling completed!";
const SAFE_REBOOT_MESSAGE = "Safe to reboot";
const MOST_COMMON_TERM = "Most_Common_Term";
const safePath = path.join(__dirname, SAFE_TO_REBOOT_FLAG);
const tempDir = path.join(__dirname, 'temp');
let addedLinks = new Set();
let workers = [];
let consoleLog = ''
terms = terms.map((term) => term.toLowerCase());
function getTimestamp() {
return new Date().toISOString();
}
/** Reset the console log by clearing the content. */
function resetLog() {
consoleLog = '';
}
function saveLog(reason = 'unknown') {
const logFileName = `log_${getTimestamp().replace(/[:.]/g, '-')}_${reason}.txt`;
const logFilePath = path.join(__dirname, logFileName);
fs.writeFileSync(logFilePath, consoleLog);
console.log(`Log saved to: ${logFilePath}`);
}
const originalConsole = {
log: console.log,
error: console.error
};
console.log = function() { logToConsoleAndMemory('log', arguments); };
console.error = function() { logToConsoleAndMemory('error', arguments); };
/** Avoids capturing stack trace to save memory */
class LightweightError extends Error {
constructor(message) {
super(message);
this.name = 'LightweightError';
Error.captureStackTrace = null;
}
}
/* Function to generate extensive RegExp patterns for a given tag, attributes, and values*/
const generatePatterns = (tag, attributes) => {
let patterns = [];
attributes.forEach(attr => {
attr.values.forEach(value => {
patterns.push(new RegExp(`<${tag}[^>]*${attr.name}="[^"]*${value}[^"]*"[^>]*>[\\s\\S]*?<\\/${tag}>`, 'gi'));
patterns.push(new RegExp(`<${tag}[^>]*${attr.name}='[^']*${value}[^']*'[^>]*>[\\s\\S]*?<\\/${tag}>`, 'gi'));
patterns.push(new RegExp(`<${tag}[^>]*${attr.name}=[^\\s>]*${value}[^\\s>]*[^>]*>[\\s\\S]*?<\\/${tag}>`, 'gi'));
});
});
return patterns;
};
/* Function to generate patterns for attributes containing specific substrings*/
const generateContainsPatterns = (tag, substrings) => {
let patterns = [];
substrings.forEach(substring => {
patterns.push(new RegExp(`<${tag}[^>]*class="[^"]*${substring}[^"]*"[^>]*>[\\s\\S]*?<\\/${tag}>`, 'gi'));
patterns.push(new RegExp(`<${tag}[^>]*class='[^']*${substring}[^']*'[^>]*>[\\s\\S]*?<\\/${tag}>`, 'gi'));
patterns.push(new RegExp(`<${tag}[^>]*class=[^\\s>]*${substring}[^\\s>]*[^>]*>[\\s\\S]*?<\\/${tag}>`, 'gi'));
});
return patterns;
};
/* Attributes and their potential values commonly associated with the unwanted sections */
const attributes = [
{ name: 'id', values: ['comments', 'comment-respond', 'related', 'most-read', 'newsletter', 'suscription', 'headerScroll', 'other-content', 'footer'] },
{ name: 'class', values: ['comments', 'comments-area', 'comment-respond', 'related', 'most-read', 'suggested-news', 'recirculation', 'newsletter', 'cta', 'subscription', 'author', 'bio', 'meta-tags', 'widget', 'lazyload-wrapper', 'ez-toc', 'sticky', 'mas-leidas', 'popular-posts', 'best-comments', 'content-related', 'o-carousel', 'share-after', 'Page-below', 'footer'] },
{ name: 'src', values: ['most_read'] }
];
/* Substrings to match attributes containing specific substrings*/
const substrings = ['o-carousel', 'c-article'];
/** Hyperexhaustive pattern list that contains unwanted sections of HTML*/
let patternsToRemoveFromHTML = [
...generatePatterns('aside', attributes),
...generatePatterns('div', attributes),
...generateContainsPatterns('div', substrings),
...generatePatterns('section', attributes),
...generateContainsPatterns('section', substrings),
...generatePatterns('footer', attributes),
...generatePatterns('article', attributes),
...generateContainsPatterns('article', substrings),
...generatePatterns('ul', attributes),
...generatePatterns('ol', attributes),
// Sidebars and sidebar sections
/<aside[^>]*>[\s\S]*?<\/aside>/gi,
// Related news sections
/<section[^>]*(id|class)="[^"]*related[^"]*"[^>]*>[\s\S]*?<\/section>/gi,
/<section[^>]*(id|class)="[^"]*puede-interesar[^"]*"[^>]*>[\s\S]*?<\/section>/gi,
/<div[^>]*(id|class)="[^"]*related[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<aside[^>]*(id|class)="[^"]*related[^"]*"[^>]*>[\s\S]*?<\/aside>/gi,
/<section[^>]*(id|class)="[^"]*most-read[^"]*"[^>]*>[\s\S]*?<\/section>/gi,
/<div[^>]*(id|class)="[^"]*most-read[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<aside[^>]*(id|class)="[^"]*most-read[^"]*"[^>]*>[\s\S]*?<\/aside>/gi,
/<div[^>]*(id|class)="[^"]*suggested-news[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*recirculation[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div id=\"comments\" class=\"comments-area\">[\s\S]*?<\/div>/gi,
// Subscription and newsletter sections
/<article[^>]*(id|class)="[^"]*newsletter[^"]*"[^>]*>[\s\S]*?<\/article>/gi,
/<section[^>]*(id|class)="[^"]*suscription[^"]*"[^>]*>[\s\S]*?<\/section>/gi,
/<div[^>]*(id|class)="[^"]*cta[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*subscription[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
// Author information
/<div[^>]*(id|class)="[^"]*author[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*bio[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
// Miscellaneous sections, footer, and others
/<footer[^>]*>[\s\S]*?<\/footer>/gi,
/<div[^>]*(id|class)="[^"]*meta-tags[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*widget[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*headerScroll[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*lazyload-wrapper[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<amp-list[^>]*src="[^"]*most_read[^"]*"[^>]*>[\s\S]*?<\/amp-list>/gi,
/<div[^>]*(id|class)="[^"]*ez-toc[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<ev-content-recommendations[^>]*>[\s\S]*?<\/ev-content-recommendations>/gi,
/<div[^>]*(id|class)="[^"]*sticky[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*mas-leidas[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<section[^>]*(id|class)="[^"]*popular-posts[^"]*"[^>]*>[\s\S]*?<\/section>/gi,
/<span[^>]*(id|class)="[^"]*content-related[^"]*"[^>]*>[\s\S]*?<\/span>/gi,
/<div[^>]*(id|class)="[^"]*other-content[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*o-carousel[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*share-after[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*Page-below[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*footer[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<footer[^>]*(id|class)="[^"]*footer[^"]*"[^>]*>[\s\S]*?<\/footer>/gi,
// Comment sections
/<div[^>]*(id|class)="[^"]*comments[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<section[^>]*(id|class)="[^"]*comments[^"]*"[^>]*>[\s\S]*?<\/section>/gi,
/<div[^>]*(id|class)="[^"]*comment-respond[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(id|class)="[^"]*best-comments[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
/<div id="comments" class="comments-area"*>[\s\S]*?<\/div>/gi,
/<div id="comments"[\s\S]*?<\/div>\s*<\/div>\s*<\/div>/gi,
/<div[^>]*(?:id|class)=[^>]*comments?[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-[^>]*>[\s\S]*?<\/div>/gi,
/<ol[^>]*class=[^>]*commentlist[^>]*>[\s\S]*?<\/ol>/gi,
/<div[^>]*id="respond"[^>]*>[\s\S]*?<\/div>/gi,
/<h2[^>]*class=[^>]*comments-title[^>]*>[\s\S]*?<\/h2>/gi,
/<li[^>]*class=[^>]*comment[^>]*>[\s\S]*?<\/li>/gi,
/<form[^>]*id="commentform"[^>]*>[\s\S]*?<\/form>/gi,
/<p[^>]*class=[^>]*comment-[^>]*>[\s\S]*?<\/p>/gi,
/<section[^>]*(?:id|class)=[^>]*comments?[^>]*>[\s\S]*?<\/section>/gi,
/<article[^>]*(?:id|class)=[^>]*comment[^>]*>[\s\S]*?<\/article>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-respond[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-reply[^>]*>[\s\S]*?<\/div>/gi,
/<textarea[^>]*(?:id|name)=[^>]*comment[^>]*>[\s\S]*?<\/textarea>/gi,
/<input[^>]*(?:id|name)=[^>]*comment[^>]*>/gi,
/<button[^>]*(?:id|class)=[^>]*comment[^>]*>[\s\S]*?<\/button>/gi,
/<a[^>]*class=[^>]*comment-reply-link[^>]*>[\s\S]*?<\/a>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-author[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-metadata[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-content[^>]*>[\s\S]*?<\/div>/gi,
/<nav[^>]*(?:id|class)=[^>]*comment-navigation[^>]*>[\s\S]*?<\/nav>/gi,
/<ul[^>]*(?:id|class)=[^>]*comment-list[^>]*>[\s\S]*?<\/ul>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-pagination[^>]*>[\s\S]*?<\/div>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-awaiting-moderation[^>]*>[\s\S]*?<\/div>/gi,
/<p[^>]*(?:id|class)=[^>]*comment-notes[^>]*>[\s\S]*?<\/p>/gi,
/<p[^>]*(?:id|class)=[^>]*comment-form-[^>]*>[\s\S]*?<\/p>/gi,
/<div[^>]*(?:id|class)=[^>]*comment-subscription-form[^>]*>[\s\S]*?<\/div>/gi,
// Additional specific patterns
/<amp-list[^>]*src="[^"]*most_read[^"]*"[^>]*>[\s\S]*?<\/amp-list>/gi,
/<ev-content-recommendations[^>]*>[\s\S]*?<\/ev-content-recommendations>/gi,
// Broad patterns to capture common unwanted tags
/<aside[^>]*>[\s\S]*?<\/aside>/gi,
/<footer[^>]*>[\s\S]*?<\/footer>/gi
];
patternsToRemoveFromHTML = Array.from(new Set(patternsToRemoveFromHTML));
let globalLinks = new Set();
function addLinkGlobally(link) {
if (!globalLinks.has(link)) {
globalLinks.add(link);
return true;
}
return false;
}
function logToConsoleAndMemory(type, args) {
const timestamp = getTimestamp();
const msg = util.format.apply(null, args);
consoleLog += `[${timestamp}] [${type.toUpperCase()}] ${msg}\n`;
originalConsole[type].apply(console, args);
}
/** Removes patterns from the content recursively.
* @param {string} content - The content to remove patterns from.
* @return {string} The content with patterns removed. */
const removePatterns = (content, ArrRegExpToRemove) => {
let newContent = content;
let changed = false;
for (let pat of ArrRegExpToRemove) {
const tempContent = newContent.replace(pat, '');
if (tempContent !== newContent) {
newContent = tempContent;
changed = true;
}
}
if (changed) {
return removePatterns(newContent, ArrRegExpToRemove);
}
return newContent;
};
const parseTime = (timeStr) => {
// Regular expression to match HH:MM format
const timeRegex = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/;
if (!timeRegex.test(timeStr)) {
throw new LightweightError('Invalid time format. Please use HH:MM (24-hour format).');
}
const [hourStr, minuteStr] = timeStr.split(":");
const hour = parseInt(hourStr, 10);
const minute = parseInt(minuteStr, 10);
if (isNaN(hour) || isNaN(minute)) {
throw new LightweightError('Invalid time: hour or minute is not a number');
}
const now = new Date();
const result = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute);
// Subtract MINUTES_TO_CLOSE
result.setMinutes(result.getMinutes() - Math.floor(MINUTES_TO_CLOSE / 60000));
// If the resulting time is earlier than now, set it to tomorrow
if (result <= now) {
result.setDate(result.getDate() + 1);
}
return result;
};
let globalStopFlag = false;
//GLOBAL ERROR HANDLERS
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
checkSafeAndReboot(error);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
checkSafeAndReboot(reason);
});
function checkSafeAndReboot(reason) {
console.log(`Checking if it's safe to reboot due to: ${reason}`);
fs.readFile(safePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading safe-to-reboot flag: ${err}`);
console.log('Skipping reboot due to error reading flag.');
process.exit(1);
} else if (data.trim() === SAFE_REBOOT_MESSAGE) {
if (reason.message.includes('FATAL') ||
reason.code == 'CRITICAL_ERROR' ||
reason instanceof TypeError) {
console.log('Safe to reboot flag is set. Initiating reboot...');
saveLog(reason);
initiateReboot(reason);
} else {
console.log('That was NOT fatal. Exiting without reboot.');
process.exit(1);
}
} else {
console.log('Not safe to reboot. Exiting without reboot.');
process.exit(1);
}
});
}
function initiateReboot(reason) {
console.log(`Initiating system reboot due to: ${reason}`);
if (process.platform === "win32") {
exec('shutdown /r /t 10', (error, stdout, stderr) => {
if (error) {
console.error(`Reboot failed: ${error}`);
return;
}
console.log('System will reboot in 10 seconds.');
});
} else {
// For Unix-like systems
exec('sudo /sbin/shutdown -r now', (error, stdout, stderr) => {
if (error) {
console.error(`Reboot failed: ${error}`);
return;
}
console.log('System is rebooting now.');
});
}
// Give some time for the reboot command to be processed
setTimeout(() => process.exit(1), 5000);
}
//FUNCTIONS
/** Assigns a valid browser path to the BROWSER_PATH variable based on the configuration
* @return {Promise<void>} A promise that resolves when the browser path is assigned. */
async function assignBrowserPath() {
BROWSER_PATH = config.browser.path === STRING_PLACEHOLDER
? await findValidChromiumPath()
: config.browser.path;
}
const todayDate = () => {
const today = new Date();
const day = String(today.getDate()).padStart(2, '0');
const month = String(today.getMonth() + 1).padStart(2, '0'); // Months are zero-based
const year = today.getFullYear();
return `${day}/${month}/${year}`;
}
const sleep = async (ms) => new Promise(resolve => setTimeout(resolve, ms));
/** Asynchronously extracts article text with retry logic.
* @param {string} url - The URL of the article to extract text from.
* @param {number} [maxRetries=3] - The maximum number of retry attempts.
* @return {Promise<string>} The extracted article text. */
async function extractArticleTextWithRetry(url, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await extractArticleText(url);
} catch (error) {
if (attempt === maxRetries) throw error;
console.log(`Attempt ${attempt} failed for ${url}. Retrying...`);
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
/** Extracts the text content of an article from a given URL.
* @param {string} url - The URL of the article.
* @return {Promise<string>} A Promise that resolves to the extracted text content. */
async function extractArticleText(url) {
let articleHtml;
try {
articleHtml = await fetchTextWithRetry(url);
articleHtml = cleanText(articleHtml);
try {
if (countTokens(articleHtml) < 100) {
let { url: proxiedUrl, content: text } = await getProxiedContent(removeWeirdCharactersFromUrl(url));
text = cleanText(text);
articleHtml = countTokens(articleHtml) < countTokens(text) ? text : articleHtml;
}
} catch (error) {
console.log("There was an error extracting article text!", error.message);
} finally {
return articleHtml;
}
} catch (error) {
console.error(`Fetch error for ${url}: ${error.message}`);
return EMPTY_STRING;
}
}
/** Cleans the HTML text by removing patterns, sanitizing, and replacing unwanted characters.
* @param {string} html - The HTML text to be cleaned.
* @return {string} The cleaned HTML text. */
const cleanText = (html) => {
let cleanedHtml = removePatterns(html, patternsToRemoveFromHTML);
cleanedHtml = sanitizeHtml(cleanedHtml, {
allowedTags: [],
allowedAttributes: {}
});
const accentMap = {
'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u',
'Á': 'A', 'É': 'E', 'Í': 'I', 'Ó': 'O', 'Ú': 'U',
'ñ': 'n', 'Ñ': 'N', 'ü': 'u', 'Ü': 'U'
};
cleanedHtml = cleanedHtml
.replace(/\n/g, ' ')
.replace(/\t/g, ' ')
.replace(/<[^>]*>/g, '')
.replace(/[áéíóúñü]/g, char => accentMap[char] || char)
.replace(/\s{2,}/g, ' ')
.trim();
return cleanedHtml;
};
async function getChunkedOpenAIResponse(text, topic, maxTokens) {
/** Generates a prompt for OpenAI to generate a summary of a specific part of a news article.
* @param {string} news_content - The content of the news article.
* @param {string} news_topic - The topic of the news article.
* @param {number} current - The current part number of the news article being summarized.
* @param {number} total - The total number of parts in the news article.
* @return {string} The generated prompt for OpenAI. */
function getPrompt(news_content, news_topic, current, total) {
return `Haz un resumen del siguiente fragmento que cubre la parte ${current} de ${total}` +
`de la siguiente noticia:\n\n\n\n${news_content}\n\n\n\n` +
`Ignora todo texto que no tenga que ver con el tema de la noticia: ${news_topic}`;
}
try {
const chunks = splitTextIntoChunks(text);
let respuesta = EMPTY_STRING;
maxTokens = Math.floor(maxTokens / chunks.length);
for (let i = 0; i < chunks.length; i++) {
let content = getPrompt(chunks[i], topic, (i + 1), chunks.length);
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: content }],
stream: true,
max_tokens: maxTokens,
temperature: 0.1,
top_p: 0.1,
frequency_penalty: 0.0,
presence_penalty: 0.0,
});
for await (const chunkResponse of response) {
respuesta += chunkResponse.choices[0]?.delta?.content || EMPTY_STRING;
}
}
return respuesta;
} catch (error) {
console.error('Error in OpenAI response:', error);
return EMPTY_STRING;
}
}
/** Counts the tokens of a string
* @param {String} text The text whose tokens are to be counted
* @returns {number} The amount of tokens */
const countTokens = (text) => {
if (!text) return 0;
return text.trim().split(/\s+/).length;
}
/** Splits a text into chunks of a maximum number of tokens per call
* @param {string} text - The text to be split into chunks.
* @return {string[]} An array of chunks, each containing a maximum of MAX_TOKENS_PER_CALL tokens. */
function splitTextIntoChunks(text) {
const tokens = text.split(/\s+/);
const chunks = [];
let currentChunk = EMPTY_STRING;
for (const token of tokens) {
if ((currentChunk + " " + token).length <= MAX_TOKENS_PER_CALL) {
currentChunk += " " + token;
} else {
chunks.push(currentChunk.trim());
currentChunk = token;
}
}
if (currentChunk) {
chunks.push(currentChunk.trim());
}
return chunks;
}
async function getNonChunkedOpenAIResponse(text, topic, maxTokens) {
text = `Haz un resumen de la siguiente noticia:\n\n\n\n${text}\n\n\n\nIgnora todo texto que no tenga que ver con el tema de la noticia: ${topic}`;
try {
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: text }],
stream: true,
max_tokens: maxTokens,
temperature: 0.1,
top_p: 0.1,
frequency_penalty: 0.0,
presence_penalty: 0.0,
});
let respuesta = EMPTY_STRING;
for await (const chunk of response) {
respuesta += chunk.choices[0]?.delta?.content || EMPTY_STRING;
}
return respuesta;
} catch (error) {
console.error('Error in OpenAI response:', error);
return EMPTY_STRING;
}
}
/** Retrieves an OpenAI response for the given text and title.
* @param {string} text - The text to be summarized.
* @param {string} topic - The topic of the news article.
* @param {number} maxTokens - The maximum number of tokens allowed in the response.
* @return {Promise<string>} A promise that resolves to the OpenAI response. If the text is empty or the topic is empty, an empty string is returned. If the number of tokens in the text exceeds the maximum allowed tokens per call, the function calls getChunkedOpenAIResponse to handle the text in chunks.
* Otherwise, it calls getNonChunkedOpenAIResponse to generate the response. */
async function getOpenAIResponse(text, topic, maxTokens) {
if (text == EMPTY_STRING || topic == EMPTY_STRING) {
return EMPTY_STRING;
}
if (countTokens(text) >= MAX_TOKENS_PER_CALL) {
return getChunkedOpenAIResponse(text, topic, maxTokens);
}
return getNonChunkedOpenAIResponse(text, topic, maxTokens);
}
/** Retrieves the content of a webpage behind a paywall by using a proxy website.
* @param {string} link - The URL of the webpage.
* @return {Promise<{url: string, content: string}>} A promise that resolves to an object containing the content of the webpage
* and the URL of the retrieved content if it is successfully retrieved, or an empty string if an error occurs. */
async function getProxiedContent(link) {
try {
console.log(`Article may be behind a PayWall :-(\nLet's try to access via proxy for ${link} ...`);
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
executablePath: BROWSER_PATH,
protocolTimeout: 120000
});
let page = await browser.newPage();
await page.setDefaultNavigationTimeout(120000);
await page.goto('https://www.removepaywall.com/', { waitUntil: 'domcontentloaded' });
await page.type('input#simple-search', link);
await page.click('#__next > div > section > div > header > div > div:nth-child(4) > form > button');
await page.waitForNavigation({ waitUntil: 'domcontentloaded' });
const content = await page.evaluate(() => document.body.innerText);
const retrievedUrl = page.url();
await browser.close();
return { url: retrievedUrl, content: content };
} catch (error) {
console.error('Error in fetching proxied content:', error);
return { url: EMPTY_STRING, content: EMPTY_STRING };
}
}
/** Retrieves a summary of the text using OpenAI's GPT-4 model.
* @param {string} link - The URL of the webpage
* @param {string} fullText - The text content of the news article
* @param {number} numberOfLinks - The total number of links under the same TERM search
* @param {string} topic - The topic of the news article
* @return {Promise<{url: string, response: string}>} A promise that resolves to an object containing the summary of the text and the valid URL. */
const summarizeText = async (link, fullText, numberOfLinks, topic) => {
let text = fullText;
let maxTokens = 150 + Math.ceil(300 / numberOfLinks);
let response = EMPTY_STRING;
let count = 0;
let url = link;
while ((response === EMPTY_STRING || countTokens(text) < 150) && count < 3) {
if (count === 0) {
response = await getOpenAIResponse(text, topic, maxTokens);
} else if (count === 1) {
({ url, content: text } = await getProxiedContent(link));
response = await getOpenAIResponse(text, topic, maxTokens);
} else {
response = FAILED_SUMMARY_MSSG;
url = link;
}
count++;
}
return { url, response };
};
/** Checks if a given date is recent.
* @param {string} dateText - The date to be checked.
* @return {boolean} Returns true if the date is recent, false otherwise. */
function isRecent(dateText) {
if (!dateText) return false;
const now = new Date();
let date;
// Check if the input is a Unix timestamp
if (/^\d+$/.test(dateText)) {
const timestamp = parseInt(dateText, 10);
if (timestamp > 0) {
date = new Date(timestamp * 1000);
return differenceInHours(now, date) < 24 || date > now;
}
}
// Try parsing as ISO 8601 first
date = parseISO(dateText);
if (isValid(date)) {
return differenceInHours(now, date) < 24 || date > now;
}
const months = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 };
// Handle "dd MMM yyyy HH:mm:ss +ZZZZ" format
const rfc822Match_1 = dateText.match(/(\d{1,2}) ([A-Za-z]{3}) (\d{4}) (\d{2}:\d{2}:\d{2}) ([+-]\d{4})/);
if (rfc822Match_1) {
const [_, day, month, year, time, offset] = rfc822Match_1;
date = new Date(`${year}-${(months[month] + 1).toString().padStart(2, '0')}-${day.padStart(2, '0')}T${time}${offset}`);
return differenceInHours(now, date) < 24 || date > now;
}
// Try parsing as RFC 2822
const rfc2822Match_2 = dateText.match(/[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}:\d{2}:\d{2}) ([+-]\d{4}|GMT)/);
if (rfc2822Match_2) {
const [_, day, monthStr, year, time, offset] = rfc2822Match_2;
const month = months[monthStr];
const combinedDate = `${year}-${month + 1}-${day}T${time}`;
date = new Date(combinedDate);
if (offset !== 'GMT') {
const offsetHours = parseInt(offset.slice(0, 3));
const offsetMinutes = parseInt(offset.slice(3));
const totalOffsetMinutes = offsetHours * 60 + (offsetHours < 0 ? -offsetMinutes : offsetMinutes);
date = subMinutes(date, totalOffsetMinutes);
}
return differenceInHours(now, date) < 24 || date > now;
}
const offsetMap = {
'ACDT': 10.5, 'ACST': 9.5, 'ACT': -5, 'ACWST': 8.75, 'ADT': -3, 'AEDT': 11,
'AEST': 10, 'AET': 10, 'AFT': 4.5, 'AKDT': -8, 'AKST': -9, 'ALMT': 6,
'AMST': -3, 'AMT': -4, 'ANAT': 12, 'AQTT': 5, 'ART': -3, 'AST': -4,
'AWST': 8, 'AZOST': 0, 'AZOT': -1, 'AZT': 4, 'BDT': 8, 'BIOT': 6,
'BIT': -12, 'BOT': -4, 'BRST': -2, 'BRT': -3, 'BST': 1, 'BTT': 6,
'CAT': 2, 'CCT': 6.5, 'CDT': -5, 'CEST': 2, 'CET': 1, 'CHADT': 13.75,
'CHAST': 12.75, 'CHOT': 8, 'CHOST': 9, 'CHST': 10, 'CHUT': 10, 'CIST': -8,
'CIT': 8, 'CKT': -10, 'CLST': -3, 'CLT': -4, 'COST': -4, 'COT': -5,
'CST': -6, 'CT': 8, 'CVT': -1, 'CWST': 8.75, 'CXT': 7, 'DAVT': 7,
'DDUT': 10, 'DFT': 1, 'EASST': -5, 'EAST': -6, 'EAT': 3, 'ECT': -5,
'EDT': -4, 'EEST': 3, 'EET': 2, 'EGST': 0, 'EGT': -1, 'EST': -5,
'ET': -5, 'FET': 3, 'FJT': 12, 'FKST': -3, 'FKT': -4, 'FNT': -2,
'GALT': -6, 'GAMT': -9, 'GET': 4, 'GFT': -3, 'GILT': 12, 'GMT': 0,
'GST': 4, 'GYT': -4, 'HDT': -9, 'HAEC': 2, 'HST': -10, 'HKT': 8,
'HMT': 5, 'HOVT': 7, 'ICT': 7, 'IDLW': -12, 'IDT': 3, 'IOT': 6,
'IRDT': 4.5, 'IRKT': 8, 'IRST': 3.5, 'IST': 5.5, 'JST': 9, 'KALT': 2,
'KGT': 6, 'KOST': 11, 'KRAT': 7, 'KST': 9, 'LHST': 10.5, 'LINT': 14,
'MAGT': 12, 'MART': -9.5, 'MAWT': 5, 'MDT': -6, 'MET': 1, 'MEST': 2,
'MHT': 12, 'MIST': 11, 'MIT': -9.5, 'MMT': 6.5, 'MSK': 3, 'MST': -7,
'MUT': 4, 'MVT': 5, 'MYT': 8, 'NCT': 11, 'NDT': -2.5, 'NFT': 11,
'NOVT': 7, 'NPT': 5.75, 'NST': -3.5, 'NT': -3.5, 'NUT': -11, 'NZDT': 13,
'NZST': 12, 'OMST': 6, 'ORAT': 5, 'PDT': -7, 'PET': -5, 'PETT': 12,
'PGT': 10, 'PHOT': 13, 'PHT': 8, 'PKT': 5, 'PMDT': -2, 'PMST': -3,
'PONT': 11, 'PST': -8, 'PWT': 9, 'PYST': -3, 'PYT': -4, 'RET': 4,
'ROTT': -3, 'SAKT': 11, 'SAMT': 4, 'SAST': 2, 'SBT': 11, 'SCT': 4,
'SDT': -10, 'SGT': 8, 'SLST': 5.5, 'SRET': 11, 'SRT': -3, 'SST': 8,
'SYOT': 3, 'TAHT': -10, 'THA': 7, 'TFT': 5, 'TJT': 5, 'TKT': 13,
'TLT': 9, 'TMT': 5, 'TRT': 3, 'TOT': 13, 'TVT': 12, 'ULAST': 9,
'ULAT': 8, 'USZ1': 2, 'UTC': 0, 'UYST': -2, 'UYT': -3, 'UZT': 5,
'VET': -4, 'VLAT': 10, 'VOLT': 4, 'VOST': 6, 'VUT': 11, 'WAKT': 12,
'WAST': 2, 'WAT': 1, 'WEST': 1, 'WET': 0, 'WIT': 7, 'WGST': -2,
'WGT': -3, 'WST': 8, 'YAKT': 9, 'YEKT': 5
};
// Handle "dd/MM/yyyy HH:mm:ss Z" format
let tzOffsetMatch = dateText.match(/(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2}) ([+-]\d{2}:\d{2})/);
if (tzOffsetMatch) {
let [_, datePart, offset] = tzOffsetMatch;
date = parse(datePart, 'dd/MM/yyyy HH:mm:ss', new Date());
if (isValid(date)) {
let [hoursOffset, minutesOffset] = offset.split(':').map(Number);
let totalOffsetMinutes = hoursOffset * 60 + (hoursOffset < 0 ? -minutesOffset : minutesOffset);
date = subMinutes(date, totalOffsetMinutes);
return differenceInHours(now, date) < 24 || date > now;
}
}
let cosa = dateText.match(/(\d{2}\/\d{2}\/\d{4} \d{1}:\d{2}:\d{2}) ([+-]\d{2}:\d{2})/);
if (cosa) {
let [_, datePart, offset] = cosa;
date = parse(datePart, 'dd/MM/yyyy H:mm:ss', new Date());
if (isValid(date)) {
let [hoursOffset, minutesOffset] = offset.split(':').map(Number);
let totalOffsetMinutes = hoursOffset * 60 + (hoursOffset < 0 ? -minutesOffset : minutesOffset);
date = subMinutes(date, totalOffsetMinutes);
return differenceInHours(now, date) < 24 || date > now;
}
}
// Handle "YYYY-MM-DD[TIMEZONE]HH:MM:SS" format
let tzAbbrMatch = dateText.match(/(\d{4}-\d{2}-\d{2})([A-Z]{3,5})(\d{2}:\d{2}:\d{2})/);
if (tzAbbrMatch) {
let [_, datePart, tz, timePart] = tzAbbrMatch;
let combinedDate = `${datePart}T${timePart}`;
let offset = offsetMap[tz];
if (offset !== undefined) {
date = parse(combinedDate, "yyyy-MM-dd'T'HH:mm:ss", new Date());
if (isValid(date)) {
let totalOffsetMinutes = offset * 60;
date = subMinutes(date, totalOffsetMinutes);
return differenceInHours(now, date) < 24 || date > now;
}
}
}
// Handle "YYYY-MM-DD[TIMEZONE]HH:MM" format
let tzMatch = dateText.match(/(\d{4}-\d{2}-\d{2})([A-Z]{3,5})(\d{2}:\d{2})/);
if (tzMatch) {
let [_, datePart, tz, timePart] = tzMatch;
let combinedDate = `${datePart}T${timePart}`;
let offset = offsetMap[tz];
if (offset !== undefined) {
date = parse(combinedDate, "yyyy-MM-dd'T'HH:mm", new Date());
if (isValid(date)) {
let totalOffsetMinutes = offset * 60;
date = subMinutes(date, totalOffsetMinutes);
return differenceInHours(now, date) < 24 || date > now;
}
}
}
// Handle "dd/MM/yyyy HH:mm" format
date = parse(dateText, 'dd/MM/yyyy HH:mm', new Date());
if (isValid(date)) {
return differenceInHours(now, date) < 24 || date > now;
}
// Handle "dd-MM-yyyy HH:mm:ss" format
date = parse(dateText, 'dd-MM-yyyy HH:mm:ss', new Date());
if (isValid(date)) {
return differenceInHours(now, date) < 24 || date > now;
}
// Handle preamble like "By Lucas Leiroz de Almeida, July 08, 2024"
let preambleMatch = dateText.match(/.*, (\w+ \d{2}, \d{4})/);
if (preambleMatch) {
let [_, datePart] = preambleMatch;
date = parse(datePart, 'MMMM dd, yyyy', new Date(), { locale: enUS });
if (isValid(date)) {
return differenceInHours(now, date) < 24 || date > now;
}
}
// Handle relative dates
let relativeMatchES = dateText.match(/hace (\d+) (minutos?|horas?|días?|semanas?|meses?)/i);
let relativeMatchEN = dateText.match(/(\d+) (minute|hour|day|week|month)s? ago/i);
if (relativeMatchES || relativeMatchEN) {
let [_, amount, unit] = relativeMatchES || relativeMatchEN;
date = new Date(now);
switch (unit.toLowerCase()) {
case 'minuto':
case 'minutos':
case 'minute':
case 'minutes':
date.setMinutes(date.getMinutes() - parseInt(amount));
break;
case 'hora':
case 'horas':
case 'hour':
case 'hours':
date.setHours(date.getHours() - parseInt(amount));
break;
case 'día':
case 'días':
case 'day':
case 'days':
date.setDate(date.getDate() - parseInt(amount));
break;
case 'semana':
case 'semanas':
case 'week':
case 'weeks':
date.setDate(date.getDate() - (parseInt(amount) * 7));
break;
case 'mes':
case 'meses':
case 'month':
case 'months':
date.setMonth(date.getMonth() - parseInt(amount));
break;
}
return differenceInHours(now, date) < 24;
}
// Handle various date formats
let formats = [
'dd/MM/yyyy',
'MM/dd/yyyy',
'dd-MM-yyyy',
'yyyy-MM-dd',
'd MMMM yyyy',
'MMMM d, yyyy',
'd MMM yyyy',
'MMM d, yyyy',
"d 'de' MMMM 'de' yyyy",
"d 'de' MMM'.' 'de' yyyy",
'yyyy-MM-dd HH:mm:ss',
"EEEE d 'de' MMMM"
];
for (let format of formats) {
date = parse(dateText, format, new Date(), { locale: es });
if (isValid(date)) break;
date = parse(dateText, format, new Date(), { locale: enUS });
if (isValid(date)) break;
}
if (isValid(date)) {
return differenceInHours(now, date) < 24 || date > now;
}
// Handle natural language dates like "Panamá, 09 de julio del 2024"
let spanishMonthAbbr = {
'ene': 0, 'feb': 1, 'mar': 2, 'abr': 3, 'may': 4, 'jun': 5,
'jul': 6, 'ago': 7, 'sept': 8, 'sep': 8, 'oct': 9, 'nov': 10, 'dic': 11
};
let match = dateText.match(/(\d{1,2})?\s*(?:de)?\s*(\w+)\.?\s*(?:de)?\s*(\d{4})?/i);
if (match) {
let [_, day, month, year] = match;
month = spanishMonthAbbr[month.toLowerCase().substring(0, 3)];
if (month !== undefined) {
year = year ? parseInt(year) : now.getFullYear();
day = day ? parseInt(day) : 1;
date = new Date(year, month, day);
return differenceInHours(now, date) < 24 || date > now;
}
}
let nlMatch = dateText.match(/(\d{1,2})\s*de\s*(\w+)\s*del?\s*(\d{4})/i);
if (nlMatch) {
let [_, day, month, year] = nlMatch;
let spanishMonthFull = {
'enero': 0, 'febrero': 1, 'marzo': 2, 'abril': 3, 'mayo': 4, 'junio': 5,
'julio': 6, 'agosto': 7, 'septiembre': 8, 'octubre': 9, 'noviembre': 10, 'diciembre': 11
};
month = spanishMonthFull[month.toLowerCase()];
if (month !== undefined) {
date = new Date(parseInt(year), month, parseInt(day));
return differenceInHours(now, date) < 24 || date > now;
}
}
// Last resort: try to parse with built-in Date constructor
date = new Date(dateText);
if (isValid(date)) {
return differenceInHours(now, date) < 24 || date > now;
}
console.warn(`Could not parse date: ${dateText}`);
return false;
}
/** Wrapper function to get the text data of a given URL
* @param {string} url
* @returns {string} The text data */
async function fetchTextWithRetry(url) {
const response = await fetchWithRetry(removeWeirdCharactersFromUrl(url));
if (typeof response === 'string') {
return response;
} else if (response && typeof response.data === 'string') {
return response.data;
} else {
throw new Error('Unexpected response format');
}
}
/** Weird characters that make my life difficult if present in URL */
const weirdCharacters = ['?', '%', '#'];
/** Removes any characters from (and including) weird characters from the given URL.
* @param {string} url - The URL from which to remove the weird characters.
* @return {string} The modified URL with the weird characters removed. */
function removeWeirdCharactersFromUrl(url) {
for (let char of weirdCharacters) {
if (url.includes(char)) {
const index = url.indexOf(char);
url = url.substring(0, index);
}
}
return url;
}
/** Fetches data from a given URL with retry logic.
* @param {string} url - The URL to fetch data from.
* @param {number} [retries=0] - The number of retries.
* @param {number} [initialDelay=INITIAL_DELAY] - The initial delay in milliseconds.
* @param {boolean} [triedBoth=false] - Indicates if both variants of the URL have been tried.
* @return {Promise<any>} A Promise that resolves to the fetched data.
* @throws {LightweightError} If the maximum number of retries is reached or if the crawl is stopped. */
async function fetchWithRetry(url, retries = 0, initialDelay = INITIAL_DELAY, triedBoth = false) {
if (globalStopFlag) {
throw new LightweightError('Crawl stopped');
}
let urlWithoutSlash = normalizeUrl(url);
let urlWithSlash = denormalizeUrl(url);
let urlToFetch = triedBoth ? url : (retries % 2 === 0 ? urlWithoutSlash : urlWithSlash);
try {
const randomDelay = Math.floor(Math.random() * initialDelay);
await sleep(randomDelay);
await rateLimiter.removeTokens(1);
const response = await axios.get(urlToFetch, {
headers: {
'User-Agent': 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59'
},
timeout: 15000
});
return response.data;
} catch (error) {
if (!triedBoth) {
// If we haven't tried both variants yet, try the other one immediately
console.log(`Attempt failed for ${urlToFetch}. Trying alternate URL...`);
return fetchWithRetry(urlToFetch === urlWithoutSlash ? urlWithSlash : urlWithoutSlash, retries, initialDelay, true);
}
if (retries >= MAX_RETRIES_PER_FETCH - 1) { // -1 because we're counting from 0
throw new LightweightError(`Failed to fetch ${url} after ${MAX_RETRIES_PER_FETCH} retries: ${error.message}`);
}
const delay = initialDelay * Math.pow(3, retries);
console.log(`Attempt ${retries + 1} failed for ${url}. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, retries + 1, delay, false);
}
}
/** Calculates the relevance score and finds the most common term in the given text.
* @param {string} title - The title of the article.
* @param {string} articleContent - The content of the article.
* @return {object} An object containing the score and the most common term.
* - {number} score: The relevance score.
* - {string} mostCommonTerm: The most common term found in the text. */
const relevanceScoreAndMaxCommonFoundTerm = (title, articleContent) => {
let text = (title + ' ' + articleContent).toLowerCase();
let termFrequencies = {};
let termPresence = {};
let totalWords = text.split(/\s+/).length;
let termCount = 0;
let presenceCount = 0;
let coOccurrenceCount = 0;
let mostCommonTerm = '';
let maxCommonFoundTermCount = 0;
// Initialize metrics
terms.forEach(term => {
termFrequencies[term] = 0;
termPresence[term] = 0;
});
// Calculate term frequencies, presence, and find most common term
terms.forEach(term => {
let regex = new RegExp("\\b" + term + "\\b", 'ig');
let matches = text.match(regex) || [];
let termCount = matches.length;
termFrequencies[term] = termCount;
termPresence[term] = termCount > 0 ? 1 : 0;
presenceCount += termPresence[term];
termCount += termCount;
if (termCount > maxCommonFoundTermCount) {
mostCommonTerm = term;
maxCommonFoundTermCount = termCount;
}
});