Somewhat large overhaul to move the kiosk towards using normal python
[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 import bootstrap
23 import config
24 import datetime_utils
25
26 import constants
27 import file_writer
28 import renderer_catalog
29 import chooser
30 import listen
31 import trigger_catalog
32 import utils
33
34
35 cfg = config.add_commandline_args(
36     f'Kiosk Server ({__file__})',
37     'A python server that runs a kiosk.'
38 )
39 logger = logging.getLogger(__file__)
40
41
42 def thread_janitor() -> None:
43     tracemalloc.start()
44     tracemalloc_target = 0.0
45     gc_target = 0.0
46     gc.enable()
47
48     # Main janitor loop; dump the largest pigs and force regular gcs.
49     while True:
50         now = time.time()
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>"),
57             ))
58             key_type = 'lineno'
59             limit = 10
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]
64
65                 # replace "/path/to/module/file.py" with "module/file.py"
66                 filename = os.sep.join(frame.filename.split(os.sep)[-2:])
67                 logger.info(
68                     f'janitor: #{index}: {filename}:{frame.lineno}: {stat.size / 1024:.1f} KiB'
69                 )
70
71             other = top_stats[limit:]
72             if other:
73                 size = sum(stat.size for stat in other)
74                 logger.info(
75                     f'janitor: {len(other)} others: {size/1024:.1f} KiB'
76                 )
77             total = sum(stat.size for stat in top_stats)
78             logger.info(
79                 f'janitor: Total allocated size: {total / 1024:.1f} KiB'
80             )
81         if now > gc_target:
82             logger.info('janitor: kicking off a manual gc operation now.')
83             gc.collect()
84             gc_target = now + 120.0
85         time.sleep(30.0)
86
87
88 def guess_page(command: str, page_chooser: chooser.chooser) -> str:
89
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}')
112         return page
113
114     best_page = None
115     best_score = None
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:
120             best_page = page
121     assert best_page is not None
122     return best_page
123
124
125 def process_command(command: str, page_history: List[str], page_chooser) -> str:
126     logger.debug(f'Parsing verbal command: {command}')
127     page = None
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:
133         while True:
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.')
137             else:
138                 break
139     elif 'internal' in command:
140         if 'render' in command:
141             page = constants.render_stats_pagename
142         else:
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'
149         else:
150             page = 'weather-home_3_10800.html'
151     elif 'cabin' in command:
152         if 'list' in command:
153             page = 'Cabin-(gocabin)_2_3600.html'
154         else:
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'
196     else:
197         page = guess_page(command, page_chooser)
198     assert page is not None
199     logger.debug(f'Chose page {page}')
200     return page
201
202
203 def thread_change_current(command_queue: Queue) -> None:
204     page_history = ["", ""]
205     swap_page_target = 0.0
206
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 (
211             "cnn" in page
212             or "news" in page
213             or "mynorthwest" in page
214             or "seattle" in page
215             or "wsj" in page
216         )
217
218     page_chooser = chooser.weighted_random_chooser_with_triggers(
219         trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
220     )
221     current_file = os.path.join(constants.pages_dir, "current.shtml")
222     emergency_file = os.path.join(constants.pages_dir, "reload_immediately.html")
223
224     # Main chooser loop
225     while True:
226         now = time.time()
227
228         # Check for a verbal command.
229         command = None
230         try:
231             command = command_queue.get(block=False)
232         except Exception:
233             command = None
234
235         if command is not None:
236             logger.info(f'chooser: We got a verbal command ("{command}"), parsing it...')
237             triggered = True
238             page = process_command(command, page_history, page_chooser)
239         else:
240             while True:
241                 (page, triggered) = page_chooser.choose_next_page()
242                 if triggered:
243                     logger.info('chooser: A trigger is active...')
244                     break
245                 else:
246                     if page == page_history[0]:
247                         logger.debug(f'chooser: {page} is the same as last time! Try again.')
248                     else:
249                         break
250
251         if triggered:
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
255
256                 # Set current.shtml to the right page.
257                 try:
258                     with open(current_file, "w") as f:
259                         emit_wrapped(
260                             f,
261                             page,
262                             override_refresh_sec = constants.emergency_refresh_period_sec,
263                             command = command
264                         )
265                     logger.debug(f'chooser: Wrote {current_file}.')
266                 except Exception as e:
267                     logger.exception(e)
268                     logger.error(f'chooser: Unexpected exception; assuming {page} doesn\'t exist?!')
269                     continue
270
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}...')
275
276                 # Fix this hack... maybe read the webserver logs and see if it
277                 # actually was picked up?
278                 time.sleep(0.95)
279                 os.remove(emergency_file)
280                 logger.debug(f'chooser: ...and removed {emergency_file}.')
281
282         elif now >= swap_page_target:
283             assert page != page_history[0]
284             logger.info(
285                 f'chooser: Nominal choice of {page} as the next to show.'
286             )
287             swap_page_target = now + constants.refresh_period_sec
288             try:
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:
293                 logger.exception(e)
294                 logger.error(f'chooser: Unexpected exception; assuming {page} doesn\'t exist?!')
295                 continue
296         page_history.insert(0, page)
297         page_history = page_history[0:10]
298         time.sleep(0.5)
299
300
301 def emit_wrapped(f,
302                  filename: str,
303                  *,
304                  override_refresh_sec: int = None,
305                  command: str = None) -> None:
306
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
311         )
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):
317             return "E6B8B8"
318         elif now_mod < (sunrise_mod + 45) or now_mod > (sunset_mod + 120):
319             return "EECDCD"
320         else:
321             return "FFFFFF"
322
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"))
327         if now.hour < 6:
328             return float(constants.refresh_period_night_sec * 1000.0)
329         else:
330             return float(constants.refresh_period_sec * 1000.0)
331
332     age = utils.describe_age_of_file_briefly(f"pages/{filename}")
333     bgcolor = pick_background_color()
334     if command is None:
335         pageid = filename
336     else:
337         pageid = f'"{command}" -> {filename}'
338
339     f.write(
340 """
341 <HEAD>
342   <TITLE>Kitchen Kiosk</TITLE>
343   <LINK rel="stylesheet" type="text/css" href="style.css">
344   <SCRIPT TYPE="text/javascript">
345
346   // Zoom the 'contents' div to fit without scrollbars and then make
347   // it visible.
348   function zoomScreen() {
349     z = 285;
350     do {
351       document.getElementById("content").style.zoom = z+"%";
352       var body = document.body;
353       var html = document.documentElement;
354       var height = Math.max(body.scrollHeight,
355                             body.offsetHeight,
356                             html.clientHeight,
357                             html.scrollHeight,
358                             html.offsetHeight);
359       var windowHeight = window.innerHeight;
360       var width = Math.max(body.scrollWidth,
361                            body.offsetWidth,
362                            html.clientWidth,
363                            html.scrollWidth,
364                            html.offsetWidth);
365       var windowWidth = window.innerWidth;
366       var heightRatio = height / windowHeight;
367       var widthRatio = width / windowWidth;
368
369       if (heightRatio <= 1.0 && widthRatio <= 1.0) {
370         break;
371       }
372       z -= 4;
373     } while(z >= 70);
374     document.getElementById("content").style.visibility = "visible";
375   }
376
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'));
383       }
384     }
385   }
386 """
387     )
388     f.write(
389 """
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';
395     h = h %% 12;
396     h = h ? h : 12; // the hour '0' should be '12'
397     var m = maybeAddZero(today.getMinutes());
398     var colon = ":";
399     if (today.getSeconds() %% 2 == 0) {
400       colon = "<FONT STYLE='color: #%s; font-size: 4vmin; font-weight: bold'>:</FONT>";
401     }
402     document.getElementById("time").innerHTML = h + colon + m + ampm;
403     document.getElementById("date").innerHTML = today.toDateString();
404     var t = setTimeout(function(){runClock()}, 1000);
405   }
406 """ % bgcolor
407     )
408     f.write(
409 """
410   // Helper method for running the clock.
411   function maybeAddZero(x) {
412     return (x < 10) ? "0" + x : x;
413   }
414
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;
420     } else {
421       window.onload = function() {
422         if (oldonload) {
423           oldonload();
424         }
425         func();
426       }
427     }
428   }
429
430   // Sleep thread helper.
431   const sleep = (milliseconds) => {
432     return new Promise(resolve => setTimeout(resolve, milliseconds))
433   }
434
435   var loadedDate = new Date();
436
437   addLoadEvent(zoomScreen);
438   addLoadEvent(runClock);
439   addLoadEvent(lateLoadImages);
440 """
441     )
442     f.write(
443 """
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() {
447     setTimeout(
448       function() {
449         var now = new Date();
450         var deltaMs = now.getTime() - loadedDate.getTime();
451         var totalMs = %d;
452         var remainingMs = (totalMs - deltaMs);
453
454         if (remainingMs > 0) {
455           var hr = document.getElementById("countdown");
456           var width = (remainingMs / (totalMs - 5000)) * 100.0;
457           if (width <= 100) {
458             hr.style.visibility = "visible";
459             hr.style.width = " ".concat(width, "%%");
460             hr.style.backgroundColor = "maroon";
461           }
462         } else {
463           // Reload unconditionally after 22 sec.
464           window.location.reload(true);
465         }
466
467         // Brief sleep before doing it all over again.
468         sleep(50).then(() => {
469           countdown();
470         });
471       }, 50)
472   })();
473 """ % get_refresh_period()
474     )
475     f.write(
476 """
477   function check_reload() {
478     var xhr = new XMLHttpRequest();
479     xhr.open('GET',
480              '%s/reload_immediately.html');
481     xhr.onload =
482       function() {
483         if (xhr.status === 200) {
484           window.location.reload(true);
485         }
486       };
487     xhr.send();
488   }
489
490   // Periodically checks for emergency reload events.
491   setInterval(check_reload, 500);
492   </SCRIPT>
493 </HEAD>
494 """ % constants.root_url)
495     f.write(f'<BODY BGCOLOR="#{bgcolor}">')
496     f.write(
497 """
498     <TABLE style="height:100%; width:100%" BORDER=0>
499     <TR HEIGHT=30>
500         <TD ALIGN="left">
501             <DIV id="date">&nbsp;</DIV>
502         </TD>
503         <TD ALIGN="center"><FONT COLOR=#bbbbbb>
504             <DIV id="info"></DIV></FONT>
505         </TD>
506         <TD ALIGN="right">
507             <DIV id="time">&nbsp;</DIV>
508         </TD>
509     </TR>
510     <TR STYLE="vertical-align:top">
511         <TD COLSPAN=3>
512             <DIV ID="content" STYLE="zoom: 1; visibility: hidden;">
513               <!-- BEGIN main page contents. -->
514 """
515     )
516     f.write(f'<!--#include virtual="{filename}"-->')
517     f.write(
518 """
519             <!-- END main page contents. -->
520             </DIV>
521             <BR>
522             <DIV STYLE="position: absolute; top:1030px; width:99%">
523             <P ALIGN="right">
524 """
525     )
526     f.write(f'<FONT SIZE=2 COLOR=#bbbbbb>{pageid} @ {age} ago.</FONT>')
527     f.write(
528 """
529             </P>
530             <HR id="countdown" STYLE="width:0px;
531                                       text-align:left;
532                                       margin:0;
533                                       border:none;
534                                       border-width:0;
535                                       height:5px;
536                                       visibility:hidden;
537                                       background-color:#ffffff;">
538             </DIV>
539         </TD>
540     </TR>
541     </TABLE>
542 </BODY>"""
543     )
544
545
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],
550 ) -> None:
551     logger.debug(
552         f'renderer: Updating internal render statistics page.'
553     )
554     with file_writer.file_writer(constants.render_stats_pagename) as f:
555         f.write(
556 f'''
557 <CENTER>
558 <TABLE BORDER=0 WIDTH=95%>
559     <TR>
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>
564     </TR>
565 ''')
566         for n, r in enumerate(renderer_catalog.get_renderers()):
567             if n % 2 == 0:
568                 style = 'style="margin: 0; padding: 0; background: #c6b0b0;"'
569             else:
570                 style = 'style="margin: 0; padding: 0; background: #eeeeee;"'
571             name = r.get_name()
572             last = last_render.get(name, None)
573             if last is None:
574                 last = 'never'
575             else:
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'
580             try:
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)
586             except IndexError:
587                 pass
588             f.write(
589 f'''
590     <TR>
591     <TD {style}>{name}&nbsp;</TD>
592     <TD {style}>&nbsp;{last}&nbsp;</TD>
593     <TD {style}><CENTER>&nbsp;{count}&nbsp;</CENTER></TD>
594     <TD {style}>&nbsp;p25={p25:5.2f}, p50={p50:5.2f}, p75={p75:5.2f}, p90={p90:5.2f}, p99={p99:5.2f}</TD>
595     </TR>
596 '''
597             )
598             f.write('</TABLE>')
599
600
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] = {}
605
606     # Main renderer loop
607     while True:
608         logger.info(
609             'renderer: invoking all overdue renderers in catalog...'
610         )
611         for r in renderer_catalog.get_renderers():
612             name = r.get_name()
613             now = time.time()
614             try:
615                 r.render()
616             except Exception as e:
617                 logger.exception(e)
618                 logger.error(
619                     f'renderer: Unexpected and unhandled exception ({e}) in {name}, swallowing it.'
620                 )
621                 continue
622
623             # Increment the count of render operations per renderer.
624             render_counts[name] += 1
625
626             # Keep track of the last time we invoked each renderer.
627             last_render[name] = datetime_utils.now_pacific()
628
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
634             if delta > 1.0:
635                 hdr = f'renderer: '
636                 logger.warning(
637 f'''
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}
640 '''
641                 )
642
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)
647
648
649 @bootstrap.initialize
650 def main() -> None:
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
656     while True:
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...')
660             else:
661                 logger.warning(
662                     'watchdog: The hotword detector thread seems to have died; restarting it and hoping for the best.'
663                 )
664             keyword_paths = [pvporcupine.KEYWORD_PATHS[x] for x in ["bumblebee"]]
665             sensitivities = [0.7] * len(keyword_paths)
666             listener = listen.HotwordListener(
667                 command_queue,
668                 keyword_paths,
669                 sensitivities,
670             )
671             hotword_thread = Thread(target=listener.listen_forever, args=())
672             hotword_thread.start()
673
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...')
677             else:
678                 logger.warning(
679                     'watchdog: The current page changer thread seems to have died; restarting it and hoping for the best.'
680                 )
681             changer_thread = Thread(target=thread_change_current, args=(command_queue,))
682             changer_thread.start()
683
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...')
687             else:
688                 logger.warning(
689                     'watchdog: The page renderer thread seems to have died; restarting it and hoping for the best.'
690                 )
691             renderer_thread = Thread(target=thread_invoke_renderers, args=())
692             renderer_thread.start()
693
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...')
697             else:
698                 logger.warning(
699                     'watchdog: The memory janitor thread seems to have died; restarting it and hoping for the best.'
700                 )
701             janitor_thread = Thread(target=thread_janitor, args=())
702             janitor_thread.start()
703
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)
707
708
709 if __name__ == "__main__":
710     main()