pyasjp 1.6.0__py3-none-any.whl

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.
pyasjp/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ #
2
+ from pyasjp.api import ASJP # noqa: F401
3
+
4
+ __version__ = '1.6.0'
pyasjp/__main__.py ADDED
@@ -0,0 +1,34 @@
1
+ import sys
2
+ import contextlib
3
+
4
+ from clldutils.clilib import get_parser_and_subparsers, register_subcommands
5
+ from clldutils.loglib import Logging
6
+
7
+ import pyasjp.commands
8
+
9
+
10
+ def main(args=None, catch_all=False, parsed_args=None):
11
+ parser, subparsers = get_parser_and_subparsers('asjp')
12
+ register_subcommands(subparsers, pyasjp.commands)
13
+
14
+ args = parsed_args or parser.parse_args(args=args)
15
+
16
+ if not hasattr(args, "main"): # pragma: no cover
17
+ parser.print_help()
18
+ return 1
19
+
20
+ with contextlib.ExitStack() as stack:
21
+ stack.enter_context(Logging(args.log, level=args.log_level))
22
+ try:
23
+ return args.main(args) or 0
24
+ except KeyboardInterrupt: # pragma: no cover
25
+ return 0
26
+ except Exception as e: # pragma: no cover
27
+ if catch_all:
28
+ print(e)
29
+ return 1
30
+ raise
31
+
32
+
33
+ if __name__ == '__main__': # pragma: no cover
34
+ sys.exit(main() or 0)
pyasjp/api.py ADDED
@@ -0,0 +1,90 @@
1
+ import functools
2
+ import itertools
3
+ import collections
4
+
5
+ from clldutils.apilib import API
6
+ from csvw.dsv import reader
7
+
8
+ from pyasjp import models
9
+
10
+
11
+ def iter_chunks(fp):
12
+ wordlist = None
13
+
14
+ for line in fp:
15
+ m = models.LANGUAGE_LINE_PATTERN.match(line)
16
+ if m:
17
+ if wordlist:
18
+ yield wordlist
19
+ wordlist = [line]
20
+ else:
21
+ if wordlist:
22
+ wordlist.append(line)
23
+
24
+ if wordlist:
25
+ yield wordlist
26
+
27
+
28
+ class ASJP(API):
29
+ def __init__(self, repos=None):
30
+ super().__init__(repos)
31
+ self.missing_transcribers = collections.Counter()
32
+
33
+ def to_txt(self, *doculects, **kw):
34
+ res = [models.txt_header()]
35
+ wals_family, wals_genus = None, None
36
+ for dl in sorted(doculects, key=lambda d: (d.wals_family or 'ZZZ', d.wals_genus or 'ZZZ')):
37
+ if dl.wals_family and dl.wals_family != wals_family:
38
+ wals_marker = '3'
39
+ elif dl.wals_genus and dl.wals_genus != wals_genus:
40
+ wals_marker = '2'
41
+ else:
42
+ wals_marker = '1'
43
+ wals_family = dl.wals_family
44
+ wals_genus = dl.wals_genus
45
+ res.append(dl.to_txt(
46
+ add_missing=kw.get('add_missing', False),
47
+ full_list=kw.get('full_list', False),
48
+ wals_marker=wals_marker))
49
+ return '\n'.join(res) + '\n'
50
+
51
+ def iter_doculects(self, p=None):
52
+ ids = set()
53
+ p = p or self.repos / 'lists.txt'
54
+ with p.open(encoding='cp1252') as fp:
55
+ for chunk in iter_chunks(fp):
56
+ d = models.Doculect.from_txt('\n'.join(chunk))
57
+ if d.id in ids: # pragma: no cover
58
+ print('skipping duplicate doculect {}'.format(d.id))
59
+ continue
60
+ ids.add(d.id)
61
+ yield d
62
+
63
+ @functools.cached_property
64
+ def sources(self):
65
+ res = collections.defaultdict(list)
66
+ for i, row in enumerate(
67
+ reader(self.repos / 'sources.csv', dicts=True, encoding='utf8'),
68
+ start=1,
69
+ ):
70
+ res[row['ASJP_NAME'].lower().replace('-', '_')].append(models.Source(
71
+ id=i, **{k.lower(): v for k, v in row.items()}))
72
+ return res
73
+
74
+ def source(self, dl):
75
+ return self.sources.get(dl.asjp_name.lower())
76
+
77
+ def transcriber(self, dl):
78
+ srcs = self.source(dl)
79
+ if srcs:
80
+ trss = sorted(set(itertools.chain(*[src.list_made_by for src in srcs])))
81
+ for trs in trss:
82
+ if trs not in self.transcribers: # pragma: no cover
83
+ self.missing_transcribers.update([trs])
84
+ return [self.transcribers[trs] for trs in trss if trs in self.transcribers]
85
+
86
+ @functools.cached_property
87
+ def transcribers(self):
88
+ return {
89
+ t.id: t for t in
90
+ [models.Transcriber(*row) for row in reader(self.repos / 'transcribers.csv')]}
File without changes
@@ -0,0 +1,59 @@
1
+ """
2
+ Diff synsets between two ASJP releases.
3
+
4
+ This command only compares the forms for synsets present in both releases, i.e. whether forms have
5
+ changed - **not** whether synsets were added or removed.
6
+ """
7
+ import collections
8
+
9
+ from clldutils.clilib import PathType
10
+
11
+ from pyasjp import ASJP
12
+ from pyasjp.meanings import MEANINGS, MEANINGS_NON_CORE
13
+
14
+
15
+ def register(parser):
16
+ parser.add_argument(
17
+ 'listA',
18
+ type=PathType(type='file')
19
+ )
20
+ parser.add_argument(
21
+ 'listB',
22
+ type=PathType(type='file')
23
+ )
24
+ parser.add_argument(
25
+ '--match-label',
26
+ help="Match synsets based on meaning label rather than meaning number",
27
+ action='store_true',
28
+ default=False,
29
+ )
30
+
31
+
32
+ def run(args):
33
+ api = ASJP('.')
34
+ reverse_meaning_lookup = {}
35
+ for mid, ms in MEANINGS.items():
36
+ for m in ms:
37
+ reverse_meaning_lookup[m] = mid
38
+ for mid, m in MEANINGS_NON_CORE.items():
39
+ reverse_meaning_lookup[m] = mid
40
+
41
+ formsA = collections.defaultdict(lambda: collections.defaultdict(dict))
42
+ for dl in api.iter_doculects(args.listA):
43
+ for ss in dl.synsets:
44
+ mid = reverse_meaning_lookup[ss.meaning] if args.match_label else ss.meaning_id
45
+ formsA[dl.id][mid] = ', '.join(str(w) for w in ss.words)
46
+
47
+ for dl in api.iter_doculects(args.listB):
48
+ if dl.id in formsA:
49
+ for ss in dl.synsets:
50
+ mid = reverse_meaning_lookup[ss.meaning] if args.match_label else ss.meaning_id
51
+ if mid in formsA[dl.id]:
52
+ formsB = ', '.join(str(w) for w in ss.words)
53
+ formsetB = set(
54
+ w.strip().replace('~', '') for w in formsB.split(','))
55
+ formsetA = set(
56
+ w.strip().replace('~', '') for w in formsA[dl.id][mid].split(','))
57
+ # if formsA[dl.id][mid] != formsB:
58
+ if formsetA != formsetB:
59
+ print('{}:{}:{} -> {}'.format(dl.id, mid, formsA[dl.id][mid], formsB))
@@ -0,0 +1,24 @@
1
+ """
2
+ Convert an ASJP database to tab-delimited "formatted" data.
3
+ """
4
+ import csv
5
+
6
+ from clldutils.clilib import PathType
7
+ from csvw.dsv import UnicodeWriter
8
+
9
+ from pyasjp import ASJP
10
+
11
+
12
+ def register(parser):
13
+ parser.add_argument('list', type=PathType())
14
+ parser.add_argument('out', type=PathType(must_exist=False, type='file'))
15
+
16
+
17
+ def run(args):
18
+ api = ASJP(args.list if args.list.is_dir() else '.')
19
+
20
+ with UnicodeWriter(args.out, delimiter='\t', quoting=csv.QUOTE_NONE, quotechar="…") as w:
21
+ for i, dl in enumerate(api.iter_doculects(args.list if args.list.is_file() else None)):
22
+ if not i:
23
+ w.writerow(dl.formatted_header())
24
+ w.writerow(dl.to_formatted_row())
pyasjp/meanings.py ADDED
@@ -0,0 +1,115 @@
1
+ __all__ = ['MEANINGS', 'MEANINGS_ALL', 'MEANINGS_NON_CORE']
2
+
3
+ MEANINGS = {
4
+ 1: ['I', 'je', 'ego', 'yo'],
5
+ 2: ['you', 'tú', 'tu', 'thou', 'tu, vos'],
6
+ 3: ['we', 'nous', 'nosotros', 'we two', 'nos', 'we (incl.)'],
7
+ 11: ['one', 'uno', 'un', 'unus'],
8
+ 12: ['two', 'deux', 'duo', 'dos'],
9
+ 18: ['person', 'personne', 'persona', 'homo, quidam'],
10
+ 19: ['fish', 'poisson', 'pez', 'fisx', 'piscis'],
11
+ 21: ['dog', 'perro', 'canis', 'chien'],
12
+ 22: ['louse', 'piojo', 'pediculus', 'pou'],
13
+ 23: ['tree', 'arbor', 'arbre', 'árbol', 'arbol'],
14
+ 25: ['leaf', 'folium', 'hoja', 'feuille'],
15
+ 28: ['skin', 'peaux', 'cutis, pellis', 'piel', 'peau'],
16
+ 30: ['blood', 'sangre', 'sang', 'sanguis'],
17
+ 31: ['bone', 'os', '%bone', 'hueso'],
18
+ 34: ['horn', 'corne', 'cuerno'],
19
+ 39: ['ear', 'oreille', 'oreja', 'auris'],
20
+ 40: ['eye', 'ojo', 'oculus', 'oeil'],
21
+ 41: ['nose', 'nariz', 'nez', 'nasus, nares'],
22
+ 43: ['tooth', 'dent', 'diente', 'dens'],
23
+ 44: ['tongue', 'lingua', 'lengua', 'langue'],
24
+ 47: ['knee', 'rodilla', 'genou', 'genu'],
25
+ 48: ['hand', 'main', 'mano', 'manus'],
26
+ 51: ['breast', 'breasts', 'seno', 'sein', 'mamma'],
27
+ 53: ['liver', 'higado', 'liverp', 'hígado', 'el higado', 'foie'],
28
+ 54: ['drink', 'boire', 'drinK', 'beber', 'bibere, potare', 'dring'],
29
+ 57: ['see', 'voir', 'ver'],
30
+ 58: ['hear', 'oir', 'oír', 'audire, exaudire', 'entendre', 'to hear'],
31
+ 61: ['die', 'morir', 'mourir', 'mori, obire'],
32
+ 66: ['come', 'venire', 'venir'],
33
+ 72: ['sun', 'soleil', 'sol'],
34
+ 74: ['star', 'etoile', 'estrella', 'stella, sidus'],
35
+ 75: ['water', 'eau', 'agua', 'aqua'],
36
+ 77: ['stone', 'piedra', 'pierre', 'lapis, saxum'],
37
+ 82: ['fire', 'firek', 'ignis', 'feu', 'fuego'],
38
+ 85: ['path', 'camino', 'semitas, trames, via', 'route', 'road', 'sendero'],
39
+ 86: ['mountain', 'mons', 'montagne', 'cerro', 'montaña', 'moundain'],
40
+ 92: ['night', 'noche', 'nuit'],
41
+ 95: ['full', 'full(ness)', 'lleno/a', 'plenus', 'lleno', 'plein'],
42
+ 96: ['new', 'nouveaux', 'nuevo'],
43
+ 100: ['name', 'nombre', 'nom', 'name (noun)'],
44
+ }
45
+
46
+ NMEANINGS = 100
47
+ MEANINGS_NON_CORE = {
48
+ 4: 'this',
49
+ 5: 'that',
50
+ 6: 'who',
51
+ 7: 'what',
52
+ 8: 'not',
53
+ 9: 'all',
54
+ 10: 'many',
55
+ 13: 'big',
56
+ 14: 'long',
57
+ 15: 'small',
58
+ 16: 'woman',
59
+ 17: 'man',
60
+ 20: 'bird',
61
+ 24: 'seed',
62
+ 26: 'root',
63
+ 27: 'bark',
64
+ 29: 'flesh',
65
+ 32: 'grease',
66
+ 33: 'egg',
67
+ 35: 'tail',
68
+ 36: 'feather',
69
+ 37: 'hair',
70
+ 38: 'head',
71
+ 42: 'mouth',
72
+ 45: 'claw',
73
+ 46: 'foot',
74
+ 49: 'belly',
75
+ 50: 'neck',
76
+ 52: 'heart',
77
+ 55: 'eat',
78
+ 56: 'bite',
79
+ 59: 'know',
80
+ 60: 'sleep',
81
+ 62: 'kill',
82
+ 63: 'swim',
83
+ 64: 'fly',
84
+ 65: 'walk',
85
+ 67: 'lie',
86
+ 68: 'sit',
87
+ 69: 'stand',
88
+ 70: 'give',
89
+ 71: 'say',
90
+ 73: 'moon',
91
+ 76: 'rain',
92
+ 78: 'sand',
93
+ 79: 'earth',
94
+ 80: 'cloud',
95
+ 81: 'smoke',
96
+ 83: 'ash',
97
+ 84: 'burn',
98
+ 87: 'red',
99
+ 88: 'green',
100
+ 89: 'yellow',
101
+ 90: 'white',
102
+ 91: 'black',
103
+ 93: 'hot',
104
+ 94: 'cold',
105
+ 97: 'good',
106
+ 98: 'round',
107
+ 99: 'dry',
108
+ }
109
+
110
+ MEANINGS_ALL = {}
111
+ MEANINGS_ALL.update({k: v[0] for k, v in MEANINGS.items()})
112
+ MEANINGS_ALL.update(MEANINGS_NON_CORE)
113
+ # Check consistency of the meanings (Keys are numbers from 1 to 100):
114
+ assert set(MEANINGS_ALL.keys()) == set(range(1, NMEANINGS + 1))
115
+ assert len(set(MEANINGS_ALL.values())) == NMEANINGS # Meaning labels are unique.
pyasjp/models.py ADDED
@@ -0,0 +1,347 @@
1
+ import re
2
+ import logging
3
+ import collections
4
+ import dataclasses
5
+
6
+ from clldutils.misc import nfilter
7
+
8
+ from pyasjp.meanings import MEANINGS, MEANINGS_ALL
9
+
10
+ __all__ = [
11
+ 'Transcriber', 'Source', 'Word', 'Synset', 'Doculect', 'ASJPCODES', 'txt_header',
12
+ 'valid_strict_orthography',
13
+ ]
14
+
15
+ # see
16
+ # Brown, Cecil H., Eric W. Holman, Søren Wichmann, and Viveka Vilupillai. 2008.
17
+ # Automated classification of the world’s languages:
18
+ # a description of the method and preliminary results.
19
+ # STUF – Language Typology and Universals 61:285-308.
20
+ CONSONANTS = 'pbfvmw8tdszcnrlSZCjT5ykgxNqXh7L4G!'
21
+ VOWELS = 'ieE3auo'
22
+ ASJPCODES = CONSONANTS + VOWELS
23
+ MODIFIERS = ''.join([
24
+ "*", # An asterisk following any one of the seven vowel symbols indicates vowel nasalization.
25
+ "~", # A modifier that follows two juxtaposed consonants.
26
+ "$", # Similar ~ except that it follows three juxtaposed consonants.
27
+ '"', # Immediately follows a consonant that is glottalized.
28
+ ])
29
+ PUNCTUATION = " "
30
+ WORD_PATTERN = re.compile('[{}]+'.format(re.escape(ASJPCODES + MODIFIERS + PUNCTUATION)))
31
+ MISSING_WORD = 'XXX'
32
+ LANGUAGE_LINE_PATTERN = re.compile(
33
+ r'(?P<name>[^{]+){(?P<w>[^|]*)\|(?P<e>[^@}]*)(@(?P<g>[^}]*))?}?')
34
+ RECENTLY_EXTINCT = -1
35
+ LONG_EXTINCT = -2
36
+
37
+
38
+ def valid_strict_orthography(word):
39
+ for modifier, modified in [
40
+ ('*', VOWELS),
41
+ ('~', CONSONANTS),
42
+ ('$', CONSONANTS),
43
+ ('"', CONSONANTS),
44
+ ]:
45
+ if re.search('(?<![{}]){}'.format(re.escape(modified), re.escape(modifier)), word):
46
+ raise ValueError('Misplaced modifier: {}'.format(word))
47
+
48
+
49
+ @dataclasses.dataclass
50
+ class Transcriber:
51
+ id: str
52
+ name: str
53
+
54
+
55
+ @dataclasses.dataclass
56
+ class Source:
57
+ id: str
58
+ asjp_name: str
59
+ author: str
60
+ year: str
61
+ title_etc: str
62
+ list_made_by: list[str]
63
+
64
+ def __post_init__(self):
65
+ self.list_made_by = nfilter([ss.strip() for ss in re.split(r'/|->', self.list_made_by)])
66
+
67
+
68
+ @dataclasses.dataclass
69
+ class Word:
70
+ form: str
71
+ loan: bool
72
+
73
+ def __post_init__(self):
74
+ assert WORD_PATTERN.fullmatch(self.form), self.form
75
+ assert isinstance(self.loan, bool)
76
+
77
+ @classmethod
78
+ def from_txt(cls, txt):
79
+ if txt.startswith('%'):
80
+ return cls(form=txt[1:], loan=True)
81
+ return cls(form=txt, loan=False)
82
+
83
+ def __str__(self):
84
+ return '%' + self.form if self.loan else self.form
85
+
86
+
87
+ @dataclasses.dataclass
88
+ class Synset:
89
+ meaning_id: int
90
+ meaning: str
91
+ words: list[Word]
92
+ comment: str | None
93
+
94
+ def __post_init__(self):
95
+ self.meaning_id = int(self.meaning_id)
96
+ assert self.meaning_id in MEANINGS_ALL
97
+
98
+ @classmethod
99
+ def from_txt(cls, line):
100
+ header, body = line.split('\t', 1)
101
+ body = body.strip()
102
+ comment = ''
103
+ if re.search(' | //', body):
104
+ body, comment = re.split(' | //', body, maxsplit=1)
105
+ # Degenerate cases:
106
+ elif re.fullmatch(r'[^/]+/\s*[^/]+/$', body):
107
+ body, comment, _ = body.split('/')
108
+ body = body.strip()
109
+ elif body.endswith('//'): # pragma: no cover
110
+ body = body[:-2].strip()
111
+ elif body.endswith('/'): # pragma: no cover
112
+ body = body[:-1].strip()
113
+ comment = comment.strip()
114
+ words = []
115
+ for word in body.split(','):
116
+ word = word.strip()
117
+ if word and word != MISSING_WORD:
118
+ try:
119
+ words.append(Word.from_txt(word))
120
+ except AssertionError:
121
+ logging.getLogger(__name__).warning('skipping invalid word "{}"'.format(word))
122
+
123
+ number, meaning = header.split(maxsplit=1)
124
+ if number.endswith('.'):
125
+ number = number[:-1].strip()
126
+ return cls(int(number), meaning.strip(), words, comment or None)
127
+
128
+ @staticmethod
129
+ def format(mid, meaning=None, form=MISSING_WORD, comment=None):
130
+ return '{} {}\t{} //{}'.format(
131
+ mid, meaning or MEANINGS_ALL[mid], form, ' ' + comment if comment else '')
132
+
133
+ def format_words(self):
134
+ return ', '.join(str(w) for w in self.words) or MISSING_WORD
135
+
136
+ def __str__(self):
137
+ return self.format(
138
+ self.meaning_id,
139
+ meaning=self.meaning,
140
+ form=', '.join(str(w) for w in self.words),
141
+ comment=self.comment)
142
+
143
+
144
+ def txt_header(synonyms=2, words=28, year=1700):
145
+ """
146
+ 2 28 1700 3
147
+ (I4,20X,10A1)
148
+ """
149
+ def rjust(n, s=6):
150
+ return str(n).rjust(s)
151
+
152
+ lines = [
153
+ '%s%s%s%s%s%s' % tuple(map(rjust, (synonyms, words, year, 3, 92, 72))), '(I4,20X,10A1)']
154
+
155
+ for mid, concept in sorted(MEANINGS_ALL.items(), key=lambda p: p[0]):
156
+ lines.append('%s%s%s' % (rjust(mid, 4), 20 * ' ', concept))
157
+
158
+ lines.append('')
159
+ for char in ASJPCODES:
160
+ lines.append(char)
161
+ lines.append('')
162
+ lines.append('')
163
+ return '\n'.join(lines)
164
+
165
+
166
+ @dataclasses.dataclass
167
+ class Doculect:
168
+ id: str
169
+ name: str
170
+ classification_wals: str | None
171
+ classification_ethnologue: str | None
172
+ classification_glottolog: str | None
173
+ latitude: float | None
174
+ longitude: float | None
175
+ number_of_speakers: int
176
+ recently_extinct: bool
177
+ long_extinct: bool
178
+ year_of_extinction: int | None
179
+ code_wals: str | None
180
+ code_iso: str | None
181
+ synsets: list[Synset]
182
+
183
+ def __post_init__(self):
184
+ self.synsets = [vv for vv in self.synsets if vv.words]
185
+ if self.latitude is not None and self.longitude is not None:
186
+ assert -90.0 <= self.latitude <= 90.0 # noqa: PLR2004
187
+ assert -180.0 <= self.longitude <= 180.0 # noqa: PLR2004
188
+
189
+ def get(self, item):
190
+ for ss in self.synsets:
191
+ if ss.meaning_id == item or ss.meaning == item or MEANINGS_ALL[ss.meaning_id] == item:
192
+ return ss
193
+
194
+ @property
195
+ def asjp_name(self):
196
+ name = self.name
197
+ if '"' in name:
198
+ name = name.split('"')[1]
199
+ return name.replace("'", "").replace(" ", "_").replace("/", "_").upper()
200
+
201
+ @property
202
+ def wals_family(self):
203
+ return self.classification_wals.split('.')[0] if self.classification_wals else None
204
+
205
+ @property
206
+ def wals_genus(self):
207
+ return self.classification_wals.split('.')[1] if self.classification_wals else None
208
+
209
+ @classmethod
210
+ def from_txt(cls, txt, **kw):
211
+ """
212
+ The second line gives properties of the languages, in fixed format separated by blanks
213
+ (not tabs), so the columns are important.
214
+
215
+ Col. 2: 3 if the language is the first one in a new WALS family, 2 if it’s the first
216
+ language in a new WALS genus, 1 otherwise.
217
+
218
+ Col. 4-10, right justified: latitude in degrees and
219
+ hundredths of a degree; minus means South.
220
+
221
+ Col. 12-18, right justified: longitude in degrees a
222
+ nd hundredths of a degree; minus means West.
223
+ Latitudes and longitudes were ascertained from WALS, or from the maps in Ethnologue or
224
+ Moseley and Asher (1994), or from information in the source for the list.
225
+
226
+ Col. 19-30, right justified: number of speakers, from Ethnologue. This number always
227
+ refers to the entire language, as defined in Ethnologue, even if the list itself
228
+ refers to a dialect. The number is
229
+
230
+ 0 if the number of speakers is unknown;
231
+ -1 if the language is recently extinct;
232
+ -2 if the language is long extinct;
233
+ or if the approximate date of extinction is known, the date is preceded by a minus
234
+ sign.
235
+
236
+ In the ASJP software, if there is a date in the first line of the entire file, lists
237
+ with earlier extinction dates here are ignored, as are lists with -2; otherwise, all
238
+ lists are read.
239
+
240
+ Col. 34-36: three-letter WALS code, if any.
241
+
242
+ Col. 40-42: three-letter ISO639-3 code, if any. This code is included for languages in
243
+ previous editions of Ethnologue even if they aren’t in the 17th edition. Languages
244
+ that lack an ISO639-3 code but can be placed in the Ethnologue classification are
245
+ given a code consisting of two letters followed by the number 0 (for use in ASJP
246
+ software).
247
+ """
248
+ lines = nfilter(txt.split('\n'))
249
+ m = LANGUAGE_LINE_PATTERN.match(lines[0])
250
+ assert m
251
+ line = lines[1]
252
+ try:
253
+ lat = line[4:11].strip()
254
+ lng = line[11:18].strip()
255
+ nos = int(line[18:30].strip() or 0)
256
+ code_wals = line[33:36].strip() or None
257
+ code_iso = line[39:42].strip() or None
258
+ except ValueError: # pragma: no cover
259
+ _, lat, lng, nos, code_wals, code_iso = line.strip().split()
260
+ nos = int(nos)
261
+ assert all(('\t' in line) or (not line.strip()) for line in lines[2:])
262
+ words = [line for line in lines[2:] if '\t' in line]
263
+ synsets = collections.OrderedDict()
264
+ for line in words:
265
+ synset = Synset.from_txt(line)
266
+ assert synset.meaning_id not in synsets, '{}: {}'.format(m.group('name'), line)
267
+ synsets[synset.meaning_id] = synset
268
+ return cls(
269
+ id=m.group('name'),
270
+ name=' '.join(s.capitalize() for s in m.group('name').split('_')),
271
+ classification_wals=m.group('w') if m.group('w') else None,
272
+ classification_ethnologue=m .group('e') if m.group('e') else None,
273
+ classification_glottolog=m.group('g') if m.group('g') else None,
274
+ latitude=float(lat) if lat else None,
275
+ longitude=float(lng) if lng else None,
276
+ number_of_speakers=nos if nos >= 0 else 0,
277
+ recently_extinct=nos == RECENTLY_EXTINCT or nos < LONG_EXTINCT,
278
+ long_extinct=nos == LONG_EXTINCT,
279
+ year_of_extinction=abs(nos) if nos < LONG_EXTINCT else None,
280
+ code_wals=code_wals,
281
+ code_iso=code_iso,
282
+ synsets=list(synsets.values()),
283
+ )
284
+
285
+ def __str__(self):
286
+ return self.to_txt()
287
+
288
+ def format(self, what):
289
+ val = getattr(self, what)
290
+ if what in ['latitude', 'longitude'] and val is not None:
291
+ return '{:.2f}'.format(getattr(self, what)) # noqa: UP032
292
+ if what == 'number_of_speakers':
293
+ if self.year_of_extinction:
294
+ val = -self.year_of_extinction
295
+ elif self.recently_extinct:
296
+ val = -1
297
+ elif self.long_extinct:
298
+ val = -2
299
+ return str(val)
300
+ return val or ''
301
+
302
+ def to_txt(self, add_missing=False, full_list=False, wals_marker='1'):
303
+ """render the wordlist in the ASJP plain text format.
304
+ """
305
+ lines = [
306
+ '%s{%s|%s@%s}' % ( # noqa: UP031
307
+ self.id,
308
+ self.format('classification_wals'),
309
+ self.format('classification_ethnologue'),
310
+ self.format('classification_glottolog')),
311
+ '%s%s%s%s%s%s' % ( # noqa: UP031
312
+ wals_marker.rjust(2),
313
+ self.format('latitude').rjust(8),
314
+ self.format('longitude').rjust(8),
315
+ self.format('number_of_speakers').rjust(12),
316
+ (self.code_wals or '').rjust(6),
317
+ (self.code_iso or '').rjust(6))]
318
+ synsets = {s.meaning_id: s for s in self.synsets}
319
+ for mid, concept in sorted(MEANINGS_ALL.items(), key=lambda i: i[0]):
320
+ if mid in synsets:
321
+ lines.append(str(synsets[mid]))
322
+ elif add_missing and ((mid in MEANINGS) or full_list):
323
+ lines.append(Synset.format(mid))
324
+ return '\n'.join(lines)
325
+
326
+ @staticmethod
327
+ def formatted_header():
328
+ res = ['names', 'wls_fam', 'wls_gen', 'e', 'hh', 'lat', 'lon', 'pop', 'wcode', 'iso']
329
+ return res + [v for _, v in sorted(MEANINGS_ALL.items(), key=lambda i: i[0])]
330
+
331
+ def to_formatted_row(self):
332
+ res = [
333
+ self.id,
334
+ self.wals_family,
335
+ self.wals_genus,
336
+ self.classification_ethnologue,
337
+ self.classification_glottolog,
338
+ self.format('latitude'),
339
+ self.format('longitude'),
340
+ self.format('number_of_speakers'),
341
+ self.code_wals or '',
342
+ self.code_iso or '',
343
+ ]
344
+ synsets = {s.meaning_id: s for s in self.synsets}
345
+ for mid in sorted(MEANINGS_ALL.keys()):
346
+ res.append(synsets[mid].format_words() if mid in synsets else MISSING_WORD)
347
+ return res
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyasjp
3
+ Version: 1.6.0
4
+ Summary: Programmatic access to ASJP data.
5
+ Author-email: Robert Forkel <dlce.rdm@eva.mpg.de>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/dlce-eva/pyasjp
8
+ Keywords: data,clld
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Natural Language :: English
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: csvw
23
+ Requires-Dist: clldutils
24
+ Provides-Extra: dev
25
+ Requires-Dist: ruff; extra == "dev"
26
+ Requires-Dist: wheel; extra == "dev"
27
+ Requires-Dist: build; extra == "dev"
28
+ Requires-Dist: twine; extra == "dev"
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest>=5; extra == "test"
31
+ Requires-Dist: pytest-mock; extra == "test"
32
+ Requires-Dist: pytest-cov; extra == "test"
33
+ Requires-Dist: tox; extra == "test"
34
+ Dynamic: license-file
35
+
36
+ # pyasjp
37
+ Programmatic access to data in ASJP's text format
38
+
39
+ [![PyPI](https://img.shields.io/pypi/v/pyasjp.svg)](https://pypi.org/project/pyasjp)
40
+
@@ -0,0 +1,14 @@
1
+ pyasjp/__init__.py,sha256=8LtXpIril8FoX5UCZNz9zwpxO-_Q_d-DW2mMusWEEp0,67
2
+ pyasjp/__main__.py,sha256=GuU13-haFKXEIcrQQth86D2_DPMq6O8Qi5xY7A1n_dI,955
3
+ pyasjp/api.py,sha256=6_Fz8IIzwySb-9bIy572lV27gdXHdL8ZbwJpNjt1Th8,2954
4
+ pyasjp/meanings.py,sha256=o2PmXbP05KEwfWHe5pe0IXhFeG4_KTs8o6nWVgqXd9g,3439
5
+ pyasjp/models.py,sha256=NHFKWOVQPMfSp1zu0dveFhRoXbXUPAkci4ZM-aSkQ_k,12433
6
+ pyasjp/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ pyasjp/commands/diff.py,sha256=fqZCKzGq-YorrjE-hligTv7HosVg4Gu7SIUHwzG3CW0,2040
8
+ pyasjp/commands/formatted.py,sha256=ko90OhhaGlpEONgmLBxAbHX2QwiTJD0nQMZRGmUvwqI,713
9
+ pyasjp-1.6.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ pyasjp-1.6.0.dist-info/METADATA,sha256=osJa6q-K9zSDWURyDOUmB8VI-Tv3dtAJxH74mITlH0Q,1395
11
+ pyasjp-1.6.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
12
+ pyasjp-1.6.0.dist-info/entry_points.txt,sha256=xcdNKQoCHTNyAnuwbdt461FjGUL0IWGSolKCmFYXBik,46
13
+ pyasjp-1.6.0.dist-info/top_level.txt,sha256=cMVstqAEEQ65niq1ENLe82wuLh1foaBIQhBmlVhT4Ng,7
14
+ pyasjp-1.6.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ asjp = pyasjp.__main__:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ pyasjp