forked from lucaswerkmeister/tool-lexeme-forms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlanguage_names.py
58 lines (51 loc) · 1.86 KB
/
language_names.py
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
import re
import sys
from typing import Optional
import mwapi # type: ignore
import toolforge
_language_info = None
_labels: dict[str, str] = {}
_user_agent = toolforge.set_user_agent('lexeme-forms', email='[email protected]')
def load_language_info():
session = mwapi.Session(
'https://meta.wikimedia.org',
user_agent=_user_agent,
)
response = session.get(action='query',
meta='languageinfo',
liprop='autonym',
formatversion='2')
if 'continue' in response:
print('WARNING: MediaWiki languageinfo incomplete, continue={}'.format(response['continue']),
file=sys.stderr)
return response['query']['languageinfo']
def autonym(code: str) -> Optional[str]:
global _language_info
if _language_info is None:
_language_info = load_language_info()
return _language_info.get(code, {}).get('autonym')
def label(code: str) -> Optional[str]:
"""Get the label for an item-based language code.
Expects a language code in the format abc-x-Q123
and return Q123’s label for the abc language code."""
try:
return _labels[code]
except KeyError:
pass
match = re.fullmatch(r'([a-z]+)-x-(Q[1-9][0-9]*)', code)
if match is None:
return None
language, item_id = match.group(1, 2)
session = mwapi.Session(
'https://www.wikidata.org',
user_agent=_user_agent,
)
response = session.get(action='wbgetentities',
ids=[item_id],
props=['labels'],
languages=[language],
languagefallback=True,
formatversion=2)
label = response['entities'][item_id].get('labels', {}).get(language, {}).get('value')
_labels[code] = label
return label