File size: 7,408 Bytes
032e687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os.path

from mmengine.model import BaseModel

from lmdeploy import pipeline, TurbomindEngineConfig
from lmdeploy.vl import load_image
import torch
import torch.nn as nn

class MLLM_Annotor(BaseModel):
    def __init__(self,
        model=None,
        save_folder='./work_dirs/internvl72b_sam2_obj_cap/'
        ):
        super().__init__()
        print(torch.cuda.device_count())
        pipe = pipeline(model,
                        backend_config=TurbomindEngineConfig(
                            # session_len=8192,
                            session_len=16000,
                            tp=torch.cuda.device_count()),
                        )
        self.pipe = [pipe]
        self._zero = nn.Linear(10, 10)
        self.results_list = []
        self.item_idx = 0

        if not os.path.exists(save_folder):
            os.mkdir(save_folder)
        self.save_folder = save_folder

    def forward(self, **kwargs):
        return None

    def predict_forward_sam2(self, data_dicts):
        prompts = []
        for data_dict in data_dicts:
            images = data_dict['images']
            texts = data_dict['text_prompt']
            prompts.append((texts, images))

        response_list = self.pipe[0](prompts)
        text_lsit = [item.text for item in response_list]

        results_list = []

        for i, text in enumerate(text_lsit):
            if '图' in text or len(text) < 15:
                # wrong response
                continue
            results_list.append({
                'video_id': data_dicts[i]['video_id'],
                'obj_id': data_dicts[i]['obj_id'],
                'caption': text,
                'type': data_dicts[i]['type'],
            })
            # print('\n\n', results_list[-1], '\n\n')

        self.results_list += results_list

        if len(self.results_list) > 100:
            self.save_step()
            print("Saved !!!")

        return {}

    def predict_forward_sam2_recap(self, data_dicts):
        prompts = []
        for data_dict in data_dicts:
            images = data_dict['images']
            texts = data_dict['text_prompt']
            prompts.append((texts, images))

        response_list = self.pipe[0](prompts)
        text_lsit = [item.text for item in response_list]

        results_list = []

        for i, text in enumerate(text_lsit):
            if '图' in text or len(text) < 15:
                # wrong response
                continue
            results_list.append({
                'video_id': data_dicts[i]['video_id'],
                'obj_id': data_dicts[i]['obj_id'],
                'crop_caption': data_dicts[i]['crop_caption'],
                'crop_category': data_dicts[i]['crop_category'],
                'caption': text,
            })
            # print('\n\n', prompts[i], '\n', results_list[-1], '\n\n')

        self.results_list += results_list

        if len(self.results_list) > 100:
            self.save_step()
            print("Saved !!!")

        return {}

    def predict_forward_sam2_video_recap(self, data_dicts):
        prompts = []
        for data_dict in data_dicts:
            images = data_dict['images']
            texts = data_dict['text_prompt']
            prompts.append((texts, images))

        response_list = self.pipe[0](prompts)
        text_lsit = [item.text for item in response_list]

        results_list = []

        for i, text in enumerate(text_lsit):
            if '图' in text or len(text) < 15:
                # wrong response
                continue
            results_list.append({
                'video_id': data_dicts[i]['video_id'],
                'obj_id': data_dicts[i]['obj_id'],
                'crop_caption': data_dicts[i]['crop_caption'],
                'crop_category': data_dicts[i]['crop_category'],
                'image_caption': data_dicts[i]['image_caption'],
                'video_caption': text,
            })
            # print('\n\n', prompts[i], '\n', results_list[-1], '\n\n')

        self.results_list += results_list

        if len(self.results_list) > 100:
            self.save_step()
            print("Saved !!!")

        return {}

    def predict_forward_image_dense_cap_objcap(self, data_dicts):
        prompts = []
        for data_dict in data_dicts:
            images = data_dict['images']
            texts = data_dict['text_prompt']
            prompts.append((texts, images))

        response_list = self.pipe[0](prompts)
        text_lsit = [item.text for item in response_list]

        results_list = []

        for i, text in enumerate(text_lsit):
            results_list.append({
                'image_id': data_dicts[i]['image_id'],
                'caption': text,
                'object_anno': data_dicts[i]['object_anno']
            })
            print('\n\n', prompts[i], '\n', results_list[-1], '\n\n')

        self.results_list += results_list

        if len(self.results_list) > 100:
            self.save_step()
            print("Saved !!!")

        return {}

    def predict_forward_image_dense_cap_overallcap(self, data_dicts):
        prompts = []
        for data_dict in data_dicts:
            images = data_dict['images']
            texts = data_dict['text_prompt']
            prompts.append((texts, images))

        response_list = self.pipe[0](prompts)
        text_lsit = [item.text for item in response_list]

        results_list = []

        for i, text in enumerate(text_lsit):
            results_list.append({
                'image_id': data_dicts[i]['image_id'],
                'caption': text,
            })
            print('\n\n', prompts[i], '\n', results_list[-1], '\n\n')

        self.results_list += results_list

        if len(self.results_list) > 100:
            self.save_step()
            print("Saved !!!")

        return {}

    def save_step(self, last=False):
        if last:
            save_list = self.results_list
        else:
            save_list = self.results_list[:100]
            self.results_list = self.results_list[100:]

        json_path = os.path.join(self.save_folder, f'{self.item_idx}.json')
        self.item_idx += 1
        with open(json_path, 'w') as f:
            json.dump(save_list, fp=f)
        return

    def predict_forward(self, image_paths, **kwargs):

        if 'type' in kwargs.keys() and kwargs['type'] == 'sam2':
            return self.predict_forward_sam2(kwargs['data_dicts'])
        elif 'type' in kwargs.keys() and kwargs['type'] == 'sam2_recap':
            return self.predict_forward_sam2_recap(kwargs['data_dicts'])
        elif 'type' in kwargs.keys() and kwargs['type'] == 'sam2_video_recap':
            return self.predict_forward_sam2_video_recap(kwargs['data_dicts'])
        elif 'type' in kwargs.keys() and kwargs['type'] == 'demo_imgcap':
            return self.predict_forward_image_dense_cap_objcap(kwargs['data_dicts'])
        elif 'type' in kwargs.keys() and kwargs['type'] == 'demo_imgcap_overall':
            return self.predict_forward_image_dense_cap_overallcap(kwargs['data_dicts'])

        images = [load_image(image_path) for image_path in image_paths]
        prompts = [('Please briefly describe this image in a sentence.', image) for image in images]
        response_list = self.pipe[0](prompts)
        text_lsit = [item.text for item in response_list]
        print(text_lsit)
        return {}