| 1 |
"""This file imports the epo-eng dictionary from |
| 2 |
#!/usr/bin/env python3 |
| 3 |
<http://www.denisowski.org/Esperanto/ESPDIC/espdic_readme.htm>. Please see the |
| 4 |
README for more information.""" |
| 5 |
|
| 6 |
import enum |
| 7 |
import os |
| 8 |
import sys |
| 9 |
import urllib.request |
| 10 |
import xml.sax.saxutils as saxutils |
| 11 |
|
| 12 |
# allow tokenizer import |
| 13 |
from fd_import.tokenizer import ChunkType, tokenize |
| 14 |
import fd_import |
| 15 |
|
| 16 |
|
| 17 |
class WordType(enum.Enum): |
| 18 |
Full = '' # normal words |
| 19 |
Prefix = 'pref' # word prefixes |
| 20 |
Suffix = 'suff' # :) |
| 21 |
Part = 'part' # "-x-", so an infix |
| 22 |
|
| 23 |
class Definition: |
| 24 |
#pylint: disable=too-few-public-methods |
| 25 |
"""Only relevant for headwords with no direct translations, they define the |
| 26 |
headword.""" |
| 27 |
def __init__(self, definition): |
| 28 |
self.definition = definition |
| 29 |
|
| 30 |
def as_xml(self): |
| 31 |
return '<cit>\n<def>%s</def>\n</cit>' % saxutils.escape(self.definition) |
| 32 |
|
| 33 |
class Word: |
| 34 |
#pylint: disable=too-few-public-methods |
| 35 |
"""This is either a head word or a translation.""" |
| 36 |
def __init__(self, word, usage_info=None): |
| 37 |
self.word = word |
| 38 |
# gramGrp is a list of ready-to-use xml strings, basically *one* node |
| 39 |
self.gramGrp, self.usage_info = self.__get_gram_info(usage_info) |
| 40 |
self.word_type = type |
| 41 |
|
| 42 |
def __repr__(self): |
| 43 |
return ('%s (%s)' % (self.word, self.usage_info) if self.usage_info else |
| 44 |
self.word) |
| 45 |
|
| 46 |
def __get_gram_info(self, usage_info): |
| 47 |
"""Figure out, whether text is a collocating word or a usage hint. |
| 48 |
Return tuple ready-to-use XML. """ |
| 49 |
# special cases: catch collocations |
| 50 |
collocations = ['for', 'of', 'up', 'to', 'in', 'on', 'by', 'upon', |
| 51 |
'ke', 'de', "do"] # esperanto |
| 52 |
if not usage_info: |
| 53 |
return (None, None) |
| 54 |
elif usage_info in collocations: |
| 55 |
return (['<colloc>%s</colloc>' % saxutils.escape(usage_info)], None) |
| 56 |
else: |
| 57 |
return (None, '<usg type="hint">%s</usg>' % |
| 58 |
saxutils.escape(usage_info)) |
| 59 |
|
| 60 |
def as_xml(self): |
| 61 |
xml = ['<cit type="trans">\n<quote>', saxutils.escape(self.word), |
| 62 |
'</quote>'] |
| 63 |
if self.usage_info: |
| 64 |
xml.append('\n' + self.usage_info) # already escaped |
| 65 |
if self.gramGrp: |
| 66 |
xml.append('\n<gramGrp>\n%s\n</gramGrp>' % '\n'.join(self.gramGrp)) |
| 67 |
return ''.join(xml + ['\n</cit>']) |
| 68 |
|
| 69 |
#pylint: disable=redefined-variable-type |
| 70 |
class HeadWord(Word): |
| 71 |
#pylint: disable=too-few-public-methods |
| 72 |
def __init__(self, word, usg=None): |
| 73 |
if word.startswith('-') and word.endswith('-'): |
| 74 |
self.type = WordType.Part |
| 75 |
elif word.startswith('-'): |
| 76 |
self.type = WordType.Suffix |
| 77 |
elif word.endswith('-'): |
| 78 |
self.type = WordType.Prefix |
| 79 |
else: |
| 80 |
self.type = WordType.Full |
| 81 |
self.word = word.lstrip('-').rstrip('-') |
| 82 |
super().__init__(self.word, usg) |
| 83 |
|
| 84 |
def as_xml(self): |
| 85 |
extent = '' |
| 86 |
if not self.type == WordType.Full: |
| 87 |
extent = ' extent="%s"' % self.type.value |
| 88 |
orth = '<orth%s>%s</orth>' % (extent, saxutils.escape(self.word)) |
| 89 |
if self.gramGrp: |
| 90 |
orth += '\n<gramGrp>\n%s</gramGrp>' % '\n'.join(self.gramGrp) |
| 91 |
if self.usage_info: |
| 92 |
orth += '\n' + self.usage_info |
| 93 |
return '<form>\n%s\n</form>' % orth |
| 94 |
|
| 95 |
def structure_translations(unordered_list): |
| 96 |
"""Take a list of chunks (see docs of parse_meanings) and return a list of |
| 97 |
list of words. The outer lists holds different meanings (homonyms) and has |
| 98 |
in most cases only one entry. The inner list contains objects of type |
| 99 |
Word.""" |
| 100 |
translations = [[]] # initialize list with one sense |
| 101 |
while unordered_list: |
| 102 |
chunk = unordered_list.pop(0) |
| 103 |
# test for type of chunk |
| 104 |
if chunk[0] == ChunkType.Paren: |
| 105 |
# is this an additional info for a word: |
| 106 |
if unordered_list and unordered_list[0][0] == ChunkType.Word: |
| 107 |
translations[-1].append(Word(unordered_list.pop(0)[1], chunk[1])) |
| 108 |
else: # no next chunk or no word |
| 109 |
# this is either a parenthesized expression with no word before |
| 110 |
# or after, then it's a definition; otherwise it's an unhandled |
| 111 |
# case and a bug |
| 112 |
if (len(translations) == 1 and not translations[0]) and \ |
| 113 |
(not unordered_list or unordered_list[0][0] == ChunkType.Comma): # definition |
| 114 |
translations[-1].append(Definition(chunk[1])) |
| 115 |
else: |
| 116 |
print(',',repr(translations)) |
| 117 |
raise ValueError(("Couldn't parse translations; tokens " |
| 118 |
"parsed: %s\nCurrent token: %s\nTokens left: %s") % \ |
| 119 |
(translations,chunk,unordered_list)) |
| 120 |
elif chunk[0] == ChunkType.Word: |
| 121 |
# word with usage info / colloc |
| 122 |
if unordered_list and unordered_list[0][0] == ChunkType.Paren: |
| 123 |
# in some cases definitions are written as "to (be in) a |
| 124 |
# position", this is poor markup. ignore those parenthesis and |
| 125 |
# add it as a whole word: |
| 126 |
if len(unordered_list) >= 2 and unordered_list[1][0] == ChunkType.Word: |
| 127 |
translations[-1].append(Word(chunk[1] +" " + \ |
| 128 |
unordered_list.pop(0)[1] + " " + \ |
| 129 |
unordered_list.pop(0)[1])) |
| 130 |
else: |
| 131 |
translations[-1].append(Word(chunk[1], |
| 132 |
unordered_list.pop(0)[1])) |
| 133 |
else: |
| 134 |
translations[-1].append(Word(chunk[1])) |
| 135 |
elif chunk[0] == ChunkType.Comma: # new word starts, ignore |
| 136 |
pass |
| 137 |
elif chunk[0] == ChunkType.Semicolon: # homonym, new sense |
| 138 |
translations.append([]) |
| 139 |
# add brackets and braces verbatim |
| 140 |
elif chunk[0] in (ChunkType.Bracket, ChunkType.Brace): |
| 141 |
chars = ('[]' if chunk[0] == ChunkType.Bracket else '{}') |
| 142 |
# readd translation in bracket/brace, verbatim |
| 143 |
if translations[-1]: # at least one word found |
| 144 |
translations[-1][-1].word += ' ' + chars[0] + chunk[1] + chars[1] |
| 145 |
else: # new word |
| 146 |
translations[-1].append(Word(chars[0] + chunk[1] + chars[1])) |
| 147 |
else: |
| 148 |
raise NotImplementedError("Unhandled case: " + repr(chunk)) |
| 149 |
return translations |
| 150 |
|
| 151 |
def guess_grammar_details(translations): |
| 152 |
"""This function inspects the English translations to infer grammatical |
| 153 |
information. Definitions starting with "to " are verbs in the infinitive |
| 154 |
form, etc. The translations might get altered, for instance, to strip the |
| 155 |
"to " from the actual definition.""" |
| 156 |
gram = '' |
| 157 |
firstword = translations[0][0] |
| 158 |
if isinstance(firstword, Definition): |
| 159 |
return (None, translations) # don't fiddle around with def's |
| 160 |
if firstword.word.startswith('to '): |
| 161 |
gram = '<pos>v</pos>' |
| 162 |
for deflist in translations: |
| 163 |
for word in deflist: |
| 164 |
if word.word.startswith('to '): |
| 165 |
word.word = word.word[3:] |
| 166 |
# remove wrongly parsed colloc's |
| 167 |
collocs = ['<colloc>%s</colloc>' % c for c in ['to', 'a', 'an']] |
| 168 |
for deflist in translations: |
| 169 |
for word in deflist: |
| 170 |
if word.gramGrp: # it need to have a colloc, otherwise no checks |
| 171 |
for colloc in collocs: |
| 172 |
if colloc in word.gramGrp: |
| 173 |
idx = collocs.index(colloc) |
| 174 |
del word.gramGrp[idx] |
| 175 |
return (gram, translations) |
| 176 |
|
| 177 |
|
| 178 |
def translations_to_xml(translations): |
| 179 |
"""Translate nested definition / translation (word) structure into a |
| 180 |
TEI:sense structure.""" |
| 181 |
xml = [] |
| 182 |
for definition_list in translations: |
| 183 |
if not definition_list: |
| 184 |
raise ValueError("Found empty translation list; all translations: " \ |
| 185 |
+ repr(translations)) |
| 186 |
xml.append('<sense>') |
| 187 |
xml.extend(x.as_xml() for x in definition_list) |
| 188 |
xml.append('</sense>') |
| 189 |
return xml |
| 190 |
|
| 191 |
def write_output(input_file, base_dir, tei_skeleton, body_xml): |
| 192 |
"""This writes the imported dictionary into the specified directory.""" |
| 193 |
print("Writing TEI dictionary…") |
| 194 |
with open(tei_skeleton, 'r', encoding='utf-8') as f: |
| 195 |
header = f.read() |
| 196 |
body_start = header.find('<body>') + 6 |
| 197 |
tei_file = os.path.join(base_dir, 'epo-eng.tei') |
| 198 |
if not os.path.exists(base_dir): |
| 199 |
os.mkdir(base_dir) |
| 200 |
with open(tei_file, 'w', encoding='utf-8') as f: |
| 201 |
f.write(header[:body_start] + '\n') |
| 202 |
f.write(body_xml) |
| 203 |
f.write(header[body_start+1:].lstrip().rstrip() + '\n') |
| 204 |
|
| 205 |
fd_import.output.reindent_xml(tei_file) |
| 206 |
if not os.path.exists(os.path.join(base_dir, 'COPYING')): |
| 207 |
# retrieve copyright information |
| 208 |
print("Downloading CC unported 3.0 license") |
| 209 |
with open(os.path.join(base_dir, 'COPYING'), 'wb') as f: |
| 210 |
req = req = urllib.request.Request( |
| 211 |
'https://creativecommons.org/licenses/by/3.0/legalcode.txt', |
| 212 |
data=None, |
| 213 |
headers = { |
| 214 |
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0' |
| 215 |
}) |
| 216 |
with urllib.request.urlopen(req) as u: |
| 217 |
f.write(u.read()) |
| 218 |
|
| 219 |
# write Makefile |
| 220 |
fd_import.output.mk_makefile(base_dir, ['epo-eng.tei', 'epo-eng.patch']) |
| 221 |
|
| 222 |
|
| 223 |
def main(input_file, tei_skeleton, output_directory): |
| 224 |
print("Parsing dictionary…") |
| 225 |
with open(input_file, 'r', encoding='utf-8') as f: |
| 226 |
# gnerator with word pairs; ignore indented lines (only file header, |
| 227 |
# ATM) |
| 228 |
words = (wp for wp in f.read().split('\n') |
| 229 |
if wp.strip() and not wp.startswith(" ")) |
| 230 |
|
| 231 |
word_list = [] |
| 232 |
for lnum, word_pair in enumerate(words): |
| 233 |
if word_pair.lstrip().startswith("#"): |
| 234 |
continue |
| 235 |
try: |
| 236 |
head, trans = word_pair.split(' : ') |
| 237 |
translations = tokenize(trans) |
| 238 |
translations = structure_translations(translations) |
| 239 |
head = tokenize(head) |
| 240 |
if len(head) == 2: # headword with definition |
| 241 |
head = HeadWord(head[0][1], head[1][1]) |
| 242 |
else: |
| 243 |
head = HeadWord(head[0][1]) |
| 244 |
word_list.append((head, translations)) |
| 245 |
except ValueError as v: |
| 246 |
raise ValueError(f"line {lnum+1}: {''.join(v.args)}") |
| 247 |
|
| 248 |
# enrich words with grammatical info, strip "to" and other words *and* |
| 249 |
# convert to XML |
| 250 |
xml = [] |
| 251 |
for head, trans in word_list: |
| 252 |
# translations might get altered, e.g. "to" is stripped |
| 253 |
gram, trans = guess_grammar_details(trans) |
| 254 |
xml += ['<entry>', head.as_xml()] |
| 255 |
if gram: |
| 256 |
xml.append('<gramGrp>\n%s\n</gramGrp>' % gram) |
| 257 |
xml += translations_to_xml(trans) + ['</entry>'] |
| 258 |
|
| 259 |
write_output(input_file, output_directory, tei_skeleton, '\n'.join(xml)) |
| 260 |
print("Done. Now it's time to copy DTD, CSS and RNG and validate the dictionary.") |
| 261 |
|
| 262 |
def check_args(): |
| 263 |
"""command line parameter validation""" |
| 264 |
if len(sys.argv) != 4: |
| 265 |
print("Error: invalid command line parameters.") |
| 266 |
import textwrap |
| 267 |
print("Usage: %s <INPUT_FILE> <TEI SKELETON> <OUTPUT_DIRECTORY>\n "\ |
| 268 |
% sys.argv[0], end="") |
| 269 |
print('\n '.join(textwrap.wrap(("TEI SKELETON has to be a FreeDict TEI file, with an empty " |
| 270 |
"body tag. The opening and closing body tags have to be on " |
| 271 |
"separate lines.\n" |
| 272 |
"The output directory may exist and files will be overwritten, " |
| 273 |
"as necessary."), 78))) |
| 274 |
sys.exit(1) |
| 275 |
|
| 276 |
if not os.environ['FREEDICT_TOOLS']: |
| 277 |
print("The environment variable FREEDICT_TOOLS is not set.") |
| 278 |
print("This is mandatory, so that the necessary scripts can be located.") |
| 279 |
print("Have a look at the FreeDict wiki for more information:") |
| 280 |
print("https://github.com/freedict/fd-dictionaries/wiki") |
| 281 |
sys.exit(4) |
| 282 |
for file in sys.argv[1:3]: |
| 283 |
if not os.path.exists(file): |
| 284 |
print('Sorry, but the file "%s" does not exist.' % file) |
| 285 |
sys.exit(2) |
| 286 |
dictdir = os.path.basename(os.path.abspath(sys.argv[3])) |
| 287 |
if not len(dictdir) == 7 or '-' not in dictdir: |
| 288 |
print("The output directory has to be named with the usual FreeDict naming scheme. Otherwise, the Make rules will fail.") |
| 289 |
sys.exit(5) |
| 290 |
|
| 291 |
if __name__ == '__main__': |
| 292 |
check_args() |
| 293 |
main(sys.argv[1], sys.argv[2], sys.argv[3]) |
| 294 |
|