-
Notifications
You must be signed in to change notification settings - Fork 0
/
svg_split.py
177 lines (138 loc) · 4.92 KB
/
svg_split.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
try:
import unzip_requirements
except ImportError:
pass
import logging
import string
import traceback
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
from svgpathtools import parse_path
from custom_svg import davis_disvg
from parse_sentences import split_into_sentences
def get_sentences(input_text, split_dict, primary_color):
"""
:param input_text: str
:param primary_color: str
:param split_dict: { words: [str,str], color: str }
:return: { 'color' : str , 'length': int }
"""
try:
array_of_sentences = split_into_sentences(input_text)
default_color = primary_color
store = []
for array_of_words in array_of_sentences:
segment_color = default_color
for highlight_word in split_dict['words']:
if highlight_word.lower() in array_of_words:
segment_color = split_dict['color']
store.append({'color': segment_color, 'length': len(array_of_words)})
return store
except Exception as e:
traceback.print_exc()
logger.info(e)
raise e
def filter_alpha(a_list):
stripped = [strip_non_alpha(x) for x in a_list]
return [x.lower() for x in stripped if x.isalpha() and x is not None]
def filter_length(list_of_sentence_lists):
return [len(x) for x in list_of_sentence_lists]
def strip_non_alpha(word):
exclusion_list = set(string.punctuation)
return ''.join(x for x in word if x not in exclusion_list)
def strip_parens(word):
exclusion_list = ["(", ")"]
return ''.join(x for x in word if x not in exclusion_list)
def fix_coordinate(str):
if len([x for x in str if x in ['(', ')']]) == 0:
return '%s+0' % str
else:
return str
def plot_lengths(a):
"""
:param a: [{'color':'','length':5}]
:return: [{'color': 'red', 'path': Path()}]
"""
# Turn left 90 degrees each time
behavior_ref = ['h -', 'v ', 'h ', 'v -']
path_store = []
path_str = 'M50 20j'
count = 0
color = a[0].get('color', 'black')
for obj in a:
if obj['color'] != color:
# print 'Changed colors from %s to %s' % (color, obj['color'])
last_point = fix_coordinate(str(parse_path(path_str).point(1.0)))
new_path_start = 'M%s' % strip_parens(last_point)
res = {'color': color, 'path': parse_path(path_str)}
path_store.append(res) # Add the Path to the line_store
path_str = new_path_start # Start the new path
color = obj['color'] # With the new color
move = behavior_ref[count] + str(obj['length'])
path_str = ' '.join([path_str, move])
count = 0 if count == 3 else count + 1
# Add the last entry
path_store.append({'color': color, 'path': parse_path(path_str)})
return path_store
def build_pre_parsed_path_str(json_obj):
"""
:param input_text: str
:return: [{'color':'red','path':Path()}]
"""
try:
return plot_lengths(json_obj['split_pre_parsed'])
except Exception as e:
logger.info(e)
traceback.print_exc()
return []
def build_path_str(json_obj):
"""
:param input_text: str
:return: [{'color':'red','path':Path()}]
"""
try:
sentence_lengths = get_sentences(json_obj['text'], json_obj['split'], json_obj['color'])
return plot_lengths(sentence_lengths)
except Exception as e:
logger.info(e)
traceback.print_exc()
return []
def satisfies_split_conditions(json_obj):
"""
:param json_obj:
:return: bool
"""
if 'split' not in json_obj or json_obj.get('split', None) is None:
return False
split = json_obj['split']
if 'words' not in split or split['words'] is None or len(split['words']) == 0:
return False
return True
def save_split_xml_to_s3(json_obj):
"""
:param json_obj:
:return:
"""
try:
if json_obj['split_pre_parsed'] is not None and len(json_obj['split_pre_parsed']) > 0:
logger.info('Using split_pre_parsed calculations with %s sentences' % len(json_obj['split_pre_parsed']))
paths = build_pre_parsed_path_str(json_obj)
else:
logger.info('Using split get_paths calculations')
paths = build_path_str(json_obj)
if json_obj['node_colors'] is not None:
node_opts = {'node_colors': json_obj['node_colors'], 'node_radii': [1, 1]}
else:
node_opts = {'node_colors': None, 'node_radii': [0, 0]}
url = davis_disvg(
paths=[x['path'] for x in paths],
colors=[x['color'] for x in paths],
nodes=[paths[0]['path'].point(0.0), paths[-1]['path'].point(1.0)],
checksum=json_obj['checksum'],
bg_color=json_obj['bg_color'],
**node_opts
)
return url
except Exception as e:
traceback.print_exc()
return 'Error building xml_string: %s' % str(e)