Pranav0111 commited on
Commit
6c88285
β€’
1 Parent(s): 041fea2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -0
app.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+ import plotly.graph_objects as go
5
+
6
+ # Page config
7
+ st.set_page_config(
8
+ page_title="Emotion Detector",
9
+ page_icon="πŸ“Š",
10
+ layout="wide"
11
+ )
12
+
13
+ @st.cache_resource
14
+ def load_model():
15
+ tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
16
+ model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
17
+ return tokenizer, model
18
+
19
+ def analyze_text(text, tokenizer, model):
20
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
21
+ outputs = model(**inputs)
22
+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
23
+ return probs[0].detach().numpy()
24
+
25
+ def create_emotion_plot(emotions_dict):
26
+ fig = go.Figure(data=[
27
+ go.Bar(
28
+ x=list(emotions_dict.keys()),
29
+ y=list(emotions_dict.values()),
30
+ marker_color=['#FF9999', '#99FF99', '#9999FF', '#FFFF99', '#FF99FF', '#99FFFF', '#FFB366']
31
+ )
32
+ ])
33
+
34
+ fig.update_layout(
35
+ title="Emotion Analysis Results",
36
+ xaxis_title="Emotions",
37
+ yaxis_title="Confidence Score",
38
+ yaxis_range=[0, 1]
39
+ )
40
+ return fig
41
+
42
+ # App title and description
43
+ st.title("πŸ“Š Text Emotion Analysis")
44
+ st.markdown("""
45
+ This app analyzes the emotional content of your text using a pre-trained emotion detection model.
46
+ Try typing or pasting some text below!
47
+ """)
48
+
49
+ # Load model
50
+ with st.spinner("Loading model..."):
51
+ tokenizer, model = load_model()
52
+
53
+ # Define emotions
54
+ emotions = ['anger', 'disgust', 'fear', 'joy', 'neutral', 'sadness', 'surprise']
55
+
56
+ # Text input
57
+ text_input = st.text_area("Enter your text here:", height=150)
58
+
59
+ # Add example button
60
+ if st.button("Try an example"):
61
+ text_input = "I just got the best news ever! I'm so excited and happy I can hardly contain myself! πŸŽ‰"
62
+ st.text_area("Enter your text here:", value=text_input, height=150)
63
+
64
+ if st.button("Analyze Emotions"):
65
+ if text_input.strip() == "":
66
+ st.warning("Please enter some text to analyze.")
67
+ else:
68
+ with st.spinner("Analyzing emotions..."):
69
+ # Get predictions
70
+ probs = analyze_text(text_input, tokenizer, model)
71
+ emotions_dict = dict(zip(emotions, probs))
72
+
73
+ # Display results
74
+ st.subheader("Analysis Results")
75
+
76
+ # Create columns for layout
77
+ col1, col2 = st.columns([2, 1])
78
+
79
+ with col1:
80
+ # Display plot
81
+ fig = create_emotion_plot(emotions_dict)
82
+ st.plotly_chart(fig, use_container_width=True)
83
+
84
+ with col2:
85
+ # Display scores
86
+ st.subheader("Emotion Scores:")
87
+ for emotion, score in emotions_dict.items():
88
+ st.write(f"{emotion.capitalize()}: {score:.2%}")
89
+
90
+ # Add footer
91
+ st.markdown("---")
92
+ st.markdown("""
93
+ Created with ❀️ using Hugging Face Transformers and Streamlit.
94
+ Model: j-hartmann/emotion-english-distilroberta-base
95
+ """)