Roudrigus commited on
Commit
a94822d
·
verified ·
1 Parent(s): 293de9b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -12
app.py CHANGED
@@ -69,17 +69,40 @@ from uuid import uuid4
69
  from sqlalchemy import text, func, or_
70
 
71
  # 🗄️ Banco ativo (Produção/Teste/Treinamento)
 
72
  try:
73
- from db_router import current_db_choice, bank_label
74
  _HAS_ROUTER = True
75
  except Exception:
76
  _HAS_ROUTER = False
77
 
78
  def current_db_choice() -> str:
79
- return "prod"
 
80
 
81
  def bank_label(choice: str) -> str:
82
- return "🟢 Produção" if choice == "prod" else "🔴 Teste"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  # =========================================
85
  # 🔧 STARTUP HOOKS (1x por container / process)
@@ -670,6 +693,70 @@ def exibir_logo_once(top: bool = False, sidebar: bool = False):
670
  if need_sidebar:
671
  state["sidebar"] = True
672
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673
  # ===============================
674
  # MAIN
675
  # ===============================
@@ -688,6 +775,9 @@ def main():
688
  st.session_state.setdefault("__auto_refresh_interval_sec__", 60)
689
  st.session_state.setdefault("__auth_diag__", False) # 🔧 estado do painel de diagnóstico (Admin)
690
 
 
 
 
691
  # LOGIN
692
  if not st.session_state.logado:
693
  st.session_state.quiz_verificado = False
@@ -695,9 +785,9 @@ def main():
695
  exibir_logo_once(top=True, sidebar=False)
696
  login()
697
 
698
- # ⚠️ Opcional: dica breve quando nenhum caminho de auth está definido
699
- if not os.getenv("DISABLE_AUTH") and not os.getenv("ALLOW_EMERGENCY_LOGIN"):
700
- st.info("🔒 Autenticação ativa. Para testes rápidos no Spaces, defina **DISABLE_AUTH=1** ou habilite o **login emergencial** (ALLOW_EMERGENCY_LOGIN=1 + EMERG_*). Depois, **Restart this Space**.")
701
  return
702
 
703
  # 👥 Heartbeat + Badge de usuários logados (APENAS ADMIN)
@@ -927,11 +1017,9 @@ def main():
927
 
928
  st.sidebar.markdown("### Menu | 🎉 Carnaval 🎭 2026!")
929
 
930
- # Banco ativo na sidebar
931
  try:
932
- _b_label = bank_label(current_db_choice()) if _HAS_ROUTER else (
933
- "🟢 Produção" if current_db_choice() == "prod" else "🔴 Teste"
934
- )
935
  st.sidebar.caption(f"🗄️ Banco ativo: {_b_label}")
936
  except Exception:
937
  pass
@@ -1039,9 +1127,9 @@ def main():
1039
  termo_busca = st.sidebar.text_input("Pesquisar módulo:").strip().lower()
1040
 
1041
  try:
1042
- ambiente_atual = current_db_choice() if _HAS_ROUTER else "prod"
1043
  except Exception:
1044
- ambiente_atual = "prod"
1045
 
1046
  grupos_disponiveis = obter_grupos_disponiveis(
1047
  MODULES,
 
69
  from sqlalchemy import text, func, or_
70
 
71
  # 🗄️ Banco ativo (Produção/Teste/Treinamento)
72
+ # Tentativa de importar utilitários do db_router, com fallback seguro.
73
  try:
74
+ from db_router import current_db_choice, bank_label # já usados no seu app
75
  _HAS_ROUTER = True
76
  except Exception:
77
  _HAS_ROUTER = False
78
 
79
  def current_db_choice() -> str:
80
+ # Fallback simples
81
+ return st.session_state.get("__db_choice_override__", "prod")
82
 
83
  def bank_label(choice: str) -> str:
84
+ return {
85
+ "prod": "🟢 Produção",
86
+ "test": "🔴 Teste",
87
+ "train": "🟡 Treinamento",
88
+ }.get(choice, "🟢 Produção")
89
+
90
+ # 🔁 Tentativas de funções adicionais do router (se existirem)
91
+ _get_available_choices = None
92
+ _set_db_choice_func = None
93
+ if _HAS_ROUTER:
94
+ try:
95
+ from db_router import get_available_choices as _get_available_choices
96
+ except Exception:
97
+ _get_available_choices = None
98
+ # tenta 2 nomes comuns de setter
99
+ try:
100
+ from db_router import set_current_db_choice as _set_db_choice_func # tipo preferido
101
+ except Exception:
102
+ try:
103
+ from db_router import set_db_choice as _set_db_choice_func # alias
104
+ except Exception:
105
+ _set_db_choice_func = None
106
 
107
  # =========================================
108
  # 🔧 STARTUP HOOKS (1x por container / process)
 
693
  if need_sidebar:
694
  state["sidebar"] = True
695
 
696
+ # ===============================
697
+ # 🔧 Escolha do Banco (UI + setters)
698
+ # ===============================
699
+ def _db_choice_ui():
700
+ """
701
+ Renderiza na sidebar a seleção de banco de dados (Produção/Teste/Treinamento).
702
+ Usa db_router quando disponível; caso não, mantém fallback visual.
703
+ """
704
+ with st.sidebar.expander("🗄️ Banco de dados", expanded=True):
705
+ # Obtém lista de choices
706
+ if _get_available_choices:
707
+ try:
708
+ avail = list(_get_available_choices()) # ex.: ["prod","test","train"]
709
+ if not avail:
710
+ avail = ["prod", "test", "train"]
711
+ except Exception:
712
+ avail = ["prod", "test", "train"]
713
+ else:
714
+ avail = ["prod", "test", "train"]
715
+
716
+ # Label amigável para cada opção
717
+ def _lbl(c):
718
+ try:
719
+ return bank_label(c)
720
+ except Exception:
721
+ return {"prod": "🟢 Produção", "test": "🔴 Teste", "train": "🟡 Treinamento"}.get(c, c)
722
+
723
+ current = current_db_choice() if callable(current_db_choice) else st.session_state.get("__db_choice_override__", "prod")
724
+ labels = [_lbl(c) for c in avail]
725
+ # Mapeia índice atual
726
+ try:
727
+ idx = avail.index(current)
728
+ except Exception:
729
+ idx = 0
730
+
731
+ sel_label = st.selectbox(
732
+ "Escolha o banco:",
733
+ options=labels,
734
+ index=idx,
735
+ key="__db_choice_select__",
736
+ )
737
+ # Resolve escolha → código
738
+ sel_idx = labels.index(sel_label)
739
+ sel_code = avail[sel_idx]
740
+
741
+ # Aplica se mudou
742
+ if sel_code != current:
743
+ # Tenta aplicar no router (se houver)
744
+ applied = False
745
+ if _set_db_choice_func:
746
+ try:
747
+ _set_db_choice_func(sel_code)
748
+ applied = True
749
+ except Exception:
750
+ applied = False
751
+
752
+ # Fallback: guarda override local e exporta env var (se algum loader usar)
753
+ if not applied:
754
+ st.session_state["__db_choice_override__"] = sel_code
755
+ os.environ["DB_CHOICE"] = sel_code # se o router/engine ler do env
756
+
757
+ st.toast(f"Banco alterado para: {_lbl(sel_code)}", icon="🗄️")
758
+ st.rerun()
759
+
760
  # ===============================
761
  # MAIN
762
  # ===============================
 
775
  st.session_state.setdefault("__auto_refresh_interval_sec__", 60)
776
  st.session_state.setdefault("__auth_diag__", False) # 🔧 estado do painel de diagnóstico (Admin)
777
 
778
+ # ===== Seleção de banco (sempre visível na sidebar) =====
779
+ _db_choice_ui()
780
+
781
  # LOGIN
782
  if not st.session_state.logado:
783
  st.session_state.quiz_verificado = False
 
785
  exibir_logo_once(top=True, sidebar=False)
786
  login()
787
 
788
+ # 🔕 REMOVIDO: mensagem de dica de autenticação no Spaces (conforme solicitado)
789
+ # (antes havia um st.info(...) aqui removemos)
790
+
791
  return
792
 
793
  # 👥 Heartbeat + Badge de usuários logados (APENAS ADMIN)
 
1017
 
1018
  st.sidebar.markdown("### Menu | 🎉 Carnaval 🎭 2026!")
1019
 
1020
+ # Banco ativo na sidebar (badge rápido)
1021
  try:
1022
+ _b_label = bank_label(current_db_choice()) if _HAS_ROUTER else bank_label(current_db_choice())
 
 
1023
  st.sidebar.caption(f"🗄️ Banco ativo: {_b_label}")
1024
  except Exception:
1025
  pass
 
1127
  termo_busca = st.sidebar.text_input("Pesquisar módulo:").strip().lower()
1128
 
1129
  try:
1130
+ ambiente_atual = current_db_choice() if _HAS_ROUTER else current_db_choice()
1131
  except Exception:
1132
+ ambiente_atual = current_db_choice()
1133
 
1134
  grupos_disponiveis = obter_grupos_disponiveis(
1135
  MODULES,