-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcore.py
190 lines (151 loc) · 7.65 KB
/
core.py
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
import os
import requests
import threading
from utils import rgb_to_hex, get_foreground_color
def get_file(file, token):
response = requests.get(f"https://api.figma.com/v1/files/{file}", headers={'X-FIGMA-TOKEN': token})
if response.status_code == 200:
return response.json()
else:
return response.status_code, response.text
def download_image(file, id, name, token, out=None, frame=None):
response = requests.get(f"https://api.figma.com/v1/images/{file}", headers={'X-FIGMA-TOKEN': token}, params={'ids': id})
if response.status_code == 200:
json_data = response.json()
image_url = json_data.get('images', {}).get(id)
if image_url:
if frame is not None:
folder_path = os.path.join(out, 'TkForge/assets', f'frame_{frame}') if out else os.path.join('TkForge/assets', f'frame_{frame}')
else:
folder_path = os.path.join(out, 'TkForge/assets') if out else 'TkForge/assets'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
file_name = f'{name}.png'
file_path = os.path.join(folder_path, file_name)
image_response = requests.get(image_url)
if image_response.status_code == 200:
with open(file_path, 'wb') as f:
f.write(image_response.content)
if frame is not None:
return os.path.join(f'frame_{frame}', file_name).replace('\\', '/')
else:
return file_name
else:
print("Failed to download the image.")
else:
print("No image URL found for the specified ID.")
else:
print("Failed to retrieve image URL.")
return None
def parse_file(file, token, download_images=True, out=None):
output = []
result = get_file(file, token)
if isinstance(result, tuple):
return []
try:
frames = result['document']['children'][0]['children']
frame_count = 1 if len(frames) > 1 else 0
# import json
# print(json.dumps(frames, indent=4, sort_keys=True))
def parse_frame(frame, frame_count):
nonlocal output
parsed = []
image_count = 0
entry_placeholder = False
text_placeholder = False
for i in frame['children']:
if 'absoluteBoundingBox' in i:
bounds = i['absoluteBoundingBox']
else:
bounds = i['absoluteRenderBounds']
items = ["image", "button", "label", "scale", "listbox", "textbox", "textarea", "rectangle", "spinbox", "circle", "oval", "line"]
type = i['name'].split(' ', 1)[0].lower()
type = type if type in items else "text"
i['type'] = type
i['x'] = abs(int(frame['absoluteBoundingBox']['x']) - int(bounds['x']))
i['y'] = abs(int(frame['absoluteBoundingBox']['y']) - int(bounds['y']))
i['width'] = int(bounds['width'])
i['height'] = int(bounds['height'])
i['background'] = None
bg_color = i.get('backgroundColor') or \
(i.get('background', [{}])[0].get('color') if i.get('background') else None) or \
(i.get('fills', [{}])[0].get('color') if i.get('fills') else "#000000")
if bg_color and bg_color != "#000000":
i['background'] = rgb_to_hex(bg_color['r'], bg_color['g'], bg_color['b'])
fg = get_foreground_color(bg_color['r'], bg_color['g'], bg_color['b'])
if fg == i['background']:
i['foreground'] = '#ffffff' if fg == '#000000' else '#000000' if fg == '#ffffff' else fg
else:
i['foreground'] = fg
else:
i['background'] = "#000000"
i['foreground'] = "#FFFFFF"
def download(name):
nonlocal i
image = download_image(file, i['id'], name, token, out, frame_count) if frame_count > 0 else download_image(file, i['id'], name, token, out)
if image:
i['image'] = image
else:
i['image'] = None
if (i.get('strokes') and not i.get('strokes') == []):
stroke_color = i.get('strokes', [{}])[0].get('color')
i['stroke_color'] = rgb_to_hex(stroke_color['r'], stroke_color['g'], stroke_color['b'])
if type in ['text', 'label']:
i['text'] = i.get('characters', '').replace('\n', '\\n')
style = i.get('style', {})
i['font'] = style.get('fontFamily', 'Default Font')
i['font_size'] = int(style.get('fontSize', 12))
elif type == 'image':
parts = i['name'].split(' ')
name = " ".join(parts[1:])
if not name.replace(' ', '') == '':
download(name)
else:
image_count += 1
download(str(image_count))
elif type == 'scale':
scale = i['name'].split(' ')
i['from'] = int(scale[1])
i['to'] = int(scale[2])
i['orient'] = scale[3] if len(scale) > 3 else "HORIZONTAL"
elif type in ['textbox', 'textarea']:
parts = i['name'].split(' ')
placeholder = " ".join(parts[1:])
if not placeholder.replace(' ', '') == '':
i['placeholder'] = placeholder
if type == 'textbox':
entry_placeholder = True
elif type == 'textarea':
text_placeholder = True
elif type == 'button' and download_images:
image_count += 1
download(image_count)
parsed.append(i)
frame_bg = frame.get('backgroundColor') or \
(frame.get('background', [{}])[0].get('color') if frame.get('background') else None) or \
(frame.get('fills', [{}])[0].get('color') if frame.get('fills') else None)
if frame_bg:
frame_bg = rgb_to_hex(frame_bg['r'], frame_bg['g'], frame_bg['b'])
else:
frame_bg = "No background color specified"
output.append([parsed, [
int(frame['absoluteBoundingBox']['width']),
int(frame['absoluteBoundingBox']['height']),
frame_bg,
result['name'].replace('\n', '\\n'),
frame_count,
entry_placeholder,
text_placeholder
]])
threads = []
for frame in frames:
if frame["type"] == "FRAME":
thread = threading.Thread(target=parse_frame, args=(frame, frame_count,))
threads.append(thread)
thread.start()
frame_count = frame_count + 1;
for thread in threads:
thread.join()
except KeyError as e:
print(f"KeyError: {str(e)} - likely due to missing keys in JSON response")
return output