雾聪
2023-11-16 5297a2dc4b2f22c07b9bfd5aef6190efd51de0bb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#include "bias-lm.h"
#ifdef _WIN32
#include "fst-types.cc"
#endif
namespace funasr {
void print(std::queue<StateId> &q) {
  std::queue<StateId> data = q;
  while (!data.empty())
  {
    cout << data.front() << " ";
    data.pop();
  }
  cout << endl;
}
 
void BiasLm::LoadCfgFromYaml(const char* filename, BiasLmOption &opt) {
  YAML::Node config;
  try {
    config = YAML::LoadFile(filename);
  } catch(exception const &e) {
    LOG(INFO) << "Error loading file, yaml file error or not exist.";
    exit(-1);
  }
  try {
    YAML::Node bias_lm_conf = config["bias_lm_conf"];
    opt_.incre_bias_ = bias_lm_conf["increment_weight"].as<float>();
  } catch(exception const &e) {
  }
}
 
void BiasLm::BuildGraph(std::vector<std::vector<int>> &split_id_vec,
  std::vector<float> &custom_weight) {
  if (split_id_vec.empty()) {
    LOG(INFO) << "Skip building biaslm graph, hotword not exits.";
    return ; 
  }
  assert(split_id_vec.size() == custom_weight.size());
  // Build prefix tree
  std::unique_ptr<fst::StdVectorFst> prefix_tree(new fst::StdVectorFst());
  StateId start_state = prefix_tree->AddState();
  prefix_tree->SetStart(start_state);
  int id = 0;
  for (auto& x : split_id_vec) {
    StateId state = start_state;
    StateId next_state = state;
    float w = custom_weight[id++];
    std::vector<int> split_id = x;
    for (int j = 0; j < split_id.size(); j++) {
      next_state = prefix_tree->AddState();
      if (j == split_id.size() - 1) {
        prefix_tree->SetFinal(next_state, w);
      }
      prefix_tree->AddArc(state, Arc(split_id[j], split_id[j], opt_.incre_bias_, next_state));
      state = next_state;
    }
  }
  graph_ = std::unique_ptr<fst::StdVectorFst>(new fst::StdVectorFst());
  fst::Determinize(*prefix_tree, graph_.get());
 
  int num_node = graph_->NumStates();
  node_list_.resize(num_node);
  for (auto& x : split_id_vec) {
    StateId cur_state = 0;
    StateId next_state = 0;
    std::vector<int> split_id = x;
    for (int j = 0; j < split_id.size(); j++) {
      Matcher matcher(*graph_, fst::MATCH_INPUT);
      matcher.SetState(cur_state);
      if (matcher.Find(split_id[j])) {
        next_state = matcher.Value().nextstate;
        if (graph_->Final(next_state) != Weight::Zero()) {
          node_list_[next_state].is_final_ = true;
        }
        node_list_[next_state].score_ = opt_.incre_bias_ * (j + 1);
        cur_state = next_state;
      }
    }
  }
  
  // Build Aho-Corasick Automata
  std::queue<StateId> q;
  Matcher matcher(*graph_, fst::MATCH_INPUT);
  // Back off state of all child nodes of the root node points to the root node
  for (ArcIterator aiter(*graph_, start_state); !aiter.Done(); aiter.Next()) {
    const Arc& arc = aiter.Value();
    node_list_[arc.nextstate].back_off_ = start_state;
    float back_off_score = (node_list_[arc.nextstate].is_final_ ? 0 :
      node_list_[start_state].score_ - node_list_[arc.nextstate].score_);
    graph_->AddArc(arc.nextstate, Arc(0, 0, back_off_score, start_state));
    q.push(arc.nextstate);
  }
  while (!q.empty()) {
    StateId state_id = q.front();
    q.pop();
    for (ArcIterator aiter(*graph_, state_id); !aiter.Done(); aiter.Next()) {
      const Arc& arc = aiter.Value();
      StateId next_state = arc.nextstate;
      StateId temp_state = node_list_[state_id].back_off_;
      if (next_state == start_state || next_state == temp_state) { 
        continue; 
      }
      while (true) {
        matcher.SetState(temp_state);
        if (matcher.Find(arc.ilabel)) {
          node_list_[next_state].back_off_ = matcher.Value().nextstate;
          break;
        } else if (temp_state == start_state) {
          node_list_[next_state].back_off_ = start_state;
          break;
        }
        temp_state = node_list_[temp_state].back_off_;
      }
      float back_off_score = (node_list_[next_state].is_final_ ? 0 :
        node_list_[node_list_[next_state].back_off_].score_ -
        node_list_[next_state].score_);
      graph_->AddArc(next_state, Arc(0, 0, back_off_score, 
        node_list_[next_state].back_off_));
      q.push(next_state);
    }
  }
  fst::ArcSort(graph_.get(), fst::StdILabelCompare());
  //graph_->Write("graph.final.fst");
}
 
float BiasLm::BiasLmScore(const StateId &his_state, const Label &lab, Label &new_state) {
  if (lab < 1 || lab > phn_set_.Size() || !graph_) { return VALUE_ZERO; }
  StateId cur_state = his_state;
  StateId next_state;
  float score = VALUE_ZERO;
  Matcher matcher(*graph_, fst::MATCH_INPUT);
  while (true) {
    StateId prev_state = cur_state;
    matcher.SetState(cur_state);
    if (matcher.Find(lab)) {
      next_state = matcher.Value().nextstate;
      score += matcher.Value().weight.Value();
      if (node_list_[next_state].is_final_) {
        score = score + graph_->Final(next_state).Value();
      }
      cur_state = next_state;
      break;
    } else {
      ArcIterator aiter(*graph_, cur_state);
      const Arc& arc = aiter.Value();
      if (arc.ilabel == 0) {
        score += arc.weight.Value();
        next_state = arc.nextstate;
        cur_state = next_state;
      }
      if (prev_state == ROOT_NODE && cur_state == ROOT_NODE) {
        break;
      }
    }
  }
  new_state = cur_state;
  return score;
}
 
void BiasLm::VocabIdToPhnIdVector(int vocab_id, std::vector<int> &phn_ids) {
  bool is_oov = false;
  phn_ids.clear();
  std::string word = vocab_.Id2String(vocab_id);
  std::vector<std::string> phn_vec;
  Utf8ToCharset(word, phn_vec);
  for (auto& phn : phn_vec) {
    if (!phn_set_.Find(phn)) {
      is_oov = true;
      break;
    } else {
      phn_ids.push_back(phn_set_.String2Id(phn));
    }
  }
  if (is_oov) { phn_ids.clear(); }
}
 
std::string BiasLm::GetPhoneLabel(int phone_id) {
  if (phone_id < 0 || phone_id >= phn_set_.Size()) { return ""; }
  return phn_set_.Id2String(phone_id);
}
}