-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmeridianinsights.py
More file actions
3428 lines (3186 loc) · 96.1 KB
/
Copy pathmeridianinsights.py
File metadata and controls
3428 lines (3186 loc) · 96.1 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
#!/usr/bin/env python3
"""
Meridian RSS News Insights Aggregator with Enhanced Impact Classification and Clustering
By: Stephen A. Hedrick
With: Wavebound, LLC
Email: Stephen@wavebound.io
--- All Rights Reserved ---
This script fetches articles from specified RSS feeds, aggregates them based on similarity using advanced techniques,
assigns relevant meta tags, and sends an HTML-formatted email with the top news headlines,
organized by day of the week and date, using information from the RSS feeds and advanced matching.
"""
import os
import re
import ssl
import json
import numpy as np
import asyncio
import subprocess
from tqdm import tqdm
from tqdm.asyncio import tqdm
from typing import List, Dict
from collections import defaultdict
from datetime import datetime, timedelta, date
from dateutil import parser as date_parser
from dateutil import tz
import pycountry
from zoneinfo import ZoneInfo
from urllib.parse import urlparse
from googletrans import Translator
import feedparser
from bs4 import BeautifulSoup
from sentence_transformers import SentenceTransformer
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from ftfy import fix_text as ftfy_fix_text
import spacy
from fuzzywuzzy import fuzz
import nltk
from nltk.corpus import stopwords
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk.tokenize import word_tokenize
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('stopwords')
nltk.download('vader_lexicon')
import language_tool_python
import contractions
import tldextract
import torch
from sklearn.cluster import DBSCAN
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.cluster import AgglomerativeClustering
from newspaper import Article
from aiohttp import ClientSession
from collections import defaultdict, Counter
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email_validator import validate_email, EmailNotValidError
import logging
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("meridian.log"),
logging.StreamHandler()
]
)
# Initialize global variables
nlp = None
# redis_client = None
translator = None
def fix_contractions(text):
return contractions.fix(text)
def capitalize_proper_nouns(text: str) -> str:
words = nltk.word_tokenize(text)
pos_tags = nltk.pos_tag(words)
capitalized_words = []
for word, tag in pos_tags:
if tag in ['NNP', 'NNPS']:
word = word.capitalize()
capitalized_words.append(word)
return ' '.join(capitalized_words)
def divider() -> str:
# Return an HTML divider
return "<hr style='border:1px solid #ccc;'>\n"
# Initialize the grammar tool
tool = language_tool_python.LanguageTool('en-US')
def initialize_resources():
global nlp, translator, sentiment_analyzer, s3_client
# redis_client,
nltk.data.path.append("/tmp/nltk_data")
subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"], check=True)
# Load spaCy model
nlp = spacy.load("en_core_web_sm")
# Initialize Google Translator
translator = Translator()
nltk.download("stopwords", download_dir="/tmp/nltk_data")
# Ensure the VADER lexicon is downloaded
nltk.download("vader_lexicon", download_dir="/tmp/nltk_data")
# Initialize the VADER sentiment analyzer
sentiment_analyzer = SentimentIntensityAnalyzer()
# Update VADER lexicon with custom words specific to major news headlines
new_words = {
"catastrophe": -3.5,
"disaster": -3.0,
"explosion": -3.0,
"explosions": -3.0,
"blows up": -3.0,
"war": -3.0,
"tragedy": -3.0,
"collapse": -3.0,
"hurricane": -3.0,
"earthquake": -3.0,
"shooting": -3.0,
"terrorist": -3.0,
"fraud": -3.0,
"impeach": -3.0,
"impeached": -3.0,
"impeachment": -3.0,
"impeaches": -3.0,
"attack": -2.5,
"cyberattack": -2.5,
"defeat": -2.5,
"failure": -2.5,
"fail": -2.5,
"crash": -2.5,
"recession": -2.5,
"pandemic": -2.5,
"plummet": -2.5,
"conflict": -2.5,
"flood": -2.5,
"disinformation": -2.5,
"urgent": -2.5,
"security probe": -2.5,
"critical": -2.0,
"breaking": -2.0,
"decline": -2.0,
"wildfire": -2.0,
"critical condition": -2.0,
"brace for": -2.0,
"hemoraging": -2.0,
"braces for": -2.0,
"loss": -2.0,
"leak": -2.0,
"siezes": -2.0,
"low growth": -2.0,
"high debt": -2.0,
"weigh on": -2.0,
"imminent risk": -2.0,
"famine": -2.0,
"virus": -2.0,
"afraid": -2.0,
"accident": -2.0,
"nonexistent": -2.0,
"storm": -2.0,
"shocked": -2.0,
"recall": -2.0,
"recalls": -2.0,
"could impact": -2.0,
"explosions": -2.0,
"explosion": -2.0,
"drought": -2.0,
"killed": -2.0,
"alert": -1.5,
"bailout": -1.5,
"sanctions on": -1.5,
"to cut up to": -1.5,
"strike": -1.5,
"hospitalized": -1.5,
"antisemitic": -1.5,
"trump": -1.5,
"putin": -1.5,
"nazi": -1.5,
"nazis": -1.5,
"protest": -1.5,
"gap is growing": -1.5,
"controversial": -1.0,
"despite": -1.0,
"migrants": -1.0,
"condemn": -1.0,
"racist": -1.0,
"rubio": -1.0,
"gaetz": -1.0,
"gabbard": -1.0,
"thune": -1.0,
"ramaswamy": -1.0,
"musk": -1.0,
"flood": -1.0,
"tax": -1.0,
"react to": -1.0,
"taxes": -1.0,
"capital gains": -1.0,
"plunge": -1.0,
"disappointing": -1.0,
"warning": -1.0,
"closing": -1.0,
"raising": -1.0,
"faces at least": -1.0,
"plot": -1.0,
"assasination": -1.0,
"to invest": 1.0,
"nasa": 1.0,
"launch of": 1.0,
"launching": 1.0,
"moon": 1.0,
"stars": 1.0,
"surge": 1.5,
"help": 1.5,
"invest": 1.5,
"soar": 2.0,
"soars": 2.0,
"new high": 2.0,
"launches": 2.0,
"expedition": 2.0,
"making it easier": 2.0,
"gain": 2.0,
"making it easier to": 2.0,
"win": 2.0,
"soars": 2.0,
"growth": 2.0,
"breakthrough": 2.5,
"success": 2.5,
"victory": 2.5,
"turnout": 3,
"nuclear power": 3,
# Add more words as needed
}
sentiment_analyzer.lexicon.update(new_words)
rss_feeds = [
# High-Impact Feeds
"https://www.whitehouse.gov/briefing-room/feed/",
"https://www.scotusblog.com/feed/",
"https://www.weather.gov/news/",
"https://www.govinfo.gov/rss/cprt.xml",
"https://www.cio.gov/feed.xml",
"https://www.ftc.gov/feeds/press-release.xml",
"https://www.nass.usda.gov/rss/news.xml",
"https://www.usda.gov/rss/latest-releases.xml",
"https://www.rd.usda.gov/rss.xml",
"https://www.nrc.gov/public-involve/rss?feed=news",
"https://www.usace.army.mil/DesktopModules/ArticleCS/RSS.ashx?ContentType=9&Site=420&Category=20166&isdashboardselected=0&max=20",
"https://www.census.gov/economic-indicators/indicator.xml",
"https://www.nasa.gov/rss/dyn/breaking_news.rss",
"https://www.nature.com/nature.rss",
"https://www.sciencemag.org/rss/news_current.xml",
"https://www.theguardian.com/world/world-health-organization/rss",
"https://www.nih.gov/news-releases/feed.xml",
"https://tools.cdc.gov/api/v2/resources/media/733939.rss",
"https://tools.cdc.gov/api/v2/resources/media/132608.rss",
"https://tools.cdc.gov/api/v2/resources/media/320567.rss",
"https://tools.cdc.gov/api/v2/resources/media/132782.rss",
"https://tools.cdc.gov/api/v2/resources/media/316422.rss",
"https://www.ecb.europa.eu/rss/press.html",
"https://www.federalreserve.gov/feeds/press_all.xml",
"https://www.imf.org/en/News/RSS?TemplateID={2FA3421A-F179-46B6-B8D9-5C65CB4A6584}",
"https://www.sec.gov/news/pressreleases.rss",
"https://www.nist.gov/news-events/news/rss.xml",
"https://news.un.org/feed/subscribe/en/news/all/rss.xml",
"https://isc.sans.edu/rssfeed_full.xml",
"https://www.usgs.gov/news/149245/feed",
"https://www.esa.int/rssfeed/Our_Activities/Telecommunications_Integrated_Applications",
# "http://www.worldbank.org/en/news/rss",
"https://www.rand.org/news/press.xml",
"https://www.energylivenews.com/feed/",
# "https://www.iea.org/newsroom/rss",
"https://unevoc.unesco.org/unevoc_rss.xml",
"https://www.iaea.org/feeds/topnews",
"https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/oci-press-releases/rss.xml",
# "https://www.osha.gov/news/newsreleases.xml",
"https://oceanservice.noaa.gov/rss/nosnews.xml",
"https://oceanservice.noaa.gov/newsroom/nosmedia.xml",
"https://www.safetyandhealthmagazine.com/rss/topic/99-news",
"https://www.defense.gov/DesktopModules/ArticleCS/RSS.ashx?max=10&ContentType=1&Site=945",
"https://www.wipo.int/pressroom/en/rss.xml",
# "https://www.fao.org/feeds/fao-newsroom-rss", #https://www.fao.org/news/rss-feed/en/
"https://www.eia.gov/rss/press_rss.xml",
# "https://www.rigzone.com/news/rss/rigzone_headlines.aspx",
"https://www.ogj.com/__rss/website-scheduled-content.xml?input=%7B%22sectionAlias%22%3A%22general-interest%22%7D",
"https://www.irena.org/iapi/rssfeed/News",
"https://www.itu.int/hub/tag/itu-t/feed/",
# "https://www.ifc.org/wps/wcm/connect/corp_ext_content/ifc_external_corporate_site/home/newsroom/media_rss",
"https://news.mit.edu/topic/mitmachine-learning-rss.xml",
"https://news.mit.edu/topic/mitcyber-security-rss.xml",
"https://www.ft.com/news-feed?format=rss",
"https://nasdaqtrader.com/rss.aspx?feed=currentheadlines&categorylist=0",
"https://www.nasdaq.com/feed/nasdaq-original/rss.xml",
"https://www.nasdaq.com/feed/rssoutbound?category=Commodities",
"https://www.nasdaq.com/feed/rssoutbound?category=IPOs",
"https://www.nasdaq.com/feed/rssoutbound?category=Markets",
"https://www.nasdaq.com/feed/rssoutbound?category=Stocks",
"https://www.nasdaq.com/feed/rssoutbound?category=Artificial+Intelligence",
"https://www.nasdaq.com/feed/rssoutbound?category=FinTech",
"https://www.nasdaq.com/feed/rssoutbound?category=Innovation",
"https://www.nasdaq.com/feed/rssoutbound?category=Nasdaq",
"https://www.nasdaq.com/feed/rssoutbound?category=Technology",
"https://asia.nikkei.com/rss/feed/nar",
"https://travel.state.gov/_res/rss/TAsTWs.xml",
"https://www.railway.supply/en/news-en/feed/",
"https://markets.newyorkfed.org/read?productCode=50&eventCodes=500&limit=25&startPosition=0&sort=postDt:-1&format=xml",
"https://www.prnewswire.com/rss/news-releases-list.rss",
"https://www.opec.org/opec_web/en/pressreleases.rss",
"https://www.windpowermonthly.com/rss/news",
"https://feed.businesswire.com/rss/home/?rss=G1QFDERJXkJeEF9YXA==&_gl=1*1lurxps*_gcl_au*MTI0MDcyOTY2Mi4xNzM0NjUwMjk4*_ga*MTQyMTk2MzY1MC4xNzM0NjUwMjk4*_ga_ZQWF70T3FK*MTczNDY1MDI5Ny4xLjEuMTczNDY1MDQzMy40Ni4wLjA.",
"https://feed.businesswire.com/rss/home/?rss=G1QFDERJXkJeGVtWWQ==&_gl=1*1di1nun*_gcl_au*MTI0MDcyOTY2Mi4xNzM0NjUwMjk4*_ga*MTQyMTk2MzY1MC4xNzM0NjUwMjk4*_ga_ZQWF70T3FK*MTczNDY1MDI5Ny4xLjEuMTczNDY1MDQzMy40Ni4wLjA.",
"https://feed.businesswire.com/rss/home/?rss=G1QFDERJXkJeEFtRXw==&_gl=1*ibfq09*_gcl_au*MTI0MDcyOTY2Mi4xNzM0NjUwMjk4*_ga*MTQyMTk2MzY1MC4xNzM0NjUwMjk4*_ga_ZQWF70T3FK*MTczNDY1MDI5Ny4xLjEuMTczNDY1MDY0NC42MC4wLjA.",
"https://feed.businesswire.com/rss/home/?rss=G1QFDERJXkJeEFtRWA==&_gl=1*ucren7*_gcl_au*MTI0MDcyOTY2Mi4xNzM0NjUwMjk4*_ga*MTQyMTk2MzY1MC4xNzM0NjUwMjk4*_ga_ZQWF70T3FK*MTczNDY1MDI5Ny4xLjEuMTczNDY1MDY1OS40NS4wLjA.",
"https://www.usgs.gov/news/all/feed",
"https://www.dol.gov/rss/releases.xml",
"https://www.justice.gov/news/rss?m=1",
"https://federalnewsnetwork.com/category/all-news/feed/",
"https://www.space.com/home/feed/site.xml",
"https://spacenews.com/feed/",
"https://www.bankinfosecurity.com/rss-feeds",
"https://www.cisa.gov/news.xml",
"https://krebsonsecurity.com/feed/",
# "https://www.cshub.com/rss/news",
"https://ourworldindata.org/atom-data-insights.xml",
"https://www.spglobal.com/commodityinsights/en/rss-feed/oil#",
"https://www.spglobal.com/commodityinsights/en/rss-feed/natural-gas",
"https://www.spglobal.com/commodityinsights/en/rss-feed/coal",
"https://www.spglobal.com/commodityinsights/en/rss-feed/electric-power",
"https://www.spglobal.com/commodityinsights/en/rss-feed/metals",
"https://www.spglobal.com/commodityinsights/en/rss-feed/shipping",
"https://www.spglobal.com/commodityinsights/en/rss-feed/agriculture",
"https://www.spglobal.com/commodityinsights/en/rss-feed/lng",
"https://www.spglobal.com/commodityinsights/en/rss-feed/energy-transition",
# "https://www.bls.gov/feed/cpi_latest.rss",
"https://www.chicagofed.org/forms/rss/DataReleases",
"https://www.consumerfinance.gov/about-us/newsroom/feed/",
"https://www.chicagofed.org/forms/rss/NewsReleases",
"https://www.aba.com/rss/press",
"https://www.federalreserve.gov/feeds/press_all.xml", # fed press all
"https://www.federalreserve.gov/feeds/press_monetary.xml", # fed monetary press all
"https://www.federalreserve.gov/feeds/Data/H15_H15_RIFSPFF_N.B.XML", # fed funds
"https://www.federalreserve.gov/feeds/Data/H15_H15_RIFSRP_F02_N.B.XML", # discount rate release
"https://www.hkex.com.hk/Services/RSS-Feeds/News-Releases?sc_lang=en", # HKEX
# "https://news.crunchbase.com/feed/",
# "https://www.digitaljournal.com/feed",
"https://www.elastic.co/blog/feed",
"https://www.uscourts.gov/news/rss",
# Medium-High Impact Feeds
"https://www.schneier.com/feed/atom/",
"https://news.sophos.com/en-us/category/threat-research/feed/",
"https://securelist.com/feed/",
"https://www.bleepingcomputer.com/feed/",
"https://feeds.feedburner.com/eset/blog",
"https://feeds.feedburner.com/TheHackersNews?format=xml",
"https://github.blog/engineering.atom",
"https://developer.nvidia.com/blog/feed",
"https://www.adp.com/~/spark_feed/people-management",
"https://www.globenewswire.com/RssFeed/country/United%20States/feedTitle/GlobeNewswire%20-%20News%20from%20United%20States",
"https://www.labornotes.org/feed",
"https://audioboom.com/channels/4905579.rss",
# "https://thebusinessjournal.com/feed/",
"https://newsletter.blockthreat.io/feed",
"https://www.c4isrnet.com/arc/outboundfeeds/rss/category/cyber/?outputType=xml",
"https://blog.criminalip.io/feed/",
"https://www.eff.org/rss/updates.xml",
"https://mondovisione.com/media-and-resources/news/rss/",
"https://www.morningstar.ca/ca/news/27103/RSS.aspx",
"https://mises.org/rss.xml",
"https://feeds.feedburner.com/LibertyStreetEconomics",
"https://ai-techpark.com/feed/",
"https://www.artificialintelligence-news.com/feed/",
"https://lastweekin.ai/feed",
"https://feeds.feedburner.com/RBloggers",
"https://news.mit.edu/topic/mitmachine-learning-rss.xml",
"https://feeds.feedburner.com/blogspot/gJZg",
"https://www.reddit.com/r/machinelearningnews/hot/.rss",
"https://www.automotive-iq.com/rss/categories/cybersecurity",
"https://www.automotive-iq.com/rss/categories/industry-reports",
"https://www.automotive-iq.com/rss/news",
"https://www.automotive-iq.com/rss/news-trends",
"https://spectrum.ieee.org/customfeeds/feed/all-topics/rss",
"https://www.rcrwireless.com/feed",
"https://feeds.feedburner.com/edgeindustryreview",
"https://feed.theregister.com/atom?q=edge+computing",
"https://www.manufacturingtomorrow.com/rss/news/",
"https://feeds.feedburner.com/biometricupdate",
"https://www.finextra.com/rss/headlines.aspx",
"https://www.manufacturingtomorrow.com/rss/news/",
"https://feeds.feedburner.com/sc247/rss/news",
"https://dataprivacymanager.net/feed",
"https://www.earthquakenewstoday.com/feed/",
"https://www.rnz.co.nz/rss/world.xml",
"https://www.rnz.co.nz/rss/media-technology.xml",
"https://feedx.net/rss/ap.xml",
# "https://www.reutersagency.com/feed/?taxonomy=best-customer-impacts&post_type=best",
"https://feeds.bbci.co.uk/news/world/rss.xml",
"https://time.com/feed/",
"https://chaski.huffpost.com/us/auto/vertical/world-news",
# "https://www.telegraph.co.uk/news/rss.xml",
"https://feeds.feedburner.com/NDTV-LatestNews",
"https://www.forbes.com/real-time/feed2/",
"https://feeds.npr.org/1001/rss.xml",
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
"https://feeds.bloomberg.com/economics/news.rss",
"https://feeds.bloomberg.com/industries/news.rss",
"https://feeds.bloomberg.com/markets/news.rss",
"https://feeds.a.dj.com/rss/RSSWorldNews.xml",
"https://www.economist.com/sections/economics/rss.xml",
"https://feeds.marketwatch.com/marketwatch/topstories/",
"https://feeds.content.dowjones.io/public/rss/mw_topstories",
"https://www.investing.com/rss/news.rss",
"https://www.wired.com/feed/rss",
"https://www.techradar.com/rss",
"https://arstechnica.com/feed/",
"https://qz.com/rss",
"http://feeds.hbr.org/harvardbusiness",
# "https://news.crunchbase.com/feed/",
"https://techcrunch.com/tag/saas/feed/",
"https://www.aljazeera.com/xml/rss/all.xml",
"https://rss.dw.com/xml/rss-en-all",
"https://feeds.feedburner.com/fastcompany/headlines",
"https://feeds.feedburner.com/InformationIsBeautiful",
# Medium Impact Feeds
"https://www.cbsnews.com/latest/rss/main",
"https://feeds.abcnews.com/abcnews/topstories",
"https://www.latimes.com/world-nation/rss2.0.xml",
"https://www.globaltimes.cn/rss/outbrain.xml",
"https://feeds.nbcnews.com/feeds/topstories",
"https://moxie.foxnews.com/google-publisher/world.xml",
"https://rss.cnn.com/rss/edition.rss",
"https://feeds.washingtonpost.com/rss/business",
"https://www.barchart.com/news/rss/commodities",
"https://www.barchart.com/news/rss/financials",
"https://www.barchart.com/news/authors/rss",
"https://biztoc.com/feed",
"https://feeds.feedburner.com/InformationIsBeautiful",
"https://www.bitdefender.com/nuxt/api/en-us/rss/hotforsecurity/industry-news/",
"https://bluepurple.binaryfirefly.com/feed",
"https://www.cyberdefensemagazine.com/feed/",
"https://cyberscoop.com/feed/",
"https://www.cybersecuritydive.com/feeds/news/",
"https://hackread.com/feed/",
# Medium-Low Impact Feeds
"http://feeds.feedburner.com/DrudgeReportFeed",
"https://www.theregister.com/headlines.rss",
"https://rss.slashdot.org/Slashdot/slashdot",
"https://gtmnow.com/feed/",
"https://www.thesalesblog.com/blog/rss.xml",
"https://oldschoolsalesdog.com/feed/",
# "https://www.producthunt.com/feed?category=undefined",
# "https://age-of-product.com/category/news/",
# "https://spectechular.walkme.com/feed/",
"https://feeds.feedburner.com/StrategyBusiness-Manufacturing",
"https://www.waterstechnology.com/feeds/rss/category/operations",
"https://feeds.feedburner.com/StrategyBusiness-Strategy",
"https://www.allthingssupplychain.com/feed/",
"https://www.supplychainbrain.com/rss/articles",
"https://theundercoverrecruiter.com/feed/",
"https://recruitingblogs.com/profiles/blog/feed?xn_auth=no",
"https://legaltechnology.com/feed/",
"https://medium.com/feed/artificialis",
"https://www.waterstechnology.com/feeds/rss/category/data-management",
"https://tech.eu/category/deep-tech/feed",
# "https://www.sciencedaily.com/rss/computers_math/artificial_intelligence.xml",
]
def clean_html(raw_html):
cleanr = re.compile("<.*?>")
return re.sub(cleanr, "", raw_html)
def extract_text_from_html(html_content):
soup = BeautifulSoup(html_content, "html.parser")
return soup.get_text(separator=" ", strip=True)
def preprocess_text(text: str) -> str:
"""
Preprocesses the input text by lemmatizing, removing stopwords and punctuation.
Parameters:
- text (str): The text to preprocess.
Returns:
- str: The preprocessed text.
"""
doc = nlp(text)
return ' '.join([token.lemma_ for token in doc if not token.is_stop and not token.is_punct])
def extract_entities(text: str) -> List[str]:
doc = nlp(text)
return [ent.text for ent in doc.ents]
async def fetch_feed(session, feed_url: str) -> str:
try:
async with session.get(feed_url) as response:
if response.status == 200:
return await response.text()
else:
logging.error(f"Failed to fetch {feed_url}: Status {response.status}")
return None
except Exception as e:
logging.error(f"Error fetching {feed_url}: {e}")
return None
async def fetch_all_feeds(rss_feeds: List[str]) -> List[str]:
async with ClientSession() as session:
tasks = [fetch_feed(session, feed_url) for feed_url in rss_feeds]
return await asyncio.gather(*tasks)
def process_article(entry, feed_url: str) -> Dict:
if not hasattr(entry, "link"):
return None
article_url = entry.link
article_data = {
"title": entry.get("title", "Untitled Article"),
"url": article_url,
"publish_date": entry.get("published", entry.get("updated", "")),
"source": feed_url,
"content": ''
}
# Try to get the content from the entry
if 'content' in entry and entry.content:
content = entry.content[0].value if isinstance(entry.content, list) else entry.content
article_data['content'] = extract_text_from_html(content)
elif 'summary' in entry and entry.summary:
article_data['content'] = extract_text_from_html(entry.summary)
else:
article_data['content'] = ''
# If content is still empty, fetch the article
if not article_data['content'].strip():
try:
article = Article(article_url)
article.download()
article.parse()
article_data['content'] = article.text
except Exception as e:
logging.error(f"Error fetching content from {article_url}: {e}")
article_data['content'] = ''
return article_data
# if 'content' in entry:
# content = entry.content[0].value if isinstance(entry.content, list) else entry.content
# article_data['content'] = extract_text_from_html(content)
# else:
# article_data['content'] = article_data['summary']
# try:
# lang = translator.detect(article_data['content']).lang
# if lang != 'en':
# article_data['content'] = translator.translate(article_data['content'], src=lang, dest='en').text
# article_data['title'] = translator.translate(article_data['title'], src=lang, dest='en').text
# except Exception as e:
# logging.error(f"Language detection/translation error: {e}")
#
# redis_client.setex(article_id, 86400, json.dumps(article_data))
# return article_data
def calculate_headline_count(article: Dict, all_articles: List[Dict]) -> int:
target_headline = article.get("title", "").strip().lower()
if not target_headline:
return 0
count = sum(1 for a in all_articles if a.get("title", "").strip().lower() == target_headline)
return count
def calculate_priority_score(article: Dict, all_articles: List[Dict]) -> float:
sentiment_score, impact_score, action_score = calculate_scores_for_headline(article.get("title", ""))
# Adjust the weights as needed
priority_score = 0.4 * sentiment_score + 0.3 * impact_score + 0.3 * action_score
return priority_score
def process_feeds(rss_feeds: List[str]) -> List[Dict]:
# Run the asynchronous feed fetching and processing
loop = asyncio.get_event_loop()
feed_contents = loop.run_until_complete(fetch_all_feeds(rss_feeds))
articles_content = []
for feed_content, feed_url in tqdm(
zip(feed_contents, rss_feeds), total=len(rss_feeds), desc="Processing feeds"
):
if feed_content:
feed = feedparser.parse(feed_content)
if "entries" in feed and len(feed.entries) > 0:
for entry in feed.entries:
article_data = process_article(entry, feed_url)
if article_data:
articles_content.append(article_data)
else:
logging.warning(f"No entries found in feed: {feed_url}")
logging.info(
f"Processed {len(articles_content)} articles from {len(rss_feeds)} feeds"
)
return articles_content
# Define common time zone abbreviations and their mappings
tzinfos = {
"EST": tz.gettz("America/New_York"),
"EDT": tz.gettz("America/New_York"),
"CST": tz.gettz("America/Chicago"),
"CDT": tz.gettz("America/Chicago"),
"MST": tz.gettz("America/Denver"),
"MDT": tz.gettz("America/Denver"),
"PST": tz.gettz("America/Los_Angeles"),
"PDT": tz.gettz("America/Los_Angeles"),
"BST": tz.gettz("Europe/London"),
"GMT": tz.gettz("Europe/London"),
"IST": tz.gettz("Asia/Kolkata"),
"UTC": tz.UTC,
# Add other time zones as needed
}
def fix_invalid_time(date_str):
# Match times with hour '24'
match = re.search(r"24:(\d{2}):(\d{2})", date_str)
if match:
# Replace '24' with '00'
fixed_time = "00:{}:{}".format(match.group(1), match.group(2))
# Replace in the date string
date_str = date_str.replace(
"24:{}:{}".format(match.group(1), match.group(2)), fixed_time
)
# Indicate that the date should be incremented
increment_day = True
else:
increment_day = False
return date_str, increment_day
def filter_and_preprocess_articles(articles_content: List[Dict]) -> List[Dict]:
"""
Filters articles within a 7-day window and preprocesses their content.
Parameters:
- articles_content (List[Dict]): The list of all fetched articles.
Returns:
- List[Dict]: The list of filtered and preprocessed articles.
"""
logging.info("Filtering articles by date and preprocessing...")
filtered_articles = []
today = datetime.now(tz.gettz("America/Chicago")).date()
seven_days_ago = today - timedelta(days=6)
future_allowed = today + timedelta(days=1)
for article in tqdm(articles_content, desc="Preprocessing articles"):
publish_date = article.get("publish_date")
publish_datetime = today # Default to today
if publish_date:
# Fix invalid times
fixed_publish_date, increment_day = fix_invalid_time(publish_date)
try:
# Try parsing the date using dateutil.parser with tzinfos
parsed_date = date_parser.parse(
fixed_publish_date, tzinfos=tzinfos, fuzzy=True
)
if increment_day:
parsed_date += timedelta(days=1)
publish_datetime = parsed_date.date()
except (ValueError, TypeError) as e:
logging.warning(
f"Unrecognized date format for article '{article['title']}': {publish_date}. Assigning today's date."
)
publish_datetime = today # Assign today's date
else:
logging.warning(
f"No publish date for article '{article['title']}'. Assigning today's date."
)
publish_datetime = today # Assign today's date
# Assign the parsed or default date with consistent key name
article["publish_datetime"] = publish_datetime
# Calculate 'headline_count' and 'priority_score'
article["headline_count"] = calculate_headline_count(article, articles_content)
article["priority_score"] = calculate_priority_score(article, articles_content)
# Check if the article falls within the desired date range
if seven_days_ago <= publish_datetime <= future_allowed:
article["preprocessed_content"] = preprocess_article_content(article["content"])
article["entities"] = extract_entities(article["title"])
if article["title"] and len(article["title"].split()) >= 4:
# Only add articles with non-empty title and at least 4 words
filtered_articles.append(article)
else:
logging.info(f"Skipping article with short title: '{article['title']}'")
else:
logging.info(
f"Skipping article outside the 7-day window: '{article['title']}' (Date: {publish_datetime})"
)
logging.info(f"Filtered and preprocessed {len(filtered_articles)} articles")
return filtered_articles
def calculate_similarity(article1, article2):
# Title similarity using fuzzy matching
title_similarity = fuzz.token_set_ratio(article1["title"], article2["title"]) / 100
# Title similarity using TF-IDF and cosine similarity
if article1["title"] and article2["title"]:
try:
# Use bigrams and ignore common stopwords with TF-IDF
tfidf = TfidfVectorizer(
ngram_range=(1, 2), stop_words="english"
).fit_transform([article1["title"], article2["title"]])
# Calculate cosine similarity between the two titles
title_similarity2 = cosine_similarity(tfidf[0], tfidf[1])[0][0]
# Only consider similarity scores above a set threshold 0-1
if title_similarity2 < 0.85:
title_similarity2 = 0 # Set to 0 if below threshold
except ValueError:
title_similarity2 = 0
else:
title_similarity2 = 0
# Temporal similarity based on date only
date_diff = abs(
(article1["publish_datetime"] - article2["publish_datetime"]).days
) # Difference in days
temporal_similarity = (
1 if date_diff == 0 else 0
) # Full similarity if published on the same day, otherwise 0
# Combine similarities with weights
total_similarity = (
0.3 * title_similarity + 0.6 * title_similarity2 + 0.1 * temporal_similarity
)
return total_similarity
# Original clustering function using nested loops (commented out)
# def cluster_articles(filtered_articles):
# logging.info("Clustering similar articles...")
# num_articles = len(filtered_articles)
# # Adding a check to ensure there are articles to cluster
# if num_articles == 0:
# logging.error("No articles available for clustering.")
# return defaultdict(list) # Return empty result
# similarity_matrix = np.zeros((num_articles, num_articles))
# for i in tqdm(range(num_articles), desc="Calculating similarities"):
# for j in range(i + 1, num_articles):
# similarity = calculate_similarity(
# filtered_articles[i], filtered_articles[j]
# )
# similarity_matrix[i, j] = similarity_matrix[j, i] = similarity
# # Use a higher threshold for clustering
# threshold = 0.4
# clustered_articles = defaultdict(list)
# for i in range(num_articles):
# cluster_found = False
# for cluster_id, cluster in clustered_articles.items():
# if any(
# similarity_matrix[i][filtered_articles.index(article)] >= threshold
# for article in cluster
# ):
# clustered_articles[cluster_id].append(filtered_articles[i])
# cluster_found = True
# break
# if not cluster_found:
# new_cluster_id = len(clustered_articles)
# clustered_articles[new_cluster_id].append(filtered_articles[i])
# # Logging the number of clusters found
# logging.info(f"Clustering complete. Found {len(clustered_articles)} clusters")
# return clustered_articles
# Alternative clustering function using Agglomerative Clustering (commented out)
# def cluster_articles(filtered_articles):
# logging.info("Clustering similar articles...")
# num_articles = len(filtered_articles)
# if num_articles == 0:
# logging.error("No articles available for clustering.")
# return defaultdict(list)
# # Extract article texts
# texts = [article["title"] for article in filtered_articles]
# # Convert texts to TF-IDF vectors
# vectorizer = TfidfVectorizer()
# tfidf_matrix = vectorizer.fit_transform(texts)
# # Compute cosine similarity matrix
# similarity_matrix = cosine_similarity(tfidf_matrix)
# np.fill_diagonal(similarity_matrix, 0) # Ensure self-similarity is 1
# # Convert similarity to distance matrix
# distance_matrix = 1 - similarity_matrix
# # Perform Agglomerative Clustering
# threshold = 0.85 # Adjust as needed
# clustering_model = AgglomerativeClustering(
# n_clusters=None,
# # affinity='precomputed',
# linkage='average',
# distance_threshold=threshold
# )
# clustering_model.fit(distance_matrix)
# # Organize articles into clusters
# clustered_articles = defaultdict(list)
# for idx, label in enumerate(clustering_model.labels_):
# clustered_articles[label].append(filtered_articles[idx])
# logging.info(f"Clustering complete. Found {len(clustered_articles)} clusters")
# return clustered_articles
# New clustering function using Hugging Face Sentence Transformers and DBSCAN
def cluster_articles(filtered_articles):
logging.info(
"Clustering similar articles using Sentence Transformers and DBSCAN..."
)
num_articles = len(filtered_articles)
if num_articles == 0:
logging.error("No articles available for clustering.")
return defaultdict(list)
# Extract article titles
texts = [article["title"] for article in filtered_articles]
# Load the pre-trained Sentence Transformer model
model_name = "all-MiniLM-L6-v2"
model = SentenceTransformer(model_name)
# Generate embeddings for the titles
embeddings = model.encode(texts, show_progress_bar=True)
# Normalize embeddings
embeddings = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
# Use DBSCAN for clustering, adjust as needed
clustering_model = DBSCAN(eps=0.25, min_samples=2, metric="cosine")
clustering_model.fit(embeddings)
labels = clustering_model.labels_
# Organize articles into clusters
clustered_articles = defaultdict(list)
for idx, label in enumerate(labels):
if label == -1:
# Noise point, assign to its own cluster
clustered_articles[f"noise_{idx}"].append(filtered_articles[idx])
else:
clustered_articles[label].append(filtered_articles[idx])
logging.info(f"Clustering complete. Found {len(clustered_articles)} clusters")
return clustered_articles
def is_valid_headline(title):
# Avoid headlines that are likely advertisements, video streams, or news bulletins
invalid_patterns = [
r"(?i)\bnews bulletin\b",
r"(?i)\bvideo:",
r"(?i)\bsports\b",
r"(?i)\watch on tv\b",
r"(?i)\bonline for free\b",
r"(?i)\bhow to watch\b",
r"(?i)\bathlete\b",
r"(?i)\bhow to get\b",
r"(?i)\bhints, answers\b",
r"(?i)\bcelebrity\b",
r"(?i)\bholiday\b",
r"(?i)\bhow to\b",
r"(?i)\bwatch live:",
r"(?i)\broundup:",
r"(?i)\bhurdle hints\b",
r"(?i)\bstreaming",
r"(?i)\bbest restaurants\b",
r"(?i)\bnow available\b",
r"(?i)\bin free\b",
r"(?i)\bcustomer\b",
r"(?i)\bvideo...\b",
r"(?i)\bmensware",
r"(?i)\bfashion",
r"(?i)\bpromo",
r"(?i)\btouchscreen",
r"(?i)\bblogging",
r"(?i)\btested and reviewed\b",
r"(?i)\bthe best\b",
r"(?i)\bbest movies\b",
r"(?i)\blower blood pressure\b",
r"(?i)\bshare the 1\b",
r"(?i)\bshare the one\b",
r"(?i)\bdegree",
r"(?i)\bmentorship",
r"(?i)\bhelp\b",
r"(?i)\blowest price\b",
r"(?i)\baseball\b",
r"(?i)\bfootball\b",
r"(?i)\basketball\b",
r"(?i)\depository\b",
r"(?i)\dividend\b",
r"(?i)\sneaker\b",
r"(?i)\bstar-studded\b",
r"(?i)\bwordle\b",
r"(?i)\bget the new\b",
r"(?i)\bpromo code\b",
r"(?i)\breview:\b",
r"(?i)\binnovation",
r"(?i)\bstormcast",
r"(?i)\bhas anyone ever\b",
r"(?i)\btoday:",
r"(?i)\bawesome",
r"(?i)\btop picks\b",
r"(?i)\bbest phones\b",
r"(?i)\bhoroscope:",
r"(?i)\bapple launches\b",
r"(?i)\bquick take:\b",
r"(?i)\banalysis",
r"(?i)\bcoupon",
r"(?i)\bsavings",
r"(?i)\bwebinar",
r"(?i)\bgrammy",
r"(?i)\bvideo",
r"(?i)\bReview:",
r"(?i)\bmorning read\b",
r"(?i)\bmy notes\b",
r"(?i)\bdownload:\b",
r"(?i)\bcheap",
r"(?i)\bmac",
r"(?i)\bearnings call:\b",
r"(?i)\best things\b",
r"(?i)\btoday:",
r"(?i)\bshopping season\b",
r"(?i)\bwhat to expect\b",
r"(?i)\bhints and answers\b",
r"(?i)\bprime day\b",
r"(?i)\bbrands\b",
r"(?i)\bfor free\b",
r"(?i)\bnominated",
r"(?i)\bwatch:",
r"(?i)\bclosing bell\b",
r"(?i)\bdaily discussion\b",
r"(?i)\bsigns of ageing\b",
r"(?i)\bvs\.\b",
r"(?i)\bv\.\b",
r"(?i)\bvs\b",
r"(?i)\bv\b",
r"(?i)\bleague\b",