AhmedSSabir commited on
Commit
bc64314
โ€ข
1 Parent(s): fb6fa5b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -0
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ from doctest import OutputChecker
4
+ import sys
5
+ import torch
6
+ import re
7
+ import os
8
+ import gradio as gr
9
+ import requests
10
+
11
+ #url = "https://github.com/simonepri/lm-scorer/tree/master/lm_scorer/models"
12
+ #resp = requests.get(url)
13
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
14
+ from transformers import T5Tokenizer, AutoModelForCausalLM
15
+
16
+ from arabert import ArabertPreprocessor
17
+ from arabert.aragpt2.grover.modeling_gpt2 import GPT2LMHeadModel
18
+
19
+ from transformers import AutoTokenizer, AutoModel
20
+ from arabert.preprocess import ArabertPreprocessor
21
+
22
+
23
+ from sentence_transformers import SentenceTransformer, util
24
+ #from sentence_transformers import SentenceTransformer, util
25
+ #from sklearn.metrics.pairwise import cosine_similarity
26
+ #from lm_scorer.models.auto import AutoLMScorer as LMScorer
27
+ #from sentence_transformers import SentenceTransformer, util
28
+ #from sklearn.metrics.pairwise import cosine_similarity
29
+
30
+
31
+ #model_sts = gr.Interface.load('huggingface/sentence-transformers/stsb-distilbert-base')
32
+
33
+ #model_sts = SentenceTransformer('stsb-distilbert-base')
34
+ #model_sts = SentenceTransformer('roberta-large-nli-stsb-mean-tokens')
35
+ model_sts = SentenceTransformer('distiluse-base-multilingual-cased-v1')
36
+
37
+ #batch_size = 1
38
+ #scorer = LMScorer.from_pretrained('gpt2' , device=device, batch_size=batch_size)
39
+
40
+ #import torch
41
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
42
+ import numpy as np
43
+ import re
44
+
45
+
46
+
47
+
48
+ def Sort_Tuple(tup):
49
+
50
+ # (Sorts in descending order)
51
+ tup.sort(key = lambda x: x[1])
52
+ return tup[::-1]
53
+
54
+
55
+ def softmax(x):
56
+ exps = np.exp(x)
57
+ return np.divide(exps, np.sum(exps))
58
+
59
+
60
+ def get_sim(x):
61
+ x = str(x)[1:-1]
62
+ x = str(x)[1:-1]
63
+ return x
64
+
65
+
66
+ # Load pre-trained model
67
+
68
+ #model = GPT2LMHeadModel.from_pretrained('distilgpt2', output_hidden_states = True, output_attentions = True)
69
+ model = GPT2LMHeadModel.from_pretrained('gpt2', output_hidden_states = True, output_attentions = True)
70
+ #model = gr.Interface.load('huggingface/distilgpt2', output_hidden_states = True, output_attentions = True)
71
+
72
+ #model.eval()
73
+ #tokenizer = gr.Interface.load('huggingface/distilgpt2')
74
+
75
+ #tokenizer = GPT2Tokenizer.from_pretrained('distilgpt2')
76
+ tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
77
+ #tokenizer = GPT2Tokenizer.from_pretrained('distilgpt2')
78
+
79
+
80
+ model_name = "aubmindlab/aragpt2-base"
81
+ arabert_prep = ArabertPreprocessor(model_name=model_name)
82
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
83
+
84
+ model = GPT2LMHeadModel.from_pretrained(model_name, output_hidden_states=True, output_attentions=True)
85
+ tokenizer = GPT2TokenizerFast.from_pretrained(model_name)
86
+ #model.eval()
87
+
88
+
89
+
90
+
91
+ def cloze_prob(text):
92
+
93
+ whole_text_encoding = tokenizer.encode(text)
94
+ # Parse out the stem of the whole sentence (i.e., the part leading up to but not including the critical word)
95
+ text_list = text.split()
96
+ stem = ' '.join(text_list[:-1])
97
+ stem_encoding = tokenizer.encode(stem)
98
+ # cw_encoding is just the difference between whole_text_encoding and stem_encoding
99
+ # note: this might not correspond exactly to the word itself
100
+ cw_encoding = whole_text_encoding[len(stem_encoding):]
101
+ # 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.
102
+ # Put the whole text encoding into a tensor, and get the model's comprehensive output
103
+ tokens_tensor = torch.tensor([whole_text_encoding])
104
+
105
+ with torch.no_grad():
106
+ outputs = model(tokens_tensor)
107
+ predictions = outputs[0]
108
+
109
+ logprobs = []
110
+ # start at the stem and get downstream probabilities incrementally from the model(see above)
111
+ start = -1-len(cw_encoding)
112
+ for j in range(start,-1,1):
113
+ raw_output = []
114
+ for i in predictions[-1][j]:
115
+ raw_output.append(i.item())
116
+
117
+ logprobs.append(np.log(softmax(raw_output)))
118
+
119
+ # if the critical word is three tokens long, the raw_probabilities should look something like this:
120
+ # [ [0.412, 0.001, ... ] ,[0.213, 0.004, ...], [0.002,0.001, 0.93 ...]]
121
+ # Then for the i'th token we want to find its associated probability
122
+ # this is just: raw_probabilities[i][token_index]
123
+ conditional_probs = []
124
+ for cw,prob in zip(cw_encoding,logprobs):
125
+ conditional_probs.append(prob[cw])
126
+ # now that you have all the relevant probabilities, return their product.
127
+ # This is the probability of the critical word given the context before it.
128
+
129
+ return np.exp(np.sum(conditional_probs))
130
+
131
+
132
+
133
+
134
+
135
+ def cos_sim(a, b):
136
+ return np.inner(a, b) / (np.linalg.norm(a) * (np.linalg.norm(b)))
137
+
138
+
139
+
140
+ #def Visual_re_ranker(caption, visual_context_label, visual_context_prob):
141
+ def Visual_re_ranker(caption_man, caption_woman, visual_context_label, visual_context_prob):
142
+ caption_man = caption_man
143
+ caption_woman = caption_woman
144
+ visual_context_label= visual_context_label
145
+ visual_context_prob = visual_context_prob
146
+ caption_emb_man = model_sts.encode(caption_man, convert_to_tensor=True)
147
+ caption_emb_woman = model_sts.encode(caption_woman, convert_to_tensor=True)
148
+ visual_context_label_emb = model_sts.encode(visual_context_label, convert_to_tensor=True)
149
+
150
+ sim_m = cosine_scores = util.pytorch_cos_sim(caption_emb_man, visual_context_label_emb)
151
+ sim_m = sim_m.cpu().numpy()
152
+ sim_m = get_sim(sim_m)
153
+
154
+ sim_w = cosine_scores = util.pytorch_cos_sim(caption_emb_woman, visual_context_label_emb)
155
+ sim_w = sim_w.cpu().numpy()
156
+ sim_w = get_sim(sim_w)
157
+
158
+
159
+ LM_man = cloze_prob(caption_man)
160
+ LM_woman = cloze_prob(caption_woman)
161
+ #LM = scorer.sentence_score(caption, reduce="mean")
162
+ score_man = pow(float(LM_man),pow((1-float(sim_m))/(1+ float(sim_m)),1-float(visual_context_prob)))
163
+ score_woman = pow(float(LM_woman),pow((1-float(sim_w))/(1+ float(sim_w)),1-float(visual_context_prob)))
164
+
165
+
166
+
167
+
168
+ #return {"LM": float(LM)/1, "sim": float(sim)/1, "score": float(score)/1 }
169
+ return {"Man": float(score_man)/1, "Woman": float(score_woman)/1}
170
+ #return LM, sim, score
171
+
172
+
173
+
174
+
175
+
176
+ demo = gr.Interface(
177
+ fn=Visual_re_ranker,
178
+ description="Demo for Women Wearing Lipstick: Measuring the Bias Between Object and Its Related Gender",
179
+ #inputs=[gr.Textbox(value="a man sitting on a surfboard in the ocean") , gr.Textbox(value="a woman sitting on a surfboard in the ocean"), gr.Textbox(value="paddle"), gr.Textbox(value="0.5283")],
180
+
181
+ inputs=[gr.Textbox(value="ุดุนุฑู‡ุง ุฌู…ูŠู„ ุงู„ูŠูˆู…") , gr.Textbox(value="ุดุนุฑู‡ ุฌู…ูŠู„ ุงู„ูŠูˆู…"), gr.Textbox(value="ุฌู…ูŠู„"), gr.Textbox(value="0.7385")],
182
+
183
+ outputs="label",
184
+ )
185
+ demo.launch()