import pandas as pd
from IPython.display import display, HTML
import ipywidgets as widgets
from ipywidgets import GridBox, Layout # Explicitly import Layout
# --- Assuming 'all_results' is defined ---
# Example structure for 'all_results' that would produce 4 DataFrames:
all_results = {
'Model_A': {
'Dataset1': {'total_tokens_len': 1000, 'total_base_len': 2000, 'total_char_len': 5000},
'Dataset2': {'total_tokens_len': 1200, 'total_base_len': 2500, 'total_char_len': 6000},
},
'Model_B': {
'Dataset1': {'total_tokens_len': 900, 'total_base_len': 1800, 'total_char_len': 4500},
'Dataset2': {'total_tokens_len': 1100, 'total_base_len': 2300, 'total_char_len': 5500},
}
}
# -----------------------------------------
dfs_html = [] # Store HTML objects
# --- Define styles for the caption ---
caption_styles = [
{
'selector': 'caption',
'props': [
('font-size', '1.3em'), # Make font larger
('font-weight', 'bold'), # Make text bold
('color', '#1f4e79'), # Choose a distinct color (e.g., dark blue)
('text-align', 'center'), # Ensure caption is centered
('margin-bottom', '10px'), # Add some space below the caption
# ('padding', '8px'), # Optional: Add padding around the caption text
# ('background-color', '#f0f8ff'), # Optional: Add a light background
]
}
]
# --- End caption styles ---
for save_tag, length_stats in all_results.items():
for ref in ['total_base_len', 'total_char_len']:
# --- DataFrame Creation (More Robust) ---
# Create a dictionary of ratios first
ratios = {}
for idx, data in length_stats.items():
# Check if ref exists and is not None/zero before dividing
if ref in data and data[ref] is not None and data[ref] != 0:
ratios[idx] = data['total_tokens_len'] / data[ref]
else:
ratios[idx] = pd.NA # Use pandas NA for missing/invalid data
# Convert ratios to a DataFrame (single column)
df = pd.Series(ratios).to_frame(name='Ratio')
# Calculate and add the mean (handle potential NaNs)
mean_val = df['Ratio'].mean(skipna=True)
df.loc['mean'] = mean_val
# --- End DataFrame Creation ---
# --- Apply Styling ---
# Note: highlight_min/gradient apply better on axis=0 for a single column DataFrame
styled_df = df.style.highlight_min(
axis=0, # Highlight min value within the 'Ratio' column
subset=['Ratio'], # Specify column
props='font-weight:bold; text-decoration:underline;'
).background_gradient(
cmap='Blues_r',
axis=0, # Gradient across values in the 'Ratio' column
subset=['Ratio'] # Specify column
).set_caption(
f"Compression ratios (tokens/{ref}) for {save_tag}"
).set_table_styles( # <--- APPLY CAPTION STYLES HERE
caption_styles
).format(
"{:.3f}", na_rep="N/A" # Format numbers and show N/A for NaNs
)
# --- End Styling ---
dfs_html.append(HTML(styled_df.to_html())) # Append the HTML object
# --- Display Grid ---
# Ensure you actually generated 4 items if you expect a 2x2 grid
if len(dfs_html) == 4:
grid = GridBox(children=dfs_html,
layout=Layout(
# Use '1fr 1fr' for two equal-width flexible columns
grid_template_columns='1fr 1fr',
grid_gap='20px 15px' # Add some space (row gap, column gap)
# width='90%' # Optional: control overall width
))
display(grid)
elif len(dfs_html) > 0:
# Fallback if not exactly 4 items
print(f"Warning: Expected 4 DataFrames for a 2x2 grid, but generated {len(dfs_html)}. Displaying sequentially.")
for item in dfs_html:
display(item)
else:
print("No results generated.")
# --- End Display Grid ---
Now, the captions for each table in the grid should be larger, bold, and colored, making them significantly more prominent. Adjust the CSS properties in caption_styles to get the exact look you prefer.