Arabic Iʿrāb AI – Interactive Model Tester

An interactive Python application for testing Iraab-v3-full, a language model specialized in Arabic grammatical analysis (الإعراب).

The application allows users to submit Arabic sentences and receive detailed word-by-word grammatical analysis in structured JSON format.

Features

  • Interactive command-line chat.
  • Arabic grammatical and morphological analysis.
  • Word-by-word parsing.
  • Detailed grammatical explanations.
  • Structured JSON output.
  • Arabic grammatical terminology.
  • GPU acceleration using Hugging Face Accelerate.
  • Token generation tracking.
  • Continuous sentence testing in one session.
  • No Hugging Face authentication required for the public model.

Model Information

Property Value
Model Iraab-v3-full
Hugging Face 6tarek/Iraab-v3-full
Framework PyTorch
Transformers Interface AutoModelForCausalLM
Tokenizer AutoTokenizer
Maximum New Tokens 1024
Output Format JSON
Primary Language Arabic

Requirements

  • Python 3.10+
  • PyTorch
  • Transformers
  • Accelerate
  • Internet connection for downloading the model
  • GPU recommended

Installation

pip install torch transformers accelerate

Complete Runnable Script

Save the following code as main.py or run it directly in Google Colab.

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

MAX_NEW_TOKENS = 1024

MODEL_ID = "6tarek/Iraab-v3-full"

print(f"Loading {MODEL_ID}...")

tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)

model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    torch_dtype="auto",
    device_map="auto"
)

print("Model loaded successfully!")
print("Device:", model.device)

# -------- CHAT --------

systemMsg = {
    "role": "system",
    "content": """
    You are a university-level professor and expert in Arabic grammar (i'rab).
Your task is to perform a deep syntactic and morphological analysis of an Arabic sentence.
The analysis must be returned in pure JSON format, matching the Pydantic schema provided.
Do not include any headings, explanations, introductions, or formatting outside of JSON.
Ensure the word order matches the input exactly.
Provide detailed grammatical reasoning based on classical Arabic grammar.
Include: the word, its part of speech, syntactic role, grammatical case, diacritic, and explanation.
Do not translate or simplify; use standard Arabic grammatical terminology.
The output must be in the same language as the input sentence.
Respond only with a JSON block and nothing else.
⚠️ Field **values** for 'type', 'position', and 'case' must be in Arabic (e.g. 'اسم', 'مفعول به', 'مرفوع').

## message:
وَٱلَّذِينَ إِذَا فَعَلُواْ فَٰحِشَةً أَوۡ ظَلَمُوٓاْ أَنفُسَهُمۡ ذَكَرُواْ ٱللَّهَ فَٱسۡتَغۡفَرُواْ لِذُنُوبِهِمۡ وَمَن يَغۡفِرُ ٱلذُّنُوبَ إِلَّا ٱللَّهُ وَلَمۡ يُصِرُّواْ عَلَىٰ مَا فَعَلُواْ وَهُمۡ يَعْلَمُونَ

## Pydantic Details:
{"$defs": {"WordI3rab": {"properties": {"word": {"description": "The word in the sentence.", "title": "Word", "type": "string"}, "type": {"description": "Part of speech: noun, verb, particle.", "title": "Type", "type": "string"}, "position": {"description": "Syntactic role: subject, object, predicate, etc.", "title": "Position", "type": "string"}, "case": {"description": "Grammatical case: nominative, accusative, genitive.", "title": "Case", "type": "string"}, "diacritic": {"description": "The main diacritic on the word.", "title": "Diacritic", "type": "string"}, "reason": {"description": "Explanation of the grammatical rule applied.", "title": "Reason", "type": "string"}}, "required": ["word", "type", "position", "case", "diacritic", "reason"], "title": "WordI3rab", "type": "object"}}, "properties": {"words": {"description": "Detailed i'rab (grammatical analysis) for each word.", "items": {"$ref": "#/$defs/WordI3rab"}, "title": "Words", "type": "array"}}, "required": ["words"], "title": "Main", "type": "object"}

## Your Output:
```json
"""
}

while True:

    user_input = input("\\nYou: ").strip()

    if user_input.lower() in ["exit", "quit"]:
        print("Goodbye!")
        break

    if not user_input:
        continue

    messages = [
        systemMsg,
        {
            "role": "user",
            "content": user_input
        }
    ]

    prompt = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True,
        enable_thinking=False
    )

    inputs = tokenizer(
        prompt,
        return_tensors="pt"
    ).to(model.device)

    with torch.inference_mode():
        outputs = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            pad_token_id=tokenizer.eos_token_id
        )

    response = tokenizer.decode(
        outputs[0][inputs["input_ids"].shape[1]:],
        skip_special_tokens=True
    )

    print("\\nModel:", response)

    print(
        "\\nTokens generated:",
        outputs.shape[1] - inputs["input_ids"].shape[1]
    )

Usage

Google Colab

  1. Open Google Colab.
  2. Create a new notebook.
  3. Select Runtime → Change runtime type → T4 GPU if available.
  4. Install the dependencies.
  5. Paste and execute the script.

Local Environment

Run:

python main.py

Example Interaction

Input:

ذهب أحمد إلى الامتحان

Expected JSON Structure:

{
  "words": [
    {
      "word": "ذهب",
      "type": "فعل",
      "position": "فعل",
      "case": "مبني",
      "diacritic": "فتحة",
      "reason": "فعل ماضٍ مبني على الفتح الظاهر على آخره."
    },
    {
      "word": "احمد",
      "type": "اسم",
      "position": "فاعل",
      "case": "مرفوع",
      "diacritic": "ضمة",
      "reason": "فاعل للفعل 'ذهب' مرفوع وعلامة رفعه الضمة الظاهرة على آخره."
    },
    {
      "word": "الى",
      "type": "حرف",
      "position": "حرف جر",
      "case": "مبني",
      "diacritic": "سكون",
      "reason": "حرف جر مبني على السكون لا محل له من الإعراب."
    },
    {
      "word": "الامتحان",
      "type": "اسم",
      "position": "اسم مجرور",
      "case": "مجرور",
      "diacritic": "كسرة",
      "reason": "اسم مجرور بـ 'إلى' وعلامة جره الكسرة الظاهرة على آخره."
    }
  ]
}

The example illustrates the expected structure, not a verified model response.

Output Schema

Field Description
word Original word from the input sentence.
type Part of speech: اسم، فعل، حرف.
position Syntactic role: فاعل، مفعول به، مبتدأ، خبر, etc.
case Grammatical status: مرفوع، منصوب، مجرور، مبني.
diacritic Main grammatical diacritic.
reason Explanation of the grammatical rule.

Configuration

The generation limit can be configured through:

MAX_NEW_TOKENS = 1024

The model is loaded directly from its public Hugging Face repository. No access token or account login is required.

Limitations

  • Grammatical predictions may contain errors and should be reviewed for academic use.
  • Long sentences may require more generation tokens.
  • GPU memory requirements depend on the model size and hardware.
  • The script requests JSON output but does not independently validate its correctness.

Author

Tarek Mahmoud Ali

License

Refer to the model repository for its licensing and usage conditions.


Project Purpose: Providing a straightforward interactive environment for testing the Arabic grammatical analysis capabilities of Iraab-v3-full.

Downloads last month
556
Safetensors
Model size
0.6B params
Tensor type
BF16
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support