Download app.py from Codeitnow/Debate: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/spaces/Codeitnow/Debate/resolve/main/app.py
- Command line
-
hf download hf://spaces/Codeitnow/Debate/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Codeitnow/Debate/resolve/main/app.py
12.7 kB
| 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 | |
| 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" | |
| 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() | |