Spaces:
Running on Zero
Running on Zero
Download src/text_utils.py from leeshal/EvidenceGuard-AI: direct link, hf CLI and curl.
- Browser
- Download file 5.48 kB
-
https://huggingface.co/spaces/leeshal/EvidenceGuard-AI/resolve/main/src/text_utils.py
- Command line
-
hf download hf://spaces/leeshal/EvidenceGuard-AI/src/text_utils.py
-
curl -L -o text_utils.py https://huggingface.co/spaces/leeshal/EvidenceGuard-AI/resolve/main/src/text_utils.py
5.48 kB
| """Shared text helpers: normalisation, tokenisation, sentence splitting, fact extraction.""" | |
| from __future__ import annotations | |
| import re | |
| import unicodedata | |
| STOPWORDS = set(""" | |
| a an the and or of to in on for by with at from as is are was were be been being this that these those | |
| it its into than then there their they them what which who whom whose when where why how can could | |
| may might must shall should will would do does did done have has had having i me my we our you your | |
| he she his her not no yes if any all each every per about after before up down over under again | |
| further once only own same so too very s t just also both either neither such other some more most | |
| given since as under according am i'm my is there does do much many long within how during while | |
| """.split()) | |
| # Words so common in this domain that they say little about *what* is being asked. | |
| DOMAIN_STOPWORDS = set(""" | |
| student students university avu aranya valley course courses semester policy rule rules document | |
| documents regulation regulations required require requires requirement allowed allow need needed | |
| """.split()) | |
| _SENT_SPLIT = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9(])") | |
| _TOKEN = re.compile(r"[a-z0-9]+(?:[.:'+-][a-z0-9]+)*%?|[a-z]\+") | |
| def normalize(text: str) -> str: | |
| """Lower-case, unify unicode, drop thousands separators, collapse whitespace.""" | |
| text = unicodedata.normalize("NFKC", text or "") | |
| text = text.replace("–", "-").replace("—", "-").replace("’", "'") | |
| text = re.sub(r"(?<=\d),(?=\d)", "", text) # 6,00,000 -> 600000 | |
| text = re.sub(r"\s+", " ", text) | |
| return text.lower().strip() | |
| def tokenize(text: str) -> list[str]: | |
| return _TOKEN.findall(normalize(text)) | |
| def content_tokens(text: str, drop_domain: bool = False) -> list[str]: | |
| toks = [t for t in tokenize(text) if t not in STOPWORDS and len(t) > 1 or t[:1].isdigit()] | |
| if drop_domain: | |
| toks = [t for t in toks if t not in DOMAIN_STOPWORDS] | |
| return toks | |
| def split_sentences(text: str) -> list[str]: | |
| text = re.sub(r"\s+", " ", text or "").strip() | |
| if not text: | |
| return [] | |
| return [s.strip() for s in _SENT_SPLIT.split(text) if s.strip()] | |
| # ---------------------------------------------------------------- fact signatures | |
| _NUM_UNIT = re.compile( | |
| r"(?:inr\s*)?(\d+(?:\.\d+)?)\s*(%|percent|working days|calendar days|days|day|weeks|months|" | |
| r"books|book|marks|credits|minutes|hours|contact hours|mb|gb|members|semesters|years)?", | |
| ) | |
| _DATE = re.compile(r"\b(\d{1,2})\s+(january|february|march|april|may|june|july|august|september|october|" | |
| r"november|december)\s+(\d{4})\b") | |
| _TIME = re.compile(r"\b(\d{1,2}:\d{2})\s*(am|pm)\b") | |
| _WORD_NUM = {"one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6"} | |
| def extract_facts(text: str) -> set[str]: | |
| """Return a set of normalised value strings (numbers with units, dates, times, money).""" | |
| t = normalize(text) | |
| facts: set[str] = set() | |
| for d, m, y in _DATE.findall(t): | |
| facts.add(f"date:{int(d)} {m} {y}") | |
| t_wo_dates = _DATE.sub(" ", t) | |
| for hm, ap in _TIME.findall(t_wo_dates): | |
| facts.add(f"time:{hm}{ap}") | |
| t_wo = _TIME.sub(" ", t_wo_dates) | |
| for m in re.finditer(r"inr\s*(\d+)", t_wo): | |
| facts.add(f"inr:{m.group(1)}") | |
| t_wo = re.sub(r"inr\s*\d+", " ", t_wo) | |
| for w, n in _WORD_NUM.items(): | |
| t_wo = re.sub(rf"\b{w}\b(?=\s+(semesters|years|make-up|external|members|books))", n, t_wo) | |
| for num, unit in _NUM_UNIT.findall(t_wo): | |
| if unit: | |
| unit = {"percent": "%", "day": "days", "book": "books", "calendar days": "days"}.get(unit, unit) | |
| facts.add(f"{unit}:{float(num):g}") | |
| return facts | |
| def fact_occurrences(text: str, before: int = 75, after: int = 45) -> list[tuple[str, str, str]]: | |
| """Each value mention as (unit, value, surrounding context text without the value itself).""" | |
| t = normalize(text) | |
| occ, taken = [], [] | |
| def free(a, b): | |
| return all(b <= x or a >= y for x, y in taken) | |
| pats = [ | |
| (_DATE, lambda m: ("date", f"{int(m.group(1))} {m.group(2)} {m.group(3)}")), | |
| (_TIME, lambda m: ("time", f"{m.group(1)}{m.group(2)}")), | |
| (re.compile(r"inr\s*(\d+)"), lambda m: ("inr", m.group(1))), | |
| (re.compile(r"(\d+(?:\.\d+)?)\s*(%|percent|working days|calendar days|days|weeks|months|books|marks|" | |
| r"credits|minutes|contact hours|hours|mb|gb|members|semesters|years)\b|(\d+(?:\.\d+)?)%"), | |
| lambda m: ("%" if m.group(3) else {"percent": "%", "calendar days": "days"}.get(m.group(2), m.group(2)), | |
| f"{float(m.group(1) or m.group(3)):g}")), | |
| ] | |
| for pat, fn in pats: | |
| for m in pat.finditer(t): | |
| a, b = m.span() | |
| if not free(a, b): | |
| continue | |
| taken.append((a, b)) | |
| unit, val = fn(m) | |
| ctx = t[max(0, a - before):a] + " " + t[b:b + after] | |
| occ.append((unit, val, ctx)) | |
| return occ | |
| def fact_values(text: str) -> set[str]: | |
| """Just the numeric parts (used for loose support checks).""" | |
| out = set() | |
| for f in extract_facts(text): | |
| out.add(f.split(":", 1)[1]) | |
| return out | |
| def keyword_present(answer: str, keyword: str) -> bool: | |
| """keyword may contain alternatives separated by '|'.""" | |
| a = " " + normalize(answer) + " " | |
| return any(normalize(k) in a if not k.endswith(" ") else normalize(k) + " " in a | |
| for k in keyword.split("|")) | |