File size: 12,449 Bytes
9858829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
"""
Distribution visualization components using Plotly
Creates charts for intent, language, and other distributions
"""
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
import json
from pathlib import Path


class DistributionCharts:
    """
    Creates distribution visualizations
    """

    def __init__(self, config_path=None):
        """
        Initialize with configuration

        Args:
            config_path: Path to configuration file
        """
        if config_path is None:
            config_path = Path(__file__).parent.parent / "config" / "viz_config.json"

        with open(config_path, 'r') as f:
            self.config = json.load(f)

        self.intent_colors = self.config['color_schemes']['intent']
        self.platform_colors = self.config['color_schemes']['platform']
        self.brand_colors = self.config['color_schemes']['brand']
        self.intent_order = self.config['intent_order']
        self.chart_height = self.config['dashboard']['chart_height']

    def create_intent_bar_chart(self, df, title="Intent Distribution", orientation='h'):
        """
        Create horizontal bar chart for intent distribution (handles multi-label)

        Args:
            df: Sentiment dataframe
            title: Chart title
            orientation: 'h' for horizontal, 'v' for vertical

        Returns:
            plotly.graph_objects.Figure
        """
        # Explode intents
        df_exploded = df.copy()
        df_exploded['intent'] = df_exploded['intent'].str.split(',')
        df_exploded = df_exploded.explode('intent')
        df_exploded['intent'] = df_exploded['intent'].str.strip()

        # Count intents
        intent_counts = df_exploded['intent'].value_counts()

        # Order by intent_order
        ordered_intents = [i for i in self.intent_order if i in intent_counts.index]
        intent_counts = intent_counts[ordered_intents]

        colors = [self.intent_colors.get(i, '#CCCCCC') for i in intent_counts.index]

        if orientation == 'h':
            fig = go.Figure(data=[go.Bar(
                y=intent_counts.index,
                x=intent_counts.values,
                orientation='h',
                marker=dict(color=colors),
                text=intent_counts.values,
                textposition='auto',
                hovertemplate='<b>%{y}</b><br>Count: %{x}<extra></extra>'
            )])

            fig.update_layout(
                title=title,
                xaxis_title="Number of Comments",
                yaxis_title="Intent",
                height=self.chart_height,
                yaxis={'categoryorder': 'total ascending'}
            )
        else:
            fig = go.Figure(data=[go.Bar(
                x=intent_counts.index,
                y=intent_counts.values,
                marker=dict(color=colors),
                text=intent_counts.values,
                textposition='auto',
                hovertemplate='<b>%{x}</b><br>Count: %{y}<extra></extra>'
            )])

            fig.update_layout(
                title=title,
                xaxis_title="Intent",
                yaxis_title="Number of Comments",
                height=self.chart_height
            )

        return fig

    def create_intent_pie_chart(self, df, title="Intent Distribution"):
        """
        Create pie chart for intent distribution

        Args:
            df: Sentiment dataframe
            title: Chart title

        Returns:
            plotly.graph_objects.Figure
        """
        # Explode intents
        df_exploded = df.copy()
        df_exploded['intent'] = df_exploded['intent'].str.split(',')
        df_exploded = df_exploded.explode('intent')
        df_exploded['intent'] = df_exploded['intent'].str.strip()

        intent_counts = df_exploded['intent'].value_counts()

        # Order by intent_order
        ordered_intents = [i for i in self.intent_order if i in intent_counts.index]
        intent_counts = intent_counts[ordered_intents]

        colors = [self.intent_colors.get(i, '#CCCCCC') for i in intent_counts.index]

        fig = go.Figure(data=[go.Pie(
            labels=intent_counts.index,
            values=intent_counts.values,
            marker=dict(colors=colors),
            textinfo='label+percent',
            textposition='auto',
            hovertemplate='<b>%{label}</b><br>Count: %{value}<br>Percentage: %{percent}<extra></extra>'
        )])

        fig.update_layout(
            title=title,
            height=self.chart_height,
            showlegend=True,
            legend=dict(orientation="v", yanchor="middle", y=0.5, xanchor="left", x=1.05)
        )

        return fig

    def create_platform_distribution(self, df, title="Comments by Platform"):
        """
        Create bar chart for platform distribution

        Args:
            df: Sentiment dataframe
            title: Chart title

        Returns:
            plotly.graph_objects.Figure
        """
        platform_counts = df['platform'].value_counts()

        colors = [self.platform_colors.get(p, self.platform_colors['default']) for p in platform_counts.index]

        fig = go.Figure(data=[go.Bar(
            x=platform_counts.index,
            y=platform_counts.values,
            marker=dict(color=colors),
            text=platform_counts.values,
            textposition='auto',
            hovertemplate='<b>%{x}</b><br>Comments: %{y}<extra></extra>'
        )])

        fig.update_layout(
            title=title,
            xaxis_title="Platform",
            yaxis_title="Number of Comments",
            height=self.chart_height
        )

        return fig

    def create_brand_distribution(self, df, title="Comments by Brand"):
        """
        Create bar chart for brand distribution

        Args:
            df: Sentiment dataframe
            title: Chart title

        Returns:
            plotly.graph_objects.Figure
        """
        brand_counts = df['brand'].value_counts()

        colors = [self.brand_colors.get(b, self.brand_colors['default']) for b in brand_counts.index]

        fig = go.Figure(data=[go.Bar(
            x=brand_counts.index,
            y=brand_counts.values,
            marker=dict(color=colors),
            text=brand_counts.values,
            textposition='auto',
            hovertemplate='<b>%{x}</b><br>Comments: %{y}<extra></extra>'
        )])

        fig.update_layout(
            title=title,
            xaxis_title="Brand",
            yaxis_title="Number of Comments",
            height=self.chart_height
        )

        return fig

    def create_language_distribution(self, df, top_n=10, title="Language Distribution"):
        """
        Create bar chart for language distribution

        Args:
            df: Sentiment dataframe
            top_n: Number of top languages to show
            title: Chart title

        Returns:
            plotly.graph_objects.Figure
        """
        if 'detected_language' not in df.columns:
            return go.Figure().add_annotation(
                text="No language data available",
                xref="paper", yref="paper",
                x=0.5, y=0.5, showarrow=False
            )

        lang_counts = df['detected_language'].value_counts().head(top_n)

        fig = go.Figure(data=[go.Bar(
            x=lang_counts.index,
            y=lang_counts.values,
            marker=dict(color='#2196F3'),
            text=lang_counts.values,
            textposition='auto',
            hovertemplate='<b>%{x}</b><br>Comments: %{y}<extra></extra>'
        )])

        fig.update_layout(
            title=title,
            xaxis_title="Language",
            yaxis_title="Number of Comments",
            height=self.chart_height
        )

        return fig

    def create_combined_distribution_sunburst(self, df, title="Hierarchical Distribution"):
        """
        Create sunburst chart showing hierarchical distribution
        (Brand > Platform > Sentiment)

        Args:
            df: Sentiment dataframe
            title: Chart title

        Returns:
            plotly.graph_objects.Figure
        """
        # Prepare data for sunburst
        sunburst_data = df.groupby(['brand', 'platform', 'sentiment_polarity']).size().reset_index(name='count')

        fig = px.sunburst(
            sunburst_data,
            path=['brand', 'platform', 'sentiment_polarity'],
            values='count',
            title=title,
            height=500
        )

        fig.update_layout(
            margin=dict(t=50, l=0, r=0, b=0)
        )

        return fig

    def create_brand_platform_matrix(self, df, title="Brand-Platform Comment Matrix"):
        """
        Create heatmap showing comment distribution across brands and platforms

        Args:
            df: Sentiment dataframe
            title: Chart title

        Returns:
            plotly.graph_objects.Figure
        """
        # Create pivot table
        matrix_data = pd.crosstab(df['brand'], df['platform'])

        fig = go.Figure(data=go.Heatmap(
            z=matrix_data.values,
            x=matrix_data.columns,
            y=matrix_data.index,
            colorscale='Blues',
            text=matrix_data.values,
            texttemplate='%{text}',
            textfont={"size": 14},
            hovertemplate='<b>%{y} - %{x}</b><br>Comments: %{z}<extra></extra>',
            colorbar=dict(title="Comments")
        ))

        fig.update_layout(
            title=title,
            xaxis_title="Platform",
            yaxis_title="Brand",
            height=self.chart_height
        )

        return fig

    def create_reply_required_chart(self, df, group_by='brand', title="Comments Requiring Reply"):
        """
        Create stacked bar chart showing reply requirements

        Args:
            df: Sentiment dataframe
            group_by: Column to group by
            title: Chart title

        Returns:
            plotly.graph_objects.Figure
        """
        # Create aggregation
        reply_data = df.groupby([group_by, 'requires_reply']).size().reset_index(name='count')
        reply_pivot = reply_data.pivot(index=group_by, columns='requires_reply', values='count').fillna(0)

        fig = go.Figure()

        if False in reply_pivot.columns:
            fig.add_trace(go.Bar(
                name='No Reply Needed',
                x=reply_pivot.index,
                y=reply_pivot[False],
                marker_color='#81C784',
                hovertemplate='<b>%{x}</b><br>No Reply: %{y}<extra></extra>'
            ))

        if True in reply_pivot.columns:
            fig.add_trace(go.Bar(
                name='Reply Required',
                x=reply_pivot.index,
                y=reply_pivot[True],
                marker_color='#FF7043',
                hovertemplate='<b>%{x}</b><br>Reply Required: %{y}<extra></extra>'
            ))

        fig.update_layout(
            title=title,
            xaxis_title=group_by.capitalize(),
            yaxis_title="Number of Comments",
            barmode='stack',
            height=self.chart_height,
            legend=dict(title="Reply Status", orientation="v", yanchor="top", y=1, xanchor="left", x=1.02)
        )

        return fig

    def create_engagement_scatter(self, content_summary_df, title="Content Engagement Analysis"):
        """
        Create scatter plot showing content engagement

        Args:
            content_summary_df: DataFrame with content summary statistics
            title: Chart title

        Returns:
            plotly.graph_objects.Figure
        """
        fig = px.scatter(
            content_summary_df,
            x='total_comments',
            y='negative_percentage',
            size='reply_required_count',
            color='negative_percentage',
            hover_data=['content_description'],
            title=title,
            labels={
                'total_comments': 'Total Comments',
                'negative_percentage': 'Negative Sentiment %',
                'reply_required_count': 'Replies Required'
            },
            color_continuous_scale='RdYlGn_r',
            height=self.chart_height
        )

        fig.update_layout(
            xaxis_title="Total Comments",
            yaxis_title="Negative Sentiment %",
            coloraxis_colorbar=dict(title="Negative %")
        )

        return fig