MikailDuzenli commited on
Commit
5a42f41
·
1 Parent(s): 8a113c5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import requests
5
+ import numpy as np
6
+ import re
7
+ import io
8
+
9
+ from PIL import Image
10
+ from transformers import ViltProcessor, ViltForMaskedLM
11
+ from torchvision import transforms
12
+
13
+ processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-mlm")
14
+ model = ViltForMaskedLM.from_pretrained("dandelin/vilt-b32-mlm")
15
+
16
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
17
+ model.to(device)
18
+
19
+ class MinMaxResize:
20
+ def __init__(self, shorter=800, longer=1333):
21
+ self.min = shorter
22
+ self.max = longer
23
+
24
+ def __call__(self, x):
25
+ w, h = x.size
26
+ scale = self.min / min(w, h)
27
+ if h < w:
28
+ newh, neww = self.min, scale * w
29
+ else:
30
+ newh, neww = scale * h, self.min
31
+
32
+ if max(newh, neww) > self.max:
33
+ scale = self.max / max(newh, neww)
34
+ newh = newh * scale
35
+ neww = neww * scale
36
+
37
+ newh, neww = int(newh + 0.5), int(neww + 0.5)
38
+ newh, neww = newh // 32 * 32, neww // 32 * 32
39
+
40
+ return x.resize((neww, newh), resample=Image.BICUBIC)
41
+
42
+ def pixelbert_transform(size=800):
43
+ longer = int((1333 / 800) * size)
44
+ return transforms.Compose(
45
+ [
46
+ MinMaxResize(shorter=size, longer=longer),
47
+ transforms.ToTensor(),
48
+ transforms.Compose([transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])]),
49
+ ]
50
+ )
51
+
52
+
53
+ def infer(url, mp_text):
54
+ try:
55
+ res = requests.get(url)
56
+ image = Image.open(io.BytesIO(res.content)).convert("RGB")
57
+ img = pixelbert_transform(size=384)(image)
58
+ img = img.unsqueeze(0).to(device)
59
+ except:
60
+ return False
61
+
62
+ tl = len(re.findall("\[MASK\]", mp_text))
63
+ inferred_token = [mp_text]
64
+ encoding = processor(image, mp_text, return_tensors="pt")
65
+
66
+ with torch.no_grad():
67
+ for i in range(tl):
68
+ encoded = processor.tokenizer(inferred_token)
69
+ input_ids = torch.tensor(encoded.input_ids)
70
+ encoded = encoded["input_ids"][0][1:-1]
71
+ outputs = model(input_ids=input_ids, pixel_values=encoding.pixel_values)
72
+ mlm_logits = outputs.logits[0] # shape (seq_len, vocab_size)
73
+
74
+ # only take into account text features (minus CLS and SEP token)
75
+ mlm_logits = mlm_logits[1 : input_ids.shape[1] - 1, :]
76
+ mlm_values, mlm_ids = mlm_logits.softmax(dim=-1).max(dim=-1)
77
+
78
+ # only take into account text
79
+ mlm_values[torch.tensor(encoded) != 103] = 0
80
+ select = mlm_values.argmax().item()
81
+ encoded[select] = mlm_ids[select].item()
82
+ inferred_token = [processor.decode(encoded)]
83
+
84
+ encoded = processor.tokenizer(inferred_token)
85
+ output = processor.decode(encoded.input_ids[0], skip_special_tokens=True)
86
+
87
+ return [np.array(image), output]
88
+
89
+ inputs_interface = [
90
+ gr.inputs.Textbox(
91
+ label="Url of an image.",
92
+ lines=5,
93
+ ),
94
+ gr.inputs.Textbox(label="Caption with [MASK] tokens to be filled.", lines=5),
95
+ ]
96
+ outputs_interface = [
97
+ gr.outputs.Image(label="Image"),
98
+ gr.outputs.Textbox(label="description"),
99
+ ]
100
+
101
+ interface = gr.Interface(
102
+ fn=infer,
103
+ inputs=inputs_interface,
104
+ outputs=outputs_interface,
105
+ server_name="0.0.0.0",
106
+ server_port=8888,
107
+ examples=[
108
+ [
109
+ "https://s3.geograph.org.uk/geophotos/06/21/24/6212487_1cca7f3f_1024x1024.jpg",
110
+ "a display of flowers growing out and over the [MASK] [MASK] in front of [MASK] on a [MASK] [MASK].",
111
+ ],
112
+
113
+ [
114
+ "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT5W71UTcSBm3r5l9NzBemglq983bYvKOHRkw&usqp=CAU",
115
+ "An [MASK] with the [MASK] in the [MASK].",
116
+ ],
117
+
118
+ [
119
+ "https://www.referenseo.com/wp-content/uploads/2019/03/image-attractive-960x540.jpg",
120
+ "An [MASK] is flying with a [MASK] over a [MASK].",
121
+ ],
122
+ ],
123
+ )
124
+
125
+ interface.launch()
126
+