| """ |
| generate_dataset_report.py |
| ========================== |
| Automated dataset diagnostics report for GomParam-v1. |
| Computes difficulty calibration, lexical diversity, distractor similarity, |
| distribution summaries, and duplicate detection. |
| |
| Outputs: |
| - results/dataset_report.md (human-readable markdown) |
| - results/dataset_report.json (machine-readable) |
| """ |
|
|
| import json |
| import math |
| import re |
| import statistics |
| import unicodedata |
| from collections import Counter, defaultdict |
| from pathlib import Path |
|
|
| import numpy as np |
|
|
| DATA_DIR = Path("/mnt/data/projects/GomParam-v1/data") |
| OUT_DIR = Path("/mnt/data/projects/GomParam-v1/results") |
| OUT_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| |
| |
| |
| print("Loading dataset from local JSON files...") |
| all_items = [] |
| module_counts = Counter() |
|
|
| for json_file in sorted(DATA_DIR.glob("*.json")): |
| module_name = json_file.stem |
| with open(json_file, "r", encoding="utf-8") as f: |
| data = json.load(f) |
| for item in data: |
| item["module"] = module_name |
| all_items.append(item) |
| module_counts[module_name] = len(data) |
|
|
| N = len(all_items) |
| print(f"Loaded {N} items across {len(module_counts)} modules.\n") |
|
|
| |
| |
| |
| print("Computing length statistics...") |
|
|
| q_lengths = [] |
| correct_lengths = [] |
| incorrect_lengths = [] |
| all_option_lengths = [] |
|
|
| for item in all_items: |
| q = item.get("context", "") or "" |
| question = item.get("question", "") or "" |
| combined = f"{q} {question}".strip() |
| q_lengths.append(len(combined)) |
|
|
| candidates = item.get("candidates", []) |
| correct_idx = item.get("correct", -1) |
|
|
| for i, c in enumerate(candidates): |
| c_len = len(str(c)) |
| all_option_lengths.append(c_len) |
| if i == correct_idx: |
| correct_lengths.append(c_len) |
| else: |
| incorrect_lengths.append(c_len) |
|
|
|
|
| def dist_stats(values, label=""): |
| """Compute mean, median, std, min, max, p95.""" |
| if not values: |
| return {} |
| arr = np.array(values) |
| return { |
| "mean": round(float(np.mean(arr)), 2), |
| "median": round(float(np.median(arr)), 2), |
| "std": round(float(np.std(arr)), 2), |
| "min": int(np.min(arr)), |
| "max": int(np.max(arr)), |
| "p95": round(float(np.percentile(arr, 95)), 2), |
| } |
|
|
|
|
| q_stats = dist_stats(q_lengths) |
| correct_stats = dist_stats(correct_lengths) |
| incorrect_stats = dist_stats(incorrect_lengths) |
|
|
| |
| |
| |
| print("Computing answer distribution...") |
|
|
| answer_dist = Counter() |
| for item in all_items: |
| idx = item.get("correct", -1) |
| label = {0: "A", 1: "B", 2: "C", 3: "D"}.get(idx, "X") |
| answer_dist[label] += 1 |
|
|
| total_ans = sum(answer_dist.values()) |
| answer_pcts = {k: round(v / total_ans * 100, 1) for k, v in sorted(answer_dist.items())} |
|
|
| |
| probs = [v / total_ans for v in answer_dist.values() if v > 0] |
| entropy = -sum(p * math.log2(p) for p in probs) |
| max_entropy = math.log2(len(probs)) |
|
|
| |
| |
| |
| print("Computing lexical diversity...") |
|
|
| all_tokens = [] |
| devanagari_re = re.compile(r'[\u0900-\u097F]+') |
|
|
| for item in all_items: |
| for field in ["context", "question"]: |
| text = item.get(field, "") or "" |
| all_tokens.extend(devanagari_re.findall(text)) |
| for c in item.get("candidates", []): |
| all_tokens.extend(devanagari_re.findall(str(c))) |
|
|
| total_tokens = len(all_tokens) |
| unique_tokens = len(set(all_tokens)) |
| ttr = round(unique_tokens / total_tokens * 100, 2) if total_tokens > 0 else 0 |
|
|
| |
| def compute_mtld(tokens, threshold=0.72): |
| """Measure of Textual Lexical Diversity (McCarthy & Jarvis, 2010).""" |
| def mtld_forward(tokens, threshold): |
| factors = 0 |
| types = set() |
| token_count = 0 |
| for t in tokens: |
| types.add(t) |
| token_count += 1 |
| if len(types) / token_count < threshold: |
| factors += 1 |
| types = set() |
| token_count = 0 |
| if token_count > 0: |
| ttr = len(types) / token_count |
| factors += (1.0 - ttr) / (1.0 - threshold) |
| return len(tokens) / factors if factors > 0 else len(tokens) |
|
|
| fwd = mtld_forward(tokens, threshold) |
| bwd = mtld_forward(tokens[::-1], threshold) |
| return round((fwd + bwd) / 2, 2) |
|
|
| mtld = compute_mtld(all_tokens) if len(all_tokens) > 100 else 0 |
|
|
| |
| |
| |
| print("Computing distractor similarity...") |
|
|
| def jaccard(s1, s2): |
| set1 = set(str(s1).split()) |
| set2 = set(str(s2).split()) |
| if not set1 or not set2: |
| return 0.0 |
| return len(set1 & set2) / len(set1 | set2) |
|
|
| pairwise_sims = [] |
| for item in all_items: |
| candidates = item.get("candidates", []) |
| for i in range(len(candidates)): |
| for j in range(i + 1, len(candidates)): |
| sim = jaccard(candidates[i], candidates[j]) |
| pairwise_sims.append(sim) |
|
|
| sim_stats = dist_stats([s * 100 for s in pairwise_sims]) |
|
|
| |
| |
| |
| print("Computing near-duplicate detection...") |
|
|
| combined_texts = [] |
| for item in all_items: |
| ctx = item.get("context", "") or "" |
| q = item.get("question", "") or "" |
| combined_texts.append(f"{ctx} {q}".strip()) |
|
|
| |
| def char_ngrams(text, n=4): |
| return set(text[i:i+n] for i in range(len(text) - n + 1)) |
|
|
| high_sim_pairs = 0 |
| THRESHOLD = 0.90 |
| |
| sample_size = min(500, N) |
| for i in range(sample_size): |
| ng_i = char_ngrams(combined_texts[i]) |
| if not ng_i: |
| continue |
| for j in range(i + 1, sample_size): |
| ng_j = char_ngrams(combined_texts[j]) |
| if not ng_j: |
| continue |
| overlap = len(ng_i & ng_j) / len(ng_i | ng_j) |
| if overlap > THRESHOLD: |
| high_sim_pairs += 1 |
|
|
| |
| |
| |
| print("Computing category balance...") |
|
|
| cat_entropy_probs = [c / N for c in module_counts.values()] |
| cat_entropy = -sum(p * math.log2(p) for p in cat_entropy_probs if p > 0) |
| max_cat_entropy = math.log2(len(module_counts)) |
|
|
| |
| difficulty_dist = Counter() |
| for item in all_items: |
| d = item.get("difficulty", "unknown") |
| difficulty_dist[d] += 1 |
|
|
| |
| |
| |
| report = { |
| "total_items": N, |
| "total_modules": len(module_counts), |
| "module_counts": dict(module_counts.most_common()), |
| "question_length": q_stats, |
| "correct_option_length": correct_stats, |
| "incorrect_option_length": incorrect_stats, |
| "answer_distribution": answer_pcts, |
| "answer_entropy": round(entropy, 4), |
| "max_entropy": round(max_entropy, 4), |
| "vocabulary": { |
| "total_tokens": total_tokens, |
| "unique_types": unique_tokens, |
| "ttr_pct": ttr, |
| "mtld": mtld, |
| }, |
| "distractor_similarity_pct": sim_stats, |
| "near_duplicates": { |
| "threshold": THRESHOLD, |
| "sample_size": sample_size, |
| "pairs_above_threshold": high_sim_pairs, |
| }, |
| "category_entropy": round(cat_entropy, 4), |
| "max_category_entropy": round(max_cat_entropy, 4), |
| "difficulty_distribution": dict(difficulty_dist), |
| } |
|
|
| |
| with open(OUT_DIR / "dataset_report.json", "w") as f: |
| json.dump(report, f, indent=2, ensure_ascii=False) |
|
|
| |
| |
| |
| md = [] |
| md.append("# GomParam-v1 Dataset Diagnostics Report\n") |
| md.append(f"**Total Items:** {N} ") |
| md.append(f"**Total Modules:** {len(module_counts)}\n") |
|
|
| md.append("## Module Balance\n") |
| md.append("| Module | Count |") |
| md.append("|--------|-------|") |
| for mod, cnt in module_counts.most_common(): |
| md.append(f"| {mod} | {cnt} |") |
| md.append(f"\n**Category Entropy:** {cat_entropy:.4f} / {max_cat_entropy:.4f} (max)\n") |
|
|
| md.append("## Question Length\n") |
| md.append("| Stat | Value |") |
| md.append("|------|-------|") |
| for k, v in q_stats.items(): |
| md.append(f"| {k} | {v} |") |
|
|
| md.append("\n## Option Length (Correct vs. Incorrect)\n") |
| md.append("| Stat | Correct | Incorrect |") |
| md.append("|------|---------|-----------|") |
| for k in correct_stats: |
| md.append(f"| {k} | {correct_stats[k]} | {incorrect_stats.get(k, 'N/A')} |") |
|
|
| md.append("\n## Answer Distribution\n") |
| md.append("| Option | Percentage |") |
| md.append("|--------|------------|") |
| for k, v in sorted(answer_pcts.items()): |
| md.append(f"| {k} | {v}% |") |
| md.append(f"\n**Shannon Entropy:** {entropy:.4f} / {max_entropy:.4f} (max)\n") |
|
|
| md.append("## Vocabulary & Lexical Diversity\n") |
| md.append(f"- **Total Tokens:** {total_tokens:,}") |
| md.append(f"- **Unique Types:** {unique_tokens:,}") |
| md.append(f"- **Type-Token Ratio:** {ttr}%") |
| md.append(f"- **MTLD:** {mtld}\n") |
|
|
| md.append("## Distractor Similarity (Jaccard %)\n") |
| md.append("| Stat | Value |") |
| md.append("|------|-------|") |
| for k, v in sim_stats.items(): |
| md.append(f"| {k} | {v}% |") |
|
|
| md.append(f"\n## Near-Duplicate Detection\n") |
| md.append(f"- **Threshold:** {THRESHOLD}") |
| md.append(f"- **Sample Size:** {sample_size}") |
| md.append(f"- **Pairs Above Threshold:** {high_sim_pairs}\n") |
|
|
| md.append("## Difficulty Distribution\n") |
| md.append("| Difficulty | Count |") |
| md.append("|------------|-------|") |
| for d, c in difficulty_dist.most_common(): |
| md.append(f"| {d} | {c} |") |
|
|
| md.append("\n---\n*Auto-generated by `generate_dataset_report.py`*\n") |
|
|
| with open(OUT_DIR / "dataset_report.md", "w") as f: |
| f.write("\n".join(md)) |
|
|
| print(f"\nReport saved to:") |
| print(f" {OUT_DIR / 'dataset_report.json'}") |
| print(f" {OUT_DIR / 'dataset_report.md'}") |
| print("Done.") |
|
|