Spaces:
Sleeping
Sleeping
import streamlit as st | |
import nltk | |
import spacy | |
import matplotlib.pyplot as plt | |
from transformers import pipeline | |
import random | |
import subprocess | |
# Ensure spaCy model is installed | |
try: | |
nlp = spacy.load("en_core_web_sm") | |
except OSError: | |
subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"]) | |
nlp = spacy.load("en_core_web_sm") | |
# Ensure NLTK resources are available | |
nltk.download("vader_lexicon") | |
from nltk.sentiment import SentimentIntensityAnalyzer | |
sia = SentimentIntensityAnalyzer() | |
# Load English emotion detection pipeline | |
emotion_pipeline = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True) | |
# Load a better multilingual sentiment analysis model | |
multilingual_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-xlm-roberta-base-sentiment") | |
# Sample texts | |
sample_texts = [ | |
"The digital world is transforming the way we read and engage with text.", | |
"Reading is an essential skill that shapes our understanding of the world.", | |
"AI-driven education tools can personalize the learning experience for students." | |
] | |
# Supported languages for multilingual sentiment analysis | |
supported_languages = { | |
"English": "en", | |
"Dutch": "nl", | |
"French": "fr", | |
"German": "de" | |
} | |
# Streamlit UI | |
st.title("π AI-Powered Adaptive Reading Engagement") | |
st.write("Analyze how users engage with digital reading using AI-powered insights.") | |
# Language selection | |
selected_language = st.selectbox("Select a language:", list(supported_languages.keys())) | |
# Use session state to store text input | |
if "user_text" not in st.session_state: | |
st.session_state.user_text = "" | |
# Dropdown menu with a new option for "Choose Your Own Text" | |
text_option = st.selectbox("Choose a sample text or enter your own:", ["Choose Your Own Text"] + sample_texts) | |
# Text input limit | |
MAX_WORDS = 100 # Set the max word limit | |
# If user selects a sample text, use it. Otherwise, allow manual input. | |
if text_option == "Choose Your Own Text": | |
text = st.text_area("Enter your own text:", st.session_state.user_text, height=150) | |
else: | |
text = sample_texts[sample_texts.index(text_option)] # Select the chosen sample text | |
# Show word count & limit warning only if the user is entering their own text | |
word_count = len(text.split()) | |
if text_option == "Choose Your Own Text": | |
st.markdown(f'<p style="font-size:12px; color:gray;">β οΈ Limit: {MAX_WORDS} words max.</p>', unsafe_allow_html=True) | |
if word_count > MAX_WORDS: | |
st.warning(f"β οΈ Your input has {word_count} words. Please limit it to {MAX_WORDS} words.") | |
# Save user input in session state only if within limit | |
if text_option == "Choose Your Own Text" and word_count <= MAX_WORDS: | |
st.session_state.user_text = text | |
# Function to generate AI-driven feedback | |
def generate_feedback(sentiment_score, top_emotion): | |
if sentiment_score['pos'] > 0.6: | |
return "π Your reading is positive! This text might boost engagement and motivation." | |
elif sentiment_score['neg'] > 0.6: | |
return "π The text seems to have a strong negative tone. Consider balancing it with positive information." | |
elif top_emotion in ["anger", "disgust"]: | |
return "π‘ This text might evoke strong emotions. Reflect on how it makes you feel and why." | |
elif top_emotion in ["joy", "optimism"]: | |
return "π This is an engaging and uplifting text. Keep exploring such content!" | |
else: | |
return "π€ The text is neutral. You might want to explore different perspectives." | |
# Sentiment Analysis | |
if st.button("Analyze Engagement"): | |
if text and (text_option != "Choose Your Own Text" or word_count <= MAX_WORDS): | |
# Sentiment Analysis | |
sentiment_score = sia.polarity_scores(text) | |
# Emotion Detection | |
if selected_language == "English": | |
emotion_results = emotion_pipeline(text) | |
top_emotion = max(emotion_results[0], key=lambda x: x['score'])['label'] | |
emotion_scores = {e['label']: e['score'] for e in emotion_results[0]} | |
else: | |
# Multilingual Sentiment Analysis | |
multilingual_results = multilingual_pipeline(text) | |
top_emotion = multilingual_results[0]["label"] | |
emotion_scores = {top_emotion: multilingual_results[0]["score"]} | |
# Display Sentiment | |
st.subheader("π Sentiment Analysis") | |
st.write(f"Positive: {sentiment_score['pos'] * 100:.2f}%, Negative: {sentiment_score['neg'] * 100:.2f}%, Neutral: {sentiment_score['neu'] * 100:.2f}%") | |
# Display Emotion | |
st.subheader("π Emotion Detection") | |
st.write(f"Top Emotion: **{top_emotion.capitalize()}**") | |
# Display Multiple Emotion Scores | |
st.subheader("π Expanded Emotion Insights") | |
for emotion, score in emotion_scores.items(): | |
st.write(f"**{emotion.capitalize()}**: {score:.2f}") | |
# AI-Generated Feedback | |
st.subheader("π‘ AI-Generated Feedback") | |
feedback = generate_feedback(sentiment_score, top_emotion) | |
st.write(feedback) | |
# Visualization | |
fig, ax = plt.subplots() | |
ax.bar(emotion_scores.keys(), emotion_scores.values()) | |
st.pyplot(fig) | |
elif text_option == "Choose Your Own Text" and word_count > MAX_WORDS: | |
st.warning("β οΈ Please reduce the text length to analyze.") | |
else: | |
st.warning("β οΈ Please enter a text to analyze.") |