Convert transducers

This section demonstrates how to convert a transducer from k2 to OpenFst.

k2-transducer.svg

Fig. 7 A transducer in k2.

openfst-transducer.svg

Fig. 8 The above transducer converted to OpenFst. Pay attention to the negative sign for numbers on the arcs.

Listing 5 Convert a transducer from k2 to OpenFst
 1#!/usr/bin/env python3
 2
 3import graphviz
 4import k2
 5from kaldifst.utils import k2_to_openfst
 6
 7import kaldifst
 8
 9
10def main():
11    s = """
12    0 1 1 1 0.5
13    0 1 2 2 1.5
14    1 2 3 3 2.5
15    1 3 -1 -1 3.0
16    2 3 -1 -1 3.5
17    3
18    """
19    labels_sym = k2.SymbolTable.from_str("""
20        a 1
21        b 2
22        c 3
23    """)
24
25    aux_labels_sym = k2.SymbolTable.from_str("""
26        x 1
27        y 2
28        z 3
29    """)
30    fsa = k2.Fsa.from_str(s, acceptor=False)
31    fsa.labels_sym = labels_sym
32    fsa.aux_labels_sym = aux_labels_sym
33    fsa.draw("k2-transducer.svg")
34
35    fst = k2_to_openfst(fsa, olabels='aux_labels')
36
37    fst_dot = kaldifst.draw(fst, acceptor=False, portrait=True)
38    source = graphviz.Source(fst_dot)
39    source.render(outfile="openfst-transducer.svg")
40
41
42if __name__ == "__main__":
43    main()