Spaces:
Sleeping
Sleeping
Commit ·
5fcf371
0
Parent(s):
Initial commit of the video and image editor project
Browse files- .gitignore +17 -0
- DOCUMENTACAO.md +263 -0
- Editor.bat +19 -0
- main.py +772 -0
- packages.txt +1 -0
- requirements.txt +0 -0
- upscale_realesrgan.py +1 -0
.gitignore
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ambiente Virtual
|
| 2 |
+
venv/
|
| 3 |
+
__pycache__/
|
| 4 |
+
|
| 5 |
+
# Arquivos temporários e de cache
|
| 6 |
+
*.pyc
|
| 7 |
+
*.pyo
|
| 8 |
+
*.pyd
|
| 9 |
+
.DS_Store
|
| 10 |
+
|
| 11 |
+
# Arquivos de distribuição
|
| 12 |
+
*.egg-info/
|
| 13 |
+
dist/
|
| 14 |
+
build/
|
| 15 |
+
|
| 16 |
+
# Arquivos zipados
|
| 17 |
+
*.zip
|
DOCUMENTACAO.md
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚀 Guia Completo - Escalando o Editor de Vídeo/Imagem
|
| 2 |
+
|
| 3 |
+
## 📋 **Estrutura do Código**
|
| 4 |
+
|
| 5 |
+
### **1. Imports e Configuração**
|
| 6 |
+
```python
|
| 7 |
+
import streamlit as st # Interface web
|
| 8 |
+
import ffmpeg # Processamento de vídeo
|
| 9 |
+
from PIL import Image # Processamento de imagem
|
| 10 |
+
import tempfile # Arquivos temporários
|
| 11 |
+
import os # Sistema operacional
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
### **2. Anatomia das Funções**
|
| 15 |
+
|
| 16 |
+
**Função de Processamento de Vídeo:**
|
| 17 |
+
```python
|
| 18 |
+
def processar_video(input_path, output_path, largura=None, altura=None, crop=None, formato="mp4"):
|
| 19 |
+
# 1. Verificar formato
|
| 20 |
+
# 2. Montar comando/filtros
|
| 21 |
+
# 3. Executar processamento
|
| 22 |
+
# 4. Retornar True/False
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
**Função de Processamento de Imagem:**
|
| 26 |
+
```python
|
| 27 |
+
def processar_imagem(img, largura=None, altura=None, manter_proporcao=True, formato="JPEG"):
|
| 28 |
+
# 1. Aplicar transformações PIL
|
| 29 |
+
# 2. Retornar imagem processada
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## 🛠️ **Como Adicionar Novos Formatos de Vídeo**
|
| 35 |
+
|
| 36 |
+
### **Passo 1: Adicionar na Interface**
|
| 37 |
+
```python
|
| 38 |
+
# Localizar esta linha (aprox. linha 150)
|
| 39 |
+
formato_saida = st.selectbox("Formato de saída", ["mp4", "avi", "mov", "gif"])
|
| 40 |
+
|
| 41 |
+
# Modificar para:
|
| 42 |
+
formato_saida = st.selectbox("Formato de saída", ["mp4", "avi", "mov", "gif", "webm", "mkv"])
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
### **Passo 2: Adicionar Lógica de Processamento**
|
| 46 |
+
```python
|
| 47 |
+
# Na função processar_video(), adicionar novo elif:
|
| 48 |
+
elif formato == "webm":
|
| 49 |
+
out = ffmpeg.output(stream, output_path,
|
| 50 |
+
vcodec='libvpx-vp9',
|
| 51 |
+
acodec='libvorbis',
|
| 52 |
+
crf=30)
|
| 53 |
+
elif formato == "mkv":
|
| 54 |
+
out = ffmpeg.output(stream, output_path,
|
| 55 |
+
vcodec='libx264',
|
| 56 |
+
acodec='aac',
|
| 57 |
+
crf=23)
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
### **Passo 3: Atualizar Download**
|
| 61 |
+
```python
|
| 62 |
+
# Atualizar mime type (aprox. linha 180)
|
| 63 |
+
mime_mapping = {
|
| 64 |
+
"mp4": "video/mp4",
|
| 65 |
+
"avi": "video/x-msvideo",
|
| 66 |
+
"mov": "video/quicktime",
|
| 67 |
+
"webm": "video/webm",
|
| 68 |
+
"mkv": "video/x-matroska",
|
| 69 |
+
"gif": "image/gif"
|
| 70 |
+
}
|
| 71 |
+
mime_type = mime_mapping.get(formato_saida, f"video/{formato_saida}")
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
---
|
| 75 |
+
|
| 76 |
+
## 🎨 **Como Adicionar Novos Filtros de Vídeo**
|
| 77 |
+
|
| 78 |
+
### **Exemplo: Adicionar Filtro de Velocidade**
|
| 79 |
+
|
| 80 |
+
**1. Interface:**
|
| 81 |
+
```python
|
| 82 |
+
# Adicionar após as configurações de redimensionamento
|
| 83 |
+
velocidade = st.selectbox("Velocidade", ["Normal", "2x Mais Rápido", "0.5x Mais Lento"])
|
| 84 |
+
|
| 85 |
+
# Converter para valor
|
| 86 |
+
speed_mapping = {
|
| 87 |
+
"Normal": 1.0,
|
| 88 |
+
"2x Mais Rápido": 2.0,
|
| 89 |
+
"0.5x Mais Lento": 0.5
|
| 90 |
+
}
|
| 91 |
+
speed_value = speed_mapping[velocidade]
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
**2. Processamento:**
|
| 95 |
+
```python
|
| 96 |
+
# Na função processar_video(), adicionar filtro:
|
| 97 |
+
if speed_value != 1.0:
|
| 98 |
+
if formato == "gif":
|
| 99 |
+
filtros.append(f'setpts={1/speed_value}*PTS') # Para GIF
|
| 100 |
+
else:
|
| 101 |
+
stream = ffmpeg.filter(stream, 'setpts', f'{1/speed_value}*PTS') # Para vídeo
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
### **Exemplo: Adicionar Filtro de Brilho**
|
| 105 |
+
```python
|
| 106 |
+
# Interface
|
| 107 |
+
brilho = st.slider("Brilho", -1.0, 1.0, 0.0, 0.1)
|
| 108 |
+
|
| 109 |
+
# Processamento
|
| 110 |
+
if brilho != 0.0:
|
| 111 |
+
if formato == "gif":
|
| 112 |
+
filtros.append(f'eq=brightness={brilho}')
|
| 113 |
+
else:
|
| 114 |
+
stream = ffmpeg.filter(stream, 'eq', brightness=brilho)
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
---
|
| 118 |
+
|
| 119 |
+
## 🖼️ **Como Adicionar Novos Filtros de Imagem**
|
| 120 |
+
|
| 121 |
+
### **Exemplo: Adicionar Filtro de Rotação**
|
| 122 |
+
|
| 123 |
+
**1. Interface:**
|
| 124 |
+
```python
|
| 125 |
+
rotacao = st.selectbox("Rotação", ["0°", "90°", "180°", "270°"])
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
**2. Processamento:**
|
| 129 |
+
```python
|
| 130 |
+
# Na função processar_imagem()
|
| 131 |
+
rotation_mapping = {"0°": 0, "90°": 90, "180°": 180, "270°": 270}
|
| 132 |
+
if rotacao != "0°":
|
| 133 |
+
angle = rotation_mapping[rotacao]
|
| 134 |
+
img = img.rotate(angle, expand=True)
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
### **Exemplo: Adicionar Filtro de Blur**
|
| 138 |
+
```python
|
| 139 |
+
# Interface
|
| 140 |
+
blur_amount = st.slider("Blur", 0, 10, 0)
|
| 141 |
+
|
| 142 |
+
# Import adicional no topo
|
| 143 |
+
from PIL import ImageFilter
|
| 144 |
+
|
| 145 |
+
# Processamento
|
| 146 |
+
if blur_amount > 0:
|
| 147 |
+
img = img.filter(ImageFilter.GaussianBlur(radius=blur_amount))
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
---
|
| 151 |
+
|
| 152 |
+
## 📦 **Como Adicionar Nova Aba**
|
| 153 |
+
|
| 154 |
+
### **Exemplo: Aba de "Conversão de Formatos"**
|
| 155 |
+
|
| 156 |
+
**1. Adicionar na Interface:**
|
| 157 |
+
```python
|
| 158 |
+
# Localizar esta linha (aprox. linha 20)
|
| 159 |
+
tipo_edicao = st.sidebar.selectbox(
|
| 160 |
+
"Tipo de Edição",
|
| 161 |
+
["📹 Vídeos", "🖼️ Imagens", "📦 Lote de Imagens"]
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# Modificar para:
|
| 165 |
+
tipo_edicao = st.sidebar.selectbox(
|
| 166 |
+
"Tipo de Edição",
|
| 167 |
+
["📹 Vídeos", "🖼️ Imagens", "📦 Lote de Imagens", "🔄 Conversão"]
|
| 168 |
+
)
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
**2. Adicionar Lógica da Aba:**
|
| 172 |
+
```python
|
| 173 |
+
# Adicionar após as outras seções
|
| 174 |
+
elif tipo_edicao == "🔄 Conversão":
|
| 175 |
+
st.header("Conversão de Formatos")
|
| 176 |
+
|
| 177 |
+
arquivo = st.file_uploader("Escolha um arquivo", type=['mp4', 'avi', 'mov', 'mkv'])
|
| 178 |
+
|
| 179 |
+
if arquivo is not None:
|
| 180 |
+
formato_destino = st.selectbox("Converter para:", ["mp4", "avi", "webm", "gif"])
|
| 181 |
+
|
| 182 |
+
if st.button("🔄 Converter"):
|
| 183 |
+
# Lógica de conversão aqui
|
| 184 |
+
pass
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
---
|
| 188 |
+
|
| 189 |
+
## 📚 **Documentações Essenciais**
|
| 190 |
+
|
| 191 |
+
### **🎬 FFmpeg**
|
| 192 |
+
- **Oficial:** https://ffmpeg.org/documentation.html
|
| 193 |
+
- **Filtros:** https://ffmpeg.org/ffmpeg-filters.html
|
| 194 |
+
- **Python FFmpeg:** https://github.com/kkroening/ffmpeg-python
|
| 195 |
+
|
| 196 |
+
### **🖼️ PIL/Pillow**
|
| 197 |
+
- **Oficial:** https://pillow.readthedocs.io/
|
| 198 |
+
- **Filtros:** https://pillow.readthedocs.io/en/stable/reference/ImageFilter.html
|
| 199 |
+
- **Transformações:** https://pillow.readthedocs.io/en/stable/handbook/tutorial.html
|
| 200 |
+
|
| 201 |
+
### **🌐 Streamlit**
|
| 202 |
+
- **Oficial:** https://docs.streamlit.io/
|
| 203 |
+
- **Widgets:** https://docs.streamlit.io/library/api-reference/widgets
|
| 204 |
+
- **Layout:** https://docs.streamlit.io/library/api-reference/layout
|
| 205 |
+
|
| 206 |
+
---
|
| 207 |
+
|
| 208 |
+
## 🔧 **Template para Adicionar Recursos**
|
| 209 |
+
|
| 210 |
+
### **1. Novo Filtro de Vídeo:**
|
| 211 |
+
```python
|
| 212 |
+
# Interface (adicionar nas configurações)
|
| 213 |
+
meu_filtro = st.checkbox("Ativar Meu Filtro")
|
| 214 |
+
if meu_filtro:
|
| 215 |
+
intensidade = st.slider("Intensidade", 0, 100, 50)
|
| 216 |
+
|
| 217 |
+
# Processamento GIF
|
| 218 |
+
if meu_filtro:
|
| 219 |
+
filtros.append(f'meu_filtro_ffmpeg={intensidade/100}')
|
| 220 |
+
|
| 221 |
+
# Processamento Vídeo Normal
|
| 222 |
+
if meu_filtro:
|
| 223 |
+
stream = ffmpeg.filter(stream, 'meu_filtro_ffmpeg', intensidade/100)
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
### **2. Novo Filtro de Imagem:**
|
| 227 |
+
```python
|
| 228 |
+
# Interface
|
| 229 |
+
aplicar_filtro = st.checkbox("Aplicar Filtro")
|
| 230 |
+
|
| 231 |
+
# Processamento (na função processar_imagem)
|
| 232 |
+
if aplicar_filtro:
|
| 233 |
+
# Usar métodos PIL aqui
|
| 234 |
+
img = img.filter(ImageFilter.CONTOUR)
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
### **3. Novo Formato:**
|
| 238 |
+
```python
|
| 239 |
+
# 1. Adicionar na lista de formatos
|
| 240 |
+
# 2. Adicionar lógica no elif formato == "novo_formato"
|
| 241 |
+
# 3. Adicionar mime type
|
| 242 |
+
# 4. Testar!
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
---
|
| 246 |
+
|
| 247 |
+
## 🚀 **Próximos Passos Sugeridos**
|
| 248 |
+
|
| 249 |
+
1. **Começar Simples:** Adicione um novo preset de resolução
|
| 250 |
+
2. **Filtros Básicos:** Blur, brilho, contraste para imagens
|
| 251 |
+
3. **Formatos Novos:** WEBM, MKV para vídeos
|
| 252 |
+
4. **Funcionalidades:** Corte de tempo, fade in/out
|
| 253 |
+
5. **Interface:** Drag & drop, preview em tempo real
|
| 254 |
+
|
| 255 |
+
## 💡 **Dicas de Desenvolvimento**
|
| 256 |
+
|
| 257 |
+
- **Sempre testar** cada mudança separadamente
|
| 258 |
+
- **Usar try/except** para capturar erros
|
| 259 |
+
- **Comentar código** novo que você adicionar
|
| 260 |
+
- **Backup** antes de mudanças grandes
|
| 261 |
+
- **Streamlit rerun** automaticamente ao salvar arquivo
|
| 262 |
+
|
| 263 |
+
**Para recarregar após mudanças:** Salve o arquivo e a página atualiza sozinha! 🔄
|
Editor.bat
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
echo ====================================================================
|
| 3 |
+
echo Configurando o ambiente e instalando dependencias...
|
| 4 |
+
echo Isso pode levar um momento na primeira execucao.
|
| 5 |
+
echo ====================================================================
|
| 6 |
+
|
| 7 |
+
REM Ativa o ambiente virtual
|
| 8 |
+
call venv\Scripts\activate
|
| 9 |
+
|
| 10 |
+
REM Instala/atualiza as dependencias a partir do requirements.txt
|
| 11 |
+
pip install -r requirements.txt
|
| 12 |
+
|
| 13 |
+
echo.
|
| 14 |
+
echo ====================================================================
|
| 15 |
+
echo Iniciando o Editor...
|
| 16 |
+
echo ====================================================================
|
| 17 |
+
streamlit run main.py
|
| 18 |
+
|
| 19 |
+
pause
|
main.py
ADDED
|
@@ -0,0 +1,772 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 5 |
+
import os
|
| 6 |
+
import zipfile
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
import subprocess
|
| 9 |
+
from pytubefix import YouTube
|
| 10 |
+
import rembg
|
| 11 |
+
import vtracer
|
| 12 |
+
|
| 13 |
+
# Configuração da página
|
| 14 |
+
st.set_page_config(
|
| 15 |
+
page_title="Editor de Vídeo e Imagem",
|
| 16 |
+
page_icon="🎬",
|
| 17 |
+
layout="wide"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
st.title("🎬 Editor de Vídeo, Imagem e Áudio Local")
|
| 21 |
+
st.markdown("Redimensione, mude aspect ratio e edite seus arquivos localmente!")
|
| 22 |
+
|
| 23 |
+
# Sidebar para escolher tipo de edição
|
| 24 |
+
tipo_edicao = st.sidebar.selectbox(
|
| 25 |
+
"Tipo de Edição",
|
| 26 |
+
["📹 Vídeos", "🖼️ Imagens", "📦 Lote de Imagens", "🎵 Áudio", "📥 Baixar do YouTube"]
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def processar_video(input_path, output_path, largura=None, altura=None, crop=None, formato="mp4", padding=False):
|
| 30 |
+
"""Processa vídeo com FFmpeg"""
|
| 31 |
+
try:
|
| 32 |
+
# Lógica para GIF permanece a mesma
|
| 33 |
+
if formato == "gif":
|
| 34 |
+
cmd = ['ffmpeg', '-i', input_path, '-y']
|
| 35 |
+
filtros = []
|
| 36 |
+
|
| 37 |
+
if crop:
|
| 38 |
+
x, y, w, h = crop
|
| 39 |
+
filtros.append(f'crop={w}:{h}:{x}:{y}')
|
| 40 |
+
|
| 41 |
+
if largura and altura:
|
| 42 |
+
filtros.append(f'scale={largura}:{altura}')
|
| 43 |
+
elif largura:
|
| 44 |
+
filtros.append(f'scale={largura}:-1')
|
| 45 |
+
elif altura:
|
| 46 |
+
filtros.append(f'scale=-1:{altura}')
|
| 47 |
+
|
| 48 |
+
filtros.append('fps=10')
|
| 49 |
+
|
| 50 |
+
if filtros:
|
| 51 |
+
cmd.extend(['-vf', ','.join(filtros)])
|
| 52 |
+
|
| 53 |
+
cmd.append(output_path)
|
| 54 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 55 |
+
|
| 56 |
+
if result.returncode != 0:
|
| 57 |
+
raise Exception(f"FFmpeg error: {result.stderr}")
|
| 58 |
+
else:
|
| 59 |
+
stream = ffmpeg.input(input_path)
|
| 60 |
+
|
| 61 |
+
if crop:
|
| 62 |
+
x, y, w, h = crop
|
| 63 |
+
stream = ffmpeg.crop(stream, x, y, w, h)
|
| 64 |
+
|
| 65 |
+
if padding and largura and altura:
|
| 66 |
+
# Redimensiona mantendo o aspect ratio e adiciona barras pretas
|
| 67 |
+
stream = ffmpeg.filter(stream, 'scale', w=f'if(gt(a,{largura}/{altura}),{largura},-1)', h=f'if(gt(a,{largura}/{altura}),-1,{altura})')
|
| 68 |
+
stream = ffmpeg.filter(stream, 'pad', w=largura, h=altura, x='(ow-iw)/2', y='(oh-ih)/2', color='black')
|
| 69 |
+
elif largura and altura:
|
| 70 |
+
stream = ffmpeg.filter(stream, 'scale', largura, altura)
|
| 71 |
+
elif largura:
|
| 72 |
+
stream = ffmpeg.filter(stream, 'scale', largura, -1)
|
| 73 |
+
elif altura:
|
| 74 |
+
stream = ffmpeg.filter(stream, 'scale', -1, altura)
|
| 75 |
+
|
| 76 |
+
out = ffmpeg.output(stream, output_path, vcodec='libx264', acodec='aac', crf=23)
|
| 77 |
+
ffmpeg.run(out, overwrite_output=True, quiet=True)
|
| 78 |
+
|
| 79 |
+
return True
|
| 80 |
+
except Exception as e:
|
| 81 |
+
st.error(f"Erro ao processar vídeo: {str(e)}")
|
| 82 |
+
return False
|
| 83 |
+
|
| 84 |
+
def processar_imagem(img, largura=None, altura=None, manter_proporcao=True, formato="JPEG"):
|
| 85 |
+
"""Processa imagem com PIL"""
|
| 86 |
+
try:
|
| 87 |
+
if manter_proporcao:
|
| 88 |
+
if largura and altura:
|
| 89 |
+
img.thumbnail((largura, altura), Image.Resampling.LANCZOS)
|
| 90 |
+
elif largura:
|
| 91 |
+
ratio = largura / img.width
|
| 92 |
+
nova_altura = int(img.height * ratio)
|
| 93 |
+
img = img.resize((largura, nova_altura), Image.Resampling.LANCZOS)
|
| 94 |
+
elif altura:
|
| 95 |
+
ratio = altura / img.height
|
| 96 |
+
nova_largura = int(img.width * ratio)
|
| 97 |
+
img = img.resize((nova_largura, altura), Image.Resampling.LANCZOS)
|
| 98 |
+
else:
|
| 99 |
+
if largura and altura:
|
| 100 |
+
img = img.resize((largura, altura), Image.Resampling.LANCZOS)
|
| 101 |
+
|
| 102 |
+
return img
|
| 103 |
+
except Exception as e:
|
| 104 |
+
st.error(f"Erro ao processar imagem: {str(e)}")
|
| 105 |
+
return None
|
| 106 |
+
|
| 107 |
+
def processar_audio(input_path, output_path, formato="mp3", bitrate="192k", sample_rate=None, canais=None):
|
| 108 |
+
"""Processa áudio com FFmpeg"""
|
| 109 |
+
try:
|
| 110 |
+
cmd = ['ffmpeg', '-i', input_path, '-y']
|
| 111 |
+
|
| 112 |
+
if formato == "mp3":
|
| 113 |
+
cmd.extend(['-acodec', 'libmp3lame', '-ab', str(bitrate)])
|
| 114 |
+
elif formato == "wav":
|
| 115 |
+
cmd.extend(['-acodec', 'pcm_s16le'])
|
| 116 |
+
elif formato == "flac":
|
| 117 |
+
cmd.extend(['-acodec', 'flac'])
|
| 118 |
+
elif formato == "aac":
|
| 119 |
+
cmd.extend(['-acodec', 'aac', '-ab', str(bitrate)])
|
| 120 |
+
elif formato == "ogg":
|
| 121 |
+
# OGG precisa de sintaxe específica
|
| 122 |
+
cmd.extend(['-acodec', 'libvorbis', '-q:a', '4']) # Qualidade ao invés de bitrate
|
| 123 |
+
|
| 124 |
+
if sample_rate and sample_rate != "Manter original":
|
| 125 |
+
cmd.extend(['-ar', str(sample_rate)])
|
| 126 |
+
|
| 127 |
+
if canais and canais != "Manter original":
|
| 128 |
+
cmd.extend(['-ac', str(canais)])
|
| 129 |
+
|
| 130 |
+
cmd.append(output_path)
|
| 131 |
+
|
| 132 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 133 |
+
|
| 134 |
+
if result.returncode != 0:
|
| 135 |
+
raise Exception(f"FFmpeg error: {result.stderr}")
|
| 136 |
+
|
| 137 |
+
return True
|
| 138 |
+
except Exception as e:
|
| 139 |
+
st.error(f"Erro ao processar áudio: {str(e)}")
|
| 140 |
+
return False
|
| 141 |
+
|
| 142 |
+
def extrair_audio_video(input_path, output_path, formato="mp3", bitrate="192k"):
|
| 143 |
+
"""Extrai áudio de vídeo"""
|
| 144 |
+
try:
|
| 145 |
+
cmd = ['ffmpeg', '-i', input_path, '-vn', '-y']
|
| 146 |
+
|
| 147 |
+
if formato == "mp3":
|
| 148 |
+
cmd.extend(['-acodec', 'libmp3lame', '-ab', str(bitrate)])
|
| 149 |
+
elif formato == "wav":
|
| 150 |
+
cmd.extend(['-acodec', 'pcm_s16le'])
|
| 151 |
+
elif formato == "flac":
|
| 152 |
+
cmd.extend(['-acodec', 'flac'])
|
| 153 |
+
elif formato == "aac":
|
| 154 |
+
cmd.extend(['-acodec', 'aac', '-ab', str(bitrate)])
|
| 155 |
+
|
| 156 |
+
cmd.append(output_path)
|
| 157 |
+
|
| 158 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 159 |
+
|
| 160 |
+
if result.returncode != 0:
|
| 161 |
+
raise Exception(f"FFmpeg error: {result.stderr}")
|
| 162 |
+
|
| 163 |
+
return True
|
| 164 |
+
except Exception as e:
|
| 165 |
+
st.error(f"Erro ao extrair áudio: {str(e)}")
|
| 166 |
+
return False
|
| 167 |
+
|
| 168 |
+
# IMPORTAR FUNÇÕES DE ÁUDIO
|
| 169 |
+
if tipo_edicao == "🎵 Áudio":
|
| 170 |
+
# SEÇÃO DE ÁUDIO
|
| 171 |
+
st.header("Processamento de Áudio")
|
| 172 |
+
|
| 173 |
+
operacao = st.selectbox("Tipo de Operação", [
|
| 174 |
+
"🎵 Converter Áudio para Áudio",
|
| 175 |
+
"📹➡️🎵 Extrair Áudio de Vídeo"
|
| 176 |
+
], key="audio_op")
|
| 177 |
+
|
| 178 |
+
if operacao == "🎵 Converter Áudio para Áudio":
|
| 179 |
+
st.subheader("Conversão de Formatos de Áudio")
|
| 180 |
+
|
| 181 |
+
audio_file = st.file_uploader("Escolha um arquivo de áudio",
|
| 182 |
+
type=['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a', 'wma',"mp4"],
|
| 183 |
+
key="audio_uploader")
|
| 184 |
+
|
| 185 |
+
if audio_file is not None:
|
| 186 |
+
file_extension = os.path.splitext(audio_file.name)[1]
|
| 187 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as tmp_file:
|
| 188 |
+
tmp_file.write(audio_file.read())
|
| 189 |
+
temp_input = tmp_file.name
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
probe = ffmpeg.probe(temp_input)
|
| 193 |
+
audio_info = next(s for s in probe['streams'] if s['codec_type'] == 'audio')
|
| 194 |
+
|
| 195 |
+
sample_rate_original = int(audio_info.get('sample_rate', 0))
|
| 196 |
+
channels_original = int(audio_info.get('channels', 0))
|
| 197 |
+
bitrate_original = audio_info.get('bit_rate', 'N/A')
|
| 198 |
+
|
| 199 |
+
st.success(f"Áudio carregado: {sample_rate_original}Hz, {channels_original} canais")
|
| 200 |
+
|
| 201 |
+
col1, col2 = st.columns(2)
|
| 202 |
+
|
| 203 |
+
with col1:
|
| 204 |
+
st.subheader("⚙️ Configurações")
|
| 205 |
+
|
| 206 |
+
formato_audio = st.selectbox("Formato de saída", ["mp3", "wav", "flac", "aac", "ogg","mp4"], key="audio_format")
|
| 207 |
+
|
| 208 |
+
if formato_audio in ["mp3", "aac","mp4"]:
|
| 209 |
+
bitrate_audio = st.selectbox("Bitrate", ["128k", "192k", "256k", "320k"], index=1, key="audio_bitrate")
|
| 210 |
+
elif formato_audio == "ogg":
|
| 211 |
+
bitrate_audio = st.selectbox("Qualidade OGG", ["2 (baixa)", "4 (média)", "6 (alta)", "8 (máxima)"], index=1, key="audio_ogg_quality")
|
| 212 |
+
else:
|
| 213 |
+
bitrate_audio = None
|
| 214 |
+
|
| 215 |
+
sample_rate_novo = st.selectbox("Sample Rate",
|
| 216 |
+
["Manter original", "22050", "44100", "48000", "96000"], key="audio_samplerate")
|
| 217 |
+
if sample_rate_novo == "Manter original":
|
| 218 |
+
sample_rate_novo = None
|
| 219 |
+
else:
|
| 220 |
+
sample_rate_novo = int(sample_rate_novo)
|
| 221 |
+
|
| 222 |
+
canais_novo = st.selectbox("Canais", ["Manter original", "1 (Mono)", "2 (Stereo)"], key="audio_channels")
|
| 223 |
+
if canais_novo == "Manter original":
|
| 224 |
+
canais_novo = None
|
| 225 |
+
elif canais_novo == "1 (Mono)":
|
| 226 |
+
canais_novo = 1
|
| 227 |
+
else:
|
| 228 |
+
canais_novo = 2
|
| 229 |
+
|
| 230 |
+
with col2:
|
| 231 |
+
st.subheader("📊 Informações")
|
| 232 |
+
st.write(f"**Original:** {sample_rate_original}Hz, {channels_original} canais")
|
| 233 |
+
st.write(f"**Formato original:** {file_extension.upper()}")
|
| 234 |
+
if bitrate_original != 'N/A':
|
| 235 |
+
st.write(f"**Bitrate original:** {int(bitrate_original)//1000}k")
|
| 236 |
+
|
| 237 |
+
st.write("---")
|
| 238 |
+
st.write(f"**Novo formato:** {formato_audio.upper()}")
|
| 239 |
+
if sample_rate_novo:
|
| 240 |
+
st.write(f"**Novo sample rate:** {sample_rate_novo}Hz")
|
| 241 |
+
if canais_novo:
|
| 242 |
+
st.write(f"**Novos canais:** {canais_novo}")
|
| 243 |
+
if bitrate_audio:
|
| 244 |
+
st.write(f"**Novo bitrate:** {bitrate_audio}")
|
| 245 |
+
|
| 246 |
+
if st.button("🎵 Converter Áudio", type="primary", key="audio_convert_button"):
|
| 247 |
+
with st.spinner("Convertendo áudio..."):
|
| 248 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{formato_audio}') as output_file:
|
| 249 |
+
temp_output = output_file.name
|
| 250 |
+
|
| 251 |
+
if processar_audio(temp_input, temp_output, formato_audio, bitrate_audio, sample_rate_novo, canais_novo):
|
| 252 |
+
with open(temp_output, 'rb') as f:
|
| 253 |
+
st.download_button(
|
| 254 |
+
label="⬇️ Baixar Áudio Convertido",
|
| 255 |
+
data=f.read(),
|
| 256 |
+
file_name=f"audio_convertido.{formato_audio}",
|
| 257 |
+
mime=f"audio/{formato_audio}",
|
| 258 |
+
key="audio_download_button"
|
| 259 |
+
)
|
| 260 |
+
st.success("✅ Áudio convertido com sucesso!")
|
| 261 |
+
|
| 262 |
+
os.unlink(temp_input)
|
| 263 |
+
if os.path.exists(temp_output):
|
| 264 |
+
os.unlink(temp_output)
|
| 265 |
+
|
| 266 |
+
except Exception as e:
|
| 267 |
+
st.error(f"Erro ao processar áudio: {str(e)}")
|
| 268 |
+
|
| 269 |
+
elif operacao == "📹➡️🎵 Extrair Áudio de Vídeo":
|
| 270 |
+
st.subheader("Extrair Áudio de Vídeo")
|
| 271 |
+
|
| 272 |
+
video_file = st.file_uploader("Escolha um vídeo para extrair o áudio",
|
| 273 |
+
type=['mp4', 'avi', 'mov', 'mkv', 'flv', 'webm'],
|
| 274 |
+
key="audio_extract_uploader")
|
| 275 |
+
|
| 276 |
+
if video_file is not None:
|
| 277 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_file:
|
| 278 |
+
tmp_file.write(video_file.read())
|
| 279 |
+
temp_input = tmp_file.name
|
| 280 |
+
|
| 281 |
+
try:
|
| 282 |
+
probe = ffmpeg.probe(temp_input)
|
| 283 |
+
audio_info = next((s for s in probe['streams'] if s['codec_type'] == 'audio'), None)
|
| 284 |
+
|
| 285 |
+
if audio_info:
|
| 286 |
+
st.success(f"Áudio encontrado no vídeo!")
|
| 287 |
+
|
| 288 |
+
col1, col2 = st.columns(2)
|
| 289 |
+
|
| 290 |
+
with col1:
|
| 291 |
+
st.subheader("⚙️ Configurações")
|
| 292 |
+
|
| 293 |
+
formato_extracao = st.selectbox("Formato do áudio extraído",
|
| 294 |
+
["mp3", "wav", "flac", "aac"],
|
| 295 |
+
key="audio_extract_format")
|
| 296 |
+
|
| 297 |
+
if formato_extracao in ["mp3", "aac"]:
|
| 298 |
+
bitrate_extracao = st.selectbox("Qualidade",
|
| 299 |
+
["128k", "192k", "256k", "320k"],
|
| 300 |
+
index=1,
|
| 301 |
+
key="audio_extract_quality")
|
| 302 |
+
else:
|
| 303 |
+
bitrate_extracao = None
|
| 304 |
+
|
| 305 |
+
with col2:
|
| 306 |
+
st.subheader("📊 Informações")
|
| 307 |
+
sample_rate = audio_info.get('sample_rate', 'N/A')
|
| 308 |
+
channels = audio_info.get('channels', 'N/A')
|
| 309 |
+
st.write(f"**Sample Rate:** {sample_rate}Hz")
|
| 310 |
+
st.write(f"**Canais:** {channels}")
|
| 311 |
+
st.write(f"**Formato de saída:** {formato_extracao.upper()}")
|
| 312 |
+
if bitrate_extracao:
|
| 313 |
+
st.write(f"**Qualidade:** {bitrate_extracao}")
|
| 314 |
+
|
| 315 |
+
if st.button("🎵 Extrair Áudio", type="primary", key="audio_extract_button"):
|
| 316 |
+
with st.spinner("Extraindo áudio do vídeo..."):
|
| 317 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{formato_extracao}') as output_file:
|
| 318 |
+
temp_output = output_file.name
|
| 319 |
+
|
| 320 |
+
if extrair_audio_video(temp_input, temp_output, formato_extracao, bitrate_extracao):
|
| 321 |
+
with open(temp_output, 'rb') as f:
|
| 322 |
+
st.download_button(
|
| 323 |
+
label="⬇️ Baixar Áudio Extraído",
|
| 324 |
+
data=f.read(),
|
| 325 |
+
file_name=f"audio_extraido.{formato_extracao}",
|
| 326 |
+
mime=f"audio/{formato_extracao}",
|
| 327 |
+
key="audio_extract_download_button"
|
| 328 |
+
)
|
| 329 |
+
st.success("✅ Áudio extraído com sucesso!")
|
| 330 |
+
|
| 331 |
+
os.unlink(temp_input)
|
| 332 |
+
if os.path.exists(temp_output):
|
| 333 |
+
os.unlink(temp_output)
|
| 334 |
+
else:
|
| 335 |
+
st.warning("⚠️ Nenhum áudio encontrado neste vídeo!")
|
| 336 |
+
|
| 337 |
+
except Exception as e:
|
| 338 |
+
st.error(f"Erro ao processar vídeo: {str(e)}")
|
| 339 |
+
|
| 340 |
+
# SEÇÃO DE VÍDEOS
|
| 341 |
+
elif tipo_edicao == "📹 Vídeos":
|
| 342 |
+
st.header("Edição de Vídeos")
|
| 343 |
+
|
| 344 |
+
video_file = st.file_uploader("Escolha um vídeo", type=['mp4', 'avi', 'mov', 'mkv'], key="video_uploader")
|
| 345 |
+
|
| 346 |
+
if video_file is not None:
|
| 347 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_file:
|
| 348 |
+
tmp_file.write(video_file.read())
|
| 349 |
+
temp_input = tmp_file.name
|
| 350 |
+
|
| 351 |
+
try:
|
| 352 |
+
probe = ffmpeg.probe(temp_input)
|
| 353 |
+
video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video')
|
| 354 |
+
width_original = int(video_info['width'])
|
| 355 |
+
height_original = int(video_info['height'])
|
| 356 |
+
|
| 357 |
+
st.success(f"Vídeo carregado: {width_original}x{height_original}")
|
| 358 |
+
|
| 359 |
+
col1, col2 = st.columns(2)
|
| 360 |
+
|
| 361 |
+
with col1:
|
| 362 |
+
st.subheader("⚙️ Configurações")
|
| 363 |
+
|
| 364 |
+
# Substituído por um sistema de presets mais claro
|
| 365 |
+
preset = st.selectbox("Preset de Redimensionamento", [
|
| 366 |
+
"Manter original",
|
| 367 |
+
"Personalizado",
|
| 368 |
+
"Vertical (9:16) - TikTok, Reels, Stories",
|
| 369 |
+
"Retrato (4:5) - Feed do Instagram",
|
| 370 |
+
"Quadrado (1:1) - Feed do Instagram",
|
| 371 |
+
"Horizontal (16:9) - X (Twitter), YouTube"
|
| 372 |
+
], key="video_preset_social")
|
| 373 |
+
|
| 374 |
+
nova_largura = None
|
| 375 |
+
nova_altura = None
|
| 376 |
+
padding_video = False
|
| 377 |
+
|
| 378 |
+
if preset == "Personalizado":
|
| 379 |
+
nova_largura = st.number_input("Nova largura", min_value=1, value=width_original, key="video_width_custom")
|
| 380 |
+
nova_altura = st.number_input("Nova altura", min_value=1, value=height_original, key="video_height_custom")
|
| 381 |
+
padding_video = st.checkbox("Manter proporção (adicionar barras pretas)", value=True, key="video_padding_custom")
|
| 382 |
+
|
| 383 |
+
elif preset != "Manter original":
|
| 384 |
+
padding_video = True # Padding é padrão para presets de redes sociais
|
| 385 |
+
aspect_ratios = {
|
| 386 |
+
"Vertical (9:16) - TikTok, Reels, Stories": 9/16,
|
| 387 |
+
"Retrato (4:5) - Feed do Instagram": 4/5,
|
| 388 |
+
"Quadrado (1:1) - Feed do Instagram": 1/1,
|
| 389 |
+
"Horizontal (16:9) - X (Twitter), YouTube": 16/9
|
| 390 |
+
}
|
| 391 |
+
target_ratio = aspect_ratios[preset]
|
| 392 |
+
|
| 393 |
+
# Calcula as novas dimensões mantendo o aspect ratio original, para depois aplicar o padding
|
| 394 |
+
# A lógica aqui é definir um alvo (ex: 1080p de altura para 9:16)
|
| 395 |
+
if target_ratio < 1: # Vertical ou Quadrado
|
| 396 |
+
nova_altura = 1920 if target_ratio == 9/16 else 1350 if target_ratio == 4/5 else 1080
|
| 397 |
+
nova_largura = int(nova_altura * target_ratio)
|
| 398 |
+
else: # Horizontal
|
| 399 |
+
nova_largura = 1920
|
| 400 |
+
nova_altura = int(nova_largura / target_ratio)
|
| 401 |
+
|
| 402 |
+
formato_saida = st.selectbox("Formato de saída", ["mp4", "avi", "mov", "gif"], key="video_format")
|
| 403 |
+
|
| 404 |
+
if formato_saida == "gif":
|
| 405 |
+
st.info("🎨 GIF será otimizado!")
|
| 406 |
+
|
| 407 |
+
with col2:
|
| 408 |
+
st.subheader("📊 Preview")
|
| 409 |
+
st.write(f"**Original:** {width_original}x{height_original}")
|
| 410 |
+
if nova_largura and nova_altura:
|
| 411 |
+
st.write(f"**Novo:** {nova_largura}x{nova_altura}")
|
| 412 |
+
ratio_orig = width_original / height_original
|
| 413 |
+
ratio_novo = nova_largura / nova_altura
|
| 414 |
+
if abs(ratio_orig - ratio_novo) > 0.1:
|
| 415 |
+
st.warning("⚠️ Aspect ratio será alterado!")
|
| 416 |
+
|
| 417 |
+
if formato_saida == "gif":
|
| 418 |
+
st.write("**Formato:** GIF Animado")
|
| 419 |
+
st.write("**FPS:** 10 (otimizado)")
|
| 420 |
+
|
| 421 |
+
if st.button("🎬 Processar Vídeo", type="primary", key="video_process_button"):
|
| 422 |
+
with st.spinner(f"Processando {'GIF' if formato_saida == 'gif' else 'vídeo'}..."):
|
| 423 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{formato_saida}') as output_file:
|
| 424 |
+
temp_output = output_file.name
|
| 425 |
+
|
| 426 |
+
if processar_video(temp_input, temp_output, nova_largura, nova_altura, formato=formato_saida, padding=padding_video):
|
| 427 |
+
with open(temp_output, 'rb') as f:
|
| 428 |
+
mime_type = f"video/{formato_saida}" if formato_saida != "gif" else "image/gif"
|
| 429 |
+
st.download_button(
|
| 430 |
+
label=f"⬇️ Baixar {'GIF' if formato_saida == 'gif' else 'Vídeo'} Processado",
|
| 431 |
+
data=f.read(),
|
| 432 |
+
file_name=f"{'animacao' if formato_saida == 'gif' else 'video'}_editado.{formato_saida}",
|
| 433 |
+
mime=mime_type,
|
| 434 |
+
key="video_download_button"
|
| 435 |
+
)
|
| 436 |
+
st.success(f"✅ {'GIF' if formato_saida == 'gif' else 'Vídeo'} processado!")
|
| 437 |
+
|
| 438 |
+
os.unlink(temp_input)
|
| 439 |
+
if os.path.exists(temp_output):
|
| 440 |
+
os.unlink(temp_output)
|
| 441 |
+
|
| 442 |
+
except Exception as e:
|
| 443 |
+
st.error(f"Erro ao ler vídeo: {str(e)}")
|
| 444 |
+
|
| 445 |
+
# SEÇÃO DE IMAGENS
|
| 446 |
+
elif tipo_edicao == "🖼️ Imagens":
|
| 447 |
+
st.header("Edição de Imagens")
|
| 448 |
+
|
| 449 |
+
image_file = st.file_uploader("Escolha uma imagem", type=['jpg', 'jpeg', 'png', 'bmp', 'tiff'], key="image_uploader")
|
| 450 |
+
|
| 451 |
+
if image_file is not None:
|
| 452 |
+
img = Image.open(image_file)
|
| 453 |
+
width_original, height_original = img.size
|
| 454 |
+
|
| 455 |
+
col1, col2 = st.columns(2)
|
| 456 |
+
|
| 457 |
+
with col1:
|
| 458 |
+
st.subheader("⚙️ Redimensionar e Converter")
|
| 459 |
+
st.write(f"Tamanho original: {width_original}x{height_original}")
|
| 460 |
+
|
| 461 |
+
nova_largura_img = st.number_input("Nova largura", min_value=1, value=width_original, key="img_width_single")
|
| 462 |
+
nova_altura_img = st.number_input("Nova altura", min_value=1, value=height_original, key="img_height_single")
|
| 463 |
+
|
| 464 |
+
manter_proporcao = st.checkbox("Manter proporção", value=True, key="img_prop_single")
|
| 465 |
+
|
| 466 |
+
preset_img = st.selectbox("Preset de tamanho", [
|
| 467 |
+
"Personalizado", "HD (1920x1080)", "Instagram Post (1080x1080)",
|
| 468 |
+
"Instagram Story (1080x1920)", "Facebook Cover (1200x630)", "YouTube Thumbnail (1280x720)"
|
| 469 |
+
], key="img_preset_single")
|
| 470 |
+
|
| 471 |
+
if preset_img != "Personalizado":
|
| 472 |
+
presets_img = {
|
| 473 |
+
"HD (1920x1080)": (1920, 1080),
|
| 474 |
+
"Instagram Post (1080x1080)": (1080, 1080),
|
| 475 |
+
"Instagram Story (1080x1920)": (1080, 1920),
|
| 476 |
+
"Facebook Cover (1200x630)": (1200, 630),
|
| 477 |
+
"YouTube Thumbnail (1280x720)": (1280, 720)
|
| 478 |
+
}
|
| 479 |
+
nova_largura_img, nova_altura_img = presets_img[preset_img]
|
| 480 |
+
|
| 481 |
+
formato_img = st.selectbox("Formato de saída", ["JPEG", "PNG", "WEBP", "SVG"], key="img_format_single")
|
| 482 |
+
|
| 483 |
+
qualidade = None
|
| 484 |
+
if formato_img == "JPEG":
|
| 485 |
+
qualidade = st.slider("Qualidade JPEG", 1, 100, 85, key="img_quality_single")
|
| 486 |
+
|
| 487 |
+
with col2:
|
| 488 |
+
st.subheader("🖼️ Preview")
|
| 489 |
+
img_preview = img.copy()
|
| 490 |
+
img_preview.thumbnail((400, 300))
|
| 491 |
+
st.image(img_preview, caption="Preview da imagem original")
|
| 492 |
+
|
| 493 |
+
if st.button("🖼️ Processar Imagem", type="primary", key="img_process_single"):
|
| 494 |
+
with st.spinner("Processando imagem..."):
|
| 495 |
+
if formato_img == "SVG":
|
| 496 |
+
try:
|
| 497 |
+
# Para SVG, usamos um caminho diferente
|
| 498 |
+
image_file.seek(0)
|
| 499 |
+
input_bytes = image_file.read()
|
| 500 |
+
|
| 501 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{image_file.type.split('/')[1]}") as tmp_in:
|
| 502 |
+
tmp_in.write(input_bytes)
|
| 503 |
+
temp_input_path = tmp_in.name
|
| 504 |
+
|
| 505 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".svg") as tmp_out:
|
| 506 |
+
temp_output_path = tmp_out.name
|
| 507 |
+
|
| 508 |
+
vtracer.convert_image_to_svg_py(temp_input_path, temp_output_path, colormode='color')
|
| 509 |
+
|
| 510 |
+
with open(temp_output_path, 'rb') as f:
|
| 511 |
+
svg_bytes = f.read()
|
| 512 |
+
|
| 513 |
+
st.success("✅ Imagem convertida para SVG com sucesso!")
|
| 514 |
+
st.download_button(
|
| 515 |
+
label="⬇️ Baixar Imagem SVG",
|
| 516 |
+
data=svg_bytes,
|
| 517 |
+
file_name="imagem_convertida.svg",
|
| 518 |
+
mime="image/svg+xml",
|
| 519 |
+
key="svg_download_button"
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
os.unlink(temp_input_path)
|
| 523 |
+
os.unlink(temp_output_path)
|
| 524 |
+
|
| 525 |
+
except Exception as e:
|
| 526 |
+
st.error(f"Erro ao converter para SVG: {e}")
|
| 527 |
+
|
| 528 |
+
else:
|
| 529 |
+
# Lógica existente para outros formatos
|
| 530 |
+
img_processada = processar_imagem(
|
| 531 |
+
img.copy(),
|
| 532 |
+
nova_largura_img if nova_largura_img != width_original else None,
|
| 533 |
+
nova_altura_img if nova_altura_img != height_original else None,
|
| 534 |
+
manter_proporcao, formato_img
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
if img_processada:
|
| 538 |
+
img_bytes = BytesIO()
|
| 539 |
+
save_kwargs = {}
|
| 540 |
+
if formato_img == "JPEG" and qualidade is not None:
|
| 541 |
+
save_kwargs['quality'] = qualidade
|
| 542 |
+
save_kwargs['optimize'] = True
|
| 543 |
+
|
| 544 |
+
img_processada.save(img_bytes, format=formato_img, **save_kwargs)
|
| 545 |
+
img_bytes.seek(0)
|
| 546 |
+
|
| 547 |
+
col1_res, col2_res = st.columns(2)
|
| 548 |
+
with col1_res:
|
| 549 |
+
st.write("**Antes:**")
|
| 550 |
+
prev_orig = img.copy()
|
| 551 |
+
prev_orig.thumbnail((300, 300))
|
| 552 |
+
st.image(prev_orig)
|
| 553 |
+
|
| 554 |
+
with col2_res:
|
| 555 |
+
st.write("**Depois:**")
|
| 556 |
+
prev_nova = img_processada.copy()
|
| 557 |
+
prev_nova.thumbnail((300, 300))
|
| 558 |
+
st.image(prev_nova)
|
| 559 |
+
|
| 560 |
+
ext = formato_img.lower()
|
| 561 |
+
if ext == "jpeg":
|
| 562 |
+
ext = "jpg"
|
| 563 |
+
|
| 564 |
+
st.download_button(
|
| 565 |
+
label="⬇️ Baixar Imagem Processada",
|
| 566 |
+
data=img_bytes.getvalue(),
|
| 567 |
+
file_name=f"imagem_editada.{ext}",
|
| 568 |
+
mime=f"image/{ext}",
|
| 569 |
+
key="img_download_single"
|
| 570 |
+
)
|
| 571 |
+
st.success("✅ Imagem processada com sucesso!")
|
| 572 |
+
|
| 573 |
+
st.markdown("---")
|
| 574 |
+
st.subheader("✨ Remover Fundo")
|
| 575 |
+
if st.button("🎨 Remover Fundo da Imagem", type="primary", key="bg_remover_button"):
|
| 576 |
+
with st.spinner("Processando e removendo o fundo..."):
|
| 577 |
+
# Resetar o ponteiro do arquivo para ler novamente
|
| 578 |
+
image_file.seek(0)
|
| 579 |
+
input_bytes = image_file.getvalue()
|
| 580 |
+
|
| 581 |
+
try:
|
| 582 |
+
output_bytes = rembg.remove(input_bytes)
|
| 583 |
+
|
| 584 |
+
st.success("✅ Fundo removido com sucesso!")
|
| 585 |
+
|
| 586 |
+
col1_bg, col2_bg = st.columns(2)
|
| 587 |
+
with col1_bg:
|
| 588 |
+
st.write("**Original**")
|
| 589 |
+
st.image(input_bytes, width=300)
|
| 590 |
+
with col2_bg:
|
| 591 |
+
st.write("**Sem Fundo**")
|
| 592 |
+
st.image(output_bytes, width=300)
|
| 593 |
+
|
| 594 |
+
st.download_button(
|
| 595 |
+
label="⬇️ Baixar Imagem sem Fundo",
|
| 596 |
+
data=output_bytes,
|
| 597 |
+
file_name=f"{os.path.splitext(image_file.name)[0]}_sem_fundo.png",
|
| 598 |
+
mime="image/png",
|
| 599 |
+
key="bg_remover_download_button"
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
except Exception as e:
|
| 603 |
+
st.error(f"Ocorreu um erro ao remover o fundo: {e}")
|
| 604 |
+
|
| 605 |
+
# SEÇÃO DE LOTE DE IMAGENS
|
| 606 |
+
elif tipo_edicao == "📦 Lote de Imagens":
|
| 607 |
+
st.header("Edição em Lote de Imagens")
|
| 608 |
+
st.markdown("Faça upload de várias imagens e processe todas de uma vez!")
|
| 609 |
+
|
| 610 |
+
image_files = st.file_uploader("Escolha várias imagens", type=['jpg', 'jpeg', 'png', 'bmp'], accept_multiple_files=True, key="lote_uploader")
|
| 611 |
+
|
| 612 |
+
if image_files:
|
| 613 |
+
st.success(f"📁 {len(image_files)} imagens carregadas")
|
| 614 |
+
|
| 615 |
+
col1, col2 = st.columns(2)
|
| 616 |
+
|
| 617 |
+
with col1:
|
| 618 |
+
st.subheader("⚙️ Configurações para todas as imagens")
|
| 619 |
+
|
| 620 |
+
largura_lote = st.number_input("Largura", min_value=1, value=1920, key="lote_width")
|
| 621 |
+
altura_lote = st.number_input("Altura", min_value=1, value=1080, key="lote_height")
|
| 622 |
+
manter_proporcao_lote = st.checkbox("Manter proporção", value=True, key="lote_prop")
|
| 623 |
+
formato_lote = st.selectbox("Formato de saída", ["JPEG", "PNG", "WEBP", "SVG"], key="lote_format")
|
| 624 |
+
|
| 625 |
+
qualidade_lote = None
|
| 626 |
+
if formato_lote == "JPEG":
|
| 627 |
+
qualidade_lote = st.slider("Qualidade JPEG", 1, 100, 85, key="lote_quality")
|
| 628 |
+
|
| 629 |
+
with col2:
|
| 630 |
+
st.subheader("📊 Informações")
|
| 631 |
+
st.write(f"**Imagens selecionadas:** {len(image_files)}")
|
| 632 |
+
st.write(f"**Tamanho final:** {largura_lote}x{altura_lote}")
|
| 633 |
+
st.write(f"**Formato:** {formato_lote}")
|
| 634 |
+
|
| 635 |
+
if st.button("📦 Processar Lote", type="primary", key="lote_process_button"):
|
| 636 |
+
progress_bar = st.progress(0)
|
| 637 |
+
status_text = st.empty()
|
| 638 |
+
|
| 639 |
+
zip_buffer = BytesIO()
|
| 640 |
+
|
| 641 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 642 |
+
for i, image_file in enumerate(image_files):
|
| 643 |
+
status_text.text(f"Processando {image_file.name}...")
|
| 644 |
+
|
| 645 |
+
try:
|
| 646 |
+
nome_original = os.path.splitext(image_file.name)[0]
|
| 647 |
+
|
| 648 |
+
if formato_lote == "SVG":
|
| 649 |
+
image_file.seek(0)
|
| 650 |
+
input_bytes = image_file.read()
|
| 651 |
+
|
| 652 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{image_file.type.split('/')[1]}") as tmp_in:
|
| 653 |
+
tmp_in.write(input_bytes)
|
| 654 |
+
temp_input_path = tmp_in.name
|
| 655 |
+
|
| 656 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".svg") as tmp_out:
|
| 657 |
+
temp_output_path = tmp_out.name
|
| 658 |
+
|
| 659 |
+
vtracer.convert_image_to_svg_py(temp_input_path, temp_output_path, colormode='color')
|
| 660 |
+
|
| 661 |
+
novo_nome = f"{nome_original}_editado.svg"
|
| 662 |
+
zip_file.write(temp_output_path, novo_nome)
|
| 663 |
+
|
| 664 |
+
os.unlink(temp_input_path)
|
| 665 |
+
os.unlink(temp_output_path)
|
| 666 |
+
|
| 667 |
+
else:
|
| 668 |
+
img = Image.open(image_file)
|
| 669 |
+
img_processada = processar_imagem(img, largura_lote, altura_lote, manter_proporcao_lote, formato_lote)
|
| 670 |
+
|
| 671 |
+
if img_processada:
|
| 672 |
+
img_bytes = BytesIO()
|
| 673 |
+
save_kwargs = {}
|
| 674 |
+
if formato_lote == "JPEG" and qualidade_lote is not None:
|
| 675 |
+
save_kwargs['quality'] = qualidade_lote
|
| 676 |
+
save_kwargs['optimize'] = True
|
| 677 |
+
|
| 678 |
+
img_processada.save(img_bytes, format=formato_lote, **save_kwargs)
|
| 679 |
+
|
| 680 |
+
ext = formato_lote.lower()
|
| 681 |
+
if ext == "jpeg":
|
| 682 |
+
ext = "jpg"
|
| 683 |
+
novo_nome = f"{nome_original}_editado.{ext}"
|
| 684 |
+
|
| 685 |
+
zip_file.writestr(novo_nome, img_bytes.getvalue())
|
| 686 |
+
|
| 687 |
+
except Exception as e:
|
| 688 |
+
st.warning(f"Erro ao processar {image_file.name}: {str(e)}")
|
| 689 |
+
|
| 690 |
+
progress_bar.progress((i + 1) / len(image_files))
|
| 691 |
+
|
| 692 |
+
status_text.text("✅ Processamento concluído!")
|
| 693 |
+
|
| 694 |
+
zip_buffer.seek(0)
|
| 695 |
+
st.download_button(
|
| 696 |
+
label="⬇️ Baixar ZIP com Imagens Processadas",
|
| 697 |
+
data=zip_buffer.getvalue(),
|
| 698 |
+
file_name="imagens_editadas.zip",
|
| 699 |
+
mime="application/zip",
|
| 700 |
+
key="lote_download_button"
|
| 701 |
+
)
|
| 702 |
+
st.success(f"✅ {len(image_files)} imagens processadas com sucesso!")
|
| 703 |
+
|
| 704 |
+
# SEÇÃO DE DOWNLOAD DO YOUTUBE
|
| 705 |
+
elif tipo_edicao == "📥 Baixar do YouTube":
|
| 706 |
+
st.header("📥 Baixar Vídeo do YouTube")
|
| 707 |
+
|
| 708 |
+
url = st.text_input("Cole a URL do vídeo do YouTube aqui:", key="youtube_url_input")
|
| 709 |
+
|
| 710 |
+
if url:
|
| 711 |
+
try:
|
| 712 |
+
progress_bar = st.empty()
|
| 713 |
+
status_text = st.empty()
|
| 714 |
+
|
| 715 |
+
def on_progress(stream, chunk, bytes_remaining):
|
| 716 |
+
total_size = stream.filesize
|
| 717 |
+
bytes_downloaded = total_size - bytes_remaining
|
| 718 |
+
percentage = int((bytes_downloaded / total_size) * 100)
|
| 719 |
+
status_text.text(f"Baixando... {percentage}%")
|
| 720 |
+
progress_bar.progress(percentage)
|
| 721 |
+
|
| 722 |
+
yt = YouTube(url, on_progress_callback=on_progress)
|
| 723 |
+
|
| 724 |
+
st.write(f"**{yt.title}**")
|
| 725 |
+
st.image(yt.thumbnail_url, width=400)
|
| 726 |
+
|
| 727 |
+
# Filtrar streams para ter vídeo e áudio (progressive)
|
| 728 |
+
video_streams = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc()
|
| 729 |
+
|
| 730 |
+
if not video_streams:
|
| 731 |
+
st.warning("Nenhuma stream de vídeo MP4 (com áudio) encontrada para este vídeo.")
|
| 732 |
+
else:
|
| 733 |
+
stream_options = [f"{stream.resolution} ({stream.filesize_mb:.2f} MB)" for stream in video_streams]
|
| 734 |
+
|
| 735 |
+
chosen_option = st.selectbox("Escolha a qualidade do vídeo para baixar:", stream_options, key="youtube_quality_select")
|
| 736 |
+
|
| 737 |
+
if st.button("📥 Baixar Vídeo", type="primary", key="youtube_download_button"):
|
| 738 |
+
selected_stream = None
|
| 739 |
+
for stream in video_streams:
|
| 740 |
+
if f"{stream.resolution} ({stream.filesize_mb:.2f} MB)" == chosen_option:
|
| 741 |
+
selected_stream = stream
|
| 742 |
+
break
|
| 743 |
+
|
| 744 |
+
if selected_stream:
|
| 745 |
+
with st.spinner(f"Iniciando download em {selected_stream.resolution}..."):
|
| 746 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 747 |
+
file_path = selected_stream.download(output_path=temp_dir)
|
| 748 |
+
file_name = os.path.basename(file_path)
|
| 749 |
+
|
| 750 |
+
with open(file_path, 'rb') as f:
|
| 751 |
+
video_bytes = f.read()
|
| 752 |
+
|
| 753 |
+
status_text.text("✅ Download concluído!")
|
| 754 |
+
progress_bar.empty()
|
| 755 |
+
|
| 756 |
+
st.download_button(
|
| 757 |
+
label="⬇️ Clique para salvar o vídeo",
|
| 758 |
+
data=video_bytes,
|
| 759 |
+
file_name=file_name,
|
| 760 |
+
mime="video/mp4",
|
| 761 |
+
key="youtube_save_button"
|
| 762 |
+
)
|
| 763 |
+
else:
|
| 764 |
+
st.error("Não foi possível encontrar a stream selecionada. Tente novamente.")
|
| 765 |
+
|
| 766 |
+
except Exception as e:
|
| 767 |
+
st.error(f"Ocorreu um erro: {e}")
|
| 768 |
+
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.")
|
| 769 |
+
|
| 770 |
+
# Footer
|
| 771 |
+
st.markdown("---")
|
| 772 |
+
st.markdown("🚀 **Editor Local** - Seus arquivos não saem do seu computador!")
|
packages.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
requirements.txt
ADDED
|
Binary file (3.31 kB). View file
|
|
|
upscale_realesrgan.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|