GuglielmoTor commited on
Commit
7ec7117
·
verified ·
1 Parent(s): 9c20604

Update ui_generators.py

Browse files
Files changed (1) hide show
  1. ui_generators.py +23 -26
ui_generators.py CHANGED
@@ -147,28 +147,26 @@ def run_mentions_tab_display(token_state):
147
  html_parts.append(mentions_df_display[display_columns].head(20).to_html(escape=False, index=False, classes="table table-sm"))
148
 
149
  mentions_html_output = "\n".join(html_parts)
150
- fig = None
 
151
  if not mentions_df.empty and "sentiment_label" in mentions_df.columns:
152
  try:
153
- fig_plot, ax = plt.subplots(figsize=(6,4))
154
  sentiment_counts = mentions_df["sentiment_label"].value_counts()
155
  sentiment_counts.plot(kind='bar', ax=ax, color=['#4CAF50', '#FFC107', '#F44336', '#9E9E9E', '#2196F3'])
156
- ax.set_title("Mention Sentiment Distribution", y=1.03) # MODIFIED: Added y parameter
157
  ax.set_ylabel("Count")
158
  plt.xticks(rotation=45, ha='right')
 
159
  plt.tight_layout() # Ensure tight_layout is called
160
- fig = fig_plot
161
  logging.info("Mentions tab: Sentiment distribution plot generated.")
162
  except Exception as e:
163
  logging.error(f"Error generating mentions plot: {e}", exc_info=True)
164
  fig = None # Ensure fig is None on error
165
  finally:
166
- # Only close if fig_plot was successfully created and is not the global plt context
167
- if fig_plot and fig_plot is not plt: # fig_plot is the figure object from subplots
168
- plt.close(fig_plot)
169
- # Fallback if somehow a global figure was left open without being assigned to fig_plot
170
- # elif fig is None and plt.get_fignums():
171
- # plt.close('all') # This might be too aggressive if other plots are intended to be open
172
  return mentions_html_output, fig
173
 
174
 
@@ -192,7 +190,7 @@ def run_follower_stats_tab_display(token_state):
192
  plot_industry_dist = None
193
 
194
  # Monthly Gains Plot
195
- fig_gains_local = None # Use local var for figure to manage closing
196
  try:
197
  monthly_gains_df = follower_stats_df[
198
  (follower_stats_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_gains_monthly') &
@@ -216,7 +214,6 @@ def run_follower_stats_tab_display(token_state):
216
  organic=(FOLLOWER_STATS_ORGANIC_COLUMN, 'sum'),
217
  paid=(FOLLOWER_STATS_PAID_COLUMN, 'sum')
218
  ).reset_index()
219
- # Ensure months are sorted correctly for plotting after groupby
220
  plot_data['_plot_month_dt'] = pd.to_datetime(plot_data['_plot_month'], format=UI_MONTH_FORMAT)
221
  plot_data = plot_data.sort_values(by='_plot_month_dt')
222
 
@@ -224,23 +221,24 @@ def run_follower_stats_tab_display(token_state):
224
  fig_gains_local, ax_gains = plt.subplots(figsize=(10,5))
225
  ax_gains.plot(plot_data['_plot_month'], plot_data['organic'], marker='o', linestyle='-', label='Organic Gain')
226
  ax_gains.plot(plot_data['_plot_month'], plot_data['paid'], marker='x', linestyle='--', label='Paid Gain')
227
- ax_gains.set_title("Monthly Follower Gains Over Time", y=1.03) # MODIFIED
228
  ax_gains.set_ylabel("Follower Count")
229
  ax_gains.set_xlabel("Month (YYYY-MM)")
230
  plt.xticks(rotation=45, ha='right')
231
  ax_gains.legend()
232
  plt.grid(True, linestyle='--', alpha=0.7)
 
233
  plt.tight_layout()
234
- plot_monthly_gains = fig_gains_local # Assign to the return variable
235
  logging.info("Follower stats tab: Monthly gains plot generated.")
236
  else:
237
  html_parts.append("<p>No monthly follower gain data available or required columns missing.</p>")
238
  except Exception as e:
239
  logging.error(f"Error processing or plotting monthly gains: {e}", exc_info=True)
240
  html_parts.append("<p>Error displaying monthly follower gain data.</p>")
241
- plot_monthly_gains = None # Ensure it's None on error
242
  finally:
243
- if fig_gains_local and fig_gains_local is not plt: # Check local var
244
  plt.close(fig_gains_local)
245
  html_parts.append("<hr/>")
246
 
@@ -261,10 +259,11 @@ def run_follower_stats_tab_display(token_state):
261
  fig_seniority_local, ax_seniority = plt.subplots(figsize=(8,5))
262
  top_n_seniority = seniority_df_sorted.nlargest(10, FOLLOWER_STATS_ORGANIC_COLUMN)
263
  ax_seniority.bar(top_n_seniority[FOLLOWER_STATS_CATEGORY_COLUMN], top_n_seniority[FOLLOWER_STATS_ORGANIC_COLUMN], color='skyblue')
264
- ax_seniority.set_title("Follower Distribution by Seniority (Top 10 Organic)", y=1.03) # MODIFIED
265
  ax_seniority.set_ylabel("Organic Follower Count")
266
  plt.xticks(rotation=45, ha='right')
267
  plt.grid(axis='y', linestyle='--', alpha=0.7)
 
268
  plt.tight_layout()
269
  plot_seniority_dist = fig_seniority_local
270
  logging.info("Follower stats tab: Seniority distribution plot generated.")
@@ -295,10 +294,11 @@ def run_follower_stats_tab_display(token_state):
295
  fig_industry_local, ax_industry = plt.subplots(figsize=(8,5))
296
  top_n_industry = industry_df_sorted.nlargest(10, FOLLOWER_STATS_ORGANIC_COLUMN)
297
  ax_industry.bar(top_n_industry[FOLLOWER_STATS_CATEGORY_COLUMN], top_n_industry[FOLLOWER_STATS_ORGANIC_COLUMN], color='lightcoral')
298
- ax_industry.set_title("Follower Distribution by Industry (Top 10 Organic)", y=1.03) # MODIFIED
299
  ax_industry.set_ylabel("Organic Follower Count")
300
  plt.xticks(rotation=45, ha='right')
301
  plt.grid(axis='y', linestyle='--', alpha=0.7)
 
302
  plt.tight_layout()
303
  plot_industry_dist = fig_industry_local
304
  logging.info("Follower stats tab: Industry distribution plot generated.")
@@ -331,9 +331,9 @@ def create_analytics_plot_panel(label, plot_id_str):
331
  formula_button (gr.Button): Formula button.
332
  """
333
  with gr.Column() as panel_col: # This will be the component that gets hidden/shown by explore
334
- with gr.Row(equal_height=False, variant="panel"): # Removed variant="compact" as it might affect spacing
335
  plot_component = gr.Plot(label=label, scale=8) # The label here is for Gradio, not the Matplotlib title
336
- with gr.Column(scale=2, min_width=100): # min_width for button column
337
  bomb_button = gr.Button(BOMB_ICON, variant="secondary", size="sm", elem_id=f"bomb_{plot_id_str}")
338
  explore_button = gr.Button(EXPLORE_ICON, variant="secondary", size="sm", elem_id=f"explore_{plot_id_str}")
339
  formula_button = gr.Button(FORMULA_ICON, variant="secondary", size="sm", elem_id=f"formula_{plot_id_str}")
@@ -358,14 +358,14 @@ def build_analytics_tab_plot_area(plot_configs):
358
  gr.Markdown(f"### {current_section_title}") # Section title
359
 
360
  # Create a new row for each pair of plots or a single plot
361
- with gr.Row(equal_height=False): # A new row for one or two plots
362
  # Process the first plot of the potential pair
363
  panel_col1, plot_comp1, bomb_btn1, explore_btn1, formula_btn1 = \
364
  create_analytics_plot_panel(config1["label"], config1["id"])
365
  plot_ui_objects[config1["id"]] = {
366
  "plot_component": plot_comp1, "bomb_button": bomb_btn1,
367
  "explore_button": explore_btn1, "formula_button": formula_btn1,
368
- "label": config1["label"], "panel_component": panel_col1 # panel_col1 is the gr.Column from create_analytics_plot_panel
369
  }
370
  logging.debug(f"Created UI panel for plot_id: {config1['id']}")
371
  i += 1
@@ -383,10 +383,7 @@ def build_analytics_tab_plot_area(plot_configs):
383
  }
384
  logging.debug(f"Created UI panel for plot_id: {config2['id']} in same row")
385
  i += 1
386
- # If config2 is in a new section, the row ends with config1.
387
- # config2 will be processed as the first plot in a new row in the next iteration.
388
- # Row ends here. Next iteration will start a new gr.Row if needed.
389
-
390
  logging.info(f"Finished building plot area. Total plot objects: {len(plot_ui_objects)}")
391
  if len(plot_ui_objects) != len(plot_configs):
392
  logging.error(f"MISMATCH: Expected {len(plot_configs)} plot objects, but created {len(plot_ui_objects)}.")
 
147
  html_parts.append(mentions_df_display[display_columns].head(20).to_html(escape=False, index=False, classes="table table-sm"))
148
 
149
  mentions_html_output = "\n".join(html_parts)
150
+ fig = None # Initialize fig to None
151
+ fig_plot_local = None # Use a local variable for the figure object
152
  if not mentions_df.empty and "sentiment_label" in mentions_df.columns:
153
  try:
154
+ fig_plot_local, ax = plt.subplots(figsize=(6,4))
155
  sentiment_counts = mentions_df["sentiment_label"].value_counts()
156
  sentiment_counts.plot(kind='bar', ax=ax, color=['#4CAF50', '#FFC107', '#F44336', '#9E9E9E', '#2196F3'])
157
+ ax.set_title("Mention Sentiment Distribution", y=1.08) # MODIFIED: Increased y parameter
158
  ax.set_ylabel("Count")
159
  plt.xticks(rotation=45, ha='right')
160
+ # fig_plot_local.subplots_adjust(top=0.88) # Alternative: Adjust top margin if y isn't enough
161
  plt.tight_layout() # Ensure tight_layout is called
162
+ fig = fig_plot_local # Assign to fig for returning
163
  logging.info("Mentions tab: Sentiment distribution plot generated.")
164
  except Exception as e:
165
  logging.error(f"Error generating mentions plot: {e}", exc_info=True)
166
  fig = None # Ensure fig is None on error
167
  finally:
168
+ if fig_plot_local and fig_plot_local is not plt:
169
+ plt.close(fig_plot_local)
 
 
 
 
170
  return mentions_html_output, fig
171
 
172
 
 
190
  plot_industry_dist = None
191
 
192
  # Monthly Gains Plot
193
+ fig_gains_local = None
194
  try:
195
  monthly_gains_df = follower_stats_df[
196
  (follower_stats_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_gains_monthly') &
 
214
  organic=(FOLLOWER_STATS_ORGANIC_COLUMN, 'sum'),
215
  paid=(FOLLOWER_STATS_PAID_COLUMN, 'sum')
216
  ).reset_index()
 
217
  plot_data['_plot_month_dt'] = pd.to_datetime(plot_data['_plot_month'], format=UI_MONTH_FORMAT)
218
  plot_data = plot_data.sort_values(by='_plot_month_dt')
219
 
 
221
  fig_gains_local, ax_gains = plt.subplots(figsize=(10,5))
222
  ax_gains.plot(plot_data['_plot_month'], plot_data['organic'], marker='o', linestyle='-', label='Organic Gain')
223
  ax_gains.plot(plot_data['_plot_month'], plot_data['paid'], marker='x', linestyle='--', label='Paid Gain')
224
+ ax_gains.set_title("Monthly Follower Gains Over Time", y=1.08) # MODIFIED
225
  ax_gains.set_ylabel("Follower Count")
226
  ax_gains.set_xlabel("Month (YYYY-MM)")
227
  plt.xticks(rotation=45, ha='right')
228
  ax_gains.legend()
229
  plt.grid(True, linestyle='--', alpha=0.7)
230
+ # fig_gains_local.subplots_adjust(top=0.88) # Alternative adjustment
231
  plt.tight_layout()
232
+ plot_monthly_gains = fig_gains_local
233
  logging.info("Follower stats tab: Monthly gains plot generated.")
234
  else:
235
  html_parts.append("<p>No monthly follower gain data available or required columns missing.</p>")
236
  except Exception as e:
237
  logging.error(f"Error processing or plotting monthly gains: {e}", exc_info=True)
238
  html_parts.append("<p>Error displaying monthly follower gain data.</p>")
239
+ plot_monthly_gains = None
240
  finally:
241
+ if fig_gains_local and fig_gains_local is not plt:
242
  plt.close(fig_gains_local)
243
  html_parts.append("<hr/>")
244
 
 
259
  fig_seniority_local, ax_seniority = plt.subplots(figsize=(8,5))
260
  top_n_seniority = seniority_df_sorted.nlargest(10, FOLLOWER_STATS_ORGANIC_COLUMN)
261
  ax_seniority.bar(top_n_seniority[FOLLOWER_STATS_CATEGORY_COLUMN], top_n_seniority[FOLLOWER_STATS_ORGANIC_COLUMN], color='skyblue')
262
+ ax_seniority.set_title("Follower Distribution by Seniority (Top 10 Organic)", y=1.08) # MODIFIED
263
  ax_seniority.set_ylabel("Organic Follower Count")
264
  plt.xticks(rotation=45, ha='right')
265
  plt.grid(axis='y', linestyle='--', alpha=0.7)
266
+ # fig_seniority_local.subplots_adjust(top=0.85) # Alternative adjustment
267
  plt.tight_layout()
268
  plot_seniority_dist = fig_seniority_local
269
  logging.info("Follower stats tab: Seniority distribution plot generated.")
 
294
  fig_industry_local, ax_industry = plt.subplots(figsize=(8,5))
295
  top_n_industry = industry_df_sorted.nlargest(10, FOLLOWER_STATS_ORGANIC_COLUMN)
296
  ax_industry.bar(top_n_industry[FOLLOWER_STATS_CATEGORY_COLUMN], top_n_industry[FOLLOWER_STATS_ORGANIC_COLUMN], color='lightcoral')
297
+ ax_industry.set_title("Follower Distribution by Industry (Top 10 Organic)", y=1.08) # MODIFIED
298
  ax_industry.set_ylabel("Organic Follower Count")
299
  plt.xticks(rotation=45, ha='right')
300
  plt.grid(axis='y', linestyle='--', alpha=0.7)
301
+ # fig_industry_local.subplots_adjust(top=0.85) # Alternative adjustment
302
  plt.tight_layout()
303
  plot_industry_dist = fig_industry_local
304
  logging.info("Follower stats tab: Industry distribution plot generated.")
 
331
  formula_button (gr.Button): Formula button.
332
  """
333
  with gr.Column() as panel_col: # This will be the component that gets hidden/shown by explore
334
+ with gr.Row(equal_height=False, variant="panel"):
335
  plot_component = gr.Plot(label=label, scale=8) # The label here is for Gradio, not the Matplotlib title
336
+ with gr.Column(scale=2, min_width=100):
337
  bomb_button = gr.Button(BOMB_ICON, variant="secondary", size="sm", elem_id=f"bomb_{plot_id_str}")
338
  explore_button = gr.Button(EXPLORE_ICON, variant="secondary", size="sm", elem_id=f"explore_{plot_id_str}")
339
  formula_button = gr.Button(FORMULA_ICON, variant="secondary", size="sm", elem_id=f"formula_{plot_id_str}")
 
358
  gr.Markdown(f"### {current_section_title}") # Section title
359
 
360
  # Create a new row for each pair of plots or a single plot
361
+ with gr.Row(equal_height=False):
362
  # Process the first plot of the potential pair
363
  panel_col1, plot_comp1, bomb_btn1, explore_btn1, formula_btn1 = \
364
  create_analytics_plot_panel(config1["label"], config1["id"])
365
  plot_ui_objects[config1["id"]] = {
366
  "plot_component": plot_comp1, "bomb_button": bomb_btn1,
367
  "explore_button": explore_btn1, "formula_button": formula_btn1,
368
+ "label": config1["label"], "panel_component": panel_col1
369
  }
370
  logging.debug(f"Created UI panel for plot_id: {config1['id']}")
371
  i += 1
 
383
  }
384
  logging.debug(f"Created UI panel for plot_id: {config2['id']} in same row")
385
  i += 1
386
+
 
 
 
387
  logging.info(f"Finished building plot area. Total plot objects: {len(plot_ui_objects)}")
388
  if len(plot_ui_objects) != len(plot_configs):
389
  logging.error(f"MISMATCH: Expected {len(plot_configs)} plot objects, but created {len(plot_ui_objects)}.")