BNLP: Bengali Natural Language Processing Toolkit

repository·main·Indexed 43 days ago

https://github.com/sagorbrur/bnlp

A comprehensive NLP toolkit for the Bengali language providing tools for tokenization, POS tagging, NER, spell checking, and text cleaning. It includes support for pretrained models such as Word2Vec, FastText, GloVe, and Doc2Vec, as well as a Pipeline API for chaining operations and a CLI for quick text processing.

Tokens
15.1K
Snippets
72
Records
75
Agent score
54%

What's inside BNLP

  1. Use the LanguageDetector class

    main

    The LanguageDetector class provides high-performance language identification using FastText. It automatically downloads the required model on its first use unless configured otherwise.

    Key capabilities:

    • Single detection: Detect the primary language and confidence score.
    • Top-K predictions: Retrieve multiple possible language candidates.
    • Bengali check: Quickly verify if text is Bengali.
    • Batch processing: Detect languages for a list of strings efficiently.
    • Mixed language detection: Identify proportions of different languages in code-mixed text (e.g., Bengali-English).
    from bnlp import LanguageDetector
    
    detector = LanguageDetector()
    result = detector.detect("আমি বাংলায় গান গাই")
    print(result.language)      # 'bn'
    print(result.confidence)    # ~0.99
    print(result.is_bengali)    # True
  2. Proposed BNLP Directory Structure

    main

    The BNLP package is undergoing a refactoring to improve modularity and type safety. The new structure organizes features into specialized submodules, making it easier to locate specific NLP components like tokenizers, embeddings, and transformers.

    Key modules include:

    • core/: Contains core abstractions, protocols, and the Pipeline API.
    • tokenizer/: Houses various tokenizer implementations (basic, nltk, sentencepiece).
    • embedding/: Provides word, document, and sentence embedding models (word2vec, fasttext, glove, doc2vec, sentence).
    • token_classification/: Includes POS tagging, NER, and training utilities.
    • transformers/: Provides modern model support (BERT, T5).
    • cleantext/: Handles text cleaning and normalization.
    • augmentation/: Provides text augmentation capabilities.
    • corpus/: Manages corpora and stopwords.
    • utils/: Contains shared utilities like config, downloader, and logging.
    • cli/: Provides the command-line interface.
    bnlp/
    ├── __init__.py              # Public API exports
    ├── _version.py              # Version info
    ├── core/                    # NEW: Core abstractions
    │   ├── protocols.py         # Protocol definitions
    │   ├── pipeline.py          # Pipeline API
    │   └── base.py              # Base classes
    ├── tokenizer/
    │   ├── base.py              # NEW: TokenizerProtocol
    │   ├── basic.py
    │   ├── nltk.py
    │   └── sentencepiece.py
    ├── embedding/
    │   ├── base.py              # NEW: EmbeddingProtocol
    │   ├── word2vec.py
    │   ├── fasttext.py
    │   ├── glove.py
    │   ├── doc2vec.py
    │   └── sentence.py          # NEW: Sentence embeddings
    ├── token_classification/
    │   ├── base.py              # NEW: TaggerProtocol
    │   ├── pos.py
    │   ├── ner.py
    │   └── trainer.py           # Renamed for clarity
    ├── transformers/            # NEW: Modern models
    │   ├── bert.py
    │   └── t5.py
    ├── cleantext/
    │   ├── clean.py
    │   ├── normalize.py         # NEW: Normalization
    │   └── constants.py
    ├── augmentation/
    │   └── augmenter.py
    ├── corpus/
    │   ├── corpus.py
    │   └── _stopwords.py
    ├── utils/
    │   ├── config.py
    │   ├── downloader.py
    │   ├── utils.py
    │   └── logging.py           # NEW: Centralized logging
    └── cli/                     # NEW: Command-line interface
        └── main.py
    └── py.typed                 # NEW: PEP 561 marker
  3. Integrate Transformer-based models with BNLP

    main

    The project roadmap includes support for modern Bengali transformer models. Developers looking for high-performance embeddings can look for integration with models like BanglaBERT or BanglaT5 (e.g., from sagorsarker/bangla-bert-base or csebuetnlp/csebuetnlp).

    Proposed usage pattern:

    from bnlp.transformers import BanglaBERT, BanglaT5
    
    model = BanglaBERT()
    embeddings = model.encode("আমি বাংলায় গান গাই।")
  4. Install bnlp_toolkit via PIP

    main

    You can install the BNLP toolkit using pip. It supports Python versions 3.8 through 3.13 on Linux, Windows, and Mac.

    To install:

    pip install bnlp_toolkit

    To upgrade to the latest version:

    pip install -U bnlp_toolkit
  5. Use pretrained Bengali Doc2Vec models

    main

    BNLP provides two pretrained BengaliDoc2vec models that are automatically downloaded when initialized. You can choose between a model trained on news articles or one trained on Wikipedia.

    To use them, pass the corresponding identifier to the model_path argument of BengaliDoc2vec():

    • NEWS_DOC2VEC: Model trained on News Article dataset.
    • WIKI_DOC2VEC: Model trained on Wikipedia Dump dataset.

    If no model_path is provided, NEWS_DOC2VEC is selected by default.

    from bnlp import BengaliDoc2vec
    
    # Use the news-trained model
    model_key = "NEWS_DOC2VEC"
    bn_doc2vec = BengaliDoc2vec(model_path=model_key)
  6. Install FastText dependency for BNLP

    main

    To use FastText features in BNLP, you must install the fasttext library. You can do this via standard pip or by using the BNLP toolkit extra:

    pip install fasttext==0.9.2
    # OR
    pip install bnlp_toolkit[fasttext]

    Note for Windows users: You may need to follow specific instructions for building the fasttext python wrapper from source.

  7. Use a custom Doc2Vec model

    main

    You can load your own trained Doc2Vec model by passing the local file path to the model_path argument in BengaliDoc2vec().

    Note: Ensure that any associated .npy model files are kept in the same directory as the .pkl model file.

    from bnlp import BengaliDoc2vec
    
    own_model_path = "own_directory/own_doc2vec_model.pkl"
    bn_doc2vec = BengaliDoc2vec(model_path=own_model_path)
    
    document = "আপনার টেক্সট"
    vector = bn_doc2vec.get_document_vector(document)
  8. Configure LanguageDetector options

    main

    When initializing LanguageDetector, you can pass several configuration parameters:

    • threshold: Set a custom confidence threshold.
    • model_path: Provide a path to a specific FastText model file (e.g., lid.176.ftz).
    • auto_download: Set to False to prevent automatic model downloading.

    You can also use detector.get_language_name(lang_code) to retrieve the full name of a language code.

    from bnlp import LanguageDetector
    
    # Custom threshold
    detector = LanguageDetector(threshold=0.7)
    
    # Custom model path
    detector = LanguageDetector(model_path="/path/to/lid.176.ftz")
    
    # Disable auto-download
    detector = LanguageDetector(auto_download=False)
    
    # Get language name
    print(detector.get_language_name('bn'))  # 'Bengali'