cjclassifier 1.0.2__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,25 @@
1
+ # Copyright 2026 Jeremy Lilley (jeremy@jlilley.net)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """CJClassifier — classify text as Chinese Simplified, Chinese Traditional, or Japanese.
16
+
17
+ Uses a statistical model of unigram and bigram ideograph probabilities built from
18
+ Japanese and Chinese language Wikipedia corpora.
19
+ """
20
+
21
+ from cjclassifier.classifier import CJClassifier
22
+ from cjclassifier.language import CJLanguage
23
+
24
+ __all__ = ["CJClassifier", "CJLanguage"]
25
+ __version__ = "1.0.2"
Binary file
@@ -0,0 +1,605 @@
1
+ # Copyright 2026 Jeremy Lilley (jeremy@jlilley.net)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Core classifier: detects whether CJ text is Japanese, Chinese Simplified,
16
+ or Chinese Traditional.
17
+
18
+ Classification of ideographs is based on a unigram + bigram statistical model
19
+ built from Japanese and Chinese language Wikipedia corpora. For every character
20
+ and character-pair in the CJ range, the model stores per-language
21
+ log-probabilities. At classification time the library sums these
22
+ log-probabilities across the input and picks the language with the highest
23
+ score."""
24
+
25
+ from __future__ import annotations
26
+
27
+ import array
28
+ import gzip
29
+ import importlib.resources
30
+ import logging
31
+ from typing import Dict, List, Optional, Tuple
32
+
33
+ from cjclassifier.language import CJLanguage
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ _CJ_RANGE_START = 0x3400
38
+ _CJ_RANGE_END = 0x9FFF
39
+ _CJ_RANGE_SIZE = _CJ_RANGE_END - _CJ_RANGE_START + 1
40
+ _LANG_COUNT = 3 # zh-hans=0, zh-hant=1, ja=2
41
+
42
+ CJ_LANGUAGES: List[CJLanguage] = [
43
+ CJLanguage.CHINESE_SIMPLIFIED,
44
+ CJLanguage.CHINESE_TRADITIONAL,
45
+ CJLanguage.JAPANESE,
46
+ ]
47
+
48
+ # Singleton cache
49
+ _cache: Dict[str, "CJClassifier"] = {}
50
+
51
+
52
+ def _is_kana(c: int) -> bool:
53
+ """Check if a Unicode code point is Hiragana, Katakana, or half-width Katakana."""
54
+ if 0x3040 <= c <= 0x30FF:
55
+ return True
56
+ if 0x31F0 <= c <= 0x31FF:
57
+ return True
58
+ if 0xFF65 <= c <= 0xFF9F:
59
+ return True
60
+ return False
61
+
62
+
63
+ def _in_main_cj_range(c: int) -> bool:
64
+ """Check if a Unicode code point is in the main CJ Unified Ideograph range."""
65
+ return _CJ_RANGE_START <= c <= _CJ_RANGE_END
66
+
67
+
68
+ # ========================================================================
69
+ # BigramMap: open-addressing hash map using flat array.array storage
70
+ # ========================================================================
71
+ # We could just use a Dict[int, int] here, but this cuts the model's
72
+ # memory overhead from 109MB to 29MB, since all the int boxing and
73
+ # hashtable overhead adds up.
74
+ #
75
+ # This is just a port of the Java BigramToFloatArrayMap. It avoids Python
76
+ # object boxing by storing keys and value-offsets in array.array('i')
77
+ # (4 bytes per slot) instead of a dict of Python int objects
78
+ # (~28-32 bytes each).
79
+
80
+ _EMPTY = 0
81
+ _MAX_LOAD_FACTOR = 0.75
82
+
83
+
84
+ def _mix(k: int) -> int:
85
+ """Hash mixing function to spread bits of the key."""
86
+ k = (k ^ (k >> 16)) & 0xFFFFFFFF
87
+ k = (k * 0x85EBCA6B) & 0xFFFFFFFF
88
+ k = (k ^ (k >> 13)) & 0xFFFFFFFF
89
+ return k
90
+
91
+
92
+ def _table_size_for(expected: int) -> int:
93
+ """Return the smallest power of 2 that can hold expected entries at <=75% load."""
94
+ min_cap = int(expected / _MAX_LOAD_FACTOR) + 1
95
+ cap = 1
96
+ while cap < min_cap:
97
+ cap <<= 1
98
+ return max(cap, 16)
99
+
100
+
101
+ class _BigramMap:
102
+ """Open-addressing hash map: bigram key (int) -> offset into prob_data.
103
+
104
+ Keys and value-offsets are stored in array.array('i') to avoid the overhead
105
+ of Python int objects. Probabilities are in a separate array.array('f').
106
+ """
107
+
108
+ __slots__ = ("_keys", "_value_indices", "prob_data", "_mask")
109
+
110
+ def __init__(self, keys, value_indices, prob_data, mask):
111
+ self._keys = keys
112
+ self._value_indices = value_indices
113
+ self.prob_data = prob_data
114
+ self._mask = mask
115
+
116
+ def get_offset(self, c1: int, c2: int) -> int:
117
+ """Look up the offset for a bigram. Returns 0 if not present."""
118
+ key = (c1 << 16) | c2
119
+ keys = self._keys
120
+ value_indices = self._value_indices
121
+ mask = self._mask
122
+ idx = _mix(key) & mask
123
+ while True:
124
+ k = keys[idx]
125
+ if k == key:
126
+ return value_indices[idx]
127
+ if k == _EMPTY:
128
+ return 0
129
+ idx = (idx + 1) & mask
130
+
131
+
132
+ class _BigramMapBuilder:
133
+ """Mutable builder for constructing a _BigramMap."""
134
+
135
+ __slots__ = ("_keys", "_value_indices", "_prob_data", "_prob_data_size",
136
+ "_size", "_mask", "_threshold")
137
+
138
+ def __init__(self, expected_size: int):
139
+ capacity = _table_size_for(expected_size)
140
+ self._keys = array.array('I', [0]) * capacity
141
+ self._value_indices = array.array('I', [0]) * capacity
142
+ self._mask = capacity - 1
143
+ self._threshold = int(capacity * _MAX_LOAD_FACTOR)
144
+ self._prob_data = array.array('f', [0.0]) # offset 0 reserved
145
+ self._prob_data_size = 1
146
+ self._size = 0
147
+
148
+ def put(self, c1: int, c2: int, probs: List[float]):
149
+ """Store probabilities for a bigram key. Copies from probs list."""
150
+ key = (c1 << 16) | c2
151
+ if self._size >= self._threshold:
152
+ self._resize()
153
+ idx = _mix(key) & self._mask
154
+ while True:
155
+ k = self._keys[idx]
156
+ if k == _EMPTY:
157
+ self._keys[idx] = key
158
+ self._value_indices[idx] = len(self._prob_data)
159
+ self._prob_data.extend(probs)
160
+ self._size += 1
161
+ return
162
+ if k == key:
163
+ # Update in place
164
+ off = self._value_indices[idx]
165
+ for i in range(len(probs)):
166
+ self._prob_data[off + i] = probs[i]
167
+ return
168
+ idx = (idx + 1) & self._mask
169
+
170
+ def build(self) -> _BigramMap:
171
+ """Build an immutable _BigramMap."""
172
+ return _BigramMap(self._keys, self._value_indices,
173
+ self._prob_data, self._mask)
174
+
175
+ def _resize(self):
176
+ new_capacity = (self._mask + 1) << 1
177
+ old_keys = self._keys
178
+ old_value_indices = self._value_indices
179
+ self._keys = array.array('I', [0]) * new_capacity
180
+ self._value_indices = array.array('I', [0]) * new_capacity
181
+ self._mask = new_capacity - 1
182
+ self._threshold = int(new_capacity * _MAX_LOAD_FACTOR)
183
+ self._size = 0
184
+ for i in range(len(old_keys)):
185
+ if old_keys[i] != _EMPTY:
186
+ self._rehash_put(old_keys[i], old_value_indices[i])
187
+
188
+ def _rehash_put(self, key: int, value_index: int):
189
+ idx = _mix(key) & self._mask
190
+ while True:
191
+ if self._keys[idx] == _EMPTY:
192
+ self._keys[idx] = key
193
+ self._value_indices[idx] = value_index
194
+ self._size += 1
195
+ return
196
+ idx = (idx + 1) & self._mask
197
+
198
+
199
+ class Scores:
200
+ """Accumulates per-language scoring data during CJ text processing."""
201
+
202
+ __slots__ = (
203
+ "unigram_scores", "bigram_scores",
204
+ "unigram_hits_per_lang", "bigram_hits_per_lang",
205
+ "kana_count", "cj_char_count",
206
+ )
207
+
208
+ def __init__(self):
209
+ self.unigram_scores = [0.0] * _LANG_COUNT
210
+ self.bigram_scores = [0.0] * _LANG_COUNT
211
+ self.unigram_hits_per_lang = [0] * _LANG_COUNT
212
+ self.bigram_hits_per_lang = [0] * _LANG_COUNT
213
+ self.kana_count = 0
214
+ self.cj_char_count = 0
215
+
216
+ def clear(self):
217
+ """Reset all accumulated scores and counts to zero."""
218
+ for i in range(_LANG_COUNT):
219
+ self.unigram_scores[i] = 0.0
220
+ self.bigram_scores[i] = 0.0
221
+ self.unigram_hits_per_lang[i] = 0
222
+ self.bigram_hits_per_lang[i] = 0
223
+ self.kana_count = 0
224
+ self.cj_char_count = 0
225
+
226
+ def any_hits(self) -> bool:
227
+ """True if at least one unigram was matched in any language."""
228
+ return max(self.unigram_hits_per_lang) > 0
229
+
230
+
231
+ class Results:
232
+ """Detection results, including accumulated Scores and the computed result."""
233
+
234
+ __slots__ = ("scores", "total_scores", "boosts", "result", "gap")
235
+
236
+ def __init__(self, scores: Optional[Scores] = None):
237
+ self.scores = scores if scores is not None else Scores()
238
+ self.total_scores = [0.0] * _LANG_COUNT
239
+ self.boosts = [0.0] * _LANG_COUNT
240
+ self.result: Optional[CJLanguage] = None
241
+ self.gap: float = 0.0
242
+
243
+ def clear(self):
244
+ """Reset all scores, boosts, and the computed result."""
245
+ self.scores.clear()
246
+ for i in range(_LANG_COUNT):
247
+ self.total_scores[i] = 0.0
248
+ self.boosts[i] = 0.0
249
+ self.result = None
250
+ self.gap = 0.0
251
+
252
+ def _compute_totals(self, placeholder_score: float):
253
+ max_unigram = max(self.scores.unigram_hits_per_lang)
254
+ max_bigram = max(self.scores.bigram_hits_per_lang)
255
+ for i in range(_LANG_COUNT):
256
+ self.total_scores[i] = (
257
+ self.scores.unigram_scores[i]
258
+ + (max_unigram - self.scores.unigram_hits_per_lang[i]) * placeholder_score
259
+ + self.scores.bigram_scores[i]
260
+ + (max_bigram - self.scores.bigram_hits_per_lang[i]) * placeholder_score
261
+ )
262
+ # Implement boosts: since logprob values are negative, a favorable boost
263
+ # is negative.
264
+ self.total_scores[i] -= self.boosts[i] * self.total_scores[i]
265
+
266
+ def to_short_string(self) -> str:
267
+ """Compact comma-separated representation of per-language relative scores.
268
+
269
+ Example: 'zh-hans:1.00,zh-hant:0.97,ja:0.85'
270
+ Returns '' if no result has been computed or the result is UNKNOWN.
271
+ """
272
+ if self.result is None or self.result is CJLanguage.UNKNOWN:
273
+ return ""
274
+ if self.scores.kana_count > 0 and self.result is CJLanguage.JAPANESE:
275
+ return "ja:1.0,zh-hans:0,zh-hant:0"
276
+
277
+ # Sort indices by total_scores descending
278
+ order = sorted(range(_LANG_COUNT), key=lambda i: self.total_scores[i], reverse=True)
279
+ best = self.total_scores[order[0]]
280
+ if best == 0:
281
+ return ""
282
+
283
+ parts = []
284
+ for li in order:
285
+ ratio = best / self.total_scores[li] if self.total_scores[li] != 0 else 0
286
+ parts.append(f"{CJ_LANGUAGES[li].iso_code}:{ratio:.2f}")
287
+ return ",".join(parts)
288
+
289
+ def __repr__(self) -> str:
290
+ code = self.result.iso_code if self.result else "None"
291
+ parts = [f"Results(result={code}"]
292
+ if self.scores.kana_count > 0:
293
+ total = self.scores.kana_count + self.scores.cj_char_count
294
+ parts.append(f" kana={self.scores.kana_count}/{total}")
295
+ for li in range(_LANG_COUNT):
296
+ parts.append(
297
+ f" | {CJ_LANGUAGES[li].iso_code}:"
298
+ f" uni={self.scores.unigram_scores[li]:.2f}"
299
+ f" bi={self.scores.bigram_scores[li]:.2f}"
300
+ f" total={self.total_scores[li]:.2f}"
301
+ f" biHits={self.scores.bigram_hits_per_lang[li]}"
302
+ )
303
+ parts.append(")")
304
+ return "".join(parts)
305
+
306
+
307
+ class CJClassifier:
308
+ """Detects whether CJ text is Japanese, Chinese Simplified, or Chinese Traditional.
309
+
310
+ Load with ``CJClassifier.load()``. The model is cached as a singleton.
311
+ Call ``detect(text)`` to classify text.
312
+
313
+ Example::
314
+
315
+ cjc = CJClassifier.load()
316
+ cjc.detect("今天天气很好") # => CJLanguage.CHINESE_SIMPLIFIED
317
+ cjc.detect("事務所") # => CJLanguage.JAPANESE
318
+ """
319
+
320
+ # Class-level constants exposed for user code
321
+ CJ_LANGUAGES = CJ_LANGUAGES
322
+
323
+ def __init__(
324
+ self,
325
+ unigram_log_probs: List[float],
326
+ bigram_map: _BigramMap,
327
+ default_log_prob: float,
328
+ ):
329
+ self._unigram_log_probs = unigram_log_probs
330
+ self._bigram_map = bigram_map
331
+ self._default_log_prob = default_log_prob
332
+ self._tolerated_kana_threshold = 0.01
333
+
334
+ @property
335
+ def tolerated_kana_threshold(self) -> float:
336
+ """Kana fraction threshold above which text is classified as Japanese."""
337
+ return self._tolerated_kana_threshold
338
+
339
+ @tolerated_kana_threshold.setter
340
+ def tolerated_kana_threshold(self, value: float):
341
+ self._tolerated_kana_threshold = value
342
+
343
+ # ========================================================================
344
+ # Loading
345
+ # ========================================================================
346
+
347
+ @classmethod
348
+ def load(cls, path: Optional[str] = None, log_prob_floor: float = 0.0) -> "CJClassifier":
349
+ """Load a CJClassifier, using a cached singleton.
350
+
351
+ Args:
352
+ path: Filesystem path to a model file (may be gzipped).
353
+ If None, loads the bundled model from the package.
354
+ log_prob_floor: Custom log-probability floor.
355
+ If 0, uses the file's MinLogProb header value.
356
+
357
+ Returns:
358
+ A cached (or newly-loaded) CJClassifier instance.
359
+ """
360
+ cache_key = f"{path or 'bundled'}:{log_prob_floor}"
361
+ if cache_key in _cache:
362
+ return _cache[cache_key]
363
+
364
+ if path is not None:
365
+ instance = cls._load_from_file(path, log_prob_floor)
366
+ else:
367
+ instance = cls._load_bundled(log_prob_floor)
368
+
369
+ _cache[cache_key] = instance
370
+ return instance
371
+
372
+ @classmethod
373
+ def clear_cached_models(cls):
374
+ """Clear loaded model(s), primarily for testing."""
375
+ _cache.clear()
376
+
377
+ @classmethod
378
+ def _load_bundled(cls, log_prob_floor: float) -> "CJClassifier":
379
+ """Load the bundled model from package resources."""
380
+ # Compatible with Python 3.8+
381
+ try:
382
+ # Python 3.9+
383
+ ref = importlib.resources.files("cjclassifier").joinpath("cjlogprobs.gz")
384
+ data = ref.read_bytes()
385
+ except AttributeError:
386
+ # Python 3.8 fallback
387
+ with importlib.resources.open_binary("cjclassifier", "cjlogprobs.gz") as f:
388
+ data = f.read()
389
+
390
+ text = gzip.decompress(data).decode("utf-8")
391
+ return cls._parse_model(text, "bundled:cjlogprobs.gz", log_prob_floor)
392
+
393
+ @classmethod
394
+ def _load_from_file(cls, path: str, log_prob_floor: float) -> "CJClassifier":
395
+ """Load a model from a filesystem path."""
396
+ if path.endswith(".gz"):
397
+ with gzip.open(path, "rt", encoding="utf-8") as f:
398
+ text = f.read()
399
+ else:
400
+ with open(path, "r", encoding="utf-8") as f:
401
+ text = f.read()
402
+ return cls._parse_model(text, path, log_prob_floor)
403
+
404
+ @classmethod
405
+ def _parse_model(cls, text: str, label: str, log_prob_floor: float) -> "CJClassifier":
406
+ """Parse the model file format into arrays."""
407
+ lines = text.split("\n")
408
+
409
+ # Parse header
410
+ header = lines[0]
411
+ if not header.startswith("Languages: "):
412
+ raise ValueError(f"Invalid model file (bad header): {label}")
413
+
414
+ header_parts = header.split(" ")
415
+ lang_codes = header_parts[1].split(",")
416
+ lang_map = []
417
+ for code in lang_codes:
418
+ lang = CJLanguage.from_string(code)
419
+ if lang is CJLanguage.UNKNOWN:
420
+ raise ValueError(f"Unknown CJ language in header: {code} in {label}")
421
+ lang_map.append(int(lang))
422
+
423
+ # Parse MinLogProb from header
424
+ parsed_min_prob = None
425
+ for i in range(len(header_parts) - 1):
426
+ if header_parts[i] == "MinLogProb:":
427
+ parsed_min_prob = float(header_parts[i + 1])
428
+ break
429
+
430
+ if log_prob_floor == 0.0:
431
+ if parsed_min_prob is None:
432
+ raise ValueError(
433
+ f"No MinLogProb in header and no explicit log_prob_floor: {label}"
434
+ )
435
+ default_log_prob = parsed_min_prob
436
+ else:
437
+ if parsed_min_prob is not None:
438
+ default_log_prob = max(log_prob_floor, parsed_min_prob)
439
+ else:
440
+ default_log_prob = log_prob_floor
441
+
442
+ # Parse unigram and bigram lines.
443
+ # Bigram data uses an open-addressing hash map backed by array.array
444
+ # to avoid the overhead of Python object boxing (~28 bytes per int/float
445
+ # vs 4 bytes in a C-level array).
446
+ unigram_log_probs = [0.0] * (_CJ_RANGE_SIZE * _LANG_COUNT)
447
+ bigram_builder = _BigramMapBuilder(16 * 1024)
448
+
449
+ unigram_count = 0
450
+ bigram_count = 0
451
+ probs = [0.0] * _LANG_COUNT # reused across bigram lines
452
+
453
+ for line in lines[1:]:
454
+ if not line:
455
+ continue
456
+ parts = line.split(" ")
457
+ key = parts[0]
458
+ if len(parts) != len(lang_map) + 1:
459
+ raise ValueError(f"Column count mismatch on line: {line} in {label}")
460
+
461
+ if len(key) == 1:
462
+ # Unigram
463
+ c = ord(key)
464
+ idx = c - _CJ_RANGE_START
465
+ if 0 <= idx < _CJ_RANGE_SIZE:
466
+ for col in range(len(lang_map)):
467
+ val = max(float(parts[col + 1]), default_log_prob)
468
+ unigram_log_probs[idx * _LANG_COUNT + lang_map[col]] = val
469
+ unigram_count += 1
470
+
471
+ elif len(key) == 2:
472
+ # Bigram
473
+ any_higher = False
474
+ for col in range(len(lang_map)):
475
+ val = float(parts[col + 1])
476
+ if val < default_log_prob or val == 0.0:
477
+ val = default_log_prob
478
+ else:
479
+ any_higher = True
480
+ probs[lang_map[col]] = val
481
+ if any_higher:
482
+ bigram_builder.put(ord(key[0]), ord(key[1]), probs)
483
+ bigram_count += 1
484
+
485
+ logger.info(
486
+ "Loaded %d unigrams and %d bigrams, minLogProb: %.2f, from %s",
487
+ unigram_count, bigram_count, default_log_prob, label,
488
+ )
489
+
490
+ return cls(unigram_log_probs, bigram_builder.build(), default_log_prob)
491
+
492
+ # ========================================================================
493
+ # Detection
494
+ # ========================================================================
495
+
496
+ def detect(self, text: str, results: Optional[Results] = None) -> CJLanguage:
497
+ """Detect the language of the given CJ text.
498
+
499
+ Args:
500
+ text: The text to classify.
501
+ results: Optional Results instance to populate with scoring details.
502
+
503
+ Returns:
504
+ The detected CJLanguage, or CJLanguage.UNKNOWN if undetermined.
505
+ """
506
+ if results is None:
507
+ results = Results()
508
+ else:
509
+ results.clear()
510
+ self.add_text(text, results.scores)
511
+ return self.compute_result(results)
512
+
513
+ def add_text(self, text: str, scores: Scores):
514
+ """Add text to the scoring accumulator.
515
+
516
+ This is the lower-level API for incremental classification.
517
+ Call compute_result() when all text has been added.
518
+
519
+ Args:
520
+ text: A chunk of CJ text to process.
521
+ scores: The Scores instance to accumulate into.
522
+ """
523
+ prev = 0
524
+ prev_in_range = False
525
+
526
+ unigram_log_probs = self._unigram_log_probs
527
+ bigram_map = self._bigram_map
528
+ bigram_prob_data = bigram_map.prob_data
529
+ default_log_prob = self._default_log_prob
530
+
531
+ for ch in text:
532
+ c = ord(ch)
533
+ if _is_kana(c):
534
+ scores.kana_count += 1
535
+ continue
536
+ in_range = _in_main_cj_range(c)
537
+ if in_range:
538
+ scores.cj_char_count += 1
539
+ # Unigram scoring
540
+ idx = c - _CJ_RANGE_START
541
+ base = idx * _LANG_COUNT
542
+ for li in range(_LANG_COUNT):
543
+ u_prob = unigram_log_probs[base + li]
544
+ scores.unigram_scores[li] += max(u_prob, default_log_prob)
545
+ if u_prob != 0:
546
+ scores.unigram_hits_per_lang[li] += 1
547
+
548
+ # Bigram scoring
549
+ if prev_in_range:
550
+ b_off = bigram_map.get_offset(prev, c)
551
+ if b_off != 0:
552
+ for li in range(_LANG_COUNT):
553
+ bp = bigram_prob_data[b_off + li]
554
+ scores.bigram_scores[li] += max(bp, default_log_prob)
555
+ if bp != 0:
556
+ scores.bigram_hits_per_lang[li] += 1
557
+
558
+ prev = c
559
+ prev_in_range = in_range
560
+
561
+ def compute_result(self, results: Results) -> CJLanguage:
562
+ """Compute the final language result from accumulated scores.
563
+
564
+ Args:
565
+ results: The Results instance containing accumulated scores.
566
+
567
+ Returns:
568
+ The detected CJLanguage, or CJLanguage.UNKNOWN if undetermined.
569
+ """
570
+ scores = results.scores
571
+
572
+ if scores.kana_count > 0:
573
+ kana_ratio = scores.kana_count / (scores.kana_count + scores.cj_char_count)
574
+ if kana_ratio > self._tolerated_kana_threshold:
575
+ results.result = CJLanguage.JAPANESE
576
+ results.gap = 1.0
577
+ results.total_scores[CJLanguage.JAPANESE] = 1.0
578
+ return results.result
579
+
580
+ if not scores.any_hits():
581
+ results.result = CJLanguage.UNKNOWN
582
+ results.gap = 0.0
583
+ return results.result
584
+
585
+ results._compute_totals(self._default_log_prob)
586
+
587
+ # Find best and second-best language
588
+ best_idx = 0
589
+ second_idx = -1
590
+ for li in range(1, _LANG_COUNT):
591
+ if results.total_scores[li] > results.total_scores[best_idx]:
592
+ second_idx = best_idx
593
+ best_idx = li
594
+ elif second_idx < 0 or results.total_scores[li] > results.total_scores[second_idx]:
595
+ second_idx = li
596
+
597
+ results.result = CJ_LANGUAGES[best_idx]
598
+
599
+ # Compute gap: 1 - (best / second). Scores are negative logprobs,
600
+ # so best is least negative.
601
+ best = results.total_scores[best_idx]
602
+ second = results.total_scores[second_idx] if second_idx >= 0 else best
603
+ results.gap = (1.0 - (best / second)) if second != 0.0 else 0.0
604
+
605
+ return results.result
@@ -0,0 +1,90 @@
1
+ # Copyright 2026 Jeremy Lilley (jeremy@jlilley.net)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Language enum for CJClassifier."""
16
+
17
+ from enum import IntEnum
18
+ from typing import Dict, List, Tuple
19
+
20
+
21
+ class CJLanguage(IntEnum):
22
+ """Represents the three CJ languages plus UNKNOWN.
23
+
24
+ The int value is the internal array index used by the classifier:
25
+ CHINESE_SIMPLIFIED=0, CHINESE_TRADITIONAL=1, JAPANESE=2, UNKNOWN=-1.
26
+ """
27
+
28
+ UNKNOWN = -1
29
+ CHINESE_SIMPLIFIED = 0
30
+ CHINESE_TRADITIONAL = 1
31
+ JAPANESE = 2
32
+
33
+ @property
34
+ def iso_code(self) -> str:
35
+ """ISO 639-1-style code (e.g. 'zh-hans', 'ja')."""
36
+ return _LANG_INFO[self][0]
37
+
38
+ @property
39
+ def iso_code3(self) -> str:
40
+ """ISO 639-3-style code (e.g. 'zho-hans', 'jpn')."""
41
+ return _LANG_INFO[self][1]
42
+
43
+ @property
44
+ def alt_names(self) -> List[str]:
45
+ """Alternate name strings recognized by from_string()."""
46
+ return list(_LANG_INFO[self][2])
47
+
48
+ def is_chinese(self) -> bool:
49
+ """True if this is CHINESE_SIMPLIFIED or CHINESE_TRADITIONAL."""
50
+ return self in (CJLanguage.CHINESE_SIMPLIFIED, CJLanguage.CHINESE_TRADITIONAL)
51
+
52
+ def is_japanese(self) -> bool:
53
+ """True if this is JAPANESE."""
54
+ return self is CJLanguage.JAPANESE
55
+
56
+ @classmethod
57
+ def from_string(cls, s: str) -> "CJLanguage":
58
+ """Look up a CJLanguage by name, ISO code, or alternate name (case-insensitive).
59
+
60
+ Returns UNKNOWN if not recognized.
61
+ """
62
+ if s is None:
63
+ return cls.UNKNOWN
64
+ return _BY_NAME.get(s.lower(), cls.UNKNOWN)
65
+
66
+
67
+ # Per-language metadata: (iso_code, iso_code3, alt_names)
68
+ _LANG_INFO: Dict[CJLanguage, Tuple[str, str, List[str]]] = {
69
+ CJLanguage.UNKNOWN: ("", "", []),
70
+ CJLanguage.CHINESE_SIMPLIFIED: (
71
+ "zh-hans", "zho-hans",
72
+ ["chinese", "zh", "zh-cn", "zh-hans-cn", "zh-hans-sg"],
73
+ ),
74
+ CJLanguage.CHINESE_TRADITIONAL: (
75
+ "zh-hant", "zho-hant",
76
+ ["zh-hant-hk", "zh-hk", "zh-hant-tw"],
77
+ ),
78
+ CJLanguage.JAPANESE: ("ja", "jpn", ["jp"]),
79
+ }
80
+
81
+ # Build the lookup table once at module load time.
82
+ _BY_NAME: Dict[str, CJLanguage] = {}
83
+ for _lang in CJLanguage:
84
+ _BY_NAME[_lang.name.lower()] = _lang
85
+ if _lang.iso_code:
86
+ _BY_NAME[_lang.iso_code] = _lang
87
+ if _lang.iso_code3:
88
+ _BY_NAME[_lang.iso_code3] = _lang
89
+ for _name in _lang.alt_names:
90
+ _BY_NAME[_name] = _lang
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: cjclassifier
3
+ Version: 1.0.2
4
+ Summary: Classify text as Chinese Simplified, Chinese Traditional, or Japanese using a statistical model.
5
+ Author-email: Jeremy Lilley <jeremy@jlilley.net>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/jlpka/cjclassifier
8
+ Project-URL: Repository, https://github.com/jlpka/cjclassifier
9
+ Keywords: chinese,japanese,language-detection,cjk,nlp
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Text Processing :: Linguistic
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Dynamic: license-file
18
+
19
+ # CJClassifier
20
+
21
+ A focused, pure-Python library for distinguishing between **Japanese**,
22
+ **Chinese Simplified**, and **Chinese Traditional** text using a statistical
23
+ model of ideograph frequencies built from Japanese and Chinese language Wikipedia
24
+ corpora.
25
+
26
+ No external dependencies. The bundled model is ~7 MB on disk and ~29 MB in
27
+ memory (loaded once and cached).
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install cjclassifier
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ from cjclassifier import CJClassifier, CJLanguage
39
+
40
+ cjc = CJClassifier.load()
41
+
42
+ cjc.detect("今天天气很好,我们去公园散步") # => CJLanguage.CHINESE_SIMPLIFIED
43
+ cjc.detect("今天天氣很好,我們去公園散步") # => CJLanguage.CHINESE_TRADITIONAL
44
+ cjc.detect("事務所") # => CJLanguage.JAPANESE (all Kanji)
45
+ cjc.detect("ひらがなとカタカナと") # => CJLanguage.JAPANESE (all kana)
46
+ cjc.detect("hello") # => CJLanguage.UNKNOWN
47
+ ```
48
+
49
+ ## Detailed results
50
+
51
+ ```python
52
+ from cjclassifier.classifier import Results
53
+
54
+ results = Results()
55
+ cjc.detect("今天天气很好", results)
56
+
57
+ results.result # CJLanguage.CHINESE_SIMPLIFIED
58
+ results.gap # confidence gap: 0 = dead heat, 1 = no contest
59
+ results.total_scores # per-language log-probability totals
60
+ results.to_short_string() # e.g. "zh-hans:1.00,zh-hant:0.97,ja:0.85"
61
+ ```
62
+
63
+ ## How it works
64
+
65
+ CJClassifier uses a **unigram + bigram statistical model** trained on the
66
+ Chinese and Japanese Wikipedia corpora. For every character and character-pair
67
+ in the CJ range, the model stores per-language log-probabilities. At
68
+ classification time the library sums these log-probabilities across the input
69
+ and picks the language with the highest score.
70
+
71
+ A Java implementation and the model-building tools are also available in the
72
+ same repository: [github.com/jlpka/cjclassifier](https://github.com/jlpka/cjclassifier)
73
+
74
+ ## License
75
+
76
+ Apache License 2.0
@@ -0,0 +1,9 @@
1
+ cjclassifier/__init__.py,sha256=HnqkDnoewd2ZCMR0EumFQ-FQ7SS5HafaQrsNQ9QaZnA,985
2
+ cjclassifier/cjlogprobs.gz,sha256=sPyx6C2sEdLhFxABK1Y_exnuPpLOagHn3oBryq38AS8,7597074
3
+ cjclassifier/classifier.py,sha256=fH4sdVA7uIr_CI8SUVqpdy8HDX0fSEKvY4P67lrs8wA,22152
4
+ cjclassifier/language.py,sha256=nZPBeWAEnAIWnd5bmcCvYXHnlYJ4uy7PMHjZG4GGTO0,2923
5
+ cjclassifier-1.0.2.dist-info/licenses/LICENSE,sha256=eL5ZFQlGwgXafnpu26n_FyrAToFQtQuKNecgNEiPiSM,11359
6
+ cjclassifier-1.0.2.dist-info/METADATA,sha256=ika04ZOlxLx7LU5Tz-6ytDBGU1nAfYcIBlxfX5YAEn0,2657
7
+ cjclassifier-1.0.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
+ cjclassifier-1.0.2.dist-info/top_level.txt,sha256=YgZwIODTloGw6uDvvgc7gEQqIkru_-c_XjrRmlnCbos,13
9
+ cjclassifier-1.0.2.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressed or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ cjclassifier