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.

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