import streamlit as st from google.cloud import language_v1 from google.oauth2 import service_account import json # Load Google Cloud credentials credentials = service_account.Credentials.from_service_account_file(json.loads(st.secrets["GOOGLE_APPLICATION_CREDENTIALS"])) def print_result(annotations): # Overall Sentiment score = annotations.document_sentiment.score magnitude = annotations.document_sentiment.magnitude st.write("**Overall Sentiment:**") st.write(f" * Score: {score}") st.write(f" * Magnitude: {magnitude}") # Sentence-Level Sentiment st.write("**Sentence-Level Sentiment:**") for index, sentence in enumerate(annotations.sentences): sentence_text = sentence.text.content sentence_sentiment = sentence.sentiment.score st.write(f"Sentence {index}: {sentence_text}") st.write(f" * Sentiment score: {sentence_sentiment}") # Entity-Level Sentiment (If Applicable) if annotations.entities: st.write("**Entity-Level Sentiment:**") for entity in annotations.entities: st.write(f"Entity: {entity.name} ({entity.type})") st.write(f" * Sentiment Score: {entity.sentiment.score}") st.write(f" * Magnitude: {entity.sentiment.magnitude}") st.write(f" * Salience: {entity.salience}") def analyze_sentiment(texts, credentials): client = language_v1.LanguageServiceClient(credentials=credentials) # Include options for entity analysis document = language_v1.Document(content=texts, type_=language_v1.Document.Type.PLAIN_TEXT) annotations = client.analyze_sentiment(request={"document": document}) return annotations 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, credentials) print_result(annotations) else: st.warning("Please enter some text.")