Fixup weather renderer.
[kiosk.git] / kiosk.py
1 #!/usr/bin/env python3
2
3 import collections
4 from datetime import datetime
5 from difflib import SequenceMatcher
6 import gc
7 import logging
8 import os
9 import re
10 from threading import Thread
11 import time
12 import tracemalloc
13 from typing import Dict, List, Optional
14 from queue import Queue
15
16 import astral  # type: ignore
17 from astral.sun import sun  # type: ignore
18 import numpy as np
19 import pvporcupine
20 import pytz
21
22 from pyutils import (
23     bootstrap,
24     config,
25 )
26 from pyutils.datetimes import datetime_utils
27 from pyutils.files import file_utils
28
29 import kiosk_constants
30 import file_writer
31 import renderer_catalog
32 import chooser
33 import listen
34 import trigger_catalog
35
36
37 cfg = config.add_commandline_args(
38     f'Kiosk Server ({__file__})',
39     'A python server that runs a kiosk.'
40 )
41 logger = logging.getLogger(__file__)
42
43
44 def thread_janitor() -> None:
45     tracemalloc.start()
46     tracemalloc_target = 0.0
47     gc_target = 0.0
48     gc.enable()
49
50     # Main janitor loop; dump the largest pigs and force regular gcs.
51     while True:
52         now = time.time()
53         if now > tracemalloc_target:
54             tracemalloc_target = now + 30.0
55             snapshot = tracemalloc.take_snapshot()
56             snapshot = snapshot.filter_traces((
57                 tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
58                 tracemalloc.Filter(False, "<unknown>"),
59             ))
60             key_type = 'lineno'
61             limit = 10
62             top_stats = snapshot.statistics(key_type)
63             logger.info(f'janitor: Top {limit} lines')
64             for index, stat in enumerate(top_stats[:limit], 1):
65                 frame = stat.traceback[0]
66
67                 # replace "/path/to/module/file.py" with "module/file.py"
68                 filename = os.sep.join(frame.filename.split(os.sep)[-2:])
69                 logger.info(
70                     f'janitor: #{index}: {filename}:{frame.lineno}: {stat.size / 1024:.1f} KiB'
71                 )
72
73             other = top_stats[limit:]
74             if other:
75                 size = sum(stat.size for stat in other)
76                 logger.info(
77                     f'janitor: {len(other)} others: {size/1024:.1f} KiB'
78                 )
79             total = sum(stat.size for stat in top_stats)
80             logger.info(
81                 f'janitor: Total allocated size: {total / 1024:.1f} KiB'
82             )
83         if now > gc_target:
84             logger.info('janitor: kicking off a manual gc operation now.')
85             gc.collect()
86             gc_target = now + 120.0
87         time.sleep(30.0)
88
89
90 def guess_page(command: str, page_chooser: chooser.chooser) -> str:
91
92     def normalize_page(page: str) -> str:
93         logger.debug(f'normalize_page input: {page}')
94         page = page.replace('(', ' ')
95         page = page.replace('_', ' ')
96         page = page.replace(')', ' ')
97         page = page.replace('.html', '')
98         page = page.replace('CNNNews', 'news')
99         page = page.replace('CNNTechnology', 'technology')
100         page = page.replace('gocostco', 'costco list')
101         page = page.replace('gohardware', 'hardware list')
102         page = page.replace('gohouse', 'house list honey do')
103         page = page.replace('gcal', 'google calendar events')
104         page = page.replace('mynorthwest', 'northwest news')
105         page = page.replace('myq', 'myq garage door status')
106         page = page.replace('gomenu', 'dinner menu')
107         page = page.replace('gmaps-seattle-unwrapped', 'traffic')
108         page = page.replace('gomenu', 'dinner menu')
109         page = page.replace('WSJNews', 'news')
110         page = page.replace('telma', 'telma cabin')
111         page = page.replace('WSJBusiness', 'business news')
112         page = re.sub(r'[0-9]+', '', page)
113         logger.debug(f'normalize_page output: {page}')
114         return page
115
116     logger.info(f'No exact match for f{command}; trying to guess...')
117     best_page = None
118     best_score = None
119     for page in page_chooser.get_page_list():
120         npage = normalize_page(page)
121         score = SequenceMatcher(None, command, npage).ratio()
122         if best_score is None or score > best_score:
123             best_page = page
124             best_score = score
125     assert best_page is not None
126     logger.info(f'Best guess for f{command} => {best_page} (score = {best_score})')
127     return best_page
128
129
130 def process_command(command: str, page_history: List[str], page_chooser) -> str:
131     command = command.lower()
132     logger.info(f'Parsing verbal command: {command}')
133     page = None
134     if 'hold' in command:
135         page = page_history[0]
136     elif 'back' in command:
137         page = page_history[1]
138     elif 'skip' in command:
139         while True:
140             (page, _) = page_chooser.choose_next_page()
141             if page == page_history[0]:
142                 logger.debug(f'chooser: {page} is the same as last time!  Try again.')
143             else:
144                 break
145     elif 'internal' in command:
146         if 'render' in command:
147             page = kiosk_constants.render_stats_pagename
148         else:
149             page = kiosk_constants.render_stats_pagename
150     elif 'weather' in command:
151         if 'telma' in command or 'cabin' in command:
152             page = 'weather-telma_3_10800.html'
153         elif 'stevens' in command:
154             page = 'weather-stevens_3_10800.html'
155         else:
156             page = 'weather-home_3_10800.html'
157     elif 'cabin' in command:
158         if 'list' in command:
159             page = 'Cabin-(gocabin)_2_3600.html'
160         else:
161             page = 'hidden/cabin_driveway.html'
162     elif 'news' in command or 'headlines' in command:
163         page = 'cnn-CNNNews_4_25900.html'
164     elif 'clock' in command or 'time' in command:
165         page = 'clock_10_none.html'
166     elif 'countdown' in command or 'countdowns' in command:
167         page = 'countdown_3_7200.html'
168     elif 'costco' in command:
169         page = 'Costco-(gocostco)_2_3600.html'
170     elif 'calendar' in command or 'events' in command:
171         page = 'gcal_3_86400.html'
172     elif 'countdown' in command or 'countdowns' in command:
173         page = 'countdown_3_7200.html'
174     elif 'grocery' in command or 'groceries' in command:
175         page = 'Grocery-(gogrocery)_2_3600.html'
176     elif 'hardware' in command:
177         page = 'Hardware-(gohardware)_2_3600.html'
178     elif 'garage' in command:
179         page = 'myq_4_300.html'
180     elif 'menu' in command:
181         page = 'Menu-(gomenu)_2_3600.html'
182     elif 'cron' in command or 'health' in command:
183         page = 'periodic-health_6_300.html'
184     elif 'photo' in command or 'picture' in command:
185         page = 'photo_23_3600.html'
186     elif 'quote' in command or 'quotation' in command or 'quotes' in command:
187         page = 'quotes_4_10800.html'
188     elif 'stevens' in command:
189         page = 'stevens-conditions_1_86400.html'
190     elif 'stock' in command or 'stocks' in command:
191         page = 'stock_3_86400.html'
192     elif 'twitter' in command:
193         page = 'twitter_10_3600.html'
194     elif 'traffic' in command:
195         page = 'gmaps-seattle-unwrapped_5_none.html'
196     elif 'front' in command and 'door' in command:
197         page = 'hidden/frontdoor.html'
198     elif 'driveway' in command:
199         page = 'hidden/driveway.html'
200     elif 'backyard' in command:
201         page = 'hidden/backyard.html'
202     else:
203         page = guess_page(command, page_chooser)
204     assert page is not None
205     logger.info(f'Parsed to {page}')
206     return page
207
208
209 def thread_change_current(command_queue: Queue) -> None:
210     page_history = ["", ""]
211     swap_page_target = 0.0
212
213     def filter_news_during_dinnertime(page: str) -> bool:
214         now = datetime.now(tz=pytz.timezone("US/Pacific"))
215         is_dinnertime = now.hour >= 18 and now.hour <= 20
216         return not is_dinnertime or not (
217             "cnn" in page
218             or "news" in page
219             or "mynorthwest" in page
220             or "seattle" in page
221             or "wsj" in page
222         )
223
224     page_chooser = chooser.weighted_random_chooser_with_triggers(
225         trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
226     )
227     current_file = os.path.join(kiosk_constants.pages_dir, "current.shtml")
228     emergency_file = os.path.join(kiosk_constants.pages_dir, "reload_immediately.html")
229
230     # Main chooser loop
231     while True:
232         now = time.time()
233
234         # Check for a verbal command.
235         command = None
236         try:
237             command = command_queue.get(block=False)
238         except Exception:
239             command = None
240
241         if command is not None:
242             logger.info(f'chooser: We got a verbal command ("{command}"), parsing it...')
243             triggered = True
244             page = process_command(command, page_history, page_chooser)
245         else:
246             while True:
247                 (page, triggered) = page_chooser.choose_next_page()
248                 if triggered:
249                     logger.info('chooser: A trigger is active...')
250                     break
251                 else:
252                     if page == page_history[0]:
253                         logger.debug(f'chooser: {page} is the same as last time! Try again.')
254                     else:
255                         break
256
257         if triggered:
258             if page != page_history[0] or (swap_page_target - now) < 10.0:
259                 logger.info(f'chooser: An emergency page reload to {page} is needed at this time.')
260                 swap_page_target = now + kiosk_constants.emergency_refresh_period_sec
261
262                 # Set current.shtml to the right page.
263                 try:
264                     with open(current_file, "w") as f:
265                         emit(
266                             f,
267                             page,
268                             override_refresh_sec = kiosk_constants.emergency_refresh_period_sec,
269                             command = command
270                         )
271                     logger.debug(f'chooser: Wrote {current_file}.')
272                 except Exception as e:
273                     logger.exception(e)
274                     logger.error(f'chooser: Unexpected exception; assuming {page} doesn\'t exist?!')
275                     continue
276
277                 # Also notify XMLHTTP clients that they need to refresh now.
278                 with open(emergency_file, "w") as f:
279                     f.write(f'Reload, suckers... you HAVE to see {page}!')
280                 logger.debug(f'chooser: Wrote {emergency_file}...')
281
282                 # Fix this hack... maybe read the webserver logs and see if it
283                 # actually was picked up?
284                 time.sleep(0.999)
285                 os.remove(emergency_file)
286                 logger.debug(f'chooser: ...and removed {emergency_file}.')
287
288         elif now >= swap_page_target:
289             assert page != page_history[0]
290             logger.info(
291                 f'chooser: Nominal choice of {page} as the next to show.'
292             )
293             swap_page_target = now + kiosk_constants.refresh_period_sec
294             try:
295                 with open(current_file, "w") as f:
296                     emit(f, page)
297                 logger.debug(f'chooser: Wrote {current_file}.')
298             except Exception as e:
299                 logger.exception(e)
300                 logger.error(f'chooser: Unexpected exception; assuming {page} doesn\'t exist?!')
301                 continue
302         page_history.insert(0, page)
303         page_history = page_history[0:10]
304         time.sleep(0.5)
305
306
307 def emit(f,
308          filename: str,
309          *,
310          override_refresh_sec: int = None,
311          command: str = None):
312     if 'unwrapped' not in filename:
313         logger.debug(f'Emitting {filename} wrapped.')
314         emit_wrapped(f, filename, override_refresh_sec=override_refresh_sec, command=command)
315     else:
316         logger.debug(f'Emitting {filename} raw.')
317         emit_raw(f, filename)
318
319
320 def emit_raw(f, filename: str):
321     f.write(f'<!--#include virtual="{filename}"-->')
322
323
324 def emit_wrapped(f,
325                  filename: str,
326                  *,
327                  override_refresh_sec: int = None,
328                  command: str = None) -> None:
329
330     def pick_background_color() -> str:
331         now = datetime_utils.now_pacific()
332         city = astral.LocationInfo(
333             "Bellevue", "USA", "US/Pacific", 47.610, -122.201
334         )
335         s = sun(city.observer, date=now, tzinfo=pytz.timezone("US/Pacific"))
336         sunrise_mod = datetime_utils.minute_number(s["sunrise"].hour, s["sunrise"].minute)
337         sunset_mod = datetime_utils.minute_number(s["sunset"].hour, s["sunset"].minute)
338         now_mod = datetime_utils.minute_number(now.hour, now.minute)
339         if now_mod < sunrise_mod or now_mod > (sunset_mod + 45):
340             return "E6B8B8"
341         elif now_mod < (sunrise_mod + 45) or now_mod > (sunset_mod + 120):
342             return "EECDCD"
343         else:
344             return "FFFFFF"
345
346     def get_refresh_period() -> float:
347         if override_refresh_sec is not None:
348             return float(override_refresh_sec * 1000.0)
349         now = datetime.now(tz=pytz.timezone("US/Pacific"))
350         if now.hour < 6:
351             return float(kiosk_constants.refresh_period_night_sec * 1000.0)
352         else:
353             return float(kiosk_constants.refresh_period_sec * 1000.0)
354
355     age = file_utils.describe_file_ctime(f"pages/{filename}")
356     bgcolor = pick_background_color()
357     if command is None:
358         pageid = filename
359     else:
360         pageid = f'"{command}" -> {filename}'
361
362     f.write(
363 """
364 <HEAD>
365   <TITLE>Kitchen Kiosk</TITLE>
366   <LINK rel="stylesheet" type="text/css" href="style.css">
367   <meta name="google" content="notranslate">
368   <SCRIPT TYPE="text/javascript">
369
370   // Zoom the 'contents' div to fit without scrollbars and then make
371   // it visible.
372   function zoomScreen() {
373     z = 285;
374     do {
375       document.getElementById("content").style.zoom = z+"%";
376       var body = document.body;
377       var html = document.documentElement;
378       var height = Math.max(body.scrollHeight,
379                             body.offsetHeight,
380                             html.clientHeight,
381                             html.scrollHeight,
382                             html.offsetHeight);
383       var windowHeight = window.innerHeight;
384       var width = Math.max(body.scrollWidth,
385                            body.offsetWidth,
386                            html.clientWidth,
387                            html.scrollWidth,
388                            html.offsetWidth);
389       var windowWidth = window.innerWidth;
390       var heightRatio = height / windowHeight;
391       var widthRatio = width / windowWidth;
392
393       if (heightRatio <= 1.0 && widthRatio <= 1.0) {
394         break;
395       }
396       z -= 4;
397     } while(z >= 70);
398     document.getElementById("content").style.visibility = "visible";
399   }
400
401   // Load IMG tags with DATA-SRC attributes late.
402   function lateLoadImages() {
403     var image = document.getElementsByTagName('img');
404     for (var i = 0; i < image.length; i++) {
405       if (image[i].getAttribute('DATA-SRC')) {
406         image[i].setAttribute('SRC', image[i].getAttribute('DATA-SRC'));
407       }
408     }
409   }
410 """
411     )
412     f.write(
413 """
414   // Operate the clock at the top of the page.
415   function runClock() {
416     var today = new Date();
417     var h = today.getHours();
418     var ampm = h >= 12 ? 'pm' : 'am';
419     h = h %% 12;
420     h = h ? h : 12; // the hour '0' should be '12'
421     var m = maybeAddZero(today.getMinutes());
422     var colon = ":";
423     if (today.getSeconds() %% 2 == 0) {
424       colon = "<FONT STYLE='color: #%s; font-size: 4vmin; font-weight: bold'>:</FONT>";
425     }
426     document.getElementById("time").innerHTML = h + colon + m + ampm;
427     document.getElementById("date").innerHTML = today.toDateString();
428     var t = setTimeout(function(){runClock()}, 1000);
429   }
430 """ % bgcolor
431     )
432     f.write(
433 """
434   // Helper method for running the clock.
435   function maybeAddZero(x) {
436     return (x < 10) ? "0" + x : x;
437   }
438
439   // Do something on page load.
440   function addLoadEvent(func) {
441     var oldonload = window.onload;
442     if (typeof window.onload != 'function') {
443       window.onload = func;
444     } else {
445       window.onload = function() {
446         if (oldonload) {
447           oldonload();
448         }
449         func();
450       }
451     }
452   }
453
454   // Sleep thread helper.
455   const sleep = (milliseconds) => {
456     return new Promise(resolve => setTimeout(resolve, milliseconds))
457   }
458
459   var loadedDate = new Date();
460
461   addLoadEvent(zoomScreen);
462   addLoadEvent(runClock);
463   addLoadEvent(lateLoadImages);
464 """
465     )
466     f.write(
467 """
468   // Runs the countdown line at the bottom and is responsible for
469   // normal page reloads caused by the expiration of a timer.
470   (function countdown() {
471     setTimeout(
472       function() {
473         var now = new Date();
474         var deltaMs = now.getTime() - loadedDate.getTime();
475         var totalMs = %d;
476         var remainingMs = (totalMs - deltaMs);
477
478         if (remainingMs > 0) {
479           var hr = document.getElementById("countdown");
480           var width = (remainingMs / (totalMs - 5000)) * 100.0;
481           if (width <= 100) {
482             hr.style.visibility = "visible";
483             hr.style.width = " ".concat(width, "%%");
484             hr.style.backgroundColor = "maroon";
485           }
486         } else {
487           // Reload unconditionally after 22 sec.
488           window.location.reload(true);
489         }
490
491         // Brief sleep before doing it all over again.
492         sleep(50).then(() => {
493           countdown();
494         });
495       }, 50)
496   })();
497 """ % get_refresh_period()
498     )
499     f.write(
500 """
501   function check_reload() {
502     var xhr = new XMLHttpRequest();
503     xhr.open('GET',
504              '%s/reload_immediately.html');
505     xhr.onload =
506       function() {
507         if (xhr.status === 200) {
508           window.location.reload(true);
509         }
510       };
511     xhr.send();
512   }
513
514   // Periodically checks for emergency reload events.
515   setInterval(check_reload, 500);
516   </SCRIPT>
517 </HEAD>
518 """ % kiosk_constants.root_url)
519     f.write(f'<BODY BGCOLOR="#{bgcolor}">')
520     f.write(
521 """
522     <TABLE style="height:100%; width:100%" BORDER=0>
523     <TR HEIGHT=30>
524         <TD ALIGN="left">
525             <DIV id="date">&nbsp;</DIV>
526         </TD>
527         <TD ALIGN="center"><FONT COLOR=#bbbbbb>
528             <DIV id="info"></DIV></FONT>
529         </TD>
530         <TD ALIGN="right">
531             <DIV id="time">&nbsp;</DIV>
532         </TD>
533     </TR>
534     <TR STYLE="vertical-align:top">
535         <TD COLSPAN=3>
536             <DIV ID="content" STYLE="zoom: 1; visibility: hidden;">
537               <!-- BEGIN main page contents. -->
538 """
539     )
540     f.write(f'<!--#include virtual="{filename}"-->')
541     f.write(
542 """
543             <!-- END main page contents. -->
544             </DIV>
545             <BR>
546             <DIV STYLE="position: absolute; top:1030px; width:99%">
547             <P ALIGN="right">
548 """
549     )
550     f.write(f'<FONT SIZE=2 COLOR=#bbbbbb>{pageid} @ {age} ago.</FONT>')
551     f.write(
552 """
553             </P>
554             <HR id="countdown" STYLE="width:0px;
555                                       text-align:left;
556                                       margin:0;
557                                       border:none;
558                                       border-width:0;
559                                       height:5px;
560                                       visibility:hidden;
561                                       background-color:#ffffff;">
562             </DIV>
563         </TD>
564     </TR>
565     </TABLE>
566 </BODY>"""
567     )
568
569
570 def renderer_update_internal_stats_page(
571         last_render: Dict[str, datetime],
572         render_counts: collections.Counter,
573         render_times: Dict[str, np.array],
574 ) -> None:
575     logger.info(
576         'renderer: Updating internal render statistics page.'
577     )
578     with file_writer.file_writer(kiosk_constants.render_stats_pagename) as f:
579         f.write(
580 '''
581 <CENTER>
582 <TABLE BORDER=0 WIDTH=95%>
583     <TR>
584     <TH><B>Renderer Name</B></TH>
585     <TH><B>Last Run</B></TH>
586     <TH><B>Num Invocations</B></TH>
587     <TH><B>Render Latency</B></TH>
588     </TR>
589 ''')
590         for n, r in enumerate(renderer_catalog.get_renderers()):
591             if n % 2 == 0:
592                 style = 'style="margin: 0; padding: 0; background: #c6b0b0;"'
593             else:
594                 style = 'style="margin: 0; padding: 0; background: #eeeeee;"'
595             name = r.get_name()
596             last = last_render.get(name, None)
597             if last is None:
598                 last = 'never'
599             else:
600                 last = last.strftime('%Y/%m/%d %I:%M:%S%P')
601             count = render_counts.get(name, 0)
602             latency = render_times.get(name, np.array([]))
603             p25 = p50 = p75 = p90 = p99 = 'N/A'
604             try:
605                 p25 = np.percentile(latency, 25)
606                 p50 = np.percentile(latency, 50)
607                 p75 = np.percentile(latency, 75)
608                 p90 = np.percentile(latency, 90)
609                 p99 = np.percentile(latency, 99)
610                 f.write(
611 f'''
612     <TR>
613     <TD {style}>{name}&nbsp;</TD>
614     <TD {style}>&nbsp;{last}&nbsp;</TD>
615     <TD {style}><CENTER>&nbsp;{count}&nbsp;</CENTER></TD>
616     <TD {style}>&nbsp;p25={p25:5.2f}, p50={p50:5.2f}, p75={p75:5.2f}, p90={p90:5.2f}, p99={p99:5.2f}</TD>
617     </TR>
618 '''
619                 )
620             except IndexError:
621                 pass
622         f.write('</TABLE>')
623
624
625 def thread_invoke_renderers() -> None:
626     render_times: Dict[str, np.array] = {}
627     render_counts: collections.Counter = collections.Counter()
628     last_render: Dict[str, datetime] = {}
629
630     # Touch the internal render page now to signal that we're alive.
631     renderer_update_internal_stats_page(last_render, render_counts, render_times)
632
633     # Main renderer loop
634     while True:
635         logger.info(
636             'renderer: invoking all overdue renderers in catalog...'
637         )
638         for r in renderer_catalog.get_renderers():
639             name = r.get_name()
640             now = time.time()
641             logger.info(f'renderer: Invoking {name}\'s render method.')
642             try:
643                 r.render()
644             except Exception as e:
645                 logger.exception(e)
646                 logger.error(
647                     f'renderer: Unexpected and unhandled exception ({e}) in {name}, swallowing it.'
648                 )
649                 continue
650
651             # Increment the count of render operations per renderer.
652             render_counts[name] += 1
653
654             # Keep track of the last time we invoked each renderer.
655             last_render[name] = datetime_utils.now_pacific()
656
657             # Record how long each render operation takes and warn if very long.
658             delta = time.time() - now
659             times = render_times.get(name, np.array([]))
660             times = np.insert(times, 0, delta)
661             render_times[name] = times
662             if delta > 1.0:
663                 hdr = 'renderer: '
664                 logger.warning(
665 f'''
666 {hdr} Warning: {name}'s rendering took {delta:5.2f}s.
667 {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}
668 '''
669                 )
670
671         # Update a page about internal stats of renderers.
672         renderer_update_internal_stats_page(last_render, render_counts, render_times)
673         logger.info('renderer: having a little nap...')
674         time.sleep(kiosk_constants.render_period_sec)
675
676
677 @bootstrap.initialize
678 def main() -> None:
679     command_queue: Queue = Queue()
680     changer_thread: Optional[Thread] = None
681     renderer_thread: Optional[Thread] = None
682     janitor_thread: Optional[Thread] = None
683     hotword_thread: Optional[Thread] = None
684     while True:
685         if hotword_thread is None or not hotword_thread.is_alive():
686             if hotword_thread is None:
687                 logger.info('watchdog: Starting up the hotword detector thread...')
688             else:
689                 logger.warning(
690                     'watchdog: The hotword detector thread seems to have died; restarting it and hoping for the best.'
691                 )
692             keyword_paths = [pvporcupine.KEYWORD_PATHS[x] for x in ["bumblebee"]]
693             sensitivities = [0.7] * len(keyword_paths)
694             listener = listen.HotwordListener(
695                 command_queue,
696                 keyword_paths,
697                 sensitivities,
698             )
699             hotword_thread = Thread(target=listener.listen_forever, args=())
700             hotword_thread.start()
701
702         if changer_thread is None or not changer_thread.is_alive():
703             if changer_thread is None:
704                 logger.info('watchdog: Starting up the current page changer thread...')
705             else:
706                 logger.warning(
707                     'watchdog: The current page changer thread seems to have died; restarting it and hoping for the best.'
708                 )
709             changer_thread = Thread(target=thread_change_current, args=(command_queue,))
710             changer_thread.start()
711
712         if renderer_thread is None or not renderer_thread.is_alive():
713             if renderer_thread is None:
714                 logger.info('watchdog: Starting up the page renderer thread...')
715             else:
716                 logger.warning(
717                     'watchdog: The page renderer thread seems to have died; restarting it and hoping for the best.'
718                 )
719             renderer_thread = Thread(target=thread_invoke_renderers, args=())
720             renderer_thread.start()
721
722         if janitor_thread is None or not janitor_thread.is_alive():
723             if janitor_thread is None:
724                 logger.info('watchdog: Starting up the memory janitor thread...')
725             else:
726                 logger.warning(
727                     'watchdog: The memory janitor thread seems to have died; restarting it and hoping for the best.'
728                 )
729             janitor_thread = Thread(target=thread_janitor, args=())
730             janitor_thread.start()
731
732         # Have a little break and then check to make sure all threads are still alive.
733         logger.debug('watchdog: having a little nap.')
734         time.sleep(kiosk_constants.check_threads_period_sec)
735
736
737 if __name__ == "__main__":
738     main()