Coding-With-Bashir commited on
Commit
94aa00a
·
verified ·
1 Parent(s): 37b2575

Upload .\src\data_collection\masakhane_collector.py with huggingface_hub

Browse files
.//src//data_collection//masakhane_collector.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Masakhane benchmark datasets collector."""
2
+
3
+ import json
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from datasets import load_dataset
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ KINYARWANDA_IDENTIFIERS = ["kin_Latn", "kin", "rw", "kinyarwanda", "kirundi"]
13
+
14
+ MASAKHANE_DATASETS = [
15
+ ("masakhane/afrixnli", "train", "kin_Latn"),
16
+ ("masakhane/afrimmlu", "test", "kin_Latn"),
17
+ ("masakhane/InjongoIntent", "train", "kin_Latn"),
18
+ ("masakhane/afrimgsm", "train", "kin_Latn"),
19
+ ("masakhane/AfriADR", "train", "kin_Latn"),
20
+ ("masakhane/uhura-arc-easy", "test", "kin_Latn"),
21
+ ("masakhane/uhura-truthfulqa", "test", "kin_Latn"),
22
+ ("masakhane/mafand", "train", "kin_Latn"),
23
+ ("masakhane/afrisenti", "train", "kin_Latn"),
24
+ ("masakhane/masakhaner2", "train", "kin_Latn"),
25
+ ("masakhane/masakhaner", "train", "kin_Latn"),
26
+ ("masakhane/afriqa", "train", "kin_Latn"),
27
+ ("masakhane/jfleg_kin", "train", None),
28
+ ("masakhane/masakhapos", "train", "kin_Latn"),
29
+ ("masakhane/masakhanews", "train", "kin_Latn"),
30
+ ("masakhane/afri-hate-speech", "train", "kin_Latn"),
31
+ ("masakhane/uhura-hellaswag", "test", "kin_Latn"),
32
+ ("masakhane/uhura-winogrande", "test", "kin_Latn"),
33
+ ("masakhane/uhura-sciq", "test", "kin_Latn"),
34
+ ("masakhane/uhura-openbookqa", "test", "kin_Latn"),
35
+ ("masakhane/uhura-mmlu", "test", "kin_Latn"),
36
+ ("masakhane/uhura-gsm8k", "test", "kin_Latn"),
37
+ ("masakhane/uhura-arctest", "test", "kin_Latn"),
38
+ ("facebook/flores", "dev", "kin_Latn"),
39
+ ("facebook/flores", "devtest", "kin_Latn"),
40
+ ("openlanguagedata/flores_plus", "dev", "kin_Latn"),
41
+ ("google/fleurs", "train", "rw"),
42
+ ]
43
+
44
+
45
+ class MasakhaneCollector:
46
+ """Collects Masakhane benchmark datasets with Kinyarwanda subsets."""
47
+
48
+ def __init__(self, output_dir: str, config: dict[str, Any]):
49
+ self.output_dir = Path(output_dir)
50
+ self.output_dir.mkdir(parents=True, exist_ok=True)
51
+ self.config = config
52
+
53
+ def collect_dataset(self, name: str, split: str = "train", language: str | None = None) -> dict[str, Any]:
54
+ """Download and save a Masakhane dataset filtered to Kinyarwanda."""
55
+ safe_name = name.replace("/", "_")
56
+ lang_suffix = f"_{language}" if language else ""
57
+ output_path = self.output_dir / f"{safe_name}{lang_suffix}.jsonl"
58
+ done_marker = self.output_dir / f"{safe_name}{lang_suffix}.jsonl.done"
59
+
60
+ if done_marker.exists():
61
+ try:
62
+ row_count = int(done_marker.read_text().strip())
63
+ logger.info(f"Already collected: {name} (lang={language}, {row_count} rows), skipping")
64
+ return {
65
+ "name": name,
66
+ "split": split,
67
+ "language": language,
68
+ "rows": row_count,
69
+ "output_path": str(output_path),
70
+ "status": "success",
71
+ }
72
+ except (ValueError, OSError):
73
+ pass
74
+
75
+ logger.info(f"Collecting Masakhane dataset: {name} (lang={language})")
76
+
77
+ try:
78
+ kwargs = {"split": split}
79
+ if language:
80
+ kwargs["name"] = language
81
+
82
+ dataset = load_dataset(name, **kwargs)
83
+
84
+ count = 0
85
+ with open(output_path, "w", encoding="utf-8") as f:
86
+ for item in dataset:
87
+ f.write(json.dumps(item, ensure_ascii=False) + "\n")
88
+ count += 1
89
+
90
+ done_marker.write_text(str(count))
91
+
92
+ return {
93
+ "name": name,
94
+ "split": split,
95
+ "language": language,
96
+ "rows": count,
97
+ "output_path": str(output_path),
98
+ "status": "success",
99
+ }
100
+
101
+ except Exception as e:
102
+ logger.error(f"Failed to collect {name} (lang={language}): {e}")
103
+
104
+ if language and language in KINYARWANDA_IDENTIFIERS:
105
+ logger.info(f" Retrying {name} without language filter...")
106
+ try:
107
+ dataset = load_dataset(name, split=split)
108
+ count = 0
109
+ with open(output_path, "w", encoding="utf-8") as f:
110
+ for item in dataset:
111
+ item_str = json.dumps(item, ensure_ascii=False)
112
+ if any(kw in item_str.lower() for kw in ["kinyarwanda", "kin_", "rwanda"]):
113
+ f.write(item_str + "\n")
114
+ count += 1
115
+
116
+ done_marker.write_text(str(count))
117
+ return {
118
+ "name": name,
119
+ "split": split,
120
+ "language": language,
121
+ "rows": count,
122
+ "output_path": str(output_path),
123
+ "status": "success",
124
+ }
125
+ except Exception as e2:
126
+ logger.error(f" Retry also failed for {name}: {e2}")
127
+
128
+ return {"name": name, "status": "failed", "error": str(e)}
129
+
130
+ def collect_all(self) -> list[dict[str, Any]]:
131
+ """Collect all Masakhane benchmarks with Kinyarwanda filtering."""
132
+ results = []
133
+ for name, split, lang in MASAKHANE_DATASETS:
134
+ result = self.collect_dataset(name, split, lang)
135
+ results.append(result)
136
+
137
+ successful = sum(1 for r in results if r["status"] == "success")
138
+ failed = sum(1 for r in results if r["status"] == "failed")
139
+ total_rows = sum(r.get("rows", 0) for r in results if r["status"] == "success")
140
+
141
+ summary = {
142
+ "total": len(results),
143
+ "successful": successful,
144
+ "failed": failed,
145
+ "total_rows": total_rows,
146
+ }
147
+
148
+ summary_path = self.output_dir / "masakhane_summary.json"
149
+ with open(summary_path, "w", encoding="utf-8") as f:
150
+ json.dump(summary, f, indent=2, ensure_ascii=False)
151
+
152
+ logger.info(f"Masakhane collection: {summary}")
153
+ return results