File size: 4,920 Bytes
30ab71c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from pprint import pprint
from omegaconf import OmegaConf
from PIL import Image, ImageDraw
import streamlit as st

os.environ['ROOT'] = os.path.dirname(os.path.realpath(__file__))
# print("ROOT", os.environ['ROOT'])

class ImageRetriever:

    def __init__(self, root_path, anno_path):
        self.root_path = Path(root_path)
        self.anno = json.load(open(anno_path))

    def key2img_path(self, key):
        file_paths = [
            self.root_path / f"images/{key}.jpg",
            self.root_path / f"images/{key}.png",
            self.root_path / f"var_images/{key}.jpg",
            self.root_path / f"var_images/{key}.png",
            self.root_path / f"images/{key}.jpg",
            self.root_path / f"img/train/{key.split('_')[0]}/{key}.png",
            self.root_path / f"img/val/{key.split('_')[0]}/{key}.png",
            self.root_path / f"img/test/{key.split('_')[0]}/{key}.png",
        ]
        for file_path in file_paths:
            if file_path.exists():
                return file_path

    def key2img(self, key, draw_bbox=True):
        file_path = self.key2img_path(key)

        image = Image.open(file_path)
        if draw_bbox:
            meta = self.anno[key]['details'][-1]
            bboxes = [meta['bounding_box'].get(str(box_idx + 1), None) for box_idx in range(3)]
            image = self.hide_region(image, bboxes)
        return image

    def hide_region(self, image, bboxes):
        self.hide_true_bbox = 2

        image = image.convert('RGBA')

        if self.hide_true_bbox == 1:  # hide mode
            draw = ImageDraw.Draw(image, 'RGBA')

        if self.hide_true_bbox in [2, 5, 7, 8, 9]:  #highlight mode
            overlay = Image.new('RGBA', image.size, '#00000000')
            draw = ImageDraw.Draw(overlay, 'RGBA')

        if self.hide_true_bbox == 3 or self.hide_true_bbox == 6:  #blackout mode or position only mode
            overlay = Image.new('RGBA', image.size, '#7B7575ff')
            draw = ImageDraw.Draw(overlay, 'RGBA')

        color_fill_list = ['#ff05cd3c', '#00F1E83c', '#F2D4003c']  # Green, Blue, Yellow?

        for idx, bbox in enumerate(bboxes):
            if bbox == None:
                continue

            color_fill = color_fill_list[idx]
            x, y = bbox['left'], bbox['top']

            if self.hide_true_bbox == 1:  # hide mode
                draw.rectangle([(x, y), (x + bbox['width'], y + bbox['height'])], fill='#7B7575')
            elif self.hide_true_bbox in [2, 5, 7, 8, 9]:  # highlight mode
                draw.rectangle([(x, y), (x + bbox['width'], y + bbox['height'])], fill=color_fill, outline='#05ff37ff',
                               width=3)  # Fill with Pink 60% ##00F1E8
            elif self.hide_true_bbox == 3:  # blackout mode
                draw.rectangle([(x, y), (x + bbox['width'], y + bbox['height'])], fill='#00000000')
            elif self.hide_true_bbox == 6:  # position only mode
                draw.rectangle([(x, y), (x + bbox['width'], y + bbox['height'])], fill=color_fill)

        if self.hide_true_bbox in [2, 3, 5, 6, 7, 8, 9]:
            image = Image.alpha_composite(image, overlay)
        return image


def main(mode='spec', split='val', which='best'):
    result_dict = json.load(open(os.path.join(os.environ['ROOT'], f"{mode}_{split}_demo.json")))
    main_dataset = json.load(open(os.path.join(os.environ['ROOT'], f"anno_{split}_combined.json")))

    which_keys = {'best': [], 'worst': []}
    message_dict = {}

    for file_key in result_dict.keys():
        if file_key == 'settings':
            continue

        annotated_hazard = result_dict[file_key]['annotated_hazard']
        annotated_rank = result_dict[file_key]['annotated_rank']

        res = result_dict[file_key]

        message = {'annotated_hazard': f"{int(annotated_rank)} - {annotated_hazard}"}
        message['hazard'] = [f"rank: {int(tup[0])}, score: {tup[1]}, sent: {tup[2]}" for tup in zip(res['rank'], res['chatgpt_score'], res['hazard'])]
        message_dict[file_key] = message

        if 1 <= annotated_rank <= 20:
            which_keys['best'].append(file_key)

        if annotated_rank > 100:
            which_keys['worst'].append(file_key)

    img_retriever = ImageRetriever(
        root_path=os.path.join(os.environ['ROOT'], ''),
        anno_path=os.path.join(os.environ['ROOT'], f'anno_{split}_combined.json'),
    )
    
    # st.write(f"Total cases: {len(which_keys[which])}")
    st.write("---")

    for file_key in which_keys[which]:
        # st.write(f"File key: {file_key}")

        img = img_retriever.key2img(file_key)
        # img = img.resize((img.width // 3, img.height // 3))

        st.image(img)
        st.json(message_dict[file_key])
        st.write('---')


if __name__ == '__main__':
    main(mode='spec', split='val', which='best')