JayLacoma's picture
Update app.py
d1388f2 verified
raw
history blame
2.75 kB
import torch
import numpy as np
import pandas as pd
from datetime import datetime
from newsapi import NewsApiClient
from transformers import pipeline
import plotly.graph_objects as go
import gradio as gr
# Initialize News API client with your API key
newsapi = NewsApiClient(api_key='381793b3d6834758918838bca0cf52ee')
# Define sentiment analyzer using FinBERT
sentiment_analyzer = pipeline("text-classification", model="ProsusAI/finbert")
# Function to fetch news, analyze sentiment, and create an interactive Plotly plot
def analyze_news_sentiment(company_name):
# Fetch news articles related to the company
news = newsapi.get_everything(q=company_name, language='en', sort_by='publishedAt')
# Extract headlines from news articles
headlines = [article['title'] for article in news['articles']]
# Perform sentiment analysis on the headlines
result = sentiment_analyzer(headlines)
df = pd.DataFrame(result)
# Map labels to numeric values
label_mapping = {'positive': 1, 'neutral': 0, 'negative': -1}
df['sentiment'] = df['label'].map(label_mapping)
# Drop the 'label' column
df.drop(columns=['label'], inplace=True)
# Filter out neutral sentiment values
positive_sentiment = df[df['sentiment'] == 1]['sentiment']
negative_sentiment = df[df['sentiment'] == -1]['sentiment']
# Create the interactive Plotly histogram
fig = go.Figure()
# Add Positive sentiment histogram
fig.add_trace(go.Histogram(
x=positive_sentiment,
nbinsx=1,
name='Positive',
marker_color='purple',
opacity=0.75
))
# Add Negative sentiment histogram
fig.add_trace(go.Histogram(
x=negative_sentiment,
nbinsx=1,
name='Negative',
marker_color='skyblue',
opacity=0.75
))
# Update layout for better visualization
fig.update_layout(
title=f'Sentiment Distribution for {company_name}',
xaxis_title='Sentiment',
yaxis_title='Count',
barmode='overlay',
plot_bgcolor='black',
paper_bgcolor='black',
font=dict(color='white'),
xaxis=dict(tickvals=[-1, 1], ticktext=['Negative', 'Positive']),
bargap=0.2,
)
return fig
# %%
# Create a Gradio interface
interface = gr.Interface(
fn=analyze_news_sentiment, # Function to run
inputs=gr.Textbox(label="Enter Company Name"), # Input: company name
outputs=gr.Plot(label="Sentiment Distribution"), # Output: Interactive Plotly chart
title="Sentiment Analysis on News Headlines",
description="Enter a company name to analyze the sentiment of the latest news related to that company."
)
# Launch the Gradio app
interface.launch()