deva2iast
def deva2iast(
s:str
)->str:Transliterate Devanagari to IAST, keeping the vowel length that scansion needs.
Sanskrit verse is measured in syllables, and each syllable is either light (laghu, written l) or heavy (guru, written g). A syllable is heavy when its vowel is long (ā, ī, ū, ṝ, e, ai, o, au), when it ends in an anusvāra (ṃ) or a visarga (ḥ), or when two or more consonants follow its vowel, even across a word break. A syllable at the very end of the text that ends in a consonant is also heavy. Every other syllable is light. A metre (chandas) is a rule about the pattern of these weights, usually stated for one pāda, a quarter of the verse. The anuṣṭubh or śloka of the epics has eight syllables in each pāda, and the mandākrāntā of the Meghadūta has seventeen in a fixed pattern.
Finding a metre takes three steps. deva2iast writes Devanagari in IAST and keeps the vowel length that the weights depend on. syllables divides the text into syllables and marks each one heavy or light, and scan gives the same result as a string of g and l. detect_meter then compares that string with the known metres.
deva2iast is a separate transliteration from fold_token in ganapati.sanskrit, because fold_token drops vowel length on purpose so that a search matches either spelling.
Transliterate Devanagari to IAST, keeping the vowel length that scansion needs.
syllables takes IAST or Devanagari and returns (syllable, heavy) pairs. It reads an aspirated consonant such as kh or th as one consonant and the diphthongs ai and au as one vowel, so atha has two syllables, a and tha. A consonant that closes one syllable is not counted again at the start of the next: in kaṃsa the ṃ belongs to kaṃ, which makes it heavy. scan gives the pattern as a string, and mora_weights gives each syllable’s length in mātrās, the unit of duration: one for a light syllable and two for a heavy one.
Return the syllables as (syllable, mātrās) pairs, 2 for a heavy syllable and 1 for a light one.
Return the weight pattern of a string, g for each heavy syllable and l for each light one.
Divide a Sanskrit string in IAST or Devanagari into syllables, as (syllable, heavy) pairs.
assert [s for s, _ in syllables('atha')] == ['a', 'tha'] # `th` is one consonant
assert [s for s, _ in syllables('kaṃsa')] == ['kaṃ', 'sa'] # the ṃ closes the first, not opens the second
assert scan('gam') == 'g' # a final cluster makes it heavy
assert scan('rāma') == 'gl' # long ā, then a bare short a
assert scan('īśā vāsyam idaṃ sarvaṃ') == 'gggllggg'
assert scan(unicodedata.normalize('NFD', 'īśā vāsyam idaṃ sarvaṃ')) == 'gggllggg' # decomposed IAST keeps its long vowelsThe handbooks of prosody describe a metre with gaṇas. A gaṇa is a named group of three syllables, and each of the eight possible groups of weights has a one-syllable name: ya is lgg, ma ggg, ta ggl, ra glg, ja lgl, bha gll, na lll and sa llg. A leftover single heavy or light syllable is ga or la. The indravajrā, for example, is ta ta ja ga ga, which spells out gglgglglgg.
GANAS holds that table. gana_pattern turns a recipe of gaṇa names into its pattern, and ganas does the reverse, reading a pattern three syllables at a time. METERS lists twenty common metres by their gaṇa recipes, the way the handbooks state them, and VRTTA_EXTRA adds eighty more as plain patterns. The recipe of every verse is stored in the search metadata, which is what by_meter in ganapati.lemma searches on.
A second family of metres counts duration instead of syllables. In the āryā and its relatives a light syllable is one mātrā and a heavy syllable two, and each half of the verse is built from groups of four mātrās. The first half of an āryā has 30 mātrās and the second 27, because its sixth group shrinks to a single light syllable. detect_matra_meter finds these metres by fitting the weights into the groups, rather than by matching a fixed pattern.
Remove the citations, verse numbers, headings, gloss lines and bracketed notes that are printed with a verse but not scanned.
Spell out a gaṇa recipe as a g/l pattern: ta ta ja ga ga gives gglgglglgg.
Name the gaṇas of a g/l pattern three syllables at a time, with a leftover one or two syllables as ga or la.
metrical_text removes everything printed beside a verse that should not be scanned: citations, verse numbers between daṇḍas, headings, > gloss lines, and anything in square brackets, such as an audio timing or a page number. detect_meter calls it first, so you can pass a verse as the source prints it.
Meter is an enum of every metre ganapati can name. Each member has an ASCII name for code and the IAST name as its value, so Meter.MANDAKRANTA == 'mandākrāntā'. Besides the metres above, it holds two other kinds. In an ardhasamavṛtta the odd and even pādas follow different patterns, and ARDHASAMA holds two of them, the viyoginī and the puṣpitāgrā. MATRA_METERS holds the five mātrā metres of the āryā family, and matras counts the mātrās in a string.
Count the mātrās of a string: one for each light syllable and two for each heavy one.
Find the āryā-family metre of a verse as AttrDict(name, halves, ganas, matras), or None if none fits.
Find the metre of one whole verse, as AttrDict(name, variant, syllables, per_pada, ganas, scan, matras, halves).
Find the ardhasamavṛtta of a verse, whose odd and even pādas differ, as AttrDict(name, padas, ganas), or None.
detect_meter names the metre of a whole verse. It returns an AttrDict with the metre’s name (a Meter, or None if nothing fits), the number of syllables, the syllables per_pada, the gaṇas of the first pāda in ganas, the full scan, the total matras, and, for an āryā-type metre, the mātrās of each half in halves. It returns None only for text with no syllables at all.
It tries the metres in a fixed order: first those with one pattern for all four pādas, then upajāti, then the anuṣṭubh, then the ardhasamavṛttas, and the mātrā metres last, so that a verse in a fixed-pattern metre is never relabelled as an āryā. Two rules from the tradition apply throughout. The last syllable of a pāda may be heavy or light, whatever the pattern says. And upajāti is a licence rather than a metre: a verse whose pādas mix the indravajrā and the upendravajrā. The anuṣṭubh has its own rules, which fix only the fifth to seventh syllables of each pāda, and variant says which form its odd pādas take, the regular pathyā or one of the vipulā forms.
The examples are the first verse of the Meghadūta in mandākrāntā and Gītā 1.1 in anuṣṭubh.
# Meghadūta 1.1, four pādas of seventeen syllables
mand = ('kaścit kāntāvirahaguruṇā svādhikārātpramattaḥ '
'śāpenāstaṃgamitamahimā varṣabhogyeṇa bhartuḥ '
'yakṣaścakre janakatanayāsnānapuṇyodakeṣu '
'snigdhacchāyātaruṣu vasatiṃ rāmagiryāśrameṣu')
m = detect_meter(mand)
assert m.name is Meter.MANDAKRANTA and m.per_pada == 17
assert m.ganas == 'ma bha na ta ta ga ga'
# Gītā 1.1: the anuṣṭubh, and which of its variants
a = detect_meter('dharmakṣetre kurukṣetre samavetā yuyutsavaḥ '
'māmakāḥ pāṇḍavāścaiva kimakurvata sañjaya')
assert a.name is Meter.ANUSTUBH and a.variant == 'pathyā' and a.per_pada == 8
assert Meter.VASANTATILAKA.value == 'vasantatilakā'
assert Meter.MANDAKRANTA == 'mandākrāntā'detect_meter needs a whole verse. Some sources give you one line at a time with no daṇḍa to show where a verse ends: forced alignment of a recording, speech recognition, and TEI files that store each line as a record. Two functions work on such input. match_pada takes one pāda, as text or as a g/l pattern, and returns every metre whose pāda it fits. group_verses joins the lines one, two and four at a time, runs detect_meter on each grouping, and keeps the grouping in which the most verses get a name. It returns the lines per verse in size, the share of verses that got a name in coverage, and the joined verses with their meters. The four lines of the Meghadūta’s first verse give a size of 4; a Rāmāyaṇa aligned half a verse at a time would give 2.
Find how many lines make a verse by trying each size in sizes, returning AttrDict(size, coverage, verses, meters).
List the metres whose pāda matches one pāda of text or one g/l pattern.
# one pāda of the Meghadūta, which detect_meter can only call unmatched
padas = ['kaścit kāntāvirahaguruṇā svādhikārātpramattaḥ',
'śāpenāstaṃgamitamahimā varṣabhogyeṇa bhartuḥ',
'yakṣaścakre janakatanayāsnānapuṇyodakeṣu',
'snigdhacchāyātaruṣu vasatiṃ rāmagiryāśrameṣu']
assert detect_meter(padas[0]).name is None # an AttrDict, never None
assert Meter.MANDAKRANTA in match_pada(padas[0])
assert match_pada('gglggllglgg') == [Meter.INDRAVAJRA] # a g/l pattern reads the same way
# the four lines with no daṇḍa anywhere: the grouping has to be guessed
g = group_verses(padas)
assert g.size == 4 and g.coverage == 1.0
assert g.meters[0].name is Meter.MANDAKRANTA
assert group_verses([]).coverage == 0.0# Kumārasambhava 4.1, viyoginī: the odd pādas are 10 syllables, the even 11
K41 = ('अथ मोहपरायणा सती विवशा कामवधूर्विबोधिता ।\n'
'विधिना प्रतिपादयिष्यता नववैधव्यमसह्यवेदनम् ॥')
m = detect_meter(K41)
assert m.name == Meter.VIYOGINI and m.syllables == 42 and m.per_pada is None
# and its closing verse, puṣpitāgrā: 12 + 13
K446 = ('अथ मदनवधूरुपप्लवान्तं व्यसनकृशा परिपालयां बभूव ।\n'
'शशिन इव दिवातनस्य लेखा किरणपरिक्षयधूसरा प्रदोषम् ॥')
assert detect_meter(K446).name == Meter.PUSPITAGRA
# a samavṛtta is still named by the pāda table, not relabelled by the new one
assert detect_meter(' '.join(padas)).name == Meter.MANDAKRANTAA recording aligned line by line gives an outside check on the scansion. If each line’s duration comes from line_times and its mātrās from matras, the milliseconds per mātrā should stay roughly constant through a recitation. A line far from the median rate was scanned wrongly or aligned wrongly.
mora_rate gives the median milliseconds per mātrā over a chunk’s timed lines, or None if the chunk has no timings. timing_check lists the timed lines whose rate is more than tol (35% by default) away from that median, and it needs at least three timed lines to say anything. guru_laghu_ratio estimates how much longer a heavy syllable lasts than a light one, with a least-squares fit over many timed lines. The texts on prosody say 2:1. Measured over aligned Vedic recitation, the ratio comes out between 1.3 and 2.7.
The example builds timed lines from the four Meghadūta pādas at exactly 100 ms per mātrā, then slows the last line down so that timing_check flags it.
Estimate how many times longer a heavy syllable lasts than a light one, by least squares over timed lines, or None if the lines cannot tell.
List the timed lines whose milliseconds per mātrā are more than tol away from the chunk’s median, where audio and scansion disagree.
Return the median milliseconds per mātrā over a chunk’s timed lines, or None if it has none.
def timed(ps, rate=100):
'Each pāda with an audio span that honours its morae at `rate` ms per mora.'
rs = rate if isinstance(rate, list) else [rate] * len(ps)
out, t = [], 0
for p, r in zip(ps, rs):
d = matras(p) * r; out.append(f'{p} {time_marker(t, t + d)}'); t += d
return '\n'.join(out)
assert mora_rate(timed(padas)) == 100
assert timing_check(timed(padas)) == []
assert 1.99 < guru_laghu_ratio(timed(padas)) < 2.01 # a guru is two laghus, measured
assert timing_check(timed(padas, [100, 100, 100, 180]))[0].start == 8000 # the line out of proportion
assert mora_rate('\n'.join(padas)) is None # no timings, nothing to measureverse_meta is how metre gets into a search index. It finds the verses in a chunk with verse_units, runs detect_meter on each, and returns a flat dict of strings. meter and variant name the metres found. gana holds the gaṇa recipes, joined with underscores so that each is one search token, and pada the syllables per pāda. matra gives the mātrās of each half of an āryā-type verse, and mora_rate and timing appear when the chunk has audio timings. Keys with nothing to say are left out, so an empty chunk gives {}. litesearch stores this dict in each chunk’s metadata column and indexes it for full-text search beside the content, so no new column is needed.
Return the metre facets of one chunk as the flat dict litesearch stores in its metadata.
Split one chunk into its verses, since a chunk may hold several and each has its own metre.
meter_name is the short form for a single verse: the metre’s name as a string, or '' when the verse has no metre ganapati knows or cannot be scanned at all. It never raises, so it is safe to call on every verse of a large corpus.
Return the name of the metre one verse scans as, or '', without ever raising an exception.