File size: 11,007 Bytes
1a4d79b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import os
from dotenv import load_dotenv
from transformers import pipeline
import pandas as pd
from GoogleNews import GoogleNews
from langchain_openai import ChatOpenAI
import praw
from datetime import datetime
import numpy as np
from tavily import TavilyClient

load_dotenv()
TAVILY_API_KEY = os.environ["TAVILY_API_KEY"]

def fetch_news(topic):
    
    """ Fetches news articles within a specified date range.

    Args:
    - topic (str): Topic of interest
    
    Returns:
    - list: A list of dictionaries containing news. """
    
    load_dotenv()
    days_to_fetch_news = os.environ["DAYS_TO_FETCH_NEWS"]

    googlenews = GoogleNews()
    googlenews.set_period(days_to_fetch_news)
    googlenews.get_news(topic)
    news_json=googlenews.get_texts()
    urls=googlenews.get_links()
    
    no_of_news_articles_to_fetch = os.environ["NO_OF_NEWS_ARTICLES_TO_FETCH"]
    news_article_list = []
    counter = 0
    for article in news_json:
        
        if(counter >= int(no_of_news_articles_to_fetch)):
            break

        relevant_info = {
            'News_Article': article,
            'URL': urls[counter]
        }
        news_article_list.append(relevant_info)
        counter+=1
    return news_article_list

# def fetch_tavily_news(topic):
#     """ Fetches news articles.

#     Args:
#     - topic (str): Topic of interest
    
#     Returns:
#     - list: A list of dictionaries containing news. """
    
#     # Step 1. Instantiating your TavilyClient
#     tavily_client = TavilyClient(api_key=TAVILY_API_KEY)

#     #response = tavily_client.search(topic)
#     # Step 2.1. Executing a context search query
#     answer = tavily_client.get_search_context(query=f"Give me news on {topic}")
    
#     line=[]
#     tavily_news=[]

#     for i in range(len(answer.split("url")))[1:]:
#         https_link=(answer.split("url")[i].split("\\\\\\")[2]).split('"')[1]
#         topic_answer=answer.split("url")[i].split("\\\\\\")[-3]
#         tavily_news=np.append(tavily_news,{'https':https_link,'topic_answer':topic_answer})

#     return tavily_news

def fetch_tavily_news(prompt):
    try:
        # Assuming answer contains the Tavily API response
        # First, let's make the URL extraction more robust
        urls = []
        
        # Method 1: Using string manipulation with error handling
        try:
            parts = answer.split("url")
            for part in parts[1:]:  # Skip the first part before 'url'
                try:
                    # Try different splitting patterns
                    if '\\\\' in part:
                        url = part.split('\\\\')[2].split('"')[1]
                    elif '"' in part:
                        url = part.split('"')[1]
                    else:
                        continue
                    
                    if url.startswith('http'):  # Validate URL
                        urls.append(url)
                except (IndexError, AttributeError):
                    continue
        except Exception as e:
            print(f"Error extracting URLs: {e}")

        # If no URLs found, try alternative parsing
        if not urls:
            # Method 2: Try JSON parsing if the response is JSON formatted
            try:
                import json
                data = json.loads(answer)
                if isinstance(data, list):
                    for item in data:
                        if isinstance(item, dict) and 'url' in item:
                            urls.append(item['url'])
            except json.JSONDecodeError:
                pass

        # If still no URLs found, try regex
        if not urls:
            import re
            url_pattern = r'https?://[^\s<>"]+|www\.[^\s<>"]+|http?://[^\s<>"]+'
            urls = re.findall(url_pattern, answer)

        # Remove duplicates while preserving order
        urls = list(dict.fromkeys(urls))
        
        return urls

    except Exception as e:
        print(f"Error in fetch_tavily_news: {e}")
        return []  # Return empty list on error


def fetch_reddit_news(topic):
    load_dotenv()
    REDDIT_USER_AGENT= os.environ["REDDIT_USER_AGENT"]
    REDDIT_CLIENT_ID= os.environ["REDDIT_CLIENT_ID"]
    REDDIT_CLIENT_SECRET= os.environ["REDDIT_CLIENT_SECRET"]
    #https://medium.com/geekculture/a-complete-guide-to-web-scraping-reddit-with-python-16e292317a52
    user_agent = REDDIT_USER_AGENT
    reddit = praw.Reddit (
    client_id= REDDIT_CLIENT_ID,
    client_secret= REDDIT_CLIENT_SECRET,
    user_agent=user_agent
    )

    headlines = set ( )
    for submission in reddit.subreddit('nova').search(topic,time_filter='day'):
        headlines.add(submission.title + ', Date: ' +datetime.utcfromtimestamp(int(submission.created_utc)).strftime('%Y-%m-%d %H:%M:%S') + ', URL:' +submission.url)
    
    for submission in reddit.subreddit('fednews').search(topic,time_filter='day'):
        headlines.add(submission.title + ', Date: ' +datetime.utcfromtimestamp(int(submission.created_utc)).strftime('%Y-%m-%d %H:%M:%S') + ', URL:' +submission.url)

    for submission in reddit.subreddit('washingtondc').search(topic,time_filter='day'):
        headlines.add(submission.title + ', Date: ' +datetime.utcfromtimestamp(int(submission.created_utc)).strftime('%Y-%m-%d %H:%M:%S') + ', URL:' +submission.url)
    
    if len(headlines)<10:
       for submission in reddit.subreddit('washingtondc').search(topic,time_filter='year'):
           headlines.add(submission.title + ', Date: ' +datetime.utcfromtimestamp(int(submission.created_utc)).strftime('%Y-%m-%d %H:%M:%S') + ', URL:' +submission.url)
    if len(headlines)<10:
       for submission in reddit.subreddit('washingtondc').search(topic): #,time_filter='week'):
           headlines.add(submission.title + ', Date: ' +datetime.utcfromtimestamp(int(submission.created_utc)).strftime('%Y-%m-%d %H:%M:%S') + ', URL:' +submission.url)

    return headlines

def analyze_sentiment(article):
    """
    Analyzes the sentiment of a given news article.

    Args:
    - news_article (dict): Dictionary containing 'summary', 'headline', and 'created_at' keys.

    Returns:
    - dict: A dictionary containing sentiment analysis results.
    """

    #Analyze sentiment using default model
    #classifier = pipeline('sentiment-analysis')

    #Analyze sentiment using specific model
    classifier = pipeline(model='tabularisai/robust-sentiment-analysis') #mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis')
    sentiment_result = classifier(str(article))

    analysis_result = {
        'News_Article': article,
        'Sentiment': sentiment_result
    }

    return analysis_result


def generate_summary_of_sentiment(sentiment_analysis_results): #, dominant_sentiment):
    
    
    news_article_sentiment = str(sentiment_analysis_results)
    print("News article sentiment : " + news_article_sentiment)
    

    OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
    model = ChatOpenAI(
        model="gpt-4o",
        temperature=0,
        max_tokens=None,
        timeout=None,
        max_retries=2,
        api_key=OPENAI_API_KEY,  # if you prefer to pass api key in directly instaed of using env vars
        # base_url="...",
        # organization="...",
        # other params...
    )

    messages=[
            {"role": "system", "content": "You are a helpful assistant that looks at all news articles with their sentiment, hyperlink and date in front of the article text, the articles MUST be ordered by date!, and generate a summary rationalizing dominant sentiment. At the end of the summary, add URL links for all the articles in the markdown format for streamlit. Make sure the articles as well as the links are ordered descending by Date!!!!!!! Example of adding the URLs: The Check out the links: [link](%s) % url. "},
            {"role": "user", "content": f"News articles and their sentiments: {news_article_sentiment}"} #, and dominant sentiment is: {dominant_sentiment}"}
    ]
    response = model.invoke(messages)
    

    summary = response.content
    print ("+++++++++++++++++++++++++++++++++++++++++++++++")
    print(summary)
    print ("+++++++++++++++++++++++++++++++++++++++++++++++")
    return summary


def plot_sentiment_graph(sentiment_analysis_results):
    """
    Plots a sentiment analysis graph 

    Args:
    - sentiment_analysis_result): (dict): Dictionary containing 'Review Title : Summary', 'Rating', and 'Sentiment' keys.

    Returns:
    - dict: A dictionary containing sentiment analysis results.
    """
    df = pd.DataFrame(sentiment_analysis_results)
    #print(df)

    #Group by Rating, sentiment value count
    grouped = df['Sentiment'].value_counts()

    sentiment_counts = df['Sentiment'].value_counts()

    # Plotting pie chart
    # fig = plt.figure(figsize=(5, 3))
    # plt.pie(sentiment_counts, labels=sentiment_counts.index, autopct='%1.1f%%', startangle=140)
    # plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
    
    #Open below when u running this program locally and c
    #plt.show()

    return sentiment_counts


def get_dominant_sentiment (sentiment_analysis_results):
    """
    Returns overall sentiment, negative or positive or neutral depending on the count of negative sentiment vs positive sentiment 

    Args:
    - sentiment_analysis_result): (dict): Dictionary containing 'summary', 'headline', and 'created_at' keys.

    Returns:
    - dict: A dictionary containing sentiment analysis results.
    """
    df = pd.DataFrame(sentiment_analysis_results)

    # Group by the 'sentiment' column and count the occurrences of each sentiment value
    #print(df)
    #print(df['Sentiment'])
    sentiment_counts = df['Sentiment'].value_counts().reset_index()
    sentiment_counts.columns = ['sentiment', 'count']
    print(sentiment_counts)

    # Find the sentiment with the highest count
    dominant_sentiment = sentiment_counts.loc[sentiment_counts['count'].idxmax()]

    return dominant_sentiment['sentiment']

#starting point of the program
if __name__ == '__main__':
    
    #fetch news
    news_articles = fetch_news('AAPL')

    analysis_results = []
    
    #Perform sentiment analysis for each product review
    for article in news_articles:
        sentiment_analysis_result = analyze_sentiment(article['News_Article'])

        # Display sentiment analysis results
        print(f'News Article: {sentiment_analysis_result["News_Article"]} : Sentiment: {sentiment_analysis_result["Sentiment"]}', '\n')

        result = {
                    'News_Article': sentiment_analysis_result["News_Article"],
                    'Sentiment': sentiment_analysis_result["Sentiment"][0]['label']
                }
        
        analysis_results.append(result)

    
    #Graph dominant sentiment based on sentiment analysis data of reviews
    dominant_sentiment = get_dominant_sentiment(analysis_results)
    print(dominant_sentiment)
    
    #Plot graph
    plot_sentiment_graph(analysis_results)