Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(relevance,dedupe): CJK-aware tokenization for Chinese sources

An-idd026639614d7e
diff --git a/skills/last30days/scripts/lib/cjk.py b/skills/last30days/scripts/lib/cjk.py
new file mode 100644
index 00000000..2ebf8496
--- /dev/null
+++ b/skills/last30days/scripts/lib/cjk.py
@@ -0,0 +1,105 @@
+"""CJK-aware tokenization for relevance scoring and near-duplicate detection.
+
+The skill ships with zero hard dependencies (pyproject ``dependencies = []``)
+so it installs across 50+ Agent Skills hosts as plain Python. Chinese text has
+no whitespace word boundaries, so the original ``str.split()`` tokenizers in
+relevance.py / dedupe.py collapse a whole sentence into a single token and
+break token-overlap scoring and Jaccard de-duplication for Chinese sources
+(Xiaohongshu, Bilibili).
+
+``segment(text)`` fixes that. It splits text into maximal CJK and non-CJK runs:
+
+- Non-CJK (ASCII / Latin) runs keep the original ``\\w+`` word behaviour.
+- CJK runs are routed through jieba when it is installed (best quality), and
+ fall back to character bigrams when jieba is absent. Bigrams are a
+ dictionary-free segmentation that still gives robust overlap signal — e.g.
+ query "大模型" -> {大模, 模型} overlaps text "国产大模型评测" -> {..大模, 模型..}.
+
+jieba stays OPTIONAL: present -> used; absent -> bigram fallback. We never add
+it to the hard dependency set, preserving the install-anywhere property.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import List
+
+# CJK ideographs + Japanese kana + Korean hangul. The Chinese ideograph block
+# (一-鿿) and its extension-A (㐀-䶿) cover the cases we care
+# about; kana/hangul are included so mixed-language text degrades gracefully.
+_CJK_CHARS = r"㐀-䶿一-鿿豈-﫿぀-ヿ가-힯"
+_CJK_RE = re.compile(f"[{_CJK_CHARS}]")
+_CJK_RUN_RE = re.compile(f"[{_CJK_CHARS}]+")
+_LATIN_RE = re.compile(r"\w+")
+
+# High-frequency Chinese function words that dilute overlap signal, mirroring
+# the role of the English STOPWORDS sets in relevance.py / dedupe.py.
+CHINESE_STOPWORDS = frozenset(
+ {
+ "的", "了", "和", "是", "在", "我", "有", "也", "就", "不", "人", "都",
+ "一", "一个", "上", "很", "到", "说", "要", "去", "你", "会", "着",
+ "没有", "看", "好", "自己", "这", "那", "这个", "那个", "什么", "怎么",
+ "为什么", "以及", "或者", "但是", "因为", "所以", "如果", "可以",
+ "这样", "那样", "他们", "我们", "你们", "它", "她", "他", "吗", "呢",
+ "吧", "啊", "哦", "嗯", "与", "及", "等", "被", "把", "让", "给", "向",
+ "还", "再", "又", "从", "对", "为", "以", "之", "其", "中",
+ }
+)
+
+# Lazy, optional jieba. Import failure (not installed) leaves _jieba = None and
+# the bigram fallback handles CJK segmentation.
+_jieba = None
+_jieba_tried = False
+
+
+def _get_jieba():
+ global _jieba, _jieba_tried
+ if not _jieba_tried:
+ _jieba_tried = True
+ try:
+ import jieba # type: ignore
+
+ jieba.setLogLevel(60) # silence dictionary-build chatter on stderr
+ _jieba = jieba
+ except Exception:
+ _jieba = None
+ return _jieba
+
+
+def has_cjk(text: str) -> bool:
+ """True if the text contains any CJK / kana / hangul character."""
+ return bool(text) and _CJK_RE.search(text) is not None
+
+
+def _cjk_tokens(run: str) -> List[str]:
+ jieba = _get_jieba()
+ if jieba is not None:
+ return [w for w in jieba.cut(run) if w.strip() and _CJK_RE.search(w)]
+ # Dictionary-free fallback: character bigrams (single char if run length 1).
+ if len(run) <= 1:
+ return [run] if run else []
+ return [run[i:i + 2] for i in range(len(run) - 1)]
+
+
+def segment(text: str) -> List[str]:
+ """Tokenize mixed CJK / Latin text into a flat list of lowercased tokens.
+
+ CJK runs -> jieba words or character bigrams. Latin runs -> ``\\w+`` words.
+ Order is preserved; callers that want a set can wrap the result.
+ """
+ if not text:
+ return []
+ text = text.lower()
+ if not has_cjk(text):
+ return _LATIN_RE.findall(text)
+
+ out: List[str] = []
+ pos = 0
+ for match in _CJK_RUN_RE.finditer(text):
+ if match.start() > pos:
+ out.extend(_LATIN_RE.findall(text[pos:match.start()]))
+ out.extend(_cjk_tokens(match.group()))
+ pos = match.end()
+ if pos < len(text):
+ out.extend(_LATIN_RE.findall(text[pos:]))
+ return out
diff --git a/skills/last30days/scripts/lib/dedupe.py b/skills/last30days/scripts/lib/dedupe.py
index 43324404..7151addd 100644
--- a/skills/last30days/scripts/lib/dedupe.py
+++ b/skills/last30days/scripts/lib/dedupe.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import re
-from . import schema
+from . import cjk, schema
STOPWORDS = frozenset(
{
@@ -31,7 +31,7 @@ STOPWORDS = frozenset(
"do",
"can",
}
-)
+) | cjk.CHINESE_STOPWORDS
def normalize_text(text: str) -> str:
@@ -61,12 +61,12 @@ def jaccard_similarity(left: set[str], right: set[str]) -> float:
def token_jaccard(text_a: str, text_b: str) -> float:
tokens_a = {
token
- for token in normalize_text(text_a).split()
+ for token in cjk.segment(normalize_text(text_a))
if len(token) > 1 and token not in STOPWORDS
}
tokens_b = {
token
- for token in normalize_text(text_b).split()
+ for token in cjk.segment(normalize_text(text_b))
if len(token) > 1 and token not in STOPWORDS
}
return jaccard_similarity(tokens_a, tokens_b)
@@ -81,7 +81,7 @@ def hybrid_similarity(text_a: str, text_b: str) -> float:
def _tokenize(normalized: str) -> frozenset[str]:
return frozenset(
- tok for tok in normalized.split()
+ tok for tok in cjk.segment(normalized)
if len(tok) > 1 and tok not in STOPWORDS
)
diff --git a/skills/last30days/scripts/lib/relevance.py b/skills/last30days/scripts/lib/relevance.py
index c99051bd..c7cc49ca 100644
--- a/skills/last30days/scripts/lib/relevance.py
+++ b/skills/last30days/scripts/lib/relevance.py
@@ -9,6 +9,8 @@ The score is intentionally query-centric:
import re
from typing import List, Optional, Set
+from . import cjk
+
# Stopwords for relevance computation (common English words that dilute token overlap)
STOPWORDS = frozenset({
'the', 'a', 'an', 'to', 'for', 'how', 'is', 'in', 'of', 'on',
@@ -16,7 +18,7 @@ STOPWORDS = frozenset({
'your', 'i', 'me', 'we', 'you', 'what', 'are', 'do', 'can',
'its', 'be', 'or', 'not', 'no', 'so', 'if', 'but', 'about',
'all', 'just', 'get', 'has', 'have', 'was', 'will',
-})
+}) | cjk.CHINESE_STOPWORDS
# Synonym groups for relevance scoring (bidirectional expansion)
# Superset of all platform-specific synonym dicts
@@ -56,8 +58,12 @@ def tokenize(text: str) -> Set[str]:
"""Lowercase, strip punctuation, remove stopwords, drop single-char tokens.
Expands tokens with synonyms for better cross-domain matching.
+
+ Chinese text is segmented via cjk.segment (jieba or character bigrams) so
+ overlap scoring works on Chinese sources; ASCII text keeps the original
+ whitespace path.
"""
- words = re.sub(r'[^\w\s]', ' ', text.lower()).split()
+ words = cjk.segment(text)
tokens = {w for w in words if w not in STOPWORDS and len(w) > 1}
expanded = set(tokens)
for t in tokens:
diff --git a/tests/test_cjk.py b/tests/test_cjk.py
new file mode 100644
index 00000000..14216a31
--- /dev/null
+++ b/tests/test_cjk.py
@@ -0,0 +1,60 @@
+import unittest
+
+from lib import cjk, dedupe, relevance
+
+
+class TestCjkSegment(unittest.TestCase):
+ def test_has_cjk(self):
+ self.assertTrue(cjk.has_cjk("国产大模型"))
+ self.assertTrue(cjk.has_cjk("GPT4很强"))
+ self.assertFalse(cjk.has_cjk("hello world"))
+ self.assertFalse(cjk.has_cjk(""))
+
+ def test_ascii_path_unchanged(self):
+ # Non-CJK text keeps whitespace/word tokenization.
+ self.assertEqual(cjk.segment("best react hooks"), ["best", "react", "hooks"])
+
+ def test_chinese_bigrams(self):
+ # Without jieba installed, CJK runs become character bigrams.
+ toks = cjk.segment("大模型")
+ self.assertIn("大模", toks)
+ self.assertIn("模型", toks)
+
+ def test_mixed_language(self):
+ toks = cjk.segment("GPT4很强 react")
+ self.assertIn("gpt4", toks)
+ self.assertIn("react", toks)
+ self.assertIn("很强", toks)
+
+ def test_single_cjk_char(self):
+ self.assertEqual(cjk.segment("中"), ["中"])
+
+
+class TestChineseRelevance(unittest.TestCase):
+ def test_chinese_query_matches_chinese_text(self):
+ q = relevance.PreparedQuery("国产大模型 测评")
+ score = relevance.token_overlap_relevance(q, "这是国产大模型的最新测评")
+ self.assertGreater(score, 0.5)
+
+ def test_chinese_query_rejects_unrelated_text(self):
+ q = relevance.PreparedQuery("国产大模型 测评")
+ score = relevance.token_overlap_relevance(q, "今天天气很好适合出门散步")
+ self.assertEqual(score, 0.0)
+
+ def test_english_relevance_not_regressed(self):
+ q = relevance.PreparedQuery("react hooks")
+ self.assertGreaterEqual(relevance.token_overlap_relevance(q, "a guide to react hooks"), 0.9)
+
+
+class TestChineseDedupe(unittest.TestCase):
+ def test_reordered_chinese_is_near_duplicate(self):
+ sim = dedupe.hybrid_similarity("国产大模型最新测评对比", "国产大模型测评对比最新")
+ self.assertGreater(sim, 0.5)
+
+ def test_distinct_chinese_is_not_duplicate(self):
+ sim = dedupe.hybrid_similarity("国产大模型测评", "今天天气很好出门散步")
+ self.assertLess(sim, 0.3)
+
+
+if __name__ == "__main__":
+ unittest.main()