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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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import os
import json
import pickle
import random
import time
import itertools

import numpy as np
from PIL import Image
import skimage.io as io
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon, Rectangle
from torch.utils.data import Dataset
import webdataset as wds
from minigpt4.datasets.datasets.base_dataset import BaseDataset
from minigpt4.datasets.datasets.caption_datasets import CaptionDataset
from minigpt4.datasets.datasets.base_dataset import BaseDataset


class COYOCaptionWDSDataset(BaseDataset):
    def __init__(self, vis_processor, text_processor, location):
        super().__init__(vis_processor=vis_processor, text_processor=text_processor)
        """
        vis_root (string): Root directory of images (e.g. coco/images/)
        ann_root (string): directory to store the annotation file
        """

        self.inner_dataset = wds.DataPipeline(
            wds.ResampledShards(location),
            wds.tarfile_to_samples(handler=wds.warn_and_continue),
            wds.shuffle(1000, handler=wds.warn_and_continue),
            wds.decode("pilrgb", handler=wds.warn_and_continue),
            wds.to_tuple("jpg", "json"),
            wds.map_tuple(self.vis_processor, handler=wds.warn_and_continue),
            wds.map(self.to_dict, handler=wds.warn_and_continue),
        )
  
        self.instruction_pool = [
            '[grounding] Briefly describe this image with grounding objects.',
            '[grounding] Provide a concise depiction of this image with grounding objects.',
            '[grounding] Present a short description of this image with grounding objects.',
            '[grounding] Summarize this image in a few words with grounding objects.',
            '[grounding] A short image caption with grounding objects:',
            '[grounding] A short image description with grounding objects:',
            '[grounding] Write a short description for the image with grounding objects.',
            '[grounding] Write a description for the photo with grounding objects.',
            '[grounding] Briefly describe the content of the image with grounding objects.',
            '[grounding] Please provide a short depiction of the picture with grounding objects.',
        ]

        # self.instruction_pool = [
        #     '[grounding] Briefly describe this image.',
        #     '[grounding] Provide a concise depiction of this image.',
        #     '[grounding] Present a short description of this image.',
        #     '[grounding] Summarize this image in a few words.',
        #     '[grounding] A short image caption:',
        #     '[grounding] A short image description:',
        #     '[grounding] A photo of',
        #     '[grounding] An image that shows',
        #     '[grounding] Write a short description for the image.',
        #     '[grounding] Write a description for the photo.',
        #     '[grounding] Provide a description of what is presented in the photo.',
        #     '[grounding] Briefly describe the content of the image.',
        #     '[grounding] Can you briefly explain what you see in the image?',
        #     '[grounding] Could you use a few words to describe what you perceive in the photo?',
        #     '[grounding] Please provide a short depiction of the picture.',
        #     '[grounding] Using language, provide a short account of the image.',
        #     '[grounding] Use a few words to illustrate what is happening in the picture.',
        # ]

    def generate_ground_caption(self,image_caption, phrases, bounding_boxes):
        
        grounded_caption = image_caption
        
        # Iterate over the phrases and bounding boxes
        phrase_bbox={}
        for phrase, bbox in zip(phrases, bounding_boxes):
            # Replace the phrase with the grounded HTML format
            # print(phrase, bbox, type(phrase), type(bbox))

            if phrase not in phrase_bbox.keys():
                grounded_phrase = "<p>{}</p> ".format(phrase)
                grounded_phrase_bbox = grounded_phrase+str(bbox)
            else:
                grounded_phrase = phrase_bbox[phrase]

                grounded_phrase_bbox = grounded_phrase+"<delim>"+str(bbox)

            phrase_bbox[phrase] = grounded_phrase_bbox
            

        grounded_caption = grounded_caption.replace(phrase, grounded_phrase_bbox)
        
        return grounded_caption


    def preprocess_ground_caption(self, sample):

        # info = self.ann["data"][index]
        image_id = sample[1]["id"]


        caption = sample[1]["caption"]
        ref_exps = sample[1]["noun_chunks"]
        image_size = 100

        bboxs = []
        ref_phrases = []
        for item in ref_exps:
            phrase_start = int(item[0])
            phrase_end = int(item[1])

            x_min = item[2]
            y_min = item[3]
            x_max = item[4]
            y_max = item[5]
            ref_phrase = caption[phrase_start: phrase_end]

            x1 = int(x_min*image_size)
            y1 = int(y_min*image_size)
            x2 = int(x_max*image_size)
            y2 = int(y_max*image_size)
            assert x1>=0 and x1<=image_size
            assert x2>=0 and x2<=image_size
            assert y1>=0 and y1<=image_size
            assert y2>=0 and y2<=image_size
            # print(x1, y2, x2, y2)
            bbox = [str(x1),str(y1),str(x2),str(y2)]
            # bbox = "<"+str(x1)+"><"+str(y1)+"><"+str(x2)+"><"+str(y2)+">"
            bbox = "{{<{}><{}><{}><{}>}}".format(*bbox)
            bboxs.append(bbox)
            ref_phrases.append(ref_phrase)
        
        grounded_caption = self.generate_ground_caption(caption, ref_phrases,bboxs)
       


        return {
            "answer": grounded_caption
        }


    def to_dict(self, sample):
        data = self.preprocess_ground_caption(sample)

        instruction = random.choice(self.instruction_pool)
        instruction = "<Img><ImageHere></Img> {} ".format(instruction)

        answer = self.text_processor(data['answer'])
        return {
            "image": sample[0],
            "instruction_input": instruction,
            "answer": answer,
        }



class COYOBoxToPhraseWDSDataset(BaseDataset):
    def __init__(self, vis_processor, text_processor, location):
        super().__init__(vis_processor=vis_processor, text_processor=text_processor)
        """
        vis_root (string): Root directory of images (e.g. coco/images/)
        ann_root (string): directory to store the annotation file
        """

        self.inner_dataset = wds.DataPipeline(
            wds.ResampledShards(location),
            wds.tarfile_to_samples(handler=wds.warn_and_continue),
            wds.shuffle(1000, handler=wds.warn_and_continue),
            wds.decode("pilrgb", handler=wds.warn_and_continue),
            wds.to_tuple("jpg", "json", handler=wds.warn_and_continue),
            wds.map_tuple(self.vis_processor, handler=wds.warn_and_continue),
            wds.map(self.to_dict, handler=wds.warn_and_continue),
        )


        self.instruction_pool = [
            "[identify] {}",
            "[identify] what object is in this location {}",
            "[identify] identify the object present at this location {}",
            "[identify] what is it in {}",
            "[identify] describe this object in {}",
            "[identify] this {} is",
            "[identify] the object in {} is",
            ]
    def bbox_phrase_preprocess(self, sample):

        caption = sample[1]["caption"]
        # ref_exps = sample[1]["ref_exps"]
        ref_exps = sample[1]["noun_chunks"]
        image_size = 100

        bboxs = []
        ref_phrases = []
        for item in ref_exps:
            # print(item)
            phrase_start = int(item[0])
            phrase_end = int(item[1])

            x_min = item[2]
            y_min = item[3]
            x_max = item[4]
            y_max = item[5]
            ref_phrase = caption[phrase_start: phrase_end]

            x1 = int(x_min*image_size)
            y1 = int(y_min*image_size)
            x2 = int(x_max*image_size)
            y2 = int(y_max*image_size)
            assert x1>=0 and x1<=image_size
            assert x2>=0 and x2<=image_size
            assert y1>=0 and y1<=image_size
            assert y2>=0 and y2<=image_size

            bbox = [str(x1),str(y1),str(x2),str(y2)]

            
            # bbox = "<"+str(x1)+"><"+str(y1)+"><"+str(x2)+"><"+str(y2)+">"
            bbox = "{{<{}><{}><{}><{}>}}".format(*bbox)
            bboxs.append(bbox)
            ref_phrases.append(ref_phrase)

            # print(ref_phrase, bbox)

        index = random.randint(0, len(bboxs)-1)

        # Retrieve the corresponding elements
        sampled_bbox = bboxs[index]
        sampled_phrase = ref_phrases[index]

        return {
            "instruction_input": sampled_bbox,
            "answer": sampled_phrase,
        }

    def to_dict(self, sample):

        data = self.bbox_phrase_preprocess(sample)

        instruction = random.choice(self.instruction_pool).format(data['instruction_input'])
        instruction = "<Img><ImageHere></Img> {} ".format(instruction)

        answer = self.text_processor(data['answer'])

        return {
            "image": sample[0],
            "instruction_input": instruction,
            "answer": answer,
        }



class COYOPhraseToBoxWDSDataset(BaseDataset):
    def __init__(self, vis_processor, text_processor, location):
        super().__init__(vis_processor=vis_processor, text_processor=text_processor)
        """
        vis_root (string): Root directory of images (e.g. coco/images/)
        ann_root (string): directory to store the annotation file
        """

        self.inner_dataset = wds.DataPipeline(
            wds.ResampledShards(location),
            wds.tarfile_to_samples(handler=wds.warn_and_continue),
            wds.shuffle(1000, handler=wds.warn_and_continue),
            wds.decode("pilrgb", handler=wds.warn_and_continue),
            wds.to_tuple("jpg", "json", handler=wds.warn_and_continue),
            wds.map_tuple(self.vis_processor, handler=wds.warn_and_continue),
            wds.map(self.to_dict, handler=wds.warn_and_continue),
        )

        self.instruction_pool = [
            "[refer] {}",
            "[refer] give me the location of {}",
            "[refer] where is {} ?",
            "[refer] from this image, tell me the location of {}",
            "[refer] the location of {} is ",
            "[refer] could you tell me the location for {}?",
            "[refer] where can I locate the {}?",
        ]

        # self.instruction_pool = [
        #     # "[refer] {}",
        #     "[refer] give me the bounding box location of {}",
        #     "[refer] where is bounding box location of {} ?",
        #     "[refer] from this image, tell me the bounding box location of {}",
        #     "[refer] the bounding box location of {} is",
        #     "[refer] could you tell me the bounding box location for {} ?",
        #     "[refer] where can I locate the bounding box of {} ?",
        # ]
    def phrase_bbox_preprocess(self, sample):

        caption = sample[1]["caption"]
        ref_exps = sample[1]["ref_exps"]
        image_size = 100

        bboxs = []
        ref_phrases = []
        for item in ref_exps:
            phrase_start = int(item[0])
            phrase_end = int(item[1])

            x_min = item[2]
            y_min = item[3]
            x_max = item[4]
            y_max = item[5]
            ref_phrase = caption[phrase_start: phrase_end]

            x1 = int(x_min*image_size)
            y1 = int(y_min*image_size)
            x2 = int(x_max*image_size)
            y2 = int(y_max*image_size)
            assert x1>=0 and x1<=image_size
            assert x2>=0 and x2<=image_size
            assert y1>=0 and y1<=image_size
            assert y2>=0 and y2<=image_size
            
            # bbox = "<"+str(x1)+"><"+str(y1)+"><"+str(x2)+"><"+str(y2)+">"
            bbox = [str(x1),str(y1),str(x2),str(y2)]
            
            bbox = "{{<{}><{}><{}><{}>}}".format(*bbox)
            bboxs.append(bbox)
            ref_phrases.append(ref_phrase)

        index = random.randint(0, len(bboxs)-1)

        # Retrieve the corresponding elements
        sampled_bbox = bboxs[index]
        sampled_phrase = ref_phrases[index]

        return {
            "instruction_input": sampled_phrase,
            "answer": sampled_bbox,
        }


    def to_dict(self, sample):
        data = self.phrase_bbox_preprocess(sample)
        instruction_input = self.text_processor(data['instruction_input'])
        instruction = random.choice(self.instruction_pool).format(instruction_input)
        instruction = "<Img><ImageHere></Img> {} ".format(instruction)

        return {
            "image": sample[0],
            "instruction_input": instruction,
            "answer": data["answer"],
        }




# class COYOBBoxPhraseDataset(Dataset):
#     def __init__(self, vis_processor, text_processor, vis_root, ann_path):
#         """
#         vis_root (string): Root directory of images (e.g. coco/images/)
#         ann_root (string): directory to store the annotation file
#         """
#         self.vis_root = vis_root

#         self.vis_processor = vis_processor
#         self.text_processor = text_processor

#         self.ann = {"data":[]}

        
#         with open(ann_path, 'r') as f:
#             for line in f.readlines():
#                 line = line.strip()
#                 # print(line, type(line))
#                 try:
#                     item = json.loads(line.strip())
#                 except:
#                     print(line)
#                     # print(item)
#                     assert False

#                 # print(item, type(item))
#                 # assert False
#                 self.ann["data"].append(item)


#         self.bbox_phrase_instruction_pool = [
#             "<Img><ImageHere></Img> what object is in this bounding box location {} ",
#             "<Img><ImageHere></Img> what object is in this location {} ",
#             "<Img><ImageHere></Img> identify the object present at this location {} ",
#             "<Img><ImageHere></Img> what is it in bounding box location{} ",
#             "<Img><ImageHere></Img> describe this object in {} ",
#             "<Img><ImageHere></Img> this {} is ",
#             "<Img><ImageHere></Img> the object in {} is ",
#             "<Img><ImageHere></Img> please tell me what is inside the bounding box position {} ",
#             "<Img><ImageHere></Img> what can you find in the bounding box area at position {}? ",
#             "<Img><ImageHere></Img> what is the object occupying this area {} ",
#             "<Img><ImageHere></Img> could you identify the content within the bounding box located at {} ",
#             ]

#     def __len__(self):
#         return len(self.ann["data"])

#     def bbox_phrase_preprocess(self, index):

#         info = self.ann["data"][index]
#         image_id = info["id"]

#         image_file = str(image_id)+".jpg"
#         image_path = os.path.join(self.vis_root, image_file)
#         image = Image.open(image_path).convert("RGB")
#         image = self.vis_processor(image)

#         caption = info["caption"]
#         ref_exps = info["ref_exps"]
#         image_size = 100

#         bboxs = []
#         ref_phrases = []
#         for item in ref_exps:
#             # print(item)
#             phrase_start = int(item[0])
#             phrase_end = int(item[1])

#             x_min = item[2]
#             y_min = item[3]
#             x_max = item[4]
#             y_max = item[5]
#             ref_phrase = caption[phrase_start: phrase_end]

#             x1 = int(x_min*image_size)
#             y1 = int(y_min*image_size)
#             x2 = int(x_max*image_size)
#             y2 = int(y_max*image_size)
#             assert x1>=0 and x1<=image_size
#             assert x2>=0 and x2<=image_size
#             assert y1>=0 and y1<=image_size
#             assert y2>=0 and y2<=image_size

#             bbox = [str(x1),str(y1),str(x2),str(y2)]

            
#             # bbox = "<"+str(x1)+"><"+str(y1)+"><"+str(x2)+"><"+str(y2)+">"
#             bbox = "{{<{}><{}><{}><{}>}}".format(*bbox)
#             bboxs.append(bbox)
#             ref_phrases.append(ref_phrase)

#             # print(ref_phrase, bbox)

#         index = random.randint(0, len(bboxs)-1)

#         # Retrieve the corresponding elements
#         sampled_bbox = bboxs[index]
#         sampled_phrase = ref_phrases[index]

#         return {
#             "image": image,
#             "instruction_input": sampled_phrase,
#             "answer": sampled_bbox,
#             "image_id": info['id'],
#         }



#     def __getitem__(self, index):

#         data = self.preprocess(index)
#         instruction = random.choice(self.instruction_pool).format(data['instruction_input'])
#         return {
#             "image": data['image'],
#             "instruction_input": instruction,
#             "answer": data['answer'],
#             "image_id": data['image_id'],
#         }