Debian Codegraph @

utils/generate_snowball.py

raw ◀ ▶
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 # record the original source of the stopwords list
59 txt_path = STOPWORDS_DIR / f'{lang_code}.txt'
•60 data = txt_path.read_text()
61
62 # generate the Python stopwords set
63 stopwords = parse_stop_word(data)
64 with (STOPWORDS_DIR / f'{lang_code}.py').open('w', encoding='utf-8') as f:
65 f.write('# automatically generated by utils/generate-snowball.py\n')
66 f.write(f'# from {url}\n\n')
67 f.write('from __future__ import annotations\n\n')
68 f.write(f'{lang_name.upper()}_STOPWORDS = frozenset(')
69 if stopwords:
70 f.write('{\n')
71 for word in sorted(stopwords, key=str.casefold):
72 f.write(f' {word!r},\n')
73 f.write('}')
74 f.write(')\n')
75
76
77 def parse_stop_word(source: str) -> frozenset[str]:
78 """Collect the stopwords from a snowball style word list:
79
80 .. code:: text
81
82 list of space separated stop words | optional comment
83 """
84 stop_words: set[str] = set()
85 for line in source.splitlines():
86 stop_words.update(line.partition('|')[0].split()) # remove comment
87 return frozenset(stop_words)
88
89
90 def regenerate_javascript() -> None:
91 tmp_root = Path(tempfile.mkdtemp())
92
93 # Download and verify the snowball release
94 archive = requests.get(SNOWBALL_URL, timeout=60).content
95 digest = hashlib.sha256(archive).hexdigest()
96 if digest != SNOWBALL_SHA256:
97 msg = (
98 f'data does not match expected checksum '
99 f'(expected {SNOWBALL_SHA256}, saw {digest}).'
100 )
101 raise RuntimeError(msg)
102
103 # Extract the release archive
104 with tarfile.TarFile.gzopen(
105 'snowball.tar.gz', mode='r', fileobj=BytesIO(archive)
106 ) as tar:
107 tar.extractall(tmp_root, filter='data')
108 snowball_root = tmp_root / f'snowball-{SNOWBALL_VERSION}'
109 snowball_dist = snowball_root / 'dist'
110
111 # Generate JS stemmer files
112 cmd = ('make', '--jobs=8', 'dist_libstemmer_js')
113 subprocess.run(cmd, check=True, cwd=snowball_root)
114 with tarfile.open(snowball_dist / f'jsstemmer-{SNOWBALL_VERSION}.tar.gz') as tar:
115 tar.extractall(snowball_dist, filter='data')
116
117 # Copy generated JS to sphinx/search/
118 NON_MINIFIED_JS_DIR.mkdir(exist_ok=True)
119 js_dir = snowball_dist / f'jsstemmer-{SNOWBALL_VERSION}' / 'javascript'
120 shutil.copytree(js_dir, NON_MINIFIED_JS_DIR, dirs_exist_ok=True)
121
122 # Clean up
123 shutil.rmtree(snowball_root)
124
125
126 if __name__ == '__main__':
127 regenerate_stopwords()