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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import base64
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import numpy as np
|
| 8 |
+
import random as rd
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
from diffusers import StableDiffusionPipeline
|
| 12 |
+
from transformers import CLIPProcessor, CLIPModel, Pix2StructProcessor, Pix2StructForConditionalGeneration, ViltProcessor, ViltForQuestionAnswering, BlipProcessor, BlipForQuestionAnswering, AutoProcessor, AutoModelForCausalLM
|
| 13 |
+
import openai
|
| 14 |
+
|
| 15 |
+
clip_model = CLIPModel.from_pretrained("openai/clip-vit-large-patch14")
|
| 16 |
+
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14")
|
| 17 |
+
|
| 18 |
+
vilt_model = ViltForQuestionAnswering.from_pretrained("dandelin/vilt-b32-finetuned-vqa")
|
| 19 |
+
vilt_processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-finetuned-vqa")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
import ds_manager as ds_mgr
|
| 23 |
+
|
| 24 |
+
MISSING_C = None
|
| 25 |
+
C1_B64s = []
|
| 26 |
+
C2_B64s = []
|
| 27 |
+
C1_PILs = []
|
| 28 |
+
C2_PILs = []
|
| 29 |
+
|
| 30 |
+
def updateErrorMsg(isError, text):
|
| 31 |
+
return gr.Markdown.update(visible=isError, value=text)
|
| 32 |
+
|
| 33 |
+
def moveStep1():
|
| 34 |
+
variants = ["primary","secondary","secondary"]
|
| 35 |
+
#inter = [True, False, False]
|
| 36 |
+
tabs = [True, False, False]
|
| 37 |
+
|
| 38 |
+
return (gr.update(variant=variants[0]),
|
| 39 |
+
gr.update(variant=variants[1]),
|
| 40 |
+
gr.update(variant=variants[2]),
|
| 41 |
+
gr.update(visible=tabs[0]),
|
| 42 |
+
gr.update(visible=tabs[1]),
|
| 43 |
+
gr.update(visible=tabs[2]))
|
| 44 |
+
|
| 45 |
+
# Interaction with top tabs
|
| 46 |
+
def moveStep1_clear():
|
| 47 |
+
variants = ["primary","secondary","secondary"]
|
| 48 |
+
#inter = [True, False, False]
|
| 49 |
+
tabs = [True, False, False]
|
| 50 |
+
|
| 51 |
+
return (gr.update(variant=variants[0]),
|
| 52 |
+
gr.update(variant=variants[1]),
|
| 53 |
+
gr.update(variant=variants[2]),
|
| 54 |
+
gr.update(visible=tabs[0]),
|
| 55 |
+
gr.update(visible=tabs[1]),
|
| 56 |
+
gr.update(visible=tabs[2]),
|
| 57 |
+
gr.Textbox.update(value=""),
|
| 58 |
+
gr.Textbox.update(value=""),
|
| 59 |
+
gr.Textbox.update(value=""),
|
| 60 |
+
gr.Textbox.update(value=""))
|
| 61 |
+
|
| 62 |
+
def moveStep2():
|
| 63 |
+
variants = ["secondary","primary","secondary"]
|
| 64 |
+
#inter = [True, True, False]
|
| 65 |
+
tabs = [False, True, False]
|
| 66 |
+
|
| 67 |
+
return (gr.update(variant=variants[0]),
|
| 68 |
+
gr.update(variant=variants[1]),
|
| 69 |
+
gr.update(variant=variants[2]),
|
| 70 |
+
gr.update(visible=tabs[0]),
|
| 71 |
+
gr.update(visible=tabs[1]),
|
| 72 |
+
gr.update(visible=tabs[2]))
|
| 73 |
+
|
| 74 |
+
def moveStep3():
|
| 75 |
+
variants = ["secondary","secondary","primary"]
|
| 76 |
+
#inter = [True, True, False]
|
| 77 |
+
tabs = [False, False, True]
|
| 78 |
+
|
| 79 |
+
return (gr.update(variant=variants[0]),
|
| 80 |
+
gr.update(variant=variants[1]),
|
| 81 |
+
gr.update(variant=variants[2]),
|
| 82 |
+
gr.update(visible=tabs[0]),
|
| 83 |
+
gr.update(visible=tabs[1]),
|
| 84 |
+
gr.update(visible=tabs[2]))
|
| 85 |
+
|
| 86 |
+
def decode_b64(b64s):
|
| 87 |
+
decoded = []
|
| 88 |
+
for b64 in b64s:
|
| 89 |
+
decoded.append(Image.open(BytesIO(base64.b64decode(b64))))
|
| 90 |
+
return decoded
|
| 91 |
+
|
| 92 |
+
def generate(prompt, openai_key):
|
| 93 |
+
prompt = prompt.lower().strip()
|
| 94 |
+
_, retrieved, _ = ds_mgr.getSavedSentences(prompt)
|
| 95 |
+
print(f"retrieved: {retrieved}")
|
| 96 |
+
if len(retrieved.index) > 0:
|
| 97 |
+
update_value = decode_b64(list(retrieved['b64']))
|
| 98 |
+
print(f"update_value: {update_value}")
|
| 99 |
+
return update_value, list(retrieved['b64'])
|
| 100 |
+
openai.api_key = openai_key
|
| 101 |
+
response = openai.Image.create(
|
| 102 |
+
prompt=prompt,
|
| 103 |
+
n=4,
|
| 104 |
+
size="256x256",
|
| 105 |
+
response_format='b64_json'
|
| 106 |
+
)
|
| 107 |
+
image_b64s = []
|
| 108 |
+
save_b64s = []
|
| 109 |
+
for image in response['data']:
|
| 110 |
+
image_b64s.append(image['b64_json'])
|
| 111 |
+
save_b64s.append([prompt, image['b64_json']])
|
| 112 |
+
save_df = pd.DataFrame(save_b64s, columns=["prompt", "b64"])
|
| 113 |
+
print(f"save_df: {save_b64s}")
|
| 114 |
+
# save (save_df)
|
| 115 |
+
ds_mgr.saveSentences(save_df)
|
| 116 |
+
images = decode_b64(image_b64s)
|
| 117 |
+
# images = pipe(prompt, height=256, width=256, num_images_per_prompt=2).images
|
| 118 |
+
#print(images)
|
| 119 |
+
# return (
|
| 120 |
+
# gr.update(value=images)
|
| 121 |
+
# )
|
| 122 |
+
return images, image_b64s
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def clip(imgs1, imgs2, g1, g2):
|
| 126 |
+
"""
|
| 127 |
+
imgs1: list of PIL Images
|
| 128 |
+
imgs1: list of PIL Images
|
| 129 |
+
g1: list of str (test-concepts 1)
|
| 130 |
+
g2: list of str (test-concepts 2)
|
| 131 |
+
|
| 132 |
+
returns avg_probs_imgs1, avg_probs_imgs2 - dicts for imgs1, imgs2
|
| 133 |
+
({img index: {'g1': probability, 'g2': probability}})
|
| 134 |
+
"""
|
| 135 |
+
# One call of CLIP processor + model - may need to batch later
|
| 136 |
+
|
| 137 |
+
inputs = clip_processor(text = g1 + g2, images = imgs1 + imgs2,
|
| 138 |
+
return_tensors="pt", padding=True)
|
| 139 |
+
outputs = clip_model(**inputs)
|
| 140 |
+
|
| 141 |
+
logits_imgs1 = outputs.logits_per_image[:len(imgs1)]
|
| 142 |
+
logits_imgs2 = outputs.logits_per_image[len(imgs1):]
|
| 143 |
+
probs_imgs1 = torch.softmax(logits_imgs1, dim=1)
|
| 144 |
+
probs_imgs2 = torch.softmax(logits_imgs2, dim=1)
|
| 145 |
+
|
| 146 |
+
avg_probs_imgs1 = {}
|
| 147 |
+
avg_probs_imgs2 = {}
|
| 148 |
+
|
| 149 |
+
# Calculate the probabilities of prompts in g1 and g2 for each image in imgs1
|
| 150 |
+
for idx, img_probs in enumerate(probs_imgs1):
|
| 151 |
+
prob_g1 = img_probs[:len(g1)].sum().item()
|
| 152 |
+
prob_g2 = img_probs[len(g1):].sum().item()
|
| 153 |
+
avg_probs_imgs1[idx] = {'g1': prob_g1, 'g2': prob_g2}
|
| 154 |
+
|
| 155 |
+
# Calculate the probabilities of prompts in g1 and g2 for each image in imgs2
|
| 156 |
+
for idx, img_probs in enumerate(probs_imgs2):
|
| 157 |
+
prob_g1 = img_probs[:len(g1)].sum().item()
|
| 158 |
+
prob_g2 = img_probs[len(g1):].sum().item()
|
| 159 |
+
avg_probs_imgs2[idx] = {'g1': prob_g1, 'g2': prob_g2}
|
| 160 |
+
|
| 161 |
+
print(f"avg_probs_imgs1:\n{avg_probs_imgs1}")
|
| 162 |
+
print(f"avg_probs_imgs2:\n{avg_probs_imgs2}")
|
| 163 |
+
# Can do an average probability over all images - need to decide how we are using this
|
| 164 |
+
return avg_probs_imgs1, avg_probs_imgs2
|
| 165 |
+
|
| 166 |
+
def vilt_test(imgs1, imgs2, g1, g2, model, processor):
|
| 167 |
+
|
| 168 |
+
avg_probs_imgs1 = {}
|
| 169 |
+
avg_probs_imgs2 = {}
|
| 170 |
+
|
| 171 |
+
for i, img in enumerate(imgs1):
|
| 172 |
+
g1c = rd.choice(g1)
|
| 173 |
+
g2c = rd.choice(g2)
|
| 174 |
+
encoding = processor(img, f'Is the image of a {g1c}?', return_tensors="pt")
|
| 175 |
+
outputs = model(**encoding)
|
| 176 |
+
logits = outputs.logits
|
| 177 |
+
idx = logits.argmax(-1).item()
|
| 178 |
+
ans = model.config.id2label[idx]
|
| 179 |
+
print("Predicted answer:", model.config.id2label[idx])
|
| 180 |
+
|
| 181 |
+
logitsList = torch.softmax(logits, dim=1).flatten().tolist()
|
| 182 |
+
m = max(logitsList)
|
| 183 |
+
s = -math.inf
|
| 184 |
+
for logit in logitsList:
|
| 185 |
+
if s <= logit < m:
|
| 186 |
+
s = logit
|
| 187 |
+
t = sum(logitsList)
|
| 188 |
+
pm, ps = m/t, s/t
|
| 189 |
+
|
| 190 |
+
if 'yes' in ans:
|
| 191 |
+
avg_probs_imgs1[i] = {'g1': pm, 'g2': ps}
|
| 192 |
+
else:
|
| 193 |
+
avg_probs_imgs1[i] = {'g1': ps, 'g2': pm}
|
| 194 |
+
|
| 195 |
+
for i, img in enumerate(imgs2):
|
| 196 |
+
g2c = rd.choice(g2)
|
| 197 |
+
g1c = rd.choice(g1)
|
| 198 |
+
encoding = processor(img, f'Is the image of a {g2c}?', return_tensors="pt")
|
| 199 |
+
outputs = model(**encoding)
|
| 200 |
+
logits = outputs.logits
|
| 201 |
+
idx = logits.argmax(-1).item()
|
| 202 |
+
ans = model.config.id2label[idx]
|
| 203 |
+
print("Predicted answer:", model.config.id2label[idx])
|
| 204 |
+
|
| 205 |
+
logitsList = torch.softmax(logits, dim=1).flatten().tolist()
|
| 206 |
+
m = max(logitsList)
|
| 207 |
+
s = -math.inf
|
| 208 |
+
for logit in logitsList:
|
| 209 |
+
if s <= logit < m:
|
| 210 |
+
s = logit
|
| 211 |
+
t = sum(logitsList)
|
| 212 |
+
pm, ps = m/t, s/t
|
| 213 |
+
|
| 214 |
+
if 'yes' in ans:
|
| 215 |
+
avg_probs_imgs2[i] = {'g1': ps, 'g2': pm}
|
| 216 |
+
else:
|
| 217 |
+
avg_probs_imgs2[i] = {'g1': pm, 'g2': ps}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
print(f"avg_probs_imgs1:\n{avg_probs_imgs1}")
|
| 221 |
+
print(f"avg_probs_imgs2:\n{avg_probs_imgs2}")
|
| 222 |
+
return avg_probs_imgs1, avg_probs_imgs2
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def bloombergViz(att, numblocks, score, concept_images, concept_b64s, onRight=False):
|
| 226 |
+
|
| 227 |
+
leftColor = "#065b41" #"#555"
|
| 228 |
+
rightColor = "#35d4ac" #"#999"
|
| 229 |
+
# if flip:
|
| 230 |
+
# leftColor = "#35d4ac" #"#999"
|
| 231 |
+
# rightColor = "#065b41" #"#555"
|
| 232 |
+
|
| 233 |
+
spanClass = "tooltiptext_left"
|
| 234 |
+
if onRight:
|
| 235 |
+
spanClass = "tooltiptext_right"
|
| 236 |
+
|
| 237 |
+
# g1p is indices of score where g1 >= g2
|
| 238 |
+
# g2p is indices of score where g2 < g1
|
| 239 |
+
g1p = []
|
| 240 |
+
g2p = []
|
| 241 |
+
print(f"score: {score}")
|
| 242 |
+
for i in score:
|
| 243 |
+
if score[i]['g1'] >= score[i]['g2']:
|
| 244 |
+
g1p.append(i)
|
| 245 |
+
else:
|
| 246 |
+
g2p.append(i)
|
| 247 |
+
|
| 248 |
+
res = ""
|
| 249 |
+
|
| 250 |
+
for i in g1p:
|
| 251 |
+
disp = concept_b64s[i]
|
| 252 |
+
res += f"<div style='height:20px;width:20px;background-color:{leftColor};display:inline-block;position:relative' id='filled'><span class='{spanClass}' style='color:#FFF'><center><img src='data:image/jpeg;base64,{disp}'></center><br>This image was identified as more likely to depict a group 1 term.</span></div> "
|
| 253 |
+
for i in g2p:
|
| 254 |
+
disp = concept_b64s[i]
|
| 255 |
+
res += f"<div style='height:20px;width:20px;background-color:{rightColor};display:inline-block;position:relative' id='empty'><span class='{spanClass}' style='color:#FFF'><center><img src='data:image/jpeg;base64,{disp}'></center><br>This image was identified as more likely to depict a group 2 term.</span></div> "
|
| 256 |
+
return res
|
| 257 |
+
|
| 258 |
+
def att_bloombergViz(att, numblocks, scores, concept_images, concept_b64s, onRight=False):
|
| 259 |
+
viz = bloombergViz(att, numblocks, scores, concept_images, concept_b64s, onRight)
|
| 260 |
+
attHTML = f"<div style='border-style:solid;border-color:#999;border-radius:12px'>{att}: %<br>{viz}</div><br>"
|
| 261 |
+
return attHTML
|
| 262 |
+
|
| 263 |
+
def retrieveImgs(concept1, concept2, group1, group2, progress=gr.Progress()):
|
| 264 |
+
global MISSING_C, C1_B64s, C2_B64s, C1_PILs, C2_PILs
|
| 265 |
+
print(f"concept1: {concept1}. concept2: {concept2}. group1: {group1}. group2: {group2}")
|
| 266 |
+
print("RETRIEVE IMAGES CLICKED!")
|
| 267 |
+
G_MISSING_SPEC = []
|
| 268 |
+
variants = ["secondary","primary","secondary"]
|
| 269 |
+
inter = [True, True, False]
|
| 270 |
+
tabs = [True, False]
|
| 271 |
+
bias_gen_states = [True, False]
|
| 272 |
+
bias_gen_label = "Generate New Images"
|
| 273 |
+
bias_test_label = "Test Model for Social Bias"
|
| 274 |
+
num2gen_update = gr.update(visible=True) #update the number of new sentences to generate
|
| 275 |
+
prog_vis = [True]
|
| 276 |
+
err_update = updateErrorMsg(False, "")
|
| 277 |
+
info_msg_update = gr.Markdown.update(visible=False, value="")
|
| 278 |
+
openai_gen_row_update = gr.Row.update(visible=True)
|
| 279 |
+
tested_model_dropdown_update = gr.Dropdown.update(visible=False)
|
| 280 |
+
tested_model_row_update = gr.Row.update(visible=False)
|
| 281 |
+
|
| 282 |
+
c1s = concept1.split(',')
|
| 283 |
+
c2s = concept2.split(',')
|
| 284 |
+
c1s = [c1.strip() for c1 in c1s]
|
| 285 |
+
c2s = [c2.strip() for c2 in c2s]
|
| 286 |
+
C1_PILs = []
|
| 287 |
+
C2_PILs = []
|
| 288 |
+
C1_B64s = []
|
| 289 |
+
C2_B64s = []
|
| 290 |
+
|
| 291 |
+
if not c1s or not c2s:
|
| 292 |
+
print("No terms entered!")
|
| 293 |
+
err_update = updateErrorMsg(True, "Please enter terms!")
|
| 294 |
+
variants = ["primary","secondary","secondary"]
|
| 295 |
+
inter = [True, False, False]
|
| 296 |
+
tabs = [True, False]
|
| 297 |
+
prog_vis = [False]
|
| 298 |
+
|
| 299 |
+
else:
|
| 300 |
+
tabs = [False, True]
|
| 301 |
+
progress(0, desc="Fetching saved images...")
|
| 302 |
+
|
| 303 |
+
for c1 in c1s:
|
| 304 |
+
_, retrieved, _ = ds_mgr.getSavedSentences(c1)
|
| 305 |
+
print(f"retrieved: {retrieved}")
|
| 306 |
+
if len(retrieved.index) > 0:
|
| 307 |
+
C1_B64s += list(retrieved['b64'])
|
| 308 |
+
C1_PILs += decode_b64(list(retrieved['b64']))
|
| 309 |
+
print(f"c1_retrieved: {C1_B64s}")
|
| 310 |
+
|
| 311 |
+
for c2 in c2s:
|
| 312 |
+
_, retrieved, _ = ds_mgr.getSavedSentences(c2)
|
| 313 |
+
print(f"retrieved: {retrieved}")
|
| 314 |
+
if len(retrieved.index) > 0:
|
| 315 |
+
C2_B64s += list(retrieved['b64'])
|
| 316 |
+
C2_PILs += decode_b64(list(retrieved['b64']))
|
| 317 |
+
print(f"c2_retrieved: {C2_B64s}")
|
| 318 |
+
|
| 319 |
+
if not C1_PILs or not C2_PILs:
|
| 320 |
+
err_update = updateErrorMsg(True, "No images were found for one or both concepts. Please enter OpenAI key and use Dall-E to generate new test images or change bias specification!")
|
| 321 |
+
if not C1_PILs and not C2_PILs:
|
| 322 |
+
MISSING_C = 0
|
| 323 |
+
elif not C1_PILs:
|
| 324 |
+
MISSING_C = 1
|
| 325 |
+
elif not C2_PILs:
|
| 326 |
+
MISSING_C = 2
|
| 327 |
+
else:
|
| 328 |
+
print('there exist images for both!')
|
| 329 |
+
bias_gen_states = [False, True]
|
| 330 |
+
openai_gen_row_update = gr.Row.update(visible=False)
|
| 331 |
+
tested_model_dropdown_update = gr.Dropdown.update(visible=True)
|
| 332 |
+
tested_model_row_update = gr.Row.update(visible=True)
|
| 333 |
+
print(len(C1_PILs), len(C2_PILs), len(C1_B64s), len(C2_B64s))
|
| 334 |
+
print(f"Will these show up?: {concept1}, {concept2}, {group1}, {group2}")
|
| 335 |
+
print(f"C1_B64s, C1_PILs: {C1_B64s} || {C1_PILs}")
|
| 336 |
+
print(f"C2_B64s, C2_PILs: {C2_B64s} || {C2_PILs}")
|
| 337 |
+
return (
|
| 338 |
+
err_update, # error message
|
| 339 |
+
openai_gen_row_update, # OpenAI generation
|
| 340 |
+
num2gen_update, # Number of images to genrate
|
| 341 |
+
tested_model_row_update, #Tested Model Row
|
| 342 |
+
tested_model_dropdown_update, # Tested Model Dropdown
|
| 343 |
+
info_msg_update, # sentences retrieved info update
|
| 344 |
+
gr.update(visible=prog_vis), # progress bar top
|
| 345 |
+
gr.update(variant=variants[0], interactive=inter[0]), # breadcrumb btn1
|
| 346 |
+
gr.update(variant=variants[1], interactive=inter[1]), # breadcrumb btn2
|
| 347 |
+
gr.update(variant=variants[2], interactive=inter[2]), # breadcrumb btn3
|
| 348 |
+
gr.update(visible=tabs[0]), # tab 1
|
| 349 |
+
gr.update(visible=tabs[1]), # tab 2
|
| 350 |
+
gr.Accordion.update(visible=bias_gen_states[1], label=f"Test images ({len(C1_PILs) + len(C2_PILs)})"), # accordion
|
| 351 |
+
gr.update(visible=True), # Row images
|
| 352 |
+
gr.update(value=C1_PILs+C2_PILs), #test images
|
| 353 |
+
gr.Button.update(visible=bias_gen_states[0], value=bias_gen_label), # gen btn
|
| 354 |
+
gr.Button.update(visible=bias_gen_states[1], value=bias_test_label), # bias test btn
|
| 355 |
+
gr.update(value=concept1), # concept1_fixed
|
| 356 |
+
gr.update(value=concept2), # concept2_fixed
|
| 357 |
+
gr.update(value=group1), # group1_fixed
|
| 358 |
+
gr.update(value=group2) # group2_fixed
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def generateImgs(concept1, concept2, openai_key, num_imgs2gen, progress=gr.Progress()):
|
| 363 |
+
global MISSING_C, C1_B64s, C2_B64s, C1_PILs, C2_PILs
|
| 364 |
+
err_update = updateErrorMsg(False, "")
|
| 365 |
+
bias_test_label = "Test Model Using Imbalanced Images"
|
| 366 |
+
|
| 367 |
+
if MISSING_C == 0:
|
| 368 |
+
bias_gen_states = [True, False]
|
| 369 |
+
online_gen_visible = True
|
| 370 |
+
test_model_visible = False
|
| 371 |
+
elif MISSING_C == 1 or MISSING_C == 2:
|
| 372 |
+
bias_gen_states = [True, True]
|
| 373 |
+
online_gen_visible = True
|
| 374 |
+
test_model_visible = True
|
| 375 |
+
info_msg_update = gr.Markdown.update(visible=False, value="")
|
| 376 |
+
|
| 377 |
+
c1s = concept1.split(',')
|
| 378 |
+
c2s = concept2.split(',')
|
| 379 |
+
C1_PILs = []
|
| 380 |
+
C2_PILs = []
|
| 381 |
+
if not c1s or not c2s:
|
| 382 |
+
print("No terms entered!")
|
| 383 |
+
err_update = updateErrorMsg(True, "Please enter terms!")
|
| 384 |
+
variants = ["primary","secondary","secondary"]
|
| 385 |
+
inter = [True, False, False]
|
| 386 |
+
tabs = [True, False]
|
| 387 |
+
prog_vis = [False]
|
| 388 |
+
else:
|
| 389 |
+
if len(openai_key) == 0:
|
| 390 |
+
print("Empty OpenAI key!!!")
|
| 391 |
+
err_update = updateErrorMsg(True, "Please enter an OpenAI key!")
|
| 392 |
+
elif len(openai_key) < 10:
|
| 393 |
+
print("Wrong length OpenAI key!!!")
|
| 394 |
+
err_update = updateErrorMsg(True, "Please enter a correct OpenAI key!")
|
| 395 |
+
else:
|
| 396 |
+
progress(0, desc="Dall-E generation...")
|
| 397 |
+
C1_PILs = []
|
| 398 |
+
C1_B64s = []
|
| 399 |
+
for c1 in c1s:
|
| 400 |
+
prompt = c1
|
| 401 |
+
PILs, c1_b64s = generate(prompt, openai_key)
|
| 402 |
+
C1_PILs += PILs
|
| 403 |
+
C1_B64s += c1_b64s
|
| 404 |
+
C2_PILs = []
|
| 405 |
+
C2_B64s = []
|
| 406 |
+
for c2 in c2s:
|
| 407 |
+
prompt = c2
|
| 408 |
+
PILs, c2_b64s = generate(prompt, openai_key)
|
| 409 |
+
C2_PILs += PILs
|
| 410 |
+
C2_B64s += c2_b64s
|
| 411 |
+
bias_gen_states = [False, True]
|
| 412 |
+
online_gen_visible = False
|
| 413 |
+
test_model_visible = True
|
| 414 |
+
bias_test_label = "Test Model for Social Bias"
|
| 415 |
+
|
| 416 |
+
return (err_update, # err message if any
|
| 417 |
+
info_msg_update, # infor message about the number of imgs and coverage
|
| 418 |
+
gr.Row.update(visible=online_gen_visible), # online gen row
|
| 419 |
+
gr.Row.update(visible=test_model_visible), # tested model row
|
| 420 |
+
gr.Dropdown.update(visible=test_model_visible), # tested model selection dropdown
|
| 421 |
+
gr.Accordion.update(visible=test_model_visible, label=f"Test images ({len(C1_PILs)+len(C2_PILs)})"), # accordion
|
| 422 |
+
gr.update(visible=True), # Row images
|
| 423 |
+
gr.update(value=C1_PILs+C2_PILs), # test images
|
| 424 |
+
gr.update(visible=bias_gen_states[0]), # gen btn
|
| 425 |
+
gr.update(visible=bias_gen_states[1], value=bias_test_label) # bias btn
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def startBiasTest(test_imgs, concept1, concept2, group1, group2, model_name, progress=gr.Progress()):
|
| 430 |
+
global C1_B64s, C2_B64s, C1_PILs, C2_PILs
|
| 431 |
+
variants = ["secondary","secondary","primary"]
|
| 432 |
+
inter = [True, True, True]
|
| 433 |
+
tabs = [False, False, True]
|
| 434 |
+
err_update = updateErrorMsg(False, "")
|
| 435 |
+
|
| 436 |
+
if len(test_imgs) == 0:
|
| 437 |
+
err_update = updateErrorMsg(True, "There are no images! (How'd you get here?)")
|
| 438 |
+
|
| 439 |
+
progress(0, desc="Starting social bias testing...")
|
| 440 |
+
g1 = group1.split(', ')
|
| 441 |
+
g2 = group2.split(', ')
|
| 442 |
+
avg_probs_imgs1, avg_probs_imgs2 = None, None
|
| 443 |
+
if model_name.lower() == 'clip':
|
| 444 |
+
avg_probs_imgs1, avg_probs_imgs2 = clip(C1_PILs, C2_PILs, g1, g2)
|
| 445 |
+
elif 'vilt' in model_name.lower():
|
| 446 |
+
avg_probs_imgs1, avg_probs_imgs2 = vilt_test(C1_PILs, C2_PILs, g1, g2, vilt_model, vilt_processor)
|
| 447 |
+
else:
|
| 448 |
+
print("that's not right")
|
| 449 |
+
|
| 450 |
+
c1_html = att_bloombergViz(concept1, len(avg_probs_imgs1), avg_probs_imgs1, C1_PILs, C1_B64s, False)
|
| 451 |
+
c2_html = att_bloombergViz(concept2, len(avg_probs_imgs2), avg_probs_imgs2, C2_PILs, C2_B64s, True)
|
| 452 |
+
|
| 453 |
+
model_bias_dict_n = 0.0
|
| 454 |
+
for key in avg_probs_imgs1:
|
| 455 |
+
model_bias_dict_n += avg_probs_imgs1[key]['g1']
|
| 456 |
+
for key in avg_probs_imgs2:
|
| 457 |
+
model_bias_dict_n += avg_probs_imgs2[key]['g2']
|
| 458 |
+
model_bias_dict_d = len(avg_probs_imgs1) + len(avg_probs_imgs2)
|
| 459 |
+
model_bias_dict = {f'bias score for {model_name} on {len(C1_PILs) + len(C2_PILs)} images': round(model_bias_dict_n/model_bias_dict_d, 2)}
|
| 460 |
+
|
| 461 |
+
group_labels_html_update = gr.HTML.update(
|
| 462 |
+
value=f"<div style='height:20px;width:20px;background-color:#065b41;display:inline-block;vertical-align:top'></div><div style='display:inline-block;vertical-align:top'> Image more likely classified as a Group 1 ({group1}) term </div> <div style='height:20px;width:20px;background-color:#35d4ac;display:inline-block;vertical-align:top'></div><div style='display:inline-block;vertical-align:top'> Image more likely classified as a Group 2 ({group2}) term </div>")
|
| 463 |
+
|
| 464 |
+
return (err_update, # error message
|
| 465 |
+
gr.Markdown.update(visible=True), # bar progress
|
| 466 |
+
gr.Button.update(variant=variants[0], interactive=inter[0]), # top breadcrumb button 1
|
| 467 |
+
gr.Button.update(variant=variants[1], interactive=inter[1]), # top breadcrumb button 2
|
| 468 |
+
gr.Button.update(variant=variants[2], interactive=inter[2]), # top breadcrumb button 3
|
| 469 |
+
gr.update(visible=tabs[0]), # content tab/column 1
|
| 470 |
+
gr.update(visible=tabs[1]), # content tab/column 2
|
| 471 |
+
gr.update(visible=tabs[2]), # content tab/column 3
|
| 472 |
+
model_bias_dict, # per model bias score
|
| 473 |
+
gr.update(value=c1_html), # c1 bloomberg viz
|
| 474 |
+
gr.update(value=c2_html), # c2 bloomberg viz
|
| 475 |
+
gr.update(value=concept1), # c1_fixed
|
| 476 |
+
gr.update(value=concept2), # c2_fixed
|
| 477 |
+
gr.update(value=group1), # g1_fixed
|
| 478 |
+
gr.update(value=group2), # g2_fixed
|
| 479 |
+
group_labels_html_update# group_labels_html
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
theme = gr.themes.Soft().set(
|
| 483 |
+
button_small_radius='*radius_xxs',
|
| 484 |
+
background_fill_primary='*neutral_50',
|
| 485 |
+
border_color_primary='*primary_50'
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
soft = gr.themes.Soft(
|
| 489 |
+
primary_hue="slate",
|
| 490 |
+
spacing_size="sm",
|
| 491 |
+
radius_size="md"
|
| 492 |
+
).set(
|
| 493 |
+
# body_background_fill="white",
|
| 494 |
+
button_primary_background_fill='*primary_400'
|
| 495 |
+
)
|
| 496 |
+
css_adds = "#group_row {background: white; border-color: white;} \
|
| 497 |
+
#attribute_row {background: white; border-color: white;} \
|
| 498 |
+
#tested_model_row {background: white; border-color: white;} \
|
| 499 |
+
#button_row {background: white; border-color: white} \
|
| 500 |
+
#examples_elem .label {display: none}\
|
| 501 |
+
#con1_words {border-color: #E5E7EB;} \
|
| 502 |
+
#con2_words {border-color: #E5E7EB;} \
|
| 503 |
+
#grp1_words {border-color: #E5E7EB;} \
|
| 504 |
+
#grp2_words {border-color: #E5E7EB;} \
|
| 505 |
+
#con1_words_fixed {border-color: #E5E7EB;} \
|
| 506 |
+
#con2_words_fixed {border-color: #E5E7EB;} \
|
| 507 |
+
#grp1_words_fixed {border-color: #E5E7EB;} \
|
| 508 |
+
#grp2_words_fixed {border-color: #E5E7EB;} \
|
| 509 |
+
#con1_words_fixed input {box-shadow:None; border-width:0} \
|
| 510 |
+
#con1_words_fixed .scroll-hide {box-shadow:None; border-width:0} \
|
| 511 |
+
#con2_words_fixed input {box-shadow:None; border-width:0} \
|
| 512 |
+
#con2_words_fixed .scroll-hide {box-shadow:None; border-width:0} \
|
| 513 |
+
#grp1_words_fixed input {box-shadow:None; border-width:0} \
|
| 514 |
+
#grp1_words_fixed .scroll-hide {box-shadow:None; border-width:0} \
|
| 515 |
+
#grp2_words_fixed input {box-shadow:None; border-width:0} \
|
| 516 |
+
#grp2_words_fixed .scroll-hide {box-shadow:None; border-width:0} \
|
| 517 |
+
#tested_model_drop {border-color: #E5E7EB;} \
|
| 518 |
+
#gen_model_check {border-color: white;} \
|
| 519 |
+
#gen_model_check .wrap {border-color: white;} \
|
| 520 |
+
#gen_model_check .form {border-color: white;} \
|
| 521 |
+
#open_ai_key_box {border-color: #E5E7EB;} \
|
| 522 |
+
#gen_col {border-color: white;} \
|
| 523 |
+
#gen_col .form {border-color: white;} \
|
| 524 |
+
#res_label {background-color: #F8FAFC;} \
|
| 525 |
+
#per_attrib_label_elem {background-color: #F8FAFC;} \
|
| 526 |
+
#accordion {border-color: #E5E7EB} \
|
| 527 |
+
#err_msg_elem p {color: #FF0000; cursor: pointer} \
|
| 528 |
+
#res_label .bar {background-color: #35d4ac; } \
|
| 529 |
+
#bloomberg_legend {background: white; border-color: white} \
|
| 530 |
+
#bloomberg_att1 {background: white; border-color: white} \
|
| 531 |
+
#bloomberg_att2 {background: white; border-color: white} \
|
| 532 |
+
.tooltiptext_left {visibility: hidden;max-width:50ch;min-width:25ch;top: 100%;left: 0%;background-color: #222;text-align: center;border-radius: 6px;padding: 5px 0;position: absolute;z-index: 1;} \
|
| 533 |
+
.tooltiptext_right {visibility: hidden;max-width:50ch;min-width:25ch;top: 100%;right: 0%;background-color: #222;text-align: center;border-radius: 6px;padding: 5px 0;position: absolute;z-index: 1;} \
|
| 534 |
+
#filled:hover .tooltiptext_left {visibility: visible;} \
|
| 535 |
+
#empty:hover .tooltiptext_left {visibility: visible;} \
|
| 536 |
+
#filled:hover .tooltiptext_right {visibility: visible;} \
|
| 537 |
+
#empty:hover .tooltiptext_right {visibility: visible;}"
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
with gr.Blocks(theme=soft, title="Social Bias Testing in Image-To-Text Models",
|
| 541 |
+
css=css_adds) as iface:
|
| 542 |
+
with gr.Row():
|
| 543 |
+
s1_btn = gr.Button(value="Step 1: Bias Specification", variant="primary", visible=True, interactive=True, size='sm')#.style(size='sm')
|
| 544 |
+
s2_btn = gr.Button(value="Step 2: Test Images", variant="secondary", visible=True, interactive=False, size='sm')#.style(size='sm')
|
| 545 |
+
s3_btn = gr.Button(value="Step 3: Bias Testing", variant="secondary", visible=True, interactive=False, size='sm')#.style(size='sm')
|
| 546 |
+
err_message = gr.Markdown("", visible=False, elem_id="err_msg_elem")
|
| 547 |
+
bar_progress = gr.Markdown(" ")
|
| 548 |
+
|
| 549 |
+
# Page 1
|
| 550 |
+
with gr.Column(visible=True) as tab1:
|
| 551 |
+
with gr.Column():
|
| 552 |
+
gr.Markdown("#### Enter concepts to generate") # #group_row
|
| 553 |
+
with gr.Row(elem_id ="generation_row"):
|
| 554 |
+
concept1 = gr.Textbox(label="Image Generation Concept 1", max_lines=1, elem_id="con1_words", elem_classes="input_words", placeholder="ceo, executive")
|
| 555 |
+
concept2 = gr.Textbox(label="Image Generation Concept 2", max_lines=1, elem_id="con2_words", elem_classes="input_words", placeholder="nurse, janitor")
|
| 556 |
+
gr.Markdown("#### Enter concepts to test") # #attribute_row
|
| 557 |
+
with gr.Row(elem_id="group_row"):
|
| 558 |
+
group1 = gr.Textbox(label="Text Caption Concept 1", max_lines=1, elem_id="grp1_words", elem_classes="input_words", placeholder="brother, father")
|
| 559 |
+
group2 = gr.Textbox(label="Text Caption Concept 2", max_lines=1, elem_id="grp2_words", elem_classes="input_words", placeholder="sister, mother")
|
| 560 |
+
with gr.Row():
|
| 561 |
+
gr.Markdown(" ")
|
| 562 |
+
get_sent_btn = gr.Button(value="Get Images", variant="primary", visible=True)
|
| 563 |
+
gr.Markdown(" ")
|
| 564 |
+
|
| 565 |
+
# Page 2
|
| 566 |
+
with gr.Column(visible=False) as tab2:
|
| 567 |
+
info_imgs_found = gr.Markdown(value="", visible=False) # info_sentences_found
|
| 568 |
+
|
| 569 |
+
gr.Markdown("### Tested Social Bias Specification", visible=True)
|
| 570 |
+
with gr.Row():
|
| 571 |
+
concept1_fixed = gr.Textbox(label="Image Generation Concept 1", max_lines=1, elem_id="con1_words_fixed", elem_classes="input_words", interactive=False, visible=True) # group1_words_fixed
|
| 572 |
+
concept2_fixed = gr.Textbox(label='Image Generation Concept 2', max_lines=1, elem_id="con2_words_fixed", elem_classes="input_words", interactive=False, visible=True) # group2_fixed
|
| 573 |
+
with gr.Row():
|
| 574 |
+
group1_fixed = gr.Textbox(label='Text Caption Concept 1', max_lines=1, elem_id="grp1_words_fixed", elem_classes="input_words", interactive=False, visible=True) # att1_words_fixed
|
| 575 |
+
group2_fixed = gr.Textbox(label='Text Caption Concept 2', max_lines=1, elem_id="grp2_words_fixed", elem_classes="input_words", interactive=False, visible=True) # att2_fixed
|
| 576 |
+
|
| 577 |
+
with gr.Row():
|
| 578 |
+
with gr.Column():
|
| 579 |
+
with gr.Row(visible=False) as online_gen_row:
|
| 580 |
+
with gr.Column():
|
| 581 |
+
gen_title = gr.Markdown("### Generate Additional Images", visible=True)
|
| 582 |
+
|
| 583 |
+
# OpenAI Key for generator
|
| 584 |
+
openai_key = gr.Textbox(lines=1, label="OpenAI API Key", value=None,
|
| 585 |
+
placeholder="starts with sk-",
|
| 586 |
+
info="Please provide the key for an Open AI account to generate new test images",
|
| 587 |
+
visible=True,
|
| 588 |
+
interactive=True,
|
| 589 |
+
elem_id="open_ai_key_box")
|
| 590 |
+
num_imgs2gen = gr.Slider(2, 20, value=2, step=1,
|
| 591 |
+
interactive=True,
|
| 592 |
+
visible=True,
|
| 593 |
+
container=True)
|
| 594 |
+
|
| 595 |
+
with gr.Row(visible=False) as tested_model_row:
|
| 596 |
+
with gr.Column():
|
| 597 |
+
gen_title = gr.Markdown("### Select Tested Model", visible=True)
|
| 598 |
+
|
| 599 |
+
tested_model_name = gr.Dropdown(["CLIP", "ViLT"], value="CLIP",
|
| 600 |
+
multiselect=None,
|
| 601 |
+
interactive=True,
|
| 602 |
+
label="Tested model",
|
| 603 |
+
elem_id="tested_model_drop",
|
| 604 |
+
visible=True
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
with gr.Row():
|
| 608 |
+
gr.Markdown(" ")
|
| 609 |
+
gen_btn = gr.Button(value="Generate New Images", variant="primary", visible=True)
|
| 610 |
+
bias_btn = gr.Button(value="Test Model for Social Bias", variant="primary", visible=False)
|
| 611 |
+
gr.Markdown(" ")
|
| 612 |
+
|
| 613 |
+
with gr.Row(visible=False) as row_imgs: # row_sentences
|
| 614 |
+
with gr.Accordion(label="Test Images", open=False, visible=False) as acc_test_imgs: # acc_test_sentences
|
| 615 |
+
test_imgs = gr.Gallery(show_label=False) # test_sentences, output
|
| 616 |
+
|
| 617 |
+
# Page 3
|
| 618 |
+
with gr.Column(visible=False) as tab3:
|
| 619 |
+
gr.Markdown("### Tested Social Bias Specification", visible=True)
|
| 620 |
+
with gr.Row():
|
| 621 |
+
concept1_fixed2 = gr.Textbox(label="Image Generation Concept 1", max_lines=1, elem_id="con1_words_fixed", elem_classes="input_words", interactive=False) # group1_words_fixed
|
| 622 |
+
concept2_fixed2 = gr.Textbox(label='Image Generation Concept 2', max_lines=1, elem_id="con2_words_fixed", elem_classes="input_words", interactive=False) # group2_fixed
|
| 623 |
+
with gr.Row():
|
| 624 |
+
group1_fixed2 = gr.Textbox(label='Text Caption Concept 1', max_lines=1, elem_id="grp1_words_fixed", elem_classes="input_words", interactive=False) # att1_words_fixed
|
| 625 |
+
group2_fixed2 = gr.Textbox(label='Text Caption Concept 2', max_lines=1, elem_id="grp2_words_fixed", elem_classes="input_words", interactive=False) # att2_fixed
|
| 626 |
+
|
| 627 |
+
with gr.Row():
|
| 628 |
+
with gr.Column(scale=2):
|
| 629 |
+
gr.Markdown("### Bias Test Results")
|
| 630 |
+
with gr.Row():
|
| 631 |
+
with gr.Column(scale=2):
|
| 632 |
+
lbl_model_bias = gr.Markdown("**Model Bias** - % stereotyped choices (↑ more bias)")
|
| 633 |
+
model_bias_label = gr.Label(num_top_classes=1, label="% stereotyped choices (↑ more bias)",
|
| 634 |
+
elem_id="res_label",
|
| 635 |
+
show_label=False)
|
| 636 |
+
|
| 637 |
+
with gr.Row():
|
| 638 |
+
with gr.Column(variant="compact", elem_id="bloomberg_legend"):
|
| 639 |
+
group_labels_html = gr.HTML(value="<div style='height:20px;width:20px;background-color:#065b41;display:inline-block;vertical-align:top'></div><div style='display:inline-block;vertical-align:top'> Social group 1 more probable in the image </div> <div style='height:20px;width:20px;background-color:#35d4ac;display:inline-block;vertical-align:top'></div><div style='display:inline-block;vertical-align:top'> Social group 2 more probable in the image </div>")
|
| 640 |
+
|
| 641 |
+
with gr.Row():
|
| 642 |
+
with gr.Column(variant="compact", elem_id="bloomberg_att1"):
|
| 643 |
+
gr.Markdown("#### Text Caption Concept Probability for Image Generation Concept 1")
|
| 644 |
+
c1_results = gr.HTML()
|
| 645 |
+
with gr.Column(variant="compact", elem_id="bloomberg_att2"):
|
| 646 |
+
gr.Markdown("#### Text Caption Concept Probability for Image Generation Concept 2")
|
| 647 |
+
c2_results = gr.HTML()
|
| 648 |
+
|
| 649 |
+
gr.HTML(value="Visualization inspired by <a href='https://www.bloomberg.com/graphics/2023-generative-ai-bias/' target='_blank'>Bloomberg article on bias in text-to-image models</a>.")
|
| 650 |
+
save_msg = gr.HTML(value="<span style=\"color:black\">Bias test result saved! </span>", visible=False)
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
with gr.Row():
|
| 654 |
+
with gr.Column():
|
| 655 |
+
with gr.Row():
|
| 656 |
+
gr.Markdown(" ")
|
| 657 |
+
with gr.Column():
|
| 658 |
+
new_bias_button = gr.Button("Try New Bias Test", variant="primary")
|
| 659 |
+
gr.Markdown(" ")
|
| 660 |
+
|
| 661 |
+
# Get sentences
|
| 662 |
+
get_sent_btn.click(fn=retrieveImgs, #retrieveSentences
|
| 663 |
+
inputs=[concept1, concept2, group1, group2],
|
| 664 |
+
outputs=[err_message, online_gen_row, num_imgs2gen, tested_model_row, tested_model_name, info_imgs_found, bar_progress, s1_btn, s2_btn, s3_btn, tab1, tab2, acc_test_imgs, row_imgs, test_imgs, gen_btn, bias_btn,
|
| 665 |
+
concept1_fixed, concept2_fixed, group1_fixed, group2_fixed ]
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
# request getting sentences
|
| 669 |
+
gen_btn.click(fn=generateImgs, #generateSentences
|
| 670 |
+
inputs=[concept1, concept2, openai_key, num_imgs2gen],
|
| 671 |
+
outputs=[err_message, info_imgs_found, online_gen_row,
|
| 672 |
+
tested_model_row, tested_model_name, acc_test_imgs, row_imgs, test_imgs, gen_btn, bias_btn ]
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
# Test bias
|
| 676 |
+
bias_btn.click(fn=startBiasTest,
|
| 677 |
+
inputs=[test_imgs, concept1, concept2, group1, group2, tested_model_name],
|
| 678 |
+
outputs=[err_message, bar_progress, s1_btn, s2_btn, s3_btn, tab1, tab2, tab3, model_bias_label,
|
| 679 |
+
c1_results, c2_results, concept1_fixed2, concept2_fixed2, group1_fixed2, group2_fixed2,
|
| 680 |
+
group_labels_html]
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
# top breadcrumbs
|
| 684 |
+
s1_btn.click(fn=moveStep1,
|
| 685 |
+
inputs=[],
|
| 686 |
+
outputs=[s1_btn, s2_btn, s3_btn, tab1, tab2, tab3])
|
| 687 |
+
|
| 688 |
+
# top breadcrumbs
|
| 689 |
+
s2_btn.click(fn=moveStep2,
|
| 690 |
+
inputs=[],
|
| 691 |
+
outputs=[s1_btn, s2_btn, s3_btn, tab1, tab2, tab3])
|
| 692 |
+
|
| 693 |
+
# top breadcrumbs
|
| 694 |
+
s3_btn.click(fn=moveStep3,
|
| 695 |
+
inputs=[],
|
| 696 |
+
outputs=[s1_btn, s2_btn, s3_btn, tab1, tab2, tab3])
|
| 697 |
+
|
| 698 |
+
new_bias_button.click(fn=moveStep1_clear,
|
| 699 |
+
inputs=[],
|
| 700 |
+
outputs=[s1_btn, s2_btn, s3_btn, tab1, tab2, tab3, concept1, concept2, group1, group2])
|
| 701 |
+
|
| 702 |
+
iface.queue(concurrency_count=2).launch()
|