Spaces:
Running

backend / scripts /gen_emoji_groups.py
paisaly's picture
Upload 1776 files
25834e9 verified
Raw History Blame Contribute Delete
5.07 kB
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Distill the canonical Unicode emoji grouping into a committed artifact.
The pinned ``emoji`` package (2.15.0, Unicode Emoji 15.1) exposes no group
or category field, so the ``/api/v1/emoji-set`` picker has no categories
and no sensible opening order. This script reads the canonical grouping
from Unicode's ``emoji-test.txt`` (the CLDR-ordered source every emoji
picker uses) and writes ``data/emoji_groups.json`` — a distilled
char -> (group, order-index) map with NO runtime network dependency.
The artifact is PRESENTATION metadata only. The accepted emoji set stays
policy-derived in ``shared.emoji_policy``; this data is joined onto it by
character at response time (group name + canonical sort key). It never
decides which emoji are accepted.
Only single-codepoint canonical entries (the join domain: the accepted set
is single-codepoint) are kept. Each char is stored VS16-stripped so it
matches the canonical form the policy and the endpoint use. The first
occurrence in CLDR file order wins (fixes both group and order index).
Run from the repo root (fetches once over the network)::
uv run scripts/gen_emoji_groups.py
Pin a specific Unicode Emoji version with ``--version`` (default 15.1, to
match the pinned ``emoji`` package). Re-run and commit the result whenever
the ``emoji`` pin is bumped to a new Unicode version.
"""
from __future__ import annotations
import argparse
import json
import sys
import urllib.request
from pathlib import Path
_VS16 = "️"
_URL = "https://unicode.org/Public/emoji/{version}/emoji-test.txt"
def _char_from_codepoints(codepoints: str) -> str | None:
"""Return the VS16-stripped char for a code-point list, or None.
None when the result is not a single codepoint — we only distil the
single-codepoint domain the accepted set is drawn from.
"""
chars = [chr(int(cp, 16)) for cp in codepoints.split()]
stripped = "".join(c for c in chars if c != _VS16)
return stripped if len(stripped) == 1 else None
def distill(text: str) -> tuple[list[str], list[tuple[str, int]]]:
"""Parse emoji-test.txt into (group names, [(char, group_index)]).
Entries are in canonical CLDR order; the list position is the order
index. Only fully-qualified single-codepoint entries are kept, first
occurrence wins.
"""
groups: list[str] = []
entries: list[tuple[str, int]] = []
seen: set[str] = set()
current = -1
for line in text.splitlines():
if line.startswith("# group:"):
groups.append(line.split(":", 1)[1].strip())
current = len(groups) - 1
continue
if not line or line.startswith("#"):
continue
codepoints, _, rest = line.partition(";")
if "fully-qualified" not in rest:
continue
char = _char_from_codepoints(codepoints.strip())
if char is None or char in seen:
continue
seen.add(char)
entries.append((char, current))
return groups, entries
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--version", default="15.1", help="Unicode Emoji version")
args = parser.parse_args()
url = _URL.format(version=args.version)
with urllib.request.urlopen(url) as resp: # trusted unicode.org URL
text = resp.read().decode("utf-8")
groups, entries = distill(text)
if not groups or not entries:
print("ERROR: parsed no groups/entries", file=sys.stderr)
return 1
comment = (
"GENERATED by scripts/gen_emoji_groups.py — do not edit by hand. "
"Canonical Unicode emoji grouping distilled from emoji-test.txt "
"(CLDR order). PRESENTATION metadata joined onto the "
"policy-derived accepted set by char; never decides acceptance. "
"entries are [char, group_index] in canonical order; list "
"position is the sort key. Re-run when the emoji pin is bumped."
)
# Header via json.dumps for correct escaping; entries compact, one per
# line, so the generated file stays reviewable rather than 3 lines/entry.
lines = [
"{",
f' "_comment": {json.dumps(comment, ensure_ascii=False)},',
f' "unicode_emoji_version": {json.dumps(args.version)},',
f' "groups": {json.dumps(groups, ensure_ascii=False)},',
' "entries": [',
]
body = [f" {json.dumps([char, gi], ensure_ascii=False)}" for char, gi in entries]
lines.append(",\n".join(body))
lines.append(" ]")
lines.append("}")
dest = Path(__file__).resolve().parent.parent / "app" / "data" / "emoji_groups.json"
dest.write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"wrote {dest} — {len(groups)} groups, {len(entries)} single-cp entries")
return 0
if __name__ == "__main__":
sys.exit(main())