DadmaTools Persian NLP Library

repository·main·Indexed 42 days ago

https://github.com/dadmatech/dadmatools

A comprehensive Python NLP library for the Persian language supporting Python 10, 11, and 12. It provides tools for tokenization, lemmatization, POS tagging, dependency parsing, NER, and sentiment analysis. The library integrates with spaCy, PyTorch, and Transformers, and includes utilities for loading Persian NLP datasets and word embeddings (GloVe, FastText, Word2Vec), as well as a CLI for model conversion and inference.

Tokens
11K
Snippets
33
Records
45
Agent score
52%

What's inside DadmaTools

  1. Overview of DadmaTools NLP capabilities

    main

    DadmaTools provides a wide range of Natural Language Processing (NLP) resources specifically for Persian. Key features include:

    • Syntactic Analysis: Part of Speech (POS) Tagging, Dependency Parsing, Constituency Parsing, and Chunking.
    • Morphological Analysis: Tokenization, Lemmatization, and Kasreh Ezafe Detection.
    • Text Normalization & Cleaning: Normalizer, Spellchecker, and Informal-to-Formal text conversion.
    • Semantic & Higher-level Tasks: Named Entity Recognition (NER), Sentiment Analysis, and support for Persian embeddings and datasets.

    The library is designed for industrial applicability and supports integration with popular frameworks like spaCy, Transformers, and PyTorch.

  2. Overview of DadmaTools for Persian NLP

    main

    DadmaTools is a collection of Natural Language Processing (NLP) resources specifically designed for the Persian language. It provides datasets, embeddings, and models for various NLP tasks. The library is designed for industrial applicability and is licensed for commercial use. It integrates with popular NLP and Deep Learning frameworks, including:

    • NLP Frameworks: spaCy, Transformers, and Flair.
    • Deep Learning Frameworks: PyTorch.
  3. Explore DadmaTools NLP tasks and features

    main

    DadmaTools provides a suite of NLP (Natural Language Processing) capabilities. You can use the library to perform various linguistic tasks including text normalization, lemmatization, part-of-speech tagging, and syntactic parsing.

    Available feature sets include:

    • Datasets: Access to various linguistic datasets.
    • Word Embeddings: Vector representations of words.
    • Normalizer: Text cleaning and normalization.
    • Lemmatizer: Reducing words to their base/dictionary form.
    • POS Tagger: Assigning parts of speech to tokens.
    • Dependency Parser: Analyzing grammatical relationships between words.
    • Constituency Parser: Analyzing the hierarchical structure of sentences.
    • Chunker: Grouping words into meaningful phrases (chunks).
  4. Understand Persian Part-of-Speech (POS) tagging in DadmaTools

    main

    DadmaTools provides Part-of-Speech (POS) tagging for Persian text, which classifies words into categories (word classes) based on their definition and context (e.g., identifying whether a word is a noun, verb, or adjective).

    POS tagging is primarily used as a pre-processing step to facilitate more complex NLP tasks. The tags used in DadmaTools follow the Universal Tags standard.

  5. Access NLP annotations via spaCy Doc object

    main

    When using the Pipeline, the resulting doc is a spaCy Doc object. You can access standard spaCy attributes and custom DadmaTools extensions directly through the object.

    Standard spaCy attributes:

    • doc.text, doc.ents, doc.sents
    • token.pos_, token.lemma_, token.dep_, token.head

    Custom DadmaTools extensions:

    • token._.kasreh: Access Kasreh Ezafe information.
    • doc._.lang: Access the language attribute.
    • doc._.sentiment: Access sentiment analysis results.
    • doc._.spellchecker: Access spellchecker results.
    # Access token information
    for token in doc:
        print(f"Token: {token.text}, POS: {token.pos_}, Lemma: {token.lemma_}, Dep: {token.dep_")
    
    # Access entities
    for ent in doc.ents:
        print(f"Entity: {ent.text}, Type: {ent.label_}")
    
    # Access custom attributes
    print(f"Language: {doc._.lang}")
    print(f"Sentiment: {doc._.sentiment}")
    
    # Use spaCy utilities
    from spacy import displacy
    displacy.serve(doc, style="dep")
  6. Use pretrained Persian embeddings with dadmatools.embeddings

    main

    You can interact with Persian word embeddings using the dadmatools.embeddings module. This allows you to retrieve embedding information, load specific models, and perform vector operations like finding nearest neighbors, calculating similarity, or generating embeddings for text.

    Workflow

    1. Inspect available models: Use get_all_embeddings_info() to see all supported models.
    2. Get model metadata: Use get_embedding_info(name) to get details about a specific model.
    3. Load a model: Use get_embedding(name) to load the embedding object.
    4. Perform operations: Once loaded, you can access word vectors, retrieve the vocabulary, find nearest neighbors, check similarity, or embed full text strings.
    from dadmatools.embeddings import get_embedding, get_all_embeddings_info, get_embedding_info
    from pprint import pprint
    
    # 1. Inspect all available embeddings
    pprint(get_all_embeddings_info())
    
    # 2. Get info for a specific model
    embedding_info = get_embedding_info('glove-wiki')
    
    # 3. Load the embedding model
    word_embedding = get_embedding('glove-wiki')
    
    # 4. Perform operations
    # Get vector for a specific word
    print(word_embedding['سلام'])
    
    # Get the vocabulary
    vocab = word_embedding.get_vocab()
    
    # Find top 10 nearest neighbors for a word
    print(word_embedding.top_nearest("زمستان", 10))
    
    # Calculate similarity between two words
    print(word_embedding.similarity('کتب', 'کتاب'))
    
    # Generate embedding for a full text string
    print(word_embedding.embedding_text('امروز هوای خوبی بود'))
  7. Load Persian NLP datasets

    main

    DadmaTools provides an easy way to load popular Persian NLP datasets. Each dataset is provided as an iterator (e.g., .train, .test, .dev, or .data) and can be used in loops or as generators.

    Supported datasets include:

    • Named Entity Recognition (NER): PersianNER, ARMAN, Peyma
    • Textual Entailment: FarsTail
    • Spell Checking: FaSpell
    • Text Classification: PersianNews
    • Universal Dependency: PerUDT
    • Text Summarization: PnSummary
    • Sentiment Classification: SnappfoodSentiment
    • Text Translation (eng-fa): TEP
    • Corpus: WikipediaCorpus, PersianTweets
    from dadmatools.datasets import FarsTail, SnappfoodSentiment, Peyma, PerUDT, PersianTweets, PnSummary
    
    # Initialize a dataset
    farstail = FarsTail()
    
    # Access splits (e.g., train, test, dev)
    print(len(farstail.train))
    print(next(farstail.train))
    
    # Loop over items in a split
    snappfood_sa = SnappfoodSentiment()
    for i, item in enumerate(snpfood_sa.test):
        print(item['comment'], item['label'])
  8. Load and use Persian word embeddings

    main

    DadmaTools supports glove, fasttext, and word2vec formats. To use fasttext-based embeddings, you must first install the fasttext library via pip install fasttext.

    Supported embeddings:

    • glove-wiki: GloVe algorithm trained on Wikipedia
    • fasttext-commoncrawl-bin: FastText algorithm trained on CommonCrawl (binary format)
    • fasttext-commoncrawl-vec: FastText algorithm trained on CommonCrawl (vector format)
    • word2vec-conll: Word2Vec algorithm trained on Persian CoNLL17 corpus

    Once loaded, you can perform vector lookups, find nearest neighbors, calculate similarity, or generate embeddings for entire text strings.

    from dadmatools.embeddings import get_embedding, get_all_embeddings_info, get_embedding_info
    
    # Get info on all available embeddings
    print(get_all_embeddings_info())
    
    # Load a specific embedding (e.g., glove-wiki)
    word_embedding = get_embedding('glove-wiki')
    
    # Get vector for a word
    vector = word_embedding['سلام']
    
    # Get vocabulary
    vocab = word_embedding.get_vocab()
    
    # Useful operations
    print(word_embedding.top_nearest("زمستان", 10))
    print(word_embedding.similarity('کتب', 'کتاب'))
    print(word_embedding.embedding_text('امروز هوای خوبی بود'))
  9. Use Dependency Parsing and Noun Phrase Chunking in the pipeline

    main

    You can perform dependency parsing and noun phrase chunking by adding specific tokens to your dadmatools pipeline.

    • To use only dependency parsing, add dep to the pipeline.
    • To use only noun phrase chunking, add chunk to the pipeline.
    • To use both features, add dep,chunk to the pipeline.

    Dependency parsing extracts a directed graph of grammatical structures where nodes are words and edges are triplets consisting of a head, a dependent, and a dependency label. Noun phrase chunking groups words into syntactic phrases, identifying components like pronouns (PRON), proper nouns (PROPN), or nouns (NOUN) along with their modifiers (e.g., ADJ).

    # Example of how to configure the pipeline (conceptual usage based on documentation)
    # To use both dependency parsing and chunking:
    pipeline = ["dep", "chunk"]
  10. Perform Named Entity Recognition (NER) with DadmaTools

    main
    Named Entity Recognition (NER) allows you to extract named entities such as locations, organizations, and persons from raw text. DadmaTools provides access to popular NER models, including BERT-based models that are continuously trained on datasets like ARMAN and Peyma. Currently, these tools are specifically available for the Danish language.
  11. Access Persian NLP datasets via dadmatools.datasets

    main

    The dadmatools.datasets module provides programmatic access to several publicly available Persian NLP datasets. Each dataset class typically exposes splits such as .train, .test, .dev, or .data.

    Datasets are designed to be iterable, similar to generators. You can access individual items using next() or loop over them directly. Some datasets also provide an .info attribute for metadata.

    Available Datasets

    DatasetTask
    PersianNERNamed Entity Recognition
    ARMANNamed Entity Recognition
    PeymaNamed Entity Recognition
    FarsTailTextual Entailment
    FaSpellSpell Checking
    PersianNewsText Classification
    PerUDTUniversal Dependency
    PnSummaryText Summarization
    SnappfoodSentimentSentiment Classification
    TEPText Translation (eng-fa)
    WikipediaCorpusCorpus
    PersianTweetsCorpus
    from dadmatools.datasets import FarsTail, SnappfoodSentiment, Peyma, PerUDT, PersianTweets, PnSummary
    
    # Accessing splits and iterating
    farstail = FarsTail()
    print(len(farstail.train))  # Get length of train split
    print(next(farstail.train)) # Get next item
    
    # Accessing dataset info
    pn_summary = PnSummary()
    print(pn_summary.info)
    
    # Looping over test split
    snappfood_sa = SnappfoodSentiment()
    for i, item in enumerate(snpfood_sa.test):
        print(item['comment'], item['label'])
    
    # Accessing specific fields (e.g., lemma in PerUDT)
    perudt = PerUDT()
    for token_list in perudt.dev:
        print(token_list[0]['lemma'])
    
    # Accessing NER tags in Peyma
    peyma = Peyma()
    print(next(peyma.data)[0]['tag'])
    
    # Accessing corpus data
    tweets = PersianTweets()
    print(len(tweets.data))
    print(next(tweets.data))
  12. Perform sequence labelling with BERT Pipeline

    main

    For advanced NLP tasks like Part-of-Speech (POS) tagging, dependency parsing, constituency parsing, and Named Entity Recognition (NER), use the Pipeline class from dadmatools.pipeline_v1.language.

    When you initialize a Pipeline with specific tasks, it automatically loads the necessary components (like the lemmatizer, POS tagger, and tokenizer).

    Workflow:

    1. Define the required tasks as a comma-separated string (e.g., 'pos,dep,cons,ner').
    2. Initialize the Pipeline.
    3. Pass text to the pipeline object to receive a spaCy Doc object.
    4. Use language.to_json() to export analysis results to a dictionary format.
    5. Access NER results via the doc._.ners attribute.
    import dadmatools.pipeline_v1.language as language
    
    # Define tasks: pos (part-of-speech), dep (dependency), cons (constituency), ner (named entity recognition)
    pips = 'pos,dep,cons,ner'
    nlp = language.Pipeline(pips)
    
    # Inspect the loaded pipeline components
    print(nlp.analyze_pipes(pretty=True))
    
    # Process text - returns a spaCy Doc object
    doc = nlp('از قصهٔ کودکیشان که می‌گفت، گاهی حرص می‌خورد!')
    
    # Export analysis to JSON-compatible dictionary
    dictionary = language.to_json(pips, doc)
    print(dictionary)
    
    # Access NER results specifically
    print(doc._.ners)