-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgp.py
executable file
·1419 lines (1096 loc) · 43.6 KB
/
gp.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
## {{{ requirements
## for .venv_keylogger: keylogger
## By Davoud Arsalani
## https://github.com/davoudarsalani/scripts
## https://github.com/davoudarsalani/scripts/blob/master/gp.py
## https://raw.githubusercontent.com/davoudarsalani/scripts/master/gp.py
## https://davoudarsalani.ir
## for .venv: (
## beautifulsoup4
## black
## clipboard
## dbus-python
## dmenu
## google-api-python-client
## halo
## jdatetime
## notify2
## pillow
## pycurl
## pyfzf
## PyGObject (instead of vext.gi which threw error when installing)
## pyminizip
## pynput
## python-magic
## rarfile
## requests
## requests[socks]
## tabulate
## tinytag
## wget
## wordcloud
## youtube_dl
## [jedi]
## )
## }}}
## {{{ imports
from os import getenv ## for send_email* functions
from typing import Any ## for Audio, get_input, get_single_input, get_last, get_datetime
## }}}
class Color: ## {{{
## {{{
@staticmethod
def red(text: str) -> str:
return f'\033[00;49;031m{text}\033[0m'
@staticmethod
def green(text: str) -> str:
return f'\033[00;49;032m{text}\033[0m'
@staticmethod
def yellow(text: str) -> str:
return f'\033[00;49;033m{text}\033[0m'
@staticmethod
def blue(text: str) -> str:
return f'\033[00;49;034m{text}\033[0m'
@staticmethod
def purple(text: str) -> str:
return f'\033[00;49;035m{text}\033[0m'
@staticmethod
def cyan(text: str) -> str:
return f'\033[00;49;036m{text}\033[0m'
@staticmethod
def white(text: str) -> str:
return f'\033[00;49;037m{text}\033[0m'
@staticmethod
def grey(text: str) -> str:
return f'\033[00;49;090m{text}\033[0m'
@staticmethod
def brown(text: str) -> str:
return f'\033[38;05;094m{text}\033[0m'
@staticmethod
def orange(text: str) -> str:
return f'\033[38;05;202m{text}\033[0m'
@staticmethod
def olive(text: str) -> str:
return f'\033[38;05;064m{text}\033[0m'
## }}}
## {{{ bold
@staticmethod
def red_bold(text: str) -> str:
return f'\033[01;49;031m{text}\033[0m'
@staticmethod
def green_bold(text: str) -> str:
return f'\033[01;49;032m{text}\033[0m'
@staticmethod
def yellow_bold(text: str) -> str:
return f'\033[01;49;033m{text}\033[0m'
@staticmethod
def blue_bold(text: str) -> str:
return f'\033[01;49;034m{text}\033[0m'
@staticmethod
def purple_bold(text: str) -> str:
return f'\033[01;49;035m{text}\033[0m'
@staticmethod
def cyan_bold(text: str) -> str:
return f'\033[01;49;036m{text}\033[0m'
@staticmethod
def white_bold(text: str) -> str:
return f'\033[01;49;037m{text}\033[0m'
@staticmethod
def grey_bold(text: str) -> str:
return f'\033[01;49;090m{text}\033[0m'
## }}}
## {{{ dim
@staticmethod
def red_dim(text: str) -> str:
return f'\033[02;49;031m{text}\033[0m'
@staticmethod
def green_dim(text: str) -> str:
return f'\033[02;49;032m{text}\033[0m'
@staticmethod
def yellow_dim(text: str) -> str:
return f'\033[02;49;033m{text}\033[0m'
@staticmethod
def blue_dim(text: str) -> str:
return f'\033[02;49;034m{text}\033[0m'
@staticmethod
def purple_dim(text: str) -> str:
return f'\033[02;49;035m{text}\033[0m'
@staticmethod
def cyan_dim(text: str) -> str:
return f'\033[02;49;036m{text}\033[0m'
@staticmethod
def white_dim(text: str) -> str:
return f'\033[02;49;037m{text}\033[0m'
@staticmethod
def grey_dim(text: str) -> str:
return f'\033[02;49;090m{text}\033[0m'
## }}}
## {{{ italic
@staticmethod
def red_italic(text: str) -> str:
return f'\033[03;49;031m{text}\033[0m'
@staticmethod
def green_italic(text: str) -> str:
return f'\033[03;49;032m{text}\033[0m'
@staticmethod
def yellow_italic(text: str) -> str:
return f'\033[03;49;033m{text}\033[0m'
@staticmethod
def blue_italic(text: str) -> str:
return f'\033[03;49;034m{text}\033[0m'
@staticmethod
def purple_italic(text: str) -> str:
return f'\033[03;49;035m{text}\033[0m'
@staticmethod
def cyan_italic(text: str) -> str:
return f'\033[03;49;036m{text}\033[0m'
@staticmethod
def white_italic(text: str) -> str:
return f'\033[03;49;037m{text}\033[0m'
@staticmethod
def grey_italic(text: str) -> str:
return f'\033[03;49;090m{text}\033[0m'
## }}}
## {{{ underline
@staticmethod
def red_underline(text: str) -> str:
return f'\033[04;49;031m{text}\033[0m'
@staticmethod
def green_underline(text: str) -> str:
return f'\033[04;49;032m{text}\033[0m'
@staticmethod
def yellow_underline(text: str) -> str:
return f'\033[04;49;033m{text}\033[0m'
@staticmethod
def blue_underline(text: str) -> str:
return f'\033[04;49;034m{text}\033[0m'
@staticmethod
def purple_underline(text: str) -> str:
return f'\033[04;49;035m{text}\033[0m'
@staticmethod
def cyan_underline(text: str) -> str:
return f'\033[04;49;036m{text}\033[0m'
@staticmethod
def white_underline(text: str) -> str:
return f'\033[04;49;037m{text}\033[0m'
@staticmethod
def grey_underline(text: str) -> str:
return f'\033[04;49;090m{text}\033[0m'
## }}}
## {{{ blink
@staticmethod
def red_blink(text: str) -> str:
return f'\033[05;49;031m{text}\033[0m'
@staticmethod
def green_blink(text: str) -> str:
return f'\033[05;49;032m{text}\033[0m'
@staticmethod
def yellow_blink(text: str) -> str:
return f'\033[05;49;033m{text}\033[0m'
@staticmethod
def blue_blink(text: str) -> str:
return f'\033[05;49;034m{text}\033[0m'
@staticmethod
def purple_blink(text: str) -> str:
return f'\033[05;49;035m{text}\033[0m'
@staticmethod
def cyan_blink(text: str) -> str:
return f'\033[05;49;036m{text}\033[0m'
@staticmethod
def white_blink(text: str) -> str:
return f'\033[05;49;037m{text}\033[0m'
@staticmethod
def grey_blink(text: str) -> str:
return f'\033[05;49;090m{text}\033[0m'
## }}}
## {{{ bg
@staticmethod
def red_bg(text: str) -> str:
return f'\033[07;49;031m{text}\033[0m'
@staticmethod
def green_bg(text: str) -> str:
return f'\033[07;49;032m{text}\033[0m'
@staticmethod
def yellow_bg(text: str) -> str:
return f'\033[07;49;033m{text}\033[0m'
@staticmethod
def blue_bg(text: str) -> str:
return f'\033[07;49;034m{text}\033[0m'
@staticmethod
def purple_bg(text: str) -> str:
return f'\033[07;49;035m{text}\033[0m'
@staticmethod
def cyan_bg(text: str) -> str:
return f'\033[07;49;036m{text}\033[0m'
@staticmethod
def white_bg(text: str) -> str:
return f'\033[07;49;037m{text}\033[0m'
@staticmethod
def grey_bg(text: str) -> str:
return f'\033[07;49;090m{text}\033[0m'
@staticmethod
def brown_bg(text: str) -> str:
return f'\033[48;05;094m{text}\033[0m'
@staticmethod
def orange_bg(text: str) -> str:
return f'\033[48;05;202m{text}\033[0m'
@staticmethod
def olive_bg(text: str) -> str:
return f'\033[48;05;064m{text}\033[0m'
## }}}
## {{{ strikethrough
@staticmethod
def red_strikethrough(text: str) -> str:
return f'\033[09;49;031m{text}\033[0m'
@staticmethod
def green_strikethrough(text: str) -> str:
return f'\033[09;49;032m{text}\033[0m'
@staticmethod
def yellow_strikethrough(text: str) -> str:
return f'\033[09;49;033m{text}\033[0m'
@staticmethod
def blue_strikethrough(text: str) -> str:
return f'\033[09;49;034m{text}\033[0m'
@staticmethod
def purple_strikethrough(text: str) -> str:
return f'\033[09;49;035m{text}\033[0m'
@staticmethod
def cyan_strikethrough(text: str) -> str:
return f'\033[09;49;036m{text}\033[0m'
@staticmethod
def white_strikethrough(text: str) -> str:
return f'\033[09;49;037m{text}\033[0m'
@staticmethod
def grey_strikethrough(text: str) -> str:
return f'\033[09;49;090m{text}\033[0m'
## }}}
def heading(self, text: str) -> str:
return self.green(text)
def ask(self, text: str) -> str:
return self.olive(text)
def flag(self, text: str) -> str:
return self.purple(text)
def default(self, text: str) -> str:
return self.white_dim(text)
## }}}
class Audio: ## {{{
@staticmethod
def vol(arg: str) -> Any:
from re import match
from subprocess import run, check_output
# port = check_output(f'pacmd list-sinks | grep -iA 65 "*" | grep -i "active port" | grep -ioP "(?<=<).*?(?=>)"', shell=True, universal_newlines=True).strip()
name = check_output(f'pacmd list-sinks | grep -iA 1 "*" | grep -i "name:" | grep -ioP "(?<=<).*?(?=>)"', shell=True, universal_newlines=True).strip()
index = check_output(f'pacmd list-sinks | grep -i "*"', shell=True, universal_newlines=True).strip().split()[-1]
level = check_output(f'pacmd list-sinks | grep -iA 6 {name} | grep -i "volume: front"', shell=True, universal_newlines=True).strip().split()[4].replace("%", "")
state = check_output(f'pacmd list-sinks | grep -iA 3 {name} | grep -i "state:"', shell=True, universal_newlines=True).strip().split()[-1]
if not match('^bluez_sink', name):
mute_status = check_output(f'pacmd list-sinks | grep -i "muted"', shell=True, universal_newlines=True).strip().split()[1]
else:
mute_status = check_output(f'pacmd list-sinks | grep -i "muted"', shell=True, universal_newlines=True).strip().split()[-1]
if arg == 'name':
return name
elif arg == 'index':
return index
elif arg == 'level':
return level
elif arg == 'state':
return state
elif arg == 'mute_status':
return mute_status
# elif arg == 'port': return port
elif arg == 'mute':
run(f'pactl set-sink-mute {index} 1', shell=True)
elif arg == 'unmute':
run(f'pactl set-sink-mute {index} 0', shell=True)
@staticmethod
def mic(arg: str) -> Any:
from re import match
from subprocess import run, check_output
# port = check_output(f'pacmd list-sources | grep -iA 65 "*" | grep -i "active port" | grep -ioP "(?<=<).*?(?=>)"', shell=True, universal_newlines=True).strip()
name = check_output(f'pacmd list-sources | grep -iA 1 "*" | grep -i "name:" | grep -ioP "(?<=<).*?(?=>)"', shell=True, universal_newlines=True).strip()
index = check_output(f'pacmd list-sources | grep -i "*"', shell=True, universal_newlines=True).strip().split()[-1]
level = check_output(f'pacmd list-sources | grep -iA 6 {name} | grep -i "volume: front"', shell=True, universal_newlines=True).strip().split()[4].replace('%', '')
state = check_output(f'pacmd list-sources | grep -iA 3 {name} | grep -i "state:"', shell=True, universal_newlines=True).strip().split()[-1]
mute_status = check_output(f'pacmd list-sources | grep -A 10 {name} | grep -i "muted"', shell=True, universal_newlines=True).strip().split()[-1]
if arg == 'name':
return name
elif arg == 'index':
return index
elif arg == 'level':
return level
elif arg == 'state':
return state
elif arg == 'mute_status':
return mute_status
# elif arg == 'port': return port
elif arg == 'mute':
run(f'pactl set-source-mute {index} 1', shell=True)
elif arg == 'unmute':
run(f'pactl set-source-mute {index} 0', shell=True)
elif arg == '0':
run(f'pactl set-source-volume {index} 0%', shell=True)
elif arg == '25':
run(f'pactl set-source-volume {index} 25%', shell=True)
@staticmethod
def mon(arg: str) -> Any:
from re import match
from subprocess import run, check_output
mons = check_output(f'pacmd list-sources | grep -i "\.monitor" | grep -ioP "(?<=<).*?(?=>)"', shell=True, universal_newlines=True).strip().split()
for eachmon in mons:
name = eachmon
if match('^bluez_sink', name):
break
index = check_output(f'pacmd list-sources | grep -iB 1 {name} | grep -i "index"', shell=True, universal_newlines=True).strip().split()[-1]
level = check_output(f'pacmd list-sources | grep -iA 6 {name} | grep -i "volume: front"', shell=True, universal_newlines=True).strip().split()[4].replace('%', '')
state = check_output(f'pacmd list-sources | grep -iA 3 {name} | grep -i "state:"', shell=True, universal_newlines=True).strip().split()[-1]
mute_status = check_output(f'pacmd list-sources | grep -A 10 {name} | grep -i "muted"', shell=True, universal_newlines=True).strip().split()[-1]
if arg == 'name':
return name
elif arg == 'index':
return index
elif arg == 'level':
return level
elif arg == 'state':
return state
elif arg == 'mute_status':
return mute_status
elif arg == 'mute':
run(f'pactl set-source-mute {index} 1', shell=True)
elif arg == 'unmute':
run(f'pactl set-source-mute {index} 0', shell=True)
elif arg == '0':
run(f'pactl set-source-volume {index} 0%', shell=True)
elif arg == '100':
run(f'pactl set-source-volume {index} 100%', shell=True)
## }}}
class Screen: ## {{{
@staticmethod
def screen_1() -> tuple[str, str, int, int]:
from subprocess import check_output
scr_1 = check_output('xrandr | grep -iw connected | grep -i primary', shell=True, universal_newlines=True).strip()
scr_1_name, *_ = scr_1.split() ## eDP-1
scr_1_res_total = scr_1.split()[3] ## 1366x768+1920+0
scr_1_res, *_ = scr_1_res_total.split('+') ## 1366x768
scr_1_x, scr_1_y = scr_1_res.split('x') ## 1366 768
scr_1_x_offset, scr_1_y_offset = scr_1_res_total.split('+')[1:] ## 1920 0
return scr_1_name, scr_1_res, scr_1_x, scr_1_y, scr_1_x_offset, scr_1_y_offset
@staticmethod
def screen_2() -> tuple[str, str, int, int]:
from subprocess import check_output
scr_2 = check_output('xrandr | grep -iw connected | grep -vi primary | sed "1q;d"', shell=True, universal_newlines=True).strip()
scr_2_name, *_ = scr_2.split()
scr_2_res_total = scr_2.split()[2]
scr_2_res, *_ = scr_2_res_total.split('+')
scr_2_x, scr_2_y = scr_2_res.split('x')
scr_2_x_offset, scr_2_y_offset = scr_2_res_total.split('+')[1:]
return scr_2_name, scr_2_res, scr_2_x, scr_2_y, scr_2_x_offset, scr_2_y_offset
@staticmethod
def screen_3() -> tuple[str, str, int, int]:
from subprocess import check_output
scr_3 = check_output('xrandr | grep -iw connected | grep -vi primary | sed "2q;d"', shell=True, universal_newlines=True).strip()
scr_3_name, *_ = scr_3.split()
scr_3_res_total = scr_3.split()[2]
scr_3_res, *_ = scr_3_res_total.split('+')
## scr_3 may have a name but no proper scr_3_res (e.g. is 'normal' instead of '1920x1080') because
## screen 3 has been turned off at startup with 'xrandr --output "$scr_3_name" --off' command
## therefore it doesn't have proper x and y. So, we need try here
## TODO can this happen to scr_2 (in screen_2 function) too when second monitor is not attached?
try:
scr_3_x, scr_3_y = scr_3_res.split('x')
scr_3_x_offset, scr_3_y_offset = scr_3_res_total.split('+')[1:]
except Exception:
scr_3_x, scr_3_y = None, None
scr_3_x_offset, scr_3_y_offset = None, None
return scr_3_name, scr_3_res, scr_3_x, scr_3_y, scr_3_x_offset, scr_3_y_offset
@staticmethod
def screen_all() -> str:
from subprocess import check_output
scr_all_res = list(check_output('xrandr | grep -iw current', shell=True, universal_newlines=True).strip().split())
scr_all_res = scr_all_res[7:10]
scr_all_res = ''.join(scr_all_res).replace(',', '')
return scr_all_res
@staticmethod
def screens_count() -> int:
from subprocess import check_output
screens_count = check_output('xrandr --listmonitors', shell=True, universal_newlines=True).strip().split()[1] ## 2
return screens_count
## }}}
class Record: ## {{{
from halo import Halo
def __init__(self):
self.Aud = Audio()
self.def_video_dev = def_video_dev()
def audio(self, duration: str, output: str, suffix: str, timer_secs: int) -> None:
from subprocess import run
from threading import Thread
th = Thread(target=timer, args=(suffix, timer_secs), daemon=True)
th.start()
run(f'ffmpeg -f pulse -i {self.Aud.mon("index")} -f pulse -i default -filter_complex amix=inputs=2 -t {duration} {output} -loglevel quiet', shell=True)
def screen(self, resolution: str, x_offset: int, duration: str, output: str, suffix: str, timer_secs: int) -> None:
from subprocess import run
from threading import Thread
th = Thread(target=timer, args=(suffix, timer_secs), daemon=True)
th.start()
run(
f'ffmpeg -f pulse -i {self.Aud.mon("index")} -f pulse -i default -filter_complex amix=inputs=2 -f x11grab -r 30 \
-video_size {resolution} -i :0.0+{x_offset},0 -vcodec libx264 -preset veryfast -crf 18 -acodec libmp3lame -q:a 1 \
-pix_fmt yuv420p -vf eq=saturation=1.3 -t {duration} {output} -loglevel quiet',
shell=True,
)
def video(self, duration: str, output: str, suffix: str, timer_secs: int) -> None:
from subprocess import run
from threading import Thread
th = Thread(target=timer, args=(suffix, timer_secs), daemon=True)
th.start()
run(
f'ffmpeg -f v4l2 -framerate 25 -video_size 1366x768 -i {self.def_video_dev} -f pulse -i {self.Aud.mon("index")} \
-f pulse -i default -filter_complex amix=inputs=2 -t {duration} {output} -loglevel quiet',
shell=True,
)
@Halo(color='green', spinner='dots12')
def audio_ul(self, output: str) -> None:
from subprocess import run
run(f'ffmpeg -f pulse -i {self.Aud.mon("index")} -f pulse -i default -filter_complex amix=inputs=2 {output} -loglevel quiet', shell=True)
@Halo(color='green', spinner='dots12')
def screen_ul(self, resolution: str, x_offset: int, output: str) -> None:
from subprocess import run
run(
f'ffmpeg -f pulse -i {self.Aud.mon("index")} -f pulse -i default -filter_complex amix=inputs=2 -f x11grab -r 30 \
-video_size {resolution} -i :0.0+{x_offset},0 -vcodec libx264 -preset veryfast -crf 18 -acodec libmp3lame -q:a 1 \
-pix_fmt yuv420p -vf eq=saturation=1.3 {output} -loglevel quiet',
shell=True,
)
@Halo(color='green', spinner='dots12')
def video_ul(self, output: str) -> None:
from subprocess import run
run(
f'ffmpeg -f v4l2 -framerate 25 -video_size 1366x768 -i {self.def_video_dev} -f pulse -i {self.Aud.mon("index")} \
-f pulse -i default -filter_complex amix=inputs=2 {output} -loglevel quiet',
shell=True,
)
## }}}
def fzf(items: list[str], header: str = '') -> str: ## {{{
from os import getenv
from pyfzf.pyfzf import FzfPrompt
if header:
header = f'--header {header}'
Col = Color()
fzf = FzfPrompt()
fzf_opts = f'{getenv("FZF_DEFAULT_OPTS")} {header}'
try:
item = fzf.prompt(items, fzf_opts)
item = item[0]
print(f'{Col.brown("--=[")} {item} {Col.brown("]=--")}')
return item
except Exception:
print(Col.red('No item selected'))
exit(38)
## }}}
def invalid(text: str) -> None: ## {{{
print(Color().red(text))
exit(38)
## }}}
def relative_date(start_date) -> str: ## {{{
## convert start_date to second if not one
try:
start_date_in_seconds = int(start_date)
except ValueError:
start_date_in_seconds = convert_to_second(start_date)
now_in_seconds = get_datetime('seconds')
diff = int(now_in_seconds) - int(start_date_in_seconds)
return f"{convert_second(diff, 'verbose')} ago"
## }}}
def convert_to_second(fulldate: str) -> int: ## {{{ convert 2021-04-15T11:10:03+0430 to 1618468803
from datetime import datetime
return int(datetime.strptime(fulldate, '%Y-%m-%dT%H:%M:%S%Z').timestamp())
## }}}
def convert_second(seconds: int, verbose: bool = False) -> str: ## {{{
from re import sub
seconds = int(seconds)
if seconds < 1:
if verbose:
return 'less than a second'
else:
return '00:00:00'
ss = f'{int(seconds % 60):02}'
mi = f'{int(seconds / 60 % 60):02}'
hh = f'{int(seconds / 3600 % 24):02}'
dd = f'{int(seconds / 3600 / 24 % 30):02}'
mo = f'{int(seconds / 3600 / 24 / 30 % 12):02}'
yy = f'{int(seconds / 3600 / 24 / 30 / 12):02}'
if yy == '00' and mo == '00' and dd == '00':
if verbose:
result = f'{hh} hours, {mi} minutes and {ss} seconds'
else:
result = f'{hh}:{mi}:{ss}'
elif yy == '00' and mo == '00':
if verbose:
result = f'{dd} days, {hh} hours, {mi} minutes and {ss} seconds'
else:
result = f'{dd}:{hh}:{mi}:{ss}'
elif yy == '00':
if verbose:
result = f'{mo} months, {dd} days, {hh} hours, {mi} minutes and {ss} seconds'
else:
result = f'{mo}:{dd}:{hh}:{mi}:{ss}'
else:
if verbose:
result = f'{yy} years, {mo} months, {dd} days, {hh} hours, {mi} minutes and {ss} seconds'
else:
result = f'{yy}:{mo}:{dd}:{hh}:{mi}:{ss}'
## NOTE the same modifications in JUMP_4 are applied in
## 1. convert_second function in gb
## 2. 'relative' method of whatever-its-name-is class in models.py in django app
## so any changes you make here, make sure to update them too
## JUMP_4 remove items whose values are 00, and adjust comma and 'and'
result = sub(r'00 [a-z]+s, ', r'', result)
result = sub(r'00 [a-z]+s and ', r'', result)
result = sub(r'00 [a-z]+s$', r'', result)
result = sub(r', ([0-9][0-9] [a-z]+s )', r' and \1', result)
result = sub(r'and 00 [a-z]+s ', r'', result)
result = sub(r' and $', r'', result)
result = sub(r', ([0-9][0-9] [a-z]+)$', r' and \1', result)
result = sub(r' and ([0-9][0-9] [a-z]+) and', r', \1 and', result)
result = sub(r', +$', r'', result)
result = sub(r', ([0-9][0-9] [a-z]+s)$', r' and \1', result)
## JUMP_4 remove plural s when value is 01
result = sub(r'(01 [a-z]+)s ', r'\1 ', result)
result = sub(r'(01 [a-z]+)s, ', r'\1, ', result)
result = sub(r'(01 [a-z]+)s$', r'\1', result)
return result
## }}}
def duration_wrapper() -> str: ## {{{ TODO is str correct for outputs?
from typing import Callable
def dec(func: Callable) -> str:
from functools import wraps
from time import perf_counter
@wraps(func)
def wrapper(*args: str, **kwargs: str) -> str:
start = perf_counter()
func(*args, **kwargs)
end = perf_counter()
secs = end - start
return convert_second(secs)
return wrapper
return dec
## }}}
def get_headers() -> dict[str, str]: ## {{{
return {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip',
'DNT': '1', ## do not track request header
'Connection': 'close',
}
## }}}
def get_width() -> int: ## {{{
from shutil import get_terminal_size
return get_terminal_size()[0]
## OR:
# import subprocess
# return subprocess.check_output('tput cols', shell=True, universal_newlines=True).strip()
## }}}
def get_input(prompt: str) -> Any: ## {{{
answer = input(Color().ask(f'{prompt} '))
if answer:
return answer
## }}}
def get_single_input(prompt: str) -> Any: ## {{{ https://stackoverflow.com/questions/510357/how-to-read-a-single-character-from-the-user
def _find_getch() -> Any:
from sys import stdin
from termios import tcgetattr, tcsetattr, TCSADRAIN
from tty import setraw
def _getch() -> Any:
print(Color().ask(f'{prompt} '), end='')
fd = stdin.fileno()
old_settings = tcgetattr(fd)
try:
setraw(fd)
ch = stdin.read(1)
finally:
tcsetattr(fd, TCSADRAIN, old_settings)
return ch
return _getch
getch = _find_getch()
single_char = getch()
if single_char:
print(single_char)
return single_char
'''
from click import getchar, echo
while (single_character := getchar(echo(Color().ask(prompt), nl=False))) == '\r':
print()
pass
print(single_character)
return single_character
'''
## }}}
def get_datetime(frmt: str) -> Any: ## {{{
from datetime import datetime as dt
from jdatetime import datetime as jdt
if frmt == 'ymdhms':
output = dt.now().strftime('%Y%m%d%H%M%S')
elif frmt == 'ymd':
output = dt.now().strftime('%Y%m%d')
elif frmt == 'hms':
output = dt.now().strftime('%H%M%S')
elif frmt == 'seconds':
output = dt.now().strftime('%s')
elif frmt == 'weekday':
output = dt.now().strftime('%A')
elif frmt == 'jymdhms':
output = jdt.now().strftime('%Y%m%d%H%M%S')
elif frmt == 'jymd':
output = jdt.now().strftime('%Y%m%d')
elif frmt == 'jhms':
output = jdt.now().strftime('%H%M%S')
elif frmt == 'jseconds':
output = int(jdt.now().timestamp()) ## exceptionally written in this format. have to use int to get rid of decimals
elif frmt == 'jweekday':
output = jdt.now().strftime('%A')
return output
## }}}
def convert_byte(size_in_bytes: int) -> str: ## {{{ https://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python
from math import floor, log, pow as math_pow
from re import compile as re_compile, match, sub
reg = '^[0-9]+\.00$'
if size_in_bytes == 0:
return '0B'
suff = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
i = int(floor(log(size_in_bytes, 1024)))
p = math_pow(1024, i)
conv = f'{float(size_in_bytes / p):.2f}'
## remove trailing 00
if match(reg, conv):
conv = sub('\.00$', '', conv)
return f'{conv}{suff[i]}'
## }}}
def if_exists(dest) -> str: ## {{{
from os import path
append_index = 2
if path.exists(dest):
while path.exists(f'{dest}_{append_index:02}'):
append_index += 1
dest = f'{dest}_{append_index:02}'
return dest
## }}}
def last_file_exists(last_file) -> bool: ## {{{
from os import path
condition = [path.exists(last_file)]
return all(condition)
## }}}
def get_last(last_file) -> Any: ## {{{
with open(last_file, 'r') as opened_last_file:
output = opened_last_file.read().splitlines()[-1]
return output
## }}}
def save_as_last(last_file, text) -> None: ## {{{
current_datetime = get_datetime('jymdhms')
weekday = get_datetime('jweekday')
with open(last_file, 'w') as opened_last_file:
opened_last_file.write(f'{current_datetime}\t{weekday}\n{text}\n')
## }}}
def save_error(error_file, text) -> None: ## {{{
current_datetime = get_datetime('jymdhms')
weekday = get_datetime('jweekday')
with open(error_file, 'w') as opened_error_file:
opened_error_file.write(f'{current_datetime}\t{weekday}\n{text}\n')
## }}}
def msgn(message: str, title: str = '', icon: str = '', duration: int = 10) -> None: ## {{{
## https://notify2.readthedocs.io/en/latest/#notify2.Notification.set_urgency
## also have a look at https://www.devdungeon.com/content/desktop-notifications-linux-python
import notify2
notify2.init('app name')
n = notify2.Notification(str(message), str(title), icon)
n.timeout = duration * 1000
n.set_urgency(notify2.URGENCY_NORMAL) ## URGENCY_CRITICAL, URGENCY_LOW & URGENCY_NORMAL
n.show()
notify2.uninit()
## }}}
def msgc(message: str, title: str = '', icon: str = '') -> None: ## {{{
## https://notify2.readthedocs.io/en/latest/#notify2.Notification.set_urgency
## also have a look at https://www.devdungeon.com/content/desktop-notifications-linux-python
import notify2
notify2.init('app name')
n = notify2.Notification(str(message), str(title), icon)
n.set_urgency(notify2.URGENCY_CRITICAL) ## URGENCY_CRITICAL, URGENCY_LOW & URGENCY_NORMAL
n.show()
notify2.uninit()
## }}}
def countdown(start: int = 5) -> None: ## {{{
from time import sleep
for i in range(start, 0, -1):
msgn(i, duration=1)
sleep(1)
sleep(1)
## }}}
def centralize(text: str, wrapper: str = ' ') -> str: ## {{{
width = get_width()
return text.center(width, wrapper)
## }}}
def dmenu(items: list[str] = [], title: str = '', fg: str = '') -> str: ## {{{ Docs: https://dmenu.readthedocs.io/en/latest/
from os import getenv
import dmenu
if fg == 'red':
sb = getenv('red_dark')
else:
sb = getenv('dmenusb')
try:
return dmenu.show(
items,
case_insensitive=True,
lines=getenv('dmenulines'),
background=getenv('dmenunb'),
foreground=getenv('dmenunf'),
background_selected=sb,
foreground_selected=getenv('dmenusf'),
font=getenv('dmenufn'),
prompt=title,
)
except Exception:
print(Color().red('No item selected'))
exit(38)
## }}}
def rofi(items: list[str] = [], title: str = '', fg: str = '') -> str: ## {{{
from os import getenv
from subprocess import check_output
items = '\n'.join(items)
if not fg == 'red':
theme = f'{getenv("HOME")}/.config/rofi/onedark.rasi'
else:
theme = f'{getenv("HOME")}/.config/rofi/onedark-red.rasi'
try:
return check_output(f'echo -e "{items}" | rofi -theme {theme} -dmenu -i -p "{title}"', shell=True, universal_newlines=True).strip()
except Exception:
print(Color().red('No item selected'))
exit(38)
## }}}
def get_password(prompt: str) -> str: ## {{{ https://linuxhint.com/python-getpass-module/
from getpass import getpass
while len(password := getpass(prompt=Color().ask(prompt))) < 1:
pass
return password
## }}}
def remove_leading_zeros(number: int) -> int: ## {{{
from re import sub
number = str(number)