You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.2 KiB

  1. // Copyright (c) 2021 Mobvoi Inc (Zhendong Peng)
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef DECODER_CONTEXT_GRAPH_H_
  15. #define DECODER_CONTEXT_GRAPH_H_
  16. #include <memory>
  17. #include <string>
  18. #include <unordered_map>
  19. #include <unordered_set>
  20. #include <vector>
  21. #include "fst/compose.h"
  22. #include "fst/fst.h"
  23. #include "fst/matcher.h"
  24. #include "fst/vector-fst.h"
  25. namespace wenet {
  26. using ArcIterator = fst::ArcIterator<fst::StdFst>;
  27. using Matcher = fst::SortedMatcher<fst::StdFst>;
  28. using Weight = fst::StdArc::Weight;
  29. bool SplitContextToUnits(const std::string& context,
  30. const std::shared_ptr<fst::SymbolTable>& unit_table,
  31. std::vector<int>* units);
  32. struct ContextConfig {
  33. int max_contexts = 5000;
  34. int max_context_length = 100;
  35. float context_score = 3.0;
  36. float incremental_context_score = 0.0;
  37. };
  38. class ContextGraph {
  39. public:
  40. explicit ContextGraph(ContextConfig config);
  41. int TraceContext(int cur_state, int unit_id, int* final_state);
  42. void BuildContextGraph(const std::vector<std::string>& context,
  43. const std::shared_ptr<fst::SymbolTable>& unit_table);
  44. void ConvertToAC();
  45. int GetNextState(int cur_state, int unit_id, float* score,
  46. std::unordered_set<std::string>* contexts = nullptr);
  47. // check context state is the final state
  48. bool IsFinalState(int state) {
  49. return graph_->Final(state) != Weight::Zero();
  50. }
  51. private:
  52. ContextConfig config_;
  53. std::unique_ptr<fst::StdVectorFst> graph_;
  54. std::unordered_map<int, int> fallback_finals_; // States fallback to final
  55. std::unordered_map<int, std::string> context_table_; // Finals to context
  56. };
  57. } // namespace wenet
  58. #endif // DECODER_CONTEXT_GRAPH_H_