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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Kenyan Languages to Swahili Translation Dataset"""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Dict, List, Tuple
|
| 7 |
+
|
| 8 |
+
import datasets
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
_CITATION = """\
|
| 12 |
+
@misc{kenyan_translation,
|
| 13 |
+
title={Kenyan Languages to Swahili Translation Dataset},
|
| 14 |
+
author={Kenya NLP},
|
| 15 |
+
year={2025}
|
| 16 |
+
}
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
_DESCRIPTION = """\
|
| 20 |
+
This dataset contains parallel text translations from several Kenyan languages (Dholuo, Lubukusu, Lucheka, Lulogooli)
|
| 21 |
+
into Swahili. Each file contains sentence pairs in the format:
|
| 22 |
+
- O: <source_sentence> (Original)
|
| 23 |
+
- T: <target_sentence> (Translation/Target)
|
| 24 |
+
|
| 25 |
+
The dataset is organized by source language and can be loaded by specifying the language code.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
_HOMEPAGE = "https://github.com/yourusername/kenyan-translation"
|
| 29 |
+
|
| 30 |
+
_LICENSE = "CC-BY-4.0"
|
| 31 |
+
|
| 32 |
+
_LANGUAGES = ["dho", "lbk", "lch", "llg"]
|
| 33 |
+
_LANG_NAMES = {
|
| 34 |
+
"dho": "Dholuo",
|
| 35 |
+
"lbk": "Lubukusu",
|
| 36 |
+
"lch": "Lucheka",
|
| 37 |
+
"llg": "Lulogooli"
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
_TARGET_LANGUAGE = "swa" # Swahili
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class KenyanTranslationConfig(datasets.BuilderConfig):
|
| 44 |
+
"""BuilderConfig for Kenyan Translation Dataset."""
|
| 45 |
+
|
| 46 |
+
def __init__(self, lang: str = None, **kwargs):
|
| 47 |
+
"""
|
| 48 |
+
Args:
|
| 49 |
+
lang: Language code (dho, lbk, lch, or llg)
|
| 50 |
+
**kwargs: keyword arguments forwarded to super.
|
| 51 |
+
"""
|
| 52 |
+
super().__init__(**kwargs)
|
| 53 |
+
self.lang = lang
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class KenyanTranslation(datasets.GeneratorBasedBuilder):
|
| 57 |
+
"""Kenyan Languages to Swahili Translation Dataset"""
|
| 58 |
+
|
| 59 |
+
VERSION = datasets.Version("1.0.0")
|
| 60 |
+
|
| 61 |
+
BUILDER_CONFIG_CLASS = KenyanTranslationConfig
|
| 62 |
+
|
| 63 |
+
def _info(self):
|
| 64 |
+
features = datasets.Features(
|
| 65 |
+
{
|
| 66 |
+
"id": datasets.Value("string"),
|
| 67 |
+
"source": datasets.Value("string"),
|
| 68 |
+
"target": datasets.Value("string"),
|
| 69 |
+
"src_lang": datasets.Value("string"),
|
| 70 |
+
"tgt_lang": datasets.Value("string"),
|
| 71 |
+
"pair": datasets.Value("string"),
|
| 72 |
+
"filename": datasets.Value("string"),
|
| 73 |
+
}
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
return datasets.DatasetInfo(
|
| 77 |
+
description=_DESCRIPTION,
|
| 78 |
+
features=features,
|
| 79 |
+
homepage=_HOMEPAGE,
|
| 80 |
+
license=_LICENSE,
|
| 81 |
+
citation=_CITATION,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
def _split_generators(self, dl_manager):
|
| 85 |
+
"""Returns SplitGenerators."""
|
| 86 |
+
|
| 87 |
+
# Validate that lang was provided
|
| 88 |
+
if not self.config.lang:
|
| 89 |
+
raise ValueError(
|
| 90 |
+
"Please specify a language code using lang parameter. "
|
| 91 |
+
f"Available languages: {', '.join(_LANGUAGES)}\n"
|
| 92 |
+
f"Example: load_dataset('USERNAME/REPO_NAME', lang='dho')"
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
if self.config.lang not in _LANGUAGES:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
f"Language '{self.config.lang}' not supported. "
|
| 98 |
+
f"Available languages: {', '.join(_LANGUAGES)}"
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Get data files - either from config or by listing from the data directory
|
| 102 |
+
if self.config.data_files:
|
| 103 |
+
# Get all files for this language from provided data_files
|
| 104 |
+
if isinstance(self.config.data_files, dict):
|
| 105 |
+
all_files = []
|
| 106 |
+
for split_files in self.config.data_files.values():
|
| 107 |
+
if isinstance(split_files, list):
|
| 108 |
+
all_files.extend(split_files)
|
| 109 |
+
else:
|
| 110 |
+
all_files.append(split_files)
|
| 111 |
+
else:
|
| 112 |
+
all_files = self.config.data_files if isinstance(self.config.data_files, list) else [self.config.data_files]
|
| 113 |
+
|
| 114 |
+
# Filter files that belong to the selected language
|
| 115 |
+
lang_files = [f for f in all_files if f"data/{self.config.lang}/" in str(f)]
|
| 116 |
+
else:
|
| 117 |
+
# No data_files provided - need to list files from the repository
|
| 118 |
+
# Use dl_manager's dataset_name to construct paths
|
| 119 |
+
import datasets
|
| 120 |
+
from datasets.data_files import DataFilesDict, get_data_patterns
|
| 121 |
+
|
| 122 |
+
# Get base path - this works for both local and Hub loading
|
| 123 |
+
base_path = dl_manager._base_path if hasattr(dl_manager, '_base_path') and dl_manager._base_path else ""
|
| 124 |
+
|
| 125 |
+
# Construct the pattern for the language data directory
|
| 126 |
+
data_pattern = f"{base_path}/data/{self.config.lang}/*.txt" if base_path else f"data/{self.config.lang}/*.txt"
|
| 127 |
+
|
| 128 |
+
# List files using the data files pattern
|
| 129 |
+
from datasets.data_files import DataFilesList
|
| 130 |
+
lang_files = DataFilesList.from_patterns([data_pattern], base_path=base_path)
|
| 131 |
+
|
| 132 |
+
if not lang_files:
|
| 133 |
+
raise ValueError(
|
| 134 |
+
f"No data files found for language '{self.config.lang}'. "
|
| 135 |
+
f"Expected files in data/{self.config.lang}/"
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# Download all files
|
| 139 |
+
downloaded_files = dl_manager.download(lang_files)
|
| 140 |
+
|
| 141 |
+
return [
|
| 142 |
+
datasets.SplitGenerator(
|
| 143 |
+
name=datasets.Split.TRAIN,
|
| 144 |
+
gen_kwargs={
|
| 145 |
+
"files": downloaded_files,
|
| 146 |
+
"lang": self.config.lang,
|
| 147 |
+
},
|
| 148 |
+
),
|
| 149 |
+
]
|
| 150 |
+
|
| 151 |
+
def _parse_ot_format(self, content: str) -> List[Tuple[str, str]]:
|
| 152 |
+
"""Parse O:/T: format from file content."""
|
| 153 |
+
pairs = []
|
| 154 |
+
lines = content.split('\n')
|
| 155 |
+
|
| 156 |
+
current_source = ""
|
| 157 |
+
current_target = ""
|
| 158 |
+
|
| 159 |
+
for line in lines:
|
| 160 |
+
line = line.strip()
|
| 161 |
+
|
| 162 |
+
# Remove line numbers (e.g., "1→O:" becomes "O:")
|
| 163 |
+
line = re.sub(r'^\s*\d+→', '', line)
|
| 164 |
+
|
| 165 |
+
if line.startswith('O:'):
|
| 166 |
+
# Save previous pair if exists
|
| 167 |
+
if current_source and current_target:
|
| 168 |
+
pairs.append((current_source.strip(), current_target.strip()))
|
| 169 |
+
current_target = ""
|
| 170 |
+
|
| 171 |
+
# Start new source
|
| 172 |
+
current_source = line[2:].strip()
|
| 173 |
+
|
| 174 |
+
elif line.startswith('T:'):
|
| 175 |
+
# Add to target (might span multiple T: lines)
|
| 176 |
+
target_text = line[2:].strip()
|
| 177 |
+
if current_target:
|
| 178 |
+
current_target += " " + target_text
|
| 179 |
+
else:
|
| 180 |
+
current_target = target_text
|
| 181 |
+
|
| 182 |
+
# Add last pair
|
| 183 |
+
if current_source and current_target:
|
| 184 |
+
pairs.append((current_source.strip(), current_target.strip()))
|
| 185 |
+
|
| 186 |
+
return pairs
|
| 187 |
+
|
| 188 |
+
def _parse_tab_format(self, content: str) -> List[Tuple[str, str]]:
|
| 189 |
+
"""Parse tab-separated format."""
|
| 190 |
+
pairs = []
|
| 191 |
+
for line in content.split('\n'):
|
| 192 |
+
line = line.strip()
|
| 193 |
+
if not line:
|
| 194 |
+
continue
|
| 195 |
+
parts = line.split('\t')
|
| 196 |
+
if len(parts) >= 2:
|
| 197 |
+
pairs.append((parts[0].strip(), parts[1].strip()))
|
| 198 |
+
return pairs
|
| 199 |
+
|
| 200 |
+
def _parse_pipe_format(self, content: str) -> List[Tuple[str, str]]:
|
| 201 |
+
"""Parse ||| separated format."""
|
| 202 |
+
pairs = []
|
| 203 |
+
for line in content.split('\n'):
|
| 204 |
+
line = line.strip()
|
| 205 |
+
if not line:
|
| 206 |
+
continue
|
| 207 |
+
parts = line.split('|||')
|
| 208 |
+
if len(parts) >= 2:
|
| 209 |
+
pairs.append((parts[0].strip(), parts[1].strip()))
|
| 210 |
+
return pairs
|
| 211 |
+
|
| 212 |
+
def _parse_content(self, content: str) -> List[Tuple[str, str]]:
|
| 213 |
+
"""Parse content string and return list of (source, target) pairs."""
|
| 214 |
+
# Try O:/T: format first
|
| 215 |
+
if 'O:' in content and 'T:' in content:
|
| 216 |
+
pairs = self._parse_ot_format(content)
|
| 217 |
+
if pairs:
|
| 218 |
+
return pairs
|
| 219 |
+
|
| 220 |
+
# Fall back to tab-separated
|
| 221 |
+
if '\t' in content:
|
| 222 |
+
pairs = self._parse_tab_format(content)
|
| 223 |
+
if pairs:
|
| 224 |
+
return pairs
|
| 225 |
+
|
| 226 |
+
# Fall back to pipe-separated
|
| 227 |
+
if '|||' in content:
|
| 228 |
+
pairs = self._parse_pipe_format(content)
|
| 229 |
+
if pairs:
|
| 230 |
+
return pairs
|
| 231 |
+
|
| 232 |
+
return []
|
| 233 |
+
|
| 234 |
+
def _parse_file(self, filepath: Path) -> List[Tuple[str, str]]:
|
| 235 |
+
"""Parse a file and return list of (source, target) pairs."""
|
| 236 |
+
try:
|
| 237 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 238 |
+
content = f.read()
|
| 239 |
+
except UnicodeDecodeError:
|
| 240 |
+
# Try with different encoding
|
| 241 |
+
with open(filepath, 'r', encoding='latin-1') as f:
|
| 242 |
+
content = f.read()
|
| 243 |
+
|
| 244 |
+
return self._parse_content(content)
|
| 245 |
+
|
| 246 |
+
def _generate_examples(self, files, lang: str):
|
| 247 |
+
"""Yields examples."""
|
| 248 |
+
|
| 249 |
+
idx = 0
|
| 250 |
+
|
| 251 |
+
from pathlib import Path
|
| 252 |
+
|
| 253 |
+
# Ensure files is a list
|
| 254 |
+
if isinstance(files, str):
|
| 255 |
+
files = [files]
|
| 256 |
+
|
| 257 |
+
# Sort files for consistent ordering
|
| 258 |
+
for filepath in sorted(files):
|
| 259 |
+
filepath = Path(filepath)
|
| 260 |
+
filename = filepath.name
|
| 261 |
+
|
| 262 |
+
# Read and parse the file
|
| 263 |
+
try:
|
| 264 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 265 |
+
content = f.read()
|
| 266 |
+
except UnicodeDecodeError:
|
| 267 |
+
with open(filepath, 'r', encoding='latin-1') as f:
|
| 268 |
+
content = f.read()
|
| 269 |
+
|
| 270 |
+
# Parse content
|
| 271 |
+
pairs = self._parse_content(content)
|
| 272 |
+
|
| 273 |
+
# Yield each pair as an example
|
| 274 |
+
for pair_idx, (source, target) in enumerate(pairs):
|
| 275 |
+
# Skip empty pairs
|
| 276 |
+
if not source or not target:
|
| 277 |
+
continue
|
| 278 |
+
|
| 279 |
+
example_id = f"{lang}_{filename}_{pair_idx}"
|
| 280 |
+
|
| 281 |
+
yield idx, {
|
| 282 |
+
"id": example_id,
|
| 283 |
+
"source": source,
|
| 284 |
+
"target": target,
|
| 285 |
+
"src_lang": lang,
|
| 286 |
+
"tgt_lang": _TARGET_LANGUAGE,
|
| 287 |
+
"pair": f"{lang}-{_TARGET_LANGUAGE}",
|
| 288 |
+
"filename": filename,
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
idx += 1
|