tempbench / code /resolve_labels.py
Guen's picture
Add the deterministic construction pipeline
210b340 verified
Raw
History Blame Contribute Delete
15.1 kB
"""
TempBench — Wikidata Label Resolver
=======================================
Converts Wikidata QIDs and PIDs in benchmark JSONL files into human-readable
English labels, turning machine-generated questions like:
"Q230104's P17 in 1929 was?"
into:
"What country was Poland in 1929?" (after full template rewrite)
or at minimum: "Danzig's country in 1929 was?"
Two modes:
1. API mode (default): fetches labels from Wikidata REST API in batches of 50.
Requires internet access; rate-limited politely (~1 req/s).
2. Dump mode (--label_dump): reads from a pre-downloaded TSV label file
(format: QID<TAB>label<TAB>description, one per line).
Faster and offline — use this for production runs.
Label dump can be produced via:
python resolve_labels.py --collect_ids benchmark.jsonl --id_output ids.txt
# then on a machine with internet:
python resolve_labels.py --fetch_dump ids.txt --dump_output labels.tsv
# then resolve:
python resolve_labels.py --input benchmark.jsonl --label_dump labels.tsv --output benchmark_labelled.jsonl
Usage (quick / API mode):
python resolve_labels.py --input benchmark.jsonl --output benchmark_labelled.jsonl
Usage (offline / dump mode):
python resolve_labels.py --input benchmark.jsonl --label_dump labels.tsv --output benchmark_labelled.jsonl
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import time
from pathlib import Path
from typing import Dict, List, Optional, Set
try:
import urllib.request
import urllib.error
except ImportError:
pass
# ---------------------------------------------------------------------------
# Wikidata API label fetcher
# ---------------------------------------------------------------------------
WIKIDATA_API = "https://www.wikidata.org/w/api.php"
BATCH_SIZE = 50 # Wikidata allows up to 50 IDs per wbgetentities call
RETRY_LIMIT = 3
SLEEP_BETWEEN_BATCHES = 0.5 # seconds — polite rate limiting
def fetch_labels_api(ids: List[str], lang: str = "en") -> Dict[str, str]:
"""
Fetch English labels for a list of Wikidata IDs (Q-IDs and P-IDs) via API.
Returns a dict {id: label}. Missing IDs get empty string.
"""
labels: Dict[str, str] = {}
for i in range(0, len(ids), BATCH_SIZE):
batch = ids[i : i + BATCH_SIZE]
ids_str = "|".join(batch)
url = (
f"{WIKIDATA_API}?action=wbgetentities"
f"&ids={ids_str}"
f"&props=labels"
f"&languages={lang}"
f"&format=json"
)
for attempt in range(RETRY_LIMIT):
try:
req = urllib.request.Request(
url,
headers={"User-Agent": "TempBench/1.0 (research; label resolver)"},
)
with urllib.request.urlopen(req, timeout=15) as resp:
data = json.loads(resp.read().decode("utf-8"))
for qid, entity in data.get("entities", {}).items():
lab = entity.get("labels", {}).get(lang, {}).get("value", "")
labels[qid] = lab
break # success
except Exception as e:
if attempt < RETRY_LIMIT - 1:
time.sleep(2 ** attempt)
else:
print(f"[Warning] API fetch failed for batch {i//BATCH_SIZE}: {e}", file=sys.stderr)
time.sleep(SLEEP_BETWEEN_BATCHES)
print(f" Fetched {min(i + BATCH_SIZE, len(ids))}/{len(ids)} labels...", end="\r", flush=True)
print()
return labels
# ---------------------------------------------------------------------------
# Dump-based label loader (offline mode)
# ---------------------------------------------------------------------------
def load_label_dump(dump_path: str) -> Dict[str, str]:
"""
Load a TSV label dump: QID<TAB>label (one entity per line).
Lines starting with # are comments.
"""
labels: Dict[str, str] = {}
with open(dump_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split("\t", 2)
if len(parts) >= 2:
labels[parts[0]] = parts[1]
print(f"[LabelDump] Loaded {len(labels):,} labels from {dump_path}")
return labels
def save_label_dump(labels: Dict[str, str], output_path: str) -> None:
"""Save fetched labels to a TSV dump for offline re-use."""
with open(output_path, "w", encoding="utf-8") as f:
f.write("# Wikidata label dump for TempBench\n")
f.write("# Format: QID<TAB>label\n")
for qid, label in sorted(labels.items()):
f.write(f"{qid}\t{label}\n")
print(f"[LabelDump] Saved {len(labels):,} labels to {output_path}")
# ---------------------------------------------------------------------------
# ID extraction
# ---------------------------------------------------------------------------
QID_PATTERN = re.compile(r'\b(Q\d+|P\d+)\b')
def extract_ids_from_jsonl(path: str) -> Set[str]:
"""Extract all unique Wikidata QIDs and PIDs from a benchmark JSONL."""
ids: Set[str] = set()
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
ids.update(QID_PATTERN.findall(line))
return ids
# ---------------------------------------------------------------------------
# Question rewriter
# ---------------------------------------------------------------------------
RELATION_TEMPLATES: Dict[str, str] = {
# Standard Wikidata properties → natural language verbs/phrases
"P17": "country",
"P19": "place of birth",
"P20": "place of death",
"P21": "sex or gender",
"P22": "father",
"P25": "mother",
"P26": "spouse",
"P27": "country of citizenship",
"P39": "position held",
"P40": "child",
"P50": "author",
"P57": "director",
"P131": "located in",
"P136": "genre",
"P155": "follows",
"P156": "followed by",
"P159": "headquarters",
"P166": "award received",
"P175": "performer",
"P176": "manufacturer",
"P178": "developer",
"P184": "doctoral advisor",
"P185": "doctoral student",
"P190": "twinned with",
"P276": "location",
"P286": "head coach",
"P355": "subsidiary",
"P361": "part of",
"P413": "position played",
"P452": "industry",
"P488": "chairperson",
"P495": "country of origin",
"P527": "has part",
"P571": "inception",
"P576": "dissolved",
"P577": "publication date",
"P580": "start time",
"P582": "end time",
"P598": "commander",
"P607": "conflict",
"P664": "organizer",
"P710": "participant",
"P737": "influenced by",
"P749": "parent organization",
"P800": "notable work",
"P921": "main subject",
"P1037": "manager",
"P1308": "officeholder",
"P2632": "point in time",
"P3342": "significant person",
}
class LabelApplier:
"""
Applies resolved labels to benchmark questions and subgraphs.
Replaces QIDs/PIDs in-place and rewrites question text.
"""
def __init__(self, labels: Dict[str, str]):
self.labels = labels
def resolve(self, qid: str) -> str:
"""Return human-readable label for a QID/PID, falling back to the raw ID."""
label = self.labels.get(qid, "")
return label if label else qid
def resolve_relation(self, pid: str) -> str:
"""Return a natural-language relation phrase, using RELATION_TEMPLATES first."""
if pid in RELATION_TEMPLATES:
return RELATION_TEMPLATES[pid]
# Fallback to fetched label
label = self.labels.get(pid, "")
return label if label else pid
def rewrite_question(self, question: str, t_query: float) -> str:
"""
Rewrite a machine-generated question by substituting labels for QIDs/PIDs.
Also rewrites common template patterns for naturalness.
"""
# Step 1: find all QIDs/PIDs in the question
qids = QID_PATTERN.findall(question)
substituted = question
for qid in qids:
if re.match(r'^P\d+$', qid):
substituted = substituted.replace(qid, self.resolve_relation(qid))
else:
substituted = substituted.replace(qid, self.resolve(qid))
# Step 2: rewrite common template patterns
# Pattern: "X's RELATION in YEAR was?" → "What was X's RELATION in YEAR?"
m = re.match(r"^(.+)'s (.+) in (\d{4}) was\?$", substituted)
if m:
subj, rel, year = m.group(1), m.group(2), m.group(3)
substituted = f"What was {subj}'s {rel} in {year}?"
# Pattern: "Who was the RELATION of ENTITY in YEAR?" → keep as-is (already natural)
# Pattern: "Who was the RELATION of ENTITY before OTHER?" → keep as-is
return substituted
def rewrite_triple(self, triple: dict) -> dict:
"""Apply labels to a single triple dict {s, r, o, t_start, t_end}."""
return {
**triple,
"s": self.resolve(triple["s"]),
"s_id": triple["s"],
"r": self.resolve_relation(triple["r"]),
"r_id": triple["r"],
"o": self.resolve(triple["o"]),
"o_id": triple["o"],
}
def rewrite_question_record(self, record: dict) -> dict:
"""Apply labels to all fields of a benchmark question record."""
out = dict(record)
out["answer_raw"] = record["answer"]
out["answer"] = self.resolve(record["answer"])
out["question_raw"] = record["question"]
out["question"] = self.rewrite_question(record["question"], record["t_query"])
for field in ("S_star", "S_dist", "S_stale"):
if field in record and record[field]:
out[field] = [self.rewrite_triple(t) for t in record[field]]
return out
# ---------------------------------------------------------------------------
# Main pipeline
# ---------------------------------------------------------------------------
def resolve_benchmark(
input_path: str,
output_path: str,
label_dump: Optional[str] = None,
lang: str = "en",
save_dump: Optional[str] = None,
) -> None:
"""
Full label resolution pipeline for a benchmark JSONL file.
"""
print(f"[Resolver] Input: {input_path}")
# Step 1: extract all IDs
print("[Step 1] Extracting Wikidata IDs...")
ids = extract_ids_from_jsonl(input_path)
print(f" Found {len(ids):,} unique IDs (Q-IDs + P-IDs)")
# Step 2: load or fetch labels
if label_dump and Path(label_dump).exists():
labels = load_label_dump(label_dump)
# Fetch any IDs missing from the dump
missing = [qid for qid in ids if qid not in labels]
if missing:
print(f"[Step 2] Fetching {len(missing):,} labels missing from dump via API...")
fetched = fetch_labels_api(missing, lang=lang)
labels.update(fetched)
else:
print(f"[Step 2] Fetching {len(ids):,} labels from Wikidata API...")
labels = fetch_labels_api(sorted(ids), lang=lang)
if save_dump:
save_label_dump(labels, save_dump)
# Coverage report
resolved = sum(1 for qid in ids if labels.get(qid, ""))
unresolved = [qid for qid in ids if not labels.get(qid, "")]
print(f" Label coverage: {resolved}/{len(ids)} ({100*resolved/max(len(ids),1):.1f}%)")
if unresolved:
print(f" Unresolved IDs (using raw): {unresolved[:10]}{'...' if len(unresolved)>10 else ''}")
# Step 3: apply labels to all records
print("[Step 3] Applying labels to benchmark records...")
applier = LabelApplier(labels)
out_path = Path(output_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
n_written = 0
with open(input_path, "r", encoding="utf-8") as fin, \
open(output_path, "w", encoding="utf-8") as fout:
for line in fin:
line = line.strip()
if not line:
continue
record = json.loads(line)
resolved_record = applier.rewrite_question_record(record)
fout.write(json.dumps(resolved_record, ensure_ascii=False) + "\n")
n_written += 1
print(f"[Resolver] Done — {n_written:,} records written to {output_path}")
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="Resolve Wikidata QIDs/PIDs in TempBench benchmark JSONL to human-readable labels."
)
parser.add_argument("--input", required=False, help="Input benchmark JSONL path")
parser.add_argument("--output", required=False, help="Output labelled JSONL path")
parser.add_argument("--label_dump", default=None, help="Path to pre-fetched TSV label dump (QID<TAB>label)")
parser.add_argument("--save_dump", default=None, help="Save fetched labels to this TSV file for reuse")
parser.add_argument("--lang", default="en", help="Wikidata label language (default: en)")
parser.add_argument("--collect_ids", default=None, help="Only collect IDs from JSONL and write to --id_output")
parser.add_argument("--id_output", default="ids.txt", help="Output file for collected IDs")
parser.add_argument("--fetch_dump", default=None, help="Fetch labels for IDs in this file and save to --dump_output")
parser.add_argument("--dump_output", default="labels.tsv", help="Output file for fetched label dump")
args = parser.parse_args()
# Mode 1: just collect IDs
if args.collect_ids:
ids = extract_ids_from_jsonl(args.collect_ids)
with open(args.id_output, "w") as f:
for qid in sorted(ids):
f.write(qid + "\n")
print(f"[ID Collector] {len(ids):,} unique IDs written to {args.id_output}")
return
# Mode 2: fetch dump from ID list
if args.fetch_dump:
with open(args.fetch_dump) as f:
ids = [line.strip() for line in f if line.strip() and not line.startswith("#")]
print(f"[DumpFetcher] Fetching labels for {len(ids):,} IDs...")
labels = fetch_labels_api(ids, lang=args.lang)
save_label_dump(labels, args.dump_output)
return
# Mode 3: full resolution
if not args.input or not args.output:
parser.error("--input and --output are required for label resolution")
resolve_benchmark(
input_path=args.input,
output_path=args.output,
label_dump=args.label_dump,
lang=args.lang,
save_dump=args.save_dump,
)
if __name__ == "__main__":
main()