File size: 26,694 Bytes
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
999d355
aa3603f
 
 
 
 
 
 
 
656d34f
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a57dc34
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656d34f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f97bbf
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a57dc34
4f97bbf
a57dc34
 
 
15efe15
 
 
 
 
 
 
 
 
 
a57dc34
15efe15
a57dc34
15efe15
 
 
2cdb771
a57dc34
 
 
 
 
 
2cdb771
a57dc34
 
15efe15
 
216d7df
4f97bbf
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8406abb
2cdb771
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cdb771
aa3603f
15efe15
 
8406abb
4f97bbf
1df1826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216d7df
4f97bbf
 
 
216d7df
4f97bbf
 
 
 
 
aa3603f
 
 
 
 
2cdb771
aa3603f
 
 
 
4f97bbf
aa3603f
 
216d7df
aa3603f
 
 
 
4f97bbf
2cdb771
aa3603f
4f97bbf
2cdb771
aa3603f
 
 
 
 
 
 
 
2cdb771
aa3603f
 
4f97bbf
8406abb
4f97bbf
aa3603f
 
4f97bbf
aa3603f
 
 
 
 
 
 
a57dc34
aa3603f
 
 
 
 
4f97bbf
aa3603f
 
 
 
4f97bbf
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
2cdb771
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656d34f
aa3603f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cdb771
aa3603f
 
 
 
 
 
 
 
 
b2dba0d
 
 
 
2cdb771
b2dba0d
 
 
 
 
2cdb771
 
 
b2dba0d
 
 
 
 
 
 
 
 
4f97bbf
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import streamlit as st
import subprocess
import os
import random
import tempfile
import shutil
import time
import base64

st.set_page_config(page_title="TikTok Video Generator - PRO", layout="centered")

abas = ["🎬 Gerador de Vídeo", "📂 Gerenciador de Arquivos", "🔐 Admin"]
pagina = st.sidebar.radio("Escolha uma página:", abas)

CATEGORIAS = ["AVATAR WORLD","TOCA LIFE","BLOX FRUITS","99 NIGHTS","STEAL A BRAINROT","FC MOBILE"]
BASE_ASSETS = "assets"
BASE_SALVOS = "uploaded_files"

os.makedirs("assets/musicas", exist_ok=True)
for cat in CATEGORIAS:
    os.makedirs(os.path.join(BASE_ASSETS, cat, "cortes"), exist_ok=True)
    os.makedirs(os.path.join(BASE_ASSETS, cat, "tutoriais"), exist_ok=True)
    os.makedirs(os.path.join(BASE_SALVOS, cat), exist_ok=True)

if pagina == "🎬 Gerador de Vídeo":
    st.title("🎥 TikTok Video Generator - PRO")

    categoria_selecionada = st.selectbox("Escolha a categoria:", ["Selecione..."] + CATEGORIAS)
    if categoria_selecionada == "Selecione...":
        st.warning("👈 Por favor, selecione uma categoria antes de continuar.")
        st.stop()

    st.markdown("### 🎛️ Opções de Mídia")
    usar_tutorial = st.checkbox("Ativar tutorial", value=True)
    usar_fundo = st.checkbox("Ativar fundo", value=True)
    usar_musica = st.checkbox("Ativar música", value=False)

    path_cortes = os.path.join(BASE_ASSETS, categoria_selecionada, "cortes")
    path_tutoriais = os.path.join(BASE_ASSETS, categoria_selecionada, "tutoriais")
    path_musicas = os.path.join(BASE_ASSETS, "musicas")

    cortes_files = [os.path.join(path_cortes, f) for f in os.listdir(path_cortes) if f.endswith(".mp4")]
    tutoriais_files = [os.path.join(path_tutoriais, f) for f in os.listdir(path_tutoriais) if f.endswith(".mp4")]
    musicas_files = [os.path.join(path_musicas, f) for f in os.listdir(path_musicas) if f.endswith(".mp3")]

    if not cortes_files:
        st.error("❌ Nenhum vídeo de corte encontrado. Use a aba Admin.")
    else:
        num_videos_finais = st.number_input("Quantos vídeos gerar?", 1, 10, 1)
        duracao_final = st.number_input("Duração final (s)", 10, 300, 30)

        st.write("## Configuração dos cortes")
        aleatorizar = st.checkbox("🎲 Aleatorizar configurações por vídeo")
        duracao_corte_min = st.slider("Duração mínima (s)", 1, 10, 3)
        duracao_corte_max = st.slider("Duração máxima (s)", duracao_corte_min + 1, 20, 5)

        zoom = st.slider("Zoom", 1.0, 2.0, 1.0, 0.1)
        blur_strength = st.slider("Blur no fundo", 1, 50, 10)
        velocidade_final = st.slider("Velocidade final", 0.5, 2.0, 1.0, 0.1)
        crf_value = st.slider("Qualidade CRF", 18, 30, 18)

        st.write("## Texto no Vídeo")
        ativar_texto = st.checkbox("Ativar texto")
        if ativar_texto:
            texto_personalizado = st.text_input("Texto", "🔥 Siga para mais!")
            posicao_texto = st.selectbox("Posição", ["Topo", "Centro", "Base"])
            duracao_texto = st.radio("Duração do texto", ["Vídeo todo", "Apenas primeiros segundos"])
            segundos_texto = st.slider("Segundos", 1, 30, 5) if duracao_texto == "Apenas primeiros segundos" else 0
            cor_texto = st.color_picker("Cor do texto", "#FFFF00")
            cor_sombra = st.color_picker("Cor da sombra", "#000000")
            tamanho_texto = st.slider("Tamanho da fonte", 20, 100, 60, step=2)

        st.write("## Filtros no fundo")
        ativar_blur_fundo = st.checkbox("Ativar blur", value=True)
        ativar_sepia = st.checkbox("Sépia")
        ativar_granulado = st.checkbox("Granulado")
        ativar_pb = st.checkbox("Preto e branco")
        ativar_vignette = st.checkbox("Vignette")

        with st.expander("🎨 Filtros Avançados"):
            ativar_brilho = st.checkbox("Brilho extra")
            ativar_contraste = st.checkbox("Contraste forte")
            ativar_colorboost = st.checkbox("Cores intensas")
            ativar_azul = st.checkbox("Filtro Azul")
            ativar_quente = st.checkbox("Filtro Quente")
            ativar_desaturar = st.checkbox("Desaturar")
            ativar_vhs = st.checkbox("Efeito VHS")

        st.write("## Outros efeitos")
        ativar_espelhar = st.checkbox("Espelhar", True)
        ativar_filtro_cor = st.checkbox("Ajuste de cor", True)
        remover_borda = st.checkbox("Remover borda")
        tamanho_borda = st.slider("Tamanho da borda (px)", 0, 200, 0, 5)

        ativar_borda_personalizada = st.checkbox("Borda personalizada")
        if ativar_borda_personalizada:
            cor_borda = st.color_picker("Cor da borda", "#FF0000")
            animacao_borda = st.selectbox("Animação", ["Nenhuma", "Pulsante", "Cor Animada", "Neon", "Ondulada"])

        salvar_no_gerenciador = st.checkbox("Salvar no gerenciador de arquivos")
        if st.button("Gerar Vídeo(s)", key="gerar_video_usuario"):
            with st.spinner("🎬 Processando..."):
                progresso = st.progress(0)
                temp_dir = tempfile.mkdtemp()

                def atualizar_barra(n, etapa, total_videos, total_etapas):
                    progresso.progress(min(100, int(((n + etapa / total_etapas) / total_videos) * 100)))

                try:
                    cortes_names = cortes_files.copy()
                    tutorials_salvos = tutoriais_files.copy()
                    musicas_salvas = musicas_files.copy()
                    for n in range(num_videos_finais):
                        total_etapas = 6
                        etapa_atual = 0
                        tempo_total = 0
                        cortes_prontos = []
                        cortes_usados = []

                        # === Config aleatória ou fixa ===
                        if aleatorizar:
                            duracao_corte_min_n = random.randint(1, 5)
                            duracao_corte_max_n = random.randint(duracao_corte_min_n + 1, 8)
                            zoom_n = round(random.uniform(1.0, 1.5), 2)
                            blur_strength_n = random.randint(5, 30)
                            velocidade_final_n = velocidade_final
                            remover_borda_n = remover_borda and random.choice([True, False])
                            tamanho_borda_n = random.randint(0, 50) if remover_borda_n else 0
                            ativar_blur_fundo_n = random.choice([True, False])
                            ativar_espelhar_n = random.choice([True, False])
                        else:
                            duracao_corte_min_n = duracao_corte_min
                            duracao_corte_max_n = duracao_corte_max
                            zoom_n = zoom
                            blur_strength_n = blur_strength
                            velocidade_final_n = velocidade_final
                            remover_borda_n = remover_borda
                            tamanho_borda_n = tamanho_borda
                            ativar_blur_fundo_n = ativar_blur_fundo
                            ativar_espelhar_n = ativar_espelhar

                        # === Etapa 1 - Fundo ===
                        if usar_fundo:
                            fundo_origem = random.choice(cortes_names)
                            fundo_convertido = os.path.join(temp_dir, f"fundo_convertido_{n}.mp4")
                            dur_proc = subprocess.run([
                                "ffprobe", "-v", "error", "-show_entries", "format=duration",
                                "-of", "default=noprint_wrappers=1:nokey=1", fundo_origem
                            ], stdout=subprocess.PIPE)
                            try:
                                dur_total = float(dur_proc.stdout.decode().strip())
                                ponto_inicio = random.uniform(0, max(0, dur_total - duracao_final))
                            except:
                                ponto_inicio = 0.0

                            subprocess.run([
                                "ffmpeg", "-ss", str(ponto_inicio), "-i", fundo_origem,
                                "-t", str(duracao_final),
                                "-vf",
                                "scale='if(gt(iw/ih,720/1280),max(720,iw),-2)':'if(gt(iw/ih,720/1280),-2,max(1280,ih))',"
                                "scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,fps=30",
                                "-preset", "ultrafast", "-crf", "18",
                                fundo_convertido
                            ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                        else:
                            fundo_convertido = os.path.join(temp_dir, f"fundo_vazio_{n}.mp4")
                            subprocess.run([
                                "ffmpeg", "-f", "lavfi", "-i", f"color=color=black:size=720x1280:d={duracao_final}:rate=30",
                                "-c:v", "libx264", "-t", str(duracao_final), "-preset", "ultrafast", "-crf", "18",
                                fundo_convertido
                            ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                        etapa_atual += 1
                        atualizar_barra(n, etapa_atual, num_videos_finais, total_etapas)

                        # === Etapa 2 - Cortes ===
                        tentativas = 0
                        while tempo_total < duracao_final and tentativas < 100:
                            tentativas += 1
                            random.shuffle(cortes_names)
                            for c in cortes_names:
                                dur = subprocess.run([
                                    "ffprobe", "-v", "error", "-show_entries", "format=duration",
                                    "-of", "default=noprint_wrappers=1:nokey=1", c
                                ], stdout=subprocess.PIPE).stdout.decode().strip()
                                if not dur:
                                    continue
                                try:
                                    d = float(dur)
                                    if d < duracao_corte_min_n + 0.5:
                                        continue
                                    duracao_aleatoria = random.uniform(duracao_corte_min_n, min(d, duracao_corte_max_n))
                                    ini = random.uniform(0, d - duracao_aleatoria)
                                    repetido = any(c == usado[0] and abs(ini - usado[1]) < 0.5 for usado in cortes_usados)
                                    if repetido:
                                        continue
                                    out = os.path.join(temp_dir, f"cut_{random.randint(1000,9999)}.mp4")
                                    subprocess.run([
                                        "ffmpeg", "-ss", str(ini), "-i", c, "-t", str(duracao_aleatoria),
                                        "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",
                                        "-an", "-c:v", "libx264", "-preset", "ultrafast", "-crf", "30", out
                                    ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                                    cortes_prontos.append(out)
                                    cortes_usados.append((c, ini, duracao_aleatoria))
                                    tempo_total += duracao_aleatoria
                                    if tempo_total >= duracao_final:
                                        break
                                except:
                                    continue

                        lista = os.path.join(temp_dir, f"lista_{n}.txt")
                        with open(lista, "w") as f:
                            for c in cortes_prontos:
                                f.write(f"file '{c}'\n")

                        video_raw = os.path.join(temp_dir, f"video_raw_{n}.mp4")
                        subprocess.run([
                            "ffmpeg", "-f", "concat", "-safe", "0", "-i", lista,
                            "-c:v", "libx264", "-preset", "ultrafast", "-crf", "30", video_raw
                        ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                        etapa_atual += 1
                        atualizar_barra(n, etapa_atual, num_videos_finais, total_etapas)

                        # === Etapa 3 - Filtros ===
                        filtros_main = ["scale=720:1280:force_original_aspect_ratio=decrease"]
                        if zoom_n != 1.0:
                            filtros_main.append(f"scale=iw*{zoom_n}:ih*{zoom_n}")
                        if ativar_espelhar_n:
                            filtros_main.append("hflip")
                        if remover_borda_n and tamanho_borda_n > 0:
                            filtros_main.append(f"crop=in_w-{tamanho_borda_n*2}:in_h-{tamanho_borda_n*2}")
                        if ativar_filtro_cor:
                            filtros_main.append("eq=contrast=1.1:saturation=1.2")
                        filtros_main.append("scale=trunc(iw/2)*2:trunc(ih/2)*2")
                        if ativar_borda_personalizada:
                            cor_ffmpeg = f"0x{cor_borda.lstrip('#')}FF"
                            filtros_main.append(f"drawbox=x=0:y=0:w=iw:h=ih:color={cor_ffmpeg}:t=5")

                        filtro_complex = f"[0:v]scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280"
                        if ativar_blur_fundo_n:
                            filtro_complex += f",boxblur={blur_strength_n}:1"
                        if ativar_sepia:
                            filtro_complex += ",colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131"
                        if ativar_granulado:
                            filtro_complex += ",noise=alls=20:allf=t+u"
                        if ativar_pb:
                            filtro_complex += ",hue=s=0.3"
                        if ativar_vignette:
                            filtro_complex += ",vignette"
                        if ativar_brilho:
                            filtro_complex += ",eq=brightness=0.05"
                        if ativar_contraste:
                            filtro_complex += ",eq=contrast=1.3"
                        if ativar_colorboost:
                            filtro_complex += ",eq=saturation=1.5"
                        if ativar_azul:
                            filtro_complex += ",colorbalance=bs=0.5"
                        if ativar_quente:
                            filtro_complex += ",colorbalance=rs=0.3"
                        if ativar_desaturar:
                            filtro_complex += ",hue=s=0.5"
                        if ativar_vhs:
                            filtro_complex += ",noise=alls=10:allf=t+u,format=yuv420p"

                        filtro_complex += "[blur];"
                        filtro_complex += f"[1:v]{','.join(filtros_main)}[zoomed];"
                        filtro_complex += "[blur][zoomed]overlay=(W-w)/2:(H-h)/2[base]"

                        if ativar_texto and texto_personalizado.strip():
                            y_pos = "100" if posicao_texto == "Topo" else "(h-text_h)/2" if posicao_texto == "Centro" else "h-text_h-100"
                            enable = f":enable='lt(t\\,{segundos_texto})'" if duracao_texto == "Apenas primeiros segundos" else ""
                            texto_clean = texto_personalizado.replace(":", "\\:").replace("'", "\\'")
                            filtro_complex += f";[base]drawtext=text='{texto_clean}':"
                            filtro_complex += (
                                f"fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf:"
                                f"fontcolor={cor_texto}:fontsize={tamanho_texto}:"
                                f"shadowcolor={cor_sombra}:shadowx=3:shadowy=3:"
                                f"x=(w-text_w)/2:y={y_pos}{enable}[final]"
                            )
                        else:
                            filtro_complex += ";[base]null[final]"

                        video_editado = os.path.join(temp_dir, f"video_editado_{n}.mp4")
                        subprocess.run([
                            "ffmpeg", "-i", fundo_convertido, "-i", video_raw,
                            "-filter_complex", filtro_complex,
                            "-map", "[final]",
                            "-c:v", "libx264", "-preset", "ultrafast", "-crf", str(crf_value),
                            video_editado
                        ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                        etapa_atual += 1
                        atualizar_barra(n, etapa_atual, num_videos_finais, total_etapas)

                        # === Etapa 4 - VELOCIDADE (corrigido) ===
                        video_com_velocidade = os.path.join(temp_dir, f"video_com_velocidade_{n}.mp4")
                        subprocess.run([
                            "ffmpeg", "-y", "-i", video_editado, "-an",
                            "-filter:v", f"setpts=PTS/{velocidade_final_n},fps=30",
                            "-c:v", "libx264", "-preset", "ultrafast", "-crf", str(crf_value),
                            video_com_velocidade
                        ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

                        # === Etapa 5 - Tutorial (sem ser acelerado) ===
                        if usar_tutorial and tutorials_salvos:
                            tutorial_path = random.choice(tutorials_salvos)
                            tutorial_mp4 = os.path.join(temp_dir, f"tutorial_conv_{n}.mp4")
                            subprocess.run([
                                "ffmpeg", "-i", tutorial_path, "-vf", "scale=720:1280,fps=30",
                                "-c:v", "libx264", "-preset", "ultrafast", "-crf", str(crf_value),
                                "-y", tutorial_mp4
                            ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                            dur_proc = subprocess.run([
                                "ffprobe", "-v", "error", "-show_entries", "format=duration",
                                "-of", "default=noprint_wrappers=1:nokey=1", video_com_velocidade
                            ], stdout=subprocess.PIPE)
                            dur_f = float(dur_proc.stdout.decode().strip() or 0)
                            pt = dur_f / 2 if dur_f < 10 else random.uniform(5, max(6, dur_f - 5))

                            part1 = os.path.join(temp_dir, f"part1_{n}.mp4")
                            part2 = os.path.join(temp_dir, f"part2_{n}.mp4")

                            subprocess.run(["ffmpeg", "-i", video_com_velocidade, "-ss", "0", "-t", str(pt),
                                            "-c:v", "libx264", "-preset", "ultrafast", part1],
                                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                            subprocess.run(["ffmpeg", "-i", video_com_velocidade, "-ss", str(pt),
                                            "-c:v", "libx264", "-preset", "ultrafast", part2],
                                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

                            final_txt = os.path.join(temp_dir, f"final_{n}.txt")
                            with open(final_txt, "w") as f:
                                f.write(f"file '{part1}'\nfile '{tutorial_mp4}'\nfile '{part2}'\n")

                            video_final_raw = os.path.join(temp_dir, f"video_final_raw_{n}.mp4")
                            subprocess.run(["ffmpeg", "-f", "concat", "-safe", "0", "-i", final_txt,
                                            "-c:v", "libx264", "-preset", "ultrafast", "-crf", str(crf_value),
                                            video_final_raw], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                        else:
                            video_final_raw = video_com_velocidade

                        # === Etapa 6 - Música e saída final ===
                        dur_final_str = subprocess.run([
                            "ffprobe", "-v", "error", "-show_entries", "format=duration",
                            "-of", "default=noprint_wrappers=1:nokey=1", video_final_raw
                        ], stdout=subprocess.PIPE).stdout.decode().strip()
                        if not dur_final_str:
                            continue
                        dur_video_real = float(dur_final_str)

                        final_name = f"video_final_{n}_{int(time.time())}.mp4"
                        if usar_musica and musicas_salvas:
                            musica_path = random.choice(musicas_salvas)
                            musica_cortada = os.path.join(temp_dir, f"musica_{n}.aac")
                            subprocess.run(["ffmpeg", "-i", musica_path, "-ss", "0", "-t", str(dur_video_real),
                                            "-vn", "-acodec", "aac", "-y", musica_cortada],
                                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

                            subprocess.run(["ffmpeg", "-i", video_final_raw, "-i", musica_cortada,
                                            "-map", "0:v:0", "-map", "1:a:0",
                                            "-c:v", "copy", "-c:a", "aac", "-shortest", final_name],
                                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                        else:
                            shutil.copy(video_final_raw, final_name)

                        if salvar_no_gerenciador:
                            destino = os.path.join(BASE_SALVOS, categoria_selecionada, final_name)
                            shutil.move(final_name, destino)
                            st.success(f"✅ Vídeo {n+1} salvo na categoria '{categoria_selecionada}'.")
                        else:
                            st.video(final_name)
                            with open(final_name, "rb") as f:
                                st.download_button(f"📥 Baixar vídeo {n+1}", f, file_name=final_name)

                except Exception as e:
                    st.error(f"❌ Erro inesperado: {str(e)}")
                finally:
                    shutil.rmtree(temp_dir)

# ======================== GERENCIADOR ========================
elif pagina == "📂 Gerenciador de Arquivos":
    st.header("📂 Vídeos Salvos por Categoria")

    for categoria in CATEGORIAS:
        pasta = os.path.join(BASE_SALVOS, categoria)
        os.makedirs(pasta, exist_ok=True)
        arquivos = os.listdir(pasta)

        st.subheader(f"📁 {categoria}")

        if not arquivos:
            st.info("Nenhum vídeo salvo.")
        else:
            for file in arquivos:
                file_path = os.path.join(pasta, file)

                st.markdown("---")
                st.markdown(f"**🎞️ {file}**")
                col1, col2, col3 = st.columns(3)

                with col1:
                    if st.button(f"▶ Assistir", key=f"play_{categoria}_{file}"):
                        st.video(file_path)

                with col2:
                    with open(file_path, "rb") as f_obj:
                        st.download_button("⬇ Download", f_obj, file_name=file, key=f"download_{categoria}_{file}")

                with col3:
                    with open(file_path, "rb") as f_obj:
                        if st.download_button("⬇ Baixar & Apagar", f_obj, file_name=file, key=f"down_del_{categoria}_{file}"):
                            os.remove(file_path)
                            st.success(f"✅ Arquivo '{file}' baixado e excluído.")
                            st.rerun()

                if st.button("🗑 Excluir", key=f"delete_{categoria}_{file}"):
                    os.remove(file_path)
                    st.success(f"❌ Arquivo '{file}' excluído.")
                    st.rerun()

# ======================== ADMIN ========================
elif pagina == "🔐 Admin":
    st.title("🔐 Área de Administração")
    senha_certa = "YWRtaW4xMjM="  # base64 de admin123

    if "autenticado" not in st.session_state:
        st.session_state.autenticado = False

    if not st.session_state.autenticado:
        senha = st.text_input("Senha:", type="password")
        lembrar = st.checkbox("Lembrar nesta sessão")
        login = st.button("Entrar")

        if login:
            if base64.b64encode(senha.encode()).decode() == senha_certa:
                st.success("✅ Acesso liberado!")
                st.session_state.autenticado = True
            else:
                st.error("❌ Senha incorreta.")
                st.stop()

        if not st.session_state.autenticado:
            st.stop()

    cat = st.selectbox("Categoria", ["Selecione..."] + CATEGORIAS)
    if cat == "Selecione...":
        st.warning("👈 Por favor, selecione uma categoria antes de enviar arquivos.")
        st.stop()

    tipo = st.radio("Tipo", ["Cortes", "Tutoriais", "Músicas"])
    path = "assets/musicas" if tipo == "Músicas" else os.path.join(BASE_ASSETS, cat, tipo.lower())

    arquivos = st.file_uploader("Enviar arquivos", accept_multiple_files=True, key=f"{cat}_{tipo}")

    if arquivos:
        with st.spinner("⏳ Processando e padronizando arquivos..."):
            for f in arquivos:
                extensao = os.path.splitext(f.name)[1].lower()
                nome_aleatorio = f"{random.randint(1000000, 9999999)}{extensao}"
                temp = f"temp_input_{nome_aleatorio}"
                with open(temp, "wb") as out:
                    out.write(f.read())

                final = os.path.join(path, nome_aleatorio)

                if tipo != "Músicas":
                    subprocess.run([
                        "ffmpeg", "-i", temp,
                        "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2,fps=30",
                        "-c:v", "libx264", "-preset", "ultrafast", "-crf", "18",
                        "-y", final
                    ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                else:
                    shutil.move(temp, final)

                os.remove(temp)

            st.success("✅ Arquivos enviados, padronizados e renomeados com sucesso!")

    st.write("Arquivos existentes:")
    for arq in os.listdir(path):
        col1, col2 = st.columns([5, 1])
        with col1:
            st.markdown(f"`{arq}`")
        with col2:
            if st.button("🗑", key=f"{tipo}_{cat}_{arq}"):
                os.remove(os.path.join(path, arq))
                st.rerun()