Spaces:
Sleeping
Sleeping
Added urgency, brand impact and issue categories
Browse files- app.py +159 -37
- requirements.txt +4 -1
app.py
CHANGED
|
@@ -1,60 +1,182 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import pipeline
|
| 3 |
import pandas as pd
|
| 4 |
-
import
|
| 5 |
-
import csv
|
| 6 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
def
|
| 15 |
"""
|
| 16 |
-
|
| 17 |
"""
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def process_csv(file):
|
| 24 |
"""
|
| 25 |
-
Process posts from CSV file
|
| 26 |
"""
|
| 27 |
try:
|
| 28 |
# Read the input CSV file
|
| 29 |
df = pd.read_csv(file.name)
|
| 30 |
|
| 31 |
-
# Verify required columns
|
| 32 |
if 'post_id' not in df.columns or 'text' not in df.columns:
|
| 33 |
return None, "Error: CSV must contain 'post_id' and 'text' columns"
|
| 34 |
|
| 35 |
-
#
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
df.to_csv(output_file, index=False)
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
except Exception as e:
|
| 45 |
-
return None, f"Error processing CSV: {str(e)}"
|
| 46 |
|
| 47 |
-
#
|
| 48 |
def create_example_file():
|
| 49 |
"""
|
| 50 |
Create an example CSV file for demonstration
|
| 51 |
"""
|
| 52 |
example_data = {
|
| 53 |
-
'post_id':
|
| 54 |
'text': [
|
| 55 |
-
"I absolutely love
|
| 56 |
-
"
|
| 57 |
-
"
|
|
|
|
|
|
|
| 58 |
]
|
| 59 |
}
|
| 60 |
df = pd.DataFrame(example_data)
|
|
@@ -75,29 +197,29 @@ iface = gr.Interface(
|
|
| 75 |
)
|
| 76 |
],
|
| 77 |
outputs=[
|
| 78 |
-
gr.File(label="Download
|
| 79 |
-
gr.Textbox(label="
|
| 80 |
],
|
| 81 |
-
title="Social Media
|
| 82 |
description="""
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
Input CSV format:
|
| 86 |
- Required columns: 'post_id', 'text'
|
| 87 |
- Each row should contain a unique post ID and the post text
|
| 88 |
-
|
| 89 |
-
Output CSV will contain:
|
| 90 |
-
- post_id: Original post ID
|
| 91 |
-
- text: Original post text
|
| 92 |
-
- sentiment: Analyzed sentiment (positive/negative/neutral)
|
| 93 |
""",
|
| 94 |
examples=[
|
| 95 |
-
[example_file]
|
| 96 |
]
|
| 97 |
)
|
| 98 |
|
| 99 |
if __name__ == "__main__":
|
| 100 |
-
# Clean up example file when the program exits
|
| 101 |
try:
|
| 102 |
iface.launch()
|
| 103 |
finally:
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import pipeline
|
| 3 |
import pandas as pd
|
| 4 |
+
import numpy as np
|
|
|
|
| 5 |
import os
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import plotly.graph_objects as go
|
| 8 |
+
from plotly.subplots import make_subplots
|
| 9 |
+
import base64
|
| 10 |
+
import io
|
| 11 |
+
|
| 12 |
+
# [Previous imports and constants remain the same]
|
| 13 |
+
# Initialize the classification pipelines
|
| 14 |
+
sentiment_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
| 15 |
|
| 16 |
+
# Define various classification labels
|
| 17 |
+
SENTIMENT_LABELS = ["positive", "negative", "neutral"]
|
| 18 |
+
URGENCY_LABELS = ["critical", "high", "medium", "low"]
|
| 19 |
+
BRAND_IMPACT_LABELS = ["severe", "moderate", "minimal"]
|
| 20 |
+
ISSUE_CATEGORIES = ["product", "service", "security", "fraud", "compliance", "technical", "billing", "general"]
|
| 21 |
|
| 22 |
+
# [Previous keyword definitions and helper functions remain the same]
|
| 23 |
+
CRITICAL_KEYWORDS = {
|
| 24 |
+
'security': ['hack', 'breach', 'leaked', 'stolen', 'unauthorized', 'privacy'],
|
| 25 |
+
'fraud': ['scam', 'fraud', 'fake', 'unauthorized charge', 'stolen'],
|
| 26 |
+
'compliance': ['lawsuit', 'legal', 'regulation', 'complaint', 'policy violation'],
|
| 27 |
+
'sensitive': ['racist', 'discrimination', 'harassment', 'abuse', 'offensive']
|
| 28 |
+
}
|
| 29 |
|
| 30 |
+
def create_pie_charts(df):
|
| 31 |
"""
|
| 32 |
+
Create pie charts for Urgency, Brand Impact, and Critical Issues
|
| 33 |
"""
|
| 34 |
+
# Create a figure with subplots
|
| 35 |
+
fig = make_subplots(
|
| 36 |
+
rows=1, cols=3,
|
| 37 |
+
subplot_titles=('Urgency Distribution', 'Brand Impact Distribution', 'Critical Issues Distribution'),
|
| 38 |
+
specs=[[{'type':'pie'}, {'type':'pie'}, {'type':'pie'}]]
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Urgency Pie Chart
|
| 42 |
+
urgency_counts = df['urgency'].value_counts()
|
| 43 |
+
fig.add_trace(
|
| 44 |
+
go.Pie(labels=urgency_counts.index, values=urgency_counts.values,
|
| 45 |
+
marker_colors=['#FF0000', '#FFA500', '#FFFF00', '#90EE90']),
|
| 46 |
+
row=1, col=1
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Brand Impact Pie Chart
|
| 50 |
+
# impact_counts = df['brand_impact'].value_counts()
|
| 51 |
+
# fig.add_trace(
|
| 52 |
+
# go.Pie(labels=impact_counts.index, values=impact_counts.values,
|
| 53 |
+
# marker_colors=['#FF0000', '#FFA500', '#90EE90']),
|
| 54 |
+
# row=1, col=2
|
| 55 |
+
# )
|
| 56 |
+
|
| 57 |
+
# Critical Issues Pie Chart
|
| 58 |
+
# Split the combined issues and count unique occurrences
|
| 59 |
+
all_issues = df[df['critical_issues'] != 'none']['critical_issues'].str.split('|').explode()
|
| 60 |
+
# if len(all_issues) == 0:
|
| 61 |
+
# issue_counts = pd.Series({'No Critical Issues': 1})
|
| 62 |
+
# else:
|
| 63 |
+
# issue_counts = all_issues.value_counts()
|
| 64 |
+
|
| 65 |
+
# fig.add_trace(
|
| 66 |
+
# go.Pie(labels=issue_counts.index, values=issue_counts.values,
|
| 67 |
+
# marker_colors=['#FF0000', '#FFA500', '#FFFF00', '#90EE90', '#4169E1']),
|
| 68 |
+
# row=1, col=3
|
| 69 |
+
# )
|
| 70 |
+
|
| 71 |
+
# Update layout
|
| 72 |
+
fig.update_layout(
|
| 73 |
+
height=400,
|
| 74 |
+
width=1200,
|
| 75 |
+
showlegend=True,
|
| 76 |
+
title_text="Analysis Distribution",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# Save the plot to a bytes buffer
|
| 80 |
+
buf = io.BytesIO()
|
| 81 |
+
fig.write_image(buf, format='png')
|
| 82 |
+
buf.seek(0)
|
| 83 |
+
|
| 84 |
+
return buf
|
| 85 |
|
| 86 |
def process_csv(file):
|
| 87 |
"""
|
| 88 |
+
Process posts from CSV file with enhanced analysis and visualizations
|
| 89 |
"""
|
| 90 |
try:
|
| 91 |
# Read the input CSV file
|
| 92 |
df = pd.read_csv(file.name)
|
| 93 |
|
| 94 |
+
# Verify required columns
|
| 95 |
if 'post_id' not in df.columns or 'text' not in df.columns:
|
| 96 |
return None, "Error: CSV must contain 'post_id' and 'text' columns"
|
| 97 |
|
| 98 |
+
# Perform comprehensive analysis
|
| 99 |
+
analysis_results = []
|
| 100 |
+
|
| 101 |
+
for _, row in df.iterrows():
|
| 102 |
+
text = row['text']
|
| 103 |
+
|
| 104 |
+
# Basic sentiment analysis
|
| 105 |
+
sentiment, sentiment_score = classify_text(text, SENTIMENT_LABELS, sentiment_classifier)
|
| 106 |
|
| 107 |
+
# Detect critical issues
|
| 108 |
+
critical_issues = detect_critical_issues(text)
|
|
|
|
| 109 |
|
| 110 |
+
# Determine urgency and brand impact
|
| 111 |
+
urgency = determine_urgency(text, sentiment, critical_issues)
|
| 112 |
+
brand_impact = analyze_brand_impact(text, sentiment, critical_issues)
|
| 113 |
+
|
| 114 |
+
# Store results
|
| 115 |
+
analysis_results.append({
|
| 116 |
+
'post_id': row['post_id'],
|
| 117 |
+
'text': text,
|
| 118 |
+
'sentiment': sentiment,
|
| 119 |
+
'sentiment_confidence': round(sentiment_score, 3),
|
| 120 |
+
'urgency': urgency,
|
| 121 |
+
'brand_impact': brand_impact,
|
| 122 |
+
'critical_issues': '|'.join(critical_issues) if critical_issues else 'none',
|
| 123 |
+
})
|
| 124 |
+
|
| 125 |
+
# Create results DataFrame
|
| 126 |
+
results_df = pd.DataFrame(analysis_results)
|
| 127 |
+
|
| 128 |
+
# Generate recommendations
|
| 129 |
+
results_df['recommendations'] = results_df.apply(generate_recommendations, axis=1)
|
| 130 |
+
|
| 131 |
+
# Add analysis timestamp
|
| 132 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 133 |
+
output_file = f"social_media_analysis_{timestamp}.csv"
|
| 134 |
+
|
| 135 |
+
# Save results
|
| 136 |
+
results_df.to_csv(output_file, index=False)
|
| 137 |
+
|
| 138 |
+
# Generate pie charts
|
| 139 |
+
charts_buf = create_pie_charts(results_df)
|
| 140 |
+
charts_file = f"analysis_charts_{timestamp}.png"
|
| 141 |
+
with open(charts_file, 'wb') as f:
|
| 142 |
+
f.write(charts_buf.getvalue())
|
| 143 |
+
|
| 144 |
+
# Generate summary statistics
|
| 145 |
+
total_posts = len(results_df)
|
| 146 |
+
critical_posts = len(results_df[results_df['urgency'] == 'critical'])
|
| 147 |
+
negative_sentiment = len(results_df[results_df['sentiment'] == 'negative'])
|
| 148 |
+
severe_impact = len(results_df[results_df['brand_impact'] == 'severe'])
|
| 149 |
+
|
| 150 |
+
summary = f"""
|
| 151 |
+
Analysis Summary:
|
| 152 |
+
----------------
|
| 153 |
+
Total Posts Analyzed: {total_posts}
|
| 154 |
+
Critical Issues Requiring Immediate Attention: {critical_posts}
|
| 155 |
+
Negative Sentiment Posts: {negative_sentiment}
|
| 156 |
+
Severe Brand Impact Posts: {severe_impact}
|
| 157 |
+
|
| 158 |
+
The detailed analysis has been saved to: {output_file}
|
| 159 |
+
Charts have been saved to: {charts_file}
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
return [output_file, charts_file], summary
|
| 163 |
|
| 164 |
except Exception as e:
|
| 165 |
+
return [None, None], f"Error processing CSV: {str(e)}"
|
| 166 |
|
| 167 |
+
# [Previous example file creation function remains the same]
|
| 168 |
def create_example_file():
|
| 169 |
"""
|
| 170 |
Create an example CSV file for demonstration
|
| 171 |
"""
|
| 172 |
example_data = {
|
| 173 |
+
'post_id': range(1, 6),
|
| 174 |
'text': [
|
| 175 |
+
"I absolutely love your product! Best purchase ever!",
|
| 176 |
+
"My account appears to have been hacked and unauthorized charges made. Need immediate assistance!",
|
| 177 |
+
"This service is terrible, never using it again. Going to share my experience on social media.",
|
| 178 |
+
"Your app is constantly crashing. Please fix this issue.",
|
| 179 |
+
"Concerned about potential compliance violations in your recent policy update."
|
| 180 |
]
|
| 181 |
}
|
| 182 |
df = pd.DataFrame(example_data)
|
|
|
|
| 197 |
)
|
| 198 |
],
|
| 199 |
outputs=[
|
| 200 |
+
gr.File(label="Download Analysis Files", file_count="multiple"),
|
| 201 |
+
gr.Textbox(label="Analysis Summary", max_lines=10)
|
| 202 |
],
|
| 203 |
+
title="Enhanced Social Media Analysis System",
|
| 204 |
description="""
|
| 205 |
+
Comprehensive social media post analyzer that provides:
|
| 206 |
+
- Sentiment Analysis
|
| 207 |
+
- Urgency Classification
|
| 208 |
+
- Brand Impact Assessment
|
| 209 |
+
- Critical Issue Detection
|
| 210 |
+
- Actionable Recommendations
|
| 211 |
+
- Visual Analytics
|
| 212 |
|
| 213 |
Input CSV format:
|
| 214 |
- Required columns: 'post_id', 'text'
|
| 215 |
- Each row should contain a unique post ID and the post text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
""",
|
| 217 |
examples=[
|
| 218 |
+
[example_file]
|
| 219 |
]
|
| 220 |
)
|
| 221 |
|
| 222 |
if __name__ == "__main__":
|
|
|
|
| 223 |
try:
|
| 224 |
iface.launch()
|
| 225 |
finally:
|
requirements.txt
CHANGED
|
@@ -1,5 +1,8 @@
|
|
| 1 |
-
transformers>=4.46.2
|
| 2 |
gradio>=5.5.0
|
|
|
|
|
|
|
| 3 |
pandas>=2.2.3
|
|
|
|
|
|
|
| 4 |
tensorflow
|
| 5 |
tf-keras
|
|
|
|
|
|
|
| 1 |
gradio>=5.5.0
|
| 2 |
+
transformers>=4.46.2
|
| 3 |
+
torch
|
| 4 |
pandas>=2.2.3
|
| 5 |
+
plotly
|
| 6 |
+
kaleido
|
| 7 |
tensorflow
|
| 8 |
tf-keras
|