Spaces:
Sleeping
Sleeping
Update app.py
Browse filesuma função de tradução que usa um modelo específico do Hugging Face para converter o texto de descricao_img_input de Português para Inglês antes de enviá-lo para a função gerar_imagem
app.py
CHANGED
|
@@ -27,6 +27,7 @@ if not HUGGINGFACE_API_KEY:
|
|
| 27 |
BASE_URL = "https://router.huggingface.co/v1"
|
| 28 |
MODELO_TEXTO = "meta-llama/Llama-3.1-8B-Instruct"
|
| 29 |
MODELO_IMAGEM = "black-forest-labs/FLUX.1-schnell"
|
|
|
|
| 30 |
|
| 31 |
# Headers para requisições
|
| 32 |
headers = {
|
|
@@ -110,6 +111,42 @@ Escreva apenas a legenda, sem introduções ou explicações."""
|
|
| 110 |
except Exception as e:
|
| 111 |
return f"❌ Erro de Conexão: {str(e)}"
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
def gerar_imagem(descricao):
|
| 115 |
"""
|
|
@@ -120,11 +157,10 @@ def gerar_imagem(descricao):
|
|
| 120 |
return None
|
| 121 |
|
| 122 |
try:
|
| 123 |
-
# A importação já foi movida para o topo, mas manter o try/except
|
| 124 |
-
# para garantir a robustez em caso de falha de importação
|
| 125 |
client = InferenceClient(api_key=HUGGINGFACE_API_KEY)
|
| 126 |
|
| 127 |
# Adicionar prompt engineering para melhor qualidade
|
|
|
|
| 128 |
prompt = f"{descricao}, professional photography, vibrant colors, high quality, 4k"
|
| 129 |
|
| 130 |
# Gerar imagem
|
|
@@ -166,13 +202,6 @@ def gerar_post_interface(tema, nicho, estilo, descricao_imagem, gerar_img):
|
|
| 166 |
|
| 167 |
|
| 168 |
# Etapa 1: Gerar texto
|
| 169 |
-
# Gradio aceita que retornemos um gerador ou múltiplos outputs de uma vez.
|
| 170 |
-
# Para o status, vamos retornar o texto logo no início.
|
| 171 |
-
# No entanto, a função principal do Gradio deve retornar *todos* os outputs de uma vez.
|
| 172 |
-
|
| 173 |
-
# Simulação de status inicial (Gradio não suporta yield/generator para mudar o status aqui facilmente)
|
| 174 |
-
# Vamos gerar o texto e depois a imagem.
|
| 175 |
-
|
| 176 |
texto = gerar_texto(tema, nicho, estilo)
|
| 177 |
|
| 178 |
# Verificar se houve erro no texto
|
|
@@ -182,12 +211,18 @@ def gerar_post_interface(tema, nicho, estilo, descricao_imagem, gerar_img):
|
|
| 182 |
# Etapa 2: Gerar imagem (se solicitado)
|
| 183 |
imagem = None
|
| 184 |
if gerar_img:
|
| 185 |
-
#
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
-
imagem
|
|
|
|
| 191 |
|
| 192 |
if imagem is None:
|
| 193 |
status_final = "⚠️ Texto gerado, mas houve erro na imagem"
|
|
@@ -204,15 +239,7 @@ def gerar_post_interface(tema, nicho, estilo, descricao_imagem, gerar_img):
|
|
| 204 |
# INTERFACE GRADIO
|
| 205 |
# ============================================
|
| 206 |
|
| 207 |
-
|
| 208 |
-
primary_hue="blue", # Cor primária
|
| 209 |
-
secondary_hue="purple", # Cor secundária
|
| 210 |
-
neutral_hue="slate", # Cor neutra
|
| 211 |
-
font=["Helvetica", "sans-serif"]
|
| 212 |
-
)
|
| 213 |
-
|
| 214 |
-
with gr.Blocks(theme=tema_custom, title="Gerador de Posts") as demo:
|
| 215 |
-
# with gr.Blocks(theme=gr.themes.Glass(), title="Gerador de Posts") as demo:
|
| 216 |
|
| 217 |
gr.Markdown("""
|
| 218 |
# 🚀 Gerador de Posts para Redes Sociais
|
|
@@ -253,10 +280,9 @@ with gr.Blocks(theme=tema_custom, title="Gerador de Posts") as demo:
|
|
| 253 |
)
|
| 254 |
|
| 255 |
descricao_img_input = gr.Textbox(
|
| 256 |
-
label="Descrição da
|
| 257 |
-
placeholder="Ex:
|
| 258 |
visible=False # Só aparece se gerar_img_checkbox for marcado
|
| 259 |
-
info="Descreva o que deve aparecer na imagem"
|
| 260 |
)
|
| 261 |
|
| 262 |
def toggle_descricao_img(gerar):
|
|
@@ -266,9 +292,9 @@ with gr.Blocks(theme=tema_custom, title="Gerador de Posts") as demo:
|
|
| 266 |
gerar_img_checkbox.change(
|
| 267 |
toggle_descricao_img,
|
| 268 |
inputs=[gerar_img_checkbox],
|
| 269 |
-
outputs=[descricao_img_input]
|
| 270 |
)
|
| 271 |
-
|
| 272 |
gerar_btn = gr.Button("✨ Gerar Post", variant="primary")
|
| 273 |
|
| 274 |
with gr.Column(scale=1):
|
|
@@ -309,7 +335,10 @@ with gr.Blocks(theme=tema_custom, title="Gerador de Posts") as demo:
|
|
| 309 |
|
| 310 |
|
| 311 |
# ==============================================================
|
| 312 |
-
#
|
|
|
|
|
|
|
|
|
|
| 313 |
# ==============================================================
|
| 314 |
gerar_btn.click(
|
| 315 |
fn=gerar_post_interface,
|
|
@@ -317,7 +346,6 @@ with gr.Blocks(theme=tema_custom, title="Gerador de Posts") as demo:
|
|
| 317 |
inputs=[tema_input, nicho_input, estilo_input, descricao_img_input, gerar_img_checkbox],
|
| 318 |
# Ordem CORRETA para a função retornar (texto, imagem, status_final)
|
| 319 |
outputs=[texto_output, imagem_output, status_output]
|
| 320 |
-
show_progress="full" # Barra de progresso completa
|
| 321 |
)
|
| 322 |
|
| 323 |
# ABA 2: Histórico
|
|
@@ -331,6 +359,7 @@ with gr.Blocks(theme=tema_custom, title="Gerador de Posts") as demo:
|
|
| 331 |
gr.Markdown("### Configurações do Gerador")
|
| 332 |
gr.Markdown("**Modelo de Texto:** Llama 3.1 8B")
|
| 333 |
gr.Markdown("**Modelo de Imagem:** FLUX.1 Schnell")
|
|
|
|
| 334 |
gr.Markdown("**API Provider:** Hugging Face Inference")
|
| 335 |
|
| 336 |
# ABA 4: Sobre
|
|
@@ -345,14 +374,16 @@ with gr.Blocks(theme=tema_custom, title="Gerador de Posts") as demo:
|
|
| 345 |
- Gradio (interface web)
|
| 346 |
- Llama 3.1 8B (geração de texto)
|
| 347 |
- FLUX.1 (geração de imagens)
|
|
|
|
| 348 |
|
| 349 |
**Como funciona:**
|
| 350 |
-
1. Você escolhe nicho e tema
|
| 351 |
-
2.
|
| 352 |
-
3.
|
| 353 |
-
4.
|
|
|
|
| 354 |
|
| 355 |
-
**Desenvolvido por:**
|
| 356 |
""")
|
| 357 |
|
| 358 |
# Footer
|
|
|
|
| 27 |
BASE_URL = "https://router.huggingface.co/v1"
|
| 28 |
MODELO_TEXTO = "meta-llama/Llama-3.1-8B-Instruct"
|
| 29 |
MODELO_IMAGEM = "black-forest-labs/FLUX.1-schnell"
|
| 30 |
+
MODELO_TRADUCAO = "Helsinki-NLP/opus-mt-pt-en" # NOVO: Modelo para tradução PT -> EN
|
| 31 |
|
| 32 |
# Headers para requisições
|
| 33 |
headers = {
|
|
|
|
| 111 |
except Exception as e:
|
| 112 |
return f"❌ Erro de Conexão: {str(e)}"
|
| 113 |
|
| 114 |
+
def traduzir_texto(texto_pt):
|
| 115 |
+
"""Traduz texto de Português (PT) para Inglês (EN) usando API do Hugging Face.
|
| 116 |
+
Retorna o texto original (PT) em caso de erro ou falha na API.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
if not HUGGINGFACE_API_KEY:
|
| 120 |
+
return texto_pt
|
| 121 |
+
|
| 122 |
+
# Endpoint da API de Inferência para o modelo de tradução
|
| 123 |
+
url = f"https://api-inference.huggingface.co/models/{MODELO_TRADUCAO}"
|
| 124 |
+
|
| 125 |
+
payload = {
|
| 126 |
+
"inputs": texto_pt,
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
# Usamos requests.post com os headers existentes
|
| 131 |
+
response = requests.post(url, headers=headers, json=payload, timeout=30)
|
| 132 |
+
|
| 133 |
+
if response.status_code == 200:
|
| 134 |
+
resultado = response.json()
|
| 135 |
+
# O modelo opus-mt-pt-en retorna uma lista de dicionários com 'translation_text'
|
| 136 |
+
if resultado and isinstance(resultado, list) and 'translation_text' in resultado[0]:
|
| 137 |
+
texto_en = resultado[0]['translation_text']
|
| 138 |
+
return texto_en
|
| 139 |
+
else:
|
| 140 |
+
print(f"⚠️ Tradução falhou (resposta inesperada): {resultado}")
|
| 141 |
+
return texto_pt # Fallback
|
| 142 |
+
else:
|
| 143 |
+
print(f"⚠️ Tradução falhou ({response.status_code}): {response.text}")
|
| 144 |
+
return texto_pt # Fallback
|
| 145 |
+
|
| 146 |
+
except Exception as e:
|
| 147 |
+
print(f"❌ Erro na tradução: {str(e)}")
|
| 148 |
+
return texto_pt # Fallback
|
| 149 |
+
|
| 150 |
|
| 151 |
def gerar_imagem(descricao):
|
| 152 |
"""
|
|
|
|
| 157 |
return None
|
| 158 |
|
| 159 |
try:
|
|
|
|
|
|
|
| 160 |
client = InferenceClient(api_key=HUGGINGFACE_API_KEY)
|
| 161 |
|
| 162 |
# Adicionar prompt engineering para melhor qualidade
|
| 163 |
+
# Observação: A descrição (descricao) que chega aqui JÁ ESTÁ EM INGLÊS.
|
| 164 |
prompt = f"{descricao}, professional photography, vibrant colors, high quality, 4k"
|
| 165 |
|
| 166 |
# Gerar imagem
|
|
|
|
| 202 |
|
| 203 |
|
| 204 |
# Etapa 1: Gerar texto
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
texto = gerar_texto(tema, nicho, estilo)
|
| 206 |
|
| 207 |
# Verificar se houve erro no texto
|
|
|
|
| 211 |
# Etapa 2: Gerar imagem (se solicitado)
|
| 212 |
imagem = None
|
| 213 |
if gerar_img:
|
| 214 |
+
# 1. Definir o prompt em Português
|
| 215 |
+
descricao_pt = descricao_imagem
|
| 216 |
+
if not descricao_pt or len(descricao_pt.strip()) < 3:
|
| 217 |
+
# Se a descrição estiver vazia, usa o tema como base (em português)
|
| 218 |
+
descricao_pt = f"{tema}, imagem profissional"
|
| 219 |
+
|
| 220 |
+
# 2. Traduzir para Inglês
|
| 221 |
+
# Chamamos a função de tradução ANTES de gerar a imagem
|
| 222 |
+
descricao_en = traduzir_texto(descricao_pt)
|
| 223 |
|
| 224 |
+
# 3. Gerar imagem (usando o prompt em INGLÊS)
|
| 225 |
+
imagem = gerar_imagem(descricao_en)
|
| 226 |
|
| 227 |
if imagem is None:
|
| 228 |
status_final = "⚠️ Texto gerado, mas houve erro na imagem"
|
|
|
|
| 239 |
# INTERFACE GRADIO
|
| 240 |
# ============================================
|
| 241 |
|
| 242 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Posts") as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
gr.Markdown("""
|
| 245 |
# 🚀 Gerador de Posts para Redes Sociais
|
|
|
|
| 280 |
)
|
| 281 |
|
| 282 |
descricao_img_input = gr.Textbox(
|
| 283 |
+
label="Descrição da imagem (em Português)",
|
| 284 |
+
placeholder="Ex: Pessoa correndo ao nascer do sol",
|
| 285 |
visible=False # Só aparece se gerar_img_checkbox for marcado
|
|
|
|
| 286 |
)
|
| 287 |
|
| 288 |
def toggle_descricao_img(gerar):
|
|
|
|
| 292 |
gerar_img_checkbox.change(
|
| 293 |
toggle_descricao_img,
|
| 294 |
inputs=[gerar_img_checkbox],
|
| 295 |
+
outputs=[descricao_img_input] # O código selecionado estava correto
|
| 296 |
)
|
| 297 |
+
|
| 298 |
gerar_btn = gr.Button("✨ Gerar Post", variant="primary")
|
| 299 |
|
| 300 |
with gr.Column(scale=1):
|
|
|
|
| 335 |
|
| 336 |
|
| 337 |
# ==============================================================
|
| 338 |
+
# ESTE BLOCO ESTÁ CORRETO APÓS A ÚLTIMA CORREÇÃO:
|
| 339 |
+
# 1. fn: A função correta é 'gerar_post_interface'.
|
| 340 |
+
# 2. inputs: Ordem correta para (tema, nicho, estilo, descricao_imagem, gerar_img)
|
| 341 |
+
# 3. outputs: Ordem correta para (texto_output, imagem_output, status_output)
|
| 342 |
# ==============================================================
|
| 343 |
gerar_btn.click(
|
| 344 |
fn=gerar_post_interface,
|
|
|
|
| 346 |
inputs=[tema_input, nicho_input, estilo_input, descricao_img_input, gerar_img_checkbox],
|
| 347 |
# Ordem CORRETA para a função retornar (texto, imagem, status_final)
|
| 348 |
outputs=[texto_output, imagem_output, status_output]
|
|
|
|
| 349 |
)
|
| 350 |
|
| 351 |
# ABA 2: Histórico
|
|
|
|
| 359 |
gr.Markdown("### Configurações do Gerador")
|
| 360 |
gr.Markdown("**Modelo de Texto:** Llama 3.1 8B")
|
| 361 |
gr.Markdown("**Modelo de Imagem:** FLUX.1 Schnell")
|
| 362 |
+
gr.Markdown("**Modelo de Tradução (PT -> EN):** Helsinki-NLP/opus-mt-pt-en") # NOVO
|
| 363 |
gr.Markdown("**API Provider:** Hugging Face Inference")
|
| 364 |
|
| 365 |
# ABA 4: Sobre
|
|
|
|
| 374 |
- Gradio (interface web)
|
| 375 |
- Llama 3.1 8B (geração de texto)
|
| 376 |
- FLUX.1 (geração de imagens)
|
| 377 |
+
- Opus-MT (tradução)
|
| 378 |
|
| 379 |
**Como funciona:**
|
| 380 |
+
1. Você escolhe nicho e tema.
|
| 381 |
+
2. Se a imagem estiver marcada, a descrição é **automaticamente traduzida para Inglês** (melhor performance).
|
| 382 |
+
3. Sistema envia requisição para APIs da Hugging Face.
|
| 383 |
+
4. IAs processam e geram conteúdo.
|
| 384 |
+
5. Resultado aparece instantaneamente.
|
| 385 |
|
| 386 |
+
**Desenvolvido por:** Wilder Paz
|
| 387 |
""")
|
| 388 |
|
| 389 |
# Footer
|