Skip to content

Commit 8cc6aee

Browse files
authored
feat: support nbest output in normalize/tag (#296) (#348)
normalize(input, nbest=1) returns a single string (default, backward compatible). normalize(input, nbest=N) returns a list of N-best results. Example: n.normalize('海淀区108号', nbest=3) # ['海淀区一百零八号', '海淀区十八号', '海淀区幺零八号']
1 parent 6ee1abd commit 8cc6aee

1 file changed

Lines changed: 15 additions & 7 deletions

File tree

tn/processor.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -104,21 +104,29 @@ def build_fst(self, prefix, cache_dir, overwrite_cache):
104104
logger.info("fst path: {}".format(tagger_path))
105105
logger.info(" {}".format(verbalizer_path))
106106

107-
def tag(self, input):
107+
def tag(self, input, nbest=1):
108108
if len(input) == 0:
109-
return ""
109+
return "" if nbest == 1 else [""]
110110
input = escape(input)
111111
lattice = input @ self.tagger
112-
return shortestpath(lattice, nshortest=1, unique=True).string()
112+
if nbest == 1:
113+
return shortestpath(lattice, nshortest=1, unique=True).string()
114+
lattice = shortestpath(lattice.project("output").rmepsilon(), nshortest=nbest, unique=True)
115+
paths = lattice.paths()
116+
results = []
117+
while not paths.done():
118+
results.append(paths.ostring())
119+
paths.next()
120+
return results
113121

114122
def verbalize(self, input):
115-
# Only words from the blacklist are contained.
116123
if len(input) == 0:
117124
return ""
118125
output = TokenParser(self.ordertype).reorder(input)
119-
# We need escape for pynini to build the fst from string.
120126
lattice = escape(output) @ self.verbalizer
121127
return shortestpath(lattice, nshortest=1, unique=True).string()
122128

123-
def normalize(self, input):
124-
return self.verbalize(self.tag(input))
129+
def normalize(self, input, nbest=1):
130+
if nbest == 1:
131+
return self.verbalize(self.tag(input))
132+
return [self.verbalize(tagged) for tagged in self.tag(input, nbest)]

0 commit comments

Comments
 (0)