Skip to content

feat: add language-aware stemming support to RagTokenizer - #3356

Merged
yingfeng merged 1 commit into
infiniflow:mainfrom
rwb-truelime:feature/language-aware-stemming
May 6, 2026
Merged

yingfeng merged 1 commit into
infiniflow:mainfrom
rwb-truelime:feature/language-aware-stemming

Conversation

@rwb-truelime

@rwb-truelime rwb-truelime commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add set_language() method to RagTokenizer to 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 names
  • set_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 in tokenize() and english_normalize_(). Applies stemming (+ optional lemmatization) to alphabetic tokens
  • english_normalize_(tks): Now delegates to _normalize_token() -- same behavior, less duplication
  • tokenize(): Uses _normalize_token() instead of hardcoded self.stemmer.stem(self.lemmatizer.lemmatize(t))

Backward compatibility

  • Default behavior is unchanged: __init__ sets English stemmer + WordNet lemmatizer, _use_lemmatizer = True
  • Callers that never call set_language() get identical results
  • No new dependencies -- NLTK SnowballStemmer already supports all listed languages
  • english_normalize_() produces identical output for English (refactored, not changed)

Design notes

  • Why set_language() instead of per-call parameter? Matches the existing pattern where stemmer and lemmatizer are instance attributes. RAGFlow task executor runs separate OS processes per worker, each configuring its tokenizer once per task.
  • WordNet limitation: WordNet only has English lemma data. For non-English languages, we skip lemmatization and apply Snowball stemming directly. This is standard -- Snowball stemmers are designed to work standalone.
  • CJK languages: Languages without Snowball support (Chinese, Japanese, Korean, etc.) keep the default English stemmer. Harmless because CJK text uses dictionary segmentation, not stemming.

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
@coderabbitai

coderabbitai Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The pull request enhances the RAG tokenizer with language configuration capabilities via a new set_language() method, enabling dynamic switching of Snowball stemming languages. Token normalization logic is refactored into a reusable _normalize_token() helper method that centralizes stemming and lemmatization behavior, with WordNet lemmatization restricted to English. Debug logging is added for language selection tracking.

Changes

Cohort / File(s) Summary
RAG Tokenizer Enhancement
python/infinity_sdk/infinity/rag_tokenizer.py
Added set_language() method for language configuration. Introduced _normalize_token() helper to centralize token normalization logic. Made WordNet lemmatization conditional on English language. Enhanced debug logging for language selection and unsupported language detection.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A tokenizer hops with new grace,
Languages switch at a quickened pace,
Snowballs stem in every tongue,
While lemmas dance (for English, sung),
Normalization flows, oh what a race! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: adding language-aware stemming support to RagTokenizer.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description provides comprehensive context, motivation, detailed change description, and backward compatibility assurances.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 72028e6 and c000a70.

📒 Files selected for processing (1)
  • python/infinity_sdk/infinity/rag_tokenizer.py

Comment on lines +181 to +188
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,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Comment on lines +394 to +398
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 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))}")
PY

Repository: 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}")
PY

Repository: 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 -25

Repository: 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 -5

Repository: 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 -50

Repository: 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.py

Repository: 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.py

Repository: 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 -10

Repository: 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.

@yingfeng yingfeng added the ci PR can be test label Apr 30, 2026
@yingfeng
yingfeng marked this pull request as draft April 30, 2026 06:31
@yingfeng
yingfeng marked this pull request as ready for review April 30, 2026 06:31
@qinling0210

Copy link
Copy Markdown
Contributor

Thanks @rwb-truelime , we will release a new version of Infinity soon. After that, RAGFlow can import the new file.

@yingfeng
yingfeng merged commit c2e21a0 into infiniflow:main May 6, 2026
50 checks passed
yingfeng pushed a commit that referenced this pull request May 6, 2026
### 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci PR can be test

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants