File size: 9,412 Bytes
210b06e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | #!/usr/bin/env python3
"""
FoundationalASSIST Processing Script for DIF Analysis
======================================================
Run AFTER you get access to: https://huggingface.co/datasets/ASSISTments/FoundationalASSIST
This script:
1. Downloads all 3 data files (Interactions, Problems, Skills)
2. Cleans the HTML/MathML from Problem Body to readable text
3. Computes item-level statistics
4. Merges everything into one DIF-ready table
5. Exports to parquet + CSV
Usage:
pip install huggingface_hub pandas pyarrow beautifulsoup4 lxml
python process_foundational_assist.py
"""
import os, json, re, sys
import pandas as pd
from huggingface_hub import hf_hub_download
OUT = "foundational_assist_data"
os.makedirs(OUT, exist_ok=True)
REPO = "ASSISTments/FoundationalASSIST"
# ============================================================
# Step 1: Download
# ============================================================
print("Downloading FoundationalASSIST data files...")
files = {
"Data/Interactions.csv": "interactions.csv",
"Data/Problems.csv": "problems.csv",
"Data/Skills.csv": "skills.csv",
}
for hf_path, local_name in files.items():
local_path = os.path.join(OUT, local_name)
if os.path.exists(local_path):
print(f" Already exists: {local_name}")
else:
try:
path = hf_hub_download(repo_id=REPO, filename=hf_path, repo_type="dataset")
import shutil
shutil.copy(path, local_path)
print(f" ✅ Downloaded: {local_name} ({os.path.getsize(local_path)/1e6:.1f} MB)")
except Exception as e:
print(f" ❌ {local_name}: {e}")
if "GatedRepoError" in str(type(e).__name__) or "403" in str(e):
print("\n⚠️ ACCESS DENIED — You need to accept the data agreement at:")
print(" https://huggingface.co/datasets/ASSISTments/FoundationalASSIST")
print(" Then re-run this script.")
sys.exit(1)
# ============================================================
# Step 2: Load data
# ============================================================
print("\nLoading data...")
interactions = pd.read_csv(os.path.join(OUT, "interactions.csv"))
problems = pd.read_csv(os.path.join(OUT, "problems.csv"))
skills = pd.read_csv(os.path.join(OUT, "skills.csv"))
print(f"Interactions: {len(interactions):,} rows")
print(f" Columns: {list(interactions.columns)}")
print(f"Problems: {len(problems):,} rows")
print(f" Columns: {list(problems.columns)}")
print(f"Skills: {len(skills):,} rows")
print(f" Columns: {list(skills.columns)}")
# ============================================================
# Step 3: Clean HTML from Problem Body
# ============================================================
print("\nCleaning Problem Body HTML → plain text...")
try:
from bs4 import BeautifulSoup
except ImportError:
os.system("pip install beautifulsoup4 lxml -q")
from bs4 import BeautifulSoup
def clean_html(html_str):
"""Convert HTML/MathML problem body to readable text.
Based on the approach in the dataset's Code/cleantext.py"""
if pd.isna(html_str) or not isinstance(html_str, str):
return ""
# Parse HTML
soup = BeautifulSoup(html_str, "html.parser")
# Handle MathML: extract text content
for math_tag in soup.find_all("math"):
# Try to extract readable math from MathML
math_text = math_tag.get_text(separator=" ", strip=True)
math_tag.replace_with(f" [{math_text}] ")
# Handle images (note: images may contain diagrams)
for img in soup.find_all("img"):
alt = img.get("alt", "")
if alt:
img.replace_with(f"[Image: {alt}]")
else:
img.replace_with("[Image]")
# Handle tables
for table in soup.find_all("table"):
rows = []
for tr in table.find_all("tr"):
cells = [td.get_text(strip=True) for td in tr.find_all(["td", "th"])]
rows.append(" | ".join(cells))
table.replace_with("\n".join(rows))
# Get text
text = soup.get_text(separator=" ", strip=True)
# Clean up whitespace
text = re.sub(r'\s+', ' ', text).strip()
# Clean up common HTML entities
text = text.replace('&', '&').replace('<', '<').replace('>', '>')
text = text.replace(' ', ' ').replace(''', "'")
return text
# Apply cleaning
problems["problem_text_clean"] = problems["Problem Body"].apply(clean_html)
# Also clean MC options if present
for col in ["Multiple Choice Options", "Multiple Choice Answers", "Fill-in Options", "Fill-in Answers"]:
if col in problems.columns:
problems[f"{col}_clean"] = problems[col].apply(
lambda x: clean_html(str(x)) if pd.notna(x) else ""
)
# Show samples
print("\nSample cleaned problems:")
for _, row in problems.head(5).iterrows():
text = row["problem_text_clean"][:200]
ans_type = row.get("Answer Type", "?")
print(f" ID {row['problem_id']} [{ans_type}]: {text}...")
# ============================================================
# Step 4: Aggregate skills per problem
# ============================================================
print("\nAggregating skills per problem...")
skills_agg = skills.groupby("problem_id").agg(
skill_ids=("skill_id", lambda x: ";".join(str(i) for i in x)),
skill_names=("node_name", lambda x: " | ".join(str(n) for n in x)),
n_skills=("skill_id", "count"),
).reset_index()
# ============================================================
# Step 5: Compute item statistics
# ============================================================
print("Computing item-level statistics...")
item_stats = interactions.groupby("problem_id").agg(
n_responses=("discrete_score", "count"),
n_correct=("discrete_score", "sum"),
p_value=("discrete_score", "mean"),
mean_hints=("hint_count", "mean"),
pct_saw_answer=("saw_answer", "mean"),
).reset_index()
# ============================================================
# Step 6: Compute student statistics
# ============================================================
print("Computing student-level statistics...")
student_stats = interactions.groupby("user_xid").agg(
n_problems=("problem_id", "count"),
n_unique_problems=("problem_id", "nunique"),
n_correct=("discrete_score", "sum"),
accuracy=("discrete_score", "mean"),
total_hints=("hint_count", "sum"),
pct_saw_answer=("saw_answer", "mean"),
).reset_index()
# ============================================================
# Step 7: Create merged problem table
# ============================================================
print("Creating master problem table...")
problem_master = problems.merge(item_stats, on="problem_id", how="left")
problem_master = problem_master.merge(skills_agg, on="problem_id", how="left")
# ============================================================
# Step 8: Save everything
# ============================================================
print("\nSaving processed files...")
# Problems with clean text + stats + skills
problem_master.to_parquet(os.path.join(OUT, "problems_master.parquet"), index=False)
problem_master.to_csv(os.path.join(OUT, "problems_master.csv"), index=False)
# Interactions (full)
interactions.to_parquet(os.path.join(OUT, "interactions.parquet"), index=False)
# Student stats
student_stats.to_parquet(os.path.join(OUT, "student_stats.parquet"), index=False)
# Item stats
item_stats.to_parquet(os.path.join(OUT, "item_stats.parquet"), index=False)
# Skills
skills.to_parquet(os.path.join(OUT, "skills.parquet"), index=False)
# Summary
summary = {
"dataset": "FoundationalASSIST (processed)",
"n_interactions": len(interactions),
"n_problems": len(problems),
"n_students": interactions["user_xid"].nunique(),
"n_skills": skills["skill_id"].nunique(),
"accuracy": float(interactions["discrete_score"].mean()),
"answer_types": problems["Answer Type"].value_counts().to_dict() if "Answer Type" in problems.columns else {},
"has_question_text": True,
"has_distractor_text": True,
"has_selected_answer": True,
"has_demographics": False,
"dif_note": "No demographics — contact etrials@assistments.org for demographic linkage",
}
with open(os.path.join(OUT, "summary.json"), "w") as f:
json.dump(summary, f, indent=2, default=str)
print(f"\n{'='*60}")
print("PROCESSING COMPLETE!")
print(f"{'='*60}")
print(f"Output: {os.path.abspath(OUT)}/")
for f in sorted(os.listdir(OUT)):
size = os.path.getsize(os.path.join(OUT, f)) / 1e6
print(f" {f}: {size:.1f} MB")
print(f"""
KEY FILES:
problems_master.parquet — 3,395 problems with:
- problem_text_clean (readable question text)
- Multiple Choice Options/Answers (cleaned)
- p_value, n_responses (item difficulty stats)
- skill_names (Common Core alignment)
interactions.parquet — 1.7M student responses with:
- user_xid, problem_id, discrete_score (0/1)
- answer_text (what the student actually typed/selected)
- hint_count, saw_answer
student_stats.parquet — per-student summary
NOTE: No demographic grouping variables available.
For DIF, you would need to:
1. Contact etrials@assistments.org for demographic linkage, OR
2. Create proficiency-based groups (e.g., top/bottom quartile) as proxy
""")
|