Debian Codegraph @

importers/wikdict/import_wikdict.py

raw
1 #!/usr/bin/env python3
2 #vim: set expandtab sts=4 ts=4 sw=4 autoindent ft=python:
3 """This script downloads all (already approved) dictionary from the WikDict
4 project to be included in FreeDict's repository.
5 This script requires a FreeDict API file to figure out which dictionaries are
6 from WikDict and which not. It searches first for a local file referenced by the
7 FreeDict configuration. This is the preferred way. Then it downloads a version
8 from freedict.org.
9 """
10
11 #pylint: disable=multiple-imports
12 import enum
13 import html.parser
14 import json
15 import multiprocessing
16 import os
17 import re
18 import sys
19 import urllib.request, urllib.parse
20 import shutil
21 import xml.etree.ElementTree as ET
22 from datetime import date
23
24 SOURCE_URL = 'https://download.wikdict.com/dictionaries/tei/no-infl/'
25 # minimal number of words to consider a dictionary for inclusion
26 MIN_WORD_COUNT = 10000
27 DOWNLOAD_PREFIX = 'http://{0.netloc}{0.path}'.format(urllib.parse.urlsplit(SOURCE_URL))
28 def get_fd_api():
29 """Read local FreeDict API file or load from given path from configuration
30 or download it from freedict.org as fallback.
31 It is advised to generate a fresh API copy locally.
32 This function will try to load a virtual environment, if configured."""
33 js = None
34 #pylint: disable=bare-except
35 api_file = lambda c: os.path.join(os.path.expanduser(
36 c['DEFAULT']['api_output_path']), 'freedict-database.json')
37
38 try:
39 import fd_tool.config as config
40 cnf = config.discover_and_load()
41 js = json.load(open(api_file(cnf), encoding="UTF-8"))
42 except ImportError:
43 # try to activate virtual env, if configured but not sourced yet
44 paths = [os.path.join(os.path.expanduser("~"), '.config/freedict/freedictrc')]
45 if os.environ.get('LOCALAPPDATA'):
46 paths.append(os.path.join(os.environ['LOCALAPPDATA'], 'freedict/freedict.ini'))
47 conffile = [path for path in paths if os.path.exists(path)]
48 if conffile:
49 import configparser
50 cnf = configparser.ConfigParser()
51 cnf.read_file(open(conffile[0], encoding="UTF-8"))
52 if 'DEFAULT' in cnf and 'api_output_path' in cnf['DEFAULT']:
53 with open(api_file(cnf), encoding="UTF-8") as fhandle:
54 js = json.load(fhandle)
55 except KeyboardInterrupt:
56 pass
57 if not js:
58 from urllib.request import urlopen
59 with urlopen('https://freedict.org/freedict-database.json') as u:
60 js = json.loads(u.read().decode('utf-8'))
61 # strip all non-dictionary nodes (e.g. 'software'
62 return [node for node in js if 'name' in node]
63
64
65 class LinkExtractor(html.parser.HTMLParser):
66 """Extract all URL's from a HTML file. Use extract_links for a more
67 easy-to-use function."""
68 def __init__(self):
69 self.links = []
70 super().__init__()
71
72 def handle_starttag(self, tag, attrs):
73 if tag == 'a':
74 attrs = dict(attrs)
75 if 'href' in attrs:
76 self.links.append(attrs['href'])
77
78
79 def extract_links(from_string):
80 """Return a list with all links contained in the HTML page passed as input
81 parameter."""
82 parser = LinkExtractor()
83 parser.feed(from_string)
84 return parser.links
85
86
87 def download(link):
88 """Download given link and decode the bytes."""
89 try:
90 with urllib.request.urlopen(link) as u:
91 return u.read().decode('UTF-8')
92 except urllib.error.HTTPError as h:
93 if int(h.code) == 404:
94 reason = '%s; url: %s' % (str(h), link)
95 raise urllib.error.URLError(reason)
96 else:
97 raise h from None
98
99
100 def assert_correct_working_directory():
101 """Check that this script is executed from the correct directory."""
102 num_files = sum(1 for fn in os.listdir('.')
103 if re.search('^[a-z]{3}-[a-z]{3}$', fn))
104 if num_files < 2: # less than two dictionaries, probably not a dictionary root
105 print("Error: must be run from a FreeDict source root, i.e. "
106 "where all generated dictionaries are stored.")
107 sys.exit(9)
108
109
110 def make_changelog(path):
111 tmpl_vars = {
112 'date': date.today(),
113 'dict': path,
114 }
115 changelog_path = 'ChangeLog'
116 changelog = ''
117 if os.path.exists(changelog_path):
118 with open(os.path.join(path, changelog_path), 'r', encoding="UTF-8") as chlog_file:
119 changelog += chlog_file.read()
120 with open(os.path.join(path, 'ChangeLog'), 'w', encoding="UTF-8") as f:
121 f.write(("""\n
122 {date}
123
124 * automatic import of {dict} dictionary from WikDict
125 \n""" + changelog).strip().format(**tmpl_vars) + '\n')
126
127
128 def update_dict_files(path, shared_file_path):
129 dir_template = os.path.join(
130 os.path.dirname(os.path.realpath(__file__)),
131 'template'
132 )
133 shutil.rmtree(path, ignore_errors=True)
134 os.makedirs(path, exist_ok=True)
135 def copy(files):
136 for file in files:
137 try:
138 shutil.copy2(file, path)
139 except shutil.SameFileError:
140 pass
141 copy(os.path.join(shared_file_path, f) for f in
142 ('freedict-dictionary.css', 'freedict-P5.dtd', 'INSTALL',
143 'freedict-P5.rng', 'freedict-P5.xml'))
144 copy(os.path.join(dir_template, f) for f in os.listdir(dir_template))
145
146
147 def dict_exists_from_other_source(api_dump, dictname):
148 """FreeDict dictionaries come from different sources. At the time of writing,
149 these are the VCS-tracked, partly hand-written dictionaries and the
150 auto-imported dictionaries. WikDict are auto-imported and hence in the bucked of
151 non-VCS tracked, generated dictionaries. Before importing a WikDict dictionary,
152 we have to check whether a dictionary with the same name exists somewhere
153 else."""
154 dictionary = [d for d in api_dump if d['name'] == dictname]
155
156 return dictionary and ('sourceURL' not in dictionary[0] or \
157 'wikdict' not in dictionary[0]['sourceURL'])
158
159 def enough_headwords(tei):
160 """This function parses the TEI header and returns true if the given
161 dictionary contains more than the minimal required number of headwords."""
162 tei = ET.fromstring(tei)
163 node = tei.find('*//{http://www.tei-c.org/ns/1.0}extent')
164 count = re.search(r'(\d+\s*,?\.?\d*)\s+.*word', node.text).groups()[0]
165 return int(count.strip(' ,.')) >= MIN_WORD_COUNT
166
167 def parse_links():
168 with urllib.request.urlopen(SOURCE_URL) as src:
169 try:
170 data = src.read().decode('utf-8')
171 except UnicodeEncodeError:
172 raise ValueError("Could not encode page with encoding UTF-8; please adjust manually")
173 return (l for l in extract_links(data) if l.endswith('.tei'))
174
175 class DictionaryStrategy(enum.Enum):
176 TooSmall = 0
177 ManuallyEdited = 1
178 Imported = 2
179 Rubbish = 3
180
181 def import_dictionary(api, link):
182 """Import a dictionary from WikDict and prepare dictionary directory for a
183 release."""
184 if not urllib.parse.urlsplit(link)[1]: # no host in URL
185 link = urllib.parse.urljoin(DOWNLOAD_PREFIX, link)
186 base_name = os.path.splitext(link.split('/')[-1])[0] # name without .tei
187 if not re.match(r'\w{3}-\w{3}', base_name):
188 return (DictionaryStrategy.Rubbish, None)
189 if dict_exists_from_other_source(api, base_name):
190 return (base_name, DictionaryStrategy.ManuallyEdited)
191 tei = download(link)
192 if not enough_headwords(tei):
193 return (base_name, DictionaryStrategy.TooSmall)
194
195 print('Importing', base_name)
196 if not os.path.exists(base_name):
197 os.makedirs(base_name)
198 # erase old files, write new ones
199 update_dict_files(base_name, sys.argv[1])
200 with open(os.path.join(base_name, base_name + '.tei'), 'w',
201 encoding='utf-8') as file:
202 file.write(tei)
203 make_changelog(base_name)
204 return (base_name, DictionaryStrategy.Imported)
205
206
207 def main():
208 assert_correct_working_directory()
209 if len(sys.argv) != 2:
210 print("Error, path to shared FreeDict files required as first argument.")
211 sys.exit(1)
212 if not os.path.exists(sys.argv[1]):
213 print("Error, path does not exist",sys.argv[1])
214 sys.exit(2)
215 # statistics
216 too_small, manual = [], []
217 api = get_fd_api()
218 with multiprocessing.Pool(5) as p:
219 res = p.starmap(import_dictionary, # ↓ pair with api, see import_dictionary
220 ((api, l) for l in sorted(parse_links())))
221 for action in res:
222 dictname, action = action # what has been done with which dictionary
223 if action is DictionaryStrategy.TooSmall:
224 too_small.append(dictname)
225 elif action == DictionaryStrategy.ManuallyEdited:
226 manual.append(dictname)
227 print("The following dictionaries were skipped because:")
228 print("… a non-WikDict version exists:",', '.join(manual))
229 print("… they were too small:", ', '.join(too_small))
230
231
232 if __name__ == '__main__':
233 main()
234