Spaces:
Running
Running
File size: 8,554 Bytes
4d732f4 f8e49c0 4d732f4 f8e49c0 4d732f4 f8e49c0 4d732f4 f8e49c0 4d732f4 f8e49c0 4d732f4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
from flask import Flask, request, jsonify
import torch
import torch.nn as nn
import pandas as pd
from transformers import BertModel, AutoTokenizer
import re
from flask_cors import CORS
import logging
import os
import requests
from dotenv import load_dotenv
# Carregar variáveis de ambiente
load_dotenv()
app = Flask(__name__)
CORS(app)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
MAX_LEN = 200
# --- OpenRouter API ---
OPENROUTER_API_KEY = os.getenv('OPENROUTER_API_KEY')
OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'
# --- Emoções (mesma ordem do treino) ---
EMOTION_LABELS = [
'Neutro', 'Alegria', 'Tristeza', 'Raiva', 'Medo',
'Nojo', 'Surpresa', 'Confiança', 'Antecipação'
]
# Modelo usado no TREINO
MODEL_NAME = "neuralmind/bert-base-portuguese-cased"
SAVE_DIR = "models"
MODEL_PATH = f"{SAVE_DIR}/best_model.pth"
# ======================================================================
# BERT CLASSIFIER IGUAL AO DO TREINO
# ======================================================================
class BERTClassifier(nn.Module):
def __init__(self, model_name="neuralmind/bert-base-portuguese-cased", num_classes=9, dropout=0.3):
super().__init__()
self.bert = BertModel.from_pretrained(model_name)
self.dropout = nn.Dropout(dropout)
self.classifier = nn.Linear(self.bert.config.hidden_size, num_classes)
def forward(self, input_ids, attention_mask, token_type_ids=None):
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
return_dict=True
)
cls = outputs.last_hidden_state[:, 0]
x = self.dropout(cls)
return self.classifier(x)
# ======================================================================
# CARREGAR O MESMO MODELO E TOKENIZER DO TREINO
# ======================================================================
def load_trained_model():
logger.info(f"Carregando modelo e tokenizer de '{SAVE_DIR}'...")
if not os.path.exists(MODEL_PATH):
raise FileNotFoundError(f"Não encontrei o modelo treinado em {MODEL_PATH}")
tokenizer = AutoTokenizer.from_pretrained(SAVE_DIR)
model = BERTClassifier(model_name=MODEL_NAME, num_classes=len(EMOTION_LABELS))
state_dict = torch.load(MODEL_PATH, map_location=device)
model.load_state_dict(state_dict)
model.to(device)
model.eval()
logger.info("Modelo treinado carregado com sucesso!")
return model, tokenizer
try:
bert_model, tokenizer = load_trained_model()
loaded = True
except Exception as e:
logger.error(f"ERRO ao carregar modelo: {e}")
loaded = False
# ======================================================================
# PRÉ-PROCESSAMENTO (mesmo estilo do treino)
# ======================================================================
def preprocess_text(text: str):
if not isinstance(text, str):
return ""
text = re.sub(r'http\S+', '', text)
return text.strip()
def tokenize_text(text: str):
text = preprocess_text(text)
encoding = tokenizer.encode_plus(
text,
add_special_tokens=True,
max_length=MAX_LEN,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_token_type_ids=True,
return_tensors='pt'
)
return {
'input_ids': encoding['input_ids'].to(device),
'attention_mask': encoding['attention_mask'].to(device),
'token_type_ids': encoding['token_type_ids'].to(device)
}
# ======================================================================
# FUNÇÃO PARA CHAMAR OPENROUTER
# ======================================================================
import time
def call_openrouter(frase):
if not OPENROUTER_API_KEY:
raise ValueError("OPENROUTER_API_KEY não configurada")
prompt = f"""
Analise a frase: "{frase}".
Escolha UMA emoção principal de Plutchik:
'Neutro', 'Alegria', 'Tristeza', 'Raiva', 'Medo', 'Nojo', 'Surpresa', 'Confiança', 'Antecipação'.
Responda apenas com a emoção, sem explicação.
"""
headers = {
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"HTTP-Referer": "http://localhost:3030",
"Content-Type": "application/json"
}
# MODELOS A SEREM TENTADOS (ordem de fallback)
modelos_fallback = [
"google/gemma-3-12b-it:free",
"google/gemma-3-4b-it:free",
"google/gemma-3-27b-it:free",
"nvidia/nemotron-nano-12b-v2-vl:free"
]
erros = []
# 🔁 Tentar cada modelo até um funcionar
for modelo in modelos_fallback:
payload = {
"model": modelo,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.0
}
for tentativa in range(2): # duas tentativas por modelo
try:
response = requests.post(OPENROUTER_URL, json=payload, headers=headers)
result = response.json()
# Erro da OpenRouter
if "error" in result:
msg = str(result["error"]).lower()
# ⚠ Rate limit → tentar outra vez ou outro modelo
if "rate" in msg or "429" in msg:
time.sleep(1.2)
continue
# Outro erro → pular para próximo modelo
erros.append((modelo, result["error"]))
break
# Resposta válida
if "choices" in result:
emocao = result["choices"][0]["message"]["content"].strip().title()
emocao = emocao.replace("ç", "c").replace("ã", "a")
return emocao, modelo
# Formato inesperado
erros.append((modelo, result))
break
except Exception as e:
erros.append((modelo, str(e)))
time.sleep(1)
# Se chegou aqui, tenta o próximo modelo
# Se nenhum modelo funcionou
raise ValueError({
"mensagem": "Nenhum modelo conseguiu responder.",
"tentativas": erros
})
# ======================================================================
# ENDPOINTS
# ======================================================================
@app.route('/')
def home():
return jsonify({
"status": "API de Emoções BERT",
"modelo_carregado": loaded,
"device": str(device),
"emocoes": EMOTION_LABELS
})
@app.route('/bert', methods=['POST'])
def predict_emotion():
try:
if not loaded:
return jsonify({"erro": "Modelo BERT não carregado!"}), 500
data = request.get_json()
texto = data.get("texto", "").strip()
if not texto:
return jsonify({"erro": "Campo 'texto' é obrigatório"}), 400
inputs = tokenize_text(texto)
with torch.no_grad():
outputs = bert_model(
inputs['input_ids'],
inputs['attention_mask'],
inputs['token_type_ids']
)
probs = torch.softmax(outputs, dim=1)[0].cpu().numpy()
pred_idx = int(probs.argmax())
return jsonify({
"texto": texto,
"emocao": EMOTION_LABELS[pred_idx],
"confianca": float(probs[pred_idx]),
"todas_emocoes": {
EMOTION_LABELS[i]: float(probs[i]) for i in range(9)
}
})
except Exception as e:
logger.exception("Erro na predição:")
return jsonify({"erro": str(e)}), 500
@app.route('/llm', methods=['POST'])
def predict_llm():
try:
data = request.get_json()
frase = data.get("frase", "")
if not frase:
return jsonify({"erro": "Campo 'frase' é obrigatório"}), 400
emocao, modelo_usado = call_openrouter(frase)
return jsonify({
"frase": frase,
"emocao": emocao,
"modelo": modelo_usado
})
except Exception as e:
return jsonify({"erro": str(e)}), 500
# ======================================================================
# EXECUTAR SERVIDOR
# ======================================================================
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)
|