Durganihantri commited on
Commit
e1881c6
Β·
verified Β·
1 Parent(s): 236bb3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -8
app.py CHANGED
@@ -2,9 +2,10 @@ import streamlit as st
2
  import nltk
3
  import spacy
4
  import matplotlib.pyplot as plt
5
- from transformers import pipeline
6
  import random
7
  import subprocess
 
8
 
9
  # Ensure spaCy model is installed
10
  try:
@@ -13,11 +14,17 @@ except OSError:
13
  subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"])
14
  nlp = spacy.load("en_core_web_sm")
15
 
16
- # Load NLP models
17
  nltk.download("vader_lexicon")
18
  from nltk.sentiment import SentimentIntensityAnalyzer
19
  sia = SentimentIntensityAnalyzer()
20
 
 
 
 
 
 
 
21
  emotion_pipeline = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True)
22
 
23
  # Sample texts
@@ -27,10 +34,21 @@ sample_texts = [
27
  "AI-driven education tools can personalize the learning experience for students."
28
  ]
29
 
 
 
 
 
 
 
 
 
30
  # Streamlit UI
31
  st.title("πŸ“– AI-Powered Adaptive Reading Engagement")
32
  st.write("Analyze how users engage with digital reading using AI-powered insights.")
33
 
 
 
 
34
  # Use session state to store text input
35
  if "user_text" not in st.session_state:
36
  st.session_state.user_text = ""
@@ -59,11 +77,40 @@ if text_option == "Choose Your Own Text":
59
  if text_option == "Choose Your Own Text" and word_count <= MAX_WORDS:
60
  st.session_state.user_text = text
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  # Sentiment Analysis
63
  if st.button("Analyze Engagement"):
64
  if text and (text_option != "Choose Your Own Text" or word_count <= MAX_WORDS):
 
65
  sentiment_score = sia.polarity_scores(text)
66
- emotion_results = emotion_pipeline(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  # Display Sentiment
69
  st.subheader("πŸ“Š Sentiment Analysis")
@@ -71,14 +118,21 @@ if st.button("Analyze Engagement"):
71
 
72
  # Display Emotion
73
  st.subheader("🎭 Emotion Detection")
74
- top_emotion = max(emotion_results[0], key=lambda x: x['score'])
75
- st.write(f"Detected Emotion: **{top_emotion['label']}** (Confidence: {top_emotion['score']:.2f})")
 
 
 
 
 
 
 
 
 
76
 
77
  # Visualization
78
- labels = [e['label'] for e in emotion_results[0]]
79
- scores = [e['score'] for e in emotion_results[0]]
80
  fig, ax = plt.subplots()
81
- ax.bar(labels, scores)
82
  st.pyplot(fig)
83
  elif text_option == "Choose Your Own Text" and word_count > MAX_WORDS:
84
  st.warning("⚠️ Please reduce the text length to analyze.")
 
2
  import nltk
3
  import spacy
4
  import matplotlib.pyplot as plt
5
+ from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
6
  import random
7
  import subprocess
8
+ import torch
9
 
10
  # Ensure spaCy model is installed
11
  try:
 
14
  subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"])
15
  nlp = spacy.load("en_core_web_sm")
16
 
17
+ # Ensure NLTK resources are available
18
  nltk.download("vader_lexicon")
19
  from nltk.sentiment import SentimentIntensityAnalyzer
20
  sia = SentimentIntensityAnalyzer()
21
 
22
+ # Load multilingual emotion detection model
23
+ model_name = "joeddav/xlm-roberta-large-xnli"
24
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
25
+ emotion_model = AutoModelForSequenceClassification.from_pretrained(model_name)
26
+
27
+ # Load English emotion detection pipeline
28
  emotion_pipeline = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True)
29
 
30
  # Sample texts
 
34
  "AI-driven education tools can personalize the learning experience for students."
35
  ]
36
 
37
+ # Supported languages for multilingual sentiment analysis
38
+ supported_languages = {
39
+ "English": "en",
40
+ "Dutch": "nl",
41
+ "French": "fr",
42
+ "German": "de"
43
+ }
44
+
45
  # Streamlit UI
46
  st.title("πŸ“– AI-Powered Adaptive Reading Engagement")
47
  st.write("Analyze how users engage with digital reading using AI-powered insights.")
48
 
49
+ # Language selection
50
+ selected_language = st.selectbox("Select a language:", list(supported_languages.keys()))
51
+
52
  # Use session state to store text input
53
  if "user_text" not in st.session_state:
54
  st.session_state.user_text = ""
 
77
  if text_option == "Choose Your Own Text" and word_count <= MAX_WORDS:
78
  st.session_state.user_text = text
79
 
80
+ # Function to generate AI-driven feedback
81
+ def generate_feedback(sentiment_score, top_emotion):
82
+ if sentiment_score['pos'] > 0.6:
83
+ return "😊 Your reading is positive! This text might boost engagement and motivation."
84
+ elif sentiment_score['neg'] > 0.6:
85
+ return "πŸ˜” The text seems to have a strong negative tone. Consider balancing it with positive information."
86
+ elif top_emotion in ["anger", "disgust"]:
87
+ return "😑 This text might evoke strong emotions. Reflect on how it makes you feel and why."
88
+ elif top_emotion in ["joy", "optimism"]:
89
+ return "πŸŽ‰ This is an engaging and uplifting text. Keep exploring such content!"
90
+ else:
91
+ return "πŸ€” The text is neutral. You might want to explore different perspectives."
92
+
93
  # Sentiment Analysis
94
  if st.button("Analyze Engagement"):
95
  if text and (text_option != "Choose Your Own Text" or word_count <= MAX_WORDS):
96
+ # Sentiment Analysis
97
  sentiment_score = sia.polarity_scores(text)
98
+
99
+ # English Emotion Detection
100
+ if selected_language == "English":
101
+ emotion_results = emotion_pipeline(text)
102
+ top_emotion = max(emotion_results[0], key=lambda x: x['score'])['label']
103
+ emotion_scores = {e['label']: e['score'] for e in emotion_results[0]}
104
+ else:
105
+ # Multilingual Sentiment Analysis
106
+ inputs = tokenizer(text, return_tensors="pt", truncation=True)
107
+ with torch.no_grad():
108
+ outputs = emotion_model(**inputs)
109
+ probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
110
+ top_emotion_idx = torch.argmax(probabilities).item()
111
+ emotion_labels = ["neutral", "entailment", "contradiction"]
112
+ top_emotion = emotion_labels[top_emotion_idx]
113
+ emotion_scores = {top_emotion: probabilities[0][top_emotion_idx].item()}
114
 
115
  # Display Sentiment
116
  st.subheader("πŸ“Š Sentiment Analysis")
 
118
 
119
  # Display Emotion
120
  st.subheader("🎭 Emotion Detection")
121
+ st.write(f"Top Emotion: **{top_emotion.capitalize()}**")
122
+
123
+ # Display Multiple Emotion Scores
124
+ st.subheader("πŸ” Expanded Emotion Insights")
125
+ for emotion, score in emotion_scores.items():
126
+ st.write(f"**{emotion.capitalize()}**: {score:.2f}")
127
+
128
+ # AI-Generated Feedback
129
+ st.subheader("πŸ’‘ AI-Generated Feedback")
130
+ feedback = generate_feedback(sentiment_score, top_emotion)
131
+ st.write(feedback)
132
 
133
  # Visualization
 
 
134
  fig, ax = plt.subplots()
135
+ ax.bar(emotion_scores.keys(), emotion_scores.values())
136
  st.pyplot(fig)
137
  elif text_option == "Choose Your Own Text" and word_count > MAX_WORDS:
138
  st.warning("⚠️ Please reduce the text length to analyze.")