ViniciusKhan commited on
Commit
31fae4b
·
1 Parent(s): 0c970c3

🚀 Add Gradio app com análise de sentimentos para texto e Excel

Browse files
Files changed (3) hide show
  1. README.md +73 -0
  2. app.py +37 -8
  3. requirements.txt +6 -3
README.md CHANGED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ title: Senticore – Análise de Sentimentos
4
+ sdk: gradio
5
+ emoji: 🚀
6
+ colorFrom: green
7
+ colorTo: green
8
+ pinned: false
9
+ ---
10
+
11
+ # 🚀 Senticore – Análise de Sentimentos com FastAPI + BERT
12
+
13
+ O **Senticore API** é uma solução de inferência de sentimentos baseada em BERT e implementada com FastAPI, hospedada como um Space no Hugging Face. Ele recebe um texto livre e retorna a polaridade (`Positivo`, `Neutro`, `Negativo`) com sua respectiva confiança.
14
+
15
+ ---
16
+
17
+ ## ✅ Funcionalidades
18
+
19
+ - Classificação de sentimento em português (positivo, neutro ou negativo)
20
+ - Uso do modelo `ViniciusKhan/bert-nps-feedback-analyzer`
21
+ - API RESTful com FastAPI
22
+ - Suporte a múltiplas chamadas (batch)
23
+ - Deploy no Hugging Face Spaces via Docker
24
+
25
+ ---
26
+
27
+ ## 🚀 Como usar
28
+
29
+ Após o deploy no Hugging Face Spaces, acesse a URL da sua API e envie uma requisição `POST` com um JSON como este:
30
+
31
+ ```json
32
+ {
33
+ "texto": "Muito satisfeito com o atendimento e suporte da equipe."
34
+ }
35
+ ```
36
+
37
+ A resposta será:
38
+
39
+ ```json
40
+ {
41
+ "sentimento": "Positivo",
42
+ "confianca": 0.9453
43
+ }
44
+ ```
45
+
46
+ ---
47
+
48
+ ## 📂 Estrutura do Projeto
49
+
50
+ ```
51
+ senticore-api/
52
+ ├── app/
53
+ │ ├── main.py
54
+ │ └── routes/
55
+ │ └── sentiment.py
56
+ ├── app.py
57
+ ├── requirements.txt
58
+ ├── Dockerfile
59
+ └── README.md
60
+ ```
61
+
62
+ ---
63
+
64
+ ## 👨‍💻 Autor
65
+
66
+ Desenvolvido por **Vinicius de Souza Santos**
67
+ 🎓 Eng. da Computação | Especialista em ML, Data Analysis e Software
68
+
69
+ ---
70
+
71
+ ## 📄 Licença
72
+
73
+ Licenciado sob os termos da Licença MIT.
app.py CHANGED
@@ -1,22 +1,51 @@
1
  import gradio as gr
 
2
  from transformers import pipeline
3
 
4
- # Carrega modelo do Hugging Face Hub
5
  modeloHF = "ViniciusKhan/bert-nps-feedback-analyzer"
6
  sentiment_pipeline = pipeline("text-classification", model=modeloHF)
7
 
 
8
  def analisar_sentimento(texto):
9
  resultado = sentiment_pipeline([texto[:512]])[0]
10
  sentimento = resultado["label"]
11
  confianca = round(resultado["score"], 4)
12
  return f"Sentimento: {sentimento}\nConfiança: {confianca}"
13
 
14
- demo = gr.Interface(
15
- fn=analisar_sentimento,
16
- inputs=gr.Textbox(lines=6, placeholder="Cole aqui o feedback do cliente..."),
17
- outputs="text",
18
- title="Senticore – Análise de Sentimentos NPS",
19
- description="Classificador inteligente baseado em BERT para identificar sentimentos em textos de feedback e NPS."
20
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  demo.launch()
 
1
  import gradio as gr
2
+ import pandas as pd
3
  from transformers import pipeline
4
 
5
+ # Carrega o modelo do Hugging Face
6
  modeloHF = "ViniciusKhan/bert-nps-feedback-analyzer"
7
  sentiment_pipeline = pipeline("text-classification", model=modeloHF)
8
 
9
+ # 🔍 Função para analisar texto simples
10
  def analisar_sentimento(texto):
11
  resultado = sentiment_pipeline([texto[:512]])[0]
12
  sentimento = resultado["label"]
13
  confianca = round(resultado["score"], 4)
14
  return f"Sentimento: {sentimento}\nConfiança: {confianca}"
15
 
16
+ # 📊 Função para processar arquivo Excel
17
+ def analisar_arquivo(file):
18
+ try:
19
+ df = pd.read_excel(file)
20
+ except Exception:
21
+ return " Erro ao ler o arquivo. Certifique-se de que é um .xlsx válido."
22
+
23
+ if "Resumo" not in df.columns:
24
+ return "❌ A coluna obrigatória 'Resumo' não foi encontrada."
25
+
26
+ textos = df["Resumo"].fillna("").astype(str).str[:512].tolist()
27
+ resultados = sentiment_pipeline(textos, truncation=True)
28
+
29
+ df["Sentimento_Class"] = [r["label"] for r in resultados]
30
+ df["Confianca"] = [round(r["score"], 4) for r in resultados]
31
+
32
+ return df
33
+
34
+ # 🎛️ Interface Gradio
35
+ with gr.Blocks(title="Senticore – Análise de Sentimentos NPS") as demo:
36
+ gr.Markdown("## 🤖 Senticore – Análise de Sentimentos NPS")
37
+ gr.Markdown("Classificador inteligente baseado em BERT para identificar sentimentos em textos de feedback e NPS.")
38
+
39
+ with gr.Tab("📝 Texto Único"):
40
+ entrada_texto = gr.Textbox(lines=6, label="Cole aqui o feedback do cliente...")
41
+ saida_texto = gr.Textbox(label="Resultado")
42
+ botao_texto = gr.Button("🔍 Analisar Sentimento")
43
+ botao_texto.click(analisar_sentimento, entrada_texto, saida_texto)
44
+
45
+ with gr.Tab("📂 Arquivo Excel"):
46
+ entrada_arquivo = gr.File(file_types=[".xlsx"], label="Selecione um arquivo Excel (.xlsx)")
47
+ saida_tabela = gr.Dataframe(label="Resultado", interactive=False)
48
+ botao_excel = gr.Button("📥 Processar Arquivo")
49
+ botao_excel.click(analisar_arquivo, entrada_arquivo, saida_tabela)
50
 
51
  demo.launch()
requirements.txt CHANGED
@@ -1,5 +1,8 @@
1
  fastapi==0.110.2
2
  uvicorn==0.30.1
3
- transformers==4.41.1
4
- torch>=2.2
5
- pydantic==2.7.1
 
 
 
 
1
  fastapi==0.110.2
2
  uvicorn==0.30.1
3
+ pydantic==2.7.1
4
+ gradio
5
+ transformers
6
+ torch
7
+ pandas
8
+ openpyxl