|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright 2023 Telefónica Soluciones de Informática y Comunicaciones de España, S.A.U. |
| 3 | +# |
| 4 | +# This file is part of tc_etl_lib |
| 5 | +# |
| 6 | +# tc_etl_lib is free software: you can redistribute it and/or |
| 7 | +# modify it under the terms of the GNU Affero General Public License as |
| 8 | +# published by the Free Software Foundation, either version 3 of the |
| 9 | +# License, or (at your option) any later version. |
| 10 | +# |
| 11 | +# tc_etl_lib is distributed in the hope that it will be useful, |
| 12 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero |
| 14 | +# General Public License for more details. |
| 15 | +# |
| 16 | +# You should have received a copy of the GNU Affero General Public License |
| 17 | +# along with IoT orchestrator. If not, see http://www.gnu.org/licenses/. |
| 18 | +# |
| 19 | + |
| 20 | +import unicodedata |
| 21 | +import re |
| 22 | + |
| 23 | +from typing import Mapping, Optional |
| 24 | + |
| 25 | +_whitespace_re = re.compile(r"\s+") |
| 26 | + |
| 27 | +class normalizer: |
| 28 | + """ |
| 29 | + Normalizer is a class that will normalize unicode strings to |
| 30 | + valid NGSI entity IDs. Normalization rules are at: |
| 31 | +
|
| 32 | + https://github.com/telefonicaid/fiware-orion/blob/master/doc/manuals/orion-api.md#general-syntax-restrictions |
| 33 | +
|
| 34 | + Normalizers have a __call__ function that takes an input string and: |
| 35 | +
|
| 36 | + - Turn accented characters (á, é, í, ó, u) into unaccented variants. |
| 37 | + - Remove any other unicode character not available in ascii |
| 38 | + - Remove ascii control codes |
| 39 | + - Replace forbidden characters '&', '?', '/', '#' '<', '>', '"', ''', '=', ';', '(', ')' |
| 40 | + with the replacement character (default "-", can be changed in the constructor) |
| 41 | + - Merges consecutive whitespace and replaces it with the replacement character |
| 42 | +
|
| 43 | + You can also set a different replacement character for a specific forbidden |
| 44 | + character, by adding the translation to the `override` optional argument of the |
| 45 | + constructor. |
| 46 | +
|
| 47 | + E.g. if you want to replace " " with "+", you can call: |
| 48 | +
|
| 49 | + ``` |
| 50 | + norm = normalizer(override={" ": "+"}) |
| 51 | + norm("text (with spaces)") |
| 52 | + ``` |
| 53 | +
|
| 54 | + And you will get `"text+-with+spaces-"`. |
| 55 | +
|
| 56 | + You can also remove a forbidden character altogether, by setting its value to |
| 57 | + `None` in the `override` argument. E.g if you want to remove parenthesis, |
| 58 | + you can call: |
| 59 | +
|
| 60 | + ``` |
| 61 | + norm = normalizer(override={"(": None, ")": None}) |
| 62 | + norm("text (with parenthesis)") |
| 63 | + ``` |
| 64 | +
|
| 65 | + If you want to remove ALL special characters (except whitespace): |
| 66 | +
|
| 67 | + ``` |
| 68 | + norm = normalizer(replacement="", override={ " ": "-" }) |
| 69 | + norm("text (with & special > characters)") |
| 70 | + ``` |
| 71 | +
|
| 72 | + And you will get `"text-with-special-characters"` |
| 73 | +
|
| 74 | + The function does not trim the string size to 256 characters, because |
| 75 | + you might want the full normalized original string to store it somewhere |
| 76 | + else before truncating. |
| 77 | + """ |
| 78 | + |
| 79 | + def __init__(self, replacement: str = "-", override: Optional[Mapping[str, str]] = None): |
| 80 | + """Set the default replacement string and custom override mapping""" |
| 81 | + if override is None: |
| 82 | + override = {} |
| 83 | + forbidden_chars = { |
| 84 | + "&": replacement, |
| 85 | + "?": replacement, |
| 86 | + "/": replacement, |
| 87 | + "#": replacement, |
| 88 | + "<": replacement, |
| 89 | + ">": replacement, |
| 90 | + '"': replacement, |
| 91 | + "'": replacement, |
| 92 | + "=": replacement, |
| 93 | + ";": replacement, |
| 94 | + "(": replacement, |
| 95 | + ")": replacement |
| 96 | + } |
| 97 | + source = [] |
| 98 | + target = [] |
| 99 | + remove = [] |
| 100 | + for key, val in forbidden_chars.items(): |
| 101 | + custom = override.get(key, val) |
| 102 | + if custom is None or custom == "": |
| 103 | + remove.append(key) |
| 104 | + else: |
| 105 | + if len(custom) > 1: |
| 106 | + raise ValueError(f"wrong override '{custom}' for char '{key}': must be a single character") |
| 107 | + source.append(key) |
| 108 | + target.append(custom) |
| 109 | + self.space_replacement = override.get(" ", replacement) or "" |
| 110 | + self.table = str.maketrans( |
| 111 | + "".join(source), "".join(target), "".join(remove)) |
| 112 | + |
| 113 | + def __call__(self, text: str) -> str: |
| 114 | + """Normalize text to NGSI entity ID""" |
| 115 | + global _whitespace_re |
| 116 | + ascii = unicodedata.normalize('NFD', text).encode('utf-8').decode('ascii', errors='ignore') |
| 117 | + without_control_chars = "".join(ch for ch in ascii if unicodedata.category(ch)[0] != "C") |
| 118 | + without_specials = without_control_chars.translate(self.table).strip() |
| 119 | + return _whitespace_re.sub(self.space_replacement, without_specials) |
0 commit comments