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.

77 lines
2.5 KiB

  1. // Copyright (c) 2022 Zhendong Peng (pzd17@tsinghua.org.cn)
  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. #include "wetext_processor.h"
  15. #include "fst/string.h"
  16. namespace wetext {
  17. Processor::Processor(const std::string& tagger_path,
  18. const std::string& verbalizer_path) {
  19. tagger_.reset(StdVectorFst::Read(tagger_path));
  20. verbalizer_.reset(StdVectorFst::Read(verbalizer_path));
  21. compiler_ = std::make_shared<StringCompiler<StdArc>>(fst::StringTokenType::BYTE);
  22. printer_ = std::make_shared<StringPrinter<StdArc>>(fst::StringTokenType::BYTE);
  23. if (tagger_path.find("_tn_") != tagger_path.npos) {
  24. parse_type_ = ParseType::kTN;
  25. } else if (tagger_path.find("_itn_") != tagger_path.npos) {
  26. parse_type_ = ParseType::kITN;
  27. } else {
  28. LOG(FATAL) << "Invalid fst prefix, prefix should contain"
  29. << " either \"_tn_\" or \"_itn_\".";
  30. }
  31. }
  32. std::string Processor::ShortestPath(const StdVectorFst& lattice) {
  33. StdVectorFst shortest_path;
  34. fst::ShortestPath(lattice, &shortest_path, 1, true);
  35. std::string output;
  36. printer_->operator()(shortest_path, &output);
  37. return output;
  38. }
  39. std::string Processor::Compose(const std::string& input,
  40. const StdVectorFst* fst) {
  41. StdVectorFst input_fst;
  42. // compiler_->operator()(input, &input_fst);
  43. StdVectorFst lattice;
  44. fst::Compose(input_fst, *fst, &lattice);
  45. return ShortestPath(lattice);
  46. }
  47. std::string Processor::Tag(const std::string& input) {
  48. if (input.empty()) {
  49. return "";
  50. }
  51. return Compose(input, tagger_.get());
  52. }
  53. std::string Processor::Verbalize(const std::string& input) {
  54. if (input.empty()) {
  55. return "";
  56. }
  57. TokenParser parser(parse_type_);
  58. std::string output = parser.Reorder(input);
  59. output = Compose(output, verbalizer_.get());
  60. output.erase(std::remove(output.begin(), output.end(), '\0'), output.end());
  61. return output;
  62. }
  63. std::string Processor::Normalize(const std::string& input) {
  64. return Verbalize(Tag(input));
  65. }
  66. } // namespace wetext