Subversion Repositories LCARS

Rev

Rev 295 | Rev 297 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
293 PointedEar 1
"""
2
Created on 2014-10-20
3
 
4
@author: Thomas 'PointedEars' Lahn <mail@PointedEars.de>
5
 
6
"""
7
 
8
from os import chdir, stat
9
from sys import stderr
10
from os.path import dirname, realpath, basename
11
from pickle import dump, load
12
from re import match, DOTALL, search, sub, split, compile
13
 
14
debug_level = 2
15
 
16
def dmsg(*args, **kwargs):
17
    if not hasattr(kwargs, 'min_level') or kwargs['min_level'] is None:
18
        kwargs['min_level'] = 1
19
 
20
    if not hasattr(kwargs, 'file'):
21
        kwargs['file'] = stderr
22
 
23
    if debug_level >= kwargs['min_level']:
24
        del kwargs['min_level']
25
        print(*args, **kwargs)
26
 
27
def sort_dict_alnum_english_key(phrase):
28
    return sub(r'\{(.+)\}', r'\1', phrase[0]).lower()
29
 
30
class Dictionary(dict):
31
    """
32
    classdocs
33
 
34
    """
296 PointedEar 35
    _language_key = 'en'
293 PointedEar 36
    _keys = "ipa|en|lit|pos|com|tag|ex"
37
    _expressions = {}
38
 
294 PointedEar 39
    def load (self, dictionary_file, language_key='en'):
296 PointedEar 40
        self._language_key = language_key
41
 
293 PointedEar 42
        dmsg('Loading dictionary '.format(dictionary_file), end='', min_level=1)
43
 
44
        chdir(dirname(realpath(__file__)))
45
 
46
        pickle_file = basename(dictionary_file) + '.pickle'
47
 
48
        try:
49
            pickle_mtime = stat(pickle_file).st_mtime
50
        except FileNotFoundError:
51
            pickle_mtime = None
52
 
53
        if pickle_mtime is None or stat(dictionary_file).st_mtime > pickle_mtime:
54
            dmsg('from {0} ...'.format(dictionary_file), end='', min_level=1)
55
            phrase = None
56
            key = None
57
            value = None
58
            with open(dictionary_file) as f:
59
                indent = None
60
 
61
                for line in f:
296 PointedEar 62
                    m = match(r'^\s*{0}:\s*(?P<phrase>.+)'.format(self._language_key), line)
293 PointedEar 63
                    if m is not None:
64
                        phrase = m.group("phrase")
295 PointedEar 65
                        self[phrase] = {}
293 PointedEar 66
                        indent = None
67
                    else:
68
                        m = match(r'(?P<indent>\s*)(?P<key>{0}):\s*(?P<value>.+)'.format(self._keys), line)
69
                        if m is not None:
70
                            # join previous value if necessary
71
                            if type(value) == list:
295 PointedEar 72
                                self[phrase][key] = ' '.join(value)
293 PointedEar 73
 
74
                            indent = m.group("indent")
75
                            key = m.group("key")
76
                            value = m.group("value")
77
                            # assign a string for memory efficiency
295 PointedEar 78
                            self[phrase][key] = value
293 PointedEar 79
                        elif indent is not None:
80
                            m = match(r'(?P<indent>\s+)(?P<continuation>\S.*)', line)
81
                            if m is not None:
82
                                if len(m.group("indent")) == len(indent) + 2:
83
                                    continuation = m.group("continuation")
84
                                    if type(value) == str:
85
                                        # when a continuation is first found, convert to a list
86
                                        # because there could be more continuations
295 PointedEar 87
                                        value = self[phrase][key] = [value, continuation]
293 PointedEar 88
                                    else:
89
                                        value.append(continuation)
90
 
91
            # join last value if necessary
92
            if type(value) == list:
295 PointedEar 93
                self[phrase][key] = ' '.join(value)
293 PointedEar 94
 
95
            dmsg('\nSaving pickle {0} ...'.format(pickle_file), end='', min_level=1)
96
            # TODO: Pickle should only contain strings to be small
295 PointedEar 97
            with open(pickle_file, mode='wb') as f: dump(self, f)
293 PointedEar 98
            dmsg(' done.', min_level=1)
99
        else:
100
            dmsg('from {0} ...'.format(pickle_file), end='', min_level=1)
101
            with open(pickle_file, mode='rb') as f: pickle = load(f)
102
            for key, value in pickle.items():
295 PointedEar 103
                self[key] = value
293 PointedEar 104
 
295 PointedEar 105
        dmsg(' done ({0} entries).'.format(len(self)), min_level=1)
293 PointedEar 106
 
107
    def clean (self):
296 PointedEar 108
        re_parens = compile(r'\(.+\)', DOTALL)
109
        re_parens_no_alt = compile(r'\(([^|]+)\)', DOTALL)
110
        re_braces = compile(
295 PointedEar 111
            r'^\s*\{(?P<phrase>.+)\}(?:\s*\((?P<variant>.+?)\))?\s*$',
112
            DOTALL)
296 PointedEar 113
        re_semicolon = compile(r'\s*;\s*')
293 PointedEar 114
 
295 PointedEar 115
        for orig_phrase, data in list(self.items()):
293 PointedEar 116
            # if there are optional or alternating parts
296 PointedEar 117
            if search(re_parens, orig_phrase):
293 PointedEar 118
                if orig_phrase.find('|') > -1:
119
                    # TODO alternation
120
                    pass
121
                else:
122
                    # TODO optional parts
123
                    pass
124
 
125
            if orig_phrase.find(';') > -1:
126
                synonyms = map(
296 PointedEar 127
                    lambda x: sub(re_braces, r'\1', x),
128
                    split(re_semicolon, orig_phrase))
293 PointedEar 129
 
130
                for synonym in synonyms:
295 PointedEar 131
                    self[synonym] = data
293 PointedEar 132
 
295 PointedEar 133
                del self[orig_phrase]
293 PointedEar 134
            else:
296 PointedEar 135
                m = match(re_braces, orig_phrase)
293 PointedEar 136
                if m is not None:
295 PointedEar 137
                    phrase = m.group("phrase")
296 PointedEar 138
                    m_parens = search(re_parens, phrase)
139
                    if m_parens is not None:
140
                        # alternation and optional parts
141
                        expr = sub(re_parens_no_alt, r'(?:\1)?', phrase)
142
                        expr = sub('~', '(?=.)', expr)
143
                        self._expressions[expr] = data
144
                    else:
145
                        # remove braces
146
                        self[phrase] = data
295 PointedEar 147
 
148
                    del self[orig_phrase]
296 PointedEar 149
 
150
    def translate (self, phrase):
151
        translation = self.get(phrase.lower(), None)
152
        if translation is not None:
153
            translation[self._language_key] = phrase
154
            return translation
155
 
156
        return None
157
 
158
    def translate_expression (self, phrase):
159
        for expression, data in list(self._expressions.items()):
160
            expression_match = match(expression, phrase)
161
            if expression_match is not None:
162
                data[self._language_key] = expression_match.group(0)
163
                return data
164
 
165
        return None