File size: 2,942 Bytes
6d2354e
 
 
f5c9839
6d2354e
 
 
4f76b9d
 
f5c9839
4f76b9d
f5c9839
 
 
6d2354e
4f76b9d
6d2354e
 
 
 
 
 
f5c9839
 
c6b8ea5
 
4f76b9d
f5c9839
 
4f76b9d
 
 
 
 
 
 
 
 
c6b8ea5
4f76b9d
 
 
 
 
 
 
 
 
f5c9839
4f76b9d
6d2354e
4f76b9d
f5c9839
4f76b9d
f5c9839
 
 
 
6d2354e
4f76b9d
 
 
 
 
 
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
import streamlit as st
from transformers import AutoTokenizer, AutoModelForSequenceClassification

model_name = "mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

# Seting the page title
st.title("Financial Sentiment Analysis")

# Adding a text input for the user to input financial news
text_input = st.text_area("Enter Financial News:", "Tesla stock is soaring after record-breaking earnings.")

# Function to perform sentiment analysis
def predict_sentiment(text):
    inputs = tokenizer(text, return_tensors="pt", max_length=1022, truncation=True)
    outputs = model(**inputs)
    sentiment_class = outputs.logits.argmax(dim=1).item()
    sentiment_mapping = {0: 'Negative', 1: 'Neutral', 2: 'Positive'}
    predicted_sentiment = sentiment_mapping.get(sentiment_class, 'Unknown')
    return predicted_sentiment

# Button to trigger sentiment analysis
if st.button("Analyze Sentiment"):
    # Checking if the input text is not empty
    if text_input and text_input.strip():  # Checking if input is not empty or contains only whitespaces
        # Showing loading spinner while processing
        with st.spinner("Analyzing sentiment..."):
            sentiment = predict_sentiment(text_input)

            # Extracting confidence scores
            inputs = tokenizer(text_input, return_tensors="pt")
            outputs = model(**inputs)
            confidence_scores = outputs.logits.softmax(dim=1)[0].tolist()

            # Considering a threshold for sentiment prediction
            threshold = 0.5

            # Changing the success message background color based on sentiment and threshold
            if sentiment == 'Positive' and confidence_scores[2] > threshold:
                st.success(f"Sentiment: {sentiment} (Confidence: {confidence_scores[2]:.3f})")
            elif sentiment == 'Negative' and confidence_scores[0] > threshold:
                st.error(f"Sentiment: {sentiment} (Confidence: {confidence_scores[0]:.3f})")
            elif sentiment == 'Neutral' and confidence_scores[1] > threshold:
                st.info(f"Sentiment: {sentiment} (Confidence: {confidence_scores[1]:.3f})")
            else:
                st.warning("Low confidence, or sentiment not above threshold. Please try again.")

    else:
        st.warning("Please enter some valid text for sentiment analysis.")

# Optional: Displaying the raw sentiment scores
if st.checkbox("Show Raw Sentiment Scores"):
    if text_input and text_input.strip():
        inputs = tokenizer(text_input, return_tensors="pt")
        outputs = model(**inputs)
        raw_scores = outputs.logits[0].tolist()
        st.info(f"Raw Sentiment Scores: {raw_scores}")

# footer
st.markdown(
    """
    **Built with [Streamlit](https://streamlit.io/) and [Transformers](https://huggingface.co/models).**
    """
)