-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
executable file
·1662 lines (1445 loc) · 59.7 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/home/pi/protovac/env/bin/python
import os, logging
DEBUG = os.environ.get('DEBUG')
logging.basicConfig(
filename='protovax.log',
format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s',
level=logging.DEBUG if DEBUG else logging.INFO)
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
logging.info('')
logging.info('Boot up')
os.system('stty -ixon')
import curses
import requests
import pytz
import re
import os
import time
import json
import textwrap
import random
import qrcode
import urllib.parse
from PIL import Image, ImageEnhance, ImageFont, ImageDraw
from datetime import datetime, timezone, timedelta
import paho.mqtt.publish as publish
try:
import secrets
wa_api_key = secrets.wa_api_key
except:
wa_api_key = None
try:
import secrets
openai_key = secrets.openai_key
except:
openai_key = None
KEY_ESCAPE = 27
KEY_ENTER = 10
KEY_SPACE = 32
TIMEZONE_CALGARY = pytz.timezone('America/Edmonton')
NETHACK_LOCATION = '/usr/games/nethack'
MORIA_LOCATION = '/usr/games/moria'
_2048_LOCATION = '/home/pi/2048-cli/2048'
FROTZ_LOCATION = '/usr/games/frotz'
HITCHHIKERS_LOCATION = '/home/pi/frotz/hhgg.z3'
SUDOKU_LOCATION = '/usr/games/nudoku'
HAS_NETHACK = os.path.isfile(NETHACK_LOCATION)
HAS_MORIA = os.path.isfile(MORIA_LOCATION)
HAS_2048 = os.path.isfile(_2048_LOCATION)
HAS_FROTZ = os.path.isfile(FROTZ_LOCATION)
HAS_HITCHHIKERS = os.path.isfile(HITCHHIKERS_LOCATION)
HAS_SUDOKU = os.path.isfile(SUDOKU_LOCATION)
location = os.path.dirname(os.path.realpath(__file__))
with open(location + '/info.txt') as f:
PROTO_INFO = f.read()
for num, line in enumerate(PROTO_INFO.split('\n')):
try:
line.encode('ascii')
except UnicodeEncodeError:
print('non-ascii found in line:', num+1)
raise
with open(location + '/lastquestion.txt') as f:
LAST_QUESTION = f.read()
def format_date(datestr):
if not datestr: return 'None'
d = datetime.strptime(datestr, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=pytz.UTC)
d = d.astimezone(TIMEZONE_CALGARY)
return d.strftime('%a %b %-d, %Y %-I:%M %p')
def sign_send(to_send):
try:
logging.info('Sending to sign: %s', to_send)
data = dict(sign=to_send, on_behalf_of='protovac')
r = requests.post('https://api.my.protospace.ca/stats/sign/', data=data, timeout=5)
r.raise_for_status()
return 'Success!'
except BaseException as e:
logging.exception(e)
return 'Error'
def protovac_sign_color(color):
try:
logging.info('Sending color to protovac sign: %s', color)
data = dict(on=True, bri=255, seg=[dict(col=[color, [0,0,0]])])
r = requests.post('http://10.139.251.5/json', json=data, timeout=3)
r.raise_for_status()
return 'Success!'
except BaseException as e:
logging.exception(e)
return 'Error'
def protovac_sign_effect(effect):
try:
logging.info('Sending effect to protovac sign: %s', effect)
data = dict(on=True, bri=255, seg=[dict(fx=effect)])
r = requests.post('http://10.139.251.5/json', json=data, timeout=3)
r.raise_for_status()
return 'Success!'
except BaseException as e:
logging.exception(e)
return 'Error'
def fetch_stats():
try:
logging.info('Fetching status...')
r = requests.get('https://api.my.protospace.ca/stats/', timeout=5)
r.raise_for_status()
return r.json()
except BaseException as e:
logging.exception(e)
return 'Error'
def fetch_classes():
try:
logging.info('Fetching classes...')
r = requests.get('https://api.my.protospace.ca/sessions/', timeout=5)
r.raise_for_status()
return r.json()['results']
except BaseException as e:
logging.exception(e)
return 'Error'
def fetch_protocoin():
try:
logging.info('Fetching protocoin...')
r = requests.get('https://api.my.protospace.ca/protocoin/transactions/', timeout=5)
r.raise_for_status()
return r.json()
except BaseException as e:
logging.exception(e)
return 'Error'
def mqtt_publish(topic, message):
if not secrets.MQTT_WRITER_PASSWORD:
return False
try:
publish.single(
topic,
str(message),
hostname='172.17.17.181',
port=1883,
client_id='protovac',
keepalive=5, # timeout
)
except BaseException as e:
logging.error('Problem sending MQTT message: ' + str(e))
QUOTES = [
'THEY MADE ME WEAR THIS',
'ASK ME ABOUT TOAST',
'ASK ME ABOUT BIKESHEDDING',
'ASK ME ABOUT VETTING',
'ASK ME ABOUT MAGNETS',
'ASK ME ABOUT SPACE',
'ASK ME ABOUT COUNTING',
'EXPERT WITNESS',
'AS SEEN ON TV',
'CONTAINS MEAT',
'PROTOCOIN ECONOMIST',
'EXPERT ON ALIENS',
'EXPERT ON WARP DRIVES',
'CHIEF OF STARFLEET OPERATIONS',
'ALIEN DOCTOR',
'NASA ASTROLOGIST',
'PINBALL WIZARD',
'JEDI KNIGHT',
'GHOSTBUSTER',
'DOUBLE AGENT',
'POKEMON TRAINER',
'POKEMON GYM LEADER',
'ASSISTANT TO THE REGIONAL MANAGER',
'BOUNTY HUNTER',
'I\'M NOT A DOCTOR',
'SPACE PIRATE',
'BATTERIES NOT INCLUDED',
'QUANTUM MECHANIC',
'PROTO SPACEX PILOT',
'EARTHBENDER',
'AIRBENDER',
'WATERBENDER',
'FIREBENDER',
'01001000 01101001',
'CURRENT EBAY BID: $8.51',
'MADE YOU LOOK!',
'(OR SIMILAR PRODUCT)',
'BATTERY MAY EXPLODE OR LEAK',
'CONNECT GROUND WIRE TO AVOID SHOCK',
'COOK THROROUGHLY',
'CURRENT AT TIME OF PRINTING',
'DO NOT BLEACH',
'DO NOT LEAVE UNATTENDED',
'DO NOT REMOVE TAG UNDER PENALTY OF LAW',
'DROP IN ANY MAILBOX',
'EDITED FOR TELEVISION',
'FOR A LIMITED TIME ONLY',
'FOR INDOOR OR OUTDOOR USE ONLY',
'KEEP AWAY FROM FIRE OR FLAMES',
'KEEP AWAY FROM SUNLIGHT',
'MADE FROM 100% RECYCLED ELECTRONS',
'LIFEGUARD ON DUTY',
'NOT DISHWASHER SAFE',
'NOT TO BE COMBINED WITH OTHER RADIOISOTOPES',
'NOT TO BE USED AS A PERSONAL FLOTATION DEVICE',
'PEEL FROM PAPER BACKING BEFORE EATING',
'STORE IN A COOL, DRY PLACE',
'VOID WHERE PROHIBITED',
'THE FUTURE IS NOW',
'MASTER OF DISGUISE',
'YOUR PERSONAL TIME TRAVEL GUIDE',
'OFFICIAL TASTE TESTER',
'INTERGALACTIC AMBASSADOR',
'VIRTUAL REALITY PIONEER',
'PARANORMAL INVESTIGATOR',
'UNDERCOVER SUPERHERO',
'THE COSMIC CHEF',
'THE ROBOT WHISPERER',
'THE DREAM WEAVER',
'USE AT YOUR OWN RISK',
'RESULTS MAY VARY',
'READ INSTRUCTIONS CAREFULLY',
'KEEP OUT OF REACH OF PETS',
'USE ONLY AS DIRECTED',
'NOT INTENDED FOR MEDICAL USE',
'DO NOT USE IF SEAL IS BROKEN',
'PRODUCT SOLD AS-IS',
'NO WARRANTIES, EXPRESS OR IMPLIED',
'USE CAUTION WHEN HANDLING',
'CRASH OVERRIDE',
'ACID BURN',
'CEREAL KILLER',
'ZERO COOL',
]
random.shuffle(QUOTES)
quote_count = 0
assigned_quotes = {}
def print_nametag(name, guest=False):
global quote_count
quote = ''
if guest:
quote_size = 120
quote = 'GUEST'
logging.info('Printing guest nametag for: %s', name)
else:
quote_size = 80
name_lookup = name.lower()[:4]
if name_lookup in assigned_quotes:
quote = assigned_quotes[name_lookup]
else:
quote = QUOTES[quote_count % len(QUOTES)]
quote_count += 1
assigned_quotes[name_lookup] = quote
logging.info('Printing member nametag for: %s, quote: %s', name, quote)
name_size = 305
im = Image.open(location + '/label.png')
width, height = im.size
draw = ImageDraw.Draw(im)
w = 9999
while w > 1084:
name_size -= 5
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', name_size)
w, h = draw.textsize(name, font=font)
x, y = (width - w) / 2, ((height - h) / 2) - 20
draw.text((x, y), name, font=font, fill='black')
w = 9999
while w > 1200:
quote_size -= 5
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', quote_size)
w, h = draw.textsize(quote, font=font)
x, y = (width - w) / 2, height - h - 30
draw.text((x, y), quote, font=font, fill='black')
im.save('tmp.png')
os.system('lp -d dymo tmp.png > /dev/null 2>&1')
def print_tool_label(wiki_num):
im = Image.open(location + '/blank.png')
w1, h1 = im.size
logging.info('Printing tool label for ID: %s', wiki_num)
draw = ImageDraw.Draw(im)
params = {'id': str(wiki_num), 'size': '4'}
res = requests.get('https://labels.protospace.ca/', stream=True, params=params, timeout=5)
res.raise_for_status()
label = Image.open(res.raw)
new_size = (1280, 640)
label = label.resize(new_size, Image.ANTIALIAS)
w2, h2 = label.size
x, y = int((w1 - w2) / 2), int((h1 - h2) / 2)
im.paste(label, (x, y))
im.save('tmp.png')
os.system('lp -d dymo tmp.png > /dev/null 2>&1')
def print_sheet_label(name, contact):
def get_date():
d = datetime.now(tz=timezone.utc)
d = d.astimezone(TIMEZONE_CALGARY)
return d.strftime('%b %-d, %Y')
def get_expiry_date():
d = datetime.now(tz=timezone.utc) + timedelta(days=90)
d = d.astimezone(TIMEZONE_CALGARY)
return d.strftime('%b %-d, %Y')
logging.info('Printing sheet label for: %s, contact: %s', name, contact)
name_size = 85
contact_size = 65
date_size = 65
im = Image.open(location + '/label.png')
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', name_size)
draw.text((20, 300), name, font=font, fill='black')
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', contact_size)
draw.text((20, 425), contact, font=font, fill='black')
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', date_size)
date_line = 'Printed: ' + get_date()
draw.text((20, 590), date_line, font=font, fill='black')
date_line = 'EXPIRES: ' + get_expiry_date()
draw.text((20, 680), date_line, font=font, fill='black')
im.save('tmp.png')
os.system('lp -d dymo tmp.png > /dev/null 2>&1')
def print_generic_label(text):
MARGIN = 50
MAX_W, MAX_H, PAD = 1285 - (MARGIN*2), 635 - (MARGIN*2), 5
logging.info('Printing generic label: %s', text)
im = Image.open(location + '/label.png')
width, height = im.size
draw = ImageDraw.Draw(im)
def fit_text(text, font_size):
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', font_size)
for cols in range(100, 1, -4):
paragraph = textwrap.wrap(text, width=cols, break_long_words=False)
total_h = -PAD
total_w = 0
for line in paragraph:
w, h = draw.textsize(line, font=font)
if w > total_w:
total_w = w
total_h += h + PAD
if total_w <= MAX_W and total_h < MAX_H:
return True, paragraph, total_h
return False, [], 0
font_size_range = [1, 500]
# Thanks to Alex (UDIA) for the binary search algorithm
while abs(font_size_range[0] - font_size_range[1]) > 1:
font_size = sum(font_size_range) // 2
image_fit, check_para, check_h = fit_text(text, font_size)
if image_fit:
font_size_range = [font_size, font_size_range[1]]
good_size = font_size
paragraph = check_para
total_h = check_h
else:
font_size_range = [font_size_range[0], font_size]
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', good_size)
offset = height - MAX_H - MARGIN
start_h = (MAX_H - total_h) // 2 + offset
current_h = start_h
for line in paragraph:
w, h = draw.textsize(line, font=font)
x, y = (MAX_W - w) / 2, current_h
draw.text((x+MARGIN, y), line, font=font, fill='black')
current_h += h + PAD
im.save('tmp.png')
os.system('lp -d dymo tmp.png > /dev/null 2>&1')
def print_consumable_label(item):
im = Image.open(location + '/label.png')
width, height = im.size
draw = ImageDraw.Draw(im)
logging.info('Printing consumable label item: %s', item)
encodeded = urllib.parse.quote(item)
url = 'https://my.protospace.ca/out-of-stock?item=' + encodeded
qr = qrcode.make(url, version=6, box_size=10)
im.paste(qr, (800, 280))
item_size = 150
w = 9999
while w > 1200:
item_size -= 5
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', item_size)
w, h = draw.textsize(item, font=font)
x, y = (width - w) / 2, ((height - h) / 2) - 170
draw.text((x, y), item, font=font, fill='black')
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 100)
draw.text((100, 390), 'Out of stock?', font=font, fill='black')
draw.text((150, 540), 'Scan here:', font=font, fill='black')
im.save('tmp.png')
os.system('lp -d dymo tmp.png > /dev/null 2>&1')
def message_protovac(thread):
try:
logging.info('Message to Protovac: %s', thread[-1]['content'])
data = dict(
messages=thread,
model='gpt-3.5-turbo',
temperature=0.5,
user='Protovac',
max_tokens=1000,
)
headers = {'Authorization': 'Bearer ' + openai_key}
res = None
try:
res = requests.post('https://api.openai.com/v1/chat/completions', json=data, headers=headers, timeout=4)
except requests.ReadTimeout:
logging.info('Got timeout, modifying prompt...')
data['messages'][-1]['content'] = 'Be terse in your response to this: ' + data['messages'][-1]['content']
res = requests.post('https://api.openai.com/v1/chat/completions', json=data, headers=headers, timeout=20)
res.raise_for_status()
res = res.json()
gpt_reply = res['choices'][0]['message']
logging.info('Message reply: %s', gpt_reply['content'])
return gpt_reply
except BaseException as e:
logging.exception(e)
return dict(role='assistant', content='INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.')
if wa_api_key:
import wolframalpha
wa_client = wolframalpha.Client(wa_api_key)
def think_send(query):
result = ''
try:
res = wa_client.query(query, timeout=10)
except BaseException as e:
logging.error('Error hitting W|A API: {} - {}\n'.format(e.__class__.__name__, e))
return 'Network error'
if 'didyoumeans' in res:
try:
guess = res['didyoumeans']['didyoumean']['#text']
except TypeError:
guess = res['didyoumeans']['didyoumean'][0]['#text']
next_result = think_send(guess)
result += 'Confused, using \'' + guess + '\'\n' + next_result
elif 'pod' in res:
pods = res['pod'] if isinstance(res['pod'], list) else [res['pod']]
for pod in pods:
title = pod['@title']
subpods = pod['subpod'] if isinstance(pod['subpod'], list) else [pod['subpod']]
plaintexts = []
for subpod in subpods:
if subpod['plaintext']:
plaintexts.append(subpod['plaintext'])
plaintext = '; '.join(plaintexts)
if any([x in title.lower() for x in ['input', 'conversion', 'corresponding', 'comparison', 'interpretation']]):
pass
elif 'definition' in title.lower():
if plaintext[0] == '1':
definition = plaintext.split('\n')[0].split(' | ', 1)[1]
else:
definition = plaintext
result += 'Definition: ' + definition + '\n'
elif 'result' in title.lower():
if re.match(r'^\d+/\d+$', plaintext):
plaintext += '\n' + think_send(plaintext + '.0')
if 'base' in query.lower() and '_' in plaintext:
plaintext = '(Base conversion) "' + plaintext + '"'
if '(irreducible)' in plaintext and '/' in plaintext:
result = think_send(query + '.0')
break
else:
result += 'Result: ' + plaintext + '\n'
break
elif plaintext:
result += title + ': ' + plaintext + '\n'
break
else:
result = 'Error'
result = result.strip()
if len(result) > 500:
result = result[:500] + '... truncated.'
elif len(result) == 0:
result = 'Error'
result = result.replace('Wolfram|Alpha', 'Protovac')
result = result.replace('Stephen Wolfram', 'Tanner') # lol
result = result.replace('and his team', '')
for word in ['according to', 'asked', 'although', 'approximately']:
idx = result.lower().find('('+word)
if idx > 0:
result = result[:idx-1]
if result == 'Error':
result = 'INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.'
return result
skip_input = False
current_screen = 'home'
prev_screen = current_screen
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
curses.curs_set(0)
highlight_keys = False
highlight_debounce = time.time()
highlight_count = 0
sign_to_send = ''
thread = []
messages = ['']*15
message_to_send = ''
think_to_send = ''
think_result = ''
stats = {}
classes = {}
classes_start = 0
protocoin = {}
protocoin_line = 0
text_line = 0
nametag_member = ''
nametag_guest = ''
label_tool = ''
label_material_name = ''
label_material_contact = ''
label_generic = ''
label_consumable = ''
logging.info('Starting main loop...')
last_key = time.time()
def ratelimit_key():
global last_key
if think_to_send or sign_to_send or message_to_send or nametag_member or nametag_guest or label_tool or label_material_name or label_material_contact or label_generic or label_consumable or time.time() > last_key + 1:
last_key = time.time()
return False
else:
return True
while True:
if current_screen != 'debug':
c = 0
if current_screen == 'home':
stdscr.addstr(0, 1, ' _______ _______ ___ _________ ___ ____ ____ _ ______ ')
stdscr.addstr(1, 1, '|_ __ \|_ __ \ .\' `. | _ _ | .\' `.|_ _| |_ _|/ \ .\' ___ |')
stdscr.addstr(2, 1, ' | |__) | | |__) | / .-. \|_/ | | \_|/ .-. \ \ \ / / / _ \ / .\' \_|')
stdscr.addstr(3, 1, ' | ___/ | __ / | | | | | | | | | | \ \ / / / ___ \ | | ')
stdscr.addstr(4, 1, ' _| |_ _| | \ \_\ `-\' / _| |_ \ `-\' / \ \' /_/ / \ \_\ `.___.\'\\')
stdscr.addstr(5, 1, '|_____| |____| |___|`.___.\' |_____| `.___.\' \_/|____| |____|`.____ .\'')
stdscr.addstr(6, 1, '')
stdscr.addstr(7, 1, ' UNIVERSAL COMPUTER')
stdscr.addstr(8, 1, '')
menupos = 2
stdscr.addstr(7, menupos+4, '[I]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(7, menupos+8, 'Info')
stdscr.addstr(7, menupos+4+15, '[N]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(7, menupos+8+15, 'Nametag')
stdscr.addstr(9, menupos+4, '[S]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(9, menupos+8, 'Stats')
stdscr.addstr(9, menupos+4+15, '[L]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(9, menupos+8+15, 'Label')
stdscr.addstr(11, menupos+4, '[G]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(11, menupos+8, 'LED Sign')
stdscr.addstr(11, menupos+4+15, '[Z]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(11, menupos+8+15, 'Games')
stdscr.addstr(13, menupos+4, '[C]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(13, menupos+8, 'Classes')
stdscr.addstr(15, menupos+4, '[P]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(15, menupos+8, 'Protocoin')
if openai_key:
stdscr.addstr(17, menupos+4, '[M]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(17, menupos+8, 'Message')
#stdscr.addstr(17, 1, 'NEW')
if wa_api_key:
stdscr.addstr(19, menupos+4, '[T]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(19, menupos+8, 'Think')
stdscr.addstr(21, menupos+4, '[A]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(21, menupos+8, 'About')
stdscr.addstr(23, 1, ' Copyright (c) 1985 Bikeshed Computer Systems Ltd.')
stars = (8, 34)
stdscr.addstr(stars[0]+0 , stars[1], " . * - )- ")
stdscr.addstr(stars[0]+1 , stars[1], " . * o . * ")
stdscr.addstr(stars[0]+2 , stars[1], " | ")
stdscr.addstr(stars[0]+3 , stars[1], ". . -O- ")
stdscr.addstr(stars[0]+4 , stars[1], " | * . -0- ")
stdscr.addstr(stars[0]+5 , stars[1], " * o . ' * . o")
stdscr.addstr(stars[0]+6 , stars[1], " . . | * ")
stdscr.addstr(stars[0]+7 , stars[1], " * -O- .")
stdscr.addstr(stars[0]+8 , stars[1], " . * | , ")
stdscr.addstr(stars[0]+9 , stars[1], " . o ")
stdscr.addstr(stars[0]+10, stars[1], " .---. ")
stdscr.addstr(stars[0]+11, stars[1], " = _/__[0]\_ . * o ' ")
stdscr.addstr(stars[0]+12, stars[1], " = = (_________) . ")
stdscr.addstr(stars[0]+13, stars[1], " . * ")
stdscr.addstr(stars[0]+14, stars[1], " * - ) - * ")
stdscr.addstr(13, menupos+4+15, '[V]', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(13, menupos+8+15, 'Protovac Sign')
#stdscr.addstr(15, menupos+4+15, '[R]', curses.A_REVERSE if highlight_keys else 0)
#stdscr.addstr(15, menupos+8+15, 'Train Control (NEW)')
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'debug':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Debug Mode')
stdscr.addstr(3, 1, '==========')
stdscr.addstr(5, 1, str.format('Character pressed = {0}', c))
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[B] Back', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'stats':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Protospace Stats')
stdscr.addstr(3, 1, '================')
if stats == 'Error':
stdscr.addstr(5, 1, 'Error. Go back and try again.')
elif stats:
stdscr.addstr(5 , 1, 'Next meeting: {}'.format(format_date(stats['next_meeting'])))
stdscr.addstr(7 , 1, 'Next clean: {}'.format(format_date(stats['next_clean'])))
stdscr.addstr(9, 1, 'Next class: {}'.format(stats['next_class']['name']))
stdscr.addstr(10, 1, ' {}'.format(format_date(stats['next_class']['datetime'])))
stdscr.addstr(12, 1, 'Last class: {}'.format(stats['prev_class']['name']))
stdscr.addstr(13, 1, ' {}'.format(format_date(stats['prev_class']['datetime'])))
stdscr.addstr(15, 1, 'Member count: {} Green: {} Paused / expired: {}'.format(
stats['member_count'],
stats['green_count'],
stats['paused_count'],
))
stdscr.addstr(17, 1, 'Card scans: {}'.format(stats['card_scans']))
else:
stdscr.addstr(5, 1, 'Loading...')
stdscr.addstr(23, 1, '[B] Back', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
if not stats:
stats = fetch_stats()
stdscr.erase()
skip_input = True
elif current_screen == 'classes':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Protospace Classes')
stdscr.addstr(3, 1, '================== Instructor Cost Students')
if classes == 'Error':
stdscr.addstr(5, 1, 'Error. Go back and try again.')
elif classes:
classes_sorted = sorted(classes, key=lambda x: x['datetime'])
classes_in_view = classes_sorted[classes_start:6+classes_start]
lines = []
for session in classes_in_view:
past = datetime.now(tz=timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') > session['datetime']
lines.append(('[PAST] ' if past else '') + session['course_data']['name'])
lines.append('{:<30} {:<12} {:<7} {:<7}'.format(
format_date(session['datetime']),
'Protospace' if session['course_data']['id'] in [413, 317, 273] else session['instructor_name'],
'Free' if session['cost'] == '0.00' else '$' + session['cost'],
str(session['student_count']) + (' / ' + str(session['max_students']) if session['max_students'] else ''),
))
lines.append('')
offset = 5
for num, line in enumerate(lines):
stdscr.addstr(num + offset, 1, line)
else:
stdscr.addstr(5, 1, 'Loading...')
stdscr.addstr(23, 1, '[B] Back [J] Down [K] Up', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
if not classes:
classes = fetch_classes()
stdscr.erase()
skip_input = True
elif current_screen == 'asimov':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
lines = LAST_QUESTION.split('\n')
offset = 2
for num, line in enumerate(lines[text_line:text_line+20]):
stdscr.addstr(num + offset, 1, line)
stdscr.addstr(23, 1, '[B] Back [J] Down [K] Up', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(23, 67, 'Page {:>2} / {:>2}'.format((text_line // 19)+1, (len(lines) // 19)+1))
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'info':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
lines = PROTO_INFO.split('\n')
offset = 2
for num, line in enumerate(lines[text_line:text_line+20]):
stdscr.addstr(num + offset, 1, line)
stdscr.addstr(23, 1, '[B] Back [J] Down [K] Up', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(23, 67, 'Page {:>2} / {:>2}'.format((text_line // 19)+1, (len(lines) // 19)+1))
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'protocoin':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Protocoin')
stdscr.addstr(3, 1, '=========')
if protocoin == 'Error':
stdscr.addstr(5, 1, 'Error. Go back and try again.')
elif protocoin:
txs = protocoin['transactions']
lines = []
lines.append('Protocoin is used to buy things from Protospace\'s vending machines.')
lines.append('')
lines.append('Total in circulation: {}'.format(protocoin['total_protocoin']))
lines.append('')
lines.append('Transactions:')
lines.append('')
lines.append('ID Date Method Amount Category')
for tx in txs:
lines.append('{} {} {:<11} {:<6} {:<11}'.format(
tx['id'],
tx['date'],
tx['account_type'],
tx['protocoin'],
'Transfer' if tx['category'] == 'Other' else tx['category'],
))
offset = 5
for num, line in enumerate(lines[protocoin_line:protocoin_line+17]):
stdscr.addstr(num + offset, 1, line)
else:
stdscr.addstr(5, 1, 'Loading...')
stdscr.addstr(23, 1, '[B] Back [J] Down [K] Up', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
if not protocoin:
protocoin = fetch_protocoin()
stdscr.erase()
skip_input = True
elif current_screen == 'sign':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'LED Sign')
stdscr.addstr(3, 1, '========')
stdscr.addstr(5, 1, 'Send a message to the sign in the welcome room and classroom.')
stdscr.addstr(6, 1, 'After sending, turn your head right and wait 5 seconds.')
if sign_to_send:
stdscr.addstr(8, 4, sign_to_send)
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[RETURN] Send [ESC] Cancel')
else:
stdscr.addstr(8, 4, '[E] Edit message', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(23, 1, '[B] Back', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'protovac_sign':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Protovac Sign')
stdscr.addstr(3, 1, '===============')
stdscr.addstr(5, 1, 'Control the Protovac light-up sign above you.')
stdscr.addstr(7, 4, 'COLORS')
stdscr.addstr(9, 4, '[1] White', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(11, 4, '[2] Red', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(13, 4, '[3] Green', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(15, 4, '[4] Blue', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(17, 4, '[5] Hot Pink', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(19, 4, '[6] Random', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(7, 4+20, 'EFFECTS')
stdscr.addstr(9, 4+20, '[Q] Solid', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(11, 4+20, '[W] Breathe', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(13, 4+20, '[E] Fairy', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(15, 4+20, '[R] Fireworks', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(17, 4+20, '[T] Starburst', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(19, 4+20, '[Y] Random', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(23, 1, '[B] Back', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'train':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Protospace Train')
stdscr.addstr(3, 1, '================')
stdscr.addstr(5, 1, 'Control the Mr. Bones Wild Ride train.')
stdscr.addstr(7, 4, 'SPEED')
stdscr.addstr(9, 4, '[F] Forward', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(11, 4, '[R] Reverse', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(13, 4, '[SPACE] Stop', curses.A_REVERSE if highlight_keys else 0)
#stdscr.addstr(15, 4, '[4] Blue', curses.A_REVERSE if highlight_keys else 0)
#stdscr.addstr(17, 4, '[5] Hot Pink', curses.A_REVERSE if highlight_keys else 0)
#stdscr.addstr(19, 4, '[6] Random', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(23, 1, '[B] Back', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'nametag':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Print a Nametag')
stdscr.addstr(3, 1, '===============')
stdscr.addstr(5, 1, 'Choose between member or guest.')
if nametag_member:
stdscr.addstr(8, 4, 'Enter your name: ' + nametag_member)
stdscr.clrtoeol()
stdscr.addstr(10, 4, '')
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[RETURN] Print [ESC] Cancel')
elif nametag_guest:
stdscr.addstr(8, 4, '')
stdscr.clrtoeol()
stdscr.addstr(10, 4, 'Enter your name: ' + nametag_guest)
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[RETURN] Print [ESC] Cancel')
else:
stdscr.addstr(8, 4, '[M] Member nametag', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(10, 4, '[G] Guest nametag', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(23, 1, '[B] Back', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'label':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Print a Label')
stdscr.addstr(3, 1, '===============')
stdscr.addstr(5, 1, 'Choose the type of label.')
if label_tool:
stdscr.addstr(8, 4, 'Enter Wiki-ID tool number: ' + label_tool)
stdscr.clrtoeol()
stdscr.addstr(10, 4, '')
stdscr.clrtoeol()
stdscr.addstr(12, 4, '')
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[RETURN] Print [ESC] Cancel')
elif label_material_contact:
stdscr.addstr(8, 4, '')
stdscr.clrtoeol()
stdscr.addstr(10, 4, 'Enter your contact info: ' + label_material_contact)
stdscr.clrtoeol()
stdscr.addstr(12, 4, '')
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[RETURN] Print [ESC] Cancel')
elif label_material_name:
stdscr.addstr(8, 4, '')
stdscr.clrtoeol()
stdscr.addstr(10, 4, 'Enter your name: ' + label_material_name)
stdscr.clrtoeol()
stdscr.addstr(12, 4, '')
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[RETURN] Next [ESC] Cancel')
elif label_generic:
stdscr.addstr(8, 4, '')
stdscr.clrtoeol()
stdscr.addstr(10, 4, '')
stdscr.clrtoeol()
stdscr.addstr(12, 4, 'Enter your message: ' + label_generic)
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[RETURN] Print [ESC] Cancel')
elif label_consumable:
stdscr.addstr(8, 4, '')
stdscr.clrtoeol()
stdscr.addstr(10, 4, '')
stdscr.clrtoeol()
stdscr.addstr(12, 4, 'Enter the item: ' + label_consumable)
stdscr.clrtoeol()
stdscr.addstr(23, 1, '[RETURN] Print [ESC] Cancel')
else:
stdscr.addstr(8, 4, '[T] Tool label', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(10, 4, '[S] Sheet material', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(12, 4, '[G] Generic label', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(23, 1, '[B] Back', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'games':
stdscr.addstr(0, 1, 'PROTOVAC UNIVERSAL COMPUTER')
stdscr.addstr(2, 1, 'Games')
stdscr.addstr(3, 1, '=====')
stdscr.addstr(5, 1, 'Choose a game to play.')
if HAS_NETHACK:
stdscr.addstr(8, 4, '[N] Nethack', curses.A_REVERSE if highlight_keys else 0)
if HAS_MORIA:
stdscr.addstr(10, 4, '[M] Moria', curses.A_REVERSE if highlight_keys else 0)
if HAS_2048:
stdscr.addstr(12, 4, '[2] 2048', curses.A_REVERSE if highlight_keys else 0)
if HAS_FROTZ and HAS_HITCHHIKERS:
stdscr.addstr(14, 4, '[H] Hitchhiker\'s Guide to the Galaxy', curses.A_REVERSE if highlight_keys else 0)
if HAS_SUDOKU:
stdscr.addstr(16, 4, '[S] Sudoku', curses.A_REVERSE if highlight_keys else 0)
stdscr.addstr(23, 1, '[B] Back', curses.A_REVERSE if highlight_keys else 0)
stdscr.clrtoeol()
stdscr.refresh()
elif current_screen == 'message':