Compare commits

..

No commits in common. "OneDriveHLS" and "master" have entirely different histories.

3 changed files with 143 additions and 134 deletions

View File

@ -1,97 +0,0 @@
import os
from urllib.parse import urlparse
import urllib
from unidecode import unidecode
import subprocess
import glob
import shutil
import emoji
import re
from functools import reduce
import time
LIMIT = 20
def extractURL():
with open("external_links.txt", "r") as file:
url_list = file.read().splitlines()
return url_list
def writeToText(text):
with open("converted_links.txt", "a", encoding="utf-8", errors="ignore") as f:
f.write(f"{text}\n")
def replaceString(string):
repls = (".", " "), ("()", "")
return reduce(lambda a, kv: a.replace(*kv), repls, string)
def removeYearString(string):
pattern = r"\d{4}"
return re.sub(pattern, "", string)
def checkURLConverted(value, status):
if status:
emojitype = emoji.emojize(":check_mark_button:")
text = f"{value} - Stato : {emojitype} Convertito"
else:
emojitype = emoji.emojize(":cross_mark:")
text = f"{value} - Stato : {emojitype} Non Convertito {emojitype}"
writeToText(text)
def convertMP4toHLSFFmpeg(url,folder,subfolder):
limitCounter = 1
if (limitCounter % LIMIT) == 0:
time.sleep(3600)
# Encode URL
encoded_url = urllib.parse.quote(url)
# Extract the filename from the URL
filename = os.path.basename(urlparse(encoded_url).path)
# Remove the file extension from the filename
extractFileName = os.path.splitext(filename)[0]
# Decode Folder in More Human Friendly Name
decode_filename = urllib.parse.unquote(extractFileName)
decode_filename = urllib.parse.unquote(decode_filename)
decode_filename = unidecode(decode_filename.replace(".", " "))
convertedFileName = decode_filename.replace(" ", "")
convertedFileName = removeYearString(convertedFileName)
convertedFileName = replaceString(convertedFileName)
try:
ffmpeg_command = f"ffmpeg -i {url} -c:v copy -c:a aac -start_number 0 -hls_time 10 -hls_list_size 0 -f hls '{convertedFileName}.m3u8'"
subprocess.call(ffmpeg_command, shell=True)
os.makedirs(folder)
os.makedirs(os.path.join(folder, subfolder))
ts_files = glob.glob(f"/var/www/{convertedFileName}*.ts")
m3u8_files = glob.glob(f"/var/www/{convertedFileName}*.m3u8")
vtt_files = glob.glob(f"/var/www/{convertedFileName}*.vtt")
all_files = ts_files + m3u8_files + vtt_files
for file in all_files:
shutil.move(file, subfolder)
checkURLConverted(folder, status=True)
limitCounter += 1
except Exception:
checkURLConverted(folder, status=False)
if __name__ == "__main__":
convertMP4toHLSFFmpeg()

143
ffmpegHLS.py/ffmpeg_2.0.py Normal file
View File

@ -0,0 +1,143 @@
import sys
import pyfiglet
import pyfiglet.fonts
from rich.console import Console
from rich.table import Table
import os
import ffmpeg
import time
# import pkg_resources
# from pyimod03_importers import FrozenImporter
# if getattr(sys, 'frozen', False):
# pkg_resources.register_loader_type(FrozenImporter, pkg_resources.DefaultProvider)
console = Console()
class ConvertMultipleVideo():
def __init__(self):
self.files = []
self.convert_files_folder = ""
self.bitrate = ""
self.files_converted = 0
self.files_trovati = []
self.estensione_da_trovare = ""
self.estensione_da_convertire = ""
self.selected_profile_converter = ""
self.save_folder = ""
self.bitrate_list = {1:{"bitrate":"uguale","h265":"no","input_args":{"hwaccel": "nvdec","vcodec": "h264_cuvid","c:v": "h264_cuvid"},"output_args":{"vcodec": "h264_nvenc","c:v": "h264_nvenc","acodec": "aac","ab":"320k","max_muxing_queue_size":"9999"}}
,2:{"bitrate":"uguale","h265":"si","input_args":{"c:v": "hevc"},"output_args":{"vcodec": "h264_nvenc","c:v": "h264_nvenc","acodec": "aac","ab":"320k","pix_fmt":"yuv420p","max_muxing_queue_size":"9999"}}
,3:{"bitrate":"Scelta Utente","h265":"no","input_args":{"hwaccel": "nvdec","vcodec": "h264_cuvid","c:v": "h264_cuvid"},"output_args":{"vcodec": "h264_nvenc","c:v": "h264_nvenc","preset": "slow","crf": 23,"acodec": "aac","ab":"320k","tune":"film","b:v":"","max_muxing_queue_size":"9999"}}
,4:{"bitrate":"Scelta Utente","h265":"si","input_args":{"c:v": "hevc"},"output_args":{"vcodec": "h264_nvenc","c:v": "h264_nvenc","preset": "slow","crf": 23,"acodec": "aac","ab":"320k","tune":"film","b:v":"","pix_fmt":"yuv420p","max_muxing_queue_size":"9999"}}
,5:{"bitrate":"No NVENC (No GPU)","h265":"no","input_args":{},"output_args":{"vcodec":"copy","acodec": "aac","ab":"320k","strict":"2"},
},6:{"bitrate":"uguale (HLS)","h265":"no","input_args":{},"output_args":{"vcodec":"copy","acodec": "aac","start_number": 0,"hls_time":10,"hls_list_size":0,"f":"hls"},
}
}
@staticmethod
def startupMessage():
ascii_art = pyfiglet.figlet_format("# FFMPEG Video Converter #")
console.print(f"[bold green]{ascii_art}[/bold green]")
def cartella_save_file(self):
self.save_folder = console.input("[bold purple]Inserisci la cartella dove salvare i file [Premi ENTER o INVIO per usare la stessa cartella dei file] --> [/bold purple]")
if self.save_folder == "":
self.save_folder = self.convert_files_folder
if os.path.isdir(self.save_folder):
console.print(f"\nOk i file verranno salvati su {self.save_folder}",style="bold green")
else:
console.print("\n❌ La cartella non esiste! ❌ \nVerrá creata...",style="bold red")
time.sleep(0.3)
os.makedirs(self.save_folder)
console.print(f"\n✅ Cartella {self.save_folder} creata ✅...",style="bold green")
def convertVideo(self):
try:
console.input("\n[bold green]FFmpeg Video Converter Pronto. Premi ENTER per iniziare la conversione![/bold green]\n")
except KeyboardInterrupt:
console.print("\nUscita dal programma...",style="bold red")
sys.exit()
try:
input_args = self.bitrate_list[self.selected_profile_converter]["input_args"]
output_args = self.bitrate_list[self.selected_profile_converter]["output_args"]
for files in os.listdir(self.convert_files_folder):
if files.endswith(self.estensione_da_trovare):
video = os.path.splitext(files)[0]
output = os.path.join(self.convert_files_folder, files)
stream = ffmpeg.input(os.path.join(self.convert_files_folder, files), **input_args)
stream = ffmpeg.output(stream, os.path.join(self.save_folder, '') + video + self.estensione_da_convertire, **output_args)
ffmpeg.run(stream)
self.files.append(files)
self.files_converted += 1
if self.files_converted >1:
console.print(f"\nI files {self.files} sono stati convertiti in {self.estensione_da_convertire} correttamente! ✅",style="bold green")
print()
console.print(f"\nIn totale sono stati convertiti {self.files_converted} elementi",style="bold green")
else:
print()
console.print(f"✅ Il file {files} é stato convertito in {video}{self.estensione_da_convertire} correttamente! ✅\n",style="bold green")
except:
console.print("\nErrore!\n",style="bold red")
sys.exit()
def visualizza_codec(self):
console.print("\nSeleziona Il Bitrate...\nPossibili Scelte : \n",style="bold blue")
table = Table(show_header=True,header_style="bold green")
table.add_column("NUMERO SCELTA",style="blue",justify="center")
table.add_column("BITRATE",style="blue")
table.add_column("FILE IN H265",style="blue",justify="center")
for bitrate_id,bitrate_info in self.bitrate_list.items():
table.add_row(str(bitrate_id),str(bitrate_info["bitrate"]),str(bitrate_info["h265"]))
console.print(table)
def seleziona_codec(self):
try:
self.selected_profile_converter = int(console.input("[bold purple]Seleziona il numero scelto --> [/bold purple]"))
if self.selected_profile_converter == 3 or self.selected_profile_converter == 4:
self.bitrate = console.input("\n[bold purple]Seleziona Bitrate [Esempio : 1M 2M ecc...] --> [/bold purple]")
self.bitrate_list[self.selected_profile_converter]["output_args"]["b:v"] = self.bitrate
except:
print()
console.print("\nErrore!\n",style="bold red")
sys.exit()
def files_da_convertire(self):
self.estensione_da_trovare = console.input("\n[bold purple]Inserisci un'estensione da cercare e convertire [Esempio : .mp4 .mkv ecc...] --> [/bold purple]")
self.estensione_da_convertire = console.input("\n[bold purple]Inserisci un'estensione per convertire i video [Esempio : .mp4 .mkv ecc...] --> [/bold purple]")
for files in os.listdir(self.convert_files_folder):
if files.endswith(self.estensione_da_trovare):
self.files_trovati.append(files)
console.print(f"\nAbbiamo trovato questi File nel formato {self.estensione_da_trovare} : {files}\n",style="bold green")
else:
console.print(f"\nIl file {files} non ha estensione {self.estensione_da_trovare}!",style="red")
if self.files_trovati == []:
console.print("\nNessun File Trovato da Convertire...\n",style="bold red")
sys.exit()
def run(self):
self.cartella_save_file()
self.visualizza_codec()
self.seleziona_codec()
self.files_da_convertire()
self.convertVideo()
def initialize(self):
self.startupMessage()
try:
self.convert_files_folder = console.input("[bold purple]\nInserisci la cartella dove sono conservati i file --> [/bold purple]")
except KeyboardInterrupt:
print()
console.print("\nUscita dal programma...\n",style="bold red")
sys.exit()
else:
self.run()
video = ConvertMultipleVideo()
video.initialize()

View File

@ -1,37 +0,0 @@
import requests
from ffmpegHLS import convertMP4toHLSFFmpeg
LC_URL = "https://onedrive-vercel-index-nnyg.vercel.app/api/?path=/"
LC_FILEURL = "https://onedrive-vercel-index-nnyg.vercel.app/api/raw/?path=/"
session = requests.Session() # Avvio la Sessione
ROOT_FOLDER = input("Inserisci la cartella di Root : ")
def checkHLS(folder=""): # sourcery skip: move-assign
# print("CARTELLA :",folder)
apiURL = f"{LC_URL}{ROOT_FOLDER}/{folder}"
rawURL = f"{LC_FILEURL}{ROOT_FOLDER}/{folder}"
r = session.get(apiURL)
if r.status_code == 200:
r = r.json()
data = r["folder"]["value"]
if "next" in r:
while "next" in r:
nextLink = r["next"]
r = session.get(f"{apiURL}&next={nextLink}").json()
data.extend(r["folder"]["value"])
for elements in data:
fileorFolderName = requests.utils.quote(elements["name"])
if "stagione" in fileorFolderName.lower():
checkHLS(f"{folder}/{fileorFolderName}")
if(fileorFolderName.endswith(".mp4")):
# print("MP4 FILES : ",fileorFolderName)
# print(f"FULL URL : {rawURL}/{fileorFolderName}")
cartella_principale,sottocartella = folder.split("/")
# TODO: FFMPEG HLS CONVERTER
convertMP4toHLSFFmpeg(f"{rawURL}/{fileorFolderName}",cartella_principale,sottocartella)
checkHLS(fileorFolderName)
if __name__ == "__main__":
checkHLS()