xinyu1205 commited on
Commit
a7b8ada
1 Parent(s): 6ddd344

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -49
app.py CHANGED
@@ -1,65 +1,73 @@
1
- from PIL import Image
2
- import requests
 
 
3
  import torch
4
- from torchvision import transforms
5
- from torchvision.transforms.functional import InterpolationMode
6
 
7
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
 
8
 
 
9
 
 
10
 
 
11
 
12
 
13
- import gradio as gr
 
 
14
 
15
- # from models.blip import blip_decoder
16
- from transformers import BlipProcessor, BlipForConditionalGeneration
17
 
18
- model_id = "Salesforce/blip-image-captioning-base"
 
19
 
20
- model = BlipForConditionalGeneration.from_pretrained(model_id)
 
21
 
22
 
23
- image_size = 384
24
- transform = transforms.Compose([
25
- transforms.Resize((image_size,image_size),interpolation=InterpolationMode.BICUBIC),
26
- transforms.ToTensor(),
27
- transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
28
- ])
29
 
30
- # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_large_caption.pth'
31
-
32
- # model = blip_decoder(pretrained=model_url, image_size=384, vit='large')
33
  model.eval()
34
  model = model.to(device)
35
 
36
 
37
- # from models.blip_vqa import blip_vqa
38
-
39
- # image_size_vq = 480
40
- # transform_vq = transforms.Compose([
41
- # transforms.Resize((image_size_vq,image_size_vq),interpolation=InterpolationMode.BICUBIC),
42
- # transforms.ToTensor(),
43
- # transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
44
- # ])
45
-
46
- # model_url_vq = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model*_vqa.pth'
47
-
48
- # model_vq = blip_vqa(pretrained=model_url_vq, image_size=480, vit='base')
49
- # model_vq.eval()
50
- # model_vq = model_vq.to(device)
51
-
52
-
53
-
54
- def inference(raw_image, model_n, question, strategy):
55
  if model_n == 'Image Captioning':
 
56
  image = transform(raw_image).unsqueeze(0).to(device)
 
 
 
 
 
 
57
  with torch.no_grad():
58
- if strategy == "Beam search":
59
- caption = model.generate(image, sample=False, num_beams=3, max_length=20, min_length=5)
60
- else:
61
- caption = model.generate(image, sample=True, top_p=0.9, max_length=20, min_length=5)
62
- return 'caption: '+caption[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  else:
65
  image_vq = transform_vq(raw_image).unsqueeze(0).to(device)
@@ -67,16 +75,26 @@ def inference(raw_image, model_n, question, strategy):
67
  answer = model_vq(image_vq, question, train=False, inference='generate')
68
  return 'answer: '+answer[0]
69
 
70
- # inputs = [gr.inputs.Image(type='pil'),gr.inputs.Radio(choices=['Image Captioning',"Visual Question Answering"], type="value", default="Image Captioning", label="Task"),gr.inputs.Textbox(lines=2, label="Question"),gr.inputs.Radio(choices=['Beam search','Nucleus sampling'], type="value", default="Nucleus sampling", label="Caption Decoding Strategy")]
71
- 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="Question"),gr.inputs.Radio(choices=['Beam search','Nucleus sampling'], type="value", default="Nucleus sampling", label="Caption Decoding Strategy")]
 
 
 
 
 
72
 
73
- outputs = gr.outputs.Textbox(label="Output")
74
 
75
- title = "BLIP"
 
 
 
 
 
 
 
 
76
 
77
- description = "Gradio demo for BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation (Salesforce Research). To use it, simply upload your image, or click one of the examples to load them. Read more at the links below."
78
 
79
- article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2201.12086' target='_blank'>BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation</a> | <a href='https://github.com/salesforce/BLIP' target='_blank'>Github Repo</a></p>"
80
 
81
 
82
- gr.Interface(inference, inputs, outputs, title=title, description=description, article=article, examples=[['starrynight.jpeg',"Image Captioning","None","Nucleus sampling"]]).launch(enable_queue=True)
 
1
+ import ruamel_yaml as yaml
2
+ import numpy as np
3
+ import random
4
+
5
  import torch
6
+ import torchvision.transforms as transforms
 
7
 
8
+ from PIL import Image
9
+ from models.tag2text import tag2text_caption
10
 
11
+ import gradio as gr
12
 
13
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
14
 
15
+ image_size = 384
16
 
17
 
18
+ normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
19
+ std=[0.229, 0.224, 0.225])
20
+ transform = transforms.Compose([transforms.Resize((image_size, image_size)),transforms.ToTensor(),normalize])
21
 
 
 
22
 
23
+ #######Swin Version
24
+ 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'
25
 
26
+ config_file = 'configs/tag2text_caption.yaml'
27
+ config = yaml.load(open(config_file, 'r'), Loader=yaml.Loader)
28
 
29
 
30
+ model = tag2text_caption(pretrained=pretrained, image_size=image_size, vit=config['vit'],
31
+ vit_grad_ckpt=config['vit_grad_ckpt'], vit_ckpt_layer=config['vit_ckpt_layer'],
32
+ prompt=config['prompt'],config=config,threshold = 0.75 )
 
 
 
33
 
 
 
 
34
  model.eval()
35
  model = model.to(device)
36
 
37
 
38
+ def inference(raw_image, model_n, input_tag, strategy):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  if model_n == 'Image Captioning':
40
+ raw_image = raw_image.resize((image_size, image_size))
41
  image = transform(raw_image).unsqueeze(0).to(device)
42
+ model.threshold = 0.7
43
+ if input_tag == '' or input_tag == 'none' or input_tag == 'None':
44
+ input_tag_list = None
45
+ else:
46
+ input_tag_list = []
47
+ input_tag_list.append(input_tag.replace(',',' | '))
48
  with torch.no_grad():
49
+ if strategy == "Beam search":
50
+
51
+
52
+ caption, tag_predict = model.generate(image,tag_input = input_tag_list, return_tag_predict = True)
53
+ if input_tag_list == None:
54
+ tag_1 = tag_predict
55
+ tag_2 = ['none']
56
+ else:
57
+ _, tag_1 = model.generate(image,tag_input = None, return_tag_predict = True)
58
+ tag_2 = tag_predict
59
+
60
+ else:
61
+
62
+ caption,tag_predict = model.generate(image, tag_input = input_tag_list,sample=True, top_p=0.9, max_length=20, min_length=5, return_tag_predict = True)
63
+ if input_tag_list == None:
64
+ tag_1 = tag_predict
65
+ tag_2 = ['none']
66
+ else:
67
+ _, tag_1 = model.generate(image,tag_input = None, return_tag_predict = True)
68
+ tag_2 = tag_predict
69
+ return tag_1[0],tag_2[0],caption[0]
70
+
71
 
72
  else:
73
  image_vq = transform_vq(raw_image).unsqueeze(0).to(device)
 
75
  answer = model_vq(image_vq, question, train=False, inference='generate')
76
  return 'answer: '+answer[0]
77
 
78
+ 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")]
79
+
80
+ outputs = [gr.outputs.Textbox(label="Model Identified Tags"),gr.outputs.Textbox(label="User Identified Tags"), gr.outputs.Textbox(label="Image Caption") ]
81
+
82
+ title = "Tag2Text"
83
+
84
+ description = "Gradio demo for Tag2Text: Guiding Language-Image Model via Image Tagging (Fudan University, OPPO Research Institute, International Digital Economy Academy)."
85
 
86
+ 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>"
87
 
88
+ demo = gr.Interface(inference, inputs, outputs, title=title, description=description, article=article, examples=[['images/COCO_val2014_000000551338.jpg',"Image Captioning","none","Beam search"],
89
+ ['images/COCO_val2014_000000551338.jpg',"Image Captioning","fence, sky","Beam search"],
90
+ # ['images/COCO_val2014_000000551338.jpg',"Image Captioning","grass","Beam search"],
91
+ ['images/COCO_val2014_000000483108.jpg',"Image Captioning","none","Beam search"],
92
+ ['images/COCO_val2014_000000483108.jpg',"Image Captioning","electric cable","Beam search"],
93
+ # ['images/COCO_val2014_000000483108.jpg',"Image Captioning","sky, train","Beam search"],
94
+ ['images/COCO_val2014_000000483108.jpg',"Image Captioning","track, train","Beam search"] ,
95
+ ['images/COCO_val2014_000000483108.jpg',"Image Captioning","grass","Beam search"]
96
+ ])
97
 
 
98
 
 
99
 
100