Token Classification
spaCy
Transformers
Indonesian
dependency-parsing
pos-tagging
lemmatization
ner
Eval Results (legacy)
Run this model with HF Jobs
Run firqaaa/id_core_web_trf on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/firqaaa/id_core_web_trf. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/firqaaa/id_core_web_trf on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use firqaaa/id_core_web_trf with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- spaCy
How to use firqaaa/id_core_web_trf with spaCy:
!pip install https://huggingface.co/firqaaa/id_core_web_trf/resolve/main/id_core_web_trf-any-py3-none-any.whl # Using spacy.load(). import spacy nlp = spacy.load("id_core_web_trf") # Importing as module. import id_core_web_trf nlp = id_core_web_trf.load() - Transformers
How to use firqaaa/id_core_web_trf with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="firqaaa/id_core_web_trf")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("firqaaa/id_core_web_trf", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download id_rules.py from firqaaa/id_core_web_trf: direct link, hf CLI and curl.
- Browser
- Download file 22.6 kB
-
https://huggingface.co/firqaaa/id_core_web_trf/resolve/main/id_rules.py
- Command line
-
hf download hf://firqaaa/id_core_web_trf/id_rules.py
-
curl -L -o id_rules.py https://huggingface.co/firqaaa/id_core_web_trf/resolve/main/id_rules.py
22.6 kB
| """Rule-based Indonesian entities: DATE, TIME, MONEY, PERCENT, QUANTITY, | |
| ORDINAL, CARDINAL and LAW, following docs/03-ner-guideline.md. | |
| Pipeline component `id_rule_ner`. It adds entities that do not overlap any | |
| existing entity, so it can run after a statistical `ner` without overriding | |
| PERSON/ORG/... predictions. Overlapping rule matches are resolved by length, | |
| then by label priority (LAW > MONEY > PERCENT > QUANTITY > DATE > TIME > | |
| ORDINAL > CARDINAL). | |
| Register with `--code scripts/id_rules.py` (or import this module). | |
| `conventions` (config, default "v0.1"): "v0.2" applies the span decisions of | |
| guideline v0.2 (docs/03-ner-guideline.md) to rule spans: | |
| - D1: an approximator or bound before a number is inside the span | |
| (`sekitar Rp 9.000`, `lebih dari 20 persen`, `minus 1,2 persen`); not for | |
| DATE/TIME, where `hingga` means "until". | |
| - D14: `lalu` / `mendatang` / `silam` after a full date are inside the span, | |
| and two DATE spans joined by `hingga` / `sampai` / `-` / `–` become one range. | |
| - D15: a weekday followed by a time of day (`Selasa pagi`) is TIME. | |
| "v0.1" keeps the behaviour of releases up to 0.6.0. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from spacy.language import Language | |
| from spacy.matcher import Matcher | |
| from spacy.tokens import Doc, Span | |
| from spacy.util import filter_spans | |
| # --- Lexicon ---------------------------------------------------------------- | |
| APPROX_PREFIX = [["lebih", "dari"], ["kurang", "dari"], ["lebih", "kurang"], ["paling", "tidak"], ["di", "atas"], | |
| ["di", "bawah"], ["tidak", "sampai"], ["belum", "sampai"], ["sekitar"], ["hampir"], ["setidaknya"], | |
| ["sedikitnya"], ["minimal"], ["maksimal"], ["maksimum"], ["minimum"], ["kira-kira"], ["hingga"], | |
| ["sampai"], ["minus"], ["plus"]] | |
| APPROX_LABELS = {"MONEY", "PERCENT", "QUANTITY", "CARDINAL"} | |
| DATE_TAIL = {"lalu", "mendatang", "silam"} | |
| RANGE_JOIN = {"hingga", "sampai", "-", "–", "s.d.", "s/d"} | |
| UNITS_WORDS = ["nol", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", | |
| "sepuluh", "sebelas", "seratus", "seribu", "sejuta", "semiliar", "setengah", "separuh"] | |
| SCALE_WORDS = ["belas", "puluh", "ratus", "ribu", "juta", "miliar", "milyar", "triliun"] | |
| APPROX_WORDS = ["puluhan", "ratusan", "ribuan", "jutaan", "miliaran", "belasan", "triliunan"] | |
| NUMBER_WORDS = UNITS_WORDS + SCALE_WORDS | |
| SCALE = ["ribu", "juta", "miliar", "milyar", "triliun", "rb", "jt", "m", "t"] | |
| CURRENCY_BEFORE = ["rp", "idr", "us$", "usd", "$", "€", "£", "¥", "s$", "rm", "sgd", "eur"] | |
| CURRENCY_AFTER = ["rupiah", "dolar", "dollar", "euro", "yen", "ringgit", "franc", "francs", "won", "yuan", | |
| "pound", "poundsterling", "riyal", "rupee", "baht", "peso"] | |
| UNITS = ["km", "kilometer", "m", "meter", "cm", "sentimeter", "mm", "milimeter", "kg", "kilogram", "gram", "gr", | |
| "ton", "kuintal", "liter", "ml", "mililiter", "hektare", "hektar", "ha", "mil", "inci", "kaki", "are", | |
| "km2", "m2", "m3", "mw", "megawatt", "kw", "kilowatt", "kwh", "gw", "watt", "volt", "barel", "kl", "derajat", | |
| "knot", "mph", "km/jam", "sr", "gb", "mb", "tb", "kalori", "kkal"] | |
| MONTHS = ["januari", "februari", "pebruari", "maret", "april", "mei", "juni", "juli", "agustus", "september", | |
| "oktober", "november", "nopember", "desember", "jan", "feb", "mar", "apr", "jun", "jul", "agu", "agt", | |
| "ags", "sep", "sept", "okt", "nov", "nop", "des"] | |
| DAYS = ["senin", "selasa", "rabu", "kamis", "jumat", "jum'at", "sabtu", "minggu", "ahad"] | |
| HOLIDAYS = [["lebaran"], ["idul", "fitri"], ["idulfitri"], ["idul", "adha"], ["iduladha"], ["natal"], | |
| ["imlek"], ["nyepi"], ["waisak"], ["ramadan"], ["ramadhan"], ["tahun", "baru"], ["paskah"], | |
| ["maulid", "nabi"], ["isra", "miraj"], ["isra", "mi'raj"], ["hari", "kemerdekaan"]] | |
| DATE_UNITS = ["hari", "pekan", "minggu", "bulan", "tahun", "abad", "dekade", "windu", "semester", "kuartal", | |
| "triwulan", "caturwulan"] | |
| RELATIVE = ["lalu", "depan", "ini", "kemarin", "mendatang", "silam", "sebelumnya", "berikutnya"] | |
| TIME_UNITS = ["jam", "menit", "detik"] | |
| TIME_OF_DAY = ["pagi", "siang", "sore", "malam", "petang", "subuh"] | |
| TIMEZONES = ["wib", "wita", "wit", "gmt", "utc"] | |
| ORDINAL_WORDS = ["pertama", "kedua", "ketiga", "keempat", "kelima", "keenam", "ketujuh", "kedelapan", | |
| "kesembilan", "kesepuluh", "kesebelas", "keseratus", "keseribu", "terakhir_"] # terakhir excluded | |
| LAW_HEADS = ["uu", "undang-undang", "pp", "perpres", "perppu", "perpu", "permen", "perda", "keppres", "kepres", | |
| "inpres", "perma", "pergub", "perwali", "perbup", "permendagri", "permenkeu", "permendikbud", | |
| "permenkes", "perkap", "perkapolri", "pojk", "peraturan", "keputusan", "instruksi", "qanun", "tap", | |
| "ketetapan", "surat", "se"] | |
| LAW_FIXED = [["uud", "1945"], ["uud", "nri", "1945"], ["undang-undang", "dasar", "1945"], ["kuhp"], ["kuhap"], | |
| ["kuh", "perdata"], ["kuhperdata"], ["kuhd"]] | |
| # Phase 2: names the gold NER sources do not annotate. | |
| NORP_HEADS = ["suku", "warga", "orang", "bangsa", "umat", "kaum", "etnis", "etnik", "rakyat", "keturunan", | |
| "masyarakat", "penganut", "pemeluk", "imigran", "pengungsi", "turis", "wisatawan"] | |
| NORP_WORDS = ["Muslim", "Muslimah", "Kristen", "Katolik", "Protestan", "Hindu", "Buddha", "Buddhis", "Yahudi", | |
| "Sunni", "Syiah", "Ahmadiyah", "Konghucu", "Tionghoa", "WNI", "WNA", "Nahdliyin", "Rohingya", | |
| "Uighur", "Uyghur", "Kurdi", "Badui", "Baduy", "Nasrani", "Islami"] | |
| # The token after a NORP head must not start a place name ("warga Desa X" is not NORP). | |
| PLACE_STARTS = ["desa", "kota", "kabupaten", "kecamatan", "provinsi", "kampung", "dusun", "dukuh", "kelurahan", "rt", "rw", | |
| "perumahan", "jalan", "jl", "kompleks", "pulau", "negara", "daerah", "kawasan", "sekitar"] | |
| EVENT_HEADS = ["Piala", "Liga", "Olimpiade", "Paralimpiade", "Festival", "Konferensi", "KTT", "Perang", | |
| "Pertempuran", "Kongres", "Muktamar", "Munas", "Kejuaraan", "Turnamen", "Tragedi", "Peristiwa", | |
| "Revolusi", "Pekan", "Grand", "Tour", "Konser", "Pameran", "Sidang", "Rapat", "Musyawarah", | |
| "Sumpah", "Proklamasi", "Gempa", "Tsunami", "Expo", "World"] | |
| ELECTIONS = ["pemilu", "pilpres", "pileg", "pilkada", "pilgub", "pilwalkot", "pilbup", "pemilihan"] | |
| # not cues: program/acara/game (mostly programme, event and match names, not works of art) | |
| WOA_CUES = ["film", "lagu", "novel", "buku", "album", "single", "singel", "sinetron", "serial", "drama", | |
| "lukisan", "puisi", "cerpen", "komik", "opera", "lakon", "tayangan", "judul", | |
| "karya", "kitab", "majalah_"] # majalah (magazine) is ORG in OntoNotes | |
| TITLE_SMALL = ["dan", "di", "ke", "dari", "yang", "dengan", "untuk", "the", "of", "and", "a", "in", "si", "sang"] | |
| RULE_LABELS = {"LAW", "MONEY", "PERCENT", "QUANTITY", "DATE", "TIME", "ORDINAL", "CARDINAL"} | |
| LABEL_PRIORITY = ["LAW", "EVENT", "WORK_OF_ART", "LANGUAGE", "NORP", "MONEY", "PERCENT", "QUANTITY", "DATE", "TIME", | |
| "ORDINAL", "CARDINAL"] | |
| DIGITS = {"TEXT": {"REGEX": r"^\d+([.,]\d+)*([.,]\d+)?$"}} | |
| DIGIT_RANGE = {"TEXT": {"REGEX": r"^\d+([.,]\d+)*-\d+([.,]\d+)*$"}} | |
| NUMWORD = {"LOWER": {"IN": NUMBER_WORDS}} | |
| YEAR = {"TEXT": {"REGEX": r"^(1[5-9]\d\d|20\d\d)$"}} | |
| YEAR_RANGE = {"TEXT": {"REGEX": r"^(1[5-9]\d\d|20\d\d)-(1[5-9]\d\d|20\d\d|\d\d)$"}} | |
| DECADE = {"TEXT": {"REGEX": r"^(1[5-9]\d0|20\d0)-an$"}} | |
| DAY_NUM = {"TEXT": {"REGEX": r"^([1-9]|[12]\d|3[01])$"}} | |
| DAY_RANGE = {"TEXT": {"REGEX": r"^([1-9]|[12]\d|3[01])-([1-9]|[12]\d|3[01])$"}} | |
| CLOCK = {"TEXT": {"REGEX": r"^([01]?\d|2[0-4])[.:][0-5]\d$"}} | |
| ORD_DIGIT = {"TEXT": {"REGEX": r"^(ke-\d+|Ke-\d+)$"}} | |
| def _num(op="+"): | |
| """A number: digits, digit range, or a run of number words.""" | |
| return [[DIGITS], [DIGIT_RANGE], [{"LOWER": {"IN": NUMBER_WORDS}, "OP": "+"}], | |
| [DIGITS, {"LOWER": {"IN": SCALE_WORDS}, "OP": "+"}]] | |
| def _patterns() -> list[tuple[str, list, int, int]]: | |
| """(label, token pattern, trim_left, trim_right). Trimmed tokens are context only.""" | |
| P: list[tuple[str, list, int, int]] = [] | |
| scale_opt = {"LOWER": {"IN": SCALE}, "OP": "?"} | |
| nums = _num() | |
| # MONEY | |
| for n in nums: | |
| P.append(("MONEY", [{"LOWER": {"IN": CURRENCY_BEFORE}}, {"ORTH": ".", "OP": "?"}] + n + [scale_opt], 0, 0)) | |
| P.append(("MONEY", [{"LOWER": "us"}, {"ORTH": "$"}] + n + [scale_opt], 0, 0)) | |
| P.append(("MONEY", n + [scale_opt, {"LOWER": {"IN": CURRENCY_AFTER}}], 0, 0)) | |
| P.append(("MONEY", n + [scale_opt, {"LOWER": {"IN": ["dolar", "dollar"]}}, {"LOWER": {"IN": ["as", "amerika", "singapura", "australia"]}}], 0, 0)) | |
| # PERCENT | |
| for n in nums: | |
| P.append(("PERCENT", n + [{"LOWER": {"IN": ["persen", "%", "prosen", "persennya"]}}], 0, 0)) | |
| P.append(("PERCENT", [{"LOWER": {"IN": ["setengah", "separuh"]}}, {"LOWER": "persen"}], 0, 0)) | |
| # QUANTITY | |
| for n in nums: | |
| P.append(("QUANTITY", n + [scale_opt, {"LOWER": {"IN": UNITS}}], 0, 0)) | |
| P.append(("QUANTITY", n + [{"LOWER": "derajat"}, {"LOWER": {"IN": ["celsius", "celcius", "fahrenheit", "c", "f"]}}], 0, 0)) | |
| P.append(("QUANTITY", n + [{"LOWER": "skala"}, {"LOWER": "richter"}], 0, 0)) | |
| # DATE | |
| months = {"LOWER": {"IN": MONTHS}} | |
| P += [ | |
| ("DATE", [{"LOWER": {"IN": DAYS}}, {"ORTH": ",", "OP": "?"}, DAY_NUM, months, YEAR], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": DAYS}}, {"ORTH": ",", "OP": "?"}, DAY_NUM, months], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": DAYS}}, {"ORTH": "("}, DAY_NUM, {"ORTH": "/"}, {"TEXT": {"REGEX": r"^\d{1,2}$"}}, | |
| {"ORTH": "/", "OP": "?"}, {"TEXT": {"REGEX": r"^\d{2,4}$"}, "OP": "?"}, {"ORTH": ")"}], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": DAYS}}, {"LOWER": {"IN": ["lalu", "depan", "ini", "kemarin", "pagi", "siang", "sore", "malam"]}, "OP": "?"}], 0, 0), | |
| ("DATE", [{"LOWER": "tanggal", "OP": "?"}, DAY_NUM, months, YEAR], 0, 0), | |
| ("DATE", [{"LOWER": "tanggal", "OP": "?"}, DAY_NUM, months], 0, 0), | |
| ("DATE", [{"LOWER": "tanggal", "OP": "?"}, DAY_RANGE, months, YEAR], 0, 0), | |
| ("DATE", [{"LOWER": "tanggal", "OP": "?"}, DAY_RANGE, months], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": ["bulan", "awal", "akhir", "pertengahan"]}, "OP": "?"}, months, YEAR], 0, 0), | |
| ("DATE", [{"LOWER": "bulan"}, months], 0, 0), | |
| # Bare month names, optionally relative; full names only (not "Mar", "Des") | |
| ("DATE", [{"LOWER": {"IN": ["awal", "akhir", "pertengahan"]}, "OP": "?"}, | |
| {"LOWER": {"IN": [m for m in MONTHS if len(m) > 3 and m != "sept"]}}, | |
| {"LOWER": {"IN": ["lalu", "depan", "ini", "mendatang", "silam"]}, "OP": "?"}], 0, 0), | |
| # Bracketed day/month as used in news datelines: (22/3), (9/2/2014) | |
| # (the brackets are matched but not part of the entity) | |
| ("DATE", [{"ORTH": "("}, DAY_NUM, {"ORTH": "/"}, {"TEXT": {"REGEX": r"^(1[0-2]|0?[1-9])$"}}, | |
| {"ORTH": "/", "OP": "?"}, {"TEXT": {"REGEX": r"^\d{2,4}$"}, "OP": "?"}, {"ORTH": ")"}], 1, 1), | |
| # Years before/after the common era | |
| ("DATE", [{"LOWER": "tahun", "OP": "?"}, {"TEXT": {"REGEX": r"^\d{1,4}(-\d{1,4})?$"}}, | |
| {"ORTH": "-", "OP": "?"}, {"TEXT": {"REGEX": r"^\d{1,4}$"}, "OP": "?"}, | |
| {"LOWER": {"IN": ["sm", "masehi", "m"]}}], 0, 0), | |
| ("DATE", [{"LOWER": "tahun", "OP": "?"}, {"TEXT": {"REGEX": r"^\d{1,4}$"}}, {"ORTH": "-", "OP": "?"}, | |
| {"TEXT": {"REGEX": r"^\d{1,4}$"}, "OP": "?"}, {"LOWER": "sebelum"}, {"LOWER": "masehi"}], 0, 0), | |
| ("DATE", [{"LOWER": "tahun", "OP": "?"}, YEAR], 0, 0), | |
| ("DATE", [{"LOWER": "tahun", "OP": "?"}, YEAR_RANGE], 0, 0), | |
| ("DATE", [{"LOWER": "tahun", "OP": "?"}, DECADE], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": ["awal", "akhir", "pertengahan"]}}, {"LOWER": "tahun"}, YEAR], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": ["abad"]}}, {"TEXT": {"REGEX": r"^(ke-\d+|[IVXL]+|\d+)$"}}], 0, 0), | |
| ("DATE", [DAY_NUM, {"ORTH": "/"}, {"TEXT": {"REGEX": r"^(1[0-2]|0?[1-9])$"}}, {"ORTH": "/"}, {"TEXT": {"REGEX": r"^\d{2,4}$"}}], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": ["kemarin", "besok", "lusa", "kemarin-kemarin"]}}], 0, 0), | |
| ("DATE", [{"LOWER": "hari"}, {"LOWER": {"IN": ["ini", "kemarin", "esok", "raya"]}}], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": ["tahun", "bulan", "pekan", "minggu", "abad", "dekade", "kuartal", "triwulan", "semester"]}}, | |
| {"LOWER": {"IN": ["lalu", "depan", "ini", "mendatang", "silam"]}}], 0, 0), | |
| ("DATE", [{"LOWER": "akhir"}, {"LOWER": "pekan"}], 0, 0), | |
| ("DATE", [{"LOWER": {"IN": ["awal", "akhir", "pertengahan"]}}, {"LOWER": {"IN": ["tahun", "bulan", "pekan"]}}, | |
| {"LOWER": {"IN": ["ini", "lalu", "depan"]}}], 0, 0), | |
| ] | |
| for n in nums: | |
| P.append(("DATE", n + [{"LOWER": {"IN": DATE_UNITS}}, {"LOWER": {"IN": ["lalu", "silam", "terakhir", "mendatang", "ke", "kemudian"]}, "OP": "?"}], 0, 0)) | |
| for h in HOLIDAYS: | |
| P.append(("DATE", [{"LOWER": w} for w in h], 0, 0)) | |
| P.append(("DATE", [{"LOWER": "bulan"}, {"LOWER": {"IN": ["ramadan", "ramadhan", "puasa", "suci"]}}], 0, 0)) | |
| # TIME | |
| P += [ | |
| ("TIME", [{"LOWER": {"IN": ["pukul", "jam"]}}, CLOCK, {"LOWER": {"IN": TIMEZONES}, "OP": "?"}], 0, 0), | |
| ("TIME", [{"LOWER": {"IN": ["pukul", "jam"]}}, {"TEXT": {"REGEX": r"^([01]?\d|2[0-4])$"}}, | |
| {"LOWER": {"IN": TIME_OF_DAY + ["dini"]}, "OP": "?"}, {"LOWER": {"IN": TIMEZONES}, "OP": "?"}], 0, 0), | |
| ("TIME", [CLOCK, {"LOWER": {"IN": TIMEZONES}}], 0, 0), | |
| ("TIME", [CLOCK, {"ORTH": "-"}, CLOCK, {"LOWER": {"IN": TIMEZONES}, "OP": "?"}], 0, 0), | |
| ("TIME", [{"LOWER": {"IN": TIME_OF_DAY}}, {"LOWER": {"IN": ["ini", "tadi", "nanti", "itu", "hari"]}}], 0, 0), | |
| ("TIME", [{"LOWER": {"IN": ["tadi", "nanti", "kemarin", "semalam", "besok"]}}, {"LOWER": {"IN": TIME_OF_DAY}}], 0, 0), | |
| ("TIME", [{"LOWER": "dini"}, {"LOWER": "hari"}], 0, 0), | |
| ("TIME", [{"LOWER": "semalam"}], 0, 0), | |
| ] | |
| for n in nums: | |
| P.append(("TIME", n + [{"LOWER": {"IN": TIME_UNITS}}], 0, 0)) | |
| # ORDINAL | |
| P += [ | |
| ("ORDINAL", [{"LOWER": {"IN": [w for w in ORDINAL_WORDS if not w.endswith("_")]}}], 0, 0), | |
| ("ORDINAL", [ORD_DIGIT], 0, 0), | |
| ("ORDINAL", [{"LOWER": "ke"}, {"ORTH": "-"}, {"TEXT": {"REGEX": r"^\d+$"}}], 0, 0), | |
| ("ORDINAL", [{"LOWER": {"IN": ["kedua", "ketiga", "keempat", "kelima"]}}, {"LOWER": {"IN": ["belas", "puluh"]}}], 0, 0), | |
| ] | |
| # CARDINAL (lowest priority; anything numeric left over) | |
| P += [ | |
| ("CARDINAL", [DIGITS, {"LOWER": {"IN": SCALE_WORDS}, "OP": "*"}], 0, 0), | |
| ("CARDINAL", [DIGIT_RANGE], 0, 0), | |
| ("CARDINAL", [{"LOWER": {"IN": NUMBER_WORDS}, "OP": "+"}], 0, 0), | |
| ("CARDINAL", [{"LOWER": {"IN": APPROX_WORDS}}], 0, 0), | |
| ] | |
| # LAW | |
| num_id = {"TEXT": {"REGEX": r"^\d+[A-Za-z]?(/\d+)*$"}} | |
| title_tok = {"IS_TITLE": True, "OP": "+"} | |
| for head in [[{"LOWER": {"IN": LAW_HEADS}}], [{"LOWER": "peraturan"}, {"LOWER": {"IN": ["pemerintah", "presiden", "daerah", "menteri", "bank", "mahkamah"]}}, {"IS_TITLE": True, "OP": "*"}]]: | |
| base = head + [{"IS_UPPER": True, "OP": "?"}, {"LOWER": {"IN": ["nomor", "no", "nomer"]}, "OP": "?"}, | |
| {"ORTH": ".", "OP": "?"}, num_id] | |
| P.append(("LAW", base, 0, 0)) | |
| P.append(("LAW", base + [{"LOWER": "tahun"}, YEAR], 0, 0)) | |
| P.append(("LAW", base + [{"ORTH": "/"}, YEAR], 0, 0)) | |
| P.append(("LAW", base + [{"LOWER": "tahun"}, YEAR, {"LOWER": "tentang"}, title_tok, | |
| {"LOWER": {"IN": ["dan", "atas", "di", "pada", "terhadap"]}, "OP": "?"}, {"IS_TITLE": True, "OP": "*"}], 0, 0)) | |
| P.append(("LAW", [{"LOWER": {"IN": ["uu", "undang-undang"]}}, {"IS_UPPER": True, "LENGTH": {">=": 2}}], 0, 0)) | |
| P.append(("LAW", [{"LOWER": {"IN": ["uu", "undang-undang"]}}, {"IS_TITLE": True, "OP": "+"}], 0, 0)) | |
| for f in LAW_FIXED: | |
| P.append(("LAW", [{"LOWER": w} for w in f], 0, 0)) | |
| # LANGUAGE: bahasa + Name (the word "bahasa" is excluded, guideline rule 5) | |
| P.append(("LANGUAGE", [{"LOWER": {"IN": ["bahasa", "berbahasa"]}}, {"IS_TITLE": True, "LOWER": {"NOT_IN": ["yang", "daerah", "asing", "resmi", "ibu", "nasional", "isyarat"]}}, | |
| {"IS_TITLE": True, "OP": "?"}], 1, 0)) | |
| # NORP: head + Name, or a known religious/ethnic word | |
| # the head must be lowercase: a capitalised head is usually inside an organisation name ("Rakyat Indonesia") | |
| P.append(("NORP", [{"LOWER": {"IN": NORP_HEADS}, "IS_LOWER": True}, | |
| {"IS_TITLE": True, "LOWER": {"NOT_IN": PLACE_STARTS}}, {"IS_TITLE": True, "OP": "?"}], 1, 0)) | |
| P.append(("NORP", [{"LOWER": {"IN": NORP_HEADS}, "IS_LOWER": True}, | |
| {"IS_UPPER": True, "LENGTH": {">=": 2}, "LOWER": {"NOT_IN": PLACE_STARTS}}], 1, 0)) | |
| # ... unless it is capitalised only because it starts the sentence ("Suku Batak ...") | |
| P.append(("NORP", [{"LOWER": {"IN": NORP_HEADS}, "IS_SENT_START": True}, | |
| {"IS_TITLE": True, "LOWER": {"NOT_IN": PLACE_STARTS}}, {"IS_TITLE": True, "OP": "?"}], 1, 0)) | |
| P.append(("NORP", [{"ORTH": {"IN": NORP_WORDS}}], 0, 0)) | |
| # EVENT: capitalised event head + name/year, or election + (region) + year | |
| name_tok = {"IS_TITLE": True} | |
| tail = [{"TEXT": {"REGEX": r"^([A-Z][\w'-]*|\d{4}|[IVX]+|ke-\d+)$"}, "OP": "+"}] | |
| P.append(("EVENT", [{"ORTH": {"IN": EVENT_HEADS}}] + tail, 0, 0)) | |
| P.append(("EVENT", [{"ORTH": {"IN": ["Asian", "SEA", "Sea", "Commonwealth", "Olympic", "Pan"]}}, | |
| {"ORTH": "Games"}, {"TEXT": {"REGEX": r"^\d{4}$"}, "OP": "?"}], 0, 0)) | |
| P.append(("EVENT", [{"LOWER": {"IN": ELECTIONS}}, {"TEXT": {"REGEX": r"^[A-Z]"}, "OP": "*"}, | |
| {"TEXT": {"REGEX": r"^(19|20)\d\d$"}}], 0, 0)) | |
| # WORK_OF_ART: cue word + title; without quotes the title needs >= 2 capitalised words | |
| title = [name_tok, {"LOWER": {"IN": TITLE_SMALL}, "OP": "?"}, name_tok, {"IS_TITLE": True, "OP": "*"}] | |
| cues = {"LOWER": {"IN": [c for c in WOA_CUES if not c.endswith("_")]}} | |
| P.append(("WORK_OF_ART", [cues] + title, 1, 0)) | |
| for q_open, q_close in [('"', '"'), ("“", "”"), ("'", "'")]: | |
| P.append(("WORK_OF_ART", [cues, {"ORTH": q_open}, {"ORTH": {"NOT_IN": [q_close]}, "OP": "+"}, | |
| {"ORTH": q_close}], 2, 1)) | |
| return P | |
| class RuleNER: | |
| def __init__(self, nlp: Language, name: str = "id_rule_ner", overwrite: bool = False, conventions: str = "v0.1"): | |
| if conventions not in ("v0.1", "v0.2"): | |
| raise ValueError(f"id_rule_ner: unknown conventions {conventions!r}") | |
| self.name = name | |
| self.overwrite = overwrite | |
| self.conventions = conventions | |
| self.matcher = Matcher(nlp.vocab, validate=True) | |
| self.meta: dict[str, tuple[str, int, int]] = {} | |
| for i, (label, pat, tl, tr) in enumerate(_patterns()): | |
| key = f"{label}_{i}" | |
| self.meta[key] = (label, tl, tr) | |
| self.matcher.add(key, [pat]) | |
| def find(self, doc: Doc) -> list[Span]: | |
| cands = [] | |
| for match_id, start, end in self.matcher(doc): | |
| label, tl, tr = self.meta[doc.vocab.strings[match_id]] | |
| s, e = start + tl, end - tr | |
| if e > s: | |
| cands.append(Span(doc, s, e, label=label)) | |
| # Longest first, then label priority; filter_spans keeps the first of overlapping spans | |
| cands.sort(key=lambda sp: (-(sp.end - sp.start), LABEL_PRIORITY.index(sp.label_), sp.start)) | |
| spans = filter_spans(cands) | |
| if self.conventions == "v0.2": | |
| spans = self._v02(doc, spans) | |
| return spans | |
| def _v02(self, doc: Doc, spans: list[Span]) -> list[Span]: | |
| """Guideline v0.2 span decisions D1, D14 and D15 (see the module docstring).""" | |
| spans = sorted(spans, key=lambda sp: sp.start) | |
| taken_end = 0 | |
| out = [] | |
| for sp in spans: | |
| start, end, label = sp.start, sp.end, sp.label_ | |
| if label in APPROX_LABELS: # D1: approximator before the number | |
| for pre in sorted(APPROX_PREFIX, key=len, reverse=True): | |
| k = len(pre) | |
| if start - k >= taken_end and [t.lower_ for t in doc[start - k:start]] == pre: | |
| start -= k | |
| break | |
| if label == "DATE" and end < len(doc) and doc[end].lower_ in DATE_TAIL: # D14: "... 2007 lalu" | |
| end += 1 | |
| if label == "DATE" and doc[start].lower_ in DAYS and end - start == 2 \ | |
| and doc[start + 1].lower_ in TIME_OF_DAY: # D15: "Selasa pagi" | |
| label = "TIME" | |
| out.append(Span(doc, start, end, label=label)) | |
| taken_end = end | |
| merged = [] # D14: "4 Desember hingga 11 Januari 2010" | |
| for sp in out: | |
| if merged and sp.label_ == merged[-1].label_ == "DATE" and sp.start == merged[-1].end + 1 \ | |
| and doc[merged[-1].end].lower_ in RANGE_JOIN: | |
| merged[-1] = Span(doc, merged[-1].start, sp.end, label="DATE") | |
| else: | |
| merged.append(sp) | |
| return filter_spans(merged) | |
| def __call__(self, doc: Doc) -> Doc: | |
| found = self.find(doc) | |
| existing = [] if self.overwrite else list(doc.ents) | |
| # A longer rule span may replace model entities it fully covers, but only | |
| # rule-type ones (UU No. + 2 Tahun + 2012 -> one LAW); names are never overridden. | |
| replaced = set() | |
| for s in found: | |
| inside = [e for e in existing if e.start < s.end and s.start < e.end] | |
| if inside and all(s.start <= e.start and e.end <= s.end and e.label_ in RULE_LABELS for e in inside) \ | |
| and (s.end - s.start) > max(e.end - e.start for e in inside): | |
| replaced.update(id(e) for e in inside) | |
| existing = [e for e in existing if id(e) not in replaced] | |
| taken = set() | |
| for e in existing: | |
| taken.update(range(e.start, e.end)) | |
| new = [s for s in found if not taken.intersection(range(s.start, s.end))] | |
| doc.ents = filter_spans(existing + new) | |
| return doc | |
| def make_rule_ner(nlp: Language, name: str, overwrite: bool, conventions: str): | |
| return RuleNER(nlp, name, overwrite, conventions) | |