Gregor commited on
Commit
0ebc51e
1 Parent(s): 843a1b9

Upload 7 files

Browse files
app.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path
2
+
3
+ import gradio as gr
4
+ import json
5
+
6
+ import numpy.random
7
+ import open_clip
8
+ from PIL import Image
9
+ import requests
10
+ import torch
11
+ # import torch.nn.functional as F
12
+ import numpy as np
13
+
14
+
15
+ # GLOBAL VARIABLES
16
+ openai_en_classes = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "green iguana", "Carolina anole", "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", "American alligator", "triceratops", "worm snake", "ring-necked snake", "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", "freight car", "French horn", "frying pan", "fur coat", "garbage truck", "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"]
17
+ # main_languages = ['EN'] + sorted(["WUU", "NV", "CV", "DIQ", "CHR", "CE", "HAK", "NAH", 'NE', 'ID', 'DE', 'NL', 'AF', 'HE', 'SQ', 'UZ', 'KN', 'KU', 'TA', 'LV', 'KO', 'UG', 'BR', 'EL', 'SU', 'KK', 'SK', 'GL', 'OM', 'FA', 'JV', 'CS', 'LO', 'HY', 'XH', 'HR', 'SO', 'GU', 'AM', 'AR', 'SA', 'CA', 'IS', 'IT', 'SV', 'GA', 'BG', 'VI', 'SD', 'UR', 'KM', 'PL', 'HU', 'SR', 'FR', 'HI', 'FY', 'ET', 'BS', 'SW', 'AZ', 'MK', 'ES', 'MN', 'JA', 'TL', 'TR', 'GD', 'RO', 'MG', 'MR', 'SL', 'PT', 'LT', 'NO', 'YI', 'UK', 'KY', 'KA', 'BN', 'OR', 'MY', 'PS', 'FI', 'ZH', 'DA', 'ML', 'BE', 'EO', 'HA', 'EU', 'AS', 'TE', 'TH', 'CY', 'SI', 'RU', 'LA', 'PA', 'MS'])
18
+ language_names = json.load(open("data/language_mapping.json", encoding="utf-8"))
19
+ main_language_values = sorted([[name, code] for code, name in language_names.items()], key=lambda x: x[0])
20
+ # [[main_language_names[lang], lang] for lang in main_languages+sorted(l for l in main_language_names if l not in main_languages)]
21
+
22
+ babel_imagenet = json.load(open("data/babel_imagenet-298.json", encoding="utf-8"))
23
+ babelnet_images = json.load(open("data/images.json", encoding="utf-8"))
24
+ no_image_idxs = [i for i, imgs in enumerate(babelnet_images) if len(imgs) == 0]
25
+ IMG_HEIGHT, IMG_WIDTH = 512, 512
26
+
27
+ precomputed_results = None
28
+ if os.path.exists("data/precomputed_results.json"):
29
+ precomputed_results = json.load(open("data/precomputed_results.json"))
30
+
31
+ request_header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'}
32
+ ### Loading model; hard-coded to mSigLIP for now.
33
+
34
+ if not precomputed_results:
35
+ open_clip_model, open_clip_pretrained = "ViT-B-16-SigLIP-i18n-256", "webli"
36
+ model, _, transform = open_clip.create_model_and_transforms(open_clip_model, pretrained=open_clip_pretrained)
37
+ tokenizer = open_clip.get_tokenizer(open_clip_model)
38
+
39
+ device = "cuda" if torch.cuda.is_available() else "cpu"
40
+ model = model.to(device)
41
+
42
+ def change_language(lang, randomize_imgs, randomize_labels):
43
+ # compute text embeddings
44
+ labels = babel_imagenet[lang][1]
45
+ class_order = list(range(len(labels)))
46
+ if randomize_labels:
47
+ np.random.shuffle(class_order)
48
+ ### We use no prompt ensembling for now
49
+ if not precomputed_results:
50
+ text_tokens = tokenizer(labels).to(device)
51
+ with torch.no_grad():
52
+ text_features = model.encode_text(text_tokens).float()
53
+ text_features /= text_features.norm(dim=-1, keepdim=True)
54
+ text_features = text_features.cpu().numpy()
55
+ else:
56
+ text_features = None
57
+ correct_text = gr.Text(f"Correct was: ''. Question 1/{len(babel_imagenet[lang][0])} ", label="Game")
58
+ player_score_text = gr.Text(f"Your choice: (Score: 0) ", label="Player")
59
+ clip_score_text = gr.Text(f"CLIP chose: '' (Score: 0)", label="CLIP")
60
+
61
+ return text_features, -1, class_order, correct_text, player_score_text, clip_score_text, 0, 0
62
+
63
+ def select(idx, lang, choice, correct, model_choice, player_score, clip_score):
64
+ # checks if answer choice is correct and updated scores
65
+ correct_name, correct_value = correct
66
+ model_choice_name, model_choice_value = model_choice
67
+
68
+ player_correct = choice == correct_value
69
+ model_correct = model_choice_value == correct_value
70
+
71
+ player_score = player_score + int(player_correct)
72
+ clip_score = clip_score + int(model_correct)
73
+
74
+ correct_text = gr.Text(f"Correct was: '{correct_name}'. Question {idx+1}/{len(babel_imagenet[lang][0])} ", label="Game")
75
+ player_score_text = gr.Text(f"Your choice: {'✅' if player_correct else '❌'} (Score: {player_score}) ", label="Player")
76
+ clip_score_text = gr.Text(f"CLIP chose: '{model_choice_name}' {'✅' if model_correct else '❌'} (Score: {clip_score})", label="CLIP")
77
+
78
+ return correct_text, player_score_text, clip_score_text, player_score, clip_score
79
+
80
+ def prepare(raw_idx, lang, text_embeddings, class_order, randomize_images):
81
+ # prepared next question, loads image, and computes choices
82
+
83
+ raw_idx = (raw_idx+1) % len(babel_imagenet[lang][0])
84
+ idx = class_order[raw_idx]
85
+ lang_class_idxs = babel_imagenet[lang][0]
86
+ class_idx = lang_class_idxs[idx]
87
+
88
+ # skip classes with no images
89
+ while class_idx in no_image_idxs:
90
+ raw_idx = (raw_idx + 1) % len(babel_imagenet[lang][0])
91
+ idx = class_order[raw_idx]
92
+ lang_class_idxs = babel_imagenet[lang][0] if lang != "EN" else list(range(1000))
93
+ class_idx = lang_class_idxs[idx]
94
+
95
+ img_idx = 0
96
+ if randomize_images:
97
+ img_idx = np.random.choice(len(babelnet_images[class_idx]))
98
+ img_url = babelnet_images[class_idx][img_idx]["url"]
99
+ class_labels = babel_imagenet[lang][1] if lang != "EN" else openai_en_classes
100
+
101
+ if not precomputed_results:
102
+ try:
103
+ image_input = transform(Image.open(requests.get(img_url, stream=True, headers=request_header).raw).convert("RGB")).unsqueeze(0).to(device)
104
+ with torch.no_grad():
105
+ image_features = model.encode_image(image_input).float()
106
+ image_features /= image_features.norm(dim=-1, keepdim=True)
107
+ except:
108
+ gr.Warning("There is a problem with the next class. Skipping it.")
109
+ return prepare(raw_idx, lang, text_embeddings, class_order, randomize_images)
110
+
111
+ similarity = (text_embeddings @ image_features.cpu().numpy().T).squeeze()
112
+ choices = np.argsort(similarity)[-4:].tolist()
113
+ else:
114
+ choices = list(reversed(precomputed_results[lang][idx][img_idx])) # precomputing script uses torch.topk which sorts in reverse here
115
+ if idx not in choices:
116
+ choices = [idx] + choices[1:]
117
+ model_choice_idx = choices[-1]
118
+
119
+ numpy.random.shuffle(choices)
120
+
121
+ choice_names = [class_labels[idx] for idx in choices]
122
+ choice_values = [0, 1, 2, 3]
123
+
124
+ model_choice_idx = choices.index(model_choice_idx)
125
+ model_choice = [choice_names[model_choice_idx], choice_values[model_choice_idx]]
126
+ correct_choice_idx = choices.index(idx)
127
+ correct_choice = [choice_names[correct_choice_idx], choice_values[correct_choice_idx]]
128
+
129
+ choice_values = list(zip(choice_names, choice_values))
130
+
131
+ next_radio = gr.Radio(choices=choice_values, interactive=True, label="Select the correct answer:", value=None)
132
+ next_image = gr.Image(value=img_url, width=IMG_WIDTH, height=IMG_WIDTH, label="What class does this image belong to?")
133
+
134
+ return next_radio, next_image, raw_idx, correct_choice, model_choice
135
+
136
+
137
+
138
+ with (gr.Blocks(title="Babel-ImageNet Quiz") as demo):
139
+
140
+ # setup state
141
+ class_idx = gr.State(-1)
142
+ player_score = gr.State(0)
143
+ clip_score = gr.State(0)
144
+ class_order = gr.State([])
145
+
146
+ text_embeddings = gr.State(None)
147
+ correct_choice = gr.State(["nan", 0]) # 0, 1, 2, 3
148
+ model_choice = gr.State(["nan", 0])
149
+
150
+ # Title Area
151
+ gr.Markdown("""
152
+ # Are you smarter🤓 than CLIP🤖? Take the [ Babel-ImageNet ](https://arxiv.org/abs/2306.08658) Quiz!
153
+
154
+ <small>by Gregor Geigle, WüNLP & Computer Vision Lab, University of Würzburg</small>
155
+
156
+ In this quiz, you play against a CLIP model and try to correctly classify the images over the 1000 ImageNet classes (in English) or over our (partial) Babel-ImageNet translations of those classes.
157
+ Select your language, click 'Start' and start guessing! We'll keep track of your score and of your opponent's.
158
+ > **Disclaimer:** Translations and images are derived automatically and can be wrong, unusual, or mismatch! This is supposed to be a fun game to explore the dataset and see how a CLIP model would answer the questions and not a product.
159
+ > We do *not* use the official ImageNet images. Instead, we use images linked in BabelNet for each class, which are often from Wikipedia and have not been checked for suitability.
160
+
161
+ > **Content Warning:** There are spiders, insects, and various animals under the images. Please take caution if those might scare you.
162
+
163
+ <details>
164
+ <summary> <b> FAQ</b> (click me to read)</summary>
165
+ <p><b>'Over 1000 classes? I just see 4.'</b> True, you have it easier and you only have to chose between 4 classes. These are the top-4 picks of your opponent (+ the correct class if they are wrong). Your opponent has it harder: they have to deal with all classes.</p>
166
+ <p><b>'Who is my opponent?'</b> Your opponent CLIP model is [mSigLIP](https://huggingface.co/timm/ViT-B-16-SigLIP-i18n-256), a powerful but small multilingual model with only 370M parameters.</p>
167
+ <p><b>'My game crashed/ I got an error!'</b> This usually happens because of problems with the image URLs. Unfortunately, there is nothing you can do except start a new round by clicking the 'Start' button.</p>
168
+ </details>
169
+ """)
170
+ with gr.Row():
171
+ with gr.Column(scale=1):
172
+ gr.Markdown("""
173
+ <details>
174
+ <summary> <b>What is CLIP? </b> (click me to read)</summary>
175
+ <p>
176
+ <a href='https://arxiv.org/abs/2103.00020'>CLIP</a> are vision-language models that learn to encode images and text in a joint semantic embedding space, where related concepts are close together.
177
+ With CLIP, you can search through, filter, or group large image datasets. The image encoder in CLIP also powers many of the large vision language models like Llava 1.5!
178
+ </p>
179
+ <p>
180
+ Your opponent CLIP model in this quiz does 'zero-shot image classification': We encode all possible class labels and the image and we check which class is most similar; this is then the class chosen by CLIP.
181
+ </p>
182
+ </details>
183
+ """)
184
+ with gr.Column(scale=1):
185
+ gr.Markdown("""
186
+ <details>
187
+ <summary> <b>What is ImageNet? </b> (click me to read)</summary>
188
+ <p>
189
+ ImageNet is a challenging image classification dataset with 1000 diverse classes covering animals, plants, human-made objects and more.
190
+ It is a very popular dataset used to benchmark CLIP models because strong results here usually indicates that the image model is overall usefull for many tasks.
191
+ </p>
192
+ </details>
193
+ """)
194
+ with gr.Column(scale=1):
195
+ gr.Markdown("""
196
+ <details>
197
+ <summary> <b>What is Babel-ImageNet? </b> (click me to read)</summary>
198
+ <p>
199
+ ImageNet class labels are only in English but we want to use CLIP models also in other languages. How can we know how good a CLIP model is outside of English?
200
+ This is the goal of Babel-ImageNet: to translate the English labels to other languages. However, automatic translation can give bad results for many languages and human translation is expensive.
201
+ </p>
202
+ <p>
203
+ Instead, we use the fact that ImageNet was constructed using WordNet and WordNet in turn can be linked to the multilingual resource BabelNet.
204
+ Using this link, we can get reliable (partial) translations of the English labels.
205
+ For more details, please read our <a href='https://arxiv.org/abs/2306.08658'>paper.</a>
206
+ </p>
207
+ </details>
208
+ """)
209
+ # language select dropdown
210
+ with gr.Row():
211
+ language_select = gr.Dropdown(choices=main_language_values, value="EN", interactive=True, label="Select your language:")
212
+ randomize_classes = gr.Checkbox(label="Randomize class order (or play in canonic order)")
213
+ randomize_images = gr.Checkbox(label="Randomize images (if unchecked, will always show the same image). Other images might be less relevant.")
214
+ start_btn = gr.Button(value="Start", variant="primary")
215
+
216
+ # quiz area
217
+ with gr.Row():
218
+ with gr.Column(scale=1):
219
+ image = gr.Image(value="data/bin_image.png",
220
+ width=IMG_WIDTH, height=IMG_WIDTH)
221
+
222
+ with gr.Column(scale=1):
223
+ options = gr.Radio(choices=["Click", "start", "to", "begin"], interactive=False, label="Please click start to begin.")
224
+ # with gr.Row():
225
+ correct_text = gr.Text("Please click start to begin.")
226
+ player_score_text = gr.Text(f"Player score: 0")
227
+ clip_score_text = gr.Text(f"CLIP score: 0")
228
+
229
+
230
+ # Explanation area
231
+
232
+
233
+
234
+ options.select(fn=select,
235
+ inputs=[class_idx, language_select, options, correct_choice, model_choice, player_score, clip_score],
236
+ outputs=[correct_text, player_score_text, clip_score_text, player_score, clip_score]
237
+ ).then(fn=prepare,
238
+ inputs=[class_idx, language_select, text_embeddings, class_order, randomize_images],
239
+ outputs=[options, image, class_idx, correct_choice, model_choice])
240
+
241
+ start_btn.click(fn=change_language,
242
+ inputs=[language_select, randomize_images, randomize_classes],
243
+ outputs=[text_embeddings, class_idx, class_order, correct_text, player_score_text, clip_score_text, player_score, clip_score]
244
+ ).then(fn=prepare,
245
+ inputs=[class_idx, language_select, text_embeddings, class_order, randomize_images],
246
+ outputs=[options, image, class_idx, correct_choice, model_choice])
247
+
248
+ # initialization
249
+ # demo.load(fn=change_language,
250
+ # inputs=[language_select],
251
+ # outputs=[text_embeddings, class_idx, correct_text, player_score_text, clip_score_text, player_score, clip_score]
252
+ # ).then(fn=prepare,
253
+ # inputs=[class_idx, language_select, text_embeddings],
254
+ # outputs=[options, image, class_idx, correct_choice, model_choice])
255
+
256
+
257
+
258
+ demo.launch()
data/babel_imagenet-298.json ADDED
The diff for this file is too large to render. See raw diff
 
data/bin_image.png ADDED
data/images.json ADDED
The diff for this file is too large to render. See raw diff
 
data/language_mapping.json ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "AB": "Abkhazian",
3
+ "ACW": "Hijazi Arabic",
4
+ "ADY": "Adyghe",
5
+ "AF": "Afrikaans",
6
+ "AFB": "Gulf Arabic",
7
+ "AII": "Assyrian Neo-Aramaic",
8
+ "AK": "Akan",
9
+ "ALS": "Alemannic",
10
+ "ALT": "Southern Altai",
11
+ "AM": "Amharic",
12
+ "AN": "Aragonese",
13
+ "ANG": "Anglo-Saxon",
14
+ "AR": "Arabic",
15
+ "ARC": "Aramaic",
16
+ "ARY": "Moroccan Arabic",
17
+ "ARZ": "Egyptian Arabic",
18
+ "AS": "Assamese",
19
+ "AST": "Asturian",
20
+ "AV": "Avar",
21
+ "AY": "Aymara",
22
+ "AZ": "Azerbaijani",
23
+ "AZB": "South Azerbaijani",
24
+ "BA": "Bashkir",
25
+ "BAN": "Balinese",
26
+ "BAR": "Bavarian",
27
+ "BAT_SMG": "Samogitian",
28
+ "BCL": "Central Bicolano",
29
+ "BE": "Belarusian",
30
+ "BE_X_OLD": "Belarusian (Tara\u0161kievica)",
31
+ "BG": "Bulgarian",
32
+ "BH": "Bihari",
33
+ "BHO": "Bhojpuri",
34
+ "BJN": "Banjar",
35
+ "BM": "Bambara",
36
+ "BN": "Bengali",
37
+ "BO": "Tibetan",
38
+ "BR": "Breton",
39
+ "BS": "Bosnian",
40
+ "BXR": "Buryat (Russia)",
41
+ "CA": "Catalan",
42
+ "CCC": "Chamicuro",
43
+ "CDO": "Min Dong",
44
+ "CE": "Chechen",
45
+ "CEB": "Cebuano",
46
+ "CHR": "Cherokee",
47
+ "CHY": "Cheyenne",
48
+ "CKB": "Sorani",
49
+ "CO": "Corsican",
50
+ "CR": "Cree",
51
+ "CRH": "Crimean Tatar",
52
+ "CS": "Czech",
53
+ "CSB": "Kashubian",
54
+ "CU": "Old Church Slavonic",
55
+ "CV": "Chuvash",
56
+ "CY": "Welsh",
57
+ "DA": "Danish",
58
+ "DE": "German",
59
+ "DIN": "Dinka",
60
+ "DIQ": "Zazaki",
61
+ "DLM": "Dalmatian",
62
+ "DNG": "Dungan",
63
+ "DSB": "Lower Sorbian",
64
+ "DV": "Divehi",
65
+ "DZ": "Dzongkha",
66
+ "EE": "Ewe",
67
+ "EL": "Greek",
68
+ "EML": "Emilian-Romagnol",
69
+ "EN": "English",
70
+ "ENM": "Middle English",
71
+ "EO": "Esperanto",
72
+ "ES": "Spanish",
73
+ "ET": "Estonian",
74
+ "EU": "Basque",
75
+ "EXT": "Extremaduran",
76
+ "FA": "Persian",
77
+ "FI": "Finnish",
78
+ "FIU_VRO": "V\u00f5ro",
79
+ "FJ": "Fijian",
80
+ "FO": "Faroese",
81
+ "FR": "French",
82
+ "FRO": "Old French",
83
+ "FRP": "Franco-Proven\u00e7al/Arpitan",
84
+ "FRR": "North Frisian",
85
+ "FUR": "Friulian",
86
+ "FY": "West Frisian",
87
+ "GA": "Irish",
88
+ "GAN": "Gan",
89
+ "GD": "Scottish Gaelic",
90
+ "GL": "Galician",
91
+ "GMQ_BOT": "Westrobothnian",
92
+ "GN": "Guarani",
93
+ "GOT": "Gothic",
94
+ "GRC": "Ancient Greek",
95
+ "GU": "Gujarati",
96
+ "GV": "Manx",
97
+ "HA": "Hausa",
98
+ "HAK": "Hakka",
99
+ "HAW": "Hawaiian",
100
+ "HE": "Hebrew",
101
+ "HI": "Hindi",
102
+ "HR": "Croatian",
103
+ "HRX": "Hunsrik",
104
+ "HSB": "Upper Sorbian",
105
+ "HT": "Haitian",
106
+ "HU": "Hungarian",
107
+ "HY": "Armenian",
108
+ "IA": "Interlingua",
109
+ "ID": "Indonesian",
110
+ "IG": "Igbo",
111
+ "IK": "Inupiak",
112
+ "ILO": "Ilokano",
113
+ "INH": "Ingush",
114
+ "IO": "Ido",
115
+ "IS": "Icelandic",
116
+ "IT": "Italian",
117
+ "IU": "Inuktitut",
118
+ "JA": "Japanese",
119
+ "JAM": "Patois",
120
+ "JBO": "Lojban",
121
+ "JV": "Javanese",
122
+ "KA": "Georgian",
123
+ "KAA": "Karakalpak",
124
+ "KAB": "Kabyle",
125
+ "KBD": "Kabardian Circassian",
126
+ "KG": "Kongo",
127
+ "KHB": "L\u00fc",
128
+ "KI": "Kikuyu",
129
+ "KK": "Kazakh",
130
+ "KL": "Greenlandic",
131
+ "KM": "Khmer",
132
+ "KMR": "Northern Kurdish",
133
+ "KN": "Kannada",
134
+ "KO": "Korean",
135
+ "KOI": "Komi-Permyak",
136
+ "KRC": "Karachay-Balkar",
137
+ "KS": "Kashmiri",
138
+ "KSH": "Ripuarian",
139
+ "KU": "Kurdish",
140
+ "KUM": "Kumyk",
141
+ "KV": "Komi",
142
+ "KW": "Cornish",
143
+ "KXD": "Brunei Malay",
144
+ "KY": "Kirghiz",
145
+ "LA": "Latin",
146
+ "LAD": "Ladino",
147
+ "LB": "Luxembourgish",
148
+ "LBE": "Lak",
149
+ "LEZ": "Lezgian",
150
+ "LG": "Luganda",
151
+ "LI": "Limburgish",
152
+ "LIJ": "Ligurian",
153
+ "LMO": "Lombard",
154
+ "LN": "Lingala",
155
+ "LO": "Lao",
156
+ "LT": "Lithuanian",
157
+ "LTG": "Latgalian",
158
+ "LV": "Latvian",
159
+ "LZZ": "Laz",
160
+ "MAI": "Maithili",
161
+ "MDF": "Moksha",
162
+ "MEL": "Central Melanau",
163
+ "MG": "Malagasy",
164
+ "MHR": "Meadow Mari",
165
+ "MI": "Maori",
166
+ "MIC": "Mi'kmaq",
167
+ "MIN": "Minangkabau",
168
+ "MK": "Macedonian",
169
+ "ML": "Malayalam",
170
+ "MN": "Mongolian",
171
+ "MNC": "Manchu",
172
+ "MNW": "Mon",
173
+ "MR": "Marathi",
174
+ "MRJ": "Hill Mari",
175
+ "MS": "Malay",
176
+ "MT": "Maltese",
177
+ "MWL": "Mirandese",
178
+ "MY": "Burmese",
179
+ "MYV": "Erzya",
180
+ "MZN": "Mazandarani",
181
+ "NAH": "Nahuatl",
182
+ "NAP": "Neapolitan",
183
+ "NCI": "Classical Nahuatl",
184
+ "NDS": "Low Saxon",
185
+ "NDS_NL": "Dutch Low Saxon",
186
+ "NE": "Nepali",
187
+ "NEW": "Newar / Nepal Bhasa",
188
+ "NL": "Dutch",
189
+ "NN": "Norwegian (Nynorsk)",
190
+ "NO": "Norwegian (Bokm\u00e5l)",
191
+ "NOG": "Nogai",
192
+ "NON": "Old Norse",
193
+ "NOV": "Novial",
194
+ "NRM": "Norman",
195
+ "NSO": "Northern Sotho",
196
+ "NV": "Navajo",
197
+ "NY": "Chichewa",
198
+ "OC": "Occitan",
199
+ "OJ": "Ojibwe",
200
+ "OLO": "Livvinkarjala",
201
+ "OM": "Oromo",
202
+ "OR": "Oriya",
203
+ "ORV": "Old East Slavic",
204
+ "OS": "Ossetian",
205
+ "OTA": "Ottoman Turkish",
206
+ "OVD": "Elfdalian",
207
+ "PA": "Punjabi",
208
+ "PAM": "Kapampangan",
209
+ "PAP": "Papiamentu",
210
+ "PCD": "Picard",
211
+ "PDC": "Pennsylvania German",
212
+ "PDT": "Plautdietsch",
213
+ "PL": "Polish",
214
+ "PMS": "Piedmontese",
215
+ "PNB": "Western Panjabi",
216
+ "PS": "Pashto",
217
+ "PT": "Portuguese",
218
+ "QU": "Quechua",
219
+ "RM": "Romansh",
220
+ "RMY": "Romani",
221
+ "RO": "Romanian",
222
+ "ROA_RUP": "Aromanian",
223
+ "RU": "Russian",
224
+ "RUE": "Rusyn",
225
+ "SA": "Sanskrit",
226
+ "SAH": "Sakha",
227
+ "SAT": "Santali",
228
+ "SC": "Sardinian",
229
+ "SCN": "Sicilian",
230
+ "SCO": "Scots",
231
+ "SD": "Sindhi",
232
+ "SE": "Northern Sami",
233
+ "SH": "Serbo-Croatian",
234
+ "SHI": "Tashelhit",
235
+ "SHN": "Shan",
236
+ "SI": "Sinhalese",
237
+ "SIMPLE": "Simple English",
238
+ "SK": "Slovak",
239
+ "SL": "Slovenian",
240
+ "SM": "Samoan",
241
+ "SMJ": "Lule Sami",
242
+ "SMN": "Inari Sami",
243
+ "SMS": "Skolt Sami",
244
+ "SN": "Shona",
245
+ "SNE": "Bau Bidayuh",
246
+ "SO": "Somali",
247
+ "SQ": "Albanian",
248
+ "SR": "Serbian",
249
+ "SRN": "Sranan",
250
+ "ST": "Sesotho",
251
+ "STQ": "Saterland Frisian",
252
+ "SU": "Sundanese",
253
+ "SV": "Swedish",
254
+ "SVA": "Svan",
255
+ "SW": "Swahili",
256
+ "SYC": "Classical Syriac",
257
+ "SZL": "Silesian",
258
+ "TA": "Tamil",
259
+ "TCY": "Tulu",
260
+ "TE": "Telugu",
261
+ "TG": "Tajik",
262
+ "TH": "Thai",
263
+ "TI": "Tigrinya",
264
+ "TK": "Turkmen",
265
+ "TL": "Tagalog",
266
+ "TN": "Tswana",
267
+ "TO": "Tongan",
268
+ "TPI": "Tok Pisin",
269
+ "TR": "Turkish",
270
+ "TT": "Tatar",
271
+ "TYV": "Tuvan",
272
+ "UDM": "Udmurt",
273
+ "UG": "Uyghur",
274
+ "UGA": "Ugaritic",
275
+ "UK": "Ukrainian",
276
+ "UR": "Urdu",
277
+ "UZ": "Uzbek",
278
+ "VEC": "Venetian",
279
+ "VEP": "Vepsian",
280
+ "VI": "Vietnamese",
281
+ "VLS": "West Flemish",
282
+ "VO": "Volap\u00fck",
283
+ "WA": "Walloon",
284
+ "WAR": "Waray-Waray",
285
+ "WO": "Wolof",
286
+ "WUU": "Wu",
287
+ "XAL": "Kalmyk",
288
+ "XH": "Xhosa",
289
+ "XMF": "Mingrelian",
290
+ "YI": "Yiddish",
291
+ "YO": "Yoruba",
292
+ "YUA": "Yucatec Maya",
293
+ "ZA": "Zhuang",
294
+ "ZDJ": "Ngazidja Comorian",
295
+ "ZH": "Chinese",
296
+ "ZH_CLASSICAL": "Classical Chinese",
297
+ "ZH_MIN_NAN": "Min Nan",
298
+ "ZH_YUE": "Cantonese",
299
+ "ZU": "Zulu"
300
+ }
data/precomputed_results.json ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ numpy
4
+ open_clip_torch
5
+ timm
6
+ Pillow