File size: 24,433 Bytes
c8085d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb2bcf8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>tigmorph · Tigre morphological analyzer</title>
<meta name="description" content="Morphological analyzer and generator for Tigre (ትግሬ), running in your browser.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+Ethiopic:wght@400;600;700&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap">
<style>
  :root {
    --bg: #f7f6f2; --panel: #ffffff; --ink: #1d2128; --muted: #646b76; --line: #e3e1da;
    --accent: #1f6f5c; --accent-soft: #e4f1ec; --warn: #9a5b13;
    --geez: 'Noto Sans Ethiopic', 'Abyssinica SIL', 'Nyala', sans-serif;
    --sans: 'Inter', 'Noto Sans Ethiopic', system-ui, sans-serif;
    --mono: 'JetBrains Mono', ui-monospace, monospace;
  }
  * { box-sizing: border-box; }
  body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.55 var(--sans); }
  .wrap { max-width: 1120px; margin: 0 auto; padding: 32px 24px 64px; }
  header h1 { font-size: 28px; margin: 0 0 6px; letter-spacing: -.01em; }
  header h1 .g { font-family: var(--geez); color: var(--accent); font-weight: 700; }
  header p { margin: 0 0 6px; color: var(--muted); max-width: 820px; }
  header .links { font-size: 13.5px; }
  a { color: var(--accent); }
  code { font-family: var(--mono); font-size: .88em; background: #eeece6; padding: 1px 5px; border-radius: 4px; }
  #status { margin: 18px 0 0; padding: 10px 14px; border-radius: 8px; background: var(--accent-soft); color: var(--accent);
            font-size: 14px; display: flex; gap: 10px; align-items: center; }
  #status.err { background: #fbeee0; color: var(--warn); }
  #status.hide { display: none; }
  .spin { width: 14px; height: 14px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%;
          animation: s .8s linear infinite; flex: none; }
  @keyframes s { to { transform: rotate(360deg); } }
  nav { display: flex; gap: 4px; margin: 24px 0 0; border-bottom: 1px solid var(--line); }
  nav button { background: none; border: 0; padding: 10px 16px; font: 500 14.5px var(--sans); color: var(--muted);
               cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px; }
  nav button[aria-selected="true"] { color: var(--ink); border-bottom-color: var(--accent); }
  section { display: none; padding-top: 22px; }
  section.on { display: block; }
  .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 18px; }
  .row { display: flex; gap: 14px; flex-wrap: wrap; align-items: flex-end; }
  label.f { display: flex; flex-direction: column; gap: 5px; font-size: 12.5px; font-weight: 600; color: var(--muted);
            text-transform: uppercase; letter-spacing: .04em; }
  input[type=text], textarea, select { font: 17px var(--geez); padding: 9px 11px; border: 1px solid var(--line);
            border-radius: 7px; background: #fff; color: var(--ink); }
  select { font: 14.5px var(--sans); padding: 8px 9px; }
  textarea { width: 100%; resize: vertical; }
  input:focus, textarea:focus, select:focus { outline: 2px solid var(--accent-soft); border-color: var(--accent); }
  .checks { display: flex; gap: 18px; flex-wrap: wrap; font-size: 14px; margin-top: 12px; }
  .checks label { display: flex; gap: 6px; align-items: center; cursor: pointer; }
  button.go { background: var(--accent); color: #fff; border: 0; border-radius: 7px; padding: 10px 22px;
              font: 600 14.5px var(--sans); cursor: pointer; }
  button.go:disabled { opacity: .45; cursor: default; }
  button.ghost { background: #fff; color: var(--accent); border: 1px solid var(--accent); }
  .examples { margin-top: 12px; font-size: 13.5px; color: var(--muted); display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
  .examples button { font: 15px var(--geez); background: #f1efe9; border: 1px solid var(--line); border-radius: 20px;
                     padding: 3px 12px; cursor: pointer; color: var(--ink); }
  .examples button:hover { border-color: var(--accent); }
  .note { color: var(--muted); font-size: 13.5px; margin: 14px 0 8px; }
  table { width: 100%; border-collapse: collapse; background: var(--panel); border: 1px solid var(--line);
          border-radius: 10px; overflow: hidden; font-size: 14px; }
  th { text-align: left; font-size: 12px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted);
       background: #faf9f6; padding: 9px 12px; border-bottom: 1px solid var(--line); font-weight: 600; }
  td { padding: 9px 12px; border-bottom: 1px solid #f0eee8; vertical-align: top; }
  tr.first td { border-top: 1px solid var(--line); }
  tbody tr:first-child td { border-top: 0; }
  .gz { font-family: var(--geez); font-size: 17px; }
  .w { font-family: var(--geez); font-size: 19px; font-weight: 600; }
  .raz { font-family: var(--mono); font-size: 13.5px; color: #3b4351; }
  .cls { font: 600 12px var(--mono); padding: 2px 7px; border-radius: 5px; background: var(--accent-soft); color: var(--accent); }
  .feat { display: inline-block; font: 12px var(--mono); background: #f1efe9; border-radius: 4px; padding: 1px 6px; margin: 1px 2px 1px 0; }
  .feat b { font-weight: 500; color: var(--muted); }
  .score { font: 13px var(--mono); color: var(--muted); }
  .best .score { color: var(--accent); font-weight: 600; }
  .none { color: var(--muted); font-style: italic; }
  .big { font: 700 40px var(--geez); margin: 16px 0 2px; }
  .big .raz { font-size: 20px; font-weight: 400; margin-left: 10px; }
  .par th { text-transform: none; font-size: 12.5px; }
  .scroll { overflow-x: auto; }
  .scroll table { min-width: 640px; }
  .par td .gz { font-size: 16px; }
  .par td .raz { display: block; font-size: 12px; color: var(--muted); }
  .two { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
  @media (max-width: 760px) { .two { grid-template-columns: 1fr; } .hide-sm { display: none; } }
  .about h3 { margin: 22px 0 6px; font-size: 16px; }
  .about ul { padding-left: 20px; margin: 6px 0; }
  .about table { font-size: 13.5px; }
  footer { margin-top: 40px; font-size: 12.5px; color: var(--muted); }
</style>
</head>
<body>
<div class="wrap">
  <header>
    <h1>tigmorph · <span class="g">ትግሬ</span> morphological analyzer</h1>
    <p>A morphological analyzer and generator for <b>Tigre</b> (Ge'ez script), built from Shlomo Raz,
      <i>A Descriptive Study of Tigre Grammar</i> (1973). Type a word to get its root or lemma, word class, features,
      its pronunciation in Raz's transcription (which shows the gemination, ə and vowel length that Ge'ez spelling hides)
      and an English gloss, ranked by a model learned from an 11-million-word Tigre corpus.</p>
    <p class="links"><a href="https://github.com/beshir-a-Ibrahim/tigmorph">GitHub</a> ·
      <code>pip install git+https://github.com/beshir-a-Ibrahim/tigmorph.git</code> ·
      <span id="ver">v2.1</span> · runs entirely in your browser</p>
  </header>

  <div id="status"><div class="spin"></div><span id="status-text">Loading Python and the Tigre transducers (first visit about 10 MB, then cached)…</span></div>

  <nav role="tablist">
    <button role="tab" aria-selected="true" data-tab="analyze">Analyze</button>
    <button role="tab" aria-selected="false" data-tab="generate">Generate</button>
    <button role="tab" aria-selected="false" data-tab="normalize">Normalize</button>
    <button role="tab" aria-selected="false" data-tab="about">About</button>
  </nav>

  <!-- ANALYZE -->
  <section id="analyze" class="on">
    <div class="panel">
      <div class="row">
        <label class="f" style="flex:1; min-width: 260px">Tigre word(s) or sentence
          <input type="text" id="a-in" value="ወለዐለ ቤቼ ቅሩባት" autocomplete="off" spellcheck="false"></label>
        <label class="f">Readings
          <select id="a-n"><option>1</option><option>2</option><option selected>3</option><option>5</option><option>10</option></select></label>
        <button class="go" id="a-go" disabled>Analyze</button>
      </div>
      <div class="checks">
        <label><input type="checkbox" id="a-guess"> Guess unknown roots</label>
        <label><input type="checkbox" id="a-latin"> Input is Raz transcription (Latin)</label>
        <label><input type="checkbox" id="a-cmp"> Read as one verb compound (ሰኒ ቤለ)</label>
      </div>
      <div class="examples">Try:
        <button data-ex="ወለዐለ ቤቼ ቅሩባት">ወለዐለ ቤቼ ቅሩባት</button>
        <button data-ex="ልቀትሎ">ልቀትሎ</button>
        <button data-ex="ምንገብእ ዲብለትፈናተ">ምንገብእ ዲብለትፈናተ</button>
        <button data-ex="ሰኒ ቤለ" data-cmp="1">ሰኒ ቤለ</button>
        <button data-ex="ዘረጠ" data-guess="1">ዘረጠ</button>
        <button data-ex="ləqattəl" data-latin="1">ləqattəl</button>
      </div>
    </div>
    <p class="note" id="a-note">Score 0 = best reading; higher = less likely.</p>
    <div class="scroll"><table id="a-out"><thead><tr><th>Word</th><th>Root / lemma</th><th>Class</th><th>Features</th>
      <th>Pronunciation</th><th class="hide-sm">Gloss</th><th>Score</th></tr></thead><tbody></tbody></table></div>
  </section>

  <!-- GENERATE -->
  <section id="generate">
    <div class="panel">
      <div class="row">
        <label class="f">Root <span style="text-transform:none;font-weight:400">(q-t-l or ቅ-ት-ል)</span><input type="text" id="g-root" value="q-t-l" size="12" spellcheck="false"></label>
        <label class="f">Type<select id="g-type"><option>A</option><option>B</option><option>C</option><option>D</option></select></label>
        <label class="f">Derivation<select id="g-deriv"></select></label>
        <label class="f">Form<select id="g-tam"></select></label>
        <label class="f" id="g-subj-l">Subject<select id="g-subj"></select></label>
        <label class="f" id="g-num-l" style="display:none">Gender / number<select id="g-num"></select></label>
        <label class="f" id="g-obj-l">Object<select id="g-obj"></select></label>
      </div>
      <div class="checks" id="g-flags">
        <label><input type="checkbox" id="g-neg"> Negative (ʼi-)</label>
        <label><input type="checkbox" id="g-colloq"> Prefixless imperfect</label>
      </div>
      <div class="row" style="margin-top:14px">
        <button class="go" id="g-go" disabled>Generate</button>
        <button class="go ghost" id="p-go" disabled>Show full paradigm</button>
      </div>
    </div>
    <div id="g-out"></div>
    <div id="p-out"></div>
  </section>

  <!-- NORMALIZE -->
  <section id="normalize">
    <p class="note" style="margin-top:0">Text from many sources spells the same word in several ways (ሀለ / ህለ, ይዐለ / ኢዐለ / የዐለ,
      ሠ for ሰ, ፡ between words, <code>::</code> for ።). The normalizer writes every word in one standard spelling.
      <b>chars</b>: characters only (NFC, ሠ→ሰ, ፀ→ጸ, ኀ→ሐ, punctuation, spaces).
      <b>safe</b>: plus spelling pairs that differ only by a known free alternation.
      <b>full</b>: every row of the learned table, including pairs that differ in other letters (review these).</p>
    <div class="two">
      <label class="f">Text<textarea id="n-in" rows="7">ህለ እት ዓድ፡ሠብ:: ኢዐለ</textarea></label>
      <label class="f">Normalized<textarea id="n-out" rows="7" readonly></textarea></label>
    </div>
    <div class="row" style="margin-top:12px">
      <label class="f">Level<select id="n-level"><option>chars</option><option selected>safe</option><option>full</option></select></label>
      <button class="go" id="n-go" disabled>Normalize</button>
    </div>
    <div id="n-log"></div>
  </section>

  <!-- ABOUT -->
  <section id="about" class="about">
    <h3>What it covers</h3>
    <ul>
      <li><b>Verbs</b>: types A–D, nine derivations (tə-, ʼa-, ʼat-, ʼatta-, ʼan-, ʼas-, ʼattan-, ʼattas-, ʼasta-),
        tri-, quadri- and quinqueradicals, weak and irregular roots, object suffixes, negation, the prefixless imperfect,
        and verb compounds with light verbs (<span class="gz">ሰኒ ቤለ</span>).</li>
      <li><b>Function words</b>: pronouns, demonstratives, the copula, 50 prepositions with pronoun endings, the article,
        conjunctions, adverbs and numerals.</li>
      <li><b>Attached words</b>: <span class="gz">ወ-</span> "and", <span class="gz">ከ-</span> "and so", relative/article
        <span class="gz">ለ-</span>, attached prepositions (<span class="gz">ምንገብእ, ዲብለትፈናተ</span>),
        <span class="gz">-መ</span> "also", <span class="gz">-ዲ</span> "indeed", the copula <span class="gz">-ቱ</span>.</li>
      <li><b>Nouns, adjectives and names</b>: pronoun endings, suffixed and broken plurals, gender, the article;
        participles, agent nouns, infinitives and instrument nouns from every verb root.</li>
      <li><b>Unknown words</b>: a guesser proposes roots for verbs not in the lexicon.</li>
    </ul>
    <p>About 3,300 verb stems, 9,000 nominal entries and 280 function words.</p>
    <h3>Accuracy</h3>
    <table><thead><tr><th>Test</th><th>Words</th><th>Analysed</th><th>Best reading right</th></tr></thead><tbody>
      <tr><td>Raz's example sentences (running text)</td><td>5,268</td><td>95.0%</td><td>89.9%</td></tr>
      <tr><td>Raz's verb paradigms (Ch. 5)</td><td>2,013</td><td>100%</td><td>—</td></tr>
      <tr><td>Raz's function words and clitics</td><td>245</td><td>100%</td><td>97.6%</td></tr>
      <tr><td>Raz's deverbal nominals (§ 2.7)</td><td>94</td><td>100%</td><td>80%</td></tr>
      <tr><td>Raz's nouns: singular, plural, possessive</td><td>634</td><td>99.8%</td><td>88%</td></tr>
      <tr><td>Verb forms weighted by corpus frequency</td><td>361k tokens</td><td>100%</td><td>96.9%</td></tr>
      <tr><td>Corpus tokens (10.9M) analysed from the lexicon</td><td></td><td>83.8%</td><td></td></tr>
    </tbody></table>
    <p>Ge'ez spelling hides gemination and vowel length, so some forms have two real readings that only context can
      settle, mainly verb type B vs C, and a participle vs the prefixless imperfect.</p>
    <h3>Tags</h3>
    <p><code>Type</code> A–D · <code>Deriv</code> derivation · <code>TAM</code> Perf / Impf / Jus / Imp, or a verbal noun
      (PartAct, PartPass, Agent, Inf, Instr, class <b>V&gt;N</b>) · <code>Subj</code> / <code>Obj</code> person (1Sg … 3PlF) ·
      <code>Neg</code> negative ʼi- · <code>Colloq</code> prefixless imperfect · <code>Poss</code> pronoun ending ·
      <code>Art=Def</code> article · <code>Rel</code> relative la- · <code>Cl</code> attached ወ-/ከ- · <code>Prep</code>
      attached preposition · <code>Encl</code> -መ/-ዲ. Full list:
      <a href="https://github.com/beshir-a-Ibrahim/tigmorph/blob/main/docs/TAGS.md">docs/TAGS.md</a>.</p>
    <h3>How it works</h3>
    <p>Root-independent templates following Raz Ch. 5 and Ch. 2 are compiled with pynini into finite-state transducers
      (<code>root + tags ⇄ Raz transcription ⇄ Ge'ez spelling</code>). A small pure-Python runtime reads them. On this page
      that runtime runs in your browser through <a href="https://pyodide.org">Pyodide</a>, so nothing you type is sent
      to a server.</p>
    <h3>Help improve it</h3>
    <p>Fill in a sheet in <a href="https://github.com/beshir-a-Ibrahim/tigmorph/tree/main/contrib"><code>contrib/</code></a>:
      frequent words the lexicon doesn't know yet, Wiktionary verbs to check, or 300 corpus words to annotate.
      Issues and pull requests are welcome.</p>
    <h3>Licence and citation</h3>
    <p>Code MIT; data CC0 / CC BY 4.0 / CC BY-SA 4.0 by source (compiled FSTs: CC BY-SA 4.0). If you use tigmorph, please
      cite it and Raz (1973); see <a href="https://github.com/beshir-a-Ibrahim/tigmorph/blob/main/CITATION.cff">CITATION.cff</a>.
      Corpus: <a href="https://huggingface.co/datasets/BeitTigreAI/tigre-data-monolingual-text">BeitTigreAI/tigre-data-monolingual-text</a>.
      Lexical data: the Tigre Wiktionary contributors.</p>
  </section>

  <footer>tigmorph · Tigre morphology after Raz (1973) · BeitTigreAI</footer>
</div>

<script src="https://cdn.jsdelivr.net/npm/pyodide@314.0.7/pyodide.js"></script>
<script>
const PYODIDE_URL = 'https://cdn.jsdelivr.net/npm/pyodide@314.0.7/';
const $ = s => document.querySelector(s);
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
const PERSONS = ['1Sg','2SgM','2SgF','3SgM','3SgF','1Pl','2PlM','2PlF','3PlM','3PlF'];
const NUMS = ['SgM','SgF','PlM','PlF'];
const DERIVS = ['Base','tə','ʼa','ʼat','ʼatta','ʼan','ʼas','ʼattan','ʼattas','ʼasta'];
const FINITE = {Perf:'Perfect', Impf:'Imperfect', Jus:'Jussive', Imp:'Imperative'};
const NOMINAL = {PartAct:'Active participle', PartPass:'Passive participle', Agent:'Agent noun', Inf:'Infinitive', Instr:'Instrument noun'};
let py = null, W = null;

// ---------- tabs and controls
document.querySelectorAll('nav button').forEach(b => b.onclick = () => {
  document.querySelectorAll('nav button').forEach(x => x.setAttribute('aria-selected', x === b));
  document.querySelectorAll('section').forEach(s => s.classList.toggle('on', s.id === b.dataset.tab));
});
const fill = (sel, items, val) => { $(sel).innerHTML = items.map(([v, t]) =>
  `<option value="${esc(v)}"${v === val ? ' selected' : ''}>${esc(t)}</option>`).join(''); };
fill('#g-deriv', DERIVS.map(d => [d, d]), 'Base');
fill('#g-tam', [...Object.entries(FINITE), ...Object.entries(NOMINAL)].map(([k, v]) => [k, `${k} — ${v}`]), 'Perf');
fill('#g-subj', PERSONS.map(p => [p, p]), '3SgF');
fill('#g-num', NUMS.map(p => [p, p]), 'SgM');
fill('#g-obj', [['', '—'], ...PERSONS.map(p => [p, p])], '');
$('#g-tam').onchange = () => {
  const nom = $('#g-tam').value in NOMINAL;
  $('#g-subj-l').style.display = $('#g-obj-l').style.display = $('#g-flags').style.display = nom ? 'none' : '';
  $('#g-num-l').style.display = nom ? '' : 'none';
};

// ---------- boot Pyodide
async function boot() {
  try {
    py = await loadPyodide({ indexURL: PYODIDE_URL });
    setStatus('Loading the Tigre transducers…');
    const [zip, glue] = await Promise.all([fetch('tigmorph.zip').then(r => r.arrayBuffer()),
                                           fetch('web.py').then(r => r.text())]);
    py.unpackArchive(zip, 'zip', { extractDir: '/home/pyodide/lib' });
    py.FS.writeFile('/home/pyodide/lib/web.py', glue);
    await py.runPythonAsync(`import sys; sys.path.insert(0, '/home/pyodide/lib')`);
    W = py.pyimport('web');
    $('#ver').textContent = 'v' + W.VERSION;
    $('#status').classList.add('hide');
    document.querySelectorAll('button.go').forEach(b => b.disabled = false);
    runAnalyze();
  } catch (e) {
    console.error(e);
    $('#status').classList.add('err');
    $('.spin').remove();
    setStatus('Could not load the analyzer: ' + e.message);
  }
}
const setStatus = t => $('#status-text').textContent = t;
const tick = () => new Promise(r => setTimeout(r, 0));

// ---------- analyze
const feats = f => f.map(([k, v]) => `<span class="feat"><b>${esc(k)}=</b>${esc(v)}</span>`).join('');
function runAnalyze() {
  if (!W) return;
  const res = JSON.parse(W.analyze($('#a-in').value, +$('#a-n').value, $('#a-guess').checked,
                                   $('#a-latin').checked, $('#a-cmp').checked));
  const rows = [];
  let found = 0;
  for (const { word, readings } of res) {
    if (!readings.length) {
      rows.push(`<tr class="first"><td class="w">${esc(word)}</td><td colspan="6" class="none">no analysis — try “Guess unknown roots”</td></tr>`);
      continue;
    }
    found++;
    readings.forEach((r, i) => rows.push(`<tr class="${i ? '' : 'first best'}">
      <td class="w">${i ? '' : esc(word)}</td><td class="gz">${esc(r.root)}</td><td><span class="cls">${esc(r.cls)}</span></td>
      <td>${feats(r.feats)}</td><td class="raz">⟨${esc(r.raz)}⟩</td><td class="hide-sm">${esc(r.gloss)}</td>
      <td class="score">${r.score.toFixed(2)}</td></tr>`));
  }
  $('#a-out tbody').innerHTML = rows.join('');
  $('#a-note').textContent = res.length > 1
    ? `${found} of ${res.length} words analysed. Score 0 = best reading; higher = less likely.`
    : 'Score 0 = best reading; higher = less likely.';
}
$('#a-go').onclick = runAnalyze;
$('#a-in').onkeydown = e => { if (e.key === 'Enter') runAnalyze(); };
document.querySelectorAll('.examples button').forEach(b => b.onclick = () => {
  $('#a-in').value = b.dataset.ex;
  $('#a-cmp').checked = !!b.dataset.cmp; $('#a-guess').checked = !!b.dataset.guess; $('#a-latin').checked = !!b.dataset.latin;
  runAnalyze();
});

// ---------- generate
const gen = tags => JSON.parse(W.generate($('#g-root').value, JSON.stringify(tags)));
const cell = forms => forms.length
  ? forms.map(([raz, gz]) => `<span class="gz">${esc(gz)}</span><span class="raz">⟨${esc(raz)}⟩</span>`).join('')
  : '<span class="none">—</span>';
function runGenerate() {
  const tam = $('#g-tam').value, base = { Type: $('#g-type').value, Deriv: $('#g-deriv').value, TAM: tam };
  const tags = tam in NOMINAL ? { ...base, Subj: '3' + $('#g-num').value }
    : { ...base, Subj: $('#g-subj').value, Obj: $('#g-obj').value,
        Neg: $('#g-neg').checked ? 'Yes' : '', Colloq: $('#g-colloq').checked ? 'Yes' : '' };
  const { root, forms } = gen(tags);
  const tagline = Object.entries(tags).filter(([, v]) => v).map(([k, v]) => `${k}=${v}`).join(' ');
  $('#g-out').innerHTML = forms.length
    ? forms.map(([raz, gz]) => `<div class="big">${esc(gz)}<span class="raz">⟨${esc(raz)}⟩</span></div>`).join('')
      + `<p class="note">Root <code>${esc(root)}</code> · <code>${esc(tagline)}</code></p>`
    : `<p class="note" style="margin-top:18px">No form for <code>${esc(root)}</code> with <code>${esc(tagline)}</code>.
       This combination may not exist (the imperative is 2nd person only), or the root does not take this type or derivation.</p>`;
}
async function runParadigm() {
  const btn = $('#p-go'); btn.disabled = true;
  const base = { Type: $('#g-type').value, Deriv: $('#g-deriv').value };
  const neg = $('#g-neg').checked && !($('#g-tam').value in NOMINAL) ? 'Yes' : '';
  $('#g-out').innerHTML = '';
  $('#p-out').innerHTML = `<p class="note" style="margin-top:18px">Paradigm of <code>${esc($('#g-root').value)}</code>,
      Type ${esc(base.Type)}, ${esc(base.Deriv)}${neg ? ', negative' : ''}</p>
    <div class="scroll"><table class="par" id="p-fin"><thead><tr><th>Subject</th>${Object.values(FINITE).map(t => `<th>${t}</th>`).join('')}</tr></thead><tbody></tbody></table></div>
    <p class="note">Verbal nouns</p>
    <div class="scroll"><table class="par" id="p-nom"><thead><tr><th>Form</th>${NUMS.map(n => `<th>${n}</th>`).join('')}</tr></thead><tbody></tbody></table></div>`;
  for (const p of PERSONS) {
    const cells = Object.keys(FINITE).map(tam => `<td>${cell(gen({ ...base, TAM: tam, Subj: p, Neg: neg }).forms)}</td>`);
    $('#p-fin tbody').insertAdjacentHTML('beforeend', `<tr><td><b>${p}</b></td>${cells.join('')}</tr>`);
    await tick();
  }
  for (const [tam, label] of Object.entries(NOMINAL)) {
    const cells = NUMS.map(n => `<td>${cell(gen({ ...base, TAM: tam, Subj: '3' + n }).forms)}</td>`);
    $('#p-nom tbody').insertAdjacentHTML('beforeend', `<tr><td><b>${label}</b></td>${cells.join('')}</tr>`);
    await tick();
  }
  btn.disabled = false;
}
$('#g-go').onclick = () => { $('#p-out').innerHTML = ''; runGenerate(); };
$('#g-root').onkeydown = e => { if (e.key === 'Enter') $('#g-go').click(); };
$('#p-go').onclick = runParadigm;

// ---------- normalize
$('#n-go').onclick = () => {
  const { text, changes } = JSON.parse(W.normalize($('#n-in').value, $('#n-level').value));
  $('#n-out').value = text;
  $('#n-log').innerHTML = changes.length
    ? `<p class="note">Word changes</p><table><thead><tr><th>Original</th><th>Standard</th><th>Count</th></tr></thead><tbody>${
        changes.map(([a, b, c]) => `<tr><td class="gz">${esc(a)}</td><td class="gz">${esc(b)}</td><td>${c}</td></tr>`).join('')}</tbody></table>`
    : '<p class="note">No word-level changes (characters and punctuation may still have changed).</p>';
};

boot();
</script>
</body>
</html>