Bernardo Damiani commited on
Commit
47f4dd2
·
1 Parent(s): f4e0eea

teste de alteração de script

Browse files
Files changed (1) hide show
  1. app.py +73 -20
app.py CHANGED
@@ -1,21 +1,74 @@
1
  import streamlit as st
2
- from transformers import pipeline
3
- from textblob import TextBlob
4
-
5
- pipe = pipeline('sentiment-analysis')
6
- st.title("Sentiment Analysis")
7
-
8
- st.subheader("Which framework would you like to use for sentiment analysis?")
9
- option = st.selectbox('Choose Framework:',('Transformers', 'TextBlob')) # option is stored in this variable
10
-
11
- st.subheader("Enter the text you want to analyze")
12
- text = st.text_input('Enter text:') # text is stored in this variable
13
-
14
- if option == 'Transformers':
15
- out = pipe(text)
16
- else:
17
- out = TextBlob(text)
18
- out = out.sentiment
19
-
20
- st.write("Sentiment of Text: ")
21
- st.write(out)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
+ from scipy.special import softmax
6
+ import torch
7
+
8
+ st.set_page_config(page_title="Análise de Sentimento com Transformers", layout="wide")
9
+
10
+ # Título
11
+ st.title("🔍 Análise de Sentimentos com Transformers")
12
+ st.markdown("Insira textos e escolha um modelo de linguagem para realizar a classificação de sentimentos.")
13
+
14
+ # Modelos disponíveis
15
+ modelos_disponiveis = {
16
+ "FinBert (Financeiro - PT-BR)": "turing-usp/FinBertPTBR",
17
+ "BERT Base PT-BR (NeuralMind)": "neuralmind/bert-base-portuguese-cased",
18
+ "Multilingual BERT": "nlptown/bert-base-multilingual-uncased-sentiment"
19
+ }
20
+
21
+ # Sidebar com seleção de modelo
22
+ modelo_escolhido = st.sidebar.selectbox("Escolha o modelo:", list(modelos_disponiveis.keys()))
23
+ model_name = modelos_disponiveis[modelo_escolhido]
24
+
25
+ @st.cache_resource(show_spinner=False)
26
+ def carregar_modelo(model_name):
27
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
28
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
29
+ return tokenizer, model
30
+
31
+ tokenizer, model = carregar_modelo(model_name)
32
+
33
+ def avaliar_sentimento(texto):
34
+ inputs = tokenizer(texto, return_tensors="pt", padding=True, truncation=True, max_length=512)
35
+ with torch.no_grad():
36
+ outputs = model(**inputs)
37
+ scores = softmax(outputs.logits[0].numpy())
38
+ labels = model.config.id2label
39
+ resultado = {labels[i]: float(scores[i]) for i in range(len(scores))}
40
+ sentimento_previsto = max(resultado, key=resultado.get)
41
+ return {"sentimento": sentimento_previsto, "scores": resultado}
42
+
43
+ # Entrada de textos
44
+ textos = st.text_area("Digite os textos (um por linha):", height=200)
45
+
46
+ if st.button("🔍 Analisar Sentimentos"):
47
+ linhas = [linha.strip() for linha in textos.strip().split("\n") if linha.strip()]
48
+
49
+ if not linhas:
50
+ st.warning("Por favor, insira ao menos um texto.")
51
+ else:
52
+ resultados = []
53
+ for t in linhas:
54
+ res = avaliar_sentimento(t)
55
+ resultados.append({
56
+ "Texto": t,
57
+ "Sentimento": res["sentimento"],
58
+ **res["scores"]
59
+ })
60
+
61
+ df_resultados = pd.DataFrame(resultados)
62
+ st.success("Análise concluída!")
63
+
64
+ # Mostrar tabela
65
+ st.subheader("📋 Resultados")
66
+ st.dataframe(df_resultados, use_container_width=True)
67
+
68
+ # Gráfico
69
+ st.subheader("📊 Distribuição de Sentimentos")
70
+ fig, ax = plt.subplots()
71
+ df_resultados["Sentimento"].value_counts().plot(kind='bar', ax=ax, rot=0)
72
+ ax.set_xlabel("Sentimento")
73
+ ax.set_ylabel("Frequência")
74
+ st.pyplot(fig)