forked from Vision-CAIR/MiniGPT-4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_captions.py
225 lines (177 loc) · 7.32 KB
/
generate_captions.py
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
"""
Use MiniGPT-4 to generate captions for a provided list of URLs.
"""
import argparse
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import gradio as gr
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank
from minigpt4.common.registry import registry
from minigpt4.conversation.conversation import Chat, CONV_VISION
def parse_args():
parser = argparse.ArgumentParser(description="Demo")
parser.add_argument("--cfg-path", required=True, help="path to configuration file.")
parser.add_argument("--gpu-id", type=int, default=0, help="specify the gpu to load the model.")
parser.add_argument("--urls-path", type=str, default=None, help="specify the path to the URLs to generate captions for")
parser.add_argument(
"--options",
nargs="+",
help="override some settings in the used config, the key-value pair "
"in xxx=yyy format will be merged into config file (deprecate), "
"change to --cfg-options instead.",
)
args = parser.parse_args()
return args
# ========================================
# Model Initialization
# ========================================
print('Initializing Chat')
args = parse_args()
cfg = Config(args)
model_config = cfg.model_cfg
model_config.device_8bit = args.gpu_id
model_cls = registry.get_model_class(model_config.arch)
model = model_cls.from_config(model_config).to('cuda:{}'.format(args.gpu_id))
vis_processor_cfg = cfg.datasets_cfg.cc_sbu_align.vis_processor.train
vis_processor = registry.get_processor_class(vis_processor_cfg.name).from_config(vis_processor_cfg)
chat = Chat(model, vis_processor, device='cuda:{}'.format(args.gpu_id))
print('Initialization Finished')
# ========================================
# Gradio Setting
# ========================================
def gradio_reset(chat_state, img_list):
if chat_state is not None:
chat_state.messages = []
if img_list is not None:
img_list = []
return None, gr.update(value=None, interactive=True), gr.update(placeholder='Please upload your image first',
interactive=False), gr.update(
value="Upload & Start Chat", interactive=True), chat_state, img_list
def upload_img(gr_img):
# if gr_img is None:
# return None, None, gr.update(interactive=True), chat_state, None
chat_state = CONV_VISION.copy()
img_list = []
llm_message = chat.upload_img(gr_img, chat_state, img_list)
return chat_state, img_list
def gradio_ask(user_message, chatbot, chat_state):
# if len(user_message) == 0:
# return gr.update(interactive=True, placeholder='Input should not be empty!'), chatbot, chat_state
chat.ask(user_message, chat_state)
# chatbot = chatbot + [[user_message, None]]
return '', chatbot, chat_state
def gradio_answer(chatbot, chat_state, img_list, num_beams, temperature):
llm_message = chat.answer(conv=chat_state,
img_list=img_list,
num_beams=num_beams,
temperature=temperature,
max_new_tokens=300,
max_length=2000)[0]
return llm_message
# chatbot[-1][1] = llm_message
# return chatbot, chat_state, img_list
########################
num_beams = 1
temperature = 1
# chat_state = gr.State()
# img_list = gr.State()
chatbot = gr.Chatbot(label='MiniGPT-4')
# text_input = gr.Textbox(label='User', placeholder='Please upload your image first', interactive=False, value='Caption this image')
PROMPT = 'Is this a blank image? Describe it succinctly.'
def get_caption(image):
chat_state, img_list = upload_img(image)
# gradio_ask('Describe this image in detail.', chatbot, chat_state)
gradio_ask(PROMPT, chatbot, chat_state)
llm_message = gradio_answer(chatbot, chat_state, img_list, num_beams, temperature)
chat_state.messages = []
return llm_message
# chatbot, image, text_input, upload_button, chat_state, img_list = gradio_reset(chat_state, img_list)
# print(llm_message)
import csv
import json
import os
from tqdm import tqdm
import multiprocessing
os.makedirs('results', exist_ok=True)
def load_urls(path):
with open(path, 'r') as f:
if path.endswith('.txt') or path.endswith('.csv'):
return [line.strip() for line in f.readlines()]
elif path.endswith('.json'):
results = json.load(f)['results']
return [result['image_url'] for result in results]
else:
raise Exception('URL filetype not supported')
lock = multiprocessing.Lock()
def generate_captions(urls_path, pbar):
urls = load_urls(urls_path)
if len(urls) == 0:
return
out_name = os.path.basename(urls_path)
if os.path.exists(os.path.join('results', f'{out_name}.csv')):
with open(os.path.join('results', f'{out_name}.csv'), 'r') as f:
reader = csv.reader(f)
next(reader)
results = dict()
for row in reader:
results[row[1]] = row[2]
else:
results = dict()
for url in urls:
if 'https://' in url:
# if not url.startswith('http'):
url = url.split(',', 1)[1]
if url in results:
with lock:
pbar.update()
continue
try:
caption = get_caption(url)
results[url] = caption
except Exception as e:
print(e)
print(f'Failed for {url}')
if len(results) % 20 == 0:
with open(os.path.join('results', f'{out_name}.csv'), 'w', newline="") as f:
writer = csv.writer(f)
writer.writerow(['ID', 'URL', 'caption'])
for i, (key, value) in enumerate(results.items()):
writer.writerow([i, key, value])
with lock:
pbar.update()
with open(os.path.join('results', f'{out_name}.csv'), 'w', newline="") as f:
writer = csv.writer(f)
writer.writerow(['ID', 'URL', 'caption'])
for i, (key, value) in enumerate(results.items()):
writer.writerow([i, key, value])
print(f'Done with {urls_filename}')
if __name__ == '__main__':
urls_path = args.urls_path
# generate captions for a specific set of urls or all URL files in 'url_files'
if urls_path is None:
total = 0
for urls_filename in os.listdir('url_files'):
urls = load_urls(os.path.join('url_files', urls_filename))
total += len(urls)
pbar = tqdm(desc='Generating captions', total=total)
else:
urls = load_urls(os.path.join('url_files', urls_path))
total = len(urls)
pbar = tqdm(desc=f'Generating captions for {urls_path}', total=total)
if urls_path is None:
# threads = list() # TODO test multiprocessing
for urls_filename in os.listdir('url_files'):
urls_path = os.path.join('url_files', urls_filename)
generate_captions(urls_path, pbar)
# thread = multiprocessing.Process(target=generate_captions, args=(urls_filename, pbar))
# threads.append(thread)
# thread.start()
#
# for thread in threads:
# thread.join()
else:
generate_captions(urls_path, pbar)
pbar.close()