Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,146 +1,68 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
4 |
|
5 |
-
#
|
6 |
-
|
7 |
-
|
8 |
|
9 |
-
#
|
10 |
-
|
11 |
-
"GPT-2": {
|
12 |
-
"name": "gpt2",
|
13 |
-
"max_tokens": 150
|
14 |
-
},
|
15 |
-
"GPT-Neo 125M": {
|
16 |
-
"name": "EleutherAI/gpt-neo-125M",
|
17 |
-
"max_tokens": 150
|
18 |
-
}
|
19 |
-
}
|
20 |
|
21 |
-
#
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
model = AutoModelForCausalLM.from_pretrained(
|
26 |
-
config["name"],
|
27 |
-
torch_dtype=TORCH_DTYPE,
|
28 |
-
device_map="auto" if DEVICE == 0 else None,
|
29 |
-
low_cpu_mem_usage=True
|
30 |
-
)
|
31 |
-
tokenizer = AutoTokenizer.from_pretrained(config["name"])
|
32 |
-
pipe = pipeline(
|
33 |
-
"text-generation",
|
34 |
-
model=model,
|
35 |
-
tokenizer=tokenizer,
|
36 |
-
device=DEVICE,
|
37 |
-
return_full_text=False,
|
38 |
-
pad_token_id=tokenizer.eos_token_id if tokenizer.eos_token_id else 50256
|
39 |
-
)
|
40 |
-
loaded_models[model_name] = {
|
41 |
-
"pipe": pipe,
|
42 |
-
"max_tokens": config["max_tokens"]
|
43 |
-
}
|
44 |
-
print(f"✅ {model_name} carregado com sucesso")
|
45 |
-
except Exception as e:
|
46 |
-
print(f"❌ Erro ao carregar {model_name}: {str(e)}")
|
47 |
-
loaded_models[model_name] = None
|
48 |
|
49 |
-
|
50 |
-
|
51 |
-
arbiter = pipeline(
|
52 |
-
"text-classification",
|
53 |
-
model="distilbert-base-uncased-finetuned-sst-2-english",
|
54 |
-
device=DEVICE
|
55 |
-
)
|
56 |
-
print("✅ Modelo árbitro carregado com sucesso")
|
57 |
-
except Exception as e:
|
58 |
-
print(f"❌ Erro ao carregar modelo árbitro: {str(e)}")
|
59 |
-
arbiter = None
|
60 |
-
|
61 |
-
def format_prompt(user_input):
|
62 |
-
return f"Responda de forma clara e concisa: {user_input.strip()}"
|
63 |
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
try:
|
69 |
-
response = config["pipe"](
|
70 |
-
format_prompt(prompt),
|
71 |
-
max_new_tokens=config["max_tokens"],
|
72 |
-
temperature=0.7,
|
73 |
-
top_p=0.9,
|
74 |
-
repetition_penalty=1.2
|
75 |
-
)[0]['generated_text'].strip()
|
76 |
-
return response if response else "Nenhuma resposta gerada."
|
77 |
-
except Exception as e:
|
78 |
-
return f"Erro na geração: {str(e)}"
|
79 |
-
|
80 |
-
def judge_responses(resp1, resp2):
|
81 |
-
if not arbiter:
|
82 |
-
# Se não houver árbitro, retorne a primeira resposta por padrão
|
83 |
-
return ("GPT-2", resp1)
|
84 |
-
inputs = [resp1, resp2]
|
85 |
-
try:
|
86 |
-
results = arbiter(inputs)
|
87 |
-
score1 = results[0]['score'] if results[0]['label'].lower() == 'positive' else 1 - results[0]['score']
|
88 |
-
score2 = results[1]['score'] if results[1]['label'].lower() == 'positive' else 1 - results[1]['score']
|
89 |
-
if score1 > score2:
|
90 |
-
return ("GPT-2", resp1)
|
91 |
-
else:
|
92 |
-
return ("GPT-Neo 125M", resp2)
|
93 |
-
except Exception as e:
|
94 |
-
# Em caso de erro, escolha arbitrariamente a primeira
|
95 |
-
return ("GPT-2", resp1)
|
96 |
|
|
|
97 |
def chatbot(prompt):
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
"Modelo Vencedor": winner_name,
|
105 |
-
"Resposta Escolhida": winner_resp
|
106 |
-
}
|
107 |
|
108 |
-
|
109 |
-
gr.Markdown("# 🤖 Chatbot de Comparação com Árbitro")
|
110 |
-
gr.Markdown("Testa dois modelos e escolhe a melhor resposta com um modelo árbitro")
|
111 |
-
|
112 |
-
with gr.Row():
|
113 |
-
input_prompt = gr.Textbox(
|
114 |
-
label="Digite sua pergunta:",
|
115 |
-
placeholder="Escreva algo em português...",
|
116 |
-
lines=3
|
117 |
-
)
|
118 |
-
|
119 |
-
submit_btn = gr.Button("Enviar Pergunta", variant="primary")
|
120 |
-
|
121 |
-
with gr.Row():
|
122 |
-
output_gpt2 = gr.Textbox(label="Resposta GPT-2", interactive=False)
|
123 |
-
output_gptneo = gr.Textbox(label="Resposta GPT-Neo 125M", interactive=False)
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
outputs=[output_gpt2, output_gptneo, output_winner, output_chosen]
|
132 |
)
|
133 |
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
-
|
142 |
-
|
|
|
|
|
143 |
|
144 |
-
|
145 |
-
|
|
|
146 |
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline
|
|
|
3 |
|
4 |
+
# Modelos pequenos e leves para rodar no ambiente gratuito
|
5 |
+
model_a = pipeline("text-generation", model="gpt2")
|
6 |
+
model_b = pipeline("text-generation", model="EleutherAI/gpt-neo-125M")
|
7 |
|
8 |
+
# Modelo juiz baseado em sentimento (positivo ou negativo)
|
9 |
+
arbiter = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
# Função para julgar a melhor resposta com base em sentimento positivo
|
12 |
+
def judge_response(prompt, response_a, response_b):
|
13 |
+
combined_a = f"Question: {prompt} Answer: {response_a}"
|
14 |
+
combined_b = f"Question: {prompt} Answer: {response_b}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
score_a = arbiter(combined_a)[0]['score']
|
17 |
+
score_b = arbiter(combined_b)[0]['score']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
+
if score_a > score_b:
|
20 |
+
return "Model A", response_a
|
21 |
+
else:
|
22 |
+
return "Model B", response_b
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
# Função principal do chatbot
|
25 |
def chatbot(prompt):
|
26 |
+
raw_response_a = model_a(prompt, max_new_tokens=60)[0]['generated_text']
|
27 |
+
raw_response_b = model_b(prompt, max_new_tokens=60)[0]['generated_text']
|
28 |
+
|
29 |
+
# Remove o prompt inicial da resposta
|
30 |
+
response_a = raw_response_a[len(prompt):].strip()
|
31 |
+
response_b = raw_response_b[len(prompt):].strip()
|
|
|
|
|
|
|
32 |
|
33 |
+
winner, final_response = judge_response(prompt, response_a, response_b)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
+
return (
|
36 |
+
prompt,
|
37 |
+
response_a,
|
38 |
+
response_b,
|
39 |
+
winner,
|
40 |
+
final_response
|
|
|
41 |
)
|
42 |
|
43 |
+
# Interface Gradio
|
44 |
+
iface = gr.Interface(
|
45 |
+
fn=chatbot,
|
46 |
+
inputs=gr.Textbox(label="Digite sua pergunta:"),
|
47 |
+
outputs=[
|
48 |
+
gr.Textbox(label="Pergunta"),
|
49 |
+
gr.Textbox(label="Resposta do Modelo A (GPT-2)"),
|
50 |
+
gr.Textbox(label="Resposta do Modelo B (GPT-Neo-125M)"),
|
51 |
+
gr.Textbox(label="Modelo Vencedor"),
|
52 |
+
gr.Textbox(label="Resposta Escolhida"),
|
53 |
+
],
|
54 |
+
title="Chatbot em Cascata com Julgamento",
|
55 |
+
description="""
|
56 |
+
Este chatbot utiliza dois modelos diferentes para responder à pergunta de um usuário.
|
57 |
+
Um terceiro modelo avalia qual resposta possui maior sentimento positivo e a apresenta como a melhor.
|
58 |
|
59 |
+
🧠 Modelos usados:
|
60 |
+
- Modelo A: GPT-2 (`gpt2`)
|
61 |
+
- Modelo B: GPT-Neo 125M (`EleutherAI/gpt-neo-125M`)
|
62 |
+
- Árbitro: DistilBERT SST-2 (`distilbert-base-uncased-finetuned-sst-2-english`)
|
63 |
|
64 |
+
Critério de julgamento: Resposta com maior sentimento positivo vence.
|
65 |
+
"""
|
66 |
+
)
|
67 |
|
68 |
+
iface.launch()
|