import gradio as gr
import numpy as np
import pandas as pd
import plotly.graph_objects as go
def calculate_risk(q100, q50, q33, q25, pos, neg, trials=5000):
# Setup strategies and their success probabilities
strategies = {
"Sure (100%)": (q100, 1.0),
"50/50 (50%)": (q50, 0.5),
"3-Options (33%)": (q33, 0.33),
"Blind (25%)": (q25, 0.25)
}
# 1. Generate the Visual Grid (HTML)
grid_html = '
'
q_idx = 1
total_expected_value = 0
for name, (count, prob) in strategies.items():
# Color based on probability (Green to Red)
color = f"rgba(40, 167, 69, {prob})" if prob > 0.4 else f"rgba(220, 53, 69, {1-prob})"
if prob == 1.0: color = "#28a745" # Solid Green
for _ in range(int(count)):
grid_html += f'''
{q_idx}
'''
q_idx += 1
# Calculate EV for this question
total_expected_value += (prob * pos) - ((1 - prob) * neg)
grid_html += "
"
# 2. Monte Carlo Simulation for the "Deep Analysis"
all_trial_scores = []
for _ in range(trials):
trial_score = 0
for name, (count, prob) in strategies.items():
correct = np.random.binomial(int(count), prob)
wrong = int(count) - correct
trial_score += (correct * pos) - (wrong * neg)
all_trial_scores.append(trial_score)
# 3. Statistics
avg_score = np.mean(all_trial_scores)
risk_of_loss = np.mean(np.array(all_trial_scores) < (q100 * pos)) * 100
# 4. Create Distribution Plot
fig = go.Figure()
fig.add_trace(go.Histogram(x=all_trial_scores, nbinsx=30, marker_color='#636EFA', opacity=0.75, name="Simulated Scores"))
fig.add_vline(x=q100*pos, line_dash="dash", line_color="red", annotation_text="Score if you didn't guess")
fig.update_layout(title="Distribution of Possible Final Scores", xaxis_title="Total Score", yaxis_title="Frequency", template="none")
analysis_text = f"""
### 🔍 Risk Analysis
- **Mathematically Expected Score:** {total_expected_value:.2f}
- **Probability that guessing will HURT you:** {risk_of_loss:.1f}%
- **Best Case Scenario (Top 5%):** {np.percentile(all_trial_scores, 95):.0f}
- **Worst Case Scenario (Bottom 5%):** {np.percentile(all_trial_scores, 5):.0f}
**Verdict:** {"✅ Guessing is statistically profitable." if total_expected_value > (q100 * pos) else "❌ Guessing is statistically likely to lower your score."}
"""
return grid_html, fig, analysis_text
with gr.Blocks(title="ExamRisk Pro") as demo:
gr.Markdown("# 📉 ExamRisk Pro: Deep Marking Simulator")
gr.Markdown("Define your question confidence batches to see the visual 'heatmap' of your paper and your probability of success.")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 1. Set Scoring Rules")
with gr.Row():
pos_m = gr.Number(label="Correct (+)", value=4)
neg_m = gr.Number(label="Negative (-)", value=1)
gr.Markdown("### 2. Enter Question Counts")
q_sure = gr.Slider(0, 100, step=1, label="100% Sure (Known)", value=40)
q_50 = gr.Slider(0, 100, step=1, label="50/50 (Eliminated 2)", value=10)
q_33 = gr.Slider(0, 100, step=1, label="33% (Eliminated 1)", value=5)
q_25 = gr.Slider(0, 100, step=1, label="25% (Blind Guess)", value=5)
btn = gr.Button("Analyze My Strategy", variant="primary")
with gr.Column(scale=2):
gr.Markdown("### 3. Probability Heatmap")
grid_out = gr.HTML()
with gr.Row():
with gr.Column():
plot_out = gr.Plot()
with gr.Column():
stats_out = gr.Markdown()
btn.click(
calculate_risk,
inputs=[q_sure, q_50, q_33, q_25, pos_m, neg_m],
outputs=[grid_out, plot_out, stats_out]
)
demo.launch()