Repository navigation
feat: add language-aware stemming support to RagTokenizer - #3356
Conversation
Add set_language() method to configure Snowball stemmer per language, enabling proper BM25 tokenization for Dutch, German, French, Spanish, and 12 other Snowball-supported languages. Changes: - Add _SNOWBALL_LANGUAGE_MAP for 17 supported languages - Add set_language() to switch stemmer at runtime - Extract _normalize_token() from inline stemming logic - Disable WordNet lemmatizer for non-English languages (WordNet only supports English) Default behavior (English) is unchanged. Callers that never call set_language() get identical results to before. Related: infiniflow/ragflow#14140
📝 WalkthroughWalkthroughThe pull request enhances the RAG tokenizer with language configuration capabilities via a new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@python/infinity_sdk/infinity/rag_tokenizer.py`:
- Around line 181-188: The unsupported-language else branch currently logs
"keeping defaults" but fails to reset tokenizer state, so prior non-English
stemmers persist; in the else branch that handles languages with no Snowball
stemmer (the block referencing language and the Snowball stemmer), explicitly
clear or reset any stemmer-related state (e.g., set the stemmer variable to None
or remove a SnowballStemmer instance, clear/restore use_stemmer/use_stemming
flags, and reset stopword lists to the default language set) so that after
calling the unsupported-language path (e.g., for CJK) no previous language's
stemming or stopword config remains active.
- Around line 394-398: The ASCII-only regex in _normalize_token (currently
re.match(r"[a-zA-Z_-]+$", t)) excludes accented letters so words like "niño" or
"français" skip stemming; replace the regex check with a Unicode-aware character
test (e.g., change the condition to: if all(ch.isalpha() or ch in "_-" for ch in
t): ) so tokens containing any Unicode letters plus underscores/dashes are
accepted, then continue to call self.lemmatizer.lemmatize and self.stemmer.stem
as before.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ebe363be-e3f9-4b4a-8007-6b35c5620153
📒 Files selected for processing (1)
python/infinity_sdk/infinity/rag_tokenizer.py
| else: | ||
| # Unsupported language (Chinese, Japanese, Korean, etc.) – | ||
| # keep defaults. CJK text uses dictionary segmentation, | ||
| # not stemming. | ||
| logging.debug( | ||
| "Language '%s' has no Snowball stemmer; keeping defaults", | ||
| language, | ||
| ) |
There was a problem hiding this comment.
Unsupported-language fallback currently preserves prior non-English stemmer state.
At Line 182, the comment/log says “keeping defaults”, but this branch does not reset tokenizer state. If a caller sets German first, then sets Chinese, German stemming remains active.
Suggested fix
else:
- # Unsupported language (Chinese, Japanese, Korean, etc.) –
- # keep defaults. CJK text uses dictionary segmentation,
- # not stemming.
+ # Unsupported language (Chinese, Japanese, Korean, etc.) –
+ # revert to default English normalization behavior.
+ self.stemmer = SnowballStemmer("english")
+ self.lemmatizer = WordNetLemmatizer()
+ self._use_lemmatizer = True
logging.debug(
- "Language '%s' has no Snowball stemmer; keeping defaults",
+ "Language '%s' has no Snowball stemmer; reverted to defaults",
language,
)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@python/infinity_sdk/infinity/rag_tokenizer.py` around lines 181 - 188, The
unsupported-language else branch currently logs "keeping defaults" but fails to
reset tokenizer state, so prior non-English stemmers persist; in the else branch
that handles languages with no Snowball stemmer (the block referencing language
and the Snowball stemmer), explicitly clear or reset any stemmer-related state
(e.g., set the stemmer variable to None or remove a SnowballStemmer instance,
clear/restore use_stemmer/use_stemming flags, and reset stopword lists to the
default language set) so that after calling the unsupported-language path (e.g.,
for CJK) no previous language's stemming or stopword config remains active.
| if re.match(r"[a-zA-Z_-]+$", t): | ||
| if self._use_lemmatizer: | ||
| return self.stemmer.stem(self.lemmatizer.lemmatize(t)) | ||
| return self.stemmer.stem(t) | ||
| return t |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify that the current regex excludes accented words used by supported Snowball languages.
uv run python - <<'PY'
import re
pat = re.compile(r"[a-zA-Z_-]+$")
tokens = ["niño", "français", "über", "garçon", "english_word", "co-operate"]
for t in tokens:
print(f"{t}: {bool(pat.match(t))}")
PYRepository: infiniflow/infinity
Length of output: 106
🏁 Script executed:
#!/bin/bash
# Test regex pattern with accented characters
python3 - <<'PY'
import re
pat = re.compile(r"[a-zA-Z_-]+$")
tokens = ["niño", "français", "über", "garçon", "english_word", "co-operate"]
print("Current regex [a-zA-Z_-]+$:")
for t in tokens:
match = bool(pat.match(t))
print(f" {t:20} -> {match}")
print("\nProposed fix (isalpha):")
for t in tokens:
result = bool(t and all(ch.isalpha() or ch in {"_", "-"} for ch in t))
print(f" {t:20} -> {result}")
PYRepository: infiniflow/infinity
Length of output: 492
🏁 Script executed:
# Inspect the actual code around line 394
head -415 python/infinity_sdk/infinity/rag_tokenizer.py | tail -25Repository: infiniflow/infinity
Length of output: 907
🏁 Script executed:
# Find the method containing this code and understand its purpose
grep -n "def " python/infinity_sdk/infinity/rag_tokenizer.py | tail -5Repository: infiniflow/infinity
Length of output: 214
🏁 Script executed:
# Check what stemmer library is being used and what languages it supports
rg -A 5 -B 5 "stemmer" python/infinity_sdk/infinity/rag_tokenizer.py | head -50Repository: infiniflow/infinity
Length of output: 1934
🏁 Script executed:
# Find the exact method name containing line 394
sed -n '350,400p' python/infinity_sdk/infinity/rag_tokenizer.py | grep -n "def "Repository: infiniflow/infinity
Length of output: 232
🏁 Script executed:
# Get full method context with proper line numbers
sed -n '375,410p' python/infinity_sdk/infinity/rag_tokenizer.pyRepository: infiniflow/infinity
Length of output: 1252
🏁 Script executed:
# Find SNOWBALL_LANGUAGE_MAP to see supported languages
rg "_SNOWBALL_LANGUAGE_MAP" -A 30 python/infinity_sdk/infinity/rag_tokenizer.pyRepository: infiniflow/infinity
Length of output: 2132
🏁 Script executed:
# Check if there are tests for this tokenizer
find python -name "*test*tokenizer*" -o -name "*tokenizer*test*" 2>/dev/null | head -10Repository: infiniflow/infinity
Length of output: 45
Fix regex in _normalize_token to support accented characters for non-English languages.
The regex [a-zA-Z_-]+$ at line 394 is ASCII-only and blocks tokens like niño, français, and über from being stemmed. Since the tokenizer supports 16 Snowball languages including German, French, Spanish, and Italian—many with accented characters—these words bypass stemming entirely, contradicting the documented behavior.
Replace the regex with character validation that handles Unicode letters:
Suggested fix
- if re.match(r"[a-zA-Z_-]+$", t):
+ if t and all(ch.isalpha() or ch in {"_", "-"} for ch in t):
if self._use_lemmatizer:
return self.stemmer.stem(self.lemmatizer.lemmatize(t))
return self.stemmer.stem(t)
return t🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@python/infinity_sdk/infinity/rag_tokenizer.py` around lines 394 - 398, The
ASCII-only regex in _normalize_token (currently re.match(r"[a-zA-Z_-]+$", t))
excludes accented letters so words like "niño" or "français" skip stemming;
replace the regex check with a Unicode-aware character test (e.g., change the
condition to: if all(ch.isalpha() or ch in "_-" for ch in t): ) so tokens
containing any Unicode letters plus underscores/dashes are accepted, then
continue to call self.lemmatizer.lemmatize and self.stemmer.stem as before.
|
Thanks @rwb-truelime , we will release a new version of Infinity soon. After that, RAGFlow can import the new file. |
### What problem does this PR solve? Update C++ tokenizer to match rag_tokenizer.py in #3356 ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
Summary
Add
set_language()method toRagTokenizerto configure the Snowball stemmer per language, enabling proper BM25 tokenization for Dutch, German, French, Spanish, and 12 other Snowball-supported languages.Motivation
RAGFlow's knowledge bases support a configurable language parameter, but the tokenizer always uses English stemming/lemmatization regardless of the configured language. This means non-English Latin-script languages get incorrect stems during BM25 indexing. For example, the Dutch word "huizen" (houses) should stem to "huis" but currently stems to "huizen" (English stemmer doesn't recognize it).
This was requested by the RAGFlow maintainer @qinling0210 in ragflow#14140 -- the language-aware tokenizer changes should live in the Infinity SDK so RAGFlow can import them.
Changes
_SNOWBALL_LANGUAGE_MAP: Maps 17 language names to NLTK Snowball stemmer namesset_language(language): Configures the stemmer for the given language. Disables the WordNet lemmatizer for non-English languages (WordNet only supports English)_normalize_token(t): Extracted from inline stemming logic intokenize()andenglish_normalize_(). Applies stemming (+ optional lemmatization) to alphabetic tokensenglish_normalize_(tks): Now delegates to_normalize_token()-- same behavior, less duplicationtokenize(): Uses_normalize_token()instead of hardcodedself.stemmer.stem(self.lemmatizer.lemmatize(t))Backward compatibility
__init__sets English stemmer + WordNet lemmatizer,_use_lemmatizer = Trueset_language()get identical resultsSnowballStemmeralready supports all listed languagesenglish_normalize_()produces identical output for English (refactored, not changed)Design notes
set_language()instead of per-call parameter? Matches the existing pattern wherestemmerandlemmatizerare instance attributes. RAGFlow task executor runs separate OS processes per worker, each configuring its tokenizer once per task.