File size: 9,618 Bytes
f9c9337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
226
227
228
229
230
231
232
import json
import os
import matplotlib.pyplot as plt
import numpy as np
import random
import requests
import matplotlib
import matplotlib.font_manager as font_manager
from tqdm import tqdm

# Load a font from TTF file,
# relative to this Python module
# https://stackoverflow.com/a/69016300/315168

#https://github.com/satbyy/go-noto-universal/releases/tag/v7.0
font_path = os.path.join(os.path.dirname(__file__), 'GoNotoKurrent-Regular.ttf')
assert os.path.exists(font_path)
font_manager.fontManager.addfont(font_path)
prop = font_manager.FontProperties(fname=font_path)
#  Set it as default matplotlib font
matplotlib.rc('font', family='sans-serif')
matplotlib.rcParams.update({
    'font.size': 26,
    'font.sans-serif': prop.get_name(),
})

def load_wordlist(lang):
    #https://github.com/frekwencja/most-common-words-multilingual
    os.makedirs("lists", exist_ok=True)
    if os.path.exists(f"lists/{lang}.json"):
        lines = json.load(open(f"lists/{lang}.json", "r"))
    else:
        data = requests.get(f"https://raw.githubusercontent.com/frekwencja/most-common-words-multilingual/main/data/wordfrequency.info/{lang}.txt").text  # it's a file like object and works just like a file
        lines = data.split("\n")
        lines = lines[int(len(lines) / 2):]
        json.dump(lines, open(f"lists/{lang}.json", "w"))
    return lines


def generate_bar_plot_configurations(n):
    configurations = []
    for _ in range(n):
        num_bars = random.randint(4, 8)
        config = {
            'num_bars': num_bars,
            'orientation': random.choice(['vertical', 'horizontal']),
            'values': [random.randint(30, 100) for _ in range(num_bars)],
            'colors': random.sample(
                ['blue', 'green', 'red', 'yellow', 'black', 'orange', 'purple', 'brown'],
                num_bars),
            'figsize': (random.uniform(5, 10), random.uniform(3, 8))
        }
        configurations.append(config)
    return configurations

def generate_pie_plot_configurations(n):
    configurations = []
    for _ in range(n):
        num_slices = random.randint(4, 8)
        config = {
            'num_slices': num_slices,
            'values': [random.randint(10, 200) for _ in range(num_slices)],
            'labels': [f'Label {i + 1}' for i in range(num_slices)],
            'colors': random.sample(
                ['blue', 'green', 'red', 'yellow', 'cyan', 'orange', 'purple', 'brown'],
                num_slices),
            'explode': [0.1 if random.random() > 0.8 else 0 for _ in range(num_slices)],  # Randomly explode some slices
            'figsize': (random.uniform(5, 10), random.uniform(5, 10))
        }
        configurations.append(config)
    return configurations


def create_and_save_pie_plots(configurations, language, output_dir='pie_plots'):
    word_list = load_wordlist(language)

    annotations = []
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for i, config in tqdm(enumerate(configurations)):
        config["labels"] = random.sample(word_list, config["num_slices"])
        plt.figure(figsize=config['figsize'])

        plt.pie(config['values'], labels=config['labels'], colors=config['colors'], explode=config['explode'],
                autopct='%1.1f%%', startangle=140)

        plt.tight_layout()
        plt.savefig(os.path.join(output_dir, f'pie_plot_{i}.png'))
        plt.close()
        

        half = int(config['num_slices']//2)

        questions_name = [
            f"What is the label of the biggest slice?",
            f"What is the label of the smallest slice?",
            f"What is the label of the {config['colors'][0]} slice?",
            f"What is the label of the {config['colors'][-1]} slice?",
            f"What is the label of the {config['colors'][half]} slice?",
        ]
        answer_name = [
            config["labels"][np.argmax(config['values'])],
            config["labels"][np.argmin(config['values'])],
            config["labels"][0],
            config["labels"][-1],
            config["labels"][half],
        ]

        question_ground = [
            f"Is the slice with label '{config['labels'][np.argmax(config['values'])]}' the biggest?",
            f"Is the slice with label '{config['labels'][(np.argmax(config['values'])+half)%config['num_slices']]}' the biggest?",
            f"Is the slice with label '{config['labels'][np.argmin(config['values'])]}' the smallest?",
            f"Is the slice with label '{config['labels'][(np.argmin(config['values'])+half)%config['num_slices']]}' the smallest?",
            f"Is the slice with label '{config['labels'][0]}' colored in {config['colors'][0]}?",
            f"Is the slice with label '{config['labels'][0]}' colored in {config['colors'][0+half]}?",
            f"Is the slice with label '{config['labels'][half]}' colored in {config['colors'][half]}?",
            f"Is the slice with label '{config['labels'][half]}' colored in {config['colors'][-1]}?",
        ]
        answer_ground = [
            "yes", "no",
            "yes", "no",
            "yes", "no",
            "yes", "no",
        ]


        annotation = {
            "image": f'pie_plot_{i}.png',
            "question_ground": question_ground,
            "answer_ground": answer_ground,
            "questions_name": questions_name,
            "answer_name": answer_name,
        }

        annotations.append(annotation)
    json.dump(annotations, open(os.path.join(output_dir, f'pie_annotations_{language}.json'), 'w', encoding='utf-8'), indent=4)




def create_and_save_bar_plots(configurations, language, output_dir='bar_plots'):
    word_list = load_wordlist(language)

    annotations = []

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for i, config in tqdm(enumerate(configurations)):
        config["labels"] = random.sample(word_list, config["num_bars"])

        plt.figure(figsize=config['figsize'])

        if config['orientation'] == 'vertical':
            plt.bar(config['labels'], config['values'], color=config['colors'])
            plt.gcf().autofmt_xdate()
        else:
            plt.barh(config['labels'], config['values'], color=config['colors'])
        plt.tight_layout()
        plt.savefig(os.path.join(output_dir, f'bar_plot_{i}.png'))
        plt.close()


        half = int(config['num_bars']//2)

        questions_name = [
            f"What is the label of the biggest bar?",
            f"What is the label of the smallest bar?",
            f"What is the label of the {config['colors'][0]} bar?",
            f"What is the label of the {config['colors'][-1]} bar?",
            f"What is the label of the {config['colors'][half]} bar?",
        ]
        answer_name = [
            config["labels"][np.argmax(config['values'])],
            config["labels"][np.argmin(config['values'])],
            config["labels"][0],
            config["labels"][-1],
            config["labels"][half],
        ]

        question_ground = [
            f"Is the bar with label '{config['labels'][np.argmax(config['values'])]}' the biggest?",
            f"Is the bar with label '{config['labels'][(np.argmax(config['values'])+half)%config['num_bars']]}' the biggest?",
            f"Is the bar with label '{config['labels'][np.argmin(config['values'])]}' the smallest?",
            f"Is the bar with label '{config['labels'][(np.argmin(config['values'])+half)%config['num_bars']]}' the smallest?",
            f"Is the bar with label '{config['labels'][0]}' colored in {config['colors'][0]}?",
            f"Is the bar with label '{config['labels'][0]}' colored in {config['colors'][0+half]}?",
            f"Is the bar with label '{config['labels'][half]}' colored in {config['colors'][half]}?",
            f"Is the bar with label '{config['labels'][half]}' colored in {config['colors'][-1]}?",
        ]
        answer_ground = [
            "yes", "no",
            "yes", "no",
            "yes", "no",
            "yes", "no",
        ]


        annotation = {
            "image": f'bar_plot_{i}.png',
            "question_ground": question_ground,
            "answer_ground": answer_ground,
            "questions_name": questions_name,
            "answer_name": answer_name,
        }

        annotations.append(annotation)
    json.dump(annotations, open(os.path.join(output_dir, f'bar_annotations_{language}.json'), 'w', encoding='utf-8'), indent=4)


if __name__ == '__main__':
    languages = ["en", "zu", "id", "it", "de", "th", "ar", "ko", "zh-CN", "ru", "hi"]

    if not os.path.exists("bar_configs.json"):
        bar_configs = generate_bar_plot_configurations(50)
        json.dump(bar_configs, open("bar_configs.json", "w"))
    else:
        bar_configs = json.load(open("bar_configs.json"))

    if not os.path.exists("pie_configs.json"):
        pie_configs = generate_pie_plot_configurations(50)
        json.dump(pie_configs, open("pie_configs.json", "w"))
    else:
        pie_configs = json.load(open("pie_configs.json"))

    for language in languages:
        print(language)
        os.makedirs(f"/media/gregor/DATA/datasets/smpqa/{language}", exist_ok=True)
        create_and_save_bar_plots(bar_configs, language, output_dir=f"/media/gregor/DATA/datasets/smpqa/{language}")
        create_and_save_pie_plots(pie_configs, language, output_dir=f"/media/gregor/DATA/datasets/smpqa/{language}")