PostgreSQL Source Code  git master
generate_unaccent_rules.py
Go to the documentation of this file.
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # This script builds unaccent.rules on standard output when given the
5 # contents of UnicodeData.txt [1] and Latin-ASCII.xml [2] given as
6 # arguments. Optionally includes ligature expansion and Unicode CLDR
7 # Latin-ASCII transliterator, enabled by default, this can be disabled
8 # with "--no-ligatures-expansion" command line option.
9 #
10 # The approach is to use the Unicode decomposition data to identify
11 # precomposed codepoints that are equivalent to a ligature of several
12 # letters, or a base letter with any number of diacritical marks.
13 #
14 # This approach handles most letters with diacritical marks and some
15 # ligatures. However, several characters (notably a majority of
16 # ligatures) don't have decomposition. To handle all these cases, one can
17 # use a standard Unicode transliterator available in Common Locale Data
18 # Repository (CLDR): Latin-ASCII. This transliterator associates Unicode
19 # characters to ASCII-range equivalent. Unless "--no-ligatures-expansion"
20 # option is enabled, the XML file of this transliterator [2] -- given as a
21 # command line argument -- will be parsed and used.
22 #
23 # Ideally you should use the latest release for each data set. This
24 # script is compatible with at least CLDR release 29.
25 #
26 # [1] https://www.unicode.org/Public/${UNICODE_VERSION}/ucd/UnicodeData.txt
27 # [2] https://raw.githubusercontent.com/unicode-org/cldr/${TAG}/common/transforms/Latin-ASCII.xml
28 
29 # BEGIN: Python 2/3 compatibility - remove when Python 2 compatibility dropped
30 # The approach is to be Python3 compatible with Python2 "backports".
31 from __future__ import print_function
32 from __future__ import unicode_literals
33 # END: Python 2/3 compatibility - remove when Python 2 compatibility dropped
34 
35 import argparse
36 import codecs
37 import re
38 import sys
39 import xml.etree.ElementTree as ET
40 
41 # BEGIN: Python 2/3 compatibility - remove when Python 2 compatibility dropped
42 if sys.version_info[0] <= 2:
43  # Encode stdout as UTF-8, so we can just print to it
44  sys.stdout = codecs.getwriter('utf8')(sys.stdout)
45 
46  # Map Python 2's chr to unichr
47  chr = unichr
48 
49  # Python 2 and 3 compatible bytes call
50  def bytes(source, encoding='ascii', errors='strict'):
51  return source.encode(encoding=encoding, errors=errors)
52 else:
53 # END: Python 2/3 compatibility - remove when Python 2 compatibility dropped
54  sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
55 
56 # The ranges of Unicode characters that we consider to be "plain letters".
57 # For now we are being conservative by including only Latin and Greek. This
58 # could be extended in future based on feedback from people with relevant
59 # language knowledge.
60 PLAIN_LETTER_RANGES = ((ord('a'), ord('z')), # Latin lower case
61  (ord('A'), ord('Z')), # Latin upper case
62  (0x03b1, 0x03c9), # GREEK SMALL LETTER ALPHA, GREEK SMALL LETTER OMEGA
63  (0x0391, 0x03a9)) # GREEK CAPITAL LETTER ALPHA, GREEK CAPITAL LETTER OMEGA
64 
65 # Combining marks follow a "base" character, and result in a composite
66 # character. Example: "U&'A\0300'"produces "À".There are three types of
67 # combining marks: enclosing (Me), non-spacing combining (Mn), spacing
68 # combining (Mc). We identify the ranges of marks we feel safe removing.
69 # References:
70 # https://en.wikipedia.org/wiki/Combining_character
71 # https://www.unicode.org/charts/PDF/U0300.pdf
72 # https://www.unicode.org/charts/PDF/U20D0.pdf
73 COMBINING_MARK_RANGES = ((0x0300, 0x0362), # Mn: Accents, IPA
74  (0x20dd, 0x20E0), # Me: Symbols
75  (0x20e2, 0x20e4),) # Me: Screen, keycap, triangle
76 
77 def print_record(codepoint, letter):
78  if letter:
79  output = chr(codepoint) + "\t" + letter
80  else:
81  output = chr(codepoint)
82 
83  print(output)
84 
85 class Codepoint:
86  def __init__(self, id, general_category, combining_ids):
87  self.id = id
88  self.general_category = general_category
89  self.combining_ids = combining_ids
90 
91 def is_mark_to_remove(codepoint):
92  """Return true if this is a combining mark to remove."""
93  if not is_mark(codepoint):
94  return False
95 
96  for begin, end in COMBINING_MARK_RANGES:
97  if codepoint.id >= begin and codepoint.id <= end:
98  return True
99  return False
100 
101 def is_plain_letter(codepoint):
102  """Return true if codepoint represents a "plain letter"."""
103  for begin, end in PLAIN_LETTER_RANGES:
104  if codepoint.id >= begin and codepoint.id <= end:
105  return True
106  return False
107 
108 def is_mark(codepoint):
109  """Returns true for diacritical marks (combining codepoints)."""
110  return codepoint.general_category in ("Mn", "Me", "Mc")
111 
112 def is_letter_with_marks(codepoint, table):
113  """Returns true for letters combined with one or more marks."""
114  # See https://www.unicode.org/reports/tr44/tr44-14.html#General_Category_Values
115 
116  # Letter may have no combining characters, in which case it has
117  # no marks.
118  if len(codepoint.combining_ids) == 1:
119  return False
120 
121  # A letter without diacritical marks has none of them.
122  if any(is_mark(table[i]) for i in codepoint.combining_ids[1:]) is False:
123  return False
124 
125  # Check if the base letter of this letter has marks.
126  codepoint_base = codepoint.combining_ids[0]
127  if (is_plain_letter(table[codepoint_base]) is False and \
128  is_letter_with_marks(table[codepoint_base], table) is False):
129  return False
130 
131  return True
132 
133 def is_letter(codepoint, table):
134  """Return true for letter with or without diacritical marks."""
135  return is_plain_letter(codepoint) or is_letter_with_marks(codepoint, table)
136 
137 def get_plain_letter(codepoint, table):
138  """Return the base codepoint without marks. If this codepoint has more
139  than one combining character, do a recursive lookup on the table to
140  find out its plain base letter."""
141  if is_letter_with_marks(codepoint, table):
142  if len(table[codepoint.combining_ids[0]].combining_ids) > 1:
143  return get_plain_letter(table[codepoint.combining_ids[0]], table)
144  elif is_plain_letter(table[codepoint.combining_ids[0]]):
145  return table[codepoint.combining_ids[0]]
146 
147  # Should not come here
148  assert(False)
149  elif is_plain_letter(codepoint):
150  return codepoint
151 
152  # Should not come here
153  assert(False)
154 
155 def is_ligature(codepoint, table):
156  """Return true for letters combined with letters."""
157  return all(is_letter(table[i], table) for i in codepoint.combining_ids)
158 
159 def get_plain_letters(codepoint, table):
160  """Return a list of plain letters from a ligature."""
161  assert(is_ligature(codepoint, table))
162  return [get_plain_letter(table[id], table) for id in codepoint.combining_ids]
163 
165  """Parse the XML file and return a set of tuples (src, trg), where "src"
166  is the original character and "trg" the substitute."""
167  charactersSet = set()
168 
169  # RegEx to parse rules
170  rulePattern = re.compile(r'^(?:(.)|(\\u[0-9a-fA-F]{4})) \u2192 (?:\'(.+)\'|(.+)) ;')
171 
172  # construct tree from XML
173  transliterationTree = ET.parse(latinAsciiFilePath)
174  transliterationTreeRoot = transliterationTree.getroot()
175 
176  # Fetch all the transliteration rules. Since release 29 of Latin-ASCII.xml
177  # all the transliteration rules are located in a single tRule block with
178  # all rules separated into separate lines.
179  blockRules = transliterationTreeRoot.findall("./transforms/transform/tRule")
180  assert(len(blockRules) == 1)
181 
182  # Split the block of rules into one element per line.
183  rules = blockRules[0].text.splitlines()
184 
185  # And finish the processing of each individual rule.
186  for rule in rules:
187  matches = rulePattern.search(rule)
188 
189  # The regular expression capture four groups corresponding
190  # to the characters.
191  #
192  # Group 1: plain "src" char. Empty if group 2 is not.
193  # Group 2: unicode-escaped "src" char (e.g. "\u0110"). Empty if group 1 is not.
194  #
195  # Group 3: plain "trg" char. Empty if group 4 is not.
196  # Group 4: plain "trg" char between quotes. Empty if group 3 is not.
197  if matches is not None:
198  src = matches.group(1) if matches.group(1) is not None else bytes(matches.group(2), 'UTF-8').decode('unicode-escape')
199  trg = matches.group(3) if matches.group(3) is not None else matches.group(4)
200 
201  # "'" and """ are escaped
202  trg = trg.replace("\\'", "'").replace('\\"', '"')
203 
204  # the parser of unaccent only accepts non-whitespace characters
205  # for "src" and "trg" (see unaccent.c)
206  if not src.isspace() and not trg.isspace():
207  charactersSet.add((ord(src), trg))
208 
209  return charactersSet
210 
212  """Returns the special cases which are not handled by other methods"""
213  charactersSet = set()
214 
215  # Cyrillic
216  charactersSet.add((0x0401, u"\u0415")) # CYRILLIC CAPITAL LETTER IO
217  charactersSet.add((0x0451, u"\u0435")) # CYRILLIC SMALL LETTER IO
218 
219  # Symbols of "Letterlike Symbols" Unicode Block (U+2100 to U+214F)
220  charactersSet.add((0x2103, u"\xb0C")) # DEGREE CELSIUS
221  charactersSet.add((0x2109, u"\xb0F")) # DEGREE FAHRENHEIT
222  charactersSet.add((0x2117, "(P)")) # SOUND RECORDING COPYRIGHT
223 
224  return charactersSet
225 
226 def main(args):
227  # https://www.unicode.org/reports/tr44/tr44-14.html#Character_Decomposition_Mappings
228  decomposition_type_pattern = re.compile(" *<[^>]*> *")
229 
230  table = {}
231  all = []
232 
233  # unordered set for ensure uniqueness
234  charactersSet = set()
235 
236  # read file UnicodeData.txt
237  with codecs.open(
238  args.unicodeDataFilePath, mode='r', encoding='UTF-8',
239  ) as unicodeDataFile:
240  # read everything we need into memory
241  for line in unicodeDataFile:
242  fields = line.split(";")
243  if len(fields) > 5:
244  # https://www.unicode.org/reports/tr44/tr44-14.html#UnicodeData.txt
245  general_category = fields[2]
246  decomposition = fields[5]
247  decomposition = re.sub(decomposition_type_pattern, ' ', decomposition)
248  id = int(fields[0], 16)
249  combining_ids = [int(s, 16) for s in decomposition.split(" ") if s != ""]
250  codepoint = Codepoint(id, general_category, combining_ids)
251  table[id] = codepoint
252  all.append(codepoint)
253 
254  # walk through all the codepoints looking for interesting mappings
255  for codepoint in all:
256  if codepoint.general_category.startswith('L') and \
257  len(codepoint.combining_ids) > 1:
258  if is_letter_with_marks(codepoint, table):
259  charactersSet.add((codepoint.id,
260  chr(get_plain_letter(codepoint, table).id)))
261  elif args.noLigaturesExpansion is False and is_ligature(codepoint, table):
262  charactersSet.add((codepoint.id,
263  "".join(chr(combining_codepoint.id)
264  for combining_codepoint \
265  in get_plain_letters(codepoint, table))))
266  elif is_mark_to_remove(codepoint):
267  charactersSet.add((codepoint.id, None))
268 
269  # add CLDR Latin-ASCII characters
270  if not args.noLigaturesExpansion:
271  charactersSet |= parse_cldr_latin_ascii_transliterator(args.latinAsciiFilePath)
272  charactersSet |= special_cases()
273 
274  # sort for more convenient display
275  charactersList = sorted(charactersSet, key=lambda characterPair: characterPair[0])
276 
277  for characterPair in charactersList:
278  print_record(characterPair[0], characterPair[1])
279 
280 if __name__ == "__main__":
281  parser = argparse.ArgumentParser(description='This script builds unaccent.rules on standard output when given the contents of UnicodeData.txt and Latin-ASCII.xml given as arguments.')
282  parser.add_argument("--unicode-data-file", help="Path to formatted text file corresponding to UnicodeData.txt.", type=str, required=True, dest='unicodeDataFilePath')
283  parser.add_argument("--latin-ascii-file", help="Path to XML file from Unicode Common Locale Data Repository (CLDR) corresponding to Latin-ASCII transliterator (Latin-ASCII.xml).", type=str, dest='latinAsciiFilePath')
284  parser.add_argument("--no-ligatures-expansion", help="Do not expand ligatures and do not use Unicode CLDR Latin-ASCII transliterator. By default, this option is not enabled and \"--latin-ascii-file\" argument is required. If this option is enabled, \"--latin-ascii-file\" argument is optional and ignored.", action="store_true", dest='noLigaturesExpansion')
285  args = parser.parse_args()
286 
287  if args.noLigaturesExpansion is False and args.latinAsciiFilePath is None:
288  sys.stderr.write('You must specify the path to Latin-ASCII transliterator file with \"--latin-ascii-file\" option or use \"--no-ligatures-expansion\" option. Use \"-h\" option for help.')
289  sys.exit(1)
290 
291  main(args)
void print(const void *obj)
Definition: print.c:36
def bytes(source, encoding='ascii', errors='strict')
def __init__(self, id, general_category, combining_ids)
def is_ligature(codepoint, table)
def get_plain_letters(codepoint, table)
#define assert(TEST)
Definition: imath.c:73
def parse_cldr_latin_ascii_transliterator(latinAsciiFilePath)
def print_record(codepoint, letter)
def get_plain_letter(codepoint, table)
def is_letter_with_marks(codepoint, table)
def is_letter(codepoint, table)