low-resource-nlp-toolkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ """Low-resource NLP utilities for pre-processing, routing, labels, and evaluation."""
2
+
3
+ from ._version import __version__
4
+ from .labels import (
5
+ CANONICAL_EMOTIONS,
6
+ EmotionMapping,
7
+ label_to_valence_arousal,
8
+ normalise_emotion_label,
9
+ parse_label_va,
10
+ )
11
+ from .normalisation import NormalisationConfig, normalise_for_matching, normalise_text, tokenise_words
12
+ from .routing import LanguageProfile, LexicalLanguageRouter, RouteDecision
13
+
14
+ __all__ = [
15
+ "CANONICAL_EMOTIONS",
16
+ "EmotionMapping",
17
+ "LanguageProfile",
18
+ "LexicalLanguageRouter",
19
+ "NormalisationConfig",
20
+ "RouteDecision",
21
+ "label_to_valence_arousal",
22
+ "normalise_emotion_label",
23
+ "normalise_for_matching",
24
+ "normalise_text",
25
+ "parse_label_va",
26
+ "tokenise_words",
27
+ "__version__",
28
+ ]
@@ -0,0 +1,3 @@
1
+ """Package version used by the CLI and release checks."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,98 @@
1
+ """Command-line interface for the low-resource NLP toolkit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+ from typing import List
9
+
10
+ from ._version import __version__
11
+ from .datasets import iter_text_records
12
+ from .evaluation import classification_report
13
+ from .labels import label_to_valence_arousal
14
+ from .normalisation import normalise_text
15
+ from .routing import LexicalLanguageRouter
16
+
17
+
18
+ def _print_json(value: object) -> None:
19
+ print(json.dumps(value, ensure_ascii=False, indent=2))
20
+
21
+
22
+ def build_parser() -> argparse.ArgumentParser:
23
+ """Build the CLI parser."""
24
+
25
+ parser = argparse.ArgumentParser(description="Low-resource NLP pre-processing and routing tools.")
26
+ parser.add_argument("--version", action="version", version=f"low-resource-nlp {__version__}")
27
+ subcommands = parser.add_subparsers(dest="command", required=True)
28
+
29
+ normalise = subcommands.add_parser("normalise", help="Normalise a text string.")
30
+ normalise.add_argument("text")
31
+
32
+ route = subcommands.add_parser("route", help="Route a text string to a language profile.")
33
+ route.add_argument("text")
34
+
35
+ label = subcommands.add_parser("label", help="Map an emotion label to the canonical taxonomy.")
36
+ label.add_argument("label")
37
+
38
+ evaluate = subcommands.add_parser("evaluate", help="Evaluate a CSV/JSONL file with truth and prediction fields.")
39
+ evaluate.add_argument("path", type=Path)
40
+ evaluate.add_argument("--truth-field", default="label")
41
+ evaluate.add_argument("--prediction-field", default="prediction")
42
+
43
+ return parser
44
+
45
+
46
+ def main(argv: List[str] | None = None) -> int:
47
+ """Run the CLI."""
48
+
49
+ parser = build_parser()
50
+ args = parser.parse_args(argv)
51
+
52
+ if args.command == "normalise":
53
+ print(normalise_text(args.text))
54
+ return 0
55
+
56
+ if args.command == "route":
57
+ decision = LexicalLanguageRouter.default().route(args.text)
58
+ _print_json(
59
+ {
60
+ "language_code": decision.language_code,
61
+ "language_name": decision.language_name,
62
+ "confidence": decision.confidence,
63
+ "scores": decision.scores,
64
+ "signals": decision.signals,
65
+ }
66
+ )
67
+ return 0
68
+
69
+ if args.command == "label":
70
+ mapping = label_to_valence_arousal(args.label)
71
+ _print_json(
72
+ {
73
+ "original": mapping.original,
74
+ "canonical": mapping.canonical,
75
+ "valence": mapping.valence,
76
+ "arousal": mapping.arousal,
77
+ }
78
+ )
79
+ return 0
80
+
81
+ if args.command == "evaluate":
82
+ records = list(
83
+ iter_text_records(
84
+ args.path,
85
+ label_field=args.truth_field,
86
+ )
87
+ )
88
+ truth = [record.label or "" for record in records]
89
+ predictions = [str(record.metadata.get(args.prediction_field, "")) for record in records]
90
+ _print_json(classification_report(truth, predictions))
91
+ return 0
92
+
93
+ parser.error(f"Unknown command: {args.command}")
94
+ return 2
95
+
96
+
97
+ if __name__ == "__main__":
98
+ raise SystemExit(main())
@@ -0,0 +1,82 @@
1
+ """Small dataset readers for examples and experiments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Dict, Iterator, Mapping, Optional
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class TextRecord:
14
+ """A normalised representation of a text record."""
15
+
16
+ text: str
17
+ label: Optional[str] = None
18
+ language: Optional[str] = None
19
+ metadata: Mapping[str, str] = field(default_factory=dict)
20
+
21
+
22
+ def iter_jsonl(path: str | Path) -> Iterator[Dict[str, object]]:
23
+ """Yield JSON objects from a JSONL file."""
24
+
25
+ with Path(path).open(encoding="utf-8") as handle:
26
+ for line_number, line in enumerate(handle, start=1):
27
+ line = line.strip()
28
+ if not line:
29
+ continue
30
+ try:
31
+ value = json.loads(line)
32
+ except json.JSONDecodeError as exc:
33
+ raise ValueError(f"Invalid JSON on line {line_number}: {exc}") from exc
34
+ if not isinstance(value, dict):
35
+ raise ValueError(f"JSONL line {line_number} must contain an object.")
36
+ yield value
37
+
38
+
39
+ def iter_csv(path: str | Path) -> Iterator[Dict[str, str]]:
40
+ """Yield rows from a CSV file as dictionaries."""
41
+
42
+ with Path(path).open(encoding="utf-8", newline="") as handle:
43
+ reader = csv.DictReader(handle)
44
+ for row in reader:
45
+ yield dict(row)
46
+
47
+
48
+ def iter_text_records(
49
+ path: str | Path,
50
+ *,
51
+ text_field: str = "text",
52
+ label_field: str = "label",
53
+ language_field: str = "lang",
54
+ ) -> Iterator[TextRecord]:
55
+ """Yield `TextRecord` objects from CSV or JSONL files."""
56
+
57
+ source = Path(path)
58
+ rows = iter_jsonl(source) if source.suffix.lower() == ".jsonl" else iter_csv(source)
59
+ for row in rows:
60
+ text = str(row.get(text_field, ""))
61
+ label = row.get(label_field)
62
+ language = row.get(language_field)
63
+ metadata = {str(key): str(value) for key, value in row.items() if key != text_field}
64
+ yield TextRecord(
65
+ text=text,
66
+ label=str(label) if label is not None else None,
67
+ language=str(language) if language is not None else None,
68
+ metadata=metadata,
69
+ )
70
+
71
+
72
+ def write_jsonl(path: str | Path, rows: Iterator[Mapping[str, object]]) -> int:
73
+ """Write rows to JSONL and return the number written."""
74
+
75
+ target = Path(path)
76
+ target.parent.mkdir(parents=True, exist_ok=True)
77
+ count = 0
78
+ with target.open("w", encoding="utf-8") as handle:
79
+ for row in rows:
80
+ handle.write(json.dumps(dict(row), ensure_ascii=False) + "\n")
81
+ count += 1
82
+ return count
@@ -0,0 +1,125 @@
1
+ """Evaluation utilities for classification and routing experiments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from dataclasses import dataclass
7
+ from typing import Dict, Iterable, List, Mapping, Sequence
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class LabelMetrics:
12
+ """Precision, recall, and F1 for one label."""
13
+
14
+ precision: float
15
+ recall: float
16
+ f1: float
17
+ support: int
18
+
19
+
20
+ def safe_divide(numerator: float, denominator: float) -> float:
21
+ """Divide with zero protection."""
22
+
23
+ return numerator / denominator if denominator else 0.0
24
+
25
+
26
+ def ordered_labels(y_true: Sequence[str], y_pred: Sequence[str], labels: Sequence[str] | None = None) -> List[str]:
27
+ """Return deterministic label order."""
28
+
29
+ if labels:
30
+ return list(labels)
31
+ return sorted(set(y_true) | set(y_pred))
32
+
33
+
34
+ def confusion_matrix(
35
+ y_true: Sequence[str],
36
+ y_pred: Sequence[str],
37
+ labels: Sequence[str] | None = None,
38
+ ) -> Dict[str, Dict[str, int]]:
39
+ """Build a nested confusion matrix as `truth -> prediction -> count`."""
40
+
41
+ if len(y_true) != len(y_pred):
42
+ raise ValueError("y_true and y_pred must have the same length.")
43
+
44
+ label_order = ordered_labels(y_true, y_pred, labels)
45
+ matrix = {truth: {pred: 0 for pred in label_order} for truth in label_order}
46
+ for truth, pred in zip(y_true, y_pred):
47
+ matrix.setdefault(truth, {label: 0 for label in label_order})
48
+ matrix[truth][pred] = matrix[truth].get(pred, 0) + 1
49
+ return matrix
50
+
51
+
52
+ def precision_recall_f1(
53
+ y_true: Sequence[str],
54
+ y_pred: Sequence[str],
55
+ labels: Sequence[str] | None = None,
56
+ ) -> Dict[str, LabelMetrics]:
57
+ """Compute per-label precision, recall, and F1."""
58
+
59
+ if len(y_true) != len(y_pred):
60
+ raise ValueError("y_true and y_pred must have the same length.")
61
+
62
+ label_order = ordered_labels(y_true, y_pred, labels)
63
+ true_counts = Counter(y_true)
64
+ pred_counts = Counter(y_pred)
65
+ correct_counts = Counter(
66
+ truth for truth, pred in zip(y_true, y_pred) if truth == pred
67
+ )
68
+
69
+ metrics: Dict[str, LabelMetrics] = {}
70
+ for label in label_order:
71
+ precision = safe_divide(correct_counts[label], pred_counts[label])
72
+ recall = safe_divide(correct_counts[label], true_counts[label])
73
+ f1 = safe_divide(2 * precision * recall, precision + recall)
74
+ metrics[label] = LabelMetrics(
75
+ precision=round(precision, 4),
76
+ recall=round(recall, 4),
77
+ f1=round(f1, 4),
78
+ support=true_counts[label],
79
+ )
80
+ return metrics
81
+
82
+
83
+ def classification_report(
84
+ y_true: Sequence[str],
85
+ y_pred: Sequence[str],
86
+ labels: Sequence[str] | None = None,
87
+ ) -> Mapping[str, object]:
88
+ """Return a compact classification report."""
89
+
90
+ metrics = precision_recall_f1(y_true, y_pred, labels)
91
+ support_total = sum(metric.support for metric in metrics.values())
92
+ accuracy = safe_divide(
93
+ sum(1 for truth, pred in zip(y_true, y_pred) if truth == pred),
94
+ len(y_true),
95
+ )
96
+ macro_f1 = safe_divide(sum(metric.f1 for metric in metrics.values()), len(metrics))
97
+ weighted_f1 = safe_divide(
98
+ sum(metric.f1 * metric.support for metric in metrics.values()),
99
+ support_total,
100
+ )
101
+ return {
102
+ "accuracy": round(accuracy, 4),
103
+ "macro_f1": round(macro_f1, 4),
104
+ "weighted_f1": round(weighted_f1, 4),
105
+ "labels": {
106
+ label: {
107
+ "precision": metric.precision,
108
+ "recall": metric.recall,
109
+ "f1": metric.f1,
110
+ "support": metric.support,
111
+ }
112
+ for label, metric in metrics.items()
113
+ },
114
+ "confusion_matrix": confusion_matrix(y_true, y_pred, list(metrics)),
115
+ }
116
+
117
+
118
+ def accuracy(y_true: Iterable[str], y_pred: Iterable[str]) -> float:
119
+ """Compute exact-match accuracy."""
120
+
121
+ truth = list(y_true)
122
+ pred = list(y_pred)
123
+ if len(truth) != len(pred):
124
+ raise ValueError("y_true and y_pred must have the same length.")
125
+ return round(safe_divide(sum(t == p for t, p in zip(truth, pred)), len(truth)), 4)
@@ -0,0 +1,108 @@
1
+ """Emotion label harmonisation for multilingual NLP experiments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Dict, Iterable, List, Optional, Tuple
7
+
8
+ CANONICAL_EMOTIONS = (
9
+ "anger",
10
+ "anticipation",
11
+ "disgust",
12
+ "fear",
13
+ "joy",
14
+ "love",
15
+ "negative",
16
+ "neutral",
17
+ "optimism",
18
+ "positive",
19
+ "sadness",
20
+ "surprise",
21
+ "trust",
22
+ )
23
+
24
+ EMOTION_ALIASES: Dict[str, str] = {
25
+ "angry": "anger",
26
+ "annoyance": "anger",
27
+ "annoyed": "anger",
28
+ "anticipatory": "anticipation",
29
+ "disgusted": "disgust",
30
+ "fearful": "fear",
31
+ "happy": "joy",
32
+ "happiness": "joy",
33
+ "sad": "sadness",
34
+ "positive sentiment": "positive",
35
+ "negative sentiment": "negative",
36
+ "none": "neutral",
37
+ "other": "neutral",
38
+ }
39
+
40
+ VALENCE_AROUSAL: Dict[str, Tuple[float, float]] = {
41
+ "anger": (2.5, 7.9),
42
+ "anticipation": (6.5, 6.0),
43
+ "disgust": (2.6, 5.8),
44
+ "fear": (2.8, 7.4),
45
+ "joy": (8.2, 7.6),
46
+ "love": (8.4, 5.8),
47
+ "negative": (2.5, 5.5),
48
+ "neutral": (5.0, 5.0),
49
+ "optimism": (7.5, 6.0),
50
+ "positive": (7.5, 5.5),
51
+ "sadness": (2.1, 3.4),
52
+ "surprise": (7.0, 8.5),
53
+ "trust": (7.5, 5.0),
54
+ }
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class EmotionMapping:
59
+ """A normalised emotion label and optional valence-arousal score."""
60
+
61
+ original: str
62
+ canonical: str
63
+ valence: Optional[float]
64
+ arousal: Optional[float]
65
+
66
+
67
+ def normalise_emotion_label(label: str) -> str:
68
+ """Map a raw emotion label to the canonical taxonomy."""
69
+
70
+ value = (label or "").strip().lower().replace("_", " ").replace("-", " ")
71
+ value = " ".join(value.split())
72
+ value = EMOTION_ALIASES.get(value, value)
73
+ if value in CANONICAL_EMOTIONS:
74
+ return value
75
+ return value
76
+
77
+
78
+ def parse_label_va(value: str) -> Optional[Tuple[float, float]]:
79
+ """Parse a valence-arousal string such as `5.00#7.50`."""
80
+
81
+ if not value or "#" not in value:
82
+ return None
83
+ left, right = value.split("#", 1)
84
+ try:
85
+ return float(left), float(right)
86
+ except ValueError:
87
+ return None
88
+
89
+
90
+ def label_to_valence_arousal(label: str) -> EmotionMapping:
91
+ """Return canonical label and valence-arousal coordinates when known."""
92
+
93
+ parsed = parse_label_va(label)
94
+ if parsed:
95
+ valence, arousal = parsed
96
+ return EmotionMapping(label, "valence_arousal", valence, arousal)
97
+
98
+ canonical = normalise_emotion_label(label)
99
+ pair = VALENCE_AROUSAL.get(canonical)
100
+ if pair:
101
+ return EmotionMapping(label, canonical, pair[0], pair[1])
102
+ return EmotionMapping(label, canonical, None, None)
103
+
104
+
105
+ def map_emotion_sequence(labels: Iterable[str]) -> List[EmotionMapping]:
106
+ """Map a sequence of labels to canonical emotion mappings."""
107
+
108
+ return [label_to_valence_arousal(label) for label in labels]
@@ -0,0 +1,119 @@
1
+ """Text normalisation helpers for low-resource NLP experiments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import re
7
+ import unicodedata
8
+ from dataclasses import dataclass
9
+ from typing import List
10
+
11
+ URL_RE = re.compile(r"https?://\S+|www\.\S+", re.IGNORECASE)
12
+ USER_RE = re.compile(r"(?<!\w)@\w+")
13
+ HASHTAG_RE = re.compile(r"(?<!\w)#([\w_]+)")
14
+ MULTISPACE_RE = re.compile(r"\s+")
15
+ REPEATED_CHAR_RE = re.compile(r"(.)\1{2,}", re.IGNORECASE)
16
+ JOINER_CHARS = {"-", "'"}
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class NormalisationConfig:
21
+ """Configuration for text normalisation.
22
+
23
+ Diacritics are preserved by default because they carry meaning in languages
24
+ such as Yoruba. Use `strip_diacritics=True` only for matching/indexing.
25
+ """
26
+
27
+ lowercase: bool = True
28
+ normalise_unicode: str = "NFC"
29
+ preserve_diacritics: bool = True
30
+ replace_urls: bool = True
31
+ replace_users: bool = True
32
+ unpack_hashtags: bool = True
33
+ reduce_repeated_chars: bool = True
34
+ repeated_char_limit: int = 2
35
+
36
+
37
+ def strip_diacritics(text: str) -> str:
38
+ """Remove combining marks while keeping base characters."""
39
+
40
+ decomposed = unicodedata.normalize("NFD", text)
41
+ return "".join(char for char in decomposed if unicodedata.category(char) != "Mn")
42
+
43
+
44
+ def split_hashtag(match: re.Match[str]) -> str:
45
+ """Convert `#LowResourceNLP` into readable text."""
46
+
47
+ raw = match.group(1).replace("_", " ")
48
+ spaced = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", raw)
49
+ return spaced
50
+
51
+
52
+ def normalise_text(text: str, config: NormalisationConfig | None = None) -> str:
53
+ """Normalise text while preserving linguistically meaningful characters."""
54
+
55
+ cfg = config or NormalisationConfig()
56
+ value = html.unescape(text or "")
57
+ value = unicodedata.normalize(cfg.normalise_unicode, value)
58
+
59
+ if cfg.replace_urls:
60
+ value = URL_RE.sub(" <URL> ", value)
61
+ if cfg.replace_users:
62
+ value = USER_RE.sub(" <USER> ", value)
63
+ if cfg.unpack_hashtags:
64
+ value = HASHTAG_RE.sub(split_hashtag, value)
65
+ if cfg.reduce_repeated_chars:
66
+ limit = max(1, cfg.repeated_char_limit)
67
+ value = REPEATED_CHAR_RE.sub(lambda match: match.group(1) * limit, value)
68
+ if not cfg.preserve_diacritics:
69
+ value = strip_diacritics(value)
70
+ if cfg.lowercase:
71
+ value = value.lower()
72
+
73
+ return MULTISPACE_RE.sub(" ", value).strip()
74
+
75
+
76
+ def normalise_for_matching(text: str) -> str:
77
+ """Return a lower-cased, accent-insensitive representation for matching."""
78
+
79
+ return normalise_text(
80
+ text,
81
+ NormalisationConfig(
82
+ lowercase=True,
83
+ preserve_diacritics=False,
84
+ replace_urls=True,
85
+ replace_users=True,
86
+ unpack_hashtags=True,
87
+ ),
88
+ )
89
+
90
+
91
+ def tokenise_words(text: str, *, match_form: bool = False) -> List[str]:
92
+ """Tokenise a text into Unicode-aware word tokens."""
93
+
94
+ value = normalise_for_matching(text) if match_form else normalise_text(text)
95
+ tokens: List[str] = []
96
+ current: List[str] = []
97
+
98
+ for index, char in enumerate(value):
99
+ category = unicodedata.category(char)
100
+ is_word_char = category.startswith("L") or category.startswith("M")
101
+ is_joiner = (
102
+ char in JOINER_CHARS
103
+ and current
104
+ and index + 1 < len(value)
105
+ and unicodedata.category(value[index + 1]).startswith("L")
106
+ )
107
+
108
+ if is_word_char or is_joiner:
109
+ current.append(char)
110
+ continue
111
+
112
+ if current:
113
+ tokens.append("".join(current).strip("-'"))
114
+ current = []
115
+
116
+ if current:
117
+ tokens.append("".join(current).strip("-'"))
118
+
119
+ return [token for token in tokens if token]
@@ -0,0 +1,190 @@
1
+ """Lightweight language and dialect routing for low-resource NLP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass, field
7
+ from typing import Dict, Iterable, List, Mapping, Sequence, Tuple
8
+
9
+ from .normalisation import normalise_for_matching, normalise_text, tokenise_words
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class LanguageProfile:
14
+ """Lexical profile for a language or dialect route."""
15
+
16
+ code: str
17
+ name: str
18
+ stopwords: Tuple[str, ...] = ()
19
+ keywords: Tuple[str, ...] = ()
20
+ unique_chars: Tuple[str, ...] = ()
21
+ aliases: Tuple[str, ...] = ()
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class RouteDecision:
26
+ """Routing result returned by `LexicalLanguageRouter`."""
27
+
28
+ language_code: str
29
+ language_name: str
30
+ confidence: float
31
+ scores: Mapping[str, float]
32
+ signals: Mapping[str, List[str]] = field(default_factory=dict)
33
+
34
+
35
+ def default_profiles() -> List[LanguageProfile]:
36
+ """Return default African-language-focused routing profiles."""
37
+
38
+ return [
39
+ LanguageProfile(
40
+ code="yor",
41
+ name="Yoruba",
42
+ stopwords=("ati", "ni", "si", "mo", "o", "awon", "fun", "ti", "bi", "ko"),
43
+ keywords=("ekaabo", "bawo", "jowo", "oruko", "ile", "omo", "e", "se"),
44
+ unique_chars=("ẹ", "ọ", "ṣ", "à", "á", "è", "é", "ì", "í", "ò", "ó", "ù", "ú"),
45
+ ),
46
+ LanguageProfile(
47
+ code="ibo",
48
+ name="Igbo",
49
+ stopwords=("na", "nke", "ndi", "ka", "bu", "m", "gi", "anyi", "ha", "o"),
50
+ keywords=("kedu", "biko", "nnoo", "umu", "nne", "nna", "ezi", "okwu"),
51
+ unique_chars=("ị", "ọ", "ụ", "ṅ"),
52
+ ),
53
+ LanguageProfile(
54
+ code="hau",
55
+ name="Hausa",
56
+ stopwords=("da", "na", "ne", "ce", "a", "ya", "ta", "mu", "su", "mai"),
57
+ keywords=("sannu", "ina", "lafiya", "gida", "mutum", "yau", "kuma", "wannan"),
58
+ unique_chars=("ɓ", "ɗ", "ƙ"),
59
+ ),
60
+ LanguageProfile(
61
+ code="pcm",
62
+ name="Nigerian Pidgin",
63
+ stopwords=("dey", "na", "no", "go", "we", "una", "dem", "me", "i", "you"),
64
+ keywords=("abeg", "wahala", "wetin", "sha", "sabi", "pikin", "chop", "oga", "make"),
65
+ ),
66
+ LanguageProfile(
67
+ code="swa",
68
+ name="Swahili",
69
+ stopwords=("na", "ya", "kwa", "ni", "wa", "katika", "hii", "hiyo", "mimi", "wewe"),
70
+ keywords=("habari", "asante", "tafadhali", "sana", "mtu", "watu", "nyumba", "leo"),
71
+ ),
72
+ LanguageProfile(
73
+ code="eng",
74
+ name="English",
75
+ stopwords=("the", "and", "is", "in", "to", "of", "for", "with", "this", "that"),
76
+ keywords=("hello", "please", "model", "language", "research", "data", "music", "emotion"),
77
+ ),
78
+ ]
79
+
80
+
81
+ def character_ngrams(text: str, n: int = 3) -> List[str]:
82
+ """Create character n-grams for compact lexical matching."""
83
+
84
+ collapsed = normalise_for_matching(text).replace(" ", "_")
85
+ if len(collapsed) < n:
86
+ return [collapsed] if collapsed else []
87
+ return [collapsed[index : index + n] for index in range(len(collapsed) - n + 1)]
88
+
89
+
90
+ class LexicalLanguageRouter:
91
+ """Dependency-light router using script, lexical, and character signals."""
92
+
93
+ def __init__(self, profiles: Sequence[LanguageProfile]):
94
+ self.profiles = list(profiles)
95
+ self.profile_by_code = {profile.code: profile for profile in self.profiles}
96
+ self._keyword_index = {
97
+ profile.code: {normalise_for_matching(word) for word in profile.keywords}
98
+ for profile in self.profiles
99
+ }
100
+ self._stopword_index = {
101
+ profile.code: {normalise_for_matching(word) for word in profile.stopwords}
102
+ for profile in self.profiles
103
+ }
104
+ self._char_index = {
105
+ profile.code: {normalise_for_matching(char) for char in profile.unique_chars}
106
+ for profile in self.profiles
107
+ }
108
+
109
+ @classmethod
110
+ def default(cls) -> "LexicalLanguageRouter":
111
+ """Build the default router."""
112
+
113
+ return cls(default_profiles())
114
+
115
+ def route(self, text: str) -> RouteDecision:
116
+ """Route a text to the most likely language profile."""
117
+
118
+ normalised = normalise_text(text)
119
+ match_text = normalise_for_matching(text)
120
+ tokens = tokenise_words(text, match_form=True)
121
+ if not match_text:
122
+ return RouteDecision("und", "Undetermined", 0.0, {}, {})
123
+ token_set = set(tokens)
124
+ ngrams = set(character_ngrams(text))
125
+ scores: Dict[str, float] = {}
126
+ signals: Dict[str, List[str]] = {}
127
+
128
+ for profile in self.profiles:
129
+ score = 0.0
130
+ found: List[str] = []
131
+
132
+ stop_hits = sorted(token_set & self._stopword_index[profile.code])
133
+ keyword_hits = sorted(token_set & self._keyword_index[profile.code])
134
+ char_hits = sorted(char for char in profile.unique_chars if char in normalised)
135
+
136
+ if stop_hits:
137
+ score += len(stop_hits) * 1.0
138
+ found.extend(f"stop:{hit}" for hit in stop_hits[:5])
139
+ if keyword_hits:
140
+ score += len(keyword_hits) * 2.0
141
+ found.extend(f"keyword:{hit}" for hit in keyword_hits[:5])
142
+ if char_hits:
143
+ score += len(char_hits) * 1.5
144
+ found.extend(f"char:{hit}" for hit in char_hits[:5])
145
+
146
+ profile_ngrams = set()
147
+ for item in profile.stopwords + profile.keywords:
148
+ profile_ngrams.update(character_ngrams(item))
149
+ overlap = ngrams & profile_ngrams
150
+ if overlap:
151
+ score += min(len(overlap) * 0.08, 2.5)
152
+
153
+ if profile.code == "eng" and match_text.isascii():
154
+ score += 0.2
155
+
156
+ scores[profile.code] = round(score, 4)
157
+ signals[profile.code] = found
158
+
159
+ ranked = sorted(scores.items(), key=lambda item: (-item[1], item[0]))
160
+ best_code, best_score = ranked[0] if ranked else ("und", 0.0)
161
+ total_positive = sum(value for value in scores.values() if value > 0)
162
+ confidence = best_score / total_positive if total_positive else 0.0
163
+
164
+ if best_score <= 0:
165
+ return RouteDecision("und", "Undetermined", 0.0, scores, signals)
166
+
167
+ profile = self.profile_by_code[best_code]
168
+ return RouteDecision(
169
+ language_code=profile.code,
170
+ language_name=profile.name,
171
+ confidence=round(float(confidence), 4),
172
+ scores=scores,
173
+ signals=signals,
174
+ )
175
+
176
+ def route_many(self, texts: Iterable[str]) -> List[RouteDecision]:
177
+ """Route multiple texts."""
178
+
179
+ return [self.route(text) for text in texts]
180
+
181
+
182
+ def softmax_scores(scores: Mapping[str, float]) -> Dict[str, float]:
183
+ """Convert arbitrary scores into a probability-like distribution."""
184
+
185
+ if not scores:
186
+ return {}
187
+ max_score = max(scores.values())
188
+ exps = {label: math.exp(score - max_score) for label, score in scores.items()}
189
+ total = sum(exps.values()) or 1.0
190
+ return {label: value / total for label, value in exps.items()}
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: low-resource-nlp-toolkit
3
+ Version: 0.1.0
4
+ Summary: A robust Python toolkit for low-resource African language pre-processing, emotion labels, evaluation, and routing.
5
+ Author: Oyinkansola Onwuchekwa
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/oyinkanchekwas/low-resource-nlp-toolkit
8
+ Project-URL: Documentation, https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/tree/main/docs
9
+ Project-URL: Changelog, https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/CHANGELOG.md
10
+ Project-URL: Issues, https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/issues
11
+ Keywords: low-resource-nlp,african-languages,multilingual-nlp,emotion-recognition,language-routing,responsible-ai
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Text Processing :: Linguistic
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: models
25
+ Requires-Dist: numpy; extra == "models"
26
+ Requires-Dist: scikit-learn; extra == "models"
27
+ Requires-Dist: sentence-transformers; extra == "models"
28
+ Requires-Dist: transformers; extra == "models"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest; extra == "dev"
31
+ Requires-Dist: ruff; extra == "dev"
32
+ Provides-Extra: build
33
+ Requires-Dist: build; extra == "build"
34
+ Requires-Dist: twine; extra == "build"
35
+ Provides-Extra: docs
36
+ Requires-Dist: mkdocs>=1.6; extra == "docs"
37
+ Dynamic: license-file
38
+
39
+ # Low-Resource NLP Toolkit
40
+
41
+ A public, research-facing Python toolkit for African language pre-processing, emotion-label mapping, evaluation, and language/dialect routing.
42
+
43
+ The project is designed as a safe open-source wrapper around the kinds of NLP engineering problems that appear in low-resource and multilingual AI research: noisy text, code-switching, uneven label taxonomies, small datasets, and evaluation that must be transparent.
44
+
45
+ Status: `0.1.0` seed release from source. Local checks, CI, isolated wheel builds, metadata checks, and install tests pass.
46
+
47
+ ## Why This Exists
48
+
49
+ Low-resource NLP projects often spend too much time rebuilding the same foundations before modelling begins. This toolkit provides a dependable base layer:
50
+
51
+ - Text normalisation for noisy social, conversational, and cultural text.
52
+ - Lightweight African language routing for Yoruba, Igbo, Hausa, Nigerian Pidgin, Swahili, and English.
53
+ - Emotion label harmonisation across categorical and valence-arousal formats.
54
+ - Evaluation utilities for classification and routing experiments.
55
+ - A CLI and examples that run without downloading model weights.
56
+ - Extension points for transformer or embedding backends when a project needs heavier models.
57
+
58
+ ## Architecture
59
+
60
+ ```mermaid
61
+ flowchart LR
62
+ A["Raw multilingual text"] --> B["Normaliser"]
63
+ B --> C["Tokeniser"]
64
+ C --> D["Language router"]
65
+ C --> E["Emotion label mapper"]
66
+ D --> F["Route decision + confidence"]
67
+ E --> G["Canonical emotion / valence-arousal"]
68
+ F --> H["Evaluation reports"]
69
+ G --> H
70
+ ```
71
+
72
+ ## Quick Start
73
+
74
+ ```bash
75
+ python3 -m venv .venv
76
+ source .venv/bin/activate
77
+ python -m pip install -e .
78
+ low-resource-nlp --version
79
+ ```
80
+
81
+ Route a text sample:
82
+
83
+ ```bash
84
+ low-resource-nlp route "abeg make una help me check this model output"
85
+ ```
86
+
87
+ Normalise text:
88
+
89
+ ```bash
90
+ low-resource-nlp normalise "Ẹ káàrọ̀!!! Visit https://example.com @user"
91
+ ```
92
+
93
+ Map an emotion label:
94
+
95
+ ```bash
96
+ low-resource-nlp label joy
97
+ ```
98
+
99
+ Run tests:
100
+
101
+ ```bash
102
+ make check
103
+ ```
104
+
105
+ Without `make`:
106
+
107
+ ```bash
108
+ python3 scripts/quality_gate.py
109
+ PYTHONPATH=src python3 -m unittest discover -s tests
110
+ ```
111
+
112
+ ## Python Usage
113
+
114
+ ```python
115
+ from low_resource_nlp import LexicalLanguageRouter, normalise_text, label_to_valence_arousal
116
+
117
+ text = normalise_text("Ẹ káàrọ̀, báwo ni?")
118
+ decision = LexicalLanguageRouter.default().route(text)
119
+ emotion = label_to_valence_arousal("joy")
120
+
121
+ print(decision.language_code, decision.confidence)
122
+ print(emotion)
123
+ ```
124
+
125
+ ## Current Scope
126
+
127
+ The first public release deliberately avoids bundling private datasets or model weights. The core is deterministic, inspectable, and dependency-light. Optional embedding and transformer backends are outside the current core package.
128
+
129
+ Supported core modules:
130
+
131
+ - `normalisation`: Unicode-aware text cleaning, URL/user normalisation, tokenisation, repeated-character handling.
132
+ - `routing`: script-aware and lexicon-assisted language routing.
133
+ - `labels`: canonical emotion labels and valence-arousal mapping.
134
+ - `evaluation`: precision, recall, F1, macro/micro summaries, and confusion matrices.
135
+ - `datasets`: simple CSV/JSONL readers for experiment scaffolding.
136
+
137
+ ## Public Project Materials
138
+
139
+ - [Changelog](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/CHANGELOG.md)
140
+ - [Contributing guide](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/CONTRIBUTING.md)
141
+ - [Documentation index](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/index.md)
142
+ - [0.1.0 release plan](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/release_plan_v0_1.md)
143
+ - [Adoption notes](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/adoption.md)
144
+ - [Model card template](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/model_card_template.md)
145
+ - [Data statement template](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/data_statement_template.md)
146
+ - [Citation metadata](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/CITATION.cff)
147
+
148
+ ## Responsible AI Notes
149
+
150
+ This toolkit is for research and prototyping. Language, dialect, and emotion labels are socially and culturally sensitive. Do not treat routing or emotion predictions as identity labels, clinical assessments, or ground truth. Always evaluate with speakers, domain experts, and context-specific data.
151
+
152
+ ## External Use
153
+
154
+ External use signals should be public and verifiable: issues from real users, pull requests, tutorial use, workshop demos, citations, package downloads, or adoption by a lab/community project. Self-generated activity should not be counted as impact.
@@ -0,0 +1,14 @@
1
+ low_resource_nlp/__init__.py,sha256=FEa49YyltHTr6ArenSKUmD1nh9J8_jHM2GllRGp3KLk,787
2
+ low_resource_nlp/_version.py,sha256=OwOXsXaKJjCPaheIC8Gsda6Z0OBMK6s_xS_9dImQWjE,81
3
+ low_resource_nlp/cli.py,sha256=lq1zmBFqlOySRg_AmV1HBw8GcasFDbULazTXnix3kD8,3135
4
+ low_resource_nlp/datasets.py,sha256=iB84Vo39NFhO_EfXOGFLeX3_kS8QTvvZtx6LFj_TYSU,2662
5
+ low_resource_nlp/evaluation.py,sha256=d2s7OQDwoJ7jDEcRQx1AAkJgadfj8a_FOsSFG8C3clw,4072
6
+ low_resource_nlp/labels.py,sha256=anChoyugy8tu6viUjAP4v4hwywMy4dLdDRZ-B-1P7nU,2812
7
+ low_resource_nlp/normalisation.py,sha256=_9Vbnuk2RKoTDV4wkZHx5HH8SQARQJ9TlX6LU0sJG_M,3664
8
+ low_resource_nlp/routing.py,sha256=ZiHFwN_A3UCbxMFwJid831R2AuCPsB2bEacxPdQGn2Y,7162
9
+ low_resource_nlp_toolkit-0.1.0.dist-info/licenses/LICENSE,sha256=szZpS6AZjpJHIZX0TuqQxtLdFvML2GFGqmgMCV-fHPY,1079
10
+ low_resource_nlp_toolkit-0.1.0.dist-info/METADATA,sha256=eE0zuD0aeY6SqLd8hrOAvt0_kQCpM_2mm5NBpWSgAXo,6430
11
+ low_resource_nlp_toolkit-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ low_resource_nlp_toolkit-0.1.0.dist-info/entry_points.txt,sha256=ibwvJSzOLO2MuFunGVsh0Coq_HuSCcgJ6mkPQZ-PMU8,63
13
+ low_resource_nlp_toolkit-0.1.0.dist-info/top_level.txt,sha256=eY6DKplZTs0UuMW56Vb_yUWKHwBJ6TBw57YHfMi5HvQ,17
14
+ low_resource_nlp_toolkit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ low-resource-nlp = low_resource_nlp.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oyinkansola Onwuchekwa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ low_resource_nlp