Spaces:
Running
Running
Download src/ner/postprocess.py from ArielJoe/Prompt-Builder: direct link, hf CLI and curl.
- Browser
- Download file 5.72 kB
-
https://huggingface.co/spaces/ArielJoe/Prompt-Builder/resolve/main/src/ner/postprocess.py
- Command line
-
hf download hf://spaces/ArielJoe/Prompt-Builder/src/ner/postprocess.py
-
curl -L -o postprocess.py https://huggingface.co/spaces/ArielJoe/Prompt-Builder/resolve/main/src/ner/postprocess.py
5.72 kB
| """Chunking, context filtering, span trimming, and overlap merging for NER entities.""" | |
| from __future__ import annotations | |
| import re | |
| from core.lexicons import load_word_set | |
| from core.text_utils import spans_overlap | |
| from ner.rules import COMMON_NON_ENTITIES, NEREntity | |
| _CHUNK_MAX_CHARS = 1200 | |
| _VOWELS = frozenset("aeiouAEIOU") | |
| _TOKEN_RE = re.compile(r"[A-Za-zÀ-ÿ]+") | |
| _LOCATION_LEFT_CUES = frozenset(load_word_set("ner", "location_left_cues.txt")) | |
| _LOCATION_RIGHT_CUES = frozenset(load_word_set("ner", "location_right_cues.txt")) | |
| _ETHNIC_CUE_WORDS = frozenset( | |
| load_word_set("ner", "ethnic_cue_words.txt") or {"suku", "ras", "etnis", "bangsa"} | |
| ) | |
| _TRAILING_CONTEXT_WORDS = frozenset({ | |
| "kelas", "bab", "hal", "halaman", "nomor", "no", "tentang", "tahun", | |
| }) | |
| _NAME_CONNECTORS = frozenset({ | |
| "of", "de", "van", "der", "den", "bin", "binti", "al", "da", "dos", | |
| "du", "la", "le", "el", "ter", | |
| }) | |
| def _chunk_text(text: str) -> list[tuple[str, int]]: | |
| """Split long text on nearest whitespace boundaries with original character offsets.""" | |
| if len(text) <= _CHUNK_MAX_CHARS: | |
| return [(text, 0)] | |
| chunks: list[tuple[str, int]] = [] | |
| pos = 0 | |
| total = len(text) | |
| while pos < total: | |
| end = min(pos + _CHUNK_MAX_CHARS, total) | |
| if end < total: | |
| space = text.rfind(" ", pos, end) | |
| if space > pos: | |
| end = space | |
| chunks.append((text[pos:end], pos)) | |
| pos = end + 1 if end < total and text[end] == " " else end | |
| return chunks | |
| def _is_plausible_entity(word: str) -> bool: | |
| """Filter out obvious gibberish spans while keeping valid acronyms and multi-word names.""" | |
| if not word or not word.strip(): | |
| return False | |
| letters = [c for c in word if c.isalpha()] | |
| if letters and all(c.isupper() for c in letters) and len(word) <= 10: | |
| return True | |
| if " " not in word and len(word) > 25: | |
| return False | |
| max_cons = cur = 0 | |
| for ch in word: | |
| if ch.isalpha(): | |
| cur = 0 if ch in _VOWELS else cur + 1 | |
| max_cons = max(max_cons, cur) | |
| else: | |
| cur = 0 | |
| if max_cons >= 5: | |
| return False | |
| has_vowel = any(ch in _VOWELS for ch in word if ch.isalpha()) | |
| return not (not has_vowel and len(letters) > 4) | |
| def _trim_entity_context_words(entity: NEREntity, text: str) -> NEREntity: | |
| """Trim trailing context nouns and split spans on lowercase non-connector words.""" | |
| parts = entity.word.split() | |
| if len(parts) <= 1: | |
| return entity | |
| for i, part in enumerate(parts): | |
| if i > 0 and part.lower() in _TRAILING_CONTEXT_WORDS: | |
| parts = parts[:i] | |
| break | |
| def _is_cap(tok: str) -> bool: | |
| return (not tok[:1].isalpha()) or tok[:1].isupper() | |
| runs: list[list[str]] = [] | |
| cur: list[str] = [] | |
| for part in parts: | |
| if _is_cap(part) or (part.lower() in _NAME_CONNECTORS and cur): | |
| cur.append(part) | |
| else: | |
| if cur: | |
| runs.append(cur) | |
| cur = [] | |
| if cur: | |
| runs.append(cur) | |
| if not runs: | |
| return entity | |
| best = max(runs, key=len) | |
| while best and best[0].lower() in _NAME_CONNECTORS: | |
| best = best[1:] | |
| while best and best[-1].lower() in _NAME_CONNECTORS: | |
| best = best[:-1] | |
| word = " ".join(best).strip() | |
| if not word or word == entity.word: | |
| return entity | |
| idx = text.find(word, entity.start) | |
| if idx == -1 or idx >= entity.end: | |
| return entity | |
| return NEREntity( | |
| word=word, | |
| label=entity.label, | |
| score=entity.score, | |
| start=idx, | |
| end=idx + len(word), | |
| source=entity.source, | |
| ) | |
| def _context_tokens(text: str, start: int, end: int) -> tuple[str | None, str | None]: | |
| """Return lowercased tokens immediately preceding and following a span.""" | |
| prev = None | |
| for match in _TOKEN_RE.finditer(text[:start]): | |
| prev = match.group().lower() | |
| nxt = None | |
| next_match = _TOKEN_RE.search(text[end:]) | |
| if next_match: | |
| nxt = next_match.group().lower() | |
| return prev, nxt | |
| def _is_ethnic_label_context(entity: NEREntity, text: str) -> bool: | |
| """Return True when a single-word entity immediately follows an ethnicity cue word.""" | |
| if len(_TOKEN_RE.findall(entity.word)) != 1: | |
| return False | |
| prev, _ = _context_tokens(text, entity.start, entity.end) | |
| return prev in _ETHNIC_CUE_WORDS | |
| def _has_valid_entity_context(entity: NEREntity, text: str, language: str) -> bool: | |
| """Prevent common Indonesian stopwords from being flagged as entities unless cued as locations.""" | |
| norm = entity.word.strip().lower() | |
| is_single_token = len(_TOKEN_RE.findall(entity.word)) == 1 | |
| if norm not in COMMON_NON_ENTITIES: | |
| return True | |
| if entity.label != "LOCATION" or not is_single_token: | |
| return False | |
| prev, nxt = _context_tokens(text, entity.start, entity.end) | |
| has_location_cue = (prev in _LOCATION_LEFT_CUES) or (nxt in _LOCATION_RIGHT_CUES) | |
| return entity.word[:1].isupper() and has_location_cue | |
| def _merge_entities(ml: list[NEREntity], rules: list[NEREntity]) -> list[NEREntity]: | |
| """Merge rule-based and ML entities, prioritizing more specific rule matches on overlap.""" | |
| accepted: list[NEREntity] = [] | |
| for entity in sorted(rules, key=lambda e: (e.start, -(e.end - e.start), -e.score)): | |
| if not any(spans_overlap(entity.start, entity.end, k.start, k.end) for k in accepted): | |
| accepted.append(entity) | |
| for entity in sorted(ml, key=lambda e: -e.score): | |
| if not any(spans_overlap(entity.start, entity.end, k.start, k.end) for k in accepted): | |
| accepted.append(entity) | |
| return accepted | |