-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlayout.py
More file actions
267 lines (209 loc) · 8.36 KB
/
Copy pathlayout.py
File metadata and controls
267 lines (209 loc) · 8.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# O que é um fork?
#Um fork é uma cópia de um projeto de software que permite modificá-lo independentemente do projeto original. Forks geralmente acontecem quando:
#A comunidade deseja implementar mudanças que o autor original não aceita ou não tem tempo para adicionar.
#O projeto original fica inativo, e alguém decide continuar o desenvolvimento.
#Divergências de visão entre os desenvolvedores originais e novos contribuintes.
#No caso de software open-source (código aberto), como o youtube-dl, qualquer pessoa pode fazer um fork, modificar o código e compartilhar sua #própria versão.
import yt_dlp
import tkinter as tk
import os
import time
import glob
import validators # verificar se a url é válida
from tkinter import Checkbutton, BooleanVar
from tkinter import ttk
from urllib.parse import urlparse
cor_1 = '#030303' # Preto
cor_3 = '#ffffff' # Branco
cor_5 = '#616161' # Cinza
cor_6 = '#23fa02' # verde
cor_7 = '#02faee' # ciano
cor_8 = '#f7f7e6' # sei não
# Janela principal
janela = tk.Tk()
# Configuração da janela
janela.title("URL Downloader")
janela.geometry("800x600") # Largura x Altura
janela.configure(bg=cor_3)
# Criando a label principal
label = tk.Label(janela, text="Baixe URLs da mídia de sua escolha", font=("Arial", 16), bg=cor_3, fg=cor_1)
label.pack()
# Criar o frame principal
frame = tk.Frame(janela, width=600, height=150, bg=cor_3)
frame.pack(side="top", padx=10, pady=10)
# Variável global para o estado do Checkbutton
apenas_audio = BooleanVar() # audio apenas
legendas = BooleanVar()
# Função para atualizar a tela
def Atualizar_tela():
# Limpar o conteúdo do frame atual
for widget in frame.winfo_children():
widget.destroy()
def Funcoes_botao(entrada):
url = entrada.get().strip()
if url:
if not validators.url(url):
print("URL inválida! Por favor, insira uma URL válida.")
return
# ListarFormatos(url)
Update_progress()
Download(url)
def Tela_inicial():
# Atualiza a tela e limpa widgets existentes no frame
Atualizar_tela()
entrada = tk.Entry(frame, font=("Arial", 14), width=30, bg=cor_8,fg=cor_1)
entrada.pack(pady=5)
botao = tk.Button(frame,
text='Download',
command=lambda: Funcoes_botao(entrada),
fg=cor_3,
bg=cor_6,
width=15,
height=2,
font=("Helvetica", 12, "bold"),
activebackground=cor_7,
activeforeground=cor_3,
relief="flat",
bd=4
)
botao.pack(side='top', padx=5)
check1 = Checkbutton(janela, text="Apenas Áudio (MP3)", variable=apenas_audio,bg=cor_8)
check1.pack()
check2 = Checkbutton(janela, text="Legendas (pt-BR)", variable=legendas, bg=cor_8)
check2.pack()
def Update_progress():
# Barra de progresso
progress = ttk.Progressbar(janela, orient="horizontal", length=300, mode="determinate")
progress.pack(pady=20)
for i in range(101):
progress['value'] = i # Atualiza a barra
janela.update_idletasks() # Atualiza a interface gráfica
janela.after(50) # Aguarda 50 milissegundos para dar a sensação de progresso
progress.destroy()
def Download(url):
dominio = urlparse(url).netloc
# ===============================
# BASE LOCAL (SEM GLOBAL)
# ===============================
base_opts = {
# JS necessário para player moderno
'js_runtimes': {'node': {}},
'remote_components': ['ejs:github'],
# FFmpeg
'ffmpeg_location': r'C:\ProgramData\chocolatey\bin\ffmpeg.exe',
# Estabilidade
'sleep_interval': 4,
'max_sleep_interval': 6,
'retries': 5,
'fragment_retries': 5,
}
# ===============================
# 1) DOWNLOAD VÍDEO / ÁUDIO
# ===============================
ydl_video_opts = dict(base_opts)
ydl_video_opts['outtmpl'] = 'downloads/%(title)s.%(ext)s'
if "youtube.com" in dominio or "youtu.be" in dominio:
if apenas_audio.get():
ydl_video_opts.update({
'format': 'bestaudio[ext=m4a]/bestaudio',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': 'downloads/youtube/%(title)s.%(ext)s',
})
else:
ydl_video_opts.update({
'format': '(bestvideo[ext=mp4]/best[ext=mp4])+(bestaudio[ext=m4a]/bestaudio)',
'merge_output_format': 'mp4',
'outtmpl': 'downloads/youtube/%(title)s.%(ext)s',
})
else:
ydl_video_opts.update({
'format': 'bestvideo+bestaudio/best',
'merge_output_format': 'mp4',
})
try:
with yt_dlp.YoutubeDL(ydl_video_opts) as ydl:
ydl.download([url])
print("Vídeo/áudio baixado com sucesso")
except yt_dlp.utils.DownloadError as e:
print(f"Erro no download do vídeo: {e}")
return
time.sleep(35)
# ===============================
# FUNÇÃO AUXILIAR: VERIFICA SRT
# ===============================
def legenda_existe():
return bool(glob.glob('downloads/youtube/*.srt'))
# ===============================
# 2) LEGENDAS — TENTATIVA SEM JS
# ===============================
if legendas.get():
ydl_sub_opts = dict(base_opts)
ydl_sub_opts.update({
# DESATIVA JS
'js_runtimes': {},
'remote_components': [],
'skip_download': True,
'writesubtitles': True,
'writeautomaticsub': True,
'subtitleslangs': ['pt-BR'],
'subtitlesformat': 'srt',
'outtmpl': 'downloads/youtube/%(title)s.%(ext)s',
'ignoreerrors': True,
'no_warnings': True,
'quiet': True,
'sleep_interval': 6,
'max_sleep_interval': 10,
'retries': 3,
'fragment_retries': 3,
})
with yt_dlp.YoutubeDL(ydl_sub_opts) as ydl:
ydl.download([url])
# ===============================
# 3) FALLBACK COM JS (SE NECESSÁRIO)
# ===============================
if not legenda_existe():
ydl_sub_opts_js = dict(base_opts)
ydl_sub_opts_js.update({
# JS ATIVO AQUI
'skip_download': True,
'writesubtitles': True,
'writeautomaticsub': True,
'subtitleslangs': ['pt-BR'],
'subtitlesformat': 'srt',
'outtmpl': 'downloads/youtube/%(title)s.%(ext)s',
'ignoreerrors': True,
'quiet': True,
})
try:
with yt_dlp.YoutubeDL(ydl_sub_opts_js) as ydl:
ydl.download([url])
print("Legenda obtida via fallback JS")
except yt_dlp.utils.DownloadError:
print("Legenda indisponível para este vídeo")
else:
print("Legenda obtida sem JS")
# def ListarFormatos(url):
# try:
# with yt_dlp.YoutubeDL({'listformats': None}) as ydl:
# info = ydl.extract_info(url, download=False)
# formatos = info.get('formats', [])
# print("Formatos disponíveis:")
# for formato in formatos:
# print(f"ID: {formato['format_id']}, Resolução: {formato.get('resolution', 'N/A')}, Extensão: {formato.get('ext', 'N/A')}")
# except Exception as e:
# print(f"Erro ao listar formatos: {e}")
#
Tela_inicial()
# Inicializar o projeto
janela.mainloop()
# bolar maneira de baixar video de outras midias alem do yt (ok)
# testes
# https://youtu.be/C6h0Qt329jI?si=YEP0SrQrm_g6eUuj
# https://www.tiktok.com/@zueirarrando/video/7436160671470914871?is_from_webapp=1&sender_device=pc
# https://www.twitch.tv/alanzoka/clip/BenevolentTawdryNightingaleCmonBruh-IhSaugl3kdXkyhtj
# https://youtu.be/HARmkzmXtfY?si=x02Oa9boc2kYBfif Testar a parte de legenda automatica
# https://youtu.be/QNJL6nfu__Q?si=Zl621fLLweAq-zQQ testar apenas audio mp3