decoder_utils.h 2.0 KB
Newer Older
1 2 3
#ifndef DECODER_UTILS_H_
#define DECODER_UTILS_H_

Y
Yibing Liu 已提交
4
#include <utility>
5
#include "path_trie.h"
Y
Yibing Liu 已提交
6

Y
Yibing Liu 已提交
7 8 9
const float NUM_FLT_INF = std::numeric_limits<float>::max();
const float NUM_FLT_MIN = std::numeric_limits<float>::min();

10
// Function template for comparing two pairs
Y
Yibing Liu 已提交
11
template <typename T1, typename T2>
Y
Yibing Liu 已提交
12
bool pair_comp_first_rev(const std::pair<T1, T2> &a,
Y
Yibing Liu 已提交
13 14
                         const std::pair<T1, T2> &b) {
  return a.first > b.first;
15
}
Y
Yibing Liu 已提交
16

Y
Yibing Liu 已提交
17
// Function template for comparing two pairs
Y
Yibing Liu 已提交
18
template <typename T1, typename T2>
Y
Yibing Liu 已提交
19
bool pair_comp_second_rev(const std::pair<T1, T2> &a,
Y
Yibing Liu 已提交
20 21
                          const std::pair<T1, T2> &b) {
  return a.second > b.second;
22 23
}

Y
Yibing Liu 已提交
24
// Return the sum of two probabilities in log scale
25
template <typename T>
Y
Yibing Liu 已提交
26 27 28 29 30 31
T log_sum_exp(const T &x, const T &y) {
  static T num_min = -std::numeric_limits<T>::max();
  if (x <= num_min) return y;
  if (y <= num_min) return x;
  T xmax = std::max(x, y);
  return std::log(std::exp(x - xmax) + std::exp(y - xmax)) + xmax;
32 33
}

Y
Yibing Liu 已提交
34
// Functor for prefix comparsion
Y
Yibing Liu 已提交
35
bool prefix_compare(const PathTrie *x, const PathTrie *y);
36

Y
Yibing Liu 已提交
37 38 39
/* Get length of utf8 encoding string
 * See: http://stackoverflow.com/a/4063229
 */
Y
Yibing Liu 已提交
40
size_t get_utf8_str_len(const std::string &str);
Y
Yibing Liu 已提交
41

Y
Yibing Liu 已提交
42 43 44 45
/* Split a string into a list of strings on a given string
 * delimiter. NB: delimiters on beginning / end of string are
 * trimmed. Eg, "FooBarFoo" split on "Foo" returns ["Bar"].
 */
Y
Yibing Liu 已提交
46 47 48
std::vector<std::string> split_str(const std::string &s,
                                   const std::string &delim);

Y
Yibing Liu 已提交
49 50 51
/* Splits string into vector of strings representing
 * UTF-8 characters (not same as chars)
 */
Y
Yibing Liu 已提交
52
std::vector<std::string> split_utf8_str(const std::string &str);
53

54
// Add a word in index to the dicionary of fst
Y
Yibing Liu 已提交
55 56
void add_word_to_fst(const std::vector<int> &word,
                     fst::StdVectorFst *dictionary);
57

58
// Add a word in string to dictionary
Y
Yibing Liu 已提交
59 60 61 62 63 64 65
bool add_word_to_dictionary(
    const std::string &word,
    const std::unordered_map<std::string, int> &char_map,
    bool add_space,
    int SPACE_ID,
    fst::StdVectorFst *dictionary);
#endif  // DECODER_UTILS_H