Debian Codegraph @

utils/generate_snowball.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python3
2
3 """Refresh and update language stemming data from the Snowball project."""
4
5 # /// script
6 # requires-python = ">=3.12"
7 # dependencies = [
8 # "requests>=2.30",
9 # ]
10 # ///
11
12 from __future__ import annotations
13
14 import hashlib
15 import shutil
16 import subprocess
17 import sys
18 import tarfile
19 import tempfile
20 from io import BytesIO
21 from pathlib import Path
22
23 import requests
24
25 SNOWBALL_VERSION = '3.0.1'
26 SNOWBALL_URL = f'https://github.com/snowballstem/snowball/archive/refs/tags/v{SNOWBALL_VERSION}.tar.gz'
27 SNOWBALL_SHA256 = '80ac10ce40dc4fcfbfed8d085c457b5613da0e86a73611a3d5527d044a142d60'
28
29 ROOT = Path(__file__).resolve().parent.parent
30 SEARCH_DIR = ROOT / 'sphinx' / 'search'
31 STOPWORDS_DIR = SEARCH_DIR / '_stopwords'
32 NON_MINIFIED_JS_DIR = SEARCH_DIR / 'non-minified-js'
33
34 STOPWORD_URLS = (
35 ('da', 'danish', 'https://snowballstem.org/algorithms/danish/stop.txt'),
36 ('de', 'german', 'https://snowballstem.org/algorithms/german/stop.txt'),
37 ('en', 'english', 'https://snowballstem.org/algorithms/english/stop.txt'),
38 ('es', 'spanish', 'https://snowballstem.org/algorithms/spanish/stop.txt'),
39 ('fi', 'finnish', 'https://snowballstem.org/algorithms/finnish/stop.txt'),
40 ('fr', 'french', 'https://snowballstem.org/algorithms/french/stop.txt'),
41 ('hu', 'hungarian', 'https://snowballstem.org/algorithms/hungarian/stop.txt'),
42 ('it', 'italian', 'https://snowballstem.org/algorithms/italian/stop.txt'),
43 ('nl', 'dutch', 'https://snowballstem.org/algorithms/dutch/stop.txt'),
44 ('no', 'norwegian', 'https://snowballstem.org/algorithms/norwegian/stop.txt'),
45 ('pt', 'portuguese', 'https://snowballstem.org/algorithms/portuguese/stop.txt'),
46 # ('ro', 'romanian', ''),
47 ('ru', 'russian', 'https://snowballstem.org/algorithms/russian/stop.txt'),
48 ('sv', 'swedish', 'https://snowballstem.org/algorithms/swedish/stop.txt'),
49 # ('tr', 'turkish', ''),
50 )
51
52
53 def regenerate_stopwords() -> None:
54 STOPWORDS_DIR.mkdir(parents=True, exist_ok=True)
55 STOPWORDS_DIR.joinpath('__init__.py').touch()
56
57 for lang_code, lang_name, url in STOPWORD_URLS:
58 content = requests.get(url, timeout=5).content
59 try:
60 data = content.decode('utf-8')
61 except UnicodeDecodeError:
62 if lang_code == 'ru':
63 data = content.decode('koi8-r')
64 else:
65 data = content.decode('latin-1')
66
67 # record the original source of the stopwords list
68 txt_path = STOPWORDS_DIR / f'{lang_code}.txt'
69 txt_path.write_text(data.rstrip() + '\n', encoding='utf-8')
70
71 # generate the Python stopwords set
72 stopwords = parse_stop_word(data)
73 with (STOPWORDS_DIR / f'{lang_code}.py').open('w', encoding='utf-8') as f:
74 f.write('# automatically generated by utils/generate-snowball.py\n')
75 f.write(f'# from {url}\n\n')
76 f.write('from __future__ import annotations\n\n')
77 f.write(f'{lang_name.upper()}_STOPWORDS = frozenset(')
78 if stopwords:
79 f.write('{\n')
80 for word in sorted(stopwords, key=str.casefold):
81 f.write(f' {word!r},\n')
82 f.write('}')
83 f.write(')\n')
84
85
86 def parse_stop_word(source: str) -> frozenset[str]:
87 """Collect the stopwords from a snowball style word list:
88
89 .. code:: text
90
91 list of space separated stop words | optional comment
92 """
93 stop_words: set[str] = set()
94 for line in source.splitlines():
95 stop_words.update(line.partition('|')[0].split()) # remove comment
96 return frozenset(stop_words)
97
98
99 def regenerate_javascript() -> None:
100 tmp_root = Path(tempfile.mkdtemp())
101
102 # Download and verify the snowball release
103 archive = requests.get(SNOWBALL_URL, timeout=60).content
104 digest = hashlib.sha256(archive).hexdigest()
105 if digest != SNOWBALL_SHA256:
106 msg = (
107 f'data does not match expected checksum '
108 f'(expected {SNOWBALL_SHA256}, saw {digest}).'
109 )
110 raise RuntimeError(msg)
111
112 # Extract the release archive
113 with tarfile.TarFile.gzopen(
114 'snowball.tar.gz', mode='r', fileobj=BytesIO(archive)
115 ) as tar:
116 tar.extractall(tmp_root, filter='data')
117 snowball_root = tmp_root / f'snowball-{SNOWBALL_VERSION}'
118 snowball_dist = snowball_root / 'dist'
119
120 # Generate JS stemmer files
121 cmd = ('make', '--jobs=8', 'dist_libstemmer_js')
122 subprocess.run(cmd, check=True, cwd=snowball_root)
123 with tarfile.open(snowball_dist / f'jsstemmer-{SNOWBALL_VERSION}.tar.gz') as tar:
124 tar.extractall(snowball_dist, filter='data')
125
126 # Copy generated JS to sphinx/search/
127 NON_MINIFIED_JS_DIR.mkdir(exist_ok=True)
128 js_dir = snowball_dist / f'jsstemmer-{SNOWBALL_VERSION}' / 'javascript'
129 shutil.copytree(js_dir, NON_MINIFIED_JS_DIR, dirs_exist_ok=True)
130
131 # Clean up
132 shutil.rmtree(snowball_root)
133
134
135 if __name__ == '__main__':
136 regenerate_stopwords()
137 if sys.platform != 'win32':
138 regenerate_javascript()