The generator is a Sanskrit word form generator that derives surface forms from underlying roots and stems by applying Paninian (Ashtadhyayi) grammar rules. It lives on the generator branch and is not yet merged to master.
Branch note: All generator development should happen on the
generatorbranch. See the Active Branches section of CLAUDE.md.
- Conceptual Overview
- Module Structure
- Core Objects
- The Prakriya Engine
- Sutras (Rules)
- The YAML Rule DSL
- Domains
- Rule Priority
- Worked Example
- CLI and Tests
Sanskrit grammar does not simply look words up in a table — it derives them through a sequence of rule applications. Panini's Ashtadhyayi defines roughly 4000 such rules (sutras). The generator models this derivation process:
Input: prākriti (root/stem) + pratyaya (suffix)
↓
Prakriya engine applies sutras in sequence
↓
Output: derived pada (inflected word form)
For example, to generate the nominative singular of rāma:
- Input:
rAma(prātipadika) +su(nominative singular vibhakti suffix) - Sutras fire to drop the anubandha
u~fromsu, then handle the finala+sphonology - Output:
rAmaH
The process is recorded in a derivation tree (PrakriyaTree) that shows every rule that fired, in order — analogous to Panini's "prakriya" (derivational procedure).
sanskrit_parser/generator/
├── paninian_object.py # Base class for all objects in a derivation
├── dhatu.py # Dhatu (verb root) class + predefined roots
├── pratipadika.py # Pratipadika (nominal stem) class + predefined stems
├── pratyaya.py # Pratyaya (suffix) class + predefined suffixes (sup, tiN, krt, ...)
│
├── sutra.py # Sutra base class, LRSutra, GlobalDomains
├── maheshvara.py # Pratyahara/savarna checks via Maheshvara sutras
├── paribhasha.py # Meta-rules (paribhāṣā)
├── operations.py # Phonological operation helpers (dīrgha, etc.)
│
├── prakriya.py # PrakriyaVakya, PrakriyaBase, HierPrakriya, PrakriyaNode, PrakriyaTree
├── antaranga_prakriya.py # AntarangaPrakriya — the current default engine
├── prakriya_factory.py # PrakriyaFactory — selects which engine to instantiate
│
├── sutras.yaml # ac-sandhi and general sutra definitions (YAML DSL)
├── sutras_antaranga.yaml # Sutra set for AntarangaPrakriya engine
├── sutras_hier.yaml # Sutra set for HierPrakriya engine
├── sutra_domains.yaml # Domain-level sutra definitions
├── sutras_yaml.py # SutraFactory — loads a YAML file into a sutra list
├── process_yaml.py # Converts raw YAML dicts into LRSutra objects
│
├── cmd_line.py # CLI entry point; generate_vibhakti() helper
└── test/ # pytest test suite (see below)
All objects that pass through a derivation derive from PaninianObject.
Extends SanskritObject (from base/sanskrit_base.py) with:
- Tags (
self.tags): a list of grammatical labels ("DAtu","aNga","pada","sup","tiN", etc.). Tags encode grammatical identity and are used by sutra conditions. disabled_sutras: list of sutra ids that have already been applied to this object and must not re-fire (enforces lakṣye lakṣaṇaṃ sakṛdeva pravartate).inPrakriya: flag indicating the object is mid-derivation (not yet a final pada).
Key methods: hasTag(), setTag(), deleteTag(), isPada(), join_objects().
join_objects() assembles a list of component objects into a single PaninianObject, propagating tags according to Paninian rules (e.g., 1.4.14 suptiṇantaṃ padam, 1.4.13 yasmāt pratyayavidhis tad ādi pratyaye'ṅgam).
Represents a verb root. Carries:
- Its (
self.its): anubandhas (indicatory letters like"R","Y","qu","~a") that determine which rules apply but are not pronounced in the final form. - Tag
"DAtu"and"aNga"set automatically.
Predefined roots are module-level constants: BU, as_dhatu, iR, guhU, sTA, etc.
Represents a nominal stem. Carries:
linga: grammatical gender ("pum","strI","napum"), set as a tag.- Tag
"prAtipadika"set automatically.
Predefined stems: rAma, kavi, hari, pitf, rAjan, mahat, etc.
Represents a suffix. Carries:
- Its (
self.its): anubandhas (e.g.,"p"intip,"k"inktvA). - Other tags: grammatical identity of the suffix (
"sup","tiN","sArvaDAtuka","ArDaDAtuka", etc.).
Predefined suffixes span:
- sup (nominal case endings):
su,O,jas,am,Ow,Sas,wA,ByAm,Bis,Ne,Nasi,Nas,os,Am,Ni— organised assups[8][3](8 vibhaktis × 3 vacanas) - tiN (verbal endings):
tip,sip, ... - kṛt suffixes:
tfc,ktvA,kta,Ryat,GaY,Ric, ... - taddhita suffixes:
yat_t,aR_t, ... - strī pratyayas:
NIp,NIz,Ap - nipātas/upasargas:
AN,pra,upa,ud,ati
The engine takes a PrakriyaVakya (a sequence of PaninianObjects) and iteratively applies sutras until no more rules fire.
A thin wrapper around a list of PaninianObjects. Supports copy-on-write mutation (copy_replace_at, copy_insert_at) to enable branching for optional rules without mutating shared state.
Defines the interface: execute(), describe(), output(). Holds the PrakriyaTree (derivation history).
Implements the antaranga algorithm based on Patanjali's commentary: antaranga (more internal) operations take priority over bahiranga (more external) ones.
Priority is managed at two distinct levels:
Level 1 — Sutra-vs-sutra competition (multiple sutras trigger at the same window position): sutra_priority() uses the per-sutra bahiranga field from sutras_antaranga.yaml to pick the winner. Convention (lower wins):
0— saMjñā sutras1— prakṛti kāryas (modifications of stems)2— pratyaya kāryas (modifications of suffixes)- (default
99whenbahirangais unspecified)
Level 2 — Window-position priority (which window to examine first): the engine scans the sequence in a fixed order, giving pratyaya-adjacent windows highest priority. This ensures anga kāryas and anga-pratyaya sandhi fire before pada kāryas without a per-sutra bahiranga tag — which would be impractical since the same rule may operate on an anga in one context and a pada in another.
Execution loop:
- Start with the initial
PrakriyaVakya. - Slide a window of 2 adjacent objects across the sequence.
- Select the highest-priority window by scanning left to right in this order:
- Pratyaya-adjacent pairs (anga + pratyaya): highest priority; if multiple, leftmost wins
- Samāsa-adjacent pairs: next; if multiple, leftmost wins
- Any other pair (leftmost): fallback when neither pratyaya nor samāsa is present
- Collect all sutras whose
isTriggered(left, right)returns True at that window. - If multiple sutras trigger, apply
sutra_priority()to select the winner. - Call
winner.operate(left, right)→(out_left, out_right). - Call
winner.update(...)to set tags on outputs;winner.insert(...)to inject āgamas. - Record this step as a
PrakriyaNodein thePrakriyaTree. - If the rule is optional, branch: one child node has the rule applied, the current node has it disabled and continues without it.
- Repeat from step 2 on the new
PrakriyaVakyauntil nothing fires. - Leaf nodes of the tree are the final outputs.
An earlier engine variant. Handles hierarchical inputs (nested lists, used for āgama insertion) but uses a simpler priority model. Currently available but non-default.
p = PrakriyaFactory("AntarangaPrakriya", sutra_list, PrakriyaVakya([dhatu, pratyaya]))
p.execute()
outputs = p.output() # list of PrakriyaVakyas (one per derivation branch)Pass "HierPrakriya" to use the older engine. Any unrecognized name falls back to the default.
The tree records the full derivation history. Each PrakriyaNode stores:
inputs: thePrakriyaVakyabefore the rule firedoutputs: thePrakriyaVakyaaftersutra: the rule that firedindex: the window position where it firedother_sutras: rules that triggered but lost priority
p.describe() prints the full tree. p.dict() returns it as a JSON-serialisable dict.
Holds:
name: the sutra text (SanskritImmutableString)aps: Adhyaya.Pada.Sutra id string (e.g."6.1.77")_aps_num: integer encoding of the id used for ordering (e.g. tripadi sutras > 82000)optional: whether the rule is optional (vikalpa)overrides: list of sutra ids that this rule overrides (apavāda relationship)
Takes a left and right PaninianObject and transforms them. Parameters:
| Parameter | Purpose |
|---|---|
cond |
Callable (env) -> bool: trigger condition |
xform |
Callable (env) -> (str, str): phonological transformation of (left, right) |
update |
Callable (env): sets/removes tags on outputs after transformation |
insert |
Callable (env) -> dict: injects āgama objects |
domain |
Callable (GlobalDomains) -> bool: controls which domain activates this rule |
bahiranga |
int: bahiranga score; lower = more antaranga = higher priority |
optional |
bool: rule is optional (vikalpa) |
overrides |
list of aps strings this rule is an apavāda of |
The execution environment env exposes:
| Key | Meaning |
|---|---|
lp |
left PaninianObject |
rp |
right PaninianObject |
l |
last varna of lp |
r |
first varna of rp |
ll |
second-last varna of lp |
rr |
second varna of rp |
lc |
lp minus last varna |
rc |
rp minus first varna |
Controls which rules are active. Domains are processed in order:
saMjYA → upadeSa → prakfti → pratyaya → aNga → standard → pada → saMhitA
Each execution pass activates one domain at a time. Rules can also trigger domain changes via their update function.
This feature is currently unused in the AntarangaPrakriya framework
maheshvara.py:isInPratyahara(pratyahara, varna)andisSavarna(v1, v2)— used in sutra conditions to check phonological class membership via Maheshvara sutras.paribhasha.py: meta-rules (paribhāṣā) like sthānivad ādeśa.operations.py: helpers likedirgha()(vowel lengthening).
Sutras are defined in YAML and compiled to LRSutra objects by process_yaml.py. This allows new rules to be added without writing Python.
- sutra: इको यणचि # Sutra name (Devanagari)
id: 6.1.77 # Adhyaya.Pada.Sutra number
condition: # Trigger condition (see below)
xform: # Phonological transformation
update: # Tag updates on outputs
insert: # Agama insertion
domain: # Activation domain
bahiranga: 9 # Priority class (lower = more antaranga)
optional: false # Vikalpa
overrides: # Apavada relationshipConditions are dicts whose keys are environment variable names and values are match specifications:
| Value syntax | Meaning |
|---|---|
_ac |
variable is in pratyahara "ac" |
$r |
variable is savarna of r |
=naam |
variable is exactly the string "naam" |
=!naam |
variable is not the string "naam" |
?pada |
variable has tag "pada" |
?!pada |
variable does not have tag "pada" |
+Y |
variable is a pratyaya with it Y |
$$fname |
call fname(variable) |
xform:
l: dirgha(l) # Replace last varna of lp with its dīrgha
r: "" # Delete first varna of rpupdate:
olp: +ru # Set tag "ru" on output lp
olp: ++R # Set it "R" on output lp
orp: -pada # Remove tag "pada" from output rp
olp: --Y # Remove it "Y" from output lp
olp: =krozwf # Replace output lp with predefined object krozwfinsert adds āgamas (augment elements) to the prakriya sequence. It fires after xform
and update in the execution loop (step 7 above).
insert:
<position>: <expression> # one key–value pair per insertionEval context. Expressions are Python strings evaluated at rule-trigger time. The following variables are bound (canonical SLP1 strings):
| Variable | Value |
|---|---|
l |
Last character of the left operand |
r |
First character of the right operand |
lc |
Left operand minus its last character |
rc |
Right operand minus its first character |
All names from pratyaya, paribhasha, maheshvara, and pratipadika are in scope
(star-imported by process_yaml.py), so pre-defined Pratyaya objects (e.g., tuk, UW) and
helper functions (e.g., shcutva, zwutva) can be referenced directly.
Position keys and their effect on the sequence:
| Key | Effect |
|---|---|
"m" with kit (its=["k"]) |
Appends āgama after left operand: [left, āgama] |
"m" with wit (its=["w"]) |
Prepends āgama before right operand: [āgama, right] |
"l" |
Appends āgama after left operand: [left, āgama] |
"r" |
Prepends āgama before right operand: [āgama, right] |
0 (integer) |
Prepends āgama before left operand: [āgama, left] |
1 (integer) |
Prepends āgama before right operand: [āgama, right] |
The key determines where in the sequence the āgama lands; for the "m" key the kit/wit
markers on the inserted object itself decide which side to attach to.
Hierarchical prakriya. When insert produces a list (non-scalar result), AntarangaPrakriya
runs recursively on the expanded pair before continuing. This ensures the āgama undergoes its own
phonological transformations before being merged back into the main sequence. After hierarchical
execution, the pair is collapsed into a single PaninianObject with the merged string.
Samprasāraṇa exception: when a position-
0insert places an object carrying thesamprasAraRamtag before the left operand, the hierarchical output uses the first element of the first output (hpo[0][0]) rather than the normal sub-object selection. This drives the vowel-grade alternation in roots like√vah.
Common pattern — ādeśa and lopa via delete-and-replace. xform nulls out a character (lopa)
and insert provides its replacement (ādeśa) as a fresh Pratyaya or PaninianObject. This
is the correct way to implement both substitutions and deletions where sandhi may subsequently
apply. Because the replacement is a new object, the engine detects a non-scalar result and runs
a hierarchical prakriya on the expanded pair — any sandhi rules that can apply between the
newly inserted object and its neighbours will fire. A simple varna substitution in xform alone
would not create a list, so no hierarchical prakriya would run and post-insertion sandhi would be
silently skipped.
# 8.4.40 — स्तोः श्चुना श्चुः (L): s / dental-stop → palatal equivalent
# The palatal replacement fires a hierarchical prakriya; subsequent ścu/ṣṭu sandhi
# rules can then operate on the newly inserted palatal if needed.
xform:
l: null # lopa: delete the original s or dental-stop
insert:
l: shcutva(l) # ādeśa: insert the palatal equivalent as a new objectExamples:
# 6.1.73 — छे च: insert tuk (kit) after a short vowel, before cha
# tuk = Pratyaya("t", its=["k"]) — kit, so appended to left operand
insert:
m: tuk
# 8.4.40/41 — श्चुत्व / ष्टुत्व: delete and re-insert as the appropriate class
xform:
l: null
insert:
l: shcutva(l) # or zwutva(l) for ष्टुत्व
# 6.4.134 — अल्लोपोऽनः: delete ā, re-insert n as a fresh object
xform:
lc: lc[:-1]
l: null
insert:
l: str("n") # fresh n; subsequent rules see it as a new token
# 6.4.133 — अयादीनामायः: insert UW (samprasāraṇa-tagged) before left operand
xform:
lc: lc[1:]
insert:
0: UW # integer key → prepend before left operandWhen multiple sutras trigger at the same window position, sutra_priority() selects the winner using the Paninian principle pūrvaparanityāntaraṅgāpavādānām uttarottaraṃ balīyaḥ:
- Apavāda (exception): a rule explicitly listed as overriding another wins
- Antaranga (more internal): lower
bahirangascore wins - Saṃjñā rules (numbered < 1.4.2 /
_aps_num < 14000): earlier number wins - Tripadi (numbered in 8th adhyaya,
_aps_num > 82000): earlier number wins - Para (later rule): higher
_aps_numwins (default)
Rule priority determines which sutra wins when multiple fire at the same window. Siddha/asiddha determines what state each sutra sees — i.e. which earlier outputs are visible to it.
Every sutra's view of the derivation is computed by view() in antaranga_prakriya.py. It walks back up the PrakriyaTree and returns the outputs of the most recent node that the current sutra is allowed to see. The key rule is:
TripāḍÄ« sutras (8.2.1–8.4.68, _aps_num > 82000) are asiddha with respect to sāpadasaptādhyāyī (SPSA) sutras (_aps_num < 82000).
In practice:
| Current sutra | Can see |
|---|---|
SPSA (_aps_num < 82000) |
Outputs of SPSA sutras only — tripāḍī outputs are invisible (asiddha) |
TripāḍÄ« (_aps_num ≥ 82000) |
Outputs of all SPSA sutras + earlier tripāḍī sutras (lower _aps_num) |
This is implemented by walking up the tree and skipping nodes whose sutra _aps_num falls outside the visible range. The walk stops at the first visible node, and that node's outputs become the view.
Special siddha exceptions (_special_siddha() in antaranga_prakriya.py): certain tripāḍī outputs must be visible to specific later rules even across the SPSA/tripāḍī boundary:
| Producer sutra | Visible to | Reason |
|---|---|---|
| ṣṭutva 8.4.41 | ḍ-lopa 8.3.13 | ṣṭutva output must be seen before ḍ-lopa fires |
| ḍ-lopa 8.3.13, r-lopa 8.3.14 | pūrva-dīrgha 6.3.111 | lopa must be visible for dīrgha to apply correctly |
| n-lopa 8.2.7, 7.4.33 | 7.4.25 | n-lopa siddha for inter-pada and rājīyati/rājāyate forms |
| saṃyogānta-lopa 8.2.23 | maGavan upadhā-dīrgha 6.4.8.1 | final cluster lopa must be visible for upadhā-dīrgha to fire correctly for maGavan before sarvanamasthāna |
Not yet implemented: asiddhavat (8.2.1 — SPSA sutras after 8.2.1 treat each other as asiddha within SPSA) and ṣṭutokora-siddhaḥ (a further sub-boundary within tripāḍī). These are noted as FIXMEs in the code.
Generating all vibhakti forms of rāma (masculine a-stem):
from sanskrit_parser.generator.pratipadika import rAma
from sanskrit_parser.generator.pratyaya import sups
from sanskrit_parser.generator.sutras_yaml import SutraFactory
from sanskrit_parser.generator.cmd_line import generate_vibhakti
sutra_list = SutraFactory("sutras_antaranga.yaml")
forms = generate_vibhakti(rAma, "AntarangaPrakriya", sutra_list)
# forms[0] = [nom.sg, nom.du, nom.pl] = ["rAmaH", "rAmO", "rAmAH"]
# forms[1] = [acc.sg, acc.du, acc.pl] = ["rAmam", "rAmO", "rAmAn"]
# ...For each vibhakti/vacana, the engine runs:
- Input:
[rAma (prātipadika), su (sup, nominative sg)] - Rules fire to: strip anubandha
u~fromsu→s; handlea + s→aH(visarga sandhi) - Output:
rAmaH
The main helper is generate_vibhakti(pratipadika, prakriya, sutra_list), which generates all 8×3 vibhakti forms. The entry point is registered as sanskrit_generator.
run_pp(inputs, prakriya, sutra_list) runs a single prakriya on an arbitrary input list, useful for testing individual derivations.
| File | Coverage |
|---|---|
test_ajanta_pum.py |
Ajanta (vowel-final) masculine nominals |
test_ajanta_stri.py |
Ajanta feminine nominals |
test_ajanta_napum.py |
Ajanta neuter nominals |
test_halanta.py |
Halanta (consonant-final) nominals |
test_vibhakti.py |
Vibhakti generation across stem classes |
test_list.py / manual_tests.py |
Regression and manual test cases |
Run from the generator branch:
cd sanskrit_parser/generator/test
. run.sh