File size: 12,674 Bytes
22d701f 65672dd 914936c d75262b 22d701f 914936c 65672dd 22d701f | 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 | import spaces
import gradio as gr
import os
import sys
import time
import numpy as np
# Add backend directory to Python path
backend_dir = os.path.join(os.path.dirname(__file__), "backend")
if backend_dir not in sys.path:
sys.path.insert(0, backend_dir)
# Import models and core evaluation pipelines
try:
from pipeline_b_segmentation import segment_response, is_fact_checkable
from pipeline_e_rag import verify_claim
from scoring import compute_turn_score, aggregate_final_scores, generate_final_analysis
HAS_BACKEND = True
except Exception as e:
print("[HF Backend Import Warning]", e)
HAS_BACKEND = False
# Global Match State for live 2-player sessions
MATCH_STATE = {
"topic": "AI will surpass human capabilities in software engineering within 5 years.",
"max_rounds": 2,
"current_round": 1,
"current_turn": "Proposition", # Proposition -> Opposition
"p1_name": "Debater 1 (Proposition)",
"p2_name": "Debater 2 (Opposition)",
"p1_scores": [],
"p2_scores": [],
"p1_claims": [],
"p2_claims": [],
"topic_embedding": None,
"transcript": [],
"is_finished": False
}
def _get_pipeline_models():
"""Lazily load NLP models."""
from pipeline_a_embedding import get_model as get_embed_model, cosine_similarity
from pipeline_d_nli import get_nli_model
return get_embed_model, cosine_similarity, get_nli_model
@spaces.GPU
def start_match(topic: str, rounds: int, p1_name: str, p2_name: str):
"""Initializes a new debate session and embeds the topic on ZeroGPU."""
global MATCH_STATE
topic_clean = topic.strip() or "AI will surpass human debate capability within 5 years."
rounds_val = int(rounds) if rounds else 2
p1 = p1_name.strip() or "Debater 1 (Proposition)"
p2 = p2_name.strip() or "Debater 2 (Opposition)"
topic_emb = None
try:
from pipeline_a_embedding import encode
emb = encode([topic_clean])
if len(emb) > 0:
topic_emb = emb[0]
except Exception as err:
print("[Embedding Topic Error]", err)
MATCH_STATE = {
"topic": topic_clean,
"max_rounds": rounds_val,
"current_round": 1,
"current_turn": "Proposition",
"p1_name": p1,
"p2_name": p2,
"p1_scores": [],
"p2_scores": [],
"p1_claims": [],
"p2_claims": [],
"topic_embedding": topic_emb,
"transcript": [],
"is_finished": False
}
status_msg = (
f"### 🎯 Match Initialized!\n"
f"- **Topic:** {topic_clean}\n"
f"- **Format:** {rounds_val} Rounds ({rounds_val * 2} Turns Total)\n"
f"- **Debater 1 (Proposition):** {p1}\n"
f"- **Debater 2 (Opposition):** {p2}\n\n"
f"👉 **Turn 1:** Waiting for **{p1}** (Proposition) to present opening argument."
)
return status_msg, "", "", "Round 1 of " + str(rounds_val) + " | Turn: " + p1, "0 — 0"
@spaces.GPU
def evaluate_turn(argument_text: str):
"""
Evaluates a debate turn on ZeroGPU using the full multi-dimensional scoring pipeline:
- Segment claims (Pipeline B)
- Meaning embeddings (Pipeline A: all-mpnet-base-v2)
- Cross-Encoder NLI (Pipeline D: nli-deberta-v3-small)
- Live evidence verification (Pipeline E: DuckDuckGo / Wikipedia)
- Deterministic 5-signal scoring (20% Rebuttal, 20% Reasoning, 20% Evidence, 15% Relevance, 15% Clarity, 10% Stance)
"""
global MATCH_STATE
if MATCH_STATE["is_finished"]:
return "⚠️ This debate match is already finished! Click 'Start New Match' to begin again.", "", "", "", ""
text = argument_text.strip()
if not text:
return "⚠️ Please enter a substantive argument before submitting.", "", "", "", ""
current_player_side = MATCH_STATE["current_turn"]
is_p1 = (current_player_side == "Proposition")
player_name = MATCH_STATE["p1_name"] if is_p1 else MATCH_STATE["p2_name"]
player_id = "p1" if is_p1 else "p2"
opponent_claims = MATCH_STATE["p2_claims"] if is_p1 else MATCH_STATE["p1_claims"]
# 1. Segment claims
claims = []
try:
from pipeline_b_segmentation import segment_response
claims = segment_response(text, player_id=player_id, turn_id=f"t_{len(MATCH_STATE['transcript'])+1}")
except Exception as e:
print("[Claim Segmentation Fallback]", e)
# 2. Encode claims with mpnet
claim_embs = []
try:
from pipeline_a_embedding import encode
if claims:
embs = encode([c.text for c in claims])
claim_embs = [embs[i] for i in range(len(claims))]
except Exception as e:
print("[Embedding Fallback]", e)
# 3. Cross-encoder NLI and rebuttal check against opponent
relations = []
addressed_count = 0
try:
from pipeline_d_nli import classify_pair, classify_batch
from models import RelationRecord, ArgumentRelation
for i, c in enumerate(claims):
for op in opponent_claims[-4:]: # evaluate against recent opponent claims
verdict, conf = classify_pair(c.text, op.text)
if verdict in ("CONTRADICTION", "ENTAILMENT"):
addressed_count += 1
rel = ArgumentRelation.REBUTTAL if verdict == "CONTRADICTION" else ArgumentRelation.SUPPORT
relations.append(RelationRecord(
source_claim_id=c.claim_id,
target_claim_id=op.claim_id,
relation=rel,
confidence=conf,
reasoning=f"NLI {verdict} against opponent claim '{op.text[:40]}...'"
))
except Exception as e:
print("[NLI Relations Fallback]", e)
# 4. Compute deterministic score
from scoring import compute_turn_score
turn_score = compute_turn_score(
turn_id=f"turn_{len(MATCH_STATE['transcript'])+1}",
player_id=player_id,
round_number=MATCH_STATE["current_round"],
response_text=text,
claims=claims,
claim_embeddings=claim_embs,
topic_embedding=MATCH_STATE["topic_embedding"],
relations=relations,
repetition_classes=[],
addressed_opponent_claims_count=addressed_count,
player_side=current_player_side.lower()
)
# Store turn score
if is_p1:
MATCH_STATE["p1_scores"].append(turn_score)
MATCH_STATE["p1_claims"].extend(claims)
else:
MATCH_STATE["p2_scores"].append(turn_score)
MATCH_STATE["p2_claims"].extend(claims)
# Update transcript
MATCH_STATE["transcript"].append({
"round": MATCH_STATE["current_round"],
"side": current_player_side,
"name": player_name,
"text": text,
"score": round(turn_score.weighted_total * 10, 1),
"rebuttal": round(turn_score.rebuttal_score * 10, 1),
"reasoning": round(turn_score.reasoning_score * 10, 1),
"evidence": round(turn_score.evidence_score * 10, 1),
"relevance": round(turn_score.relevance_score * 10, 1),
"clarity": round(turn_score.clarity_score * 10, 1)
})
# Format Turn Breakdown
breakdown_text = (
f"### 📊 Turn Assessment — {player_name} ({current_player_side})\n"
f"**Overall Turn Score:** `{round(turn_score.weighted_total * 10, 1)} / 10.0`\n\n"
f"| Dimension | Weight | Score | Evaluation Insight |\n"
f"| :--- | :--- | :--- | :--- |\n"
f"| ⚔️ **Counterargument / Rebuttal** | 20% | `{round(turn_score.rebuttal_score * 10, 1)}/10` | {addressed_count} opponent claims addressed directly |\n"
f"| 🧠 **Logical Reasoning** | 20% | `{round(turn_score.reasoning_score * 10, 1)}/10` | Causal logic & premise connectors |\n"
f"| 📚 **Evidence & Factual Backing** | 20% | `{round(turn_score.evidence_score * 10, 1)}/10` | Verifiable empirical claim check |\n"
f"| 🎯 **Topic Relevance** | 15% | `{round(turn_score.relevance_score * 10, 1)}/10` | Cosine similarity to motion topic |\n"
f"| ✍️ **Clarity & Structure** | 15% | `{round(turn_score.clarity_score * 10, 1)}/10` | Fluency and sentence structure |\n"
f"| 🛡️ **Stance Consistency** | 10% | `{round(turn_score.stance_score * 10, 1)}/10` | Aligned with {current_player_side} motion |\n"
)
# Calculate cumulative points
p1_total = sum(s.weighted_total * 10 for s in MATCH_STATE["p1_scores"])
p2_total = sum(s.weighted_total * 10 for s in MATCH_STATE["p2_scores"])
leaderboard_str = f"🏆 {MATCH_STATE['p1_name']}: {p1_total:.1f} pts | {MATCH_STATE['p2_name']}: {p2_total:.1f} pts"
# Advance turns
if is_p1:
MATCH_STATE["current_turn"] = "Opposition"
next_speaker = MATCH_STATE["p2_name"]
round_info = f"Round {MATCH_STATE['current_round']} of {MATCH_STATE['max_rounds']} | Next: {next_speaker} (Opposition)"
else:
MATCH_STATE["current_turn"] = "Proposition"
MATCH_STATE["current_round"] += 1
if MATCH_STATE["current_round"] > MATCH_STATE["max_rounds"]:
MATCH_STATE["is_finished"] = True
winner = MATCH_STATE["p1_name"] if p1_total > p2_total else MATCH_STATE["p2_name"]
if abs(p1_total - p2_total) < 0.5:
winner = "Tie / Draw"
round_info = f"🏁 Debate Complete! Winner: {winner}"
breakdown_text += f"\n\n---\n## 🏆 FINAL RESULT: **{winner}** Wins the Match!\n"
breakdown_text += f"**Final Tally:** {MATCH_STATE['p1_name']} ({p1_total:.1f}) vs {MATCH_STATE['p2_name']} ({p2_total:.1f})\n"
else:
next_speaker = MATCH_STATE["p1_name"]
round_info = f"Round {MATCH_STATE['current_round']} of {MATCH_STATE['max_rounds']} | Next: {next_speaker} (Proposition)"
# Format transcript
transcript_md = "### 📜 Live Debate Transcript & Arguments\n\n"
for item in MATCH_STATE["transcript"]:
tag = "🔴 [Proposition]" if item["side"] == "Proposition" else "🔵 [Opposition]"
transcript_md += f"**{tag} {item['name']} (Round {item['round']}) — Score: {item['score']}/10**\n\n"
transcript_md += f"> {item['text']}\n\n"
transcript_md += f"*Rebuttal: {item['rebuttal']} | Reasoning: {item['reasoning']} | Evidence: {item['evidence']}*\n\n---\n\n"
return breakdown_text, transcript_md, "", round_info, leaderboard_str
# Build Interactive Gradio UI
with gr.Blocks(title="Clash of Minds — AI Debate Arena") as demo:
gr.Markdown("# ⚔️ Clash of Minds — Live 2-Player AI Debate Judge")
gr.Markdown("Real-time NLP Debate Evaluation System — CSES Machine Learning Exhibition, NIT Warangal.")
with gr.Tab("⚙️ 1. Match Setup"):
with gr.Row():
topic_box = gr.Textbox(
label="Debate Motion / Topic",
value="Artificial Intelligence will replace human software engineers within 5 years.",
scale=3
)
rounds_slider = gr.Slider(minimum=1, maximum=5, value=2, step=1, label="Debate Rounds", scale=1)
with gr.Row():
p1_box = gr.Textbox(label="Debater 1 Name (Proposition)", value="Debater 1 (Alice)")
p2_box = gr.Textbox(label="Debater 2 Name (Opposition)", value="Debater 2 (Bob)")
start_btn = gr.Button("🚀 Initialize Debate Match", variant="primary")
with gr.Tab("🎙️ 2. Live Debate Arena"):
with gr.Row():
match_status_badge = gr.Markdown("👉 Initialize match in Tab 1 to begin.")
score_badge = gr.Markdown("🏆 Score: 0 — 0")
current_turn_badge = gr.Textbox(label="Current Turn", value="Not Started", interactive=False)
argument_input = gr.Textbox(
label="Speech / Argument Input",
placeholder="Type or dictate your argument for this turn...",
lines=5
)
submit_turn_btn = gr.Button("⚖️ Submit Turn for AI Evaluation", variant="primary")
with gr.Row():
verdict_card = gr.Markdown("Turn evaluation score and insights will appear here.")
transcript_card = gr.Markdown("Transcript will appear here as turns progress.")
start_btn.click(
fn=start_match,
inputs=[topic_box, rounds_slider, p1_box, p2_box],
outputs=[match_status_badge, verdict_card, transcript_card, current_turn_badge, score_badge]
)
submit_turn_btn.click(
fn=evaluate_turn,
inputs=[argument_input],
outputs=[verdict_card, transcript_card, argument_input, current_turn_badge, score_badge]
)
if __name__ == "__main__":
demo.launch()
|