| |
| """ |
| 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" |
|
|
| |
| |
| |
| 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) |
|
|
| |
| |
| |
| 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)}") |
|
|
| |
| |
| |
| 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 "" |
| |
| |
| soup = BeautifulSoup(html_str, "html.parser") |
| |
| |
| for math_tag in soup.find_all("math"): |
| |
| math_text = math_tag.get_text(separator=" ", strip=True) |
| math_tag.replace_with(f" [{math_text}] ") |
| |
| |
| for img in soup.find_all("img"): |
| alt = img.get("alt", "") |
| if alt: |
| img.replace_with(f"[Image: {alt}]") |
| else: |
| img.replace_with("[Image]") |
| |
| |
| 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)) |
| |
| |
| text = soup.get_text(separator=" ", strip=True) |
| |
| |
| text = re.sub(r'\s+', ' ', text).strip() |
| |
| |
| text = text.replace('&', '&').replace('<', '<').replace('>', '>') |
| text = text.replace(' ', ' ').replace(''', "'") |
| |
| return text |
|
|
| |
| problems["problem_text_clean"] = problems["Problem Body"].apply(clean_html) |
|
|
| |
| 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 "" |
| ) |
|
|
| |
| 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}...") |
|
|
| |
| |
| |
| 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() |
|
|
| |
| |
| |
| 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() |
|
|
| |
| |
| |
| 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() |
|
|
| |
| |
| |
| 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") |
|
|
| |
| |
| |
| print("\nSaving processed files...") |
|
|
| |
| 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.to_parquet(os.path.join(OUT, "interactions.parquet"), index=False) |
|
|
| |
| student_stats.to_parquet(os.path.join(OUT, "student_stats.parquet"), index=False) |
|
|
| |
| item_stats.to_parquet(os.path.join(OUT, "item_stats.parquet"), index=False) |
|
|
| |
| skills.to_parquet(os.path.join(OUT, "skills.parquet"), index=False) |
|
|
| |
| 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 |
| """) |
|
|