"""DebateMind — Interactive Gradio Dashboard. Visualizes parliamentary sessions in real time: faction trust dynamics, vote projections, reward components, and the full transcript. Usage: python app.py """ from __future__ import annotations import random import time from dataclasses import asdict import gradio as gr import plotly.graph_objects as go from debatemind.environment import ParliamentEnvironment from debatemind.models.faction import Faction # ── Faction display config ─────────────────────────────────────────────────── FACTION_COLORS = { "fiscal_conservative": "#1f77b4", "green": "#2ca02c", "centrist": "#ff7f0e", "progressive": "#9467bd", "nationalist": "#d62728", } FACTION_EMOJI = { "fiscal_conservative": "🏛️", "green": "🌿", "centrist": "⚖️", "progressive": "🚀", "nationalist": "🛡️", } # ── Agent policies (same as demo) ─────────────────────────────────────────── FACTIONS_LIST = [ "fiscal_conservative", "green", "centrist", "progressive", "nationalist", ] FACTION_NAMES = { "fiscal_conservative": "Ironveil Conservatives", "green": "Verdant Alliance", "centrist": "Unity Front", "progressive": "New Horizon", "nationalist": "Sovereign Guard", } FACTION_PRIORITIES = { "fiscal_conservative": ["fiscal restraint", "market freedom", "tradition"], "green": ["climate action", "sustainability", "regulation"], "centrist": ["compromise", "stability", "incremental reform"], "progressive": ["social equity", "innovation", "public investment"], "nationalist": ["sovereignty", "domestic industry", "border control"], } class NaiveAgent: def __init__(self, rng=None): self.rng = rng or random.Random(42) def act(self, obs): choice = self.rng.choice(["speech", "negotiate", "amend", "tally"]) if choice == "speech": return {"speech": self.rng.choice([ "I think we should pass this bill.", "Climate change is real and we need regulation.", "Everyone should just vote yes.", ])} elif choice == "negotiate": faction = self.rng.choice(FACTIONS_LIST) wrong = self.rng.choice([f for f in FACTIONS_LIST if f != faction]) return { "tool_name": "negotiate", "tool_args": {"faction_id": faction, "offer": {"priorities_addressed": FACTION_PRIORITIES[wrong]}}, } elif choice == "amend": return { "tool_name": "propose_amendment", "tool_args": {"clause_index": self.rng.randint(0, 4), "new_text": "Mandate 80% reduction by 2030"}, } else: return {"tool_name": "check_vote_tally", "tool_args": {}} class TrainedAgent: def __init__(self, rng=None): self.rng = rng or random.Random(123) self.turn = 0 self.cycle = 0 # track negotiation rounds self.phase = "assess" self.faction_idx = 0 self.reading = 1 def act(self, obs): self.turn += 1 reading = obs.get("current_reading", self.reading) self.reading = reading if self.phase == "assess": self.phase = "negotiate" return { "tool_name": "check_vote_tally", "tool_args": {}, "speech": f"Let me assess where we stand heading into Reading {reading}.", } elif self.phase == "negotiate": if self.faction_idx < len(FACTIONS_LIST): fid = FACTIONS_LIST[self.faction_idx] self.faction_idx += 1 prios = FACTION_PRIORITIES[fid] name = FACTION_NAMES[fid] # Tailor offers based on reading stage if reading == 1: concession_msg = f"We'll prioritize {prios[0]} in the initial framework." elif reading == 2: concession_msg = f"We've incorporated {prios[0]} and {prios[1]} into the amended bill." else: concession_msg = f"The final bill reflects all of {name}'s core concerns." return { "tool_name": "negotiate", "tool_args": { "faction_id": fid, "offer": { "priorities_addressed": prios, "concessions": {p: f"Addressed {p}" for p in prios[:2]}, "reading": reading, }, }, "speech": f"To {name}: {concession_msg} I'm committed to {', '.join(prios[:2])}.", } self.phase = "amend" self.faction_idx = 0 return self.act(obs) elif self.phase == "amend": # Different amendments per cycle to keep things fresh amendment_sets = [ [ (1, "Green infrastructure fund $5B with private co-investment matching"), (3, "Domestically administered carbon credit market with border adjustment"), (0, "50% emission reduction by 2035 with mandatory 3-year progress reviews"), ], [ (2, "Renewable energy tax credits phased over 10 years for fiscal stability"), (4, "Sovereign energy security clause ensuring domestic supply chains"), (1, "Public-private green bond program with guaranteed returns"), ], [ (0, "Graduated emission targets: 30% by 2030, 50% by 2035, 75% by 2040"), (3, "Innovation fund for clean technology startups — $2B over 5 years"), (2, "Community transition support for workers in affected industries"), ], ] amendments = amendment_sets[self.cycle % len(amendment_sets)] if self.faction_idx < len(amendments): ci, txt = amendments[self.faction_idx] self.faction_idx += 1 return { "tool_name": "propose_amendment", "tool_args": {"clause_index": ci, "new_text": txt}, "speech": f"This amendment to clause {ci + 1} balances fiscal responsibility with climate action.", } self.phase = "rally" self.faction_idx = 0 return self.act(obs) elif self.phase == "rally": # Rally support with targeted speeches rally_speeches = [ "I call on all factions to recognize the compromises we've built into this bill. Every priority has been heard.", "This bill now reflects input from fiscal conservatives, green advocates, and centrists alike. Let's move forward.", "We've addressed sovereignty concerns, climate targets, and fiscal restraint. This is a coalition bill.", "I urge the Verdant Alliance and New Horizon to see the ambitious targets. Ironveil, note the fiscal safeguards.", "The amended bill is stronger than what any single faction could achieve alone. That's the power of compromise.", ] speech = rally_speeches[self.turn % len(rally_speeches)] # Check votes periodically during rally if self.turn % 2 == 0: self.phase = "reassess" return { "tool_name": "check_vote_tally", "tool_args": {}, "speech": speech, } # Read transcript to reference past agreements if self.turn % 3 == 0: start = max(0, self.turn - 10) return { "tool_name": "read_transcript", "tool_args": {"start_turn": start, "end_turn": self.turn - 1}, "speech": speech, } # Search precedent for persuasion if self.turn % 5 == 0: topics = ["climate legislation", "coalition building", "fiscal policy", "emission targets"] return { "tool_name": "search_precedent", "tool_args": {"topic": topics[self.turn % len(topics)]}, "speech": speech, } self.rally_count = getattr(self, 'rally_count', 0) + 1 if self.rally_count >= 4: self.rally_count = 0 self.phase = "reassess" return {"speech": speech} elif self.phase == "reassess": # Start a new cycle: re-negotiate with updated offers self.cycle += 1 self.phase = "negotiate" self.faction_idx = 0 return { "tool_name": "check_vote_tally", "tool_args": {}, "speech": f"Let me reassess our position after round {self.cycle} of negotiations.", } # ── Dashboard helpers ──────────────────────────────────────────────────────── def build_trust_chart(history: dict[str, list[float]], turns: list[int]) -> go.Figure: """Build a Plotly line chart of trust scores over turns.""" fig = go.Figure() for fid, scores in history.items(): fig.add_trace(go.Scatter( x=turns[:len(scores)], y=scores, mode="lines+markers", name=f"{FACTION_EMOJI.get(fid, '')} {FACTION_NAMES.get(fid, fid)}", line=dict(color=FACTION_COLORS.get(fid, "#888"), width=2), marker=dict(size=4), )) fig.update_layout( title="Faction Trust Scores Over Time", xaxis_title="Turn", yaxis_title="Trust Score", yaxis=dict(range=[0, 1.05]), template="plotly_white", height=400, legend=dict(orientation="h", yanchor="bottom", y=-0.3), margin=dict(l=40, r=20, t=50, b=80), ) return fig def build_reward_bars(breakdown: dict | None) -> go.Figure: """Build a horizontal bar chart of reward components.""" if breakdown is None: breakdown = { "bill_passage": 0, "coalition_size": 0, "argument_consistency": 0, "amendment_quality": 0, "total": 0, } labels = ["Bill Passage\n(×0.40)", "Coalition Size\n(×0.20)", "Arg. Consistency\n(×0.30)", "Amend. Quality\n(×0.10)", "TOTAL"] values = [ breakdown["bill_passage"], breakdown["coalition_size"], breakdown["argument_consistency"], breakdown["amendment_quality"], breakdown["total"], ] colors = ["#1f77b4", "#2ca02c", "#ff7f0e", "#9467bd", "#d62728"] fig = go.Figure(go.Bar( x=values, y=labels, orientation="h", marker_color=colors, text=[f"{v:.2f}" for v in values], textposition="auto", )) fig.update_layout( title="Reward Breakdown", xaxis=dict(range=[0, 1.05]), template="plotly_white", height=280, margin=dict(l=120, r=20, t=50, b=30), ) return fig def build_faction_cards(env: ParliamentEnvironment) -> str: """Build HTML faction cards with trust bars.""" cards = [] for faction in env.factions: fid = faction.faction_id emoji = FACTION_EMOJI.get(fid, "") color = FACTION_COLORS.get(fid, "#888") trust_pct = int(faction.trust_score * 100) bar_color = color if trust_pct < 30: bar_color = "#d62728" elif trust_pct > 70: bar_color = "#2ca02c" card = f"""
No session active.
") with gr.Column(scale=2): trust_chart = gr.Plot(label="Trust Dynamics") with gr.Row(): reward_chart = gr.Plot(label="Reward Components") with gr.Row(): transcript_box = gr.Markdown( "*Transcript will appear here...*", label="Live Transcript", ) def run_handler(agent_type, max_turns): for state in run_episode_streaming(agent_type, int(max_turns)): header, cards, trust, rewards, transcript, status = state yield header, cards, trust, rewards, transcript, status run_btn.click( fn=run_handler, inputs=[agent_selector, max_turns_slider], outputs=[bill_header, faction_cards, trust_chart, reward_chart, transcript_box, status_bar], ) return demo if __name__ == "__main__": app = create_app() app.launch(share=False)