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