-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstormshell.py
More file actions
2094 lines (1809 loc) · 87 KB
/
Copy pathstormshell.py
File metadata and controls
2094 lines (1809 loc) · 87 KB
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
#!/usr/bin/env python3
"""
StormShell — animated StormShell for the terminal
──────────────────────────────────────────────────────────────
Single unified character set — works identically on:
* SSH / any terminal emulator
* HDMI kiosk via /dev/tty1 (load Uni Terminus font via setfont in service)
Characters used:
Box drawing - | + (ASCII) and box-draw: - | + for borders
Block elems : (ASCII compatible) . , | / \\ * ~ = #
CP437 sun : (fallback: *) -- see FONT NOTE below
Pure ASCII : everything else
FONT NOTE: The ☼ character (U+263C) is present in every Uni-family console
font (Terminus, LatArCyrHeb, etc.). The install script loads
Uni2-TerminusBold28x14 before the display starts on the TTY. On SSH the
terminal emulator handles it. If ☼ renders as '?' on your setup, flip
the SUN_CHAR constant below to '*'.
Data: Open-Meteo (no key) https://open-meteo.com
Coords: Nominatim/OSM (no key) https://nominatim.openstreetmap.org
Usage:
python3 stormshell.py --zip 60201
python3 stormshell.py --zip SW1A --country gb --units celsius --wind kmh
"""
import curses
import time
import json
import sys
import os
import signal
import atexit
import subprocess
import argparse
import urllib.request
import urllib.parse
from datetime import datetime, timedelta, timezone
# ─── Config ───────────────────────────────────────────────────────────────────
DEFAULT_LOCATION = "" # set by installer
DEFAULT_COUNTRY = "" # empty = let Nominatim search globally
REFRESH_SECONDS = 300
ANIMATE_FPS = 3
TEMP_UNIT = "fahrenheit" # fahrenheit | celsius
WIND_UNIT = "mph" # mph | kmh | ms | kn
# If ☼ shows as '?' on your TTY, change this to '*'
SUN_CHAR = "☼"
# Countries that default to metric units when --units/--wind not specified.
# If the resolved country code is in this set, celsius + kmh are used.
METRIC_COUNTRIES = {
"gb", "au", "ca", "nz", "ie", "za", # anglophone metric
"de", "fr", "es", "it", "pt", "nl", # western Europe
"be", "ch", "at", "se", "no", "dk", # more Europe
"fi", "pl", "cz", "sk", "hu", "ro",
"jp", "cn", "kr", "in", "br", "mx", # major non-EU
"ar", "cl", "co", "pe", "ng", "ke",
"eg", "tr", "ru", "ua", "th", "vn",
"id", "ph", "pk", "bd", "sg", "my",
}
# ─── WMO code → condition string ──────────────────────────────────────────────
def wmo_to_condition(code):
if code == 0: return "sunny"
if code in (1, 2): return "partly_cloudy"
if code == 3: return "cloudy"
if code in (45, 48): return "fog"
if code in (51, 53, 55): return "drizzle"
if code in (61, 63): return "rain"
if code in (65,): return "heavy_rain"
if code in (80, 81): return "showers"
if code in (82,): return "heavy_rain"
if code in (71, 73, 85): return "snow"
if code in (75, 86): return "blizzard"
if code in (95, 96, 99): return "storm"
return "cloudy"
# 3-char forecast condition labels — pure ASCII, no emoji
CONDITION_LABEL = {
"sunny": "Clear Sky",
"partly_cloudy": "Partly Cloudy",
"cloudy": "Overcast",
"fog": "Foggy",
"drizzle": "Drizzle",
"rain": "Rainy",
"heavy_rain": "Heavy Rain",
"showers": "Showers",
"snow": "Snowy",
"blizzard": "Blizzard",
"storm": "Thunderstorm",
}
FC_ICON = {
"sunny": "SUN",
"partly_cloudy": "PCT",
"cloudy": "CLD",
"fog": "FOG",
"drizzle": "DRZ",
"rain": "RAN",
"heavy_rain": "HVY",
"showers": "SHW",
"snow": "SNW",
"blizzard": "BLZ",
"storm": "STM",
}
# ─── ASCII Art ────────────────────────────────────────────────────────────────
#
# Full palette (works on SSH terminal and /dev/tty1 with Uni Terminus font):
#
# ☼ CP437 WHITE SMILING FACE (U+263C) — sun symbol
# \ / | ( ) pure ASCII geometry
# . , ' ` ~ punctuation as texture
# * # fill / snow / stars
# ░ ▒ ▓ block elements — fog, bars
# - + = horizontal lines
#
# No emoji. No multi-codepoint sequences. No >8 colour pairs.
#
# Each condition: list of animation frames.
# Each frame: list of exactly ART_H strings, each ART_W chars wide.
ART_W = 62 # matches right panel width at 97-col display (div_x=32, right_x=34, right_w=62)
ART_H = 40 # tall canvas — clipped to actual anim_h at draw time
def _p(s):
"""Clip to ART_W and left-pad so every line is the same width."""
return s[:ART_W].ljust(ART_W)
# ── SUNNY ─────────────────────────────────────────────────────────────────────
# User's hand-drawn sun, centered, 2-frame twinkle on the rays.
def _sunny():
# 9 rows tall — if canvas too short, top rows get cropped automatically
SUN = [
" ; : ; ",
" . \\_,!,_/ , ",
" `.,' `.,' ",
" / \\ ",
" -- : -0--0- : -- ",
" \\ .__, / ",
" ,'`._ _.'`. ",
" ' / `!` \\ ` ",
" ; : ; ",
]
SUN2 = [
" ",
" \\_,!,_/ ",
" `.,' `.,` ",
" / \\ ",
" -: -0--0 - :- ",
" \\ .__, / ",
" ,'`._ _,``. ",
" / `!` \\ ",
" ",
]
def _frame(art):
rows = []
for line in art:
rows.append(_p(line.center(ART_W)))
# Trim to ART_H - 1 rows, place at top (row 1 to leave space for border)
rows = rows[:ART_H - 1]
# Pad bottom if art shorter than canvas
while len(rows) < ART_H - 1:
rows.append(_p(""))
rows.append(_p(" CLEAR SKY "))
return rows
f1 = _frame(SUN)
f2 = _frame(SUN2)
# Repeat each frame 4x → flicker every ~1.3s at 3fps
return [f1, f1, f1, f1, f2, f2, f2, f2]
# ── PARTLY CLOUDY ─────────────────────────────────────────────────────────────
# User's sun with two clouds scrolling over it — drawn live in draw_frame
# so each cloud loops independently with no disappearing.
def _partly_cloudy():
import random
rng = random.Random(42)
SUN = [
" ; : ; ",
" . \\_,!,_/ , ",
" `.,' `.,' ",
" / \\ ",
" -- : -0--0- : -- ",
" \\ .__, / ",
" ,'`._ _.'`. ",
" ' / `!` \\ ` ",
" ; : ; ",
]
SUN2 = [
" ",
" \\_,!,_/ ",
" `.,' `.,` ",
" / \\ ",
" -: -0--0 - :- ",
" \\ .__, / ",
" ,'`._ _,``. ",
" / `!` \\ ",
" ",
]
# Pre-render sun frames (flicker) — clouds drawn live in draw_frame
frames = []
for f in range(8):
sun_art = SUN if (f // 4) % 2 == 0 else SUN2
grid = [[' '] * ART_W for _ in range(ART_H)]
for r, line in enumerate(sun_art):
if r >= ART_H - 1: break
for c, ch in enumerate(line):
if 0 <= c < ART_W:
grid[r][c] = ch
frame = [_p(''.join(row)) for row in grid]
frame[ART_H - 1] = _p(" PARTLY CLOUDY ")
frames.append(frame)
return frames
# ── CLOUDY ────────────────────────────────────────────────────────────────────
# Multiple hand-drawn clouds scroll left to right simultaneously.
# Staggered start positions give layered depth effect.
# All 5 user cloud shapes
_CLOUD_SHAPES = [
[
" .....",
" ... ( )",
" ( )-( )",
" .-.' )",
" ( )",
" `-------------------'",
],
[
" ..... ___",
" ... ( ) ( ).",
" ( )-( )-( )",
" .-.' ).-. ",
" ( )",
" `-----------------------------'",
],
[
" ........ ___",
" ...( ) ( ).",
" ( )-( )",
" .-.' ).-. ",
" ( )",
" `-----------------------------'",
],
[
" ...",
" ...( )..",
" ( )...",
" .-.' ).",
" ( )",
" `-------------------'",
],
[
" ... .....",
" ...( ).. ..( )",
" ( )... ...( '...--. ",
" .-.' )--( ).-.",
" ( )",
" `---------------------------------------------",
],
]
def _render_clouds(cloud_list, x_offset, label):
"""Render multiple clouds onto one frame at given x scroll offset.
cloud_list: list of (shape_idx, x_start, y_start) tuples."""
grid = [[' '] * ART_W for _ in range(ART_H)]
for shape_idx, base_x, y_start in cloud_list:
lines = _CLOUD_SHAPES[shape_idx]
cloud_w = max(len(l.rstrip()) for l in lines)
# current x = base_x + scroll offset, wraps around
total = ART_W + cloud_w
x = ((base_x + x_offset) % total) - cloud_w
for row_i, line in enumerate(lines):
r = y_start + row_i
if r < 0 or r >= ART_H - 1:
continue
for col_i, ch in enumerate(line.rstrip()):
col = x + col_i
if 0 <= col < ART_W and ch != ' ':
grid[r][col] = ch
frame = [_p(''.join(row)) for row in grid]
frame[ART_H - 1] = _p(label)
return frame
def _cloudy():
import random
rng = random.Random(7)
# (shape_idx, x_phase, y_row, speed)
# y can be negative or past bottom for natural cropping
clouds = [
(1, 0, rng.randint(-2, 1), 1),
(3, 28, rng.randint(0, 5), 4),
(0, 52, rng.randint(-1, 3), 1),
(4, 12, rng.randint(2, 6), 5),
(2, 72, rng.randint(-2, 2), 2),
]
total = ART_W + 67 # +7 to clear right edge fully
frames = []
for f in range(total):
grid = [[' '] * ART_W for _ in range(ART_H)]
for shape_idx, base_x, y_start, speed in clouds:
lines = _CLOUD_SHAPES[shape_idx]
cw = max(len(l.rstrip()) for l in lines)
ch = len(lines)
tw = ART_W + cw + 7
x = ((base_x + f // speed) % tw) - cw
# Erase interior span, draw only actual chars
for row_i, line in enumerate(lines):
r = y_start + row_i
if r < 0 or r >= ART_H - 1: continue
stripped = line.rstrip()
if not stripped: continue
left = next((i for i,c in enumerate(stripped) if c != ' '), None)
right = len(stripped)
if left is None: continue
for col_i in range(left, right):
col = x + col_i
if 0 <= col < ART_W:
grid[r][col] = ' '
for col_i, ch_c in enumerate(stripped):
if ch_c != ' ':
col = x + col_i
if 0 <= col < ART_W:
grid[r][col] = ch_c
frame = [_p(''.join(row)) for row in grid]
frame[ART_H - 1] = _p(" OVERCAST ")
frames.append(frame)
return frames
# ── COMPUTED DROP GENERATOR ───────────────────────────────────────────────────
# Produces falling drop animations mathematically — no hand-drawing needed.
#
# Parameters:
# W, H canvas size (chars wide, lines tall)
# drops list of (col, speed, offset) tuples — one per drop column
# chars (head, body, tail, fade) — characters for the drop trail
# dx horizontal drift per frame (0=straight, 1=angled)
# n_frames how many frames to generate
# cloud optional list of lines to prepend above the drops
# label text label for bottom row
def _make_drops(W, H, drops, chars, dx, n_frames, cloud=None, label=""):
"""Generate n_frames of falling drop animation."""
head_ch, body_ch, tail_ch, fade_ch = chars
cloud_h = len(cloud) if cloud else 0
drop_h = H - cloud_h - 1 # rows for drops (full height minus label row)
frames = []
for f in range(n_frames):
grid = [[" "] * W for _ in range(drop_h)]
for col, speed, offset in drops:
fall = (f // speed + offset) % drop_h
for trail_row in range(4):
row = fall - trail_row
if row < 0 or row >= drop_h:
continue
c = (col + f * dx) % W
if trail_row == 0: ch = head_ch
elif trail_row == 1: ch = body_ch
elif trail_row == 2: ch = tail_ch
else: ch = fade_ch
grid[row][c] = ch
frame_lines = []
if cloud:
frame_lines += cloud
for row in grid:
frame_lines.append(_p("".join(row)))
frame_lines.append(_p(label.center(W)))
frames.append(frame_lines[:H])
return frames
# ── CLOUD SHAPES ──────────────────────────────────────────────────────────────
# Cloud transcribed from user's hand-drawn REXPaint art.
# 55 chars wide. Light cloud = full shape. Heavy cloud = denser base.
def _cloud_light():
return [
_p(" oo oo "),
_p(" ooo ooooooo oo oo "),
_p(" o ooo ooo oo oo oo ooooo ooo "),
_p(" oo oo ooo oo oooo oooooo o "),
_p("o ooo oo o oooo o oo "),
_p("oo oo ooo oo ooo "),
_p("o ooo oo ooo "),
_p("ooooooooooooooooooooooooooooooooooooooooooooooooooooooo"),
]
def _cloud_heavy():
return [
_p(" oo oo "),
_p(" ooo ooooooo oo oo "),
_p(" o ooo ooo oo oo oo ooooo ooo "),
_p(" oo oo ooo oo oooo oooooo o "),
_p("o ooo oo o oooo o oo "),
_p("oo oo ooo oo ooo "),
_p("oooooooooooooooooooooooooooooooooooooooooooooooooooooo"),
_p("oooooooooooooooooooooooooooooooooooooooooooooooooooooo"),
]
def _make_precip(density, speed, chars, n_frames, label, seed):
"""Density-based precipitation — each cell independently triggered.
density: 0.0-1.0 chance of a drop head on any given cell per frame
speed: rows dropped per frame (higher = faster)
chars: (head, body, tail)
"""
import random
rng = random.Random(seed)
H = ART_H - 1
W = ART_W
# Pre-generate drop map — each column gets its own speed offset
drop_cols = []
for c in range(W):
col_speed_offset = rng.randint(-1, 2) # whole column shifts slightly
col_drops = []
n = max(1, int(density * H / 4))
for i in range(n):
start = rng.randint(0, H - 1)
spd = max(1, speed + col_speed_offset + rng.randint(0, 1))
col_drops.append((start, spd))
drop_cols.append(col_drops)
frames = []
for f in range(n_frames):
grid = [[' '] * W for _ in range(H)]
head_ch, body_ch, tail_ch = chars
for c, col_drops in enumerate(drop_cols):
for start, spd in col_drops:
# Current head position
pos = (start + f * spd) % H
# Draw trail upward
for trail in range(4):
r = pos - trail
if r < 0: r += H
if r >= H: continue
if trail == 0: grid[r][c] = head_ch
elif trail == 1: grid[r][c] = body_ch
elif trail == 2: grid[r][c] = tail_ch
frame = [_p(''.join(row)) for row in grid]
frame.append(_p(label.center(W)))
frames.append(frame[:ART_H])
return frames
# ── DRIZZLE ───────────────────────────────────────────────────────────────────
def _drizzle():
return _make_precip(density=0.3, speed=1, chars=(',', '.', ' '),
n_frames=12, label="DRIZZLE", seed=11)
# ── RAIN / SHOWERS ────────────────────────────────────────────────────────────
def _rain():
return _make_precip(density=0.6, speed=2, chars=('|', '+', '.'),
n_frames=10, label="RAIN", seed=22)
def _showers():
return _rain()
# ── HEAVY RAIN ────────────────────────────────────────────────────────────────
def _heavy_rain():
return _make_precip(density=0.9, speed=3, chars=('|', '|', '+'),
n_frames=10, label="HEAVY RAIN", seed=33)
# ── SNOW ──────────────────────────────────────────────────────────────────────
def _snow():
return _make_precip(density=0.4, speed=1, chars=('*', '.', ' '),
n_frames=14, label="SNOW", seed=44)
# ── BLIZZARD ──────────────────────────────────────────────────────────────────
def _blizzard():
return _make_precip(density=1.0, speed=3, chars=('*', '*', '.'),
n_frames=10, label="BLIZZARD", seed=55)
# ── STORM ─────────────────────────────────────────────────────────────────────
def _storm():
import random
rng = random.Random(66)
H = ART_H - 1
W = ART_W
n_frames = 12
# Rain drop columns (blue)
drop_cols = []
for c in range(W):
n = max(1, int(0.8 * H / 4))
col_drops = []
for i in range(n):
col_drops.append((rng.randint(0, H-1), max(1, 3 + rng.randint(-1,1))))
drop_cols.append(col_drops)
# Lightning bolts evenly spaced across frames so at least one is always visible
bolts = [
(rng.randint(2, W-4), 0),
(rng.randint(2, W-4), 3),
(rng.randint(2, W-4), 7),
(rng.randint(2, W-4), 10),
]
LIGHTNING = ['<', '>', '<', '/']
BOLT_LEN = len(LIGHTNING)
frames = []
for f in range(n_frames):
grid = [[' '] * W for _ in range(H)]
for c, col_drops in enumerate(drop_cols):
for start, spd in col_drops:
pos = (start + f * spd) % H
for trail in range(4):
r = pos - trail
if r < 0: r += H
if r >= H: continue
if trail == 0: grid[r][c] = '|'
elif trail == 1: grid[r][c] = '+'
elif trail == 2: grid[r][c] = '.'
frame = [_p(''.join(row)) for row in grid]
frame.append(_p("THUNDERSTORM".center(W)))
frame = frame[:ART_H]
# Overlay lightning bolts — fall through full height each cycle
for bolt_col, bolt_start in bolts:
age = (f - bolt_start) % (H + BOLT_LEN)
for i, ch in enumerate(LIGHTNING):
r = age - BOLT_LEN + i
if 0 <= r < ART_H - 1:
line = list(frame[r])
if bolt_col < len(line):
line[bolt_col] = ch
frame[r] = ''.join(line)
frames.append(frame)
return frames
# ── FOG — full canvas drifting mist bands ────────────────────────────────────
def _fog():
frames = []
# Two interleaved band patterns that scroll horizontally
band_a = "░" * ART_W
band_b = "▒" * ART_W
band_c = " " * (ART_W // 4) + "░" * (ART_W // 2) + " " * (ART_W - ART_W // 4 - ART_W // 2)
band_d = "▒" * (ART_W // 3) + " " * (ART_W // 4) + "░" * (ART_W - ART_W // 3 - ART_W // 4)
# 8 frames — bands shift left 2 chars each frame
for f in range(8):
shift = f * 3
frame = []
bands = [band_a, band_b, band_c, band_d, band_a, band_b, band_c, band_d]
# Rotate each band differently for depth
for r in range(ART_H - 1):
band = bands[r % len(bands)]
s = (shift + r * 2) % ART_W
rotated = band[s:] + band[:s]
frame.append(_p(rotated))
frame.append(_p(" FOG "))
frames.append(frame)
return frames
# ─── Art table ────────────────────────────────────────────────────────────────
# ── NIGHT CLEAR — static stars, moon phase drawn live in draw_frame ───────────
def _night():
import random
rng = random.Random(99)
W, H = ART_W, ART_H - 1
grid = [[' '] * W for _ in range(H)]
for _ in range(80):
x, y = rng.randint(0, W-1), rng.randint(0, H-1)
grid[y][x] = '*'
frame = [_p(''.join(row)) for row in grid]
frame.append(_p(" CLEAR NIGHT "))
return [frame[:ART_H]]
# ── NIGHT PARTLY CLOUDY — static stars + scrolling cloud ──────────────────────
def _night_cloudy():
import random
rng = random.Random(88)
W, H = ART_W, ART_H - 1
# Stars only — moon and clouds are drawn live in draw_frame
# so the draw order (stars → moon → clouds) is guaranteed
grid = [[' '] * W for _ in range(H)]
for _ in range(80):
x, y = rng.randint(0, W-1), rng.randint(0, H-1)
grid[y][x] = '*'
frame = [_p(''.join(row)) for row in grid]
frame.append(_p(" PARTLY CLOUDY NIGHT "))
return [frame[:ART_H]]
ART = {
"sunny": {"frames": _sunny(), "color": "yellow"},
"partly_cloudy": {"frames": _partly_cloudy(), "color": "yellow"},
"cloudy": {"frames": _cloudy(), "color": "white"},
"drizzle": {"frames": _drizzle(), "color": "cyan"},
"rain": {"frames": _rain(), "color": "cyan"},
"heavy_rain": {"frames": _heavy_rain(), "color": "cyan"},
"showers": {"frames": _showers(), "color": "cyan"},
"snow": {"frames": _snow(), "color": "white"},
"blizzard": {"frames": _blizzard(), "color": "white"},
"storm": {"frames": _storm(), "color": "blue"},
"fog": {"frames": _fog(), "color": "white"},
"night": {"frames": _night(), "color": "white"},
"night_partly_cloudy": {"frames": _night_cloudy(), "color": "white"},
}
# ─── Weather API ──────────────────────────────────────────────────────────────
def location_to_coords(location, country="", force_latin=False):
"""Resolve a location string to (lat, lon, display_name, country_code).
Tries three strategies in order:
1. Postal code lookup (fast, precise — works for ZIP, postcode, etc.)
2. Free-text city search with country filter (e.g. "London" + "gb")
3. Free-text city search globally (fallback, no country filter)
Returns: (lat, lon, city_name, country_code)
"""
def _search(params):
params.update({"format": "json", "limit": 1,
"addressdetails": 1})
req = urllib.request.Request(
"https://nominatim.openstreetmap.org/search?"
+ urllib.parse.urlencode(params),
headers={"User-Agent": "StormShell/1.0"},
)
with urllib.request.urlopen(req, timeout=10) as r:
return json.loads(r.read())
data = []
# Strategy 1 — postal code
p = {"postalcode": location}
if country:
p["country"] = country
elif location.replace(" ", "").isdigit():
p["country"] = DEFAULT_COUNTRY or "us"
try:
data = _search(p)
except Exception:
pass
# Strategy 2 — city name with country
if not data and country:
try:
data = _search({"q": location, "countrycodes": country})
except Exception:
pass
# Strategy 3 — city name global, only skip if input is all digits (zip code)
is_postal = location.replace(" ", "").isdigit()
if not data and not is_postal:
try:
data = _search({"q": location})
except Exception:
pass
if not data:
raise ValueError(
f"Could not find '{location}'"
+ (f" in country '{country}'" if country else "")
+ ". Try a city name or add --country CC."
)
item = data[0]
addr = item.get("address", {})
cc = addr.get("country_code", "").lower()
# Build a clean display name: prefer city/town/village, fall back to
# the first segment of the full display_name string
# Prefer native language name — looks great on SSH terminals which handle
# unicode. On raw TTY the Uni Terminus font covers Latin + box-draw but
# addr dict reliably has city/town/village for all location types
# Only fall back to display_name if addr has nothing useful
city = (addr.get("city")
or addr.get("town")
or addr.get("village")
or addr.get("municipality")
or addr.get("suburb")
or addr.get("city_district")
or addr.get("county")
or addr.get("province")
or addr.get("state_district")
or addr.get("region")
or addr.get("state"))
if not city:
for part in item.get("display_name", location).split(","):
part = part.strip()
if part and not part.replace(" ", "").isdigit():
city = part
break
if not city:
city = location
# If city name contains non-Latin characters (Hebrew, Arabic, CJK etc.)
# the Uni Terminus TTY font will show diamonds. Re-fetch with English.
def _is_latin(s):
try:
s.encode("latin-1")
return True
except (UnicodeEncodeError, AttributeError):
return False
return all(ord(c) < 0x0250 or c in " -'." for c in s)
if force_latin and not _is_latin(city):
try:
en_params = {"q": location, "format": "json", "limit": 1,
"addressdetails": 1, "accept-language": "en"}
if country:
en_params["countrycodes"] = country
en_req = urllib.request.Request(
"https://nominatim.openstreetmap.org/search?"
+ urllib.parse.urlencode(en_params),
headers={"User-Agent": "StormShell/1.0",
"Accept-Language": "en"},
)
with urllib.request.urlopen(en_req, timeout=10) as r:
en_data = json.loads(r.read())
if en_data:
en_addr = en_data[0].get("address", {})
en_city = (en_addr.get("city") or en_addr.get("town")
or en_addr.get("village") or en_addr.get("municipality")
or en_addr.get("suburb") or en_addr.get("city_district")
or en_addr.get("county") or en_addr.get("province")
or en_addr.get("state_district") or en_addr.get("region")
or en_addr.get("state"))
if en_city and _is_latin(en_city):
city = en_city
except Exception:
city = ''.join(c for c in city if ord(c) < 0x0250 or c in " -'.").strip() or location
return float(item["lat"]), float(item["lon"]), city, cc
def fetch_weather(lat, lon):
params = urllib.parse.urlencode({
"latitude": lat,
"longitude": lon,
"current": ",".join([
"temperature_2m", "apparent_temperature",
"relative_humidity_2m", "wind_speed_10m",
"wind_direction_10m", "weather_code",
"surface_pressure",
]),
"hourly": "temperature_2m,weather_code,precipitation_probability,surface_pressure",
"daily": "sunrise,sunset",
"temperature_unit": TEMP_UNIT,
"wind_speed_unit": WIND_UNIT,
"timezone": "auto",
"forecast_days": 2,
})
with urllib.request.urlopen(
f"https://api.open-meteo.com/v1/forecast?{params}", timeout=10
) as r:
return json.loads(r.read())
def fetch_aqi(lat, lon):
"""Fetch current US AQI and pollen from Open-Meteo air quality API."""
params = urllib.parse.urlencode({
"latitude": lat,
"longitude": lon,
"current": "us_aqi,pm2_5,alder_pollen,birch_pollen,grass_pollen,mugwort_pollen,olive_pollen,ragweed_pollen",
"timezone": "auto",
})
try:
with urllib.request.urlopen(
f"https://air-quality-api.open-meteo.com/v1/air-quality?{params}",
timeout=8
) as r:
data = json.loads(r.read())
c = data["current"]
aqi = c.get("us_aqi", None)
pm25 = c.get("pm2_5", None)
if aqi is None:
return None
if aqi <= 50: cat, col = "Good", "green"
elif aqi <= 100: cat, col = "Moderate", "yellow"
elif aqi <= 150: cat, col = "Unhealthy (sens.)", "orange"
elif aqi <= 200: cat, col = "Unhealthy", "red"
elif aqi <= 300: cat, col = "Very Unhealthy", "red"
else: cat, col = "Hazardous", "red"
# Pollen — find dominant type
pollen_types = {
"Tree": max(c.get("alder_pollen") or 0, c.get("birch_pollen") or 0, c.get("olive_pollen") or 0),
"Grass": c.get("grass_pollen") or 0,
"Weed": max(c.get("mugwort_pollen") or 0, c.get("ragweed_pollen") or 0),
}
dom_type = max(pollen_types, key=pollen_types.get)
dom_value = pollen_types[dom_type]
if dom_value == 0: pollen = None
elif dom_value < 10: pollen = {"type": dom_type, "level": "Low", "value": int(dom_value)}
elif dom_value < 50: pollen = {"type": dom_type, "level": "Medium", "value": int(dom_value)}
elif dom_value < 200: pollen = {"type": dom_type, "level": "High", "value": int(dom_value)}
else: pollen = {"type": dom_type, "level": "Very High", "value": int(dom_value)}
return {"aqi": aqi, "cat": cat, "col": col, "pm25": pm25, "pollen": pollen}
except Exception:
return None
return ["N","NE","E","SE","S","SW","W","NW"][round(deg / 45) % 8]
def moon_phase(dt=None):
"""Return (phase_name, phase_index) for the current moon phase.
phase_index: 0=New Moon ... 7=Waning Crescent
Pure math — no API needed."""
if dt is None:
dt = datetime.now()
known_new = datetime(2000, 1, 6, 18, 14)
elapsed = (dt - known_new).total_seconds()
cycle = 29.53058867 * 24 * 3600
phase_pct = (elapsed % cycle) / cycle
phases = [
(0.0, 0.03, "New Moon", 0),
(0.03, 0.22, "Waxing Crescent", 1),
(0.22, 0.28, "First Quarter", 2),
(0.28, 0.47, "Waxing Gibbous", 3),
(0.47, 0.53, "Full Moon", 4),
(0.53, 0.72, "Waning Gibbous", 5),
(0.72, 0.78, "Last Quarter", 6),
(0.78, 0.97, "Waning Crescent", 7),
(0.97, 1.0, "New Moon", 0),
]
for lo, hi, name, idx in phases:
if lo <= phase_pct < hi:
return name, idx
return "New Moon", 0
def moon_calendar(dt=None):
"""Return list of (phase_name, phase_idx, date_str, is_current) for all
8 phases showing the next occurrence of each from today.
Dots pattern: wax up 1-8, wane back down symmetrically."""
from datetime import timedelta
if dt is None:
dt = datetime.now()
known_new = datetime(2000, 1, 6, 18, 14)
cycle_sec = 29.53058867 * 24 * 3600
elapsed = (dt - known_new).total_seconds()
cycle_pct = (elapsed % cycle_sec) / cycle_sec
# Phase center offsets within the cycle (0.0 = new moon)
phase_offsets = [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
phase_names = [
"New Moon", "Waxing Crescent", "First Quarter", "Waxing Gibbous",
"Full Moon", "Waning Gibbous", "Last Quarter", "Waning Crescent",
]
# Dots filled per phase — wax up to 8, wane back down
dot_counts = [1, 2, 3, 4, 8, 6, 4, 2]
current_name, current_idx = moon_phase(dt)
rows = []
for i, (name, offset, dots) in enumerate(zip(phase_names, phase_offsets, dot_counts)):
# How far ahead (in cycle fraction) is this phase from now?
diff = (offset - cycle_pct) % 1.0
# Convert to a future date
future_dt = dt + timedelta(seconds=diff * cycle_sec)
date_str = future_dt.strftime("%b %d")
is_current = (i == current_idx)
rows.append((name, i, dots, date_str, is_current))
return rows
def _wind_dir(deg):
return ["N","NE","E","SE","S","SW","W","NW"][round(deg / 45) % 8]
def parse_weather(data):
c = data["current"]
h = data["hourly"]
d = data.get("daily", {})
unit = "F" if TEMP_UNIT == "fahrenheit" else "C"
wsym = {"mph": "mph", "kmh": "km/h", "ms": "m/s", "kn": "kn"}.get(WIND_UNIT, WIND_UNIT)
now_str = data["current"]["time"][:13]
now_index = 0
for i, t in enumerate(h["time"]):
if t.startswith(now_str):
now_index = i
break
precip_prob = h.get("precipitation_probability") or [0] * len(h["time"])
forecast = []
for offset in range(1, 7):
idx = now_index + offset
if idx >= len(h["time"]):
break
t = datetime.fromisoformat(h["time"][idx])
forecast.append({
"label": t.strftime("%-I%p").lower(),
"temp": f"{h['temperature_2m'][idx]:.0f}{unit}",
"code": h["weather_code"][idx],
"precip_pct": precip_prob[idx],
})
# Sunrise / sunset — strip date, keep HH:MM
def _hhmm(iso_str):
try:
return datetime.fromisoformat(iso_str).strftime("%H:%M")
except Exception:
return "--:--"
sunrise = _hhmm(d.get("sunrise", [""])[0]) if d.get("sunrise") else "--:--"
sunset = _hhmm(d.get("sunset", [""])[0]) if d.get("sunset") else "--:--"
phase_name, phase_idx = moon_phase()
# Pressure trend — compare now vs 3 hours ago
pressure_now = c.get("surface_pressure")
pressure_3h = None
if pressure_now is not None and "surface_pressure" in h:
idx_3h = max(0, now_index - 3)
pressure_3h = h["surface_pressure"][idx_3h]
if pressure_now is not None and pressure_3h is not None:
change = pressure_now - pressure_3h
if change > 1.0: trend, trend_dir = "Rising", "up"
elif change < -1.0: trend, trend_dir = "Falling", "down"
else: trend, trend_dir = "Steady", "flat"
pressure_data = {
"hpa": round(pressure_now, 1),
"change": round(change, 1),
"trend": trend,
"dir": trend_dir,
}
else:
pressure_data = None
return {
"temp": f"{c['temperature_2m']:.0f}{unit}",
"feels_like": f"{c['apparent_temperature']:.0f}{unit}",
"humidity": f"{c['relative_humidity_2m']:.0f}%",
"wind": f"{c['wind_speed_10m']:.0f} {wsym} {_wind_dir(c.get('wind_direction_10m', 0))}",
"condition": wmo_to_condition(c["weather_code"]),
"forecast": forecast,
"sunrise": sunrise,
"sunset": sunset,
"moon_name": phase_name,
"pressure": pressure_data,
"utc_offset": data.get("utc_offset_seconds", 0),
}
# ─── Color pairs ──────────────────────────────────────────────────────────────
CP_YELLOW = 1
CP_CYAN = 2
CP_WHITE = 3
CP_GREEN = 4
CP_RED = 5
CP_DIM = 6