File size: 2,157 Bytes
a70e249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1376e8
a70e249
0e3156c
f1376e8
0e3156c
9e49297
a70e249
f1376e8
0e3156c
a70e249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from google.cloud import language_v1
from google.oauth2 import service_account
import json

# Load credentials from Hugging Face Secrets
def load_credentials():
    credentials_info = json.loads(st.secrets["GOOGLE_APPLICATION_CREDENTIALS"])
    return service_account.Credentials.from_service_account_info(credentials_info)

# Create a Language Service client with the provided credentials
def get_language_client():
    credentials = load_credentials()
    return language_v1.LanguageServiceClient(credentials=credentials)

# Perform sentiment analysis on the input text
def analyze_sentiment(texts):
    client = get_language_client()
    document = language_v1.Document(content=texts, type_=language_v1.Document.Type.PLAIN_TEXT)
    return client.analyze_sentiment(request={"document": document})

# Display sentiment analysis results
def display_sentiment_results(annotations):
    score = annotations.document_sentiment.score
    magnitude = annotations.document_sentiment.magnitude

    # Loop through the sentences and display sentiment score with 2 decimal places
    for index, sentence in enumerate(annotations.sentences):
        sentence_sentiment = sentence.sentiment.score  # Only extract sentiment score
        sentence_text = sentence.text.content  # Get the text of the sentence
        st.write(f"Sentence {index} sentiment score: {sentence_sentiment:.2f}")  # Removed sentence magnitude
        st.write(f"Sentence {index}: {sentence_text}")  # Display the text of the sentence

    # Display overall sentiment with 2 decimal places
    st.write(f"Overall Sentiment: score of {score:.2f} with magnitude of {magnitude:.2f}")

# Main function to run the app
def main():
    st.title("Sentiment Analysis App")
    st.write("Enter some text to analyze its sentiment:")

    text_input = st.text_area("Text to analyze", height=200)

    if st.button("Analyze Sentiment"):
        if text_input:
            annotations = analyze_sentiment(text_input)
            display_sentiment_results(annotations)
        else:
            st.warning("Please enter some text.")

# Run the app
if __name__ == "__main__":
    main()