Creating FSTs using constructors and mutators

In this tutorial, we demonstrate how to create the following FST using constructors and mutators from Python.

quick-start.svg

Fig. 1 quick-start.svg

Listing 1 Create an FST using constructors and mutators in Python
 1#!/usr/bin/env python3
 2
 3import graphviz
 4
 5import kaldifst
 6
 7
 8def main():
 9    # A vector FST is a general mutable FST
10    fst = kaldifst.StdVectorFst()
11
12    # Adds state 0 to the initially empty FST and make it the start state.
13    s0 = fst.add_state()  # 1st state will be state 0 (returned by add_state)
14    assert s0 == 0
15    fst.start = 0  # set the start state to 0
16
17    # Adds two arcs exiting state 0.
18    # Arc constructor args: ilabel, olabel, weight, dest state ID.
19    fst.add_arc(
20        state=0,
21        arc=kaldifst.StdArc(ilabel=1, olabel=1, weight=0.5, nextstate=1),
22    )
23
24    fst.add_arc(
25        state=0,
26        arc=kaldifst.StdArc(ilabel=2, olabel=2, weight=1.5, nextstate=1),
27    )
28
29    # Adds state 1 and its arc.
30    fst.add_state()
31    fst.add_arc(
32        state=1,
33        arc=kaldifst.StdArc(ilabel=3, olabel=3, weight=2.5, nextstate=2),
34    )
35
36    # Adds state 2 and set its final weight.
37    fst.add_state()
38    fst.set_final(state=2, weight=3.5)  # 1st arg is state ID, 2nd arg weight
39
40    # Add an input symbol table
41    isym = kaldifst.SymbolTable()
42    isym.add_symbol(symbol="a", key=1)
43    isym.add_symbol("b", 2)
44    isym.add_symbol("c", 3)
45    fst.input_symbols = isym
46
47    # Add an output symbol table
48    osym = kaldifst.SymbolTable()
49    osym.add_symbol("x", 1)
50    osym.add_symbol("y", 2)
51    osym.add_symbol("z", 3)
52    fst.output_symbols = osym
53
54    # We can save this FST to a file with
55    fst.write(filename="binary.fst")
56
57    # We can read it back
58    fst2 = kaldifst.StdVectorFst.read("binary.fst")
59    print(fst2)
60    print(fst2.to_str())
61
62    # Get a dot format of the FST for visualization
63    fst_dot = kaldifst.draw(fst, acceptor=False, portrait=True)
64    print(fst_dot)
65    # You can use
66    # https://dreampuf.github.io/GraphvizOnline
67    # to visualize it and share the link to others
68
69    # Alternatively, you can use graphviz to visualize it
70    source = graphviz.Source(fst_dot)
71    source.render(outfile="quick-start.svg")
72    # Done. quick-start.svg is the figure we showed at the start of this section
73
74
75if __name__ == "__main__":
76    main()