Divyansh Kushwaha
commited on
Commit
·
d97cb07
1
Parent(s):
1b9de11
Utils file updated
Browse files
utils.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
from bs4 import BeautifulSoup
|
2 |
import requests
|
3 |
from langchain.schema import HumanMessage
|
@@ -7,11 +8,14 @@ from dotenv import load_dotenv
|
|
7 |
import os
|
8 |
from transformers import pipeline
|
9 |
|
|
|
10 |
load_dotenv()
|
11 |
GROQ_API_KEY = os.getenv('GROQ_API_KEY')
|
12 |
|
13 |
-
|
|
|
14 |
|
|
|
15 |
def extract_titles_and_summaries(company_name, num_articles=10):
|
16 |
url = f"https://economictimes.indiatimes.com/topic/{company_name}/news"
|
17 |
try:
|
@@ -48,10 +52,11 @@ def extract_titles_and_summaries(company_name, num_articles=10):
|
|
48 |
print(f"An error occurred: {e}")
|
49 |
return []
|
50 |
|
|
|
51 |
def perform_sentiment_analysis(news_data):
|
52 |
from transformers import pipeline
|
53 |
articles = news_data.get("Articles", [])
|
54 |
-
pipe = pipeline("text-classification", model="tabularisai/multilingual-sentiment-analysis",device=1)
|
55 |
sentiment_counts = {"Positive": 0, "Negative": 0, "Neutral": 0}
|
56 |
|
57 |
for article in articles:
|
@@ -77,13 +82,15 @@ def perform_sentiment_analysis(news_data):
|
|
77 |
|
78 |
return news_data, sentiment_counts
|
79 |
|
|
|
80 |
def extract_topics_with_hf(news_data):
|
81 |
structured_data = {
|
82 |
"Company": news_data.get("Company", "Unknown"),
|
83 |
"Articles": []
|
84 |
}
|
85 |
-
topic_pipe = pipeline("text-classification", model="valurank/distilroberta-topic-classification",device=1)
|
86 |
articles = news_data.get("Articles", [])
|
|
|
87 |
for article in articles:
|
88 |
content = f"{article['Title']} {article['Summary']}"
|
89 |
topics_result = topic_pipe(content, top_k=3)
|
@@ -98,10 +105,12 @@ def extract_topics_with_hf(news_data):
|
|
98 |
})
|
99 |
return structured_data
|
100 |
|
|
|
101 |
def generate_final_sentiment(news_data, sentiment_counts):
|
102 |
company_name = news_data["Company"]
|
103 |
total_articles = sum(sentiment_counts.values())
|
104 |
combined_summaries = " ".join([article["Summary"] for article in news_data["Articles"]])
|
|
|
105 |
prompt = f"""
|
106 |
Based on the analysis of {total_articles} articles about the company "{company_name}":
|
107 |
- Positive articles: {sentiment_counts['Positive']}
|
@@ -109,22 +118,26 @@ def generate_final_sentiment(news_data, sentiment_counts):
|
|
109 |
- Neutral articles: {sentiment_counts['Neutral']}
|
110 |
The following are the summarized key points from the articles: "{combined_summaries}".
|
111 |
Provide a single, concise summary that integrates the overall sentiment analysis and key news highlights while maintaining a natural flow. Explain its implications for the company's reputation, stock potential, and public perception.
|
112 |
-
Respond **ONLY** with a well-structured very
|
113 |
"""
|
114 |
-
|
|
|
115 |
final_sentiment = response if response else "Sentiment analysis summary not available."
|
116 |
-
return final_sentiment.content
|
117 |
|
|
|
118 |
def extract_json(response):
|
119 |
try:
|
120 |
return json.loads(response)
|
121 |
except json.JSONDecodeError:
|
122 |
return {}
|
123 |
-
|
|
|
124 |
def compare_articles(news_data, sentiment_counts):
|
125 |
articles = news_data.get("Articles", [])
|
126 |
all_topics = [set(article["Topics"]) for article in articles]
|
127 |
common_topics = set.intersection(*all_topics) if all_topics else set()
|
|
|
128 |
topics_prompt = f"""
|
129 |
Analyze the following article topics and identify **only three** key themes that are common across multiple articles,
|
130 |
even if they are phrased differently. The topics from each article are:
|
@@ -133,10 +146,12 @@ def compare_articles(news_data, sentiment_counts):
|
|
133 |
Respond **ONLY** with a JSON format:
|
134 |
{{"CommonTopics": ["topic1", "topic2", "topic3"]}}
|
135 |
"""
|
|
|
136 |
response = llm.invoke([HumanMessage(content=topics_prompt)]).content
|
137 |
contextual_common_topics = extract_json(response).get("CommonTopics", list(common_topics))[:3] # Limit to 3 topics
|
138 |
|
139 |
total_articles = sum(sentiment_counts.values())
|
|
|
140 |
comparison_prompt = f"""
|
141 |
Provide a high-level summary comparing {total_articles} news articles about "{news_data['Company']}":
|
142 |
- Sentiment distribution: {sentiment_counts}
|
@@ -155,9 +170,12 @@ def compare_articles(news_data, sentiment_counts):
|
|
155 |
]
|
156 |
}}
|
157 |
"""
|
|
|
158 |
response = llm.invoke([HumanMessage(content=comparison_prompt)]).content
|
159 |
coverage_differences = extract_json(response).get("Coverage Differences", [])
|
|
|
160 |
final_sentiment = generate_final_sentiment(news_data, sentiment_counts)
|
|
|
161 |
return {
|
162 |
"Company": news_data["Company"],
|
163 |
"Articles": articles,
|
@@ -173,4 +191,4 @@ def compare_articles(news_data, sentiment_counts):
|
|
173 |
}
|
174 |
},
|
175 |
"Final Sentiment Analysis": final_sentiment
|
176 |
-
}
|
|
|
1 |
+
# Importing libraries
|
2 |
from bs4 import BeautifulSoup
|
3 |
import requests
|
4 |
from langchain.schema import HumanMessage
|
|
|
8 |
import os
|
9 |
from transformers import pipeline
|
10 |
|
11 |
+
# Load environment variables
|
12 |
load_dotenv()
|
13 |
GROQ_API_KEY = os.getenv('GROQ_API_KEY')
|
14 |
|
15 |
+
# Initialize the LLM model
|
16 |
+
llm = ChatGroq(api_key=GROQ_API_KEY, model="llama-3.1-8b-instant")
|
17 |
|
18 |
+
# Function to extract news titles and summaries from Economic Times
|
19 |
def extract_titles_and_summaries(company_name, num_articles=10):
|
20 |
url = f"https://economictimes.indiatimes.com/topic/{company_name}/news"
|
21 |
try:
|
|
|
52 |
print(f"An error occurred: {e}")
|
53 |
return []
|
54 |
|
55 |
+
# Function to perform sentiment analysis on extracted news articles
|
56 |
def perform_sentiment_analysis(news_data):
|
57 |
from transformers import pipeline
|
58 |
articles = news_data.get("Articles", [])
|
59 |
+
pipe = pipeline("text-classification", model="tabularisai/multilingual-sentiment-analysis", device=1)
|
60 |
sentiment_counts = {"Positive": 0, "Negative": 0, "Neutral": 0}
|
61 |
|
62 |
for article in articles:
|
|
|
82 |
|
83 |
return news_data, sentiment_counts
|
84 |
|
85 |
+
# Function to extract topics from articles using Hugging Face model
|
86 |
def extract_topics_with_hf(news_data):
|
87 |
structured_data = {
|
88 |
"Company": news_data.get("Company", "Unknown"),
|
89 |
"Articles": []
|
90 |
}
|
91 |
+
topic_pipe = pipeline("text-classification", model="valurank/distilroberta-topic-classification", device=1)
|
92 |
articles = news_data.get("Articles", [])
|
93 |
+
|
94 |
for article in articles:
|
95 |
content = f"{article['Title']} {article['Summary']}"
|
96 |
topics_result = topic_pipe(content, top_k=3)
|
|
|
105 |
})
|
106 |
return structured_data
|
107 |
|
108 |
+
# Function to generate a final sentiment summary using LLM
|
109 |
def generate_final_sentiment(news_data, sentiment_counts):
|
110 |
company_name = news_data["Company"]
|
111 |
total_articles = sum(sentiment_counts.values())
|
112 |
combined_summaries = " ".join([article["Summary"] for article in news_data["Articles"]])
|
113 |
+
|
114 |
prompt = f"""
|
115 |
Based on the analysis of {total_articles} articles about the company "{company_name}":
|
116 |
- Positive articles: {sentiment_counts['Positive']}
|
|
|
118 |
- Neutral articles: {sentiment_counts['Neutral']}
|
119 |
The following are the summarized key points from the articles: "{combined_summaries}".
|
120 |
Provide a single, concise summary that integrates the overall sentiment analysis and key news highlights while maintaining a natural flow. Explain its implications for the company's reputation, stock potential, and public perception.
|
121 |
+
Respond **ONLY** with a well-structured very concise and short paragraph in plain text, focusing on overall sentiment.
|
122 |
"""
|
123 |
+
|
124 |
+
response = llm.invoke([HumanMessage(content=prompt)], max_tokens=200)
|
125 |
final_sentiment = response if response else "Sentiment analysis summary not available."
|
126 |
+
return final_sentiment.content # returns a string
|
127 |
|
128 |
+
# Function to extract JSON response from LLM output
|
129 |
def extract_json(response):
|
130 |
try:
|
131 |
return json.loads(response)
|
132 |
except json.JSONDecodeError:
|
133 |
return {}
|
134 |
+
|
135 |
+
# Function to compare articles based on common topics and sentiment variations
|
136 |
def compare_articles(news_data, sentiment_counts):
|
137 |
articles = news_data.get("Articles", [])
|
138 |
all_topics = [set(article["Topics"]) for article in articles]
|
139 |
common_topics = set.intersection(*all_topics) if all_topics else set()
|
140 |
+
|
141 |
topics_prompt = f"""
|
142 |
Analyze the following article topics and identify **only three** key themes that are common across multiple articles,
|
143 |
even if they are phrased differently. The topics from each article are:
|
|
|
146 |
Respond **ONLY** with a JSON format:
|
147 |
{{"CommonTopics": ["topic1", "topic2", "topic3"]}}
|
148 |
"""
|
149 |
+
|
150 |
response = llm.invoke([HumanMessage(content=topics_prompt)]).content
|
151 |
contextual_common_topics = extract_json(response).get("CommonTopics", list(common_topics))[:3] # Limit to 3 topics
|
152 |
|
153 |
total_articles = sum(sentiment_counts.values())
|
154 |
+
|
155 |
comparison_prompt = f"""
|
156 |
Provide a high-level summary comparing {total_articles} news articles about "{news_data['Company']}":
|
157 |
- Sentiment distribution: {sentiment_counts}
|
|
|
170 |
]
|
171 |
}}
|
172 |
"""
|
173 |
+
|
174 |
response = llm.invoke([HumanMessage(content=comparison_prompt)]).content
|
175 |
coverage_differences = extract_json(response).get("Coverage Differences", [])
|
176 |
+
|
177 |
final_sentiment = generate_final_sentiment(news_data, sentiment_counts)
|
178 |
+
|
179 |
return {
|
180 |
"Company": news_data["Company"],
|
181 |
"Articles": articles,
|
|
|
191 |
}
|
192 |
},
|
193 |
"Final Sentiment Analysis": final_sentiment
|
194 |
+
}
|