GuglielmoTor commited on
Commit
3152dad
·
verified ·
1 Parent(s): e6542ce

Update ui_generators.py

Browse files
Files changed (1) hide show
  1. ui_generators.py +33 -39
ui_generators.py CHANGED
@@ -147,7 +147,7 @@ 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 # Initialize fig to 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))
@@ -157,18 +157,15 @@ def run_mentions_tab_display(token_state):
157
  ax.set_ylabel("Count")
158
  plt.xticks(rotation=45, ha='right')
159
  plt.tight_layout()
160
- fig = fig_plot # Assign the figure object
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 remains None
165
  finally:
166
  if fig is not None and fig is not plt:
167
  plt.close(fig)
168
  elif fig is None and plt.get_fignums():
169
  plt.close('all')
170
-
171
-
172
  return mentions_html_output, fig
173
 
174
 
@@ -191,7 +188,6 @@ def run_follower_stats_tab_display(token_state):
191
  plot_seniority_dist = None
192
  plot_industry_dist = None
193
 
194
- # --- Monthly Gains Table & Plot ---
195
  monthly_gains_df = follower_stats_df[
196
  (follower_stats_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_gains_monthly') &
197
  (follower_stats_df[FOLLOWER_STATS_CATEGORY_COLUMN].notna()) &
@@ -240,7 +236,6 @@ def run_follower_stats_tab_display(token_state):
240
  html_parts.append("<p>No monthly follower gain data available or required columns missing.</p>")
241
  html_parts.append("<hr/>")
242
 
243
- # --- Seniority Table & Plot ---
244
  seniority_df = follower_stats_df[
245
  (follower_stats_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_seniority') &
246
  (follower_stats_df[FOLLOWER_STATS_CATEGORY_COLUMN].notna()) &
@@ -274,7 +269,6 @@ def run_follower_stats_tab_display(token_state):
274
  html_parts.append("<p>No follower seniority data available or required columns missing.</p>")
275
  html_parts.append("<hr/>")
276
 
277
- # --- Industry Table & Plot ---
278
  industry_df = follower_stats_df[
279
  (follower_stats_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_industry') &
280
  (follower_stats_df[FOLLOWER_STATS_CATEGORY_COLUMN].notna()) &
@@ -304,7 +298,6 @@ def run_follower_stats_tab_display(token_state):
304
  plt.close(plot_industry_dist)
305
  elif plot_industry_dist is None and plt.get_fignums():
306
  plt.close('all')
307
-
308
  else:
309
  html_parts.append("<p>No follower industry data available or required columns missing.</p>")
310
 
@@ -327,8 +320,8 @@ def create_analytics_plot_panel(label, plot_id_str):
327
  """
328
  with gr.Column() as panel_col:
329
  with gr.Row(equal_height=False, variant="panel"):
330
- plot_component = gr.Plot(label=label, scale=8) # Plot takes more space
331
- with gr.Column(scale=2, min_width=100): # Column for all buttons
332
  bomb_button = gr.Button(BOMB_ICON, variant="secondary", size="sm", elem_id=f"bomb_{plot_id_str}")
333
  explore_button = gr.Button(EXPLORE_ICON, variant="secondary", size="sm", elem_id=f"explore_{plot_id_str}")
334
  formula_button = gr.Button(FORMULA_ICON, variant="secondary", size="sm", elem_id=f"formula_{plot_id_str}")
@@ -340,50 +333,51 @@ def build_analytics_tab_plot_area(plot_configs):
340
  Returns a dictionary of plot UI objects.
341
  """
342
  logging.info(f"Building plot area for {len(plot_configs)} analytics plots.")
343
- # Stores {"plot_id": {"plot_component": gr.Plot, "bomb_button": gr.Button, "explore_button": gr.Button, "formula_button": gr.Button, "label": str, "panel_component": gr.Column}}
344
  plot_ui_objects = {}
345
 
346
  current_section_title = ""
347
-
348
- for i in range(0, len(plot_configs), 2):
349
- if plot_configs[i]["section"] != current_section_title:
350
- current_section_title = plot_configs[i]["section"]
 
 
 
351
  gr.Markdown(f"### {current_section_title}")
352
 
353
- with gr.Row(equal_height=False): # Main row for two plot panels
354
- # First plot in the pair
355
- config1 = plot_configs[i]
 
356
  panel_col1, plot_comp1, bomb_btn1, explore_btn1, formula_btn1 = \
357
  create_analytics_plot_panel(config1["label"], config1["id"])
358
  plot_ui_objects[config1["id"]] = {
359
- "plot_component": plot_comp1,
360
- "bomb_button": bomb_btn1,
361
- "explore_button": explore_btn1,
362
- "formula_button": formula_btn1,
363
- "label": config1["label"],
364
- "panel_component": panel_col1 # Store the panel itself for visibility/scale changes
365
  }
366
  logging.debug(f"Created UI panel for plot_id: {config1['id']}")
 
367
 
368
- # Second plot in the pair, if it exists
369
- if i + 1 < len(plot_configs):
370
- config2 = plot_configs[i+1]
371
- # If the second plot is in a new section, this row will only contain the first plot.
372
- # The new section header for config2 will be handled in the next iteration of the outer loop.
373
  if config2["section"] == current_section_title:
374
  panel_col2, plot_comp2, bomb_btn2, explore_btn2, formula_btn2 = \
375
  create_analytics_plot_panel(config2["label"], config2["id"])
376
  plot_ui_objects[config2["id"]] = {
377
- "plot_component": plot_comp2,
378
- "bomb_button": bomb_btn2,
379
- "explore_button": explore_btn2,
380
- "formula_button": formula_btn2,
381
- "label": config2["label"],
382
- "panel_component": panel_col2
383
  }
384
- logging.debug(f"Created UI panel for plot_id: {config2['id']}")
385
- # If config2 is in a new section, its panel will be created in the next iteration's new row.
386
- # else: panel for config1 is already in the row.
 
 
387
 
388
  logging.info(f"Finished building plot area. Total plot objects: {len(plot_ui_objects)}")
 
 
389
  return 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
151
  if not mentions_df.empty and "sentiment_label" in mentions_df.columns:
152
  try:
153
  fig_plot, ax = plt.subplots(figsize=(6,4))
 
157
  ax.set_ylabel("Count")
158
  plt.xticks(rotation=45, ha='right')
159
  plt.tight_layout()
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
  finally:
165
  if fig is not None and fig is not plt:
166
  plt.close(fig)
167
  elif fig is None and plt.get_fignums():
168
  plt.close('all')
 
 
169
  return mentions_html_output, fig
170
 
171
 
 
188
  plot_seniority_dist = None
189
  plot_industry_dist = None
190
 
 
191
  monthly_gains_df = follower_stats_df[
192
  (follower_stats_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_gains_monthly') &
193
  (follower_stats_df[FOLLOWER_STATS_CATEGORY_COLUMN].notna()) &
 
236
  html_parts.append("<p>No monthly follower gain data available or required columns missing.</p>")
237
  html_parts.append("<hr/>")
238
 
 
239
  seniority_df = follower_stats_df[
240
  (follower_stats_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_seniority') &
241
  (follower_stats_df[FOLLOWER_STATS_CATEGORY_COLUMN].notna()) &
 
269
  html_parts.append("<p>No follower seniority data available or required columns missing.</p>")
270
  html_parts.append("<hr/>")
271
 
 
272
  industry_df = follower_stats_df[
273
  (follower_stats_df[FOLLOWER_STATS_TYPE_COLUMN] == 'follower_industry') &
274
  (follower_stats_df[FOLLOWER_STATS_CATEGORY_COLUMN].notna()) &
 
298
  plt.close(plot_industry_dist)
299
  elif plot_industry_dist is None and plt.get_fignums():
300
  plt.close('all')
 
301
  else:
302
  html_parts.append("<p>No follower industry data available or required columns missing.</p>")
303
 
 
320
  """
321
  with gr.Column() as panel_col:
322
  with gr.Row(equal_height=False, variant="panel"):
323
+ plot_component = gr.Plot(label=label, scale=8)
324
+ with gr.Column(scale=2, min_width=100):
325
  bomb_button = gr.Button(BOMB_ICON, variant="secondary", size="sm", elem_id=f"bomb_{plot_id_str}")
326
  explore_button = gr.Button(EXPLORE_ICON, variant="secondary", size="sm", elem_id=f"explore_{plot_id_str}")
327
  formula_button = gr.Button(FORMULA_ICON, variant="secondary", size="sm", elem_id=f"formula_{plot_id_str}")
 
333
  Returns a dictionary of plot UI objects.
334
  """
335
  logging.info(f"Building plot area for {len(plot_configs)} analytics plots.")
 
336
  plot_ui_objects = {}
337
 
338
  current_section_title = ""
339
+ i = 0
340
+ while i < len(plot_configs):
341
+ config1 = plot_configs[i]
342
+
343
+ # Start a new section if necessary
344
+ if config1["section"] != current_section_title:
345
+ current_section_title = config1["section"]
346
  gr.Markdown(f"### {current_section_title}")
347
 
348
+ # Create a new row for each pair of plots or a single plot if it's the last one
349
+ # or if the next plot is in a different section.
350
+ with gr.Row(equal_height=False):
351
+ # Process the first plot of the potential pair
352
  panel_col1, plot_comp1, bomb_btn1, explore_btn1, formula_btn1 = \
353
  create_analytics_plot_panel(config1["label"], config1["id"])
354
  plot_ui_objects[config1["id"]] = {
355
+ "plot_component": plot_comp1, "bomb_button": bomb_btn1,
356
+ "explore_button": explore_btn1, "formula_button": formula_btn1,
357
+ "label": config1["label"], "panel_component": panel_col1
 
 
 
358
  }
359
  logging.debug(f"Created UI panel for plot_id: {config1['id']}")
360
+ i += 1 # Move to the next plot configuration
361
 
362
+ # Check if there's a second plot for this row
363
+ if i < len(plot_configs):
364
+ config2 = plot_configs[i]
365
+ # Add to the same row ONLY if it's in the same section
 
366
  if config2["section"] == current_section_title:
367
  panel_col2, plot_comp2, bomb_btn2, explore_btn2, formula_btn2 = \
368
  create_analytics_plot_panel(config2["label"], config2["id"])
369
  plot_ui_objects[config2["id"]] = {
370
+ "plot_component": plot_comp2, "bomb_button": bomb_btn2,
371
+ "explore_button": explore_btn2, "formula_button": formula_btn2,
372
+ "label": config2["label"], "panel_component": panel_col2
 
 
 
373
  }
374
+ logging.debug(f"Created UI panel for plot_id: {config2['id']} in same row")
375
+ i += 1 # Move to the next plot configuration
376
+ # If config2 is in a new section, the row ends with config1.
377
+ # config2 will be processed as the first plot in a new row in the next iteration.
378
+ # If no more plots or next is in new section, row is complete.
379
 
380
  logging.info(f"Finished building plot area. Total plot objects: {len(plot_ui_objects)}")
381
+ if len(plot_ui_objects) != len(plot_configs):
382
+ logging.error(f"MISMATCH: Expected {len(plot_configs)} plot objects, but created {len(plot_ui_objects)}.")
383
  return plot_ui_objects