Anshya commited on
Commit
290b1e4
Β·
verified Β·
1 Parent(s): 520dd85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +319 -39
app.py CHANGED
@@ -1,39 +1,319 @@
1
- import streamlit as st
2
- from transformers import pipeline
3
-
4
- # Load emotion & whisper models
5
- emotion_model = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True)
6
- whisper_model = pipeline("automatic-speech-recognition", model="openai/whisper-small")
7
-
8
- def analyze_emotion(text):
9
- results = emotion_model(text)[0]
10
- sorted_results = sorted(results, key=lambda x: x['score'], reverse=True)
11
- return sorted_results
12
-
13
- # Streamlit UI
14
- st.set_page_config(page_title="Emotion Analyzer", layout="centered")
15
- st.title("Emotion Analysis from Text & Video (via Audio)")
16
-
17
- input_type = st.radio("Choose input type:", ["Text Post", "Video (Upload Audio)"])
18
-
19
- if input_type == "Text Post":
20
- text_input = st.text_area("Enter your post:")
21
- if st.button("Analyze Text"):
22
- if text_input.strip():
23
- results = analyze_emotion(text_input)
24
- st.subheader("Detected Emotions:")
25
- for r in results:
26
- st.write(f"**{r['label']}**: {round(r['score']*100, 2)}%")
27
-
28
- elif input_type == "Video (Upload Audio)":
29
- audio = st.file_uploader("Upload audio extracted from video", type=["wav", "mp3", "m4a"])
30
- if audio and st.button("Analyze Audio"):
31
- st.info("Transcribing audio...")
32
- text = whisper_model(audio)["text"]
33
- st.success("Transcription:")
34
- st.write(text)
35
-
36
- st.subheader("Detected Emotions:")
37
- results = analyze_emotion(text)
38
- for r in results:
39
- st.write(f"**{r['label']}**: {round(r['score']*100, 2)}%")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ from deepface import DeepFace
4
+ from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
5
+ import tempfile
6
+
7
+ analyzer = SentimentIntensityAnalyzer()
8
+
9
+ def analyze_text(text):
10
+ score = analyzer.polarity_scores(text)
11
+ if score['compound'] >= 0.05:
12
+ return "Positive 😊"
13
+ elif score['compound'] <= -0.05:
14
+ return "Negative 😠"
15
+ else:
16
+ return "Neutral 😐"
17
+
18
+ def process_all(text, video):
19
+ text_sentiment = analyze_sentiment(text)
20
+ video_emotion = analyze_video_emotion(video)
21
+ return f"Text Sentiment: {text_sentiment}\nFacial Emotion: {video_emotion}"
22
+
23
+ iface = gr.Interface(
24
+ fn=process_all,
25
+ inputs=[gr.Textbox(label="Social Media Post"), gr.Video(label="Upload Video")],
26
+ outputs="text",
27
+ title="Emotion & Sentiment Analyzer"
28
+ )
29
+
30
+ iface.launch()
31
+
32
+ def analyze_video(video_file):
33
+ if video_file is None:
34
+ return "No video uploaded"
35
+
36
+ # Save uploaded file temporarily
37
+ temp_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
38
+ with open(temp_path, "wb") as f:
39
+ f.write(video_file.read())
40
+
41
+ cap = cv2.VideoCapture(temp_path)
42
+ success, frame = cap.read()
43
+ cap.release()
44
+
45
+ def analyze_video_emotion(video_file):
46
+ # Save the uploaded video to a temp file
47
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
48
+ tmp.write(video_file.read())
49
+ tmp_path = tmp.name
50
+
51
+ cap = cv2.VideoCapture(tmp_path)
52
+ emotions = []
53
+ frame_count = 0
54
+
55
+ import cv2
56
+ import tempfile
57
+ from deepface import DeepFace
58
+
59
+ def analyze_video_emotion(video_file):
60
+ # Save the uploaded video to a temp file
61
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
62
+ tmp.write(video_file.read())
63
+ tmp_path = tmp.name
64
+
65
+ cap = cv2.VideoCapture(tmp_path)
66
+ emotions = []
67
+ frame_count = 0
68
+
69
+ while cap.isOpened():
70
+ ret, frame = cap.read()
71
+ if not ret or frame_count > 60: # Limit to first 60 frames
72
+ break
73
+ try:
74
+ result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False)
75
+ emotions.append(result[0]['dominant_emotion'])
76
+ except Exception as e:
77
+ print("Error analyzing frame:", e)
78
+ frame_count += 1
79
+
80
+ cap.release()
81
+
82
+ if emotions:
83
+ # Return most frequent emotion
84
+ return max(set(emotions), key=emotions.count)
85
+ else:
86
+ return "No emotion detected or face not found"
87
+
88
+
89
+ while cap.isOpened():
90
+ ret, frame = cap.read()
91
+ if not ret or frame_count > 60: # Limit to 60 frames max
92
+ break
93
+ try:
94
+ result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False)
95
+ emotions.append(result[0]['dominant_emotion'])
96
+ except:
97
+ pass
98
+ frame_count += 1
99
+
100
+ cap.release()
101
+
102
+ if emotions:
103
+ # Return most common emotion
104
+ return max(set(emotions), key=emotions.count)
105
+ else:
106
+ return "No face detected"
107
+
108
+
109
+ if not success:
110
+ return "Could not read video"
111
+
112
+ try:
113
+ result = DeepFace.analyze(frame, actions=["emotion"], enforce_detection=False)
114
+ return result[0]['dominant_emotion'].capitalize()
115
+ except Exception as e:
116
+ return f"Error: {str(e)}"
117
+
118
+ def analyze_post(text, video):
119
+ sentiment = analyze_text(text)
120
+ emotion = analyze_video(video)
121
+ return f"πŸ“ Sentiment: {sentiment}\nπŸŽ₯ Emotion: {emotion}"
122
+ import gradio as gr
123
+
124
+ def analyze_text(text):
125
+ from transformers import pipeline
126
+ classifier = pipeline("sentiment-analysis")
127
+ return classifier(text)[0]['label']
128
+
129
+ def process_all(text_input, video_input):
130
+ text_result = analyze_text(text_input)
131
+ video_result = analyze_video_emotion(video_input)
132
+ return f"Text Sentiment: {text_result}\nFacial Emotion: {video_result}"
133
+
134
+ gr.Interface(
135
+ fn=process_all,
136
+ inputs=[
137
+ gr.Textbox(label="Enter Social Media Text"),
138
+ gr.Video(label="Upload a Video Clip")
139
+ ],
140
+ outputs="text",
141
+ title="Emotion & Sentiment Decoder",
142
+ description="Analyzes social media text & facial expressions from video."
143
+ ).launch()
144
+
145
+
146
+ interface = gr.Interface(
147
+ fn=analyze_post,
148
+ inputs=[
149
+ gr.Textbox(label="Post Text", placeholder="Enter your message here"),
150
+ gr.File(label="Upload video (.mp4)", file_types=[".mp4"])
151
+ ],
152
+ outputs="text",
153
+ title="πŸ“± Emotion & Sentiment Analyzer",
154
+ description="Analyze text sentiment and facial emotion from video. No re-running needed. Permanent on Hugging Face."
155
+ )
156
+
157
+ interface.launch()import gradio as gr
158
+ import cv2
159
+ from deepface import DeepFace
160
+ from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
161
+ import tempfile
162
+
163
+ analyzer = SentimentIntensityAnalyzer()
164
+
165
+ def analyze_text(text):
166
+ score = analyzer.polarity_scores(text)
167
+ if score['compound'] >= 0.05:
168
+ return "Positive 😊"
169
+ elif score['compound'] <= -0.05:
170
+ return "Negative 😠"
171
+ else:
172
+ return "Neutral 😐"
173
+
174
+ def process_all(text, video):
175
+ text_sentiment = analyze_sentiment(text)
176
+ video_emotion = analyze_video_emotion(video)
177
+ return f"Text Sentiment: {text_sentiment}\nFacial Emotion: {video_emotion}"
178
+
179
+ iface = gr.Interface(
180
+ fn=process_all,
181
+ inputs=[gr.Textbox(label="Social Media Post"), gr.Video(label="Upload Video")],
182
+ outputs="text",
183
+ title="Emotion & Sentiment Analyzer"
184
+ )
185
+
186
+ iface.launch()
187
+
188
+ def analyze_video(video_file):
189
+ if video_file is None:
190
+ return "No video uploaded"
191
+
192
+ # Save uploaded file temporarily
193
+ temp_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
194
+ with open(temp_path, "wb") as f:
195
+ f.write(video_file.read())
196
+
197
+ cap = cv2.VideoCapture(temp_path)
198
+ success, frame = cap.read()
199
+ cap.release()
200
+
201
+ def analyze_video_emotion(video_file):
202
+ # Save the uploaded video to a temp file
203
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
204
+ tmp.write(video_file.read())
205
+ tmp_path = tmp.name
206
+
207
+ cap = cv2.VideoCapture(tmp_path)
208
+ emotions = []
209
+ frame_count = 0
210
+
211
+ import cv2
212
+ import tempfile
213
+ from deepface import DeepFace
214
+
215
+ def analyze_video_emotion(video_file):
216
+ # Save the uploaded video to a temp file
217
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
218
+ tmp.write(video_file.read())
219
+ tmp_path = tmp.name
220
+
221
+ cap = cv2.VideoCapture(tmp_path)
222
+ emotions = []
223
+ frame_count = 0
224
+
225
+ while cap.isOpened():
226
+ ret, frame = cap.read()
227
+ if not ret or frame_count > 60: # Limit to first 60 frames
228
+ break
229
+ try:
230
+ result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False)
231
+ emotions.append(result[0]['dominant_emotion'])
232
+ except Exception as e:
233
+ print("Error analyzing frame:", e)
234
+ frame_count += 1
235
+
236
+ cap.release()
237
+
238
+ if emotions:
239
+ # Return most frequent emotion
240
+ return max(set(emotions), key=emotions.count)
241
+ else:
242
+ return "No emotion detected or face not found"
243
+
244
+
245
+ while cap.isOpened():
246
+ ret, frame = cap.read()
247
+ if not ret or frame_count > 60: # Limit to 60 frames max
248
+ break
249
+ try:
250
+ result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False)
251
+ emotions.append(result[0]['dominant_emotion'])
252
+ except:
253
+ pass
254
+ frame_count += 1
255
+
256
+ cap.release()
257
+
258
+ if emotions:
259
+ # Return most common emotion
260
+ return max(set(emotions), key=emotions.count)
261
+ else:
262
+ return "No face detected"
263
+
264
+
265
+ if not success:
266
+ return "Could not read video"
267
+
268
+ try:
269
+ result = DeepFace.analyze(frame, actions=["emotion"], enforce_detection=False)
270
+ return result[0]['dominant_emotion'].capitalize()
271
+ except Exception as e:
272
+ return f"Error: {str(e)}"
273
+
274
+ def analyze_post(text, video):
275
+ sentiment = analyze_text(text)
276
+ emotion = analyze_video(video)
277
+ return f"πŸ“ Sentiment: {sentiment}\nπŸŽ₯ Emotion: {emotion}"
278
+ import gradio as gr
279
+
280
+ def analyze_text(text):
281
+ from transformers import pipeline
282
+ classifier = pipeline("sentiment-analysis")
283
+ return classifier(text)[0]['label']
284
+
285
+ def process_all(text_input, video_input):
286
+ text_result = analyze_text(text_input)
287
+ video_result = analyze_video_emotion(video_input)
288
+ return f"Text Sentiment: {text_result}\nFacial Emotion: {video_result}"
289
+
290
+ gr.Interface(
291
+ fn=process_all,
292
+ inputs=[
293
+ gr.Textbox(label="Enter Social Media Text"),
294
+ gr.Video(label="Upload a Video Clip")
295
+ ],
296
+ outputs="text",
297
+ title="Emotion & Sentiment Decoder",
298
+ description="Analyzes social media text & facial expressions from video."
299
+ ).launch()
300
+
301
+
302
+ interface = gr.Interface(
303
+ fn=analyze_post,
304
+ inputs=[
305
+ gr.Textbox(label="Post Text", placeholder="Enter your message here"),
306
+ gr.File(label="Upload video (.mp4)", file_types=[".mp4"])
307
+ ],
308
+ outputs="text",
309
+ title="πŸ“± Emotion & Sentiment Analyzer",
310
+ description="Analyze text sentiment and facial emotion from video. No re-running needed. Permanent on Hugging Face."
311
+ if text_input:
312
+ # Process text only
313
+ elif video_input:
314
+ # Process video only
315
+ else:
316
+ return "No input provided"
317
+ )
318
+
319
+ interface.launch()