AhmedSSabir commited on
Commit
4387c41
·
1 Parent(s): 9121417

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +162 -0
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from doctest import OutputChecker
3
+ import sys
4
+ import torch
5
+ import re
6
+ import os
7
+ import gradio as gr
8
+ import requests
9
+
10
+ #url = "https://github.com/simonepri/lm-scorer/tree/master/lm_scorer/models"
11
+ #resp = requests.get(url)
12
+
13
+ from sentence_transformers import SentenceTransformer, util
14
+ #from sentence_transformers import SentenceTransformer, util
15
+ #from sklearn.metrics.pairwise import cosine_similarity
16
+ #from lm_scorer.models.auto import AutoLMScorer as LMScorer
17
+ #from sentence_transformers import SentenceTransformer, util
18
+ #from sklearn.metrics.pairwise import cosine_similarity
19
+
20
+ #device = "cuda:0" if torch.cuda.is_available() else "cpu"
21
+ #model_sts = gr.Interface.load('huggingface/sentence-transformers/stsb-distilbert-base')
22
+
23
+ #model_sts = SentenceTransformer('stsb-distilbert-base')
24
+ model_sts = SentenceTransformer('roberta-large-nli-stsb-mean-tokens')
25
+ #batch_size = 1
26
+ #scorer = LMScorer.from_pretrained('gpt2' , device=device, batch_size=batch_size)
27
+
28
+ #import torch
29
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
30
+ import numpy as np
31
+ import re
32
+
33
+ def Sort_Tuple(tup):
34
+
35
+ # (Sorts in descending order)
36
+ tup.sort(key = lambda x: x[1])
37
+ return tup[::-1]
38
+
39
+
40
+ def softmax(x):
41
+ exps = np.exp(x)
42
+ return np.divide(exps, np.sum(exps))
43
+
44
+
45
+ def get_sim(x):
46
+ x = str(x)[1:-1]
47
+ x = str(x)[1:-1]
48
+ return x
49
+
50
+ # Load pre-trained model
51
+
52
+ model = GPT2LMHeadModel.from_pretrained('gpt2', output_hidden_states = True, output_attentions = True)
53
+
54
+ #model = gr.Interface.load('huggingface/distilgpt2', output_hidden_states = True, output_attentions = True)
55
+
56
+ #model.eval()
57
+ #tokenizer = gr.Interface.load('huggingface/distilgpt2')
58
+
59
+ tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
60
+ #tokenizer = GPT2Tokenizer.from_pretrained('distilgpt2')
61
+
62
+
63
+ def cloze_prob(text):
64
+
65
+ whole_text_encoding = tokenizer.encode(text)
66
+ # Parse out the stem of the whole sentence (i.e., the part leading up to but not including the critical word)
67
+ text_list = text.split()
68
+ stem = ' '.join(text_list[:-1])
69
+ stem_encoding = tokenizer.encode(stem)
70
+ # cw_encoding is just the difference between whole_text_encoding and stem_encoding
71
+ # note: this might not correspond exactly to the word itself
72
+ cw_encoding = whole_text_encoding[len(stem_encoding):]
73
+ # Run the entire sentence through the model. Then go "back in time" to look at what the model predicted for each token, starting at the stem.
74
+ # Put the whole text encoding into a tensor, and get the model's comprehensive output
75
+ tokens_tensor = torch.tensor([whole_text_encoding])
76
+
77
+ with torch.no_grad():
78
+ outputs = model(tokens_tensor)
79
+ predictions = outputs[0]
80
+
81
+ logprobs = []
82
+ # start at the stem and get downstream probabilities incrementally from the model(see above)
83
+ start = -1-len(cw_encoding)
84
+ for j in range(start,-1,1):
85
+ raw_output = []
86
+ for i in predictions[-1][j]:
87
+ raw_output.append(i.item())
88
+
89
+ logprobs.append(np.log(softmax(raw_output)))
90
+
91
+ # if the critical word is three tokens long, the raw_probabilities should look something like this:
92
+ # [ [0.412, 0.001, ... ] ,[0.213, 0.004, ...], [0.002,0.001, 0.93 ...]]
93
+ # Then for the i'th token we want to find its associated probability
94
+ # this is just: raw_probabilities[i][token_index]
95
+ conditional_probs = []
96
+ for cw,prob in zip(cw_encoding,logprobs):
97
+ conditional_probs.append(prob[cw])
98
+ # now that you have all the relevant probabilities, return their product.
99
+ # This is the probability of the critical word given the context before it.
100
+
101
+ return np.exp(np.sum(conditional_probs))
102
+
103
+
104
+
105
+
106
+
107
+ def cos_sim(a, b):
108
+ return np.inner(a, b) / (np.linalg.norm(a) * (np.linalg.norm(b)))
109
+
110
+
111
+
112
+ def Visual_re_ranker(caption_G, caption_B, caption_VR, visual_context_label, visual_context_prob):
113
+ caption_G = caption_G
114
+ caption_B = caption_B
115
+ caption_VR = caption_VR
116
+ visual_context_label= visual_context_label
117
+ visual_context_prob = visual_context_prob
118
+ caption_emb_G = model_sts.encode(caption_G, convert_to_tensor=True)
119
+ caption_emb_B = model_sts.encode(caption_B, convert_to_tensor=True)
120
+ caption_emb_VR = model_sts.encode(caption_VR, convert_to_tensor=True)
121
+
122
+ visual_context_label_emb = model_sts.encode(visual_context_label, convert_to_tensor=True)
123
+
124
+
125
+ sim_1 = cosine_scores = util.pytorch_cos_sim(caption_emb_G, visual_context_label_emb)
126
+ sim_1 = sim_1.cpu().numpy()
127
+ sim_1 = get_sim(sim_1)
128
+
129
+ sim_2 = cosine_scores = util.pytorch_cos_sim(caption_emb_B, visual_context_label_emb)
130
+ sim_2 = sim_2.cpu().numpy()
131
+ sim_2 = get_sim(sim_2)
132
+
133
+ sim_3 = cosine_scores = util.pytorch_cos_sim(caption_emb_VR, visual_context_label_emb)
134
+ sim_3 = sim_3.cpu().numpy()
135
+ sim_3 = get_sim(sim_3)
136
+
137
+
138
+ LM_1 = cloze_prob(caption_G)
139
+ LM_2 = cloze_prob(caption_B)
140
+ LM_3 = cloze_prob(caption_VR)
141
+
142
+ #LM = scorer.sentence_score(caption, reduce="mean")
143
+ score_1 = pow(float(LM_1),pow((1-float(sim_1))/(1+ float(sim_1)),1-float(visual_context_prob)))
144
+ score_2 = pow(float(LM_2),pow((1-float(sim_2))/(1+ float(sim_2)),1-float(visual_context_prob)))
145
+ score_3 = pow(float(LM_3),pow((1-float(sim_3))/(1+ float(sim_3)),1-float(visual_context_prob)))
146
+
147
+ #return {"LM": float(LM)/1, "sim": float(sim)/1, "score": float(score)/1 }
148
+ return {"Graddy": float(score_1)/1, "Best-Beam-5": float(score_2)/1, "Visual_re-Ranker": float(score_3)/1 }
149
+ #return LM, sim, score
150
+
151
+
152
+
153
+
154
+ demo = gr.Interface(
155
+ fn=Visual_re_ranker,
156
+ description="Demo for Belief Revision based Caption Re-ranker with Visual Semantic Information",
157
+ #inputs=[gr.Textbox(value="a city street filled with traffic at night") , gr.Textbox(value="traffic"), gr.Textbox(value="0.7458009")],
158
+ inputs=[gr.Textbox(value="a longhorn cow with horns standing in a field") , gr.Textbox(value="two bulls with horns standing next to each other"), gr.Textbox(value="two bulls standing next to each other"), gr.Textbox(value="ox"), gr.Textbox(value="0.49095494")],
159
+ #outputs=[gr.Textbox(value="Language Model Score") , gr.Textbox(value="Semantic Similarity Score"), gr.Textbox(value="Belief revision score via visual context")],
160
+ outputs="label",
161
+ )
162
+ demo.launch()