Skip to content

API Reference

Complete auto-generated reference for PyArud's strictly typed (mypy --strict), zero-dependency public Python API.

Ergonomic Aliases & JSON Serialization

ArudProcessor is exported as a first-class alias for ArudhProcessor. Every analysis dataclass (VerseAnalysis, PoemAnalysis, ShatrAnalysis, FootAnalysis, QafiyahAnalysis, RhymeFault, MeterMatchCandidate) supports .to_dict() and .to_json(ensure_ascii=False).

Prosody Processor (ArudProcessor / ArudhProcessor)

pyarud.processor.ArudhProcessor

Prosodic Engine for Arabic Poetry.

Performs phonetic Arudi alignment, deterministic meter identification across classical, Muhmal, free-verse, and custom user-defined meters, foot-by-foot Zihaf/'Ilal diagnosis, and poem-level Qafiyah & rhyme-fault analysis.

Source code in pyarud/processor.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
class ArudhProcessor:
    """
    Prosodic Engine for Arabic Poetry.

    Performs phonetic Arudi alignment, deterministic meter identification across
    classical, Muhmal, free-verse, and custom user-defined meters, foot-by-foot
    Zihaf/'Ilal diagnosis, and poem-level Qafiyah & rhyme-fault analysis.
    """

    def __init__(
        self,
        custom_replacements: dict[str, str] | None = None,
        *,
        registry: MeterRegistry | None = None,
        extra_meters: Sequence[MeterSpec | type[Bahr]] = (),
        include_muhmal: bool = False,
        prefer_custom: bool = False,
    ) -> None:
        if registry is not None:
            resolved_registry = registry.with_meters(*MUHMAL_METERS) if include_muhmal else registry
        else:
            resolved_registry = (
                MeterRegistry.classical_with_muhmal() if include_muhmal else MeterRegistry.classical()
            )
        if extra_meters:
            resolved_registry = resolved_registry.with_meters(*extra_meters)

        self._custom_replacements: dict[str, str] | None = (
            dict(custom_replacements) if custom_replacements else None
        )
        self._registry: MeterRegistry = resolved_registry
        self._prefer_custom: bool = prefer_custom

        self.converter: ArudiConverter = ArudiConverter(custom_replacements=self._custom_replacements)
        self.qafiyah_analyzer: QafiyahAnalyzer = QafiyahAnalyzer(converter=self.converter)
        self.engine: DeterministicProsodyEngine = self._registry.create_engine(prefer_custom=prefer_custom)

    @property
    def registry(self) -> MeterRegistry:
        """The immutable ``MeterRegistry`` backing this processor."""
        return self._registry

    @property
    def prefer_custom(self) -> bool:
        """Whether custom/Muhmal meters outrank classical meters on exact tie-breaks."""
        return self._prefer_custom

    def with_meters(
        self,
        *meters: MeterSpec | type[Bahr],
        prefer_custom: bool | None = None,
    ) -> ArudhProcessor:
        """Return a new scoped ``ArudhProcessor`` with ``meters`` added (non-mutating)."""
        eff_prefer = self._prefer_custom if prefer_custom is None else prefer_custom
        return ArudhProcessor(
            custom_replacements=self._custom_replacements,
            registry=self._registry.with_meters(*meters),
            prefer_custom=eff_prefer,
        )

    def without_meters(self, *keys: str) -> ArudhProcessor:
        """Return a new scoped ``ArudhProcessor`` excluding meter keys in ``keys`` (non-mutating)."""
        return ArudhProcessor(
            custom_replacements=self._custom_replacements,
            registry=self._registry.without_meters(*keys),
            prefer_custom=self._prefer_custom,
        )

    def list_meters(self) -> list[MeterSpec]:
        """Return all ``MeterSpec`` definitions registered in this processor."""
        return self._registry.list_meters()

    def validate_tashkeel(
        self,
        text: str,
        *,
        min_ratio: float = 0.4,
        raise_on_error: bool = False,
    ) -> bool:
        """Validate that ``text`` carries sufficient diacritization for accurate scansion."""
        return _validate_tashkeel(text, min_ratio=min_ratio, raise_on_error=raise_on_error)

    def _validate_target_meter(self, meter_key: str | None) -> None:
        if meter_key is not None and not self._registry.has(meter_key):
            raise MeterNotFoundError(
                f"Meter '{meter_key}' is not registered in this processor's MeterRegistry."
            )

    def _build_exact_verse_analysis(
        self,
        best: ExactVerseMatch,
        alternatives: list[MeterMatchCandidate],
        sadr_text: str,
        ajuz_text: str,
        sadr_alignments: Sequence[ArudiAlignment],
        ajuz_alignments: Sequence[ArudiAlignment],
        verse_index: int,
    ) -> VerseAnalysis:
        grammar = best.grammar
        chosen_sadr_aln = _select_alignment(sadr_alignments, best.sadr_candidate[1])
        chosen_ajuz_aln = (
            _select_alignment(ajuz_alignments, best.ajuz_candidate[1])
            if (ajuz_text and best.ajuz_candidate is not None and ajuz_alignments)
            else None
        )

        sadr_feet = _attach_arudi_slices(best.sadr_deriv.to_foot_analyses(), chosen_sadr_aln)
        ajuz_feet = (
            _attach_arudi_slices(best.ajuz_deriv.to_foot_analyses(), chosen_ajuz_aln)
            if (best.ajuz_deriv is not None and chosen_ajuz_aln is not None)
            else None
        )

        sadr_analysis = ShatrAnalysis(
            text=sadr_text,
            arudi_text=chosen_sadr_aln.arudi_text,
            pattern=chosen_sadr_aln.pattern,
            feet=sadr_feet,
            score=1.0,
            is_valid=True,
        )
        ajuz_analysis = (
            ShatrAnalysis(
                text=ajuz_text,
                arudi_text=chosen_ajuz_aln.arudi_text,
                pattern=chosen_ajuz_aln.pattern,
                feet=ajuz_feet or [],
                score=1.0,
                is_valid=True,
            )
            if (ajuz_text and chosen_ajuz_aln is not None)
            else None
        )

        # Qafiyah analysis reusing precomputed Ajuz alignment (zero redundant conversion)
        qafiyah_obj: QafiyahAnalysis | None = None
        ajuz_is_muqayyad = False
        if ajuz_text and chosen_ajuz_aln is not None:
            ajuz_is_muqayyad = chosen_ajuz_aln.is_muqayyad
            qafiyah_obj = self.qafiyah_analyzer.analyze(
                ajuz_text,
                is_muqayyad=ajuz_is_muqayyad,
                alignment=chosen_ajuz_aln,
            )

        # Verify Tasri' (التصريع) via QafiyahAnalyzer when a Tasri' derivation wins or on verse 0
        is_tasri = False
        if ajuz_text and (best.is_tasri or verse_index == 0):
            sadr_qaf = self.qafiyah_analyzer.analyze(
                sadr_text,
                is_muqayyad=chosen_sadr_aln.is_muqayyad,
                alignment=chosen_sadr_aln,
            )
            rhyme_tasri = self.qafiyah_analyzer.is_tasri_rhyme(
                sadr_text,
                ajuz_text,
                sadr_qafiyah=sadr_qaf,
                ajuz_qafiyah=qafiyah_obj,
                is_muqayyad=ajuz_is_muqayyad,
            )
            is_tasri = rhyme_tasri

        sadr_std = " ".join(f.pattern for f in best.sadr_deriv.feet)
        ajuz_std = (" " + " ".join(f.pattern for f in best.ajuz_deriv.feet)) if best.ajuz_deriv else ""
        standard_pattern = (sadr_std + ajuz_std).strip()

        errors: list[str] = []
        is_valid = True
        if not best.is_valid_pair:
            is_valid = False
            arud_k = best.sadr_deriv.arudh_or_dharb_key
            darb_k = best.ajuz_deriv.arudh_or_dharb_key if best.ajuz_deriv else ""
            errors.append(
                f"Incompatible Arudh-Dharb pairing for {grammar.name_en} ({arud_k} / {darb_k})."
            )

        return VerseAnalysis(
            verse_index=verse_index,
            sadr_text=sadr_text,
            ajuz_text=ajuz_text,
            meter_key=_coerce_meter_key(grammar.meter_key),
            meter_name_ar=grammar.name_ar,
            meter_name_en=grammar.name_en,
            bahr_type=_coerce_variation(grammar.bahr_type),
            standard_pattern=standard_pattern,
            score=_clamp_score(best.score),
            sadr=sadr_analysis,
            ajuz=ajuz_analysis,
            qafiyah=qafiyah_obj,
            is_valid=is_valid,
            errors=errors,
            alternatives=alternatives,
            is_tasri=is_tasri,
        )

    def _build_broken_verse_analysis(
        self,
        best: BrokenVerseMatch,
        alternatives: list[MeterMatchCandidate],
        sadr_text: str,
        ajuz_text: str,
        sadr_alignments: Sequence[ArudiAlignment],
        ajuz_alignments: Sequence[ArudiAlignment],
        verse_index: int,
    ) -> VerseAnalysis:
        grammar = best.grammar
        chosen_sadr_aln = _select_alignment(sadr_alignments, best.sadr_candidate[1])
        chosen_ajuz_aln = (
            _select_alignment(ajuz_alignments, best.ajuz_candidate[1])
            if (ajuz_text and best.ajuz_candidate is not None and ajuz_alignments)
            else None
        )

        sadr_feet = _attach_arudi_slices(
            [f.to_foot_analysis() for f in best.sadr_alignment.feet],
            chosen_sadr_aln,
        )
        ajuz_feet = (
            _attach_arudi_slices(
                [f.to_foot_analysis() for f in best.ajuz_alignment.feet],
                chosen_ajuz_aln,
            )
            if (best.ajuz_alignment is not None and chosen_ajuz_aln is not None)
            else None
        )

        sadr_score = _clamp_score(best.sadr_alignment.score)
        sadr_valid = best.sadr_alignment.is_valid and all(f.is_valid for f in sadr_feet)
        sadr_analysis = ShatrAnalysis(
            text=sadr_text,
            arudi_text=chosen_sadr_aln.arudi_text,
            pattern=chosen_sadr_aln.pattern,
            feet=sadr_feet,
            score=sadr_score,
            is_valid=sadr_valid,
        )

        ajuz_analysis: ShatrAnalysis | None = None
        if ajuz_text and best.ajuz_alignment is not None and chosen_ajuz_aln is not None:
            ajuz_score = _clamp_score(best.ajuz_alignment.score)
            ajuz_valid = best.ajuz_alignment.is_valid and all(f.is_valid for f in (ajuz_feet or []))
            ajuz_analysis = ShatrAnalysis(
                text=ajuz_text,
                arudi_text=chosen_ajuz_aln.arudi_text,
                pattern=chosen_ajuz_aln.pattern,
                feet=ajuz_feet or [],
                score=ajuz_score,
                is_valid=ajuz_valid,
            )

        qafiyah_obj: QafiyahAnalysis | None = None
        ajuz_is_muqayyad = False
        if ajuz_text and chosen_ajuz_aln is not None:
            ajuz_is_muqayyad = chosen_ajuz_aln.is_muqayyad
            qafiyah_obj = self.qafiyah_analyzer.analyze(
                ajuz_text,
                is_muqayyad=ajuz_is_muqayyad,
                alignment=chosen_ajuz_aln,
            )

        is_tasri = False
        if ajuz_text and (best.is_tasri or verse_index == 0):
            sadr_qaf = self.qafiyah_analyzer.analyze(
                sadr_text,
                is_muqayyad=chosen_sadr_aln.is_muqayyad,
                alignment=chosen_sadr_aln,
            )
            is_tasri = self.qafiyah_analyzer.is_tasri_rhyme(
                sadr_text,
                ajuz_text,
                sadr_qafiyah=sadr_qaf,
                ajuz_qafiyah=qafiyah_obj,
                is_muqayyad=ajuz_is_muqayyad,
            )

        sadr_exp = best.sadr_alignment.expected_pattern
        ajuz_exp = best.ajuz_alignment.expected_pattern if best.ajuz_alignment else ""
        standard_pattern = (sadr_exp + (" " + ajuz_exp if ajuz_exp else "")).strip()

        combined_score = _clamp_score(best.score)
        is_valid = (
            best.is_valid_pair
            and combined_score >= 0.85
            and sadr_analysis.is_valid
            and (ajuz_analysis is None or ajuz_analysis.is_valid)
        )

        errors: list[str] = []
        if not best.is_valid_pair:
            arud_k = best.sadr_alignment.arudh_or_dharb_key
            darb_k = best.ajuz_alignment.arudh_or_dharb_key if best.ajuz_alignment else ""
            errors.append(
                f"Incompatible Arudh-Dharb pairing for {grammar.name_en} ({arud_k} / {darb_k})."
            )
        if combined_score < 0.85:
            errors.append(f"Low metric similarity score: {combined_score:.2f}")
        for foot in sadr_feet:
            if not foot.is_valid:
                errors.append(
                    f"Sadr Foot {foot.foot_index + 1} is {foot.status}: "
                    f"expected {foot.expected_pattern}, got {foot.actual_segment}"
                )
        if ajuz_feet:
            for foot in ajuz_feet:
                if not foot.is_valid:
                    errors.append(
                        f"Ajuz Foot {foot.foot_index + 1} is {foot.status}: "
                        f"expected {foot.expected_pattern}, got {foot.actual_segment}"
                    )

        return VerseAnalysis(
            verse_index=verse_index,
            sadr_text=sadr_text,
            ajuz_text=ajuz_text,
            meter_key=_coerce_meter_key(grammar.meter_key),
            meter_name_ar=grammar.name_ar,
            meter_name_en=grammar.name_en,
            bahr_type=_coerce_variation(grammar.bahr_type),
            standard_pattern=standard_pattern,
            score=combined_score,
            sadr=sadr_analysis,
            ajuz=ajuz_analysis,
            qafiyah=qafiyah_obj,
            is_valid=is_valid,
            errors=errors,
            alternatives=alternatives,
            is_tasri=is_tasri,
        )

    def analyze_verse(
        self,
        sadr_text: str,
        ajuz_text: str | None = None,
        forced_meter: str | None = None,
        verse_index: int = 0,
    ) -> VerseAnalysis:
        """
        Analyze a single poetic verse (Sadr and optional Ajuz).

        Args:
            sadr_text: First hemistich (الصدر).
            ajuz_text: Optional second hemistich (العجز).
            forced_meter: Target meter key to constrain analysis against.
                Raises ``MeterNotFoundError`` if not registered.
            verse_index: Zero-based index of the verse in its poem.

        Returns:
            VerseAnalysis: Strongly typed prosodic, metric, and Qafiyah breakdown.
        """
        self._validate_target_meter(forced_meter)
        ajuz_str = ajuz_text or ""

        # Compile hemistich variants ONCE (reused for exact matching, fallback, & Qafiyah)
        sadr_alignments = self.converter.align_hemistich_variants(
            sadr_text,
            muqayyad=False,
            include_licenses=False,
        )
        ajuz_alignments = (
            self.converter.align_hemistich_variants(
                ajuz_str,
                muqayyad=True,
                include_licenses=False,
            )
            if ajuz_str.strip()
            else []
        )

        sadr_cands = [(a.arudi_text, a.pattern) for a in sadr_alignments if a.pattern]
        ajuz_cands = [(a.arudi_text, a.pattern) for a in ajuz_alignments if a.pattern]

        if not sadr_cands:
            return VerseAnalysis(
                verse_index=verse_index,
                sadr_text=sadr_text,
                ajuz_text=ajuz_str,
                meter_key=MeterKey.UNKNOWN,
                meter_name_ar="بحر غير محدد",
                meter_name_en="Unknown Meter",
                bahr_type=MeterVariation.UNKNOWN,
                standard_pattern="",
                score=0.0,
                sadr=ShatrAnalysis(text=sadr_text, arudi_text="", pattern="", score=0.0, is_valid=False),
                ajuz=(
                    ShatrAnalysis(text=ajuz_str, arudi_text="", pattern="", score=0.0, is_valid=False)
                    if ajuz_str
                    else None
                ),
                is_valid=False,
                errors=["Could not determine poetic meter."],
            )

        # 1. Exact deterministic grammar matching
        exact_matches = self.engine.match_verse_detailed(
            sadr_cands,
            ajuz_cands,
            target_meter=forced_meter,
        )

        # 1b. Classical poetic-license fallback (أَنَا lengthening, mid-line هاء الضمير ikhtilas/ishba')
        if not exact_matches or not exact_matches[0].is_valid_pair:
            lic_sadr = self.converter.align_hemistich_variants(
                sadr_text,
                muqayyad=False,
                include_licenses=True,
            )
            lic_ajuz = (
                self.converter.align_hemistich_variants(
                    ajuz_str,
                    muqayyad=True,
                    include_licenses=True,
                )
                if ajuz_str.strip()
                else []
            )
            if len(lic_sadr) > len(sadr_alignments) or len(lic_ajuz) > len(ajuz_alignments):
                lic_s_cands = [(a.arudi_text, a.pattern) for a in lic_sadr if a.pattern]
                lic_a_cands = [(a.arudi_text, a.pattern) for a in lic_ajuz if a.pattern]
                lic_matches = self.engine.match_verse_detailed(
                    lic_s_cands,
                    lic_a_cands,
                    target_meter=forced_meter,
                )
                if lic_matches and (
                    not exact_matches
                    or (lic_matches[0].is_valid_pair and not exact_matches[0].is_valid_pair)
                    or (
                        lic_matches[0].is_valid_pair == exact_matches[0].is_valid_pair
                        and lic_matches[0].score > exact_matches[0].score
                    )
                ):
                    sadr_alignments = lic_sadr
                    ajuz_alignments = lic_ajuz
                    sadr_cands = lic_s_cands
                    ajuz_cands = lic_a_cands
                    exact_matches = lic_matches

        if exact_matches:
            best_exact = exact_matches[0]
            alts = [m.to_candidate() for m in exact_matches[1:5]]
            return self._build_exact_verse_analysis(
                best=best_exact,
                alternatives=alts,
                sadr_text=sadr_text,
                ajuz_text=ajuz_str,
                sadr_alignments=sadr_alignments,
                ajuz_alignments=ajuz_alignments,
                verse_index=verse_index,
            )

        # 2. Unified slot-level Viterbi DP diagnostic alignment for broken/irregular verses
        broken_matches = self.engine.match_broken_verse(
            sadr_cands,
            ajuz_cands,
            target_meter=forced_meter,
        )
        if not broken_matches:
            s_aln = sadr_alignments[0]
            a_aln = ajuz_alignments[0] if ajuz_alignments else None
            return VerseAnalysis(
                verse_index=verse_index,
                sadr_text=sadr_text,
                ajuz_text=ajuz_str,
                meter_key=MeterKey.UNKNOWN,
                meter_name_ar="بحر غير محدد",
                meter_name_en="Unknown Meter",
                bahr_type=MeterVariation.UNKNOWN,
                standard_pattern="",
                score=0.0,
                sadr=ShatrAnalysis(
                    text=sadr_text,
                    arudi_text=s_aln.arudi_text,
                    pattern=s_aln.pattern,
                    score=0.0,
                    is_valid=False,
                ),
                ajuz=(
                    ShatrAnalysis(
                        text=ajuz_str,
                        arudi_text=a_aln.arudi_text,
                        pattern=a_aln.pattern,
                        score=0.0,
                        is_valid=False,
                    )
                    if a_aln is not None
                    else None
                ),
                is_valid=False,
                errors=["Could not determine poetic meter."],
            )

        best_broken = broken_matches[0]
        broken_alts = [m.to_candidate() for m in broken_matches[1:5]]
        return self._build_broken_verse_analysis(
            best=best_broken,
            alternatives=broken_alts,
            sadr_text=sadr_text,
            ajuz_text=ajuz_str,
            sadr_alignments=sadr_alignments,
            ajuz_alignments=ajuz_alignments,
            verse_index=verse_index,
        )

    def _resolve_spec_metadata(
        self,
        meter_key: str,
        bahr_type: str,
    ) -> tuple[str, str]:
        if meter_key == MeterKey.UNKNOWN or not self._registry.has(meter_key):
            return "غير محدد", "Unknown"
        variants = self._registry.get_variants(meter_key)
        for spec in variants:
            if spec.variation == bahr_type:
                return spec.name_ar, spec.name_en
        primary = variants[0]
        return primary.name_ar, primary.name_en

    def analyze_poem(
        self,
        verses: Sequence[tuple[str, str] | Sequence[str] | str],
        forced_meter: str | None = None,
        *,
        meter_name: str | None = None,
    ) -> PoemAnalysis:
        """
        Analyze a multi-verse Arabic poem for consensus meter, homogeneity,
        opening-verse Tasri', dominant Rawi, and poem-level rhyme faults.

        Args:
            verses: Sequence of ``(sadr, ajuz)`` tuples/lists or separator-delimited verse strings.
            forced_meter: Optional meter key to enforce across all verses.
            meter_name: Backward-compatible alias for ``forced_meter``.

        Returns:
            PoemAnalysis: Complete poem-level prosodic and Qafiyah report.
        """
        if forced_meter is not None and meter_name is not None and forced_meter != meter_name:
            raise ValueError(
                f"Conflicting meter arguments: forced_meter={forced_meter!r}, meter_name={meter_name!r}."
            )
        target_meter = forced_meter if forced_meter is not None else meter_name
        self._validate_target_meter(target_meter)

        normalized_verses: list[tuple[str, str]] = []
        for v in verses:
            if isinstance(v, str):
                normalized_verses.append(split_verse_string(v))
            elif isinstance(v, tuple) and len(v) >= 2:
                normalized_verses.append((str(v[0]), str(v[1])))
            elif isinstance(v, Sequence) and len(v) >= 2:
                normalized_verses.append((str(v[0]), str(v[1])))
            elif isinstance(v, Sequence) and len(v) == 1:
                normalized_verses.append((str(v[0]), ""))

        if not normalized_verses:
            if target_meter is not None:
                spec = self._registry.get(target_meter)
                return PoemAnalysis(
                    meter_key=_coerce_meter_key(spec.key),
                    meter_name_ar=spec.name_ar,
                    meter_name_en=spec.name_en,
                    bahr_type=_coerce_variation(spec.variation),
                    verses=[],
                    average_score=0.0,
                    is_homogeneous=True,
                    dominant_rawi=None,
                    total_verses=0,
                    valid_verses_count=0,
                    rhyme_faults=[],
                    has_tasri=False,
                )
            return PoemAnalysis()

        # Pass 1: independent per-verse detection (or forced meter)
        detected_counts: Counter[str] = Counter()
        detected_valid_counts: Counter[str] = Counter()
        detected_score_sums: dict[str, float] = {}
        first_pass_analyses: list[VerseAnalysis] = []

        for i, (sadr, ajuz) in enumerate(normalized_verses):
            v_analysis = self.analyze_verse(sadr, ajuz, forced_meter=target_meter, verse_index=i)
            first_pass_analyses.append(v_analysis)
            mk = str(v_analysis.meter_key)
            if mk != MeterKey.UNKNOWN:
                detected_counts[mk] += 1
                if v_analysis.is_valid:
                    detected_valid_counts[mk] += 1
                detected_score_sums[mk] = detected_score_sums.get(mk, 0.0) + v_analysis.score

        # Compute homogeneity BEFORE consensus re-evaluation (fixes false-positive homogeneity bug)
        first_pass_meters = {
            str(v.meter_key)
            for v in first_pass_analyses
            if str(v.meter_key) != MeterKey.UNKNOWN
        }
        is_homogeneous = len(first_pass_meters) <= 1

        if target_meter is not None:
            global_meter = target_meter
        elif detected_counts:
            global_meter = max(
                detected_counts.keys(),
                key=lambda k: (
                    detected_counts[k],
                    detected_valid_counts[k],
                    round(detected_score_sums.get(k, 0.0), 6),
                    METER_PRIORITY.get(k, 0),
                ),
            )
        else:
            global_meter = str(MeterKey.UNKNOWN)

        # Pass 2: re-evaluate only verses that differed from the consensus meter
        final_verses: list[VerseAnalysis] = []
        rawi_counter: Counter[str] = Counter()
        bahr_type_counter: Counter[str] = Counter()

        for i, (sadr, ajuz) in enumerate(normalized_verses):
            if (
                target_meter is not None
                or global_meter == MeterKey.UNKNOWN
                or str(first_pass_analyses[i].meter_key) == global_meter
            ):
                v_res = first_pass_analyses[i]
            else:
                v_res = self.analyze_verse(sadr, ajuz, forced_meter=global_meter, verse_index=i)

            final_verses.append(v_res)
            if str(v_res.meter_key) == global_meter:
                bahr_type_counter[str(v_res.bahr_type)] += 1
            if v_res.qafiyah and v_res.qafiyah.rawi:
                rawi_counter[v_res.qafiyah.rawi] += 1

        consensus_bahr_type = (
            bahr_type_counter.most_common(1)[0][0]
            if bahr_type_counter
            else str(MeterVariation.UNKNOWN)
        )
        meter_name_ar, meter_name_en = self._resolve_spec_metadata(global_meter, consensus_bahr_type)

        scores = [v.score for v in final_verses]
        avg_score = _clamp_score(sum(scores) / len(scores)) if scores else 0.0
        valid_count = sum(1 for v in final_verses if v.is_valid)
        dominant_rawi = rawi_counter.most_common(1)[0][0] if rawi_counter else None
        rhyme_faults = self.qafiyah_analyzer.detect_rhyme_faults([v.qafiyah for v in final_verses])
        has_tasri = bool(final_verses and final_verses[0].is_tasri)

        return PoemAnalysis(
            meter_key=_coerce_meter_key(global_meter),
            meter_name_ar=meter_name_ar,
            meter_name_en=meter_name_en,
            bahr_type=_coerce_variation(consensus_bahr_type),
            verses=final_verses,
            average_score=avg_score,
            is_homogeneous=is_homogeneous,
            dominant_rawi=dominant_rawi,
            total_verses=len(final_verses),
            valid_verses_count=valid_count,
            rhyme_faults=rhyme_faults,
            has_tasri=has_tasri,
        )

    def process_poem(
        self,
        verses: Sequence[tuple[str, str] | Sequence[str] | str],
        meter_name: str | None = None,
        *,
        forced_meter: str | None = None,
    ) -> dict[str, Any]:
        """
        Backward-compatible wrapper returning a legacy dictionary payload.
        """
        poem_analysis = self.analyze_poem(verses, forced_meter=forced_meter, meter_name=meter_name)
        if poem_analysis.meter_key == MeterKey.UNKNOWN:
            return {"error": "Could not detect any valid meter."}

        legacy_verses: list[dict[str, Any]] = []
        for v in poem_analysis.verses:
            v_dict = v.to_dict()
            v_dict["sadr_analysis"] = [f.to_dict() for f in v.sadr.feet] if v.sadr is not None else None
            v_dict["ajuz_analysis"] = [f.to_dict() for f in v.ajuz.feet] if v.ajuz is not None else None
            legacy_verses.append(v_dict)

        return {
            "meter": str(poem_analysis.meter_key),
            "meter_name_ar": poem_analysis.meter_name_ar,
            "meter_name_en": poem_analysis.meter_name_en,
            "bahr_type": str(poem_analysis.bahr_type),
            "verses": legacy_verses,
        }

analyze_verse(sadr_text, ajuz_text=None, forced_meter=None, verse_index=0)

Analyze a single poetic verse (Sadr and optional Ajuz).

Parameters:

Name Type Description Default
sadr_text str

First hemistich (الصدر).

required
ajuz_text str | None

Optional second hemistich (العجز).

None
forced_meter str | None

Target meter key to constrain analysis against. Raises MeterNotFoundError if not registered.

None
verse_index int

Zero-based index of the verse in its poem.

0

Returns:

Name Type Description
VerseAnalysis VerseAnalysis

Strongly typed prosodic, metric, and Qafiyah breakdown.

Source code in pyarud/processor.py
def analyze_verse(
    self,
    sadr_text: str,
    ajuz_text: str | None = None,
    forced_meter: str | None = None,
    verse_index: int = 0,
) -> VerseAnalysis:
    """
    Analyze a single poetic verse (Sadr and optional Ajuz).

    Args:
        sadr_text: First hemistich (الصدر).
        ajuz_text: Optional second hemistich (العجز).
        forced_meter: Target meter key to constrain analysis against.
            Raises ``MeterNotFoundError`` if not registered.
        verse_index: Zero-based index of the verse in its poem.

    Returns:
        VerseAnalysis: Strongly typed prosodic, metric, and Qafiyah breakdown.
    """
    self._validate_target_meter(forced_meter)
    ajuz_str = ajuz_text or ""

    # Compile hemistich variants ONCE (reused for exact matching, fallback, & Qafiyah)
    sadr_alignments = self.converter.align_hemistich_variants(
        sadr_text,
        muqayyad=False,
        include_licenses=False,
    )
    ajuz_alignments = (
        self.converter.align_hemistich_variants(
            ajuz_str,
            muqayyad=True,
            include_licenses=False,
        )
        if ajuz_str.strip()
        else []
    )

    sadr_cands = [(a.arudi_text, a.pattern) for a in sadr_alignments if a.pattern]
    ajuz_cands = [(a.arudi_text, a.pattern) for a in ajuz_alignments if a.pattern]

    if not sadr_cands:
        return VerseAnalysis(
            verse_index=verse_index,
            sadr_text=sadr_text,
            ajuz_text=ajuz_str,
            meter_key=MeterKey.UNKNOWN,
            meter_name_ar="بحر غير محدد",
            meter_name_en="Unknown Meter",
            bahr_type=MeterVariation.UNKNOWN,
            standard_pattern="",
            score=0.0,
            sadr=ShatrAnalysis(text=sadr_text, arudi_text="", pattern="", score=0.0, is_valid=False),
            ajuz=(
                ShatrAnalysis(text=ajuz_str, arudi_text="", pattern="", score=0.0, is_valid=False)
                if ajuz_str
                else None
            ),
            is_valid=False,
            errors=["Could not determine poetic meter."],
        )

    # 1. Exact deterministic grammar matching
    exact_matches = self.engine.match_verse_detailed(
        sadr_cands,
        ajuz_cands,
        target_meter=forced_meter,
    )

    # 1b. Classical poetic-license fallback (أَنَا lengthening, mid-line هاء الضمير ikhtilas/ishba')
    if not exact_matches or not exact_matches[0].is_valid_pair:
        lic_sadr = self.converter.align_hemistich_variants(
            sadr_text,
            muqayyad=False,
            include_licenses=True,
        )
        lic_ajuz = (
            self.converter.align_hemistich_variants(
                ajuz_str,
                muqayyad=True,
                include_licenses=True,
            )
            if ajuz_str.strip()
            else []
        )
        if len(lic_sadr) > len(sadr_alignments) or len(lic_ajuz) > len(ajuz_alignments):
            lic_s_cands = [(a.arudi_text, a.pattern) for a in lic_sadr if a.pattern]
            lic_a_cands = [(a.arudi_text, a.pattern) for a in lic_ajuz if a.pattern]
            lic_matches = self.engine.match_verse_detailed(
                lic_s_cands,
                lic_a_cands,
                target_meter=forced_meter,
            )
            if lic_matches and (
                not exact_matches
                or (lic_matches[0].is_valid_pair and not exact_matches[0].is_valid_pair)
                or (
                    lic_matches[0].is_valid_pair == exact_matches[0].is_valid_pair
                    and lic_matches[0].score > exact_matches[0].score
                )
            ):
                sadr_alignments = lic_sadr
                ajuz_alignments = lic_ajuz
                sadr_cands = lic_s_cands
                ajuz_cands = lic_a_cands
                exact_matches = lic_matches

    if exact_matches:
        best_exact = exact_matches[0]
        alts = [m.to_candidate() for m in exact_matches[1:5]]
        return self._build_exact_verse_analysis(
            best=best_exact,
            alternatives=alts,
            sadr_text=sadr_text,
            ajuz_text=ajuz_str,
            sadr_alignments=sadr_alignments,
            ajuz_alignments=ajuz_alignments,
            verse_index=verse_index,
        )

    # 2. Unified slot-level Viterbi DP diagnostic alignment for broken/irregular verses
    broken_matches = self.engine.match_broken_verse(
        sadr_cands,
        ajuz_cands,
        target_meter=forced_meter,
    )
    if not broken_matches:
        s_aln = sadr_alignments[0]
        a_aln = ajuz_alignments[0] if ajuz_alignments else None
        return VerseAnalysis(
            verse_index=verse_index,
            sadr_text=sadr_text,
            ajuz_text=ajuz_str,
            meter_key=MeterKey.UNKNOWN,
            meter_name_ar="بحر غير محدد",
            meter_name_en="Unknown Meter",
            bahr_type=MeterVariation.UNKNOWN,
            standard_pattern="",
            score=0.0,
            sadr=ShatrAnalysis(
                text=sadr_text,
                arudi_text=s_aln.arudi_text,
                pattern=s_aln.pattern,
                score=0.0,
                is_valid=False,
            ),
            ajuz=(
                ShatrAnalysis(
                    text=ajuz_str,
                    arudi_text=a_aln.arudi_text,
                    pattern=a_aln.pattern,
                    score=0.0,
                    is_valid=False,
                )
                if a_aln is not None
                else None
            ),
            is_valid=False,
            errors=["Could not determine poetic meter."],
        )

    best_broken = broken_matches[0]
    broken_alts = [m.to_candidate() for m in broken_matches[1:5]]
    return self._build_broken_verse_analysis(
        best=best_broken,
        alternatives=broken_alts,
        sadr_text=sadr_text,
        ajuz_text=ajuz_str,
        sadr_alignments=sadr_alignments,
        ajuz_alignments=ajuz_alignments,
        verse_index=verse_index,
    )

analyze_poem(verses, forced_meter=None, *, meter_name=None)

Analyze a multi-verse Arabic poem for consensus meter, homogeneity, opening-verse Tasri', dominant Rawi, and poem-level rhyme faults.

Parameters:

Name Type Description Default
verses Sequence[tuple[str, str] | Sequence[str] | str]

Sequence of (sadr, ajuz) tuples/lists or separator-delimited verse strings.

required
forced_meter str | None

Optional meter key to enforce across all verses.

None
meter_name str | None

Backward-compatible alias for forced_meter.

None

Returns:

Name Type Description
PoemAnalysis PoemAnalysis

Complete poem-level prosodic and Qafiyah report.

Source code in pyarud/processor.py
def analyze_poem(
    self,
    verses: Sequence[tuple[str, str] | Sequence[str] | str],
    forced_meter: str | None = None,
    *,
    meter_name: str | None = None,
) -> PoemAnalysis:
    """
    Analyze a multi-verse Arabic poem for consensus meter, homogeneity,
    opening-verse Tasri', dominant Rawi, and poem-level rhyme faults.

    Args:
        verses: Sequence of ``(sadr, ajuz)`` tuples/lists or separator-delimited verse strings.
        forced_meter: Optional meter key to enforce across all verses.
        meter_name: Backward-compatible alias for ``forced_meter``.

    Returns:
        PoemAnalysis: Complete poem-level prosodic and Qafiyah report.
    """
    if forced_meter is not None and meter_name is not None and forced_meter != meter_name:
        raise ValueError(
            f"Conflicting meter arguments: forced_meter={forced_meter!r}, meter_name={meter_name!r}."
        )
    target_meter = forced_meter if forced_meter is not None else meter_name
    self._validate_target_meter(target_meter)

    normalized_verses: list[tuple[str, str]] = []
    for v in verses:
        if isinstance(v, str):
            normalized_verses.append(split_verse_string(v))
        elif isinstance(v, tuple) and len(v) >= 2:
            normalized_verses.append((str(v[0]), str(v[1])))
        elif isinstance(v, Sequence) and len(v) >= 2:
            normalized_verses.append((str(v[0]), str(v[1])))
        elif isinstance(v, Sequence) and len(v) == 1:
            normalized_verses.append((str(v[0]), ""))

    if not normalized_verses:
        if target_meter is not None:
            spec = self._registry.get(target_meter)
            return PoemAnalysis(
                meter_key=_coerce_meter_key(spec.key),
                meter_name_ar=spec.name_ar,
                meter_name_en=spec.name_en,
                bahr_type=_coerce_variation(spec.variation),
                verses=[],
                average_score=0.0,
                is_homogeneous=True,
                dominant_rawi=None,
                total_verses=0,
                valid_verses_count=0,
                rhyme_faults=[],
                has_tasri=False,
            )
        return PoemAnalysis()

    # Pass 1: independent per-verse detection (or forced meter)
    detected_counts: Counter[str] = Counter()
    detected_valid_counts: Counter[str] = Counter()
    detected_score_sums: dict[str, float] = {}
    first_pass_analyses: list[VerseAnalysis] = []

    for i, (sadr, ajuz) in enumerate(normalized_verses):
        v_analysis = self.analyze_verse(sadr, ajuz, forced_meter=target_meter, verse_index=i)
        first_pass_analyses.append(v_analysis)
        mk = str(v_analysis.meter_key)
        if mk != MeterKey.UNKNOWN:
            detected_counts[mk] += 1
            if v_analysis.is_valid:
                detected_valid_counts[mk] += 1
            detected_score_sums[mk] = detected_score_sums.get(mk, 0.0) + v_analysis.score

    # Compute homogeneity BEFORE consensus re-evaluation (fixes false-positive homogeneity bug)
    first_pass_meters = {
        str(v.meter_key)
        for v in first_pass_analyses
        if str(v.meter_key) != MeterKey.UNKNOWN
    }
    is_homogeneous = len(first_pass_meters) <= 1

    if target_meter is not None:
        global_meter = target_meter
    elif detected_counts:
        global_meter = max(
            detected_counts.keys(),
            key=lambda k: (
                detected_counts[k],
                detected_valid_counts[k],
                round(detected_score_sums.get(k, 0.0), 6),
                METER_PRIORITY.get(k, 0),
            ),
        )
    else:
        global_meter = str(MeterKey.UNKNOWN)

    # Pass 2: re-evaluate only verses that differed from the consensus meter
    final_verses: list[VerseAnalysis] = []
    rawi_counter: Counter[str] = Counter()
    bahr_type_counter: Counter[str] = Counter()

    for i, (sadr, ajuz) in enumerate(normalized_verses):
        if (
            target_meter is not None
            or global_meter == MeterKey.UNKNOWN
            or str(first_pass_analyses[i].meter_key) == global_meter
        ):
            v_res = first_pass_analyses[i]
        else:
            v_res = self.analyze_verse(sadr, ajuz, forced_meter=global_meter, verse_index=i)

        final_verses.append(v_res)
        if str(v_res.meter_key) == global_meter:
            bahr_type_counter[str(v_res.bahr_type)] += 1
        if v_res.qafiyah and v_res.qafiyah.rawi:
            rawi_counter[v_res.qafiyah.rawi] += 1

    consensus_bahr_type = (
        bahr_type_counter.most_common(1)[0][0]
        if bahr_type_counter
        else str(MeterVariation.UNKNOWN)
    )
    meter_name_ar, meter_name_en = self._resolve_spec_metadata(global_meter, consensus_bahr_type)

    scores = [v.score for v in final_verses]
    avg_score = _clamp_score(sum(scores) / len(scores)) if scores else 0.0
    valid_count = sum(1 for v in final_verses if v.is_valid)
    dominant_rawi = rawi_counter.most_common(1)[0][0] if rawi_counter else None
    rhyme_faults = self.qafiyah_analyzer.detect_rhyme_faults([v.qafiyah for v in final_verses])
    has_tasri = bool(final_verses and final_verses[0].is_tasri)

    return PoemAnalysis(
        meter_key=_coerce_meter_key(global_meter),
        meter_name_ar=meter_name_ar,
        meter_name_en=meter_name_en,
        bahr_type=_coerce_variation(consensus_bahr_type),
        verses=final_verses,
        average_score=avg_score,
        is_homogeneous=is_homogeneous,
        dominant_rawi=dominant_rawi,
        total_verses=len(final_verses),
        valid_verses_count=valid_count,
        rhyme_faults=rhyme_faults,
        has_tasri=has_tasri,
    )

process_poem(verses, meter_name=None, *, forced_meter=None)

Backward-compatible wrapper returning a legacy dictionary payload.

Source code in pyarud/processor.py
def process_poem(
    self,
    verses: Sequence[tuple[str, str] | Sequence[str] | str],
    meter_name: str | None = None,
    *,
    forced_meter: str | None = None,
) -> dict[str, Any]:
    """
    Backward-compatible wrapper returning a legacy dictionary payload.
    """
    poem_analysis = self.analyze_poem(verses, forced_meter=forced_meter, meter_name=meter_name)
    if poem_analysis.meter_key == MeterKey.UNKNOWN:
        return {"error": "Could not detect any valid meter."}

    legacy_verses: list[dict[str, Any]] = []
    for v in poem_analysis.verses:
        v_dict = v.to_dict()
        v_dict["sadr_analysis"] = [f.to_dict() for f in v.sadr.feet] if v.sadr is not None else None
        v_dict["ajuz_analysis"] = [f.to_dict() for f in v.ajuz.feet] if v.ajuz is not None else None
        legacy_verses.append(v_dict)

    return {
        "meter": str(poem_analysis.meter_key),
        "meter_name_ar": poem_analysis.meter_name_ar,
        "meter_name_en": poem_analysis.meter_name_en,
        "bahr_type": str(poem_analysis.bahr_type),
        "verses": legacy_verses,
    }

with_meters(*meters, prefer_custom=None)

Return a new scoped ArudhProcessor with meters added (non-mutating).

Source code in pyarud/processor.py
def with_meters(
    self,
    *meters: MeterSpec | type[Bahr],
    prefer_custom: bool | None = None,
) -> ArudhProcessor:
    """Return a new scoped ``ArudhProcessor`` with ``meters`` added (non-mutating)."""
    eff_prefer = self._prefer_custom if prefer_custom is None else prefer_custom
    return ArudhProcessor(
        custom_replacements=self._custom_replacements,
        registry=self._registry.with_meters(*meters),
        prefer_custom=eff_prefer,
    )

without_meters(*keys)

Return a new scoped ArudhProcessor excluding meter keys in keys (non-mutating).

Source code in pyarud/processor.py
def without_meters(self, *keys: str) -> ArudhProcessor:
    """Return a new scoped ``ArudhProcessor`` excluding meter keys in ``keys`` (non-mutating)."""
    return ArudhProcessor(
        custom_replacements=self._custom_replacements,
        registry=self._registry.without_meters(*keys),
        prefer_custom=self._prefer_custom,
    )

list_meters()

Return all MeterSpec definitions registered in this processor.

Source code in pyarud/processor.py
def list_meters(self) -> list[MeterSpec]:
    """Return all ``MeterSpec`` definitions registered in this processor."""
    return self._registry.list_meters()

validate_tashkeel(text, *, min_ratio=0.4, raise_on_error=False)

Validate that text carries sufficient diacritization for accurate scansion.

Source code in pyarud/processor.py
def validate_tashkeel(
    self,
    text: str,
    *,
    min_ratio: float = 0.4,
    raise_on_error: bool = False,
) -> bool:
    """Validate that ``text`` carries sufficient diacritization for accurate scansion."""
    return _validate_tashkeel(text, min_ratio=min_ratio, raise_on_error=raise_on_error)

Top-Level Functional Helpers

pyarud

PyArud: High-Performance, Zero-Dependency Arabic Prosody and Meter Analysis Engine.

Provides comprehensive tools for: - Phonetic Arudi transcription & alignment (الكتابة العروضية) - Metric pattern extraction (التقطيع العروضي بالترميز الثنائي) - Classical Arabic meter identification (16 Buhur + sub-meters + opt-in Muhmal & custom meters) - Foot-by-foot Zihaf & 'Ilal diagnosis (الزحافات والعلل) - Classical rhyme & rhyme-fault analysis (علم القافية وعيوبها)

analyze_verse(sadr, ajuz='', forced_meter=None, *, registry=None, extra_meters=(), include_muhmal=False, prefer_custom=False)

Convenience top-level function to analyze a single Arabic verse.

Source code in pyarud/__init__.py
def analyze_verse(
    sadr: str,
    ajuz: str = "",
    forced_meter: str | None = None,
    *,
    registry: MeterRegistry | None = None,
    extra_meters: Sequence[MeterSpec | type[Bahr]] = (),
    include_muhmal: bool = False,
    prefer_custom: bool = False,
) -> VerseAnalysis:
    """Convenience top-level function to analyze a single Arabic verse."""
    proc = _get_processor(
        registry=registry,
        extra_meters=extra_meters,
        include_muhmal=include_muhmal,
        prefer_custom=prefer_custom,
    )
    return proc.analyze_verse(sadr, ajuz, forced_meter=forced_meter)

analyze_poem(verses, forced_meter=None, *, registry=None, extra_meters=(), include_muhmal=False, prefer_custom=False)

Convenience top-level function to analyze a full Arabic poem.

Source code in pyarud/__init__.py
def analyze_poem(
    verses: Sequence[tuple[str, str] | Sequence[str] | str],
    forced_meter: str | None = None,
    *,
    registry: MeterRegistry | None = None,
    extra_meters: Sequence[MeterSpec | type[Bahr]] = (),
    include_muhmal: bool = False,
    prefer_custom: bool = False,
) -> PoemAnalysis:
    """Convenience top-level function to analyze a full Arabic poem."""
    proc = _get_processor(
        registry=registry,
        extra_meters=extra_meters,
        include_muhmal=include_muhmal,
        prefer_custom=prefer_custom,
    )
    return proc.analyze_poem(verses, forced_meter=forced_meter)

scan(verse_or_poem, forced_meter=None, *, registry=None, extra_meters=(), include_muhmal=False, prefer_custom=False)

Ergonomic scansion helper accepting either a single verse string (e.g. 'Sadr ... Ajuz' or 'Sadr * Ajuz') or a sequence of verses.

Source code in pyarud/__init__.py
def scan(
    verse_or_poem: str | Sequence[tuple[str, str] | Sequence[str] | str],
    forced_meter: str | None = None,
    *,
    registry: MeterRegistry | None = None,
    extra_meters: Sequence[MeterSpec | type[Bahr]] = (),
    include_muhmal: bool = False,
    prefer_custom: bool = False,
) -> VerseAnalysis | PoemAnalysis:
    """
    Ergonomic scansion helper accepting either a single verse string
    (e.g. ``'Sadr ... Ajuz'`` or ``'Sadr * Ajuz'``) or a sequence of verses.
    """
    if isinstance(verse_or_poem, str):
        sadr, ajuz = split_verse_string(verse_or_poem)
        return analyze_verse(
            sadr,
            ajuz,
            forced_meter=forced_meter,
            registry=registry,
            extra_meters=extra_meters,
            include_muhmal=include_muhmal,
            prefer_custom=prefer_custom,
        )
    return analyze_poem(
        verse_or_poem,
        forced_meter=forced_meter,
        registry=registry,
        extra_meters=extra_meters,
        include_muhmal=include_muhmal,
        prefer_custom=prefer_custom,
    )

to_arudi(text, saturate=True, muqayyad=False)

Convert Arabic text to Arudi phonetic text and binary pattern.

Source code in pyarud/__init__.py
def to_arudi(text: str, saturate: bool = True, muqayyad: bool = False) -> tuple[str, str]:
    """Convert Arabic text to Arudi phonetic text and binary pattern."""
    return _get_processor().converter.prepare_text(text, saturate=saturate, muqayyad=muqayyad)

get_qafiyah(ajuz_text, is_muqayyad=False)

Analyze the rhyme (Qafiyah) of an Arabic verse ending.

Source code in pyarud/__init__.py
def get_qafiyah(ajuz_text: str, is_muqayyad: bool = False) -> QafiyahAnalysis:
    """Analyze the rhyme (Qafiyah) of an Arabic verse ending."""
    return _get_processor().qafiyah_analyzer.analyze(ajuz_text, is_muqayyad=is_muqayyad)

split_verse_string(line)

Split a single verse string into (sadr, ajuz) using canonical separators.

Source code in pyarud/processor.py
def split_verse_string(line: str) -> tuple[str, str]:
    """Split a single verse string into ``(sadr, ajuz)`` using canonical separators."""
    for sep in HEMISTICH_SEPARATORS:
        if sep in line:
            left, right = line.split(sep, 1)
            return left.strip(), right.strip()
    return line.strip(), ""

Custom Meters & Registry

pyarud.meters.registry.MeterRegistry

Immutable, lazily compiled collection of MeterSpec definitions.

Source code in pyarud/meters/registry.py
class MeterRegistry:
    """Immutable, lazily compiled collection of ``MeterSpec`` definitions."""

    __slots__ = ("_specs", "_compiled_cache", "_keys_tuple")

    def __init__(
        self,
        specs: Sequence[MeterSpec] = (),
        *,
        _compiled_cache: dict[tuple[str, str, str], MeterGrammar] | None = None,
    ) -> None:
        self._specs: tuple[MeterSpec, ...] = tuple(specs)
        # Share already-compiled grammars across derived registries (cache is strictly pure/derived)
        self._compiled_cache: dict[tuple[str, str, str], MeterGrammar] = (
            dict(_compiled_cache) if _compiled_cache else {}
        )
        seen: set[str] = set()
        ordered_keys: list[str] = []
        for s in self._specs:
            if s.key not in seen:
                seen.add(s.key)
                ordered_keys.append(s.key)
        self._keys_tuple: tuple[str, ...] = tuple(ordered_keys)

    @staticmethod
    def _cache_key(spec: MeterSpec) -> tuple[str, str, str]:
        return (spec.key, spec.variation, spec.tier)

    def _compile_spec(self, spec: MeterSpec) -> MeterGrammar:
        ck = self._cache_key(spec)
        grammar = self._compiled_cache.get(ck)
        if grammar is None or grammar.spec is not spec:
            grammar = build_grammar_from_spec(spec)
            self._compiled_cache[ck] = grammar
        return grammar

    @classmethod
    def classical(cls) -> MeterRegistry:
        """Return the lazily cached registry of all 16 classical Farahidian meters (29 grammars)."""
        global _CLASSICAL_REGISTRY_CACHE
        if _CLASSICAL_REGISTRY_CACHE is None:
            specs = tuple(
                MeterSpec.from_bahr_class(bahr_cls, tier="classical")
                for bahr_cls in _CLASSICAL_BAHR_CLASSES
            )
            _CLASSICAL_REGISTRY_CACHE = cls(specs)
        return _CLASSICAL_REGISTRY_CACHE

    @classmethod
    def classical_with_muhmal(cls) -> MeterRegistry:
        """Return a registry containing all 16 classical meters plus the 6 Muhmal meters."""
        return cls.classical().with_meters(*MUHMAL_METERS)

    @classmethod
    def empty(cls) -> MeterRegistry:
        """Return an empty registry for building custom-only meter sets."""
        return cls(())

    @classmethod
    def from_specs(cls, specs: Sequence[MeterSpec | type[Bahr]]) -> MeterRegistry:
        """Construct a registry from an explicit sequence of ``MeterSpec`` or ``Bahr`` classes."""
        return cls(tuple(_coerce_spec(s) for s in specs))

    @classmethod
    def from_json(cls, source: str | Path) -> MeterRegistry:
        """Load one or more meters from a JSON file path or raw JSON string.

        Accepts a single meter JSON object, a JSON array of meter objects, or
        ``{"meters": [...]}``.
        """
        raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source
        if isinstance(source, str) and not source.lstrip().startswith(("{", "[")):
            path = Path(source)
            if path.is_file():
                raw = path.read_text(encoding="utf-8")
        try:
            data = json.loads(raw)
        except json.JSONDecodeError as exc:
            raise InvalidMeterSpecError(f"Invalid JSON for MeterRegistry: {exc}") from exc
        return cls._from_parsed_payload(data)

    @classmethod
    def from_toml(cls, source: str | Path) -> MeterRegistry:
        """Load one or more meters from a TOML file path or raw TOML string.

        Accepts a single meter table or a ``[[meters]]`` array of tables.
        """
        raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source
        if isinstance(source, str) and "\n" not in source and "=" not in source:
            path = Path(source)
            if path.is_file():
                raw = path.read_text(encoding="utf-8")
        try:
            data = tomllib.loads(raw)
        except tomllib.TOMLDecodeError as exc:
            raise InvalidMeterSpecError(f"Invalid TOML for MeterRegistry: {exc}") from exc
        return cls._from_parsed_payload(data)

    @classmethod
    def _from_parsed_payload(cls, data: Any) -> MeterRegistry:
        if isinstance(data, list):
            return cls(tuple(MeterSpec.from_dict(item) for item in data))
        if isinstance(data, Mapping):
            if "meters" in data:
                meters_val = data["meters"]
                if not isinstance(meters_val, list):
                    raise InvalidMeterSpecError("'meters' entry must be a list of meter definitions.")
                return cls(tuple(MeterSpec.from_dict(item) for item in meters_val))
            return cls((MeterSpec.from_dict(data),))
        raise InvalidMeterSpecError("Meter file root must be an object or a list of meter objects.")

    def with_meters(self, *meters: MeterSpec | type[Bahr]) -> MeterRegistry:
        """Return a new registry with ``meters`` added (replacing matching ``(key, variation)`` entries)."""
        if not meters:
            return self
        new_specs = [_coerce_spec(m) for m in meters]
        replace_ids = {(s.key, s.variation) for s in new_specs}
        kept = [s for s in self._specs if (s.key, s.variation) not in replace_ids]
        shared_cache = {
            ck: g
            for ck, g in self._compiled_cache.items()
            if (ck[0], ck[1]) not in replace_ids
        }
        return MeterRegistry((*kept, *new_specs), _compiled_cache=shared_cache)

    def without_meters(self, *keys: str) -> MeterRegistry:
        """Return a new registry excluding all meters whose ``key`` is in ``keys``."""
        if not keys:
            return self
        drop = set(keys)
        kept = tuple(s for s in self._specs if s.key not in drop)
        shared_cache = {ck: g for ck, g in self._compiled_cache.items() if ck[0] not in drop}
        return MeterRegistry(kept, _compiled_cache=shared_cache)

    def get(self, key: str) -> MeterSpec:
        """Return the primary ``MeterSpec`` for ``key``, or raise ``MeterNotFoundError``."""
        for s in self._specs:
            if s.key == key:
                return s
        raise MeterNotFoundError(f"Meter '{key}' is not registered in this MeterRegistry.")

    def get_variants(self, key: str) -> tuple[MeterSpec, ...]:
        """Return all registered ``MeterSpec`` variants for ``key``, or raise ``MeterNotFoundError``."""
        found = tuple(s for s in self._specs if s.key == key)
        if not found:
            raise MeterNotFoundError(f"Meter '{key}' is not registered in this MeterRegistry.")
        return found

    def has(self, key: str) -> bool:
        """Return ``True`` if ``key`` is registered."""
        return key in self._keys_tuple

    def list_meters(self) -> list[MeterSpec]:
        """Return all registered ``MeterSpec`` objects in registration order."""
        return list(self._specs)

    def keys(self) -> tuple[str, ...]:
        """Return unique registered meter keys in registration order."""
        return self._keys_tuple

    @property
    def grammars(self) -> tuple[MeterGrammar, ...]:
        """Lazily compiled tuple of all ``MeterGrammar`` objects in this registry."""
        return tuple(self._compile_spec(s) for s in self._specs)

    def grammars_for(self, key: str | None = None) -> tuple[MeterGrammar, ...]:
        """Return compiled grammars for ``key`` (raising ``MeterNotFoundError`` if unknown), or all."""
        if key is None:
            return self.grammars
        variants = self.get_variants(key)
        return tuple(self._compile_spec(s) for s in variants)

    def create_engine(self, *, prefer_custom: bool = False) -> DeterministicProsodyEngine:
        """Create a ``DeterministicProsodyEngine`` backed by this registry."""
        return DeterministicProsodyEngine.from_registry(self, prefer_custom=prefer_custom)

    def __contains__(self, key: object) -> bool:
        return isinstance(key, str) and key in self._keys_tuple

    def __len__(self) -> int:
        return len(self._specs)

    def __iter__(self) -> Iterator[MeterSpec]:
        return iter(self._specs)

    def __repr__(self) -> str:
        return f"MeterRegistry({len(self._specs)} specs, keys={self._keys_tuple!r})"

classical() classmethod

Return the lazily cached registry of all 16 classical Farahidian meters (29 grammars).

Source code in pyarud/meters/registry.py
@classmethod
def classical(cls) -> MeterRegistry:
    """Return the lazily cached registry of all 16 classical Farahidian meters (29 grammars)."""
    global _CLASSICAL_REGISTRY_CACHE
    if _CLASSICAL_REGISTRY_CACHE is None:
        specs = tuple(
            MeterSpec.from_bahr_class(bahr_cls, tier="classical")
            for bahr_cls in _CLASSICAL_BAHR_CLASSES
        )
        _CLASSICAL_REGISTRY_CACHE = cls(specs)
    return _CLASSICAL_REGISTRY_CACHE

classical_with_muhmal() classmethod

Return a registry containing all 16 classical meters plus the 6 Muhmal meters.

Source code in pyarud/meters/registry.py
@classmethod
def classical_with_muhmal(cls) -> MeterRegistry:
    """Return a registry containing all 16 classical meters plus the 6 Muhmal meters."""
    return cls.classical().with_meters(*MUHMAL_METERS)

empty() classmethod

Return an empty registry for building custom-only meter sets.

Source code in pyarud/meters/registry.py
@classmethod
def empty(cls) -> MeterRegistry:
    """Return an empty registry for building custom-only meter sets."""
    return cls(())

from_specs(specs) classmethod

Construct a registry from an explicit sequence of MeterSpec or Bahr classes.

Source code in pyarud/meters/registry.py
@classmethod
def from_specs(cls, specs: Sequence[MeterSpec | type[Bahr]]) -> MeterRegistry:
    """Construct a registry from an explicit sequence of ``MeterSpec`` or ``Bahr`` classes."""
    return cls(tuple(_coerce_spec(s) for s in specs))

from_json(source) classmethod

Load one or more meters from a JSON file path or raw JSON string.

Accepts a single meter JSON object, a JSON array of meter objects, or {"meters": [...]}.

Source code in pyarud/meters/registry.py
@classmethod
def from_json(cls, source: str | Path) -> MeterRegistry:
    """Load one or more meters from a JSON file path or raw JSON string.

    Accepts a single meter JSON object, a JSON array of meter objects, or
    ``{"meters": [...]}``.
    """
    raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source
    if isinstance(source, str) and not source.lstrip().startswith(("{", "[")):
        path = Path(source)
        if path.is_file():
            raw = path.read_text(encoding="utf-8")
    try:
        data = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise InvalidMeterSpecError(f"Invalid JSON for MeterRegistry: {exc}") from exc
    return cls._from_parsed_payload(data)

from_toml(source) classmethod

Load one or more meters from a TOML file path or raw TOML string.

Accepts a single meter table or a [[meters]] array of tables.

Source code in pyarud/meters/registry.py
@classmethod
def from_toml(cls, source: str | Path) -> MeterRegistry:
    """Load one or more meters from a TOML file path or raw TOML string.

    Accepts a single meter table or a ``[[meters]]`` array of tables.
    """
    raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source
    if isinstance(source, str) and "\n" not in source and "=" not in source:
        path = Path(source)
        if path.is_file():
            raw = path.read_text(encoding="utf-8")
    try:
        data = tomllib.loads(raw)
    except tomllib.TOMLDecodeError as exc:
        raise InvalidMeterSpecError(f"Invalid TOML for MeterRegistry: {exc}") from exc
    return cls._from_parsed_payload(data)

with_meters(*meters)

Return a new registry with meters added (replacing matching (key, variation) entries).

Source code in pyarud/meters/registry.py
def with_meters(self, *meters: MeterSpec | type[Bahr]) -> MeterRegistry:
    """Return a new registry with ``meters`` added (replacing matching ``(key, variation)`` entries)."""
    if not meters:
        return self
    new_specs = [_coerce_spec(m) for m in meters]
    replace_ids = {(s.key, s.variation) for s in new_specs}
    kept = [s for s in self._specs if (s.key, s.variation) not in replace_ids]
    shared_cache = {
        ck: g
        for ck, g in self._compiled_cache.items()
        if (ck[0], ck[1]) not in replace_ids
    }
    return MeterRegistry((*kept, *new_specs), _compiled_cache=shared_cache)

without_meters(*keys)

Return a new registry excluding all meters whose key is in keys.

Source code in pyarud/meters/registry.py
def without_meters(self, *keys: str) -> MeterRegistry:
    """Return a new registry excluding all meters whose ``key`` is in ``keys``."""
    if not keys:
        return self
    drop = set(keys)
    kept = tuple(s for s in self._specs if s.key not in drop)
    shared_cache = {ck: g for ck, g in self._compiled_cache.items() if ck[0] not in drop}
    return MeterRegistry(kept, _compiled_cache=shared_cache)

get(key)

Return the primary MeterSpec for key, or raise MeterNotFoundError.

Source code in pyarud/meters/registry.py
def get(self, key: str) -> MeterSpec:
    """Return the primary ``MeterSpec`` for ``key``, or raise ``MeterNotFoundError``."""
    for s in self._specs:
        if s.key == key:
            return s
    raise MeterNotFoundError(f"Meter '{key}' is not registered in this MeterRegistry.")

get_variants(key)

Return all registered MeterSpec variants for key, or raise MeterNotFoundError.

Source code in pyarud/meters/registry.py
def get_variants(self, key: str) -> tuple[MeterSpec, ...]:
    """Return all registered ``MeterSpec`` variants for ``key``, or raise ``MeterNotFoundError``."""
    found = tuple(s for s in self._specs if s.key == key)
    if not found:
        raise MeterNotFoundError(f"Meter '{key}' is not registered in this MeterRegistry.")
    return found

has(key)

Return True if key is registered.

Source code in pyarud/meters/registry.py
def has(self, key: str) -> bool:
    """Return ``True`` if ``key`` is registered."""
    return key in self._keys_tuple

list_meters()

Return all registered MeterSpec objects in registration order.

Source code in pyarud/meters/registry.py
def list_meters(self) -> list[MeterSpec]:
    """Return all registered ``MeterSpec`` objects in registration order."""
    return list(self._specs)

pyarud.meters.specs.MeterSpec dataclass

Immutable, validated formal specification of any poetic meter (classical, muhmal, free-verse, or custom).

Source code in pyarud/meters/specs.py
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
@dataclass(frozen=True, slots=True, eq=False)
class MeterSpec:
    """Immutable, validated formal specification of any poetic meter (classical, muhmal, free-verse, or custom)."""

    key: str
    name_ar: str
    name_en: str
    variation: str = "tam"
    sadr_feet: tuple[FootSlotSpec, ...] = ()
    ajuz_feet: tuple[FootSlotSpec, ...] | None = None
    single_shatr: bool = False
    arud_darb_rules: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...] = field(
        default_factory=lambda: MappingProxyType({SALIM: (SALIM,)})
    )
    tasri_pairs: tuple[tuple[ProsodicRule, ProsodicRule], ...] = ()
    extended_pairs: tuple[tuple[ProsodicRule, ProsodicRule], ...] = ()
    adjacent_constraints: tuple[AdjacentFootConstraint, ...] = ()
    repeat_range: tuple[int, int] | None = None
    tier: MeterTierLiteral = "custom"
    priority: int = 5
    allow_tasri: bool = True
    metadata: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))
    legacy_bahr_cls: type[Bahr] | None = None

    def __post_init__(self) -> None:
        if not self.key or not self.key.strip():
            raise InvalidMeterSpecError("MeterSpec.key must be a non-empty string.")
        if self.tier not in _VALID_TIERS:
            raise InvalidMeterSpecError(
                f"Invalid MeterSpec.tier '{self.tier}'; expected one of {sorted(_VALID_TIERS)}."
            )
        if not self.sadr_feet:
            raise InvalidMeterSpecError(f"MeterSpec '{self.key}' must define at least one foot in sadr_feet.")

        coerced_sadr = tuple(_coerce_slot(f) for f in self.sadr_feet)
        object.__setattr__(self, "sadr_feet", coerced_sadr)

        if self.ajuz_feet is not None:
            if self.single_shatr:
                raise InvalidMeterSpecError(
                    f"MeterSpec '{self.key}' has single_shatr=True and cannot also specify ajuz_feet."
                )
            if not self.ajuz_feet:
                raise InvalidMeterSpecError(f"MeterSpec '{self.key}' ajuz_feet cannot be empty.")
            object.__setattr__(self, "ajuz_feet", tuple(_coerce_slot(f) for f in self.ajuz_feet))

        if self.repeat_range is not None:
            lo, hi = self.repeat_range
            if lo < 1 or hi < lo:
                raise InvalidMeterSpecError(
                    f"MeterSpec '{self.key}' repeat_range must satisfy 1 <= min <= max, got {self.repeat_range}."
                )
            if len(coerced_sadr) not in (1, 2):
                raise InvalidMeterSpecError(
                    f"MeterSpec '{self.key}' with repeat_range must have 1 (or 2 with ending) foot template."
                )

        # Normalize arud_darb_rules into immutable form
        if isinstance(self.arud_darb_rules, Mapping):
            frozen_ad: dict[ProsodicRule, tuple[ProsodicRule, ...]] = {
                k: tuple(v) for k, v in self.arud_darb_rules.items()
            }
            if not frozen_ad:
                raise InvalidMeterSpecError(f"MeterSpec '{self.key}' arud_darb_rules cannot be empty.")
            object.__setattr__(self, "arud_darb_rules", MappingProxyType(frozen_ad))
        else:
            rule_seq = tuple(self.arud_darb_rules)
            if not rule_seq:
                raise InvalidMeterSpecError(f"MeterSpec '{self.key}' arud_darb_rules cannot be empty.")
            object.__setattr__(self, "arud_darb_rules", rule_seq)

        object.__setattr__(self, "tasri_pairs", tuple(self.tasri_pairs))
        object.__setattr__(self, "extended_pairs", tuple(self.extended_pairs))
        object.__setattr__(self, "adjacent_constraints", tuple(self.adjacent_constraints))
        object.__setattr__(self, "metadata", _freeze_mapping(self.metadata))

        # Validate reachability: every Hashw slot and Arud/Darb slot must produce >= 1 pattern
        last_sadr_tafeela = coerced_sadr[-1].tafeela
        for idx, slot in enumerate(coerced_sadr[:-1]):
            if not slot.extra_patterns and not any(
                slot.tafeela.apply_rule(r) is not None for r in slot.effective_rules()
            ):
                raise InvalidMeterSpecError(
                    f"MeterSpec '{self.key}' Sadr Hashw slot {idx} ({slot.tafeela.key}) produces zero valid patterns."
                )

        arud_rules = (
            tuple(self.arud_darb_rules.keys())
            if isinstance(self.arud_darb_rules, Mapping)
            else self.arud_darb_rules
        )
        if not any(last_sadr_tafeela.apply_rule(r) is not None for r in arud_rules):
            raise InvalidMeterSpecError(
                f"MeterSpec '{self.key}' Arud rules produce zero valid patterns on '{last_sadr_tafeela.key}'."
            )

        if not self.single_shatr:
            eff_ajuz = self.effective_ajuz_feet
            last_ajuz_tafeela = eff_ajuz[-1].tafeela
            if isinstance(self.arud_darb_rules, Mapping):
                darb_rules = tuple(d for ds in self.arud_darb_rules.values() for d in ds)
            else:
                darb_rules = self.arud_darb_rules
            if not any(last_ajuz_tafeela.apply_rule(r) is not None for r in darb_rules):
                raise InvalidMeterSpecError(
                    f"MeterSpec '{self.key}' Darb rules produce zero valid patterns on '{last_ajuz_tafeela.key}'."
                )

    def __eq__(self, other: object) -> bool:
        if isinstance(other, MeterSpec):
            return (
                self.key == other.key
                and self.variation == other.variation
                and self.tier == other.tier
                and self.sadr_feet == other.sadr_feet
                and self.ajuz_feet == other.ajuz_feet
                and self.single_shatr == other.single_shatr
                and self.repeat_range == other.repeat_range
            )
        return False

    def __hash__(self) -> int:
        return hash((self.key, self.variation, self.tier, self.sadr_feet, self.ajuz_feet, self.repeat_range))

    @property
    def effective_ajuz_feet(self) -> tuple[FootSlotSpec, ...]:
        """Ajuz foot slots (mirrors ``sadr_feet`` when ``ajuz_feet`` is ``None``)."""
        return self.sadr_feet if self.ajuz_feet is None else self.ajuz_feet

    @classmethod
    def from_tafeelat(
        cls,
        key: str,
        name_ar: str,
        name_en: str,
        feet: Sequence[FootSlotSpec | TafeelaSpec | type[Tafeela] | str],
        *,
        ajuz_feet: Sequence[FootSlotSpec | TafeelaSpec | type[Tafeela] | str] | None = None,
        arud_darb: Mapping[ProsodicRule | str, Sequence[ProsodicRule | str]]
        | Sequence[ProsodicRule | str]
        | None = None,
        tasri_pairs: Sequence[tuple[ProsodicRule | str, ProsodicRule | str]] = (),
        extended_pairs: Sequence[tuple[ProsodicRule | str, ProsodicRule | str]] = (),
        adjacent_constraints: Sequence[AdjacentFootConstraint] = (),
        single_shatr: bool = False,
        variation: str = "custom",
        tier: MeterTierLiteral = "custom",
        priority: int = 5,
        allow_tasri: bool = True,
        metadata: Mapping[str, Any] | None = None,
    ) -> MeterSpec:
        """Declarative constructor accepting Arabic names, keys, ``TafeelaSpec``, or legacy ``Tafeela`` classes."""
        sadr_slots = tuple(_coerce_slot(f) for f in feet)
        ajuz_slots = tuple(_coerce_slot(f) for f in ajuz_feet) if ajuz_feet is not None else None

        if arud_darb is None:
            resolved_ad: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...] = (
                (SALIM,) if single_shatr else {SALIM: (SALIM,)}
            )
        elif isinstance(arud_darb, Mapping):
            resolved_ad = {
                _resolve_rule(a): tuple(_resolve_rule(d) for d in ds)
                for a, ds in arud_darb.items()
            }
        else:
            resolved_ad = tuple(_resolve_rule(r) for r in arud_darb)

        resolved_tasri = tuple((_resolve_rule(a), _resolve_rule(d)) for a, d in tasri_pairs)
        resolved_ext = tuple((_resolve_rule(a), _resolve_rule(d)) for a, d in extended_pairs)

        return cls(
            key=key,
            name_ar=name_ar,
            name_en=name_en,
            variation=variation,
            sadr_feet=sadr_slots,
            ajuz_feet=ajuz_slots,
            single_shatr=single_shatr,
            arud_darb_rules=resolved_ad,
            tasri_pairs=resolved_tasri,
            extended_pairs=resolved_ext,
            adjacent_constraints=tuple(adjacent_constraints),
            tier=tier,
            priority=priority,
            allow_tasri=allow_tasri,
            metadata=metadata or {},
        )

    @classmethod
    def from_patterns(
        cls,
        key: str,
        name_ar: str,
        name_en: str,
        sadr: Sequence[str],
        *,
        ajuz: Sequence[str] | None = None,
        single_shatr: bool = False,
        variation: str = "custom",
        tier: MeterTierLiteral = "custom",
        priority: int = 5,
        metadata: Mapping[str, Any] | None = None,
    ) -> MeterSpec:
        """Create a meter directly from literal binary pattern sequences (great for Muwashshah / custom rhythms)."""
        if not sadr:
            raise InvalidMeterSpecError(f"MeterSpec.from_patterns '{key}' requires non-empty sadr patterns.")

        def _pat_to_slot(idx: int, pat: str, side: str) -> FootSlotSpec:
            t_spec = TafeelaSpec(
                key=f"{key}_{side}_{idx}",
                name_ar=pat,
                name_en=f"Foot{idx + 1}",
                pattern=pat,
            )
            return FootSlotSpec(tafeela=t_spec, allowed_rules=(SALIM,))

        sadr_slots = tuple(_pat_to_slot(i, p, "sadr") for i, p in enumerate(sadr))
        ajuz_slots = (
            tuple(_pat_to_slot(i, p, "ajuz") for i, p in enumerate(ajuz))
            if ajuz is not None
            else None
        )
        ad: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...] = (
            (SALIM,) if single_shatr else {SALIM: (SALIM,)}
        )
        return cls(
            key=key,
            name_ar=name_ar,
            name_en=name_en,
            variation=variation,
            sadr_feet=sadr_slots,
            ajuz_feet=ajuz_slots,
            single_shatr=single_shatr,
            arud_darb_rules=ad,
            tier=tier,
            priority=priority,
            allow_tasri=False,
            metadata=metadata or {},
        )

    @classmethod
    def free_verse(
        cls,
        key: str,
        name_ar: str,
        name_en: str,
        foot: FootSlotSpec | TafeelaSpec | type[Tafeela] | str,
        *,
        min_feet: int = 1,
        max_feet: int = 10,
        hashw_rules: Sequence[ProsodicRule | str] | None = None,
        ending_rules: Sequence[ProsodicRule | str] | None = None,
        variation: str = "tafeela",
        tier: MeterTierLiteral = "custom",
        priority: int = 5,
        metadata: Mapping[str, Any] | None = None,
    ) -> MeterSpec:
        """Create a modern Arabic free-verse (شعر التفعيلة) meter repeating ``foot`` ``min_feet..max_feet`` times."""
        base_slot = _coerce_slot(foot)
        base_tafeela = base_slot.tafeela
        h_rules = (
            tuple(_resolve_rule(r) for r in hashw_rules)
            if hashw_rules is not None
            else base_slot.allowed_rules
        )
        e_rules = (
            tuple(_resolve_rule(r) for r in ending_rules)
            if ending_rules is not None
            else (SALIM, *base_tafeela.allowed_zihafs)
        )
        repeat_slot = FootSlotSpec(
            tafeela=base_tafeela,
            allowed_rules=h_rules,
            disallowed_rules=base_slot.disallowed_rules,
            extra_patterns=base_slot.extra_patterns,
        )
        return cls(
            key=key,
            name_ar=name_ar,
            name_en=name_en,
            variation=variation,
            sadr_feet=(repeat_slot,),
            ajuz_feet=None,
            single_shatr=True,
            arud_darb_rules=e_rules,
            repeat_range=(min_feet, max_feet),
            tier=tier,
            priority=priority,
            allow_tasri=False,
            metadata=metadata or {},
        )

    @classmethod
    def from_bahr_class(
        cls,
        bahr_cls: type[Bahr],
        *,
        tier: MeterTierLiteral = "classical",
        priority: int | None = None,
    ) -> MeterSpec:
        """Losslessly convert any legacy or classical ``Bahr`` subclass into a ``MeterSpec``."""
        if not bahr_cls.tafeelat:
            raise InvalidMeterSpecError(f"Bahr class '{bahr_cls.__name__}' defines no tafeelat.")

        def _build_side_slots(shatr_idx: int) -> tuple[FootSlotSpec, ...]:
            slots: list[FootSlotSpec] = []
            for i, t_cls in enumerate(bahr_cls.tafeelat):
                t_spec = TafeelaSpec.from_tafeela_class(t_cls)
                if i < len(bahr_cls.tafeelat) - 1:
                    extra_cls_list: list[type[BaseEllahZehaf]] = []
                    if shatr_idx in bahr_cls.extra_hashw_zehafs:
                        et = bahr_cls.extra_hashw_zehafs[shatr_idx]
                        if i < len(et):
                            extra_cls_list = et[i]
                    disallowed_cls_list: list[type[BaseEllahZehaf]] = []
                    if shatr_idx in bahr_cls.disallowed_zehafs_for_hashw:
                        dt = bahr_cls.disallowed_zehafs_for_hashw[shatr_idx]
                        if i < len(dt):
                            disallowed_cls_list = dt[i]

                    allowed = (
                        SALIM,
                        *t_spec.allowed_zihafs,
                        *(rule_from_legacy(z) for z in extra_cls_list),
                    )
                    disallowed = tuple(rule_from_legacy(z) for z in disallowed_cls_list)
                    slots.append(
                        FootSlotSpec(
                            tafeela=t_spec,
                            allowed_rules=allowed,
                            disallowed_rules=disallowed,
                        )
                    )
                else:
                    slots.append(FootSlotSpec(tafeela=t_spec))
            return tuple(slots)

        sadr_slots = _build_side_slots(0)
        ajuz_slots = None if bahr_cls.only_one_shatr else _build_side_slots(1)

        if bahr_cls.only_one_shatr:
            # Preserve deterministic order even when legacy map is a set
            raw_endings = sorted(bahr_cls.arod_dharbs_map, key=lambda c: c.__name__)
            arud_darb: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...] = tuple(
                rule_from_legacy(z) for z in raw_endings
            )
        elif isinstance(bahr_cls.arod_dharbs_map, dict):
            arud_darb = {
                rule_from_legacy(a_cls): tuple(rule_from_legacy(d_cls) for d_cls in d_tuple)
                for a_cls, d_tuple in bahr_cls.arod_dharbs_map.items()
            }
        else:
            raw_endings = sorted(bahr_cls.arod_dharbs_map, key=lambda c: c.__name__)
            arud_darb = tuple(rule_from_legacy(z) for z in raw_endings)

        tasri = tuple((rule_from_legacy(a), rule_from_legacy(d)) for a, d in bahr_cls.tasri_pairs)
        extended = tuple((rule_from_legacy(a), rule_from_legacy(d)) for a, d in bahr_cls.extended_pairs)
        eff_priority = METER_PRIORITY.get(bahr_cls.key, 5) if priority is None else priority

        return cls(
            key=bahr_cls.key,
            name_ar=bahr_cls.name_ar,
            name_en=bahr_cls.name_en,
            variation=bahr_cls.bahr_type,
            sadr_feet=sadr_slots,
            ajuz_feet=ajuz_slots,
            single_shatr=bahr_cls.only_one_shatr,
            arud_darb_rules=arud_darb,
            tasri_pairs=tasri,
            extended_pairs=extended,
            adjacent_constraints=bahr_cls.adjacent_constraints,
            tier=tier,
            priority=eff_priority,
            allow_tasri=bool(tasri),
            legacy_bahr_cls=bahr_cls,
        )

    def to_dict(self) -> dict[str, Any]:
        """Serialize this ``MeterSpec`` to a JSON/TOML-compatible dictionary."""
        custom_tafeelat: dict[str, dict[str, Any]] = {}
        custom_rules: dict[str, dict[str, Any]] = {}

        def _collect_rule(r: ProsodicRule) -> None:
            if r.key in CLASSICAL_RULES or r.key in custom_rules:
                return
            for sub in r.sub_rules:
                _collect_rule(sub)
            custom_rules[r.key] = r.to_dict()

        def _collect_slot(slot: FootSlotSpec) -> None:
            t = slot.tafeela
            if t.key not in CLASSICAL_TAFEELAT and t.key not in custom_tafeelat:
                custom_tafeelat[t.key] = t.to_dict()
                for z in t.allowed_zihafs:
                    _collect_rule(z)
            if slot.allowed_rules is not None:
                for r in slot.allowed_rules:
                    _collect_rule(r)
            for r in slot.disallowed_rules:
                _collect_rule(r)

        for slot in self.sadr_feet:
            _collect_slot(slot)
        if self.ajuz_feet is not None:
            for slot in self.ajuz_feet:
                _collect_slot(slot)

        arud_darb_out: dict[str, list[str]] | list[str]
        if isinstance(self.arud_darb_rules, Mapping):
            arud_darb_out = {}
            for a_rule, d_rules in self.arud_darb_rules.items():
                _collect_rule(a_rule)
                for dr in d_rules:
                    _collect_rule(dr)
                arud_darb_out[a_rule.key] = [dr.key for dr in d_rules]
        else:
            for r in self.arud_darb_rules:
                _collect_rule(r)
            arud_darb_out = [r.key for r in self.arud_darb_rules]

        for a_r, d_r in (*self.tasri_pairs, *self.extended_pairs):
            _collect_rule(a_r)
            _collect_rule(d_r)

        out: dict[str, Any] = {
            "key": self.key,
            "name_ar": self.name_ar,
            "name_en": self.name_en,
            "variation": self.variation,
            "tier": self.tier,
            "priority": self.priority,
            "single_shatr": self.single_shatr,
            "allow_tasri": self.allow_tasri,
            "sadr_feet": [s.to_dict() for s in self.sadr_feet],
            "arud_darb_rules": arud_darb_out,
        }
        if self.ajuz_feet is not None:
            out["ajuz_feet"] = [s.to_dict() for s in self.ajuz_feet]
        if self.repeat_range is not None:
            out["repeat_range"] = [self.repeat_range[0], self.repeat_range[1]]
        if self.tasri_pairs:
            out["tasri_pairs"] = [[a.key, d.key] for a, d in self.tasri_pairs]
        if self.extended_pairs:
            out["extended_pairs"] = [[a.key, d.key] for a, d in self.extended_pairs]
        if self.adjacent_constraints:
            out["adjacent_constraints"] = [
                {
                    "left_rule": c.left_rule,
                    "right_rule": c.right_rule,
                    "slot_index": c.slot_index,
                    "penalty": c.penalty,
                    "forbidden": c.forbidden,
                    "name_ar": c.name_ar,
                }
                for c in self.adjacent_constraints
            ]
        if custom_rules:
            out["custom_rules"] = list(custom_rules.values())
        if custom_tafeelat:
            out["custom_tafeelat"] = list(custom_tafeelat.values())
        if self.metadata:
            out["metadata"] = dict(self.metadata)
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> MeterSpec:
        """Deserialize a ``MeterSpec`` from a plain dictionary (JSON or TOML)."""
        if not isinstance(data, Mapping):
            raise InvalidMeterSpecError("MeterSpec.from_dict expects a mapping.")
        key = str(data.get("key", "")).strip()
        if not key:
            raise InvalidMeterSpecError("MeterSpec dictionary missing required field 'key'.")

        # Multi-pass topological resolution so composed custom rules work in any JSON/TOML order
        extra_rules: dict[str, ProsodicRule] = {}
        pending_rules: list[Any] = list(data.get("custom_rules", ()))
        while pending_rules:
            next_pending: list[Any] = []
            progressed = False
            last_error: InvalidMeterSpecError | None = None
            for r_raw in pending_rules:
                try:
                    rule_obj = ProsodicRule.from_dict(r_raw, known_rules=extra_rules)
                except InvalidMeterSpecError as exc:
                    next_pending.append(r_raw)
                    last_error = exc
                else:
                    extra_rules[rule_obj.key] = rule_obj
                    progressed = True
            if not progressed:
                assert last_error is not None
                raise last_error
            pending_rules = next_pending

        extra_tafeelat: dict[str, TafeelaSpec] = {}
        for t_raw in data.get("custom_tafeelat", ()):
            t_obj = TafeelaSpec.from_dict(t_raw, known_rules=extra_rules)
            extra_tafeelat[t_obj.key] = t_obj
            extra_tafeelat[t_obj.name_ar] = t_obj

        def _parse_slot(item: Any) -> FootSlotSpec:
            if isinstance(item, str):
                return FootSlotSpec(tafeela=_resolve_tafeela(item, extra_tafeelat=extra_tafeelat))
            if isinstance(item, Mapping):
                t_ref = item.get("tafeela")
                if not isinstance(t_ref, str):
                    raise InvalidMeterSpecError(f"Foot slot in '{key}' must specify 'tafeela' string.")
                t_spec = _resolve_tafeela(t_ref, extra_tafeelat=extra_tafeelat)
                allowed_raw = item.get("allowed_rules")
                allowed = (
                    tuple(_resolve_rule(r, extra_rules=extra_rules) for r in allowed_raw)
                    if allowed_raw is not None
                    else None
                )
                disallowed = tuple(
                    _resolve_rule(r, extra_rules=extra_rules)
                    for r in item.get("disallowed_rules", ())
                )
                extras = tuple(str(p) for p in item.get("extra_patterns", ()))
                return FootSlotSpec(
                    tafeela=t_spec,
                    allowed_rules=allowed,
                    disallowed_rules=disallowed,
                    extra_patterns=extras,
                )
            raise InvalidMeterSpecError(f"Unsupported foot slot entry in '{key}': {item!r}.")

        # Support shorthand `feet` or explicit `sadr_feet`
        raw_sadr = data.get("sadr_feet", data.get("feet"))
        if not raw_sadr or not isinstance(raw_sadr, Sequence) or isinstance(raw_sadr, (str, bytes)):
            raise InvalidMeterSpecError(f"MeterSpec '{key}' requires non-empty 'sadr_feet' (or 'feet').")
        sadr_slots = tuple(_parse_slot(s) for s in raw_sadr)

        raw_ajuz = data.get("ajuz_feet")
        ajuz_slots: tuple[FootSlotSpec, ...] | None = None
        if raw_ajuz is not None:
            if not isinstance(raw_ajuz, Sequence) or isinstance(raw_ajuz, (str, bytes)):
                raise InvalidMeterSpecError(f"MeterSpec '{key}' ajuz_feet must be a list.")
            ajuz_slots = tuple(_parse_slot(s) for s in raw_ajuz)

        single_shatr = bool(data.get("single_shatr", False))
        raw_ad = data.get("arud_darb_rules", data.get("arud_darb"))
        ad_rules: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...]
        if raw_ad is None:
            ad_rules = (SALIM,) if single_shatr else {SALIM: (SALIM,)}
        elif isinstance(raw_ad, Mapping):
            ad_rules = {
                _resolve_rule(a, extra_rules=extra_rules): tuple(
                    _resolve_rule(d, extra_rules=extra_rules) for d in ds
                )
                for a, ds in raw_ad.items()
            }
        elif isinstance(raw_ad, Sequence) and not isinstance(raw_ad, (str, bytes)):
            ad_rules = tuple(_resolve_rule(r, extra_rules=extra_rules) for r in raw_ad)
        else:
            raise InvalidMeterSpecError(f"Invalid arud_darb_rules in '{key}': {raw_ad!r}.")

        tasri_pairs = tuple(
            (_resolve_rule(pair[0], extra_rules=extra_rules), _resolve_rule(pair[1], extra_rules=extra_rules))
            for pair in data.get("tasri_pairs", ())
        )
        extended_pairs = tuple(
            (_resolve_rule(pair[0], extra_rules=extra_rules), _resolve_rule(pair[1], extra_rules=extra_rules))
            for pair in data.get("extended_pairs", ())
        )

        constraints: list[AdjacentFootConstraint] = []
        for c_raw in data.get("adjacent_constraints", ()):
            constraints.append(
                AdjacentFootConstraint(
                    left_rule=str(c_raw["left_rule"]),
                    right_rule=str(c_raw["right_rule"]),
                    slot_index=int(c_raw["slot_index"]) if c_raw.get("slot_index") is not None else None,
                    penalty=int(c_raw.get("penalty", 4)),
                    forbidden=bool(c_raw.get("forbidden", False)),
                    name_ar=str(c_raw.get("name_ar", "")),
                )
            )

        raw_rr = data.get("repeat_range")
        repeat_range: tuple[int, int] | None = None
        if raw_rr is not None:
            if not isinstance(raw_rr, Sequence) or len(raw_rr) != 2:
                raise InvalidMeterSpecError(f"repeat_range in '{key}' must be a 2-element list [min, max].")
            repeat_range = (int(raw_rr[0]), int(raw_rr[1]))

        tier_raw = str(data.get("tier", "custom"))
        if tier_raw not in _VALID_TIERS:
            raise InvalidMeterSpecError(f"Invalid tier '{tier_raw}' in '{key}'.")
        tier: MeterTierLiteral = tier_raw  # type: ignore[assignment]

        meta = data.get("metadata")
        return cls(
            key=key,
            name_ar=str(data.get("name_ar", key)),
            name_en=str(data.get("name_en", key)),
            variation=str(data.get("variation", "custom")),
            sadr_feet=sadr_slots,
            ajuz_feet=ajuz_slots,
            single_shatr=single_shatr,
            arud_darb_rules=ad_rules,
            tasri_pairs=tasri_pairs,
            extended_pairs=extended_pairs,
            adjacent_constraints=tuple(constraints),
            repeat_range=repeat_range,
            tier=tier,
            priority=int(data.get("priority", 5)),
            allow_tasri=bool(data.get("allow_tasri", True)),
            metadata=meta if isinstance(meta, Mapping) else {},
        )

    @classmethod
    def from_json(cls, source: str | Path) -> MeterSpec:
        """Load a single ``MeterSpec`` from a JSON file path or raw JSON string."""
        raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source
        if isinstance(source, str) and not source.lstrip().startswith("{"):
            path = Path(source)
            if path.is_file():
                raw = path.read_text(encoding="utf-8")
        try:
            data = json.loads(raw)
        except json.JSONDecodeError as exc:
            raise InvalidMeterSpecError(f"Invalid JSON for MeterSpec: {exc}") from exc
        if not isinstance(data, Mapping):
            raise InvalidMeterSpecError("MeterSpec JSON root must be an object.")
        return cls.from_dict(data)

    @classmethod
    def from_toml(cls, source: str | Path) -> MeterSpec:
        """Load a single ``MeterSpec`` from a TOML file path or raw TOML string."""
        raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source
        if isinstance(source, str) and "\n" not in source and "=" not in source:
            path = Path(source)
            if path.is_file():
                raw = path.read_text(encoding="utf-8")
        try:
            data = tomllib.loads(raw)
        except tomllib.TOMLDecodeError as exc:
            raise InvalidMeterSpecError(f"Invalid TOML for MeterSpec: {exc}") from exc
        return cls.from_dict(data)

effective_ajuz_feet property

Ajuz foot slots (mirrors sadr_feet when ajuz_feet is None).

free_verse(key, name_ar, name_en, foot, *, min_feet=1, max_feet=10, hashw_rules=None, ending_rules=None, variation='tafeela', tier='custom', priority=5, metadata=None) classmethod

Create a modern Arabic free-verse (شعر التفعيلة) meter repeating foot min_feet..max_feet times.

Source code in pyarud/meters/specs.py
@classmethod
def free_verse(
    cls,
    key: str,
    name_ar: str,
    name_en: str,
    foot: FootSlotSpec | TafeelaSpec | type[Tafeela] | str,
    *,
    min_feet: int = 1,
    max_feet: int = 10,
    hashw_rules: Sequence[ProsodicRule | str] | None = None,
    ending_rules: Sequence[ProsodicRule | str] | None = None,
    variation: str = "tafeela",
    tier: MeterTierLiteral = "custom",
    priority: int = 5,
    metadata: Mapping[str, Any] | None = None,
) -> MeterSpec:
    """Create a modern Arabic free-verse (شعر التفعيلة) meter repeating ``foot`` ``min_feet..max_feet`` times."""
    base_slot = _coerce_slot(foot)
    base_tafeela = base_slot.tafeela
    h_rules = (
        tuple(_resolve_rule(r) for r in hashw_rules)
        if hashw_rules is not None
        else base_slot.allowed_rules
    )
    e_rules = (
        tuple(_resolve_rule(r) for r in ending_rules)
        if ending_rules is not None
        else (SALIM, *base_tafeela.allowed_zihafs)
    )
    repeat_slot = FootSlotSpec(
        tafeela=base_tafeela,
        allowed_rules=h_rules,
        disallowed_rules=base_slot.disallowed_rules,
        extra_patterns=base_slot.extra_patterns,
    )
    return cls(
        key=key,
        name_ar=name_ar,
        name_en=name_en,
        variation=variation,
        sadr_feet=(repeat_slot,),
        ajuz_feet=None,
        single_shatr=True,
        arud_darb_rules=e_rules,
        repeat_range=(min_feet, max_feet),
        tier=tier,
        priority=priority,
        allow_tasri=False,
        metadata=metadata or {},
    )

from_bahr_class(bahr_cls, *, tier='classical', priority=None) classmethod

Losslessly convert any legacy or classical Bahr subclass into a MeterSpec.

Source code in pyarud/meters/specs.py
@classmethod
def from_bahr_class(
    cls,
    bahr_cls: type[Bahr],
    *,
    tier: MeterTierLiteral = "classical",
    priority: int | None = None,
) -> MeterSpec:
    """Losslessly convert any legacy or classical ``Bahr`` subclass into a ``MeterSpec``."""
    if not bahr_cls.tafeelat:
        raise InvalidMeterSpecError(f"Bahr class '{bahr_cls.__name__}' defines no tafeelat.")

    def _build_side_slots(shatr_idx: int) -> tuple[FootSlotSpec, ...]:
        slots: list[FootSlotSpec] = []
        for i, t_cls in enumerate(bahr_cls.tafeelat):
            t_spec = TafeelaSpec.from_tafeela_class(t_cls)
            if i < len(bahr_cls.tafeelat) - 1:
                extra_cls_list: list[type[BaseEllahZehaf]] = []
                if shatr_idx in bahr_cls.extra_hashw_zehafs:
                    et = bahr_cls.extra_hashw_zehafs[shatr_idx]
                    if i < len(et):
                        extra_cls_list = et[i]
                disallowed_cls_list: list[type[BaseEllahZehaf]] = []
                if shatr_idx in bahr_cls.disallowed_zehafs_for_hashw:
                    dt = bahr_cls.disallowed_zehafs_for_hashw[shatr_idx]
                    if i < len(dt):
                        disallowed_cls_list = dt[i]

                allowed = (
                    SALIM,
                    *t_spec.allowed_zihafs,
                    *(rule_from_legacy(z) for z in extra_cls_list),
                )
                disallowed = tuple(rule_from_legacy(z) for z in disallowed_cls_list)
                slots.append(
                    FootSlotSpec(
                        tafeela=t_spec,
                        allowed_rules=allowed,
                        disallowed_rules=disallowed,
                    )
                )
            else:
                slots.append(FootSlotSpec(tafeela=t_spec))
        return tuple(slots)

    sadr_slots = _build_side_slots(0)
    ajuz_slots = None if bahr_cls.only_one_shatr else _build_side_slots(1)

    if bahr_cls.only_one_shatr:
        # Preserve deterministic order even when legacy map is a set
        raw_endings = sorted(bahr_cls.arod_dharbs_map, key=lambda c: c.__name__)
        arud_darb: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...] = tuple(
            rule_from_legacy(z) for z in raw_endings
        )
    elif isinstance(bahr_cls.arod_dharbs_map, dict):
        arud_darb = {
            rule_from_legacy(a_cls): tuple(rule_from_legacy(d_cls) for d_cls in d_tuple)
            for a_cls, d_tuple in bahr_cls.arod_dharbs_map.items()
        }
    else:
        raw_endings = sorted(bahr_cls.arod_dharbs_map, key=lambda c: c.__name__)
        arud_darb = tuple(rule_from_legacy(z) for z in raw_endings)

    tasri = tuple((rule_from_legacy(a), rule_from_legacy(d)) for a, d in bahr_cls.tasri_pairs)
    extended = tuple((rule_from_legacy(a), rule_from_legacy(d)) for a, d in bahr_cls.extended_pairs)
    eff_priority = METER_PRIORITY.get(bahr_cls.key, 5) if priority is None else priority

    return cls(
        key=bahr_cls.key,
        name_ar=bahr_cls.name_ar,
        name_en=bahr_cls.name_en,
        variation=bahr_cls.bahr_type,
        sadr_feet=sadr_slots,
        ajuz_feet=ajuz_slots,
        single_shatr=bahr_cls.only_one_shatr,
        arud_darb_rules=arud_darb,
        tasri_pairs=tasri,
        extended_pairs=extended,
        adjacent_constraints=bahr_cls.adjacent_constraints,
        tier=tier,
        priority=eff_priority,
        allow_tasri=bool(tasri),
        legacy_bahr_cls=bahr_cls,
    )

from_dict(data) classmethod

Deserialize a MeterSpec from a plain dictionary (JSON or TOML).

Source code in pyarud/meters/specs.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> MeterSpec:
    """Deserialize a ``MeterSpec`` from a plain dictionary (JSON or TOML)."""
    if not isinstance(data, Mapping):
        raise InvalidMeterSpecError("MeterSpec.from_dict expects a mapping.")
    key = str(data.get("key", "")).strip()
    if not key:
        raise InvalidMeterSpecError("MeterSpec dictionary missing required field 'key'.")

    # Multi-pass topological resolution so composed custom rules work in any JSON/TOML order
    extra_rules: dict[str, ProsodicRule] = {}
    pending_rules: list[Any] = list(data.get("custom_rules", ()))
    while pending_rules:
        next_pending: list[Any] = []
        progressed = False
        last_error: InvalidMeterSpecError | None = None
        for r_raw in pending_rules:
            try:
                rule_obj = ProsodicRule.from_dict(r_raw, known_rules=extra_rules)
            except InvalidMeterSpecError as exc:
                next_pending.append(r_raw)
                last_error = exc
            else:
                extra_rules[rule_obj.key] = rule_obj
                progressed = True
        if not progressed:
            assert last_error is not None
            raise last_error
        pending_rules = next_pending

    extra_tafeelat: dict[str, TafeelaSpec] = {}
    for t_raw in data.get("custom_tafeelat", ()):
        t_obj = TafeelaSpec.from_dict(t_raw, known_rules=extra_rules)
        extra_tafeelat[t_obj.key] = t_obj
        extra_tafeelat[t_obj.name_ar] = t_obj

    def _parse_slot(item: Any) -> FootSlotSpec:
        if isinstance(item, str):
            return FootSlotSpec(tafeela=_resolve_tafeela(item, extra_tafeelat=extra_tafeelat))
        if isinstance(item, Mapping):
            t_ref = item.get("tafeela")
            if not isinstance(t_ref, str):
                raise InvalidMeterSpecError(f"Foot slot in '{key}' must specify 'tafeela' string.")
            t_spec = _resolve_tafeela(t_ref, extra_tafeelat=extra_tafeelat)
            allowed_raw = item.get("allowed_rules")
            allowed = (
                tuple(_resolve_rule(r, extra_rules=extra_rules) for r in allowed_raw)
                if allowed_raw is not None
                else None
            )
            disallowed = tuple(
                _resolve_rule(r, extra_rules=extra_rules)
                for r in item.get("disallowed_rules", ())
            )
            extras = tuple(str(p) for p in item.get("extra_patterns", ()))
            return FootSlotSpec(
                tafeela=t_spec,
                allowed_rules=allowed,
                disallowed_rules=disallowed,
                extra_patterns=extras,
            )
        raise InvalidMeterSpecError(f"Unsupported foot slot entry in '{key}': {item!r}.")

    # Support shorthand `feet` or explicit `sadr_feet`
    raw_sadr = data.get("sadr_feet", data.get("feet"))
    if not raw_sadr or not isinstance(raw_sadr, Sequence) or isinstance(raw_sadr, (str, bytes)):
        raise InvalidMeterSpecError(f"MeterSpec '{key}' requires non-empty 'sadr_feet' (or 'feet').")
    sadr_slots = tuple(_parse_slot(s) for s in raw_sadr)

    raw_ajuz = data.get("ajuz_feet")
    ajuz_slots: tuple[FootSlotSpec, ...] | None = None
    if raw_ajuz is not None:
        if not isinstance(raw_ajuz, Sequence) or isinstance(raw_ajuz, (str, bytes)):
            raise InvalidMeterSpecError(f"MeterSpec '{key}' ajuz_feet must be a list.")
        ajuz_slots = tuple(_parse_slot(s) for s in raw_ajuz)

    single_shatr = bool(data.get("single_shatr", False))
    raw_ad = data.get("arud_darb_rules", data.get("arud_darb"))
    ad_rules: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...]
    if raw_ad is None:
        ad_rules = (SALIM,) if single_shatr else {SALIM: (SALIM,)}
    elif isinstance(raw_ad, Mapping):
        ad_rules = {
            _resolve_rule(a, extra_rules=extra_rules): tuple(
                _resolve_rule(d, extra_rules=extra_rules) for d in ds
            )
            for a, ds in raw_ad.items()
        }
    elif isinstance(raw_ad, Sequence) and not isinstance(raw_ad, (str, bytes)):
        ad_rules = tuple(_resolve_rule(r, extra_rules=extra_rules) for r in raw_ad)
    else:
        raise InvalidMeterSpecError(f"Invalid arud_darb_rules in '{key}': {raw_ad!r}.")

    tasri_pairs = tuple(
        (_resolve_rule(pair[0], extra_rules=extra_rules), _resolve_rule(pair[1], extra_rules=extra_rules))
        for pair in data.get("tasri_pairs", ())
    )
    extended_pairs = tuple(
        (_resolve_rule(pair[0], extra_rules=extra_rules), _resolve_rule(pair[1], extra_rules=extra_rules))
        for pair in data.get("extended_pairs", ())
    )

    constraints: list[AdjacentFootConstraint] = []
    for c_raw in data.get("adjacent_constraints", ()):
        constraints.append(
            AdjacentFootConstraint(
                left_rule=str(c_raw["left_rule"]),
                right_rule=str(c_raw["right_rule"]),
                slot_index=int(c_raw["slot_index"]) if c_raw.get("slot_index") is not None else None,
                penalty=int(c_raw.get("penalty", 4)),
                forbidden=bool(c_raw.get("forbidden", False)),
                name_ar=str(c_raw.get("name_ar", "")),
            )
        )

    raw_rr = data.get("repeat_range")
    repeat_range: tuple[int, int] | None = None
    if raw_rr is not None:
        if not isinstance(raw_rr, Sequence) or len(raw_rr) != 2:
            raise InvalidMeterSpecError(f"repeat_range in '{key}' must be a 2-element list [min, max].")
        repeat_range = (int(raw_rr[0]), int(raw_rr[1]))

    tier_raw = str(data.get("tier", "custom"))
    if tier_raw not in _VALID_TIERS:
        raise InvalidMeterSpecError(f"Invalid tier '{tier_raw}' in '{key}'.")
    tier: MeterTierLiteral = tier_raw  # type: ignore[assignment]

    meta = data.get("metadata")
    return cls(
        key=key,
        name_ar=str(data.get("name_ar", key)),
        name_en=str(data.get("name_en", key)),
        variation=str(data.get("variation", "custom")),
        sadr_feet=sadr_slots,
        ajuz_feet=ajuz_slots,
        single_shatr=single_shatr,
        arud_darb_rules=ad_rules,
        tasri_pairs=tasri_pairs,
        extended_pairs=extended_pairs,
        adjacent_constraints=tuple(constraints),
        repeat_range=repeat_range,
        tier=tier,
        priority=int(data.get("priority", 5)),
        allow_tasri=bool(data.get("allow_tasri", True)),
        metadata=meta if isinstance(meta, Mapping) else {},
    )

from_json(source) classmethod

Load a single MeterSpec from a JSON file path or raw JSON string.

Source code in pyarud/meters/specs.py
@classmethod
def from_json(cls, source: str | Path) -> MeterSpec:
    """Load a single ``MeterSpec`` from a JSON file path or raw JSON string."""
    raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source
    if isinstance(source, str) and not source.lstrip().startswith("{"):
        path = Path(source)
        if path.is_file():
            raw = path.read_text(encoding="utf-8")
    try:
        data = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise InvalidMeterSpecError(f"Invalid JSON for MeterSpec: {exc}") from exc
    if not isinstance(data, Mapping):
        raise InvalidMeterSpecError("MeterSpec JSON root must be an object.")
    return cls.from_dict(data)

from_patterns(key, name_ar, name_en, sadr, *, ajuz=None, single_shatr=False, variation='custom', tier='custom', priority=5, metadata=None) classmethod

Create a meter directly from literal binary pattern sequences (great for Muwashshah / custom rhythms).

Source code in pyarud/meters/specs.py
@classmethod
def from_patterns(
    cls,
    key: str,
    name_ar: str,
    name_en: str,
    sadr: Sequence[str],
    *,
    ajuz: Sequence[str] | None = None,
    single_shatr: bool = False,
    variation: str = "custom",
    tier: MeterTierLiteral = "custom",
    priority: int = 5,
    metadata: Mapping[str, Any] | None = None,
) -> MeterSpec:
    """Create a meter directly from literal binary pattern sequences (great for Muwashshah / custom rhythms)."""
    if not sadr:
        raise InvalidMeterSpecError(f"MeterSpec.from_patterns '{key}' requires non-empty sadr patterns.")

    def _pat_to_slot(idx: int, pat: str, side: str) -> FootSlotSpec:
        t_spec = TafeelaSpec(
            key=f"{key}_{side}_{idx}",
            name_ar=pat,
            name_en=f"Foot{idx + 1}",
            pattern=pat,
        )
        return FootSlotSpec(tafeela=t_spec, allowed_rules=(SALIM,))

    sadr_slots = tuple(_pat_to_slot(i, p, "sadr") for i, p in enumerate(sadr))
    ajuz_slots = (
        tuple(_pat_to_slot(i, p, "ajuz") for i, p in enumerate(ajuz))
        if ajuz is not None
        else None
    )
    ad: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...] = (
        (SALIM,) if single_shatr else {SALIM: (SALIM,)}
    )
    return cls(
        key=key,
        name_ar=name_ar,
        name_en=name_en,
        variation=variation,
        sadr_feet=sadr_slots,
        ajuz_feet=ajuz_slots,
        single_shatr=single_shatr,
        arud_darb_rules=ad,
        tier=tier,
        priority=priority,
        allow_tasri=False,
        metadata=metadata or {},
    )

from_tafeelat(key, name_ar, name_en, feet, *, ajuz_feet=None, arud_darb=None, tasri_pairs=(), extended_pairs=(), adjacent_constraints=(), single_shatr=False, variation='custom', tier='custom', priority=5, allow_tasri=True, metadata=None) classmethod

Declarative constructor accepting Arabic names, keys, TafeelaSpec, or legacy Tafeela classes.

Source code in pyarud/meters/specs.py
@classmethod
def from_tafeelat(
    cls,
    key: str,
    name_ar: str,
    name_en: str,
    feet: Sequence[FootSlotSpec | TafeelaSpec | type[Tafeela] | str],
    *,
    ajuz_feet: Sequence[FootSlotSpec | TafeelaSpec | type[Tafeela] | str] | None = None,
    arud_darb: Mapping[ProsodicRule | str, Sequence[ProsodicRule | str]]
    | Sequence[ProsodicRule | str]
    | None = None,
    tasri_pairs: Sequence[tuple[ProsodicRule | str, ProsodicRule | str]] = (),
    extended_pairs: Sequence[tuple[ProsodicRule | str, ProsodicRule | str]] = (),
    adjacent_constraints: Sequence[AdjacentFootConstraint] = (),
    single_shatr: bool = False,
    variation: str = "custom",
    tier: MeterTierLiteral = "custom",
    priority: int = 5,
    allow_tasri: bool = True,
    metadata: Mapping[str, Any] | None = None,
) -> MeterSpec:
    """Declarative constructor accepting Arabic names, keys, ``TafeelaSpec``, or legacy ``Tafeela`` classes."""
    sadr_slots = tuple(_coerce_slot(f) for f in feet)
    ajuz_slots = tuple(_coerce_slot(f) for f in ajuz_feet) if ajuz_feet is not None else None

    if arud_darb is None:
        resolved_ad: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...] = (
            (SALIM,) if single_shatr else {SALIM: (SALIM,)}
        )
    elif isinstance(arud_darb, Mapping):
        resolved_ad = {
            _resolve_rule(a): tuple(_resolve_rule(d) for d in ds)
            for a, ds in arud_darb.items()
        }
    else:
        resolved_ad = tuple(_resolve_rule(r) for r in arud_darb)

    resolved_tasri = tuple((_resolve_rule(a), _resolve_rule(d)) for a, d in tasri_pairs)
    resolved_ext = tuple((_resolve_rule(a), _resolve_rule(d)) for a, d in extended_pairs)

    return cls(
        key=key,
        name_ar=name_ar,
        name_en=name_en,
        variation=variation,
        sadr_feet=sadr_slots,
        ajuz_feet=ajuz_slots,
        single_shatr=single_shatr,
        arud_darb_rules=resolved_ad,
        tasri_pairs=resolved_tasri,
        extended_pairs=resolved_ext,
        adjacent_constraints=tuple(adjacent_constraints),
        tier=tier,
        priority=priority,
        allow_tasri=allow_tasri,
        metadata=metadata or {},
    )

from_toml(source) classmethod

Load a single MeterSpec from a TOML file path or raw TOML string.

Source code in pyarud/meters/specs.py
@classmethod
def from_toml(cls, source: str | Path) -> MeterSpec:
    """Load a single ``MeterSpec`` from a TOML file path or raw TOML string."""
    raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source
    if isinstance(source, str) and "\n" not in source and "=" not in source:
        path = Path(source)
        if path.is_file():
            raw = path.read_text(encoding="utf-8")
    try:
        data = tomllib.loads(raw)
    except tomllib.TOMLDecodeError as exc:
        raise InvalidMeterSpecError(f"Invalid TOML for MeterSpec: {exc}") from exc
    return cls.from_dict(data)

to_dict()

Serialize this MeterSpec to a JSON/TOML-compatible dictionary.

Source code in pyarud/meters/specs.py
def to_dict(self) -> dict[str, Any]:
    """Serialize this ``MeterSpec`` to a JSON/TOML-compatible dictionary."""
    custom_tafeelat: dict[str, dict[str, Any]] = {}
    custom_rules: dict[str, dict[str, Any]] = {}

    def _collect_rule(r: ProsodicRule) -> None:
        if r.key in CLASSICAL_RULES or r.key in custom_rules:
            return
        for sub in r.sub_rules:
            _collect_rule(sub)
        custom_rules[r.key] = r.to_dict()

    def _collect_slot(slot: FootSlotSpec) -> None:
        t = slot.tafeela
        if t.key not in CLASSICAL_TAFEELAT and t.key not in custom_tafeelat:
            custom_tafeelat[t.key] = t.to_dict()
            for z in t.allowed_zihafs:
                _collect_rule(z)
        if slot.allowed_rules is not None:
            for r in slot.allowed_rules:
                _collect_rule(r)
        for r in slot.disallowed_rules:
            _collect_rule(r)

    for slot in self.sadr_feet:
        _collect_slot(slot)
    if self.ajuz_feet is not None:
        for slot in self.ajuz_feet:
            _collect_slot(slot)

    arud_darb_out: dict[str, list[str]] | list[str]
    if isinstance(self.arud_darb_rules, Mapping):
        arud_darb_out = {}
        for a_rule, d_rules in self.arud_darb_rules.items():
            _collect_rule(a_rule)
            for dr in d_rules:
                _collect_rule(dr)
            arud_darb_out[a_rule.key] = [dr.key for dr in d_rules]
    else:
        for r in self.arud_darb_rules:
            _collect_rule(r)
        arud_darb_out = [r.key for r in self.arud_darb_rules]

    for a_r, d_r in (*self.tasri_pairs, *self.extended_pairs):
        _collect_rule(a_r)
        _collect_rule(d_r)

    out: dict[str, Any] = {
        "key": self.key,
        "name_ar": self.name_ar,
        "name_en": self.name_en,
        "variation": self.variation,
        "tier": self.tier,
        "priority": self.priority,
        "single_shatr": self.single_shatr,
        "allow_tasri": self.allow_tasri,
        "sadr_feet": [s.to_dict() for s in self.sadr_feet],
        "arud_darb_rules": arud_darb_out,
    }
    if self.ajuz_feet is not None:
        out["ajuz_feet"] = [s.to_dict() for s in self.ajuz_feet]
    if self.repeat_range is not None:
        out["repeat_range"] = [self.repeat_range[0], self.repeat_range[1]]
    if self.tasri_pairs:
        out["tasri_pairs"] = [[a.key, d.key] for a, d in self.tasri_pairs]
    if self.extended_pairs:
        out["extended_pairs"] = [[a.key, d.key] for a, d in self.extended_pairs]
    if self.adjacent_constraints:
        out["adjacent_constraints"] = [
            {
                "left_rule": c.left_rule,
                "right_rule": c.right_rule,
                "slot_index": c.slot_index,
                "penalty": c.penalty,
                "forbidden": c.forbidden,
                "name_ar": c.name_ar,
            }
            for c in self.adjacent_constraints
        ]
    if custom_rules:
        out["custom_rules"] = list(custom_rules.values())
    if custom_tafeelat:
        out["custom_tafeelat"] = list(custom_tafeelat.values())
    if self.metadata:
        out["metadata"] = dict(self.metadata)
    return out

pyarud.meters.specs.MeterBuilder

Fluent, validated builder for constructing custom MeterSpec instances step by step.

Source code in pyarud/meters/specs.py
class MeterBuilder:
    """Fluent, validated builder for constructing custom ``MeterSpec`` instances step by step."""

    def __init__(self, key: str, name_ar: str, name_en: str = "") -> None:
        self._key = key
        self._name_ar = name_ar
        self._name_en = name_en or key
        self._variation: str = "custom"
        self._tier: MeterTierLiteral = "custom"
        self._priority: int = 5
        self._single_shatr: bool = False
        self._allow_tasri: bool = True
        self._sadr_feet: list[FootSlotSpec] = []
        self._ajuz_feet: list[FootSlotSpec] = []
        self._arud_darb: dict[ProsodicRule, list[ProsodicRule]] = {}
        self._single_endings: list[ProsodicRule] = []
        self._tasri_pairs: list[tuple[ProsodicRule, ProsodicRule]] = []
        self._extended_pairs: list[tuple[ProsodicRule, ProsodicRule]] = []
        self._constraints: list[AdjacentFootConstraint] = []
        self._repeat_range: tuple[int, int] | None = None
        self._metadata: dict[str, Any] = {}

    def variation(self, variation: str) -> MeterBuilder:
        self._variation = variation
        return self

    def tier(self, tier: MeterTierLiteral) -> MeterBuilder:
        self._tier = tier
        return self

    def priority(self, priority: int) -> MeterBuilder:
        self._priority = priority
        return self

    def single_shatr(self, value: bool = True) -> MeterBuilder:
        self._single_shatr = value
        return self

    def allow_tasri(self, value: bool = True) -> MeterBuilder:
        self._allow_tasri = value
        return self

    def add_foot(
        self,
        foot: FootSlotSpec | TafeelaSpec | type[Tafeela] | str,
        *,
        allowed: Sequence[ProsodicRule | type[BaseEllahZehaf] | str] | None = None,
        disallowed: Sequence[ProsodicRule | type[BaseEllahZehaf] | str] = (),
        extra_patterns: Sequence[str] = (),
    ) -> MeterBuilder:
        """Append a foot slot to Sadr (and mirrored to Ajuz unless ``add_ajuz_foot`` is used)."""
        base = _coerce_slot(foot)
        slot = FootSlotSpec(
            tafeela=base.tafeela,
            allowed_rules=tuple(_resolve_rule(r) for r in allowed) if allowed is not None else base.allowed_rules,
            disallowed_rules=tuple(_resolve_rule(r) for r in disallowed) or base.disallowed_rules,
            extra_patterns=tuple(extra_patterns) or base.extra_patterns,
        )
        self._sadr_feet.append(slot)
        return self

    def add_ajuz_foot(
        self,
        foot: FootSlotSpec | TafeelaSpec | type[Tafeela] | str,
        *,
        allowed: Sequence[ProsodicRule | type[BaseEllahZehaf] | str] | None = None,
        disallowed: Sequence[ProsodicRule | type[BaseEllahZehaf] | str] = (),
        extra_patterns: Sequence[str] = (),
    ) -> MeterBuilder:
        """Append an explicit foot slot to Ajuz for asymmetric meters (e.g. Muwashshah)."""
        base = _coerce_slot(foot)
        slot = FootSlotSpec(
            tafeela=base.tafeela,
            allowed_rules=tuple(_resolve_rule(r) for r in allowed) if allowed is not None else base.allowed_rules,
            disallowed_rules=tuple(_resolve_rule(r) for r in disallowed) or base.disallowed_rules,
            extra_patterns=tuple(extra_patterns) or base.extra_patterns,
        )
        self._ajuz_feet.append(slot)
        return self

    def arud_darb(
        self,
        arud: ProsodicRule | type[BaseEllahZehaf] | str,
        darbs: Sequence[ProsodicRule | type[BaseEllahZehaf] | str],
    ) -> MeterBuilder:
        """Register a valid Arud -> Darbs pairing."""
        a_rule = _resolve_rule(arud)
        d_list = self._arud_darb.setdefault(a_rule, [])
        for d in darbs:
            d_rule = _resolve_rule(d)
            if d_rule not in d_list:
                d_list.append(d_rule)
        return self

    def ending_rules(
        self,
        *rules: ProsodicRule | type[BaseEllahZehaf] | str,
    ) -> MeterBuilder:
        """Register valid ending rules for a ``single_shatr`` or free-verse meter."""
        for r in rules:
            resolved = _resolve_rule(r)
            if resolved not in self._single_endings:
                self._single_endings.append(resolved)
        return self

    def tasri(
        self,
        arud: ProsodicRule | type[BaseEllahZehaf] | str,
        darb: ProsodicRule | type[BaseEllahZehaf] | str,
    ) -> MeterBuilder:
        """Register a valid Tasri' (التصريع) pairing."""
        self._tasri_pairs.append((_resolve_rule(arud), _resolve_rule(darb)))
        return self

    def extended_pair(
        self,
        arud: ProsodicRule | type[BaseEllahZehaf] | str,
        darb: ProsodicRule | type[BaseEllahZehaf] | str,
    ) -> MeterBuilder:
        """Register an extended (lower-preference) Arud-Darb pairing."""
        self._extended_pairs.append((_resolve_rule(arud), _resolve_rule(darb)))
        return self

    def constraint(self, constraint: AdjacentFootConstraint) -> MeterBuilder:
        """Add an adjacent-foot prosodic constraint (e.g. Mu'aqabah or I'timad)."""
        self._constraints.append(constraint)
        return self

    def repeat(self, min_feet: int, max_feet: int) -> MeterBuilder:
        """Configure variable-length repetition (شعر التفعيلة)."""
        self._repeat_range = (min_feet, max_feet)
        self._single_shatr = True
        if self._variation == "custom":
            self._variation = "tafeela"
        return self

    def metadata(self, **kwargs: Any) -> MeterBuilder:
        self._metadata.update(kwargs)
        return self

    def build(self) -> MeterSpec:
        """Validate and return the immutable ``MeterSpec``."""
        ad: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...]
        if self._single_shatr:
            ad = tuple(self._single_endings) if self._single_endings else (SALIM,)
        elif self._arud_darb:
            ad = {a: tuple(ds) for a, ds in self._arud_darb.items()}
        else:
            ad = {SALIM: (SALIM,)}

        return MeterSpec(
            key=self._key,
            name_ar=self._name_ar,
            name_en=self._name_en,
            variation=self._variation,
            sadr_feet=tuple(self._sadr_feet),
            ajuz_feet=tuple(self._ajuz_feet) if self._ajuz_feet else None,
            single_shatr=self._single_shatr,
            arud_darb_rules=ad,
            tasri_pairs=tuple(self._tasri_pairs),
            extended_pairs=tuple(self._extended_pairs),
            adjacent_constraints=tuple(self._constraints),
            repeat_range=self._repeat_range,
            tier=self._tier,
            priority=self._priority,
            allow_tasri=self._allow_tasri,
            metadata=self._metadata,
        )

add_ajuz_foot(foot, *, allowed=None, disallowed=(), extra_patterns=())

Append an explicit foot slot to Ajuz for asymmetric meters (e.g. Muwashshah).

Source code in pyarud/meters/specs.py
def add_ajuz_foot(
    self,
    foot: FootSlotSpec | TafeelaSpec | type[Tafeela] | str,
    *,
    allowed: Sequence[ProsodicRule | type[BaseEllahZehaf] | str] | None = None,
    disallowed: Sequence[ProsodicRule | type[BaseEllahZehaf] | str] = (),
    extra_patterns: Sequence[str] = (),
) -> MeterBuilder:
    """Append an explicit foot slot to Ajuz for asymmetric meters (e.g. Muwashshah)."""
    base = _coerce_slot(foot)
    slot = FootSlotSpec(
        tafeela=base.tafeela,
        allowed_rules=tuple(_resolve_rule(r) for r in allowed) if allowed is not None else base.allowed_rules,
        disallowed_rules=tuple(_resolve_rule(r) for r in disallowed) or base.disallowed_rules,
        extra_patterns=tuple(extra_patterns) or base.extra_patterns,
    )
    self._ajuz_feet.append(slot)
    return self

add_foot(foot, *, allowed=None, disallowed=(), extra_patterns=())

Append a foot slot to Sadr (and mirrored to Ajuz unless add_ajuz_foot is used).

Source code in pyarud/meters/specs.py
def add_foot(
    self,
    foot: FootSlotSpec | TafeelaSpec | type[Tafeela] | str,
    *,
    allowed: Sequence[ProsodicRule | type[BaseEllahZehaf] | str] | None = None,
    disallowed: Sequence[ProsodicRule | type[BaseEllahZehaf] | str] = (),
    extra_patterns: Sequence[str] = (),
) -> MeterBuilder:
    """Append a foot slot to Sadr (and mirrored to Ajuz unless ``add_ajuz_foot`` is used)."""
    base = _coerce_slot(foot)
    slot = FootSlotSpec(
        tafeela=base.tafeela,
        allowed_rules=tuple(_resolve_rule(r) for r in allowed) if allowed is not None else base.allowed_rules,
        disallowed_rules=tuple(_resolve_rule(r) for r in disallowed) or base.disallowed_rules,
        extra_patterns=tuple(extra_patterns) or base.extra_patterns,
    )
    self._sadr_feet.append(slot)
    return self

arud_darb(arud, darbs)

Register a valid Arud -> Darbs pairing.

Source code in pyarud/meters/specs.py
def arud_darb(
    self,
    arud: ProsodicRule | type[BaseEllahZehaf] | str,
    darbs: Sequence[ProsodicRule | type[BaseEllahZehaf] | str],
) -> MeterBuilder:
    """Register a valid Arud -> Darbs pairing."""
    a_rule = _resolve_rule(arud)
    d_list = self._arud_darb.setdefault(a_rule, [])
    for d in darbs:
        d_rule = _resolve_rule(d)
        if d_rule not in d_list:
            d_list.append(d_rule)
    return self

build()

Validate and return the immutable MeterSpec.

Source code in pyarud/meters/specs.py
def build(self) -> MeterSpec:
    """Validate and return the immutable ``MeterSpec``."""
    ad: Mapping[ProsodicRule, tuple[ProsodicRule, ...]] | tuple[ProsodicRule, ...]
    if self._single_shatr:
        ad = tuple(self._single_endings) if self._single_endings else (SALIM,)
    elif self._arud_darb:
        ad = {a: tuple(ds) for a, ds in self._arud_darb.items()}
    else:
        ad = {SALIM: (SALIM,)}

    return MeterSpec(
        key=self._key,
        name_ar=self._name_ar,
        name_en=self._name_en,
        variation=self._variation,
        sadr_feet=tuple(self._sadr_feet),
        ajuz_feet=tuple(self._ajuz_feet) if self._ajuz_feet else None,
        single_shatr=self._single_shatr,
        arud_darb_rules=ad,
        tasri_pairs=tuple(self._tasri_pairs),
        extended_pairs=tuple(self._extended_pairs),
        adjacent_constraints=tuple(self._constraints),
        repeat_range=self._repeat_range,
        tier=self._tier,
        priority=self._priority,
        allow_tasri=self._allow_tasri,
        metadata=self._metadata,
    )

constraint(constraint)

Add an adjacent-foot prosodic constraint (e.g. Mu'aqabah or I'timad).

Source code in pyarud/meters/specs.py
def constraint(self, constraint: AdjacentFootConstraint) -> MeterBuilder:
    """Add an adjacent-foot prosodic constraint (e.g. Mu'aqabah or I'timad)."""
    self._constraints.append(constraint)
    return self

ending_rules(*rules)

Register valid ending rules for a single_shatr or free-verse meter.

Source code in pyarud/meters/specs.py
def ending_rules(
    self,
    *rules: ProsodicRule | type[BaseEllahZehaf] | str,
) -> MeterBuilder:
    """Register valid ending rules for a ``single_shatr`` or free-verse meter."""
    for r in rules:
        resolved = _resolve_rule(r)
        if resolved not in self._single_endings:
            self._single_endings.append(resolved)
    return self

extended_pair(arud, darb)

Register an extended (lower-preference) Arud-Darb pairing.

Source code in pyarud/meters/specs.py
def extended_pair(
    self,
    arud: ProsodicRule | type[BaseEllahZehaf] | str,
    darb: ProsodicRule | type[BaseEllahZehaf] | str,
) -> MeterBuilder:
    """Register an extended (lower-preference) Arud-Darb pairing."""
    self._extended_pairs.append((_resolve_rule(arud), _resolve_rule(darb)))
    return self

repeat(min_feet, max_feet)

Configure variable-length repetition (شعر التفعيلة).

Source code in pyarud/meters/specs.py
def repeat(self, min_feet: int, max_feet: int) -> MeterBuilder:
    """Configure variable-length repetition (شعر التفعيلة)."""
    self._repeat_range = (min_feet, max_feet)
    self._single_shatr = True
    if self._variation == "custom":
        self._variation = "tafeela"
    return self

tasri(arud, darb)

Register a valid Tasri' (التصريع) pairing.

Source code in pyarud/meters/specs.py
def tasri(
    self,
    arud: ProsodicRule | type[BaseEllahZehaf] | str,
    darb: ProsodicRule | type[BaseEllahZehaf] | str,
) -> MeterBuilder:
    """Register a valid Tasri' (التصريع) pairing."""
    self._tasri_pairs.append((_resolve_rule(arud), _resolve_rule(darb)))
    return self

pyarud.meters.specs.TafeelaSpec dataclass

Immutable, validated specification of a prosodic foot (تفعيلة).

Source code in pyarud/meters/specs.py
@dataclass(frozen=True, slots=True, eq=False)
class TafeelaSpec:
    """Immutable, validated specification of a prosodic foot (تفعيلة)."""

    key: str
    name_ar: str
    name_en: str
    pattern: str
    allowed_zihafs: tuple[ProsodicRule, ...] = ()
    ending_unit: EndingUnitLiteral = "other"
    form_names_ar: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
    legacy_cls: type[Tafeela] | None = None

    def __post_init__(self) -> None:
        if not self.key or not self.key.strip():
            raise InvalidMeterSpecError("TafeelaSpec.key must be a non-empty string.")
        if not _RE_TAFEELA_PATTERN.match(self.pattern):
            raise InvalidMeterSpecError(
                f"TafeelaSpec '{self.key}' pattern must match ^[01]{{2,}}$, got {self.pattern!r}."
            )
        if self.ending_unit not in _VALID_ENDING_UNITS:
            raise InvalidMeterSpecError(
                f"Invalid ending_unit '{self.ending_unit}' on TafeelaSpec '{self.key}'."
            )
        object.__setattr__(self, "allowed_zihafs", tuple(self.allowed_zihafs))
        object.__setattr__(self, "form_names_ar", _freeze_str_mapping(self.form_names_ar))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, TafeelaSpec):
            return (
                self.key == other.key
                and self.pattern == other.pattern
                and self.ending_unit == other.ending_unit
                and self.allowed_zihafs == other.allowed_zihafs
            )
        return False

    def __hash__(self) -> int:
        return hash((self.key, self.pattern, self.ending_unit, self.allowed_zihafs))

    def apply_rule(self, rule: ProsodicRule) -> str | None:
        """Apply ``rule`` to this foot, enforcing exact classical structural preconditions."""
        if rule is SALIM or rule.kind == "salim":
            return self.pattern
        if self.legacy_cls is not None and rule.legacy_cls is not None:
            try:
                return rule.legacy_cls(self.legacy_cls()).modified_tafeela.pattern_str
            except AssertionError:
                return None
        return rule.apply(self.pattern)

    def resolve_form_name(self, rule: ProsodicRule) -> str:
        """Return the surface Arabic foot name after applying ``rule``."""
        if rule.key in self.form_names_ar:
            return self.form_names_ar[rule.key]
        if self.key in rule.form_names_ar:
            return rule.form_names_ar[self.key]
        if self.name_en in rule.form_names_ar:
            return rule.form_names_ar[self.name_en]
        lookup = TAFEELA_FORM_NAMES_AR.get((self.name_en, rule.key))
        if lookup is not None:
            return lookup
        return self.name_ar

    @classmethod
    def from_arabic(
        cls,
        key: str,
        vocalized: str,
        *,
        name_ar: str | None = None,
        name_en: str | None = None,
        allowed_zihafs: Sequence[ProsodicRule] = (),
        ending_unit: EndingUnitLiteral | None = None,
        form_names_ar: Mapping[str, str] | None = None,
        converter: Any = None,
    ) -> TafeelaSpec:
        """Construct a ``TafeelaSpec`` directly from a vocalized Arabic foot string."""
        if not vocalized or not vocalized.strip():
            raise InvalidMeterSpecError("TafeelaSpec.from_arabic requires non-empty vocalized Arabic text.")
        if converter is None:
            from ..core.phonetics import ArudiConverter

            converter = ArudiConverter()
        _arudi, pat = converter.prepare_text(vocalized.strip(), saturate=False)
        if not _RE_TAFEELA_PATTERN.match(pat):
            raise InvalidMeterSpecError(
                f"Vocalized foot {vocalized!r} produced invalid binary pattern {pat!r}."
            )
        inferred_unit: EndingUnitLiteral
        if ending_unit is not None:
            inferred_unit = ending_unit
        elif pat.endswith("110"):
            inferred_unit = "watad_majmu"
        elif pat.endswith("101"):
            inferred_unit = "watad_mafruq"
        elif pat.endswith("10"):
            inferred_unit = "sabab_khafif"
        else:
            inferred_unit = "other"

        return cls(
            key=key,
            name_ar=name_ar or vocalized.strip(),
            name_en=name_en or key,
            pattern=pat,
            allowed_zihafs=tuple(allowed_zihafs),
            ending_unit=inferred_unit,
            form_names_ar=form_names_ar or {},
        )

    @classmethod
    def from_tafeela_class(cls, tafeela_cls: type[Tafeela]) -> TafeelaSpec:
        """Convert a classical or custom ``Tafeela`` subclass into a ``TafeelaSpec``."""
        cached = _LEGACY_TAFEELA_TO_SPEC.get(tafeela_cls)
        if cached is not None:
            return cached
        fnames = {
            r_name: ar_name
            for (t_en, r_name), ar_name in TAFEELA_FORM_NAMES_AR.items()
            if t_en == tafeela_cls.name_en
        }
        unit_raw = tafeela_cls.ending_unit_default
        unit: EndingUnitLiteral = (
            unit_raw if unit_raw in _VALID_ENDING_UNITS else "other"  # type: ignore[assignment]
        )
        return cls(
            key=tafeela_cls.name_en.lower() or tafeela_cls.__name__.lower(),
            name_ar=tafeela_cls.name,
            name_en=tafeela_cls.name_en or tafeela_cls.__name__,
            pattern=tafeela_cls.base_pattern,
            allowed_zihafs=tuple(rule_from_legacy(z) for z in tafeela_cls.allowed_zehafs),
            ending_unit=unit,
            form_names_ar=fnames,
            legacy_cls=tafeela_cls,
        )

    def to_dict(self) -> dict[str, Any]:
        out: dict[str, Any] = {
            "key": self.key,
            "name_ar": self.name_ar,
            "name_en": self.name_en,
            "pattern": self.pattern,
            "ending_unit": self.ending_unit,
            "allowed_zihafs": [z.key for z in self.allowed_zihafs],
        }
        if self.form_names_ar:
            out["form_names_ar"] = dict(self.form_names_ar)
        return out

    @classmethod
    def from_dict(
        cls,
        data: Mapping[str, Any],
        *,
        known_rules: Mapping[str, ProsodicRule] | None = None,
    ) -> TafeelaSpec:
        key = str(data.get("key", "")).strip()
        if not key:
            raise InvalidMeterSpecError("Tafeela dictionary missing required field 'key'.")
        pattern = str(data.get("pattern", "")).strip()
        name_ar = str(data.get("name_ar", key))
        name_en = str(data.get("name_en", key))
        unit_raw = str(data.get("ending_unit", "other"))
        if unit_raw not in _VALID_ENDING_UNITS:
            raise InvalidMeterSpecError(f"Invalid ending_unit '{unit_raw}' for tafeela '{key}'.")
        unit: EndingUnitLiteral = unit_raw  # type: ignore[assignment]
        raw_zihafs = data.get("allowed_zihafs", ())
        zihafs = tuple(_resolve_rule(z, extra_rules=known_rules) for z in raw_zihafs)
        fnames_raw = data.get("form_names_ar")
        fnames: Mapping[str, str] = (
            {str(k): str(v) for k, v in fnames_raw.items()}
            if isinstance(fnames_raw, Mapping)
            else {}
        )
        return cls(
            key=key,
            name_ar=name_ar,
            name_en=name_en,
            pattern=pattern,
            allowed_zihafs=zihafs,
            ending_unit=unit,
            form_names_ar=fnames,
        )

apply_rule(rule)

Apply rule to this foot, enforcing exact classical structural preconditions.

Source code in pyarud/meters/specs.py
def apply_rule(self, rule: ProsodicRule) -> str | None:
    """Apply ``rule`` to this foot, enforcing exact classical structural preconditions."""
    if rule is SALIM or rule.kind == "salim":
        return self.pattern
    if self.legacy_cls is not None and rule.legacy_cls is not None:
        try:
            return rule.legacy_cls(self.legacy_cls()).modified_tafeela.pattern_str
        except AssertionError:
            return None
    return rule.apply(self.pattern)

from_arabic(key, vocalized, *, name_ar=None, name_en=None, allowed_zihafs=(), ending_unit=None, form_names_ar=None, converter=None) classmethod

Construct a TafeelaSpec directly from a vocalized Arabic foot string.

Source code in pyarud/meters/specs.py
@classmethod
def from_arabic(
    cls,
    key: str,
    vocalized: str,
    *,
    name_ar: str | None = None,
    name_en: str | None = None,
    allowed_zihafs: Sequence[ProsodicRule] = (),
    ending_unit: EndingUnitLiteral | None = None,
    form_names_ar: Mapping[str, str] | None = None,
    converter: Any = None,
) -> TafeelaSpec:
    """Construct a ``TafeelaSpec`` directly from a vocalized Arabic foot string."""
    if not vocalized or not vocalized.strip():
        raise InvalidMeterSpecError("TafeelaSpec.from_arabic requires non-empty vocalized Arabic text.")
    if converter is None:
        from ..core.phonetics import ArudiConverter

        converter = ArudiConverter()
    _arudi, pat = converter.prepare_text(vocalized.strip(), saturate=False)
    if not _RE_TAFEELA_PATTERN.match(pat):
        raise InvalidMeterSpecError(
            f"Vocalized foot {vocalized!r} produced invalid binary pattern {pat!r}."
        )
    inferred_unit: EndingUnitLiteral
    if ending_unit is not None:
        inferred_unit = ending_unit
    elif pat.endswith("110"):
        inferred_unit = "watad_majmu"
    elif pat.endswith("101"):
        inferred_unit = "watad_mafruq"
    elif pat.endswith("10"):
        inferred_unit = "sabab_khafif"
    else:
        inferred_unit = "other"

    return cls(
        key=key,
        name_ar=name_ar or vocalized.strip(),
        name_en=name_en or key,
        pattern=pat,
        allowed_zihafs=tuple(allowed_zihafs),
        ending_unit=inferred_unit,
        form_names_ar=form_names_ar or {},
    )

from_tafeela_class(tafeela_cls) classmethod

Convert a classical or custom Tafeela subclass into a TafeelaSpec.

Source code in pyarud/meters/specs.py
@classmethod
def from_tafeela_class(cls, tafeela_cls: type[Tafeela]) -> TafeelaSpec:
    """Convert a classical or custom ``Tafeela`` subclass into a ``TafeelaSpec``."""
    cached = _LEGACY_TAFEELA_TO_SPEC.get(tafeela_cls)
    if cached is not None:
        return cached
    fnames = {
        r_name: ar_name
        for (t_en, r_name), ar_name in TAFEELA_FORM_NAMES_AR.items()
        if t_en == tafeela_cls.name_en
    }
    unit_raw = tafeela_cls.ending_unit_default
    unit: EndingUnitLiteral = (
        unit_raw if unit_raw in _VALID_ENDING_UNITS else "other"  # type: ignore[assignment]
    )
    return cls(
        key=tafeela_cls.name_en.lower() or tafeela_cls.__name__.lower(),
        name_ar=tafeela_cls.name,
        name_en=tafeela_cls.name_en or tafeela_cls.__name__,
        pattern=tafeela_cls.base_pattern,
        allowed_zihafs=tuple(rule_from_legacy(z) for z in tafeela_cls.allowed_zehafs),
        ending_unit=unit,
        form_names_ar=fnames,
        legacy_cls=tafeela_cls,
    )

resolve_form_name(rule)

Return the surface Arabic foot name after applying rule.

Source code in pyarud/meters/specs.py
def resolve_form_name(self, rule: ProsodicRule) -> str:
    """Return the surface Arabic foot name after applying ``rule``."""
    if rule.key in self.form_names_ar:
        return self.form_names_ar[rule.key]
    if self.key in rule.form_names_ar:
        return rule.form_names_ar[self.key]
    if self.name_en in rule.form_names_ar:
        return rule.form_names_ar[self.name_en]
    lookup = TAFEELA_FORM_NAMES_AR.get((self.name_en, rule.key))
    if lookup is not None:
        return lookup
    return self.name_ar

pyarud.meters.specs.ProsodicRule dataclass

Immutable, hashable prosodic modification rule (Zihaf, 'Ilah, or custom transformation).

Transforms a binary pattern string ('1' = Haraka, '0' = Sukun) into a new binary pattern string or None if the rule is not applicable to the input foot.

Source code in pyarud/meters/specs.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
@dataclass(frozen=True, slots=True, eq=False)
class ProsodicRule:
    """Immutable, hashable prosodic modification rule (Zihaf, 'Ilah, or custom transformation).

    Transforms a binary pattern string (``'1'`` = Haraka, ``'0'`` = Sukun) into a new
    binary pattern string or ``None`` if the rule is not applicable to the input foot.
    """

    key: str
    name_ar: str
    name_en: str
    kind: RuleKind = "zihaf"
    cost: int = 1
    transform: Callable[[str], str | None] = _identity_transform
    form_names_ar: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
    description_ar: str = ""
    is_illah: bool = False
    legacy_cls: type[BaseEllahZehaf] | None = None
    rule_spec: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))
    sub_rules: tuple[ProsodicRule, ...] = ()

    def __post_init__(self) -> None:
        if not self.key or not self.key.strip():
            raise InvalidMeterSpecError("ProsodicRule.key must be a non-empty string.")
        if self.kind not in _VALID_RULE_KINDS:
            raise InvalidMeterSpecError(
                f"Invalid ProsodicRule.kind '{self.kind}'; expected one of {sorted(_VALID_RULE_KINDS)}."
            )
        if self.cost < 0:
            raise InvalidMeterSpecError(f"ProsodicRule.cost must be >= 0, got {self.cost}.")
        object.__setattr__(self, "form_names_ar", _freeze_str_mapping(self.form_names_ar))
        object.__setattr__(self, "rule_spec", _freeze_mapping(self.rule_spec))
        object.__setattr__(self, "sub_rules", tuple(self.sub_rules))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, ProsodicRule):
            return (
                self.key == other.key
                and self.kind == other.kind
                and self.cost == other.cost
                and self.is_illah == other.is_illah
            )
        return False

    def __hash__(self) -> int:
        return hash((self.key, self.kind, self.cost, self.is_illah))

    def apply(self, pattern: str) -> str | None:
        """Apply this rule to a binary pattern string; returns ``None`` if inapplicable."""
        if not pattern or not _RE_BINARY_PATTERN.match(pattern):
            return None
        result = self.transform(pattern)
        if result is None or not result or not _RE_BINARY_PATTERN.match(result):
            return None
        return result

    @classmethod
    def delete_at(
        cls,
        key: str,
        index: int,
        *,
        expected: str | None = None,
        name_ar: str = "",
        name_en: str = "",
        kind: RuleKind = "zihaf",
        cost: int = 1,
        is_illah: bool = False,
        description_ar: str = "",
        form_names_ar: Mapping[str, str] | None = None,
    ) -> ProsodicRule:
        """Create a rule that deletes the bit at ``index`` (optionally checking ``expected`` bit)."""
        if index < 0:
            raise InvalidMeterSpecError(f"delete_at index must be >= 0, got {index}.")
        if expected is not None and expected not in ("0", "1"):
            raise InvalidMeterSpecError(f"expected bit must be '0', '1', or None, got {expected!r}.")

        def _tx(pat: str) -> str | None:
            if index >= len(pat):
                return None
            if expected is not None and pat[index] != expected:
                return None
            res = pat[:index] + pat[index + 1 :]
            return res if res else None

        spec: dict[str, Any] = {"op": "delete_at", "index": index}
        if expected is not None:
            spec["expected"] = expected
        return cls(
            key=key,
            name_ar=name_ar or key,
            name_en=name_en or key,
            kind=kind,
            cost=cost,
            transform=_tx,
            form_names_ar=form_names_ar or {},
            description_ar=description_ar,
            is_illah=is_illah,
            rule_spec=spec,
        )

    @classmethod
    def quiesce_at(
        cls,
        key: str,
        index: int,
        *,
        name_ar: str = "",
        name_en: str = "",
        kind: RuleKind = "zihaf",
        cost: int = 1,
        is_illah: bool = False,
        description_ar: str = "",
        form_names_ar: Mapping[str, str] | None = None,
    ) -> ProsodicRule:
        """Create a rule that turns a Mutaharrik (``'1'``) at ``index`` into a Sakin (``'0'``)."""
        if index < 0:
            raise InvalidMeterSpecError(f"quiesce_at index must be >= 0, got {index}.")

        def _tx(pat: str) -> str | None:
            if index >= len(pat) or pat[index] != "1":
                return None
            return pat[:index] + "0" + pat[index + 1 :]

        return cls(
            key=key,
            name_ar=name_ar or key,
            name_en=name_en or key,
            kind=kind,
            cost=cost,
            transform=_tx,
            form_names_ar=form_names_ar or {},
            description_ar=description_ar,
            is_illah=is_illah,
            rule_spec={"op": "quiesce_at", "index": index},
        )

    @classmethod
    def append_pattern(
        cls,
        key: str,
        suffix: str,
        *,
        require_suffix: str | None = None,
        name_ar: str = "",
        name_en: str = "",
        kind: RuleKind = "illah",
        cost: int = 0,
        is_illah: bool = True,
        description_ar: str = "",
        form_names_ar: Mapping[str, str] | None = None,
    ) -> ProsodicRule:
        """Create an addition rule that appends ``suffix`` (e.g. ``'10'`` or ``'0'``)."""
        if not suffix or not _RE_BINARY_PATTERN.match(suffix):
            raise InvalidMeterSpecError(f"append_pattern suffix must be binary [01]+, got {suffix!r}.")
        if require_suffix is not None and not _RE_BINARY_PATTERN.match(require_suffix):
            raise InvalidMeterSpecError(
                f"append_pattern require_suffix must be binary [01]+, got {require_suffix!r}."
            )

        def _tx(pat: str) -> str | None:
            if require_suffix is not None and not pat.endswith(require_suffix):
                return None
            return pat + suffix

        spec: dict[str, Any] = {"op": "append_pattern", "suffix": suffix}
        if require_suffix is not None:
            spec["require_suffix"] = require_suffix
        return cls(
            key=key,
            name_ar=name_ar or key,
            name_en=name_en or key,
            kind=kind,
            cost=cost,
            transform=_tx,
            form_names_ar=form_names_ar or {},
            description_ar=description_ar,
            is_illah=is_illah,
            rule_spec=spec,
        )

    @classmethod
    def strip_suffix(
        cls,
        key: str,
        suffix: str,
        *,
        replace_with: str = "",
        name_ar: str = "",
        name_en: str = "",
        kind: RuleKind = "illah",
        cost: int = 0,
        is_illah: bool = True,
        description_ar: str = "",
        form_names_ar: Mapping[str, str] | None = None,
    ) -> ProsodicRule:
        """Create a deletion/cadence rule stripping ``suffix`` and optionally appending ``replace_with``."""
        if not suffix or not _RE_BINARY_PATTERN.match(suffix):
            raise InvalidMeterSpecError(f"strip_suffix suffix must be binary [01]+, got {suffix!r}.")
        if replace_with and not _RE_BINARY_PATTERN.match(replace_with):
            raise InvalidMeterSpecError(
                f"strip_suffix replace_with must be binary [01]*, got {replace_with!r}."
            )

        def _tx(pat: str) -> str | None:
            if not pat.endswith(suffix):
                return None
            res = pat[: -len(suffix)] + replace_with
            return res if res else None

        return cls(
            key=key,
            name_ar=name_ar or key,
            name_en=name_en or key,
            kind=kind,
            cost=cost,
            transform=_tx,
            form_names_ar=form_names_ar or {},
            description_ar=description_ar,
            is_illah=is_illah,
            rule_spec={"op": "strip_suffix", "suffix": suffix, "replace_with": replace_with},
        )

    @classmethod
    def explicit(
        cls,
        key: str,
        mapping: Mapping[str, str],
        *,
        name_ar: str = "",
        name_en: str = "",
        kind: RuleKind = "zihaf",
        cost: int = 1,
        is_illah: bool = False,
        description_ar: str = "",
        form_names_ar: Mapping[str, str] | None = None,
    ) -> ProsodicRule:
        """Create a rule defined by an explicit ``input_pattern -> output_pattern`` map."""
        if not mapping:
            raise InvalidMeterSpecError("explicit mapping must not be empty.")
        clean_map: dict[str, str] = {}
        for src, dst in mapping.items():
            if not _RE_BINARY_PATTERN.match(src) or not _RE_BINARY_PATTERN.match(dst):
                raise InvalidMeterSpecError(
                    f"explicit mapping entries must be binary [01]+, got {src!r} -> {dst!r}."
                )
            clean_map[src] = dst

        frozen_map = MappingProxyType(clean_map)

        def _tx(pat: str) -> str | None:
            return frozen_map.get(pat)

        return cls(
            key=key,
            name_ar=name_ar or key,
            name_en=name_en or key,
            kind=kind,
            cost=cost,
            transform=_tx,
            form_names_ar=form_names_ar or {},
            description_ar=description_ar,
            is_illah=is_illah,
            rule_spec={"op": "explicit", "mapping": dict(clean_map)},
        )

    @classmethod
    def compose(
        cls,
        key: str,
        *rules: ProsodicRule,
        name_ar: str = "",
        name_en: str = "",
        kind: RuleKind = "compound",
        cost: int | None = None,
        is_illah: bool | None = None,
        description_ar: str = "",
        form_names_ar: Mapping[str, str] | None = None,
    ) -> ProsodicRule:
        """Compose multiple ``ProsodicRule`` transformations left-to-right."""
        if not rules:
            raise InvalidMeterSpecError("ProsodicRule.compose requires at least one rule.")
        rule_tuple = tuple(rules)

        def _tx(pat: str) -> str | None:
            cur: str | None = pat
            for r in rule_tuple:
                if cur is None:
                    return None
                cur = r.apply(cur)
            return cur

        total_cost = sum(r.cost for r in rule_tuple) if cost is None else cost
        any_illah = any(r.is_illah for r in rule_tuple) if is_illah is None else is_illah
        return cls(
            key=key,
            name_ar=name_ar or " + ".join(r.name_ar for r in rule_tuple),
            name_en=name_en or " + ".join(r.name_en for r in rule_tuple),
            kind=kind,
            cost=total_cost,
            transform=_tx,
            form_names_ar=form_names_ar or {},
            description_ar=description_ar,
            is_illah=any_illah,
            rule_spec={"op": "compose", "rules": [r.key for r in rule_tuple]},
            sub_rules=rule_tuple,
        )

    def to_dict(self) -> dict[str, Any]:
        """Serialize rule metadata and declarative spec to a plain dictionary."""
        out: dict[str, Any] = {
            "key": self.key,
            "name_ar": self.name_ar,
            "name_en": self.name_en,
            "kind": self.kind,
            "cost": self.cost,
            "is_illah": self.is_illah,
        }
        if self.description_ar:
            out["description_ar"] = self.description_ar
        if self.form_names_ar:
            out["form_names_ar"] = dict(self.form_names_ar)
        if self.rule_spec:
            out["spec"] = dict(self.rule_spec)
        return out

    @classmethod
    def from_dict(
        cls,
        data: Mapping[str, Any],
        *,
        known_rules: Mapping[str, ProsodicRule] | None = None,
    ) -> ProsodicRule:
        """Deserialize a ``ProsodicRule`` from a JSON/TOML dictionary."""
        key = str(data.get("key", "")).strip()
        if not key:
            raise InvalidMeterSpecError("Rule dictionary is missing required field 'key'.")

        lookup = {**CLASSICAL_RULES, **(known_rules or {})}
        spec = data.get("spec")
        if spec is None and key in lookup:
            return lookup[key]
        if not isinstance(spec, Mapping):
            raise InvalidMeterSpecError(
                f"Custom rule '{key}' must provide a 'spec' object or match a built-in rule key."
            )

        op = spec.get("op")
        name_ar = str(data.get("name_ar", key))
        name_en = str(data.get("name_en", key))
        kind_raw = str(data.get("kind", "zihaf"))
        if kind_raw not in _VALID_RULE_KINDS:
            raise InvalidMeterSpecError(f"Invalid rule kind '{kind_raw}' for rule '{key}'.")
        kind: RuleKind = kind_raw  # type: ignore[assignment]
        cost = int(data.get("cost", 1))
        is_illah = bool(data.get("is_illah", kind == "illah"))
        desc = str(data.get("description_ar", ""))
        form_names = data.get("form_names_ar")
        fnames_map: Mapping[str, str] | None = (
            {str(k): str(v) for k, v in form_names.items()}
            if isinstance(form_names, Mapping)
            else None
        )

        if op == "delete_at":
            return cls.delete_at(
                key,
                int(spec["index"]),
                expected=str(spec["expected"]) if "expected" in spec and spec["expected"] is not None else None,
                name_ar=name_ar,
                name_en=name_en,
                kind=kind,
                cost=cost,
                is_illah=is_illah,
                description_ar=desc,
                form_names_ar=fnames_map,
            )
        if op == "quiesce_at":
            return cls.quiesce_at(
                key,
                int(spec["index"]),
                name_ar=name_ar,
                name_en=name_en,
                kind=kind,
                cost=cost,
                is_illah=is_illah,
                description_ar=desc,
                form_names_ar=fnames_map,
            )
        if op == "append_pattern":
            return cls.append_pattern(
                key,
                str(spec["suffix"]),
                require_suffix=str(spec["require_suffix"]) if spec.get("require_suffix") else None,
                name_ar=name_ar,
                name_en=name_en,
                kind=kind,
                cost=cost,
                is_illah=is_illah,
                description_ar=desc,
                form_names_ar=fnames_map,
            )
        if op == "strip_suffix":
            return cls.strip_suffix(
                key,
                str(spec["suffix"]),
                replace_with=str(spec.get("replace_with", "")),
                name_ar=name_ar,
                name_en=name_en,
                kind=kind,
                cost=cost,
                is_illah=is_illah,
                description_ar=desc,
                form_names_ar=fnames_map,
            )
        if op == "explicit":
            raw_map = spec.get("mapping")
            if not isinstance(raw_map, Mapping):
                raise InvalidMeterSpecError(f"Rule '{key}' with op='explicit' requires a 'mapping' dict.")
            return cls.explicit(
                key,
                {str(k): str(v) for k, v in raw_map.items()},
                name_ar=name_ar,
                name_en=name_en,
                kind=kind,
                cost=cost,
                is_illah=is_illah,
                description_ar=desc,
                form_names_ar=fnames_map,
            )
        if op == "compose":
            sub_keys = spec.get("rules")
            if not isinstance(sub_keys, Sequence) or isinstance(sub_keys, (str, bytes)):
                raise InvalidMeterSpecError(f"Rule '{key}' with op='compose' requires a 'rules' list.")
            resolved_subs: list[ProsodicRule] = []
            for sk in sub_keys:
                sk_str = str(sk)
                if sk_str not in lookup:
                    raise InvalidMeterSpecError(f"Unknown rule '{sk_str}' in compose rule '{key}'.")
                resolved_subs.append(lookup[sk_str])
            return cls.compose(
                key,
                *resolved_subs,
                name_ar=name_ar,
                name_en=name_en,
                kind=kind,
                cost=cost,
                is_illah=is_illah,
                description_ar=desc,
                form_names_ar=fnames_map,
            )

        raise InvalidMeterSpecError(f"Unsupported rule spec op '{op}' for rule '{key}'.")

append_pattern(key, suffix, *, require_suffix=None, name_ar='', name_en='', kind='illah', cost=0, is_illah=True, description_ar='', form_names_ar=None) classmethod

Create an addition rule that appends suffix (e.g. '10' or '0').

Source code in pyarud/meters/specs.py
@classmethod
def append_pattern(
    cls,
    key: str,
    suffix: str,
    *,
    require_suffix: str | None = None,
    name_ar: str = "",
    name_en: str = "",
    kind: RuleKind = "illah",
    cost: int = 0,
    is_illah: bool = True,
    description_ar: str = "",
    form_names_ar: Mapping[str, str] | None = None,
) -> ProsodicRule:
    """Create an addition rule that appends ``suffix`` (e.g. ``'10'`` or ``'0'``)."""
    if not suffix or not _RE_BINARY_PATTERN.match(suffix):
        raise InvalidMeterSpecError(f"append_pattern suffix must be binary [01]+, got {suffix!r}.")
    if require_suffix is not None and not _RE_BINARY_PATTERN.match(require_suffix):
        raise InvalidMeterSpecError(
            f"append_pattern require_suffix must be binary [01]+, got {require_suffix!r}."
        )

    def _tx(pat: str) -> str | None:
        if require_suffix is not None and not pat.endswith(require_suffix):
            return None
        return pat + suffix

    spec: dict[str, Any] = {"op": "append_pattern", "suffix": suffix}
    if require_suffix is not None:
        spec["require_suffix"] = require_suffix
    return cls(
        key=key,
        name_ar=name_ar or key,
        name_en=name_en or key,
        kind=kind,
        cost=cost,
        transform=_tx,
        form_names_ar=form_names_ar or {},
        description_ar=description_ar,
        is_illah=is_illah,
        rule_spec=spec,
    )

apply(pattern)

Apply this rule to a binary pattern string; returns None if inapplicable.

Source code in pyarud/meters/specs.py
def apply(self, pattern: str) -> str | None:
    """Apply this rule to a binary pattern string; returns ``None`` if inapplicable."""
    if not pattern or not _RE_BINARY_PATTERN.match(pattern):
        return None
    result = self.transform(pattern)
    if result is None or not result or not _RE_BINARY_PATTERN.match(result):
        return None
    return result

compose(key, *rules, name_ar='', name_en='', kind='compound', cost=None, is_illah=None, description_ar='', form_names_ar=None) classmethod

Compose multiple ProsodicRule transformations left-to-right.

Source code in pyarud/meters/specs.py
@classmethod
def compose(
    cls,
    key: str,
    *rules: ProsodicRule,
    name_ar: str = "",
    name_en: str = "",
    kind: RuleKind = "compound",
    cost: int | None = None,
    is_illah: bool | None = None,
    description_ar: str = "",
    form_names_ar: Mapping[str, str] | None = None,
) -> ProsodicRule:
    """Compose multiple ``ProsodicRule`` transformations left-to-right."""
    if not rules:
        raise InvalidMeterSpecError("ProsodicRule.compose requires at least one rule.")
    rule_tuple = tuple(rules)

    def _tx(pat: str) -> str | None:
        cur: str | None = pat
        for r in rule_tuple:
            if cur is None:
                return None
            cur = r.apply(cur)
        return cur

    total_cost = sum(r.cost for r in rule_tuple) if cost is None else cost
    any_illah = any(r.is_illah for r in rule_tuple) if is_illah is None else is_illah
    return cls(
        key=key,
        name_ar=name_ar or " + ".join(r.name_ar for r in rule_tuple),
        name_en=name_en or " + ".join(r.name_en for r in rule_tuple),
        kind=kind,
        cost=total_cost,
        transform=_tx,
        form_names_ar=form_names_ar or {},
        description_ar=description_ar,
        is_illah=any_illah,
        rule_spec={"op": "compose", "rules": [r.key for r in rule_tuple]},
        sub_rules=rule_tuple,
    )

delete_at(key, index, *, expected=None, name_ar='', name_en='', kind='zihaf', cost=1, is_illah=False, description_ar='', form_names_ar=None) classmethod

Create a rule that deletes the bit at index (optionally checking expected bit).

Source code in pyarud/meters/specs.py
@classmethod
def delete_at(
    cls,
    key: str,
    index: int,
    *,
    expected: str | None = None,
    name_ar: str = "",
    name_en: str = "",
    kind: RuleKind = "zihaf",
    cost: int = 1,
    is_illah: bool = False,
    description_ar: str = "",
    form_names_ar: Mapping[str, str] | None = None,
) -> ProsodicRule:
    """Create a rule that deletes the bit at ``index`` (optionally checking ``expected`` bit)."""
    if index < 0:
        raise InvalidMeterSpecError(f"delete_at index must be >= 0, got {index}.")
    if expected is not None and expected not in ("0", "1"):
        raise InvalidMeterSpecError(f"expected bit must be '0', '1', or None, got {expected!r}.")

    def _tx(pat: str) -> str | None:
        if index >= len(pat):
            return None
        if expected is not None and pat[index] != expected:
            return None
        res = pat[:index] + pat[index + 1 :]
        return res if res else None

    spec: dict[str, Any] = {"op": "delete_at", "index": index}
    if expected is not None:
        spec["expected"] = expected
    return cls(
        key=key,
        name_ar=name_ar or key,
        name_en=name_en or key,
        kind=kind,
        cost=cost,
        transform=_tx,
        form_names_ar=form_names_ar or {},
        description_ar=description_ar,
        is_illah=is_illah,
        rule_spec=spec,
    )

explicit(key, mapping, *, name_ar='', name_en='', kind='zihaf', cost=1, is_illah=False, description_ar='', form_names_ar=None) classmethod

Create a rule defined by an explicit input_pattern -> output_pattern map.

Source code in pyarud/meters/specs.py
@classmethod
def explicit(
    cls,
    key: str,
    mapping: Mapping[str, str],
    *,
    name_ar: str = "",
    name_en: str = "",
    kind: RuleKind = "zihaf",
    cost: int = 1,
    is_illah: bool = False,
    description_ar: str = "",
    form_names_ar: Mapping[str, str] | None = None,
) -> ProsodicRule:
    """Create a rule defined by an explicit ``input_pattern -> output_pattern`` map."""
    if not mapping:
        raise InvalidMeterSpecError("explicit mapping must not be empty.")
    clean_map: dict[str, str] = {}
    for src, dst in mapping.items():
        if not _RE_BINARY_PATTERN.match(src) or not _RE_BINARY_PATTERN.match(dst):
            raise InvalidMeterSpecError(
                f"explicit mapping entries must be binary [01]+, got {src!r} -> {dst!r}."
            )
        clean_map[src] = dst

    frozen_map = MappingProxyType(clean_map)

    def _tx(pat: str) -> str | None:
        return frozen_map.get(pat)

    return cls(
        key=key,
        name_ar=name_ar or key,
        name_en=name_en or key,
        kind=kind,
        cost=cost,
        transform=_tx,
        form_names_ar=form_names_ar or {},
        description_ar=description_ar,
        is_illah=is_illah,
        rule_spec={"op": "explicit", "mapping": dict(clean_map)},
    )

from_dict(data, *, known_rules=None) classmethod

Deserialize a ProsodicRule from a JSON/TOML dictionary.

Source code in pyarud/meters/specs.py
@classmethod
def from_dict(
    cls,
    data: Mapping[str, Any],
    *,
    known_rules: Mapping[str, ProsodicRule] | None = None,
) -> ProsodicRule:
    """Deserialize a ``ProsodicRule`` from a JSON/TOML dictionary."""
    key = str(data.get("key", "")).strip()
    if not key:
        raise InvalidMeterSpecError("Rule dictionary is missing required field 'key'.")

    lookup = {**CLASSICAL_RULES, **(known_rules or {})}
    spec = data.get("spec")
    if spec is None and key in lookup:
        return lookup[key]
    if not isinstance(spec, Mapping):
        raise InvalidMeterSpecError(
            f"Custom rule '{key}' must provide a 'spec' object or match a built-in rule key."
        )

    op = spec.get("op")
    name_ar = str(data.get("name_ar", key))
    name_en = str(data.get("name_en", key))
    kind_raw = str(data.get("kind", "zihaf"))
    if kind_raw not in _VALID_RULE_KINDS:
        raise InvalidMeterSpecError(f"Invalid rule kind '{kind_raw}' for rule '{key}'.")
    kind: RuleKind = kind_raw  # type: ignore[assignment]
    cost = int(data.get("cost", 1))
    is_illah = bool(data.get("is_illah", kind == "illah"))
    desc = str(data.get("description_ar", ""))
    form_names = data.get("form_names_ar")
    fnames_map: Mapping[str, str] | None = (
        {str(k): str(v) for k, v in form_names.items()}
        if isinstance(form_names, Mapping)
        else None
    )

    if op == "delete_at":
        return cls.delete_at(
            key,
            int(spec["index"]),
            expected=str(spec["expected"]) if "expected" in spec and spec["expected"] is not None else None,
            name_ar=name_ar,
            name_en=name_en,
            kind=kind,
            cost=cost,
            is_illah=is_illah,
            description_ar=desc,
            form_names_ar=fnames_map,
        )
    if op == "quiesce_at":
        return cls.quiesce_at(
            key,
            int(spec["index"]),
            name_ar=name_ar,
            name_en=name_en,
            kind=kind,
            cost=cost,
            is_illah=is_illah,
            description_ar=desc,
            form_names_ar=fnames_map,
        )
    if op == "append_pattern":
        return cls.append_pattern(
            key,
            str(spec["suffix"]),
            require_suffix=str(spec["require_suffix"]) if spec.get("require_suffix") else None,
            name_ar=name_ar,
            name_en=name_en,
            kind=kind,
            cost=cost,
            is_illah=is_illah,
            description_ar=desc,
            form_names_ar=fnames_map,
        )
    if op == "strip_suffix":
        return cls.strip_suffix(
            key,
            str(spec["suffix"]),
            replace_with=str(spec.get("replace_with", "")),
            name_ar=name_ar,
            name_en=name_en,
            kind=kind,
            cost=cost,
            is_illah=is_illah,
            description_ar=desc,
            form_names_ar=fnames_map,
        )
    if op == "explicit":
        raw_map = spec.get("mapping")
        if not isinstance(raw_map, Mapping):
            raise InvalidMeterSpecError(f"Rule '{key}' with op='explicit' requires a 'mapping' dict.")
        return cls.explicit(
            key,
            {str(k): str(v) for k, v in raw_map.items()},
            name_ar=name_ar,
            name_en=name_en,
            kind=kind,
            cost=cost,
            is_illah=is_illah,
            description_ar=desc,
            form_names_ar=fnames_map,
        )
    if op == "compose":
        sub_keys = spec.get("rules")
        if not isinstance(sub_keys, Sequence) or isinstance(sub_keys, (str, bytes)):
            raise InvalidMeterSpecError(f"Rule '{key}' with op='compose' requires a 'rules' list.")
        resolved_subs: list[ProsodicRule] = []
        for sk in sub_keys:
            sk_str = str(sk)
            if sk_str not in lookup:
                raise InvalidMeterSpecError(f"Unknown rule '{sk_str}' in compose rule '{key}'.")
            resolved_subs.append(lookup[sk_str])
        return cls.compose(
            key,
            *resolved_subs,
            name_ar=name_ar,
            name_en=name_en,
            kind=kind,
            cost=cost,
            is_illah=is_illah,
            description_ar=desc,
            form_names_ar=fnames_map,
        )

    raise InvalidMeterSpecError(f"Unsupported rule spec op '{op}' for rule '{key}'.")

quiesce_at(key, index, *, name_ar='', name_en='', kind='zihaf', cost=1, is_illah=False, description_ar='', form_names_ar=None) classmethod

Create a rule that turns a Mutaharrik ('1') at index into a Sakin ('0').

Source code in pyarud/meters/specs.py
@classmethod
def quiesce_at(
    cls,
    key: str,
    index: int,
    *,
    name_ar: str = "",
    name_en: str = "",
    kind: RuleKind = "zihaf",
    cost: int = 1,
    is_illah: bool = False,
    description_ar: str = "",
    form_names_ar: Mapping[str, str] | None = None,
) -> ProsodicRule:
    """Create a rule that turns a Mutaharrik (``'1'``) at ``index`` into a Sakin (``'0'``)."""
    if index < 0:
        raise InvalidMeterSpecError(f"quiesce_at index must be >= 0, got {index}.")

    def _tx(pat: str) -> str | None:
        if index >= len(pat) or pat[index] != "1":
            return None
        return pat[:index] + "0" + pat[index + 1 :]

    return cls(
        key=key,
        name_ar=name_ar or key,
        name_en=name_en or key,
        kind=kind,
        cost=cost,
        transform=_tx,
        form_names_ar=form_names_ar or {},
        description_ar=description_ar,
        is_illah=is_illah,
        rule_spec={"op": "quiesce_at", "index": index},
    )

strip_suffix(key, suffix, *, replace_with='', name_ar='', name_en='', kind='illah', cost=0, is_illah=True, description_ar='', form_names_ar=None) classmethod

Create a deletion/cadence rule stripping suffix and optionally appending replace_with.

Source code in pyarud/meters/specs.py
@classmethod
def strip_suffix(
    cls,
    key: str,
    suffix: str,
    *,
    replace_with: str = "",
    name_ar: str = "",
    name_en: str = "",
    kind: RuleKind = "illah",
    cost: int = 0,
    is_illah: bool = True,
    description_ar: str = "",
    form_names_ar: Mapping[str, str] | None = None,
) -> ProsodicRule:
    """Create a deletion/cadence rule stripping ``suffix`` and optionally appending ``replace_with``."""
    if not suffix or not _RE_BINARY_PATTERN.match(suffix):
        raise InvalidMeterSpecError(f"strip_suffix suffix must be binary [01]+, got {suffix!r}.")
    if replace_with and not _RE_BINARY_PATTERN.match(replace_with):
        raise InvalidMeterSpecError(
            f"strip_suffix replace_with must be binary [01]*, got {replace_with!r}."
        )

    def _tx(pat: str) -> str | None:
        if not pat.endswith(suffix):
            return None
        res = pat[: -len(suffix)] + replace_with
        return res if res else None

    return cls(
        key=key,
        name_ar=name_ar or key,
        name_en=name_en or key,
        kind=kind,
        cost=cost,
        transform=_tx,
        form_names_ar=form_names_ar or {},
        description_ar=description_ar,
        is_illah=is_illah,
        rule_spec={"op": "strip_suffix", "suffix": suffix, "replace_with": replace_with},
    )

to_dict()

Serialize rule metadata and declarative spec to a plain dictionary.

Source code in pyarud/meters/specs.py
def to_dict(self) -> dict[str, Any]:
    """Serialize rule metadata and declarative spec to a plain dictionary."""
    out: dict[str, Any] = {
        "key": self.key,
        "name_ar": self.name_ar,
        "name_en": self.name_en,
        "kind": self.kind,
        "cost": self.cost,
        "is_illah": self.is_illah,
    }
    if self.description_ar:
        out["description_ar"] = self.description_ar
    if self.form_names_ar:
        out["form_names_ar"] = dict(self.form_names_ar)
    if self.rule_spec:
        out["spec"] = dict(self.rule_spec)
    return out

Formatter Utilities

pyarud.formatters.console

Console, Compact, and Markdown formatting utilities for Arabic prosodic analysis.

format_verse_report(verse, *, lang='ar', style='pretty', color=None)

Format a single verse analysis into a readable prosodic report.

Source code in pyarud/formatters/console.py
def format_verse_report(
    verse: VerseAnalysis,
    *,
    lang: Lang = "ar",
    style: Style = "pretty",
    color: bool | None = None,
) -> str:
    """Format a single verse analysis into a readable prosodic report."""
    _validate_options(lang, style)
    use_color = _resolve_color(color, style)

    if style == "markdown":
        return _format_verse_markdown(verse, lang)
    if style == "compact":
        return _format_verse_compact(verse, lang, use_color)
    return _format_verse_pretty(verse, lang, use_color)

format_poem_report(poem, *, lang='ar', style='pretty', color=None)

Format a complete poem analysis into an executive prosodic report.

Source code in pyarud/formatters/console.py
def format_poem_report(
    poem: PoemAnalysis,
    *,
    lang: Lang = "ar",
    style: Style = "pretty",
    color: bool | None = None,
) -> str:
    """Format a complete poem analysis into an executive prosodic report."""
    _validate_options(lang, style)
    use_color = _resolve_color(color, style)
    btype = _label_bahr_type(str(poem.bahr_type), lang)
    avg_pct = _format_pct(poem.average_score)

    if style == "markdown":
        if lang == "ar":
            lines = [f"## تقرير التحليل العروضي الشامل: {poem.meter_name_ar}\n"]
            lines.append(f"- **البحر المكتشف:** {poem.meter_name_ar} ({poem.meter_name_en}) — {btype}")
            lines.append(f"- **عدد الأبيات:** {poem.total_verses} | **الأبيات السليمة:** {poem.valid_verses_count}")
            lines.append(f"- **متوسط التوافق العروضي:** {avg_pct}")
            homo = "تام ومتجانس" if poem.is_homogeneous else "متفاوت / متعدد البحور"
            lines.append(f"- **وحدة البحر:** {homo}")
            if poem.dominant_rawi:
                lines.append(f"- **حرف الروي السائد:** {poem.dominant_rawi}")
            if poem.has_tasri:
                lines.append("- **التصريع:** موجود في مطلع القصيدة")
        else:
            lines = [f"## Prosodic Analysis Report: {poem.meter_name_en}\n"]
            lines.append(f"- **Detected Meter:** {poem.meter_name_en} ({poem.meter_name_ar}) — {btype}")
            lines.append(f"- **Verses:** {poem.valid_verses_count}/{poem.total_verses} valid")
            lines.append(f"- **Average Confidence:** {avg_pct}")
            homo = "Homogeneous" if poem.is_homogeneous else "Mixed meters"
            lines.append(f"- **Meter Consistency:** {homo}")
            if poem.dominant_rawi:
                lines.append(f"- **Dominant Rawi:** {poem.dominant_rawi}")
            if poem.has_tasri:
                lines.append("- **Tasri':** Present in opening verse")

        if poem.rhyme_faults:
            heading = "عيوب القافية" if lang == "ar" else "Rhyme Faults"
            lines.append(f"\n### {heading}\n")
            if lang == "ar":
                lines.append("| العيب | الخطورة | الأبيات | الوصف |")
            else:
                lines.append("| Fault | Severity | Verses | Description |")
            lines.append("|---|---|---|---|")
            for f in poem.rhyme_faults:
                fname = f.name_ar if lang == "ar" else f.name_en
                fdesc = f.description_ar if lang == "ar" else f.description_en
                v_nums = ", ".join(str(i + 1) for i in f.verse_indices)
                lines.append(f"| {fname} | `{f.severity}` | {v_nums} | {fdesc} |")

        for v in poem.verses:
            lines.append("")
            lines.append(_format_verse_markdown(v, lang))

        return "\n".join(lines)

    if style == "compact":
        meter_name = poem.meter_name_ar if lang == "ar" else poem.meter_name_en
        rawi_part = f" | {'الروي' if lang == 'ar' else 'Rawi'}: {poem.dominant_rawi}" if poem.dominant_rawi else ""
        tasri_part = (" | [تصريع]" if lang == "ar" else " | [Tasri']") if poem.has_tasri else ""
        homo_part = (
            ("متجانس" if poem.is_homogeneous else "متعدد البحور")
            if lang == "ar"
            else ("homogeneous" if poem.is_homogeneous else "mixed")
        )
        lines = [
            f"{meter_name} ({btype}) | {poem.valid_verses_count}/{poem.total_verses} "
            f"| {avg_pct} | {homo_part}{rawi_part}{tasri_part}"
        ]
        if poem.rhyme_faults:
            fault_lbl = "عيوب القافية" if lang == "ar" else "Rhyme faults"
            fault_items = ", ".join(
                f"{f.name_ar if lang == 'ar' else f.name_en}({','.join(str(i + 1) for i in f.verse_indices)})"
                for f in poem.rhyme_faults
            )
            lines.append(f"  {_paint(f'{fault_lbl}:', _YELLOW, use_color)} {fault_items}")
        for v in poem.verses:
            lines.append(_format_verse_compact(v, lang, use_color))
        return "\n".join(lines)

    # Pretty style — RTL-safe horizontal banners (no fragile fixed-width box borders)
    rule = "═" * 64
    if lang == "ar":
        title = f"  تقرير التحليل العروضي الشامل — {poem.meter_name_ar} ({btype})"
        lines = [
            _paint(rule, _CYAN, use_color),
            _paint(title, _BOLD + _CYAN, use_color),
            _paint(rule, _CYAN, use_color),
            f"• البحر المكتشف: {poem.meter_name_ar} ({poem.meter_name_en}) — {btype}",
            f"• عدد الأبيات: {poem.total_verses} | الأبيات السليمة: {poem.valid_verses_count}",
            f"• متوسط التوافق العروضي: {avg_pct}",
            f"• وحدة البحر: {'تام ومتجانس' if poem.is_homogeneous else 'متفاوت / متعدد البحور'}",
        ]
        if poem.dominant_rawi:
            lines.append(f"• حرف الروي السائد: {poem.dominant_rawi}")
        if poem.has_tasri:
            lines.append("• التصريع: موجود في مطلع القصيدة")
    else:
        title = f"  Prosodic Analysis Report — {poem.meter_name_en} ({btype})"
        lines = [
            _paint(rule, _CYAN, use_color),
            _paint(title, _BOLD + _CYAN, use_color),
            _paint(rule, _CYAN, use_color),
            f"• Detected Meter: {poem.meter_name_en} ({poem.meter_name_ar}) — {btype}",
            f"• Total Verses: {poem.total_verses} | Valid Verses: {poem.valid_verses_count}",
            f"• Average Confidence: {avg_pct}",
            f"• Consistency: {'Homogeneous' if poem.is_homogeneous else 'Mixed meters'}",
        ]
        if poem.dominant_rawi:
            lines.append(f"• Dominant Rawi: {poem.dominant_rawi}")
        if poem.has_tasri:
            lines.append("• Tasri': Present in opening verse")

    if poem.rhyme_faults:
        lines.extend(_format_rhyme_faults_pretty(poem.rhyme_faults, lang, use_color))

    lines.append("\n" + "─" * 64 + "\n")

    for v in poem.verses:
        lines.append(_format_verse_pretty(v, lang, use_color))
        lines.append("")

    return "\n".join(lines)

Phonetics & Arudi Alignment Engine

pyarud.core.phonetics.ArudiConverter

Phonetic Converter for Arabic Prosody (Ilm al-Arud).

Converts standard diacritized Arabic poetry into phonetic Arudi writing (الكتابة العروضية) and extracts binary patterns (1 = Mutaharrik, 0 = Sakin) with a strict 1:1 bijection between non-space Arudi letters and pattern bits.

Source code in pyarud/core/phonetics.py
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
class ArudiConverter:
    """
    Phonetic Converter for Arabic Prosody (*Ilm al-Arud*).

    Converts standard diacritized Arabic poetry into phonetic Arudi writing
    (الكتابة العروضية) and extracts binary patterns (1 = Mutaharrik, 0 = Sakin)
    with a strict 1:1 bijection between non-space Arudi letters and pattern bits.
    """

    def __init__(self, custom_replacements: dict[str, str] | None = None) -> None:
        self.replacements: dict[str, str] = dict(DEFAULT_ARUDI_REPLACEMENTS)
        self._custom_replacements: dict[str, str] = {}
        if custom_replacements:
            self.replacements.update(custom_replacements)
            self._custom_replacements.update(custom_replacements)

    def register_custom_spelling(self, word: str, replacement: str) -> None:
        """Register a custom phonetic spelling for a specific unvocalized word."""
        clean_key = strip_tashkeel(strip_tatweel(word))
        self.replacements[clean_key] = replacement
        self._custom_replacements[clean_key] = replacement

    def _normalize_input(self, text: str) -> str:
        """Apply canonical entry normalization in strict phonetic order."""
        text = strip_tatweel(text)
        text = normalize_ligatures(text)
        text = strip_punctuation(text, replace_with_space=True)
        text = normalize_orthography(text)
        return normalize_spaces(text)

    def _expand_irregular_word(self, word: str, *, is_last_word: bool, shorten_ana: bool = True) -> str:
        """
        Expand non-phonetic classical Arabic words while strictly preserving
        inflectional harakat, tanween, shadda, and valid clitic prefixes.
        """
        # Exclude silent orthographic ا / ى carrier after Fathatan when matching stem skeleton
        # (so إِلَهًا / رَحْمَنًا / دَاوُدًا / طَاوُسًا / إِسْحَقًا still match their irregular stems)
        plain_source = (
            word[:-1]
            if word.endswith((FATHATAN + ALEF, FATHATAN + ALEF_MAKSURA))
            else word
        )
        plain = strip_tashkeel(plain_source)
        if not plain:
            return word

        # 0. User-registered custom overrides take highest priority
        if self._custom_replacements:
            cleaned_with_shadda = _RE_REMOVE_NON_SHADDA_DIACRITICS.sub("", word)
            for cand in (cleaned_with_shadda, plain):
                if cand in self._custom_replacements:
                    return self._custom_replacements[cand]
            for cand in (cleaned_with_shadda, plain):
                for key, rep in self._custom_replacements.items():
                    if cand.endswith(key) and len(cand) > len(key):
                        pref = cand[: -len(key)]
                        if pref in VALID_PREFIXES:
                            surf_pref, _ = _split_prefix_surface(word, len(pref))
                            if surf_pref == pref:
                                surf_pref = "".join(PREFIX_HARAKAT.get(p, p) for p in pref)
                            return surf_pref + rep

        # 1. Pronoun أَنَا (classical prosody drops final alif in connected speech; keeps in pause)
        if shorten_ana and not is_last_word:
            m_ana = _match_prefix_and_stem(plain, frozenset({"أنا"}), _CONJ_PREFIXES)
            if m_ana is not None:
                pref, _ = m_ana
                surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
                # Ensure ن is not shadda'd (protect أنّا)
                if SHADDA not in _letter_diacritics_at(surf_stem, 1):
                    return surf_pref + _delete_letter_index(surf_stem, 2)

        # 2. Relative pronouns الذي / التي / الذين — ensure shadda on ل so solar-lam won't eat ل
        m_rel = _match_prefix_and_stem(plain, _RELATIVE_AL_STEMS, _ALL_CLITIC_PREFIXES)
        if m_rel is not None:
            pref, _ = m_rel
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            lam_diacs = _letter_diacritics_at(surf_stem, 1)
            if SHADDA not in lam_diacs:
                surf_stem = _insert_after_letter_index(surf_stem, 1, SHADDA)
            return surf_pref + surf_stem

        # 3. الله / اللهم / لله (MUST run BEFORE solar-lam & initial-alef rewrites!)
        m_allah = _match_prefix_and_stem(plain, frozenset({"الله"}), _ALLAH_PREFIXES)
        if m_allah is not None:
            pref, _ = m_allah
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            if surf_pref and surf_pref == pref:
                surf_pref = "".join(PREFIX_HARAKAT.get(p, p) for p in pref)
            end_diacs = _extract_trailing_diacritics(surf_stem)
            # Single lam + shadda (الَّاه): yields exact 2 lams (لْ + لَ) both at start and in wasl
            return surf_pref + f"{ALEF}{LAM}{SHADDA}{FATHA}{ALEF}{HEH}" + end_diacs

        m_lillah = _match_prefix_and_stem(plain, frozenset({"لله"}), _LILLAH_PREFIXES)
        if m_lillah is not None:
            pref, _ = m_lillah
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            if surf_pref and surf_pref == pref:
                surf_pref = "".join(PREFIX_HARAKAT.get(p, p) for p in pref)
            end_diacs = _extract_trailing_diacritics(surf_stem)
            return surf_pref + f"{LAM}{KASRA}{LAM}{SHADDA}{FATHA}{ALEF}{HEH}" + end_diacs

        m_allahumma = _match_prefix_and_stem(plain, frozenset({"اللهم"}), _CONJ_PREFIXES)
        if m_allahumma is not None:
            pref, _ = m_allahumma
            surf_pref, _ = _split_prefix_surface(word, len(pref))
            if surf_pref and surf_pref == pref:
                surf_pref = "".join(PREFIX_HARAKAT.get(p, p) for p in pref)
            return surf_pref + f"{ALEF}{LAM}{SHADDA}{FATHA}{ALEF}{HEH}{DAMMA}{MEEM}{SHADDA}{FATHA}"

        # 4. الرحمن / رحمن
        m_rah = _match_prefix_and_stem(plain, frozenset({"الرحمن", "رحمن"}), _ALL_CLITIC_PREFIXES)
        if m_rah is not None:
            pref, stem_p = m_rah
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            meem_idx = 4 if stem_p == "الرحمن" else 2
            return surf_pref + _insert_after_letter_index(surf_stem, meem_idx, ALEF, ensure_fatha=True)

        # 5. إله family
        m_ilah = _match_prefix_and_stem(plain, _ILAH_STEMS, _ALL_CLITIC_PREFIXES)
        if m_ilah is not None:
            pref, stem_p = m_ilah
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            lam_idx = 3 if stem_p.startswith("الإ") else 1
            return surf_pref + _insert_after_letter_index(surf_stem, lam_idx, ALEF, ensure_fatha=True)

        # 6. هذا / هذي / هذه / هذان / هذين / هؤلاء / هكذا / ههنا
        m_hatha = _match_prefix_and_stem(plain, _HATHA_STEMS, _ALL_CLITIC_PREFIXES)
        if m_hatha is not None:
            pref, _ = m_hatha
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            return surf_pref + _insert_after_letter_index(surf_stem, 0, ALEF, ensure_fatha=True)

        # 7. ذلك / ذلكما / ذلكم / ذلكن
        m_thalika = _match_prefix_and_stem(plain, _THALIKA_STEMS, _ALL_CLITIC_PREFIXES)
        if m_thalika is not None:
            pref, _ = m_thalika
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            return surf_pref + _insert_after_letter_index(surf_stem, 0, ALEF, ensure_fatha=True)

        # 8. أولئك / أولئكم
        m_ulaika = _match_prefix_and_stem(plain, _ULAIKA_STEMS, _ALL_CLITIC_PREFIXES)
        if m_ulaika is not None:
            pref, _ = m_ulaika
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            # Drop silent و (idx 1), then insert ا after ل (now idx 1)
            trimmed = _delete_letter_index(surf_stem, 1)
            return surf_pref + _insert_after_letter_index(trimmed, 1, ALEF, ensure_fatha=True)

        # 9. أولو / أولي / أولات / أولاء (guard against أَوَّلِي where و has shadda/fatha!)
        m_ulu = _match_prefix_and_stem(plain, _ULU_STEMS, _ALL_CLITIC_PREFIXES)
        if m_ulu is not None:
            pref, _ = m_ulu
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            waw_diacs = _letter_diacritics_at(surf_stem, 1)
            if SHADDA not in waw_diacs and FATHA not in waw_diacs:
                return surf_pref + _delete_letter_index(surf_stem, 1)

        # 10. لكن / لكنّ / لكني / لكنني / لكنه / ... (ONLY و/ف prefixes; guard against لَكُنَّ!)
        m_lakin = _match_prefix_and_stem(plain, _LAKIN_STEMS, _CONJ_PREFIXES)
        if m_lakin is not None:
            pref, _ = m_lakin
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            kaf_diacs = _letter_diacritics_at(surf_stem, 1)
            if DAMMA not in kaf_diacs:
                return surf_pref + _insert_after_letter_index(surf_stem, 0, ALEF, ensure_fatha=True)

        # 11. داود / طاوس / ناوس
        m_dawud = _match_prefix_and_stem(plain, _DAWUD_STEMS, _ALL_CLITIC_PREFIXES)
        if m_dawud is not None:
            pref, stem_p = m_dawud
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            waw_idx = 4 if stem_p.startswith("ال") else 2
            return surf_pref + _insert_after_letter_index(surf_stem, waw_idx, WAW)

        # 12. مائة / مائتان / مائتين / مائات
        m_miah = _match_prefix_and_stem(plain, _MIAH_STEMS, _ALL_CLITIC_PREFIXES)
        if m_miah is not None:
            pref, stem_p = m_miah
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            alef_idx = 3 if stem_p.startswith("ال") else 1
            return surf_pref + _delete_letter_index(surf_stem, alef_idx)

        # 13. عمرو (drop silent trailing و while keeping harakat/tanween on ر)
        m_amr = _match_prefix_and_stem(plain, frozenset({"عمرو"}), _ALL_CLITIC_PREFIXES)
        if m_amr is not None:
            pref, _ = m_amr
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            return surf_pref + _expand_amr_stem(surf_stem)

        # 14. Archaic السموات / سموات / إسحق
        m_sam = _match_prefix_and_stem(plain, frozenset({"سموات", "السموات"}), _ALL_CLITIC_PREFIXES)
        if m_sam is not None:
            pref, stem_p = m_sam
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            meem_idx = 3 if stem_p.startswith("ال") else 1
            return surf_pref + _insert_after_letter_index(surf_stem, meem_idx, ALEF, ensure_fatha=True)

        m_ish = _match_prefix_and_stem(plain, frozenset({"إسحق"}), _ALL_CLITIC_PREFIXES)
        if m_ish is not None:
            pref, _ = m_ish
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            return surf_pref + _insert_after_letter_index(surf_stem, 2, ALEF, ensure_fatha=True)

        # 15. يس (STRICTLY standalone — prevents لَيْسَ / وَلَيْسَ / فَلَيْسَ / كِيسٌ collisions!)
        if plain == "يس":
            return "يَاسِينْ"

        # 16. طه (standalone or limited clitic prefixes, unshadda'd)
        m_taha = _match_prefix_and_stem(plain, frozenset({"طه"}), _TAHA_PREFIXES)
        if m_taha is not None:
            pref, _ = m_taha
            surf_pref, surf_stem = _split_prefix_surface(word, len(pref))
            if SHADDA not in surf_stem:
                if surf_pref and surf_pref == pref:
                    surf_pref = "".join(PREFIX_HARAKAT.get(p, p) for p in pref)
                return surf_pref + "طَاهَا"

        return word

    def _preprocess(self, normalized: str, *, shorten_ana: bool = True) -> tuple[str, tuple[str, ...]]:
        """
        Execute the ordered phonetic preprocessing pipeline on normalized text.

        Returns ``(preprocessed_text, normalized_words)``.
        """
        words = normalized.split(" ")
        norm_words_tuple = tuple(w for w in words if w)
        if not norm_words_tuple:
            return "", ()

        # Stage 1: Inflection-preserving lexical irregulars (BEFORE ال / solar / wasl / madda!)
        last_idx = len(norm_words_tuple) - 1
        expanded_words = [
            self._expand_irregular_word(w, is_last_word=(idx == last_idx), shorten_ana=shorten_ana)
            for idx, w in enumerate(norm_words_tuple)
        ]
        bait = " ".join(expanded_words)

        # Stage 2.1: Silent Alif of plural Waw (ألف التفريق)
        bait = _RE_WAW_SUKUN_ALEF.sub(WAW + SUKUN, bait)
        bait = _RE_PLURAL_WAW_ALEF.sub(WAW, bait)

        # Stage 2.2: Detach prefixes before الـ using intra-word marker so source word indices stay exact
        bait = _RE_DETACH_AL.sub(rf"\1\2{_INTRA_WORD_SEP}\3", bait)

        # Stage 2.3A: Iltiqa' al-Sakinayn BEFORE solar-lam deletion, across ALL Wasl words!
        # Strip explicit sukun on madd يْ / وْ before Wasl so they drop cleanly in Stage 2.3C
        bait = _RE_MADD_SUKUN_BEFORE_WASL.sub(r"\1", bait)
        bait = _RE_MIN_BEFORE_WASL.sub(rf"\1\2{FATHA}\3", bait)
        bait = _RE_PLURAL_MEEM_BEFORE_WASL.sub(rf"\1{DAMMA}\2", bait)
        bait = _RE_PLURAL_DIPHTHONG_WAW_BEFORE_WASL.sub(rf"\1{DAMMA}\2", bait)
        bait = _RE_SUKUN_BEFORE_WASL.sub(rf"{KASRA}\1", bait)
        bait = _RE_TANWEEN_BEFORE_WASL.sub(
            lambda m: TANWEEN_TO_HARAKA[m.group(1)] + NOON + KASRA + m.group(2),
            bait,
        )

        # Stage 2.3B: Solar Lam assimilation at start, mid-hemistich, and لِلـ
        bait = _RE_SOLAR_START.sub(rf"{ALEF_HAMZA_ABOVE}{FATHA}\1{SHADDA}", bait)
        bait = _RE_SOLAR_MID.sub(rf"\1{ALEF}\2{SHADDA}", bait)
        bait = _RE_SOLAR_LIL.sub(rf"\1\2\3{SHADDA}", bait)

        # Stage 2.3C: Long vowel before Wasl (preserving/restoring implied short vowel) + Space-Wasl
        # Preserve cross-word Wasl boundaries as _WASL_WORD_SEP so source word alignment stays exact!
        def _keep_wasl_sep(sep: str) -> str:
            return "" if sep == _INTRA_WORD_SEP else _WASL_WORD_SEP

        bait = _RE_LONG_ALEF_WASL.sub(
            lambda m: m.group(1) + (m.group(2) or FATHA) + _keep_wasl_sep(m.group(3)),
            bait,
        )
        bait = _RE_LONG_YEH_WASL.sub(
            lambda m: m.group(1) + (m.group(2) or KASRA) + _keep_wasl_sep(m.group(3)),
            bait,
        )
        bait = _RE_LONG_WAW_WASL.sub(
            lambda m: m.group(1) + (m.group(2) or DAMMA) + _keep_wasl_sep(m.group(3)),
            bait,
        )
        bait = _RE_INTRA_WASL.sub("", bait)
        bait = _RE_SPACE_WASL.sub(_WASL_WORD_SEP, bait)
        bait = bait.replace(_INTRA_WORD_SEP, "")

        # Connected non-ال Hamzat Wasl (وَاسْتَمَعَ, فَاصْبَحِينَا, بِاسْمِ, وَاتَّقَى, وَاسلَمي)
        bait = _RE_CONNECTED_WASL_SUKUN.sub(r"\1\2\3", bait)
        bait = _RE_CONNECTED_WASL_KASRA.sub(r"\1\2\3", bait)
        bait = _RE_CONNECTED_WASL_FORM8.sub(r"\1\2\3", bait)
        bait = _RE_CONNECTED_WASL_UNMARKED.sub(r"\1\2\3", bait)

        # Initial bare Alif (Hamzat Wasl pronounced at start of hemistich)
        if bait and bait[0] == ALEF:
            bait = ALEF_HAMZA_ABOVE + FATHA + bait[1:]

        # Stage 2.4: Expand Madda (آ -> أَا) AFTER ligatures & lexical expansion
        if ALEF_MADDA in bait:
            bait = bait.replace(ALEF_MADDA, ALEF_HAMZA_ABOVE + FATHA + ALEF)

        bait = _RE_DOUBLE_HARAKA.sub(r"\1", bait)
        return bait, norm_words_tuple

    def _parse_units(self, preprocessed: str, num_source_words: int) -> list[_PhoneticUnit]:
        """
        Parse preprocessed text into structured ``_PhoneticUnit`` tokens while
        cleanly discarding silent orthographic carriers (``ا``/``ى`` after Fathatan)
        without ever swallowing word-boundary spaces, and preserving exact source
        ``word_idx`` across Wasl-merged words (``_WASL_WORD_SEP``).
        """
        raw_groups = preprocessed.split(" ")
        units: list[_PhoneticUnit] = []
        max_w_idx = max(0, num_source_words - 1)
        src_w_idx = 0

        for raw_group in raw_groups:
            if not raw_group:
                continue

            sub_words = raw_group.split(_WASL_WORD_SEP)
            # Parse letters across the Wasl-merged phonological word while tracking exact src_w_idx
            parsed_in_group: list[tuple[str, str, str, bool, bool, int, str]] = []

            for sub_i, sub_word in enumerate(sub_words):
                if sub_i > 0:
                    src_w_idx += 1
                w_idx = min(src_w_idx, max_w_idx)
                word_plain = strip_tashkeel(sub_word)

                i = 0
                n = len(sub_word)
                while i < n:
                    ch = sub_word[i]
                    if ch not in LETTERS_SET:
                        i += 1
                        continue

                    haraka = ""
                    tanween = ""
                    has_shadda = False
                    is_sukun = False
                    j = i + 1
                    while j < n and sub_word[j] not in LETTERS_SET:
                        d = sub_word[j]
                        if d == SHADDA:
                            has_shadda = True
                        elif d in HARAKAT_SET:
                            haraka = d
                        elif d in TANWEEN_SET:
                            tanween = d
                        elif d == SUKUN:
                            is_sukun = True
                        j += 1

                    # Skip silent orthographic ا or ى immediately following Fathatan (كِتَابًا / هُدًى)
                    if (
                        ch in (ALEF, ALEF_MAKSURA)
                        and not haraka
                        and not tanween
                        and not has_shadda
                        and parsed_in_group
                        and parsed_in_group[-1][2] == FATHATAN
                    ):
                        i = j
                        continue

                    parsed_in_group.append((ch, haraka, tanween, has_shadda, is_sukun, w_idx, word_plain))
                    i = j

            src_w_idx += 1

            g_len = len(parsed_in_group)
            for k, (ch, haraka, tanween, has_shadda, is_sukun, w_idx, w_plain) in enumerate(parsed_in_group):
                units.append(
                    _PhoneticUnit(
                        letter=ch,
                        haraka=haraka,
                        tanween=tanween,
                        has_shadda=has_shadda,
                        is_sukun=is_sukun,
                        word_idx=w_idx,
                        is_word_start=(k == 0),
                        is_word_end=(k == g_len - 1),
                        word_plain=w_plain,
                    )
                )

        return units

    def _compile_units(
        self,
        original_text: str,
        units: list[_PhoneticUnit],
        normalized_words: tuple[str, ...],
        *,
        saturate: bool = True,
        muqayyad: bool = False,
        ha_damir_mode: str = "standard",
    ) -> ArudiAlignment:
        """
        Compile ``_PhoneticUnit``s into ``ArudiAlignment`` with a strict,
        unbreakable 1:1 bijection between non-space Arudi letters and pattern bits.

        ``ha_damir_mode``:
            - ``"standard"``: saturate pronominal ``ه`` (and ``هذه``) between two mutaharriks.
            - ``"no_ishba"``: poetic *ikhtilas/qasr* (do not saturate mid-line ``هاء الضمير``).
            - ``"after_sakin"``: poetic *ishba' ba'da sakin* (also saturate ``فِيهِ``/``عَلَيْهِ``/``مِنْهُ``).
        """
        if not units:
            return ArudiAlignment(
                original_text=original_text,
                arudi_text="",
                pattern="",
                arudi_positions=(),
                word_indices=(),
                normalized_words=normalized_words,
            )

        arudi_chars: list[str] = []
        bits: list[str] = []
        arudi_positions: list[int] = []
        word_indices: list[int] = []

        def _emit(ch: str, bit: str, w_idx: int) -> None:
            arudi_positions.append(len(arudi_chars))
            arudi_chars.append(ch)
            bits.append(bit)
            word_indices.append(w_idx)

        total = len(units)
        for idx, u in enumerate(units):
            if idx > 0 and u.is_word_start:
                arudi_chars.append(" ")

            is_last = idx == total - 1
            prev_bit = bits[-1] if bits else ""
            next_u = units[idx + 1] if idx + 1 < total else None
            next_next_u = units[idx + 2] if idx + 2 < total else None

            # Phonetic rendering of Ta Marbuta (ة -> ت when vocalized/connected, ه when paused quiescent)
            if u.letter == TEH_MARBUTA:
                if is_last and (muqayyad or u.is_sukun or (not u.haraka and not u.tanween)):
                    out_ch = HEH
                else:
                    out_ch = TEH
            else:
                out_ch = u.letter

            # Case 1: Bare Alif / Alif Maksura (always long vowel sakin "0")
            if u.letter in (ALEF, ALEF_MAKSURA):
                if prev_bit != "0":
                    _emit(out_ch, "0", u.word_idx)
                continue

            # Case 2: Geminated consonant (Shadda = sakin + mutaharrik)
            if u.has_shadda:
                if prev_bit != "0":
                    _emit(out_ch, "0", u.word_idx)
                elif is_last and muqayyad:
                    # End-of-verse pause on doubled letter after sakin (مقيد)
                    _emit(out_ch, "0", u.word_idx)
                second_bit = "0" if (is_last and muqayyad and not u.tanween) else "1"
                _emit(out_ch, second_bit, u.word_idx)
                if u.tanween:
                    if is_last and muqayyad:
                        bits[-1] = "0"
                    else:
                        _emit(NOON, "0", u.word_idx)
                continue

            # Case 3: Tanween (mutaharrik + sakin Noon)
            if u.tanween:
                if is_last and muqayyad:
                    _emit(out_ch, "0", u.word_idx)
                else:
                    _emit(out_ch, "1", u.word_idx)
                    _emit(NOON, "0", u.word_idx)
                continue

            # Case 4: Explicit short vowel (Haraka)
            if u.haraka:
                bit = "0" if (is_last and muqayyad) else "1"
                _emit(out_ch, bit, u.word_idx)

                # Mid-hemistich Ha' al-Damir (هاء الضمير / هذه) saturation — decoupled from `muqayyad`!
                if (
                    u.letter == HEH
                    and u.is_word_end
                    and not is_last
                    and u.haraka in (KASRA, DAMMA)
                    and u.word_plain not in _ROOT_HEH_PLAIN_STEMS
                ):
                    preceded_by_mutaharrik = len(bits) >= 2 and bits[-2] == "1"
                    preceded_by_sakin = len(bits) >= 2 and bits[-2] == "0"
                    should_saturate = (
                        (ha_damir_mode == "standard" and preceded_by_mutaharrik)
                        or (ha_damir_mode == "after_sakin" and (preceded_by_mutaharrik or preceded_by_sakin))
                    )
                    if should_saturate:
                        sat_ch = YEH if u.haraka == KASRA else WAW
                        _emit(sat_ch, "0", u.word_idx)
                continue

            # Case 5: Explicit Sukun
            if u.is_sukun:
                if prev_bit != "0" or is_last:
                    _emit(out_ch, "0", u.word_idx)
                continue

            # Case 6: Unmarked consonant (no haraka, no sukun, no shadda, no tanween)
            next_is_unmarked_madd_glide = (
                next_u is not None
                and not u.is_word_end
                and u.letter not in (WAW, YEH)
                and next_u.letter in (WAW, YEH)
                and not next_u.haraka
                and not next_u.tanween
                and not next_u.has_shadda
                and not next_u.is_sukun
                and (
                    next_u.is_word_end
                    or next_next_u is None
                    or next_next_u.letter not in (ALEF, ALEF_MAKSURA)
                )
            )
            if (next_u is not None and not u.is_word_end and next_u.letter in (ALEF, ALEF_MAKSURA)) or (
                next_is_unmarked_madd_glide
            ):
                # Unmarked consonant (including و/ي in أَيا / وَيا / شَرواهُما / الدُّنيا) before
                # long ا/ى, or non-glide consonant before unmarked madd و/ي, is necessarily mutaharrik
                _emit(out_ch, "1", u.word_idx)
                continue

            if u.letter in (WAW, YEH):
                # Long vowel / glide when preceded by mutaharrik (e.g. كَرِيم, نُور, فِي, قَلْبِي)
                if prev_bit == "1" and not u.is_word_start:
                    _emit(out_ch, "0", u.word_idx)
                elif prev_bit == "1" and is_last:
                    _emit(out_ch, "0", u.word_idx)
                else:
                    _emit(out_ch, "1", u.word_idx)
                continue

            if is_last:
                if muqayyad or prev_bit != "0":
                    _emit(out_ch, "0", u.word_idx)
                else:
                    _emit(out_ch, "1", u.word_idx)
                continue

            # Semi-diacritized mid-word consonant: NEVER emit consecutive mid-word 00!
            if prev_bit == "" or prev_bit == "0":
                _emit(out_ch, "1", u.word_idx)
            elif (
                next_u is not None
                and not u.is_word_end
                and (next_u.is_sukun or next_u.has_shadda or next_u.letter in (ALEF, ALEF_MAKSURA))
            ):
                _emit(out_ch, "1", u.word_idx)
            else:
                _emit(out_ch, "0", u.word_idx)

        # Stage 4: End-of-hemistich saturation (الإشباع في العروض والضرب)
        last_u = units[-1]
        if not muqayyad and saturate and bits:
            if last_u.tanween and bits[-1] == "0" and arudi_chars[arudi_positions[-1]] == NOON:
                # Replace pausal tanween Noon with matching saturation vowel (ٌ->و, ٍ->ي, ً->ا)
                sat_ch = HARAKA_TO_LONG_VOWEL[last_u.tanween]
                arudi_chars[arudi_positions[-1]] = sat_ch
            elif bits[-1] == "1":
                if last_u.haraka in HARAKA_TO_LONG_VOWEL:
                    sat_ch = HARAKA_TO_LONG_VOWEL[last_u.haraka]
                elif last_u.letter == WAW:
                    sat_ch = WAW
                elif last_u.letter == YEH:
                    sat_ch = YEH
                else:
                    sat_ch = ALEF
                _emit(sat_ch, "0", last_u.word_idx)

        effective_is_muqayyad = muqayyad or (
            last_u.is_sukun
            and not last_u.haraka
            and not last_u.tanween
            and last_u.letter not in (ALEF, ALEF_MAKSURA, WAW, YEH, HEH, TEH_MARBUTA)
        )

        return ArudiAlignment(
            original_text=original_text,
            arudi_text="".join(arudi_chars),
            pattern="".join(bits),
            arudi_positions=tuple(arudi_positions),
            word_indices=tuple(word_indices),
            normalized_words=normalized_words,
            is_muqayyad=effective_is_muqayyad,
        )

    def align_pattern(
        self,
        text: str,
        *,
        saturate: bool = True,
        muqayyad: bool = False,
    ) -> ArudiAlignment:
        """
        Convert Arabic poetic text into ``ArudiAlignment`` containing the Arudi
        phonetic text, binary metric pattern, and exact 1:1 bit-to-character mapping.
        """
        if not text or not text.strip():
            return ArudiAlignment(
                original_text=text,
                arudi_text="",
                pattern="",
                arudi_positions=(),
                word_indices=(),
                normalized_words=(),
            )

        normalized = self._normalize_input(text)
        if not normalized:
            return ArudiAlignment(
                original_text=text,
                arudi_text="",
                pattern="",
                arudi_positions=(),
                word_indices=(),
                normalized_words=(),
            )

        preprocessed, norm_words = self._preprocess(normalized, shorten_ana=True)
        units = self._parse_units(preprocessed, len(norm_words))
        return self._compile_units(
            text,
            units,
            norm_words,
            saturate=saturate,
            muqayyad=muqayyad,
        )

    def align_hemistich_variants(
        self,
        text: str,
        *,
        muqayyad: bool = False,
        include_licenses: bool = False,
    ) -> list[ArudiAlignment]:
        """
        Compile a hemistich ONCE and produce deduplicated ``ArudiAlignment`` candidates.

        Args:
            text: Input Arabic hemistich.
            muqayyad: If True, includes the quiescent-rhyme (مقيد) candidate alongside
                the saturated (مطلق) candidate (used for Ajuz). If False, includes the
                unsaturated candidate alongside the saturated candidate (used for Sadr).
            include_licenses: If True, also yields classical poetic-license variants
                (``أَنَا`` lengthened, mid-line ``هاء الضمير`` *ikhtilas* / *ishba' ba'da sakin*)
                only when the relevant constructs actually appear in ``text``.
        """
        if not text or not text.strip():
            return [
                ArudiAlignment(
                    original_text=text,
                    arudi_text="",
                    pattern="",
                    arudi_positions=(),
                    word_indices=(),
                    normalized_words=(),
                )
            ]

        normalized = self._normalize_input(text)
        if not normalized:
            return [
                ArudiAlignment(
                    original_text=text,
                    arudi_text="",
                    pattern="",
                    arudi_positions=(),
                    word_indices=(),
                    normalized_words=(),
                )
            ]

        preprocessed, norm_words = self._preprocess(normalized, shorten_ana=True)
        units = self._parse_units(preprocessed, len(norm_words))

        variants: list[ArudiAlignment] = []
        seen_patterns: set[str] = set()

        def _add(aln: ArudiAlignment) -> None:
            if aln.pattern not in seen_patterns:
                seen_patterns.add(aln.pattern)
                variants.append(aln)

        # Primary candidate: saturated (Mutlaqah / saturated Arudh)
        _add(self._compile_units(text, units, norm_words, saturate=True, muqayyad=False))

        # Secondary candidate: quiescent rhyme (Ajuz) or unsaturated ending (Sadr)
        if muqayyad:
            _add(self._compile_units(text, units, norm_words, saturate=False, muqayyad=True))
        else:
            _add(self._compile_units(text, units, norm_words, saturate=False, muqayyad=False))

        # Optional classical poetic license variants (triggered only when applicable)
        if include_licenses and units:
            has_mid_ha = any(
                u.letter == HEH
                and u.is_word_end
                and idx < len(units) - 1
                and u.haraka in (KASRA, DAMMA)
                and u.word_plain not in _ROOT_HEH_PLAIN_STEMS
                for idx, u in enumerate(units)
            )
            if has_mid_ha:
                _add(
                    self._compile_units(
                        text, units, norm_words, saturate=True, muqayyad=False, ha_damir_mode="no_ishba"
                    )
                )
                _add(
                    self._compile_units(
                        text, units, norm_words, saturate=True, muqayyad=False, ha_damir_mode="after_sakin"
                    )
                )
                if muqayyad:
                    _add(
                        self._compile_units(
                            text, units, norm_words, saturate=False, muqayyad=True, ha_damir_mode="no_ishba"
                        )
                    )

            has_mid_ana = any(
                strip_tashkeel(w) in ("أنا", "وأنا", "فأنا") for w in norm_words[:-1]
            )
            if has_mid_ana:
                pre_long, _ = self._preprocess(normalized, shorten_ana=False)
                units_long = self._parse_units(pre_long, len(norm_words))
                _add(self._compile_units(text, units_long, norm_words, saturate=True, muqayyad=False))
                if muqayyad:
                    _add(self._compile_units(text, units_long, norm_words, saturate=False, muqayyad=True))

        return variants

    def prepare_hemistich_variants(
        self,
        text: str,
        *,
        muqayyad: bool = False,
        include_licenses: bool = False,
    ) -> list[tuple[str, str]]:
        """
        Fast convenience wrapper returning deduplicated ``(arudi_text, pattern)``
        variants from a single normalization + preprocessing pass.
        """
        return [
            (aln.arudi_text, aln.pattern)
            for aln in self.align_hemistich_variants(
                text, muqayyad=muqayyad, include_licenses=include_licenses
            )
        ]

    def prepare_text(self, text: str, saturate: bool = True, muqayyad: bool = False) -> tuple[str, str]:
        """
        Converts standard Arabic text into phonetic Arudi writing and extracts its binary pattern.

        Args:
            text (str): Input Arabic verse or hemistich.
            saturate (bool): Whether to apply end-of-shatr saturation (Ishba'). Defaults to True.
            muqayyad (bool): Whether the verse has a restricted/quiescent rhyme (Muqayyad).

        Returns:
            tuple[str, str]: (arudi_phonetic_text, binary_pattern)
        """
        aln = self.align_pattern(text, saturate=saturate, muqayyad=muqayyad)
        return aln.arudi_text, aln.pattern

prepare_text(text, saturate=True, muqayyad=False)

Converts standard Arabic text into phonetic Arudi writing and extracts its binary pattern.

Parameters:

Name Type Description Default
text str

Input Arabic verse or hemistich.

required
saturate bool

Whether to apply end-of-shatr saturation (Ishba'). Defaults to True.

True
muqayyad bool

Whether the verse has a restricted/quiescent rhyme (Muqayyad).

False

Returns:

Type Description
tuple[str, str]

tuple[str, str]: (arudi_phonetic_text, binary_pattern)

Source code in pyarud/core/phonetics.py
def prepare_text(self, text: str, saturate: bool = True, muqayyad: bool = False) -> tuple[str, str]:
    """
    Converts standard Arabic text into phonetic Arudi writing and extracts its binary pattern.

    Args:
        text (str): Input Arabic verse or hemistich.
        saturate (bool): Whether to apply end-of-shatr saturation (Ishba'). Defaults to True.
        muqayyad (bool): Whether the verse has a restricted/quiescent rhyme (Muqayyad).

    Returns:
        tuple[str, str]: (arudi_phonetic_text, binary_pattern)
    """
    aln = self.align_pattern(text, saturate=saturate, muqayyad=muqayyad)
    return aln.arudi_text, aln.pattern

align_pattern(text, *, saturate=True, muqayyad=False)

Convert Arabic poetic text into ArudiAlignment containing the Arudi phonetic text, binary metric pattern, and exact 1:1 bit-to-character mapping.

Source code in pyarud/core/phonetics.py
def align_pattern(
    self,
    text: str,
    *,
    saturate: bool = True,
    muqayyad: bool = False,
) -> ArudiAlignment:
    """
    Convert Arabic poetic text into ``ArudiAlignment`` containing the Arudi
    phonetic text, binary metric pattern, and exact 1:1 bit-to-character mapping.
    """
    if not text or not text.strip():
        return ArudiAlignment(
            original_text=text,
            arudi_text="",
            pattern="",
            arudi_positions=(),
            word_indices=(),
            normalized_words=(),
        )

    normalized = self._normalize_input(text)
    if not normalized:
        return ArudiAlignment(
            original_text=text,
            arudi_text="",
            pattern="",
            arudi_positions=(),
            word_indices=(),
            normalized_words=(),
        )

    preprocessed, norm_words = self._preprocess(normalized, shorten_ana=True)
    units = self._parse_units(preprocessed, len(norm_words))
    return self._compile_units(
        text,
        units,
        norm_words,
        saturate=saturate,
        muqayyad=muqayyad,
    )

align_hemistich_variants(text, *, muqayyad=False, include_licenses=False)

Compile a hemistich ONCE and produce deduplicated ArudiAlignment candidates.

Parameters:

Name Type Description Default
text str

Input Arabic hemistich.

required
muqayyad bool

If True, includes the quiescent-rhyme (مقيد) candidate alongside the saturated (مطلق) candidate (used for Ajuz). If False, includes the unsaturated candidate alongside the saturated candidate (used for Sadr).

False
include_licenses bool

If True, also yields classical poetic-license variants (أَنَا lengthened, mid-line هاء الضمير ikhtilas / ishba' ba'da sakin) only when the relevant constructs actually appear in text.

False
Source code in pyarud/core/phonetics.py
def align_hemistich_variants(
    self,
    text: str,
    *,
    muqayyad: bool = False,
    include_licenses: bool = False,
) -> list[ArudiAlignment]:
    """
    Compile a hemistich ONCE and produce deduplicated ``ArudiAlignment`` candidates.

    Args:
        text: Input Arabic hemistich.
        muqayyad: If True, includes the quiescent-rhyme (مقيد) candidate alongside
            the saturated (مطلق) candidate (used for Ajuz). If False, includes the
            unsaturated candidate alongside the saturated candidate (used for Sadr).
        include_licenses: If True, also yields classical poetic-license variants
            (``أَنَا`` lengthened, mid-line ``هاء الضمير`` *ikhtilas* / *ishba' ba'da sakin*)
            only when the relevant constructs actually appear in ``text``.
    """
    if not text or not text.strip():
        return [
            ArudiAlignment(
                original_text=text,
                arudi_text="",
                pattern="",
                arudi_positions=(),
                word_indices=(),
                normalized_words=(),
            )
        ]

    normalized = self._normalize_input(text)
    if not normalized:
        return [
            ArudiAlignment(
                original_text=text,
                arudi_text="",
                pattern="",
                arudi_positions=(),
                word_indices=(),
                normalized_words=(),
            )
        ]

    preprocessed, norm_words = self._preprocess(normalized, shorten_ana=True)
    units = self._parse_units(preprocessed, len(norm_words))

    variants: list[ArudiAlignment] = []
    seen_patterns: set[str] = set()

    def _add(aln: ArudiAlignment) -> None:
        if aln.pattern not in seen_patterns:
            seen_patterns.add(aln.pattern)
            variants.append(aln)

    # Primary candidate: saturated (Mutlaqah / saturated Arudh)
    _add(self._compile_units(text, units, norm_words, saturate=True, muqayyad=False))

    # Secondary candidate: quiescent rhyme (Ajuz) or unsaturated ending (Sadr)
    if muqayyad:
        _add(self._compile_units(text, units, norm_words, saturate=False, muqayyad=True))
    else:
        _add(self._compile_units(text, units, norm_words, saturate=False, muqayyad=False))

    # Optional classical poetic license variants (triggered only when applicable)
    if include_licenses and units:
        has_mid_ha = any(
            u.letter == HEH
            and u.is_word_end
            and idx < len(units) - 1
            and u.haraka in (KASRA, DAMMA)
            and u.word_plain not in _ROOT_HEH_PLAIN_STEMS
            for idx, u in enumerate(units)
        )
        if has_mid_ha:
            _add(
                self._compile_units(
                    text, units, norm_words, saturate=True, muqayyad=False, ha_damir_mode="no_ishba"
                )
            )
            _add(
                self._compile_units(
                    text, units, norm_words, saturate=True, muqayyad=False, ha_damir_mode="after_sakin"
                )
            )
            if muqayyad:
                _add(
                    self._compile_units(
                        text, units, norm_words, saturate=False, muqayyad=True, ha_damir_mode="no_ishba"
                    )
                )

        has_mid_ana = any(
            strip_tashkeel(w) in ("أنا", "وأنا", "فأنا") for w in norm_words[:-1]
        )
        if has_mid_ana:
            pre_long, _ = self._preprocess(normalized, shorten_ana=False)
            units_long = self._parse_units(pre_long, len(norm_words))
            _add(self._compile_units(text, units_long, norm_words, saturate=True, muqayyad=False))
            if muqayyad:
                _add(self._compile_units(text, units_long, norm_words, saturate=False, muqayyad=True))

    return variants

prepare_hemistich_variants(text, *, muqayyad=False, include_licenses=False)

Fast convenience wrapper returning deduplicated (arudi_text, pattern) variants from a single normalization + preprocessing pass.

Source code in pyarud/core/phonetics.py
def prepare_hemistich_variants(
    self,
    text: str,
    *,
    muqayyad: bool = False,
    include_licenses: bool = False,
) -> list[tuple[str, str]]:
    """
    Fast convenience wrapper returning deduplicated ``(arudi_text, pattern)``
    variants from a single normalization + preprocessing pass.
    """
    return [
        (aln.arudi_text, aln.pattern)
        for aln in self.align_hemistich_variants(
            text, muqayyad=muqayyad, include_licenses=include_licenses
        )
    ]

register_custom_spelling(word, replacement)

Register a custom phonetic spelling for a specific unvocalized word.

Source code in pyarud/core/phonetics.py
def register_custom_spelling(self, word: str, replacement: str) -> None:
    """Register a custom phonetic spelling for a specific unvocalized word."""
    clean_key = strip_tashkeel(strip_tatweel(word))
    self.replacements[clean_key] = replacement
    self._custom_replacements[clean_key] = replacement

pyarud.core.phonetics.ArudiAlignment dataclass

Phonetic Arudi transcription paired with exact 1:1 bit-to-character alignment.

Invariant: len(arudi_text.replace(" ", "")) == len(pattern) == len(arudi_positions) == len(word_indices).

Source code in pyarud/core/phonetics.py
@dataclass(frozen=True, slots=True)
class ArudiAlignment:
    """
    Phonetic Arudi transcription paired with exact 1:1 bit-to-character alignment.

    Invariant: ``len(arudi_text.replace(" ", "")) == len(pattern) == len(arudi_positions) == len(word_indices)``.
    """

    original_text: str
    arudi_text: str
    pattern: str
    arudi_positions: tuple[int, ...]
    word_indices: tuple[int, ...]
    normalized_words: tuple[str, ...]
    is_muqayyad: bool = False

    def slice_arudi(self, bit_start: int, bit_end: int) -> str:
        """
        Return the exact substring of ``arudi_text`` covering binary pattern
        indices ``[bit_start:bit_end]``, preserving internal word spaces.
        """
        n = len(self.arudi_positions)
        if n == 0 or bit_start >= bit_end or bit_start >= n or bit_end <= 0:
            return ""
        lo = max(0, bit_start)
        hi = min(n, bit_end)
        char_start = self.arudi_positions[lo]
        char_end = self.arudi_positions[hi - 1] + 1
        return self.arudi_text[char_start:char_end]

    def slice_words(self, bit_start: int, bit_end: int) -> str:
        """
        Return the space-joined normalized source words spanned by binary
        pattern indices ``[bit_start:bit_end]``.
        """
        n = len(self.word_indices)
        if n == 0 or bit_start >= bit_end or bit_start >= n or bit_end <= 0 or not self.normalized_words:
            return ""
        lo = max(0, bit_start)
        hi = min(n, bit_end)
        w_start = self.word_indices[lo]
        w_end = self.word_indices[hi - 1]
        if w_start > w_end:
            return ""
        return " ".join(self.normalized_words[w_start : w_end + 1])

slice_arudi(bit_start, bit_end)

Return the exact substring of arudi_text covering binary pattern indices [bit_start:bit_end], preserving internal word spaces.

Source code in pyarud/core/phonetics.py
def slice_arudi(self, bit_start: int, bit_end: int) -> str:
    """
    Return the exact substring of ``arudi_text`` covering binary pattern
    indices ``[bit_start:bit_end]``, preserving internal word spaces.
    """
    n = len(self.arudi_positions)
    if n == 0 or bit_start >= bit_end or bit_start >= n or bit_end <= 0:
        return ""
    lo = max(0, bit_start)
    hi = min(n, bit_end)
    char_start = self.arudi_positions[lo]
    char_end = self.arudi_positions[hi - 1] + 1
    return self.arudi_text[char_start:char_end]

slice_words(bit_start, bit_end)

Return the space-joined normalized source words spanned by binary pattern indices [bit_start:bit_end].

Source code in pyarud/core/phonetics.py
def slice_words(self, bit_start: int, bit_end: int) -> str:
    """
    Return the space-joined normalized source words spanned by binary
    pattern indices ``[bit_start:bit_end]``.
    """
    n = len(self.word_indices)
    if n == 0 or bit_start >= bit_end or bit_start >= n or bit_end <= 0 or not self.normalized_words:
        return ""
    lo = max(0, bit_start)
    hi = min(n, bit_end)
    w_start = self.word_indices[lo]
    w_end = self.word_indices[hi - 1]
    if w_start > w_end:
        return ""
    return " ".join(self.normalized_words[w_start : w_end + 1])

Qafiyah Analyzer (Rhyme & Rhyme Faults)

pyarud.qafiyah.analyzer.QafiyahAnalyzer

Analyzes Arabic poetic rhyme (علم القافية) according to classical prosody, including verse-level rhyme anatomy, poem-level rhyme fault detection (عيوب القافية), and opening-verse Tasri' (التصريع).

Source code in pyarud/qafiyah/analyzer.py
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
class QafiyahAnalyzer:
    """
    Analyzes Arabic poetic rhyme (علم القافية) according to classical prosody,
    including verse-level rhyme anatomy, poem-level rhyme fault detection
    (عيوب القافية), and opening-verse Tasri' (التصريع).
    """

    def __init__(self, converter: ArudiConverter | None = None) -> None:
        self.converter: ArudiConverter = converter if converter is not None else ArudiConverter()

    def analyze(
        self,
        ajuz_text: str,
        is_muqayyad: bool = False,
        *,
        arudi_text: str | None = None,
        pattern: str | None = None,
        alignment: ArudiAlignment | None = None,
    ) -> QafiyahAnalysis:
        """
        Extracts the full Qafiyah breakdown for the concluding hemistich (Ajuz).

        Args:
            ajuz_text: The concluding hemistich (or verse ending) to analyze.
            is_muqayyad: True if the poem uses a quiescent/restricted Rawi (قافية مقيدة).
            arudi_text: Optional precomputed Arudi transcription (avoids redundant conversion).
            pattern: Optional precomputed binary pattern (used together with ``arudi_text``).
            alignment: Optional precomputed ``ArudiAlignment`` (avoids redundant conversion
                and yields exact word/character Qafiyah span slicing).

        Returns:
            QafiyahAnalysis: Complete rhyme breakdown with letters, movements, spans, and types.
        """
        if not ajuz_text or not ajuz_text.strip():
            return QafiyahAnalysis(rawi="")

        # 1. Obtain Arudi phonetic alignment (reusing precomputed data when provided)
        if alignment is not None:
            resolved_arudi = alignment.arudi_text
            resolved_pattern = alignment.pattern
        elif arudi_text is not None and pattern is not None:
            resolved_arudi = arudi_text
            resolved_pattern = pattern
        else:
            alignment = self.converter.align_pattern(
                ajuz_text,
                saturate=not is_muqayyad,
                muqayyad=is_muqayyad,
            )
            resolved_arudi = alignment.arudi_text
            resolved_pattern = alignment.pattern

        # 2. Extract Qafiyah pattern boundary (Khalil's rule) & 5 rhythmic types
        qafiyah_pattern = ""
        qafiyah_type_ar = "المتواتر"
        qafiyah_type_en = "Al-Mutawatir"
        start_idx = 0
        end_idx = len(resolved_pattern)

        sakin_indices = [i for i, c in enumerate(resolved_pattern) if c == "0"]
        if len(sakin_indices) >= 2:
            last_sakin_idx = sakin_indices[-1]
            prev_sakin_idx = sakin_indices[-2]
            start_idx = max(0, prev_sakin_idx - 1)
            end_idx = last_sakin_idx + 1
            qafiyah_pattern = resolved_pattern[start_idx:end_idx]

            num_mutaharriks = max(0, last_sakin_idx - prev_sakin_idx - 1)
            if num_mutaharriks == 0:
                qafiyah_type_ar, qafiyah_type_en = "المترادف", "Al-Mutaradif"
            elif num_mutaharriks == 1:
                qafiyah_type_ar, qafiyah_type_en = "المتواتر", "Al-Mutawatir"
            elif num_mutaharriks == 2:
                qafiyah_type_ar, qafiyah_type_en = "المتدارك", "Al-Mutadarak"
            elif num_mutaharriks == 3:
                qafiyah_type_ar, qafiyah_type_en = "المتراكب", "Al-Mutarakib"
            else:
                qafiyah_type_ar, qafiyah_type_en = "المتكاوس", "Al-Mutakawis"
        elif len(sakin_indices) == 1:
            start_idx = max(0, sakin_indices[0] - 1)
            end_idx = len(resolved_pattern)
            qafiyah_pattern = resolved_pattern[start_idx:end_idx]

        # 3. Extract exact Qafiyah Arudi span and source word span
        if alignment is not None and qafiyah_pattern:
            qafiyah_arudi = alignment.slice_arudi(start_idx, end_idx)
            qafiyah_text = alignment.slice_words(start_idx, end_idx)
        elif qafiyah_pattern:
            qafiyah_arudi = _extract_arudi_span_without_alignment(resolved_arudi, start_idx, end_idx)
            words = ajuz_text.strip().split()
            word_count = qafiyah_arudi.count(" ") + 1 if qafiyah_arudi else 1
            qafiyah_text = " ".join(words[-word_count:]) if words else ""
        else:
            qafiyah_arudi = resolved_arudi
            qafiyah_text = ajuz_text.strip()

        # 4. Token-based extraction of all 6 Qafiyah letters & 6 movements
        tokens, _ = _tokenize_for_qafiyah(ajuz_text)
        if not tokens:
            return QafiyahAnalysis(
                rawi="",
                qafiyah_text=qafiyah_text,
                qafiyah_arudi=qafiyah_arudi,
                qafiyah_pattern=qafiyah_pattern,
                qafiyah_type_ar=qafiyah_type_ar,
                qafiyah_type_en=qafiyah_type_en,
            )

        (
            rawi,
            rawi_haraka,
            wasl,
            khuruj,
            ridf,
            tasees,
            dakhil,
            majra,
            nafadh,
            hadhw,
            ishba,
            rass,
            tawjih,
            effective_muqayyad,
        ) = self._extract_rhyme_components(tokens, is_muqayyad=is_muqayyad)

        classification = RhymeType.MUQAYYADAH if effective_muqayyad else RhymeType.MUTLAQAH
        struct_ar, struct_en = _structural_classification(
            is_muqayyad=effective_muqayyad,
            wasl=wasl,
            ridf=ridf,
            tasees=tasees,
        )

        return QafiyahAnalysis(
            rawi=rawi,
            rawi_haraka=rawi_haraka,
            wasl=wasl,
            khuruj=khuruj,
            ridf=ridf,
            tasees=tasees,
            dakhil=dakhil,
            qafiyah_text=qafiyah_text,
            qafiyah_arudi=qafiyah_arudi,
            qafiyah_pattern=qafiyah_pattern,
            qafiyah_type_ar=qafiyah_type_ar,
            qafiyah_type_en=qafiyah_type_en,
            rhyme_classification=classification,
            is_muqayyad=effective_muqayyad,
            majra=majra,
            nafadh=nafadh,
            hadhw=hadhw,
            ishba=ishba,
            rass=rass,
            tawjih=tawjih,
            structural_type_ar=struct_ar,
            structural_type_en=struct_en,
        )

    def _extract_rhyme_components(
        self,
        tokens: list[_QafToken],
        *,
        is_muqayyad: bool,
    ) -> tuple[
        str,  # rawi
        str,  # rawi_haraka
        str | None,  # wasl
        str | None,  # khuruj
        str | None,  # ridf
        str | None,  # tasees
        str | None,  # dakhil
        str,  # majra
        str,  # nafadh
        str,  # hadhw
        str,  # ishba
        str,  # rass
        str,  # tawjih
        bool,  # effective_muqayyad
    ]:
        """Apply the classical Farahidian Rawi / Wasl / Khuruj / Ridf / Ta'sees decision tree."""
        n = len(tokens)
        last = tokens[-1]
        rawi_idx = n - 1
        wasl: str | None = None
        khuruj: str | None = None
        nafadh = ""
        effective_muqayyad = is_muqayyad

        # Step 1: Peel off Wasl & Khuruj from the tail to locate the Rawi index
        # Case A: Tail ends in ه + madd vowel (رَسْمُهَا, مَنَازِلُهَا, كِتَابُهُو, فِيهَا, عَلَيْهَا)
        if (
            n >= 2
            and last.is_madd
            and tokens[-2].letter == HEH
            and tokens[-2].word_idx == last.word_idx
        ):
            heh_tok = tokens[-2]
            prev_before_heh = tokens[-3] if n >= 3 and tokens[-3].word_idx == heh_tok.word_idx else None
            if (
                prev_before_heh is not None
                and not prev_before_heh.is_sakin
                and heh_tok.word_plain not in _ROOT_HEH_PLAIN_STEMS
            ):
                # Pronoun Ha' after mutaharrik -> Ha' is Wasl, madd is Khuruj, preceding letter is Rawi
                khuruj = last.letter
                wasl = HEH
                nafadh_h = heh_tok.haraka or LONG_VOWEL_TO_HARAKA.get(last.letter, "")
                nafadh = HARAKA_NAMES.get(nafadh_h, "")
                rawi_idx = n - 3
                effective_muqayyad = False
            else:
                # Ha' after sakin (فِيهَا / عَلَيْهَا / عُلَاهَا) or root Ha' -> Ha' IS Rawi
                rawi_idx = n - 2
                wasl = last.letter
                effective_muqayyad = False

        # Case B: Tail ends in ه (فُلْفُلِهِ, تُقَسِّمُهُ, لَدَيْهِ, عُلَاهُ, قَتَلُوهُ, الوَجْهُ, وَجْهَهُ)
        elif last.letter == HEH:
            prev_tok = tokens[-2] if n >= 2 and tokens[-2].word_idx == last.word_idx else None
            if (
                prev_tok is not None
                and not prev_tok.is_sakin
                and last.word_plain not in _ROOT_HEH_PLAIN_STEMS
            ):
                # Pronoun Ha' after mutaharrik -> Wasl (with Khuruj if vocalized)
                wasl = HEH
                rawi_idx = n - 2
                effective_muqayyad = False
                if last.haraka and not is_muqayyad:
                    nafadh = HARAKA_NAMES.get(last.haraka, "")
                    khuruj = HARAKA_TO_LONG_VOWEL.get(last.haraka)
            else:
                # Root Ha' or Ha' preceded by sakin -> Ha' IS Rawi
                rawi_idx = n - 1
                if last.is_sakin and not last.haraka:
                    effective_muqayyad = True

        # Case C: Tail ends in ة (Ta Marbuta)
        elif last.letter == TEH_MARBUTA:
            prev_tok = tokens[-2] if n >= 2 and tokens[-2].word_idx == last.word_idx else None
            if (last.is_sakin or (is_muqayyad and not last.haraka)) and not last.haraka:
                if prev_tok is not None and not prev_tok.is_sakin:
                    # Paused هاء التأنيث الساكنة after mutaharrik (مَدْرَسَةْ) -> Wasl
                    wasl = HEH
                    rawi_idx = n - 2
                    effective_muqayyad = False
                else:
                    # Preceded by sakin (حَيَاةْ) -> Rawi مقيد
                    rawi_idx = n - 1
                    effective_muqayyad = True
            else:
                # Vocalized ة (صَلَاةُ / الحَيَاةِ / عَامَّةُ) -> Rawi
                rawi_idx = n - 1

        # Case D: Tail ends in a true madd long vowel (تَكَلَّمِي, يَتَكَلَّمَا, سَأَلُوا, مَضَى, عَلِيِّي)
        elif last.is_madd and n >= 2 and tokens[-2].word_idx == last.word_idx:
            wasl = last.letter
            rawi_idx = n - 2
            effective_muqayyad = False

        # Case E: Regular consonant (or vocalized/shadda'd/diphthong و/ي, or real ن with tanween)
        else:
            rawi_idx = n - 1
            if last.is_sakin and not last.haraka:
                effective_muqayyad = True

        # Step 2: Determine Rawi, Rawi Haraka, Majra, Wasl (from ishba'), and Tawjih
        rawi_tok = tokens[rawi_idx]
        rawi = rawi_tok.letter

        majra = ""
        tawjih = ""
        if effective_muqayyad and wasl is None:
            rawi_haraka = "sukun"
            # Tawjih (التوجيه): haraka of the vocalized consonant before quiescent Rawi
            if rawi_idx >= 1:
                before_rawi = tokens[rawi_idx - 1]
                if not before_rawi.is_sakin and before_rawi.haraka:
                    tawjih = HARAKA_NAMES.get(before_rawi.haraka, "")
        else:
            effective_muqayyad = False
            rawi_h = rawi_tok.haraka
            if not rawi_h and wasl is not None and wasl in LONG_VOWEL_TO_HARAKA:
                rawi_h = LONG_VOWEL_TO_HARAKA[wasl]
            rawi_haraka = HARAKA_NAMES.get(rawi_h, "")
            majra = rawi_haraka
            if wasl is None and rawi_h in HARAKA_TO_LONG_VOWEL:
                wasl = HARAKA_TO_LONG_VOWEL[rawi_h]

        # Step 3: Extract Ridf (+ Hadhw) OR Ta'sees + Dakhil (+ Ishba' + Rass)
        ridf: str | None = None
        tasees: str | None = None
        dakhil: str | None = None
        hadhw = ""
        ishba = ""
        rass = ""

        # Check Ridf: true madd vowel (ا/ى, و after damma, ي after kasra) directly before Rawi in SAME word
        if rawi_idx >= 1:
            prev1 = tokens[rawi_idx - 1]
            if prev1.word_idx == rawi_tok.word_idx and prev1.is_madd:
                ridf = prev1.letter
                if rawi_idx >= 2 and tokens[rawi_idx - 2].word_idx == prev1.word_idx and tokens[rawi_idx - 2].haraka:
                    hadhw = HARAKA_NAMES.get(tokens[rawi_idx - 2].haraka, "")
                else:
                    hadhw = HARAKA_NAMES.get(LONG_VOWEL_TO_HARAKA.get(ridf, ""), "")

        # Check Ta'sees + Dakhil: madd Alif separated from Rawi by exactly 1 vocalized letter in SAME word
        if ridf is None and rawi_idx >= 2:
            dakhil_tok = tokens[rawi_idx - 1]
            tasees_tok = tokens[rawi_idx - 2]
            if (
                tasees_tok.letter == ALEF
                and tasees_tok.is_madd
                and not tasees_tok.is_wasl_alef
                and tasees_tok.word_idx == rawi_tok.word_idx
                and dakhil_tok.word_idx == rawi_tok.word_idx
                and not dakhil_tok.is_sakin
                and not dakhil_tok.is_shadda_half
            ):
                tasees = ALEF
                dakhil = dakhil_tok.letter
                ishba = HARAKA_NAMES.get(dakhil_tok.haraka, "")
                if (
                    rawi_idx >= 3
                    and tokens[rawi_idx - 3].word_idx == tasees_tok.word_idx
                    and tokens[rawi_idx - 3].haraka
                ):
                    rass = HARAKA_NAMES.get(tokens[rawi_idx - 3].haraka, "fatha")
                else:
                    rass = "fatha"

        return (
            rawi,
            rawi_haraka,
            wasl,
            khuruj,
            ridf,
            tasees,
            dakhil,
            majra,
            nafadh,
            hadhw,
            ishba,
            rass,
            tawjih,
            effective_muqayyad,
        )

    def is_tasri_rhyme(
        self,
        sadr_text: str,
        ajuz_text: str,
        *,
        sadr_qafiyah: QafiyahAnalysis | None = None,
        ajuz_qafiyah: QafiyahAnalysis | None = None,
        is_muqayyad: bool = False,
    ) -> bool:
        """
        Determine whether a verse (typically verse 1 / المطلع) exhibits phonetic
        Tasri' (التصريع), where Sadr and Ajuz share the same Rawi, Majra, and Wasl.
        """
        if not sadr_text.strip() or not ajuz_text.strip():
            return False

        q_s = sadr_qafiyah if sadr_qafiyah is not None else self.analyze(sadr_text, is_muqayyad=is_muqayyad)
        q_a = ajuz_qafiyah if ajuz_qafiyah is not None else self.analyze(ajuz_text, is_muqayyad=is_muqayyad)

        if not q_s.rawi or not q_a.rawi:
            return False

        if _canonical_rawi(q_s.rawi) != _canonical_rawi(q_a.rawi):
            return False

        if q_s.is_muqayyad != q_a.is_muqayyad:
            return False

        if not q_s.is_muqayyad:
            if q_s.majra and q_a.majra and q_s.majra != q_a.majra:
                return False
            if (q_s.wasl == HEH) != (q_a.wasl == HEH):
                return False

        return True

    def detect_rhyme_faults(
        self,
        qafiyahs: Sequence[QafiyahAnalysis | None],
    ) -> list[RhymeFault]:
        """
        Detect classical poem-level rhyme faults (عيوب القافية) across verses:
        - الإقواء (Al-Iqwa'): Majra alternates between damma and kasra.
        - الإصراف (Al-Israf): Majra mixes fatha with damma or kasra.
        - الإكفاء (Al-Ikfa'): Rawi differs by phonetically proximate consonants.
        - الإجازة (Al-Ijazah): Rawi differs by phonetically distant consonants.
        - السناد (Al-Sinad): all 5 classical types (الردف، التأسيس، الحذو، الإشباع، التوجيه),
          respecting valid و/ي Ridf pairing and vocalized ة/ت Rawi equivalence.
        - الإيطاء (Al-Ita'): lexical repetition of the final rhyme word within < 7 verses (warning).
        """
        valid: list[tuple[int, QafiyahAnalysis]] = [
            (i, q) for i, q in enumerate(qafiyahs) if q is not None and q.rawi
        ]
        if len(valid) < 2:
            return []

        faults: list[RhymeFault] = []

        # 1. Rawi consistency: الإكفاء (close makharij) vs الإجازة (distant makharij)
        rawi_counts: Counter[str] = Counter(_canonical_rawi(q.rawi) for _, q in valid)
        dom_rawi = rawi_counts.most_common(1)[0][0]

        ikfa_indices: list[int] = []
        ijazah_indices: list[int] = []
        for idx, q in valid:
            c_rawi = _canonical_rawi(q.rawi)
            if c_rawi != dom_rawi:
                if _are_close_phonemes(c_rawi, dom_rawi):
                    ikfa_indices.append(idx)
                else:
                    ijazah_indices.append(idx)

        if ikfa_indices:
            faults.append(
                RhymeFault(
                    fault_type=RhymeFaultType.IKFA,
                    name_ar="الإكفاء",
                    name_en="Al-Ikfa'",
                    verse_indices=ikfa_indices,
                    description_ar=f"اختلاف حرف الروي بحرف متقارب في المخرج مع الروي السائد ({dom_rawi}).",
                    description_en=(
                        f"Rawi diverges to a phonetically close consonant relative to dominant Rawi ({dom_rawi})."
                    ),
                    severity="error",
                )
            )

        if ijazah_indices:
            faults.append(
                RhymeFault(
                    fault_type=RhymeFaultType.IJAZAH,
                    name_ar="الإجازة",
                    name_en="Al-Ijazah",
                    verse_indices=ijazah_indices,
                    description_ar=f"اختلاف حرف الروي بحرف متباعد في المخرج عن الروي السائد ({dom_rawi}).",
                    description_en=(
                        f"Rawi diverges to a phonetically distant consonant relative to dominant Rawi ({dom_rawi})."
                    ),
                    severity="error",
                )
            )

        # 2. Majra consistency (mutlaqah verses): الإقواء (damma vs kasra) & الإصراف (fatha vs damma/kasra)
        mut_majras = [
            (idx, q.majra)
            for idx, q in valid
            if not q.is_muqayyad and q.majra in ("fatha", "damma", "kasra")
        ]
        if len(mut_majras) >= 2:
            majra_counts: Counter[str] = Counter(m for _, m in mut_majras)
            if len(majra_counts) > 1:
                dom_majra = majra_counts.most_common(1)[0][0]
                iqwa_indices: list[int] = []
                israf_indices: list[int] = []
                for idx, m in mut_majras:
                    if m == dom_majra:
                        continue
                    pair = {dom_majra, m}
                    if pair == {"damma", "kasra"}:
                        iqwa_indices.append(idx)
                    else:
                        israf_indices.append(idx)

                if iqwa_indices:
                    dom_ar = _HARAKA_AR_NAMES.get(dom_majra, dom_majra)
                    faults.append(
                        RhymeFault(
                            fault_type=RhymeFaultType.IQWA,
                            name_ar="الإقواء",
                            name_en="Al-Iqwa'",
                            verse_indices=iqwa_indices,
                            description_ar=f"اختلاف حركة المجرى بين الضمة والكسرة (المجرى السائد: {dom_ar}).",
                            description_en=f"Majra alternates between damma and kasra (dominant Majra: {dom_majra}).",
                            severity="error",
                        )
                    )

                if israf_indices:
                    dom_ar = _HARAKA_AR_NAMES.get(dom_majra, dom_majra)
                    faults.append(
                        RhymeFault(
                            fault_type=RhymeFaultType.ISRAF,
                            name_ar="الإصراف",
                            name_en="Al-Israf",
                            verse_indices=israf_indices,
                            description_ar=f"اختلاف حركة المجرى بين الفتحة والضمة أو الكسرة (المجرى السائد: {dom_ar}).",
                            description_en=f"Majra mixes fatha with damma/kasra (dominant Majra: {dom_majra}).",
                            severity="error",
                        )
                    )

        # 3a. سناد الردف (Sinad al-Ridf): none vs alef vs waw/yeh (و and ي validly inter-rhyme)
        def _ridf_class(r: str | None) -> str:
            if not r:
                return "none"
            if r in (ALEF, ALEF_MAKSURA):
                return "alef"
            return "waw_yeh"

        ridf_classes = [(idx, _ridf_class(q.ridf)) for idx, q in valid]
        ridf_counts: Counter[str] = Counter(rc for _, rc in ridf_classes)
        if len(ridf_counts) > 1:
            dom_rc = ridf_counts.most_common(1)[0][0]
            sinad_ridf_indices = [idx for idx, rc in ridf_classes if rc != dom_rc]
            faults.append(
                RhymeFault(
                    fault_type=RhymeFaultType.SINAD_RIDF,
                    name_ar="سناد الردف",
                    name_en="Sinad al-Ridf",
                    verse_indices=sinad_ridf_indices,
                    description_ar="عدم التزام الردف أو الخلط بين ردف الألف وردف الواو والياء.",
                    description_en="Inconsistent Ridf presence or mixing Alif Ridf with Waw/Yeh Ridf.",
                    severity="error",
                )
            )

        # 3b. سناد التأسيس (Sinad al-Ta'sees)
        tasees_flags = [(idx, bool(q.tasees)) for idx, q in valid]
        tasees_counts: Counter[bool] = Counter(tf for _, tf in tasees_flags)
        if len(tasees_counts) > 1:
            dom_tf = tasees_counts.most_common(1)[0][0]
            sinad_tasees_indices = [idx for idx, tf in tasees_flags if tf != dom_tf]
            faults.append(
                RhymeFault(
                    fault_type=RhymeFaultType.SINAD_TASEES,
                    name_ar="سناد التأسيس",
                    name_en="Sinad al-Ta'sees",
                    verse_indices=sinad_tasees_indices,
                    description_ar="الجمع بين قوافٍ مؤسسة بألف التأسيس وأخرى غير مؤسسة.",
                    description_en="Mixing Ta'sees-bearing rhymes with rhymes lacking Ta'sees.",
                    severity="error",
                )
            )

        # 3c. سناد الحذو (Sinad al-Hadhw): fatha vs damma/kasra within same Ridf class
        # (only when Ridf class itself is consistent, avoiding double-reporting with Sinad al-Ridf)
        if len(ridf_counts) == 1:
            hadhw_entries = [(idx, q.hadhw) for idx, q in valid if q.ridf and q.hadhw]
            if len(hadhw_entries) >= 2:
                hadhw_groups = [
                    (idx, "fatha" if h == "fatha" else "high") for idx, h in hadhw_entries
                ]
                hg_counts: Counter[str] = Counter(g for _, g in hadhw_groups)
                if len(hg_counts) > 1:
                    dom_hg = hg_counts.most_common(1)[0][0]
                    sinad_hadhw_indices = [idx for idx, g in hadhw_groups if g != dom_hg]
                    faults.append(
                        RhymeFault(
                            fault_type=RhymeFaultType.SINAD_HADHW,
                            name_ar="سناد الحذو",
                            name_en="Sinad al-Hadhw",
                            verse_indices=sinad_hadhw_indices,
                            description_ar="اختلاف حركة الحذو (ما قبل الردف) بين الفتحة والضمة أو الكسرة.",
                            description_en="Hadhw (vowel preceding Ridf) mixes fatha with damma/kasra.",
                            severity="error",
                        )
                    )

        # 3d. سناد الإشباع (Sinad al-Ishba'): Dakhil vowel mismatch among Ta'sees verses
        ishba_entries = [(idx, q.ishba) for idx, q in valid if q.tasees and q.ishba]
        if len(ishba_entries) >= 2:
            ishba_counts: Counter[str] = Counter(h for _, h in ishba_entries)
            if len(ishba_counts) > 1:
                dom_ish = ishba_counts.most_common(1)[0][0]
                sinad_ishba_indices = [idx for idx, h in ishba_entries if h != dom_ish]
                has_fatha_clash = any({dom_ish, h} != {"damma", "kasra"} for _, h in ishba_entries if h != dom_ish)
                faults.append(
                    RhymeFault(
                        fault_type=RhymeFaultType.SINAD_ISHBA,
                        name_ar="سناد الإشباع",
                        name_en="Sinad al-Ishba'",
                        verse_indices=sinad_ishba_indices,
                        description_ar="اختلاف حركة الدخيل (الإشباع) بين أبيات القافية المؤسسة.",
                        description_en="Ishba' (vowel on Dakhil) varies across Ta'sees rhymes.",
                        severity="error" if has_fatha_clash else "warning",
                    )
                )

        # 3e. سناد التوجيه (Sinad al-Tawjih): pre-Rawi vowel mismatch in Muqayyad verses
        tawjih_entries = [(idx, q.tawjih) for idx, q in valid if q.is_muqayyad and q.tawjih]
        if len(tawjih_entries) >= 2:
            tawjih_counts: Counter[str] = Counter(t for _, t in tawjih_entries)
            if len(tawjih_counts) > 1:
                dom_tw = tawjih_counts.most_common(1)[0][0]
                sinad_tawjih_indices = [idx for idx, t in tawjih_entries if t != dom_tw]
                faults.append(
                    RhymeFault(
                        fault_type=RhymeFaultType.SINAD_TAWJIH,
                        name_ar="سناد التوجيه",
                        name_en="Sinad al-Tawjih",
                        verse_indices=sinad_tawjih_indices,
                        description_ar="اختلاف حركة ما قبل الروي المقيد (التوجيه) بين الأبيات.",
                        description_en="Tawjih (vowel preceding quiescent Rawi) varies across verses.",
                        severity="warning",
                    )
                )

        # 4. الإيطاء (Al-Ita'): repeated rhyme word within < 7 verses (lexical warning; homonyms excluded)
        last_seen_word: dict[str, int] = {}
        ita_indices_set: set[int] = set()
        for idx, q in valid:
            words = q.qafiyah_text.strip().split()
            if not words:
                continue
            rhyme_word_plain = strip_tashkeel(strip_punctuation(strip_tatweel(words[-1])))
            if not rhyme_word_plain:
                continue
            prev_idx = last_seen_word.get(rhyme_word_plain)
            if prev_idx is not None and (idx - prev_idx) < 7:
                ita_indices_set.add(prev_idx)
                ita_indices_set.add(idx)
            last_seen_word[rhyme_word_plain] = idx

        if ita_indices_set:
            faults.append(
                RhymeFault(
                    fault_type=RhymeFaultType.ITA,
                    name_ar="الإيطاء",
                    name_en="Al-Ita'",
                    verse_indices=sorted(ita_indices_set),
                    description_ar="تكرار كلمة القافية بلفظها قبل مرور سبعة أبيات (يُستثنى اختلاف المعنى / الجناس).",
                    description_en="Final rhyme word repeated within 7 verses (warning: valid if homonymous / Jinas).",
                    severity="warning",
                )
            )

        return faults

analyze(ajuz_text, is_muqayyad=False, *, arudi_text=None, pattern=None, alignment=None)

Extracts the full Qafiyah breakdown for the concluding hemistich (Ajuz).

Parameters:

Name Type Description Default
ajuz_text str

The concluding hemistich (or verse ending) to analyze.

required
is_muqayyad bool

True if the poem uses a quiescent/restricted Rawi (قافية مقيدة).

False
arudi_text str | None

Optional precomputed Arudi transcription (avoids redundant conversion).

None
pattern str | None

Optional precomputed binary pattern (used together with arudi_text).

None
alignment ArudiAlignment | None

Optional precomputed ArudiAlignment (avoids redundant conversion and yields exact word/character Qafiyah span slicing).

None

Returns:

Name Type Description
QafiyahAnalysis QafiyahAnalysis

Complete rhyme breakdown with letters, movements, spans, and types.

Source code in pyarud/qafiyah/analyzer.py
def analyze(
    self,
    ajuz_text: str,
    is_muqayyad: bool = False,
    *,
    arudi_text: str | None = None,
    pattern: str | None = None,
    alignment: ArudiAlignment | None = None,
) -> QafiyahAnalysis:
    """
    Extracts the full Qafiyah breakdown for the concluding hemistich (Ajuz).

    Args:
        ajuz_text: The concluding hemistich (or verse ending) to analyze.
        is_muqayyad: True if the poem uses a quiescent/restricted Rawi (قافية مقيدة).
        arudi_text: Optional precomputed Arudi transcription (avoids redundant conversion).
        pattern: Optional precomputed binary pattern (used together with ``arudi_text``).
        alignment: Optional precomputed ``ArudiAlignment`` (avoids redundant conversion
            and yields exact word/character Qafiyah span slicing).

    Returns:
        QafiyahAnalysis: Complete rhyme breakdown with letters, movements, spans, and types.
    """
    if not ajuz_text or not ajuz_text.strip():
        return QafiyahAnalysis(rawi="")

    # 1. Obtain Arudi phonetic alignment (reusing precomputed data when provided)
    if alignment is not None:
        resolved_arudi = alignment.arudi_text
        resolved_pattern = alignment.pattern
    elif arudi_text is not None and pattern is not None:
        resolved_arudi = arudi_text
        resolved_pattern = pattern
    else:
        alignment = self.converter.align_pattern(
            ajuz_text,
            saturate=not is_muqayyad,
            muqayyad=is_muqayyad,
        )
        resolved_arudi = alignment.arudi_text
        resolved_pattern = alignment.pattern

    # 2. Extract Qafiyah pattern boundary (Khalil's rule) & 5 rhythmic types
    qafiyah_pattern = ""
    qafiyah_type_ar = "المتواتر"
    qafiyah_type_en = "Al-Mutawatir"
    start_idx = 0
    end_idx = len(resolved_pattern)

    sakin_indices = [i for i, c in enumerate(resolved_pattern) if c == "0"]
    if len(sakin_indices) >= 2:
        last_sakin_idx = sakin_indices[-1]
        prev_sakin_idx = sakin_indices[-2]
        start_idx = max(0, prev_sakin_idx - 1)
        end_idx = last_sakin_idx + 1
        qafiyah_pattern = resolved_pattern[start_idx:end_idx]

        num_mutaharriks = max(0, last_sakin_idx - prev_sakin_idx - 1)
        if num_mutaharriks == 0:
            qafiyah_type_ar, qafiyah_type_en = "المترادف", "Al-Mutaradif"
        elif num_mutaharriks == 1:
            qafiyah_type_ar, qafiyah_type_en = "المتواتر", "Al-Mutawatir"
        elif num_mutaharriks == 2:
            qafiyah_type_ar, qafiyah_type_en = "المتدارك", "Al-Mutadarak"
        elif num_mutaharriks == 3:
            qafiyah_type_ar, qafiyah_type_en = "المتراكب", "Al-Mutarakib"
        else:
            qafiyah_type_ar, qafiyah_type_en = "المتكاوس", "Al-Mutakawis"
    elif len(sakin_indices) == 1:
        start_idx = max(0, sakin_indices[0] - 1)
        end_idx = len(resolved_pattern)
        qafiyah_pattern = resolved_pattern[start_idx:end_idx]

    # 3. Extract exact Qafiyah Arudi span and source word span
    if alignment is not None and qafiyah_pattern:
        qafiyah_arudi = alignment.slice_arudi(start_idx, end_idx)
        qafiyah_text = alignment.slice_words(start_idx, end_idx)
    elif qafiyah_pattern:
        qafiyah_arudi = _extract_arudi_span_without_alignment(resolved_arudi, start_idx, end_idx)
        words = ajuz_text.strip().split()
        word_count = qafiyah_arudi.count(" ") + 1 if qafiyah_arudi else 1
        qafiyah_text = " ".join(words[-word_count:]) if words else ""
    else:
        qafiyah_arudi = resolved_arudi
        qafiyah_text = ajuz_text.strip()

    # 4. Token-based extraction of all 6 Qafiyah letters & 6 movements
    tokens, _ = _tokenize_for_qafiyah(ajuz_text)
    if not tokens:
        return QafiyahAnalysis(
            rawi="",
            qafiyah_text=qafiyah_text,
            qafiyah_arudi=qafiyah_arudi,
            qafiyah_pattern=qafiyah_pattern,
            qafiyah_type_ar=qafiyah_type_ar,
            qafiyah_type_en=qafiyah_type_en,
        )

    (
        rawi,
        rawi_haraka,
        wasl,
        khuruj,
        ridf,
        tasees,
        dakhil,
        majra,
        nafadh,
        hadhw,
        ishba,
        rass,
        tawjih,
        effective_muqayyad,
    ) = self._extract_rhyme_components(tokens, is_muqayyad=is_muqayyad)

    classification = RhymeType.MUQAYYADAH if effective_muqayyad else RhymeType.MUTLAQAH
    struct_ar, struct_en = _structural_classification(
        is_muqayyad=effective_muqayyad,
        wasl=wasl,
        ridf=ridf,
        tasees=tasees,
    )

    return QafiyahAnalysis(
        rawi=rawi,
        rawi_haraka=rawi_haraka,
        wasl=wasl,
        khuruj=khuruj,
        ridf=ridf,
        tasees=tasees,
        dakhil=dakhil,
        qafiyah_text=qafiyah_text,
        qafiyah_arudi=qafiyah_arudi,
        qafiyah_pattern=qafiyah_pattern,
        qafiyah_type_ar=qafiyah_type_ar,
        qafiyah_type_en=qafiyah_type_en,
        rhyme_classification=classification,
        is_muqayyad=effective_muqayyad,
        majra=majra,
        nafadh=nafadh,
        hadhw=hadhw,
        ishba=ishba,
        rass=rass,
        tawjih=tawjih,
        structural_type_ar=struct_ar,
        structural_type_en=struct_en,
    )

is_tasri_rhyme(sadr_text, ajuz_text, *, sadr_qafiyah=None, ajuz_qafiyah=None, is_muqayyad=False)

Determine whether a verse (typically verse 1 / المطلع) exhibits phonetic Tasri' (التصريع), where Sadr and Ajuz share the same Rawi, Majra, and Wasl.

Source code in pyarud/qafiyah/analyzer.py
def is_tasri_rhyme(
    self,
    sadr_text: str,
    ajuz_text: str,
    *,
    sadr_qafiyah: QafiyahAnalysis | None = None,
    ajuz_qafiyah: QafiyahAnalysis | None = None,
    is_muqayyad: bool = False,
) -> bool:
    """
    Determine whether a verse (typically verse 1 / المطلع) exhibits phonetic
    Tasri' (التصريع), where Sadr and Ajuz share the same Rawi, Majra, and Wasl.
    """
    if not sadr_text.strip() or not ajuz_text.strip():
        return False

    q_s = sadr_qafiyah if sadr_qafiyah is not None else self.analyze(sadr_text, is_muqayyad=is_muqayyad)
    q_a = ajuz_qafiyah if ajuz_qafiyah is not None else self.analyze(ajuz_text, is_muqayyad=is_muqayyad)

    if not q_s.rawi or not q_a.rawi:
        return False

    if _canonical_rawi(q_s.rawi) != _canonical_rawi(q_a.rawi):
        return False

    if q_s.is_muqayyad != q_a.is_muqayyad:
        return False

    if not q_s.is_muqayyad:
        if q_s.majra and q_a.majra and q_s.majra != q_a.majra:
            return False
        if (q_s.wasl == HEH) != (q_a.wasl == HEH):
            return False

    return True

detect_rhyme_faults(qafiyahs)

Detect classical poem-level rhyme faults (عيوب القافية) across verses: - الإقواء (Al-Iqwa'): Majra alternates between damma and kasra. - الإصراف (Al-Israf): Majra mixes fatha with damma or kasra. - الإكفاء (Al-Ikfa'): Rawi differs by phonetically proximate consonants. - الإجازة (Al-Ijazah): Rawi differs by phonetically distant consonants. - السناد (Al-Sinad): all 5 classical types (الردف، التأسيس، الحذو، الإشباع، التوجيه), respecting valid و/ي Ridf pairing and vocalized ة/ت Rawi equivalence. - الإيطاء (Al-Ita'): lexical repetition of the final rhyme word within < 7 verses (warning).

Source code in pyarud/qafiyah/analyzer.py
def detect_rhyme_faults(
    self,
    qafiyahs: Sequence[QafiyahAnalysis | None],
) -> list[RhymeFault]:
    """
    Detect classical poem-level rhyme faults (عيوب القافية) across verses:
    - الإقواء (Al-Iqwa'): Majra alternates between damma and kasra.
    - الإصراف (Al-Israf): Majra mixes fatha with damma or kasra.
    - الإكفاء (Al-Ikfa'): Rawi differs by phonetically proximate consonants.
    - الإجازة (Al-Ijazah): Rawi differs by phonetically distant consonants.
    - السناد (Al-Sinad): all 5 classical types (الردف، التأسيس، الحذو، الإشباع، التوجيه),
      respecting valid و/ي Ridf pairing and vocalized ة/ت Rawi equivalence.
    - الإيطاء (Al-Ita'): lexical repetition of the final rhyme word within < 7 verses (warning).
    """
    valid: list[tuple[int, QafiyahAnalysis]] = [
        (i, q) for i, q in enumerate(qafiyahs) if q is not None and q.rawi
    ]
    if len(valid) < 2:
        return []

    faults: list[RhymeFault] = []

    # 1. Rawi consistency: الإكفاء (close makharij) vs الإجازة (distant makharij)
    rawi_counts: Counter[str] = Counter(_canonical_rawi(q.rawi) for _, q in valid)
    dom_rawi = rawi_counts.most_common(1)[0][0]

    ikfa_indices: list[int] = []
    ijazah_indices: list[int] = []
    for idx, q in valid:
        c_rawi = _canonical_rawi(q.rawi)
        if c_rawi != dom_rawi:
            if _are_close_phonemes(c_rawi, dom_rawi):
                ikfa_indices.append(idx)
            else:
                ijazah_indices.append(idx)

    if ikfa_indices:
        faults.append(
            RhymeFault(
                fault_type=RhymeFaultType.IKFA,
                name_ar="الإكفاء",
                name_en="Al-Ikfa'",
                verse_indices=ikfa_indices,
                description_ar=f"اختلاف حرف الروي بحرف متقارب في المخرج مع الروي السائد ({dom_rawi}).",
                description_en=(
                    f"Rawi diverges to a phonetically close consonant relative to dominant Rawi ({dom_rawi})."
                ),
                severity="error",
            )
        )

    if ijazah_indices:
        faults.append(
            RhymeFault(
                fault_type=RhymeFaultType.IJAZAH,
                name_ar="الإجازة",
                name_en="Al-Ijazah",
                verse_indices=ijazah_indices,
                description_ar=f"اختلاف حرف الروي بحرف متباعد في المخرج عن الروي السائد ({dom_rawi}).",
                description_en=(
                    f"Rawi diverges to a phonetically distant consonant relative to dominant Rawi ({dom_rawi})."
                ),
                severity="error",
            )
        )

    # 2. Majra consistency (mutlaqah verses): الإقواء (damma vs kasra) & الإصراف (fatha vs damma/kasra)
    mut_majras = [
        (idx, q.majra)
        for idx, q in valid
        if not q.is_muqayyad and q.majra in ("fatha", "damma", "kasra")
    ]
    if len(mut_majras) >= 2:
        majra_counts: Counter[str] = Counter(m for _, m in mut_majras)
        if len(majra_counts) > 1:
            dom_majra = majra_counts.most_common(1)[0][0]
            iqwa_indices: list[int] = []
            israf_indices: list[int] = []
            for idx, m in mut_majras:
                if m == dom_majra:
                    continue
                pair = {dom_majra, m}
                if pair == {"damma", "kasra"}:
                    iqwa_indices.append(idx)
                else:
                    israf_indices.append(idx)

            if iqwa_indices:
                dom_ar = _HARAKA_AR_NAMES.get(dom_majra, dom_majra)
                faults.append(
                    RhymeFault(
                        fault_type=RhymeFaultType.IQWA,
                        name_ar="الإقواء",
                        name_en="Al-Iqwa'",
                        verse_indices=iqwa_indices,
                        description_ar=f"اختلاف حركة المجرى بين الضمة والكسرة (المجرى السائد: {dom_ar}).",
                        description_en=f"Majra alternates between damma and kasra (dominant Majra: {dom_majra}).",
                        severity="error",
                    )
                )

            if israf_indices:
                dom_ar = _HARAKA_AR_NAMES.get(dom_majra, dom_majra)
                faults.append(
                    RhymeFault(
                        fault_type=RhymeFaultType.ISRAF,
                        name_ar="الإصراف",
                        name_en="Al-Israf",
                        verse_indices=israf_indices,
                        description_ar=f"اختلاف حركة المجرى بين الفتحة والضمة أو الكسرة (المجرى السائد: {dom_ar}).",
                        description_en=f"Majra mixes fatha with damma/kasra (dominant Majra: {dom_majra}).",
                        severity="error",
                    )
                )

    # 3a. سناد الردف (Sinad al-Ridf): none vs alef vs waw/yeh (و and ي validly inter-rhyme)
    def _ridf_class(r: str | None) -> str:
        if not r:
            return "none"
        if r in (ALEF, ALEF_MAKSURA):
            return "alef"
        return "waw_yeh"

    ridf_classes = [(idx, _ridf_class(q.ridf)) for idx, q in valid]
    ridf_counts: Counter[str] = Counter(rc for _, rc in ridf_classes)
    if len(ridf_counts) > 1:
        dom_rc = ridf_counts.most_common(1)[0][0]
        sinad_ridf_indices = [idx for idx, rc in ridf_classes if rc != dom_rc]
        faults.append(
            RhymeFault(
                fault_type=RhymeFaultType.SINAD_RIDF,
                name_ar="سناد الردف",
                name_en="Sinad al-Ridf",
                verse_indices=sinad_ridf_indices,
                description_ar="عدم التزام الردف أو الخلط بين ردف الألف وردف الواو والياء.",
                description_en="Inconsistent Ridf presence or mixing Alif Ridf with Waw/Yeh Ridf.",
                severity="error",
            )
        )

    # 3b. سناد التأسيس (Sinad al-Ta'sees)
    tasees_flags = [(idx, bool(q.tasees)) for idx, q in valid]
    tasees_counts: Counter[bool] = Counter(tf for _, tf in tasees_flags)
    if len(tasees_counts) > 1:
        dom_tf = tasees_counts.most_common(1)[0][0]
        sinad_tasees_indices = [idx for idx, tf in tasees_flags if tf != dom_tf]
        faults.append(
            RhymeFault(
                fault_type=RhymeFaultType.SINAD_TASEES,
                name_ar="سناد التأسيس",
                name_en="Sinad al-Ta'sees",
                verse_indices=sinad_tasees_indices,
                description_ar="الجمع بين قوافٍ مؤسسة بألف التأسيس وأخرى غير مؤسسة.",
                description_en="Mixing Ta'sees-bearing rhymes with rhymes lacking Ta'sees.",
                severity="error",
            )
        )

    # 3c. سناد الحذو (Sinad al-Hadhw): fatha vs damma/kasra within same Ridf class
    # (only when Ridf class itself is consistent, avoiding double-reporting with Sinad al-Ridf)
    if len(ridf_counts) == 1:
        hadhw_entries = [(idx, q.hadhw) for idx, q in valid if q.ridf and q.hadhw]
        if len(hadhw_entries) >= 2:
            hadhw_groups = [
                (idx, "fatha" if h == "fatha" else "high") for idx, h in hadhw_entries
            ]
            hg_counts: Counter[str] = Counter(g for _, g in hadhw_groups)
            if len(hg_counts) > 1:
                dom_hg = hg_counts.most_common(1)[0][0]
                sinad_hadhw_indices = [idx for idx, g in hadhw_groups if g != dom_hg]
                faults.append(
                    RhymeFault(
                        fault_type=RhymeFaultType.SINAD_HADHW,
                        name_ar="سناد الحذو",
                        name_en="Sinad al-Hadhw",
                        verse_indices=sinad_hadhw_indices,
                        description_ar="اختلاف حركة الحذو (ما قبل الردف) بين الفتحة والضمة أو الكسرة.",
                        description_en="Hadhw (vowel preceding Ridf) mixes fatha with damma/kasra.",
                        severity="error",
                    )
                )

    # 3d. سناد الإشباع (Sinad al-Ishba'): Dakhil vowel mismatch among Ta'sees verses
    ishba_entries = [(idx, q.ishba) for idx, q in valid if q.tasees and q.ishba]
    if len(ishba_entries) >= 2:
        ishba_counts: Counter[str] = Counter(h for _, h in ishba_entries)
        if len(ishba_counts) > 1:
            dom_ish = ishba_counts.most_common(1)[0][0]
            sinad_ishba_indices = [idx for idx, h in ishba_entries if h != dom_ish]
            has_fatha_clash = any({dom_ish, h} != {"damma", "kasra"} for _, h in ishba_entries if h != dom_ish)
            faults.append(
                RhymeFault(
                    fault_type=RhymeFaultType.SINAD_ISHBA,
                    name_ar="سناد الإشباع",
                    name_en="Sinad al-Ishba'",
                    verse_indices=sinad_ishba_indices,
                    description_ar="اختلاف حركة الدخيل (الإشباع) بين أبيات القافية المؤسسة.",
                    description_en="Ishba' (vowel on Dakhil) varies across Ta'sees rhymes.",
                    severity="error" if has_fatha_clash else "warning",
                )
            )

    # 3e. سناد التوجيه (Sinad al-Tawjih): pre-Rawi vowel mismatch in Muqayyad verses
    tawjih_entries = [(idx, q.tawjih) for idx, q in valid if q.is_muqayyad and q.tawjih]
    if len(tawjih_entries) >= 2:
        tawjih_counts: Counter[str] = Counter(t for _, t in tawjih_entries)
        if len(tawjih_counts) > 1:
            dom_tw = tawjih_counts.most_common(1)[0][0]
            sinad_tawjih_indices = [idx for idx, t in tawjih_entries if t != dom_tw]
            faults.append(
                RhymeFault(
                    fault_type=RhymeFaultType.SINAD_TAWJIH,
                    name_ar="سناد التوجيه",
                    name_en="Sinad al-Tawjih",
                    verse_indices=sinad_tawjih_indices,
                    description_ar="اختلاف حركة ما قبل الروي المقيد (التوجيه) بين الأبيات.",
                    description_en="Tawjih (vowel preceding quiescent Rawi) varies across verses.",
                    severity="warning",
                )
            )

    # 4. الإيطاء (Al-Ita'): repeated rhyme word within < 7 verses (lexical warning; homonyms excluded)
    last_seen_word: dict[str, int] = {}
    ita_indices_set: set[int] = set()
    for idx, q in valid:
        words = q.qafiyah_text.strip().split()
        if not words:
            continue
        rhyme_word_plain = strip_tashkeel(strip_punctuation(strip_tatweel(words[-1])))
        if not rhyme_word_plain:
            continue
        prev_idx = last_seen_word.get(rhyme_word_plain)
        if prev_idx is not None and (idx - prev_idx) < 7:
            ita_indices_set.add(prev_idx)
            ita_indices_set.add(idx)
        last_seen_word[rhyme_word_plain] = idx

    if ita_indices_set:
        faults.append(
            RhymeFault(
                fault_type=RhymeFaultType.ITA,
                name_ar="الإيطاء",
                name_en="Al-Ita'",
                verse_indices=sorted(ita_indices_set),
                description_ar="تكرار كلمة القافية بلفظها قبل مرور سبعة أبيات (يُستثنى اختلاف المعنى / الجناس).",
                description_en="Final rhyme word repeated within 7 verses (warning: valid if homonymous / Jinas).",
                severity="warning",
            )
        )

    return faults

Domain Models & Enums

pyarud.models.analysis.VerseAnalysis dataclass

Full prosodic analysis of an entire poetic verse (Bait).

Source code in pyarud/models/analysis.py
@dataclass(slots=True)
class VerseAnalysis:
    """Full prosodic analysis of an entire poetic verse (Bait)."""

    verse_index: int = 0
    sadr_text: str = ""
    ajuz_text: str = ""
    meter_key: MeterKey | str = MeterKey.UNKNOWN
    meter_name_ar: str = "غير معروف"
    meter_name_en: str = "Unknown"
    bahr_type: MeterVariation | str = MeterVariation.TAM
    standard_pattern: str = ""
    score: float = 0.0
    sadr: ShatrAnalysis | None = None
    ajuz: ShatrAnalysis | None = None
    qafiyah: QafiyahAnalysis | None = None
    is_valid: bool = True
    errors: list[str] = field(default_factory=list)
    alternatives: list[MeterMatchCandidate] = field(default_factory=list)
    is_tasri: bool = False

    @property
    def meter(self) -> str:
        """Alias for meter_key for ergonomic access."""
        return str(self.meter_key)

    @property
    def is_sound(self) -> bool:
        """Alias for is_valid."""
        return self.is_valid

    def __bool__(self) -> bool:
        """Truthiness of the verse evaluation: True iff the verse is metrically valid."""
        return self.is_valid

    def __str__(self) -> str:
        status = "صحيح" if self.is_valid else "مكسور"
        return f"[{self.meter_name_ar} ({self.bahr_type})] {self.sadr_text} ... {self.ajuz_text} ({status})"

    def to_dict(self) -> dict[str, Any]:
        """Convert entire verse analysis to a deeply nested JSON-serializable dictionary."""
        return {
            "verse_index": self.verse_index,
            "sadr_text": self.sadr_text,
            "ajuz_text": self.ajuz_text,
            "meter_key": str(self.meter_key),
            "meter_name_ar": self.meter_name_ar,
            "meter_name_en": self.meter_name_en,
            "bahr_type": str(self.bahr_type),
            "standard_pattern": self.standard_pattern,
            "score": self.score,
            "is_valid": self.is_valid,
            "is_tasri": self.is_tasri,
            "errors": list(self.errors),
            "sadr": self.sadr.to_dict() if self.sadr is not None else None,
            "ajuz": self.ajuz.to_dict() if self.ajuz is not None else None,
            "qafiyah": self.qafiyah.to_dict() if self.qafiyah is not None else None,
            "alternatives": [c.to_dict() for c in self.alternatives],
        }

    def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
        """Serialize verse analysis to a UTF-8 JSON string."""
        return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

is_sound property

Alias for is_valid.

meter property

Alias for meter_key for ergonomic access.

__bool__()

Truthiness of the verse evaluation: True iff the verse is metrically valid.

Source code in pyarud/models/analysis.py
def __bool__(self) -> bool:
    """Truthiness of the verse evaluation: True iff the verse is metrically valid."""
    return self.is_valid

to_dict()

Convert entire verse analysis to a deeply nested JSON-serializable dictionary.

Source code in pyarud/models/analysis.py
def to_dict(self) -> dict[str, Any]:
    """Convert entire verse analysis to a deeply nested JSON-serializable dictionary."""
    return {
        "verse_index": self.verse_index,
        "sadr_text": self.sadr_text,
        "ajuz_text": self.ajuz_text,
        "meter_key": str(self.meter_key),
        "meter_name_ar": self.meter_name_ar,
        "meter_name_en": self.meter_name_en,
        "bahr_type": str(self.bahr_type),
        "standard_pattern": self.standard_pattern,
        "score": self.score,
        "is_valid": self.is_valid,
        "is_tasri": self.is_tasri,
        "errors": list(self.errors),
        "sadr": self.sadr.to_dict() if self.sadr is not None else None,
        "ajuz": self.ajuz.to_dict() if self.ajuz is not None else None,
        "qafiyah": self.qafiyah.to_dict() if self.qafiyah is not None else None,
        "alternatives": [c.to_dict() for c in self.alternatives],
    }

to_json(*, indent=2, ensure_ascii=False)

Serialize verse analysis to a UTF-8 JSON string.

Source code in pyarud/models/analysis.py
def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
    """Serialize verse analysis to a UTF-8 JSON string."""
    return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

pyarud.models.analysis.PoemAnalysis dataclass

Comprehensive prosodic and metric analysis of an entire multi-verse poem.

Source code in pyarud/models/analysis.py
@dataclass(slots=True)
class PoemAnalysis:
    """Comprehensive prosodic and metric analysis of an entire multi-verse poem."""

    meter_key: MeterKey | str = MeterKey.UNKNOWN
    meter_name_ar: str = "غير محدد"
    meter_name_en: str = "Unknown"
    bahr_type: MeterVariation | str = MeterVariation.UNKNOWN
    verses: list[VerseAnalysis] = field(default_factory=list)
    average_score: float = 0.0
    is_homogeneous: bool = True
    dominant_rawi: str | None = None
    total_verses: int = 0
    valid_verses_count: int = 0
    rhyme_faults: list[RhymeFault] = field(default_factory=list)
    has_tasri: bool = False

    def __iter__(self) -> Iterator[VerseAnalysis]:
        """Iterate over the verses in the poem."""
        return iter(self.verses)

    def __len__(self) -> int:
        """Total number of verses in the poem."""
        return len(self.verses)

    def __getitem__(self, index: int) -> VerseAnalysis:
        """Access a verse analysis by index."""
        return self.verses[index]

    def __bool__(self) -> bool:
        """True if the poem has analyzed verses and a recognized meter."""
        return bool(self.verses) and self.meter_key != MeterKey.UNKNOWN

    def __str__(self) -> str:
        return (
            f"Poem({self.meter_name_ar}, {self.total_verses} verses, "
            f"{self.valid_verses_count} valid, avg_score={self.average_score:.2f})"
        )

    def to_dict(self) -> dict[str, Any]:
        """Convert entire poem analysis to a JSON-serializable dictionary."""
        return {
            "meter_key": str(self.meter_key),
            "meter_name_ar": self.meter_name_ar,
            "meter_name_en": self.meter_name_en,
            "bahr_type": str(self.bahr_type),
            "average_score": self.average_score,
            "is_homogeneous": self.is_homogeneous,
            "dominant_rawi": self.dominant_rawi,
            "total_verses": self.total_verses,
            "valid_verses_count": self.valid_verses_count,
            "has_tasri": self.has_tasri,
            "rhyme_faults": [f.to_dict() for f in self.rhyme_faults],
            "verses": [v.to_dict() for v in self.verses],
        }

    def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
        """Serialize poem analysis to a UTF-8 JSON string."""
        return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

__bool__()

True if the poem has analyzed verses and a recognized meter.

Source code in pyarud/models/analysis.py
def __bool__(self) -> bool:
    """True if the poem has analyzed verses and a recognized meter."""
    return bool(self.verses) and self.meter_key != MeterKey.UNKNOWN

__getitem__(index)

Access a verse analysis by index.

Source code in pyarud/models/analysis.py
def __getitem__(self, index: int) -> VerseAnalysis:
    """Access a verse analysis by index."""
    return self.verses[index]

__iter__()

Iterate over the verses in the poem.

Source code in pyarud/models/analysis.py
def __iter__(self) -> Iterator[VerseAnalysis]:
    """Iterate over the verses in the poem."""
    return iter(self.verses)

__len__()

Total number of verses in the poem.

Source code in pyarud/models/analysis.py
def __len__(self) -> int:
    """Total number of verses in the poem."""
    return len(self.verses)

to_dict()

Convert entire poem analysis to a JSON-serializable dictionary.

Source code in pyarud/models/analysis.py
def to_dict(self) -> dict[str, Any]:
    """Convert entire poem analysis to a JSON-serializable dictionary."""
    return {
        "meter_key": str(self.meter_key),
        "meter_name_ar": self.meter_name_ar,
        "meter_name_en": self.meter_name_en,
        "bahr_type": str(self.bahr_type),
        "average_score": self.average_score,
        "is_homogeneous": self.is_homogeneous,
        "dominant_rawi": self.dominant_rawi,
        "total_verses": self.total_verses,
        "valid_verses_count": self.valid_verses_count,
        "has_tasri": self.has_tasri,
        "rhyme_faults": [f.to_dict() for f in self.rhyme_faults],
        "verses": [v.to_dict() for v in self.verses],
    }

to_json(*, indent=2, ensure_ascii=False)

Serialize poem analysis to a UTF-8 JSON string.

Source code in pyarud/models/analysis.py
def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
    """Serialize poem analysis to a UTF-8 JSON string."""
    return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

pyarud.models.analysis.ShatrAnalysis dataclass

Prosodic analysis of a single hemistich (Sadr or Ajuz).

Source code in pyarud/models/analysis.py
@dataclass(slots=True)
class ShatrAnalysis:
    """Prosodic analysis of a single hemistich (Sadr or Ajuz)."""

    text: str
    arudi_text: str
    pattern: str
    feet: list[FootAnalysis] = field(default_factory=list)
    score: float = 1.0
    is_valid: bool = True

    def __iter__(self) -> Iterator[FootAnalysis]:
        """Iterate over individual feet within this hemistich."""
        return iter(self.feet)

    def __len__(self) -> int:
        """Number of feet in this hemistich."""
        return len(self.feet)

    def __getitem__(self, index: int) -> FootAnalysis:
        """Access foot analysis by index."""
        return self.feet[index]

    def __bool__(self) -> bool:
        return bool(self.text)

    def to_dict(self) -> dict[str, Any]:
        """Convert shatr analysis to a JSON-serializable dictionary."""
        return {
            "text": self.text,
            "arudi_text": self.arudi_text,
            "pattern": self.pattern,
            "score": self.score,
            "is_valid": self.is_valid,
            "feet": [f.to_dict() for f in self.feet],
        }

    def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
        """Serialize shatr analysis to a UTF-8 JSON string."""
        return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

__getitem__(index)

Access foot analysis by index.

Source code in pyarud/models/analysis.py
def __getitem__(self, index: int) -> FootAnalysis:
    """Access foot analysis by index."""
    return self.feet[index]

__iter__()

Iterate over individual feet within this hemistich.

Source code in pyarud/models/analysis.py
def __iter__(self) -> Iterator[FootAnalysis]:
    """Iterate over individual feet within this hemistich."""
    return iter(self.feet)

__len__()

Number of feet in this hemistich.

Source code in pyarud/models/analysis.py
def __len__(self) -> int:
    """Number of feet in this hemistich."""
    return len(self.feet)

to_dict()

Convert shatr analysis to a JSON-serializable dictionary.

Source code in pyarud/models/analysis.py
def to_dict(self) -> dict[str, Any]:
    """Convert shatr analysis to a JSON-serializable dictionary."""
    return {
        "text": self.text,
        "arudi_text": self.arudi_text,
        "pattern": self.pattern,
        "score": self.score,
        "is_valid": self.is_valid,
        "feet": [f.to_dict() for f in self.feet],
    }

to_json(*, indent=2, ensure_ascii=False)

Serialize shatr analysis to a UTF-8 JSON string.

Source code in pyarud/models/analysis.py
def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
    """Serialize shatr analysis to a UTF-8 JSON string."""
    return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

pyarud.models.analysis.FootAnalysis dataclass

Detailed metric analysis of a single poetic foot (Taf'eela).

Source code in pyarud/models/analysis.py
@dataclass(slots=True)
class FootAnalysis:
    """Detailed metric analysis of a single poetic foot (Taf'eela)."""

    foot_index: int
    expected_pattern: str
    actual_segment: str
    base_tafeela: str = ""
    actual_tafeela: str = ""
    zihaf_name_ar: str = "سالمة"
    zihaf_name_en: str = "Salim"
    score: float = 1.0
    status: FootStatus | str = FootStatus.OK
    arudi_text: str = ""
    span: tuple[int, int] | None = None

    @property
    def is_valid(self) -> bool:
        """True if the foot matched standard or permitted Zihaf/'Ilal variations."""
        return self.status == FootStatus.OK

    def to_dict(self) -> dict[str, Any]:
        """Convert foot analysis to a JSON-serializable dictionary."""
        return {
            "foot_index": self.foot_index,
            "expected_pattern": self.expected_pattern,
            "actual_segment": self.actual_segment,
            "base_tafeela": self.base_tafeela,
            "actual_tafeela": self.actual_tafeela,
            "zihaf_name_ar": self.zihaf_name_ar,
            "zihaf_name_en": self.zihaf_name_en,
            "score": self.score,
            "status": str(self.status),
            "is_valid": self.is_valid,
            "arudi_text": self.arudi_text,
            "span": list(self.span) if self.span is not None else None,
        }

    def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
        """Serialize foot analysis to a UTF-8 JSON string."""
        return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

    def __bool__(self) -> bool:
        return self.is_valid

    def __str__(self) -> str:
        name = self.actual_tafeela or self.base_tafeela or "تفعيلة"
        return f"{name} ({self.actual_segment}) - {self.zihaf_name_ar}"

is_valid property

True if the foot matched standard or permitted Zihaf/'Ilal variations.

to_dict()

Convert foot analysis to a JSON-serializable dictionary.

Source code in pyarud/models/analysis.py
def to_dict(self) -> dict[str, Any]:
    """Convert foot analysis to a JSON-serializable dictionary."""
    return {
        "foot_index": self.foot_index,
        "expected_pattern": self.expected_pattern,
        "actual_segment": self.actual_segment,
        "base_tafeela": self.base_tafeela,
        "actual_tafeela": self.actual_tafeela,
        "zihaf_name_ar": self.zihaf_name_ar,
        "zihaf_name_en": self.zihaf_name_en,
        "score": self.score,
        "status": str(self.status),
        "is_valid": self.is_valid,
        "arudi_text": self.arudi_text,
        "span": list(self.span) if self.span is not None else None,
    }

to_json(*, indent=2, ensure_ascii=False)

Serialize foot analysis to a UTF-8 JSON string.

Source code in pyarud/models/analysis.py
def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
    """Serialize foot analysis to a UTF-8 JSON string."""
    return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

pyarud.models.analysis.QafiyahAnalysis dataclass

Comprehensive Rhyme (علم القافية) extraction and classification.

Source code in pyarud/models/analysis.py
@dataclass(slots=True)
class QafiyahAnalysis:
    """Comprehensive Rhyme (علم القافية) extraction and classification."""

    rawi: str = ""
    rawi_haraka: str = ""
    wasl: str | None = None
    khuruj: str | None = None
    ridf: str | None = None
    tasees: str | None = None
    dakhil: str | None = None
    qafiyah_text: str = ""
    qafiyah_pattern: str = ""
    qafiyah_type_ar: str = "المتواتر"
    qafiyah_type_en: str = "Al-Mutawatir"
    rhyme_classification: RhymeType | str = RhymeType.MUTLAQAH
    majra: str = ""
    nafadh: str = ""
    hadhw: str = ""
    ishba: str = ""
    rass: str = ""
    tawjih: str = ""
    structural_type_ar: str = ""
    structural_type_en: str = ""
    qafiyah_arudi: str = ""
    is_muqayyad: bool = False

    def to_dict(self) -> dict[str, Any]:
        """Convert rhyme analysis to a JSON-serializable dictionary."""
        return {
            "rawi": self.rawi,
            "rawi_haraka": self.rawi_haraka,
            "wasl": self.wasl,
            "khuruj": self.khuruj,
            "ridf": self.ridf,
            "tasees": self.tasees,
            "dakhil": self.dakhil,
            "qafiyah_text": self.qafiyah_text,
            "qafiyah_arudi": self.qafiyah_arudi,
            "qafiyah_pattern": self.qafiyah_pattern,
            "qafiyah_type_ar": self.qafiyah_type_ar,
            "qafiyah_type_en": self.qafiyah_type_en,
            "rhyme_classification": str(self.rhyme_classification),
            "is_muqayyad": self.is_muqayyad,
            "majra": self.majra,
            "nafadh": self.nafadh,
            "hadhw": self.hadhw,
            "ishba": self.ishba,
            "rass": self.rass,
            "tawjih": self.tawjih,
            "structural_type_ar": self.structural_type_ar,
            "structural_type_en": self.structural_type_en,
        }

    def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
        """Serialize rhyme analysis to a UTF-8 JSON string."""
        return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

    def __bool__(self) -> bool:
        return bool(self.rawi)

    def __str__(self) -> str:
        return f"الروي: {self.rawi} ({self.rawi_haraka}) | القافية: {self.qafiyah_type_ar}"

to_dict()

Convert rhyme analysis to a JSON-serializable dictionary.

Source code in pyarud/models/analysis.py
def to_dict(self) -> dict[str, Any]:
    """Convert rhyme analysis to a JSON-serializable dictionary."""
    return {
        "rawi": self.rawi,
        "rawi_haraka": self.rawi_haraka,
        "wasl": self.wasl,
        "khuruj": self.khuruj,
        "ridf": self.ridf,
        "tasees": self.tasees,
        "dakhil": self.dakhil,
        "qafiyah_text": self.qafiyah_text,
        "qafiyah_arudi": self.qafiyah_arudi,
        "qafiyah_pattern": self.qafiyah_pattern,
        "qafiyah_type_ar": self.qafiyah_type_ar,
        "qafiyah_type_en": self.qafiyah_type_en,
        "rhyme_classification": str(self.rhyme_classification),
        "is_muqayyad": self.is_muqayyad,
        "majra": self.majra,
        "nafadh": self.nafadh,
        "hadhw": self.hadhw,
        "ishba": self.ishba,
        "rass": self.rass,
        "tawjih": self.tawjih,
        "structural_type_ar": self.structural_type_ar,
        "structural_type_en": self.structural_type_en,
    }

to_json(*, indent=2, ensure_ascii=False)

Serialize rhyme analysis to a UTF-8 JSON string.

Source code in pyarud/models/analysis.py
def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
    """Serialize rhyme analysis to a UTF-8 JSON string."""
    return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

pyarud.models.analysis.RhymeFault dataclass

Represents a poem-level classical rhyme fault (عيب من عيوب القافية).

Source code in pyarud/models/analysis.py
@dataclass(slots=True)
class RhymeFault:
    """Represents a poem-level classical rhyme fault (عيب من عيوب القافية)."""

    fault_type: RhymeFaultType | str
    name_ar: str
    name_en: str
    verse_indices: list[int] = field(default_factory=list)
    description_ar: str = ""
    description_en: str = ""
    severity: str = "error"  # 'error' or 'warning'

    def to_dict(self) -> dict[str, Any]:
        """Convert rhyme fault to a JSON-serializable dictionary."""
        return {
            "fault_type": str(self.fault_type),
            "name_ar": self.name_ar,
            "name_en": self.name_en,
            "verse_indices": list(self.verse_indices),
            "description_ar": self.description_ar,
            "description_en": self.description_en,
            "severity": self.severity,
        }

    def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
        """Serialize rhyme fault to a UTF-8 JSON string."""
        return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

    def __str__(self) -> str:
        indices = ", ".join(str(i + 1) for i in self.verse_indices)
        return f"[{self.severity.upper()}] {self.name_ar} ({self.name_en}) — أبيات: {indices}"

to_dict()

Convert rhyme fault to a JSON-serializable dictionary.

Source code in pyarud/models/analysis.py
def to_dict(self) -> dict[str, Any]:
    """Convert rhyme fault to a JSON-serializable dictionary."""
    return {
        "fault_type": str(self.fault_type),
        "name_ar": self.name_ar,
        "name_en": self.name_en,
        "verse_indices": list(self.verse_indices),
        "description_ar": self.description_ar,
        "description_en": self.description_en,
        "severity": self.severity,
    }

to_json(*, indent=2, ensure_ascii=False)

Serialize rhyme fault to a UTF-8 JSON string.

Source code in pyarud/models/analysis.py
def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
    """Serialize rhyme fault to a UTF-8 JSON string."""
    return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

pyarud.models.analysis.MeterMatchCandidate dataclass

Candidate meter match used for disambiguation and alternative reporting.

Source code in pyarud/models/analysis.py
@dataclass(slots=True)
class MeterMatchCandidate:
    """Candidate meter match used for disambiguation and alternative reporting."""

    meter_key: str
    meter_name_ar: str = ""
    meter_name_en: str = ""
    bahr_type: MeterVariation | str = MeterVariation.TAM
    score: float = 0.0
    is_valid_pair: bool = True
    tier: MeterTier | str = MeterTier.CLASSICAL
    is_tasri: bool = False
    zihaf_cost: int = 0
    valid_pair: bool | None = None
    sadr_match: dict[str, Any] | None = None
    ajuz_match: dict[str, Any] | None = None
    sadr_input_pattern: str = ""
    ajuz_input_pattern: str = ""

    def __post_init__(self) -> None:
        if self.valid_pair is not None:
            self.is_valid_pair = self.valid_pair
        else:
            self.valid_pair = self.is_valid_pair

    def to_dict(self) -> dict[str, Any]:
        """Convert match candidate to a JSON-serializable dictionary."""
        return {
            "meter_key": self.meter_key,
            "meter_name_ar": self.meter_name_ar,
            "meter_name_en": self.meter_name_en,
            "bahr_type": str(self.bahr_type),
            "tier": str(self.tier),
            "score": self.score,
            "is_valid_pair": self.is_valid_pair,
            "is_tasri": self.is_tasri,
            "zihaf_cost": self.zihaf_cost,
            "sadr_input_pattern": self.sadr_input_pattern,
            "ajuz_input_pattern": self.ajuz_input_pattern,
        }

    def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
        """Serialize match candidate to a UTF-8 JSON string."""
        return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

to_dict()

Convert match candidate to a JSON-serializable dictionary.

Source code in pyarud/models/analysis.py
def to_dict(self) -> dict[str, Any]:
    """Convert match candidate to a JSON-serializable dictionary."""
    return {
        "meter_key": self.meter_key,
        "meter_name_ar": self.meter_name_ar,
        "meter_name_en": self.meter_name_en,
        "bahr_type": str(self.bahr_type),
        "tier": str(self.tier),
        "score": self.score,
        "is_valid_pair": self.is_valid_pair,
        "is_tasri": self.is_tasri,
        "zihaf_cost": self.zihaf_cost,
        "sadr_input_pattern": self.sadr_input_pattern,
        "ajuz_input_pattern": self.ajuz_input_pattern,
    }

to_json(*, indent=2, ensure_ascii=False)

Serialize match candidate to a UTF-8 JSON string.

Source code in pyarud/models/analysis.py
def to_json(self, *, indent: int | None = 2, ensure_ascii: bool = False) -> str:
    """Serialize match candidate to a UTF-8 JSON string."""
    return _dump_json(self.to_dict(), indent=indent, ensure_ascii=ensure_ascii)

pyarud.models.enums.MeterKey

Bases: StrEnum

Canonical identifier keys for the 16 classical Arabic meters.

Source code in pyarud/models/enums.py
class MeterKey(StrEnum):
    """Canonical identifier keys for the 16 classical Arabic meters."""

    TAWEEL = "taweel"
    MADEED = "madeed"
    BASEET = "baseet"
    WAFER = "wafer"
    KAMEL = "kamel"
    HAZAJ = "hazaj"
    RAJAZ = "rajaz"
    RAMAL = "ramal"
    SAREE = "saree"
    MUNSAREH = "munsareh"
    KHAFEEF = "khafeef"
    MUDHARE = "mudhare"
    MUQTADHEB = "muqtadheb"
    MUJTATH = "mujtath"
    MUTAKAREB = "mutakareb"
    MUTADARAK = "mutadarak"
    UNKNOWN = "unknown"

pyarud.models.enums.MeterVariation

Bases: StrEnum

Sub-meter metric length and structure variations.

Source code in pyarud/models/enums.py
class MeterVariation(StrEnum):
    """Sub-meter metric length and structure variations."""

    TAM = "tam"
    MAJZOO = "majzoo"
    MASHTOOR = "mashtoor"
    MANHOOK = "manhook"
    MUKHALLA = "mukhalla"
    MUHMAL = "muhmal"
    TAFEELA = "tafeela"
    CUSTOM = "custom"
    UNKNOWN = "unknown"

pyarud.models.enums.MeterTier

Bases: StrEnum

Classification tier controlling meter provenance and tie-break precedence.

Source code in pyarud/models/enums.py
class MeterTier(StrEnum):
    """Classification tier controlling meter provenance and tie-break precedence."""

    CLASSICAL = "classical"
    MUHMAL = "muhmal"
    CUSTOM = "custom"

pyarud.models.enums.FootStatus

Bases: StrEnum

Diagnostic scansion status of an individual metric foot (Taf'eela).

Source code in pyarud/models/enums.py
class FootStatus(StrEnum):
    """Diagnostic scansion status of an individual metric foot (Taf'eela)."""

    OK = "ok"
    BROKEN = "broken"
    MISSING = "missing"
    EXTRA_BITS = "extra_bits"

pyarud.models.enums.RhymeType

Bases: StrEnum

Classical Arabic rhyme movement type (حركة القافية).

Source code in pyarud/models/enums.py
class RhymeType(StrEnum):
    """Classical Arabic rhyme movement type (حركة القافية)."""

    MUTLAQAH = "mutlaqah"  # المطلقة (Vocalized Rawi)
    MUQAYYADAH = "muqayyadah"  # المقيدة (Sakin Rawi)

pyarud.models.enums.RhymeFaultType

Bases: StrEnum

Classical Arabic rhyme faults (عيوب القافية).

Source code in pyarud/models/enums.py
class RhymeFaultType(StrEnum):
    """Classical Arabic rhyme faults (عيوب القافية)."""

    IQWA = "iqwa"  # الإقواء
    ISRAF = "israf"  # الإصراف
    IKFA = "ikfa"  # الإكفاء
    IJAZAH = "ijazah"  # الإجازة
    SINAD_RIDF = "sinad_ridf"  # سناد الردف
    SINAD_TASEES = "sinad_tasees"  # سناد التأسيس
    SINAD_HADHW = "sinad_hadhw"  # سناد الحذو
    SINAD_ISHBA = "sinad_ishba"  # سناد الإشباع
    SINAD_TAWJIH = "sinad_tawjih"  # سناد التوجيه
    ITA = "ita"  # الإيطاء

Exceptions

pyarud.exceptions

Custom Exception Hierarchy for PyArud.

Defines domain-specific errors for Arabic prosody analysis, metric verification, custom meter specifications, and text normalization failures.

InvalidMeterSpecError

Bases: PyArudError

Raised when a custom or built-in meter, tafeela, or prosodic rule specification is invalid.

Source code in pyarud/exceptions.py
class InvalidMeterSpecError(PyArudError):
    """Raised when a custom or built-in meter, tafeela, or prosodic rule specification is invalid."""

InvalidVerseError

Bases: PyArudError

Raised when an input verse cannot be parsed or is syntactically malformed.

Source code in pyarud/exceptions.py
class InvalidVerseError(PyArudError):
    """Raised when an input verse cannot be parsed or is syntactically malformed."""

MeterNotFoundError

Bases: PyArudError

Raised when a specified or queried meter name is not recognized.

Source code in pyarud/exceptions.py
class MeterNotFoundError(PyArudError):
    """Raised when a specified or queried meter name is not recognized."""

ProsodyScansionError

Bases: PyArudError

Raised when phonetic or metric scansion encounters an unresolvable error.

Source code in pyarud/exceptions.py
class ProsodyScansionError(PyArudError):
    """Raised when phonetic or metric scansion encounters an unresolvable error."""

PyArudError

Bases: Exception

Base class for all exceptions raised by the PyArud library.

Source code in pyarud/exceptions.py
class PyArudError(Exception):
    """Base class for all exceptions raised by the PyArud library."""

TashkeelError

Bases: PyArudError

Raised when Arabic poetic text lacks mandatory diacritics (tashkeel).

Source code in pyarud/exceptions.py
class TashkeelError(PyArudError):
    """Raised when Arabic poetic text lacks mandatory diacritics (tashkeel)."""