OCDC
[mygpt.git] / picoclvr.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import torch, torchvision
9
10 colors = [
11     [ 255, 255, 255 ], [ 255, 0, 0 ], [ 0, 128, 0 ], [ 0, 0, 255 ], [ 255, 255, 0 ],
12     [ 0, 0, 0 ], [ 128, 0, 0 ], [ 139, 0, 0 ], [ 165, 42, 42 ], [ 178, 34, 34 ],
13     [ 220, 20, 60 ], [ 255, 99, 71 ], [ 255, 127, 80 ], [ 205, 92, 92 ], [ 240, 128, 128 ],
14     [ 233, 150, 122 ], [ 250, 128, 114 ], [ 255, 160, 122 ], [ 255, 69, 0 ], [ 255, 140, 0 ],
15     [ 255, 165, 0 ], [ 255, 215, 0 ], [ 184, 134, 11 ], [ 218, 165, 32 ], [ 238, 232, 170 ],
16     [ 189, 183, 107 ], [ 240, 230, 140 ], [ 128, 128, 0 ], [ 154, 205, 50 ], [ 85, 107, 47 ],
17     [ 107, 142, 35 ], [ 124, 252, 0 ], [ 127, 255, 0 ], [ 173, 255, 47 ], [ 0, 100, 0 ],
18     [ 34, 139, 34 ], [ 0, 255, 0 ], [ 50, 205, 50 ], [ 144, 238, 144 ], [ 152, 251, 152 ],
19     [ 143, 188, 143 ], [ 0, 250, 154 ], [ 0, 255, 127 ], [ 46, 139, 87 ], [ 102, 205, 170 ],
20     [ 60, 179, 113 ], [ 32, 178, 170 ], [ 47, 79, 79 ], [ 0, 128, 128 ], [ 0, 139, 139 ],
21     [ 0, 255, 255 ], [ 0, 255, 255 ], [ 224, 255, 255 ], [ 0, 206, 209 ], [ 64, 224, 208 ],
22     [ 72, 209, 204 ], [ 175, 238, 238 ], [ 127, 255, 212 ], [ 176, 224, 230 ], [ 95, 158, 160 ],
23     [ 70, 130, 180 ], [ 100, 149, 237 ], [ 0, 191, 255 ], [ 30, 144, 255 ], [ 173, 216, 230 ],
24     [ 135, 206, 235 ], [ 135, 206, 250 ], [ 25, 25, 112 ], [ 0, 0, 128 ], [ 0, 0, 139 ],
25     [ 0, 0, 205 ], [ 65, 105, 225 ], [ 138, 43, 226 ], [ 75, 0, 130 ], [ 72, 61, 139 ],
26     [ 106, 90, 205 ], [ 123, 104, 238 ], [ 147, 112, 219 ], [ 139, 0, 139 ], [ 148, 0, 211 ],
27     [ 153, 50, 204 ], [ 186, 85, 211 ], [ 128, 0, 128 ], [ 216, 191, 216 ], [ 221, 160, 221 ],
28     [ 238, 130, 238 ], [ 255, 0, 255 ], [ 218, 112, 214 ], [ 199, 21, 133 ], [ 219, 112, 147 ],
29     [ 255, 20, 147 ], [ 255, 105, 180 ], [ 255, 182, 193 ], [ 255, 192, 203 ], [ 250, 235, 215 ],
30     [ 245, 245, 220 ], [ 255, 228, 196 ], [ 255, 235, 205 ], [ 245, 222, 179 ], [ 255, 248, 220 ],
31     [ 255, 250, 205 ], [ 250, 250, 210 ], [ 255, 255, 224 ], [ 139, 69, 19 ], [ 160, 82, 45 ],
32     [ 210, 105, 30 ], [ 205, 133, 63 ], [ 244, 164, 96 ], [ 222, 184, 135 ], [ 210, 180, 140 ],
33     [ 188, 143, 143 ], [ 255, 228, 181 ], [ 255, 222, 173 ], [ 255, 218, 185 ], [ 255, 228, 225 ],
34     [ 255, 240, 245 ], [ 250, 240, 230 ], [ 253, 245, 230 ], [ 255, 239, 213 ], [ 255, 245, 238 ],
35     [ 245, 255, 250 ], [ 112, 128, 144 ], [ 119, 136, 153 ], [ 176, 196, 222 ], [ 230, 230, 250 ],
36     [ 255, 250, 240 ], [ 240, 248, 255 ], [ 248, 248, 255 ], [ 240, 255, 240 ], [ 255, 255, 240 ],
37     [ 240, 255, 255 ], [ 255, 250, 250 ], [ 192, 192, 192 ], [ 220, 220, 220 ], [ 245, 245, 245 ],
38 ]
39
40 color_names = [
41     'white', 'red', 'green', 'blue', 'yellow',
42     'black', 'maroon', 'dark_red', 'brown', 'firebrick',
43     'crimson', 'tomato', 'coral', 'indian_red', 'light_coral',
44     'dark_salmon', 'salmon', 'light_salmon', 'orange_red', 'dark_orange',
45     'orange', 'gold', 'dark_golden_rod', 'golden_rod', 'pale_golden_rod',
46     'dark_khaki', 'khaki', 'olive', 'yellow_green', 'dark_olive_green',
47     'olive_drab', 'lawn_green', 'chartreuse', 'green_yellow', 'dark_green',
48     'forest_green', 'lime', 'lime_green', 'light_green', 'pale_green',
49     'dark_sea_green', 'medium_spring_green', 'spring_green', 'sea_green', 'medium_aqua_marine',
50     'medium_sea_green', 'light_sea_green', 'dark_slate_gray', 'teal', 'dark_cyan',
51     'aqua', 'cyan', 'light_cyan', 'dark_turquoise', 'turquoise',
52     'medium_turquoise', 'pale_turquoise', 'aqua_marine', 'powder_blue', 'cadet_blue',
53     'steel_blue', 'corn_flower_blue', 'deep_sky_blue', 'dodger_blue', 'light_blue',
54     'sky_blue', 'light_sky_blue', 'midnight_blue', 'navy', 'dark_blue',
55     'medium_blue', 'royal_blue', 'blue_violet', 'indigo', 'dark_slate_blue',
56     'slate_blue', 'medium_slate_blue', 'medium_purple', 'dark_magenta', 'dark_violet',
57     'dark_orchid', 'medium_orchid', 'purple', 'thistle', 'plum',
58     'violet', 'magenta', 'orchid', 'medium_violet_red', 'pale_violet_red',
59     'deep_pink', 'hot_pink', 'light_pink', 'pink', 'antique_white',
60     'beige', 'bisque', 'blanched_almond', 'wheat', 'corn_silk',
61     'lemon_chiffon', 'light_golden_rod_yellow', 'light_yellow', 'saddle_brown', 'sienna',
62     'chocolate', 'peru', 'sandy_brown', 'burly_wood', 'tan',
63     'rosy_brown', 'moccasin', 'navajo_white', 'peach_puff', 'misty_rose',
64     'lavender_blush', 'linen', 'old_lace', 'papaya_whip', 'sea_shell',
65     'mint_cream', 'slate_gray', 'light_slate_gray', 'light_steel_blue', 'lavender',
66     'floral_white', 'alice_blue', 'ghost_white', 'honeydew', 'ivory',
67     'azure', 'snow', 'silver', 'gainsboro', 'white_smoke',
68 ]
69
70 color_id = dict( [ (n, k) for k, n in enumerate(color_names) ] )
71 color_tokens = dict( [ (n, c) for n, c in zip(color_names, colors) ] )
72
73 ######################################################################
74
75 def all_properties(height, width, nb_squares, square_i, square_j, square_c):
76     s = [ ]
77
78     for r, c in [ (k, color_names[square_c[k]]) for k in range(nb_squares) ]:
79         s += [ f'there is {c}' ]
80
81         if square_i[r] >= height - height//3: s += [ f'{c} bottom' ]
82         if square_i[r] < height//3: s += [ f'{c} top' ]
83         if square_j[r] >= width - width//3: s += [ f'{c} right' ]
84         if square_j[r] < width//3: s += [ f'{c} left' ]
85
86         for t, d in [ (k, color_names[square_c[k]]) for k in range(nb_squares) ]:
87             if square_i[r] > square_i[t]: s += [ f'{c} below {d}' ]
88             if square_i[r] < square_i[t]: s += [ f'{c} above {d}' ]
89             if square_j[r] > square_j[t]: s += [ f'{c} right of {d}' ]
90             if square_j[r] < square_j[t]: s += [ f'{c} left of {d}' ]
91
92     return s
93
94 ######################################################################
95
96 def generate(nb, height, width,
97              max_nb_squares = 5, max_nb_properties = 10,
98              nb_colors = 5):
99
100     assert nb_colors >= max_nb_squares and nb_colors <= len(color_tokens) - 1
101
102     descr = [ ]
103
104     for n in range(nb):
105
106         nb_squares = torch.randint(max_nb_squares, (1,)) + 1
107         square_position = torch.randperm(height * width)[:nb_squares]
108         # color 0 is white and reserved for the background
109         square_c = torch.randperm(nb_colors)[:nb_squares] + 1
110         square_i = square_position.div(width, rounding_mode = 'floor')
111         square_j = square_position % width
112
113         img = [ 0 ] * height * width
114         for k in range(nb_squares): img[square_position[k]] = square_c[k]
115
116         # generates all the true properties
117
118         s = all_properties(height, width, nb_squares, square_i, square_j, square_c)
119
120         # pick at most max_nb_properties at random
121
122         nb_properties = torch.randint(max_nb_properties, (1,)) + 1
123         s = ' <sep> '.join([ s[k] for k in torch.randperm(len(s))[:nb_properties] ] )
124         s += ' <img> ' + ' '.join([ f'{color_names[n]}' for n in img ])
125
126         descr += [ s ]
127
128     return descr
129
130 ######################################################################
131
132 def descr2img(descr, height, width):
133
134     if type(descr) == list:
135         return torch.cat([ descr2img(d, height, width) for d in descr ], 0)
136
137     def token2color(t):
138         try:
139             return color_tokens[t]
140         except KeyError:
141             return [ 128, 128, 128 ]
142
143     d = descr.split('<img>', 1)
144     d = d[-1] if len(d) > 1 else ''
145     d = d.strip().split(' ')[:height * width]
146     d = d + [ '<unk>' ] * (height * width - len(d))
147     d = [ token2color(t) for t in d ]
148     img = torch.tensor(d).permute(1, 0)
149     img = img.reshape(1, 3, height, width)
150
151     return img
152
153 ######################################################################
154
155 def descr2properties(descr, height, width):
156
157     if type(descr) == list:
158         return [ descr2properties(d, height, width) for d in descr ]
159
160     d = descr.split('<img>', 1)
161     d = d[-1] if len(d) > 1 else ''
162     d = d.strip().split(' ')[:height * width]
163
164     seen = {}
165     if len(d) != height * width: return []
166     for k, x in enumerate(d):
167         if x != color_names[0]:
168             if x in color_tokens:
169                 if x in seen: return []
170             else:
171                 return []
172             seen[x] = (color_id[x], k // width, k % width)
173
174     square_c = torch.tensor( [ x[0] for x in seen.values() ] )
175     square_i = torch.tensor( [ x[1] for x in seen.values() ] )
176     square_j = torch.tensor( [ x[2] for x in seen.values() ] )
177
178     s = all_properties(height, width, len(seen), square_i, square_j, square_c)
179
180     return s
181
182 ######################################################################
183
184 def nb_properties(descr, height, width):
185     if type(descr) == list:
186         return [ nb_properties(d, height, width) for d in descr ]
187
188     d = descr.split('<img>', 1)
189     if len(d) == 0: return 0
190     d = d[0].strip().split('<sep>')
191     d = [ x.strip() for x in d ]
192
193     requested_properties = set(d)
194     all_properties = set(descr2properties(descr, height, width))
195     missing_properties = requested_properties - all_properties
196
197     return (len(requested_properties), len(all_properties), len(missing_properties))
198
199 ######################################################################
200
201 if __name__ == '__main__':
202     descr = generate(nb = 5)
203
204     #print(descr2properties(descr))
205     print(nb_properties(descr))
206
207     with open('picoclvr_example.txt', 'w') as f:
208         for d in descr:
209             f.write(f'{d}\n\n')
210
211     img = descr2img(descr)
212     torchvision.utils.save_image(img / 255.,
213                                  'picoclvr_example.png', nrow = 16, pad_value = 0.8)
214
215     import time
216
217     start_time = time.perf_counter()
218     descr = generate(nb = 1000)
219     end_time = time.perf_counter()
220     print(f'{len(descr) / (end_time - start_time):.02f} samples per second')
221
222 ######################################################################