wpbcpaz commited on
Commit
5bc50e8
·
verified ·
1 Parent(s): 0f334f5

Update app.py

Browse files

Incrementos do botão limpar cache, retificação do botão copiar texto e Texto em UTF-8

Files changed (1) hide show
  1. app.py +56 -19
app.py CHANGED
@@ -431,7 +431,6 @@ def _formatar_historico_para_html(history_list):
431
 
432
  # Cor do texto clara padrão para fundos escuros
433
  cor_texto_clara = "#f1f5f9" # Light slate/gray
434
- cor_texto_secundaria = "#cbd5e1" # Lighter slate
435
 
436
  html = "<div style='max-height: 600px; overflow-y: auto; padding-right: 10px;'>"
437
  for i, post in enumerate(history_list):
@@ -467,10 +466,10 @@ def _formatar_historico_para_html(history_list):
467
  border-radius: 8px; background-color: {cor_fundo}; color: {cor_texto_clara};
468
  box-shadow: 0 4px 6px rgba(0,0,0,0.1); cursor: default;'>
469
  <div style='display: flex; justify-content: space-between; margin-bottom: 8px;'>
470
- <strong style='font-size: 16px; color: white;'>{favorito_icon} {post.get('Tema', 'Sem título')}</strong>
471
- <span style='color: {cor_texto_secundaria}; font-size: 12px;'>{data}</span>
472
  </div>
473
- <div style='color: {cor_texto_secundaria}; font-size: 13px; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid rgba(255,255,255,0.2);'>
474
  <span>📁 Nicho: {post.get('Nicho', 'N/A')}</span> |
475
  <span>🎨 Estilo: {post.get('Estilo', 'N/A')}</span> |
476
  <span>📄 Formato: {post.get('Formato', 'N/A')}</span>
@@ -481,7 +480,7 @@ def _formatar_historico_para_html(history_list):
481
  {texto_completo}
482
  </div>
483
 
484
- <div style='display: flex; gap: 16px; font-size: 12px; color: {cor_texto_secundaria};'>
485
  <span>📊 Palavras: {palavras}</span>
486
  <span>📏 Caracteres: {caracteres}</span>
487
  <span>#️⃣ Hashtags: {hashtags}</span>
@@ -520,6 +519,26 @@ def print_like_dislike(x: gr.LikeData):
520
  """Função de callback para o evento 'like' do chatbot."""
521
  print(f"Mensagem {x.index} foi marcada como: {x.value}, Liked: {x.liked}")
522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
523
  def limpar_tudo():
524
  """Limpa todos os inputs da UI, incluindo filtros de histórico, para seus valores padrão."""
525
  analytics_data = gerar_relatorio_analytics()
@@ -955,7 +974,7 @@ def gerar_post_interface(tema, nicho, estilo, formato, usar_cache, favorito_chec
955
  progress=gr.Progress()):
956
  """
957
  Função principal unificada, com Cache, Analytics, Favoritos e Geração Avançada.
958
- Retorna 10 valores para a UI.
959
  """
960
 
961
  analytics_display = gerar_relatorio_analytics() # Carregar estado atual
@@ -966,8 +985,8 @@ def gerar_post_interface(tema, nicho, estilo, formato, usar_cache, favorito_chec
966
  progress(0.1, desc="✅ Validando...")
967
  if not tema or len(tema.strip()) < 3:
968
  status_final = criar_alerta('error', '⚠️ Digite um tema válido!')
969
- # Retorna 10 valores
970
- return ("", None, status_final, 0, 0, 0, analytics_display, True, gr.Textbox(interactive=False), gr.Button(value="✏️ Refinar Post"))
971
  time.sleep(0.3)
972
 
973
  # 1. Lógica de Cache
@@ -998,7 +1017,7 @@ def gerar_post_interface(tema, nicho, estilo, formato, usar_cache, favorito_chec
998
  }
999
  atualizar_historico(history_entry)
1000
 
1001
- return (texto, imagem, status_final, palavras, caracteres, hashtags, analytics_display, True, gr.Textbox(interactive=False), gr.Button(value="✏️ Refinar Post"))
1002
 
1003
  print("Cache miss ou cache desativado.")
1004
  progress(0.3, desc="🤖 Gerando texto (Llama 3.1)...")
@@ -1008,7 +1027,7 @@ def gerar_post_interface(tema, nicho, estilo, formato, usar_cache, favorito_chec
1008
 
1009
  if texto.startswith("❌"):
1010
  status_final = criar_alerta('error', f'{texto}')
1011
- return (texto, None, status_final, 0, 0, 0, analytics_display, True, gr.Textbox(interactive=False), gr.Button(value="✏️ Refinar Post"))
1012
 
1013
  progress(0.5, desc="✅ Texto pronto!")
1014
  time.sleep(0.5)
@@ -1071,7 +1090,7 @@ def gerar_post_interface(tema, nicho, estilo, formato, usar_cache, favorito_chec
1071
 
1072
  progress(1.0, desc="🎉 Pronto!")
1073
 
1074
- return (texto, imagem, status_final, palavras, caracteres, hashtags, analytics_display, True, gr.Textbox(interactive=False), gr.Button(value="✏️ Refinar Post"))
1075
 
1076
 
1077
  # ============================================
@@ -1138,10 +1157,18 @@ with gr.Blocks(theme=custom_theme, title="Gerador de Posts e Chatbot (Completo)"
1138
  interactive=True
1139
  )
1140
 
1141
- usar_cache_checkbox = gr.Checkbox(
1142
- label="⚡ Usar Cache?",
1143
- value=True
1144
- )
 
 
 
 
 
 
 
 
1145
 
1146
  gr.Markdown("") # Espaçamento
1147
 
@@ -1223,7 +1250,8 @@ with gr.Blocks(theme=custom_theme, title="Gerador de Posts e Chatbot (Completo)"
1223
  refinar_btn = gr.Button("✏️ Refinar Post")
1224
 
1225
  with gr.Row():
1226
- copiar_btn = gr.Button("📋 Copiar Texto", variant="secondary")
 
1227
  limpar_btn = gr.Button("🧹 Limpar Tudo", variant="stop")
1228
 
1229
  gr.Markdown("") # Espaçamento
@@ -1470,6 +1498,7 @@ with gr.Blocks(theme=custom_theme, title="Gerador de Posts e Chatbot (Completo)"
1470
  texto_output, imagem_output, status_output,
1471
  palavras_output, caracteres_output, hashtags_output,
1472
  analytics_display,
 
1473
  editor_locked, texto_output, refinar_btn
1474
  ]
1475
 
@@ -1481,10 +1510,10 @@ with gr.Blocks(theme=custom_theme, title="Gerador de Posts e Chatbot (Completo)"
1481
  show_progress="full"
1482
  )
1483
 
1484
- # Botão copiar (sem _js)
1485
  copiar_btn.click(
1486
- fn=copiar_feedback,
1487
- inputs=[texto_output],
1488
  outputs=[status_output]
1489
  )
1490
 
@@ -1511,6 +1540,7 @@ with gr.Blocks(theme=custom_theme, title="Gerador de Posts e Chatbot (Completo)"
1511
  download_zip_output,
1512
  download_csv_file,
1513
  analytics_display,
 
1514
  # Editor
1515
  editor_locked,
1516
  texto_output,
@@ -1537,6 +1567,13 @@ with gr.Blocks(theme=custom_theme, title="Gerador de Posts e Chatbot (Completo)"
1537
  outputs=[download_zip_output]
1538
  )
1539
 
 
 
 
 
 
 
 
1540
  # Botão Refinar
1541
  refinar_btn.click(
1542
  fn=toggle_editor_interactivity,
 
431
 
432
  # Cor do texto clara padrão para fundos escuros
433
  cor_texto_clara = "#f1f5f9" # Light slate/gray
 
434
 
435
  html = "<div style='max-height: 600px; overflow-y: auto; padding-right: 10px;'>"
436
  for i, post in enumerate(history_list):
 
466
  border-radius: 8px; background-color: {cor_fundo}; color: {cor_texto_clara};
467
  box-shadow: 0 4px 6px rgba(0,0,0,0.1); cursor: default;'>
468
  <div style='display: flex; justify-content: space-between; margin-bottom: 8px;'>
469
+ <strong style='font-size: 16px; color: {cor_texto_clara};'>{favorito_icon} {post.get('Tema', 'Sem título')}</strong>
470
+ <span style='color: {cor_texto_clara}; font-size: 12px;'>{data}</span>
471
  </div>
472
+ <div style='color: {cor_texto_clara}; font-size: 13px; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid rgba(255,255,255,0.2);'>
473
  <span>📁 Nicho: {post.get('Nicho', 'N/A')}</span> |
474
  <span>🎨 Estilo: {post.get('Estilo', 'N/A')}</span> |
475
  <span>📄 Formato: {post.get('Formato', 'N/A')}</span>
 
480
  {texto_completo}
481
  </div>
482
 
483
+ <div style='display: flex; gap: 16px; font-size: 12px; color: {cor_texto_clara};'>
484
  <span>📊 Palavras: {palavras}</span>
485
  <span>📏 Caracteres: {caracteres}</span>
486
  <span>#️⃣ Hashtags: {hashtags}</span>
 
519
  """Função de callback para o evento 'like' do chatbot."""
520
  print(f"Mensagem {x.index} foi marcada como: {x.value}, Liked: {x.liked}")
521
 
522
+ def limpar_cache():
523
+ """Remove todos os arquivos de cache"""
524
+ try:
525
+ count = 0
526
+ for arquivo in CACHE_DIR.glob("*"):
527
+ if arquivo.is_file(): # Garante que só apagamos arquivos
528
+ arquivo.unlink()
529
+ count += 1
530
+ print(f"{count} arquivos de cache removidos.")
531
+ return True
532
+ except Exception as e:
533
+ print(f"Erro ao limpar cache: {e}")
534
+ return False
535
+
536
+ def limpar_cache_feedback():
537
+ """Limpa cache e retorna feedback"""
538
+ if limpar_cache():
539
+ return criar_alerta('success', '🗑️ Cache limpo com sucesso!')
540
+ return criar_alerta('error', '❌ Erro ao limpar cache')
541
+
542
  def limpar_tudo():
543
  """Limpa todos os inputs da UI, incluindo filtros de histórico, para seus valores padrão."""
544
  analytics_data = gerar_relatorio_analytics()
 
974
  progress=gr.Progress()):
975
  """
976
  Função principal unificada, com Cache, Analytics, Favoritos e Geração Avançada.
977
+ Retorna 11 valores para a UI.
978
  """
979
 
980
  analytics_display = gerar_relatorio_analytics() # Carregar estado atual
 
985
  progress(0.1, desc="✅ Validando...")
986
  if not tema or len(tema.strip()) < 3:
987
  status_final = criar_alerta('error', '⚠️ Digite um tema válido!')
988
+ # Retorna 11 valores
989
+ return ("", None, status_final, 0, 0, 0, analytics_display, "", True, gr.Textbox(interactive=False), gr.Button(value="✏️ Refinar Post"))
990
  time.sleep(0.3)
991
 
992
  # 1. Lógica de Cache
 
1017
  }
1018
  atualizar_historico(history_entry)
1019
 
1020
+ return (texto, imagem, status_final, palavras, caracteres, hashtags, analytics_display, texto, True, gr.Textbox(interactive=False), gr.Button(value="✏️ Refinar Post"))
1021
 
1022
  print("Cache miss ou cache desativado.")
1023
  progress(0.3, desc="🤖 Gerando texto (Llama 3.1)...")
 
1027
 
1028
  if texto.startswith("❌"):
1029
  status_final = criar_alerta('error', f'{texto}')
1030
+ return (texto, None, status_final, 0, 0, 0, analytics_display, "", True, gr.Textbox(interactive=False), gr.Button(value="✏️ Refinar Post"))
1031
 
1032
  progress(0.5, desc="✅ Texto pronto!")
1033
  time.sleep(0.5)
 
1090
 
1091
  progress(1.0, desc="🎉 Pronto!")
1092
 
1093
+ return (texto, imagem, status_final, palavras, caracteres, hashtags, analytics_display, texto, True, gr.Textbox(interactive=False), gr.Button(value="✏️ Refinar Post"))
1094
 
1095
 
1096
  # ============================================
 
1157
  interactive=True
1158
  )
1159
 
1160
+ with gr.Group():
1161
+ gr.Markdown("### Performance")
1162
+ usar_cache_checkbox = gr.Checkbox(
1163
+ label="Usar cache",
1164
+ value=True,
1165
+ info="Reutiliza resultados anteriores (mais rápido)"
1166
+ )
1167
+ limpar_cache_btn = gr.Button(
1168
+ "🗑️ Limpar Cache",
1169
+ size="sm",
1170
+ variant="secondary"
1171
+ )
1172
 
1173
  gr.Markdown("") # Espaçamento
1174
 
 
1250
  refinar_btn = gr.Button("✏️ Refinar Post")
1251
 
1252
  with gr.Row():
1253
+ # CORREÇÃO: Substituído gr.Button por gr.Clipboard
1254
+ copiar_btn = gr.Clipboard(label="📋 Copiar Texto", value="")
1255
  limpar_btn = gr.Button("🧹 Limpar Tudo", variant="stop")
1256
 
1257
  gr.Markdown("") # Espaçamento
 
1498
  texto_output, imagem_output, status_output,
1499
  palavras_output, caracteres_output, hashtags_output,
1500
  analytics_display,
1501
+ copiar_btn, # CORREÇÃO: Adicionado copiar_btn aqui
1502
  editor_locked, texto_output, refinar_btn
1503
  ]
1504
 
 
1510
  show_progress="full"
1511
  )
1512
 
1513
+ # Botão copiar (sem _js, agora é gr.Clipboard)
1514
  copiar_btn.click(
1515
+ fn=lambda: criar_alerta('success', '✅ Texto copiado!'),
1516
+ inputs=None,
1517
  outputs=[status_output]
1518
  )
1519
 
 
1540
  download_zip_output,
1541
  download_csv_file,
1542
  analytics_display,
1543
+ copiar_btn, # CORREÇÃO: Adicionado copiar_btn aqui
1544
  # Editor
1545
  editor_locked,
1546
  texto_output,
 
1567
  outputs=[download_zip_output]
1568
  )
1569
 
1570
+ # Conectar o novo botão Limpar Cache
1571
+ limpar_cache_btn.click(
1572
+ fn=limpar_cache_feedback,
1573
+ inputs=None,
1574
+ outputs=[status_output]
1575
+ )
1576
+
1577
  # Botão Refinar
1578
  refinar_btn.click(
1579
  fn=toggle_editor_interactivity,