-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-printer.py
More file actions
131 lines (102 loc) · 4.03 KB
/
json-printer.py
File metadata and controls
131 lines (102 loc) · 4.03 KB
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 json
from argparse import ArgumentParser
from os.path import exists
from ast import literal_eval
from figures import *
class JSONSyntaxError(Exception):
pass
def check_args(args):
print('Input file: ' + args.input_file)
input_file_splitted = args.input_file.split('.')
if len(input_file_splitted) != 2 or input_file_splitted[1] != 'json':
raise ValueError('Invalid input file name.')
if not exists(args.input_file):
raise ValueError('Input file doesn\'t exist.')
if args.output_file:
print('Output file: ' + args.output_file)
output_file_splitted = args.output_file.split('.')
if (len(output_file_splitted) != 1 and output_file_splitted[1] != 'png') or len(output_file_splitted) > 2:
raise ValueError('Invalid output file name.')
elif len(output_file_splitted) == 1:
args.output_file += '.png'
def rgb_to_html(rgb_tuple):
hex = "#"
for i in rgb_tuple:
# print(format(i, '02x'))
hex += format(i, '02x')
return hex
def get_color(palette, color):
if color[0] == '(':
result = rgb_to_html(literal_eval(color))
elif color in palette.keys():
result = palette[color]
elif color[0] == '#':
result = color
else:
raise JSONSyntaxError('Invalid JSON syntax - unknown color.')
return result
def parse_json(json_dict):
if not {'Figures', 'Screen', 'Palette'}.issubset(set(json_dict.keys())):
raise JSONSyntaxError('Invalid JSON syntax.')
figures = []
if not {'fg_color', 'bg_color', 'height', 'width'}.issubset(set(json_dict['Screen'].keys())):
raise JSONSyntaxError("Invalid JSON syntax - screen.")
screen_tmp = json_dict['Screen']
screen = Screen(screen_tmp['fg_color'], screen_tmp['bg_color'], screen_tmp['height'], screen_tmp['width'])
for fig in json_dict['Figures']:
fig_type = fig['type']
# print(fig)
if 'color' in fig:
color = get_color(json_dict['Palette'], fig['color'])
else:
color = screen.fg_color
if fig_type == 'point':
if 'x' not in fig or 'y' not in fig:
raise JSONSyntaxError('Invalid JSON syntax - point.')
figures.append(Point.create(color, fig))
elif fig_type == 'polygon':
if 'points' not in fig:
raise JSONSyntaxError('Invalid JSON syntax - polygon.')
figures.append(Polygon.create(color, fig))
elif fig_type == 'rectangle':
if not {'x', 'y', 'height', 'width'}.issubset(set(fig.keys())):
raise JSONSyntaxError('Invalid JSON syntax - rectangle.')
figures.append(Rectangle.create(color, fig))
elif fig_type == 'square':
if not {'x', 'y', 'size'}.issubset(set(fig.keys())):
raise JSONSyntaxError('Invalid JSON syntax - square.')
figures.append(Square.create(color, fig))
elif fig_type == 'circle':
if not {'x', 'y', 'radius'}.issubset(set(fig.keys())):
raise JSONSyntaxError('Invalid JSON syntax - circle.')
figures.append(Circle.create(color, fig))
return screen, figures
def draw(args, figures, screen):
picture = screen.canvas
picture.artists.append(screen.background)
for fig in figures:
picture.artists.append(fig.artist())
plt.show()
if args.output_file:
picture.savefig(args.output_file)
def main():
parser = ArgumentParser()
parser.add_argument("input_file", help="input file name")
parser.add_argument("-o", "--output_file", nargs="?", help="output file name (optional)")
args = parser.parse_args()
try:
check_args(args)
except Exception as e:
print('Error: ' + str(e))
exit(1)
with open(args.input_file, 'r') as f:
json_dict = json.load(f)
print()
try:
screen, figures = parse_json(json_dict)
draw(args, figures, screen)
except Exception as e:
print('Error: ' + str(e))
exit(1)
if __name__ == "__main__":
main()