Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -61,8 +61,8 @@ def ensure_float(value):
|
|
| 61 |
def create_empty_figure(title):
|
| 62 |
return go.Figure().update_layout(title=title, xaxis_title="", yaxis_title="", showlegend=False)
|
| 63 |
|
| 64 |
-
# Function to process and visualize log probs with interactive Plotly plots
|
| 65 |
-
def visualize_logprobs(json_input):
|
| 66 |
try:
|
| 67 |
# Parse the input (handles both JSON and Python dictionaries)
|
| 68 |
data = parse_input(json_input)
|
|
@@ -75,13 +75,13 @@ def visualize_logprobs(json_input):
|
|
| 75 |
else:
|
| 76 |
raise ValueError("Input must be a list or dictionary with 'content' key")
|
| 77 |
|
| 78 |
-
# Extract tokens
|
| 79 |
tokens = []
|
| 80 |
logprobs = []
|
| 81 |
top_alternatives = [] # List to store top 3 log probs (selected token + 2 alternatives)
|
| 82 |
for entry in content:
|
| 83 |
logprob = ensure_float(entry.get("logprob", None))
|
| 84 |
-
if logprob is not None and math.isfinite(logprob) and logprob >=
|
| 85 |
tokens.append(entry["token"])
|
| 86 |
logprobs.append(logprob)
|
| 87 |
# Get top_logprobs, default to empty dict if None
|
|
@@ -103,11 +103,19 @@ def visualize_logprobs(json_input):
|
|
| 103 |
|
| 104 |
# Check if there's valid data after filtering
|
| 105 |
if not logprobs or not tokens:
|
| 106 |
-
return (create_empty_figure("Log Probabilities of Generated Tokens"), None, "No finite log probabilities to display.", create_empty_figure("Top 3 Token Log Probabilities"), create_empty_figure("Significant Probability Drops"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
# 1. Main Log Probability Plot (Interactive Plotly)
|
| 109 |
main_fig = go.Figure()
|
| 110 |
-
main_fig.add_trace(go.Scatter(x=list(range(len(
|
| 111 |
main_fig.update_layout(
|
| 112 |
title="Log Probabilities of Generated Tokens",
|
| 113 |
xaxis_title="Token Position",
|
|
@@ -116,15 +124,15 @@ def visualize_logprobs(json_input):
|
|
| 116 |
clickmode='event+select'
|
| 117 |
)
|
| 118 |
main_fig.update_traces(
|
| 119 |
-
customdata=[f"Token: {tok}, Log Prob: {prob:.4f}, Position: {i}" for i, (tok, prob) in enumerate(zip(
|
| 120 |
hovertemplate='<b>%{customdata}</b><extra></extra>'
|
| 121 |
)
|
| 122 |
|
| 123 |
# 2. Probability Drop Analysis (Interactive Plotly)
|
| 124 |
-
if len(
|
| 125 |
drops_fig = create_empty_figure("Significant Probability Drops")
|
| 126 |
else:
|
| 127 |
-
drops = [
|
| 128 |
drops_fig = go.Figure()
|
| 129 |
drops_fig.add_trace(go.Bar(x=list(range(len(drops))), y=drops, name='Drop', marker_color='red'))
|
| 130 |
drops_fig.update_layout(
|
|
@@ -135,15 +143,15 @@ def visualize_logprobs(json_input):
|
|
| 135 |
clickmode='event+select'
|
| 136 |
)
|
| 137 |
drops_fig.update_traces(
|
| 138 |
-
customdata=[f"Drop: {drop:.4f}, From: {
|
| 139 |
hovertemplate='<b>%{customdata}</b><extra></extra>'
|
| 140 |
)
|
| 141 |
|
| 142 |
-
# Create DataFrame for the table
|
| 143 |
table_data = []
|
| 144 |
-
for i, entry in enumerate(content):
|
| 145 |
logprob = ensure_float(entry.get("logprob", None))
|
| 146 |
-
if logprob is not None and math.isfinite(logprob) and logprob >=
|
| 147 |
token = entry["token"]
|
| 148 |
top_logprobs = entry["top_logprobs"]
|
| 149 |
# Ensure all values in top_logprobs are floats
|
|
@@ -176,38 +184,38 @@ def visualize_logprobs(json_input):
|
|
| 176 |
else None
|
| 177 |
)
|
| 178 |
|
| 179 |
-
# Generate colored text
|
| 180 |
-
if
|
| 181 |
-
min_logprob = min(
|
| 182 |
-
max_logprob = max(
|
| 183 |
if max_logprob == min_logprob:
|
| 184 |
-
normalized_probs = [0.5] * len(
|
| 185 |
else:
|
| 186 |
normalized_probs = [
|
| 187 |
-
(lp - min_logprob) / (max_logprob - min_logprob) for lp in
|
| 188 |
]
|
| 189 |
|
| 190 |
colored_text = ""
|
| 191 |
-
for i, (token, norm_prob) in enumerate(zip(
|
| 192 |
r = int(255 * (1 - norm_prob)) # Red for low confidence
|
| 193 |
g = int(255 * norm_prob) # Green for high confidence
|
| 194 |
b = 0
|
| 195 |
color = f"rgb({r}, {g}, {b})"
|
| 196 |
colored_text += f'<span style="color: {color}; font-weight: bold;">{token}</span>'
|
| 197 |
-
if i < len(
|
| 198 |
colored_text += " "
|
| 199 |
colored_text_html = f"<p>{colored_text}</p>"
|
| 200 |
else:
|
| 201 |
colored_text_html = "No finite log probabilities to display."
|
| 202 |
|
| 203 |
-
# Top 3 Token Log Probabilities (Interactive Plotly)
|
| 204 |
-
alt_viz_fig = create_empty_figure("Top 3 Token Log Probabilities") if not
|
| 205 |
-
if
|
| 206 |
-
for i, (token, probs) in enumerate(zip(
|
| 207 |
for j, (alt_tok, prob) in enumerate(probs):
|
| 208 |
-
alt_viz_fig.add_trace(go.Bar(x=[f"{token} (Pos {i})"], y=[prob], name=f"{alt_tok}", marker_color=['blue', 'green', 'red'][j]))
|
| 209 |
alt_viz_fig.update_layout(
|
| 210 |
-
title="Top 3 Token Log Probabilities",
|
| 211 |
xaxis_title="Token (Position)",
|
| 212 |
yaxis_title="Log Probability",
|
| 213 |
barmode='stack',
|
|
@@ -215,29 +223,33 @@ def visualize_logprobs(json_input):
|
|
| 215 |
clickmode='event+select'
|
| 216 |
)
|
| 217 |
alt_viz_fig.update_traces(
|
| 218 |
-
customdata=[f"Token: {tok}, Alt: {alt}, Log Prob: {prob:.4f}, Position: {i}" for i, (tok, alts) in enumerate(zip(
|
| 219 |
hovertemplate='<b>%{customdata}</b><extra></extra>'
|
| 220 |
)
|
| 221 |
|
| 222 |
-
return (main_fig, df, colored_text_html, alt_viz_fig, drops_fig)
|
| 223 |
|
| 224 |
except Exception as e:
|
| 225 |
logger.error("Visualization failed: %s", str(e))
|
| 226 |
-
return (create_empty_figure("Log Probabilities of Generated Tokens"), None, "No finite log probabilities to display.", create_empty_figure("Top 3 Token Log Probabilities"), create_empty_figure("Significant Probability Drops"))
|
| 227 |
|
| 228 |
-
# Gradio interface with
|
| 229 |
with gr.Blocks(title="Log Probability Visualizer") as app:
|
| 230 |
gr.Markdown("# Log Probability Visualizer")
|
| 231 |
gr.Markdown(
|
| 232 |
-
"Paste your JSON or Python dictionary log prob data below to visualize the tokens and their probabilities. Fixed filter ≥ -100000,
|
| 233 |
)
|
| 234 |
|
| 235 |
with gr.Row():
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
with gr.Row():
|
| 243 |
plot_output = gr.Plot(label="Log Probability Plot (Click for Tokens)")
|
|
@@ -253,8 +265,36 @@ with gr.Blocks(title="Log Probability Visualizer") as app:
|
|
| 253 |
btn = gr.Button("Visualize")
|
| 254 |
btn.click(
|
| 255 |
fn=visualize_logprobs,
|
| 256 |
-
inputs=[json_input],
|
| 257 |
-
outputs=[plot_output, table_output, text_output, alt_viz_output, drops_output],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
)
|
| 259 |
|
| 260 |
app.launch()
|
|
|
|
| 61 |
def create_empty_figure(title):
|
| 62 |
return go.Figure().update_layout(title=title, xaxis_title="", yaxis_title="", showlegend=False)
|
| 63 |
|
| 64 |
+
# Function to process and visualize log probs with interactive Plotly plots and pagination
|
| 65 |
+
def visualize_logprobs(json_input, prob_filter=-100000, page_size=100, page=0):
|
| 66 |
try:
|
| 67 |
# Parse the input (handles both JSON and Python dictionaries)
|
| 68 |
data = parse_input(json_input)
|
|
|
|
| 75 |
else:
|
| 76 |
raise ValueError("Input must be a list or dictionary with 'content' key")
|
| 77 |
|
| 78 |
+
# Extract tokens, log probs, and top alternatives, skipping None or non-finite values with fixed filter
|
| 79 |
tokens = []
|
| 80 |
logprobs = []
|
| 81 |
top_alternatives = [] # List to store top 3 log probs (selected token + 2 alternatives)
|
| 82 |
for entry in content:
|
| 83 |
logprob = ensure_float(entry.get("logprob", None))
|
| 84 |
+
if logprob is not None and math.isfinite(logprob) and logprob >= prob_filter:
|
| 85 |
tokens.append(entry["token"])
|
| 86 |
logprobs.append(logprob)
|
| 87 |
# Get top_logprobs, default to empty dict if None
|
|
|
|
| 103 |
|
| 104 |
# Check if there's valid data after filtering
|
| 105 |
if not logprobs or not tokens:
|
| 106 |
+
return (create_empty_figure("Log Probabilities of Generated Tokens"), None, "No finite log probabilities to display.", create_empty_figure("Top 3 Token Log Probabilities"), create_empty_figure("Significant Probability Drops"), 1, 0)
|
| 107 |
+
|
| 108 |
+
# Paginate data for large inputs (fixed page size of 100)
|
| 109 |
+
total_pages = max(1, (len(logprobs) + page_size - 1) // page_size)
|
| 110 |
+
start_idx = page * page_size
|
| 111 |
+
end_idx = min((page + 1) * page_size, len(logprobs))
|
| 112 |
+
paginated_tokens = tokens[start_idx:end_idx]
|
| 113 |
+
paginated_logprobs = logprobs[start_idx:end_idx]
|
| 114 |
+
paginated_alternatives = top_alternatives[start_idx:end_idx] if top_alternatives else []
|
| 115 |
|
| 116 |
# 1. Main Log Probability Plot (Interactive Plotly)
|
| 117 |
main_fig = go.Figure()
|
| 118 |
+
main_fig.add_trace(go.Scatter(x=list(range(len(paginated_logprobs))), y=paginated_logprobs, mode='markers+lines', name='Log Prob', marker=dict(color='blue')))
|
| 119 |
main_fig.update_layout(
|
| 120 |
title="Log Probabilities of Generated Tokens",
|
| 121 |
xaxis_title="Token Position",
|
|
|
|
| 124 |
clickmode='event+select'
|
| 125 |
)
|
| 126 |
main_fig.update_traces(
|
| 127 |
+
customdata=[f"Token: {tok}, Log Prob: {prob:.4f}, Position: {i+start_idx}" for i, (tok, prob) in enumerate(zip(paginated_tokens, paginated_logprobs))],
|
| 128 |
hovertemplate='<b>%{customdata}</b><extra></extra>'
|
| 129 |
)
|
| 130 |
|
| 131 |
# 2. Probability Drop Analysis (Interactive Plotly)
|
| 132 |
+
if len(paginated_logprobs) < 2:
|
| 133 |
drops_fig = create_empty_figure("Significant Probability Drops")
|
| 134 |
else:
|
| 135 |
+
drops = [paginated_logprobs[i+1] - paginated_logprobs[i] for i in range(len(paginated_logprobs)-1)]
|
| 136 |
drops_fig = go.Figure()
|
| 137 |
drops_fig.add_trace(go.Bar(x=list(range(len(drops))), y=drops, name='Drop', marker_color='red'))
|
| 138 |
drops_fig.update_layout(
|
|
|
|
| 143 |
clickmode='event+select'
|
| 144 |
)
|
| 145 |
drops_fig.update_traces(
|
| 146 |
+
customdata=[f"Drop: {drop:.4f}, From: {paginated_tokens[i]} to {paginated_tokens[i+1]}, Position: {i+start_idx}" for i, drop in enumerate(drops)],
|
| 147 |
hovertemplate='<b>%{customdata}</b><extra></extra>'
|
| 148 |
)
|
| 149 |
|
| 150 |
+
# Create DataFrame for the table (paginated)
|
| 151 |
table_data = []
|
| 152 |
+
for i, entry in enumerate(content[start_idx:end_idx]):
|
| 153 |
logprob = ensure_float(entry.get("logprob", None))
|
| 154 |
+
if logprob is not None and math.isfinite(logprob) and logprob >= prob_filter and "top_logprobs" in entry and entry["top_logprobs"] is not None:
|
| 155 |
token = entry["token"]
|
| 156 |
top_logprobs = entry["top_logprobs"]
|
| 157 |
# Ensure all values in top_logprobs are floats
|
|
|
|
| 184 |
else None
|
| 185 |
)
|
| 186 |
|
| 187 |
+
# Generate colored text (paginated)
|
| 188 |
+
if paginated_logprobs:
|
| 189 |
+
min_logprob = min(paginated_logprobs)
|
| 190 |
+
max_logprob = max(paginated_logprobs)
|
| 191 |
if max_logprob == min_logprob:
|
| 192 |
+
normalized_probs = [0.5] * len(paginated_logprobs)
|
| 193 |
else:
|
| 194 |
normalized_probs = [
|
| 195 |
+
(lp - min_logprob) / (max_logprob - min_logprob) for lp in paginated_logprobs
|
| 196 |
]
|
| 197 |
|
| 198 |
colored_text = ""
|
| 199 |
+
for i, (token, norm_prob) in enumerate(zip(paginated_tokens, normalized_probs)):
|
| 200 |
r = int(255 * (1 - norm_prob)) # Red for low confidence
|
| 201 |
g = int(255 * norm_prob) # Green for high confidence
|
| 202 |
b = 0
|
| 203 |
color = f"rgb({r}, {g}, {b})"
|
| 204 |
colored_text += f'<span style="color: {color}; font-weight: bold;">{token}</span>'
|
| 205 |
+
if i < len(paginated_tokens) - 1:
|
| 206 |
colored_text += " "
|
| 207 |
colored_text_html = f"<p>{colored_text}</p>"
|
| 208 |
else:
|
| 209 |
colored_text_html = "No finite log probabilities to display."
|
| 210 |
|
| 211 |
+
# Top 3 Token Log Probabilities (Interactive Plotly, paginated)
|
| 212 |
+
alt_viz_fig = create_empty_figure("Top 3 Token Log Probabilities") if not paginated_logprobs or not paginated_alternatives else go.Figure()
|
| 213 |
+
if paginated_logprobs and paginated_alternatives:
|
| 214 |
+
for i, (token, probs) in enumerate(zip(paginated_tokens, paginated_alternatives)):
|
| 215 |
for j, (alt_tok, prob) in enumerate(probs):
|
| 216 |
+
alt_viz_fig.add_trace(go.Bar(x=[f"{token} (Pos {i+start_idx})"], y=[prob], name=f"{alt_tok}", marker_color=['blue', 'green', 'red'][j]))
|
| 217 |
alt_viz_fig.update_layout(
|
| 218 |
+
title="Top 3 Token Log Probabilities (Paginated)",
|
| 219 |
xaxis_title="Token (Position)",
|
| 220 |
yaxis_title="Log Probability",
|
| 221 |
barmode='stack',
|
|
|
|
| 223 |
clickmode='event+select'
|
| 224 |
)
|
| 225 |
alt_viz_fig.update_traces(
|
| 226 |
+
customdata=[f"Token: {tok}, Alt: {alt}, Log Prob: {prob:.4f}, Position: {i+start_idx}" for i, (tok, alts) in enumerate(zip(paginated_tokens, paginated_alternatives)) for alt, prob in alts],
|
| 227 |
hovertemplate='<b>%{customdata}</b><extra></extra>'
|
| 228 |
)
|
| 229 |
|
| 230 |
+
return (main_fig, df, colored_text_html, alt_viz_fig, drops_fig, total_pages, page)
|
| 231 |
|
| 232 |
except Exception as e:
|
| 233 |
logger.error("Visualization failed: %s", str(e))
|
| 234 |
+
return (create_empty_figure("Log Probabilities of Generated Tokens"), None, "No finite log probabilities to display.", create_empty_figure("Top 3 Token Log Probabilities"), create_empty_figure("Significant Probability Drops"), 1, 0)
|
| 235 |
|
| 236 |
+
# Gradio interface with interactive layout and pagination
|
| 237 |
with gr.Blocks(title="Log Probability Visualizer") as app:
|
| 238 |
gr.Markdown("# Log Probability Visualizer")
|
| 239 |
gr.Markdown(
|
| 240 |
+
"Paste your JSON or Python dictionary log prob data below to visualize the tokens and their probabilities. Fixed filter ≥ -100000, 100 tokens per page."
|
| 241 |
)
|
| 242 |
|
| 243 |
with gr.Row():
|
| 244 |
+
with gr.Column(scale=1):
|
| 245 |
+
json_input = gr.Textbox(
|
| 246 |
+
label="JSON Input",
|
| 247 |
+
lines=10,
|
| 248 |
+
placeholder="Paste your JSON (e.g., {\"content\": [...]}) or Python dict (e.g., {'content': [...]}) here...",
|
| 249 |
+
)
|
| 250 |
+
with gr.Column(scale=1):
|
| 251 |
+
page = gr.Number(value=0, label="Page Number", precision=0, minimum=0)
|
| 252 |
+
page_size = gr.Number(value=100, label="Page Size", precision=0, minimum=10, maximum=1000, interactive=False) # Fixed at 100, non-interactive
|
| 253 |
|
| 254 |
with gr.Row():
|
| 255 |
plot_output = gr.Plot(label="Log Probability Plot (Click for Tokens)")
|
|
|
|
| 265 |
btn = gr.Button("Visualize")
|
| 266 |
btn.click(
|
| 267 |
fn=visualize_logprobs,
|
| 268 |
+
inputs=[json_input, page_size, page],
|
| 269 |
+
outputs=[plot_output, table_output, text_output, alt_viz_output, drops_output, gr.State(), gr.State()],
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# Pagination controls
|
| 273 |
+
with gr.Row():
|
| 274 |
+
prev_btn = gr.Button("Previous Page")
|
| 275 |
+
next_btn = gr.Button("Next Page")
|
| 276 |
+
total_pages_output = gr.Number(label="Total Pages", interactive=False)
|
| 277 |
+
current_page_output = gr.Number(label="Current Page", interactive=False)
|
| 278 |
+
|
| 279 |
+
def update_page(json_input, current_page, action):
|
| 280 |
+
if action == "prev" and current_page > 0:
|
| 281 |
+
current_page -= 1
|
| 282 |
+
elif action == "next":
|
| 283 |
+
total_pages = visualize_logprobs(json_input, -100000, 100, 0)[5] # Get total pages with fixed filter and page size
|
| 284 |
+
if current_page < total_pages - 1:
|
| 285 |
+
current_page += 1
|
| 286 |
+
return gr.update(value=current_page), gr.update(value=total_pages)
|
| 287 |
+
|
| 288 |
+
prev_btn.click(
|
| 289 |
+
fn=update_page,
|
| 290 |
+
inputs=[json_input, page, gr.State()],
|
| 291 |
+
outputs=[page, total_pages_output]
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
next_btn.click(
|
| 295 |
+
fn=update_page,
|
| 296 |
+
inputs=[json_input, page, gr.State()],
|
| 297 |
+
outputs=[page, total_pages_output]
|
| 298 |
)
|
| 299 |
|
| 300 |
app.launch()
|