Spaces:
Sleeping
Sleeping
Theming and HTML generation
Browse files
app.py
CHANGED
|
@@ -4,6 +4,9 @@ import pandas as pd
|
|
| 4 |
import numpy as np
|
| 5 |
import os
|
| 6 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# Initialize the classification pipelines
|
| 9 |
sentiment_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
|
@@ -22,6 +25,74 @@ CRITICAL_KEYWORDS = {
|
|
| 22 |
'sensitive': ['racist', 'discrimination', 'harassment', 'abuse', 'offensive']
|
| 23 |
}
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
def classify_text(text, labels, classifier):
|
| 26 |
"""
|
| 27 |
Perform zero-shot classification on text
|
|
@@ -73,22 +144,22 @@ def generate_recommendations(row):
|
|
| 73 |
recommendations = []
|
| 74 |
|
| 75 |
if row['urgency'] == 'critical':
|
| 76 |
-
recommendations.append("
|
| 77 |
|
| 78 |
if 'security' in row['critical_issues']:
|
| 79 |
-
recommendations.append("Engage security team for immediate investigation")
|
| 80 |
elif 'fraud' in row['critical_issues']:
|
| 81 |
-
recommendations.append("Route to fraud prevention team for investigation")
|
| 82 |
elif 'compliance' in row['critical_issues']:
|
| 83 |
-
recommendations.append("Escalate to legal/compliance team for review")
|
| 84 |
|
| 85 |
if row['brand_impact'] == 'severe':
|
| 86 |
-
recommendations.append("Engage PR team for reputation management strategy")
|
| 87 |
|
| 88 |
if row['sentiment'] == 'negative':
|
| 89 |
-
recommendations.append("Priority customer outreach needed for resolution")
|
| 90 |
|
| 91 |
-
return ' | '.join(recommendations) if recommendations else "Standard response protocol"
|
| 92 |
|
| 93 |
def process_csv(file):
|
| 94 |
"""
|
|
@@ -100,7 +171,7 @@ def process_csv(file):
|
|
| 100 |
|
| 101 |
# Verify required columns
|
| 102 |
if 'post_id' not in df.columns or 'text' not in df.columns:
|
| 103 |
-
return None, "Error: CSV must contain 'post_id' and 'text' columns"
|
| 104 |
|
| 105 |
# Perform comprehensive analysis
|
| 106 |
analysis_results = []
|
|
@@ -135,6 +206,9 @@ def process_csv(file):
|
|
| 135 |
# Generate recommendations
|
| 136 |
results_df['recommendations'] = results_df.apply(generate_recommendations, axis=1)
|
| 137 |
|
|
|
|
|
|
|
|
|
|
| 138 |
# Add analysis timestamp
|
| 139 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 140 |
output_file = f"social_media_analysis_{timestamp}.csv"
|
|
@@ -149,34 +223,51 @@ def process_csv(file):
|
|
| 149 |
severe_impact = len(results_df[results_df['brand_impact'] == 'severe'])
|
| 150 |
|
| 151 |
summary = f"""
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
| 154 |
Total Posts Analyzed: {total_posts}
|
| 155 |
Critical Issues Requiring Immediate Attention: {critical_posts}
|
| 156 |
Negative Sentiment Posts: {negative_sentiment}
|
| 157 |
Severe Brand Impact Posts: {severe_impact}
|
| 158 |
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
"""
|
| 161 |
|
| 162 |
-
return output_file, summary
|
| 163 |
|
| 164 |
except Exception as e:
|
| 165 |
-
return None, f"Error processing CSV: {str(e)}"
|
| 166 |
|
| 167 |
-
# Create example CSV file
|
| 168 |
def create_example_file():
|
| 169 |
"""
|
| 170 |
Create an example CSV file for demonstration
|
| 171 |
"""
|
| 172 |
example_data = {
|
| 173 |
-
'post_id': range(1,
|
| 174 |
'text': [
|
| 175 |
-
"
|
| 176 |
-
"
|
| 177 |
-
"
|
| 178 |
-
"
|
| 179 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
]
|
| 181 |
}
|
| 182 |
df = pd.DataFrame(example_data)
|
|
@@ -184,38 +275,54 @@ def create_example_file():
|
|
| 184 |
df.to_csv(example_file, index=False)
|
| 185 |
return example_file
|
| 186 |
|
| 187 |
-
# Create the example file
|
| 188 |
example_file = create_example_file()
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
# Create Gradio interface
|
| 191 |
iface = gr.Interface(
|
| 192 |
fn=process_csv,
|
| 193 |
inputs=[
|
| 194 |
gr.File(
|
| 195 |
-
label="Upload CSV
|
| 196 |
file_types=[".csv"]
|
| 197 |
)
|
| 198 |
],
|
| 199 |
outputs=[
|
| 200 |
-
gr.File(label="Download Detailed Analysis"),
|
| 201 |
-
gr.
|
|
|
|
| 202 |
],
|
| 203 |
-
title="
|
| 204 |
description="""
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
-
|
| 208 |
-
|
| 209 |
-
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
-
|
| 214 |
-
|
|
|
|
| 215 |
""",
|
| 216 |
examples=[
|
| 217 |
[example_file]
|
| 218 |
-
]
|
|
|
|
|
|
|
| 219 |
)
|
| 220 |
|
| 221 |
if __name__ == "__main__":
|
|
@@ -223,4 +330,4 @@ if __name__ == "__main__":
|
|
| 223 |
iface.launch()
|
| 224 |
finally:
|
| 225 |
if os.path.exists(example_file):
|
| 226 |
-
os.remove(example_file)
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
import os
|
| 6 |
from datetime import datetime
|
| 7 |
+
import plotly.express as px
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
from plotly.subplots import make_subplots
|
| 10 |
|
| 11 |
# Initialize the classification pipelines
|
| 12 |
sentiment_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
|
|
|
| 25 |
'sensitive': ['racist', 'discrimination', 'harassment', 'abuse', 'offensive']
|
| 26 |
}
|
| 27 |
|
| 28 |
+
def create_charts(df):
|
| 29 |
+
"""
|
| 30 |
+
Create visualization charts using Plotly
|
| 31 |
+
"""
|
| 32 |
+
# Create subplot figure
|
| 33 |
+
fig = make_subplots(
|
| 34 |
+
rows=2, cols=2,
|
| 35 |
+
subplot_titles=("Urgency Distribution", "Sentiment Analysis",
|
| 36 |
+
"Brand Impact Assessment", "Critical Issues Breakdown"),
|
| 37 |
+
specs=[[{"type": "pie"}, {"type": "pie"}],
|
| 38 |
+
[{"type": "pie"}, {"type": "bar"}]]
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# 1. Urgency Distribution Pie Chart
|
| 42 |
+
urgency_counts = df['urgency'].value_counts()
|
| 43 |
+
fig.add_trace(
|
| 44 |
+
go.Pie(labels=urgency_counts.index,
|
| 45 |
+
values=urgency_counts.values,
|
| 46 |
+
marker=dict(colors=['#ff0000', '#ff6666', '#ffcccc', '#ffe6e6'])),
|
| 47 |
+
row=1, col=1
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# 2. Sentiment Analysis Pie Chart
|
| 51 |
+
sentiment_counts = df['sentiment'].value_counts()
|
| 52 |
+
fig.add_trace(
|
| 53 |
+
go.Pie(labels=sentiment_counts.index,
|
| 54 |
+
values=sentiment_counts.values,
|
| 55 |
+
marker=dict(colors=['#00cc00', '#ff0000', '#cccccc'])),
|
| 56 |
+
row=1, col=2
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# 3. Brand Impact Pie Chart
|
| 60 |
+
impact_counts = df['brand_impact'].value_counts()
|
| 61 |
+
fig.add_trace(
|
| 62 |
+
go.Pie(labels=impact_counts.index,
|
| 63 |
+
values=impact_counts.values,
|
| 64 |
+
marker=dict(colors=['#ff0000', '#ff9933', '#ffcc00'])),
|
| 65 |
+
row=2, col=1
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# 4. Critical Issues Bar Chart
|
| 69 |
+
critical_issues = df['critical_issues'].str.split('|', expand=True).stack()
|
| 70 |
+
critical_counts = critical_issues[critical_issues != 'none'].value_counts()
|
| 71 |
+
fig.add_trace(
|
| 72 |
+
go.Bar(x=critical_counts.index,
|
| 73 |
+
y=critical_counts.values,
|
| 74 |
+
marker_color='#ff0000'),
|
| 75 |
+
row=2, col=2
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# Update layout
|
| 79 |
+
fig.update_layout(
|
| 80 |
+
height=800,
|
| 81 |
+
showlegend=True,
|
| 82 |
+
title_text="Social Media Analysis Dashboard",
|
| 83 |
+
title_x=0.5,
|
| 84 |
+
title_font_size=20,
|
| 85 |
+
paper_bgcolor='rgba(0,0,0,0)',
|
| 86 |
+
plot_bgcolor='rgba(0,0,0,0)'
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Save the figure
|
| 90 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 91 |
+
chart_file = f"analysis_dashboard_{timestamp}.html"
|
| 92 |
+
fig.write_html(chart_file)
|
| 93 |
+
|
| 94 |
+
return chart_file
|
| 95 |
+
|
| 96 |
def classify_text(text, labels, classifier):
|
| 97 |
"""
|
| 98 |
Perform zero-shot classification on text
|
|
|
|
| 144 |
recommendations = []
|
| 145 |
|
| 146 |
if row['urgency'] == 'critical':
|
| 147 |
+
recommendations.append("π¨ IMMEDIATE ESCALATION REQUIRED - Route to crisis management team")
|
| 148 |
|
| 149 |
if 'security' in row['critical_issues']:
|
| 150 |
+
recommendations.append("π Engage security team for immediate investigation")
|
| 151 |
elif 'fraud' in row['critical_issues']:
|
| 152 |
+
recommendations.append("β οΈ Route to fraud prevention team for investigation")
|
| 153 |
elif 'compliance' in row['critical_issues']:
|
| 154 |
+
recommendations.append("π Escalate to legal/compliance team for review")
|
| 155 |
|
| 156 |
if row['brand_impact'] == 'severe':
|
| 157 |
+
recommendations.append("π’ Engage PR team for reputation management strategy")
|
| 158 |
|
| 159 |
if row['sentiment'] == 'negative':
|
| 160 |
+
recommendations.append("π₯ Priority customer outreach needed for resolution")
|
| 161 |
|
| 162 |
+
return ' | '.join(recommendations) if recommendations else "β
Standard response protocol"
|
| 163 |
|
| 164 |
def process_csv(file):
|
| 165 |
"""
|
|
|
|
| 171 |
|
| 172 |
# Verify required columns
|
| 173 |
if 'post_id' not in df.columns or 'text' not in df.columns:
|
| 174 |
+
return None, None, "Error: CSV must contain 'post_id' and 'text' columns"
|
| 175 |
|
| 176 |
# Perform comprehensive analysis
|
| 177 |
analysis_results = []
|
|
|
|
| 206 |
# Generate recommendations
|
| 207 |
results_df['recommendations'] = results_df.apply(generate_recommendations, axis=1)
|
| 208 |
|
| 209 |
+
# Create visualization dashboard
|
| 210 |
+
dashboard_file = create_charts(results_df)
|
| 211 |
+
|
| 212 |
# Add analysis timestamp
|
| 213 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 214 |
output_file = f"social_media_analysis_{timestamp}.csv"
|
|
|
|
| 223 |
severe_impact = len(results_df[results_df['brand_impact'] == 'severe'])
|
| 224 |
|
| 225 |
summary = f"""
|
| 226 |
+
π― Real-Time Social Media Intelligence Report
|
| 227 |
+
==========================================
|
| 228 |
+
|
| 229 |
+
π Key Metrics:
|
| 230 |
+
-------------
|
| 231 |
Total Posts Analyzed: {total_posts}
|
| 232 |
Critical Issues Requiring Immediate Attention: {critical_posts}
|
| 233 |
Negative Sentiment Posts: {negative_sentiment}
|
| 234 |
Severe Brand Impact Posts: {severe_impact}
|
| 235 |
|
| 236 |
+
β‘ Quick Actions Required:
|
| 237 |
+
----------------------
|
| 238 |
+
- {critical_posts} posts need immediate escalation
|
| 239 |
+
- {severe_impact} posts require PR team intervention
|
| 240 |
+
- {negative_sentiment} posts need customer satisfaction follow-up
|
| 241 |
+
|
| 242 |
+
π‘ AI-Powered Analysis Complete:
|
| 243 |
+
----------------------------
|
| 244 |
+
Detailed analysis saved to: {output_file}
|
| 245 |
+
Interactive dashboard saved to: {dashboard_file}
|
| 246 |
"""
|
| 247 |
|
| 248 |
+
return output_file, dashboard_file, summary
|
| 249 |
|
| 250 |
except Exception as e:
|
| 251 |
+
return None, None, f"Error processing CSV: {str(e)}"
|
| 252 |
|
| 253 |
+
# Create example CSV file with more diverse cases
|
| 254 |
def create_example_file():
|
| 255 |
"""
|
| 256 |
Create an example CSV file for demonstration
|
| 257 |
"""
|
| 258 |
example_data = {
|
| 259 |
+
'post_id': range(1, 11),
|
| 260 |
'text': [
|
| 261 |
+
"Just experienced a major security breach! My account was hacked and sensitive data leaked. This is unacceptable! #cybersecurity #breach",
|
| 262 |
+
"Thank you for the amazing customer service! The team went above and beyond to help me. Truly impressed! π",
|
| 263 |
+
"Your latest app update is constantly crashing. Can't access my account for 3 days now. Fix this ASAP!",
|
| 264 |
+
"Noticed some suspicious charges on my account. Possible fraud? Need immediate assistance! π¨",
|
| 265 |
+
"Love the new features you've added! Makes my work so much easier. Keep innovating! π",
|
| 266 |
+
"Planning to file a legal complaint due to repeated policy violations. This needs attention.",
|
| 267 |
+
"System down again? This is the third time this week. Considering switching to your competitor.",
|
| 268 |
+
"Your product has completely transformed our business operations. Best investment ever! π",
|
| 269 |
+
"Experiencing discrimination from your staff. This is unacceptable and I'm reporting it.",
|
| 270 |
+
"Warning to others: Potential scam detected in recent transactions. Be careful!"
|
| 271 |
]
|
| 272 |
}
|
| 273 |
df = pd.DataFrame(example_data)
|
|
|
|
| 275 |
df.to_csv(example_file, index=False)
|
| 276 |
return example_file
|
| 277 |
|
| 278 |
+
# Create the example file
|
| 279 |
example_file = create_example_file()
|
| 280 |
|
| 281 |
+
# Create Gradio interface with custom theme
|
| 282 |
+
theme = gr.themes.Base(
|
| 283 |
+
primary_hue="red",
|
| 284 |
+
secondary_hue="red",
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
css = """
|
| 288 |
+
.gradio-container {
|
| 289 |
+
background: linear-gradient(to bottom right, #ffffff, #ffecec);
|
| 290 |
+
}
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
# Create Gradio interface
|
| 294 |
iface = gr.Interface(
|
| 295 |
fn=process_csv,
|
| 296 |
inputs=[
|
| 297 |
gr.File(
|
| 298 |
+
label="Upload CSV File π",
|
| 299 |
file_types=[".csv"]
|
| 300 |
)
|
| 301 |
],
|
| 302 |
outputs=[
|
| 303 |
+
gr.File(label="Download Detailed Analysis Report π"),
|
| 304 |
+
gr.File(label="Download Interactive Dashboard π"),
|
| 305 |
+
gr.Textbox(label="Real-Time Analysis Summary π±", max_lines=15)
|
| 306 |
],
|
| 307 |
+
title="π NoCode Ninjas: AI-Powered Social Media Intelligence Platform",
|
| 308 |
description="""
|
| 309 |
+
### Enterprise-Grade Social Media Analytics with Advanced AI
|
| 310 |
+
|
| 311 |
+
Transform your social media monitoring with our cutting-edge AI analysis platform:
|
| 312 |
+
|
| 313 |
+
π― **Real-Time Sentiment Analysis**
|
| 314 |
+
π **Urgent Issue Detection**
|
| 315 |
+
β‘ **Instant Crisis Alerts**
|
| 316 |
+
π **Brand Impact Assessment**
|
| 317 |
+
π€ **AI-Driven Recommendations**
|
| 318 |
+
|
| 319 |
+
*Trusted by leading brands for proactive social media management and crisis prevention.*
|
| 320 |
""",
|
| 321 |
examples=[
|
| 322 |
[example_file]
|
| 323 |
+
],
|
| 324 |
+
theme=theme,
|
| 325 |
+
css=css
|
| 326 |
)
|
| 327 |
|
| 328 |
if __name__ == "__main__":
|
|
|
|
| 330 |
iface.launch()
|
| 331 |
finally:
|
| 332 |
if os.path.exists(example_file):
|
| 333 |
+
os.remove(example_file)
|