low-resource-nlp-toolkit 0.1.0__tar.gz

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.
Files changed (25) hide show
  1. low_resource_nlp_toolkit-0.1.0/LICENSE +21 -0
  2. low_resource_nlp_toolkit-0.1.0/PKG-INFO +154 -0
  3. low_resource_nlp_toolkit-0.1.0/README.md +116 -0
  4. low_resource_nlp_toolkit-0.1.0/pyproject.toml +70 -0
  5. low_resource_nlp_toolkit-0.1.0/setup.cfg +4 -0
  6. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp/__init__.py +28 -0
  7. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp/_version.py +3 -0
  8. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp/cli.py +98 -0
  9. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp/datasets.py +82 -0
  10. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp/evaluation.py +125 -0
  11. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp/labels.py +108 -0
  12. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp/normalisation.py +119 -0
  13. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp/routing.py +190 -0
  14. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp_toolkit.egg-info/PKG-INFO +154 -0
  15. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp_toolkit.egg-info/SOURCES.txt +23 -0
  16. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp_toolkit.egg-info/dependency_links.txt +1 -0
  17. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp_toolkit.egg-info/entry_points.txt +2 -0
  18. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp_toolkit.egg-info/requires.txt +17 -0
  19. low_resource_nlp_toolkit-0.1.0/src/low_resource_nlp_toolkit.egg-info/top_level.txt +1 -0
  20. low_resource_nlp_toolkit-0.1.0/tests/test_cli.py +41 -0
  21. low_resource_nlp_toolkit-0.1.0/tests/test_datasets.py +37 -0
  22. low_resource_nlp_toolkit-0.1.0/tests/test_evaluation.py +24 -0
  23. low_resource_nlp_toolkit-0.1.0/tests/test_labels.py +27 -0
  24. low_resource_nlp_toolkit-0.1.0/tests/test_normalisation.py +33 -0
  25. low_resource_nlp_toolkit-0.1.0/tests/test_routing.py +38 -0
@@ -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,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,116 @@
1
+ # Low-Resource NLP Toolkit
2
+
3
+ A public, research-facing Python toolkit for African language pre-processing, emotion-label mapping, evaluation, and language/dialect routing.
4
+
5
+ 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.
6
+
7
+ Status: `0.1.0` seed release from source. Local checks, CI, isolated wheel builds, metadata checks, and install tests pass.
8
+
9
+ ## Why This Exists
10
+
11
+ Low-resource NLP projects often spend too much time rebuilding the same foundations before modelling begins. This toolkit provides a dependable base layer:
12
+
13
+ - Text normalisation for noisy social, conversational, and cultural text.
14
+ - Lightweight African language routing for Yoruba, Igbo, Hausa, Nigerian Pidgin, Swahili, and English.
15
+ - Emotion label harmonisation across categorical and valence-arousal formats.
16
+ - Evaluation utilities for classification and routing experiments.
17
+ - A CLI and examples that run without downloading model weights.
18
+ - Extension points for transformer or embedding backends when a project needs heavier models.
19
+
20
+ ## Architecture
21
+
22
+ ```mermaid
23
+ flowchart LR
24
+ A["Raw multilingual text"] --> B["Normaliser"]
25
+ B --> C["Tokeniser"]
26
+ C --> D["Language router"]
27
+ C --> E["Emotion label mapper"]
28
+ D --> F["Route decision + confidence"]
29
+ E --> G["Canonical emotion / valence-arousal"]
30
+ F --> H["Evaluation reports"]
31
+ G --> H
32
+ ```
33
+
34
+ ## Quick Start
35
+
36
+ ```bash
37
+ python3 -m venv .venv
38
+ source .venv/bin/activate
39
+ python -m pip install -e .
40
+ low-resource-nlp --version
41
+ ```
42
+
43
+ Route a text sample:
44
+
45
+ ```bash
46
+ low-resource-nlp route "abeg make una help me check this model output"
47
+ ```
48
+
49
+ Normalise text:
50
+
51
+ ```bash
52
+ low-resource-nlp normalise "Ẹ káàrọ̀!!! Visit https://example.com @user"
53
+ ```
54
+
55
+ Map an emotion label:
56
+
57
+ ```bash
58
+ low-resource-nlp label joy
59
+ ```
60
+
61
+ Run tests:
62
+
63
+ ```bash
64
+ make check
65
+ ```
66
+
67
+ Without `make`:
68
+
69
+ ```bash
70
+ python3 scripts/quality_gate.py
71
+ PYTHONPATH=src python3 -m unittest discover -s tests
72
+ ```
73
+
74
+ ## Python Usage
75
+
76
+ ```python
77
+ from low_resource_nlp import LexicalLanguageRouter, normalise_text, label_to_valence_arousal
78
+
79
+ text = normalise_text("Ẹ káàrọ̀, báwo ni?")
80
+ decision = LexicalLanguageRouter.default().route(text)
81
+ emotion = label_to_valence_arousal("joy")
82
+
83
+ print(decision.language_code, decision.confidence)
84
+ print(emotion)
85
+ ```
86
+
87
+ ## Current Scope
88
+
89
+ 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.
90
+
91
+ Supported core modules:
92
+
93
+ - `normalisation`: Unicode-aware text cleaning, URL/user normalisation, tokenisation, repeated-character handling.
94
+ - `routing`: script-aware and lexicon-assisted language routing.
95
+ - `labels`: canonical emotion labels and valence-arousal mapping.
96
+ - `evaluation`: precision, recall, F1, macro/micro summaries, and confusion matrices.
97
+ - `datasets`: simple CSV/JSONL readers for experiment scaffolding.
98
+
99
+ ## Public Project Materials
100
+
101
+ - [Changelog](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/CHANGELOG.md)
102
+ - [Contributing guide](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/CONTRIBUTING.md)
103
+ - [Documentation index](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/index.md)
104
+ - [0.1.0 release plan](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/release_plan_v0_1.md)
105
+ - [Adoption notes](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/adoption.md)
106
+ - [Model card template](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/model_card_template.md)
107
+ - [Data statement template](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/docs/data_statement_template.md)
108
+ - [Citation metadata](https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/CITATION.cff)
109
+
110
+ ## Responsible AI Notes
111
+
112
+ 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.
113
+
114
+ ## External Use
115
+
116
+ 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,70 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "low-resource-nlp-toolkit"
7
+ version = "0.1.0"
8
+ description = "A robust Python toolkit for low-resource African language pre-processing, emotion labels, evaluation, and routing."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "Oyinkansola Onwuchekwa" }
15
+ ]
16
+ keywords = [
17
+ "low-resource-nlp",
18
+ "african-languages",
19
+ "multilingual-nlp",
20
+ "emotion-recognition",
21
+ "language-routing",
22
+ "responsible-ai"
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 3 - Alpha",
26
+ "Intended Audience :: Developers",
27
+ "Intended Audience :: Science/Research",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3.9",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
33
+ "Topic :: Text Processing :: Linguistic"
34
+ ]
35
+ dependencies = []
36
+
37
+ [project.optional-dependencies]
38
+ models = [
39
+ "numpy",
40
+ "scikit-learn",
41
+ "sentence-transformers",
42
+ "transformers"
43
+ ]
44
+ dev = [
45
+ "pytest",
46
+ "ruff"
47
+ ]
48
+ build = [
49
+ "build",
50
+ "twine"
51
+ ]
52
+ docs = [
53
+ "mkdocs>=1.6"
54
+ ]
55
+
56
+ [project.urls]
57
+ Homepage = "https://github.com/oyinkanchekwas/low-resource-nlp-toolkit"
58
+ Documentation = "https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/tree/main/docs"
59
+ Changelog = "https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/blob/main/CHANGELOG.md"
60
+ Issues = "https://github.com/oyinkanchekwas/low-resource-nlp-toolkit/issues"
61
+
62
+ [project.scripts]
63
+ low-resource-nlp = "low_resource_nlp.cli:main"
64
+
65
+ [tool.setuptools.packages.find]
66
+ where = ["src"]
67
+
68
+ [tool.ruff]
69
+ line-length = 100
70
+ target-version = "py39"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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