Skip to content

Commit 501b7d4

Browse files
Fix: prio synonym match than wordnet for english (#10762)
### What problem does this PR solve? Fix: prio synonym match than wordnet for english ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
1 parent 1d57801 commit 501b7d4

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

rag/nlp/synonym.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ def __init__(self, redis=None):
3232
path = os.path.join(get_project_base_directory(), "rag/res", "synonym.json")
3333
try:
3434
self.dictionary = json.load(open(path, 'r'))
35+
self.dictionary = { (k.lower() if isinstance(k, str) else k): v for k, v in self.dictionary.items() }
3536
except Exception:
3637
logging.warning("Missing synonym.json")
3738
self.dictionary = {}
@@ -66,18 +67,34 @@ def load(self):
6667
except Exception as e:
6768
logging.error("Fail to load synonym!" + str(e))
6869

70+
6971
def lookup(self, tk, topn=8):
70-
if re.match(r"[a-z]+$", tk):
71-
res = list(set([re.sub("_", " ", syn.name().split(".")[0]) for syn in wordnet.synsets(tk)]) - set([tk]))
72-
return [t for t in res if t]
72+
if not tk or not isinstance(tk, str):
73+
return []
7374

75+
# 1) Check the custom dictionary first (both keys and tk are already lowercase)
7476
self.lookup_num += 1
7577
self.load()
76-
res = self.dictionary.get(re.sub(r"[ \t]+", " ", tk.lower()), [])
78+
key = re.sub(r"[ \t]+", " ", tk.strip())
79+
res = self.dictionary.get(key, [])
7780
if isinstance(res, str):
7881
res = [res]
79-
return res[:topn]
82+
if res: # Found in dictionary → return directly
83+
return res[:topn]
84+
85+
# 2) If not found and tk is purely alphabetical → fallback to WordNet
86+
if re.fullmatch(r"[a-z]+", tk):
87+
wn_set = {
88+
re.sub("_", " ", syn.name().split(".")[0])
89+
for syn in wordnet.synsets(tk)
90+
}
91+
wn_set.discard(tk) # Remove the original token itself
92+
wn_res = [t for t in wn_set if t]
93+
return wn_res[:topn]
8094

95+
# 3) Nothing found in either source
96+
return []
97+
8198

8299
if __name__ == '__main__':
83100
dl = Dealer()

rag/res/synonym.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10542,5 +10542,6 @@
1054210542
"周五": ["礼拜五", "星期五"],
1054310543
"周六": ["礼拜六", "星期六"],
1054410544
"周日": ["礼拜日", "星期日", "星期天", "礼拜天"],
10545-
"上班": "办公"
10545+
"上班": "办公",
10546+
"HELO":"agn"
1054610547
}

0 commit comments

Comments
 (0)