4 from datetime import datetime
5 from difflib import SequenceMatcher
10 from threading import Thread
13 from typing import Dict, List, Optional
14 from queue import Queue
16 import astral # type: ignore
17 from astral.sun import sun # type: ignore
28 import renderer_catalog
31 import trigger_catalog
35 cfg = config.add_commandline_args(
36 f'Kiosk Server ({__file__})',
37 'A python server that runs a kiosk.'
39 logger = logging.getLogger(__file__)
42 def thread_janitor() -> None:
44 tracemalloc_target = 0.0
48 # Main janitor loop; dump the largest pigs and force regular gcs.
51 if now > tracemalloc_target:
52 tracemalloc_target = now + 30.0
53 snapshot = tracemalloc.take_snapshot()
54 snapshot = snapshot.filter_traces((
55 tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
56 tracemalloc.Filter(False, "<unknown>"),
60 top_stats = snapshot.statistics(key_type)
61 logger.info(f'janitor: Top {limit} lines')
62 for index, stat in enumerate(top_stats[:limit], 1):
63 frame = stat.traceback[0]
65 # replace "/path/to/module/file.py" with "module/file.py"
66 filename = os.sep.join(frame.filename.split(os.sep)[-2:])
68 f'janitor: #{index}: {filename}:{frame.lineno}: {stat.size / 1024:.1f} KiB'
71 other = top_stats[limit:]
73 size = sum(stat.size for stat in other)
75 f'janitor: {len(other)} others: {size/1024:.1f} KiB'
77 total = sum(stat.size for stat in top_stats)
79 f'janitor: Total allocated size: {total / 1024:.1f} KiB'
82 logger.info('janitor: kicking off a manual gc operation now.')
84 gc_target = now + 120.0
88 def guess_page(command: str, page_chooser: chooser.chooser) -> str:
90 def normalize_page(page: str) -> str:
91 logger.debug(f'normalize_page input: {page}')
92 page = page.replace('(', ' ')
93 page = page.replace('_', ' ')
94 page = page.replace(')', ' ')
95 page = page.replace('.html', '')
96 page = page.replace('CNNNews', 'news')
97 page = page.replace('CNNTechnology', 'technology')
98 page = page.replace('gocostco', 'costco list')
99 page = page.replace('gohardware', 'hardware list')
100 page = page.replace('gohouse', 'house list honey do')
101 page = page.replace('gcal', 'google calendar events')
102 page = page.replace('mynorthwest', 'northwest news')
103 page = page.replace('myq', 'myq garage door status')
104 page = page.replace('gomenu', 'dinner menu')
105 page = page.replace('wsdot', 'traffic')
106 page = page.replace('gomenu', 'dinner menu')
107 page = page.replace('WSJNews', 'news')
108 page = page.replace('telma', 'telma cabin')
109 page = page.replace('WSJBusiness', 'business news')
110 page = re.sub(r'[0-9]+', '', page)
111 logger.debug(f'normalize_page output: {page}')
116 for page in page_chooser.get_page_list():
117 npage = normalize_page(page)
118 score = SequenceMatcher(None, command, npage).ratio()
119 if best_score is None or score > best_score:
121 assert best_page is not None
125 def process_command(command: str, page_history: List[str], page_chooser) -> str:
126 logger.debug(f'Parsing verbal command: {command}')
128 if 'hold' in command:
129 page = page_history[0]
130 elif 'back' in command:
131 page = page_history[1]
132 elif 'skip' in command:
134 (page, _) = page_chooser.choose_next_page()
135 if page == page_history[0]:
136 logger.debug(f'chooser: {page} is the same as last time! Try again.')
139 elif 'internal' in command:
140 if 'render' in command:
141 page = constants.render_stats_pagename
143 page = constants.render_stats_pagename
144 elif 'weather' in command:
145 if 'telma' in command or 'cabin' in command:
146 page = 'weather-telma_3_10800.html'
147 elif 'stevens' in command:
148 page = 'weather-stevens_3_10800.html'
150 page = 'weather-home_3_10800.html'
151 elif 'cabin' in command:
152 if 'list' in command:
153 page = 'Cabin-(gocabin)_2_3600.html'
155 page = 'hidden/cabin_driveway.html'
156 elif 'news' in command or 'headlines' in command:
157 page = 'cnn-CNNNews_4_25900.html'
158 elif 'clock' in command or 'time' in command:
159 page = 'clock_10_none.html'
160 elif 'countdown' in command or 'countdowns' in command:
161 page = 'countdown_3_7200.html'
162 elif 'costco' in command:
163 page = 'Costco-(gocostco)_2_3600.html'
164 elif 'calendar' in command or 'events' in command:
165 page = 'gcal_3_86400.html'
166 elif 'countdown' in command or 'countdowns' in command:
167 page = 'countdown_3_7200.html'
168 elif 'grocery' in command or 'groceries' in command:
169 page = 'Grocery-(gogrocery)_2_3600.html'
170 elif 'hardware' in command:
171 page = 'Hardware-(gohardware)_2_3600.html'
172 elif 'garage' in command:
173 page = 'myq_4_300.html'
174 elif 'menu' in command:
175 page = 'Menu-(gomenu)_2_3600.html'
176 elif 'cron' in command or 'health' in command:
177 page = 'periodic-health_6_300.html'
178 elif 'photo' in command or 'picture' in command:
179 page = 'photo_23_3600.html'
180 elif 'quote' in command or 'quotation' in command or 'quotes' in command:
181 page = 'quotes_4_10800.html'
182 elif 'stevens' in command:
183 page = 'stevens-conditions_1_86400.html'
184 elif 'stock' in command or 'stocks' in command:
185 page = 'stock_3_86400.html'
186 elif 'twitter' in command:
187 page = 'twitter_10_3600.html'
188 elif 'traffic' in command:
189 page = 'wsdot-bridges_3_none.html'
190 elif 'front' in command and 'door' in command:
191 page = 'hidden/frontdoor.html'
192 elif 'driveway' in command:
193 page = 'hidden/driveway.html'
194 elif 'backyard' in command:
195 page = 'hidden/backyard.html'
197 page = guess_page(command, page_chooser)
198 assert page is not None
199 logger.debug(f'Chose page {page}')
203 def thread_change_current(command_queue: Queue) -> None:
204 page_history = ["", ""]
205 swap_page_target = 0.0
207 def filter_news_during_dinnertime(page: str) -> bool:
208 now = datetime.now(tz=pytz.timezone("US/Pacific"))
209 is_dinnertime = now.hour >= 18 and now.hour <= 20
210 return not is_dinnertime or not (
213 or "mynorthwest" in page
218 page_chooser = chooser.weighted_random_chooser_with_triggers(
219 trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
221 current_file = os.path.join(constants.pages_dir, "current.shtml")
222 emergency_file = os.path.join(constants.pages_dir, "reload_immediately.html")
228 # Check for a verbal command.
231 command = command_queue.get(block=False)
235 if command is not None:
236 logger.info(f'chooser: We got a verbal command ("{command}"), parsing it...')
238 page = process_command(command, page_history, page_chooser)
241 (page, triggered) = page_chooser.choose_next_page()
243 logger.info('chooser: A trigger is active...')
246 if page == page_history[0]:
247 logger.debug(f'chooser: {page} is the same as last time! Try again.')
252 if page != page_history[0] or (swap_page_target - now) < 10.0:
253 logger.info(f'chooser: An emergency page reload to {page} is needed at this time.')
254 swap_page_target = now + constants.emergency_refresh_period_sec
256 # Set current.shtml to the right page.
258 with open(current_file, "w") as f:
262 override_refresh_sec = constants.emergency_refresh_period_sec,
265 logger.debug(f'chooser: Wrote {current_file}.')
266 except Exception as e:
268 logger.error(f'chooser: Unexpected exception; assuming {page} doesn\'t exist?!')
271 # Also notify XMLHTTP clients that they need to refresh now.
272 with open(emergency_file, "w") as f:
273 f.write(f'Reload, suckers... you HAVE to see {page}!')
274 logger.debug(f'chooser: Wrote {emergency_file}...')
276 # Fix this hack... maybe read the webserver logs and see if it
277 # actually was picked up?
279 os.remove(emergency_file)
280 logger.debug(f'chooser: ...and removed {emergency_file}.')
282 elif now >= swap_page_target:
283 assert page != page_history[0]
285 f'chooser: Nominal choice of {page} as the next to show.'
287 swap_page_target = now + constants.refresh_period_sec
289 with open(current_file, "w") as f:
290 emit_wrapped(f, page)
291 logger.debug(f'chooser: Wrote {current_file}.')
292 except Exception as e:
294 logger.error(f'chooser: Unexpected exception; assuming {page} doesn\'t exist?!')
296 page_history.insert(0, page)
297 page_history = page_history[0:10]
304 override_refresh_sec: int = None,
305 command: str = None) -> None:
307 def pick_background_color() -> str:
308 now = datetime_utils.now_pacific()
309 city = astral.LocationInfo(
310 "Bellevue", "USA", "US/Pacific", 47.610, -122.201
312 s = sun(city.observer, date=now, tzinfo=pytz.timezone("US/Pacific"))
313 sunrise_mod = utils.minute_number(s["sunrise"].hour, s["sunrise"].minute)
314 sunset_mod = utils.minute_number(s["sunset"].hour, s["sunset"].minute)
315 now_mod = utils.minute_number(now.hour, now.minute)
316 if now_mod < sunrise_mod or now_mod > (sunset_mod + 45):
318 elif now_mod < (sunrise_mod + 45) or now_mod > (sunset_mod + 120):
323 def get_refresh_period() -> float:
324 if override_refresh_sec is not None:
325 return float(override_refresh_sec * 1000.0)
326 now = datetime.now(tz=pytz.timezone("US/Pacific"))
328 return float(constants.refresh_period_night_sec * 1000.0)
330 return float(constants.refresh_period_sec * 1000.0)
332 age = utils.describe_age_of_file_briefly(f"pages/{filename}")
333 bgcolor = pick_background_color()
337 pageid = f'"{command}" -> {filename}'
342 <TITLE>Kitchen Kiosk</TITLE>
343 <LINK rel="stylesheet" type="text/css" href="style.css">
344 <SCRIPT TYPE="text/javascript">
346 // Zoom the 'contents' div to fit without scrollbars and then make
348 function zoomScreen() {
351 document.getElementById("content").style.zoom = z+"%";
352 var body = document.body;
353 var html = document.documentElement;
354 var height = Math.max(body.scrollHeight,
359 var windowHeight = window.innerHeight;
360 var width = Math.max(body.scrollWidth,
365 var windowWidth = window.innerWidth;
366 var heightRatio = height / windowHeight;
367 var widthRatio = width / windowWidth;
369 if (heightRatio <= 1.0 && widthRatio <= 1.0) {
374 document.getElementById("content").style.visibility = "visible";
377 // Load IMG tags with DATA-SRC attributes late.
378 function lateLoadImages() {
379 var image = document.getElementsByTagName('img');
380 for (var i = 0; i < image.length; i++) {
381 if (image[i].getAttribute('DATA-SRC')) {
382 image[i].setAttribute('SRC', image[i].getAttribute('DATA-SRC'));
390 // Operate the clock at the top of the page.
391 function runClock() {
392 var today = new Date();
393 var h = today.getHours();
394 var ampm = h >= 12 ? 'pm' : 'am';
396 h = h ? h : 12; // the hour '0' should be '12'
397 var m = maybeAddZero(today.getMinutes());
399 if (today.getSeconds() %% 2 == 0) {
400 colon = "<FONT STYLE='color: #%s; font-size: 4vmin; font-weight: bold'>:</FONT>";
402 document.getElementById("time").innerHTML = h + colon + m + ampm;
403 document.getElementById("date").innerHTML = today.toDateString();
404 var t = setTimeout(function(){runClock()}, 1000);
410 // Helper method for running the clock.
411 function maybeAddZero(x) {
412 return (x < 10) ? "0" + x : x;
415 // Do something on page load.
416 function addLoadEvent(func) {
417 var oldonload = window.onload;
418 if (typeof window.onload != 'function') {
419 window.onload = func;
421 window.onload = function() {
430 // Sleep thread helper.
431 const sleep = (milliseconds) => {
432 return new Promise(resolve => setTimeout(resolve, milliseconds))
435 var loadedDate = new Date();
437 addLoadEvent(zoomScreen);
438 addLoadEvent(runClock);
439 addLoadEvent(lateLoadImages);
444 // Runs the countdown line at the bottom and is responsible for
445 // normal page reloads caused by the expiration of a timer.
446 (function countdown() {
449 var now = new Date();
450 var deltaMs = now.getTime() - loadedDate.getTime();
452 var remainingMs = (totalMs - deltaMs);
454 if (remainingMs > 0) {
455 var hr = document.getElementById("countdown");
456 var width = (remainingMs / (totalMs - 5000)) * 100.0;
458 hr.style.visibility = "visible";
459 hr.style.width = " ".concat(width, "%%");
460 hr.style.backgroundColor = "maroon";
463 // Reload unconditionally after 22 sec.
464 window.location.reload(true);
467 // Brief sleep before doing it all over again.
468 sleep(50).then(() => {
473 """ % get_refresh_period()
477 function check_reload() {
478 var xhr = new XMLHttpRequest();
480 '%s/reload_immediately.html');
483 if (xhr.status === 200) {
484 window.location.reload(true);
490 // Periodically checks for emergency reload events.
491 setInterval(check_reload, 500);
494 """ % constants.root_url)
495 f.write(f'<BODY BGCOLOR="#{bgcolor}">')
498 <TABLE style="height:100%; width:100%" BORDER=0>
501 <DIV id="date"> </DIV>
503 <TD ALIGN="center"><FONT COLOR=#bbbbbb>
504 <DIV id="info"></DIV></FONT>
507 <DIV id="time"> </DIV>
510 <TR STYLE="vertical-align:top">
512 <DIV ID="content" STYLE="zoom: 1; visibility: hidden;">
513 <!-- BEGIN main page contents. -->
516 f.write(f'<!--#include virtual="{filename}"-->')
519 <!-- END main page contents. -->
522 <DIV STYLE="position: absolute; top:1030px; width:99%">
526 f.write(f'<FONT SIZE=2 COLOR=#bbbbbb>{pageid} @ {age} ago.</FONT>')
530 <HR id="countdown" STYLE="width:0px;
537 background-color:#ffffff;">
546 def renderer_update_internal_stats_page(
547 last_render: Dict[str, datetime],
548 render_counts: collections.Counter,
549 render_times: Dict[str, np.array],
552 f'renderer: Updating internal render statistics page.'
554 with file_writer.file_writer(constants.render_stats_pagename) as f:
558 <TABLE BORDER=0 WIDTH=95%>
560 <TH><B>Renderer Name</B></TH>
561 <TH><B>Last Run</B></TH>
562 <TH><B>Num Invocations</B></TH>
563 <TH><B>Render Latency</B></TH>
566 for n, r in enumerate(renderer_catalog.get_renderers()):
568 style = 'style="margin: 0; padding: 0; background: #c6b0b0;"'
570 style = 'style="margin: 0; padding: 0; background: #eeeeee;"'
572 last = last_render.get(name, None)
576 last = last.strftime('%Y/%m/%d %I:%M:%S%P')
577 count = render_counts.get(name, 0)
578 latency = render_times.get(name, np.array([]))
579 p25 = p50 = p75 = p90 = p99 = 'N/A'
581 p25 = np.percentile(latency, 25)
582 p50 = np.percentile(latency, 50)
583 p75 = np.percentile(latency, 75)
584 p90 = np.percentile(latency, 90)
585 p99 = np.percentile(latency, 99)
591 <TD {style}>{name} </TD>
592 <TD {style}> {last} </TD>
593 <TD {style}><CENTER> {count} </CENTER></TD>
594 <TD {style}> p25={p25:5.2f}, p50={p50:5.2f}, p75={p75:5.2f}, p90={p90:5.2f}, p99={p99:5.2f}</TD>
601 def thread_invoke_renderers() -> None:
602 render_times: Dict[str, np.array] = {}
603 render_counts: collections.Counter = collections.Counter()
604 last_render: Dict[str, datetime] = {}
609 'renderer: invoking all overdue renderers in catalog...'
611 for r in renderer_catalog.get_renderers():
616 except Exception as e:
619 f'renderer: Unexpected and unhandled exception ({e}) in {name}, swallowing it.'
623 # Increment the count of render operations per renderer.
624 render_counts[name] += 1
626 # Keep track of the last time we invoked each renderer.
627 last_render[name] = datetime_utils.now_pacific()
629 # Record how long each render operation takes and warn if very long.
630 delta = time.time() - now
631 times = render_times.get(name, np.array([]))
632 times = np.insert(times, 0, delta)
633 render_times[name] = times
638 {hdr} Warning: {name}'s rendering took {delta:5.2f}s.
639 {hdr} FYI: {name}'s render times: p25={np.percentile(times, 25):5.2f}, p50={np.percentile(times, 50):5.2f}, p75={np.percentile(times, 75):5.2f}, p90={np.percentile(times, 90):5.2f}, p99={np.percentile(times, 99):5.2f}
643 # Update a page about internal stats of renderers.
644 renderer_update_internal_stats_page(last_render, render_counts, render_times)
645 logger.debug('renderer: having a little nap...')
646 time.sleep(constants.render_period_sec)
649 @bootstrap.initialize
651 command_queue: Queue = Queue()
652 changer_thread: Optional[Thread] = None
653 renderer_thread: Optional[Thread] = None
654 janitor_thread: Optional[Thread] = None
655 hotword_thread: Optional[Thread] = None
657 if hotword_thread is None or not hotword_thread.is_alive():
658 if hotword_thread is None:
659 logger.info('watchdog: Starting up the hotword detector thread...')
662 'watchdog: The hotword detector thread seems to have died; restarting it and hoping for the best.'
664 keyword_paths = [pvporcupine.KEYWORD_PATHS[x] for x in ["bumblebee"]]
665 sensitivities = [0.7] * len(keyword_paths)
666 listener = listen.HotwordListener(
671 hotword_thread = Thread(target=listener.listen_forever, args=())
672 hotword_thread.start()
674 if changer_thread is None or not changer_thread.is_alive():
675 if changer_thread is None:
676 logger.info('watchdog: Starting up the current page changer thread...')
679 'watchdog: The current page changer thread seems to have died; restarting it and hoping for the best.'
681 changer_thread = Thread(target=thread_change_current, args=(command_queue,))
682 changer_thread.start()
684 if renderer_thread is None or not renderer_thread.is_alive():
685 if renderer_thread is None:
686 logger.info('watchdog: Starting up the page renderer thread...')
689 'watchdog: The page renderer thread seems to have died; restarting it and hoping for the best.'
691 renderer_thread = Thread(target=thread_invoke_renderers, args=())
692 renderer_thread.start()
694 if janitor_thread is None or not janitor_thread.is_alive():
695 if janitor_thread is None:
696 logger.info('watchdog: Starting up the memory janitor thread...')
699 'watchdog: The memory janitor thread seems to have died; restarting it and hoping for the best.'
701 janitor_thread = Thread(target=thread_janitor, args=())
702 janitor_thread.start()
704 # Have a little break and then check to make sure all threads are still alive.
705 logger.debug('watchdog: having a little nap.')
706 time.sleep(constants.check_threads_period_sec)
709 if __name__ == "__main__":