youj2005 commited on
Commit
2bca1d4
1 Parent(s): 15c0354

Create app

Browse files
Files changed (1) hide show
  1. app.py +56 -1
app.py CHANGED
@@ -1,3 +1,58 @@
1
  import gradio as gr
 
 
 
 
 
2
 
3
- gr.load("models/facebook/bart-large-mnli").launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import BartForSequenceClassification, BartTokenizer
3
+ import torch.nn.functional as F
4
+ import torch
5
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
6
+ from transformers import Pipeline
7
 
8
+ te_tokenizer = BartTokenizer.from_pretrained('facebook/bart-large-mnli')
9
+ te_model = BartForSequenceClassification.from_pretrained('facebook/bart-large-mnli')
10
+ qa_tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-base")
11
+ qa_model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-base", device_map="auto")
12
+
13
+ def predict(context, intent):
14
+ input_text = "In one word, what is the opposite of: " + intent + "?"
15
+ input_ids = qa_tokenizer(input_text, return_tensors="pt")
16
+ encoded_input = qa_tokenizer(input_ids, return_tensors="pt")
17
+ opposite_output = qa_tokenizer.decode(qa_model.generate(encoded_input)[0])
18
+ input_text = "In one word, what is the following describing: " + context
19
+ input_ids = qa_tokenizer(input_text, return_tensors="pt")
20
+ encoded_input = qa_tokenizer(input_ids, return_tensors="pt")
21
+ object_output = qa_tokenizer.decode(qa_model.generate(encoded_input)[0])
22
+ batch = ['I think the ' + object_output + ' are long.', 'I think the ' + object_output + ' are ' + opposite_output, 'I think the ' + object_output + ' are the perfect']
23
+ outputs = []
24
+ for i, hypothesis in enumerate(batch):
25
+ input_ids = te_tokenizer.encode(context, hypothesis, return_tensors='pt')
26
+ # -> [contradiction, neutral, entailment]
27
+ logits = te_model(input_ids)[0][0]
28
+
29
+ if (i == 2):
30
+ # -> [contradiction, entailment]
31
+ probs = logits[[0,2]].softmax(dim=0)
32
+ else:
33
+ probs = logits.softmax(dim=0)
34
+ outputs.append(probs)
35
+
36
+ # -> [entailment, contradiction]
37
+ outputs[2] = outputs[2].flip(dims=[0])
38
+ # -> [entailment, neutral, contradiction]
39
+ outputs[0] = outputs[0].flip(dims=[0])
40
+ pn_tensor = (outputs[0] + outputs[1]).softmax(dim=0)
41
+ pn_tensor[1] = pn_tensor[1] * outputs[2][0]
42
+ pn_tensor[2] = pn_tensor[2] * outputs[2][1]
43
+ pn_tensor[0] = pn_tensor[0] * outputs[2][1]
44
+
45
+ pn_tensor = F.normalize(pn_tensor, p=1, dim=0)
46
+
47
+ pn_tensor = pn_tensor.softmax(dim=0)
48
+ return {"entailment": pn_tensor[0].item(), "neutral": pn_tensor[1].item(), "contradiction": pn_tensor[2].item()}
49
+
50
+ gradio_app = gr.Interface(
51
+ predict,
52
+ inputs=gr.Text(label="Input sentence"),
53
+ outputs=[gr.Label(num_top_classes=3)],
54
+ title="Hot Dog? Or Not?",
55
+ )
56
+
57
+ if __name__ == "__main__":
58
+ gradio_app.launch()