Durganihantri's picture
Update app.py
236bb3e verified
raw
history blame
3.47 kB
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")
# Load NLP models
nltk.download("vader_lexicon")
from nltk.sentiment import SentimentIntensityAnalyzer
sia = SentimentIntensityAnalyzer()
emotion_pipeline = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True)
# 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."
]
# Streamlit UI
st.title("πŸ“– AI-Powered Adaptive Reading Engagement")
st.write("Analyze how users engage with digital reading using AI-powered insights.")
# 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
# Sentiment Analysis
if st.button("Analyze Engagement"):
if text and (text_option != "Choose Your Own Text" or word_count <= MAX_WORDS):
sentiment_score = sia.polarity_scores(text)
emotion_results = emotion_pipeline(text)
# 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")
top_emotion = max(emotion_results[0], key=lambda x: x['score'])
st.write(f"Detected Emotion: **{top_emotion['label']}** (Confidence: {top_emotion['score']:.2f})")
# Visualization
labels = [e['label'] for e in emotion_results[0]]
scores = [e['score'] for e in emotion_results[0]]
fig, ax = plt.subplots()
ax.bar(labels, scores)
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.")