Download lingologos_thinkingpython/intent.py from tailot/lingologos-thinkingpython: direct link, hf CLI and curl.
- Browser
- Download file 4.68 kB
-
https://huggingface.co/datasets/tailot/lingologos-thinkingpython/resolve/main/lingologos_thinkingpython/intent.py
- Command line
-
hf download hf://datasets/tailot/lingologos-thinkingpython/lingologos_thinkingpython/intent.py
-
curl -L -o intent.py https://huggingface.co/datasets/tailot/lingologos-thinkingpython/resolve/main/lingologos_thinkingpython/intent.py
4.68 kB
| """Intent and intermediate representation. | |
| The intent node is the only non deterministic node: it maps a surface request in one of | |
| the six varieties onto a frame. Everything downstream is language free: no other node | |
| reads the utterance, only the frame and the anchor. | |
| """ | |
| import re | |
| from typing import Any, Dict, List, Optional, Tuple | |
| from . import lexicon | |
| IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]{2,}") | |
| STOPWORDS = {"this", "that", "with", "into", "from", "before", "after", "please", | |
| "could", "would", "should", "not", "and", "for", "the", "are"} | |
| #: Code tokens a developer types in any variety: they survive code switching, so a | |
| #: frame may be named by them alone inside Arabic, Hindi or Chinese prose. | |
| TECH_TOKENS = {"assert", "assertion", "comprehension", "default", "f", "guard", | |
| "import", "isinstance", "list", "loop", "nesting", "number", "string"} | |
| IR_KEYS = ("frame", "anchor", "lang", "score", "candidates") | |
| def make_ir(frame: str, anchor: Optional[str], lang: str, score: float, | |
| candidates: List[Tuple[str, float]]) -> Dict[str, Any]: | |
| return {"frame": frame, "anchor": anchor, "lang": lexicon.normalize(lang), | |
| "score": round(float(score), 4), | |
| "candidates": [(f, round(s, 4)) for f, s in candidates]} | |
| def is_language_free(ir: Dict[str, Any]) -> bool: | |
| """True when the plan carries no trace of the surface form. | |
| Checked in tests/test_language_free_plan.py: no utterance text, no non ASCII token, | |
| no variety name anywhere in the structure that reaches executor and gates. | |
| """ | |
| try: | |
| str(ir).encode("ascii") | |
| except UnicodeEncodeError: | |
| return False | |
| return set(ir.keys()) <= set(IR_KEYS) | |
| def anchors_in(text: str) -> List[str]: | |
| out: List[str] = [] | |
| for word in IDENT.findall(str(text or "")): | |
| if word.lower() in STOPWORDS: | |
| continue | |
| if word not in out: | |
| out.append(word) | |
| return out | |
| def rank(text: str, lang: str, frames: Dict[str, List[str]]) -> List[Tuple[str, float]]: | |
| """Score every frame against the request, using the vocabulary of its variety. | |
| Two signals are combined. A phrase that appears whole is a direct hit. Otherwise the | |
| content words of the phrase are counted: coverage over them, with a boost when the | |
| matched words are code tokens, because those survive code switching. | |
| """ | |
| data = lexicon.load(lang) | |
| folded = lexicon.fold(text, lang) | |
| words = set(folded.split()) | |
| scored: List[Tuple[str, float]] = [] | |
| for frame, phrases in frames.items(): | |
| best = 0.0 | |
| for phrase in phrases: | |
| needle = lexicon.fold(phrase, lang) | |
| if not needle: | |
| continue | |
| if needle in folded: | |
| weight = len(needle.split()) / max(1, len(folded.split())) | |
| best = max(best, 0.55 + 0.45 * min(1.0, weight * 2)) | |
| continue | |
| tokens = [t for t in needle.split() if len(t) > 1 and t not in STOPWORDS] | |
| if not tokens: | |
| continue | |
| hits = [t for t in tokens if t in words or t in folded] | |
| if not hits: | |
| continue | |
| base = 0.45 * len(hits) / len(tokens) | |
| tech = sum(1 for t in hits if t in TECH_TOKENS) | |
| partial = min(0.60, base + 0.10 * tech + 0.05 * (len(hits) - 1)) | |
| best = max(best, partial) | |
| if best > 0.0: | |
| scored.append((frame, best)) | |
| scored.sort(key=lambda pair: (-pair[1], pair[0])) | |
| return scored | |
| def route(text: str, lang: str, frames: Dict[str, List[str]], | |
| known_symbols: Optional[List[str]] = None, | |
| clarify_margin: float = 0.15, min_score: float = 0.45) -> Dict[str, Any]: | |
| """Return an IR, or an IR with frame None plus a reason.""" | |
| lang = lexicon.normalize(lang) | |
| scored = rank(text, lang, frames) | |
| symbols = anchors_in(text) | |
| anchor = None | |
| if known_symbols: | |
| lowered = {s.lower(): s for s in known_symbols} | |
| for word in symbols: | |
| if word.lower() in lowered: | |
| anchor = lowered[word.lower()] | |
| break | |
| if anchor is None and symbols: | |
| anchor = symbols[0] | |
| if not scored or scored[0][1] < min_score: | |
| ir = make_ir("", anchor, lang, scored[0][1] if scored else 0.0, scored[:3]) | |
| ir["reason"] = "NOT_UNDERSTOOD" | |
| return ir | |
| if len(scored) > 1 and (scored[0][1] - scored[1][1]) < clarify_margin: | |
| ir = make_ir(scored[0][0], anchor, lang, scored[0][1], scored[:3]) | |
| ir["reason"] = "AMBIGUOUS_TARGET" | |
| return ir | |
| return make_ir(scored[0][0], anchor, lang, scored[0][1], scored[:3]) | |