diff --git a/!_Run_NT.bat b/!_Run_NT.bat new file mode 100644 index 0000000..efc648b --- /dev/null +++ b/!_Run_NT.bat @@ -0,0 +1 @@ +py YTMVG.py -a "" \ No newline at end of file diff --git a/!_Run_Unix.sh b/!_Run_Unix.sh new file mode 100644 index 0000000..359418a --- /dev/null +++ b/!_Run_Unix.sh @@ -0,0 +1,2 @@ +#!/bin/bash +python3 YTMVG.py -a "" \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/Bug_Report.yml b/.github/ISSUE_TEMPLATE/Bug_Report.yml new file mode 100644 index 0000000..e391550 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Bug_Report.yml @@ -0,0 +1,62 @@ +name: "πŸ› Bug Report" +description: Create a new ticket for a bug. +title: "πŸ› [Bug] β€” " +labels: ["bug"] + +body: + - type: textarea + id: description + attributes: + label: "Description" + description: Please enter the detailed description of your issue. + placeholder: What happened? + validations: + required: true + - type: textarea + id: reprod + attributes: + label: "Reproduction steps" + description: Please enter the detailed description of circumstances that led to encountered problem. + placeholder: How did this happen? + validations: + required: false + - type: textarea + id: screenshot + attributes: + label: "Screenshots" + description: If applicable, add screenshots to help explain your problem. + value: | + ![Description](Image_URL.png) + render: bash + validations: + required: false + - type: textarea + id: logs + attributes: + label: "Logs" + description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks. + render: bash + validations: + required: true + - type: dropdown + id: os + attributes: + label: "Used OS" + multiple: true + options: + - Windows + - Linux + - MacOS + validations: + required: true + - type: markdown + attributes: + value: | + --- + - type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please ensure that your issue was not posted earlier before and update program version if it's outdated. + options: + - label: My issue is not a duplicate, and I am using the latest version of the program. + required: true \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/Config.yml b/.github/ISSUE_TEMPLATE/Config.yml new file mode 100644 index 0000000..ec4bb38 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/Feature_Request.yml b/.github/ISSUE_TEMPLATE/Feature_Request.yml new file mode 100644 index 0000000..fcc886b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Feature_Request.yml @@ -0,0 +1,41 @@ +name: "πŸ’‘ Feature Request" +description: Create a new ticket for a new feature request +title: "πŸ’‘ [Feature] β€” <Title>" +labels: ["question"] + +body: + - type: textarea + id: summary + attributes: + label: "Summary" + description: Provide a brief explanation of the feature. + placeholder: Describe your feature request in a few lines. + validations: + required: true + - type: textarea + id: reference_issues + attributes: + label: "Reference Issues" + description: Common issues. + placeholder: "#Issues IDs" + validations: + required: false + - type: textarea + id: basic_example + attributes: + label: "Basic Example" + description: Indicate here some basic examples of your feature. + placeholder: A few specific words about your feature request. + validations: + required: false + - type: markdown + attributes: + value: | + --- + - type: checkboxes + attributes: + label: Is there an existing ticket for this? + description: Please search to see if an issue already exists and/or is was not implemented in a recent version. + options: + - label: I have searched the existing issues and checked the recent builds/commits. + required: true \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ce96ba1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# Ignore notification +Data/Scripts/Utils/Notification.pyw \ No newline at end of file diff --git a/Data/Config.json b/Data/Config.json new file mode 100644 index 0000000..5d6bdb1 --- /dev/null +++ b/Data/Config.json @@ -0,0 +1,48 @@ +{ + "Media": { + "Image": { + "Path": "", + "Thumbnail": { + "Generate": true, + "Resize": false, + "Background": { + "Color": { + "Type": "Wet" + }, + "Properties": { + "Brightness": "40.00%", + "Saturation": "100.00%" + } + } + } + }, + "Audio": { + "Path": "", + "Bitrate": "255k" + }, + "Video": { + "Generate": true, + "WebM": false, + "Maximum_Resolution": "1080p" + }, + "Description": { + "Generate": true + } + }, + "Settings": { + "Preset": null, + "Directory": { + "Initial": { + "Audio": "~/Music", + "Image": "~/Pictures" + }, + "Open": true, + "Output": "./Videos" + }, + "Logs": { + "Verbosity": 1, + "Information": true, + "Sound": true + } + } +} \ No newline at end of file diff --git a/Data/Presets/Fast.txt b/Data/Presets/Fast.txt new file mode 100644 index 0000000..d135ac8 --- /dev/null +++ b/Data/Presets/Fast.txt @@ -0,0 +1,4 @@ +Resolution = "720p" +Audio Bitrate = "128k" +Resize Thumbnail = True +WebM Encode = False \ No newline at end of file diff --git a/Data/Presets/Music.txt b/Data/Presets/Music.txt new file mode 100644 index 0000000..72bcf95 --- /dev/null +++ b/Data/Presets/Music.txt @@ -0,0 +1,4 @@ +Resolution = "1080p" +Audio Bitrate = "224k" +Resize Thumbnail = True +WebM Encode = False \ No newline at end of file diff --git a/Data/Presets/Slow.txt b/Data/Presets/Slow.txt new file mode 100644 index 0000000..642cd07 --- /dev/null +++ b/Data/Presets/Slow.txt @@ -0,0 +1,4 @@ +Resolution = "2160p" +Audio Bitrate = "257k" +Resize Thumbnail = False +WebM Encode = True \ No newline at end of file diff --git a/Data/Scripts/ArgParse/Main.pyw b/Data/Scripts/ArgParse/Main.pyw new file mode 100644 index 0000000..9c135ee --- /dev/null +++ b/Data/Scripts/ArgParse/Main.pyw @@ -0,0 +1,188 @@ +__YT = fg.white + "You" + bg.red + "Tube" + bg.rs + Styles.Reset + +Parser = ArgumentParser( + prog = __name__ + ".py", + description = __doc__.split("\n")[0].replace("YouTube", __YT), + add_help = 0, + allow_abbrev = 0, + formatter_class = \ + lambda prog, size = 750: \ + HelpFormatter( + prog, width = size, + max_help_position = size + ) + ) + +#-=-=-=-# + +Resolutions = ( + 4320, 2160, + 1440, 1080, 720, + 480, 360, 240, 144 +) + +Colors_Dict = { + "1": 1, "Wet": 1, + "2": 2, "Dry": 2 +} + +#-=-=-=-# + +Required = Parser.add_argument_group("Required arguments") +Background = Parser.add_argument_group("Background color arguments") +Optional = Parser.add_argument_group("Optional arguments") +Switch = Parser.add_argument_group("Switch arguments") + +#-=-=-=-# +# Required + +Required.add_argument( + "-a", "--audio", type = str, required = 1, + default = Config["Media"]["Audio"]["Path"], + metavar = '"str"', help = "Audio file path or URL. {0}Accepts {0}".format( + "/".join(__ALLOWED_FORMATS), Styles.OK + ) +) + +Required.add_argument( + "-i", "--image", type = str, + default = Config["Media"]["Image"]["Path"], + metavar = '"str"', + help = '{1}Static{2} image file path or URL. {0}If none, tries to get an embedded front cover art from "-a"{2}'.format( + Styles.Info, Styles.Error, Styles.Reset + ) +) + +#-=-=-=-# +# Background + +Background.add_argument( + "-c", "--color", type = str, + choices = Colors_Dict.keys(), + default = Config["Media"]["Image"]["Thumbnail"]["Background"]["Color"]["Type"], + metavar = "[1, 2]", + help = "Index of the element of the image color clusters list" +) + +Background.add_argument( + "-bgb", "--brightness", type = str, + default = Config["Media"]["Image"]["Thumbnail"]["Background"]["Properties"]["Brightness"], + metavar = "[range(25, 75)]%", + help = "Thumbnail background color brightness, in {0}%%".format(Styles.Warning) +) + +Background.add_argument( + "-bgs", "--saturation", type = str, + default = Config["Media"]["Image"]["Thumbnail"]["Background"]["Properties"]["Saturation"], + metavar = "[range(100, 250)]%", + help = "Thumbnail background color saturation, in {0}%%".format(Styles.Warning) +) + +#-=-=-=-# +# Optional + +Optional.add_argument( + "-r", "--resolution", type = str, + choices = [str(Resolution) + "p" for Resolution in Resolutions], + default = Config["Media"]["Video"]["Maximum_Resolution"], + metavar = "[int]p", + help = "Maximum video resolution" +) + +Optional.add_argument( + "-ab", "--audio-bitrate", type = str, + default = str(Config["Media"]["Audio"]["Bitrate"]), + metavar = "[range(96, 256)]k", + help = "{0}Video audio bitrate{4}, in {2}kb/s{4}. If {2}> 255{4}, the {3}experimental{4} lossless {1}FLAC{4} codec is used".format( + Styles.Info, Styles.Meta_Info_2, Styles.Warning, Styles.Error, Styles.Reset + ) +) + +Optional.add_argument( + "-d", "--directory", type = str, + default = Config["Settings"]["Directory"]["Output"], + metavar = '"str"', + help = "Moves the directory with generated files to provided location" +) + +Optional.add_argument( + "-p", "--preset", type = str, default = Config["Settings"]["Preset"], + metavar = '["{0}", ...]'.format('", "'.join([ + ".".join(File.split(".")[:-1]).lower() + for File in os.listdir("Data/Presets")[:2] + ])), + help = "Preset name in {0}Data/Presets{2} directory. {1}Bypasses already set command flags{2}".format( + Styles.OK, Styles.Error, + Styles.Reset + ) +) + +Optional.add_argument( + "-v", "--verbosity", type = int, + choices = (-1, 0, 1, 2), + default = Config["Settings"]["Logs"]["Verbosity"], + metavar = "[-1, 0, 1, 2]", + help = "Verbosity level. {0}-1{2} for {1}none{2}, {0}0{2} for {1}basic FFmpeg stats{2}, {0}1{2} for {1}everything{2}, {0}2{2} for {1}extended logs{2}".format( + Styles.Info, Styles.Meta_Info_2, + Styles.Reset + ) +) + +#-=-=-=-# +# Switch + +Switch.add_argument( + "-rt", "--resize-thumbnail", action = ArgParseBool(Config["Media"]["Image"]["Thumbnail"]["Resize"]), + help = "Resizes thumbnail to {0}1280x720{1} if one of cover's dimensions exceeds {0}1280{1}".format( + Styles.Info, Styles.Reset + ) +) + +Switch.add_argument( + "-webm", "--webm-encode", action = ArgParseBool(not Config["Media"]["Video"]["WebM"]), + help = "Encodes {0}WebM{3} file instead of {1}MP4{3} one, resulting in smaller file size. {2}Extremely slow{3}!".format( + Styles.OK, Styles.Meta_Info_2, Styles.Error, Styles.Reset + ) +) + +Switch.add_argument( + "-nv", "--no-video", action = ArgParseBool(Config["Media"]["Video"]["Generate"]), + help = "Doesn't generate the video file" +) + +Switch.add_argument( + "-nt", "--no-thumbnail", action = ArgParseBool(Config["Media"]["Image"]["Thumbnail"]["Generate"]), + help = "Doesn't generate the thumbnail image" +) + +Switch.add_argument( + "-nd", "--no-description", action = ArgParseBool(Config["Media"]["Description"]["Generate"]), + help = "Doesn't generate the description file" +) + +Switch.add_argument( + "-nb", "--no-bell", action = ArgParseBool(Config["Settings"]["Logs"]["Sound"]), + help = 'Doesn\'t print the {0}"BEL"{1} character at the final print'.format(Styles.Meta_Info_2, Styles.Reset) +) + +Switch.add_argument( + "-nod", "--no-open-directory", + action = ArgParseBool(Config["Settings"]["Directory"]["Open"]), + help = "Doesn't open directory after finishing" +) + +Switch.add_argument( + "-cst", "--color-sorting-test", + action = "store_true", + help = SUPPRESS +) + +Switch.add_argument("-h", "--help", action = "help", help = "Shows this message") + +#-=-=-=-# + +for Argument in Parser._actions: + if not Argument.help.endswith((SUPPRESS, "!")): + Argument.help += Styles.Reset + "." + +args = Parser.parse_args() \ No newline at end of file diff --git a/Data/Scripts/ArgParse/Presets.pyw b/Data/Scripts/ArgParse/Presets.pyw new file mode 100644 index 0000000..4ca2e7b --- /dev/null +++ b/Data/Scripts/ArgParse/Presets.pyw @@ -0,0 +1,45 @@ +__CantLoad = "Couldn't load the \"{0}\" preset!" + +if args.preset: + args.preset = args.preset.lower().strip() + + __Presets = FM.Utils.Get.Path("Data/Presets") + + for File in path(__Presets).glob("*.txt"): + File = str(File.resolve()) + + if os.path.isfile(File): + File_Name = ".".join(os.path.basename(File).split(".")[:-1]) + + if File_Name.lower() == args.preset: + Content = open(File).readlines() + + for Line in Content: + Line = [Chunk.strip().replace(" ", "_") for Chunk in Line.strip().split("=")] + Line[0] = Line[0].lower() + + if Line[0] in args: + try: + exec("args.{0} = {1}".format(*Line)) + except Exception as Error: + print("\n{3}<ERROR>{5} {0} ({4}{1} - {2}{5})".format( + __CantLoad.format(File_Name), + Error.__class__.__name__, Error, + Styles.Info, Styles.Error, Styles.Reset + ) + ) + break + else: + print("\n{2}<WARNING>{3} {1} ({0} not in arguments)".format( + Line[0], CantLoad.format(File_Name), + Styles.Info, Styles.Reset + ) + ) + break + + print('\n{1}<INFO>{3} Successfully loaded the {2}"{0}"{3} preset.'.format( + File_Name, + Styles.Info, Styles.OK, Styles.Reset + ) + ) + break \ No newline at end of file diff --git a/Data/Scripts/ArgParse/Settings.pyw b/Data/Scripts/ArgParse/Settings.pyw new file mode 100644 index 0000000..d3730eb --- /dev/null +++ b/Data/Scripts/ArgParse/Settings.pyw @@ -0,0 +1,168 @@ +# Settings +args.directory = FM.Utils.Get.Path(args.directory) + +if args.verbosity == -1: + os.sys.stdout = open(os.devnull, "w", encoding = "U8") + Verbose = ["-q", "-8"] +elif args.verbosity == 0: + os.sys.stdout = open(os.devnull, "w", encoding = "U8") + Verbose = ["-q", "16"] +elif args.verbosity == 1: + Verbose = ["-v", "16"] +elif args.verbosity == 2: + Verbose = ["-v", "32"] + +if args.verbosity > -1: + Verbose[1] += " -stats" + +Verbose[1] = "-hide_banner -loglevel " + Verbose[1] + +BEL = "" if args.no_bell else "\a" + +Directory = FM.Utils.Get.Path("Videos") +if not os.path.exists(Directory): + os.mkdir(Directory) + +## Presets +exec(open_("ArgParse/Presets")) + +#-=-=-=-# + +if args.no_video: + Video_Names = (0,) + +if all((args.no_video, args.no_thumbnail, args.no_description)): + Error("It looks like I'm not doing anything.") + +#-=-=-=-=-=-# + +GUI = 0 +if any((not args.audio, args.audio == "<select>")): + GUI = 1 + __Wait = "Please select tagged audio file." + try: + print(__Wait, " " * 32, end = "\r") + args.audio = fd.askopenfilename( + title = __Wait, + initialdir = Initial_Directory["Audio"], + filetypes = [ + ("MPEG Audio Layer 3", "*.mp3"), + ("Free Lossless Audio Codec", "*.flac"), + ("Ogg Vorbis", "*.ogg"), + ("All files", "*.*"), + ], + defaultextension = "*.mp3" + ) + if not args.audio: + Error("File selection aborted.") + except TclError: + pass + +# Audio +args.audio = FM.Utils.Get.File(args.audio, 0) +if args.audio[-1]: __FILES_TO_REMOVE += [args.audio[0]] +args.audio = FM.Utils.Get.Path(args.audio[0]) + +if not args.audio.upper().endswith(__ALLOWED_FORMATS): + raise Error("Unsupported audio file format.") + +Audio = FM.Utils.Get.Path( + FM.Upload.Media(args.audio, mFile, "audio") +) +Audio_File = mFile(Audio) + +if not args.image: + File = Audio_File + try: + Type = File.mime[0].split("/")[-1].capitalize() + except AttributeError: + Error("Not an audio file!") + if len(Type) < 5: + Type = Type.upper() + + #-=-=-=-# + + try: + if Type == "MP3": + File = File.tags["APIC:"].data + elif Type == "FLAC": + File = File.pictures[0].data + elif Type == "Vorbis": + File = File.tags["coverart"] + else: + raise KeyError + File = BytesIO(File) + except (KeyError, TypeError, IndexError): + if GUI: + print("{0}Front cover art was not found in file! Please select one.{1}".format( + Styles.Warning, Styles.Reset + ) + ) + File = fd.askopenfilename( + title = "Please select image file", + initialdir = Initial_Directory["Image"], + filetypes = [ + ("Portable Network Graphics", "*.png"), + ("Lossy JPEG file", "*.jpg *.jpeg"), + ("Web Picture", "*.webp"), + ("Bitmap", "*.bmp"), + ("All files", "*.*"), + ], + defaultextension = "*.*" + ) + if not File: + Error("Image selection aborted.") + + #-=-=-=-# + + # Slow loading cause + try: + im = Image.open(File).convert("RGB") + except AttributeError: + Error("Provided file has no embedded correct front cover art image.") + + args.image = os.path.join(Directory, f"Cover_{__RAND_STR}.png") + cv2.imwrite( + args.image, + cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR) + ) + +# Image +args.image = FM.Utils.Get.File(args.image, 0) +if args.image[-1]: __FILES_TO_REMOVE += [args.image[0]] +args.image = FM.Utils.Get.Path(args.image[0]) +Cover = FM.Upload.Media(args.image, Image.open, "image") + +#-=-=-=-# + +## Thumbnail +args.color = Colors_Dict[str(args.color.title())] + +args.brightness = float(args.brightness.strip("%")) +args.brightness = Clamp(args.brightness, 25, 75) +args.brightness /= 100 + +args.saturation = float(args.saturation.strip("%")) +args.saturation = Clamp(args.saturation, 75, 250) +args.saturation /= 100 + +#-=-=-=-# + +## Video +args.resolution = int("".join(filter(lambda Character: Character.isdigit(), args.resolution))) +Video_Codec = "libx264" + +# Audio +args.audio_bitrate = "".join((Character for Character in args.audio_bitrate if Character.isdigit())) +args.audio_bitrate = Clamp(int(args.audio_bitrate), 96, 257) +Audio_Quality = "{0}k".format(args.audio_bitrate) + +if Audio_File.info.channels > 1: + Channels = "2" +else: + Channels = "1" + +if args.audio_bitrate > 256: + Audio_Codec = "flac" +else: + Audio_Codec = "opus" \ No newline at end of file diff --git a/Data/Scripts/Process/Description/Main.pyw b/Data/Scripts/Process/Description/Main.pyw new file mode 100644 index 0000000..72f4546 --- /dev/null +++ b/Data/Scripts/Process/Description/Main.pyw @@ -0,0 +1,83 @@ +print("{1}<INFO>{3} Making Description... β”‚ {2}1/2{3} β”‚ {0}0.00 KB (-0.00 KB / -0.00%){3}".format( + Styles.OK, Styles.Info, Styles.Meta_Info_2, Styles.Reset + ) +) + +#-=-=-=-# + +Metadata = "" +Missing_Fields = [] +Final_Tags = {} + +# Get _Tags +if Type == "MP3": + _Tags = {Tag: str(Audio_Tags[Tag]) for Tag in list(Audio_Tags)} + +if Type in ("FLAC", "VORBIS"): + _Tags = {Key: ", ".join(Value) for Key, Value in dict(Audio_Tags).items()} + +#-=-=-=-# + +# Assign tags appropriately +for Key, Value in Audio_Tags_List[Type].items(): + if not Value in _Tags: + Missing_Fields += [Key] + _Tags[Value] = f"<INSERT_{Key.upper()}>" + Final_Tags[Key] = _Tags[Value] + exec(f'{Key} = "{_Tags[Value]}"') + +# Skip basic tags +__LastBasicTagIndex = list(Final_Tags.keys()).index("Organization") + 1 +Final_Tags = dict(list(Final_Tags.items())[__LastBasicTagIndex:]) + +#-=-=-=-# + +# Description variables +for Delimiter in ("&", "ft", "ft.", "feat", "feat.", "featuring"): + Delimiter = f" {Delimiter} " + Artist = Artist.replace(Delimiter, Delimiter.upper()) + Artist = Artist.replace(Delimiter.upper(), " Β· ") + +Artists = Artist.split(",") +Artists = (Artist.strip(".").strip() for Artist in Artists) +Artist = ", ".join(Artists) + +Now = dt.now() +Release_Date = Now.strftime("%Y-%m-%d") + +#-=-=-=-# + +if Final_Tags: + Metadata = "\n".join((f"{Key}: {Value}" for Key, Value in Final_Tags.items())) + +if Missing_Fields: + print("{1}<WARNING>{2} {0} audio tag fields were not detected, description file will be incomplete.{3}".format( + len(Missing_Fields), + Styles.Info, Styles.Warning, Styles.Reset + ) + ) + +#-=-=-=-# +# Description fill + +Description = Description[1:-1].replace("\n", "\n\n") +Description = Description.format( + __name__, + Title, Artist, + Album, + Year, + Organization, Release_Date, + Metadata +) + +with open(Text_File, "w", encoding = "U8") as File: + File.write(Description) + print("\n{2}<INFO>{4} Making Description... β”‚ {3}2/2{4} β”‚ {1}{0} (+{0} / +100.00%){4}".format( + FM.Utils.Get.Size(len(Description)), + Styles.OK, Styles.Info, Styles.Meta_Info_2, Styles.Reset + ) + ) + print("{0}Done!{1}".format( + Styles.OK, Styles.Reset + ) + ) \ No newline at end of file diff --git a/Data/Scripts/Process/Description/Setup.pyw b/Data/Scripts/Process/Description/Setup.pyw new file mode 100644 index 0000000..4d687bb --- /dev/null +++ b/Data/Scripts/Process/Description/Setup.pyw @@ -0,0 +1,59 @@ +Audio_MIME = Audio_File.mime[0].split("/")[-1].upper() + +Description = """ +Provided to YouTube by {0} +{1} Β· {2} +{3} +β„— {4} {5} +Released on: {6} +{7} +Auto-generated by {0}. +""" + +Audio_Tags_List = { + "FLAC": { + "Title": "title", + "Artist": "artist", + "Album": "album", + "Year": "date", + "Organization": "organization", + "Composer": "composer", + "Conductor": "conductor", + "Lyricist": "lyricist", + "Remixer": "version", + }, + "MP3": { + "Title": "TIT2", + "Artist": "TPE1", + "Album": "TALB", + "Year": "TDRC", + "Organization": "TPUB", + "Composer": "TCOM", + "Conductor": "TPE3", + "Lyricist": "TEXT", + "Remixer": "TPE4", + } +} + +# FLAC and Ogg (VORBIS) keys are equivalent +Audio_Tags_List["VORBIS"] = Audio_Tags_List["FLAC"] + +try: + try: + Audio_Tags = Audio_File.tags + if not Audio_Tags: + Traceback = "no audio tags were detected" + raise Exception + except Exception as Error: + Traceback = " - {0}".format(Error[0].capitalize() + Error[1:]) + raise Exception +except Exception: + print("{2}<WARNING> {1}Couldn't create description file - {0}.{3}".format( + Traceback.rstrip("."), + Styles.Warning, Styles.Info, Styles.Reset + ) + ) + +if Audio_Tags: + Text_File = os.path.join(Final_Directory, "Description.txt") + exec(open_("Process/Description/Main")) \ No newline at end of file diff --git a/Data/Scripts/Process/Thumbnail/Main.pyw b/Data/Scripts/Process/Thumbnail/Main.pyw new file mode 100644 index 0000000..6e6a16c --- /dev/null +++ b/Data/Scripts/Process/Thumbnail/Main.pyw @@ -0,0 +1,227 @@ +from sklearn import metrics +from sklearn.cluster import KMeans + +#-=-=-=-# + +def __GTL(Log: str, Info: str = "", End: str = "\n"): + return print("{2}<IMAGE>{3} {0:<50}{1}".format( + str(Log), str(Info) if Info else "", + Styles.Warning, Styles.Flaw, + ), end = End + ) + +def __StepSort(R: int, G: int, B: int, Repetitions: int = 1, Smooth: bool = True) -> tuple: + L = sqrt(0.241 * R + 0.691 * G + 0.068 * B) + H, S, V = rgb_to_hsv(R, G, B) + H2 = int(H * Repetitions) + L2 = int(L * Repetitions) + V2 = int(V * Repetitions) + if all((Smooth, H2 % 2)): + V2 = Repetitions - V + L = Repetitions - L + return (H2, L, V2) + +def __RGB2(IT): + IT = "#" + "".join(("{:02X}".format(x) for x in IT)) + return ColorHandler(IT) + +#-=-=-=-# + +Picture = Cover.convert("RGB") +ThumbChar = "β– " + +#-=-=-=-# + +# Calculate dimensions (aspect ratio) +Dimensions = Image.new("RGB", (16, 9), "red") +Dimensions = contain(Dimensions, (float("inf"), min(Picture.size))) +Size = Dimensions.size +__GTL("Calculated dimensions", " x ".join(map(str, Size))) + +#-=-=-=-# + +# --- USE COLOR ALGORITHM HERE --- # + +# PIL to CV2 +image = np.array(Picture) +image = image[:, :, ::-1].copy() +image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) +image = cv2.resize(image, (2 ** 7,) * 2) + +__GTL("Retrieving clusters...", End = "\r") +image_array = image.reshape((image.shape[0] * image.shape[1], 3)) +Cluster = KMeans(n_init = 10) +Cluster.fit(image_array) + +numLabels = np.arange(0, len(np.unique(Cluster.labels_)) + 1) +hist = np.histogram(Cluster.labels_, bins = numLabels)[0].astype("float") +hist /= hist.sum() + +# Very rare exception +# https://stackoverflow.com/a/10063039 + +Colors = [] +try: + zipped = sorted(zip(hist, Cluster.cluster_centers_)) + zipped.sort(reverse = 1, key = lambda x: x[0]) + hist, Cluster.cluster_centers = zip(*zipped) + + # Convert to list of RGB tuples + zipped = [list(x[1]) for x in zipped] + Colors = [tuple([int(y) for y in x]) for x in zipped] + #Colors = [tuple([int(y) // 1 for y in x]) for x in zipped] +except ValueError: + # Add individual resampling modes + for Mode in range(1, 5 + 1): + Colors += [contain(Picture, (2, 2), Mode).getpixel((0, 0))] + +# Remove grayscale occurences +if Cover.mode != "L": + __GO = 0 + for Grayscale in range(255): + Grayscale = (Grayscale,) * 3 + if Grayscale in Colors: + Colors.remove(Grayscale) + __GO += 1 + __GTL("Removed monochrome colors", f"{__GO} found") + +# Remove duplicates +__RD = len(Colors) +Colors = list(set(Colors)) +__RD = __RD - len(Colors) +__GTL("Removed duplicated colors", f"{__RD} found") + +# Sort +__CBS = Colors +Colors = sorted(Colors, key = lambda C: __StepSort(*C, 8, 0)) +Colors = dict(zip([__RGB2(x).saturation for x in Colors], Colors)) +Colors = list(dict(sorted(Colors.items())).values())[::-1] +__CBS = [i for i, x in enumerate(zip(Colors, __CBS)) if x[0] != x[1]] +__CBS = len(__CBS) if __CBS else 0 +__GTL("Sorted colors", f"{__CBS} changed its place") + +""" +# Balance primitively +__RD = [len(Colors), 0, 0] +for c in range(len(Colors)): + threshold = 6.25 + #---# + threshold /= 100 + threshold = (2 * threshold, 1 - threshold) + try: + c_ = __RGB2(Colors[c]) + #---# + if threshold[1] > c_.luminance: + Colors.remove(Colors[c]) + __RD[1] += 1 + #---# + if c_.luminance < threshold[0]: + Colors.remove(Colors[c]) + __RD[2] += 1 + except IndexError: + pass + +__RD[0] = __RD[0] - len(Colors) +__GTL("Balanced colors", f"{__RD[0]} removed ({__RD[2]} bright, {__RD[1]} dark)") +""" + +if not Colors: + for Mode in range(6): + Colors += [contain(Picture, (2, 2), Mode).getpixel((0, 0))] + +# COLOR SORTING TEST +# Create and show resized `Image` with every color from `Colors` +if args.color_sorting_test: + __GTL("Launched color sorting test") + __Counter = 0 + CSTI = Image.new("RGB", (len(Colors), 1), (0,) * 3) + for C in Colors: + CSTI.putpixel((__Counter, 0), C) + __Counter += 1 + SIZE = int(max(__geometry.split("+")[0].split("x"))) // 6 + CSTI = CSTI.resize((CSTI.size[0] * SIZE, CSTI.size[1] * SIZE), 0) + CSTI.show() + +# Determine color index +if args.color == 1: + args.color = 0 +if args.color == 2: + args.color = -3 + +BgCol = Colors[args.color] +BgCol = Image.new("RGB", (1, 1), tuple(BgCol)) +__GTL( + "Determined color", + __RGB2(BgCol.getpixel((0, 0))).hex_l.upper() +) + +# Apply brightness +BgCol = Brightness(BgCol).enhance(args.brightness) +__GTL("Applied brightness", " β”‚ ".join( + ( + str(args.brightness) + "x", + str(args.brightness * 100) + "%" + ) + ) +) + +# Apply saturation +BgCol = Color(BgCol).enhance(args.saturation) +__GTL("Applied saturation", " β”‚ ".join( + ( + str(args.saturation) + "x", + str(args.saturation * 100) + "%" + ) +)) + +BgColCover = contain(Picture, (2, 2)) +BgColCover = Color(BgColCover).enhance(4) +BgColCover = BgColCover.getpixel((0, 0)) + +#-=-=-=-# +# Specify color + +BgCol = BgCol.getpixel((0, 0)) +__BgCol = [] +__BgCol += [ + __RGB2(BgCol), + __RGB2(BgColCover[:3]) +] +__BgCol = [Color.hex_l.upper() for Color in __BgCol] +__GTL("Specified the color", __BgCol[0]) + +#-=-=-=-# +# Generate background +Background = Image.new("RGB", Size, BgCol) +__GTL( + "Generated background", + fg(*RGB(__BgCol[0])) + ThumbChar * 3 +) + +# Paste original picture +Background.paste( + Picture, ( + (Background.size[0] - Picture.size[0]) // 2, + (Background.size[1] - Picture.size[1]) // 2 + ), Picture.convert("RGBA") +) +__GTL( + "Pasted original picture", + "".join( + ( + fg(*RGB(__BgCol[0])) + ThumbChar, + fg(*RGB(__BgCol[1])) + ThumbChar, + fg(*RGB(__BgCol[0])) + ThumbChar + Styles.Flaw + ) + ) +) + +#-=-=-=-# + +if args.resize_thumbnail: + if max(Background.size) > 1280: + __GTL('Resized to "MaxResDefault.jpg" size', "1280 x 720") + Background = contain(Background, (1280, 720), 3) + +Background.convert("RGB").save(Thumbnail_Path, quality = 100, optimize = 1) +__GTL("Saved image", FM.Utils.Get.Size(os.path.getsize(Thumbnail_Path))) \ No newline at end of file diff --git a/Data/Scripts/Process/Thumbnail/Setup.pyw b/Data/Scripts/Process/Thumbnail/Setup.pyw new file mode 100644 index 0000000..12d8c76 --- /dev/null +++ b/Data/Scripts/Process/Thumbnail/Setup.pyw @@ -0,0 +1,122 @@ +Cover = Image.open(Cover) + +try: + Cover.seek(1) +except EOFError: + Traceback = "" +else: + Traceback = "static" + Cover.seek(0) + +#-=-=-=-# + +if Traceback: + Traceback = f"Cover image is not {Traceback}" + Error(Traceback) + +Cover_Process = Cover.copy() +Cover_Copy = os.path.join(_TMP_DIR, f"YTMVG_{__RAND_STR}.png") + +#-=-=-=-# + +print("{1}<INFO>{4} Making Thumbnail... β”‚ {2}1/3{4} β”‚ {1}0:00:00.000{4} β”‚ {0}0.00 KB (-0.00 KB / -0.00%){3}".format( + Styles.OK, Styles.Info, Styles.Meta_Info_2, + Styles.Flaw, Styles.Reset + ) +) +__START_THUMB = time() + +# Rescaling Cover +if max(Cover.size) > args.resolution: + Cover_Process.thumbnail((args.resolution,) * 2, 1) + print("{2}<WARNING> {3}Cover dimensions ({0}) exceeded maximum video resolution ({1}p), downscaling...{4}".format( + "x".join(map(str, Cover.size)), args.resolution, + Styles.Info, Styles.Warning, Styles.Reset + ) + ) + +Cover_Process.save(Cover_Copy, quality = 100) + +#-=-=-=-# + +# Make Thumbnail +__THUMB_NAME = f"Thumbnail.jpg" +Thumbnail_Path = os.path.join(Directory, __THUMB_NAME) + +exec(open_("Process/Thumbnail/Main")) + +#-=-=-=-# + +Size_In_Thumbnail = os.path.getsize(Thumbnail_Path) +Size_In_Thumbnail_1 = os.path.getsize(Thumbnail_Path) +print("\n{3}<INFO>{6} Making Thumbnail... β”‚ {4}2/3{6} β”‚ {3}{0}{6} β”‚ {2}{1} (+{1} / +100.00%){5}".format( + str(td(seconds = time() - __START_THUMB))[:-3], + FM.Utils.Get.Size(Size_In_Thumbnail), + Styles.OK, Styles.Info, Styles.Meta_Info_2, + Styles.Flaw, Styles.Reset + ) +) + +# Optimize Thumbnail +if Size_In_Thumbnail > 2048E3: + os.system('{package} -m 100 -S2047 -o --all-progressive --strip-all --dest="{image_out_dir}" "{image_in}" {verbosity}'.format( + package = __JPEGOptim, + verbosity = Verbose[0], + + image_in = Thumbnail_Path, + image_out_dir = Directory + ) + ) +else: + print("{0}<INFO>{1} Thumbnail image file size is below 2.00 MB, not optimizing.".format( + Styles.Info, Styles.Reset + ) + ) + +# Re-optimize Thumbnail +Size_In_Thumbnail = os.path.getsize(Thumbnail_Path) +if Size_In_Thumbnail > 2048E3: + print("{1}<WARNING> {2}Thumbnail size exceeded 1.99 MB ({0}), will recompress to β‰ˆ1.85 MB.{3}".format( + FM.Utils.Get.Size(Size_In_Thumbnail), + Styles.Info, Styles.Warning, Styles.Flaw + ) + ) + os.system('{package} -m 100 -S1895 -o --all-progressive --strip-all "{image_in}" {verbosity}'.format( + package = __JPEGOptim, + verbosity = Verbose[0], + + image_in = Thumbnail_Path + ) + ) + +#-=-=-=-# + +# Print information +Size_Out_Thumbnail = os.path.getsize(Thumbnail_Path) +print("\n{5}<INFO>{8} Making Thumbnail... β”‚ {6}3/3{8} β”‚ {5}{0}{8} β”‚ {4}{1} (-{2} / -{3}%){7}".format( + str(td(seconds = time() - __START_THUMB))[:-3], + + FM.Utils.Get.Size(Size_Out_Thumbnail) if Size_Out_Thumbnail > 2048E3 else "-0.00 KB", + FM.Utils.Get.Size(Size_In_Thumbnail_1 - Size_Out_Thumbnail), + Percentage(Size_Out_Thumbnail, Size_In_Thumbnail_1), + + Styles.OK, Styles.Info, Styles.Meta_Info_2, + Styles.Flaw, Styles.Reset + ) +) +print("{0}Done!{1}".format(Styles.OK, Styles.Reset)) + +#-=-=-=-# + +# Move Thumbnail +if not args.no_thumbnail: + New_Thumbnail_Path = os.path.join(Final_Directory, __THUMB_NAME.replace(f"_{__RAND_STR}.", ".")) + os.rename( + Thumbnail_Path, + New_Thumbnail_Path + ) + Thumbnail_Path = New_Thumbnail_Path + +#-=-=-=-# + +Cover = Cover_Copy \ No newline at end of file diff --git a/Data/Scripts/Process/Video.pyw b/Data/Scripts/Process/Video.pyw new file mode 100644 index 0000000..b47217b --- /dev/null +++ b/Data/Scripts/Process/Video.pyw @@ -0,0 +1,106 @@ +Video_Names = [] +for Path in ("Video", Audio_Names[0]): + Name = os.path.join(Final_Directory, Path) + if len(Name) > 252: + Name = Name[:-4] + print("{0}<WARNING>{2} {1}Video final path exceeds 256 characters, name will be truncated.{2}".format( + Styles.Info, Styles.Warning, Styles.Reset + ) + ) + Video_Names += [f"{Name}.mp4"] + +#-=-=-=-# + +# Make Video +print("{1}<INFO>{4} Making Video... β”‚ {2}1/3{4} β”‚ {1}0:00:00.000{4} β”‚ {0}0.00 KB (-0.00 KB / -0.00%){3}".format( + Styles.OK, Styles.Info, Styles.Meta_Info_2, + Styles.Warning, Styles.Reset + ) +) + +__START_VIDEO = time() + +os.system(""" + {package} -r 12 -i "{audio_in}" -loop 1 -i "{image_in}" + -ab {audio_quality} -c:a {audio_codec} -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" + -tune stillimage -pix_fmt yuv420p + -shortest -strict -2 "{video_out}" -y {verbosity} + """[2:-2].replace("\n\t", " ").format( + package = __FFmpeg, + verbosity = Verbose[1], + + audio_in = Audio, + image_in = Cover, + video_out = Video_Names[0], + + audio_quality = Audio_Quality, + audio_codec = Audio_Codec + ) +) + +#-=-=-=-# + +# Trim Duration +Size_In_Video = os.path.getsize(Video_Names[0]) +End_Time = str(round(mFile(Video_Names[0]).info.length, 3)) + +print("\n{3}<INFO>{6} Making Video... β”‚ {4}2/3{6} β”‚ {3}{0}{6} β”‚ {2}{1} (+{1} / +100.00%){5}".format( + str(td(seconds = time() - __START_VIDEO))[:-3], FM.Utils.Get.Size(Size_In_Video), + Styles.OK, Styles.Info, Styles.Meta_Info_2, + Styles.Warning, Styles.Reset + ) +) + +# WebM optimization setup +if args.webm_encode: + Video_Names[1] = Video_Names[1].rstrip(".mp4") + ".webm" + + Video_Codec = "libvpx-vp9" + # Video_Codec = "libvpx-vp8" + Audio_Codec = "libvorbis" + +os.system(""" + {package} -r 12 -i "{video_in}" -t {video_ending} + -c:v {video_codec}{video_quality} {video_scaleFix} + -c:a {audio_codec}{audio_quality} -ac {audio_channels} + -fflags +bitexact -flags:v +bitexact -flags:a +bitexact + -map 0 -map_metadata 0:s:0 -shortest -strict -2 "{video_out}" -y {verbosity} + """[2:-2].replace("\n\t", " ").format( + package = __FFmpeg, + verbosity = Verbose[1], + + video_in = Video_Names[0], + video_out = Video_Names[1], + video_codec = Video_Codec, + video_ending = End_Time, + video_quality = " -q:v 5" if args.webm_encode else "", + video_scaleFix = '-vf "scale={0}:-1:flags=bilinear"'.format(args.resolution), + + audio_codec = Audio_Codec, + audio_quality = "" if args.webm_encode else f" -ab {Audio_Quality}", + audio_channels = Channels + ) +) + +#-=-=-=-# + +# Print Information +Size_Out_Video = os.path.getsize(Video_Names[1]) +print("\n{5}<INFO>{8} Making Video... β”‚ {6}3/3{8} β”‚ {5}{0}{8} β”‚ {4}{1} (-{2} / -{3}%){7}".format( + str(td(seconds = time() - __START_VIDEO))[:-3], + + FM.Utils.Get.Size(Size_Out_Video), FM.Utils.Get.Size(Size_In_Video - Size_Out_Video), + Percentage(Size_Out_Video, Size_In_Video), + + Styles.OK, Styles.Info, Styles.Meta_Info_2, + Styles.Warning, Styles.Reset + ) +) +print("{0}Done!{1}".format( + Styles.OK, Styles.Reset + ) +) + +#-=-=-=-# + +os.remove(Video_Names[0]) \ No newline at end of file diff --git a/Data/Scripts/Utils/Directory/Make.pyw b/Data/Scripts/Utils/Directory/Make.pyw new file mode 100644 index 0000000..29c8863 --- /dev/null +++ b/Data/Scripts/Utils/Directory/Make.pyw @@ -0,0 +1,13 @@ +ID = str(time()).split(".")[-1].zfill(7) + +#-=-=-=-# + +Audio_Names = [] +Audio_Names += [".".join(os.path.basename(Audio).split(".")[:-1])] +Audio_Names += ["_".join((*Audio_Names[0].split(), ID))] + +Final_Directory = os.path.join(Directory, Audio_Names[1]) + +#-=-=-=-# + +os.mkdir(Final_Directory) \ No newline at end of file diff --git a/Data/Scripts/Utils/Directory/Open.pyw b/Data/Scripts/Utils/Directory/Open.pyw new file mode 100644 index 0000000..e1a408e --- /dev/null +++ b/Data/Scripts/Utils/Directory/Open.pyw @@ -0,0 +1,35 @@ +if os.sys.platform == "win32": + open_command = r"start /max C:\Windows\explorer.exe" + + if not args.no_video: + open_command += " /select," +elif os.sys.platform.startswith("linux"): + distro = distro_name() + if distro == "ubuntu": + open_command = "nautilus" + elif distro == "debian": + open_command = "nemo" + elif distro == "rhel": + open_command = "gnome-open" + else: + open_command = "xdg-open" +else: + open_command = "open" + +#-=-=-=-# + +# Null device +if os.sys.platform == "win32": + null_device = "" +else: + null_device = ">/dev/null 2>&1" + +if args.no_video: + open_target = Final_Directory +else: + open_target = Video_Names[-1] + +#-=-=-=-# + +open_command += ' "{0}" {1}'.format(open_target, null_device) +os.system(open_command) \ No newline at end of file diff --git a/Data/Scripts/Utils/Main/File_Manager.pyw b/Data/Scripts/Utils/Main/File_Manager.pyw new file mode 100644 index 0000000..dc70b47 --- /dev/null +++ b/Data/Scripts/Utils/Main/File_Manager.pyw @@ -0,0 +1,143 @@ +class FM: + """Various functions for files managing.""" + + class Utils: + """Utility functions.""" + + def Cleanup_Directory(Directory: os.path.abspath, Ignore_Formats: tuple): + """Clears non-directory files and removes empty folders.""" + Formats = tuple(("." + Format.lower() for Format in tuple(Ignore_Formats))) + try: + for File in os.listdir(Directory): + File = os.path.join(Directory, File) + #-=-=-=-# + if not File.lower().endswith(Formats): + if os.path.isfile(File): + os.remove(File) + else: + if not os.listdir(File): + os.rmdir(File) + except PermissionError: + pass + + return + + #-=-=-=-# + + class Get: + """Grabbing Values from files.""" + + def Size(Bytes: int) -> str: + """Returns human-readable file size.""" + for Unit in ("", "K", "M", "G", "T"): + if Bytes < 1024: + break + Bytes /= 1024 + + return str(round(Bytes, 2)) + " " + Unit + "B" + + def File(Path: os.path.abspath, Verbose: bool = False) -> str: + """File download handler.""" + if Path.lower().startswith(("http://", "https://", "ftp://")): + Path = Path.split("//") + Path[1] = utils.quote(Path[1]).strip("/") + Path = "//".join(Path) + try: + # Normalize URL + File_Name = utils.unquote(Path.split("/")[-1]) + for Delimiter in (("?", "&", "#")): + File_Name = File_Name.split(Delimiter)[0] + File_Location = os.path.join(_TMP_DIR, File_Name) + + # Download + with get(Path, stream = 1) as Site: + if Site.ok: + if Site.headers["content-type"].split()[0].split(";")[0].split("/")[0].lower() == "audio": + with open(File_Location, "wb") as File: + if Verbose: + print("{2}<INFO>{3} Downloading {0}...{1}".format( + File_Name, " " * 32, + Styles.Info, Styles.Reset + ) + ) + for Chunk in Site.iter_content(chunk_size = 1024): + if Chunk: + File.write(Chunk) + + return File_Location, 1 + else: + Error("Provided URL is not an audio file.") + else: + Error("Failed to fetch the URL due to {0} status code. ({1})".format( + Site.status_code, Site.reason.title() + ) + ) + except exceptions.ConnectionError: + Error("Could not fetch the URL due to internet connection problems.") + except exceptions.MissingSchema: + Error("Failed to analyze the URL - please check for potential misspelling and try again!") + + return Path, 0 + + def Path(Path: os.path.abspath) -> str: + """Absolute path getter with additional user and variables expansion.""" + Path = os.path.expandvars(Path) # Windows + Path = os.path.expanduser(Path) # Linux + Path = os.path.abspath(Path) # Full + Path = str(path(Path).resolve()) # Normalize + + return Path + + def hideFile(Path: os.path.abspath) -> str: + """Hides a file or a directory.""" + if os.sys.platform == "win32": + return ctypes.windll.kernel32.SetFileAttributesW(File, 2) + + #-=-=-=-# + + class Upload: + """File uploading manager.""" + + def Media(Path: os.path.abspath, Method: type, Type: str) -> str: + """Media uploader and verification handler.""" + if os.path.exists(Path): + if os.path.isfile(Path): + try: + Method(Path) + Traceback = "" + except Exception: + Traceback = f"Not an {Type} file" + else: + Traceback = "Not a file" + else: + Traceback = "File doesn't exist" + + if Traceback: + raise Error('{0}! ("{1}")'.format(Traceback, Path)) + + return Path + +#-=-=-=-# + +# Temp File directory +_TMP_DIR = "~/AppData/Local/Temp" if os.sys.platform == "win32" else "/tmp" +_TMP_DIR = FM.Utils.Get.Path(_TMP_DIR) + +#-=-=-=-# +# Initial directories +Initial_Directory = Config["Settings"]["Directory"]["Initial"] + +# Initial audio directory +if Initial_Directory["Audio"]: + __INI_DIR_AUD = Initial_Directory["Audio"] +else: + __INI_DIR_AUD = "~/Music" + +# Initial image directory +if Initial_Directory["Image"]: + __INI_DIR_IMG = Initial_Directory["Image"] +else: + __INI_DIR_IMG = "~/" + ("Pictures" if os.sys.platform == "win32" else "Downloads") + +Initial_Directory["Audio"] = FM.Utils.Get.Path(__INI_DIR_AUD) +Initial_Directory["Image"] = FM.Utils.Get.Path(__INI_DIR_IMG) \ No newline at end of file diff --git a/Data/Scripts/Utils/Main/Internet.pyw b/Data/Scripts/Utils/Main/Internet.pyw new file mode 100644 index 0000000..022c519 --- /dev/null +++ b/Data/Scripts/Utils/Main/Internet.pyw @@ -0,0 +1,22 @@ +# This file can be removed without any consequences, but it's not recommended. +# +# Besides update notificator it also contains the message fetcher that will be +# used to inform users about future plans of the program, along with informations +# including packages changes/deprecation and such. +try: + # Update notice + with get(f"https://api.github.com/repos/{__Repo}/releases") as Site: + if Site.ok: + __version_latest__ = Site.json()[0]["tag_name"] + + if float(__version_latest__) > float(__version__): + print("{1}<WARNING>{2} You are using not using recent version of the program. ({0})".format(__version_latest__, Styles.Info, Styles.Warning)) + print("Please consider updating if possible - updates may contain bug fixes and new features!{0}\n".format(Styles.Reset)) + + # Notification + with get(f"https://raw.githubusercontent.com/{__Repo}/master/Data/Scripts/Utils/Notification.pyw") as Site: + if Site.ok: + eval(Site.text) + print("\n") +except exceptions.ConnectionError: + pass \ No newline at end of file diff --git a/Data/Scripts/Utils/Main/Main.pyw b/Data/Scripts/Utils/Main/Main.pyw new file mode 100644 index 0000000..665b88c --- /dev/null +++ b/Data/Scripts/Utils/Main/Main.pyw @@ -0,0 +1,111 @@ +Config = load(open("Data/Config.json", encoding = "U8")) + +#-=-=-=-# + +session = Session() +session.headers.update( + { + "User-Agent": + "Mozilla/5.0 (Windows NT 10.0; Win32; x32) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36" + } +) +get = session.get + +#-=-=-=-# + +RGB = lambda col: tuple([round(Value * 255) // 1 for Value in ColorHandler(col).rgb]) + +class Styles: + """Colored Prints.""" + OK = "#0C0" + Info = "#4AF" + Flaw = "#F25" + Error = "#C10" + Warning = "#FC0" + Meta_Info = "#888" + Meta_Info_2 = "#93F" + +for Variable_Name in list(vars(Styles))[2:-2]: + Variable = getattr(Styles, Variable_Name) + __clr = fg(*RGB(Variable)) + + if Variable_Name.lower().startswith(("flaw", "err", "warn")): + __clr = ef.b + __clr + + exec('{0}.{1} = "{2}"'.format(Styles.__name__, Variable_Name, __clr)) + +Styles.Reset = fg.rs + ef.rs + +Image.MAX_IMAGE_PIXELS = float("inf") +ImageFile.LOAD_TRUNCATED_IMAGES = 1 + +os.system("") +os.sys.platform = os.sys.platform.lower() +stdout_ = os.sys.stdout + +#-=-=-=-# + +def Variable_Search(Query: str.lower, Variable: os.environ = "PATH") -> str: + """Searches for `Content` in `Variable` environment variable.""" + Query = Query.lower() + #-=-=-=-# + if os.sys.platform == "win32": + for Key in os.environ[Variable].split(os.pathsep): + if f"{Query}.exe" in Key.lower(): + if os.path.exists(Key): + if os.path.isfile(Key): + Value = str(path(Key).resolve()) + break + else: + Value = "" + else: + try: + import apt + cache = apt.Cache() + if cache[Query].is_installed: + Value = Query + else: + Value = "" + except ImportError: + Value = Query + #-=-=-=# + return Value + +def Percentage(Part: float, Whole: float) -> str: + """Returns `Part` of `Whole`.""" + RetVal = "0.00" + if Part != Whole: + RetVal = round((100 - (Part / Whole) * 100), 2) + return str(RetVal) + +def Clamp(Number: float, Minimum: float, Maximum: float) -> float: + """Limits `Number` in range (`Minimum`, `Maximum`).""" + return min(max(Minimum, Number), Maximum) + +def Error(Traceback: str) -> SystemExit: + """Custom `SystemExit` wrapper.""" + raise SystemExit("{1}{0}{2}\a".format( + Traceback, + Styles.Error, Styles.Reset + ) + " " * 32 + ) + +def ArgParseBool(Boolean: bool) -> str: + """Converts default bool type to argument parser one.""" + return "store_" + str(bool(Boolean)).lower() + +def Random_String(Length: int = 16) -> str: + """Random string generation.""" + return "".join(choice(printable[0:62]) for String in range(Length)) + +def __FixTitle(String: str) -> str.title: + return " ".join([Element[0].upper() + Element[1:] for Element in String.split()]) + +#-=-=-=-# + +__Repo = "/".join((__author__, __name__)) +__BreakString = Styles.Reset + "\n" + "─" * 32 + "\n" + +__ALLOWED_FORMATS = "MP3", "FLAC", "OGG" +__RAND_STR = Random_String(8) +__FILES_TO_REMOVE = [] \ No newline at end of file diff --git a/Data/Scripts/Utils/Main/Tkinter.pyw b/Data/Scripts/Utils/Main/Tkinter.pyw new file mode 100644 index 0000000..5e90700 --- /dev/null +++ b/Data/Scripts/Utils/Main/Tkinter.pyw @@ -0,0 +1,15 @@ +Icon = os.path.abspath("Documents/Pictures/Icons/Icon.png") + +#-=-=-=-# + +try: + root = Tk() + root.withdraw() + root.call("wm", "iconphoto", root._w, PhotoImage(file = Icon)) + + root.update_idletasks() + root.winfo_screenwidth() + root.attributes("-fullscreen", 1) + root.state("iconic") +except TclError: + pass \ No newline at end of file diff --git a/Data/Scripts/Utils/Packages_Location.pyw b/Data/Scripts/Utils/Packages_Location.pyw new file mode 100644 index 0000000..e4ca1b3 --- /dev/null +++ b/Data/Scripts/Utils/Packages_Location.pyw @@ -0,0 +1,8 @@ +for Requirement in ("JPEGOptim", "FFmpeg"): + exec(""" + __{0} = "{0}".lower() + __{0} = Variable_Search(__{0}) + if not __{0}: + Error("{0} not found!") + """[2:-2].replace("\n\t", "\n").format(Requirement) + ) \ No newline at end of file diff --git a/Documents/ChangeLog.md b/Documents/ChangeLog.md new file mode 100644 index 0000000..1c9667f --- /dev/null +++ b/Documents/ChangeLog.md @@ -0,0 +1,62 @@ +Legend: +- ♾️ | Google Colab notebook changes. + +--- + +## 1.2 +### Added βž• +- **Name of the processed file.** +- **Description generator support for all supported file formats.** +- Update notice. +- Notification system. +- **Experimental URL support.** +- **WebM support.** (`-webm` / `--webm-encode`) +### Modified πŸ” +- Logging system. +- Some format strings. +- Google Colab notebook. ♾️ +- Explorer file selection command. +### Fixed πŸ“ +- NT explorer shell extension videos directory. +- Display of paths in console. +- Initial directories mapping. +- Tkinter icon display. +- **Losless encoding.** +### Removed 🚫 +- Support for involved people in the description file generator. + +## 1.1 +### Added βž• +- Shortcut creator for single-use processing. +- Command line file loading logs. +- `Saturation` option. +- Issue template. +- Primitive video audio channels detection. +- **ID3-based description generator.** +- [**Windows Context Menu Extension**](../#presets-%EF%B8%8F). +- [**Presets**](../#explorer-shell-extension-%EF%B8%8FF). +### Modified πŸ” +- Improved: + - **Color selection algorithm.** + - Package detection. + - Icons quality. + - Thumbnail size reduction. + - **Video audio quality.** + - Program overall speed. +- Renamed: + - `Utility/Batch_Processing.py` β†’ `Utility/!_GUI_Batch_Processing.pyw` +- Google Colab notebook. ♾️ +- Verbosity option. +### Fixed πŸ“ +- **`Utility/GUI_Batch_Processing.py`** +- Display of thumbnail size reduction information. +- Maximum video resolution. +- `KeyboardInterrupt` at startup. +- Non-NT OS package detection. +### Removed 🚫 +- `Alternative` color option. +- `no-information` argument. +- **`WAV` file support.** + +## 1.0 +- Initial relese. \ No newline at end of file diff --git a/Documents/Pictures/Examples/Google_Colab/Cover.png b/Documents/Pictures/Examples/Google_Colab/Cover.png new file mode 100644 index 0000000..f2cbd35 Binary files /dev/null and b/Documents/Pictures/Examples/Google_Colab/Cover.png differ diff --git a/Documents/Pictures/Examples/Google_Colab/Thumbnail.jpg b/Documents/Pictures/Examples/Google_Colab/Thumbnail.jpg new file mode 100644 index 0000000..f2488c0 Binary files /dev/null and b/Documents/Pictures/Examples/Google_Colab/Thumbnail.jpg differ diff --git a/Documents/Pictures/Examples/Shell_Extension.png b/Documents/Pictures/Examples/Shell_Extension.png new file mode 100644 index 0000000..2dd9333 Binary files /dev/null and b/Documents/Pictures/Examples/Shell_Extension.png differ diff --git a/Documents/Pictures/Examples/Shell_ExtensionOriginal.png b/Documents/Pictures/Examples/Shell_ExtensionOriginal.png new file mode 100644 index 0000000..689e8a6 Binary files /dev/null and b/Documents/Pictures/Examples/Shell_ExtensionOriginal.png differ diff --git a/Documents/Pictures/Icons/Icon.png b/Documents/Pictures/Icons/Icon.png new file mode 100644 index 0000000..e4cc917 Binary files /dev/null and b/Documents/Pictures/Icons/Icon.png differ diff --git a/Documents/Pictures/Icons/Icon_HQ.ico b/Documents/Pictures/Icons/Icon_HQ.ico new file mode 100644 index 0000000..3332af2 Binary files /dev/null and b/Documents/Pictures/Icons/Icon_HQ.ico differ diff --git a/Documents/Pictures/YTMVG.svg b/Documents/Pictures/YTMVG.svg new file mode 100644 index 0000000..5eeb635 --- /dev/null +++ b/Documents/Pictures/YTMVG.svg @@ -0,0 +1 @@ +<svg viewBox="0 0 95.25 66.721" xmlns="http://www.w3.org/2000/svg"><path d="M93.14846 10.45435a11.97249 11.97249 0 0 0-8.43015-8.43016C77.32406 0 47.56847 0 47.56847 0s-29.7437.06549-37.13794 2.08372a11.97249 11.97249 0 0 0-8.43015 8.43016C-.2322 23.6473-1.09544 43.66297 2.0599 56.26653a11.97249 11.97249 0 0 0 8.43611 8.43015c7.3883 2.0242 37.13793 2.0242 37.13793 2.0242s29.74964 0 37.14389-2.0242a11.97249 11.97249 0 0 0 8.43016-8.43015c2.35758-13.15128 3.0839-33.14909-.05954-45.81218z" fill="#212121"/><path d="M47.63 10.84c-3.116 0-6.0502.58508-8.7906 1.7686-2.7407 1.1836-5.1238 2.7983-7.1512 4.8256-2.0274 2.0274-3.632 4.4108-4.814 7.1512-1.1813 2.7407-1.7664 5.6634-1.7664 8.7792 0 3.116.58504 6.0502 1.7664 8.7906 1.1836 2.7405 2.787 5.1236 4.814 7.1512 2.0274 2.0296 4.4105 3.6333 7.1512 4.814 2.7404 1.1814 5.6746 1.7686 8.7906 1.7686 3.1158 0 6.0385-.58508 8.7792-1.7686 2.7407-1.1836 5.1242-2.7868 7.1512-4.814 2.0274-2.0274 3.632-4.4107 4.814-7.1512 1.1813-2.7404 1.7798-5.6746 1.7798-8.7906 0-3.1158-.59628-6.0384-1.7798-8.7792-1.1814-2.7404-2.7866-5.124-4.814-7.1512-2.0274-2.0274-4.4105-3.6434-7.1512-4.8256C53.6685 11.425 50.7458 10.84 47.63 10.84zm0 5.6281c4.6924 0 8.6804 1.6449 11.965 4.9303 3.2848 3.2848 4.93 7.2725 4.93 11.965 0 4.6927-1.6448 8.6799-4.93 11.965-3.285 3.2847-7.2729 4.9303-11.965 4.9303-4.6929 0-8.6799-1.6448-11.965-4.9303-3.2848-3.2852-4.93-7.2724-4.93-11.965s1.6448-8.6804 4.93-11.965c3.2852-3.285 7.2722-4.9303 11.965-4.9303zm0 3.3838c-3.7543 0-6.9534 1.3141-9.5813 3.9418-2.6279 2.628-3.9418 5.8157-3.9418 9.5699 0 3.7541 1.3141 6.9419 3.9418 9.5696 2.628 2.628 5.827 3.942 9.5813 3.942 3.7542 0 6.9419-1.3141 9.5699-3.942 2.6277-2.6277 3.9418-5.8155 3.9418-9.5696 0-3.7542-1.3141-6.9419-3.9418-9.5699-2.628-2.6277-5.8157-3.9418-9.5699-3.9418z" fill="#FFF"/><path d="m55.51 28.85-7.8748 12.399-7.8928-12.395z" fill="red"/></svg> \ No newline at end of file diff --git a/Documents/YTMVG.ipynb b/Documents/YTMVG.ipynb new file mode 100644 index 0000000..ae0e38f --- /dev/null +++ b/Documents/YTMVG.ipynb @@ -0,0 +1,234 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "name": "YTMVG", + "provenance": [], + "collapsed_sections": [ + "3" + ] + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "1" + }, + "source": [ + "## Example πŸ–ΌοΈ\n", + "| Thumbnail | Video (*Β± Middle Frame*) |\n", + "|:---:|:---:|\n", + "| <img src=\"https://raw.githubusercontent.com/kubinka0505/YTMVG/master/Documents/Pictures/Examples/Google_Colab/Thumbnail.jpg\" height=200> | <img src= \"https://raw.githubusercontent.com/kubinka0505/YTMVG/master/Documents/Pictures/Examples/Google_Colab/Cover.png\" height=200> |\n", + "| *Subjectively basing on the image clusters, a<br>16:9 background is generated, onto the<br>center of which the image is placed.* | *Generates the video with dimensions that<br>match the input image, and appends<br>the specified audio to it.*|\n", + "\n", + "---\n", + "<br>\n", + "\n", + "### πŸ“± **Information for mobile users**\n", + "<font color=\"red\"><b>If cells don't output anything and are finished immediately, please re-run the site in the <code>Desktop site</code> mode</b></font> (Chrome)\n", + "\n", + "<br>\n", + "\n", + "---\n", + "<br>\n", + "\n", + "[![](https://img.shields.io/badge/github-open-lightgray?logo=github&logoColor=white&style=for-the-badge)](https://github.com/kubinka0505/YTMVG)" + ] + }, + { + "cell_type": "code", + "source": [ + "#@title # Download requirements πŸ“₯\n", + "\n", + "import os\n", + "\n", + "#-=-=-=-#\n", + "\n", + "!rm -rf YTMVG\n", + "!git clone https://github.com/kubinka0505/YTMVG\n", + "\n", + "os.chdir(\"YTMVG\")\n", + "!apt-get install -qq -o=Dpkg::Use-Pty=0 jpegoptim\n", + "print()\n", + "%pip install -r requirements.txt | grep -v \"already satisfied\"" + ], + "metadata": { + "cellView": "form", + "id": "2" + } + }, + { + "cell_type": "markdown", + "source": [ + "# Processing βš™οΈ" + ], + "metadata": { + "id": "3" + } + }, + { + "cell_type": "code", + "source": [ + "#@title # <font color=lime>**1.**</font> Setup βš™οΈ\n", + "\n", + "import os, warnings\n", + "from pathlib import Path\n", + "from zipfile import ZipFile\n", + "from google.colab import files\n", + "warnings.filterwarnings(\"ignore\")\n", + "\n", + "#-=-=-=-#\n", + "\n", + "if os.path.exists(\"YTMVG\"):\n", + "\tos.chdir(\"YTMVG\")\n", + "else:\n", + "\traise SystemExit(\"Requirements were not installed.\\nPlease run the previous cell.\")\n", + "\n", + "Audio_URL = \"\" #@param {type: \"string\"}\n", + "Image_URL = \"\" #@param {type: \"string\"}\n", + "\n", + "\n", + "#@markdown ---\n", + "#@markdown # Thumbnail *(background color)* πŸ–ΌοΈ\n", + "\n", + "Type = \"Wet\" #@param [\"Wet\", \"Dry\"]\n", + "Brightness = 40 #@param {type: \"slider\", min: 25, max: 75, step: 0.1}\n", + "Saturation = 100 #@param {type: \"slider\", min: 75, max: 250, step: 0.1}\n", + "Resize = True #@param {type: \"boolean\"}\n", + "Generate_Thumbnail = True #@param {type: \"boolean\"}\n", + "\n", + "#@markdown <br>\n", + "\n", + "#@markdown # Video πŸ“Ή\n", + "Maximum_Resolution = \"1080p\" #@param [\"4320p\", \"2160p\", \"1440p\", \"1080p\", \"720p\", \"480p\", \"360p\", \"240p\", \"144p\"]\n", + "WebM = False #@param {type: \"boolean\"}\n", + "Generate_Video = True #@param {type: \"boolean\"}\n", + "\n", + "#@markdown <br>\n", + "\n", + "#@markdown # Audio πŸ”Š\n", + "Bitrate = 255 #@param {type: \"slider\", min: 96, max: 256, step: 1}\n", + "\n", + "#@markdown <br>\n", + "\n", + "#@markdown # Desciption πŸ“\n", + "Generate_Description = True #@param {type: \"boolean\"}\n", + "\n", + "#@markdown ---\n", + "#@markdown # Program βš™οΈ\n", + "Debug = False #@param {type: \"boolean\"}\n", + "Verbose = False #@param {type: \"boolean\"}\n", + "Help = False #@param {type: \"boolean\"}\n", + "\n", + "#-=-=-=-#\n", + "\n", + "if not Debug:\n", + "\tif not Audio_URL:\n", + "\t\traise SystemExit(\"No audio URL was provided.\")\n", + "\n", + "#-=-=-=-#\n", + "\n", + "# URLs\n", + "os.environ[\"AUDIO\"] = Audio_URL\n", + "os.environ[\"IMAGE\"] = f'-i \"{Image_URL}\"' if Image_URL else \"\"\n", + "\n", + "# Thumbnail\n", + "os.environ[\"COLOR\"] = \"1\" if Type.lower() == \"dry\" else \"2\"\n", + "os.environ[\"BRIGHTNESS\"] = str(round(Brightness / 1, 2))\n", + "os.environ[\"SATURATION\"] = str(round(Saturation / 1, 2))\n", + "os.environ[\"RESIZE\"] = \"-rt\" if Resize else \"\"\n", + "os.environ[\"GEN_THUMB\"] = \"\" if Generate_Thumbnail else \"-nt\"\n", + "\n", + "# Video\n", + "os.environ[\"RESOLUTION\"] = Maximum_Resolution.strip(\"p\") + \"p\"\n", + "os.environ[\"WEBM\"] = \"-webm\" if WebM else \"\"\n", + "os.environ[\"GEN_VIDEO\"] = \"\" if Generate_Video else \"-nv\"\n", + "\n", + "# Audio\n", + "os.environ[\"BITRATE\"] = str(Bitrate)\n", + "\n", + "# Description\n", + "os.environ[\"GEN_DESC\"] = \"\" if Generate_Description else \"-nd\"\n", + "\n", + "# Program\n", + "os.environ[\"EXEC\"] = \"echo \" if Debug else os.sys.executable\n", + "os.environ[\"VERBOSE\"] = \"-v 2\" if Verbose else \"\"\n", + "os.environ[\"HELP\"] = \"-h\" if Help else \"\"" + ], + "metadata": { + "cellView": "form", + "id": "4" + } + }, + { + "cell_type": "code", + "source": [ + "#@title # <font color=gold>**2.**</font> Run ▢️\n", + "\n", + "!$EXEC \"YTMVG.py\" \\\n", + "\t-a \"$AUDIO\" -ab $BITRATE\\k \\\n", + "\t$IMAGE -r $RESOLUTION \\\n", + "\t-c $COLOR $RESIZE \\\n", + "\t-bgb $BRIGHTNESS\\% \\\n", + "\t-bgs $SATURATION\\% \\\n", + "\t$WEBM \\\n", + "\t$GEN_THUMB $GEN_VIDEO $GEN_DESC \\\n", + "\t$VERBOSE -nod $HELP\n", + "\n", + "#-=-=-=-#\n", + "\n", + "os.chdir(\"..\")" + ], + "metadata": { + "cellView": "form", + "id": "5" + } + }, + { + "cell_type": "code", + "source": [ + "#@title # <font color=lime></font> Download archive with files *(optional)* πŸ“₯\n", + "\n", + "from google.colab import files\n", + "\n", + "Latest_Directory = [str(Directory.resolve()) for Directory in Path(\"YTMVG/Videos\").glob(\"*\")]\n", + "Latest_Directory = sorted(Latest_Directory, key = os.path.getmtime)[-1]\n", + "\n", + "Archive_Name = \"_\".join((\"YTMVG\", os.path.basename(Latest_Directory)))\n", + "Archive_Name = Archive_Name.replace(\" \", \"_\") + \".zip\"\n", + "\n", + "#-=-=-=-#\n", + "\n", + "# Archive Creation\n", + "print(\"Making Archive...\")\n", + "with ZipFile(Archive_Name, \"w\", 14, 1, 9) as Archive:\n", + "\tfor File in Path(Latest_Directory).rglob(\"*\"):\n", + "\t\tFile = str(File.resolve())\n", + "\n", + "\t\tprint('\\tWriting \"{0}\"...'.format(\n", + "\t\t\tFile.split(os.getcwd())[-1])\n", + "\t\t)\n", + "\t\tArchive.write(File, os.path.basename(File))\n", + "\n", + "files.download(Archive_Name)\n", + "\n", + "#-=-=-=-#\n", + "\n", + "print(\"\\n\" + \"─\" * 32 + \"\\n\\nDone!\")" + ], + "metadata": { + "cellView": "form", + "id": "6" + } + } + ] +} \ No newline at end of file diff --git a/Example.mp3 b/Example.mp3 new file mode 100644 index 0000000..560e37f Binary files /dev/null and b/Example.mp3 differ diff --git a/License.txt b/License.txt new file mode 100644 index 0000000..1cf89f3 --- /dev/null +++ b/License.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + YTMVG - Pack of scripts providing customizable YouTube Music Videos generation + Copyright (C) 2023 kubinka0505 + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + YTMVG Copyright (C) 2023 kubinka0505 + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. \ No newline at end of file diff --git a/ReadMe.md b/ReadMe.md new file mode 100644 index 0000000..ba8beea --- /dev/null +++ b/ReadMe.md @@ -0,0 +1,127 @@ +<h1 align=center> + <img src=Documents/Pictures/YTMVG.svg width=175> + <br> + YTMVG +</h1> + +<p align=center> + <!--a href="https://shields.io/github/kubinka0505/YTMVG/blob/master/Documents/YTMVG.ipynb"><img src="https://shields.io/badge/Colab-Open-F9AB00?&logoColor=F9AB00&style=for-the-badge&logo=Google-Colab"></a--><a href="License.txt"><img src="https://custom-icon-badges.demolab.com/github/license/kubinka0505/YTMVG?logo=law&color=red&style=for-the-badge"></a> +</p> + +<p align=center> + <img src="https://custom-icon-badges.demolab.com/github/languages/code-size/kubinka0505/YTMVG?logo=database&style=for-the-badge">γ€€<a href="https://codeclimate.com/github/kubinka0505/YTMVG"><img src="https://shields.io/codeclimate/maintainability/kubinka0505/YTMVG?logo=Code-Climate&style=for-the-badge"></a>γ€€<a href="https://app.codacy.com/gh/kubinka0505/YTMVG"><img src="https://shields.io/codacy/grade/0b21f77d557f42bbaa447bca8d3b03f5?logo=Codacy&style=for-the-badge"></a> +</p> + +## Description πŸ“ +<a href="https://www.youtube.com/playlist?list=PLmKxR1vlf4cyHwtOvWxd1nt3B0U9E2pH7"> + <img align=right src="https://shields.io/badge/YouTube-Example_Playlist-F00?logo=YouTube&logoColor=FFF&style=for-the-badge"> +</a> + +Pack of scripts providing customizable **Y**ou**T**ube **M**usic **V**ideos **G**eneration. +~~But applicable to *Shorts* too.~~ + +It generates: +- Video from image and audio file, that also can contain the embedded front cover art. 🎦 +- Thumbnail with a centered image that background color is based on the subjectively selected image color clusters. πŸ–ΌοΈ + +--- + +## Requirements πŸ“₯ +Programs: +- [`Python >= 3.8`](https://www.python.org/downloads) 🐍 + +Modules: +- [`sty >= 1.0.4`](https://github.com/feluxe/sty) - Colored terminal output 🎨 +- [`colour >= 0.1.5`](https://github.com/vaab/colour) - Colors handling 🎨 +- [`distro >= 1.7`](https://github.com/python-distro/distro)<span>*</span> - Unix directory opening handler πŸ“‚ +- [`mutagen >= 1.45.1`](https://github.com/quodlibet/mutagen) - Audio state checker & video length handler ⏳ +- [`Pillow >= 9`](https://github.com/python-pillow/Pillow) - Image processor πŸ–ΌοΈ +- [`CV2`](https://github.com/opencv/opencv-python) - Image processor πŸ–ΌοΈ +- [`numpy`](https://github.com/numpy/numpy) - Colors histogram generation βš™οΈ +- [`scikit-learn`](https://github.com/scikit-learn/scikit-learn) - Colors histogram calculations βš™οΈ + +Packages (bold links are **Windows** static executable binaries): +- [**`FFmpeg >= 4.2`**](https://videohelp.com/software/ffmpeg/old-versions) - Video processing 🎦 + - **64-bit reccomended!** ([*possible memory allocation* failures](https://forum.doom9.org/archive/index.php/t-162236.html#copyright)) +- [**`JPEGOptim >= 1.4.7`**](https://github.com/tjko/jpegoptim) - Thumbnail optimization πŸ“‰ +- [`Python3-PIP`](https://packages.debian.org/sid/python3-pip)<span>*</span> +- [`Python3-TK`](https://packages.debian.org/sid/python3-tk)<span>*</span> + +<span>*</span> - Required on Linux + +## Installation βš™οΈ +**When on Linux**, install required packages by using this one-liner: +```bash +sudo apt-get install git python3-apt python3-pip python3-tk ffmpeg jpegoptim +``` +1. Clone the repository and move to its directory. + ```bash + git clone https://github.com/kubinka0505/YTMVG + cd YTMVG + ``` +2. Install required modules by inputting `pip install -r requirements.txt` +3. Modify the parameters in the `Config.json` file. (or use command line arguments below) +4. Type **`YTMVG.py -h`** for more info. ℹ️ + +--- + +## Usage πŸ“ +Process **audio** (`-a`) and **image** (`-i`) +```bash +YTMVG.py -a "~/Music/Song.mp3" -i "~/Pictures/Image.png" +``` + +As above, but set the **video resolution** (`-r`) to `720p` and **audio bitrate** (`-ab`) to **128 kb/s** +```bash +YTMVG.py -i "../Cover.jpg" -a "%UserProfile%\Downloads\Sound.ogg" -r 720p -ab 128k +``` + +Process **audio with embedded cover**, (no `-i`) **encode lossless audio** (`-ab 257`) and encode as WebM (`-webm`) +```bash +YTMVG.py -a "~/Music/Discography/Artist/Album/Artist - Title.flac" -ab 257 -webm +``` + +As above, but **process audio URL**, **change color** (`-c`) to `Dry` and **process silently** (`-v -1`) +```bash +YTMVG.py -a "https://website.com/Artist ft. Guest - Title (Remix).flac" -ab 257 -webm -c 1 -v -1 +``` + +### Presets πŸ—ƒοΈ +Program comes in with bundled presets located as text files in the [`Data/Presets`](Data/Presets) directory. You may edit them or add your own. + +> [!Note] +> To launch the preset, use the `-p` flag, where argument is the preset file name without last extension.<br><br> +> Example: `YTMVG.py -a ... -p MyPresetFile` (`Data/Presets/MyPresetFile.txt`) + +--- + +### **Windows Explorer Context Menu Extension** βš™οΈ +By running the [`!_GUI_Add.pyw`](Utility/Windows_Explorer_Context_Menu_Extension/!_GUI_Add.pyw) file, multiple values are injected into the `HKEY_CURRENT_USER` registry hive. +<br> +It enables quick, clear and **batch** usage directly from the `Explorer.exe` level, as shown below. + +<p align=center> + <br> + <img src=Documents/Pictures/Examples/Shell_Extension.png> + <br> +</p> + +### **Batch processing** πŸ—ƒοΈ +You can configure the [`!_GUI_Batch_Processing.py`](Utility/GUI_Batch_Processing.py) file for your needs. + +--- + +## Disclaimer ⚠️ + +> [!Important] +> This program is a free and open-source tool including implementation of the algorithm responsible for creating YouTube music videos and its thumbnails.<br><br> +> It uses other free open-source tools and resources available in the public domain to guarantee satisfactory results, albeit the author of this particular software is not affiliated with YouTube or its associates, nor can be responsible β€” as stated in the license file β€” for guaranteeing its correct behavior and the consequences resulting from its improper use. + +--- + +## Meta Info ℹ️ +All versions of this project have been tested on: +| OS | Distribution | OS Version | Python Version | System Architecture (`bits`) | +|:-:|:-:|:-:|:-:|:-:| +| Windows | ― | 10 | 3.11.0 | 64 | +| Linux | Ubuntu | LTS 22.04 | 3.10.6 | 64 | \ No newline at end of file diff --git a/Utility/!_GUI_Batch_Processing.py b/Utility/!_GUI_Batch_Processing.py new file mode 100644 index 0000000..f3d1e2c --- /dev/null +++ b/Utility/!_GUI_Batch_Processing.py @@ -0,0 +1,250 @@ +"""YTMVG Iterative Video Batch Processor.""" +import sys +from os import * +from PIL import Image +from pathlib import Path +from shutil import rmtree +from time import sleep, time +from mutagen import File as mFile +from distro import id as distro_name +from tkinter import Tk, PhotoImage, messagebox as MsgBox, filedialog as fd, TclError +chdir(path.abspath(path.dirname(__file__))) +del open + +#-=-=-=-=-=-# + +__name__ = open(__file__).readlines()[0].rstrip("\n").strip('"').strip(".") +__author__ = "kubinka0505" +__credits__ = __author__ +__version__ = "1.1" +__date__ = "01.01.2023" + +#-=-=-=-=-=-# + +# Directory with files +# +# Must contain at least one: +# - Audio file in formats below +# - Picture to be used as video, as above +Folder = r"" + +# YTMVG Location +YTMVG = r"../YTMVG.py" + +#-=-=-=-# + +# Searched file formats +Formats = { + "Audio": ("MP3", "FLAC", "OGG"), + "Image": ("PNG", "JPG", "JPEG", "WebP", "BMP") +} + +# Additional processing arguments +# !!! Use long names !!! +Arguments = "--color 1", "--no-bell" + +# Print commmands instead of execute +Debug = False + +# Open directory after processing +Open_Directory = True + +# Python name on Unix operating systems +Python_Name = "python3" + +#-=-=-=-=-=-# + +Icon = path.abspath("../Documents/Pictures/Icons/Icon.png") + +root = Tk() +root.withdraw() +try: + root.call("wm", "iconphoto", root._w, PhotoImage(file = Icon)) +except TclError: + pass + +#-=-=-=-=-=-# +# Functions + +def Get_Path(FilePath: str) -> str: + """Absolute path getter with additional user and variables expansion.""" + return str(Path(path.abspath(path.expanduser(path.expandvars(FilePath)))).resolve()) + +def Error(Traceback: str, Class: Exception = Exception) -> Exception: + __args = Class.__name__, Traceback + print("{0}: {1}".format(*__args)) + if name == "nt": + MsgBox.showerror(*__args) + raise SystemExit + +def __Title(Title: str): + if name == "nt": + system("title {0} ^| {1}".format(__name__, Title)) + +__Title("Waiting for directory...") + +#-=-=-=-=-=-# +# Tkinter prompt + +print("Waiting for directory...", end = "\r") +if not Folder: + Folder = fd.askdirectory( + title = "Select directory with audio files and cover art", + initialdir = path.expanduser("~/Music") + ) + if not Folder: + Error("Folder selection aborted.") + +#-=-=-=-=-=-# +# Variables + +YTMVG = Get_Path(YTMVG) +Folder = Get_Path(Folder) + +chdir(Folder) +print(f'Current working directory is "{getcwd()}"\n') +Output = path.abspath("_".join([ + "YTMVG", + path.basename(Folder), + str(time()).split(".")[-1].zfill(7) + ]) +) + +Counter = 1 +Arguments = [Argument.strip("-") for Argument in Arguments] +Arguments += ["no-thumbnail"] +Function = print if Debug else system +if name == "nt": + Python_Name = sys.executable + +Files = [] +Audio_Files = [] +Picture = "" + +print("Checking files...") +if path.exists(Folder): + for File in Path(Folder).glob("*"): + Files += [str(File.resolve())] +else: + Error(f'Directory doesn\'t exists! ("{Folder}")', OSError) + +#-=-=-=-=-=-# +# Add audio files + +print("Adding audio files...") +for Format in Formats["Audio"]: + for File in Files: + if File.lower().endswith(Format.lower()): + try: + print('\tVerifying "{File}"...', end = "\r") + _ = mFile(File).info.length + except AttributeError: + Error('File is broken. ("{0}")'.format(File.split(sep)[-1])) + Audio_Files += [File] + +Audio_Files = set(Audio_Files) +if Audio_Files: + print("\tDone, {0} file{1} found".format( + len(Audio_Files), + "s" if len(Audio_Files) > 1 else "" + ) + ) +else: + Error("Directory doesn't contain audio files!") + +#-=-=-=-=-=-# +# Get picture + +print("Specifying picture...") +for Format in Formats["Image"]: + for File in Files: + if File.lower().endswith(Format.lower()): + try: + print("\tVerifying...", end = "\r") + Image.open(File) + except OSError as err: + Error('File is broken. ("{0}")'.format(File.split(sep)[-1]), err.__class__.__name__) + Picture = File + break + +if Picture: + print(f'\t"{Picture}"') +else: + Error("Directory doesn't contain image file!", FileNotFoundError) + +print("\n{0}".format("-=" * 16 + "-")) + +#-=-=-=-=-=-# +# Processing + +for File in Audio_Files: + if not Debug: + __Message = f"Processing files... [{Counter}/{len(Audio_Files)}]" + print("\n" + __Message) + Counter += 1 + if Counter == len(Audio_Files): + Arguments.remove("no-thumbnail") + __Title(__Message) + Function(r'{0} "{1}" -a "{2}" -i "{3}" -d "{4}"{5} -v 0 -nod'.format( + Python_Name, YTMVG, + File, Picture, Output, + (" --" if Arguments else "") + " --".join(Arguments) + ) +) + +#-=-=-=-=-=-# +# Moving files + +if not Debug: + print("\n{0}".format("-=" * 16 + "-")) + print("\nMoving videos...") + for File in Path(Output).rglob("*.mp4"): + File = str(File.resolve()) + FileName = File.split(sep)[-1] + rename(File, path.join(Output, FileName)) + + print("Moving thumbnail...") + for File in Path(Output).rglob("*.jpg"): + File = str(File.resolve()) + FileName = File.split(sep)[-1] + try: + rename(File, path.join(Output, FileName)) + except OSError: + pass + + print("Removing folders...") + for Folder in next(walk(Output))[1]: + Folder = path.join(Output, Folder) + print("\t" + Folder) + rmtree(Folder) + +#-=-=-=-=-=-# +# Ending + +if not Debug: + for x in range(2): + sleep(.25) + print("\a", end = "\r") + + if name == "nt": + Command = r"start /max C:\Windows\explorer.exe" + elif os.sys.platform.startswith("lin"): + distro = distro_name + if distro == "ubuntu": + Command = "nautilus" + elif distro == "debian": + Command = "nemo" + elif distro == "rhel": + Command = "gnome-open" + else: + Command = "xdg-open" + else: + Command = "open" + Command += ' "{0}"'.format(Output) + if Open_Directory: + system(Command) + + if name == "nt": + if len(sys.argv) > 2: + print() + system("pause") \ No newline at end of file diff --git a/Utility/!_GUI_Make_Shortcut.pyw b/Utility/!_GUI_Make_Shortcut.pyw new file mode 100644 index 0000000..a3ca77b --- /dev/null +++ b/Utility/!_GUI_Make_Shortcut.pyw @@ -0,0 +1,59 @@ +exec(open("__init__.pyw", encoding = "U8").read()) + +with redirect_stdout(None): + from pyshortcuts import make_shortcut + +Initial_Directory = path.abspath(path.expanduser("~/Desktop")) + +#---# + +Folder = fd.askdirectory( + title = "Select directory to create the shortcut in", + initialdir = Initial_Directory +) +Folder = path.abspath(Folder) + +if Folder == getcwd(): + Folder = Initial_Directory + raise SystemExit("Directory selection aborted.") + +chdir(Folder) + +#---# + +Name = "YTMVG" +try: + for Shortcut in next(walk("."))[2]: + if Shortcut.startswith(Name + ".lnk"): + print("Removing previous shortcut...") + remove(path.abspath(Shortcut)) + break +except IndexError: + pass + +#---# + +print("Making shortcut...") +make_shortcut( + script = Main_File + ' -a ""', + name = Name, + description = "Generate the YouTube Music Video", + icon = Icon_HQ, + folder = Folder, + terminal = 1, + startmenu = 0, +) + +#---# + +Message = 'Successfully created shortcut in the "' + Folder.split(sep)[-1] + '" directory.' +print(Message) + +if __file__.lower().endswith("pyw"): + MsgBox.showinfo( + title = "Success", + message = Message, + ) +elif name == "nt": + print() + system() \ No newline at end of file diff --git a/Utility/Windows_Explorer_Context_Menu_Extension/!_GUI_Add.pyw b/Utility/Windows_Explorer_Context_Menu_Extension/!_GUI_Add.pyw new file mode 100644 index 0000000..6bcc128 --- /dev/null +++ b/Utility/Windows_Explorer_Context_Menu_Extension/!_GUI_Add.pyw @@ -0,0 +1,19 @@ +for File in "Init", "Main": + exec(open(f"__{File.lower()}__.pyw", encoding = "U8").read()) + +#-=-=-=-=-=-=-=-=-=-=-# + +Message = """ +Successfully injected the values into the HKEY_CURRENT_USER hive. + +From now on, you can make the videos by selecting +{0} files WITH EMBEDDED FRONT COVER ART +and chosing the appropriate option from the "{1}" +dropdown menu by right-clicking. +"""[1:-1].format(" / ".join(Formats), Main_File_Name) + +print(Message) +if __file__.endswith(".pyw"): + MsgBox.showinfo("Success!", Message) +else: + system("pause") \ No newline at end of file diff --git a/Utility/Windows_Explorer_Context_Menu_Extension/__init__.pyw b/Utility/Windows_Explorer_Context_Menu_Extension/__init__.pyw new file mode 100644 index 0000000..1758aab --- /dev/null +++ b/Utility/Windows_Explorer_Context_Menu_Extension/__init__.pyw @@ -0,0 +1,124 @@ +__doc__ = """Registry Setter + +Script that allows batch values setting into the +Windows Registry editor with administrator privileges. + +Can be used as standalone `Registry_Set` function +(with modules) or as an ArgumentParser one. +""" + +import os, sys + +# Because I obviously can't have an icon in normal terms... +os.chdir("..") +exec(open("__init__.pyw", encoding = "U8").read()) +os.chdir(path.basename(path.dirname(__file__))) + +#-=-=-=-=-=-=-=-=-=-=-# + +__name__ = open(__file__).readlines()[0].strip('"').strip("\n") +__author__ = "kubinka0505" +__credits__ = __author__ +__version__ = "1.0" +__date__ = "12.05.2023" + +#-=-=-=-=-=-=-=-=-=-=-# + +# Non-NT OS handling +if name == "nt": + import pyuac + import ctypes + import winreg +else: + MsgBox.showerror("Error", "Windows Only!") + raise SystemExit() + +#-=-=-=-=-=-=-=-=-=-=-# + +# Main Class +class Registry: + Values = { + "Hives": { + "HKCR": "HKEY_CLASSES_ROOT", + "HKCU": "HKEY_CURRENT_USER", + "HKLM": "HKEY_LOCAL_MACHINE", + "HKU": "HKEY_USERS", + "HKCC": "HKEY_CURRENT_CONFIG" + }, + "Types": [ + "SZ", "Multi SZ", "Expand SZ", + "Binary", "D-Word", "Q-Word", + ] + } + + #-=-=-=-# + + def __init__(self, Path: str): + Main_Key = Path.replace("/", sep).strip(sep) + sep + Main_Key = Main_Key.split(sep) + for Short, Extended in self.__class__.Values["Hives"].items(): + Main_Key[0] = Main_Key[0].upper().replace(Short, Extended) + + self.Key = path.join(*Main_Key) + self.RegKey = getattr(winreg, Main_Key[0]), path.join(*Main_Key[1:]) + + + def set(self, Name: str = None, Value: str = None, Type: str = "SZ") -> tuple: + """Set the value.""" + __DefaultType = "SZ" + if not Type: + Type = __DefaultType + + for Value_Types in self.__class__.Values["Types"]: + Type = Type.replace("-", "") + Type = Type.upper().strip().replace(" ", "_").lstrip("REG_") + + Value_Types = Value_Types.replace("-", "") + Value_Types = Value_Types.upper().replace(" ", "_") + + if Type == Value_Types: + DisplayType = "REG_" + Type + Type = getattr(winreg, DisplayType) + break + + if not isinstance(Type, int): + Type = __DefaultType + + #-=-=-=-# + + winreg.CreateKey(*self.RegKey) + with winreg.OpenKey(*self.RegKey, 0, winreg.KEY_ALL_ACCESS) as Registry_Key: + winreg.SetValueEx(Registry_Key, Name, 0, Type, Value) + + return self.Key, Name, Value, DisplayType + + #-=-=-=-# + + def relcd(self, Target: str): + """Changes directory to relative.""" + Target = path.join(path.abspath(self.Key), Target) + Target = path.abspath(Target) + + self.Key = Target.split(getcwd())[1][1:].replace("/", sep) + self.RegKey = getattr(winreg, self.Key.split(sep)[0]), path.join(*self.Key.split(sep)[1:]) + + def cwd(self): + """Gets current key path.""" + return self.Key + + def dir(self): + """Gets current key name.""" + return path.dirname(self.Key) + + def hive(self): + """Gets current key hive.""" + return self.Key.split(sep)[0] + + def name(self): + """Gets current key name.""" + return path.basename(self.Key) + + getcwd = cwd + dirname = dir + basename = name + anchor = hive \ No newline at end of file diff --git a/Utility/Windows_Explorer_Context_Menu_Extension/__main__.pyw b/Utility/Windows_Explorer_Context_Menu_Extension/__main__.pyw new file mode 100644 index 0000000..bf727bd --- /dev/null +++ b/Utility/Windows_Explorer_Context_Menu_Extension/__main__.pyw @@ -0,0 +1,138 @@ +Keys = [] +Formats = "MP3", "OGG", "FLAC" + +for Key in f"Shell/{Main_File_Name}", f"ContextMenus/{Main_File_Name}": + Key = f"HKEY_CURRENT_USER/Software/Classes/*/{Key}" + Key = Key.replace("/", sep) + Keys += [Key] + +__Formats_String = [Format.lower() for Format in (Formats + [Formats[0]])] +__Formats_String = " OR System.FileExtension:=.".join(__Formats_String) +__Formats_String = __Formats_String.lstrip(f"{Formats[0].lower()} OR") + +#-=-=-=-=-=-# + +Prompt = MsgBox.askyesnocancel( + title = f"Add {Main_File_Name} to Explorer Context Menu", + message = """ + Do you want to select preset? + + Warning: Selecting preset will override the + settings associated with its certain options. + + See "ReadMe.md" for more information. + """[1:-1].replace("\t", ""), + icon = "warning", + default = "no" +) + +Preset = "" +if Prompt: + Presets = path.join(Main_File_Directory, "Data/Presets") + if not path.exists(Presets): + Presets = Main_File_Directory + + File = fd.askopenfilename( + title = "Select preset file", + initialdir = Presets, + filetypes = [ + ("Text files", "*.txt"), + ("All files", "*.*") + ], + defaultextension = "*.txt" + ) + Preset = "-p " + ".".join(path.basename(File).split(".")[:-1]) +elif Prompt == None: + exit() + +#-=-=-=-=-=-# + +Shell_Key = Registry(Keys[0]) +Shell_Key.set(None, Main_File_Name) +Shell_Key.set("AppliesTo", __Formats_String) +Shell_Key.set("ExtendedSubCommandsKey", path.join("*", Keys[1].split(f"{sep}*{sep}")[-1])) +Shell_Key.set("Icon", Icon_HQ) +Shell_Key.set("MultiSelectModel", "Document") + +#-=-=-=-# + +__CMD_KEY = "Commands/Make" +__CMD_VDTHB = "01_VideoAndThumbnail" +__CMD_VIDEO = "02_Video" +__CMD_THUMB = "03_Thumbnail" +__EXT_SUBKEY = path.join( + "*", + Keys[1].split(f"{sep}*{sep}")[-1], + __CMD_KEY.replace("/", sep) +) + +Config = { + "Shell": { + "01_Make_VideoAndThumbnail_01": ["Make Video and Thumbnail", "WMPLoc.dll,-1050", path.join(__EXT_SUBKEY, __CMD_VDTHB)], + "02_Make_Video_02": ["Make Video", "WMPLoc.dll,-503", path.join(__EXT_SUBKEY, __CMD_VIDEO)], + "03_Make_Thumbnail_03": ["Make Thumbnail", "WMPhoto.dll,-400", path.join(__EXT_SUBKEY, __CMD_THUMB)], + "04_SEP_01": [], + # Shell32.dll,-22 + # ImageRes.dll,-5334 + "05_Open_MainDirectory_01": ["Open YTMVG Main Directory", "Explorer.exe", "", fr'explorer.exe "{Main_File_Directory}"'], + # ImageRes.dll,-1005 + "06_Open_VideoDirectory_01": ["Open YTMVG Videos Directory", "WMPLoc.dll,-29557", "", r'explorer.exe "{0}"'.format(os.path.join(Main_File_Directory, "Videos"))], + }, + __CMD_KEY: { + __CMD_VDTHB: { + "01_CMD_01_MakeClusterC1_01": ["HD 1080p (Cluster 01)", "ImageRes.dll,-71", fr'py "{Main_File}" -a "%1" -r 1080p -c 1{Preset}'], + "02_CMD_02_MakeClusterC1_02": ["HD 1080p (Cluster 02)", "ImageRes.dll,-83", fr'py "{Main_File}" -a "%1" -r 1080p -c 2{Preset}'] + }, + __CMD_VIDEO: { + "03_CMD_03_MakeVideo2160_01": ["4K 2160p", "WMPLoc.dll,-503", fr'py "{Main_File}" -a "%1" -r 216p -nt -nd{Preset}'], + "04_CMD_04_MakeVideo1080_02": ["HD 1080p", "ImageRes.dll,-23", fr'py "{Main_File}" -a "%1" -r 1080p -nt -nd{Preset}'], + "05_CMD_05_MakeVideo720_03": ["HD 720p", "WMPLoc.dll,-29538", fr'py "{Main_File}" -a "%1" -r 720p -nt -nd'] + }, + __CMD_THUMB: { + "06_CMD_05_MakeThumbnailC1_01": ["Cluster 01", "Shell32.dll,-63001", fr'py "{Main_File}" -a "%1" -c 1 -nv -nd{Preset}'], + "07_CMD_06_MakeThumbnailC1_02": ["Cluster 02", "ImageRes.dll,-70", fr'py "{Main_File}" -a "%1" -c 2 -nv -nd{Preset}'] + } + } +} + +#-=-=-=-=-=-# + +for Setting, Value in Config.items(): + Context_Key = Registry(Keys[1]) + _CWD_1 = Context_Key.cwd() + + Context_Key.relcd(Setting) + if Setting == "Shell": + for Key, Values in Value.items(): + Context_Key.relcd(Key) + + if Values: + Context_Key.set(None, Values[0]) + Context_Key.set("Icon", Values[1]) + + if len(Values) > 3: + Context_Key.relcd("command") + Context_Key.set(None, Values[3]) + Context_Key.relcd("..") + elif len(Values) < 4: + Context_Key.set("ExtendedSubCommandsKey", Values[2]) + else: + Context_Key.set("CommandFlags", 8, "D-Word") + + Context_Key.relcd("..") + else: + Reg = Registry(_CWD_1 + f"/{Setting}") + _CWD_2 = Reg.cwd() + + for Name, Directory in Value.items(): + Reg = Registry(_CWD_2 + f"/{Name}/Shell") + + _CWD_3 = Reg.cwd() + for Name, Value in Directory.items(): + Reg = Registry(_CWD_3 + Name) + + Reg.set(None, Value[0]) + Reg.set("Icon", Value[1]) + + Reg.relcd("command") + Reg.set(None, Value[2]) \ No newline at end of file diff --git a/Utility/__init__.pyw b/Utility/__init__.pyw new file mode 100644 index 0000000..b7ccc8c --- /dev/null +++ b/Utility/__init__.pyw @@ -0,0 +1,42 @@ +from os import * +from pathlib import Path +from contextlib import redirect_stdout +from tkinter import Tk, PhotoImage, filedialog as fd, messagebox as MsgBox, TclError +del open + +#-=-=-=-# + +Main_File = path.abspath("../YTMVG.py") +Main_File_Directory = path.dirname(Main_File) +Main_File_Name = ".".join(path.basename(Main_File).split(".")[:-1]) + +# Won't even let me have the abspath of icon, ffs +Icon = path.join(Main_File_Directory, "Documents/Pictures/Icons/Icon.png") +Icon_HQ = path.join(Main_File_Directory, "Documents/Pictures/Icons/Icon_HQ.ico") + +#-=-=-=-# + +root = Tk() +root.withdraw() +try: + if path.exists(Icon_HQ): + root.iconbitmap(Icon_HQ) +except: + if path.exists(Icon): + root.call("wm", "iconphoto", root._w, PhotoImage(file = Icon)) + +#-=-=-=-# + +def Folder_Size(): + """Calculates folder size recursively""" + Files = [str(File.resolve()) for File in Path(".").rglob("*")] + Size = sum([os.path.getsize(File) for File in Files]) + return Size + +def File_Size(Bytes: float) -> str: + """Returns human-readable file size""" + for Unit in ["B", "KB", "MB", "GB", "TB"]: + if Bytes < 1024: + break + Bytes /= 1024 + return "{0} {1}".format(round(Bytes, 2), Unit) \ No newline at end of file diff --git a/Videos/Example_1/Example.mp4 b/Videos/Example_1/Example.mp4 new file mode 100644 index 0000000..90f3264 Binary files /dev/null and b/Videos/Example_1/Example.mp4 differ diff --git a/Videos/Example_1/Thumbnail.jpg b/Videos/Example_1/Thumbnail.jpg new file mode 100644 index 0000000..1a331d3 Binary files /dev/null and b/Videos/Example_1/Thumbnail.jpg differ diff --git a/Videos/Example_2/Example.mp4 b/Videos/Example_2/Example.mp4 new file mode 100644 index 0000000..52157e5 Binary files /dev/null and b/Videos/Example_2/Example.mp4 differ diff --git a/Videos/Example_2/Thumbnail.jpg b/Videos/Example_2/Thumbnail.jpg new file mode 100644 index 0000000..2a03c54 Binary files /dev/null and b/Videos/Example_2/Thumbnail.jpg differ diff --git a/Videos/Example_3/Example.mp4 b/Videos/Example_3/Example.mp4 new file mode 100644 index 0000000..92d5c65 Binary files /dev/null and b/Videos/Example_3/Example.mp4 differ diff --git a/Videos/Example_3/Thumbnail.jpg b/Videos/Example_3/Thumbnail.jpg new file mode 100644 index 0000000..1d006d8 Binary files /dev/null and b/Videos/Example_3/Thumbnail.jpg differ diff --git a/Videos/ReadMe.md b/Videos/ReadMe.md new file mode 100644 index 0000000..2e1c2e1 --- /dev/null +++ b/Videos/ReadMe.md @@ -0,0 +1,10 @@ +## Sources 🎦 +At the request of the owners, the multimedia sources used to generate example videos are attached below. + +--- + +| β„– | Image | Sound | +|:---:|:---:|:---:| +| 1 | <img src="https://picsum.photos/id/392/5580/3720" width=200></a><br><a href="https://picsum.photos/id/392/info">picsum.photos/id/392</a> | <a href="https://samplelib.com/sample-wav.html">sample-lib.com</a> πŸ”Š | +| 2 | <img src="https://picsum.photos/id/522/1500/2000" width=200></a><br><a href="https://picsum.photos/id/522/info">picsum.photos/id/522</a> | <a href="https://samplelib.com/sample-wav.html">file-examples.com</a> πŸ”Š | +| 3 | <img src="https://picsum.photos/id/667/4240/2832" width=200></a><br><a href="https://picsum.photos/id/667/info">picsum.photos/667</a> | <a href="https://file-examples.com/index.php/sample-audio-files/sample-mp3-download/">file-examples.com</a> πŸ”Š | \ No newline at end of file diff --git a/YTMVG.py b/YTMVG.py new file mode 100644 index 0000000..606f093 --- /dev/null +++ b/YTMVG.py @@ -0,0 +1,209 @@ +"""YouTube Music Video Generator + +Pack of scripts providing customizable +YouTube Music Videos generation.""" +__START = __import__("time").perf_counter() + +try: + import os + import logging + from math import sqrt + from json import load + from io import BytesIO + from argparse import * + from random import choice + from string import printable + from pathlib import Path as path + from time import sleep, perf_counter as time + from requests import Session, utils, exceptions + from datetime import datetime as dt, timedelta as td + from tkinter import Tk, PhotoImage, filedialog as fd, TclError + + if os.sys.platform == "win32": + import ctypes + + try: + # Commented lines has been moved to + # "Data/Scripts/Process/Thumbnail/Colors.pyw" + # script in order to optimize the program. + import cv2 + from sty import * + import numpy as np + #from sklearn import metrics + from PIL.ImageEnhance import * + from colorsys import rgb_to_hsv + from PIL import Image, ImageFile + from PIL.ImageOps import contain + from mutagen import File as mFile + #from sklearn.cluster import KMeans + from colour import Color as ColorHandler + + if os.sys.platform != "win32": + from distro import id as distro_name + + except ImportError as Error: + exit(f"{Error.__class__.__name__} - {Error}.\a") +except (EOFError, KeyboardInterrupt): + raise SystemExit() + +#-=-=-=-# + +__name__ = "".join((c for c in open(__file__).readlines()[0].strip('"').rstrip("\n") if c.isupper())) +__author__ = "kubinka0505" +__credits__ = __author__ +__version__ = "1.2" +__date__ = "10.10.2023" + +__BaseDir = os.path.abspath(os.path.dirname(__file__)) +os.chdir(__BaseDir) + +#-=-=-=-# + +def open_(File: os.path.abspath, Title: bool = True) -> open: + """File opening handler.""" + File = os.path.join(__BaseDir, "Data/Scripts", File + ".pyw") + #---# + FileName = File.replace(__BaseDir, "") + FileName = FileName.replace("_", " ") + FileName = FileName.replace(os.sep, "/")[1:] + #---# + if os.sys.platform == "win32": + os.system(f"title {__name__} ^| {FileName}") + return open(File, encoding = "U8").read() + +exec(open_("Utils/Main/Main")) + +__FileList = [ + "Utils/Main/File_Manager", + "Utils/Main/Tkinter", + "ArgParse/Main", + "ArgParse/Settings", + "Utils/Directory/Make", + "Utils/Main/Tkinter", + "Utils/Packages_Location" +] + +# Verbosity +__V = "-v -1", "-v=-1", "-v 0", "-v=0" +__V = not [x for x in __V if x in " ".join(os.sys.argv).lower()] +__H = any(("-h" in " ".join(os.sys.argv).lower(), len(os.sys.argv) < 2)) + +try: + __START_LOAD = time() + for File in __FileList: + if __V: + if not __H: + print('{1}<SETUP>{3} Loading {2}"{0}"{3} script...'.format( + File, + Styles.Info, Styles.Meta_Info, Styles.Reset + ) + " " * 32, end = "\r" + ) + exec(open_(File)) +except (EOFError, KeyboardInterrupt): + raise SystemExit() + +# Updater +try: + exec(open_("Utils/Main/Internet")) +except FileNotFoundError: + pass + +try: + # Begin + print('{2}<INFO>{3} Beggining processing the {1}"{0}"{3} file...'.format( + os.path.basename(args.audio), + Styles.OK, Styles.Info, Styles.Reset + ) + " " * 32 + ) + + print(__BreakString) + + #-=-=-=-# + + # Thumbnail + if args.no_thumbnail: + Thumbnail_Path = None + else: + exec(open_("Process/Thumbnail/Setup")) + print(__BreakString) + + # Description + if not args.no_description: + exec(open_("Process/Description/Setup")) + + # Video & Thumbnail + if not any((args.no_video, args.no_thumbnail)): + print(__BreakString) + + # Video + if not args.no_video: + try: + exec(open_("Process/Video")) + except KeyboardInterrupt: + FM.Utils.Cleanup_Directory(Directory, ["MD"]) + os.rename(Video_Names[0], Video_Names[1]) +except KeyboardInterrupt: + FM.Utils.Cleanup_Directory(Directory, ["MD"]) + #-=-=-=-# + print(__BreakString) + Error("YTMVG was interrupted by the user, exiting.") + +#-=-=-=-# + +# Cleanup +if os.path.basename(Directory) in os.listdir(): + FM.Utils.Cleanup_Directory(Directory, ["MD"]) + +# Remove temporary files +for File in __FILES_TO_REMOVE: + os.remove(File) + +#-=-=-=-# + +if args.directory != Directory: + import shutil + try: + os.makedirs(args.directory) + except OSError: + pass + shutil.move(Final_Directory, args.directory) + Final_Directory = os.path.join(args.directory, Audio_Names[1]) + +if not args.no_open_directory: + exec(open_("Utils/Directory/Open")) + +# Print information +print(__BreakString) + +Lines = { + "Video path": Video_Names[-1], + "Thumbnail path": str(Thumbnail_Path), + "Directory path": Final_Directory, + + "Runtime": Styles.Warning + str(td(seconds = time() - __START))[:-3] +} + +if args.no_video: + del Lines["Video path"] + +if args.no_thumbnail: + del Lines["Thumbnail path"] + +for Type, Line in Lines.items(): + Type = "{1}<INFO>{2} {0}".format(Type, Styles.Info, Styles.Reset) + Line = "{2}{0}{1}{3}".format( + Line, + "" if list(Lines.values())[-1] == Line else "\n", + Styles.Meta_Info, Styles.Reset + ) + for Element in (Type, Line): + print(Element) + +#-=-=-=-# + +os.sys.stdout = stdout_ + +__BeepTime = 2, 1 / 7 +for x in range(__BeepTime[0]): + print(BEL, end = "\r") + sleep(__BeepTime[1]) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3861605 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +sty >= 1.0.4 +colour >= 0.1.5 + +distro >= 1.7; sys_platform != "win32" +mutagen >= 1.45.1 + +Pillow >= 9 +opencv-python +numpy +scikit-learn \ No newline at end of file