pcdoido2 commited on
Commit
aa3603f
·
verified ·
1 Parent(s): 55a9953

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +490 -0
app.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import subprocess
3
+ import os
4
+ import random
5
+ import tempfile
6
+ import shutil
7
+ import time
8
+ import base64
9
+
10
+ st.set_page_config(page_title="TikTok Video Generator - PRO", layout="centered")
11
+
12
+ abas = ["🎬 Gerador de Vídeo", "📂 Gerenciador de Arquivos", "🔐 Admin"]
13
+ pagina = st.sidebar.radio("Escolha uma página:", abas)
14
+
15
+ CATEGORIAS = ["AVATAR WORLD", "BLOX FRUITS", "TOCA LIFE"]
16
+ BASE_ASSETS = "assets"
17
+ BASE_SALVOS = "uploaded_files"
18
+
19
+ os.makedirs("assets/musicas", exist_ok=True)
20
+ for cat in CATEGORIAS:
21
+ os.makedirs(os.path.join(BASE_ASSETS, cat, "cortes"), exist_ok=True)
22
+ os.makedirs(os.path.join(BASE_ASSETS, cat, "tutoriais"), exist_ok=True)
23
+ os.makedirs(os.path.join(BASE_SALVOS, cat), exist_ok=True)
24
+
25
+ if pagina == "🎬 Gerador de Vídeo":
26
+ st.title("🎥 TikTok Video Generator - PRO")
27
+
28
+ categoria_selecionada = st.selectbox("Escolha a categoria:", ["Selecione..."] + CATEGORIAS)
29
+ if categoria_selecionada == "Selecione...":
30
+ st.warning("👈 Por favor, selecione uma categoria antes de continuar.")
31
+ st.stop()
32
+
33
+ st.markdown("### 🎛️ Opções de Mídia")
34
+ usar_tutorial = st.checkbox("Ativar tutorial", value=True)
35
+ usar_fundo = st.checkbox("Ativar fundo", value=True)
36
+ usar_musica = st.checkbox("Ativar música", value=False)
37
+
38
+ path_cortes = os.path.join(BASE_ASSETS, categoria_selecionada, "cortes")
39
+ path_tutoriais = os.path.join(BASE_ASSETS, categoria_selecionada, "tutoriais")
40
+ path_musicas = os.path.join(BASE_ASSETS, "musicas")
41
+
42
+ cortes_files = [os.path.join(path_cortes, f) for f in os.listdir(path_cortes) if f.endswith(".mp4")]
43
+ tutoriais_files = [os.path.join(path_tutoriais, f) for f in os.listdir(path_tutoriais) if f.endswith(".mp4")]
44
+ musicas_files = [os.path.join(path_musicas, f) for f in os.listdir(path_musicas) if f.endswith(".mp3")]
45
+
46
+ if not cortes_files:
47
+ st.error("❌ Nenhum vídeo de corte encontrado. Use a aba Admin.")
48
+ else:
49
+ num_videos_finais = st.number_input("Quantos vídeos gerar?", 1, 10, 1)
50
+ duracao_final = st.number_input("Duração final (s)", 10, 300, 30)
51
+
52
+ st.write("## Configuração dos cortes")
53
+ aleatorizar = st.checkbox("🎲 Aleatorizar configurações por vídeo")
54
+ duracao_corte_min = st.slider("Duração mínima (s)", 1, 10, 3)
55
+ duracao_corte_max = st.slider("Duração máxima (s)", duracao_corte_min + 1, 20, 5)
56
+
57
+ zoom = st.slider("Zoom", 1.0, 2.0, 1.0, 0.1)
58
+ blur_strength = st.slider("Blur no fundo", 1, 50, 10)
59
+ velocidade_final = st.slider("Velocidade final", 0.5, 2.0, 1.0, 0.1)
60
+ crf_value = st.slider("Qualidade CRF", 18, 30, 23)
61
+
62
+ st.write("## Texto no Vídeo")
63
+ ativar_texto = st.checkbox("Ativar texto")
64
+ if ativar_texto:
65
+ texto_personalizado = st.text_input("Texto", "🔥 Siga para mais!")
66
+ posicao_texto = st.selectbox("Posição", ["Topo", "Centro", "Base"])
67
+ duracao_texto = st.radio("Duração do texto", ["Vídeo todo", "Apenas primeiros segundos"])
68
+ segundos_texto = st.slider("Segundos", 1, 30, 5) if duracao_texto == "Apenas primeiros segundos" else 0
69
+ cor_texto = st.color_picker("Cor do texto", "#FFFF00")
70
+ cor_sombra = st.color_picker("Cor da sombra", "#000000")
71
+ tamanho_texto = st.slider("Tamanho da fonte", 20, 100, 60, step=2)
72
+
73
+ st.write("## Filtros no fundo")
74
+ ativar_blur_fundo = st.checkbox("Ativar blur", value=True)
75
+ ativar_sepia = st.checkbox("Sépia")
76
+ ativar_granulado = st.checkbox("Granulado")
77
+ ativar_pb = st.checkbox("Preto e branco")
78
+ ativar_vignette = st.checkbox("Vignette")
79
+
80
+ with st.expander("🎨 Filtros Avançados"):
81
+ ativar_brilho = st.checkbox("Brilho extra")
82
+ ativar_contraste = st.checkbox("Contraste forte")
83
+ ativar_colorboost = st.checkbox("Cores intensas")
84
+ ativar_azul = st.checkbox("Filtro Azul")
85
+ ativar_quente = st.checkbox("Filtro Quente")
86
+ ativar_desaturar = st.checkbox("Desaturar")
87
+ ativar_vhs = st.checkbox("Efeito VHS")
88
+
89
+ st.write("## Outros efeitos")
90
+ ativar_espelhar = st.checkbox("Espelhar", True)
91
+ ativar_filtro_cor = st.checkbox("Ajuste de cor", True)
92
+ remover_borda = st.checkbox("Remover borda")
93
+ tamanho_borda = st.slider("Tamanho da borda (px)", 0, 200, 0, 5)
94
+
95
+ ativar_borda_personalizada = st.checkbox("Borda personalizada")
96
+ if ativar_borda_personalizada:
97
+ cor_borda = st.color_picker("Cor da borda", "#FF0000")
98
+ animacao_borda = st.selectbox("Animação", ["Nenhuma", "Pulsante", "Cor Animada", "Neon", "Ondulada"])
99
+
100
+ salvar_no_gerenciador = st.checkbox("Salvar no gerenciador de arquivos")
101
+ if st.button("Gerar Vídeo(s)", key="gerar_video_usuario"):
102
+ with st.spinner("🎬 Processando..."):
103
+ progresso = st.progress(0)
104
+ temp_dir = tempfile.mkdtemp()
105
+
106
+ def atualizar_barra(n, etapa, total_videos, total_etapas):
107
+ progresso.progress(min(100, int(((n + etapa / total_etapas) / total_videos) * 100)))
108
+
109
+ try:
110
+ cortes_names = cortes_files.copy()
111
+ tutorials_salvos = tutoriais_files.copy()
112
+ musicas_salvas = musicas_files.copy()
113
+
114
+ for n in range(num_videos_finais):
115
+ total_etapas = 6
116
+ etapa_atual = 0
117
+ tempo_total = 0
118
+ cortes_prontos = []
119
+ cortes_usados = []
120
+
121
+ if aleatorizar:
122
+ duracao_corte_min_n = random.randint(1, 5)
123
+ duracao_corte_max_n = random.randint(duracao_corte_min_n + 1, 8)
124
+ zoom_n = round(random.uniform(1.0, 1.5), 2)
125
+ blur_strength_n = random.randint(5, 30)
126
+ velocidade_final_n = velocidade_final
127
+ remover_borda_n = remover_borda and random.choice([True, False])
128
+ tamanho_borda_n = random.randint(0, 50) if remover_borda_n else 0
129
+ ativar_blur_fundo_n = random.choice([True, False])
130
+ ativar_espelhar_n = random.choice([True, False])
131
+ else:
132
+ duracao_corte_min_n = duracao_corte_min
133
+ duracao_corte_max_n = duracao_corte_max
134
+ zoom_n = zoom
135
+ blur_strength_n = blur_strength
136
+ velocidade_final_n = velocidade_final
137
+ remover_borda_n = remover_borda
138
+ tamanho_borda_n = tamanho_borda
139
+ ativar_blur_fundo_n = ativar_blur_fundo
140
+ ativar_espelhar_n = ativar_espelhar
141
+
142
+ # Etapa 1 - Fundo com ponto aleatório
143
+ if usar_fundo:
144
+ fundo_origem = random.choice(cortes_names)
145
+ fundo_convertido = os.path.join(temp_dir, f"fundo_convertido_{n}.mp4")
146
+ dur_proc = subprocess.run([
147
+ "ffprobe", "-v", "error", "-show_entries", "format=duration",
148
+ "-of", "default=noprint_wrappers=1:nokey=1", fundo_origem
149
+ ], stdout=subprocess.PIPE)
150
+ try:
151
+ dur_total = float(dur_proc.stdout.decode().strip())
152
+ ponto_inicio = random.uniform(0, max(0, dur_total - duracao_final))
153
+ except:
154
+ ponto_inicio = 0.0
155
+
156
+ subprocess.run([
157
+ "ffmpeg", "-ss", str(ponto_inicio), "-i", fundo_origem,
158
+ "-t", str(duracao_final),
159
+ "-vf",
160
+ "scale='if(gt(iw/ih,720/1280),max(720,iw),-2)':'if(gt(iw/ih,720/1280),-2,max(1280,ih))',"
161
+ "scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,fps=30",
162
+ "-preset", "ultrafast", "-crf", "25",
163
+ fundo_convertido
164
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
165
+ else:
166
+ fundo_convertido = os.path.join(temp_dir, f"fundo_vazio_{n}.mp4")
167
+ subprocess.run([
168
+ "ffmpeg", "-f", "lavfi", "-i", f"color=color=black:size=720x1280:d={duracao_final}:rate=30",
169
+ "-c:v", "libx264", "-t", str(duracao_final), "-preset", "ultrafast", "-crf", "25",
170
+ fundo_convertido
171
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
172
+ etapa_atual += 1
173
+ atualizar_barra(n, etapa_atual, num_videos_finais, total_etapas)
174
+
175
+ # Etapa 2 - Cortes
176
+ tentativas = 0
177
+ while tempo_total < duracao_final and tentativas < 100:
178
+ tentativas += 1
179
+ random.shuffle(cortes_names)
180
+ for c in cortes_names:
181
+ dur = subprocess.run([
182
+ "ffprobe", "-v", "error", "-show_entries", "format=duration",
183
+ "-of", "default=noprint_wrappers=1:nokey=1", c
184
+ ], stdout=subprocess.PIPE).stdout.decode().strip()
185
+ if not dur:
186
+ continue
187
+ try:
188
+ d = float(dur)
189
+ if d < duracao_corte_min_n + 0.5:
190
+ continue
191
+ duracao_aleatoria = random.uniform(duracao_corte_min_n, min(d, duracao_corte_max_n))
192
+ ini = random.uniform(0, d - duracao_aleatoria)
193
+ repetido = any(c == usado[0] and abs(ini - usado[1]) < 0.5 for usado in cortes_usados)
194
+ if repetido:
195
+ continue
196
+ out = os.path.join(temp_dir, f"cut_{random.randint(1000,9999)}.mp4")
197
+ subprocess.run([
198
+ "ffmpeg", "-ss", str(ini), "-i", c, "-t", str(duracao_aleatoria),
199
+ "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",
200
+ "-an", "-c:v", "libx264", "-preset", "ultrafast", "-crf", "30", out
201
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
202
+ cortes_prontos.append(out)
203
+ cortes_usados.append((c, ini, duracao_aleatoria))
204
+ tempo_total += duracao_aleatoria
205
+ if tempo_total >= duracao_final:
206
+ break
207
+ except:
208
+ continue
209
+
210
+ lista = os.path.join(temp_dir, f"lista_{n}.txt")
211
+ with open(lista, "w") as f:
212
+ for c in cortes_prontos:
213
+ f.write(f"file '{c}'\n")
214
+
215
+ video_raw = os.path.join(temp_dir, f"video_raw_{n}.mp4")
216
+ subprocess.run([
217
+ "ffmpeg", "-f", "concat", "-safe", "0", "-i", lista,
218
+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", "30", video_raw
219
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
220
+
221
+ etapa_atual += 1
222
+ atualizar_barra(n, etapa_atual, num_videos_finais, total_etapas)
223
+
224
+ # Etapa 3 - Filtros e Efeitos
225
+ filtros_main = ["scale=720:1280:force_original_aspect_ratio=decrease"]
226
+ if zoom_n != 1.0:
227
+ filtros_main.append(f"scale=iw*{zoom_n}:ih*{zoom_n}")
228
+ if ativar_espelhar_n:
229
+ filtros_main.append("hflip")
230
+ if remover_borda_n and tamanho_borda_n > 0:
231
+ filtros_main.append(f"crop=in_w-{tamanho_borda_n*2}:in_h-{tamanho_borda_n*2}")
232
+ if ativar_filtro_cor:
233
+ filtros_main.append("eq=contrast=1.1:saturation=1.2")
234
+ filtros_main.append("scale=trunc(iw/2)*2:trunc(ih/2)*2")
235
+ if ativar_borda_personalizada:
236
+ cor_ffmpeg = f"0x{cor_borda.lstrip('#')}FF"
237
+ filtros_main.append(f"drawbox=x=0:y=0:w=iw:h=ih:color={cor_ffmpeg}:t=5")
238
+
239
+ filtro_complex = f"[0:v]scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280"
240
+ if ativar_blur_fundo_n:
241
+ filtro_complex += f",boxblur={blur_strength_n}:1"
242
+ if ativar_sepia:
243
+ filtro_complex += ",colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131"
244
+ if ativar_granulado:
245
+ filtro_complex += ",noise=alls=20:allf=t+u"
246
+ if ativar_pb:
247
+ filtro_complex += ",hue=s=0.3"
248
+ if ativar_vignette:
249
+ filtro_complex += ",vignette"
250
+ if ativar_brilho:
251
+ filtro_complex += ",eq=brightness=0.05"
252
+ if ativar_contraste:
253
+ filtro_complex += ",eq=contrast=1.3"
254
+ if ativar_colorboost:
255
+ filtro_complex += ",eq=saturation=1.5"
256
+ if ativar_azul:
257
+ filtro_complex += ",colorbalance=bs=0.5"
258
+ if ativar_quente:
259
+ filtro_complex += ",colorbalance=rs=0.3"
260
+ if ativar_desaturar:
261
+ filtro_complex += ",hue=s=0.5"
262
+ if ativar_vhs:
263
+ filtro_complex += ",noise=alls=10:allf=t+u,format=yuv420p"
264
+
265
+ filtro_complex += "[blur];"
266
+ filtro_complex += f"[1:v]{','.join(filtros_main)}[zoomed];"
267
+ filtro_complex += "[blur][zoomed]overlay=(W-w)/2:(H-h)/2[base]"
268
+
269
+ if ativar_texto and texto_personalizado.strip():
270
+ y_pos = "100" if posicao_texto == "Topo" else "(h-text_h)/2" if posicao_texto == "Centro" else "h-text_h-100"
271
+ enable = f":enable='lt(t\\,{segundos_texto})'" if duracao_texto == "Apenas primeiros segundos" else ""
272
+ texto_clean = texto_personalizado.replace(":", "\\:").replace("'", "\\'")
273
+ filtro_complex += f";[base]drawtext=text='{texto_clean}':"
274
+ filtro_complex += (
275
+ f"fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf:"
276
+ f"fontcolor={cor_texto}:fontsize={tamanho_texto}:"
277
+ f"shadowcolor={cor_sombra}:shadowx=3:shadowy=3:"
278
+ f"x=(w-text_w)/2:y={y_pos}{enable}[final]"
279
+ )
280
+ else:
281
+ filtro_complex += ";[base]null[final]"
282
+
283
+ video_editado = os.path.join(temp_dir, f"video_editado_{n}.mp4")
284
+ subprocess.run([
285
+ "ffmpeg", "-i", fundo_convertido, "-i", video_raw,
286
+ "-filter_complex", filtro_complex,
287
+ "-map", "[final]",
288
+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", str(crf_value),
289
+ video_editado
290
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
291
+
292
+ etapa_atual += 1
293
+ atualizar_barra(n, etapa_atual, num_videos_finais, total_etapas)
294
+
295
+ # Etapa 4 - Tutorial
296
+ if usar_tutorial and tutorials_salvos:
297
+ tutorial_path = random.choice(tutorials_salvos)
298
+ tutorial_mp4 = os.path.join(temp_dir, f"tutorial_conv_{n}.mp4")
299
+ subprocess.run([
300
+ "ffmpeg", "-i", tutorial_path, "-vf", "scale=720:1280,fps=30",
301
+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", str(crf_value),
302
+ "-y", tutorial_mp4
303
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
304
+
305
+ dur_proc = subprocess.run([
306
+ "ffprobe", "-v", "error", "-show_entries", "format=duration",
307
+ "-of", "default=noprint_wrappers=1:nokey=1", video_editado
308
+ ], stdout=subprocess.PIPE)
309
+ dur_f = float(dur_proc.stdout.decode().strip() or 0)
310
+ pt = dur_f / 2 if dur_f < 10 else random.uniform(5, dur_f - 5)
311
+
312
+ part1 = os.path.join(temp_dir, f"part1_{n}.mp4")
313
+ part2 = os.path.join(temp_dir, f"part2_{n}.mp4")
314
+
315
+ subprocess.run(["ffmpeg", "-i", video_editado, "-ss", "0", "-t", str(pt),
316
+ "-c:v", "libx264", "-preset", "ultrafast", part1],
317
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
318
+ subprocess.run(["ffmpeg", "-i", video_editado, "-ss", str(pt),
319
+ "-c:v", "libx264", "-preset", "ultrafast", part2],
320
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
321
+
322
+ final_txt = os.path.join(temp_dir, f"final_{n}.txt")
323
+ with open(final_txt, "w") as f:
324
+ f.write(f"file '{part1}'\nfile '{tutorial_mp4}'\nfile '{part2}'\n")
325
+
326
+ video_final_raw = os.path.join(temp_dir, f"video_final_raw_{n}.mp4")
327
+ subprocess.run(["ffmpeg", "-f", "concat", "-safe", "0", "-i", final_txt,
328
+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", str(crf_value),
329
+ video_final_raw], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
330
+ else:
331
+ video_final_raw = video_editado
332
+ etapa_atual += 1
333
+ atualizar_barra(n, etapa_atual, num_videos_finais, total_etapas)
334
+
335
+ # Etapa 5 - Velocidade final
336
+ video_com_velocidade = os.path.join(temp_dir, f"video_com_velocidade_{n}.mp4")
337
+ subprocess.run([
338
+ "ffmpeg", "-y", "-i", video_final_raw, "-an",
339
+ "-filter:v", f"setpts=PTS/{velocidade_final_n}",
340
+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", str(crf_value),
341
+ video_com_velocidade
342
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
343
+
344
+ dur_final_str = subprocess.run([
345
+ "ffprobe", "-v", "error", "-show_entries", "format=duration",
346
+ "-of", "default=noprint_wrappers=1:nokey=1", video_com_velocidade
347
+ ], stdout=subprocess.PIPE).stdout.decode().strip()
348
+ if not dur_final_str:
349
+ continue
350
+ dur_video_real = float(dur_final_str)
351
+
352
+ final_name = f"video_final_{n}_{int(time.time())}.mp4"
353
+ if usar_musica and musicas_salvas:
354
+ musica_path = random.choice(musicas_salvas)
355
+ musica_cortada = os.path.join(temp_dir, f"musica_{n}.aac")
356
+ subprocess.run(["ffmpeg", "-i", musica_path, "-ss", "0", "-t", str(dur_video_real),
357
+ "-vn", "-acodec", "aac", "-y", musica_cortada],
358
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
359
+
360
+ subprocess.run(["ffmpeg", "-i", video_com_velocidade, "-i", musica_cortada,
361
+ "-map", "0:v:0", "-map", "1:a:0",
362
+ "-c:v", "copy", "-c:a", "aac", "-shortest", final_name],
363
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
364
+ else:
365
+ shutil.copy(video_com_velocidade, final_name)
366
+
367
+ if salvar_no_gerenciador:
368
+ destino = os.path.join(BASE_SALVOS, categoria_selecionada, final_name)
369
+ shutil.move(final_name, destino)
370
+ st.success(f"✅ Vídeo {n+1} salvo na categoria '{categoria_selecionada}'.")
371
+ else:
372
+ st.video(final_name)
373
+ with open(final_name, "rb") as f:
374
+ st.download_button(f"📥 Baixar vídeo {n+1}", f, file_name=final_name)
375
+
376
+ except Exception as e:
377
+ st.error(f"❌ Erro inesperado: {str(e)}")
378
+ finally:
379
+ shutil.rmtree(temp_dir)
380
+
381
+ # ======================== GERENCIADOR ========================
382
+ elif pagina == "📂 Gerenciador de Arquivos":
383
+ st.header("📂 Vídeos Salvos por Categoria")
384
+
385
+ for categoria in CATEGORIAS:
386
+ pasta = os.path.join(BASE_SALVOS, categoria)
387
+ os.makedirs(pasta, exist_ok=True)
388
+ arquivos = os.listdir(pasta)
389
+
390
+ st.subheader(f"📁 {categoria}")
391
+
392
+ if not arquivos:
393
+ st.info("Nenhum vídeo salvo.")
394
+ else:
395
+ for file in arquivos:
396
+ file_path = os.path.join(pasta, file)
397
+
398
+ st.markdown("---")
399
+ st.markdown(f"**🎞️ {file}**")
400
+ col1, col2, col3 = st.columns(3)
401
+
402
+ with col1:
403
+ if st.button(f"▶ Assistir", key=f"play_{categoria}_{file}"):
404
+ st.video(file_path)
405
+
406
+ with col2:
407
+ with open(file_path, "rb") as f_obj:
408
+ st.download_button("⬇ Download", f_obj, file_name=file, key=f"download_{categoria}_{file}")
409
+
410
+ with col3:
411
+ with open(file_path, "rb") as f_obj:
412
+ if st.download_button("⬇ Baixar & Apagar", f_obj, file_name=file, key=f"down_del_{categoria}_{file}"):
413
+ os.remove(file_path)
414
+ st.success(f"✅ Arquivo '{file}' baixado e excluído.")
415
+ st.rerun()
416
+
417
+ # Botão extra de exclusão
418
+ if st.button("🗑 Excluir", key=f"delete_{categoria}_{file}"):
419
+ os.remove(file_path)
420
+ st.success(f"❌ Arquivo '{file}' excluído.")
421
+ st.rerun()
422
+
423
+ # ======================== ADMIN ========================
424
+ elif pagina == "🔐 Admin":
425
+ st.title("🔐 Área de Administração")
426
+ senha_certa = "YWRtaW4xMjM=" # base64 de admin123
427
+
428
+ if "autenticado" not in st.session_state:
429
+ st.session_state.autenticado = False
430
+
431
+ if not st.session_state.autenticado:
432
+ senha = st.text_input("Senha:", type="password")
433
+ lembrar = st.checkbox("Lembrar nesta sessão")
434
+ login = st.button("Entrar")
435
+
436
+ if login:
437
+ if base64.b64encode(senha.encode()).decode() == senha_certa:
438
+ st.success("✅ Acesso liberado!")
439
+ st.session_state.autenticado = True
440
+ else:
441
+ st.error("❌ Senha incorreta.")
442
+ st.stop()
443
+
444
+ if not st.session_state.autenticado:
445
+ st.stop()
446
+
447
+ cat = st.selectbox("Categoria", ["Selecione..."] + CATEGORIAS)
448
+ if cat == "Selecione...":
449
+ st.warning("👈 Por favor, selecione uma categoria antes de enviar arquivos.")
450
+ st.stop()
451
+
452
+ tipo = st.radio("Tipo", ["Cortes", "Tutoriais", "Músicas"])
453
+ path = "assets/musicas" if tipo == "Músicas" else os.path.join(BASE_ASSETS, cat, tipo.lower())
454
+
455
+ arquivos = st.file_uploader("Enviar arquivos", accept_multiple_files=True, key=f"{cat}_{tipo}")
456
+
457
+ if arquivos:
458
+ with st.spinner("⏳ Processando e padronizando arquivos..."):
459
+ for f in arquivos:
460
+ extensao = os.path.splitext(f.name)[1].lower()
461
+ nome_aleatorio = f"{random.randint(1000000, 9999999)}{extensao}"
462
+ temp = f"temp_input_{nome_aleatorio}"
463
+ with open(temp, "wb") as out:
464
+ out.write(f.read())
465
+
466
+ final = os.path.join(path, nome_aleatorio)
467
+
468
+ if tipo != "Músicas":
469
+ subprocess.run([
470
+ "ffmpeg", "-i", temp,
471
+ "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2,fps=30",
472
+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", "25",
473
+ "-y", final
474
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
475
+ else:
476
+ shutil.move(temp, final)
477
+
478
+ os.remove(temp)
479
+
480
+ st.success("✅ Arquivos enviados, padronizados e renomeados com sucesso!")
481
+
482
+ st.write("Arquivos existentes:")
483
+ for arq in os.listdir(path):
484
+ col1, col2 = st.columns([5, 1])
485
+ with col1:
486
+ st.markdown(f"`{arq}`")
487
+ with col2:
488
+ if st.button("🗑", key=f"{tipo}_{cat}_{arq}"):
489
+ os.remove(os.path.join(path, arq))
490
+ st.rerun()