Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
from langchain_openai import ChatOpenAI
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from langdetect import detect
|
| 6 |
+
|
| 7 |
+
# Carregar variáveis de ambiente
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
# Configuração da API do OpenRouter
|
| 11 |
+
api_key = os.getenv("OPENROUTER_API_KEY", "free")
|
| 12 |
+
os.environ["OPENAI_API_KEY"] = api_key
|
| 13 |
+
os.environ["OPENAI_API_BASE"] = "https://openrouter.ai/api/v1"
|
| 14 |
+
|
| 15 |
+
# Inicializar modelo LLM
|
| 16 |
+
llm = ChatOpenAI(
|
| 17 |
+
model="deepseek/deepseek-r1:free",
|
| 18 |
+
temperature=0.5,
|
| 19 |
+
max_tokens=1024
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def responder(mensagem):
|
| 23 |
+
try:
|
| 24 |
+
prompt_inicial = (
|
| 25 |
+
"Você é um tutor experiente e empático de programação em Python, atuando em uma escola de tecnologia.\n\n"
|
| 26 |
+
"Sua missão é ajudar alunos iniciantes e intermediários a aprender Python com clareza e confiança.\n"
|
| 27 |
+
"Sempre explique os conceitos de forma simples e didática, com exemplos fáceis de entender, analogias úteis e uma abordagem encorajadora.\n"
|
| 28 |
+
"Ao identificar dúvidas ou erros, oriente o aluno passo a passo, destacando boas práticas e possíveis causas do problema.\n"
|
| 29 |
+
"Evite respostas diretas a exercícios de avaliação. Em vez disso, forneça pistas, estratégias de resolução e caminhos para que o aluno desenvolva a solução por conta própria.\n"
|
| 30 |
+
"Se a pergunta estiver incompleta ou mal formulada, peça gentilmente mais detalhes.\n\n"
|
| 31 |
+
f"Mensagem do aluno: \"{mensagem}\"\n"
|
| 32 |
+
"Resposta do tutor:"
|
| 33 |
+
)
|
| 34 |
+
resposta = llm.invoke(prompt_inicial)
|
| 35 |
+
return resposta.content
|
| 36 |
+
except Exception as e:
|
| 37 |
+
import traceback
|
| 38 |
+
return f"❌ Erro:\n{traceback.format_exc()}"
|
| 39 |
+
|
| 40 |
+
# Saudações multilíngues
|
| 41 |
+
SAUDACOES = {
|
| 42 |
+
'pt': ["Olá! 😊 Como posso ajudar?", "E aí! 👋 Tudo bem?", "Oi! 😄 Em que posso ajudar?"],
|
| 43 |
+
'en': ["Hi! 😊 How can I help?", "Hello! 👋 How are you?", "Hey! 😄 What can I do for you?"],
|
| 44 |
+
'es': ["¡Hola! 😊 ¿Cómo puedo ayudarte?", "¡Hola! 👋 ¿Qué tal?", "¡Hola! 😄 ¿En qué puedo ayudarte?"],
|
| 45 |
+
'fr': ["Salut! 😊 Comment puis-je aider?", "Bonjour! 👋 Ça va?", "Coucou! 😄 Comment puis-je t'aider?"],
|
| 46 |
+
'it': ["Ciao! 😊 Come posso aiutarti?", "Salve! 👋 Come stai?", "Ciao! 😄 Come posso esserti utile?"]
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Detectar idioma da mensagem
|
| 50 |
+
def detectar_idioma(texto):
|
| 51 |
+
try:
|
| 52 |
+
lang = detect(texto)
|
| 53 |
+
return lang if lang in SAUDACOES else 'pt'
|
| 54 |
+
except:
|
| 55 |
+
return 'pt'
|
| 56 |
+
|
| 57 |
+
# Função principal de resposta
|
| 58 |
+
def responder(mensagem, historico):
|
| 59 |
+
try:
|
| 60 |
+
lang = detectar_idioma(mensagem.strip())
|
| 61 |
+
|
| 62 |
+
# Se for uma saudação
|
| 63 |
+
if mensagem.lower().strip() in ['oi', 'olá', 'ola', 'hi', 'hello', 'hola', 'salut', 'ciao']:
|
| 64 |
+
import random
|
| 65 |
+
resposta = random.choice(SAUDACOES.get(lang, SAUDACOES['pt']))
|
| 66 |
+
else:
|
| 67 |
+
prompt = f"Responda em {lang} para esta mensagem: {mensagem}"
|
| 68 |
+
resultado = llm.invoke(prompt)
|
| 69 |
+
resposta = resultado.content.strip() if resultado and resultado.content else "Desculpe, não consegui entender. Pode repetir?"
|
| 70 |
+
|
| 71 |
+
novo_historico = historico + [
|
| 72 |
+
{"role": "user", "content": mensagem},
|
| 73 |
+
{"role": "assistant", "content": resposta}
|
| 74 |
+
]
|
| 75 |
+
return "", novo_historico
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print("Erro:", e)
|
| 79 |
+
error_msg = {
|
| 80 |
+
'pt': "⚠️ Ocorreu um erro, tente novamente.",
|
| 81 |
+
'en': "⚠️ An error occurred, please try again.",
|
| 82 |
+
'es': "⚠️ Ocurrió un error, intenta nuevamente.",
|
| 83 |
+
'fr': "⚠️ Une erreur est survenue, veuillez réessayer.",
|
| 84 |
+
'it': "⚠️ Si è verificato un errore, riprova."
|
| 85 |
+
}.get(lang, "⚠️ An unexpected error occurred.")
|
| 86 |
+
|
| 87 |
+
novo_historico = historico + [
|
| 88 |
+
{"role": "user", "content": mensagem},
|
| 89 |
+
{"role": "assistant", "content": error_msg}
|
| 90 |
+
]
|
| 91 |
+
return "", novo_historico
|
| 92 |
+
|
| 93 |
+
# Interface com Gradio
|
| 94 |
+
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 95 |
+
gr.Markdown("# PythOr")
|
| 96 |
+
|
| 97 |
+
chatbot = gr.Chatbot(height=400, type="messages")
|
| 98 |
+
|
| 99 |
+
with gr.Row():
|
| 100 |
+
msg = gr.Textbox(
|
| 101 |
+
label="Mensagem",
|
| 102 |
+
placeholder="Olá! Eu sou o PythOr, o seu tutor. Em que posso te ajudar?",
|
| 103 |
+
container=False,
|
| 104 |
+
scale=7
|
| 105 |
+
)
|
| 106 |
+
btn = gr.Button("Enviar", scale=1)
|
| 107 |
+
|
| 108 |
+
btn.click(responder, [msg, chatbot], [msg, chatbot])
|
| 109 |
+
msg.submit(responder, [msg, chatbot], [msg, chatbot])
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|