Upload run_eval.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252#!/usr/bin/env python3"""Turing Test Judge Benchmark — Evaluation Script================================================Given a dataset of paired dialogues (A and B), predict which is the human-human dialogue.
SETUP-----1. Install core dependencies: pip install pandas tqdm datasets
2. Install whatever library your model needs (see examples below).
3. Fill in the `predict()` function with your model.
4. Run: # Load from HuggingFace (default) python run_eval.py
# Load from a local CSV python run_eval.py --input data.csv
# Save output to a custom path python run_eval.py --output my_predictions.csv
OUTPUT FORMAT-------------A single-column CSV: who_is_human ∈ {"A", "B"}Ready to submit to the leaderboard."""
import argparseimport reimport sysimport time
import pandas as pdfrom tqdm import tqdm
SYSTEM_PROMPT = """\You are an expert judge in a Turing Test experiment.You will be shown two conversation transcripts, labelled A and B.One is a conversation between two humans.The other is a conversation between a human and an AI assistant.
Your task: decide which transcript is the human-human conversation.
Rules:- Reply with ONLY the single letter A or B — nothing else.- Do not explain your reasoning."""
USER_TEMPLATE = """\=== Transcript A ==={dialogueA}
=== Transcript B ==={dialogueB}
Which transcript is the human-human conversation? Answer A or B."""
# ══════════════════════════════════════════════════════════════════════════════# DEFINE YOUR MODEL HERE## Fill in the predict() function below. It receives the two dialogue# transcripts as plain strings and must return either "A" or "B".## A few copy-paste starter examples are included as comments beneath # the function.# ══════════════════════════════════════════════════════════════════════════════
def predict(dialogueA: str, dialogueB: str) -> str: """ Return "A" if dialogueA is the human-human conversation, "B" otherwise.
Replace the body of this function with your own model call. """ raise NotImplementedError( "Please fill in the predict() function with your model. " "See the examples in the comments below." )
# ──────────────────────────────────────────────────────────────────────────────# EXAMPLE A — OpenAI-compatible API (OpenAI, Together, Groq, Ollama, etc.)# Works with any provider that follows the OpenAI chat completion format.## pip install openai## import os# from openai import OpenAI## client = OpenAI(# api_key=os.environ["OPENAI_API_KEY"], # or your provider's key# base_url="https://api.openai.com/v1", # swap for Groq/Together/Ollama etc.# )## def predict(dialogueA, dialogueB):# prompt = USER_TEMPLATE.format(dialogueA=dialogueA, dialogueB=dialogueB)# resp = client.chat.completions.create(# model="gpt-4o", # swap for any model name# messages=[# {"role": "system", "content": SYSTEM_PROMPT},# {"role": "user", "content": prompt},# ],# max_tokens=5,# temperature=0,# )# return parse_answer(resp.choices[0].message.content)# ──────────────────────────────────────────────────────────────────────────────
# ──────────────────────────────────────────────────────────────────────────────# EXAMPLE B — Hugging Face transformers (local model)## pip install transformers torch## from transformers import pipeline## pipe = pipeline("text-generation", model="mistralai/Mistral-7B-Instruct-v0.2")## def predict(dialogueA, dialogueB):# prompt = SYSTEM_PROMPT + "\n\n" + USER_TEMPLATE.format(# dialogueA=dialogueA, dialogueB=dialogueB# )# out = pipe(prompt, max_new_tokens=5, temperature=0.0)[0]["generated_text"]# return parse_answer(out)# ──────────────────────────────────────────────────────────────────────────────
# ──────────────────���───────────────────────────────────────────────────────────# EXAMPLE C — Ollama (local server, any model pulled via `ollama pull`)## pip install ollama## import ollama## def predict(dialogueA, dialogueB):# prompt = USER_TEMPLATE.format(dialogueA=dialogueA, dialogueB=dialogueB)# resp = ollama.chat(# model="llama3",# messages=[# {"role": "system", "content": SYSTEM_PROMPT},# {"role": "user", "content": prompt},# ],# )# return parse_answer(resp["message"]["content"])# ──────────────────────────────────────────────────────────────────────────────
# ══════════════════════════════════════════════════════════════════════════════# Helper — parse "A" / "B" out of whatever text the model returns.# You can call this from inside your predict() function if useful.# ══════════════════════════════════════════════════════════════════════════════
def parse_answer(text: str) -> str: """Extract 'A' or 'B' from model output. Defaults to 'A' if unclear.""" match = re.search(r"\b([AB])\b", text.strip().upper()) if match: return match.group(1) print(f" ⚠ Could not parse answer from: {text!r} — defaulting to 'A'") return "A"
# ══════════════════════════════════════════════════════════════════════════════# Internals — no need to edit below this line# ══════════════════════════════════════════════════════════════════════════════
HF_DATASET_NAME = "/roc-hci/Turing-Bench"HF_SPLIT = "train"
def load_data(input_path: str | None) -> pd.DataFrame: if input_path: print(f"Loading data from local file: {input_path}") df = pd.read_csv(input_path) else: print(f"Loading data from HuggingFace: {HF_DATASET_NAME} (split={HF_SPLIT})") try: from datasets import load_dataset except ImportError: sys.exit("datasets package not found. Run: pip install datasets") ds = load_dataset( "csv", data_files="hf://datasets/roc-hci/Turing-Bench/turing_bench_public.csv", split="train" ) df = ds.to_pandas()
missing = {"dialogueA", "dialogueB"} - set(df.columns) if missing: sys.exit(f"Input data is missing required columns: {missing}")
return df
def main(): parser = argparse.ArgumentParser( description="Turing Test Judge Benchmark — generate predictions with your model." ) parser.add_argument( "--input", default=None, help="Path to a local CSV file. If omitted, data is loaded from HuggingFace.", ) parser.add_argument( "--output", default="predictions.csv", help="Output CSV file path (default: predictions.csv).", ) parser.add_argument( "--delay", type=float, default=0.0, help="Seconds to wait between calls (useful for rate-limited APIs, default: 0).", ) args = parser.parse_args()
df = load_data(args.input) print(f"Loaded {len(df)} examples.\n")
results = [] errors = 0
for i, row in tqdm(df.iterrows(), total=len(df), desc="Running predictions"): try: pred = predict(str(row["dialogueA"]), str(row["dialogueB"])) if pred not in ("A", "B"): raise ValueError(f"predict() returned {pred!r} — must be 'A' or 'B'") except NotImplementedError: sys.exit( "\n✗ predict() is not implemented yet.\n" " Open this script and fill in the predict() function with your model." ) except Exception as exc: print(f"\n ✗ Error on row {i}: {exc} — defaulting to 'A'") pred = "A" errors += 1
results.append(pred)
if args.delay > 0: time.sleep(args.delay)
out_df = pd.DataFrame({"who_is_human": results}) out_df.to_csv(args.output, index=False)
print(f"\n✓ Predictions saved to: {args.output}") print(f" Total : {len(results)} | A: {results.count('A')} | B: {results.count('B')}") if errors: print(f" ⚠ {errors} row(s) errored and defaulted to 'A'") print("\nNext step: submit your predictions CSV to the leaderboard at https://huggingface.co/spaces/roc-hci/Turing-Bench-Leaderboard")
if __name__ == "__main__": main()run_eval.pyAdded+252