Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
v0.0.3
  • Loading branch information
Thisal-D authored May 8, 2024
1 parent fb04dae commit 0885f18
Show file tree
Hide file tree
Showing 56 changed files with 3,910 additions and 0 deletions.
16 changes: 16 additions & 0 deletions functions/Accessible.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import os
from .getAvailableFileName import get_available_file_name
from .createDownloadDirectory import create_download_directory


def accessible(path: str) -> bool:
file = path + "\\" + get_available_file_name("pytube.pytube")
try:
create_download_directory(path)
with open(file, "w"):
pass
os.remove(file)
return True
except Exception as error:
print(f"@ Accessible.py : {error}")
return False
28 changes: 28 additions & 0 deletions functions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from .saveSettings import save_settings
from .getGeneralSettings import get_general_settings
from .getThemeSettings import get_theme_settings

from .Accessible import accessible

from .createDownloadDirectory import create_download_directory
from .getAvailableFileName import get_available_file_name
from .getValidFileName import get_valid_file_name
from .getConvertedPath import get_converted_path

from .getFormatedComboBoxValues import get_formated_combo_box_values
from .getSupportedDownloadTypes import get_supported_download_types
from .getThumbnails import get_thumbnails

from .getWindowScale import get_window_scale

from .sortDict import sort_dict
from .getConvertedSize import get_converted_size
from .getConvertedTime import get_converted_time

from .passCommand import pass_command
from .clearTempFiles import clear_temp_files

from .validateColor import validate_color
from .validateSimultaneousCount import validate_simultaneous_count
from .validateDownloadPath import validate_download_path
from .formatPath import format_path
11 changes: 11 additions & 0 deletions functions/clearTempFiles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import os


def clear_temp_files(temp_directory: str) -> None:
for file in os.listdir(temp_directory):
try:
if file != 'this directory is necessary':
os.remove(f"{temp_directory}\\{file}")
except Exception as error:
print("@1 clearTemp.py :", error)
pass
9 changes: 9 additions & 0 deletions functions/convertTime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def convertTime(s: int) -> str:
h = int(s/3600)
m = int((s - (h*3600)) / 60)
s = s - (h*3600) - (m*60)
if h>0:
converted_time = f"{h}:{m:0>2}:{s:0>2}"
else:
converted_time = f"{m}:{s:0>2}"
return converted_time
15 changes: 15 additions & 0 deletions functions/createDownloadDirectory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import os


def create_download_directory(path: str):
# print(path)
try:
if not os.path.exists(path):
sub_paths = path.split("\\")
for i in range(0, len(sub_paths)):
sub_path = "\\".join(sub_paths[0:i + 1])
if not os.path.exists(sub_path):
os.mkdir(sub_path)
except Exception as error:
print("@1 createDownloadDirectory.py : ", error)
raise BufferError("download path error :/")
13 changes: 13 additions & 0 deletions functions/formatPath.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def format_path(path: str):
path = path.strip().replace("/", "\\")
print(path)
while "\\\\" in path:
path = path.replace("\\\\", "\\")
paths = []
for path in path.split("\\"):
if path != " ":
paths.append(path)
path = "\\".join(paths)
if path.endswith("\\"):
path = path[0:-1]
return path
14 changes: 14 additions & 0 deletions functions/getAvailableFileName.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import os


def get_available_file_name(file_name_extension: str) -> str:
if os.path.exists(file_name_extension):
split_path = file_name_extension.split(".")
file_name, extension = ".".join(split_path[0:-1]), split_path[-1]
i = 0
while os.path.exists(f"{file_name} ({i}).{extension}"):
i += 1

return f"{file_name} ({i}).{extension}"
else:
return file_name_extension
4 changes: 4 additions & 0 deletions functions/getColor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def getColor(color, theme):
if theme == "Dark":
return color[1]
return color[0]
2 changes: 2 additions & 0 deletions functions/getConvertedPath.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def get_converted_path(path):
return path.replace("/", "\\")
16 changes: 16 additions & 0 deletions functions/getConvertedSize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from typing import Union


def get_converted_size(s: Union[int, float], decimal_points: int) -> str:
data_units = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]
index = 0

while len(str(int(s))) > 3 and (index+1) < len(data_units):
s = s / 1024
index += 1
if decimal_points > 0:
converted_size = f"{round(s, decimal_points)} {data_units[index]}"
else:
converted_size = f"{int(s)} {data_units[index]}"

return converted_size
11 changes: 11 additions & 0 deletions functions/getConvertedTime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def get_converted_time(s: int) -> str:
h = int(s / 3600)
m = int((s - (h * 3600)) / 60)
s = s - (h * 3600) - (m * 60)

if h > 0:
converted_time = f"{h}:{m:0>2}:{s:0>2}"
else:
converted_time = f"{m}:{s:0>2}"

return converted_time
11 changes: 11 additions & 0 deletions functions/getFormatedComboBoxValues.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from .getConvertedSize import get_converted_size


def get_formated_combo_box_values(supported_download_types):
combo_box_values = []

for data_dict in supported_download_types:
for data_key in data_dict:
combo_box_values.append(data_key + " | " + get_converted_size(data_dict[data_key], 1))

return combo_box_values
12 changes: 12 additions & 0 deletions functions/getGeneralSettings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import json
import os


def get_general_settings() -> dict:
general_settings_file_path = ".\\settings\\general.json"
general_settings = json.load(open(general_settings_file_path, "r"))

if not general_settings["download_directory"]:
general_settings["download_directory"] = f"C:\\Users\\{os.getlogin()}\\Downloads\\PyTube Downloader"
print(general_settings)
return general_settings
34 changes: 34 additions & 0 deletions functions/getSupportedDownloadTypes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import pytube


def to_dict(data) -> list[dict]:
data_list = []
for d in data:
data_list.append(
{value.split("=")[0]: value.split("=")[1] for value in str(d)[9:-1].replace('"', "").split(" ")})
return data_list


def get_supported_download_types(video_streams: pytube.StreamQuery) -> list[dict]:
data = to_dict(video_streams.all())

support_download_types = []
for stream_type in data:
if stream_type["type"] == "video":
try:
file_size = video_streams.get_by_resolution(stream_type["res"]).filesize
download_info = {stream_type["res"]: file_size}
if download_info not in support_download_types:
support_download_types.append(download_info)
except Exception:
pass

try:
audio_stream = video_streams.get_audio_only()
file_size = audio_stream.filesize
audio_bit_rate = f"{str(int(audio_stream.bitrate / 1024))}kbps"
support_download_types.append({audio_bit_rate: file_size})
except Exception:
pass

return support_download_types
26 changes: 26 additions & 0 deletions functions/getThemeSettings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import json


def list_to_tuple(data: dict):
for key in data.keys():
if type(data[key]) is dict:
for key2 in data[key].keys():
if type(data[key][key2]) is dict:
for key3 in data[key][key2].keys():
if type(data[key][key2][key3]) is list:
data[key][key2][key3] = tuple(data[key][key2][key3])
elif type(data[key][key2]) is list:
data[key][key2] = tuple(data[key][key2])
else:
if type(data[key]) is list:
data[key] = tuple(data[key])

print(data)
return data


def get_theme_settings():
file_name = ".\\settings\\theme.json"
settings = json.load(open(file_name, "r"))

return list_to_tuple(settings)
63 changes: 63 additions & 0 deletions functions/getThumbnails.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from .getAvailableFileName import get_available_file_name
from .getValidFileName import get_valid_file_name
from urllib import request
import tkinter
from PIL import Image, ImageDraw


def add_corners(im, rad):
circle = Image.new('L', (rad * 2, rad * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, rad * 2 - 1, rad * 2 - 1), fill=255)
alpha = Image.new('L', im.size, 255)
w, h = im.size
alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))
alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))
alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))
im.putalpha(alpha)
return im


def get_hover_thumbnail(thumbnail_download_path):
thumbnail_hover_temp = Image.open(thumbnail_download_path)
thumbnail_hover_path = ".".join(thumbnail_download_path.split(".")[0:-1]) + "-hover." + \
thumbnail_download_path.split(".")[-1]
thumbnail_hover_temp = thumbnail_hover_temp.convert("RGB")
thumbnail_hover_data = thumbnail_hover_temp.getdata()
thumbnail_hover_data_list = []
for item in thumbnail_hover_data:
item = list(item)
for index, i in enumerate(item):
if i + 30 < 256:
item[index] = i + 30
else:
item[index] = 255
thumbnail_hover_data_list.append(tuple(item))

thumbnail_hover_temp.putdata(thumbnail_hover_data_list)
thumbnail_hover_corner_rounded = add_corners(thumbnail_hover_temp, 6)
thumbnail_hover_corner_rounded.save(thumbnail_hover_path)
thumbnail_hover = tkinter.PhotoImage(file=thumbnail_hover_path)

return thumbnail_hover


def get_thumbnails(video):
thumbnail_url = video.thumbnail_url
thumbnail_download_path = get_available_file_name("./temp/" + get_valid_file_name(thumbnail_url) + ".png")
request.urlretrieve(thumbnail_url, thumbnail_download_path)

thumbnail_temp = Image.open(thumbnail_download_path)

if round(thumbnail_temp.width / 4 * 3) <= 480:
thumbnail_temp = thumbnail_temp.resize((113, 64), Image.Resampling.LANCZOS).crop((0, 8, 113, 56)).resize(
(113, 64))
else:
thumbnail_temp = thumbnail_temp.resize((113, 64), Image.Resampling.LANCZOS)

thumbnail_temp_corner_rounded = add_corners(thumbnail_temp, 6)
thumbnail_temp_corner_rounded.save(thumbnail_download_path)
thumbnail = tkinter.PhotoImage(file=thumbnail_download_path)

return thumbnail, get_hover_thumbnail(thumbnail_download_path)
8 changes: 8 additions & 0 deletions functions/getValidFileName.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def get_valid_file_name(url: str) -> str:
valid_file_name = url

replaces = ["\\", "/", ":", '"', "?", "<", ">", "|", "*"]
for re in replaces:
valid_file_name = valid_file_name.replace(re, "~")

return valid_file_name
5 changes: 5 additions & 0 deletions functions/getWindowScale.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import customtkinter as ctk


def get_window_scale(widget):
return 1 / ctk.ScalingTracker.get_widget_scaling(widget)
2 changes: 2 additions & 0 deletions functions/passCommand.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def pass_command(*args_):
pass
6 changes: 6 additions & 0 deletions functions/removeInvalidCharts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
def removeInvalidChars(url: str) -> str:
filename = url
replaces = ["\\", "/", ":", '"', "?", "<", ">", "|", "*"]
for re in replaces:
filename = filename.replace(re, "~")
return filename
7 changes: 7 additions & 0 deletions functions/saveSettings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import json


def save_settings(settings_file, settings):
file = open(settings_file, "w")
json.dump(obj=settings, fp=file, indent=8, sort_keys=True)
file.close()
31 changes: 31 additions & 0 deletions functions/sortDict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
def sort_dict(info: list[dict]) -> list[dict]:
video_keys = []
audio_keys = []
for data in info:
key = list(data.keys())[0]
if "kbps" in key:
audio_keys.append(key)
else:
video_keys.append(key)

for i in range(len(video_keys)):
for i2 in range(len(video_keys)-1):
if int(video_keys[i2][:-1]) < int(video_keys[i2 + 1][:-1]):
video_keys[i2], video_keys[i2+1] = video_keys[i2+1], video_keys[i2]

keys = video_keys+audio_keys
sorted_dict = []
index2 = 0
break_ = False
while True:
for dict_ in info:
if list(dict_.keys())[0] == keys[index2]:
sorted_dict.append(dict_)
index2 += 1
if index2 >= len(keys):
break_ = True
break
if break_:
break

return sorted_dict
15 changes: 15 additions & 0 deletions functions/validateColor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import tkinter as tk


def validate_color(color: str):
try:
normal, hover = color.split(",")
try:
tk.Button(fg=normal, bg=hover)
return True
except Exception as error:
print(f"@1 > validateColor.py : {error}")
return False
except Exception as error:
print(f"@2 > validateColor.py : {error}")
return False
Loading

0 comments on commit 0885f18

Please sign in to comment.