-
Notifications
You must be signed in to change notification settings - Fork 3
/
ed.py
51 lines (36 loc) · 1.66 KB
/
ed.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import torch
import re
import requests
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from flask import Flask, request, jsonify
tokenizer = AutoTokenizer.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion")
model = AutoModelForSequenceClassification.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion")
app = Flask(__name__)
def preprocess_text(text):
emoticons = r'(?::|;|=)(?:-)?(?:\)|\(|D|P)'
emoticon_pattern = re.compile(r'(?::|;|=)(?:-)?(?:\)|\(|D|P)', re.VERBOSE | re.IGNORECASE)
emoticon_found = emoticon_pattern.findall(text)
text = emoticon_pattern.sub('', text)
text = " ".join(text.split())
return text
def update_keywords_based_on_emotion(emotion):
emotion_to_keywords = {
"anger": ["furious", "angry", "pissed"],
"joy": ["happy", "elated", "joyful"],
"sad": ["sadness", "morose", "hurt"]
}
new_keywords = emotion_to_keywords.get(emotion, [])
if new_keywords:
response = request.post("http://link", json={"new_negative_keywords": new_keywords})
return response.json()
return{"message": "No new keywords to update for this emotion. "}
def analyze_emotion():
text = preprocess_text(text)
inputs = tokenizer(text, return_tensors="pt", padding = True, truncation = True, max_length=32)
with torch.no_grad():
logits = model(**inputs).logits
max_val = torch.max(logits)
logits -= max_val
probabilities = torch.nn.functional.softmax(logits, dim=1)
emotion = model.config.id2label[probabilities.argmax().item()]
return {"emotion": emotion}