File size: 3,867 Bytes
e4a5814
 
cdb53d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4a5814
cdb53d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4a5814
 
 
cdb53d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import os
import joblib
import pandas as pd
from datasets import load_dataset
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from transformers import pipeline


BASELINE_PATH = "baseline_pipe.pkl"


# ============================================================
# 1) Função para treinar automaticamente o modelo baseline
# ============================================================
def treinar_baseline():
    print("➡️ Nenhum baseline encontrado. Treinando modelo TF-IDF + Regressão Logística...")

    ds = load_dataset("amazon_polarity", split="train")
    ds_small = ds.shuffle(seed=42).select(range(8000))  # rápido para HF Spaces
    df = pd.DataFrame({"text": ds_small["content"], "label": ds_small["label"]})

    pipe = Pipeline([
        ("tfidf", TfidfVectorizer(max_features=20000, ngram_range=(1, 2))),
        ("clf", LogisticRegression(max_iter=1000))
    ])

    pipe.fit(df["text"], df["label"])
    joblib.dump(pipe, BASELINE_PATH)

    print("✔ Modelo baseline treinado e salvo!")
    return pipe


# ============================================================
# 2) Carregar modelo baseline
# ============================================================
def load_or_train():
    if os.path.exists(BASELINE_PATH):
        print("✔ baseline_pipe.pkl encontrado! Carregando...")
        return joblib.load(BASELINE_PATH)
    return treinar_baseline()


baseline_model = load_or_train()


# ============================================================
# 3) IA Generativa (sem token)
# ============================================================
generator = pipeline("text2text-generation", model="google/flan-t5-base")


def resposta_chatbot(texto):
    prompt = f"""
Você é um assistente de suporte educado, direto e profissional.
Responda de forma curta e natural.  
Pergunta: {texto}
Resposta:
"""
    out = generator(prompt, max_length=128)
    return out[0]["generated_text"]


# ============================================================
# 4) Classificação de sentimento
# ============================================================
def analisar_sentimento(texto):
    label = baseline_model.predict([texto])[0]
    prob = baseline_model.predict_proba([texto])[0].max()

    sentimento = "positivo" if label == 1 else "negativo"
    return {
        "sentimento": sentimento,
        "confianca": round(float(prob), 3)
    }


# ============================================================
# 5) Interface Gradio
# ============================================================
def interface_sentimento(texto):
    try:
        return analisar_sentimento(texto)
    except Exception as e:
        return {"erro": str(e)}


def interface_chatbot(texto, histórico):
    resposta = resposta_chatbot(texto)
    histórico.append((texto, resposta))
    return histórico, histórico


# ============================================================
# Aba de análise
# ============================================================
aba1 = gr.Interface(
    fn=interface_sentimento,
    inputs=gr.Textbox(label="Digite uma avaliação"),
    outputs=gr.JSON(label="Resultado"),
)


# ============================================================
# Aba de chatbot
# ============================================================
with gr.Blocks() as aba2:
    gr.Markdown("# Chatbot (IA Generativa)")

    chatbot = gr.Chatbot()
    entrada = gr.Textbox(label="Digite sua mensagem")

    entrada.submit(interface_chatbot, [entrada, chatbot], [chatbot, chatbot])


# ============================================================
# Tabs principais
# ============================================================
demo = gr.TabbedInterface(
    [aba1, aba2],
    ["Análise de Sentimentos", "Chatbot IA"]
)

demo.launch()