SMPQA / generate /generate_data.py
Gregor's picture
Upload 9 files
f9c9337 verified
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}")