Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -21,11 +21,14 @@ classifier = pipeline("text-classification", model="distilbert/distilbert-base-u
|
|
| 21 |
generator = pipeline("text2text-generation", model="google/flan-t5-base")
|
| 22 |
|
| 23 |
# Function to classify customer comments
|
| 24 |
-
@spaces.GPU
|
| 25 |
def classify_comments(categories):
|
| 26 |
global df # Ensure we're modifying the global DataFrame
|
| 27 |
sentiments = []
|
| 28 |
assigned_categories = []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
for comment in df['customer_comment']:
|
| 30 |
# Classify sentiment
|
| 31 |
sentiment = classifier(comment)[0]['label']
|
|
@@ -35,38 +38,59 @@ def classify_comments(categories):
|
|
| 35 |
category = generator(prompt, max_length=30)[0]['generated_text']
|
| 36 |
assigned_categories.append(category)
|
| 37 |
sentiments.append(sentiment)
|
|
|
|
| 38 |
df['comment_sentiment'] = sentiments
|
| 39 |
df['comment_category'] = assigned_categories
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
return df[['customer_id', 'customer_comment', 'comment_sentiment', 'comment_category', 'customer_nps', 'customer_segment']].to_html(index=False)
|
| 41 |
|
| 42 |
# Function to generate visualizations
|
| 43 |
def visualize_output():
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
# Pie Chart of Sentiment
|
| 50 |
sentiment_counts = df['comment_sentiment'].value_counts()
|
| 51 |
sentiment_pie = px.pie(
|
| 52 |
values=sentiment_counts.values,
|
| 53 |
names=sentiment_counts.index,
|
| 54 |
-
title="Sentiment Distribution"
|
| 55 |
-
hover_data=[sentiment_counts.values],
|
| 56 |
-
labels={'value': 'Count', 'names': 'Sentiment'}
|
| 57 |
)
|
| 58 |
-
sentiment_pie.update_traces(textinfo='percent+label', hovertemplate="Sentiment: %{label}<br>Count: %{value}<br>Percentage: %{percent}")
|
| 59 |
|
| 60 |
# Pie Chart of Comment Categories
|
| 61 |
category_counts = df['comment_category'].value_counts()
|
| 62 |
category_pie = px.pie(
|
| 63 |
values=category_counts.values,
|
| 64 |
names=category_counts.index,
|
| 65 |
-
title="Comment Category Distribution"
|
| 66 |
-
hover_data=[category_counts.values],
|
| 67 |
-
labels={'value': 'Count', 'names': 'Category'}
|
| 68 |
)
|
| 69 |
-
category_pie.update_traces(textinfo='percent+label', hovertemplate="Category: %{label}<br>Count: %{value}<br>Percentage: %{percent}")
|
| 70 |
|
| 71 |
# Stacked Bar Chart of Sentiment by Category
|
| 72 |
sentiment_by_category = df.groupby(['comment_category', 'comment_sentiment']).size().unstack()
|
|
@@ -99,44 +123,36 @@ def visualize_output():
|
|
| 99 |
sentiment_by_segment = df.groupby(['customer_segment', 'comment_sentiment']).size().unstack()
|
| 100 |
sentiment_by_segment_pie = px.pie(
|
| 101 |
sentiment_by_segment,
|
| 102 |
-
title="Sentiment by Customer Segment"
|
| 103 |
-
labels={'value': 'Count', 'customer_segment': 'Segment', 'comment_sentiment': 'Sentiment'}
|
| 104 |
)
|
| 105 |
|
| 106 |
return sentiment_pie, category_pie, stacked_bar, kpi_visualization, sentiment_by_segment_pie
|
| 107 |
|
| 108 |
# Gradio Interface
|
| 109 |
with gr.Blocks() as nps:
|
| 110 |
-
# State to store categories
|
| 111 |
categories = gr.State([])
|
| 112 |
|
| 113 |
-
# Function to add a category
|
| 114 |
def add_category(categories, new_category):
|
| 115 |
-
if new_category.strip() != "" and len(categories) < 5:
|
| 116 |
categories.append(new_category.strip())
|
| 117 |
return categories, "", f"**Categories:**\n" + "\n".join([f"- {cat}" for cat in categories])
|
| 118 |
|
| 119 |
-
# Function to reset categories
|
| 120 |
def reset_categories():
|
| 121 |
return [], "**Categories:**\n- None"
|
| 122 |
|
| 123 |
-
# UI for adding categories
|
| 124 |
with gr.Row():
|
| 125 |
category_input = gr.Textbox(label="New Category", placeholder="Enter category name")
|
| 126 |
add_category_btn = gr.Button("Add Category")
|
| 127 |
reset_btn = gr.Button("Reset Categories")
|
| 128 |
category_status = gr.Markdown("**Categories:**\n- None")
|
| 129 |
|
| 130 |
-
# File upload and template buttons
|
| 131 |
uploaded_file = gr.File(label="Upload CSV", type="filepath")
|
| 132 |
template_btn = gr.Button("Use Template")
|
| 133 |
gr.Markdown("# NPS Comment Categorization")
|
| 134 |
|
| 135 |
-
# Classify button
|
| 136 |
classify_btn = gr.Button("Classify Comments")
|
| 137 |
output = gr.HTML()
|
| 138 |
|
| 139 |
-
# Visualize button
|
| 140 |
visualize_btn = gr.Button("Visualize Output")
|
| 141 |
sentiment_pie = gr.Plot(label="Sentiment Distribution")
|
| 142 |
category_pie = gr.Plot(label="Comment Category Distribution")
|
|
@@ -144,56 +160,9 @@ with gr.Blocks() as nps:
|
|
| 144 |
kpi_visualization = gr.Markdown()
|
| 145 |
sentiment_by_segment_pie = gr.Plot(label="Sentiment by Customer Segment")
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
file.seek(0) # Reset file pointer
|
| 152 |
-
if file.name.endswith('.csv'):
|
| 153 |
-
custom_df = pd.read_csv(file, encoding='utf-8')
|
| 154 |
-
else:
|
| 155 |
-
return "Error: Uploaded file is not a CSV."
|
| 156 |
-
# Check for required columns
|
| 157 |
-
required_columns = ['customer_id', 'customer_comment', 'customer_nps', 'customer_segment']
|
| 158 |
-
if not all(col in custom_df.columns for col in required_columns):
|
| 159 |
-
return f"Error: Uploaded CSV must contain the following columns: {', '.join(required_columns)}"
|
| 160 |
-
df = custom_df
|
| 161 |
-
return "Custom CSV loaded successfully!"
|
| 162 |
-
else:
|
| 163 |
-
return "No file uploaded."
|
| 164 |
-
|
| 165 |
-
# Function to use template categories
|
| 166 |
-
def use_template():
|
| 167 |
-
template_categories = ["Product Experience", "Customer Support", "Price of Service", "Other"]
|
| 168 |
-
return template_categories, f"**Categories:**\n" + "\n".join([f"- {cat}" for cat in template_categories])
|
| 169 |
-
|
| 170 |
-
# Event handlers
|
| 171 |
-
add_category_btn.click(
|
| 172 |
-
fn=add_category,
|
| 173 |
-
inputs=[categories, category_input],
|
| 174 |
-
outputs=[categories, category_input, category_status]
|
| 175 |
-
)
|
| 176 |
-
reset_btn.click(
|
| 177 |
-
fn=reset_categories,
|
| 178 |
-
outputs=[categories, category_status]
|
| 179 |
-
)
|
| 180 |
-
uploaded_file.change(
|
| 181 |
-
fn=load_data,
|
| 182 |
-
inputs=uploaded_file,
|
| 183 |
-
outputs=output
|
| 184 |
-
)
|
| 185 |
-
template_btn.click(
|
| 186 |
-
fn=use_template,
|
| 187 |
-
outputs=[categories, category_status]
|
| 188 |
-
)
|
| 189 |
-
classify_btn.click(
|
| 190 |
-
fn=classify_comments,
|
| 191 |
-
inputs=categories,
|
| 192 |
-
outputs=output
|
| 193 |
-
)
|
| 194 |
-
visualize_btn.click(
|
| 195 |
-
fn=visualize_output,
|
| 196 |
-
outputs=[sentiment_pie, category_pie, stacked_bar, kpi_visualization, sentiment_by_segment_pie]
|
| 197 |
-
)
|
| 198 |
|
| 199 |
-
nps.launch(share=True)
|
|
|
|
| 21 |
generator = pipeline("text2text-generation", model="google/flan-t5-base")
|
| 22 |
|
| 23 |
# Function to classify customer comments
|
|
|
|
| 24 |
def classify_comments(categories):
|
| 25 |
global df # Ensure we're modifying the global DataFrame
|
| 26 |
sentiments = []
|
| 27 |
assigned_categories = []
|
| 28 |
+
|
| 29 |
+
# Debugging output
|
| 30 |
+
print("Classifying comments...")
|
| 31 |
+
|
| 32 |
for comment in df['customer_comment']:
|
| 33 |
# Classify sentiment
|
| 34 |
sentiment = classifier(comment)[0]['label']
|
|
|
|
| 38 |
category = generator(prompt, max_length=30)[0]['generated_text']
|
| 39 |
assigned_categories.append(category)
|
| 40 |
sentiments.append(sentiment)
|
| 41 |
+
|
| 42 |
df['comment_sentiment'] = sentiments
|
| 43 |
df['comment_category'] = assigned_categories
|
| 44 |
+
|
| 45 |
+
# Debugging output
|
| 46 |
+
print(df.head())
|
| 47 |
+
print(df['comment_sentiment'].value_counts())
|
| 48 |
+
print(df['comment_category'].value_counts())
|
| 49 |
+
|
| 50 |
return df[['customer_id', 'customer_comment', 'comment_sentiment', 'comment_category', 'customer_nps', 'customer_segment']].to_html(index=False)
|
| 51 |
|
| 52 |
# Function to generate visualizations
|
| 53 |
def visualize_output():
|
| 54 |
+
global df
|
| 55 |
+
|
| 56 |
+
# Check if DataFrame is empty
|
| 57 |
+
if df.empty:
|
| 58 |
+
return None, None, None, "Error: DataFrame is empty. Please check the data or classification step.", None
|
| 59 |
+
|
| 60 |
+
# Check for required columns
|
| 61 |
+
required_columns = ['comment_sentiment', 'comment_category', 'customer_nps', 'customer_segment']
|
| 62 |
+
if not all(col in df.columns for col in required_columns):
|
| 63 |
+
return None, None, None, "Error: Required columns are missing. Please classify comments first.", None
|
| 64 |
+
|
| 65 |
+
# Explicitly convert data types
|
| 66 |
+
df['comment_sentiment'] = df['comment_sentiment'].astype(str)
|
| 67 |
+
df['comment_category'] = df['comment_category'].astype(str)
|
| 68 |
+
df['customer_nps'] = pd.to_numeric(df['customer_nps'], errors='coerce')
|
| 69 |
+
df['customer_segment'] = df['customer_segment'].astype(str)
|
| 70 |
+
|
| 71 |
+
# Drop NaN values
|
| 72 |
+
df = df.dropna(subset=['comment_sentiment', 'comment_category', 'customer_nps', 'customer_segment'])
|
| 73 |
+
|
| 74 |
+
# Debugging output
|
| 75 |
+
print(df.head())
|
| 76 |
+
print(df['comment_sentiment'].value_counts())
|
| 77 |
+
print(df['comment_category'].value_counts())
|
| 78 |
|
| 79 |
# Pie Chart of Sentiment
|
| 80 |
sentiment_counts = df['comment_sentiment'].value_counts()
|
| 81 |
sentiment_pie = px.pie(
|
| 82 |
values=sentiment_counts.values,
|
| 83 |
names=sentiment_counts.index,
|
| 84 |
+
title="Sentiment Distribution"
|
|
|
|
|
|
|
| 85 |
)
|
|
|
|
| 86 |
|
| 87 |
# Pie Chart of Comment Categories
|
| 88 |
category_counts = df['comment_category'].value_counts()
|
| 89 |
category_pie = px.pie(
|
| 90 |
values=category_counts.values,
|
| 91 |
names=category_counts.index,
|
| 92 |
+
title="Comment Category Distribution"
|
|
|
|
|
|
|
| 93 |
)
|
|
|
|
| 94 |
|
| 95 |
# Stacked Bar Chart of Sentiment by Category
|
| 96 |
sentiment_by_category = df.groupby(['comment_category', 'comment_sentiment']).size().unstack()
|
|
|
|
| 123 |
sentiment_by_segment = df.groupby(['customer_segment', 'comment_sentiment']).size().unstack()
|
| 124 |
sentiment_by_segment_pie = px.pie(
|
| 125 |
sentiment_by_segment,
|
| 126 |
+
title="Sentiment by Customer Segment"
|
|
|
|
| 127 |
)
|
| 128 |
|
| 129 |
return sentiment_pie, category_pie, stacked_bar, kpi_visualization, sentiment_by_segment_pie
|
| 130 |
|
| 131 |
# Gradio Interface
|
| 132 |
with gr.Blocks() as nps:
|
|
|
|
| 133 |
categories = gr.State([])
|
| 134 |
|
|
|
|
| 135 |
def add_category(categories, new_category):
|
| 136 |
+
if new_category.strip() != "" and len(categories) < 5:
|
| 137 |
categories.append(new_category.strip())
|
| 138 |
return categories, "", f"**Categories:**\n" + "\n".join([f"- {cat}" for cat in categories])
|
| 139 |
|
|
|
|
| 140 |
def reset_categories():
|
| 141 |
return [], "**Categories:**\n- None"
|
| 142 |
|
|
|
|
| 143 |
with gr.Row():
|
| 144 |
category_input = gr.Textbox(label="New Category", placeholder="Enter category name")
|
| 145 |
add_category_btn = gr.Button("Add Category")
|
| 146 |
reset_btn = gr.Button("Reset Categories")
|
| 147 |
category_status = gr.Markdown("**Categories:**\n- None")
|
| 148 |
|
|
|
|
| 149 |
uploaded_file = gr.File(label="Upload CSV", type="filepath")
|
| 150 |
template_btn = gr.Button("Use Template")
|
| 151 |
gr.Markdown("# NPS Comment Categorization")
|
| 152 |
|
|
|
|
| 153 |
classify_btn = gr.Button("Classify Comments")
|
| 154 |
output = gr.HTML()
|
| 155 |
|
|
|
|
| 156 |
visualize_btn = gr.Button("Visualize Output")
|
| 157 |
sentiment_pie = gr.Plot(label="Sentiment Distribution")
|
| 158 |
category_pie = gr.Plot(label="Comment Category Distribution")
|
|
|
|
| 160 |
kpi_visualization = gr.Markdown()
|
| 161 |
sentiment_by_segment_pie = gr.Plot(label="Sentiment by Customer Segment")
|
| 162 |
|
| 163 |
+
add_category_btn.click(fn=add_category, inputs=[categories, category_input], outputs=[categories, category_input, category_status])
|
| 164 |
+
reset_btn.click(fn=reset_categories, outputs=[categories, category_status])
|
| 165 |
+
classify_btn.click(fn=classify_comments, inputs=categories, outputs=output)
|
| 166 |
+
visualize_btn.click(fn=visualize_output, outputs=[sentiment_pie, category_pie, stacked_bar, kpi_visualization, sentiment_by_segment_pie])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
nps.launch(share=True)
|