- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_processing.py
More file actions
Latest commit
158 lines (126 loc) · 5.33 KB
/
Copy pathquery_processing.py
File metadata and controls
158 lines (126 loc) · 5.33 KB
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
"""
Query processing module: normalization, expansion, and rewriting.
Handles query preprocessing to improve retrieval quality.
"""
importre
importunicodedata
fromtypingimportDict, List, Optional
fromconfigimport (
ABBREVIATION_MAP,
ENABLE_QUERY_NORMALIZATION,
ENABLE_QUERY_EXPANSION,
MAX_QUERY_EXPANSIONS,
)
classQueryNormalizer:
"""Production-grade query normalization pipeline."""
def__init__(self, abbreviations: Dict[str, str] =None):
self.abbreviations=abbreviationsorABBREVIATION_MAP
self._whitespace_re=re.compile(r'\s+')
self._special_chars_re=re.compile(r'[^\w\s\-\'\"?.,!]')
self._repeated_punct_re=re.compile(r'([?!.,])\1+')
defnormalize(self, query: str) ->Dict[str, any]:
"""Full normalization: unicode → whitespace → punctuation → abbreviations."""
ifnotqueryornotquery.strip():
return {
"original": query,
"normalized": "",
"display": "",
"expansions": []
}
original=query
expansions= []
# Unicode normalize + clean
text=unicodedata.normalize('NFKC', query).strip()
text=self._whitespace_re.sub(' ', text)
text=self._special_chars_re.sub('', text)
text=self._repeated_punct_re.sub(r'\1', text)
display=text
text_lower=text.lower()
# Expand abbreviations
words=text_lower.split()
expanded= []
forwordinwords:
word_clean=word.rstrip('?.,!"\'-')
trailing=word[len(word_clean):] iflen(word_clean) <len(word) else''
ifword_cleaninself.abbreviations:
exp=self.abbreviations[word_clean]
expansions.append(f"{word_clean} → {exp}")
expanded.append(exp+trailing)
else:
expanded.append(word)
return {
"original": original,
"normalized": ' '.join(expanded),
"display": display,
"expansions": expansions,
}
defquick_normalize(self, query: str) ->str:
"""Quick normalization returning only the normalized string."""
returnself.normalize(query)["normalized"]
classQueryExpander:
"""Generates semantic query variants for improved recall."""
PATTERNS= [
(r'^what is (the )?(.*?)\??$', ['define {0}', 'explain {0}', '{0} definition']),
(r'^how (do|does|can|to) (.*?)\??$', ['method for {0}', 'process of {0}']),
(r'^why (is|are|do|does) (.*?)\??$', ['reason for {0}', 'cause of {0}']),
]
STOP_WORDS= {
'what', 'is', 'are', 'the', 'a', 'an', 'how', 'do', 'does', 'can',
'why', 'when', 'where', 'which', 'who', 'to', 'for', 'in', 'on',
'at', 'by', 'with', 'about', 'of', 'from', 'this', 'that', 'it',
'be', 'been', 'being', 'have', 'has', 'had', 'and', 'or', 'but',
}
def__init__(self, max_expansions: int=MAX_QUERY_EXPANSIONS):
self.max_expansions=max_expansions
defexpand(self, query: str) ->List[str]:
"""Generate query variants for improved recall."""
variants= [query]
query_lower=query.lower().strip()
# Pattern-based expansion
forpattern, templatesinself.PATTERNS:
match=re.match(pattern, query_lower, re.IGNORECASE)
ifmatch:
content=match.groups()[-1]
fortmplintemplates[:self.max_expansions]:
variant=tmpl.format(content)
ifvariantnotinvariants:
variants.append(variant)
break
# Keyword extraction variant
keywords=self._extract_keywords(query)
ifkeywordsandkeywordsnotinvariants:
variants.append(keywords)
returnvariants[:self.max_expansions+1]
def_extract_keywords(self, query: str) ->str:
"""Extract meaningful keywords from query."""
words=re.findall(r'\b\w+\b', query.lower())
keywords= [wforwinwordsifwnotinself.STOP_WORDSandlen(w) >2]
return' '.join(keywords) ifkeywordselse''
classQueryProcessor:
"""Main query processing orchestrator."""
def__init__(
self,
enable_normalization: bool=ENABLE_QUERY_NORMALIZATION,
enable_expansion: bool=ENABLE_QUERY_EXPANSION,
):
self.normalizer=QueryNormalizer()
self.expander=QueryExpander()
self.enable_normalization=enable_normalization
self.enable_expansion=enable_expansion
defprocess(self, query: str) ->Dict:
"""Process query: normalize → expand."""
result= {
"original": query,
"normalized": query,
"variants": [query],
"expansions": []
}
ifself.enable_normalization:
norm=self.normalizer.normalize(query)
result["normalized"] =norm["normalized"]
result["expansions"] =norm["expansions"]
ifself.enable_expansion:
result["variants"] =self.expander.expand(result["normalized"])
returnresult
# Global instance
query_processor=QueryProcessor()