This repository has been archived by the owner on Jan 19, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshrinkray.py
executable file
·1356 lines (1174 loc) · 46 KB
/
shrinkray.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
# shrinkray, by megabyte112
# https://github.com/megabyte112/shrinkray
# see LICENSE for license info
### ----------[~~Settings~~]---------- ###
# Here you can find advanced settings for shrinkray.
# Lines prefixed with a hash (#) are comments and are ignored by the interpreter.
# Most of these are defaults: you can override them at runtime.
# All booleans (True/False) must have the first letter capitalized.
## ----[General]---- ##
# enable verbose mode.
# default: False
verbose = False
# string appended to filenames.
# default: "_shrinkray"
suffix = "_shrinkray"
# amount of 'wiggle room': higher means more chance of file being too big.
# always keep this less than 1, or else your files will be too large.
# default: 0.95
bitrate_multiplier = 0.95
# default target file size in kB.
# default: 8000
default_size = 8000
# trims the video between two timestamps by default.
# default: False
trim = False
# default shrinking speed, a number between 1 and 10, higher is faster.
# lower speeds lead to more accurate file sizes.
# set to 0 to disable ffmpeg speed presets.
# default: 5
speed = 5
# wait for enter key before closing.
# default: True
wait_when_done = True
# open in file manager by default when done.
# default: True
open_when_done = True
# send desktop notifications by default when shrinkray completes.
# default: True
send_notifs = True
# amount of allowed items in any of shrinkray's folders before showing a warning.
# these folders can eventually reach very large file sizes.
# set to None to disable.
# default: 100
warning_threshold = 100
## -----[Video]----- ##
# maximum allowed size of longest edge (in pixels) before scaling is needed.
# default: 1280
max_res_size = 1280
# framerate limit.
# this is also the framerate that the video can be interpolated to.
# default: 30
target_fps = 30
# container to contain video files.
# default: "mp4"
container = "mp4"
# video codec to use.
# default: "libx264"
video_codec = "libx264"
## -----[Audio]----- ##
# don't include video, and store file in audio container.
# default: False
audioonly = False
# don't include audio.
# doesn't work when audioonly is True.
# default: False
mute = False
# fraction of bandwith dedicated to audio.
# ignored when mute or audioonly is True.
# must be less than 1.
# default: 1/4
audioratio = 1/4
# highest allowed audio bitrate (in kbps).
# ignored when audioonly is True.
# set to None to disable.
# default: 256
max_audio_bitrate = 256
# container to store audio when audioonly is True.
# default: "mp3"
audiocontainer = "mp3"
# audio codec to use when audioonly is True.
# default: "libmp3lame"
audio_codec = "libmp3lame"
# if you want some good quality audio with a small file size, you can try
# setting the audio container to "opus" and setting the audio codec to "libopus".
# however, opus is not compatible with many programs at this time.
## ----[Colours]---- ##
# or 'colors', whatever.
# allowed colours (for all):
# "red", "green", "blue", "cyan", "magenta", "yellow", "white"
# titles.
# default: "cyan"
titlecol = "cyan"
# when asking for user input.
# default: "yellow"
inputcol = "yellow"
# warnings or errors.
# default: "red"
warningcol = "red"
# usually parts of titles, like 'pass 1' or 'mp3'.
# default: "magenta"
othercol = "magenta"
# file size numbers once completed.
# default: "cyan"
numbercol = "cyan"
# file size units once completed.
# default: "yellow"
unitcol = "yellow"
## ------[Fun]------ ##
# ultra high compression for those moldy shitposts.
# locks video bitrate to 20kbps, and audio bitrate to 10kbps.
# resolution is also smaller and FPS is capped at 10.
# default: False
meme_mode = False
# makes the volume louder, and adds some bass.
# this is for those crunchy earrape memes.
# default: False
loud = False
# add text to the top and bottom of videos.
# default: False
dotext = False
# reverb audio.
# default: False
reverb = False
# playback speed.
# default: 1.0
playbackspeed = 1.0
# interpolate frames if playback speed is changed.
# this makes it look smoother, and is interpolated to target_fps.
# however, this is extremely slow.
# default: False
interpolate = False
# how many times smaller than the width is the text padding.
# higher is smaller.
# default: 10
text_devisor = 10
# amplification.
# only effective when loud is True.
# default: 5
volume_multiplier = 5
# bass boost.
# only effective when loud is True.
# default: 2
bass_multiplier = 2
# how "crunchy" the audio should sound.
# only effective when loud is True.
# default: 64
crunchiness = 64
### -------[~~End of Settings~~]------- ###
# Everything below this point is actual code.
# Only edit if you know exactly what you're doing.
# okay, let's do this.
# import standard libraries
import sys, os, subprocess, math, shutil, logging, time, webbrowser
# get epoch time, this is used for logging filenames.
# aka seconds since Jan 1 1970 0:00:00.
# this allows multiple instances running at once.
launchtime = int(time.time())
# check folders
if not os.path.isdir("logs"):
os.mkdir("logs")
if not os.path.isdir("output"):
os.mkdir("output")
if not os.path.isdir("temp"):
os.mkdir("temp")
tempdir = "temp/"+str(launchtime)
os.mkdir(tempdir)
# don't edit
version = "1.7.5"
# setup logger
logformat='%(asctime)s: %(message)s'
logging.basicConfig(filename=f"logs/shrinkray_{launchtime}.log", filemode="w", level=logging.INFO, format=logformat)
if verbose:
logging.getLogger().addHandler(logging.StreamHandler())
logging.info("starting")
# determine host OS
if os.name == "nt": # windows
logging.info("host is Windows")
nullfile="NUL"
clearcmd = "cls"
else: # posix
logging.info("host is non-Windows")
nullfile="/dev/null"
clearcmd = "clear"
# early clear function which requires no dependencies, unlike the other
def earlyclearscreen():
global clearcmd, version
os.system(clearcmd)
print(f"shrinkray {version} | Setup\n")
# check non-standard dependencies
try:
import ffpb, yt_dlp, notifypy, showinfm, colorama
logging.info("deps already installed")
except ImportError:
# time to install deps
earlyclearscreen()
logging.info("installing deps")
print("\nInstalling dependencies, you may see some warnings.\n")
import pip
pip.main(["install","--quiet",
"ffpb",
"yt-dlp",
"notify-py",
"show-in-file-manager",
"colorama",
"--exists-action","i"])
import ffpb, yt_dlp, notifypy, showinfm, colorama
earlyclearscreen()
logging.info("done deps, closing")
print("\nDependencies have been installed,\nPlease restart shrinkray.")
if wait_when_done:
input("\nPress Enter to close.")
sys.exit()
# check for ffmpeg
if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None:
earlyclearscreen()
print("\nIt seems like FFMPEG isn't installed, or isn't in your system path.")
print("Refer to shrinkray's guide for more info.")
print("https://github.com/megabyte112/shrinkray/wiki/shrinkray-wiki")
if wait_when_done:
input("\nWhen you're done, reopen shrinkray, and you're all set.")
sys.exit()
arg_length = len(sys.argv)
if verbose:
executable = "ffmpeg"
else:
executable = "ffpb"
tempfiles = []
# initialise text colouring for Windows hosts since it isn't natively supported,
# this has no effect on other platforms.
colorama.init()
# coloured or bold text
strreset = colorama.Style.RESET_ALL
strbold = colorama.Style.BRIGHT
strunbold = colorama.Style.NORMAL
strred = colorama.Fore.RED
stryellow = colorama.Fore.YELLOW
strgreen = colorama.Fore.GREEN
strblue = colorama.Fore.BLUE
strcyan = colorama.Fore.CYAN
strpurple = colorama.Fore.MAGENTA
strwhite = colorama.Fore.WHITE
def getcolfromtext(text):
if text=="red":
return strred
elif text == "green":
return strgreen
elif text == "blue":
return strblue
elif text == "cyan":
return strcyan
elif text == "magenta":
return strpurple
elif text == "yellow":
return stryellow
else:
return strwhite
titlecolour = getcolfromtext(titlecol)
askcolour = getcolfromtext(inputcol)
errorcolour = getcolfromtext(warningcol)
othercolour = getcolfromtext(othercol)
numbercolour = getcolfromtext(numbercol)
unitcolour = getcolfromtext(unitcol)
# define clear function
def clearscreen(stage, color):
global clearcmd, version, verbose
if verbose:
return
os.system(clearcmd)
print(f"{strbold}shrinkray {version} | {color}{stage}{strreset}\n")
# configure notifs
logging.info("configuring notifs")
notif_convert = notifypy.Notify()
notif_convert.title = "Converting"
notif_convert.message = "Media is being converted to another format."
notif_audiocompress = notifypy.Notify()
notif_audiocompress.title = "Shrinking Audio"
notif_audiocompress.message = "You'll be notified once compression is complete."
notif_twopass = notifypy.Notify()
notif_twopass.title = "Shrinking Video"
notif_twopass.message = "You'll be notified once compression is complete."
notif_complete = notifypy.Notify()
notif_complete.title = "Shrinking Complete!"
notif_complete.message = "Your video was compressed successfully."
notif_failed = notifypy.Notify()
notif_failed.title = "Shrinking Failed!"
notif_failed.message = "Your video couldn't be compressed properly."
notif_toobig = notifypy.Notify()
notif_toobig.title = "Shrinking Complete!"
notif_toobig.message = "The resulting file is larger than you requested."
notif_smallenough = notifypy.Notify()
notif_smallenough.title = "Complete!"
notif_smallenough.message = "The file was already small enough."
notif_amplify = notifypy.Notify()
notif_amplify.title = "Amplifying"
notif_amplify.message = "Turning up the volume."
notif_mute = notifypy.Notify()
notif_mute.title = "Removing Audio"
notif_mute.message = "Your video will be muted."
notif_text = notifypy.Notify()
notif_text.title = "Writing text"
notif_text.message = "Text is being added to your video."
notif_trim = notifypy.Notify()
notif_trim.title = "Trimming"
notif_trim.message = "Your file is being trimmed to your specified time."
notif_spd = notifypy.Notify()
notif_spd.title = "Changing speed"
notif_spd.message = "The playback speed is being changed."
notif_reverb = notifypy.Notify()
notif_reverb.title = "Adding reverb"
notif_reverb.message = "Reverb is being added to audio."
notif_interpolate = notifypy.Notify()
notif_interpolate.title = "Interpolating"
notif_interpolate.message = "Your video is being interpolated for added smoothness."
logging.info("counting files")
# count the number of files in each folder
def countfiles(path):
return len(os.listdir(path))
log_count = countfiles("logs")
logging.info(f"logs: {log_count}")
out_count = countfiles("output")
logging.info(f"output: {out_count}")
clearscreen("Waiting for input...", stryellow)
logging.info("args: " + str(sys.argv))
logging.info("wait when done: "+str(wait_when_done))
logging.info("count threshold: "+str(warning_threshold))
logging.info("initialization complete")
# we're running!!
print(f"\n{titlecolour}Welcome back to {strbold}shrinkray{strreset}.")
logging.info(f"shrinkray {version} is running!")
logging.info("tell megabyte112 about any issues :)")
if meme_mode:
print(f"\n{strbold}{errorcolour}haha shitpost shrinkray go brrrrrrrrr")
print(f"(meme mode is active by default){strreset}")
if audioonly:
print(f"\n{strbold}{errorcolour}WARNING: Output will be audio only by default!{strreset}")
elif mute:
print(f"\n{strbold}{errorcolour}WARNING: Video will be muted by default!{strreset}")
if loud and not mute:
print(f"\n{strbold}{errorcolour}i hope your ears are okay")
print(f"(loud mode enabled by default){strreset}")
if warning_threshold is not None:
sizewarned = False
if log_count >= warning_threshold:
sizewarned = True
print(f"\n{errorcolour}Logs folder contains {log_count} items!")
print(f"Consider clearing it once shrinkray is closed.{strreset}")
if out_count >= warning_threshold:
sizewarned = True
print(f"\n{errorcolour}Output folder contains {out_count} items!")
print(f"Consider clearing it once shrinkray is closed.{strreset}")
if sizewarned:
print(f"\n{errorcolour}You can disable these folder warnings in the settings.{strreset}")
def kibiconvert(value):
return value*0.9765625
def mebiconvert(value):
return round(kibiconvert(value)*100/1024)/100
def printsizes(size1, size2):
print()
print(f"{titlecolour}before:")
print(f" {numbercolour}{round(size1)}{unitcolour}kB{strwhite}, {numbercolour}{round(kibiconvert(size1))}{unitcolour}kiB")
print(f" {numbercolour}{round(size1/10)/100}{unitcolour}MB{strwhite}, {numbercolour}{mebiconvert(size1)}{unitcolour}MiB")
print()
print(f"{strbold}{titlecolour}after:")
print(f" {numbercolour}{round(size2)}{unitcolour}kB{strwhite}, {numbercolour}{round(kibiconvert(size2))}{unitcolour}kiB")
print(f" {numbercolour}{round(size2/10)/100}{unitcolour}MB{strwhite}, {numbercolour}{mebiconvert(size2)}{unitcolour}MiB")
print(strreset)
shrinkness = round((size2/size1)*1000)/1000
print(f"{titlecolour}{strbold}File is {othercolour}{shrinkness}x{titlecolour} the original size.{strreset}")
print()
def CheckValidSizeInput(text):
if 'k' in text:
text = text[0:len(text)-1]
return text.isnumeric() and int(text) >= 0
def CheckValidInput(text):
return text.isnumeric() and int(text) > 0
def CheckValidSpeedInput(text):
return text.isnumeric() and int(text) >= 0 and int(text) <= 10
def CheckValidMultiInput(text):
return text.isnumeric() and int(text) > 0 and int(text) <= 100
def CheckValidRatioInput(text):
text = text.split("/")
return len(text) == 2 and text[0].isnumeric() and text[1].isnumeric() and int(text[0]) < int(text[1])
def GetMoreOptionsChoice():
text = input(f"\n{strbold}{askcolour}More options?{strreset} [Y/N]\n> ")
return text.lower() == "y"
def GetAdvancedOptionsChoice():
text = input(f"\n{strbold}{askcolour}Advanced options?{strreset} [Y/N]\n> ")
return text.lower() == "y"
# ask for target file size
def GetTargetSize():
text = "abc"
while not CheckValidSizeInput(text):
text = input(f"\n{strbold}{askcolour}Target file size in MB {strreset}[add k for kB, or enter 0 for no limit]\n> ")
if text == "":
return default_size
if not CheckValidSizeInput(text):
logging.warning("rejected input: "+str(text))
print(f"\n{errorcolour}Make sure your input a whole number!{strreset}")
if 'k' in text:
return text[0:len(text)-1]
return text + "000"
def GetBitrateMultiplier():
global bitrate_multiplier
text = "abc"
while not CheckValidMultiInput(text):
text = input(f"\n{strbold}{askcolour}Bitrate multiplier {strreset}[as percentage, like 95]\n> ")
if text == "":
return bitrate_multiplier*100.0
if not CheckValidMultiInput(text):
logging.warning("rejected input: "+str(text))
print(f"\n{errorcolour}Make sure your input a whole number!{strreset}")
return text
def GetAudioRatio():
text = "0"
while not CheckValidRatioInput(text):
text = input(f"\n{strbold}{askcolour}Audio ratio {strreset}[as bottom-heavy fraction of two ints: x/y]\n> ")
if text == "":
return audioratio
if not CheckValidRatioInput(text):
logging.warning("rejected input: "+str(text))
print(f"\n{errorcolour}Make sure your input a bottom-heavy fraction of two integers, like 1/4.{strreset}")
text = text.split("/")
return float(text[0])/float(text[1])
# ask for speed
def GetSpeed():
text = "123"
while not CheckValidSpeedInput(text):
text = input(f"\n{strbold}{askcolour}Encoding speed{strreset} [1-10]\n> ")
if text == "":
return speed
if not CheckValidSpeedInput(text):
logging.warning("rejected input: "+str(text))
print(f"\n{errorcolour}Make sure your input a whole number between 1 and 10{strreset}")
return text
def GetAudioContainer():
global audiocontainer
text = input(f"\n{strbold}{askcolour}Audio container{strreset}\n> ")
if text == "":
return audiocontainer
else:
return text
def GetAudioCodec():
global audio_codec
text = input(f"\n{strbold}{askcolour}Audio codec{strreset}\n> ")
if text == "":
return audio_codec
else:
return text
def GetVideoContainer():
global container
text = input(f"\n{strbold}{askcolour}Video container{strreset}\n> ")
if text == "":
return container
else:
return text
def GetVideoCodec():
global video_codec
text = input(f"\n{strbold}{askcolour}Video codec{strreset}\n> ")
if text == "":
return video_codec
else:
return text
def GetMaxAudioBitrate():
global max_audio_bitrate
text = "0"
while not CheckValidInput(text):
text = input(f"\n{strbold}{askcolour}Max audio bitrate {strreset}[in kbps]\n> ")
if text == "":
return max_audio_bitrate
if not CheckValidInput(text):
logging.warning("rejected input: "+str(text))
print(f"\n{errorcolour}Make sure your input is a whole number greater than 0.{strreset}")
return text
def GetMaxRes():
global max_res_size
text = "0"
while not CheckValidInput(text):
text = input(f"\n{strbold}{askcolour}Max resolution {strreset}[in pixels, longest edge]\n> ")
if text == "":
return max_res_size
if not CheckValidInput(text):
logging.warning("rejected input: "+str(text))
print(f"\n{errorcolour}Make sure your input is a single whole number greater than 0.{strreset}")
return text
def GetMaxFramerate():
global target_fps
text = "0"
while not CheckValidInput(text):
text = input(f"\n{strbold}{askcolour}Max framerate {strreset}[in fps]\n> ")
if text == "":
return target_fps
if not CheckValidInput(text):
logging.warning("rejected input: "+str(text))
print(f"\n{errorcolour}Make sure your input is a whole number greater than 0.{strreset}")
return text
def GetTrimChoice():
global trim
text = input(f"\n{strbold}{askcolour}Trim video?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return trim
def GetReverbChoice():
global reverb
text = input(f"\n{strbold}{askcolour}Reverb audio?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return reverb
def GetInterpolateChoice():
global interpolate
text = input(f"\n{strbold}{askcolour}Interpolate video?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return interpolate
def CheckValidSpeedFloat(text):
try:
a = float(text)
except ValueError:
return False
if a >= 0.5 and a <= 2.0:
return True
return False
def GetPlaybackSpeed():
global playbackspeed
text = "abc"
while not CheckValidSpeedFloat(text):
text = input(f"\n{strbold}{askcolour}Playback speed {strreset}[normal speed = 1]\n> ")
if text == "":
return playbackspeed
if not CheckValidSpeedFloat(text):
logging.warning("rejected input: "+str(text))
print(f"\n{errorcolour}Make sure your input is a decimal number between 0.5 and 2.0.{strreset}")
return text
def GetOpenWhenDoneChoice():
global open_when_done
text = input(f"\n{strbold}{askcolour}Open file manager when completed?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return open_when_done
def GetAudioChoice():
global audioonly
text = input(f"\n{strbold}{askcolour}Get audio only?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return audioonly
def GetNotifChoice():
global send_notifs
text = input(f"\n{strbold}{askcolour}Send notifications?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return send_notifs
def GetMemeChoice():
global meme_mode
text = input(f"\n{strbold}{askcolour}Meme mode?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return meme_mode
def GetLoudChoice():
global loud
text = input(f"\n{strbold}{askcolour}Loud mode?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return loud
def GetTextChoice():
global dotext
text = input(f"\n{strbold}{askcolour}Add text?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return dotext
def GetMuteChoice():
global mute
text = input(f"\n{strbold}{askcolour}Mute audio?{strreset} [Y/N]\n> ")
if text.lower() == "n":
return False
elif text.lower() == "y":
return True
return mute
music_sites = [
"music.youtube.com",
"bandcamp.com",
"soundcloud.com",
"spotify.com",
"deezer.com"
]
# download video if no arguments are given
if arg_length < 2:
logging.info("prepare download...")
url=input(f"\n{strbold}{askcolour}Paste a video link.{strreset}\n> ")
logging.info(f"input: \"{url}\"")
audiosite = False
for site in music_sites:
if site in url:
audiosite = True
if audiosite:
logging.info("links to audio site")
print(f"\n{othercolour}This URL links to a music site, your download will be audio-only.{strreset}")
audioonly = True
container = audiocontainer
target_size = int(GetTargetSize())
if not audiosite:
audioonly = GetAudioChoice()
logging.info("target (in kB): "+str(target_size))
if GetMoreOptionsChoice():
trim = GetTrimChoice()
if trim:
start_time = input(f"\n{strbold}{askcolour}Start time {strreset}[hh:mm:ss] / [m:ss] / [s]\n> ")
end_time = input(f"\n{strbold}{askcolour}End time {strreset}[hh:mm:ss] / [m:ss] / [s]\n> ")
if start_time == "":
start_time = 0
if end_time == "":
end_time = -1
logging.info(f"time range between {start_time} and {end_time}")
if not audioonly:
mute = GetMuteChoice()
meme_mode = GetMemeChoice()
if not mute:
loud = GetLoudChoice()
reverb = GetReverbChoice()
playbackspeed = float(GetPlaybackSpeed())
send_notifs = GetNotifChoice()
open_when_done = GetOpenWhenDoneChoice()
if not audioonly:
dotext = GetTextChoice()
else:
dotext = False
if dotext:
text1 = input(f"\n{strbold}{askcolour}Top text{strreset}\n> ")
logging.info("text1: "+text1)
text2 = input(f"\n{strbold}{askcolour}Bottom text{strreset}\n> ")
logging.info("text2: "+text2)
if GetAdvancedOptionsChoice():
print(f"\n{errorcolour}{strbold}Warning: Changing these may result in errors and crashes.{strreset}")
speed = int(GetSpeed())
bitrate_multiplier = float(GetBitrateMultiplier())/100.0
if audioonly:
audiocontainer = GetAudioContainer()
audio_codec = GetAudioCodec()
else:
container = GetVideoContainer()
video_codec = GetVideoCodec()
if not audioonly and not meme_mode:
audioratio = float(GetAudioRatio())
max_audio_bitrate = int(GetMaxAudioBitrate())
max_res_size = int(GetMaxRes())
target_fps = int(GetMaxFramerate())
interpolate = GetInterpolateChoice()
logging.info("trim: "+str(trim))
logging.info("audioonly: "+str(audioonly))
logging.info("mute: "+str(mute))
logging.info("meme: "+str(meme_mode))
logging.info("loud: "+str(loud))
logging.info("reverb: "+str(reverb))
logging.info("playbackspeed: "+str(playbackspeed))
logging.info("notifs: "+str(send_notifs))
logging.info("open filemgr: "+str(open_when_done))
logging.info("text: "+str(dotext))
logging.info("speed: "+str(speed))
logging.info("bitratemulti: "+str(bitrate_multiplier))
if audioonly:
logging.info("audio container: "+str(audiocontainer))
logging.info("audio codec: "+str(audio_codec))
else:
logging.info("video container: "+str(container))
logging.info("video codec: "+str(video_codec))
logging.info("audioratio: "+str(audioratio))
logging.info("max audio bitrate: "+str(max_audio_bitrate))
logging.info("max resolution: "+str(max_res_size))
logging.info("target fps: "+str(target_fps))
logging.info("interpolate: "+str(interpolate))
clearscreen("Downloading...", strpurple)
print(f"\n{titlecolour}Fetching...{strreset}")
titlecmd = "yt-dlp -e --no-playlist --no-warnings "+url
logging.info("fetching title with the following command")
logging.info(titlecmd)
p = subprocess.getstatusoutput(titlecmd)
if p[0] != 0:
logging.info("title grab failed with return code "+str(p[0]))
print(f"{errorcolour}There was an issue with your video URL.\nPress {strbold}[Enter]{strunbold} or {strbold}close this window{strunbold} and run shrinkray again.")
print(f"Be sure to check whether your URL is correct!{strreset}")
logging.shutdown()
if wait_when_done:
input()
sys.exit()
title = p[1].replace("\"","'")
url=url.replace("\"","'")
title = title.replace("/","#")
logging.info("title: "+str(title))
print(f"{strgreen}Found - {strbold}{othercolour}\"{title}\"{strreset}")
# easter egg
if "never gonna give you up" in title.lower() or "rickroll" in title.lower():
webbrowser.open("https://youtu.be/dQw4w9WgXcQ")
print(f"\n{othercolour}{strbold}you rickroll me, i rickroll you{strreset}")
# if using youtube, assume mp4 to save time
if container == "mp4" and ("youtube.com" in url or "youtu.be" in url or "ytsearch:" in url):
logging.info("assuming mp4 download")
typearg = "-f mp4 "
elif audioonly:
typearg = "-x "
else:
typearg = ""
# find filename extension
getfilenamecmd = f"yt-dlp \"{url}\" --get-filename --no-playlist --no-warnings {typearg}-o \"{tempdir}/{title}.%(ext)s\""
logging.info("fetching filename with the following command")
logging.info(getfilenamecmd)
filein = subprocess.getoutput(getfilenamecmd)
logging.info("filename: "+filein)
splitfile = filein.split(".")
extension = splitfile[len(splitfile)-1]
logging.info("extension: "+extension)
dlname = f"{tempdir}/dl_{launchtime}.{extension}"
targetfilename = filein
filein = dlname
# escape quotes
url=url.replace("\"","\\\"")
if verbose:
dlcommand = f"yt-dlp \"{url}\" -v --no-playlist {typearg}-o \"{filein}\""
else:
dlcommand = f"yt-dlp \"{url}\" --quiet --progress --no-playlist --no-warnings {typearg}-o \"{filein}\""
print(f"\n{titlecolour}Downloading...{strreset}")
logging.info("downloading with the following command")
logging.info(dlcommand)
os.system(dlcommand)
filein = tempdir + "/" + os.listdir(tempdir)[0]
else:
# if user is supplying file
filein=sys.argv[1]
targetfilename = filein
logging.info("target file "+filein)
target_size = int(GetTargetSize())
logging.info("target (in kB): "+str(target_size))
audioonly = GetAudioChoice()
if GetMoreOptionsChoice():
trim = GetTrimChoice()
if trim:
start_time = input(f"\n{strbold}{askcolour}Start time {strreset}[hh:mm:ss] / [m:ss] / [s]\n> ")
end_time = input(f"\n{strbold}{askcolour}End time {strreset}[hh:mm:ss] / [m:ss] / [s]\n> ")
if start_time == "":
start_time = 0
if end_time == "":
end_time = -1
logging.info(f"time range between {start_time} and {end_time}")
if not audioonly:
mute = GetMuteChoice()
meme_mode = GetMemeChoice()
if not mute:
loud = GetLoudChoice()
reverb = GetReverbChoice()
playbackspeed = float(GetPlaybackSpeed())
send_notifs = GetNotifChoice()
open_when_done = GetOpenWhenDoneChoice()
if not audioonly:
dotext = GetTextChoice()
else:
dotext = False
if dotext:
text1 = input(f"\n{strbold}{askcolour}Top text{strreset}\n> ")
logging.info("text1: "+text1)
text2 = input(f"\n{strbold}{askcolour}Bottom text{strreset}\n> ")
logging.info("text2: "+text2)
if GetAdvancedOptionsChoice():
print(f"\n{errorcolour}{strbold}Warning: Changing these may result in errors and crashes.{strreset}")
speed = int(GetSpeed())
bitrate_multiplier = float(GetBitrateMultiplier())/100.0
if audioonly:
audiocontainer = GetAudioContainer()
audio_codec = GetAudioCodec()
else:
container = GetVideoContainer()
video_codec = GetVideoCodec()
if not audioonly and not meme_mode:
audioratio = float(GetAudioRatio())
max_audio_bitrate = int(GetMaxAudioBitrate())
max_res_size = int(GetMaxRes())
target_fps = int(GetMaxFramerate())
interpolate = GetInterpolateChoice()
logging.info("trim: "+str(trim))
logging.info("audioonly: "+str(audioonly))
logging.info("mute: "+str(mute))
logging.info("meme: "+str(meme_mode))
logging.info("loud: "+str(loud))
logging.info("reverb: "+str(reverb))
logging.info("playbackspeed: "+str(playbackspeed))
logging.info("notifs: "+str(send_notifs))
logging.info("open filemgr: "+str(open_when_done))
logging.info("text: "+str(dotext))
logging.info("speed: "+str(speed))
logging.info("bitratemulti: "+str(bitrate_multiplier))
if audioonly:
logging.info("audio container: "+str(audiocontainer))
logging.info("audio codec: "+str(audio_codec))
else:
logging.info("video container: "+str(container))
logging.info("video codec: "+str(video_codec))
logging.info("audioratio: "+str(audioratio))
logging.info("max audio bitrate: "+str(max_audio_bitrate))
logging.info("max resolution: "+str(max_res_size))
logging.info("target fps: "+str(target_fps))
logging.info("interpolate: "+str(interpolate))
target_size = float(target_size)
clearscreen("Running...", strblue)
# determine ffmpeg preset based on speed
if speed != 0:
speeds = ["placebo", "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast", "superfast", "ultrafast"]
preset = " -preset "+speeds[speed-1]
logging.info(f"preset: {speeds[speed-1]}")
else:
preset = " "
originalsize = round(os.path.getsize(filein)/1000) # kB
if audioonly:
container = audiocontainer
if loud:
audiofilters = f"-af volume={volume_multiplier},acrusher=.1:1:{crunchiness}:0:log,bass=g={bass_multiplier} "
else:
audiofilters = ""
# convert to correct format
splitfilein = filein.split(".")
fileincontain = splitfilein[len(splitfilein)-1]
filenocontain = filein[0:len(filein)-len(fileincontain)-1]
if fileincontain != container:
logging.info("converting file to "+container+" with the following command")
print(f"\n{strbold}{titlecolour}Converting to {othercolour}{container}{titlecolour}...{strreset}")
if send_notifs:
notif_convert.send()
convert_filename = f"{tempdir}/conv_{launchtime}.{container}"
convertcommand = f"{executable} -y -i \"{filein}\"{preset} \"{convert_filename}\""
tempfiles.append(convert_filename)
logging.info(convertcommand)
os.system(convertcommand)
filein = convert_filename