File size: 26,753 Bytes
616e7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "35d8939e-909d-45d8-bcf9-0ff1dccacfdf",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/lib/python3.7/site-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n",
      "Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertModel: ['bert.encoder.layer.2.attention.self.key.bias', 'cls.seq_relationship.weight', 'bert.encoder.layer.5.intermediate.dense.weight', 'cls.predictions.transform.LayerNorm.weight', 'bert.encoder.layer.7.output.dense.weight', 'bert.encoder.layer.10.output.LayerNorm.bias', 'bert.encoder.layer.2.intermediate.dense.bias', 'bert.encoder.layer.6.attention.self.value.weight', 'bert.encoder.layer.5.attention.self.query.bias', 'bert.encoder.layer.8.intermediate.dense.bias', 'bert.encoder.layer.4.output.dense.bias', 'bert.encoder.layer.8.attention.output.dense.weight', 'bert.encoder.layer.8.attention.self.query.bias', 'bert.encoder.layer.4.attention.output.dense.weight', 'bert.encoder.layer.7.intermediate.dense.weight', 'bert.encoder.layer.5.attention.output.LayerNorm.bias', 'bert.encoder.layer.8.output.LayerNorm.bias', 'bert.encoder.layer.2.output.LayerNorm.bias', 'bert.encoder.layer.3.attention.self.value.weight', 'bert.encoder.layer.2.intermediate.dense.weight', 'bert.encoder.layer.5.attention.output.dense.bias', 'bert.encoder.layer.11.intermediate.dense.weight', 'cls.predictions.transform.dense.weight', 'bert.encoder.layer.4.attention.self.key.bias', 'bert.encoder.layer.2.attention.output.LayerNorm.bias', 'bert.encoder.layer.7.output.LayerNorm.bias', 'bert.encoder.layer.5.intermediate.dense.bias', 'bert.encoder.layer.10.output.dense.weight', 'bert.encoder.layer.10.attention.output.LayerNorm.bias', 'bert.encoder.layer.9.intermediate.dense.weight', 'bert.encoder.layer.3.attention.self.query.bias', 'bert.encoder.layer.11.attention.self.query.bias', 'bert.encoder.layer.7.attention.self.value.bias', 'bert.encoder.layer.6.output.dense.bias', 'bert.encoder.layer.6.attention.output.LayerNorm.bias', 'bert.encoder.layer.4.attention.output.LayerNorm.weight', 'cls.predictions.bias', 'bert.encoder.layer.10.attention.output.dense.weight', 'bert.encoder.layer.8.attention.self.value.weight', 'cls.predictions.transform.dense.bias', 'bert.encoder.layer.11.attention.self.query.weight', 'bert.encoder.layer.8.output.LayerNorm.weight', 'bert.encoder.layer.11.attention.self.value.weight', 'bert.encoder.layer.2.attention.self.key.weight', 'bert.encoder.layer.3.attention.output.LayerNorm.weight', 'bert.encoder.layer.8.attention.output.LayerNorm.weight', 'bert.encoder.layer.8.attention.output.LayerNorm.bias', 'bert.encoder.layer.2.output.dense.weight', 'bert.encoder.layer.3.attention.output.dense.bias', 'bert.encoder.layer.11.attention.output.dense.weight', 'bert.encoder.layer.10.attention.self.value.weight', 'bert.encoder.layer.7.attention.output.dense.bias', 'bert.encoder.layer.11.output.dense.bias', 'bert.pooler.dense.bias', 'bert.encoder.layer.11.attention.self.value.bias', 'bert.encoder.layer.6.attention.self.query.bias', 'bert.encoder.layer.6.output.dense.weight', 'bert.encoder.layer.9.output.LayerNorm.bias', 'bert.encoder.layer.4.output.LayerNorm.weight', 'bert.encoder.layer.9.output.LayerNorm.weight', 'bert.encoder.layer.9.intermediate.dense.bias', 'cls.predictions.decoder.weight', 'bert.encoder.layer.4.attention.output.dense.bias', 'bert.encoder.layer.4.attention.self.value.weight', 'bert.encoder.layer.7.output.LayerNorm.weight', 'bert.encoder.layer.11.attention.self.key.bias', 'bert.encoder.layer.6.attention.output.dense.weight', 'bert.encoder.layer.7.attention.self.key.weight', 'bert.encoder.layer.6.attention.output.dense.bias', 'bert.encoder.layer.10.attention.self.value.bias', 'cls.seq_relationship.bias', 'bert.encoder.layer.3.attention.self.key.weight', 'bert.encoder.layer.10.attention.self.key.bias', 'bert.encoder.layer.9.attention.output.dense.bias', 'bert.encoder.layer.4.attention.output.LayerNorm.bias', 'bert.encoder.layer.7.attention.self.key.bias', 'bert.encoder.layer.4.attention.self.query.weight', 'bert.encoder.layer.4.intermediate.dense.weight', 'bert.encoder.layer.4.attention.self.query.bias', 'bert.encoder.layer.6.output.LayerNorm.weight', 'bert.encoder.layer.3.attention.output.dense.weight', 'bert.encoder.layer.3.intermediate.dense.weight', 'bert.encoder.layer.3.intermediate.dense.bias', 'bert.encoder.layer.4.attention.self.value.bias', 'bert.encoder.layer.9.output.dense.weight', 'bert.pooler.dense.weight', 'bert.encoder.layer.11.attention.output.LayerNorm.bias', 'bert.encoder.layer.9.attention.self.query.weight', 'bert.encoder.layer.5.attention.output.dense.weight', 'bert.encoder.layer.10.attention.self.key.weight', 'bert.encoder.layer.11.output.LayerNorm.weight', 'bert.encoder.layer.9.attention.self.query.bias', 'bert.encoder.layer.6.attention.self.value.bias', 'bert.encoder.layer.8.attention.self.value.bias', 'bert.encoder.layer.7.intermediate.dense.bias', 'bert.encoder.layer.10.output.dense.bias', 'bert.encoder.layer.5.output.LayerNorm.weight', 'bert.encoder.layer.8.attention.output.dense.bias', 'bert.encoder.layer.10.intermediate.dense.bias', 'bert.encoder.layer.7.output.dense.bias', 'bert.encoder.layer.7.attention.output.LayerNorm.weight', 'bert.encoder.layer.6.attention.self.query.weight', 'bert.encoder.layer.6.attention.self.key.bias', 'bert.encoder.layer.3.attention.self.query.weight', 'bert.encoder.layer.11.output.dense.weight', 'bert.encoder.layer.9.attention.self.key.bias', 'bert.encoder.layer.2.attention.output.dense.bias', 'bert.encoder.layer.9.attention.output.dense.weight', 'bert.encoder.layer.2.attention.output.LayerNorm.weight', 'bert.encoder.layer.5.attention.output.LayerNorm.weight', 'bert.encoder.layer.11.attention.self.key.weight', 'bert.encoder.layer.4.output.dense.weight', 'bert.encoder.layer.3.attention.self.key.bias', 'bert.encoder.layer.5.output.dense.bias', 'bert.encoder.layer.3.attention.self.value.bias', 'bert.encoder.layer.9.attention.self.key.weight', 'bert.encoder.layer.3.attention.output.LayerNorm.bias', 'bert.encoder.layer.4.intermediate.dense.bias', 'bert.encoder.layer.3.output.LayerNorm.weight', 'bert.encoder.layer.8.attention.self.query.weight', 'bert.encoder.layer.2.output.LayerNorm.weight', 'bert.encoder.layer.10.intermediate.dense.weight', 'bert.encoder.layer.4.output.LayerNorm.bias', 'bert.encoder.layer.10.attention.self.query.bias', 'bert.encoder.layer.11.attention.output.LayerNorm.weight', 'cls.predictions.transform.LayerNorm.bias', 'bert.encoder.layer.2.attention.output.dense.weight', 'bert.encoder.layer.6.intermediate.dense.bias', 'bert.encoder.layer.7.attention.output.LayerNorm.bias', 'bert.encoder.layer.2.output.dense.bias', 'bert.encoder.layer.5.attention.self.key.bias', 'bert.encoder.layer.9.output.dense.bias', 'bert.encoder.layer.2.attention.self.query.weight', 'bert.encoder.layer.5.output.dense.weight', 'bert.encoder.layer.5.attention.self.value.weight', 'bert.encoder.layer.3.output.LayerNorm.bias', 'bert.encoder.layer.11.output.LayerNorm.bias', 'bert.encoder.layer.7.attention.self.query.bias', 'bert.encoder.layer.6.output.LayerNorm.bias', 'bert.encoder.layer.9.attention.output.LayerNorm.bias', 'bert.encoder.layer.3.output.dense.weight', 'bert.encoder.layer.7.attention.self.value.weight', 'bert.encoder.layer.8.output.dense.bias', 'bert.encoder.layer.5.attention.self.query.weight', 'bert.encoder.layer.5.output.LayerNorm.bias', 'bert.encoder.layer.2.attention.self.value.weight', 'bert.encoder.layer.5.attention.self.key.weight', 'bert.encoder.layer.6.attention.self.key.weight', 'bert.encoder.layer.11.intermediate.dense.bias', 'bert.encoder.layer.6.intermediate.dense.weight', 'bert.encoder.layer.10.attention.self.query.weight', 'bert.encoder.layer.10.output.LayerNorm.weight', 'bert.encoder.layer.3.output.dense.bias', 'bert.encoder.layer.6.attention.output.LayerNorm.weight', 'bert.encoder.layer.10.attention.output.dense.bias', 'bert.encoder.layer.9.attention.output.LayerNorm.weight', 'bert.encoder.layer.11.attention.output.dense.bias', 'bert.encoder.layer.4.attention.self.key.weight', 'bert.embeddings.token_type_embeddings.weight', 'bert.encoder.layer.7.attention.self.query.weight', 'bert.encoder.layer.8.output.dense.weight', 'bert.encoder.layer.5.attention.self.value.bias', 'bert.encoder.layer.2.attention.self.value.bias', 'bert.encoder.layer.9.attention.self.value.bias', 'bert.encoder.layer.10.attention.output.LayerNorm.weight', 'bert.encoder.layer.2.attention.self.query.bias', 'bert.encoder.layer.7.attention.output.dense.weight', 'bert.encoder.layer.8.attention.self.key.bias', 'bert.encoder.layer.8.intermediate.dense.weight', 'bert.encoder.layer.8.attention.self.key.weight', 'bert.encoder.layer.9.attention.self.value.weight']\n",
      "- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
      "- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n",
      "Some weights of BertModel were not initialized from the model checkpoint at bert-base-uncased and are newly initialized: ['bert.encoder.layer.0.crossattention.output.dense.bias', 'bert.encoder.layer.0.crossattention.self.value.bias', 'bert.encoder.layer.0.crossattention.self.query.bias', 'bert.encoder.layer.0.crossattention.self.value.weight', 'bert.encoder.layer.1.crossattention.self.query.weight', 'bert.encoder.layer.1.crossattention.output.dense.weight', 'bert.encoder.layer.1.crossattention.self.value.weight', 'bert.encoder.layer.1.crossattention.output.LayerNorm.weight', 'bert.encoder.layer.0.crossattention.output.LayerNorm.weight', 'bert.encoder.layer.1.crossattention.self.key.weight', 'bert.encoder.layer.1.crossattention.output.dense.bias', 'bert.encoder.layer.0.crossattention.self.key.bias', 'bert.encoder.layer.1.crossattention.self.key.bias', 'bert.encoder.layer.1.crossattention.self.query.bias', 'bert.encoder.layer.1.crossattention.self.value.bias', 'bert.encoder.layer.0.crossattention.self.query.weight', 'bert.encoder.layer.0.crossattention.output.LayerNorm.bias', 'bert.encoder.layer.0.crossattention.self.key.weight', 'bert.encoder.layer.1.crossattention.output.LayerNorm.bias', 'bert.encoder.layer.0.crossattention.output.dense.weight']\n",
      "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/encoder/layer/0/crossattention/self/query is tied\n",
      "/encoder/layer/0/crossattention/self/key is tied\n",
      "/encoder/layer/0/crossattention/self/value is tied\n",
      "/encoder/layer/0/crossattention/output/dense is tied\n",
      "/encoder/layer/0/crossattention/output/LayerNorm is tied\n",
      "/encoder/layer/0/intermediate/dense is tied\n",
      "/encoder/layer/0/output/dense is tied\n",
      "/encoder/layer/0/output/LayerNorm is tied\n",
      "/encoder/layer/1/crossattention/self/query is tied\n",
      "/encoder/layer/1/crossattention/self/key is tied\n",
      "/encoder/layer/1/crossattention/self/value is tied\n",
      "/encoder/layer/1/crossattention/output/dense is tied\n",
      "/encoder/layer/1/crossattention/output/LayerNorm is tied\n",
      "/encoder/layer/1/intermediate/dense is tied\n",
      "/encoder/layer/1/output/dense is tied\n",
      "/encoder/layer/1/output/LayerNorm is tied\n",
      "--------------\n",
      "/home/notebook/code/personal/S9049611/BLIP/output/blip_tagtotext_14m/blip_tagtotext_encoderdiv_tar_random_swin/caption_coco_finetune_tagparse_tagfinetune_threshold075_bceloss_tagsingle_5e6_epoch19_negative_1_05_pos_1_10/checkpoint_05.pth\n",
      "--------------\n",
      "load checkpoint from /home/notebook/code/personal/S9049611/BLIP/output/blip_tagtotext_14m/blip_tagtotext_encoderdiv_tar_random_swin/caption_coco_finetune_tagparse_tagfinetune_threshold075_bceloss_tagsingle_5e6_epoch19_negative_1_05_pos_1_10/checkpoint_05.pth\n",
      "vit: swin_b\n",
      "msg_v2 _IncompatibleKeys(missing_keys=['visual_encoder.layers.0.blocks.0.attn.relative_position_index', 'visual_encoder.layers.0.blocks.1.attn_mask', 'visual_encoder.layers.0.blocks.1.attn.relative_position_index', 'visual_encoder.layers.1.blocks.0.attn.relative_position_index', 'visual_encoder.layers.1.blocks.1.attn_mask', 'visual_encoder.layers.1.blocks.1.attn.relative_position_index', 'visual_encoder.layers.2.blocks.0.attn.relative_position_index', 'visual_encoder.layers.2.blocks.1.attn_mask', 'visual_encoder.layers.2.blocks.1.attn.relative_position_index', 'visual_encoder.layers.2.blocks.2.attn.relative_position_index', 'visual_encoder.layers.2.blocks.3.attn_mask', 'visual_encoder.layers.2.blocks.3.attn.relative_position_index', 'visual_encoder.layers.2.blocks.4.attn.relative_position_index', 'visual_encoder.layers.2.blocks.5.attn_mask', 'visual_encoder.layers.2.blocks.5.attn.relative_position_index', 'visual_encoder.layers.2.blocks.6.attn.relative_position_index', 'visual_encoder.layers.2.blocks.7.attn_mask', 'visual_encoder.layers.2.blocks.7.attn.relative_position_index', 'visual_encoder.layers.2.blocks.8.attn.relative_position_index', 'visual_encoder.layers.2.blocks.9.attn_mask', 'visual_encoder.layers.2.blocks.9.attn.relative_position_index', 'visual_encoder.layers.2.blocks.10.attn.relative_position_index', 'visual_encoder.layers.2.blocks.11.attn_mask', 'visual_encoder.layers.2.blocks.11.attn.relative_position_index', 'visual_encoder.layers.2.blocks.12.attn.relative_position_index', 'visual_encoder.layers.2.blocks.13.attn_mask', 'visual_encoder.layers.2.blocks.13.attn.relative_position_index', 'visual_encoder.layers.2.blocks.14.attn.relative_position_index', 'visual_encoder.layers.2.blocks.15.attn_mask', 'visual_encoder.layers.2.blocks.15.attn.relative_position_index', 'visual_encoder.layers.2.blocks.16.attn.relative_position_index', 'visual_encoder.layers.2.blocks.17.attn_mask', 'visual_encoder.layers.2.blocks.17.attn.relative_position_index', 'visual_encoder.layers.3.blocks.0.attn.relative_position_index', 'visual_encoder.layers.3.blocks.1.attn.relative_position_index'], unexpected_keys=[])\n"
     ]
    }
   ],
   "source": [
    "from PIL import Image\n",
    "import requests\n",
    "import torch\n",
    "from torchvision import transforms\n",
    "from torchvision.transforms.functional import InterpolationMode\n",
    "import ruamel_yaml as yaml\n",
    "from models.tag2text import tag2text_caption\n",
    "\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
    "\n",
    "\n",
    "\n",
    "import gradio as gr\n",
    "\n",
    "image_size = 384\n",
    "\n",
    "\n",
    "normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n",
    "                                std=[0.229, 0.224, 0.225])\n",
    "transform = transforms.Compose([transforms.Resize((image_size, image_size)),transforms.ToTensor(),normalize])\n",
    "\n",
    "\n",
    "\n",
    "#######Swin Version\n",
    "pretrained = '/home/notebook/code/personal/S9049611/BLIP/output/blip_tagtotext_14m/blip_tagtotext_encoderdiv_tar_random_swin/caption_coco_finetune_tagparse_tagfinetune_threshold075_bceloss_tagsingle_5e6_epoch19_negative_1_05_pos_1_10/checkpoint_05.pth'\n",
    "\n",
    "config_file = 'configs/tag2text_caption.yaml'\n",
    "config = yaml.load(open(config_file, 'r'), Loader=yaml.Loader)\n",
    "\n",
    "\n",
    "model = tag2text_caption(pretrained=pretrained, image_size=image_size, vit=config['vit'], \n",
    "                    vit_grad_ckpt=config['vit_grad_ckpt'], vit_ckpt_layer=config['vit_ckpt_layer'],\n",
    "                    prompt=config['prompt'],config=config,threshold = 0.75 )\n",
    "\n",
    "model.eval()\n",
    "model = model.to(device)\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9772dc6f-680d-45a7-b39c-23770eb5258e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7864\n",
      "Running on public URL: https://a10a3bf9-64b6-49d4.gradio.live\n",
      "\n",
      "This share link expires in 72 hours. For free permanent hosting and GPU upgrades (NEW!), check out Spaces: https://huggingface.co./spaces\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"https://a10a3bf9-64b6-49d4.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "def inference(raw_image, input_tag):\n",
    "    raw_image = raw_image.resize((image_size, image_size))\n",
    "    # print(type(raw_image))\n",
    "    image = transform(raw_image).unsqueeze(0).to(device)   \n",
    "    model.threshold = 0.69\n",
    "    if input_tag == '' or input_tag == 'none' or input_tag == 'None':\n",
    "        input_tag_list = None\n",
    "    else:\n",
    "        input_tag_list = []\n",
    "        input_tag_list.append(input_tag.replace(',',' | '))\n",
    "    # print(input_tag_list)\n",
    "    with torch.no_grad():\n",
    "\n",
    "\n",
    "        caption, tag_predict = model.generate(image,tag_input = input_tag_list, return_tag_predict = True)\n",
    "        if input_tag_list == None:\n",
    "            tag_1 = tag_predict\n",
    "            tag_2 = ['none']\n",
    "        else:\n",
    "            _, tag_1 = model.generate(image,tag_input = None, return_tag_predict = True)\n",
    "            tag_2 = tag_predict\n",
    "\n",
    "\n",
    "        return tag_1[0],tag_2[0],caption[0]\n",
    "\n",
    "            # return 'caption: '+caption[0], tag_predict[0]\n",
    "\n",
    "\n",
    "    \n",
    "# inputs = [gr.inputs.Image(type='pil'),gr.inputs.Radio(choices=['Image Captioning'], type=\"value\", default=\"Image Captioning\", label=\"Task\"),gr.inputs.Textbox(lines=2, label=\"User Identified Tags (Optional, Enter with commas)\"),gr.inputs.Radio(choices=['Beam search','Nucleus sampling'], type=\"value\", default=\"Beam search\", label=\"Caption Decoding Strategy\")]\n",
    "inputs = [gr.inputs.Image(type='pil'),gr.inputs.Textbox(lines=2, label=\"User Specified Tags (Optional, Enter with commas)\")]\n",
    "\n",
    "# outputs = gr.outputs.Textbox(label=\"Output\")\n",
    "# outputs = [gr.outputs.Textbox(label=\"Image Caption\"),gr.outputs.Textbox(label=\"Identified Tags\")]\n",
    "outputs = [gr.outputs.Textbox(label=\"Model Identified Tags\"),gr.outputs.Textbox(label=\"User Specified Tags\"), gr.outputs.Textbox(label=\"Image Caption\") ]\n",
    "\n",
    "title = \"Tag2Text\"\n",
    "description = \"Welcome to Tag2Text demo! (Supported by Fudan University, OPPO Research Institute, International Digital Economy Academy) <br/> Upload your image to get the tags and caption of the image. Optional: You can also input specified tags to get the corresponding caption.\"\n",
    "\n",
    "article = \"<p style='text-align: center'><a href='' target='_blank'>Tag2Text: Guiding Language-Image Model via Image Tagging</a> | <a href='' target='_blank'>Github Repo</a></p>\"\n",
    "\n",
    "demo = gr.Interface(inference, inputs, outputs, title=title, description=description, article=article, examples=[['images/COCO_val2014_000000483108.jpg',\"none\"],\n",
    "                                                                                                                 ['images/COCO_val2014_000000483108.jpg',\"electric cable\"],\n",
    "                                                                                                                 ['images/COCO_val2014_000000483108.jpg',\"track, train\"] ,    \n",
    "                                                                                                                ])\n",
    "\n",
    "\n",
    "demo.launch(share=True)\n",
    "# demo.launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0da1f11b-e737-47a9-9b07-4e00c0835f63",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def inference(raw_image, input_tag):\n",
    "    raw_image = raw_image.resize((image_size, image_size))\n",
    "    # print(type(raw_image))\n",
    "    image = transform(raw_image).unsqueeze(0).to(device)   \n",
    "    model.threshold = 0.69\n",
    "    if input_tag == '' or input_tag == 'none' or input_tag == 'None':\n",
    "        input_tag_list = None\n",
    "    else:\n",
    "        input_tag_list = []\n",
    "        input_tag_list.append(input_tag.replace(',',' | '))\n",
    "    # print(input_tag_list)\n",
    "    with torch.no_grad():\n",
    "\n",
    "\n",
    "        caption, tag_predict = model.generate(image,tag_input = input_tag_list, return_tag_predict = True)\n",
    "        if input_tag_list == None:\n",
    "            tag_1 = tag_predict\n",
    "            tag_2 = ['none']\n",
    "        else:\n",
    "            _, tag_1 = model.generate(image,tag_input = None, return_tag_predict = True)\n",
    "            tag_2 = tag_predict\n",
    "\n",
    "\n",
    "        return tag_1[0],tag_2[0],caption[0]\n",
    "\n",
    "            # return 'caption: '+caption[0], tag_predict[0]\n",
    "\n",
    "\n",
    "    \n",
    "# inputs = [gr.inputs.Image(type='pil'),gr.inputs.Radio(choices=['Image Captioning'], type=\"value\", default=\"Image Captioning\", label=\"Task\"),gr.inputs.Textbox(lines=2, label=\"User Identified Tags (Optional, Enter with commas)\"),gr.inputs.Radio(choices=['Beam search','Nucleus sampling'], type=\"value\", default=\"Beam search\", label=\"Caption Decoding Strategy\")]\n",
    "inputs = [gr.inputs.Image(type='pil'),gr.inputs.Textbox(lines=2, label=\"User Specified Tags (Optional, Enter with commas)\")]\n",
    "\n",
    "# outputs = gr.outputs.Textbox(label=\"Output\")\n",
    "# outputs = [gr.outputs.Textbox(label=\"Image Caption\"),gr.outputs.Textbox(label=\"Identified Tags\")]\n",
    "outputs = [gr.outputs.Textbox(label=\"Model Identified Tags\"),gr.outputs.Textbox(label=\"User Specified Tags\"), gr.outputs.Textbox(label=\"Image Caption\") ]\n",
    "\n",
    "title = \"Tag2Text\"\n",
    "description = \"Welcome to Tag2Text demo! (Supported by Fudan University, OPPO Research Institute, International Digital Economy Academy) <br/> Upload your image to get the tags and caption of the image. Optional: You can also input specified tags to get the corresponding caption.\"\n",
    "\n",
    "article = \"<p style='text-align: center'><a href='' target='_blank'>Tag2Text: Guiding Language-Image Model via Image Tagging</a> | <a href='' target='_blank'>Github Repo</a></p>\"\n",
    "\n",
    "demo = gr.Interface(inference, inputs, outputs, title=title, description=description, article=article, examples=[['images/COCO_val2014_000000551338.jpg',\"none\"], \n",
    "                                                                                                                ['images/COCO_val2014_000000551338.jpg',\"fence, sky\"],\n",
    "                                                                                                                # ['images/COCO_val2014_000000551338.jpg',\"grass\"],\n",
    "                                                                                                                 ['images/COCO_val2014_000000483108.jpg',\"none\"],\n",
    "                                                                                                                 ['images/COCO_val2014_000000483108.jpg',\"electric cable\"],\n",
    "                                                                                                                  # ['images/COCO_val2014_000000483108.jpg',\"sky, train\"],\n",
    "                                                                                                                 ['images/COCO_val2014_000000483108.jpg',\"track, train\"] ,    \n",
    "                                                                                                                 ['images/COCO_val2014_000000483108.jpg',\"grass\"]     \n",
    "                                                                                                                ])\n",
    "\n",
    "\n",
    "demo.launch(share=True)\n",
    "# demo.launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73a4bb88-4200-4853-b1ba-34f0d4b6dc34",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3340a61f-c6bc-4ead-87ea-b26aa97b7a68",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d49e3de4-c3f7-4835-90eb-d0d013fc0ffb",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "205e0317-1701-4afd-8d67-bedb6959f350",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf5301a5-80c5-4e44-835e-0160a97fef66",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f63d7a06-7625-4e1c-855d-177971217a0d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c929e566-1a6e-4280-96eb-c434ef9a35d0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}