File size: 2,075 Bytes
844e150
4496ce9
 
 
1b3e839
 
844e150
4496ce9
 
844e150
4496ce9
 
 
 
1b3e839
 
 
4496ce9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16226cc
1b3e839
 
 
4496ce9
 
 
 
 
 
 
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
52
53
54
import gradio as gr
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain  
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelWithLMHead


model_name="nateraw/bert-base-uncased-emotion"
model = pipeline('text-classification', model_name, truncation=True)

model_name = "mrm8488/t5-base-finetuned-emotion"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model_t5 = AutoModelWithLMHead.from_pretrained(model_name)

model_path = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
sentiment_task = pipeline("sentiment-analysis", model=model_path, tokenizer=model_path)

def get_emotion(text):
  input_ids = tokenizer.encode(text + '</s>', return_tensors='pt')
  output = model_t5.generate(input_ids=input_ids, return_dict_in_generate=True, output_scores=True)
  transition_scores = model_t5.compute_transition_scores(output.sequences, [s.softmax(dim=1) for s in output.scores], normalize_logits=False)
  dec = [tokenizer.decode(ids) for ids in output.sequences]
  score = transition_scores.min().item()
  return f"{dec[0].replace('<pad>','').replace('</s>','').strip()} [{score}]"

chat = ChatOpenAI()
conversation = ConversationChain(llm=chat)  
#Write a text example of someone angry
with gr.Blocks() as demo:
    label_text = gr.Textbox(label="Sentiment Text", text="")
    chatbot = gr.Chatbot(scale=2)
    msg = gr.Textbox()
    clear = gr.ClearButton([msg, chatbot])
            

    def respond(message, chat_history):
        bot_message = conversation.run(message)
        chat_history.append((message, bot_message))
        
        l = model(bot_message)[0]
        label_value = f"{l['label']} [{l['score']}]"
        label_value_t5 = get_emotion(bot_message)
        
        s = sentiment_task(bot_message)[0]
        sentiment_value = f"{s['label']} [{s['score']}]"
        
        return "", chat_history, f"Emotion [1]: {label_value_t5} - Emotion [2]: {label_value} - Sentiment : {sentiment_value}"

    msg.submit(respond, [msg, chatbot], [msg, chatbot, label_text])

demo.launch()