ProfRod100 commited on
Commit
7b2d825
·
verified ·
1 Parent(s): 70179e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -17
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import gradio as gr
3
  import joblib
4
  import numpy as np
@@ -11,7 +12,7 @@ from transformers import pipeline as hf_pipeline
11
 
12
 
13
  # ============================================================
14
- # 1. Baseline de Sentimentos (TF-IDF + Logistic Regression)
15
  # ============================================================
16
 
17
  BASELINE_PATH = "baseline_pipe.pkl"
@@ -53,7 +54,7 @@ baseline_model = load_baseline()
53
 
54
  def classify_sentiment(text: str):
55
  """
56
- Classifica o texto como positivo/negativo e retorna um dicionário.
57
  """
58
  text = text.strip()
59
  if not text:
@@ -65,13 +66,20 @@ def classify_sentiment(text: str):
65
  return {"sentimento": label, "confianca": round(conf, 3)}
66
 
67
 
 
 
 
 
 
 
 
 
68
  # ============================================================
69
  # 2. IA Generativa — FLAN-T5 (modelo aberto, sem token)
70
  # ============================================================
71
 
72
  GEN_MODEL = os.getenv("GEN_MODEL_ID", "google/flan-t5-base")
73
 
74
- # text2text-generation é o modo ideal para FLAN-T5
75
  generator = hf_pipeline(
76
  "text2text-generation",
77
  model=GEN_MODEL,
@@ -138,6 +146,7 @@ def generate_reply(history, user_msg: str):
138
  - Classifica sentimento da nova mensagem
139
  - Gera resposta usando FLAN-T5
140
  - Atualiza o histórico
 
141
  """
142
  user_msg = user_msg.strip()
143
  if not user_msg:
@@ -145,7 +154,7 @@ def generate_reply(history, user_msg: str):
145
 
146
  sentimento = classify_sentiment(user_msg)
147
  if "erro" in sentimento:
148
- return history, "", sentimento["erro"]
149
 
150
  prompt = build_prompt(history, user_msg, sentimento)
151
 
@@ -157,14 +166,13 @@ def generate_reply(history, user_msg: str):
157
  top_p=0.9,
158
  )[0]["generated_text"].strip()
159
 
160
- # Atualiza histórico para o Chatbot
161
  new_history = history + [(user_msg, out)]
162
- # Limpa o campo de texto do usuário e também retornamos o JSON do sentimento
163
- return new_history, "", sentimento
164
 
165
 
166
  # ============================================================
167
- # 3. Interface Gradio (compatível com HF Spaces + queue)
168
  # ============================================================
169
 
170
  with gr.Blocks(
@@ -185,19 +193,22 @@ with gr.Blocks(
185
  """
186
  )
187
 
188
- # ----------------- Aba 1: Análise isolada -----------------
189
  with gr.Tab("Análise de Sentimento"):
190
  text_in = gr.Textbox(
191
  label="Digite um comentário",
192
  lines=4,
193
  placeholder="Ex.: O produto chegou quebrado, fiquei muito chateado.",
194
  )
195
- text_out = gr.JSON(label="Resultado da classificação")
 
 
 
196
  btn_analisar = gr.Button("Analisar sentimento", variant="primary")
197
 
198
- btn_analisar.click(classify_sentiment, inputs=text_in, outputs=text_out)
199
 
200
- # ----------------- Aba 2: Chatbot com histórico -----------------
201
  with gr.Tab("Chatbot (Análise + Resposta)"):
202
  chatbot = gr.Chatbot(
203
  label="Histórico de conversa com o atendente virtual",
@@ -208,17 +219,16 @@ with gr.Blocks(
208
  lines=3,
209
  placeholder="Ex.: Estou chateado, o produto é ruim.",
210
  )
211
- sentimento_box = gr.JSON(
212
- label="Sentimento da última mensagem analisada",
 
213
  )
214
  send_btn = gr.Button("Enviar e gerar resposta", variant="primary")
215
 
216
- # Quando clicar, gera resposta + atualiza histórico + mostra sentimento
217
  send_btn.click(
218
  generate_reply,
219
  inputs=[chatbot, user_box],
220
  outputs=[chatbot, user_box, sentimento_box],
221
  )
222
 
223
- # IMPORTANTE para Spaces: ativar fila (queue) antes de lançar
224
- demo.queue().launch()
 
1
  import os
2
+ import json
3
  import gradio as gr
4
  import joblib
5
  import numpy as np
 
12
 
13
 
14
  # ============================================================
15
+ # 1. Baseline de Sentimentos (TF-IDF + Regressão Logística)
16
  # ============================================================
17
 
18
  BASELINE_PATH = "baseline_pipe.pkl"
 
54
 
55
  def classify_sentiment(text: str):
56
  """
57
+ Classifica o texto como positivo/negativo e retorna um dicionário Python.
58
  """
59
  text = text.strip()
60
  if not text:
 
66
  return {"sentimento": label, "confianca": round(conf, 3)}
67
 
68
 
69
+ def classify_sentiment_str(text: str) -> str:
70
+ """
71
+ Versão para a interface: devolve o resultado como string JSON formatada.
72
+ """
73
+ result = classify_sentiment(text)
74
+ return json.dumps(result, ensure_ascii=False, indent=2)
75
+
76
+
77
  # ============================================================
78
  # 2. IA Generativa — FLAN-T5 (modelo aberto, sem token)
79
  # ============================================================
80
 
81
  GEN_MODEL = os.getenv("GEN_MODEL_ID", "google/flan-t5-base")
82
 
 
83
  generator = hf_pipeline(
84
  "text2text-generation",
85
  model=GEN_MODEL,
 
146
  - Classifica sentimento da nova mensagem
147
  - Gera resposta usando FLAN-T5
148
  - Atualiza o histórico
149
+ - Devolve também o sentimento como string para exibir na UI
150
  """
151
  user_msg = user_msg.strip()
152
  if not user_msg:
 
154
 
155
  sentimento = classify_sentiment(user_msg)
156
  if "erro" in sentimento:
157
+ return history, "", json.dumps(sentimento, ensure_ascii=False, indent=2)
158
 
159
  prompt = build_prompt(history, user_msg, sentimento)
160
 
 
166
  top_p=0.9,
167
  )[0]["generated_text"].strip()
168
 
 
169
  new_history = history + [(user_msg, out)]
170
+ sentimento_str = json.dumps(sentimento, ensure_ascii=False, indent=2)
171
+ return new_history, "", sentimento_str
172
 
173
 
174
  # ============================================================
175
+ # 3. Interface Gradio (sem gr.JSON)
176
  # ============================================================
177
 
178
  with gr.Blocks(
 
193
  """
194
  )
195
 
196
+ # ---------- Aba 1: Análise isolada ----------
197
  with gr.Tab("Análise de Sentimento"):
198
  text_in = gr.Textbox(
199
  label="Digite um comentário",
200
  lines=4,
201
  placeholder="Ex.: O produto chegou quebrado, fiquei muito chateado.",
202
  )
203
+ text_out = gr.Textbox(
204
+ label="Resultado da classificação (JSON)",
205
+ lines=4,
206
+ )
207
  btn_analisar = gr.Button("Analisar sentimento", variant="primary")
208
 
209
+ btn_analisar.click(classify_sentiment_str, inputs=text_in, outputs=text_out)
210
 
211
+ # ---------- Aba 2: Chatbot com histórico ----------
212
  with gr.Tab("Chatbot (Análise + Resposta)"):
213
  chatbot = gr.Chatbot(
214
  label="Histórico de conversa com o atendente virtual",
 
219
  lines=3,
220
  placeholder="Ex.: Estou chateado, o produto é ruim.",
221
  )
222
+ sentimento_box = gr.Textbox(
223
+ label="Sentimento da última mensagem analisada (JSON)",
224
+ lines=4,
225
  )
226
  send_btn = gr.Button("Enviar e gerar resposta", variant="primary")
227
 
 
228
  send_btn.click(
229
  generate_reply,
230
  inputs=[chatbot, user_box],
231
  outputs=[chatbot, user_box, sentimento_box],
232
  )
233
 
234
+ demo.launch()