Various changes
[python_utils.git] / cached / weather_forecast.py
1 #!/usr/bin/env python3
2
3 from dataclasses import dataclass
4 import datetime
5 import logging
6 import os
7 import urllib.request
8
9 import astral  # type: ignore
10 from astral.sun import sun  # type: ignore
11 from bs4 import BeautifulSoup  # type: ignore
12 import pytz
13
14 import argparse_utils
15 import config
16 import datetime_utils
17 import dateparse.dateparse_utils as dp
18 import persistent
19 import text_utils
20
21 logger = logging.getLogger(__name__)
22
23 cfg = config.add_commandline_args(
24     f'Cached Weather Forecast ({__file__})',
25     'Arguments controlling detailed weather rendering'
26 )
27 cfg.add_argument(
28     '--weather_forecast_cachefile',
29     type=str,
30     default=f'{os.environ["HOME"]}/.weather_forecast_cache',
31     metavar='FILENAME',
32     help='File in which to cache weather data'
33 )
34 cfg.add_argument(
35     '--weather_forecast_stalest_acceptable',
36     type=argparse_utils.valid_duration,
37     default=datetime.timedelta(seconds=7200),   # 2 hours
38     metavar='DURATION',
39     help='Maximum acceptable age of cached data.  If zero, forces a refetch'
40 )
41
42
43 @dataclass
44 class WeatherForecast:
45     date: datetime.date                # The date
46     sunrise: datetime.datetime         # Sunrise datetime
47     sunset: datetime.datetime          # Sunset datetime
48     description: str                   # Textual description of weather
49
50
51 @persistent.persistent_autoloaded_singleton()
52 class CachedDetailedWeatherForecast(object):
53     def __init__(self, forecasts = None):
54         if forecasts is not None:
55             self.forecasts = forecasts
56             return
57
58         now = datetime_utils.now_pacific()
59         self.forecasts = {}
60
61         # Ask the raspberry pi about the outside temperature.
62         www = urllib.request.urlopen(
63             "http://10.0.0.75/~pi/outside_temp"
64         )
65         current_temp = www.read().decode("utf-8")
66         current_temp = float(current_temp)
67         current_temp *= (9/5)
68         current_temp += 32.0
69         current_temp = round(current_temp)
70         www.close()
71
72         # Get a weather forecast for Bellevue.
73         www = urllib.request.urlopen(
74             "https://forecast.weather.gov/MapClick.php?lat=47.652775&lon=-122.170716"
75         )
76         forecast_response = www.read()
77         www.close()
78
79         soup = BeautifulSoup(forecast_response, "html.parser")
80         forecast = soup.find(id='detailed-forecast-body')
81         parser = dp.DateParser()
82
83         said_temp = False
84         last_dt = now
85         dt = now
86         for (day, txt) in zip(
87                 forecast.find_all('b'),
88                 forecast.find_all(class_='col-sm-10 forecast-text')
89         ):
90             last_dt = dt
91             try:
92                 dt = parser.parse(day.get_text())
93             except Exception:
94                 dt = last_dt
95             assert dt is not None
96
97             # Compute sunrise/sunset times on dt.
98             city = astral.LocationInfo(
99                 "Bellevue", "USA", "US/Pacific", 47.653, -122.171
100             )
101             s = sun(city.observer, date=dt, tzinfo=pytz.timezone("US/Pacific"))
102             sunrise = s['sunrise']
103             sunset = s['sunset']
104
105             if dt.date() == now.date() and not said_temp:
106                 blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
107                 blurb += txt.get_text()
108                 said_temp = True
109             else:
110                 blurb = f'{day.get_text()}: {txt.get_text()}'
111             blurb = text_utils.wrap_string(blurb, 80)
112
113             if dt.date() in self.forecasts:
114                 self.forecasts[dt.date()].description += '\n' + blurb
115             else:
116                 self.forecasts[dt.date()] = WeatherForecast(
117                     date = dt,
118                     sunrise = sunrise,
119                     sunset = sunset,
120                     description = blurb,
121                 )
122
123     @classmethod
124     def load(cls):
125         if persistent.was_file_written_within_n_seconds(
126                 config.config['weather_forecast_cachefile'],
127                 config.config['weather_forecast_stalest_acceptable'].total_seconds(),
128         ):
129             import pickle
130             with open(config.config['weather_forecast_cachefile'], 'rb') as rf:
131                 weather_data = pickle.load(rf)
132                 return cls(weather_data)
133         return None
134
135     def save(self):
136         import pickle
137         with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
138             pickle.dump(
139                 self.forecasts,
140                 wf,
141                 pickle.HIGHEST_PROTOCOL,
142             )