uzmorph-segtok 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. uzmorph_segtok-0.1.0/MANIFEST.in +4 -0
  2. uzmorph_segtok-0.1.0/PKG-INFO +75 -0
  3. uzmorph_segtok-0.1.0/README.md +53 -0
  4. uzmorph_segtok-0.1.0/pyproject.toml +28 -0
  5. uzmorph_segtok-0.1.0/setup.cfg +4 -0
  6. uzmorph_segtok-0.1.0/setup.py +31 -0
  7. uzmorph_segtok-0.1.0/uzmorph_segtok.egg-info/PKG-INFO +75 -0
  8. uzmorph_segtok-0.1.0/uzmorph_segtok.egg-info/SOURCES.txt +27 -0
  9. uzmorph_segtok-0.1.0/uzmorph_segtok.egg-info/dependency_links.txt +1 -0
  10. uzmorph_segtok-0.1.0/uzmorph_segtok.egg-info/requires.txt +2 -0
  11. uzmorph_segtok-0.1.0/uzmorph_segtok.egg-info/top_level.txt +1 -0
  12. uzmorph_segtok-0.1.0/uzmorphsegtok/__init__.py +20 -0
  13. uzmorph_segtok-0.1.0/uzmorphsegtok/config.py +15 -0
  14. uzmorph_segtok-0.1.0/uzmorphsegtok/cse.py +270 -0
  15. uzmorph_segtok-0.1.0/uzmorphsegtok/data/affixes.csv +1 -0
  16. uzmorph_segtok-0.1.0/uzmorphsegtok/data/paradigm_stats.json +1 -0
  17. uzmorph_segtok-0.1.0/uzmorphsegtok/data/stems.csv +54945 -0
  18. uzmorph_segtok-0.1.0/uzmorphsegtok/femseg.py +285 -0
  19. uzmorph_segtok-0.1.0/uzmorphsegtok/metrics.py +88 -0
  20. uzmorph_segtok-0.1.0/uzmorphsegtok/models/femseg/full_s17.pt +0 -0
  21. uzmorph_segtok-0.1.0/uzmorphsegtok/models/tokenizers/bpe_fem_32000.json +159140 -0
  22. uzmorph_segtok-0.1.0/uzmorphsegtok/models/tokenizers/uni_fem_32000.json +128049 -0
  23. uzmorph_segtok-0.1.0/uzmorphsegtok/phonology.py +97 -0
  24. uzmorph_segtok-0.1.0/uzmorphsegtok/reference.py +132 -0
  25. uzmorph_segtok-0.1.0/uzmorphsegtok/rule_seg.py +172 -0
  26. uzmorph_segtok-0.1.0/uzmorphsegtok/segmenters.py +93 -0
  27. uzmorph_segtok-0.1.0/uzmorphsegtok/synthetic.py +109 -0
  28. uzmorph_segtok-0.1.0/uzmorphsegtok/text.py +130 -0
  29. uzmorph_segtok-0.1.0/uzmorphsegtok/tokenizers.py +174 -0
@@ -0,0 +1,4 @@
1
+ include LICENSE
2
+ include README.md
3
+ recursive-include uzmorphsegtok/data *
4
+ recursive-include uzmorphsegtok/models *
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: uzmorph-segtok
3
+ Version: 0.1.0
4
+ Summary: Ending-Constrained Neural Morphological Segmentation and Tokenization for Uzbek
5
+ Home-page: https://github.com/UlugbekSalaev/UzMorphSegTok
6
+ Author: Ulugbek Salaev
7
+ Author-email: Ulugbek Salaev <ulugbek0302@gmail.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/UlugbekSalaev/UzMorphSegTok
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Classifier: Topic :: Text Processing :: Linguistic
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: torch>=1.12.0
18
+ Requires-Dist: tokenizers>=0.13.0
19
+ Dynamic: author
20
+ Dynamic: home-page
21
+ Dynamic: requires-python
22
+
23
+ # uzmorph-segtok
24
+
25
+ Neural Morphological Segmentation and Morphology-Aware Subword Tokenization for Uzbek.
26
+
27
+ Based on the research paper: *Ending-Constrained Neural Morphological Segmentation and Morphology-Aware Tokenization for Uzbek* (IEEE Access, 2026).
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install uzmorph-segtok
33
+ ```
34
+
35
+ ## Quick Start
36
+
37
+ ### 1. Morphological Segmentation (Morpheme Boundary Detection)
38
+
39
+ ```python
40
+ from uzmorphsegtok import FEMSegmenter, CSESegmenter
41
+
42
+ # Neural segmenter (FEMSeg-uz)
43
+ fem = FEMSegmenter()
44
+ print(fem.segment("kitoblarimizda"))
45
+ # Output: ['kitob', 'lar', 'imiz', 'da']
46
+
47
+ print(fem.segment("o'qituvchilarimizning", as_string=True))
48
+ # Output: "o'qituvchi + lar + imiz + ning"
49
+
50
+ # Rule-based segmenter (CSE-Seg+P)
51
+ rule = CSESegmenter()
52
+ print(rule.segment("maktabgacha", as_string=True))
53
+ # Output: "maktab + gacha"
54
+ ```
55
+
56
+ ### 2. Morphology-Aware Tokenization
57
+
58
+ ```python
59
+ from uzmorphsegtok import load_morph_tokenizer
60
+
61
+ # Load pretrained morphology-aware BPE tokenizer (32k vocab)
62
+ tok = load_morph_tokenizer("bpe_fem_32000")
63
+ encoded = tok.encode("Bolalar maktabga ketishdi")
64
+ print("Tokens:", [tok.id_to_piece(i) for i, _, _ in encoded])
65
+ ```
66
+
67
+ ## Features
68
+
69
+ - **FEMSeg-uz Model**: Character-level neural segmenter constrained by Complete Set of Endings (CSE) morphotactics.
70
+ - **Morphology-Aware Subwords**: BPE and Unigram tokenizers trained to preserve morpheme boundaries, preventing subword fragmentation in Uzbek NLP pipelines.
71
+ - **Lightweight**: Pretrained neural weights (~1.2 MB) optimized for fast CPU inference.
72
+
73
+ ## License
74
+
75
+ MIT License.
@@ -0,0 +1,53 @@
1
+ # uzmorph-segtok
2
+
3
+ Neural Morphological Segmentation and Morphology-Aware Subword Tokenization for Uzbek.
4
+
5
+ Based on the research paper: *Ending-Constrained Neural Morphological Segmentation and Morphology-Aware Tokenization for Uzbek* (IEEE Access, 2026).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install uzmorph-segtok
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ### 1. Morphological Segmentation (Morpheme Boundary Detection)
16
+
17
+ ```python
18
+ from uzmorphsegtok import FEMSegmenter, CSESegmenter
19
+
20
+ # Neural segmenter (FEMSeg-uz)
21
+ fem = FEMSegmenter()
22
+ print(fem.segment("kitoblarimizda"))
23
+ # Output: ['kitob', 'lar', 'imiz', 'da']
24
+
25
+ print(fem.segment("o'qituvchilarimizning", as_string=True))
26
+ # Output: "o'qituvchi + lar + imiz + ning"
27
+
28
+ # Rule-based segmenter (CSE-Seg+P)
29
+ rule = CSESegmenter()
30
+ print(rule.segment("maktabgacha", as_string=True))
31
+ # Output: "maktab + gacha"
32
+ ```
33
+
34
+ ### 2. Morphology-Aware Tokenization
35
+
36
+ ```python
37
+ from uzmorphsegtok import load_morph_tokenizer
38
+
39
+ # Load pretrained morphology-aware BPE tokenizer (32k vocab)
40
+ tok = load_morph_tokenizer("bpe_fem_32000")
41
+ encoded = tok.encode("Bolalar maktabga ketishdi")
42
+ print("Tokens:", [tok.id_to_piece(i) for i, _, _ in encoded])
43
+ ```
44
+
45
+ ## Features
46
+
47
+ - **FEMSeg-uz Model**: Character-level neural segmenter constrained by Complete Set of Endings (CSE) morphotactics.
48
+ - **Morphology-Aware Subwords**: BPE and Unigram tokenizers trained to preserve morpheme boundaries, preventing subword fragmentation in Uzbek NLP pipelines.
49
+ - **Lightweight**: Pretrained neural weights (~1.2 MB) optimized for fast CPU inference.
50
+
51
+ ## License
52
+
53
+ MIT License.
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "uzmorph-segtok"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name = "Ulugbek Salaev", email = "ulugbek0302@gmail.com" }
10
+ ]
11
+ description = "Ending-Constrained Neural Morphological Segmentation and Tokenization for Uzbek"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ license = { text = "MIT" }
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Topic :: Text Processing :: Linguistic"
21
+ ]
22
+ dependencies = [
23
+ "torch>=1.12.0",
24
+ "tokenizers>=0.13.0"
25
+ ]
26
+
27
+ [project.urls]
28
+ "Homepage" = "https://github.com/UlugbekSalaev/UzMorphSegTok"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,31 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="uzmorph-segtok",
5
+ version="0.1.0",
6
+ author="Ulugbek Salaev",
7
+ author_email="ulugbek0302@gmail.com",
8
+ description="Ending-Constrained Neural Morphological Segmentation and Tokenization for Uzbek",
9
+ long_description=open("README.md", encoding="utf-8").read(),
10
+ long_description_content_type="text/markdown",
11
+ url="https://github.com/UlugbekSalaev/UzMorphSegTok",
12
+ packages=find_packages(),
13
+ include_package_data=True,
14
+ package_data={
15
+ "uzmorphsegtok": [
16
+ "data/*",
17
+ "models/**/*",
18
+ ]
19
+ },
20
+ install_requires=[
21
+ "torch>=1.12.0",
22
+ "tokenizers>=0.13.0",
23
+ ],
24
+ classifiers=[
25
+ "Programming Language :: Python :: 3",
26
+ "License :: OSI Approved :: MIT License",
27
+ "Operating System :: OS Independent",
28
+ "Topic :: Text Processing :: Linguistic",
29
+ ],
30
+ python_requires=">=3.8",
31
+ )
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: uzmorph-segtok
3
+ Version: 0.1.0
4
+ Summary: Ending-Constrained Neural Morphological Segmentation and Tokenization for Uzbek
5
+ Home-page: https://github.com/UlugbekSalaev/UzMorphSegTok
6
+ Author: Ulugbek Salaev
7
+ Author-email: Ulugbek Salaev <ulugbek0302@gmail.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/UlugbekSalaev/UzMorphSegTok
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Classifier: Topic :: Text Processing :: Linguistic
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: torch>=1.12.0
18
+ Requires-Dist: tokenizers>=0.13.0
19
+ Dynamic: author
20
+ Dynamic: home-page
21
+ Dynamic: requires-python
22
+
23
+ # uzmorph-segtok
24
+
25
+ Neural Morphological Segmentation and Morphology-Aware Subword Tokenization for Uzbek.
26
+
27
+ Based on the research paper: *Ending-Constrained Neural Morphological Segmentation and Morphology-Aware Tokenization for Uzbek* (IEEE Access, 2026).
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install uzmorph-segtok
33
+ ```
34
+
35
+ ## Quick Start
36
+
37
+ ### 1. Morphological Segmentation (Morpheme Boundary Detection)
38
+
39
+ ```python
40
+ from uzmorphsegtok import FEMSegmenter, CSESegmenter
41
+
42
+ # Neural segmenter (FEMSeg-uz)
43
+ fem = FEMSegmenter()
44
+ print(fem.segment("kitoblarimizda"))
45
+ # Output: ['kitob', 'lar', 'imiz', 'da']
46
+
47
+ print(fem.segment("o'qituvchilarimizning", as_string=True))
48
+ # Output: "o'qituvchi + lar + imiz + ning"
49
+
50
+ # Rule-based segmenter (CSE-Seg+P)
51
+ rule = CSESegmenter()
52
+ print(rule.segment("maktabgacha", as_string=True))
53
+ # Output: "maktab + gacha"
54
+ ```
55
+
56
+ ### 2. Morphology-Aware Tokenization
57
+
58
+ ```python
59
+ from uzmorphsegtok import load_morph_tokenizer
60
+
61
+ # Load pretrained morphology-aware BPE tokenizer (32k vocab)
62
+ tok = load_morph_tokenizer("bpe_fem_32000")
63
+ encoded = tok.encode("Bolalar maktabga ketishdi")
64
+ print("Tokens:", [tok.id_to_piece(i) for i, _, _ in encoded])
65
+ ```
66
+
67
+ ## Features
68
+
69
+ - **FEMSeg-uz Model**: Character-level neural segmenter constrained by Complete Set of Endings (CSE) morphotactics.
70
+ - **Morphology-Aware Subwords**: BPE and Unigram tokenizers trained to preserve morpheme boundaries, preventing subword fragmentation in Uzbek NLP pipelines.
71
+ - **Lightweight**: Pretrained neural weights (~1.2 MB) optimized for fast CPU inference.
72
+
73
+ ## License
74
+
75
+ MIT License.
@@ -0,0 +1,27 @@
1
+ MANIFEST.in
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ uzmorph_segtok.egg-info/PKG-INFO
6
+ uzmorph_segtok.egg-info/SOURCES.txt
7
+ uzmorph_segtok.egg-info/dependency_links.txt
8
+ uzmorph_segtok.egg-info/requires.txt
9
+ uzmorph_segtok.egg-info/top_level.txt
10
+ uzmorphsegtok/__init__.py
11
+ uzmorphsegtok/config.py
12
+ uzmorphsegtok/cse.py
13
+ uzmorphsegtok/femseg.py
14
+ uzmorphsegtok/metrics.py
15
+ uzmorphsegtok/phonology.py
16
+ uzmorphsegtok/reference.py
17
+ uzmorphsegtok/rule_seg.py
18
+ uzmorphsegtok/segmenters.py
19
+ uzmorphsegtok/synthetic.py
20
+ uzmorphsegtok/text.py
21
+ uzmorphsegtok/tokenizers.py
22
+ uzmorphsegtok/data/affixes.csv
23
+ uzmorphsegtok/data/paradigm_stats.json
24
+ uzmorphsegtok/data/stems.csv
25
+ uzmorphsegtok/models/femseg/full_s17.pt
26
+ uzmorphsegtok/models/tokenizers/bpe_fem_32000.json
27
+ uzmorphsegtok/models/tokenizers/uni_fem_32000.json
@@ -0,0 +1,2 @@
1
+ torch>=1.12.0
2
+ tokenizers>=0.13.0
@@ -0,0 +1 @@
1
+ uzmorphsegtok
@@ -0,0 +1,20 @@
1
+ """
2
+ uzmorph-segtok: Ending-Constrained Neural Morphological Segmentation and Morphology-Aware Tokenization for Uzbek.
3
+
4
+ Paper: Ending-Constrained Neural Morphological Segmentation and Morphology-Aware Tokenization for Uzbek (IEEE Access, 2026)
5
+ Authors: Ozod Yusupov, Ulugbek Salaev, Rabbim Yusupov, Shukhrat Mamadjanov, Sherzod Kholikulov
6
+ """
7
+
8
+ __version__ = "0.1.0"
9
+ __author__ = "Ulugbek Salaev"
10
+
11
+ from .segmenters import CSESegmenter, FEMSegmenter
12
+ from .tokenizers import load_morph_tokenizer, insert_boundaries, pre_tokenizer
13
+
14
+ __all__ = [
15
+ "FEMSegmenter",
16
+ "CSESegmenter",
17
+ "load_morph_tokenizer",
18
+ "insert_boundaries",
19
+ "pre_tokenizer",
20
+ ]
@@ -0,0 +1,15 @@
1
+ """Package-internal configuration for uzmorph-segtok runtime paths."""
2
+ import os
3
+
4
+ PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
5
+ DATA_DIR = os.path.join(PACKAGE_DIR, "data")
6
+ MODELS_DIR = os.path.join(PACKAGE_DIR, "models")
7
+
8
+ # Data resources
9
+ CSE_CSV = os.path.join(DATA_DIR, "affixes.csv")
10
+ LEXICON = os.path.join(DATA_DIR, "stems.csv")
11
+ CORPUS_DIR = DATA_DIR # contains paradigm_stats.json
12
+
13
+ # Model resources
14
+ SEG_DIR = os.path.join(MODELS_DIR, "femseg")
15
+ TOK_DIR = os.path.join(MODELS_DIR, "tokenizers")
@@ -0,0 +1,270 @@
1
+ """The complete set of endings (CSE) of UzMorphAnalyser and the division of a word into morphemes with it.
2
+
3
+ Each CSE entry is a suffix chain that follows a stem, for example (i)mizdan = (i)miz + dan.
4
+ The table lists the morphemes of a chain in two columns (lexical_affixes, syntactical_affixes), but their order and
5
+ spelling are not always those of the chain (lik+i -> ligi, mi at the end and so on).
6
+ The morphemes are therefore aligned with the chain by dynamic programming (decompose_all).
7
+
8
+ Allomorph symbols of the table:
9
+ G = g/k/q (after k and q of the stem), Y = a/y, (i), (a), (u) are dropped after a vowel,
10
+ (S) gives s after a vowel, (n) is dropped after n; the choice for T, A, Q, K and (t) depends on the stem itself.
11
+ """
12
+ import csv
13
+ import itertools
14
+ from collections import Counter
15
+
16
+ from .text import normalize, is_word
17
+
18
+ VOWELS = set('aeiou')
19
+ ALLOMORPHS = {'G': ['g', 'k', 'q'], 'K': ['g', 'k'], 'Y': ['a', 'y'], 'T': ['t', 'd'],
20
+ 'Q': ['g', "g'", 'k', 'q'], 'S': ['s', 'y'], 'A': ['a', 'i']}
21
+
22
+
23
+ # ----------------------------------------------------------------------------- helpers
24
+ def ends_with_vowel(s):
25
+ return s.endswith("o'") or (len(s) > 0 and s[-1] in VOWELS)
26
+
27
+
28
+ def starts_with_vowel(s):
29
+ return s.startswith("o'") or (len(s) > 0 and s[0] in VOWELS)
30
+
31
+
32
+ def ending_parts(abstract):
33
+ """'(i)mizdan' -> ['(i)', 'm', 'i', 'z', 'd', 'a', 'n']"""
34
+ out, i = [], 0
35
+ while i < len(abstract):
36
+ if abstract[i] == '(':
37
+ j = abstract.index(')', i)
38
+ out.append(abstract[i:j + 1])
39
+ i = j + 1
40
+ else:
41
+ out.append(abstract[i])
42
+ i += 1
43
+ return out
44
+
45
+
46
+ # ----------------------------------------------------------------------------- reading the table
47
+ def read_rows(path):
48
+ with open(path, encoding='utf-8', newline='') as f:
49
+ return list(csv.DictReader(f))
50
+
51
+
52
+ # ----------------------------------------------------------------------------- division into morphemes
53
+ def token_variants(tok):
54
+ """Forms that a listed morpheme can take inside a chain: a bracketed part is kept, opened or dropped; a final k/q
55
+ becomes g/g' before a vowel; a vowel-initial morpheme can be written with that vowel in brackets (imiz -> (i)miz)."""
56
+ opts = [[p, p[1:-1], ''] if p.startswith('(') else [p] for p in ending_parts(tok)]
57
+ out = {''.join(c).lower() for c in itertools.product(*opts)} - {''}
58
+ out |= {s[:-1] + 'g' for s in out if s.endswith('k')} | {s[:-1] + "g'" for s in out if s.endswith('q')}
59
+ out |= {f'({s[0]}){s[1:]}' for s in out if len(s) > 1 and s[0] in 'iau'}
60
+ return out
61
+
62
+
63
+ def align(abstract, tokens):
64
+ """Align a chain with its listed morphemes (in any order).
65
+ Cost: 2 for an unmatched run, 1 for an unused morpheme. Result: (cost, [(piece, kind)])."""
66
+ a = abstract.lower()
67
+ n, m = len(a), len(tokens)
68
+ variants = [token_variants(t) for t in tokens]
69
+ best = {(0, 0): (0, [])}
70
+ for i in range(n + 1):
71
+ for mask in range(1 << m):
72
+ if (i, mask) not in best:
73
+ continue
74
+ cost, seg = best[(i, mask)]
75
+
76
+ def update(key, c, s):
77
+ old = best.get(key)
78
+ if old is None or c < old[0] or (c == old[0] and len(s) > len(old[1])):
79
+ best[key] = (c, s)
80
+
81
+ for j in range(m):
82
+ if not mask >> j & 1:
83
+ for v in variants[j]:
84
+ if a.startswith(v, i):
85
+ update((i + len(v), mask | 1 << j), cost, seg + [(abstract[i:i + len(v)], 'T')])
86
+ if i < n:
87
+ k = a.index(')', i) + 1 if a[i] == '(' else i + 1
88
+ if seg and seg[-1][1] == 'G':
89
+ update((k, mask), cost, seg[:-1] + [(seg[-1][0] + abstract[i:k], 'G')])
90
+ else:
91
+ update((k, mask), cost + 2, seg + [(abstract[i:k], 'G')])
92
+ finals = [(c + m - bin(mask).count('1'), s) for (i, mask), (c, s) in best.items() if i == n]
93
+ return min(finals, key=lambda x: (x[0], -len(x[1])))
94
+
95
+
96
+ def split_with_inventory(piece, inventory):
97
+ """Split an unmatched run into the fewest known morphemes (it stays whole if that is not possible)."""
98
+ a = piece.lower()
99
+ n = len(a)
100
+ best = {0: []}
101
+ for i in range(n):
102
+ if i not in best:
103
+ continue
104
+ for v in inventory:
105
+ if a.startswith(v, i):
106
+ j = i + len(v)
107
+ cand = best[i] + [piece[i:j]]
108
+ if j not in best or len(cand) < len(best[j]):
109
+ best[j] = cand
110
+ return best.get(n, [piece])
111
+
112
+
113
+ def decompose_all(rows):
114
+ """The morphemes of the chain of every entry (in abstract form)."""
115
+ raw_tokens = {}
116
+ freq = Counter()
117
+ for r in rows:
118
+ toks = (r['lexical_affixes'] + ' ' + r['syntactical_affixes']).replace(',', ' ').split()
119
+ raw_tokens[r['id']] = toks
120
+ freq.update(set(toks))
121
+ inventory = {v for t, c in freq.items() if c >= 3 for v in token_variants(t)}
122
+ split_inventory = {v for t, c in freq.items() if c >= 10 for v in token_variants(t)}
123
+ result = {}
124
+ for r in rows:
125
+ cost, seg = align(r['affix'], raw_tokens[r['id']])
126
+ pieces = []
127
+ for piece, kind in seg:
128
+ if kind == 'G':
129
+ pieces += [(x, 'G') for x in split_with_inventory(piece, split_inventory)]
130
+ else:
131
+ pieces.append((piece, 'T'))
132
+ # an unmatched remainder of one part is joined to a neighbour: (S)+i -> (S)i, m+i -> mi
133
+ k = 0
134
+ while k < len(pieces):
135
+ piece, kind = pieces[k]
136
+ if kind == 'G' and len(ending_parts(piece)) == 1 and len(pieces) > 1:
137
+ if k > 0 and (pieces[k - 1][0] + piece).lower() in inventory:
138
+ pieces[k - 1:k + 1] = [(pieces[k - 1][0] + piece, 'T')]
139
+ continue
140
+ if k + 1 < len(pieces) and (piece + pieces[k + 1][0]).lower() in inventory:
141
+ pieces[k:k + 2] = [(piece + pieces[k + 1][0], 'T')]
142
+ continue
143
+ k += 1
144
+ morphs = [p for p, _ in pieces]
145
+ result[r['id']] = morphs
146
+ return harmonize(result)
147
+
148
+
149
+ def harmonize(decomp):
150
+ """The same suffix is sometimes written as one morpheme and sometimes as two (laring / lar+ing).
151
+ If most entries split it, it is split in the others as well."""
152
+ single = Counter(m.lower() for ms in decomp.values() for m in ms)
153
+ pair = Counter()
154
+ for ms in decomp.values():
155
+ for a, b in zip(ms, ms[1:]):
156
+ pair[(a.lower() + b.lower(), a, b)] += 1
157
+ splits = {}
158
+ for (joined, a, b), c in pair.items():
159
+ if c > single.get(joined, 0) and single.get(joined, 0) > 0:
160
+ if joined not in splits or c > splits[joined][2]:
161
+ splits[joined] = (a, b, c)
162
+ out = {}
163
+ for eid, ms in decomp.items():
164
+ new = []
165
+ for m in ms:
166
+ key = m.lower()
167
+ if key in splits:
168
+ a, b, _ = splits[key]
169
+ new += [m[:len(a)], m[len(a):]]
170
+ else:
171
+ new.append(m)
172
+ out[eid] = new
173
+ return out
174
+
175
+
176
+ # ----------------------------------------------------------------------------- allomorphs
177
+ def realise_parts(parts, prev):
178
+ """All possible spellings of one morpheme after the string prev."""
179
+ outs = ['']
180
+ for p in parts:
181
+ new = []
182
+ for out in outs:
183
+ cur = prev + out
184
+ if p.startswith('('):
185
+ inner = p[1:-1]
186
+ if inner in ('i', 'a', 'u'):
187
+ opts = [''] if ends_with_vowel(cur) else [inner]
188
+ elif inner == 'S':
189
+ opts = ['s'] if ends_with_vowel(cur) else ['']
190
+ elif inner == 'n':
191
+ opts = [''] if cur.endswith('n') else ['n']
192
+ elif inner in ALLOMORPHS:
193
+ opts = ALLOMORPHS[inner] + ['']
194
+ else:
195
+ opts = [normalize(inner), '']
196
+ elif p == 'G':
197
+ opts = ['k'] if cur.endswith('k') else ['q'] if cur.endswith('q') else ['g']
198
+ elif p == 'Y':
199
+ opts = ['y'] if ends_with_vowel(cur) else ['a']
200
+ elif p == 'S':
201
+ opts = ['s'] if ends_with_vowel(cur) else ['']
202
+ elif p in ALLOMORPHS:
203
+ opts = ALLOMORPHS[p]
204
+ else:
205
+ opts = [normalize(p)]
206
+ new += [out + o for o in opts]
207
+ outs = new
208
+ return outs
209
+
210
+
211
+ def realise(morphs, stem):
212
+ """Realizations of a CSE chain after a stem: [(spelling, [spellings of the morphemes])]."""
213
+ results = [('', [])]
214
+ for m in morphs:
215
+ new = []
216
+ for s, ms in results:
217
+ for o in realise_parts(ending_parts(m), stem + s):
218
+ if o:
219
+ new.append((s + o, ms + [o]))
220
+ results = new
221
+ return [(s, ms) for s, ms in results if s]
222
+
223
+
224
+ def surface_forms(morphs):
225
+ """All spellings without context (for the index): stems ending in a vowel, k, q, n or another consonant."""
226
+ out = set()
227
+ for stem in ('kitob', 'ola', 'yurak', 'qishloq', 'xon'):
228
+ for s, _ in realise(morphs, stem):
229
+ out.add(s)
230
+ return out
231
+
232
+
233
+ # ----------------------------------------------------------------------------- table and lexicon
234
+ class CSE:
235
+ """CSE table: entries, their morphemes and an index by spelling."""
236
+
237
+ def __init__(self, rows):
238
+ decomp = decompose_all(rows)
239
+ self.entries = []
240
+ for r in rows:
241
+ morphs = decomp[r['id']]
242
+ self.entries.append({'id': int(r['id']), 'abstract': r['affix'], 'pos': r['pos'], 'morphs': morphs,
243
+ 'row': r, 'sample_roots': [normalize(x) for x in r['root'].split('/')
244
+ if is_word(normalize(x))]})
245
+ self.index = {}
246
+ for i, e in enumerate(self.entries):
247
+ for s in surface_forms(e['morphs']):
248
+ self.index.setdefault(s, []).append(i)
249
+ self.max_len = max(len(s) for s in self.index)
250
+ self.morph_inventory = Counter(m for e in self.entries for m in e['morphs'])
251
+
252
+ def analyses(self, stem_surface, ending):
253
+ """Entries that give `ending` after the written stem, with their morphemes."""
254
+ out = []
255
+ for i in self.index.get(ending, ()):
256
+ for s, ms in realise(self.entries[i]['morphs'], stem_surface):
257
+ if s == ending:
258
+ out.append((i, tuple(ms)))
259
+ return out
260
+
261
+
262
+ def load_lexicon(path):
263
+ """Stem lexicon: stem -> parts of speech."""
264
+ lexicon = {}
265
+ with open(path, encoding='utf-8', newline='') as f:
266
+ for row in csv.DictReader(f):
267
+ w = normalize(row['stem'])
268
+ if is_word(w):
269
+ lexicon.setdefault(w, set()).add(row['pos'].strip())
270
+ return lexicon
@@ -0,0 +1 @@
1
+ id,root,affix,info,pos,tense,person,possession,cases,verb_voice1,verb_voice2,verb_voice3,verb_func,impulsion,degree,copula,singular,plural,question,negative,polite,lexical_affixes,syntactical_affixes