Yabin Li
2024-05-13 00cfc36b9a1ad4d114434eb7770c1e67940d4862
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
#include "phone-set.h"
#include <yaml-cpp/yaml.h>
#include <glog/logging.h>
 
#include <fstream>
#include <iostream>
#include <list>
#include <sstream>
#include <string>
 
using namespace std;
 
namespace funasr {
PhoneSet::PhoneSet(const char *filename) {
  ifstream in(filename);
  LoadPhoneSetFromJson(filename);
}
PhoneSet::~PhoneSet()
{
}
 
void PhoneSet::LoadPhoneSetFromYaml(const char* filename) {
  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);
  }
  YAML::Node myList = config["token_list"];
  int id = 0;
  for (YAML::const_iterator it = myList.begin(); it != myList.end(); ++it, id++) {
    phone_.push_back(it->as<string>());
    phn2Id_.emplace(it->as<string>(), id);
  }
}
 
void PhoneSet::LoadPhoneSetFromJson(const char* filename) {
    nlohmann::json json_array;
    std::ifstream file(filename);
    if (file.is_open()) {
        file >> json_array;
        file.close();
    } else {
        LOG(INFO) << "Error loading token file, token file error or not exist.";
        exit(-1);
    }
 
    int id = 0;
    for (const auto& element : json_array) {
        phone_.push_back(element);
        phn2Id_.emplace(element, id);
        id++;
    }
}
 
int PhoneSet::Size() const {
  return phone_.size();
}
 
int PhoneSet::String2Id(string phn_str) const {
  if (phn2Id_.count(phn_str)) {
    return phn2Id_.at(phn_str);
  } else {
    //LOG(INFO) << "Phone unit not exist.";
    return -1;
  }
}
 
string PhoneSet::Id2String(int id) const {
  if (id < 0 || id > Size()) {
    //LOG(INFO) << "Phone id not exist.";
    return "";
  } else {
    return phone_[id];
  }
}
 
bool PhoneSet::Find(string phn_str) const {
  return phn2Id_.count(phn_str) > 0;
}
 
int PhoneSet::GetBegSilPhnId() const {
  return String2Id(UNIT_BEG_SIL_SYMBOL);
}
 
int PhoneSet::GetEndSilPhnId() const {
  return String2Id(UNIT_END_SIL_SYMBOL);
}
 
int PhoneSet::GetBlkPhnId() const {
  return String2Id(UNIT_BLK_SYMBOL);
}
 
}