Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,179 +1,131 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
English Helper - Hugging Face Spaces
|
| 4 |
-
|
| 5 |
"""
|
| 6 |
|
| 7 |
import os
|
| 8 |
import gradio as gr
|
| 9 |
import threading
|
| 10 |
import time
|
| 11 |
-
from pathlib import Path
|
| 12 |
-
|
| 13 |
-
# Configurar ambiente
|
| 14 |
-
os.environ.setdefault('FLASK_ENV', 'production')
|
| 15 |
|
| 16 |
def start_flask_server():
|
| 17 |
-
"""Iniciar servidor Flask em
|
| 18 |
try:
|
| 19 |
-
#
|
| 20 |
os.environ.setdefault('FLASK_ENV', 'production')
|
| 21 |
-
from flask_app import app
|
| 22 |
|
| 23 |
-
#
|
|
|
|
| 24 |
from database import init_db
|
|
|
|
|
|
|
| 25 |
init_db()
|
|
|
|
| 26 |
|
| 27 |
-
# Executar Flask
|
| 28 |
port = int(os.environ.get("FLASK_PORT", 5000))
|
|
|
|
| 29 |
app.run(host="0.0.0.0", port=port, debug=False, threaded=True)
|
| 30 |
|
| 31 |
except Exception as e:
|
| 32 |
-
print(f"❌ Erro
|
| 33 |
|
| 34 |
-
def
|
| 35 |
-
"""
|
| 36 |
-
status = {
|
| 37 |
-
"Flask Server": "🟢 Running",
|
| 38 |
-
"Database": "🟢 Connected",
|
| 39 |
-
"Groq API": "🟢 Active" if os.getenv('GROQ_API_KEY') else "🔴 Missing",
|
| 40 |
-
"Gemini API": "🟢 Active" if os.getenv('GEMINI_API_KEY') else "🔴 Missing",
|
| 41 |
-
"Admin Panel": f"🟢 Available at /admin" if os.getenv('ADMIN_USERNAME') else "🔴 Not configured"
|
| 42 |
-
}
|
| 43 |
-
|
| 44 |
-
status_text = "## 🎯 English Helper System Status\n\n"
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
status_text += "## 🌐 Access Links\n\n"
|
| 53 |
-
status_text += f"**Main App**: [{base_url}]({base_url})\n\n"
|
| 54 |
-
status_text += f"**Admin Panel**: [{base_url}/admin]({base_url}/admin)\n\n"
|
| 55 |
-
status_text += f"**API Health**: [{base_url}/auth/check]({base_url}/auth/check)\n\n"
|
| 56 |
-
|
| 57 |
-
return status_text
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
# Interface Gradio
|
| 70 |
with gr.Blocks(
|
| 71 |
-
title="English Helper - AI Learning
|
| 72 |
-
theme=gr.themes.Soft()
|
| 73 |
-
css="""
|
| 74 |
-
.container { max-width: 1200px; margin: 0 auto; }
|
| 75 |
-
.status-panel { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 76 |
-
color: white; padding: 20px; border-radius: 10px; }
|
| 77 |
-
.feature-card { border: 1px solid #e1e5e9; border-radius: 8px; padding: 16px; margin: 8px; }
|
| 78 |
-
"""
|
| 79 |
) as demo:
|
| 80 |
|
| 81 |
gr.HTML("""
|
| 82 |
-
<div
|
| 83 |
-
<h1>🎓 English Helper
|
| 84 |
-
<p>Sistema completo de aprendizado de inglês com IA
|
| 85 |
</div>
|
| 86 |
""")
|
| 87 |
|
| 88 |
with gr.Tab("📊 System Status"):
|
| 89 |
-
|
| 90 |
-
refresh_btn = gr.Button("🔄 Refresh Status", variant="
|
| 91 |
-
refresh_btn.click(fn=
|
| 92 |
|
| 93 |
with gr.Tab("🚀 Quick Start"):
|
| 94 |
gr.Markdown("""
|
| 95 |
-
## 🎯 Como
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
|
| 102 |
-
##
|
| 103 |
-
- 🤖 **Chat
|
| 104 |
-
- 📚 **Flashcards**:
|
| 105 |
-
- 📰 **Curadoria
|
| 106 |
-
- 📅 **
|
| 107 |
-
-
|
| 108 |
-
|
| 109 |
-
### 3️⃣ **Painel Administrativo**
|
| 110 |
-
- 👤 **Admin Access**: Use o link "/admin" com suas credenciais
|
| 111 |
-
- 📈 **Analytics**: Métricas de uso e progresso dos usuários
|
| 112 |
-
- ⚙️ **Configurações**: Gerenciamento do sistema
|
| 113 |
-
- 💾 **Database**: Visualização e backup dos dados
|
| 114 |
-
""")
|
| 115 |
-
|
| 116 |
-
with gr.Tab("⚙️ Configuration"):
|
| 117 |
-
gr.Markdown("""
|
| 118 |
-
## 🔧 Configuração do Sistema
|
| 119 |
-
|
| 120 |
-
### ✅ **APIs Configuradas**:
|
| 121 |
-
- **Groq API**: Processamento rápido de linguagem natural
|
| 122 |
-
- **Gemini API**: Análise avançada de conteúdo e conversação
|
| 123 |
-
|
| 124 |
-
### 📧 **Email (Opcional)**:
|
| 125 |
-
Configure SMTP para confirmação de email e notificações
|
| 126 |
-
|
| 127 |
-
### 🔐 **Segurança**:
|
| 128 |
-
- Todas as chaves são armazenadas como Repository Secrets
|
| 129 |
-
- Sessões seguras com HTTPS
|
| 130 |
-
- Autenticação administrativa protegida
|
| 131 |
-
|
| 132 |
-
### 📊 **Monitoramento**:
|
| 133 |
-
- Logs detalhados de uso da API
|
| 134 |
-
- Métricas de performance
|
| 135 |
-
- Alertas de sistema
|
| 136 |
-
""")
|
| 137 |
-
|
| 138 |
-
with gr.Tab("🆘 Support"):
|
| 139 |
-
gr.Markdown("""
|
| 140 |
-
## 🛟 Suporte e Troubleshooting
|
| 141 |
-
|
| 142 |
-
### 🔍 **Verificações Básicas**:
|
| 143 |
-
1. **System Status**: Verifique se todos os serviços estão ativos
|
| 144 |
-
2. **API Keys**: Confirme se Groq e Gemini estão configurados
|
| 145 |
-
3. **Database**: Verifique conexão no painel admin
|
| 146 |
-
|
| 147 |
-
### ⚠️ **Problemas Comuns**:
|
| 148 |
-
- **500 Error**: Verifique logs e configurações de API
|
| 149 |
-
- **Admin não acessa**: Confirme ADMIN_USERNAME/PASSWORD
|
| 150 |
-
- **Slow response**: Verifique cotas de API
|
| 151 |
-
|
| 152 |
-
### 📚 **Documentação**:
|
| 153 |
-
- **Setup Guide**: Consulte HUGGINGFACE_SETUP.md
|
| 154 |
-
- **API Docs**: Groq e Gemini documentation
|
| 155 |
-
- **Flask Guide**: Deploy e configuração
|
| 156 |
-
|
| 157 |
-
### 🔗 **Links Úteis**:
|
| 158 |
-
- [Hugging Face Spaces Docs](https://huggingface.co/docs/hub/spaces)
|
| 159 |
-
- [Groq Console](https://console.groq.com/)
|
| 160 |
-
- [Google AI Studio](https://makersuite.google.com/)
|
| 161 |
""")
|
| 162 |
|
| 163 |
return demo
|
| 164 |
|
| 165 |
# Executar aplicação
|
| 166 |
if __name__ == "__main__":
|
| 167 |
-
print("🎯
|
| 168 |
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
#
|
|
|
|
| 172 |
demo.launch(
|
| 173 |
server_name="0.0.0.0",
|
| 174 |
server_port=7860,
|
| 175 |
share=False,
|
| 176 |
debug=False,
|
| 177 |
-
enable_queue=True,
|
| 178 |
show_error=True
|
| 179 |
)
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
English Helper - Hugging Face Spaces
|
| 4 |
+
Sistema de aprendizado de inglês com IA
|
| 5 |
"""
|
| 6 |
|
| 7 |
import os
|
| 8 |
import gradio as gr
|
| 9 |
import threading
|
| 10 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
def start_flask_server():
|
| 13 |
+
"""Iniciar servidor Flask em background"""
|
| 14 |
try:
|
| 15 |
+
# Configurar ambiente
|
| 16 |
os.environ.setdefault('FLASK_ENV', 'production')
|
|
|
|
| 17 |
|
| 18 |
+
# Importar e inicializar
|
| 19 |
+
from flask_app import app
|
| 20 |
from database import init_db
|
| 21 |
+
|
| 22 |
+
# Inicializar banco
|
| 23 |
init_db()
|
| 24 |
+
print("✅ Banco de dados inicializado")
|
| 25 |
|
| 26 |
+
# Executar Flask
|
| 27 |
port = int(os.environ.get("FLASK_PORT", 5000))
|
| 28 |
+
print(f"🌐 Iniciando Flask na porta {port}")
|
| 29 |
app.run(host="0.0.0.0", port=port, debug=False, threaded=True)
|
| 30 |
|
| 31 |
except Exception as e:
|
| 32 |
+
print(f"❌ Erro no Flask: {e}")
|
| 33 |
|
| 34 |
+
def get_system_status():
|
| 35 |
+
"""Status do sistema"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
# Verificar APIs
|
| 38 |
+
groq_status = "🟢 OK" if os.getenv('GROQ_API_KEY') else "🔴 Missing"
|
| 39 |
+
gemini_status = "🟢 OK" if os.getenv('GEMINI_API_KEY') else "🔴 Missing"
|
| 40 |
+
admin_status = "🟢 OK" if os.getenv('ADMIN_USERNAME') else "🔴 Missing"
|
| 41 |
|
| 42 |
+
status = f"""
|
| 43 |
+
## 🎓 English Helper - Sistema Status
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
### 📊 **APIs**
|
| 46 |
+
- **Groq API**: {groq_status}
|
| 47 |
+
- **Gemini API**: {gemini_status}
|
| 48 |
+
- **Admin Panel**: {admin_status}
|
| 49 |
+
|
| 50 |
+
### 🌐 **Links de Acesso**
|
| 51 |
+
- **Sistema Principal**: Use a URL do Space na porta principal
|
| 52 |
+
- **Painel Admin**: `/admin` - Acesse via navegador
|
| 53 |
+
- **Health Check**: `/auth/check` - Status da API
|
| 54 |
+
|
| 55 |
+
### ⚙️ **Como Usar**
|
| 56 |
+
1. **Configure os Repository Secrets** no HF
|
| 57 |
+
2. **Aguarde** o sistema inicializar
|
| 58 |
+
3. **Acesse** os links acima
|
| 59 |
+
4. **Login Admin** com suas credenciais
|
| 60 |
+
|
| 61 |
+
### 🔧 **Secrets Necessários**
|
| 62 |
+
- GROQ_API_KEY
|
| 63 |
+
- GEMINI_API_KEY
|
| 64 |
+
- SECRET_KEY
|
| 65 |
+
- ADMIN_USERNAME
|
| 66 |
+
- ADMIN_PASSWORD
|
| 67 |
+
- BASE_URL
|
| 68 |
+
"""
|
| 69 |
|
| 70 |
+
return status
|
| 71 |
+
|
| 72 |
+
# Interface Gradio
|
| 73 |
+
def create_interface():
|
| 74 |
+
"""Criar interface Gradio"""
|
| 75 |
|
|
|
|
| 76 |
with gr.Blocks(
|
| 77 |
+
title="English Helper - AI Learning",
|
| 78 |
+
theme=gr.themes.Soft()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
) as demo:
|
| 80 |
|
| 81 |
gr.HTML("""
|
| 82 |
+
<div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 83 |
+
<h1>🎓 English Helper</h1>
|
| 84 |
+
<p>Sistema completo de aprendizado de inglês com IA</p>
|
| 85 |
</div>
|
| 86 |
""")
|
| 87 |
|
| 88 |
with gr.Tab("📊 System Status"):
|
| 89 |
+
status_display = gr.Markdown(get_system_status())
|
| 90 |
+
refresh_btn = gr.Button("🔄 Refresh Status", variant="primary")
|
| 91 |
+
refresh_btn.click(fn=get_system_status, outputs=status_display)
|
| 92 |
|
| 93 |
with gr.Tab("🚀 Quick Start"):
|
| 94 |
gr.Markdown("""
|
| 95 |
+
## 🎯 Como começar:
|
| 96 |
|
| 97 |
+
1. **Verifique o Status** - Confirme se as APIs estão configuradas
|
| 98 |
+
2. **Acesse o Sistema** - Use os links na aba "System Status"
|
| 99 |
+
3. **Faça Login** - Use suas credenciais de admin
|
| 100 |
+
4. **Explore** - Chat IA, flashcards, curadoria, etc.
|
| 101 |
|
| 102 |
+
## 🔧 Funcionalidades:
|
| 103 |
+
- 🤖 **Chat IA**: Conversação inteligente
|
| 104 |
+
- 📚 **Flashcards**: Vocabulário personalizado
|
| 105 |
+
- 📰 **Curadoria**: Artigos por nível
|
| 106 |
+
- 📅 **Planos**: Cronograma de estudos
|
| 107 |
+
- 📊 **Analytics**: Dashboard completo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
""")
|
| 109 |
|
| 110 |
return demo
|
| 111 |
|
| 112 |
# Executar aplicação
|
| 113 |
if __name__ == "__main__":
|
| 114 |
+
print("🎯 Iniciando English Helper no Hugging Face Spaces...")
|
| 115 |
|
| 116 |
+
# Iniciar Flask em background
|
| 117 |
+
flask_thread = threading.Thread(target=start_flask_server, daemon=True)
|
| 118 |
+
flask_thread.start()
|
| 119 |
+
|
| 120 |
+
# Aguardar Flask inicializar
|
| 121 |
+
time.sleep(3)
|
| 122 |
|
| 123 |
+
# Criar e executar interface Gradio
|
| 124 |
+
demo = create_interface()
|
| 125 |
demo.launch(
|
| 126 |
server_name="0.0.0.0",
|
| 127 |
server_port=7860,
|
| 128 |
share=False,
|
| 129 |
debug=False,
|
|
|
|
| 130 |
show_error=True
|
| 131 |
)
|