CONVERTALL / app.py
gamecontroll's picture
Renomear main.py para app.py para o Space do Hugging Face iniciar.
ca8f79f
Raw History Blame Contribute Delete
39.8 kB
import streamlit as st
import ffmpeg
from PIL import Image, ImageOps
import tempfile
import os
import zipfile
from io import BytesIO
import subprocess
from pytubefix import YouTube
import rembg
import vtracer
# Configuração da página
st.set_page_config(
page_title="Editor de Vídeo e Imagem",
page_icon="🎬",
layout="wide"
)
st.title("🎬 Editor de Vídeo, Imagem e Áudio Local")
st.markdown("Redimensione, mude aspect ratio e edite seus arquivos localmente!")
# Sidebar para escolher tipo de edição
tipo_edicao = st.sidebar.selectbox(
"Tipo de Edição",
["📹 Vídeos", "🖼️ Imagens", "📦 Lote de Imagens", "🎵 Áudio", "📥 Baixar do YouTube"]
)
def processar_video(input_path, output_path, largura=None, altura=None, crop=None, formato="mp4", padding=False):
"""Processa vídeo com FFmpeg"""
try:
# Lógica para GIF permanece a mesma
if formato == "gif":
cmd = ['ffmpeg', '-i', input_path, '-y']
filtros = []
if crop:
x, y, w, h = crop
filtros.append(f'crop={w}:{h}:{x}:{y}')
if largura and altura:
filtros.append(f'scale={largura}:{altura}')
elif largura:
filtros.append(f'scale={largura}:-1')
elif altura:
filtros.append(f'scale=-1:{altura}')
filtros.append('fps=10')
if filtros:
cmd.extend(['-vf', ','.join(filtros)])
cmd.append(output_path)
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise Exception(f"FFmpeg error: {result.stderr}")
else:
stream = ffmpeg.input(input_path)
if crop:
x, y, w, h = crop
stream = ffmpeg.crop(stream, x, y, w, h)
if padding and largura and altura:
# Redimensiona mantendo o aspect ratio e adiciona barras pretas
stream = ffmpeg.filter(stream, 'scale', w=f'if(gt(a,{largura}/{altura}),{largura},-1)', h=f'if(gt(a,{largura}/{altura}),-1,{altura})')
stream = ffmpeg.filter(stream, 'pad', w=largura, h=altura, x='(ow-iw)/2', y='(oh-ih)/2', color='black')
elif largura and altura:
stream = ffmpeg.filter(stream, 'scale', largura, altura)
elif largura:
stream = ffmpeg.filter(stream, 'scale', largura, -1)
elif altura:
stream = ffmpeg.filter(stream, 'scale', -1, altura)
out = ffmpeg.output(stream, output_path, vcodec='libx264', acodec='aac', crf=23)
ffmpeg.run(out, overwrite_output=True, quiet=True)
return True
except Exception as e:
st.error(f"Erro ao processar vídeo: {str(e)}")
return False
def processar_imagem(img, largura=None, altura=None, manter_proporcao=True, formato="JPEG"):
"""Processa imagem com PIL"""
try:
if manter_proporcao:
if largura and altura:
img.thumbnail((largura, altura), Image.Resampling.LANCZOS)
elif largura:
ratio = largura / img.width
nova_altura = int(img.height * ratio)
img = img.resize((largura, nova_altura), Image.Resampling.LANCZOS)
elif altura:
ratio = altura / img.height
nova_largura = int(img.width * ratio)
img = img.resize((nova_largura, altura), Image.Resampling.LANCZOS)
else:
if largura and altura:
img = img.resize((largura, altura), Image.Resampling.LANCZOS)
return img
except Exception as e:
st.error(f"Erro ao processar imagem: {str(e)}")
return None
def processar_audio(input_path, output_path, formato="mp3", bitrate="192k", sample_rate=None, canais=None):
"""Processa áudio com FFmpeg"""
try:
cmd = ['ffmpeg', '-i', input_path, '-y']
if formato == "mp3":
cmd.extend(['-acodec', 'libmp3lame', '-ab', str(bitrate)])
elif formato == "wav":
cmd.extend(['-acodec', 'pcm_s16le'])
elif formato == "flac":
cmd.extend(['-acodec', 'flac'])
elif formato == "aac":
cmd.extend(['-acodec', 'aac', '-ab', str(bitrate)])
elif formato == "ogg":
# OGG precisa de sintaxe específica
cmd.extend(['-acodec', 'libvorbis', '-q:a', '4']) # Qualidade ao invés de bitrate
if sample_rate and sample_rate != "Manter original":
cmd.extend(['-ar', str(sample_rate)])
if canais and canais != "Manter original":
cmd.extend(['-ac', str(canais)])
cmd.append(output_path)
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise Exception(f"FFmpeg error: {result.stderr}")
return True
except Exception as e:
st.error(f"Erro ao processar áudio: {str(e)}")
return False
def extrair_audio_video(input_path, output_path, formato="mp3", bitrate="192k"):
"""Extrai áudio de vídeo"""
try:
cmd = ['ffmpeg', '-i', input_path, '-vn', '-y']
if formato == "mp3":
cmd.extend(['-acodec', 'libmp3lame', '-ab', str(bitrate)])
elif formato == "wav":
cmd.extend(['-acodec', 'pcm_s16le'])
elif formato == "flac":
cmd.extend(['-acodec', 'flac'])
elif formato == "aac":
cmd.extend(['-acodec', 'aac', '-ab', str(bitrate)])
cmd.append(output_path)
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise Exception(f"FFmpeg error: {result.stderr}")
return True
except Exception as e:
st.error(f"Erro ao extrair áudio: {str(e)}")
return False
# IMPORTAR FUNÇÕES DE ÁUDIO
if tipo_edicao == "🎵 Áudio":
# SEÇÃO DE ÁUDIO
st.header("Processamento de Áudio")
operacao = st.selectbox("Tipo de Operação", [
"🎵 Converter Áudio para Áudio",
"📹➡️🎵 Extrair Áudio de Vídeo"
], key="audio_op")
if operacao == "🎵 Converter Áudio para Áudio":
st.subheader("Conversão de Formatos de Áudio")
audio_file = st.file_uploader("Escolha um arquivo de áudio",
type=['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a', 'wma',"mp4"],
key="audio_uploader")
if audio_file is not None:
file_extension = os.path.splitext(audio_file.name)[1]
with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as tmp_file:
tmp_file.write(audio_file.read())
temp_input = tmp_file.name
try:
probe = ffmpeg.probe(temp_input)
audio_info = next(s for s in probe['streams'] if s['codec_type'] == 'audio')
sample_rate_original = int(audio_info.get('sample_rate', 0))
channels_original = int(audio_info.get('channels', 0))
bitrate_original = audio_info.get('bit_rate', 'N/A')
st.success(f"Áudio carregado: {sample_rate_original}Hz, {channels_original} canais")
col1, col2 = st.columns(2)
with col1:
st.subheader("⚙️ Configurações")
formato_audio = st.selectbox("Formato de saída", ["mp3", "wav", "flac", "aac", "ogg","mp4"], key="audio_format")
if formato_audio in ["mp3", "aac","mp4"]:
bitrate_audio = st.selectbox("Bitrate", ["128k", "192k", "256k", "320k"], index=1, key="audio_bitrate")
elif formato_audio == "ogg":
bitrate_audio = st.selectbox("Qualidade OGG", ["2 (baixa)", "4 (média)", "6 (alta)", "8 (máxima)"], index=1, key="audio_ogg_quality")
else:
bitrate_audio = None
sample_rate_novo = st.selectbox("Sample Rate",
["Manter original", "22050", "44100", "48000", "96000"], key="audio_samplerate")
if sample_rate_novo == "Manter original":
sample_rate_novo = None
else:
sample_rate_novo = int(sample_rate_novo)
canais_novo = st.selectbox("Canais", ["Manter original", "1 (Mono)", "2 (Stereo)"], key="audio_channels")
if canais_novo == "Manter original":
canais_novo = None
elif canais_novo == "1 (Mono)":
canais_novo = 1
else:
canais_novo = 2
with col2:
st.subheader("📊 Informações")
st.write(f"**Original:** {sample_rate_original}Hz, {channels_original} canais")
st.write(f"**Formato original:** {file_extension.upper()}")
if bitrate_original != 'N/A':
st.write(f"**Bitrate original:** {int(bitrate_original)//1000}k")
st.write("---")
st.write(f"**Novo formato:** {formato_audio.upper()}")
if sample_rate_novo:
st.write(f"**Novo sample rate:** {sample_rate_novo}Hz")
if canais_novo:
st.write(f"**Novos canais:** {canais_novo}")
if bitrate_audio:
st.write(f"**Novo bitrate:** {bitrate_audio}")
if st.button("🎵 Converter Áudio", type="primary", key="audio_convert_button"):
with st.spinner("Convertendo áudio..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{formato_audio}') as output_file:
temp_output = output_file.name
if processar_audio(temp_input, temp_output, formato_audio, bitrate_audio, sample_rate_novo, canais_novo):
with open(temp_output, 'rb') as f:
st.download_button(
label="⬇️ Baixar Áudio Convertido",
data=f.read(),
file_name=f"audio_convertido.{formato_audio}",
mime=f"audio/{formato_audio}",
key="audio_download_button"
)
st.success("✅ Áudio convertido com sucesso!")
os.unlink(temp_input)
if os.path.exists(temp_output):
os.unlink(temp_output)
except Exception as e:
st.error(f"Erro ao processar áudio: {str(e)}")
elif operacao == "📹➡️🎵 Extrair Áudio de Vídeo":
st.subheader("Extrair Áudio de Vídeo")
video_file = st.file_uploader("Escolha um vídeo para extrair o áudio",
type=['mp4', 'avi', 'mov', 'mkv', 'flv', 'webm'],
key="audio_extract_uploader")
if video_file is not None:
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_file:
tmp_file.write(video_file.read())
temp_input = tmp_file.name
try:
probe = ffmpeg.probe(temp_input)
audio_info = next((s for s in probe['streams'] if s['codec_type'] == 'audio'), None)
if audio_info:
st.success(f"Áudio encontrado no vídeo!")
col1, col2 = st.columns(2)
with col1:
st.subheader("⚙️ Configurações")
formato_extracao = st.selectbox("Formato do áudio extraído",
["mp3", "wav", "flac", "aac"],
key="audio_extract_format")
if formato_extracao in ["mp3", "aac"]:
bitrate_extracao = st.selectbox("Qualidade",
["128k", "192k", "256k", "320k"],
index=1,
key="audio_extract_quality")
else:
bitrate_extracao = None
with col2:
st.subheader("📊 Informações")
sample_rate = audio_info.get('sample_rate', 'N/A')
channels = audio_info.get('channels', 'N/A')
st.write(f"**Sample Rate:** {sample_rate}Hz")
st.write(f"**Canais:** {channels}")
st.write(f"**Formato de saída:** {formato_extracao.upper()}")
if bitrate_extracao:
st.write(f"**Qualidade:** {bitrate_extracao}")
if st.button("🎵 Extrair Áudio", type="primary", key="audio_extract_button"):
with st.spinner("Extraindo áudio do vídeo..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{formato_extracao}') as output_file:
temp_output = output_file.name
if extrair_audio_video(temp_input, temp_output, formato_extracao, bitrate_extracao):
with open(temp_output, 'rb') as f:
st.download_button(
label="⬇️ Baixar Áudio Extraído",
data=f.read(),
file_name=f"audio_extraido.{formato_extracao}",
mime=f"audio/{formato_extracao}",
key="audio_extract_download_button"
)
st.success("✅ Áudio extraído com sucesso!")
os.unlink(temp_input)
if os.path.exists(temp_output):
os.unlink(temp_output)
else:
st.warning("⚠️ Nenhum áudio encontrado neste vídeo!")
except Exception as e:
st.error(f"Erro ao processar vídeo: {str(e)}")
# SEÇÃO DE VÍDEOS
elif tipo_edicao == "📹 Vídeos":
st.header("Edição de Vídeos")
video_file = st.file_uploader("Escolha um vídeo", type=['mp4', 'avi', 'mov', 'mkv'], key="video_uploader")
if video_file is not None:
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_file:
tmp_file.write(video_file.read())
temp_input = tmp_file.name
try:
probe = ffmpeg.probe(temp_input)
video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video')
width_original = int(video_info['width'])
height_original = int(video_info['height'])
st.success(f"Vídeo carregado: {width_original}x{height_original}")
col1, col2 = st.columns(2)
with col1:
st.subheader("⚙️ Configurações")
# Substituído por um sistema de presets mais claro
preset = st.selectbox("Preset de Redimensionamento", [
"Manter original",
"Personalizado",
"Vertical (9:16) - TikTok, Reels, Stories",
"Retrato (4:5) - Feed do Instagram",
"Quadrado (1:1) - Feed do Instagram",
"Horizontal (16:9) - X (Twitter), YouTube"
], key="video_preset_social")
nova_largura = None
nova_altura = None
padding_video = False
if preset == "Personalizado":
nova_largura = st.number_input("Nova largura", min_value=1, value=width_original, key="video_width_custom")
nova_altura = st.number_input("Nova altura", min_value=1, value=height_original, key="video_height_custom")
padding_video = st.checkbox("Manter proporção (adicionar barras pretas)", value=True, key="video_padding_custom")
elif preset != "Manter original":
padding_video = True # Padding é padrão para presets de redes sociais
aspect_ratios = {
"Vertical (9:16) - TikTok, Reels, Stories": 9/16,
"Retrato (4:5) - Feed do Instagram": 4/5,
"Quadrado (1:1) - Feed do Instagram": 1/1,
"Horizontal (16:9) - X (Twitter), YouTube": 16/9
}
target_ratio = aspect_ratios[preset]
# Calcula as novas dimensões mantendo o aspect ratio original, para depois aplicar o padding
# A lógica aqui é definir um alvo (ex: 1080p de altura para 9:16)
if target_ratio < 1: # Vertical ou Quadrado
nova_altura = 1920 if target_ratio == 9/16 else 1350 if target_ratio == 4/5 else 1080
nova_largura = int(nova_altura * target_ratio)
else: # Horizontal
nova_largura = 1920
nova_altura = int(nova_largura / target_ratio)
formato_saida = st.selectbox("Formato de saída", ["mp4", "avi", "mov", "gif"], key="video_format")
if formato_saida == "gif":
st.info("🎨 GIF será otimizado!")
with col2:
st.subheader("📊 Preview")
st.write(f"**Original:** {width_original}x{height_original}")
if nova_largura and nova_altura:
st.write(f"**Novo:** {nova_largura}x{nova_altura}")
ratio_orig = width_original / height_original
ratio_novo = nova_largura / nova_altura
if abs(ratio_orig - ratio_novo) > 0.1:
st.warning("⚠️ Aspect ratio será alterado!")
if formato_saida == "gif":
st.write("**Formato:** GIF Animado")
st.write("**FPS:** 10 (otimizado)")
if st.button("🎬 Processar Vídeo", type="primary", key="video_process_button"):
with st.spinner(f"Processando {'GIF' if formato_saida == 'gif' else 'vídeo'}..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{formato_saida}') as output_file:
temp_output = output_file.name
if processar_video(temp_input, temp_output, nova_largura, nova_altura, formato=formato_saida, padding=padding_video):
with open(temp_output, 'rb') as f:
mime_type = f"video/{formato_saida}" if formato_saida != "gif" else "image/gif"
st.download_button(
label=f"⬇️ Baixar {'GIF' if formato_saida == 'gif' else 'Vídeo'} Processado",
data=f.read(),
file_name=f"{'animacao' if formato_saida == 'gif' else 'video'}_editado.{formato_saida}",
mime=mime_type,
key="video_download_button"
)
st.success(f"✅ {'GIF' if formato_saida == 'gif' else 'Vídeo'} processado!")
os.unlink(temp_input)
if os.path.exists(temp_output):
os.unlink(temp_output)
except Exception as e:
st.error(f"Erro ao ler vídeo: {str(e)}")
# SEÇÃO DE IMAGENS
elif tipo_edicao == "🖼️ Imagens":
st.header("Edição de Imagens")
image_file = st.file_uploader("Escolha uma imagem", type=['jpg', 'jpeg', 'png', 'bmp', 'tiff'], key="image_uploader")
if image_file is not None:
img = Image.open(image_file)
width_original, height_original = img.size
col1, col2 = st.columns(2)
with col1:
st.subheader("⚙️ Redimensionar e Converter")
st.write(f"Tamanho original: {width_original}x{height_original}")
nova_largura_img = st.number_input("Nova largura", min_value=1, value=width_original, key="img_width_single")
nova_altura_img = st.number_input("Nova altura", min_value=1, value=height_original, key="img_height_single")
manter_proporcao = st.checkbox("Manter proporção", value=True, key="img_prop_single")
preset_img = st.selectbox("Preset de tamanho", [
"Personalizado", "HD (1920x1080)", "Instagram Post (1080x1080)",
"Instagram Story (1080x1920)", "Facebook Cover (1200x630)", "YouTube Thumbnail (1280x720)"
], key="img_preset_single")
if preset_img != "Personalizado":
presets_img = {
"HD (1920x1080)": (1920, 1080),
"Instagram Post (1080x1080)": (1080, 1080),
"Instagram Story (1080x1920)": (1080, 1920),
"Facebook Cover (1200x630)": (1200, 630),
"YouTube Thumbnail (1280x720)": (1280, 720)
}
nova_largura_img, nova_altura_img = presets_img[preset_img]
formato_img = st.selectbox("Formato de saída", ["JPEG", "PNG", "WEBP", "SVG"], key="img_format_single")
qualidade = None
if formato_img == "JPEG":
qualidade = st.slider("Qualidade JPEG", 1, 100, 85, key="img_quality_single")
with col2:
st.subheader("🖼️ Preview")
img_preview = img.copy()
img_preview.thumbnail((400, 300))
st.image(img_preview, caption="Preview da imagem original")
if st.button("🖼️ Processar Imagem", type="primary", key="img_process_single"):
with st.spinner("Processando imagem..."):
if formato_img == "SVG":
try:
# Para SVG, usamos um caminho diferente
image_file.seek(0)
input_bytes = image_file.read()
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{image_file.type.split('/')[1]}") as tmp_in:
tmp_in.write(input_bytes)
temp_input_path = tmp_in.name
with tempfile.NamedTemporaryFile(delete=False, suffix=".svg") as tmp_out:
temp_output_path = tmp_out.name
vtracer.convert_image_to_svg_py(temp_input_path, temp_output_path, colormode='color')
with open(temp_output_path, 'rb') as f:
svg_bytes = f.read()
st.success("✅ Imagem convertida para SVG com sucesso!")
st.download_button(
label="⬇️ Baixar Imagem SVG",
data=svg_bytes,
file_name="imagem_convertida.svg",
mime="image/svg+xml",
key="svg_download_button"
)
os.unlink(temp_input_path)
os.unlink(temp_output_path)
except Exception as e:
st.error(f"Erro ao converter para SVG: {e}")
else:
# Lógica existente para outros formatos
img_processada = processar_imagem(
img.copy(),
nova_largura_img if nova_largura_img != width_original else None,
nova_altura_img if nova_altura_img != height_original else None,
manter_proporcao, formato_img
)
if img_processada:
img_bytes = BytesIO()
save_kwargs = {}
if formato_img == "JPEG" and qualidade is not None:
save_kwargs['quality'] = qualidade
save_kwargs['optimize'] = True
img_processada.save(img_bytes, format=formato_img, **save_kwargs)
img_bytes.seek(0)
col1_res, col2_res = st.columns(2)
with col1_res:
st.write("**Antes:**")
prev_orig = img.copy()
prev_orig.thumbnail((300, 300))
st.image(prev_orig)
with col2_res:
st.write("**Depois:**")
prev_nova = img_processada.copy()
prev_nova.thumbnail((300, 300))
st.image(prev_nova)
ext = formato_img.lower()
if ext == "jpeg":
ext = "jpg"
st.download_button(
label="⬇️ Baixar Imagem Processada",
data=img_bytes.getvalue(),
file_name=f"imagem_editada.{ext}",
mime=f"image/{ext}",
key="img_download_single"
)
st.success("✅ Imagem processada com sucesso!")
st.markdown("---")
st.subheader("✨ Remover Fundo")
with st.expander("🔧 Opções Avançadas de Remoção", expanded=False):
modelo_rembg = st.selectbox(
"Modelo de IA",
["u2net", "u2netp", "u2net_human_seg", "isnet-general-use", "silueta"],
index=3,
help="Cada modelo tem especialidades diferentes. 'isnet-general-use' é bom para uso geral."
)
col_alpha1, col_alpha2 = st.columns(2)
with col_alpha1:
alpha_matting = st.checkbox("Refinamento de bordas (Alpha Matting)", value=False)
with col_alpha2:
post_process_mask = st.checkbox("Pós-processar máscara", value=True, help="Limpa ruídos na máscara final.")
if alpha_matting:
col_t1, col_t2, col_t3 = st.columns(3)
with col_t1:
fg_threshold = st.slider("Limiar primeiro plano", 0, 255, 240,
help="Pixels acima deste valor são considerados primeiro plano.")
with col_t2:
bg_threshold = st.slider("Limial fundo", 0, 255, 10,
help="Pixels abaixo deste valor são considerados fundo.")
with col_t3:
erode_size = st.slider("Erosão da borda", 0, 30, 10,
help="Suaviza as bordas da separação.")
bgcolor_opcao = st.selectbox("Cor de fundo (substituição)", [
"Transparente (sem fundo)", "Branco", "Preto", "Personalizado"
], index=0)
bgcolor_val = None
if bgcolor_opcao == "Branco":
bgcolor_val = (255, 255, 255, 255)
elif bgcolor_opcao == "Preto":
bgcolor_val = (0, 0, 0, 255)
elif bgcolor_opcao == "Personalizado":
bg_r = st.number_input("R", 0, 255, 255, key="bg_r")
bg_g = st.number_input("G", 0, 255, 255, key="bg_g")
bg_b = st.number_input("B", 0, 255, 255, key="bg_b")
bgcolor_val = (bg_r, bg_g, bg_b, 255)
if st.button("🎨 Remover Fundo da Imagem", type="primary", key="bg_remover_button"):
with st.spinner("Processando e removendo o fundo..."):
image_file.seek(0)
input_bytes = image_file.getvalue()
try:
session = rembg.new_session(modelo_rembg)
remove_kwargs = {
"data": input_bytes,
"session": session,
"post_process_mask": post_process_mask,
}
if alpha_matting:
remove_kwargs["alpha_matting"] = True
remove_kwargs["alpha_matting_foreground_threshold"] = fg_threshold
remove_kwargs["alpha_matting_background_threshold"] = bg_threshold
remove_kwargs["alpha_matting_erode_size"] = erode_size
if bgcolor_val is not None:
remove_kwargs["bgcolor"] = bgcolor_val
output_bytes = rembg.remove(**remove_kwargs)
st.success("✅ Fundo removido com sucesso!")
col1_bg, col2_bg = st.columns(2)
with col1_bg:
st.write("**Original**")
st.image(input_bytes, width=300)
with col2_bg:
st.write("**Sem Fundo**")
st.image(output_bytes, width=300)
st.download_button(
label="⬇️ Baixar Imagem sem Fundo",
data=output_bytes,
file_name=f"{os.path.splitext(image_file.name)[0]}_sem_fundo.png",
mime="image/png",
key="bg_remover_download_button"
)
except Exception as e:
st.error(f"Ocorreu um erro ao remover o fundo: {e}")
# SEÇÃO DE LOTE DE IMAGENS
elif tipo_edicao == "📦 Lote de Imagens":
st.header("Edição em Lote de Imagens")
st.markdown("Faça upload de várias imagens e processe todas de uma vez!")
image_files = st.file_uploader("Escolha várias imagens", type=['jpg', 'jpeg', 'png', 'bmp'], accept_multiple_files=True, key="lote_uploader")
if image_files:
st.success(f"📁 {len(image_files)} imagens carregadas")
col1, col2 = st.columns(2)
with col1:
st.subheader("⚙️ Configurações para todas as imagens")
largura_lote = st.number_input("Largura", min_value=1, value=1920, key="lote_width")
altura_lote = st.number_input("Altura", min_value=1, value=1080, key="lote_height")
manter_proporcao_lote = st.checkbox("Manter proporção", value=True, key="lote_prop")
formato_lote = st.selectbox("Formato de saída", ["JPEG", "PNG", "WEBP", "SVG"], key="lote_format")
qualidade_lote = None
if formato_lote == "JPEG":
qualidade_lote = st.slider("Qualidade JPEG", 1, 100, 85, key="lote_quality")
with col2:
st.subheader("📊 Informações")
st.write(f"**Imagens selecionadas:** {len(image_files)}")
st.write(f"**Tamanho final:** {largura_lote}x{altura_lote}")
st.write(f"**Formato:** {formato_lote}")
if st.button("📦 Processar Lote", type="primary", key="lote_process_button"):
progress_bar = st.progress(0)
status_text = st.empty()
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for i, image_file in enumerate(image_files):
status_text.text(f"Processando {image_file.name}...")
try:
nome_original = os.path.splitext(image_file.name)[0]
if formato_lote == "SVG":
image_file.seek(0)
input_bytes = image_file.read()
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{image_file.type.split('/')[1]}") as tmp_in:
tmp_in.write(input_bytes)
temp_input_path = tmp_in.name
with tempfile.NamedTemporaryFile(delete=False, suffix=".svg") as tmp_out:
temp_output_path = tmp_out.name
vtracer.convert_image_to_svg_py(temp_input_path, temp_output_path, colormode='color')
novo_nome = f"{nome_original}_editado.svg"
zip_file.write(temp_output_path, novo_nome)
os.unlink(temp_input_path)
os.unlink(temp_output_path)
else:
img = Image.open(image_file)
img_processada = processar_imagem(img, largura_lote, altura_lote, manter_proporcao_lote, formato_lote)
if img_processada:
img_bytes = BytesIO()
save_kwargs = {}
if formato_lote == "JPEG" and qualidade_lote is not None:
save_kwargs['quality'] = qualidade_lote
save_kwargs['optimize'] = True
img_processada.save(img_bytes, format=formato_lote, **save_kwargs)
ext = formato_lote.lower()
if ext == "jpeg":
ext = "jpg"
novo_nome = f"{nome_original}_editado.{ext}"
zip_file.writestr(novo_nome, img_bytes.getvalue())
except Exception as e:
st.warning(f"Erro ao processar {image_file.name}: {str(e)}")
progress_bar.progress((i + 1) / len(image_files))
status_text.text("✅ Processamento concluído!")
zip_buffer.seek(0)
st.download_button(
label="⬇️ Baixar ZIP com Imagens Processadas",
data=zip_buffer.getvalue(),
file_name="imagens_editadas.zip",
mime="application/zip",
key="lote_download_button"
)
st.success(f"✅ {len(image_files)} imagens processadas com sucesso!")
# SEÇÃO DE DOWNLOAD DO YOUTUBE
elif tipo_edicao == "📥 Baixar do YouTube":
st.header("📥 Baixar Vídeo do YouTube")
url = st.text_input("Cole a URL do vídeo do YouTube aqui:", key="youtube_url_input")
if url:
try:
progress_bar = st.empty()
status_text = st.empty()
def on_progress(stream, chunk, bytes_remaining):
total_size = stream.filesize
bytes_downloaded = total_size - bytes_remaining
percentage = int((bytes_downloaded / total_size) * 100)
status_text.text(f"Baixando... {percentage}%")
progress_bar.progress(percentage)
yt = YouTube(url, on_progress_callback=on_progress)
st.write(f"**{yt.title}**")
st.image(yt.thumbnail_url, width=400)
# Filtrar streams para ter vídeo e áudio (progressive)
video_streams = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc()
if not video_streams:
st.warning("Nenhuma stream de vídeo MP4 (com áudio) encontrada para este vídeo.")
else:
stream_options = [f"{stream.resolution} ({stream.filesize_mb:.2f} MB)" for stream in video_streams]
chosen_option = st.selectbox("Escolha a qualidade do vídeo para baixar:", stream_options, key="youtube_quality_select")
if st.button("📥 Baixar Vídeo", type="primary", key="youtube_download_button"):
selected_stream = None
for stream in video_streams:
if f"{stream.resolution} ({stream.filesize_mb:.2f} MB)" == chosen_option:
selected_stream = stream
break
if selected_stream:
with st.spinner(f"Iniciando download em {selected_stream.resolution}..."):
with tempfile.TemporaryDirectory() as temp_dir:
file_path = selected_stream.download(output_path=temp_dir)
file_name = os.path.basename(file_path)
with open(file_path, 'rb') as f:
video_bytes = f.read()
status_text.text("✅ Download concluído!")
progress_bar.empty()
st.download_button(
label="⬇️ Clique para salvar o vídeo",
data=video_bytes,
file_name=file_name,
mime="video/mp4",
key="youtube_save_button"
)
else:
st.error("Não foi possível encontrar a stream selecionada. Tente novamente.")
except Exception as e:
st.error(f"Ocorreu um erro: {e}")
st.warning("Verifique se a URL está correta ou tente um vídeo diferente. Alguns vídeos podem ter restrições de download que impedem o acesso.")
# Footer
st.markdown("---")
st.markdown("🚀 **Editor Local** - Seus arquivos não saem do seu computador!")