Spaces:
Sleeping
Sleeping
File size: 11,408 Bytes
923405c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
"""
Query Enhancement Module - Improve semantic search with query expansion and synonyms.
This module helps bridge the gap between natural user language and document terminology
by expanding queries with relevant synonyms and domain-specific terms.
"""
import re
from typing import List
class QueryExpander:
"""
Expands user queries with relevant synonyms and domain-specific terminology
to improve semantic search results in corporate policy documents.
"""
def __init__(self):
"""Initialize the query expander with predefined synonym mappings."""
# Additional HR-specific synonyms
self.hr_synonyms = {
# Time off related - enhanced with policy document terms
"personal time": [
"PTO",
"paid time off",
"time off",
"vacation",
"personal days",
"leave",
"accrual",
"days off",
],
"vacation": [
"PTO",
"paid time off",
"time off",
"personal time",
"vacation days",
"holiday",
"accrual",
],
"sick leave": [
"sick time",
"medical leave",
"illness",
"health days",
"PTO",
],
"time off": [
"PTO",
"paid time off",
"vacation",
"leave",
"personal time",
"days off",
"accrual",
],
"PTO": [
"paid time off",
"vacation",
"personal time",
"time off",
"accrual",
"days off",
],
"leave": [
"time off",
"absence",
"PTO",
"paid time off",
"vacation",
"accrual",
],
"days off": [
"PTO",
"paid time off",
"vacation",
"time off",
"personal time",
"leave",
],
"accrual": [
"earn",
"accumulate",
"build up",
"PTO",
"vacation",
"time off",
],
"earn": ["accrue", "accumulate", "get", "receive", "build up"],
"annual": ["yearly", "per year", "each year", "annually"],
"allowance": [
"allocation",
"entitlement",
"amount",
"accrual",
"benefit",
"limit",
],
"allocation": ["allowance", "entitlement", "amount", "limit", "budget"],
# Benefits related - enhanced with employee terminology
"benefits": [
"perks",
"compensation",
"package",
"coverage",
"health insurance",
"401k",
"retirement",
],
"insurance": [
"coverage",
"health plan",
"medical",
"benefits",
"healthcare",
"dental",
"vision",
],
"retirement": [
"401k",
"pension",
"savings",
"investment",
"matching",
"contribution",
],
"healthcare": [
"medical",
"health insurance",
"coverage",
"benefits",
"health plan",
"dental",
"vision",
],
"401k": ["retirement", "savings", "matching", "contribution", "pension"],
"health plan": [
"healthcare",
"medical",
"insurance",
"coverage",
"benefits",
],
"dental": ["dental coverage", "dental insurance", "benefits", "healthcare"],
"vision": ["vision coverage", "eye care", "benefits", "healthcare"],
"gym": ["fitness", "wellness", "health", "membership", "benefits"],
"tuition": [
"education",
"training",
"reimbursement",
"learning",
"development",
],
# Work arrangements
"remote work": ["work from home", "telecommuting", "WFH", "telework"],
"work from home": ["remote work", "telecommuting", "WFH", "telework"],
"telecommuting": ["remote work", "work from home", "WFH", "telework"],
"WFH": ["work from home", "remote work", "telecommuting", "telework"],
"flexible schedule": ["flex time", "flexible hours", "work schedule"],
# Performance and development
"performance review": ["evaluation", "appraisal", "assessment", "feedback"],
"training": ["development", "education", "learning", "courses"],
"promotion": ["advancement", "career growth", "progression", "raise"],
# HR processes
"onboarding": ["orientation", "new hire", "getting started", "setup"],
"offboarding": ["termination", "leaving", "exit", "departure"],
"policy": ["procedure", "guidelines", "rules", "standards"],
# Workplace issues and safety
"harassment": [
"discrimination",
"bullying",
"hostile",
"inappropriate behavior",
],
"complaint": ["report", "grievance", "issue", "concern", "problem"],
"discrimination": ["harassment", "bias", "unfair treatment", "prejudice"],
"emergency": ["crisis", "urgent", "fire", "evacuation", "safety"],
"safety": ["security", "hazard", "emergency", "protection", "guidelines"],
# Expenses and travel
"expenses": ["reimbursement", "costs", "spending", "business expenses"],
"reimbursement": ["expenses", "refund", "repayment", "reimbursable"],
"travel": ["business trip", "trip", "hotel", "flight", "transportation"],
"meal allowance": ["food", "dining", "per diem", "meal budget"],
# Technology and security
"password": ["security", "login", "authentication", "access"],
"VPN": ["remote access", "network", "connection", "security"],
"security": ["password", "access", "protection", "privacy", "incident"],
"device": ["computer", "laptop", "phone", "equipment", "technology"],
"WiFi": ["network", "internet", "connection", "wireless"],
}
# Common question patterns and their expansions
self.question_patterns = {
r"how much.*time.*earn|accrue": [
"PTO accrual",
"vacation days",
"time off allocation",
],
r"how many.*days.*get|receive": [
"PTO accrual",
"vacation days",
"annual leave",
],
r"what.*my.*allowance": [
"PTO accrual",
"vacation allowance",
"time off allocation",
],
r"time off.*balance": ["PTO balance", "vacation balance", "accrued time"],
r"sick.*time": ["sick leave", "medical leave", "PTO for illness"],
}
def expand_query(self, query: str) -> str:
"""
Expand a user query with relevant synonyms and terminology.
Args:
query: Original user query
Returns:
Expanded query with additional relevant terms
"""
expanded_terms = set()
original_words = self._extract_key_terms(query.lower())
# Add original query
expanded_terms.add(query)
# Pattern-based expansion
for pattern, expansions in self.question_patterns.items():
if re.search(pattern, query.lower()):
expanded_terms.update(expansions)
# Synonym-based expansion
for word in original_words:
if word in self.hr_synonyms:
expanded_terms.update(self.hr_synonyms[word])
# Multi-word phrase matching
query_lower = query.lower()
for phrase, synonyms in self.hr_synonyms.items():
if phrase in query_lower:
expanded_terms.update(synonyms)
# Create expanded query
if len(expanded_terms) > 1:
# Join with the original query for semantic search
expanded_query = f"{query} " + " ".join(expanded_terms - {query})
return expanded_query[:500] # Limit length to prevent overly long queries
return query
def _extract_key_terms(self, text: str) -> List[str]:
"""Extract key terms from text, removing common stop words."""
stop_words = {
"the",
"a",
"an",
"and",
"or",
"but",
"in",
"on",
"at",
"to",
"for",
"of",
"with",
"by",
"how",
"what",
"when",
"where",
"why",
"is",
"are",
"do",
"does",
"can",
"could",
"should",
"would",
"will",
"i",
"me",
"my",
}
# Simple word extraction (could be enhanced with NLP libraries)
words = re.findall(r"\b\w+\b", text.lower())
return [word for word in words if word not in stop_words and len(word) > 2]
def get_domain_suggestions(self, query: str) -> List[str]:
"""
Get domain-specific suggestions for improving the query.
Args:
query: User's original query
Returns:
List of suggested alternative phrasings
"""
suggestions = []
query_lower = query.lower()
# Specific suggestions based on common user patterns
if "personal time" in query_lower:
suggestions.extend(
[
"How much PTO do I accrue each year?",
"What is my paid time off allocation?",
"How many vacation days do I get annually?",
]
)
if "time off" in query_lower and "how much" in query_lower:
suggestions.extend(
[
"What is my PTO accrual rate?",
"How many paid time off days do I earn per year?",
]
)
if "work from home" in query_lower or "remote" in query_lower:
suggestions.extend(
[
"What is the remote work policy?",
"Can I work from home?",
"What are the telecommuting guidelines?",
]
)
return suggestions[:3] # Limit to top 3 suggestions
|