4 from datetime import datetime
5 from difflib import SequenceMatcher
10 from threading import Thread
13 from typing import Dict, List, Optional, Tuple
14 from queue import Queue
16 import astral # type: ignore
17 from astral.sun import sun # type: ignore
26 from pyutils.datetimes import datetime_utils
27 from pyutils.files import file_utils
29 import kiosk_constants
31 import renderer_catalog
34 import trigger_catalog
37 cfg = config.add_commandline_args(
38 f"Kiosk Server ({__file__})", "A python server that runs a kiosk."
40 logger = logging.getLogger(__file__)
43 def thread_janitor() -> None:
45 tracemalloc_target = 0.0
49 # Main janitor loop; dump the largest pigs and force regular gcs.
52 if now > tracemalloc_target:
53 tracemalloc_target = now + 30.0
54 snapshot = tracemalloc.take_snapshot()
55 snapshot = snapshot.filter_traces(
57 tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
58 tracemalloc.Filter(False, "<unknown>"),
63 top_stats = snapshot.statistics(key_type)
64 logger.info(f"janitor: Top {limit} lines")
65 for index, stat in enumerate(top_stats[:limit], 1):
66 frame = stat.traceback[0]
68 # replace "/path/to/module/file.py" with "module/file.py"
69 filename = os.sep.join(frame.filename.split(os.sep)[-2:])
71 f"janitor: #{index}: {filename}:{frame.lineno}: {stat.size / 1024:.1f} KiB"
74 other = top_stats[limit:]
76 size = sum(stat.size for stat in other)
77 logger.info(f"janitor: {len(other)} others: {size/1024:.1f} KiB")
78 total = sum(stat.size for stat in top_stats)
79 logger.info(f"janitor: Total allocated size: {total / 1024:.1f} KiB")
81 logger.info("janitor: kicking off a manual gc operation now.")
83 gc_target = now + 120.0
87 def guess_page(command: str, page_chooser: chooser.chooser) -> str:
88 def normalize_page(page: str) -> str:
89 logger.debug(f"normalize_page input: {page}")
90 page = page.replace("(", " ")
91 page = page.replace("_", " ")
92 page = page.replace(")", " ")
93 page = page.replace(".html", "")
94 page = page.replace("CNNNews", "news")
95 page = page.replace("CNNTechnology", "technology")
96 page = page.replace("gocostco", "costco list")
97 page = page.replace("gohardware", "hardware list")
98 page = page.replace("gohouse", "house list honey do")
99 page = page.replace("gcal", "google calendar events")
100 page = page.replace("mynorthwest", "northwest news")
101 page = page.replace("myq", "myq garage door status")
102 page = page.replace("gomenu", "dinner menu")
103 page = page.replace("gmaps-seattle-unwrapped", "traffic")
104 page = page.replace("gomenu", "dinner menu")
105 page = page.replace("WSJNews", "news")
106 page = page.replace("telma", "telma cabin")
107 page = page.replace("WSJBusiness", "business news")
108 page = re.sub(r"[0-9]+", "", page)
109 logger.debug(f"normalize_page output: {page}")
112 logger.info(f"No exact match for f{command}; trying to guess...")
115 for page in page_chooser.get_page_list():
116 npage = normalize_page(page)
117 score = SequenceMatcher(None, command, npage).ratio()
118 if best_score is None or score > best_score:
121 assert best_page is not None
122 logger.info(f"Best guess for f{command} => {best_page} (score = {best_score})")
127 command: str, page_history: List[str], page_chooser
129 command = command.lower()
130 logger.info(f"Parsing verbal command: {command}")
132 if "hold" in command:
133 page = page_history[0]
134 elif "down" in command:
136 'xdotool search --onlyvisible "chrom" windowactivate click --repeat 8 5'
139 elif "up" in command:
141 'xdotool search --onlyvisible "chrom" windowactivate click --repeat 8 4'
144 elif "back" in command:
145 page = page_history[1]
146 elif "skip" in command:
148 (page, _) = page_chooser.choose_next_page()
149 if page == page_history[0]:
150 logger.debug(f"chooser: {page} is the same as last time! Try again.")
153 elif "internal" in command:
154 if "render" in command:
155 page = kiosk_constants.render_stats_pagename
157 page = kiosk_constants.render_stats_pagename
158 elif "weather" in command:
159 if "telma" in command or "cabin" in command:
160 page = "weather-telma_3_10800.html"
161 elif "stevens" in command:
162 page = "weather-stevens_3_10800.html"
164 page = "weather-home_3_10800.html"
165 elif "cabin" in command:
166 if "list" in command:
167 page = "Cabin-(gocabin)_2_3600.html"
169 page = "hidden/cabin_driveway.html"
170 elif "news" in command or "headlines" in command:
171 page = "cnn-CNNNews_4_25900.html"
172 elif "clock" in command or "time" in command:
173 page = "clock_10_none.html"
174 elif "countdown" in command or "countdowns" in command:
175 page = "countdown_3_7200.html"
176 elif "costco" in command:
177 page = "Costco-(gocostco)_2_3600.html"
178 elif "calendar" in command or "events" in command:
179 page = "gcal_3_86400.html"
180 elif "countdown" in command or "countdowns" in command:
181 page = "countdown_3_7200.html"
182 elif "grocery" in command or "groceries" in command:
183 page = "Grocery-(gogrocery)_2_3600.html"
184 elif "hardware" in command:
185 page = "Hardware-(gohardware)_2_3600.html"
186 elif "garage" in command:
187 page = "myq_4_300.html"
188 elif "menu" in command:
189 page = "Menu-(gomenu)_2_3600.html"
190 elif "cron" in command or "health" in command:
191 page = "periodic-health_6_300.html"
192 elif "photo" in command or "picture" in command:
193 page = "photo_23_3600.html"
194 elif "quote" in command or "quotation" in command or "quotes" in command:
195 page = "quotes_4_10800.html"
196 elif "stevens" in command:
197 page = "stevens-conditions_1_86400.html"
198 elif "stock" in command or "stocks" in command:
199 page = "stock_3_86400.html"
200 elif "twitter" in command:
201 page = "twitter_10_3600.html"
202 elif "traffic" in command:
203 page = "gmaps-seattle-unwrapped_5_none.html"
204 elif "front" in command and "door" in command:
205 page = "hidden/frontdoor.html"
206 elif "driveway" in command:
207 page = "hidden/driveway.html"
208 elif "backyard" in command:
209 page = "hidden/backyard.html"
211 page = guess_page(command, page_chooser)
212 assert page is not None
213 logger.info(f"Parsed to {page}")
217 def thread_change_current(command_queue: Queue) -> None:
218 page_history = ["", ""]
219 swap_page_target = 0.0
221 def filter_news_during_dinnertime(page: str) -> bool:
222 now = datetime.now(tz=pytz.timezone("US/Pacific"))
223 is_dinnertime = now.hour >= 18 and now.hour <= 20
224 return not is_dinnertime or not (
227 or "mynorthwest" in page
232 def check_for_command() -> Tuple[Optional[str], Optional[str]]:
235 command = command_queue.get(block=False)
241 f'chooser: We got a verbal command ("{command}"), parsing it...'
243 page = process_command(command, page_history, page_chooser)
248 def choose_page_randomly() -> Tuple[str, bool]:
250 (page, triggered) = page_chooser.choose_next_page()
252 logger.info("chooser: A trigger is active...")
255 if page == page_history[0]:
257 f"chooser: {page} is the same as last time! Try again."
261 return (page, triggered)
263 page_chooser = chooser.weighted_random_chooser_with_triggers(
264 trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
266 current_file = os.path.join(kiosk_constants.pages_dir, "current.shtml")
267 emergency_file = os.path.join(kiosk_constants.pages_dir, "reload_immediately.html")
269 # Main chooser loop -- note that this executes a couple of times per second
270 # to be responsive to triggers.
277 # Is there a verbal command to parse?
278 (page, command) = check_for_command()
282 # If not, choose the a (new!) page randomly or respond to a trigger.
283 (page, triggered) = choose_page_randomly()
285 # By now we have a page and we may be triggered.
288 # If we are triggered and the page is new, change the
289 # current page to the new page immediately.
290 if page != page_history[0]:
292 f"chooser: An emergency page reload to {page} is needed at this time."
294 swap_page_target = now + kiosk_constants.emergency_refresh_period_sec
296 # Set current.shtml to the triggered page.
298 with open(current_file, "w") as f:
302 override_refresh_sec=kiosk_constants.emergency_refresh_period_sec,
305 logger.debug(f"chooser: Wrote {current_file}.")
308 f"chooser: Unexpected exception; assuming {page} doesn't exist?!"
312 # Notify XMLHTTP clients that they need to refresh now.
313 with open(emergency_file, "w") as f:
314 f.write(f"Reload, suckers... you HAVE to see {page}!")
315 logger.debug(f"chooser: Wrote {emergency_file}...")
317 # Fix this hack... maybe read the webserver logs and see if it
318 # actually was picked up?
320 os.remove(emergency_file)
321 logger.debug(f"chooser: ...and removed {emergency_file}.")
322 page_history.insert(0, page)
323 page_history = page_history[0:10]
325 # If we're not triggered, only render a new page if time has expired.
326 elif now >= swap_page_target:
327 logger.info(f"chooser: Nominal choice of {page} as the next to show.")
328 swap_page_target = now + kiosk_constants.refresh_period_sec
330 with open(current_file, "w") as f:
332 logger.debug(f"chooser: Wrote {current_file}.")
335 f"chooser: Unexpected exception; assuming {page} doesn't exist?!"
338 page_history.insert(0, page)
339 page_history = page_history[0:10]
344 def emit(f, filename: str, *, override_refresh_sec: int = None, command: str = None):
345 if "unwrapped" not in filename:
346 logger.debug(f"Emitting {filename} wrapped.")
348 f, filename, override_refresh_sec=override_refresh_sec, command=command
351 logger.debug(f"Emitting {filename} raw.")
352 emit_raw(f, filename)
355 def emit_raw(f, filename: str):
356 f.write(f'<!--#include virtual="{filename}"-->')
360 f, filename: str, *, override_refresh_sec: int = None, command: str = None
362 def pick_background_color() -> str:
363 now = datetime_utils.now_pacific()
364 city = astral.LocationInfo("Bellevue", "USA", "US/Pacific", 47.610, -122.201)
365 s = sun(city.observer, date=now, tzinfo=pytz.timezone("US/Pacific"))
366 sunrise_mod = datetime_utils.minute_number(
367 s["sunrise"].hour, s["sunrise"].minute
369 sunset_mod = datetime_utils.minute_number(s["sunset"].hour, s["sunset"].minute)
370 now_mod = datetime_utils.minute_number(now.hour, now.minute)
371 if now_mod < sunrise_mod or now_mod > (sunset_mod + 45):
373 elif now_mod < (sunrise_mod + 45) or now_mod > (sunset_mod + 120):
378 def get_refresh_period() -> float:
379 if override_refresh_sec is not None:
380 return float(override_refresh_sec * 1000.0)
381 now = datetime.now(tz=pytz.timezone("US/Pacific"))
383 return float(kiosk_constants.refresh_period_night_sec * 1000.0)
385 return float(kiosk_constants.refresh_period_sec * 1000.0)
387 age = file_utils.describe_file_ctime(f"pages/{filename}")
388 bgcolor = pick_background_color()
392 pageid = f'"{command}" -> {filename}'
397 <TITLE>Kitchen Kiosk</TITLE>
398 <LINK rel="stylesheet" type="text/css" href="style.css">
399 <meta name="google" content="notranslate">
400 <SCRIPT TYPE="text/javascript">
402 // Zoom the 'contents' div to fit without scrollbars and then make
404 function zoomScreen() {
407 document.getElementById("content").style.zoom = z+"%";
408 var body = document.body;
409 var html = document.documentElement;
410 var height = Math.max(body.scrollHeight,
415 var windowHeight = window.innerHeight;
416 var width = Math.max(body.scrollWidth,
421 var windowWidth = window.innerWidth;
422 var heightRatio = height / windowHeight;
423 var widthRatio = width / windowWidth;
425 if (heightRatio <= 1.0 && widthRatio <= 1.0) {
430 document.getElementById("content").style.visibility = "visible";
433 // Load IMG tags with DATA-SRC attributes late.
434 function lateLoadImages() {
435 var image = document.getElementsByTagName('img');
436 for (var i = 0; i < image.length; i++) {
437 if (image[i].getAttribute('DATA-SRC')) {
438 image[i].setAttribute('SRC', image[i].getAttribute('DATA-SRC'));
446 // Operate the clock at the top of the page.
447 function runClock() {
448 var today = new Date();
449 var h = today.getHours();
450 var ampm = h >= 12 ? 'pm' : 'am';
452 h = h ? h : 12; // the hour '0' should be '12'
453 var m = maybeAddZero(today.getMinutes());
455 if (today.getSeconds() %% 2 == 0) {
456 colon = "<FONT STYLE='color: #%s; font-size: 4vmin; font-weight: bold'>:</FONT>";
458 document.getElementById("time").innerHTML = h + colon + m + ampm;
459 document.getElementById("date").innerHTML = today.toDateString();
460 var t = setTimeout(function(){runClock()}, 1000);
467 // Helper method for running the clock.
468 function maybeAddZero(x) {
469 return (x < 10) ? "0" + x : x;
472 // Do something on page load.
473 function addLoadEvent(func) {
474 var oldonload = window.onload;
475 if (typeof window.onload != 'function') {
476 window.onload = func;
478 window.onload = function() {
487 // Sleep thread helper.
488 const sleep = (milliseconds) => {
489 return new Promise(resolve => setTimeout(resolve, milliseconds))
492 var loadedDate = new Date();
494 addLoadEvent(zoomScreen);
495 addLoadEvent(runClock);
496 addLoadEvent(lateLoadImages);
501 // Runs the countdown line at the bottom and is responsible for
502 // normal page reloads caused by the expiration of a timer.
503 (function countdown() {
506 var now = new Date();
507 var deltaMs = now.getTime() - loadedDate.getTime();
509 var remainingMs = (totalMs - deltaMs);
511 if (remainingMs > 0) {
512 var hr = document.getElementById("countdown");
513 var width = (remainingMs / (totalMs - 5000)) * 100.0;
515 hr.style.visibility = "visible";
516 hr.style.width = " ".concat(width, "%%");
517 hr.style.backgroundColor = "maroon";
520 // Reload unconditionally after 22 sec.
521 window.location.reload(true);
524 // Brief sleep before doing it all over again.
525 sleep(50).then(() => {
531 % get_refresh_period()
535 function check_reload() {
536 var xhr = new XMLHttpRequest();
538 '%s/reload_immediately.html');
541 if (xhr.status === 200) {
542 window.location.reload(true);
548 // Periodically checks for emergency reload events.
549 setInterval(check_reload, 500);
553 % kiosk_constants.root_url
555 f.write(f'<BODY BGCOLOR="#{bgcolor}">')
558 <TABLE style="height:100%; width:100%" BORDER=0>
561 <DIV id="date"> </DIV>
563 <TD ALIGN="center"><FONT COLOR=#bbbbbb>
564 <DIV id="info"></DIV></FONT>
567 <DIV id="time"> </DIV>
570 <TR STYLE="vertical-align:top">
572 <DIV ID="content" STYLE="zoom: 1; visibility: hidden;">
573 <!-- BEGIN main page contents. -->
576 f.write(f'<!--#include virtual="{filename}"-->')
579 <!-- END main page contents. -->
582 <DIV STYLE="position: absolute; top:1030px; width:99%">
586 f.write(f"<FONT SIZE=2 COLOR=#bbbbbb>{pageid} @ {age} ago.</FONT>")
590 <HR id="countdown" STYLE="width:0px;
597 background-color:#ffffff;">
606 def renderer_update_internal_stats_page(
607 last_render: Dict[str, datetime],
608 render_counts: collections.Counter,
609 render_times: Dict[str, np.array],
611 logger.info("renderer: Updating internal render statistics page.")
612 with file_writer.file_writer(kiosk_constants.render_stats_pagename) as f:
616 <TABLE BORDER=0 WIDTH=95%>
618 <TH><B>Renderer Name</B></TH>
619 <TH><B>Last Run</B></TH>
620 <TH><B>Num Invocations</B></TH>
621 <TH><B>Render Latency</B></TH>
625 for n, r in enumerate(renderer_catalog.get_renderers()):
627 style = 'style="margin: 0; padding: 0; background: #c6b0b0;"'
629 style = 'style="margin: 0; padding: 0; background: #eeeeee;"'
631 last = last_render.get(name, None)
635 last = last.strftime("%Y/%m/%d %I:%M:%S%P")
636 count = render_counts.get(name, 0)
637 latency = render_times.get(name, np.array([]))
638 p25 = p50 = p75 = p90 = p99 = "N/A"
640 p25 = np.percentile(latency, 25)
641 p50 = np.percentile(latency, 50)
642 p75 = np.percentile(latency, 75)
643 p90 = np.percentile(latency, 90)
644 p99 = np.percentile(latency, 99)
648 <TD {style}>{name} </TD>
649 <TD {style}> {last} </TD>
650 <TD {style}><CENTER> {count} </CENTER></TD>
651 <TD {style}> p25={p25:5.2f}, p50={p50:5.2f}, p75={p75:5.2f}, p90={p90:5.2f}, p99={p99:5.2f}</TD>
660 def thread_invoke_renderers() -> None:
661 render_times: Dict[str, np.array] = {}
662 render_counts: collections.Counter = collections.Counter()
663 last_render: Dict[str, datetime] = {}
665 # Touch the internal render page now to signal that we're alive.
666 renderer_update_internal_stats_page(last_render, render_counts, render_times)
670 logger.info("renderer: invoking all overdue renderers in catalog...")
671 for r in renderer_catalog.get_renderers():
674 logger.info(f"renderer: Invoking {name}'s render method.")
677 except Exception as e:
680 f"renderer: Unexpected and unhandled exception ({e}) in {name}, swallowing it."
684 # Increment the count of render operations per renderer.
685 render_counts[name] += 1
687 # Keep track of the last time we invoked each renderer.
688 last_render[name] = datetime_utils.now_pacific()
690 # Record how long each render operation takes and warn if very long.
691 delta = time.time() - now
692 times = render_times.get(name, np.array([]))
693 times = np.insert(times, 0, delta)
694 render_times[name] = times
699 {hdr} Warning: {name}'s rendering took {delta:5.2f}s.
700 {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}
704 # Update a page about internal stats of renderers.
705 renderer_update_internal_stats_page(last_render, render_counts, render_times)
706 logger.info("renderer: having a little nap...")
707 time.sleep(kiosk_constants.render_period_sec)
710 @bootstrap.initialize
712 command_queue: Queue = Queue()
713 changer_thread: Optional[Thread] = None
714 renderer_thread: Optional[Thread] = None
715 janitor_thread: Optional[Thread] = None
716 hotword_thread: Optional[Thread] = None
718 if hotword_thread is None or not hotword_thread.is_alive():
719 if hotword_thread is None:
720 logger.info("watchdog: Starting up the hotword detector thread...")
723 "watchdog: The hotword detector thread seems to have died; restarting it and hoping for the best."
725 keyword_paths = [pvporcupine.KEYWORD_PATHS[x] for x in ["bumblebee"]]
726 sensitivities = [0.7] * len(keyword_paths)
727 listener = listen.HotwordListener(
732 hotword_thread = Thread(target=listener.listen_forever, args=())
733 hotword_thread.start()
735 if changer_thread is None or not changer_thread.is_alive():
736 if changer_thread is None:
737 logger.info("watchdog: Starting up the current page changer thread...")
740 "watchdog: The current page changer thread seems to have died; restarting it and hoping for the best."
742 changer_thread = Thread(target=thread_change_current, args=(command_queue,))
743 changer_thread.start()
745 if renderer_thread is None or not renderer_thread.is_alive():
746 if renderer_thread is None:
747 logger.info("watchdog: Starting up the page renderer thread...")
750 "watchdog: The page renderer thread seems to have died; restarting it and hoping for the best."
752 renderer_thread = Thread(target=thread_invoke_renderers, args=())
753 renderer_thread.start()
755 if janitor_thread is None or not janitor_thread.is_alive():
756 if janitor_thread is None:
757 logger.info("watchdog: Starting up the memory janitor thread...")
760 "watchdog: The memory janitor thread seems to have died; restarting it and hoping for the best."
762 janitor_thread = Thread(target=thread_janitor, args=())
763 janitor_thread.start()
765 # Have a little break and then check to make sure all threads are still alive.
766 logger.debug("watchdog: having a little nap.")
767 time.sleep(kiosk_constants.check_threads_period_sec)
770 if __name__ == "__main__":