Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,80 +1,112 @@
|
|
| 1 |
-
|
| 2 |
import gradio as gr
|
| 3 |
import torch
|
| 4 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 5 |
|
|
|
|
| 6 |
MODEL_NAME = "microsoft/DialoGPT-small"
|
| 7 |
|
| 8 |
-
# Carrega tokenizer e modelo
|
| 9 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 10 |
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME).to("cpu")
|
| 11 |
|
| 12 |
|
| 13 |
-
def gerar_resposta(
|
| 14 |
"""
|
| 15 |
-
|
| 16 |
-
[
|
| 17 |
-
{"role": "user", "content": "
|
| 18 |
-
{"role": "assistant", "content": "..."},
|
| 19 |
...
|
| 20 |
]
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
"""
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
#
|
|
|
|
|
|
|
|
|
|
| 38 |
inputs = tokenizer(
|
| 39 |
texto,
|
| 40 |
return_tensors="pt",
|
| 41 |
truncation=True,
|
| 42 |
-
max_length=512
|
| 43 |
)
|
| 44 |
|
| 45 |
-
#
|
| 46 |
with torch.no_grad():
|
| 47 |
output_ids = model.generate(
|
| 48 |
**inputs,
|
| 49 |
-
max_new_tokens=
|
| 50 |
do_sample=True,
|
| 51 |
top_p=0.9,
|
| 52 |
temperature=0.7,
|
| 53 |
pad_token_id=tokenizer.eos_token_id,
|
| 54 |
)
|
| 55 |
|
| 56 |
-
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
if "
|
| 60 |
-
resposta =
|
| 61 |
else:
|
| 62 |
-
resposta =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
return resposta
|
| 65 |
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
iface = gr.ChatInterface(
|
| 68 |
fn=gerar_resposta,
|
| 69 |
-
type="messages",
|
| 70 |
-
title="Chatbot
|
| 71 |
-
description=
|
| 72 |
examples=[
|
| 73 |
-
"
|
| 74 |
-
"
|
| 75 |
-
"
|
|
|
|
| 76 |
],
|
| 77 |
)
|
| 78 |
|
| 79 |
if __name__ == "__main__":
|
| 80 |
iface.launch()
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 4 |
|
| 5 |
+
# Modelo pequeno, viável em CPU grátis
|
| 6 |
MODEL_NAME = "microsoft/DialoGPT-small"
|
| 7 |
|
|
|
|
| 8 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 9 |
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME).to("cpu")
|
| 10 |
|
| 11 |
|
| 12 |
+
def gerar_resposta(messages):
|
| 13 |
"""
|
| 14 |
+
Novo formato do Gradio (type='messages'):
|
| 15 |
+
messages = [
|
| 16 |
+
{"role": "user" | "assistant", "content": "texto"},
|
|
|
|
| 17 |
...
|
| 18 |
]
|
| 19 |
|
| 20 |
+
A função deve receber apenas 'messages' e retornar uma string
|
| 21 |
+
com a resposta do bot.
|
| 22 |
"""
|
| 23 |
|
| 24 |
+
# Prompt de sistema: define o "personagem" do bot
|
| 25 |
+
system_prefix = (
|
| 26 |
+
"Você é o Professor DL, um professor de Deep Learning. "
|
| 27 |
+
"Responda SEMPRE em português do Brasil, de forma simples, didática e objetiva, "
|
| 28 |
+
"usando exemplos práticos quando possível. "
|
| 29 |
+
"Explique conceitos como redes neurais, CNN, RNN, overfitting, regularização, etc., "
|
| 30 |
+
"sem fórmulas muito pesadas."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# Monta o texto de conversa
|
| 34 |
+
texto = system_prefix + "\n\n"
|
| 35 |
|
| 36 |
+
for msg in messages:
|
| 37 |
+
role = msg.get("role", "user")
|
| 38 |
+
content = msg.get("content", "")
|
| 39 |
+
if role == "user":
|
| 40 |
+
texto += f"Aluno: {content}\n"
|
| 41 |
+
else:
|
| 42 |
+
texto += f"Professor DL: {content}\n"
|
| 43 |
|
| 44 |
+
# Última fala deve ser do professor
|
| 45 |
+
texto += "Professor DL:"
|
| 46 |
+
|
| 47 |
+
# Tokenização
|
| 48 |
inputs = tokenizer(
|
| 49 |
texto,
|
| 50 |
return_tensors="pt",
|
| 51 |
truncation=True,
|
| 52 |
+
max_length=512,
|
| 53 |
)
|
| 54 |
|
| 55 |
+
# Geração
|
| 56 |
with torch.no_grad():
|
| 57 |
output_ids = model.generate(
|
| 58 |
**inputs,
|
| 59 |
+
max_new_tokens=120,
|
| 60 |
do_sample=True,
|
| 61 |
top_p=0.9,
|
| 62 |
temperature=0.7,
|
| 63 |
pad_token_id=tokenizer.eos_token_id,
|
| 64 |
)
|
| 65 |
|
| 66 |
+
saida = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 67 |
|
| 68 |
+
# Pega apenas o trecho depois do último "Professor DL:"
|
| 69 |
+
if "Professor DL:" in saida:
|
| 70 |
+
resposta = saida.split("Professor DL:")[-1].strip()
|
| 71 |
else:
|
| 72 |
+
resposta = saida.strip()
|
| 73 |
+
|
| 74 |
+
if not resposta:
|
| 75 |
+
resposta = (
|
| 76 |
+
"Boa pergunta! Tenta reformular ou ser um pouco mais específico "
|
| 77 |
+
"sobre o que você quer saber em Deep Learning."
|
| 78 |
+
)
|
| 79 |
|
| 80 |
return resposta
|
| 81 |
|
| 82 |
|
| 83 |
+
descricao = """
|
| 84 |
+
### 🤖 Professor DL – Chatbot de Deep Learning
|
| 85 |
+
|
| 86 |
+
Este chatbot foi treinado para atuar como um **professor de Deep Learning**:
|
| 87 |
+
|
| 88 |
+
- Explica conceitos de redes neurais profundas
|
| 89 |
+
- Fala sobre CNN, RNN, overfitting, regularização, etc.
|
| 90 |
+
- Responde sempre em **português**, de forma simples e didática
|
| 91 |
+
|
| 92 |
+
Use este Space em aula para mostrar:
|
| 93 |
+
1. Como integrar **Transformers** + **Gradio** em um Hugging Face Space
|
| 94 |
+
2. Como adaptar o *prompt* para criar um assistente temático (neste caso, Deep Learning)
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
iface = gr.ChatInterface(
|
| 98 |
fn=gerar_resposta,
|
| 99 |
+
type="messages", # formato novo do Gradio
|
| 100 |
+
title="Professor DL - Chatbot de Deep Learning",
|
| 101 |
+
description=descricao,
|
| 102 |
examples=[
|
| 103 |
+
"O que é Deep Learning?",
|
| 104 |
+
"Qual a diferença entre rede neural e CNN?",
|
| 105 |
+
"O que é overfitting?",
|
| 106 |
+
"Como começo a estudar Deep Learning na prática?",
|
| 107 |
],
|
| 108 |
)
|
| 109 |
|
| 110 |
if __name__ == "__main__":
|
| 111 |
iface.launch()
|
| 112 |
+
|