Spaces:
Sleeping
Sleeping
File size: 13,393 Bytes
571f3d0 230696b 571f3d0 230696b d10d3ce 571f3d0 230696b 571f3d0 d10d3ce 571f3d0 230696b 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 8a0bc9d 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 1b86466 571f3d0 1b86466 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 8a0bc9d 571f3d0 8a0bc9d 571f3d0 8a0bc9d 571f3d0 8a0bc9d 571f3d0 8a0bc9d 571f3d0 8a0bc9d 571f3d0 8a0bc9d 571f3d0 230696b 571f3d0 8a0bc9d 571f3d0 8a0bc9d 571f3d0 8a0bc9d 571f3d0 d10d3ce 8a0bc9d d10d3ce 8a0bc9d 571f3d0 8a0bc9d 571f3d0 230696b 571f3d0 230696b 571f3d0 230696b d10d3ce 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 d10d3ce 571f3d0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
import gradio as gr
import matplotlib.pyplot as plt
from domains.coordination.game_coordination import BayesianGame, GamePhase
from domains.environment.environment_domain import EvidenceType
class GradioInterface:
"""Gradio interface for the Bayesian Game."""
def __init__(self):
"""Initialize the Gradio interface."""
self.game = None
self.reset_game()
def reset_game(
self,
dice_sides: int = 6,
max_rounds: int = 10,
evidence_type_str: str = "Basic",
) -> tuple[str, plt.Figure, str]:
"""Reset the game with new parameters.
Args:
dice_sides: Number of sides on the dice
max_rounds: Maximum number of rounds
evidence_type_str: Evidence type ("Basic" or "Extended")
Returns:
Tuple of (status, belief_chart, game_log)
"""
evidence_type = (
EvidenceType.EXTENDED
if evidence_type_str == "Extended"
else EvidenceType.BASIC
)
self.game = BayesianGame(
dice_sides=dice_sides, max_rounds=max_rounds, evidence_type=evidence_type
)
return self._get_interface_state()
def start_new_game(self, target_value: str = "") -> tuple[str, plt.Figure, str]:
"""Start a new game.
Args:
target_value: Optional specific target value
Returns:
Tuple of (status, belief_chart, game_log)
"""
try:
target = int(target_value) if target_value.strip() else None
if target is not None and not (1 <= target <= self.game.dice_sides):
return (
f"β Target value must be between 1 and {self.game.dice_sides}",
self._create_empty_chart(),
"",
)
self.game.start_new_game(target_value=target)
return self._get_interface_state()
except ValueError as e:
return f"β Error: {e!s}", self._create_empty_chart(), ""
def play_round(self) -> tuple[str, plt.Figure, str]:
"""Play one round of the game.
Returns:
Tuple of (status, belief_chart, game_log)
"""
try:
# Check if game is already finished - but still show the final state
if self.game.is_game_finished():
# Get the current final state but with a message about being finished
status, belief_chart, game_log = self._get_interface_state()
return (
"π Game completed! All rounds finished. Start a new game to play again.",
belief_chart,
game_log,
)
if self.game.game_state.phase != GamePhase.PLAYING:
return (
"β Game not in playing phase. Start a new game first.",
self._create_empty_chart(),
"",
)
self.game.play_round()
return self._get_interface_state()
except ValueError as e:
return f"β Error: {e!s}", self._create_empty_chart(), ""
def _get_interface_state(self) -> tuple[str, plt.Figure, str]:
"""Get current interface state.
Returns:
Tuple of (status, belief_chart, game_log)
"""
state = self.game.get_current_state()
# Status message
if state.phase == GamePhase.SETUP:
status = "π― Ready to start new game"
elif state.phase == GamePhase.PLAYING:
entropy = state.belief_entropy
status = f"π² Playing - Round {state.round_number}/{state.max_rounds} - Entropy: {entropy:.2f} bits"
else: # FINISHED
correct = "β
" if self.game.was_final_guess_correct() else "β"
accuracy = self.game.get_final_guess_accuracy()
entropy = state.belief_entropy
status = f"{correct} Game finished! Final guess: {state.most_likely_target} (True: {state.target_value}) - Accuracy: {accuracy:.2f} - Entropy: {entropy:.2f} bits"
# Round information - removed for cleaner UI
# Belief visualization
belief_chart = self._create_belief_chart()
# Game log
game_log = self._create_game_log()
return status, belief_chart, game_log
def _create_belief_chart(self) -> plt.Figure:
"""Create belief distribution chart.
Returns:
Matplotlib figure showing belief distribution
"""
# Close any existing figures to prevent memory leaks
plt.close("all")
fig, ax = plt.subplots(figsize=(10, 6))
if self.game.game_state.current_beliefs:
targets = list(range(1, len(self.game.game_state.current_beliefs) + 1))
beliefs = self.game.game_state.current_beliefs
bars = ax.bar(
targets, beliefs, alpha=0.7, color="skyblue", edgecolor="navy"
)
# Highlight the most likely target
if self.game.game_state.most_likely_target:
most_likely_idx = self.game.game_state.most_likely_target - 1
bars[most_likely_idx].set_color("orange")
bars[most_likely_idx].set_alpha(1.0)
# Highlight true target if known
if self.game.game_state.target_value:
true_target_idx = self.game.game_state.target_value - 1
bars[true_target_idx].set_edgecolor("red")
bars[true_target_idx].set_linewidth(3)
ax.set_xlabel("Target Value")
ax.set_ylabel("Belief Probability")
# Enhanced title based on game state
if self.game.game_state.phase == GamePhase.FINISHED:
correct_indicator = (
"β
" if self.game.was_final_guess_correct() else "β"
)
ax.set_title(f"Final Belief Distribution {correct_indicator}")
else:
ax.set_title("Player 2's Belief Distribution")
ax.set_xticks(targets)
ax.set_ylim(0, 1)
ax.grid(True, alpha=0.3)
# Add legend
legend_elements = []
if self.game.game_state.most_likely_target:
legend_elements.append(
plt.Rectangle(
(0, 0), 1, 1, fc="orange", alpha=1.0, label="Most Likely"
)
)
if self.game.game_state.target_value:
legend_elements.append(
plt.Rectangle(
(0, 0), 1, 1, fc="skyblue", ec="red", lw=3, label="True Target"
)
)
if legend_elements:
ax.legend(handles=legend_elements)
else:
ax.text(
0.5,
0.5,
"Start a game to see beliefs",
transform=ax.transAxes,
ha="center",
va="center",
fontsize=14,
)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.tight_layout()
return fig
def _create_empty_chart(self) -> plt.Figure:
"""Create an empty chart for error states.
Returns:
Matplotlib figure with error message
"""
# Close any existing figures to prevent memory leaks
plt.close("all")
fig, ax = plt.subplots(figsize=(10, 6))
ax.text(
0.5,
0.5,
"Error: Unable to display chart",
transform=ax.transAxes,
ha="center",
va="center",
fontsize=14,
color="red",
)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title("Chart Error")
plt.tight_layout()
return fig
def _create_game_log(self) -> str:
"""Create game log showing evidence history.
Returns:
Formatted string with game log
"""
if not self.game.game_state.evidence_history:
return "No evidence yet. Start playing rounds to see the log."
log_lines = ["**Evidence History:**\n"]
for i, evidence in enumerate(self.game.game_state.evidence_history, 1):
# Handle multiple evidence types
evidence_display = []
for result in evidence.comparison_results:
emoji = {
"higher": "β¬οΈ",
"lower": "β¬οΈ",
"same": "π―",
"half": "Β½",
"double": "x2",
}.get(result, "β")
evidence_display.append(f"{result} {emoji}")
evidence_str = ", ".join(evidence_display)
log_lines.append(f"Round {i}: Rolled {evidence.dice_roll} β {evidence_str}")
# Add completion message if game is finished
if self.game.game_state.phase == GamePhase.FINISHED:
log_lines.append("")
log_lines.append("**π Game Completed!**")
if self.game.was_final_guess_correct():
log_lines.append(
"π **Congratulations!** Player 2 correctly identified the target!"
)
else:
log_lines.append(
"π **Learning opportunity!** Player 2's beliefs converged but missed the target."
)
# Add some Bayesian insights
final_accuracy = self.game.get_final_guess_accuracy()
# Accuracy thresholds
STRONG_EVIDENCE_THRESHOLD = 0.5
MODERATE_EVIDENCE_THRESHOLD = 0.3
if final_accuracy > STRONG_EVIDENCE_THRESHOLD:
log_lines.append(
f"π― Strong evidence: {final_accuracy:.1%} confidence in true target"
)
elif final_accuracy > MODERATE_EVIDENCE_THRESHOLD:
log_lines.append(
f"π€ Moderate evidence: {final_accuracy:.1%} confidence in true target"
)
else:
log_lines.append(
f"π«οΈ Conflicting evidence: Only {final_accuracy:.1%} confidence in true target"
)
return "\n".join(log_lines)
def create_interface() -> gr.Interface:
"""Create and return the Gradio interface.
Returns:
Configured Gradio interface
"""
interface = GradioInterface()
with gr.Blocks(title="Bayesian Game", theme=gr.themes.Soft()) as demo:
gr.Markdown("# π² Bayesian Game")
gr.Markdown(
"""
**Game Rules:**
- Judge and Player 1 can see the target die value
- Player 2 must deduce the target value using Bayesian inference
- Each round: Player 1 rolls dice and reports evidence based on selected type
- **Basic Evidence**: higher/lower/same compared to target
- **Extended Evidence**: higher/lower/same/half/double (multiple types can apply)
- Game runs for a specified number of rounds
"""
)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### Game Controls")
with gr.Row():
dice_sides = gr.Number(
value=6, label="Dice Sides", minimum=2, maximum=20, precision=0
)
max_rounds = gr.Number(
value=10, label="Max Rounds", minimum=1, maximum=50, precision=0
)
evidence_type_dropdown = gr.Dropdown(
choices=["Basic", "Extended"],
value="Basic",
label="Evidence Type",
info="Basic: higher/lower/same only. Extended: adds half/double evidence.",
)
reset_btn = gr.Button("π Reset Game", variant="secondary")
target_input = gr.Textbox(
label="Target Value (optional)",
placeholder="Leave empty for random target",
max_lines=1,
)
start_btn = gr.Button("π― Start New Game", variant="primary")
play_btn = gr.Button("π² Play Round", variant="secondary")
with gr.Column(scale=2):
status_output = gr.Textbox(label="Game Status", interactive=False)
belief_plot = gr.Plot(label="Belief Distribution")
game_log = gr.Markdown("Game log will appear here.")
# Event handlers
reset_btn.click(
interface.reset_game,
inputs=[dice_sides, max_rounds, evidence_type_dropdown],
outputs=[status_output, belief_plot, game_log],
)
start_btn.click(
interface.start_new_game,
inputs=[target_input],
outputs=[status_output, belief_plot, game_log],
)
play_btn.click(
interface.play_round,
outputs=[status_output, belief_plot, game_log],
)
# Initialize interface
demo.load(
interface._get_interface_state,
outputs=[status_output, belief_plot, game_log],
)
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch()
|