Drop lots of legacy code. Support Python 3.7-3.11.
[librarian.git] / src / librarian / hyphenator.py
1 """
2
3 This is a Pure Python module to hyphenate text.
4
5 It is inspired by Ruby's Text::Hyphen, but currently reads standard *.dic files,
6 that must be installed separately.
7
8 In the future it's maybe nice if dictionaries could be distributed together with
9 this module, in a slightly prepared form, like in Ruby's Text::Hyphen.
10
11 Wilbert Berendsen, March 2008
12 info@wilbertberendsen.nl
13
14 License: LGPL.
15
16 """
17 import sys
18 import re
19
20 __all__ = ("Hyphenator")
21
22 # cache of per-file Hyph_dict objects
23 hdcache = {}
24
25 # precompile some stuff
26 parse_hex = re.compile(r'\^{2}([0-9a-f]{2})').sub
27 parse = re.compile(r'(\d?)(\D?)').findall
28
29 def hexrepl(matchObj):
30     return unichr(int(matchObj.group(1), 16))
31
32
33 class parse_alt(object):
34     """
35     Parse nonstandard hyphen pattern alternative.
36     The instance returns a special int with data about the current position
37     in the pattern when called with an odd value.
38     """
39     def __init__(self, pat, alt):
40         alt = alt.split(',')
41         self.change = alt[0]
42         if len(alt) > 2:
43             self.index = int(alt[1])
44             self.cut = int(alt[2]) + 1
45         else:
46             self.index = 1
47             self.cut = len(re.sub(r'[\d\.]', '', pat)) + 1
48         if pat.startswith('.'):
49             self.index += 1
50
51     def __call__(self, val):
52         self.index -= 1
53         val = int(val)
54         if val & 1:
55             return dint(val, (self.change, self.index, self.cut))
56         else:
57             return val
58
59
60 class dint(int):
61     """
62     Just an int some other data can be stuck to in a data attribute.
63     Call with ref=other to use the data from the other dint.
64     """
65     def __new__(cls, value, data=None, ref=None):
66         obj = int.__new__(cls, value)
67         if ref and type(ref) == dint:
68             obj.data = ref.data
69         else:
70             obj.data = data
71         return obj
72
73
74 class Hyph_dict(object):
75     """
76     Reads a hyph_*.dic file and stores the hyphenation patterns.
77     Parameters:
78     -filename : filename of hyph_*.dic to read
79     """
80     def __init__(self, filename):
81         self.patterns = {}
82         f = open(filename, 'rb')
83         charset = f.readline().strip()
84         if charset.startswith(b'charset '):
85             charset = charset[8:].strip()
86
87         for pat in f:
88             pat = pat.decode(charset.decode('latin1')).strip()
89             if not pat or pat[0] == '%': continue
90             # replace ^^hh with the real character
91             pat = parse_hex(hexrepl, pat)
92             # read nonstandard hyphen alternatives
93             if '/' in pat:
94                 pat, alt = pat.split('/', 1)
95                 factory = parse_alt(pat, alt)
96             else:
97                 factory = int
98             tag, value = zip(*[(s, factory(i or "0")) for i, s in parse(pat)])
99             # if only zeros, skip this pattern
100             if max(value) == 0: continue
101             # chop zeros from beginning and end, and store start offset.
102             start, end = 0, len(value)
103             while not value[start]: start += 1
104             while not value[end-1]: end -= 1
105             self.patterns[''.join(tag)] = start, value[start:end]
106         f.close()
107         self.cache = {}
108         self.maxlen = max(map(len, self.patterns.keys()))
109
110     def positions(self, word):
111         """
112         Returns a list of positions where the word can be hyphenated.
113         E.g. for the dutch word 'lettergrepen' this method returns
114         the list [3, 6, 9].
115
116         Each position is a 'data int' (dint) with a data attribute.
117         If the data attribute is not None, it contains a tuple with
118         information about nonstandard hyphenation at that point:
119         (change, index, cut)
120
121         change: is a string like 'ff=f', that describes how hyphenation
122             should take place.
123         index: where to substitute the change, counting from the current
124             point
125         cut: how many characters to remove while substituting the nonstandard
126             hyphenation
127         """
128         word = word.lower()
129         points = self.cache.get(word)
130         if points is None:
131             prepWord = '.%s.' % word
132             res = [0] * (len(prepWord) + 1)
133             for i in range(len(prepWord) - 1):
134                 for j in range(i + 1, min(i + self.maxlen, len(prepWord)) + 1):
135                     p = self.patterns.get(prepWord[i:j])
136                     if p:
137                         offset, value = p
138                         s = slice(i + offset, i + offset + len(value))
139                         res[s] = map(max, value, res[s])
140
141             points = [dint(i - 1, ref=r) for i, r in enumerate(res) if r % 2]
142             self.cache[word] = points
143         return points
144
145
146 class Hyphenator(object):
147     """
148     Reads a hyph_*.dic file and stores the hyphenation patterns.
149     Provides methods to hyphenate strings in various ways.
150     Parameters:
151     -filename : filename of hyph_*.dic to read
152     -left: make the first syllabe not shorter than this
153     -right: make the last syllabe not shorter than this
154     -cache: if true (default), use a cached copy of the dic file, if possible
155
156     left and right may also later be changed:
157       h = Hyphenator(file)
158       h.left = 1
159     """
160     def __init__(self, filename, left=2, right=2, cache=True):
161         self.left  = left
162         self.right = right
163         if not cache or filename not in hdcache:
164             hdcache[filename] = Hyph_dict(filename)
165         self.hd = hdcache[filename]
166
167     def positions(self, word):
168         """
169         Returns a list of positions where the word can be hyphenated.
170         See also Hyph_dict.positions. The points that are too far to
171         the left or right are removed.
172         """
173         right = len(word) - self.right
174         return [i for i in self.hd.positions(word) if self.left <= i <= right]
175
176     def iterate(self, word):
177         """
178         Iterate over all hyphenation possibilities, the longest first.
179         """
180         if isinstance(word, str):
181             word = word.decode('latin1')
182         for p in reversed(self.positions(word)):
183             if p.data:
184                 # get the nonstandard hyphenation data
185                 change, index, cut = p.data
186                 if word.isupper():
187                     change = change.upper()
188                 c1, c2 = change.split('=')
189                 yield word[:p+index] + c1, c2 + word[p+index+cut:]
190             else:
191                 yield word[:p], word[p:]
192
193     def wrap(self, word, width, hyphen='-'):
194         """
195         Return the longest possible first part and the last part of the
196         hyphenated word. The first part has the hyphen already attached.
197         Returns None, if there is no hyphenation point before width, or
198         if the word could not be hyphenated.
199         """
200         width -= len(hyphen)
201         for w1, w2 in self.iterate(word):
202             if len(w1) <= width:
203                 return w1 + hyphen, w2
204
205     def inserted(self, word, hyphen='-'):
206         """
207         Returns the word as a string with all the possible hyphens inserted.
208         E.g. for the dutch word 'lettergrepen' this method returns
209         the string 'let-ter-gre-pen'. The hyphen string to use can be
210         given as the second parameter, that defaults to '-'.
211         """
212         if isinstance(word, bytes):
213             word = word.decode('latin1')
214         l = list(word)
215         for p in reversed(self.positions(word)):
216             if p.data:
217                 # get the nonstandard hyphenation data
218                 change, index, cut = p.data
219                 if word.isupper():
220                     change = change.upper()
221                 l[p + index : p + index + cut] = change.replace('=', hyphen)
222             else:
223                 l.insert(p, hyphen)
224         return ''.join(l)
225
226     __call__ = iterate
227
228
229 if __name__ == "__main__":
230
231     dict_file = sys.argv[1]
232     word = sys.argv[2].decode('latin1')
233
234     h = Hyphenator(dict_file, left=1, right=1)
235
236     for i in h(word):
237         print(i)
238