-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweathersvg.py
241 lines (202 loc) · 8.95 KB
/
weathersvg.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
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
233
234
235
236
237
238
239
240
241
"""
weathersvg.py: a series of utilities to produce small SVG outputs
of useful weather data.
"""
from __future__ import print_function
import os
import re
import svgwrite
import logging
def fix_missing(value):
"""
If there's a missing value for a number, return two dashes. Otherwise,
return the number.
"""
try:
if value == '' or value is None:
return '--'
return value
except Exception as exc:
logging.error('Returning a missing value string: %s', exc)
return '--'
def precip_chance_svg(morning, evening, filename, outputdir='/tmp/', iconheight=50):
"""
Take the day's precip chances and produce a color-coded svg of percentages.
"""
fontheight = (iconheight / 2) - 2
svg_info = {'high_coords': (8, fontheight),
'low_coords': (2, iconheight - 2),
'dimensions': (65, iconheight),
'colors': ['#baa87d', '#7ae6c0', '#2bb5aa', '#023dbd', '#035740'],
'fontcolor': 'white',
'fontheight': fontheight
}
bgc = svg_info['colors'][int(max(morning, evening)/100.0 * (len(svg_info['colors']) - 1))]
if not re.search(r'%$', str(evening)):
evening = '{0}%'.format(evening)
if not re.search(r'%$', str(morning)):
morning = '{0}%'.format(morning)
style1 = '''.{stylename} {openbrace} font: bold {fontsize}px sans-serif;
fill:{fontcolor}; stroke:#000000; stroke-width:2px; stroke-linecap:butt;
stroke-linejoin:miter; stroke-opacity:0.5; {closebrace}'''
dwg = svgwrite.Drawing(os.path.join(outputdir, filename),
size=svg_info['dimensions'])
dwg_styles = svgwrite.container.Style(content='.background {fill: ' + bgc +
'; stroke: #f0f0f0f0;}')
dwg_styles.append(content=style1.format(stylename='morning', openbrace='{',
fontsize=fontheight, fontcolor='#f2df94',
closebrace='}'))
dwg_styles.append(content=style1.format(stylename='evening', openbrace='{',
fontsize=fontheight, fontcolor='#ffd4fb',
closebrace='}'))
dwg.defs.add(dwg_styles)
evening = fix_missing(evening)
morning = fix_missing(morning)
evening_text = svgwrite.text.TSpan(text=evening,
insert=svg_info['high_coords'],
class_='evening')
morning_text = svgwrite.text.TSpan(text=morning,
insert=svg_info['low_coords'],
class_='morning')
frame = svgwrite.shapes.Rect(insert=(0, 0),
size=svg_info['dimensions'],
class_='background')
text_block = svgwrite.text.Text('', x='0', y='0')
text_block.add(evening_text)
text_block.add(morning_text)
dwg.add(frame)
dwg.add(text_block)
dwg.save(pretty=True)
return 0
def high_low_svg(high, low, filename, outputdir='/tmp/', iconheight=50, iconwidth=50):
"""
Use svgwrite to make a simple graphic with high/low temps for the day's
forecast.
Unicode deg-Celsius is U+2103 (only for UTF-16)
Unicode deg-Fahrenheit is U+2109 (only for UTF-16)
Unicode degree symbol is U+00B0 ('\xb0') -- same as Latin-1 encoding, but is
not available in 1963-standard 7-bit ASCII
"""
fontheight = (iconheight / 2) - 2
svg_info = {'high_coords': (3, fontheight),
'low_coords': (3, iconheight - 2),
'dimensions': (iconwidth, iconheight),
'colors': ['#baa87d', '#7ae6c0', '#2bb5aa', '#023dbd', '#035740'],
'fontcolor': ['blue', 'red', 'white'],
'fontheight': fontheight
}
# high_coords = (3, 18)
# low_coords = (3, 40)
# dimensions = (iconheight, iconwidth)
style1 = '.{stylename} {openbrace} font: bold {fontsize}px sans-serif;\
fill:{fontcolor}; stroke:#000000; stroke-width:1px; stroke-linecap:butt;\
stroke-linejoin:miter; stroke-opacity:0.7; {closebrace}'
dwg = svgwrite.Drawing(os.path.join(outputdir, filename), size=svg_info['dimensions'])
dwg_styles = svgwrite.container.Style(content='.background {fill: #f0f0f0f0; stroke: #f0f0f0f0;}')
dwg_styles.append(content=style1.format(stylename='low', openbrace='{',
fontsize=fontheight,
fontcolor=svg_info['fontcolor'][0],
closebrace='}'))
dwg_styles.append(content=style1.format(stylename='high', openbrace='{',
fontsize=fontheight + 2,
fontcolor=svg_info['fontcolor'][1],
closebrace='}'))
dwg.defs.add(dwg_styles)
high = fix_missing(high)
low = fix_missing(low)
high_symbol = (unicode(high) + u'\xb0')
low_symbol = (unicode(low) + u'\xb0')
high_text = svgwrite.text.TSpan(text=high_symbol,
insert=svg_info['high_coords'], class_='high')
low_text = svgwrite.text.TSpan(text=low_symbol,
insert=svg_info['low_coords'], class_='low')
text_block = svgwrite.text.Text('', x='0', y='0')
text_block.add(high_text)
text_block.add(low_text)
dwg.add(text_block)
dwg.save(pretty=True)
return 0
def make_forecast_icons(fc_dict, outputdir='/tmp/'):
"""
Write out SVG icons of the next three days of temps and precip chances.
"""
filelabel = 'today_{fctype}_plus_{day}.svg'
for i in range(0, 3):
high_low_svg(fc_dict[i]['high'], fc_dict[i]['low'],
filelabel.format(fctype='temp', day=i),
outputdir=outputdir
)
precip_chance_svg(int(fc_dict[i]['precip_morning']),
int(fc_dict[i]['precip_evening']),
filename=filelabel.format(fctype='precip', day=i),
outputdir=outputdir
)
return True
def assign_icon(description, icon_match):
"""
Try to parse the language in forecasts for each to and match to an
appropriate weather SVG icon.
"""
if description == ''
logging.warn('No description available for icon match. Returning NA.')
return 'wi-na.svg'
returnvalue = ''
description = description.strip().lower()
description = re.sub(r'\s+', ' ', description)
logging.info('Finding icon for "%s"', description)
logging.debug('Found %s items in icon list.', len(icon_match.keys()))
for key, value in icon_match.iteritems():
logging.debug('Evaluating key %s and list %s', key, value)
for val in value:
if description == val.lower().strip():
returnvalue = key
logging.info('Matched "%s"', val)
return returnvalue
logging.warn('Unable to match "%s"', description)
return 'wi-na.svg'
def css_string(css_dict):
"""
Convenience function to format a dict into a css_friendly string.
"""
stylestring = '{'
for key, value in css_dict.iteritems():
stylestring = '{0}{1}:{2}; '.format(stylestring, key, value)
stylestring = stylestring + '}'
return stylestring
def draw_compass_svg(degrees, data):
"""
Drawing raw SVG via text and python.
"""
wcd = data['defaults']['wind_compass']
# raw_svg_header = '<?xml version="1.0" encoding="utf-8"?>'
svg_invocation = '''<svg height="{height}" width="{width}" version="1.1" id="{id_label}"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px" y="0px" viewBox="{viewbox}"
style="enable-background:new {viewbox};" xml:ispace="preserve">'''
circle_css = data['defaults']['circle_css']
rot1_css = data['defaults']['rot1_css']
rot1_css['transform'] = 'rotate({0}deg)'.format(degrees)
svg_css = '<style>circle {0} .rot1 {1}</style>'.format(css_string(circle_css),
css_string(rot1_css))
# symbol = '<symbol id="whole-icon"> <g class="rot1">
# <circle cx="20" cy="20" r="17" id="ring"/>
# <path d="M20 7 L 27 30 L 20 26 L 13 30 L 20 7 z" id="arrow" /></g> </symbol>'
# raw_svg_footer = '<use xlink:href="#whole-icon"/></svg>'
svg_string = '{0}{1}{2}{3}'.format(svg_invocation.format(height=wcd['height'],
width=wcd['width'],
id_label=wcd['id_label'],
viewbox=wcd['viewbox']),
svg_css, wcd['symbol'], wcd['raw_svg_footer'])
# print(svg_string)
return svg_string
def wind_direction_icon(heading, sourcepath='static/icons/weather-icons-master/svg'):
"""
Generate the html for the appropriately rotated SVG file for
the wind direction.
"""
filename = 'wi-wind-deg.svg'
filepath = os.path.join(sourcepath, filename)
img_html = '''<img src="{0}" width="50" height="50" fill="white"
transform="rotate({1},20,20)" />'''.format(filepath, int(heading))
logging.debug('image HTML: %s', img_html)
return img_html