sinkit 1.0.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.
sinkit/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """
2
+ sinkit — Sinhala NLP Toolkit (Python)
3
+ Part of sinhala-toolkit
4
+
5
+ The missing developer toolkit for Sinhala language processing.
6
+ සිංහල භාෂා සැකසීම සඳහා නවීන developer toolkit එක.
7
+
8
+ Quick start:
9
+ from sinkit.cleaner import TextCleaner
10
+ from sinkit.tokenizer import Tokenizer
11
+ from sinkit.stopwords import Stopwords
12
+ from sinkit.sentiment import SentimentAnalyser
13
+
14
+ GitHub: https://github.com/gosdrkht/sinhala-toolkit
15
+ License: MIT
16
+ """
17
+
18
+ from .cleaner import TextCleaner
19
+ from .tokenizer import Tokenizer
20
+ from .stopwords import Stopwords, is_stopword, filter_stopwords, all_stopwords
21
+ from .sentiment import SentimentAnalyser
22
+
23
+ __version__ = "1.0.0"
24
+ __author__ = "gosdrkht"
25
+ __license__ = "MIT"
26
+ __all__ = [
27
+ "TextCleaner",
28
+ "Tokenizer",
29
+ "Stopwords",
30
+ "SentimentAnalyser",
31
+ "is_stopword",
32
+ "filter_stopwords",
33
+ "all_stopwords",
34
+ ]
sinkit/cleaner.py ADDED
@@ -0,0 +1,217 @@
1
+ """
2
+ cleaner.py — Sinhala text cleaner and normaliser
3
+ Part of sinkit / sinhala-toolkit
4
+
5
+ Usage:
6
+ from sinkit.cleaner import TextCleaner
7
+
8
+ cleaner = TextCleaner()
9
+ clean = cleaner.clean(" මම සහ ඔබ ගෙදර ගියා ",
10
+ remove_stopwords=True)
11
+ # "ගෙදර ගියා"
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ import unicodedata
18
+ from typing import Optional
19
+
20
+ from .stopwords import Stopwords
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Unicode constants
24
+ # ---------------------------------------------------------------------------
25
+ _ZWJ = "\u200D" # Zero Width Joiner — used in Sinhala conjuncts
26
+ _ZWNJ = "\u200C" # Zero Width Non-Joiner
27
+ _ZWSP = "\u200B" # Zero Width Space
28
+ _BOM = "\uFEFF" # Byte Order Mark
29
+ _SOFT_HYPHEN = "\u00AD" # Soft Hyphen
30
+ _LRM = "\u200E" # Left-to-Right Mark
31
+ _RLM = "\u200F" # Right-to-Left Mark
32
+
33
+ # Sinhala Unicode block
34
+ _SINHALA_RE = re.compile(r"[\u0D80-\u0DFF]")
35
+ _ENGLISH_RE = re.compile(r"[a-zA-Z]")
36
+ _NUMBER_RE = re.compile(r"[0-9\u0DE6-\u0DEF]") # ASCII + Sinhala digits
37
+
38
+
39
+ class TextCleaner:
40
+ """
41
+ Clean and normalise Sinhala (and mixed) text.
42
+
43
+ Parameters
44
+ ----------
45
+ stopwords_path : str or None
46
+ Path to stopwords.json. Defaults to ../../data/stopwords.json.
47
+
48
+ Examples
49
+ --------
50
+ >>> c = TextCleaner()
51
+ >>> c.clean(" මම සහ ඔබ ගෙදර ගියා ", remove_stopwords=True)
52
+ 'ගෙදර ගියා'
53
+ >>> c.detect_script("Hello ආයුබෝවන්")
54
+ 'mixed'
55
+ """
56
+
57
+ def __init__(self, stopwords_path: Optional[str] = None) -> None:
58
+ self._sw = Stopwords(stopwords_path) if stopwords_path else Stopwords()
59
+
60
+ # ------------------------------------------------------------------
61
+ # Main pipeline
62
+ # ------------------------------------------------------------------
63
+
64
+ def clean(
65
+ self,
66
+ text: str,
67
+ *,
68
+ remove_stopwords: bool = False,
69
+ remove_punctuation: bool = False,
70
+ remove_english: bool = False,
71
+ remove_numbers: bool = False,
72
+ keep_zwj: bool = True,
73
+ ) -> str:
74
+ """
75
+ Full clean pipeline — run all steps in recommended order.
76
+
77
+ Parameters
78
+ ----------
79
+ text : Input text
80
+ remove_stopwords : Strip Sinhala stopwords
81
+ remove_punctuation : Remove punctuation (keeps Sinhala dandas by default)
82
+ remove_english : Remove ASCII letter characters
83
+ remove_numbers : Remove digit characters
84
+ keep_zwj : Preserve ZWJ (needed for conjunct consonants)
85
+ """
86
+ text = self.normalise_unicode(text)
87
+ text = self.remove_invisible_chars(text, keep_zwj=keep_zwj)
88
+ text = self.normalise_whitespace(text)
89
+
90
+ if remove_punctuation:
91
+ text = self.remove_punctuation(text)
92
+ if remove_english:
93
+ text = self.remove_english(text)
94
+ if remove_numbers:
95
+ text = self.remove_numbers(text)
96
+ if remove_stopwords:
97
+ text = self.remove_stopwords(text)
98
+
99
+ return text.strip()
100
+
101
+ # ------------------------------------------------------------------
102
+ # Individual steps
103
+ # ------------------------------------------------------------------
104
+
105
+ def normalise_unicode(self, text: str) -> str:
106
+ """
107
+ Normalise text to NFC form.
108
+ Sinhala text from different sources may use different compositions —
109
+ NFC ensures consistent character representation.
110
+ """
111
+ return unicodedata.normalize("NFC", text)
112
+
113
+ def remove_invisible_chars(self, text: str, *, keep_zwj: bool = True) -> str:
114
+ """
115
+ Remove invisible/control characters.
116
+
117
+ By default ZWJ is kept because Sinhala uses it for conjunct
118
+ consonants (e.g. ශ් + ZWJ + ර = ශ්‍ර).
119
+ Set keep_zwj=False for bare token comparison.
120
+ """
121
+ # Remove specific invisible chars
122
+ to_remove = [_ZWNJ, _ZWSP, _BOM, _SOFT_HYPHEN, _LRM, _RLM]
123
+ if not keep_zwj:
124
+ to_remove.append(_ZWJ)
125
+
126
+ for char in to_remove:
127
+ text = text.replace(char, "")
128
+
129
+ # Remove C0 control characters (except \t \n \r)
130
+ text = re.sub(r"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]", "", text)
131
+
132
+ return text
133
+
134
+ def normalise_whitespace(self, text: str) -> str:
135
+ """
136
+ Collapse all whitespace variants into single spaces.
137
+ Handles non-breaking space, ideographic space etc.
138
+ """
139
+ text = re.sub(r"[\s\u00A0\u3000]+", " ", text)
140
+ return text.strip()
141
+
142
+ def remove_punctuation(self, text: str, *, keep_danda: bool = True) -> str:
143
+ """
144
+ Remove punctuation marks.
145
+
146
+ Parameters
147
+ ----------
148
+ keep_danda : Keep Sinhala danda (।) and double danda (॥). Default True.
149
+ """
150
+ if keep_danda:
151
+ # Remove all punctuation except dandas (\u0964 \u0965), preserving Sinhala marks and ZWJ
152
+ text = re.sub(r"(?:[^\w\s\u0D80-\u0DF3\u200D\u0964\u0965]|_)", " ", text, flags=re.UNICODE)
153
+ else:
154
+ text = re.sub(r"(?:[^\w\s\u0D80-\u0DF3\u200D]|_)", " ", text, flags=re.UNICODE)
155
+
156
+ return self.normalise_whitespace(text)
157
+
158
+ def remove_english(self, text: str) -> str:
159
+ """Remove ASCII English letters from text."""
160
+ text = re.sub(r"[a-zA-Z]+", " ", text)
161
+ return self.normalise_whitespace(text)
162
+
163
+ def remove_numbers(self, text: str) -> str:
164
+ """Remove digits — both ASCII (0-9) and Sinhala numeral block."""
165
+ text = re.sub(r"[0-9\u0DE6-\u0DEF]", " ", text)
166
+ return self.normalise_whitespace(text)
167
+
168
+ def remove_stopwords(self, text: str) -> str:
169
+ """Remove stopwords by splitting, filtering, and rejoining."""
170
+ tokens = text.split()
171
+ filtered = self._sw.filter(tokens)
172
+ return " ".join(filtered)
173
+
174
+ # ------------------------------------------------------------------
175
+ # Detection utilities
176
+ # ------------------------------------------------------------------
177
+
178
+ def detect_script(self, text: str) -> str:
179
+ """
180
+ Detect the dominant script in a string.
181
+
182
+ Returns
183
+ -------
184
+ 'sinhala' | 'english' | 'mixed' | 'unknown'
185
+ """
186
+ has_sinhala = bool(_SINHALA_RE.search(text))
187
+ has_english = bool(_ENGLISH_RE.search(text))
188
+
189
+ if has_sinhala and has_english:
190
+ return "mixed"
191
+ if has_sinhala:
192
+ return "sinhala"
193
+ if has_english:
194
+ return "english"
195
+ return "unknown"
196
+
197
+ def is_pure_sinhala(self, text: str) -> bool:
198
+ """
199
+ Return True if the text contains only Sinhala characters,
200
+ whitespace, ZWJ, and dandas.
201
+ """
202
+ return bool(re.match(r"^[\u0D80-\u0DFF\u200D\s\u0964\u0965]+$", text.strip()))
203
+
204
+ def contains_sinhala(self, text: str) -> bool:
205
+ """Return True if the text contains any Sinhala characters."""
206
+ return bool(_SINHALA_RE.search(text))
207
+
208
+ def is_stopword(self, word: str) -> bool:
209
+ """Check if a single word is a stopword."""
210
+ return self._sw.is_stopword(word)
211
+
212
+ def tokenize(self, text: str) -> list[str]:
213
+ """
214
+ Simple whitespace tokenizer.
215
+ For advanced tokenization use sinkit.tokenizer.Tokenizer.
216
+ """
217
+ return [t for t in text.split() if t]
sinkit/sentiment.py ADDED
@@ -0,0 +1,235 @@
1
+ """
2
+ sentiment.py — Rule-based Sinhala sentiment analyser
3
+ Part of sinkit / sinhala-toolkit
4
+
5
+ A lightweight, dictionary-based sentiment analyser for Sinhala text.
6
+ No ML dependencies required — works out of the box.
7
+
8
+ Usage:
9
+ from sinkit.sentiment import SentimentAnalyser
10
+
11
+ sa = SentimentAnalyser()
12
+ result = sa.analyse("මෙය ඉතා හොඳ චිත්‍රපටයකි")
13
+ # {"label": "positive", "score": 0.8, "positive": 2, "negative": 0}
14
+
15
+ For a fine-tuned ML model, see the roadmap in README.md.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import TypedDict
21
+ from .tokenizer import Tokenizer
22
+
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Sentiment lexicons
26
+ # Built from common Sinhala social media, reviews, and everyday speech.
27
+ # Contributions welcome — see CONTRIBUTING.md
28
+ # ---------------------------------------------------------------------------
29
+
30
+ POSITIVE_WORDS: list[str] = [
31
+ # Positive adjectives
32
+ "හොඳ", "හොඳයි", "හොඳම", "හොඳටම",
33
+ "ලස්සන", "ලස්සනයි",
34
+ "සුන්දර", "සුන්දරයි",
35
+ "අපූරු", "අපූරුයි",
36
+ "ජය", "ජයග්‍රහණය",
37
+ "සතුට", "සතුටුයි", "සතුටු",
38
+ "ආදරය", "ආදරණීය",
39
+ "සාර්ථක", "සාර්ථකයි",
40
+ "ශ්‍රේෂ්ඨ", "ශ්‍රේෂ්ඨයි",
41
+ "නියම", "නියමයි",
42
+ "ඉක්මන්", "ශක්තිමත්",
43
+ "නිදහස", "නිදහස්",
44
+ "ප්‍රිය", "ප්‍රියමනාප",
45
+ "සුඛ", "සුඛී",
46
+ "දිනුම", "දිනුවා",
47
+ "ශක්ති",
48
+ "ප්‍රශංසා", "ප්‍රශංසනීය",
49
+ "දීප්තිමත්", "දක්ෂ",
50
+ "විශිෂ්ට", "විශිෂ්ටයි",
51
+ "සමෘද්ධිමත්", "සමෘද්ධිය",
52
+ "ඔව්", "හරි", "ඇත්ත",
53
+ "සාමය", "ශාන්ත",
54
+ "ගෞරව", "ගෞරවනීය",
55
+ "කීර්තිමත්", "කීර්තිය",
56
+ "ප්‍රේමය", "ප්‍රේමණීය",
57
+ "රසවත්", "රසවතා",
58
+ "අගේ", "ගිනිකෙළි",
59
+ "අලංකාර", "සිත් ගන්නා",
60
+ ]
61
+
62
+ NEGATIVE_WORDS: list[str] = [
63
+ # Negative adjectives and expressions
64
+ "නරක", "නරකයි", "නරකම",
65
+ "කණගාටු", "කණගාටුයි",
66
+ "දුක", "දුකයි", "දුක්",
67
+ "රොත්ත", "කෝපය", "කෝපයි",
68
+ "අපජය", "පරාජය",
69
+ "බිය", "බියයි", "භය",
70
+ "ගැටලු", "ගැටලුව",
71
+ "අසාර්ථක", "අසාර්ථකයි",
72
+ "ශෝකය", "ශෝකී",
73
+ "නිදහස් නෑ",
74
+ "වේදනා", "වේදනාකාරී",
75
+ "රෝගය", "රෝගී",
76
+ "දූෂිත", "දූෂණය",
77
+ "ක්‍රෝධය", "ක්‍රෝධී",
78
+ "ද්වේෂය", "ද්වේෂී",
79
+ "පාඩු", "අහිමි",
80
+ "හිරිහැර", "හිරිහැරකාරී",
81
+ "අසාධාරණ", "අසාධාරණයි",
82
+ "සුසාන", "ශාපය",
83
+ "මරණය", "මරණ",
84
+ "හිං", "හිංසා",
85
+ "ෆේල්",
86
+ "ව්‍යසනය", "ව්‍යසනකාරී",
87
+ "හරිම නරක",
88
+ "කිළිටි",
89
+ ]
90
+
91
+ NEGATION_WORDS: list[str] = [
92
+ "නෑ", "නැහැ", "නැත", "නෙමෙයි", "බෑ", "බැරි", "නෙ", "නෙමේ",
93
+ ]
94
+
95
+ INTENSIFIERS: dict[str, float] = {
96
+ "ඉතා": 1.5,
97
+ "ඉතාමත්": 1.8,
98
+ "බොහෝ": 1.3,
99
+ "ගොඩාක්": 1.4,
100
+ "හරිම": 1.6,
101
+ "ඉතාම": 1.5,
102
+ }
103
+
104
+
105
+ class SentimentResult(TypedDict):
106
+ label: str # "positive" | "negative" | "neutral"
107
+ score: float # 0.0 to 1.0
108
+ positive: int # count of positive signals
109
+ negative: int # count of negative signals
110
+ tokens: list[str]
111
+
112
+
113
+ class SentimentAnalyser:
114
+ """
115
+ Rule-based Sinhala sentiment analyser.
116
+
117
+ Uses a curated lexicon of positive/negative words,
118
+ handles negation and intensifiers.
119
+
120
+ Note: For production accuracy on diverse text, a fine-tuned
121
+ ML model is recommended. This rule-based version is a solid
122
+ baseline and works with zero dependencies.
123
+
124
+ Examples
125
+ --------
126
+ >>> sa = SentimentAnalyser()
127
+ >>> sa.analyse("මෙය ඉතා හොඳ චිත්‍රපටයකි")["label"]
128
+ 'positive'
129
+
130
+ >>> sa.analyse("මෙය හොඳ නෑ")["label"]
131
+ 'negative'
132
+ """
133
+
134
+ def __init__(
135
+ self,
136
+ positive_words: list[str] | None = None,
137
+ negative_words: list[str] | None = None,
138
+ ) -> None:
139
+ self._positive = set(positive_words or POSITIVE_WORDS)
140
+ self._negative = set(negative_words or NEGATIVE_WORDS)
141
+ self._negations = set(NEGATION_WORDS)
142
+ self._tokenizer = Tokenizer()
143
+
144
+ # ------------------------------------------------------------------
145
+ # Public API
146
+ # ------------------------------------------------------------------
147
+
148
+ def analyse(self, text: str) -> SentimentResult:
149
+ """
150
+ Analyse the sentiment of a Sinhala text string.
151
+
152
+ Returns a SentimentResult dict with:
153
+ - label : "positive", "negative", or "neutral"
154
+ - score : confidence 0.0–1.0
155
+ - positive : number of positive signals found
156
+ - negative : number of negative signals found
157
+ - tokens : the token list used for analysis
158
+ """
159
+ tokens = self._tokenizer.tokenize(text)
160
+
161
+ pos_score = 0.0
162
+ neg_score = 0.0
163
+
164
+ for i, token in enumerate(tokens):
165
+ # Check for negation before or after token (Sinhala is SOV, so negation usually follows)
166
+ prev_neg = i > 0 and tokens[i - 1] in self._negations
167
+ next_neg = i + 1 < len(tokens) and tokens[i + 1] in self._negations
168
+ negate = prev_neg != next_neg
169
+
170
+ # Get intensifier multiplier from previous token
171
+ multiplier = 1.0
172
+ if i > 0:
173
+ multiplier = INTENSIFIERS.get(tokens[i - 1], 1.0)
174
+
175
+ if token in self._positive:
176
+ if negate:
177
+ neg_score += 1.0 * multiplier
178
+ else:
179
+ pos_score += 1.0 * multiplier
180
+
181
+ elif token in self._negative:
182
+ if negate:
183
+ pos_score += 1.0 * multiplier
184
+ else:
185
+ neg_score += 1.0 * multiplier
186
+
187
+ total = pos_score + neg_score
188
+
189
+ if total == 0:
190
+ return SentimentResult(
191
+ label="neutral", score=0.5,
192
+ positive=0, negative=0, tokens=tokens
193
+ )
194
+
195
+ # Normalise to 0-1
196
+ pos_ratio = pos_score / total
197
+ neg_ratio = neg_score / total
198
+
199
+ if pos_ratio > neg_ratio:
200
+ label = "positive"
201
+ score = round(0.5 + (pos_ratio - 0.5) * 0.9, 3)
202
+ elif neg_ratio > pos_ratio:
203
+ label = "negative"
204
+ score = round(0.5 + (neg_ratio - 0.5) * 0.9, 3)
205
+ else:
206
+ label = "neutral"
207
+ score = 0.5
208
+
209
+ return SentimentResult(
210
+ label=label,
211
+ score=min(score, 1.0),
212
+ positive=int(pos_score),
213
+ negative=int(neg_score),
214
+ tokens=tokens,
215
+ )
216
+
217
+ def batch_analyse(self, texts: list[str]) -> list[SentimentResult]:
218
+ """Analyse a list of texts and return results in order."""
219
+ return [self.analyse(t) for t in texts]
220
+
221
+ def is_positive(self, text: str) -> bool:
222
+ return self.analyse(text)["label"] == "positive"
223
+
224
+ def is_negative(self, text: str) -> bool:
225
+ return self.analyse(text)["label"] == "negative"
226
+
227
+ def add_positive_words(self, words: list[str]) -> "SentimentAnalyser":
228
+ """Add custom positive words to the lexicon."""
229
+ self._positive.update(words)
230
+ return self
231
+
232
+ def add_negative_words(self, words: list[str]) -> "SentimentAnalyser":
233
+ """Add custom negative words to the lexicon."""
234
+ self._negative.update(words)
235
+ return self
sinkit/stopwords.py ADDED
@@ -0,0 +1,188 @@
1
+ """
2
+ stopwords.py — Sinhala stopwords loader
3
+ Part of sinkit / sinhala-toolkit
4
+
5
+ Usage:
6
+ from sinkit.stopwords import Stopwords
7
+
8
+ sw = Stopwords()
9
+ print(sw.all()) # full list
10
+ print(sw.by_category("pronouns"))
11
+ print(sw.is_stopword("මම")) # True
12
+ print(sw.filter(["මම", "ගුරු", "සඳහා"])) # ["ගුරු"]
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+ from typing import Optional
21
+
22
+
23
+ def _default_stopwords_path() -> Path:
24
+ """Locate stopwords.json across repo checkout, package dir, or installed data."""
25
+ candidates = [
26
+ Path(__file__).resolve().parent / "data" / "stopwords.json",
27
+ Path(__file__).resolve().parent.parent.parent / "data" / "stopwords.json",
28
+ Path(sys.prefix) / "share" / "sinkit" / "data" / "stopwords.json",
29
+ ]
30
+ for candidate in candidates:
31
+ if candidate.exists():
32
+ return candidate
33
+ return candidates[1]
34
+
35
+
36
+ # Default path to the shared data file
37
+ _DATA_DIR = Path(__file__).resolve().parent.parent.parent / "data"
38
+ _SW_FILE = _default_stopwords_path()
39
+
40
+
41
+ class Stopwords:
42
+ """
43
+ Load and query the curated Sinhala stopwords dataset.
44
+
45
+ Examples
46
+ --------
47
+ >>> sw = Stopwords()
48
+ >>> sw.is_stopword("මම")
49
+ True
50
+ >>> sw.is_stopword("ගුරු")
51
+ False
52
+ >>> sw.filter(["මම", "ගුරු", "සඳහා"])
53
+ ['ගුරු']
54
+ """
55
+
56
+ def __init__(self, json_path: Optional[str | Path] = None) -> None:
57
+ self._path: Path = Path(json_path) if json_path else _default_stopwords_path()
58
+ self._data: dict = {}
59
+ self._flat: list[str] = []
60
+ self._flat_set: set[str] = set()
61
+ self._load()
62
+
63
+ # ------------------------------------------------------------------
64
+ # Public API
65
+ # ------------------------------------------------------------------
66
+
67
+ def all(self) -> list[str]:
68
+ """Return the full flat list of stopwords."""
69
+ return list(self._flat)
70
+
71
+ def by_category(self, category: str) -> list[str]:
72
+ """
73
+ Return stopwords for a specific category.
74
+
75
+ Available: pronouns, conjunctions, prepositions, particles,
76
+ auxiliary_verbs, question_words, demonstratives,
77
+ numerals, common_adverbs, discourse_markers
78
+ """
79
+ section = self._data.get(category)
80
+ if not isinstance(section, dict):
81
+ return []
82
+
83
+ words: list[str] = []
84
+
85
+ for key, value in section.items():
86
+ if key == "_description":
87
+ continue
88
+ if isinstance(value, list):
89
+ words.extend(value)
90
+ elif isinstance(value, str):
91
+ words.append(value)
92
+
93
+ return list(dict.fromkeys(words)) # deduplicate, preserve order
94
+
95
+ def categories(self) -> list[str]:
96
+ """Return all available category names."""
97
+ return [
98
+ k for k in self._data.keys()
99
+ if not k.startswith("_") and k != "flat_list"
100
+ ]
101
+
102
+ def is_stopword(self, word: str) -> bool:
103
+ """Check if a single word is a stopword."""
104
+ return word.strip() in self._flat_set
105
+
106
+ def filter(self, tokens: list[str]) -> list[str]:
107
+ """Remove stopwords from a list of tokens."""
108
+ return [t for t in tokens if not self.is_stopword(t)]
109
+
110
+ def add(self, word: str) -> "Stopwords":
111
+ """Add a custom stopword at runtime (does not persist to file)."""
112
+ w = word.strip()
113
+ if w and w not in self._flat_set:
114
+ self._flat.append(w)
115
+ self._flat_set.add(w)
116
+ return self
117
+
118
+ def add_many(self, words: list[str]) -> "Stopwords":
119
+ """Add multiple custom stopwords at runtime."""
120
+ for w in words:
121
+ self.add(w)
122
+ return self
123
+
124
+ def remove(self, word: str) -> "Stopwords":
125
+ """Remove a word from the stopwords list at runtime."""
126
+ w = word.strip()
127
+ self._flat = [t for t in self._flat if t != w]
128
+ self._flat_set.discard(w)
129
+ return self
130
+
131
+ def meta(self) -> dict:
132
+ """Return dataset metadata."""
133
+ return self._data.get("_meta", {})
134
+
135
+ def __len__(self) -> int:
136
+ return len(self._flat)
137
+
138
+ def __contains__(self, word: str) -> bool:
139
+ return self.is_stopword(word)
140
+
141
+ def __repr__(self) -> str:
142
+ return f"Stopwords(count={len(self)}, path='{self._path}')"
143
+
144
+ # ------------------------------------------------------------------
145
+ # Private
146
+ # ------------------------------------------------------------------
147
+
148
+ def _load(self) -> None:
149
+ if not self._path.exists():
150
+ raise FileNotFoundError(
151
+ f"Stopwords file not found: {self._path}\n"
152
+ "Make sure data/stopwords.json exists."
153
+ )
154
+
155
+ with open(self._path, encoding="utf-8") as f:
156
+ self._data = json.load(f)
157
+
158
+ self._flat = self._data.get("flat_list", [])
159
+ self._flat_set = set(self._flat)
160
+
161
+
162
+ # ---------------------------------------------------------------------------
163
+ # Module-level convenience functions
164
+ # ---------------------------------------------------------------------------
165
+
166
+ _default: Optional[Stopwords] = None
167
+
168
+
169
+ def _get_default() -> Stopwords:
170
+ global _default
171
+ if _default is None:
172
+ _default = Stopwords()
173
+ return _default
174
+
175
+
176
+ def is_stopword(word: str) -> bool:
177
+ """Module-level shortcut: check if a word is a stopword."""
178
+ return _get_default().is_stopword(word)
179
+
180
+
181
+ def filter_stopwords(tokens: list[str]) -> list[str]:
182
+ """Module-level shortcut: filter stopwords from a token list."""
183
+ return _get_default().filter(tokens)
184
+
185
+
186
+ def all_stopwords() -> list[str]:
187
+ """Module-level shortcut: get all stopwords."""
188
+ return _get_default().all()