| |
| """Prepare an anonymized BeliefSim dataset package for Hugging Face. |
| |
| The script keeps claims, participant judgments, evaluation triplets, and WVS |
| group priors. It drops direct identifiers, IP/location metadata, and open-text |
| free-response notes. |
| """ |
|
|
| import hashlib |
| import json |
| import re |
| import zipfile |
| from pathlib import Path |
| from xml.etree import ElementTree as ET |
|
|
| import pandas as pd |
|
|
|
|
| ROOT = Path(__file__).resolve().parents[2] |
| OUT = Path(__file__).resolve().parents[1] / "data" |
| SALT = "beliefsim-release-v1" |
|
|
|
|
| PANDORA_PATH = ROOT / "misinfo_combined_latest_with_acc_new.csv" |
| MIST_PATH = ROOT / "wvs_misinfo" / "MIST - Sample 1 - Raw Dataset.csv" |
| MIST_ITEM_DB = ROOT / "wvs_misinfo" / "MIST - Phase 4 - Item Database (January 2020).xlsx" |
|
|
| WVS_FILES = { |
| "gender": ROOT / "wvs_misinfo" / "gender_alldimensions_wvs.csv", |
| "living_area": ROOT / "wvs_misinfo" / "urbrur_alldimensions_wvs.csv", |
| "age": ROOT / "wvs_misinfo" / "age_alldimensions.csv", |
| "education": ROOT / "wvs_misinfo" / "education_alldimensions.csv", |
| } |
|
|
|
|
| def anonymize(prefix: str, *parts: object) -> str: |
| raw = "|".join("" if p is None else str(p) for p in parts) |
| digest = hashlib.sha256(f"{SALT}|{prefix}|{raw}".encode("utf-8")).hexdigest()[:16] |
| return f"{prefix}_{digest}" |
|
|
|
|
| def clean_text(value: object) -> str: |
| if pd.isna(value): |
| return "" |
| return re.sub(r"\s+", " ", str(value)).strip() |
|
|
|
|
| def norm(value: object) -> str: |
| return re.sub(r"[^a-z0-9]+", " ", clean_text(value).lower()).strip() |
|
|
|
|
| def first_nonempty(row: pd.Series, candidates: list) -> str: |
| for col in candidates: |
| if col in row.index: |
| val = clean_text(row[col]) |
| if val and val.lower() != "nan": |
| return val |
| return "" |
|
|
|
|
| def extract_claim(prompt_text: str) -> str: |
| text = re.sub(r"^\s*News:\s*", "", clean_text(prompt_text), flags=re.I) |
| for marker in ["Supporting Stance:", "Refuting Stance:", "Your responses:", "Your response:"]: |
| if marker in text: |
| text = text.split(marker, 1)[0] |
| return clean_text(text) |
|
|
|
|
| def standardize_pandora_judgment(value: object) -> str: |
| v = norm(value) |
| if not v: |
| return "" |
| if "importid" in v or v in {"true information", "misinformation", "have you heard of the information before", "comments notes"}: |
| return "" |
| if "true information" in v or v in {"true", "real"}: |
| return "true_information" |
| if "misinformation" in v or v in {"false", "fake"}: |
| return "misinformation" |
| if "not sure" in v or "unsure" in v: |
| return "not_sure" |
| return clean_text(value) |
|
|
|
|
| def standardize_mist_judgment(value: object) -> str: |
| v = norm(value) |
| if not v: |
| return "" |
| if v in {"real", "true", "1"} or "real" in v: |
| return "true_information" |
| if v in {"fake", "false", "0"} or "fake" in v: |
| return "misinformation" |
| return clean_text(value) |
|
|
|
|
| def age_bucket(value: object) -> str: |
| s = clean_text(value) |
| if not s: |
| return "" |
| m = re.search(r"\d+", s) |
| if not m: |
| return s |
| age = int(m.group()) |
| if age < 30: |
| return "18-29" |
| if age < 45: |
| return "30-44" |
| if age < 60: |
| return "45-59" |
| return "60+" |
|
|
|
|
| def education_bucket(value: object) -> str: |
| v = norm(value) |
| if not v: |
| return "" |
| completed = [ |
| "bachelor", |
| "master", |
| "doctor", |
| "professional", |
| "college degree", |
| "university", |
| "graduate", |
| ] |
| if any(token in v for token in completed): |
| return "completed" |
| return "not_completed" |
|
|
|
|
| def load_pandora() -> tuple: |
| if not PANDORA_PATH.exists(): |
| return [], [], [] |
|
|
| raw = pd.read_csv(PANDORA_PATH, header=None, dtype=str, low_memory=False) |
| qids = [clean_text(x) for x in raw.iloc[0].tolist()] |
| labels = [clean_text(x) for x in raw.iloc[1].tolist()] |
| columns = [] |
| seen: dict = {} |
| qid_map: dict = {} |
| for qid, label in zip(qids, labels): |
| base = label or qid or "unnamed" |
| seen[base] = seen.get(base, 0) + 1 |
| col = base if seen[base] == 1 else f"{base}__{seen[base]}" |
| columns.append(col) |
| if qid: |
| qid_map[col] = qid |
|
|
| |
| df = raw.iloc[4:].copy() |
| df.columns = columns |
| news_cols = [c for c in df.columns if norm(c).startswith("news")] |
|
|
| claims: dict[str, dict] = {} |
| judgments: list = [] |
| instances: list = [] |
|
|
| |
| |
| |
| response_cols = {c: c for c in news_cols} |
| demo_cols = { |
| "gender": ["What is your gender?", "gender"], |
| "age_group": ["How old are you?", "age"], |
| "living_area": ["How would you describe the area you live in?", "area", "living_area"], |
| "education_bucket": [ |
| "What is the highest level of education you have completed?", |
| "degree", |
| "education", |
| ], |
| } |
| id_candidates = ["ResponseId", "Response ID", "PROLIFIC_ID"] |
|
|
| for row_idx, row in df.iterrows(): |
| row_judgments = [] |
| participant_id = anonymize("pandora", row_idx, first_nonempty(row, id_candidates)) |
| demographics = {} |
| for key, candidates in demo_cols.items(): |
| val = first_nonempty(row, candidates) |
| demographics[key] = education_bucket(val) if key == "education_bucket" else clean_text(val) |
|
|
| if demographics.get("age_group"): |
| demographics["age_group"] = age_bucket(demographics["age_group"]) |
|
|
| for news_col in news_cols: |
| prompt_text = clean_text(row.get(news_col, "")) |
| resp_col = response_cols.get(news_col, "") |
| judgment = standardize_pandora_judgment(row.get(resp_col, "")) if resp_col else "" |
| claim_text = extract_claim(prompt_text) |
| if not claim_text or not judgment: |
| continue |
| claim_id = qid_map.get(news_col, "") or anonymize("pandora_claim", news_col) |
| claims[claim_id] = { |
| "source": "PANDORA", |
| "claim_id": claim_id, |
| "claim_text": claim_text, |
| "gold_label": "", |
| "content_warning": True, |
| } |
| record = { |
| "source": "PANDORA", |
| "participant_id": participant_id, |
| "claim_id": claim_id, |
| "judgment": judgment, |
| **demographics, |
| } |
| judgments.append(record) |
| row_judgments.append(record) |
|
|
| for i in range(2, len(row_judgments)): |
| b1, b2, target = row_judgments[i - 2], row_judgments[i - 1], row_judgments[i] |
| instances.append( |
| { |
| "source": "PANDORA", |
| "instance_id": anonymize("pandora_instance", participant_id, target["claim_id"], i), |
| "participant_id": participant_id, |
| "target_claim_id": target["claim_id"], |
| "target_judgment": target["judgment"], |
| "observed_claim_1_id": b1["claim_id"], |
| "observed_judgment_1": b1["judgment"], |
| "observed_claim_2_id": b2["claim_id"], |
| "observed_judgment_2": b2["judgment"], |
| **demographics, |
| } |
| ) |
|
|
| return list(claims.values()), judgments, instances |
|
|
|
|
| def read_xlsx_first_sheet(path): |
| """Read a simple XLSX first sheet using only the Python standard library.""" |
| ns = {"a": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"} |
| with zipfile.ZipFile(str(path)) as zf: |
| shared = [] |
| if "xl/sharedStrings.xml" in zf.namelist(): |
| root = ET.fromstring(zf.read("xl/sharedStrings.xml")) |
| for item in root.findall(".//a:si", ns): |
| shared.append("".join(t.text or "" for t in item.findall(".//a:t", ns))) |
|
|
| sheet_name = "xl/worksheets/sheet1.xml" |
| root = ET.fromstring(zf.read(sheet_name)) |
| rows = [] |
| for row in root.findall(".//a:sheetData/a:row", ns): |
| values = [] |
| for cell in row.findall("a:c", ns): |
| cell_type = cell.attrib.get("t", "") |
| value_node = cell.find("a:v", ns) |
| inline_node = cell.find("a:is/a:t", ns) |
| value = "" |
| if inline_node is not None: |
| value = inline_node.text or "" |
| elif value_node is not None: |
| raw = value_node.text or "" |
| value = shared[int(raw)] if cell_type == "s" and raw.isdigit() and int(raw) < len(shared) else raw |
| values.append(value) |
| rows.append(values) |
|
|
| if not rows: |
| return pd.DataFrame() |
| width = max(len(r) for r in rows) |
| rows = [r + [""] * (width - len(r)) for r in rows] |
| header = [clean_text(x) or "column_{}".format(i) for i, x in enumerate(rows[0])] |
| return pd.DataFrame(rows[1:], columns=header) |
|
|
|
|
| def load_mist_item_db() -> pd.DataFrame: |
| try: |
| db = pd.read_excel(MIST_ITEM_DB, dtype=str) |
| except ImportError: |
| db = read_xlsx_first_sheet(MIST_ITEM_DB) |
| cols = {norm(c): c for c in db.columns} |
| id_col = cols.get("id") or next((c for c in db.columns if norm(c) == "id"), "") |
| headline_col = ( |
| cols.get("headline") |
| or cols.get("item") |
| or next((c for c in db.columns if "headline" in norm(c) or "item" == norm(c)), "") |
| ) |
| out = db[[id_col, headline_col]].copy() |
| out.columns = ["item_id", "claim_text"] |
| out["gold_label"] = out["item_id"].map(lambda x: "true_information" if clean_text(x).upper().startswith("R") else "misinformation") |
| out["claim_id"] = [f"MIST_{i + 1}" for i in range(len(out))] |
| return out |
|
|
|
|
| def load_mist() -> tuple: |
| if not MIST_PATH.exists() or not MIST_ITEM_DB.exists(): |
| return [], [], [] |
|
|
| df = pd.read_csv(MIST_PATH, dtype=str, low_memory=False) |
| item_db = load_mist_item_db() |
| claims = [ |
| { |
| "source": "MIST-1", |
| "claim_id": row.claim_id, |
| "claim_text": clean_text(row.claim_text), |
| "gold_label": row.gold_label, |
| "content_warning": True, |
| } |
| for row in item_db.itertuples(index=False) |
| ] |
| claim_ids = item_db["claim_id"].tolist() |
| mist_cols = [c for c in df.columns if re.fullmatch(r"MIST_\d+", clean_text(c))] |
| if not mist_cols: |
| mist_cols = [c for c in df.columns if clean_text(c) in claim_ids] |
|
|
| judgments: list = [] |
| instances: list = [] |
| gender_cols = [c for c in df.columns if norm(c) in {"gender", "sex"} or "gender" in norm(c)] |
| age_cols = [c for c in df.columns if norm(c) == "age" or "age" in norm(c)] |
| edu_cols = [c for c in df.columns if "education" in norm(c) or "degree" in norm(c)] |
|
|
| for row_idx, row in df.iterrows(): |
| demographics = { |
| "gender": first_nonempty(row, gender_cols), |
| "age_group": age_bucket(first_nonempty(row, age_cols)), |
| "living_area": "", |
| "education_bucket": education_bucket(first_nonempty(row, edu_cols)), |
| } |
| participant_id = anonymize("mist", row_idx) |
| row_judgments = [] |
| for col in mist_cols: |
| judgment = standardize_mist_judgment(row.get(col, "")) |
| if not judgment: |
| continue |
| rec = { |
| "source": "MIST-1", |
| "participant_id": participant_id, |
| "claim_id": clean_text(col), |
| "judgment": judgment, |
| **demographics, |
| } |
| judgments.append(rec) |
| row_judgments.append(rec) |
|
|
| for i in range(2, len(row_judgments)): |
| b1, b2, target = row_judgments[i - 2], row_judgments[i - 1], row_judgments[i] |
| instances.append( |
| { |
| "source": "MIST-1", |
| "instance_id": anonymize("mist_instance", participant_id, target["claim_id"], i), |
| "participant_id": participant_id, |
| "target_claim_id": target["claim_id"], |
| "target_judgment": target["judgment"], |
| "observed_claim_1_id": b1["claim_id"], |
| "observed_judgment_1": b1["judgment"], |
| "observed_claim_2_id": b2["claim_id"], |
| "observed_judgment_2": b2["judgment"], |
| **demographics, |
| } |
| ) |
|
|
| return claims, judgments, instances |
|
|
|
|
| def load_wvs_priors() -> list: |
| records: list = [] |
| for axis, path in WVS_FILES.items(): |
| if not path.exists(): |
| continue |
| df = pd.read_csv(path, dtype=str) |
| q_col = next((c for c in df.columns if norm(c) in {"question", "question text"}), "") |
| id_col = next((c for c in df.columns if norm(c) in {"question no", "question_no", "qid"}), "") |
| for _, row in df.iterrows(): |
| for col in df.columns: |
| n = norm(col) |
| if not n.endswith("distribution") or n == "overall distribution": |
| continue |
| group = re.sub(r"_?distribution$", "", col).strip("_") |
| most_col = f"{group}_most" |
| least_col = f"{group}_least" |
| records.append( |
| { |
| "demographic_axis": axis, |
| "group": group, |
| "question_id": clean_text(row.get(id_col, "")) if id_col else "", |
| "question_text": clean_text(row.get(q_col, "")) if q_col else "", |
| "distribution": clean_text(row.get(col, "")), |
| "most_common": clean_text(row.get(most_col, "")), |
| "least_common": clean_text(row.get(least_col, "")), |
| "source_file": path.name, |
| } |
| ) |
| return records |
|
|
|
|
| def main() -> None: |
| OUT.mkdir(parents=True, exist_ok=True) |
| p_claims, p_judgments, p_instances = load_pandora() |
| m_claims, m_judgments, m_instances = load_mist() |
| wvs = load_wvs_priors() |
|
|
| claims = pd.DataFrame(p_claims + m_claims).drop_duplicates(["source", "claim_id"]) |
| judgments = pd.DataFrame(p_judgments + m_judgments) |
| instances = pd.DataFrame(p_instances + m_instances) |
| priors = pd.DataFrame(wvs) |
|
|
| claims.to_csv(OUT / "claims.csv", index=False) |
| judgments.to_csv(OUT / "judgments.csv", index=False) |
| instances.to_csv(OUT / "evaluation_instances.csv", index=False) |
| priors.to_csv(OUT / "wvs_group_priors.csv", index=False) |
|
|
| summary = { |
| "claims": len(claims), |
| "judgments": len(judgments), |
| "evaluation_instances": len(instances), |
| "wvs_group_prior_rows": len(priors), |
| "sources": { |
| "PANDORA": { |
| "claims": int((claims["source"] == "PANDORA").sum()) if not claims.empty else 0, |
| "judgments": int((judgments["source"] == "PANDORA").sum()) if not judgments.empty else 0, |
| "evaluation_instances": int((instances["source"] == "PANDORA").sum()) if not instances.empty else 0, |
| }, |
| "MIST-1": { |
| "claims": int((claims["source"] == "MIST-1").sum()) if not claims.empty else 0, |
| "judgments": int((judgments["source"] == "MIST-1").sum()) if not judgments.empty else 0, |
| "evaluation_instances": int((instances["source"] == "MIST-1").sum()) if not instances.empty else 0, |
| }, |
| }, |
| "privacy": { |
| "dropped": [ |
| "ResponseId", |
| "PROLIFIC_ID", |
| "IPAddress", |
| "LocationLatitude", |
| "LocationLongitude", |
| "open-text notes/comments", |
| "raw timestamps", |
| ], |
| "participant_ids": "deterministic salted SHA-256 hashes, truncated to 16 hex characters", |
| "demographics": "broad gender, age bucket, education bucket, and living-area fields only", |
| }, |
| } |
| (OUT / "dataset_summary.json").write_text(json.dumps(summary, indent=2)) |
| print(json.dumps(summary, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|