Spaces:
Runtime error
Runtime error
Added app
Browse files- app.py +52 -0
- requirements.txt +1 -0
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# we will take last 8 messages as input and calculate the sentiment of each message
|
| 2 |
+
NUM_MESSAGES = 8
|
| 3 |
+
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
pipe = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def sentiment_analysis(*messages):
|
| 12 |
+
"""
|
| 13 |
+
Input will be a list of messages.
|
| 14 |
+
The function calculates the sentiment of each message, and then returns the average sentiment of the messages.
|
| 15 |
+
while calculating the sentiment, also take positive and negative labels into account.
|
| 16 |
+
scores are normalized to 0-100 range.
|
| 17 |
+
"""
|
| 18 |
+
# return 0 if no messages are provided
|
| 19 |
+
if len(messages) == 0:
|
| 20 |
+
return 0
|
| 21 |
+
|
| 22 |
+
if len(messages) > NUM_MESSAGES:
|
| 23 |
+
messages = messages[-NUM_MESSAGES:]
|
| 24 |
+
|
| 25 |
+
# each message should be of same length, so we will pad the messages
|
| 26 |
+
# find longest message
|
| 27 |
+
max_len = max([len(m) for m in messages])
|
| 28 |
+
# pad each message to the length of the longest message
|
| 29 |
+
messages = [m.ljust(max_len) for m in messages]
|
| 30 |
+
|
| 31 |
+
output = pipe(messages)
|
| 32 |
+
score = 0
|
| 33 |
+
for i in range(len(output)):
|
| 34 |
+
if output[i]['label'] == 'POSITIVE':
|
| 35 |
+
score += output[i]['score']
|
| 36 |
+
else:
|
| 37 |
+
score -= output[i]['score']
|
| 38 |
+
|
| 39 |
+
# shift score to 0-100 range
|
| 40 |
+
score = (score + NUM_MESSAGES) * 50 / NUM_MESSAGES
|
| 41 |
+
return round(score, 2)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
demo = gr.Interface(
|
| 45 |
+
fn=sentiment_analysis,
|
| 46 |
+
inputs=["text"] * NUM_MESSAGES,
|
| 47 |
+
outputs=["number"],
|
| 48 |
+
title="Sentiment Analysis",
|
| 49 |
+
description=f"Analyze the sentiment of the last {NUM_MESSAGES} messages"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
transformers~=4.38.0
|