Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
Update app.py
Browse files
app.py
CHANGED
@@ -1,114 +1,98 @@
|
|
1 |
-
import numpy as np
|
2 |
-
from sklearn.decomposition import PCA
|
3 |
-
import gensim.downloader as api
|
4 |
import gradio as gr
|
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 |
-
width=600, # Adjust width as needed
|
41 |
-
height=400) # Adjust height as needed
|
42 |
-
|
43 |
-
return fig
|
44 |
-
|
45 |
-
|
46 |
-
def gradio_interface(choice, custom_input):
|
47 |
-
if choice == "Custom":
|
48 |
-
if not custom_input or len(custom_input.split(", ")) != 3:
|
49 |
-
return "Invalid input. Please enter exactly three words, separated by commas.", None, {
|
50 |
-
"error": "Invalid input"}
|
51 |
-
words = custom_input.split(", ")
|
52 |
-
else:
|
53 |
-
if not choice:
|
54 |
-
return "Invalid input. Please select or enter words.", None, {
|
55 |
-
"error": "Invalid input"}
|
56 |
-
words = choice.split(", ")
|
57 |
-
|
58 |
-
word1, word2, word3 = words
|
59 |
-
word4 = gensim_analogy(model, word1, word2, word3)
|
60 |
-
plot_fig = plot_words_plotly(model, [word1, word2, word3, word4])
|
61 |
-
|
62 |
-
if word4 in model.key_to_index:
|
63 |
-
vector = model[word4]
|
64 |
-
vector_display = f"{word4}: {np.round(vector, 2).tolist()}"
|
65 |
-
else:
|
66 |
-
vector_display = "Vector not available for the resulting word"
|
67 |
-
|
68 |
-
return word4, plot_fig, vector_display
|
69 |
-
|
70 |
-
|
71 |
-
choices = [
|
72 |
-
"man, king, woman",
|
73 |
-
"Paris, France, London",
|
74 |
-
"strong, stronger, weak",
|
75 |
-
"pork, pig, beef",
|
76 |
-
"Custom"
|
77 |
]
|
78 |
|
79 |
-
|
80 |
-
def
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline
|
3 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
4 |
+
from sklearn.naive_bayes import MultinomialNB
|
5 |
+
from sklearn.svm import SVC
|
6 |
+
from sklearn.ensemble import RandomForestClassifier
|
7 |
+
from sklearn.pipeline import make_pipeline
|
8 |
+
from sklearn.model_selection import train_test_split
|
9 |
+
from sklearn import metrics
|
10 |
+
import pandas as pd
|
11 |
+
|
12 |
+
# Load the provided dataset
|
13 |
+
file_path = 'data.csv'
|
14 |
+
df = pd.read_csv(file_path)
|
15 |
+
|
16 |
+
# Split data into training and test sets
|
17 |
+
X_train, X_test, y_train, y_test = train_test_split(df['Sentence'], df['Sentiment'], test_size=0.2, random_state=42)
|
18 |
+
|
19 |
+
# Define models
|
20 |
+
nb_model = make_pipeline(TfidfVectorizer(), MultinomialNB())
|
21 |
+
svm_model = make_pipeline(TfidfVectorizer(), SVC(probability=True))
|
22 |
+
rf_model = make_pipeline(TfidfVectorizer(), RandomForestClassifier())
|
23 |
+
|
24 |
+
# Train models
|
25 |
+
nb_model.fit(X_train, y_train)
|
26 |
+
svm_model.fit(X_train, y_train)
|
27 |
+
rf_model.fit(X_train, y_train)
|
28 |
+
|
29 |
+
# Define sentences to choose from
|
30 |
+
sentences = [
|
31 |
+
"The announced restructuring will significantly decrease the company's indebtedness.",
|
32 |
+
"UPM-Kymmene upgraded to `in-line' from `underperform' by Goldman Sachs.",
|
33 |
+
"$AAPL shares are breaking out of the recent resistance level.",
|
34 |
+
"Profitability (in EBIT %) was 13.6%, compared to 14.3% in Q2 2009.",
|
35 |
+
"The Finnish bank has issued a profit warning.",
|
36 |
+
"TeliaSonera's underlying results however included 457 mln SKr in positive one-offs, hence the adjusted underlying EBITDA actually amounts to 7.309 bln SKr, clearly below expectations, analysts said."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
]
|
38 |
|
39 |
+
# Function to map BERT labels
|
40 |
+
def map_bert_label(label):
|
41 |
+
if label in ["1 star", "2 stars"]:
|
42 |
+
return "negative"
|
43 |
+
elif label == "3 stars":
|
44 |
+
return "neutral"
|
45 |
+
elif label in ["4 stars", "5 stars"]:
|
46 |
+
return "positive"
|
47 |
+
|
48 |
+
|
49 |
+
# Function to map RoBERTa labels
|
50 |
+
def map_roberta_label(label):
|
51 |
+
label_mapping = {"LABEL_0": "negative", "LABEL_1": "neutral", "LABEL_2": "positive"}
|
52 |
+
return label_mapping[label]
|
53 |
+
|
54 |
+
|
55 |
+
# Function to analyze sentiment
|
56 |
+
def analyze_sentiment(sentence):
|
57 |
+
# Define model paths
|
58 |
+
model_paths = {
|
59 |
+
"FinBert": "ProsusAI/finbert",
|
60 |
+
"BERT": "nlptown/bert-base-multilingual-uncased-sentiment",
|
61 |
+
"RoBERTa": "cardiffnlp/twitter-roberta-base-sentiment"
|
62 |
+
}
|
63 |
+
|
64 |
+
# Analyze sentiment using transformers models
|
65 |
+
results = {}
|
66 |
+
for model_name, model_path in model_paths.items():
|
67 |
+
sentiment_analyzer = pipeline("sentiment-analysis", model=model_path)
|
68 |
+
result = sentiment_analyzer(sentence[:512])[0] # Analyze first 512 characters for brevity
|
69 |
+
|
70 |
+
if model_name == "BERT":
|
71 |
+
result['label'] = map_bert_label(result['label'])
|
72 |
+
elif model_name == "RoBERTa":
|
73 |
+
result['label'] = map_roberta_label(result['label'])
|
74 |
+
|
75 |
+
results[model_name] = result
|
76 |
+
|
77 |
+
# Analyze sentiment using sklearn models
|
78 |
+
results["Naive Bayes"] = {"label": nb_model.predict([sentence])[0],
|
79 |
+
"score": nb_model.predict_proba([sentence]).max()}
|
80 |
+
results["SVM"] = {"label": svm_model.predict([sentence])[0], "score": svm_model.predict_proba([sentence]).max()}
|
81 |
+
results["Random Forest"] = {"label": rf_model.predict([sentence])[0],
|
82 |
+
"score": rf_model.predict_proba([sentence]).max()}
|
83 |
+
|
84 |
+
return sentence, results
|
85 |
+
|
86 |
+
|
87 |
+
# Create Gradio interface
|
88 |
+
dropdown = gr.Dropdown(choices=sentences, label="Select Sentence")
|
89 |
+
text_output = gr.Textbox(label="Selected Sentence", lines=2)
|
90 |
+
sentiment_output = gr.JSON(label="Sentiment Scores")
|
91 |
+
|
92 |
+
gr.Interface(
|
93 |
+
fn=analyze_sentiment,
|
94 |
+
inputs=[dropdown],
|
95 |
+
outputs=[text_output, sentiment_output],
|
96 |
+
title="Compare Sentiment Analysis Across Models",
|
97 |
+
description="Select a sentence to see sentiment analysis results from multiple models."
|
98 |
+
).launch(share=True)
|