44
55from abc import ABC , abstractmethod
66from functools import reduce
7- from typing import TYPE_CHECKING , Any , Iterable , NamedTuple , Tuple , Union
7+ from typing import TYPE_CHECKING , Any , Iterable , List , NamedTuple , Tuple , Union
88
99import numpy as np
1010import torch
@@ -106,6 +106,28 @@ def to(self, device: Union[str, torch.device]) -> WeightedFsaV2:
106106 )
107107
108108
109+ AppendedFsa = Tuple [List [int ], List [int ], torch .Tensor , torch .Tensor ]
110+ """Data structure used for FSA appending (see function below)."""
111+
112+
113+ def _append_fsa (original_fsa : AppendedFsa , fsa_to_append : FsaTuple ) -> AppendedFsa :
114+ """
115+ Appends an FSA :paramref:`fsa_to_append` at the end of another FSA :paramref:`original_fsa`.
116+
117+ :param original_fsa: Original FSA.
118+ :param fsa_to_append: FSA to concatenate to :paramref:`original_fsa`.
119+ :return: FSA with the number of states/edges, the edges, and the weights of :paramref:`fsa_to_append`
120+ appended at the end of :paramref:`original_fsa`.
121+ """
122+ edges = torch .from_numpy (np .int32 (fsa_to_append [2 ])).reshape ((3 , fsa_to_append [1 ]))
123+ return (
124+ original_fsa [0 ] + [fsa_to_append [0 ]], # num states
125+ original_fsa [1 ] + [fsa_to_append [1 ]], # num edges
126+ torch .hstack ([original_fsa [2 ], edges ]), # edges
127+ torch .cat ([original_fsa [3 ], torch .from_numpy (fsa_to_append [3 ])]), # weights
128+ )
129+
130+
109131class _AbstractRasrFsaBuilder (ABC ):
110132 """
111133 Builder class that wraps around the `librasr.AllophoneStateFsaBuilder` class.
@@ -235,15 +257,6 @@ def build_single(self, seq_tag: str) -> FsaTuple:
235257 raw_fsa = self .builder .build_by_segment_name (seq_tag )
236258 return raw_fsa
237259
238- def _append_fsa (self , a , b ):
239- edges = torch .from_numpy (np .int32 (b [2 ])).reshape ((3 , b [1 ]))
240- return (
241- a [0 ] + [b [0 ]], # num states
242- a [1 ] + [b [1 ]], # num edges
243- torch .hstack ([a [2 ], edges ]), # edges
244- torch .cat ([a [3 ], torch .from_numpy (b [3 ])]), # weights
245- )
246-
247260 def build_batched_fsa (self , fsas : Iterable [FsaTuple ]) -> WeightedFsa :
248261 """
249262 Build and concatenate the FSAs for a batch of sequence tags
@@ -264,7 +277,7 @@ def build_batched_fsa(self, fsas: Iterable[FsaTuple]) -> WeightedFsa:
264277 """
265278
266279 empty_fsa = ([], [], torch .empty ((3 , 0 ), dtype = torch .int32 ), torch .empty ((0 ,)))
267- num_states , num_edges , all_edges , all_weights = reduce (self . _append_fsa , fsas , empty_fsa )
280+ num_states , num_edges , all_edges , all_weights = reduce (_append_fsa , fsas , empty_fsa )
268281 num_edges = torch .tensor (num_edges , dtype = torch .int32 )
269282 num_states = torch .tensor (num_states , dtype = torch .int32 )
270283
0 commit comments