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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Versão Gradio para Hugging Face Spaces
|
| 3 |
+
Mais simples e com GPU gratuita!
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
# Configuração
|
| 12 |
+
MODEL_NAME = "lxyuan/distilbert-base-multilingual-cased-sentiments-student"
|
| 13 |
+
|
| 14 |
+
# Carregar modelo
|
| 15 |
+
print("Carregando modelo...")
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 17 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
|
| 18 |
+
model.eval()
|
| 19 |
+
|
| 20 |
+
# Labels
|
| 21 |
+
LABEL_MAP = {
|
| 22 |
+
0: "NEGATIVO",
|
| 23 |
+
1: "NEUTRO",
|
| 24 |
+
2: "POSITIVO"
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
EMOJI_MAP = {
|
| 28 |
+
"NEGATIVO": "😢",
|
| 29 |
+
"NEUTRO": "😐",
|
| 30 |
+
"POSITIVO": "😊"
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
def classificar_sentimento(texto):
|
| 34 |
+
"""
|
| 35 |
+
Classifica o sentimento do texto.
|
| 36 |
+
"""
|
| 37 |
+
if not texto or len(texto.strip()) < 3:
|
| 38 |
+
return "Por favor, digite um texto válido.", {}, 0.0
|
| 39 |
+
|
| 40 |
+
# Tokenizar
|
| 41 |
+
inputs = tokenizer(
|
| 42 |
+
texto,
|
| 43 |
+
padding=True,
|
| 44 |
+
truncation=True,
|
| 45 |
+
max_length=512,
|
| 46 |
+
return_tensors='pt'
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Predição
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
outputs = model(**inputs)
|
| 52 |
+
|
| 53 |
+
# Probabilidades
|
| 54 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 55 |
+
probs = probs.numpy()[0]
|
| 56 |
+
|
| 57 |
+
# Resultado
|
| 58 |
+
pred_class = int(np.argmax(probs))
|
| 59 |
+
sentimento = LABEL_MAP[pred_class]
|
| 60 |
+
confianca = float(np.max(probs))
|
| 61 |
+
|
| 62 |
+
# Criar dicionário de probabilidades para o Label
|
| 63 |
+
prob_dict = {
|
| 64 |
+
f"{EMOJI_MAP[LABEL_MAP[i]]} {LABEL_MAP[i]}": float(probs[i])
|
| 65 |
+
for i in range(len(probs))
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
# Resultado principal
|
| 69 |
+
resultado = f"{EMOJI_MAP[sentimento]} **{sentimento}**"
|
| 70 |
+
|
| 71 |
+
return resultado, prob_dict, confianca
|
| 72 |
+
|
| 73 |
+
# Exemplos
|
| 74 |
+
exemplos = [
|
| 75 |
+
["Adorei o produto! Superou minhas expectativas."],
|
| 76 |
+
["Péssimo atendimento, nunca mais volto."],
|
| 77 |
+
["Ok, nada de especial."],
|
| 78 |
+
["O filme é sensacional! Recomendo muito!"],
|
| 79 |
+
["Horrível! Pior experiência da minha vida."],
|
| 80 |
+
["Satisfeito com a compra, chegou rápido."],
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
+
# Tema customizado
|
| 84 |
+
tema = gr.themes.Soft(
|
| 85 |
+
primary_hue="purple",
|
| 86 |
+
secondary_hue="blue",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Interface Gradio
|
| 90 |
+
with gr.Blocks(theme=tema, title="Análise de Sentimentos") as demo:
|
| 91 |
+
gr.Markdown(
|
| 92 |
+
"""
|
| 93 |
+
# 🤖 Análise de Sentimentos com IA
|
| 94 |
+
|
| 95 |
+
Descubra o sentimento por trás do texto usando modelos Transformer!
|
| 96 |
+
|
| 97 |
+
Digite ou cole um texto e descubra se é **positivo**, **negativo** ou **neutro**.
|
| 98 |
+
"""
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
with gr.Row():
|
| 102 |
+
with gr.Column(scale=2):
|
| 103 |
+
texto_input = gr.Textbox(
|
| 104 |
+
label="📝 Digite seu texto aqui",
|
| 105 |
+
placeholder="Ex: Adorei o produto! Superou todas as minhas expectativas...",
|
| 106 |
+
lines=5,
|
| 107 |
+
max_lines=10
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
with gr.Row():
|
| 111 |
+
btn_analisar = gr.Button("🔍 Analisar Sentimento", variant="primary", size="lg")
|
| 112 |
+
btn_limpar = gr.ClearButton([texto_input], value="🗑️ Limpar")
|
| 113 |
+
|
| 114 |
+
with gr.Row():
|
| 115 |
+
with gr.Column(scale=1):
|
| 116 |
+
resultado_output = gr.Markdown(
|
| 117 |
+
label="Resultado",
|
| 118 |
+
value=""
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
confianca_output = gr.Number(
|
| 122 |
+
label="📊 Confiança",
|
| 123 |
+
precision=2
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
with gr.Column(scale=1):
|
| 127 |
+
probs_output = gr.Label(
|
| 128 |
+
label="📈 Distribuição de Probabilidades",
|
| 129 |
+
num_top_classes=3
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
gr.Markdown("### 💡 Exemplos para testar:")
|
| 133 |
+
gr.Examples(
|
| 134 |
+
examples=exemplos,
|
| 135 |
+
inputs=texto_input,
|
| 136 |
+
outputs=[resultado_output, probs_output, confianca_output],
|
| 137 |
+
fn=classificar_sentimento,
|
| 138 |
+
cache_examples=False
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
gr.Markdown(
|
| 142 |
+
"""
|
| 143 |
+
---
|
| 144 |
+
### 📚 Sobre o Modelo
|
| 145 |
+
|
| 146 |
+
Este sistema usa modelos **Transformer** treinados em milhares de textos em português.
|
| 147 |
+
|
| 148 |
+
**Características:**
|
| 149 |
+
- ✅ Análise em tempo real
|
| 150 |
+
- ✅ Suporte para português brasileiro
|
| 151 |
+
- ✅ Alta precisão
|
| 152 |
+
- ✅ Múltiplas classes (Positivo, Neutro, Negativo)
|
| 153 |
+
|
| 154 |
+
**Limitações:**
|
| 155 |
+
- Textos muito longos são truncados
|
| 156 |
+
- Sarcasmo pode ser difícil de detectar
|
| 157 |
+
- Contexto cultural pode afetar resultados
|
| 158 |
+
|
| 159 |
+
---
|
| 160 |
+
**Feito com ❤️ usando Transformers e Gradio**
|
| 161 |
+
"""
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# Eventos
|
| 165 |
+
btn_analisar.click(
|
| 166 |
+
fn=classificar_sentimento,
|
| 167 |
+
inputs=texto_input,
|
| 168 |
+
outputs=[resultado_output, probs_output, confianca_output]
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
texto_input.submit(
|
| 172 |
+
fn=classificar_sentimento,
|
| 173 |
+
inputs=texto_input,
|
| 174 |
+
outputs=[resultado_output, probs_output, confianca_output]
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# Iniciar
|
| 178 |
+
if __name__ == "__main__":
|
| 179 |
+
demo.launch(
|
| 180 |
+
share=False,
|
| 181 |
+
show_error=True
|
| 182 |
+
)
|