Spaces:
Sleeping
Sleeping
Download src/context/coreference_rewriter.py from Darshan03/nonllm-chatbot-main: direct link, hf CLI and curl.
- Browser
- Download file 6.92 kB
-
https://huggingface.co/spaces/Darshan03/nonllm-chatbot-main/resolve/main/src/context/coreference_rewriter.py
- Command line
-
hf download hf://spaces/Darshan03/nonllm-chatbot-main/src/context/coreference_rewriter.py
-
curl -L -o coreference_rewriter.py https://huggingface.co/spaces/Darshan03/nonllm-chatbot-main/resolve/main/src/context/coreference_rewriter.py
6.92 kB
| """ | |
| Coreference & Query Rewriter | |
| ---------------------------- | |
| Replaces anaphoric pronouns and elliptical fragments with concrete antecedent topics | |
| and domain slots, preventing context poisoning and naive concatenation. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import logging | |
| from typing import Optional, Tuple | |
| logger = logging.getLogger(__name__) | |
| # Pronoun patterns | |
| ANAPHORIC_PRONOUNS = {"it", "its", "they", "them", "this", "that", "these", "those"} | |
| # Elliptical prefixes and keywords aligned with extra.csv and pl_extra.csv training data | |
| ELLIPTICAL_PREFIXES = ( | |
| "what about", | |
| "how about", | |
| "and ", | |
| "also ", | |
| "what is the", | |
| "what are the", | |
| "time complexity", | |
| "space complexity", | |
| "auxiliary space", | |
| "amortized complexity", | |
| "amortized time complexity", | |
| "worst case", | |
| "best case", | |
| "average case", | |
| "give code", | |
| "show code", | |
| "code example", | |
| "give example", | |
| "show example", | |
| "pseudo code", | |
| "pseudocode", | |
| "complexity", | |
| "edge cases", | |
| "edge case", | |
| "diamond problem", | |
| "method overriding", | |
| "method overloading", | |
| "garbage collection", | |
| "memory leak", | |
| "memory leaks", | |
| "tle", | |
| "mle", | |
| "fast io", | |
| "types of", | |
| "what are its types", | |
| "real world example", | |
| "practical example", | |
| "difference from", | |
| "difference between", | |
| ) | |
| EXPLICIT_ELLIPTICAL_EXACT = { | |
| "complexity?", | |
| "complexity", | |
| "time complexity?", | |
| "time complexity", | |
| "space complexity?", | |
| "space complexity", | |
| "auxiliary space?", | |
| "auxiliary space", | |
| "amortized?", | |
| "amortized", | |
| "amortized complexity?", | |
| "amortized complexity", | |
| "worst case?", | |
| "worst case", | |
| "best case?", | |
| "best case", | |
| "average case?", | |
| "average case", | |
| "edge cases?", | |
| "edge cases", | |
| "diamond problem?", | |
| "diamond problem", | |
| "tle?", | |
| "tle", | |
| "mle?", | |
| "mle", | |
| "memory leak?", | |
| "memory leak", | |
| "garbage collection?", | |
| "garbage collection", | |
| "types?", | |
| "types", | |
| "example?", | |
| "example", | |
| "code?", | |
| "code", | |
| "why?", | |
| "why", | |
| "how?", | |
| "how", | |
| } | |
| class CoreferenceRewriter: | |
| """Intelligently rewrites multi-turn queries using coreference resolution and slot memory.""" | |
| def is_anaphoric(text: str) -> bool: | |
| """Check if query contains anaphoric pronouns referencing prior context.""" | |
| words = set(re.findall(r"\b\w+\b", text.lower())) | |
| return bool(words.intersection(ANAPHORIC_PRONOUNS)) | |
| def is_elliptical(text: str) -> bool: | |
| """Check if query is an elliptical follow-up fragment.""" | |
| lower = text.lower().strip() | |
| return lower.startswith(ELLIPTICAL_PREFIXES) or lower in EXPLICIT_ELLIPTICAL_EXACT | |
| def rewrite( | |
| user_text: str, | |
| active_topic: Optional[str] = None, | |
| slots: Optional[dict[str, str]] = None, | |
| ) -> Tuple[str, bool]: | |
| """ | |
| Rewrites the query using the active topic and slot memory. | |
| Returns: | |
| (rewritten_query, was_modified) | |
| """ | |
| if not active_topic: | |
| return user_text, False | |
| clean_topic = active_topic.replace("_", " ").strip() | |
| lower = user_text.lower().strip() | |
| words = set(re.findall(r"\b\w+\b", lower)) | |
| # Check if query already contains the active topic (no rewriting needed) | |
| topic_words = set(clean_topic.lower().split()) | |
| if topic_words and topic_words.issubset(words): | |
| return user_text, False | |
| is_ana = CoreferenceRewriter.is_anaphoric(user_text) | |
| is_elli = CoreferenceRewriter.is_elliptical(user_text) | |
| # Guard against context poisoning across all domain entities (Algorithms, DS, OOP, PL) | |
| # Note: If query is an elliptical follow-up (e.g. "what about ..."), the user is exploring an | |
| # aspect, subtopic, or edge case of the current topic. Only non-elliptical queries trigger the hijack guard. | |
| from .slot_memory import ALL_DOMAIN_ENTITIES | |
| explicit_new_subject = False | |
| if not is_elli: | |
| for entity_name in sorted(ALL_DOMAIN_ENTITIES.keys(), key=lambda x: len(x), reverse=True): | |
| if re.search(r"\b" + re.escape(entity_name) + r"\b", lower) and entity_name not in clean_topic.lower(): | |
| explicit_new_subject = True | |
| break | |
| if explicit_new_subject: | |
| logger.debug(f"Explicit new subject detected in '{user_text}'. Guarding against context poisoning.") | |
| return user_text, False | |
| if not (is_ana or is_elli): | |
| return user_text, False | |
| rewritten = user_text | |
| # 1. Possessive pronoun replacement: "its time complexity" -> "binary search time complexity" | |
| rewritten = re.sub( | |
| r"\b(its|their)\s+([a-zA-Z\s]+)", | |
| lambda m: f"{clean_topic} {m.group(2)}", | |
| rewritten, | |
| flags=re.IGNORECASE, | |
| ) | |
| # 2. General pronoun replacement: "how does it work" -> "how does binary search work" | |
| rewritten = re.sub( | |
| r"\b(it|they|this|that|these|those)\b", | |
| clean_topic, | |
| rewritten, | |
| flags=re.IGNORECASE, | |
| ) | |
| # 3. Elliptical expansion: "what about space complexity?" -> "what is the space complexity of binary search?" | |
| if is_elli and clean_topic.lower() not in rewritten.lower(): | |
| if lower.startswith("what about "): | |
| aspect = user_text[11:].strip().rstrip("?") | |
| rewritten = f"What is the {aspect} of {clean_topic}?" | |
| elif lower.startswith("how about "): | |
| aspect = user_text[10:].strip().rstrip("?") | |
| rewritten = f"What is the {aspect} of {clean_topic}?" | |
| elif lower.startswith("and "): | |
| aspect = user_text[4:].strip().rstrip("?") | |
| rewritten = f"What is the {aspect} of {clean_topic}?" | |
| elif lower.startswith("also "): | |
| aspect = user_text[5:].strip().rstrip("?") | |
| rewritten = f"What is the {aspect} of {clean_topic}?" | |
| else: | |
| rewritten = f"{clean_topic} {user_text}" | |
| # 4. Slot enrichment (e.g. if code is requested and language slot is set) | |
| if slots and "programming_language" in slots: | |
| lang = slots["programming_language"] | |
| if any(term in rewritten.lower() for term in ["code", "implementation", "pseudocode"]) and lang.lower() not in rewritten.lower(): | |
| rewritten = f"{rewritten} in {lang}" | |
| logger.debug(f"Query rewritten: '{user_text}' -> '{rewritten}'") | |
| return rewritten, True | |