Skip to content

Commit a1d7a2a

Browse files
authored
Merge pull request #50 from sagorbrur/feature/langdetect
Add language detection using FastText
2 parents b02fd6f + 4e4f530 commit a1d7a2a

7 files changed

Lines changed: 947 additions & 5 deletions

File tree

README.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ BNLP is a natural language processing toolkit for Bengali Language. This tool wi
2828
- [Batch Processing](#batch-processing)
2929
- [Async Model Loading](#async-model-loading)
3030
- [Spell Checking](#spell-checking)
31+
- [Language Detection](#language-detection)
3132

3233
## Installation
3334

@@ -327,6 +328,104 @@ prob = checker.word_probability("আমি")
327328
print(prob) # Higher = more common word
328329
```
329330

331+
## Language Detection
332+
333+
Fast and accurate language detection using FastText's language identification model. Supports 176 languages including Bengali.
334+
335+
```bash
336+
# Install with language detection support
337+
pip install bnlp_toolkit[langdetect]
338+
```
339+
340+
```python
341+
from bnlp import LanguageDetector, detect_language, is_bengali
342+
343+
# Create detector (downloads model automatically on first use)
344+
detector = LanguageDetector()
345+
346+
# Detect language
347+
result = detector.detect("আমি বাংলায় গান গাই")
348+
print(result.language) # 'bn'
349+
print(result.confidence) # ~0.99
350+
print(result.is_bengali) # True
351+
352+
# Get multiple predictions
353+
result = detector.detect("আমি বাংলায় গান গাই", top_k=3)
354+
print(result.all_predictions)
355+
# Output: [('bn', 0.99), ('hi', 0.005), ...]
356+
357+
# Check if text is Bengali
358+
print(detector.is_bengali("আমি বাংলায় গান গাই")) # True
359+
print(detector.is_bengali("Hello world")) # False
360+
361+
# Detect English
362+
result = detector.detect("Hello, this is English text")
363+
print(result.language) # 'en'
364+
print(result.is_bengali) # False
365+
```
366+
367+
### Convenience Functions
368+
369+
```python
370+
from bnlp import detect_language, is_bengali
371+
372+
# Quick language detection
373+
result = detect_language("আমি বাংলায় গান গাই")
374+
print(result.language) # 'bn'
375+
376+
# Quick Bengali check
377+
print(is_bengali("আমি বাংলায় গান গাই")) # True
378+
print(is_bengali("Hello world")) # False
379+
```
380+
381+
### Batch Detection
382+
383+
```python
384+
from bnlp import LanguageDetector
385+
386+
detector = LanguageDetector()
387+
388+
texts = ["আমি বাংলায় গান গাই", "Hello world", "Bonjour le monde"]
389+
results = detector.detect_batch(texts)
390+
391+
for text, result in zip(texts, results):
392+
print(f"{text[:20]}... -> {result.language} ({result.confidence:.2f})")
393+
```
394+
395+
### Mixed Language Detection
396+
397+
Detect code-mixed text (e.g., Bengali-English):
398+
399+
```python
400+
from bnlp import LanguageDetector
401+
402+
detector = LanguageDetector()
403+
404+
mixed_text = "আমি today বাংলায় গান গাই। This is mixed text।"
405+
languages = detector.detect_mixed(mixed_text)
406+
print(languages)
407+
# Output: {'bn': 0.5, 'en': 0.5}
408+
```
409+
410+
### Language Detection Options
411+
412+
```python
413+
from bnlp import LanguageDetector
414+
415+
# Custom confidence threshold
416+
detector = LanguageDetector(threshold=0.7)
417+
418+
# Use your own model file
419+
detector = LanguageDetector(model_path="/path/to/lid.176.ftz")
420+
421+
# Disable auto-download
422+
detector = LanguageDetector(auto_download=False)
423+
424+
# Get language name
425+
print(detector.get_language_name('bn')) # 'Bengali'
426+
print(detector.get_language_name('en')) # 'English'
427+
```
428+
330429
## Documentation
331430
Full documentation are available [here](https://sagorbrur.github.io/bnlp/)
332431

bnlp/__init__.py

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
__version__ = "4.3.0"
2+
__version__ = "4.4.0"
33

44
import os
55
from bnlp.tokenizer.basic import BasicTokenizer
@@ -28,8 +28,31 @@
2828

2929
from bnlp.corpus.corpus import BengaliCorpus
3030

31-
# Spell checking
32-
from bnlp.spellcheck import BengaliSpellChecker, SpellingError
31+
# Lazy imports for optional dependencies (spell checking, language detection)
32+
# These are loaded on-demand to avoid requiring symspellpy/fasttext at package load
33+
def __getattr__(name):
34+
"""Lazy load optional modules."""
35+
# Spell checking (requires symspellpy)
36+
if name == "BengaliSpellChecker":
37+
from bnlp.spellcheck import BengaliSpellChecker
38+
return BengaliSpellChecker
39+
elif name == "SpellingError":
40+
from bnlp.spellcheck import SpellingError
41+
return SpellingError
42+
# Language detection (requires fasttext)
43+
elif name == "LanguageDetector":
44+
from bnlp.langdetect import LanguageDetector
45+
return LanguageDetector
46+
elif name == "DetectionResult":
47+
from bnlp.langdetect import DetectionResult
48+
return DetectionResult
49+
elif name == "detect_language":
50+
from bnlp.langdetect import detect_language
51+
return detect_language
52+
elif name == "is_bengali":
53+
from bnlp.langdetect import is_bengali
54+
return is_bengali
55+
raise AttributeError(f"module 'bnlp' has no attribute '{name}'")
3356

3457
# Core module - Protocols, Pipeline, Exceptions, Batch Processing, Async Loading
3558
from bnlp.core import (

bnlp/langdetect/__init__.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
"""
2+
Bengali Language Detection Module
3+
4+
This module provides language detection capabilities for Bengali text
5+
using FastText's language identification model.
6+
"""
7+
8+
from bnlp.langdetect.detector import (
9+
LanguageDetector,
10+
DetectionResult,
11+
detect_language,
12+
is_bengali,
13+
)
14+
15+
__all__ = [
16+
"LanguageDetector",
17+
"DetectionResult",
18+
"detect_language",
19+
"is_bengali",
20+
]

0 commit comments

Comments
 (0)