shl-recommender / app /utils /text_utils.py
maddy1007's picture
Initial commit: SHL Assessment Recommender
122f5b9
Raw History Blame Contribute Delete
2.69 kB
"""
Text utilities: cleaning, normalisation, and tokenisation helpers
shared across the catalog ingestion and retrieval layers.
"""
from __future__ import annotations
import re
import unicodedata
from typing import List
_STOP_WORDS = frozenset({
"the", "a", "an", "for", "to", "in", "of", "and", "or", "is", "it",
"at", "by", "on", "we", "you", "i", "that", "this", "with", "our",
"are", "be", "as", "from", "but", "not", "also", "can", "will",
"they", "their", "which", "have", "has", "had", "been", "about",
})
def normalize_text(text: str) -> str:
"""
Normalize unicode, collapse whitespace, strip leading/trailing.
Handles HTML entity remnants and broken encodings.
"""
# Normalize unicode composition
text = unicodedata.normalize("NFKD", text)
# Remove non-printable control chars (except newline/tab)
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
# Collapse runs of whitespace (preserve single spaces)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def tokenize(text: str, remove_stop_words: bool = True) -> List[str]:
"""
Lowercase, unicode-normalize, and extract word tokens.
Optionally remove stop words.
"""
text = unicodedata.normalize("NFKD", text.lower())
tokens = re.findall(r"\b[a-z][a-z0-9+#.]*\b", text)
if remove_stop_words:
tokens = [t for t in tokens if t not in _STOP_WORDS and len(t) > 1]
return tokens
def slug(text: str) -> str:
"""
Convert a display name to a URL-friendly slug id.
Example: "Verify Numerical Reasoning" → "verify-numerical-reasoning"
"""
text = unicodedata.normalize("NFKD", text.lower())
text = re.sub(r"[^a-z0-9]+", "-", text)
return text.strip("-")
def truncate(text: str, max_chars: int = 200, suffix: str = "…") -> str:
"""Truncate text at a word boundary near `max_chars`."""
if len(text) <= max_chars:
return text
cut = text[:max_chars].rsplit(" ", 1)[0]
return cut + suffix
def extract_keywords_from_text(text: str, top_n: int = 15) -> List[str]:
"""
Extract the most frequent meaningful tokens from free text.
Used to auto-generate keyword lists during catalog ingestion.
"""
tokens = tokenize(text, remove_stop_words=True)
# Filter very short tokens and numbers-only
tokens = [t for t in tokens if len(t) > 2 and not t.isdigit()]
# Count frequency
freq: dict[str, int] = {}
for t in tokens:
freq[t] = freq.get(t, 0) + 1
# Return top-n by frequency
sorted_tokens = sorted(freq, key=lambda k: freq[k], reverse=True)
return sorted_tokens[:top_n]