Metadata-Version: 2.5
Name: pyarud
Version: 2.0.0
Summary: A zero-dependency Python library for Arabic prosody (Arud) and rhyme (Qafiyah) analysis.
Project-URL: Homepage, https://github.com/cnemri/pyarud
Project-URL: Documentation, https://cnemri.github.io/pyarud/
Project-URL: Repository, https://github.com/cnemri/pyarud
Project-URL: Issues, https://github.com/cnemri/pyarud/issues
Author-email: Chouaieb Nemri <chouaib.nemri@gmail.com>
License: MIT License
        
        Copyright (c) 2022 Maged Saeed
        Copyright (c) 2025 Chouaieb Nemri
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: arabic,arud,arudh,bahr,meter,nlp,poetry,prosody,qafiyah,scansion
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: Arabic
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Typing :: Typed
Requires-Python: >=3.12
Provides-Extra: dev
Requires-Dist: mypy>=1.9.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.3.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5.0; extra == 'docs'
Requires-Dist: mkdocs>=1.5.0; extra == 'docs'
Requires-Dist: mkdocstrings[python]>=0.24.0; extra == 'docs'
Description-Content-Type: text/markdown

# PyArud (پَايْعَرُوضْ)

**PyArud** is a deterministic, high-performance, **zero-dependency** Python engine for Classical & Modern Arabic Prosody (*علم العروض والقافية*). It delivers formal Farahidian grammar scansion across all 16 classical meters (*البحور الستة عشر*) and their authentic sub-meters (*التام، المجزوء، المشطور، المنهوك، المخلّع*), opt-in support for the 6 neglected Farahidian circle meters (*البحور المهملة*), an extensible API for custom user-defined & modern free-verse (*التفعيلة*) meters, foot-by-foot Zihaf & 'Ilal diagnosis, and complete rhyme (*القافية*) & rhyme-fault (*عيوب القافية*) analysis.

[![PyPI](https://img.shields.io/pypi/v/pyarud)](https://pypi.org/project/pyarud/)
[![License](https://img.shields.io/github/license/cnemri/pyarud)](LICENSE)
[![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/)
[![Zero Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)]()

---

## ✨ Features

- **🚀 Zero Runtime Dependencies**: 100% pure Python 3.12+ standard library. No `pyarabic` or heavy C extensions.
- **⚡ High Throughput**:
  - Phonetic Arudi Alignment (`1:1` letter-to-bit bijection): **~10,000 hemistichs/second**
  - Full Deterministic Multi-Meter Verse Scansion: **>2,200 verses/second**
- **🎼 Full 16-Meter Farahidian Coverage + Opt-In Muhmal Pack**: All 16 classical meters (29 authentic forms across *Tam, Majzoo, Mashtoor, Manhook, Mukhalla'*), enforcing *المراقبة* (Muraqabah), *المعاقبة* (Mu'aqabah), *الاعتماد* (I'timad), and *التصريع* (Tasri'), plus an opt-in pack (`include_muhmal=True`) for the 6 neglected circle meters (*المستطيل، الممتد، المتوفر، المتئد، المنسرد، المطرد*).
- **🧩 Custom User-Defined & Free-Verse Meters**: Declarative, immutable `MeterSpec`, `TafeelaSpec`, `ProsodicRule`, fluent `MeterBuilder`, JSON/TOML loading, and persistent non-mutating `MeterRegistry` for modern *التفعيلة* free verse, asymmetric Andalusian *الموشحات*, and personal meters.
- **🔬 Granular Slot-Viterbi Foot Scansion**: Exact per-foot status (`ok`, `broken`, `missing`, `extra_bits`), real surface Arabic foot forms (`actual_tafeela` vs `base_tafeela`), per-foot Arudi text slices (`foot.arudi_text`), and exact Arabic & English Zihaf/'Ilal diagnosis.
- **📜 Complete Qafiyah & Rhyme-Fault Analysis**: Identifies Rawi (*الروي*), Wasl (*الوصل*), Khuruj (*الخروج*), Ridf (*الردف*), Ta'sees (*التأسيس*), Dakhil (*الدخيل*), all 6 classical movements (*المجرى، النفاذ، الحذو، الإشباع، الرس، التوجيه*), rhythmic & structural types, opening-verse Tasri', and poem-level rhyme faults (*الإقواء، الإصراف، الإكفاء، الإجازة، السناد، الإيطاء*).
- **🎨 Bilingual Formatters, CLI & Agent Skill**: `format_verse_report` / `format_poem_report` (`ar`/`en`, `pretty`/`compact`/`markdown`), zero-dep `pyarud` / `arud` CLI, `.to_dict()` / `.to_json()`, plus a bundled AI Agent Skill at [`skills/arud/SKILL.md`](skills/arud/SKILL.md).
- **🛡️ Strict Typing (PEP 561)**: Verified with `mypy --strict` across the entire package.

---

## 🚀 Installation

Requires **Python 3.12+**.

```bash
pip install pyarud
```

Or with `uv`:

```bash
uv add pyarud
```

---

## ⚡ Quick Start

```python
from pyarud import ArudProcessor, format_verse_report

processor = ArudProcessor()

# 1. Analyze a classical verse (Sadr & Ajuz)
verse = ("أَخِي جَاوَزَ الظَّالِمُونَ الْمَدَى", "فَحَقَّ الْجِهَادُ وَحَقَّ الْفِدَا")
analysis = processor.analyze_verse(*verse)

print(f"Meter: {analysis.meter_name_ar} ({analysis.meter_key}, {analysis.bahr_type})")
print(f"Score: {analysis.score:.2%} | Valid: {analysis.is_valid} | Tasri': {analysis.is_tasri}")

# Foot-by-foot breakdown with Arudi slices
if analysis.sadr:
    print(f"Sadr Arudi: {analysis.sadr.arudi_text}  [{analysis.sadr.pattern}]")
    for foot in analysis.sadr.feet:
        print(
            f"  [{foot.status.upper()}] {foot.actual_tafeela} ({foot.actual_segment}) "
            f"«{foot.arudi_text}» — {foot.zihaf_name_ar}"
        )

# Rhyme (Qafiyah)
if analysis.qafiyah:
    print(f"Rawi: {analysis.qafiyah.rawi} | Type: {analysis.qafiyah.qafiyah_type_ar}")

# Rich terminal or Markdown report (Arabic or English)
print(format_verse_report(analysis, lang="ar", style="pretty"))
```

### Analyzing Complete Poems & Rhyme Faults

```python
from pyarud import ArudProcessor

processor = ArudProcessor()
verses = [
    ("قِفَا نَبْكِ مِنْ ذِكْرَى حَبِيبٍ وَمَنْزِلِ", "بِسِقْطِ اللِّوَى بَيْنَ الدَّخُولِ فَحَوْمَلِ"),
    ("فَتُوضِحَ فَالْمِقْرَاةِ لَمْ يَعْفُ رَسْمُهَا", "لِمَا نَسَجَتْهَا مِنْ جَنُوبٍ وَشَمْأَلِ"),
]

poem = processor.analyze_poem(verses)
print(f"Global Meter: {poem.meter_name_ar} ({poem.bahr_type})")
print(f"Homogeneous: {poem.is_homogeneous} | Tasri': {poem.has_tasri}")
print(f"Dominant Rawi: {poem.dominant_rawi} | Rhyme Faults: {len(poem.rhyme_faults)}")
print(f"Average Confidence: {poem.average_score:.2%}")
```

### Custom User-Defined & Free-Verse Meters

```python
from pyarud import ArudProcessor, MeterSpec
from pyarud.meters.specs import EDMAAR, HATHATH, MUTAFAELON, QATAA, SALIM

# 1. Opt-in 6 neglected Farahidian meters (البحور المهملة)
muhmal_proc = ArudProcessor(include_muhmal=True)
res = muhmal_proc.analyze_verse(
    "لَقَدْ هَاجَ اشْتِيَاقِي غَزَالٌ فِي المَرَاعِي",
    "أَمِيرُ الحُسْنِ يَزْهُو عَلَى كُلِّ البِقَاعِ",
)
print(res.meter_name_ar, res.meter_key, res.is_valid)  # بحر المستطيل mustateel True

# 2. Modern Arabic free-verse (شعر التفعيلة) with variable foot count
free_kamel = MeterSpec.free_verse(
    key="tafeela_kamel",
    name_ar="تفعيلة الكامل",
    name_en="Free-Verse Kamel",
    foot=MUTAFAELON,
    min_feet=1,
    max_feet=8,
    ending_rules=(SALIM, EDMAAR, QATAA, HATHATH),
)
free_proc = ArudProcessor().with_meters(free_kamel, prefer_custom=True)
line = free_proc.analyze_verse("مُتَفَاعِلُنْ مُتَفَاعِلُنْ مُتَفَاعِلُنْ مُتَفَاعِلُنْ مُتَفَاعِلُنْ")
print(line.meter_name_ar, len(line.sadr.feet) if line.sadr else 0, line.is_valid)
```

---

## 💻 Command-Line Interface (`pyarud` / `arud`)

PyArud includes a zero-dependency CLI (`pyarud`, `arud`, or `python -m pyarud`) with UTF-8 JSON stdout, stderr error reporting, and CI-friendly `--strict` exit codes (`0` valid, `1` broken/rhyme fault, `2` error):

```bash
# Scan a classical verse (pretty, compact, markdown, or json)
pyarud scan "قِفَا نَبْكِ مِنْ ذِكْرَى حَبِيبٍ وَمَنْزِلِ ... بِسِقْطِ اللِّوَى بَيْنَ الدَّخُولِ فَحَوْمَلِ" --format json --strict

# Phonetic Kitabah 'Arudiyyah & classical //0 scansion
pyarud arudi "أَخِي جَاوَزَ الظَّالِمُونَ الْمَدَى" --notation classical

# Rhyme (Qafiyah) & poem-level rhyme-fault analysis
pyarud qafiyah -f poem.txt --format json

# Inspect meters (with opt-in Muhmal or custom TOML/JSON) & zihafs
pyarud meters --show taweel
pyarud zihafs --tafeela "فَعُولُنْ"

# Step-by-step pedagogical explanation
pyarud explain "أَخِي جَاوَزَ الظَّالِمُونَ الْمَدَى ... فَحَقَّ الْجِهَادُ وَحَقَّ الْفِدَا" --lang en
```

---

## 🤖 Arud AI Agent Skill (`skills/arud/`)

LLMs struggle with deterministic Arabic syllable counting and *Kitabah 'Arudiyyah* natively. This repository ships an open-standard **Arud Agent Skill** at [`skills/arud/SKILL.md`](skills/arud/SKILL.md) (with concise prosody, phonetics/Qafiyah, and custom-meter reference sheets under `skills/arud/references/`) that pairs any coding/writing agent with the `pyarud` CLI for a verified **Compose → Diacritize → Scan (`--strict --format json`) → Repair** loop.

Installable directly from this repo with Agent Skills tooling (excluded from the PyPI wheel to keep runtime packaging lean).

---

## 📊 Benchmarks & Test Coverage

Verified across **234 unit, classical, custom-meter, Qafiyah, CLI, Agent Skill, and real-world benchmark tests** (including 27 curated classical meter/sub-meter entries and 80 real diacritized poems from [Al-Diwan](https://www.aldiwan.net/) across all 16 meters):

| Metric | Result |
|---|---|
| **Full Test Suite** | **234 / 234 passed (~1.2s)** |
| **Classical & Unseen Meter Benchmarks** | **100.0% (27/27 curated + 80/80 unseen)** |
| **Arudi ↔ Binary 1:1 Alignment Invariant** | **100.0% (0 mismatches)** |
| **Phonetic Conversion Throughput** | **~10,000 hemistichs / sec** |
| **Full Verse Scansion Throughput** | **>2,200 verses / sec** |
| **External Runtime Dependencies** | **0 (Zero)** |

---

## 🛠️ Testing & Development

```bash
git clone https://github.com/cnemri/pyarud.git
cd pyarud

# Install dev dependencies (PEP 735 dependency-groups)
uv sync --group dev

# Run complete test suite
uv run pytest

# Lint & strict type check
uv run ruff check .
uv run mypy .
```

---

## 📄 Changelog & License

See [CHANGELOG.md](CHANGELOG.md) for full release notes (latest: **v2.0.0**).

This project is licensed under the [MIT License](LICENSE).
