|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""Fancy Codecs - Unicode styled alphabets content encoding. |
| 3 | +
|
| 4 | +Unicode has styled versions of the Latin letters and of the digits, often used to write "fancy" text (e.g. in social |
| 5 | + networks) or to obfuscate text (e.g. to evade filters): the mathematical alphanumeric symbols (bold, italic, bold |
| 6 | + italic, script, bold script, fraktur, bold fraktur, double-struck, sans-serif, sans-serif bold, sans-serif italic, |
| 7 | + sans-serif bold italic and monospace, some letters being in the Letterlike Symbols block, e.g. "ℬ" or "ℎ"), the |
| 8 | + circled and parenthesized letters and digits, the full-width forms of ASCII and the small capitals (for the lowercase |
| 9 | + letters, except "x" that has no small capital). Encoding writes the letters and digits of the text in the given style |
| 10 | + (or, for full-width forms, all the printable ASCII characters, and the space as an ideographic space), keeping the |
| 11 | + other characters, while decoding writes back the characters of this style ; "fancy" without a style decodes all of |
| 12 | + them at once (e.g. for text mixing several styles). |
| 13 | +
|
| 14 | +The NFKC normalization (unicodedata.normalize("NFKC", ...)) also undoes the mathematical, circled and full-width styles, |
| 15 | + but not the parenthesized one (giving e.g. "(a)") nor the small capitals ; unlike this codec, it changes other |
| 16 | + characters as well (e.g. ligatures and superscripts). |
| 17 | +
|
| 18 | +These codecs: |
| 19 | +- en/decode strings from str to str |
| 20 | +- en/decode strings from bytes to bytes |
| 21 | +- decode file content to str (read) |
| 22 | +- encode file content from str to bytes (write) |
| 23 | +
|
| 24 | +Reference: https://www.unicode.org/charts/PDF/U1D400.pdf |
| 25 | +""" |
| 26 | +import unicodedata |
| 27 | +from string import ascii_lowercase, ascii_uppercase, digits |
| 28 | + |
| 29 | +from ..__common__ import * |
| 30 | + |
| 31 | + |
| 32 | +__examples1__ = { |
| 33 | + 'enc(fancy-bold|fancy_bold)': {'Hello 2026!': "\U0001d407\U0001d41e\U0001d425\U0001d425\U0001d428 \U0001d7d0" |
| 34 | + "\U0001d7ce\U0001d7d0\U0001d7d4!"}, |
| 35 | + 'enc(fancy-script)': {'Bohe': "ℬℴ\U0001d4bdℯ"}, |
| 36 | + 'dec(fancy)': {'\U0001d407\U0001d58a\U0001d695ⓛ⒪ wᴏʀʟᴅ': "Hello world"}, |
| 37 | + 'enc-dec(fancy-%s)': ["", "Hello World 2026", "caf\xe9 & €, 日本!"], |
| 38 | +} |
| 39 | +__examples2__ = { |
| 40 | + 'enc(fullwidth|full-width|full_width)': {'Hello, World!': "Hello,\u3000Wo" |
| 41 | + "rld!"}, |
| 42 | + 'enc-dec(fullwidth)': ["", "@random{256}"], |
| 43 | +} |
| 44 | +__examples3__ = { |
| 45 | + 'enc(smallcaps|small-caps|small_caps)': {'Hello World': "Hᴇʟʟᴏ Wᴏʀʟᴅ"}, |
| 46 | + 'enc-dec(smallcaps)': ["", "The quick brown fox jumps over the lazy dog", "@random{256}"], |
| 47 | +} |
| 48 | + |
| 49 | + |
| 50 | +_DIGITS = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] |
| 51 | +# names of the letters of some styles that are in the Letterlike Symbols block (e.g. "SCRIPT CAPITAL B") |
| 52 | +_LETTERLIKE = {'SCRIPT': "SCRIPT", 'FRAKTUR': "BLACK-LETTER", 'DOUBLE-STRUCK': "DOUBLE-STRUCK"} |
| 53 | + |
| 54 | + |
| 55 | +def _lookup(*names): |
| 56 | + """ First character with one of the given names (the characters missing from the Unicode database of the version of |
| 57 | + Python being skipped). """ |
| 58 | + for name in names: |
| 59 | + try: |
| 60 | + return unicodedata.lookup(name) |
| 61 | + except KeyError: |
| 62 | + pass |
| 63 | + |
| 64 | + |
| 65 | +def __alphabet(name, chars): |
| 66 | + return {c: f for c in chars if (f := _lookup(*name(c)))} |
| 67 | + |
| 68 | + |
| 69 | +def __math(style): |
| 70 | + case = lambda c: "CAPITAL" if c.isupper() else "SMALL" |
| 71 | + return __alphabet(lambda c: [f"MATHEMATICAL {style} DIGIT {_DIGITS[int(c)]}"] if c.isdigit() else |
| 72 | + [f"MATHEMATICAL {style} {case(c)} {c.upper()}"] + |
| 73 | + ([f"{_LETTERLIKE[style]} {case(c)} {c.upper()}"] if style in _LETTERLIKE else []) + |
| 74 | + ["PLANCK CONSTANT"] * (style == "ITALIC" and c == "h"), |
| 75 | + ascii_uppercase + ascii_lowercase + digits) |
| 76 | + |
| 77 | + |
| 78 | +def __enclosed(kind): |
| 79 | + return __alphabet(lambda c: [f"{kind} DIGIT {_DIGITS[int(c)]}"] if c.isdigit() else |
| 80 | + [f"{kind} LATIN {'CAPITAL' if c.isupper() else 'SMALL'} LETTER {c.upper()}"], |
| 81 | + ascii_uppercase + ascii_lowercase + digits) |
| 82 | + |
| 83 | + |
| 84 | +ALPHABETS = {s.lower().replace(" ", "-"): __math(s) for s in ["BOLD", "ITALIC", "BOLD ITALIC", "SCRIPT", "BOLD SCRIPT", |
| 85 | + "FRAKTUR", "BOLD FRAKTUR", "DOUBLE-STRUCK", "SANS-SERIF", "SANS-SERIF BOLD", "SANS-SERIF ITALIC", |
| 86 | + "SANS-SERIF BOLD ITALIC", "MONOSPACE"]} |
| 87 | +ALPHABETS.update({ |
| 88 | + 'circled': __enclosed("CIRCLED"), |
| 89 | + 'parenthesized': __enclosed("PARENTHESIZED"), |
| 90 | + 'fullwidth': {chr(i): chr(i + 0xfee0) for i in range(0x21, 0x7f)} | {" ": "\u3000"}, |
| 91 | + 'smallcaps': __alphabet(lambda c: [f"LATIN LETTER SMALL CAPITAL {c.upper()}"], ascii_lowercase), |
| 92 | +}) |
| 93 | +DECODE = {k: {f: c for c, f in a.items()} for k, a in ALPHABETS.items()} |
| 94 | +DECODE_ALL = {f: c for d in DECODE.values() for f, c in d.items()} |
| 95 | +__examples1__["enc-dec(fancy-%s)" % "|fancy-".join(ALPHABETS)] = __examples1__.pop("enc-dec(fancy-%s)") |
| 96 | + |
| 97 | + |
| 98 | +def fancy_encode(style=None): |
| 99 | + def encode(text, errors="strict"): |
| 100 | + if not style: |
| 101 | + raise LookupError("Bad parameter for encoding 'fancy': a style is required, among " + ", ".join(ALPHABETS)) |
| 102 | + alphabet = ALPHABETS[style.replace("_", "-")] |
| 103 | + return "".join(alphabet.get(c, c) for c in ensure_str(text)), len(text) |
| 104 | + return encode |
| 105 | + |
| 106 | + |
| 107 | +def fancy_decode(style=None): |
| 108 | + def decode(text, errors="strict"): |
| 109 | + table = DECODE[style.replace("_", "-")] if style else DECODE_ALL |
| 110 | + return "".join(table.get(c, c) for c in ensure_str(text)), len(text) |
| 111 | + return decode |
| 112 | + |
| 113 | + |
| 114 | +add("fancy", fancy_encode, fancy_decode, r"^fancy(?:[-_](" + "|".join(s.replace("-", "[-_]") for s in ALPHABETS) + |
| 115 | + r"))?$", examples=__examples1__, guess=None) |
| 116 | +add("fullwidth", fancy_encode("fullwidth"), fancy_decode("fullwidth"), r"^full[-_]?width$", examples=__examples2__, |
| 117 | + guess=None) |
| 118 | +add("smallcaps", fancy_encode("smallcaps"), fancy_decode("smallcaps"), r"^small[-_]?caps$", examples=__examples3__, |
| 119 | + guess=None) |
0 commit comments