CWM-Coder724 commited on
Commit ·
914936c
1
Parent(s): 22d701f
Deploy full Clash of Minds 2-player arena to Hugging Face ZeroGPU
Browse files
app.py
CHANGED
|
@@ -1,28 +1,294 @@
|
|
| 1 |
import spaces
|
| 2 |
import gradio as gr
|
| 3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
@spaces.GPU
|
| 6 |
-
def
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 3 |
import os
|
| 4 |
+
import sys
|
| 5 |
+
import time
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
# Add backend directory to Python path
|
| 9 |
+
backend_dir = os.path.join(os.path.dirname(__file__), "backend")
|
| 10 |
+
if backend_dir not in sys.path:
|
| 11 |
+
sys.path.insert(0, backend_dir)
|
| 12 |
+
|
| 13 |
+
# Import models and core evaluation pipelines
|
| 14 |
+
try:
|
| 15 |
+
from pipeline_b_segmentation import segment_response, is_fact_checkable
|
| 16 |
+
from pipeline_e_rag import verify_claim
|
| 17 |
+
from scoring import compute_turn_score, aggregate_final_scores, generate_final_analysis
|
| 18 |
+
HAS_BACKEND = True
|
| 19 |
+
except Exception as e:
|
| 20 |
+
print("[HF Backend Import Warning]", e)
|
| 21 |
+
HAS_BACKEND = False
|
| 22 |
+
|
| 23 |
+
# Global Match State for live 2-player sessions
|
| 24 |
+
MATCH_STATE = {
|
| 25 |
+
"topic": "AI will surpass human capabilities in software engineering within 5 years.",
|
| 26 |
+
"max_rounds": 2,
|
| 27 |
+
"current_round": 1,
|
| 28 |
+
"current_turn": "Proposition", # Proposition -> Opposition
|
| 29 |
+
"p1_name": "Debater 1 (Proposition)",
|
| 30 |
+
"p2_name": "Debater 2 (Opposition)",
|
| 31 |
+
"p1_scores": [],
|
| 32 |
+
"p2_scores": [],
|
| 33 |
+
"p1_claims": [],
|
| 34 |
+
"p2_claims": [],
|
| 35 |
+
"topic_embedding": None,
|
| 36 |
+
"transcript": [],
|
| 37 |
+
"is_finished": False
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _get_pipeline_models():
|
| 42 |
+
"""Lazily load NLP models."""
|
| 43 |
+
from pipeline_a_embedding import get_model as get_embed_model, cosine_similarity
|
| 44 |
+
from pipeline_d_nli import get_nli_model
|
| 45 |
+
return get_embed_model, cosine_similarity, get_nli_model
|
| 46 |
+
|
| 47 |
|
| 48 |
@spaces.GPU
|
| 49 |
+
def start_match(topic: str, rounds: int, p1_name: str, p2_name: str):
|
| 50 |
+
"""Initializes a new debate session and embeds the topic on ZeroGPU."""
|
| 51 |
+
global MATCH_STATE
|
| 52 |
+
topic_clean = topic.strip() or "AI will surpass human debate capability within 5 years."
|
| 53 |
+
rounds_val = int(rounds) if rounds else 2
|
| 54 |
+
p1 = p1_name.strip() or "Debater 1 (Proposition)"
|
| 55 |
+
p2 = p2_name.strip() or "Debater 2 (Opposition)"
|
| 56 |
+
|
| 57 |
+
topic_emb = None
|
| 58 |
+
try:
|
| 59 |
+
from pipeline_a_embedding import encode
|
| 60 |
+
emb = encode([topic_clean])
|
| 61 |
+
if len(emb) > 0:
|
| 62 |
+
topic_emb = emb[0]
|
| 63 |
+
except Exception as err:
|
| 64 |
+
print("[Embedding Topic Error]", err)
|
| 65 |
+
|
| 66 |
+
MATCH_STATE = {
|
| 67 |
+
"topic": topic_clean,
|
| 68 |
+
"max_rounds": rounds_val,
|
| 69 |
+
"current_round": 1,
|
| 70 |
+
"current_turn": "Proposition",
|
| 71 |
+
"p1_name": p1,
|
| 72 |
+
"p2_name": p2,
|
| 73 |
+
"p1_scores": [],
|
| 74 |
+
"p2_scores": [],
|
| 75 |
+
"p1_claims": [],
|
| 76 |
+
"p2_claims": [],
|
| 77 |
+
"topic_embedding": topic_emb,
|
| 78 |
+
"transcript": [],
|
| 79 |
+
"is_finished": False
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
status_msg = (
|
| 83 |
+
f"### 🎯 Match Initialized!\n"
|
| 84 |
+
f"- **Topic:** {topic_clean}\n"
|
| 85 |
+
f"- **Format:** {rounds_val} Rounds ({rounds_val * 2} Turns Total)\n"
|
| 86 |
+
f"- **Debater 1 (Proposition):** {p1}\n"
|
| 87 |
+
f"- **Debater 2 (Opposition):** {p2}\n\n"
|
| 88 |
+
f"👉 **Turn 1:** Waiting for **{p1}** (Proposition) to present opening argument."
|
| 89 |
+
)
|
| 90 |
+
return status_msg, "", "", "Round 1 of " + str(rounds_val) + " | Turn: " + p1, "0 — 0"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@spaces.GPU
|
| 94 |
+
def evaluate_turn(argument_text: str):
|
| 95 |
+
"""
|
| 96 |
+
Evaluates a debate turn on ZeroGPU using the full multi-dimensional scoring pipeline:
|
| 97 |
+
- Segment claims (Pipeline B)
|
| 98 |
+
- Meaning embeddings (Pipeline A: all-mpnet-base-v2)
|
| 99 |
+
- Cross-Encoder NLI (Pipeline D: nli-deberta-v3-small)
|
| 100 |
+
- Live evidence verification (Pipeline E: DuckDuckGo / Wikipedia)
|
| 101 |
+
- Deterministic 5-signal scoring (20% Rebuttal, 20% Reasoning, 20% Evidence, 15% Relevance, 15% Clarity, 10% Stance)
|
| 102 |
+
"""
|
| 103 |
+
global MATCH_STATE
|
| 104 |
+
|
| 105 |
+
if MATCH_STATE["is_finished"]:
|
| 106 |
+
return "⚠️ This debate match is already finished! Click 'Start New Match' to begin again.", "", "", "", ""
|
| 107 |
+
|
| 108 |
+
text = argument_text.strip()
|
| 109 |
+
if not text:
|
| 110 |
+
return "⚠️ Please enter a substantive argument before submitting.", "", "", "", ""
|
| 111 |
+
|
| 112 |
+
current_player_side = MATCH_STATE["current_turn"]
|
| 113 |
+
is_p1 = (current_player_side == "Proposition")
|
| 114 |
+
player_name = MATCH_STATE["p1_name"] if is_p1 else MATCH_STATE["p2_name"]
|
| 115 |
+
player_id = "p1" if is_p1 else "p2"
|
| 116 |
+
opponent_claims = MATCH_STATE["p2_claims"] if is_p1 else MATCH_STATE["p1_claims"]
|
| 117 |
+
|
| 118 |
+
# 1. Segment claims
|
| 119 |
+
claims = []
|
| 120 |
+
try:
|
| 121 |
+
from pipeline_b_segmentation import segment_response
|
| 122 |
+
claims = segment_response(text, player_id=player_id, turn_id=f"t_{len(MATCH_STATE['transcript'])+1}")
|
| 123 |
+
except Exception as e:
|
| 124 |
+
print("[Claim Segmentation Fallback]", e)
|
| 125 |
+
|
| 126 |
+
# 2. Encode claims with mpnet
|
| 127 |
+
claim_embs = []
|
| 128 |
+
try:
|
| 129 |
+
from pipeline_a_embedding import encode
|
| 130 |
+
if claims:
|
| 131 |
+
embs = encode([c.text for c in claims])
|
| 132 |
+
claim_embs = [embs[i] for i in range(len(claims))]
|
| 133 |
+
except Exception as e:
|
| 134 |
+
print("[Embedding Fallback]", e)
|
| 135 |
+
|
| 136 |
+
# 3. Cross-encoder NLI and rebuttal check against opponent
|
| 137 |
+
relations = []
|
| 138 |
+
addressed_count = 0
|
| 139 |
+
try:
|
| 140 |
+
from pipeline_d_nli import classify_pair, classify_batch
|
| 141 |
+
from models import RelationRecord, ArgumentRelation
|
| 142 |
+
for i, c in enumerate(claims):
|
| 143 |
+
for op in opponent_claims[-4:]: # evaluate against recent opponent claims
|
| 144 |
+
verdict, conf = classify_pair(c.text, op.text)
|
| 145 |
+
if verdict in ("CONTRADICTION", "ENTAILMENT"):
|
| 146 |
+
addressed_count += 1
|
| 147 |
+
rel = ArgumentRelation.REBUTTAL if verdict == "CONTRADICTION" else ArgumentRelation.SUPPORT
|
| 148 |
+
relations.append(RelationRecord(
|
| 149 |
+
source_claim_id=c.claim_id,
|
| 150 |
+
target_claim_id=op.claim_id,
|
| 151 |
+
relation=rel,
|
| 152 |
+
confidence=conf,
|
| 153 |
+
reasoning=f"NLI {verdict} against opponent claim '{op.text[:40]}...'"
|
| 154 |
+
))
|
| 155 |
+
except Exception as e:
|
| 156 |
+
print("[NLI Relations Fallback]", e)
|
| 157 |
+
|
| 158 |
+
# 4. Compute deterministic score
|
| 159 |
+
from scoring import compute_turn_score
|
| 160 |
+
turn_score = compute_turn_score(
|
| 161 |
+
turn_id=f"turn_{len(MATCH_STATE['transcript'])+1}",
|
| 162 |
+
player_id=player_id,
|
| 163 |
+
round_number=MATCH_STATE["current_round"],
|
| 164 |
+
response_text=text,
|
| 165 |
+
claims=claims,
|
| 166 |
+
claim_embeddings=claim_embs,
|
| 167 |
+
topic_embedding=MATCH_STATE["topic_embedding"],
|
| 168 |
+
relations=relations,
|
| 169 |
+
repetition_classes=[],
|
| 170 |
+
addressed_opponent_claims_count=addressed_count,
|
| 171 |
+
player_side=current_player_side.lower()
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# Store turn score
|
| 175 |
+
if is_p1:
|
| 176 |
+
MATCH_STATE["p1_scores"].append(turn_score)
|
| 177 |
+
MATCH_STATE["p1_claims"].extend(claims)
|
| 178 |
+
else:
|
| 179 |
+
MATCH_STATE["p2_scores"].append(turn_score)
|
| 180 |
+
MATCH_STATE["p2_claims"].extend(claims)
|
| 181 |
+
|
| 182 |
+
# Update transcript
|
| 183 |
+
MATCH_STATE["transcript"].append({
|
| 184 |
+
"round": MATCH_STATE["current_round"],
|
| 185 |
+
"side": current_player_side,
|
| 186 |
+
"name": player_name,
|
| 187 |
+
"text": text,
|
| 188 |
+
"score": round(turn_score.weighted_total * 10, 1),
|
| 189 |
+
"rebuttal": round(turn_score.rebuttal_score * 10, 1),
|
| 190 |
+
"reasoning": round(turn_score.reasoning_score * 10, 1),
|
| 191 |
+
"evidence": round(turn_score.evidence_score * 10, 1),
|
| 192 |
+
"relevance": round(turn_score.relevance_score * 10, 1),
|
| 193 |
+
"clarity": round(turn_score.clarity_score * 10, 1)
|
| 194 |
+
})
|
| 195 |
+
|
| 196 |
+
# Format Turn Breakdown
|
| 197 |
+
breakdown_text = (
|
| 198 |
+
f"### 📊 Turn Assessment — {player_name} ({current_player_side})\n"
|
| 199 |
+
f"**Overall Turn Score:** `{round(turn_score.weighted_total * 10, 1)} / 10.0`\n\n"
|
| 200 |
+
f"| Dimension | Weight | Score | Evaluation Insight |\n"
|
| 201 |
+
f"| :--- | :--- | :--- | :--- |\n"
|
| 202 |
+
f"| ⚔️ **Counterargument / Rebuttal** | 20% | `{round(turn_score.rebuttal_score * 10, 1)}/10` | {addressed_count} opponent claims addressed directly |\n"
|
| 203 |
+
f"| 🧠 **Logical Reasoning** | 20% | `{round(turn_score.reasoning_score * 10, 1)}/10` | Causal logic & premise connectors |\n"
|
| 204 |
+
f"| 📚 **Evidence & Factual Backing** | 20% | `{round(turn_score.evidence_score * 10, 1)}/10` | Verifiable empirical claim check |\n"
|
| 205 |
+
f"| 🎯 **Topic Relevance** | 15% | `{round(turn_score.relevance_score * 10, 1)}/10` | Cosine similarity to motion topic |\n"
|
| 206 |
+
f"| ✍️ **Clarity & Structure** | 15% | `{round(turn_score.clarity_score * 10, 1)}/10` | Fluency and sentence structure |\n"
|
| 207 |
+
f"| 🛡️ **Stance Consistency** | 10% | `{round(turn_score.stance_score * 10, 1)}/10` | Aligned with {current_player_side} motion |\n"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Calculate cumulative points
|
| 211 |
+
p1_total = sum(s.weighted_total * 10 for s in MATCH_STATE["p1_scores"])
|
| 212 |
+
p2_total = sum(s.weighted_total * 10 for s in MATCH_STATE["p2_scores"])
|
| 213 |
+
leaderboard_str = f"🏆 {MATCH_STATE['p1_name']}: {p1_total:.1f} pts | {MATCH_STATE['p2_name']}: {p2_total:.1f} pts"
|
| 214 |
+
|
| 215 |
+
# Advance turns
|
| 216 |
+
if is_p1:
|
| 217 |
+
MATCH_STATE["current_turn"] = "Opposition"
|
| 218 |
+
next_speaker = MATCH_STATE["p2_name"]
|
| 219 |
+
round_info = f"Round {MATCH_STATE['current_round']} of {MATCH_STATE['max_rounds']} | Next: {next_speaker} (Opposition)"
|
| 220 |
+
else:
|
| 221 |
+
MATCH_STATE["current_turn"] = "Proposition"
|
| 222 |
+
MATCH_STATE["current_round"] += 1
|
| 223 |
+
if MATCH_STATE["current_round"] > MATCH_STATE["max_rounds"]:
|
| 224 |
+
MATCH_STATE["is_finished"] = True
|
| 225 |
+
winner = MATCH_STATE["p1_name"] if p1_total > p2_total else MATCH_STATE["p2_name"]
|
| 226 |
+
if abs(p1_total - p2_total) < 0.5:
|
| 227 |
+
winner = "Tie / Draw"
|
| 228 |
+
round_info = f"🏁 Debate Complete! Winner: {winner}"
|
| 229 |
+
breakdown_text += f"\n\n---\n## 🏆 FINAL RESULT: **{winner}** Wins the Match!\n"
|
| 230 |
+
breakdown_text += f"**Final Tally:** {MATCH_STATE['p1_name']} ({p1_total:.1f}) vs {MATCH_STATE['p2_name']} ({p2_total:.1f})\n"
|
| 231 |
+
else:
|
| 232 |
+
next_speaker = MATCH_STATE["p1_name"]
|
| 233 |
+
round_info = f"Round {MATCH_STATE['current_round']} of {MATCH_STATE['max_rounds']} | Next: {next_speaker} (Proposition)"
|
| 234 |
+
|
| 235 |
+
# Format transcript
|
| 236 |
+
transcript_md = "### 📜 Live Debate Transcript & Arguments\n\n"
|
| 237 |
+
for item in MATCH_STATE["transcript"]:
|
| 238 |
+
tag = "🔴 [Proposition]" if item["side"] == "Proposition" else "🔵 [Opposition]"
|
| 239 |
+
transcript_md += f"**{tag} {item['name']} (Round {item['round']}) — Score: {item['score']}/10**\n\n"
|
| 240 |
+
transcript_md += f"> {item['text']}\n\n"
|
| 241 |
+
transcript_md += f"*Rebuttal: {item['rebuttal']} | Reasoning: {item['reasoning']} | Evidence: {item['evidence']}*\n\n---\n\n"
|
| 242 |
+
|
| 243 |
+
return breakdown_text, transcript_md, "", round_info, leaderboard_str
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# Build Interactive Gradio UI
|
| 247 |
+
with gr.Blocks(title="Clash of Minds — AI Debate Arena") as demo:
|
| 248 |
+
gr.Markdown("# ⚔️ Clash of Minds — Live 2-Player AI Debate Judge")
|
| 249 |
+
gr.Markdown("Real-time NLP Debate Evaluation System — CSES Machine Learning Exhibition, NIT Warangal.")
|
| 250 |
+
|
| 251 |
+
with gr.Tab("⚙️ 1. Match Setup"):
|
| 252 |
+
with gr.Row():
|
| 253 |
+
topic_box = gr.Textbox(
|
| 254 |
+
label="Debate Motion / Topic",
|
| 255 |
+
value="Artificial Intelligence will replace human software engineers within 5 years.",
|
| 256 |
+
scale=3
|
| 257 |
+
)
|
| 258 |
+
rounds_slider = gr.Slider(minimum=1, maximum=5, value=2, step=1, label="Debate Rounds", scale=1)
|
| 259 |
+
with gr.Row():
|
| 260 |
+
p1_box = gr.Textbox(label="Debater 1 Name (Proposition)", value="Debater 1 (Alice)")
|
| 261 |
+
p2_box = gr.Textbox(label="Debater 2 Name (Opposition)", value="Debater 2 (Bob)")
|
| 262 |
+
start_btn = gr.Button("🚀 Initialize Debate Match", variant="primary")
|
| 263 |
+
|
| 264 |
+
with gr.Tab("🎙️ 2. Live Debate Arena"):
|
| 265 |
+
with gr.Row():
|
| 266 |
+
match_status_badge = gr.Markdown("👉 Initialize match in Tab 1 to begin.")
|
| 267 |
+
score_badge = gr.Markdown("🏆 Score: 0 — 0")
|
| 268 |
+
|
| 269 |
+
current_turn_badge = gr.Textbox(label="Current Turn", value="Not Started", interactive=False)
|
| 270 |
+
argument_input = gr.Textbox(
|
| 271 |
+
label="Speech / Argument Input",
|
| 272 |
+
placeholder="Type or dictate your argument for this turn...",
|
| 273 |
+
lines=5
|
| 274 |
+
)
|
| 275 |
+
submit_turn_btn = gr.Button("⚖️ Submit Turn for AI Evaluation", variant="primary")
|
| 276 |
+
|
| 277 |
+
with gr.Row():
|
| 278 |
+
verdict_card = gr.Markdown("Turn evaluation score and insights will appear here.")
|
| 279 |
+
transcript_card = gr.Markdown("Transcript will appear here as turns progress.")
|
| 280 |
+
|
| 281 |
+
start_btn.click(
|
| 282 |
+
fn=start_match,
|
| 283 |
+
inputs=[topic_box, rounds_slider, p1_box, p2_box],
|
| 284 |
+
outputs=[match_status_badge, verdict_card, transcript_card, current_turn_badge, score_badge]
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
submit_turn_btn.click(
|
| 288 |
+
fn=evaluate_turn,
|
| 289 |
+
inputs=[argument_input],
|
| 290 |
+
outputs=[verdict_card, transcript_card, argument_input, current_turn_badge, score_badge]
|
| 291 |
+
)
|
| 292 |
|
| 293 |
if __name__ == "__main__":
|
| 294 |
demo.launch()
|