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.

580 lines
19 KiB

  1. // util/text-utils.cc
  2. // Copyright 2009-2011 Saarland University; Microsoft Corporation
  3. // See ../../COPYING for clarification regarding multiple authors
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10. // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  11. // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  12. // MERCHANTABLITY OR NON-INFRINGEMENT.
  13. // See the Apache 2 License for the specific language governing permissions and
  14. // limitations under the License.
  15. #include "util/text-utils.h"
  16. #include <algorithm>
  17. #include <limits>
  18. #include <map>
  19. #include <utility>
  20. #include "base/kaldi-common.h"
  21. namespace kaldi {
  22. template <class F>
  23. bool SplitStringToFloats(const std::string& full, const char* delim,
  24. bool omit_empty_strings, // typically false
  25. std::vector<F>* out) {
  26. KALDI_ASSERT(out != NULL);
  27. if (*(full.c_str()) == '\0') {
  28. out->clear();
  29. return true;
  30. }
  31. std::vector<std::string> split;
  32. SplitStringToVector(full, delim, omit_empty_strings, &split);
  33. out->resize(split.size());
  34. for (size_t i = 0; i < split.size(); i++) {
  35. F f = 0;
  36. if (!ConvertStringToReal(split[i], &f)) return false;
  37. (*out)[i] = f;
  38. }
  39. return true;
  40. }
  41. // Instantiate the template above for float and double.
  42. template bool SplitStringToFloats(const std::string& full, const char* delim,
  43. bool omit_empty_strings,
  44. std::vector<float>* out);
  45. template bool SplitStringToFloats(const std::string& full, const char* delim,
  46. bool omit_empty_strings,
  47. std::vector<double>* out);
  48. void SplitStringToVector(const std::string& full, const char* delim,
  49. bool omit_empty_strings,
  50. std::vector<std::string>* out) {
  51. size_t start = 0, found = 0, end = full.size();
  52. out->clear();
  53. while (found != std::string::npos) {
  54. found = full.find_first_of(delim, start);
  55. // start != end condition is for when the delimiter is at the end
  56. if (!omit_empty_strings || (found != start && start != end))
  57. out->push_back(full.substr(start, found - start));
  58. start = found + 1;
  59. }
  60. }
  61. void JoinVectorToString(const std::vector<std::string>& vec_in,
  62. const char* delim, bool omit_empty_strings,
  63. std::string* str_out) {
  64. std::string tmp_str;
  65. for (size_t i = 0; i < vec_in.size(); i++) {
  66. if (!omit_empty_strings || !vec_in[i].empty()) {
  67. tmp_str.append(vec_in[i]);
  68. if (i < vec_in.size() - 1)
  69. if (!omit_empty_strings || !vec_in[i + 1].empty())
  70. tmp_str.append(delim);
  71. }
  72. }
  73. str_out->swap(tmp_str);
  74. }
  75. void Trim(std::string* str) {
  76. const char* white_chars = " \t\n\r\f\v";
  77. std::string::size_type pos = str->find_last_not_of(white_chars);
  78. if (pos != std::string::npos) {
  79. str->erase(pos + 1);
  80. pos = str->find_first_not_of(white_chars);
  81. if (pos != std::string::npos) str->erase(0, pos);
  82. } else {
  83. str->erase(str->begin(), str->end());
  84. }
  85. }
  86. bool IsToken(const std::string& token) {
  87. size_t l = token.length();
  88. if (l == 0) return false;
  89. for (size_t i = 0; i < l; i++) {
  90. unsigned char c = token[i];
  91. if ((!isprint(c) || isspace(c)) && (isascii(c) || c == (unsigned char)255))
  92. return false;
  93. // The "&& (isascii(c) || c == 255)" was added so that we won't reject
  94. // non-ASCII characters such as French characters with accents [except for
  95. // 255 which is "nbsp", a form of space].
  96. }
  97. return true;
  98. }
  99. void SplitStringOnFirstSpace(const std::string& str, std::string* first,
  100. std::string* rest) {
  101. const char* white_chars = " \t\n\r\f\v";
  102. typedef std::string::size_type I;
  103. const I npos = std::string::npos;
  104. I first_nonwhite = str.find_first_not_of(white_chars);
  105. if (first_nonwhite == npos) {
  106. first->clear();
  107. rest->clear();
  108. return;
  109. }
  110. // next_white is first whitespace after first nonwhitespace.
  111. I next_white = str.find_first_of(white_chars, first_nonwhite);
  112. if (next_white == npos) { // no more whitespace...
  113. *first = std::string(str, first_nonwhite);
  114. rest->clear();
  115. return;
  116. }
  117. I next_nonwhite = str.find_first_not_of(white_chars, next_white);
  118. if (next_nonwhite == npos) {
  119. *first = std::string(str, first_nonwhite, next_white - first_nonwhite);
  120. rest->clear();
  121. return;
  122. }
  123. I last_nonwhite = str.find_last_not_of(white_chars);
  124. KALDI_ASSERT(last_nonwhite != npos); // or coding error.
  125. *first = std::string(str, first_nonwhite, next_white - first_nonwhite);
  126. *rest = std::string(str, next_nonwhite, last_nonwhite + 1 - next_nonwhite);
  127. }
  128. bool IsLine(const std::string& line) {
  129. if (line.find('\n') != std::string::npos) return false;
  130. if (line.empty()) return true;
  131. if (isspace(*(line.begin()))) return false;
  132. if (isspace(*(line.rbegin()))) return false;
  133. std::string::const_iterator iter = line.begin(), end = line.end();
  134. for (; iter != end; iter++)
  135. if (!isprint(*iter)) return false;
  136. return true;
  137. }
  138. template <class T>
  139. class NumberIstream {
  140. public:
  141. explicit NumberIstream(std::istream& i) : in_(i) {}
  142. NumberIstream& operator>>(T& x) {
  143. if (!in_.good()) return *this;
  144. in_ >> x;
  145. if (!in_.fail() && RemainderIsOnlySpaces()) return *this;
  146. return ParseOnFail(&x);
  147. }
  148. private:
  149. std::istream& in_;
  150. bool RemainderIsOnlySpaces() {
  151. if (in_.tellg() != std::istream::pos_type(-1)) {
  152. std::string rem;
  153. in_ >> rem;
  154. if (rem.find_first_not_of(' ') != std::string::npos) {
  155. // there is not only spaces
  156. return false;
  157. }
  158. }
  159. in_.clear();
  160. return true;
  161. }
  162. NumberIstream& ParseOnFail(T* x) {
  163. std::string str;
  164. in_.clear();
  165. in_.seekg(0);
  166. // If the stream is broken even before trying
  167. // to read from it or if there are many tokens,
  168. // it's pointless to try.
  169. if (!(in_ >> str) || !RemainderIsOnlySpaces()) {
  170. in_.setstate(std::ios_base::failbit);
  171. return *this;
  172. }
  173. std::map<std::string, T> inf_nan_map;
  174. // we'll keep just uppercase values.
  175. inf_nan_map["INF"] = std::numeric_limits<T>::infinity();
  176. inf_nan_map["+INF"] = std::numeric_limits<T>::infinity();
  177. inf_nan_map["-INF"] = -std::numeric_limits<T>::infinity();
  178. inf_nan_map["INFINITY"] = std::numeric_limits<T>::infinity();
  179. inf_nan_map["+INFINITY"] = std::numeric_limits<T>::infinity();
  180. inf_nan_map["-INFINITY"] = -std::numeric_limits<T>::infinity();
  181. inf_nan_map["NAN"] = std::numeric_limits<T>::quiet_NaN();
  182. inf_nan_map["+NAN"] = std::numeric_limits<T>::quiet_NaN();
  183. inf_nan_map["-NAN"] = -std::numeric_limits<T>::quiet_NaN();
  184. // MSVC
  185. inf_nan_map["1.#INF"] = std::numeric_limits<T>::infinity();
  186. inf_nan_map["-1.#INF"] = -std::numeric_limits<T>::infinity();
  187. inf_nan_map["1.#QNAN"] = std::numeric_limits<T>::quiet_NaN();
  188. inf_nan_map["-1.#QNAN"] = -std::numeric_limits<T>::quiet_NaN();
  189. std::transform(str.begin(), str.end(), str.begin(), ::toupper);
  190. if (inf_nan_map.find(str) != inf_nan_map.end()) {
  191. *x = inf_nan_map[str];
  192. } else {
  193. in_.setstate(std::ios_base::failbit);
  194. }
  195. return *this;
  196. }
  197. };
  198. template <typename T>
  199. bool ConvertStringToReal(const std::string& str, T* out) {
  200. std::istringstream iss(str);
  201. NumberIstream<T> i(iss);
  202. i >> *out;
  203. if (iss.fail()) {
  204. // Number conversion failed.
  205. return false;
  206. }
  207. return true;
  208. }
  209. template bool ConvertStringToReal(const std::string& str, float* out);
  210. template bool ConvertStringToReal(const std::string& str, double* out);
  211. /*
  212. This function is a helper function of StringsApproxEqual. It should be
  213. thought of as a recursive function-- it was designed that way-- but rather
  214. than actually recursing (which would cause problems with stack overflow), we
  215. just set the args and return to the start.
  216. The 'decimal_places_tolerance' argument is just passed in from outside,
  217. see the documentation for StringsApproxEqual in text-utils.h to see an
  218. explanation. The argument 'places_into_number' provides some information
  219. about the strings 'a' and 'b' that precedes the current pointers.
  220. For purposes of this comment, let's define the 'decimal' of a number
  221. as the part that comes after the decimal point, e.g. in '99.123',
  222. '123' would be the decimal. If 'places_into_number' is -1, it means
  223. we're not currently inside some place like that (i.e. it's not the
  224. case that we're pointing to the '1' or the '2' or the '3').
  225. If it's 0, then we'd be pointing to the first place after the decimal,
  226. '1' in this case. Note if one of the numbers is shorter than the
  227. other, like '99.123' versus '99.1234' and 'a' points to the first '3'
  228. while 'b' points to the second '4', 'places_into_number' referes to the
  229. shorter of the two, i.e. it would be 2 in this example.
  230. */
  231. bool StringsApproxEqualInternal(const char* a, const char* b,
  232. int32 decimal_places_tolerance,
  233. int32 places_into_number) {
  234. start:
  235. char ca = *a, cb = *b;
  236. if (ca == cb) {
  237. if (ca == '\0') {
  238. return true;
  239. } else {
  240. if (places_into_number >= 0) {
  241. if (isdigit(ca)) {
  242. places_into_number++;
  243. } else {
  244. places_into_number = -1;
  245. }
  246. } else {
  247. if (ca == '.') {
  248. places_into_number = 0;
  249. }
  250. }
  251. a++;
  252. b++;
  253. goto start;
  254. }
  255. } else {
  256. if (places_into_number >= decimal_places_tolerance &&
  257. (isdigit(ca) || isdigit(cb))) {
  258. // we're potentially willing to accept this difference between the
  259. // strings.
  260. if (isdigit(ca)) a++;
  261. if (isdigit(cb)) b++;
  262. // we'll have advanced at least one of the two strings.
  263. goto start;
  264. } else if (places_into_number >= 0 &&
  265. ((ca == '0' && !isdigit(cb)) || (cb == '0' && !isdigit(ca)))) {
  266. // this clause is designed to ensure that, for example,
  267. // "0.1" would count the same as "0.100001".
  268. if (ca == '0')
  269. a++;
  270. else
  271. b++;
  272. places_into_number++;
  273. goto start;
  274. } else {
  275. return false;
  276. }
  277. }
  278. }
  279. bool StringsApproxEqual(const std::string& a, const std::string& b,
  280. int32 decimal_places_tolerance) {
  281. return StringsApproxEqualInternal(a.c_str(), b.c_str(),
  282. decimal_places_tolerance, -1);
  283. }
  284. bool ConfigLine::ParseLine(const std::string& line) {
  285. data_.clear();
  286. whole_line_ = line;
  287. if (line.size() == 0) return false; // Empty line
  288. size_t pos = 0, size = line.size();
  289. while (isspace(line[pos]) && pos < size) pos++;
  290. if (pos == size) return false; // whitespace-only line
  291. size_t first_token_start_pos = pos;
  292. // first get first_token_.
  293. while (!isspace(line[pos]) && pos < size) {
  294. if (line[pos] == '=') {
  295. // If the first block of non-whitespace looks like "foo-bar=...",
  296. // then we ignore it: there is no initial token, and FirstToken()
  297. // is empty.
  298. pos = first_token_start_pos;
  299. break;
  300. }
  301. pos++;
  302. }
  303. first_token_ =
  304. std::string(line, first_token_start_pos, pos - first_token_start_pos);
  305. // first_token_ is expected to be either empty or something like
  306. // "component-node", which actually is a slightly more restrictive set of
  307. // strings than IsValidName() checks for this is a convenient way to check it.
  308. if (!first_token_.empty() && !IsValidName(first_token_)) return false;
  309. while (pos < size) {
  310. if (isspace(line[pos])) {
  311. pos++;
  312. continue;
  313. }
  314. // OK, at this point we know that we are pointing at nonspace.
  315. size_t next_equals_sign = line.find_first_of("=", pos);
  316. if (next_equals_sign == pos || next_equals_sign == std::string::npos) {
  317. // we're looking for something like 'key=value'. If there is no equals
  318. // sign, or it's not preceded by something, it's a parsing failure.
  319. return false;
  320. }
  321. std::string key(line, pos, next_equals_sign - pos);
  322. if (!IsValidName(key)) return false;
  323. // handle any quotes. we support key='blah blah' or key="foo bar".
  324. // no escaping is supported.
  325. if (line[next_equals_sign + 1] == '\'' ||
  326. line[next_equals_sign + 1] == '"') {
  327. char my_quote = line[next_equals_sign + 1];
  328. size_t next_quote = line.find_first_of(my_quote, next_equals_sign + 2);
  329. if (next_quote == std::string::npos) { // no matching quote was found.
  330. KALDI_WARN << "No matching quote for " << my_quote
  331. << " in config line '" << line << "'";
  332. return false;
  333. } else {
  334. std::string value(line, next_equals_sign + 2,
  335. next_quote - next_equals_sign - 2);
  336. data_.insert(std::make_pair(key, std::make_pair(value, false)));
  337. pos = next_quote + 1;
  338. continue;
  339. }
  340. } else {
  341. // we want to be able to parse something like "... input=Offset(a, -1)
  342. // foo=bar": in general, config values with spaces in them, even without
  343. // quoting.
  344. size_t next_next_equals_sign =
  345. line.find_first_of("=", next_equals_sign + 1),
  346. terminating_space = size;
  347. if (next_next_equals_sign !=
  348. std::string::npos) { // found a later equals sign.
  349. size_t preceding_space =
  350. line.find_last_of(" \t", next_next_equals_sign);
  351. if (preceding_space != std::string::npos &&
  352. preceding_space > next_equals_sign)
  353. terminating_space = preceding_space;
  354. }
  355. while (isspace(line[terminating_space - 1]) && terminating_space > 0)
  356. terminating_space--;
  357. std::string value(line, next_equals_sign + 1,
  358. terminating_space - (next_equals_sign + 1));
  359. data_.insert(std::make_pair(key, std::make_pair(value, false)));
  360. pos = terminating_space;
  361. }
  362. }
  363. return true;
  364. }
  365. bool ConfigLine::GetValue(const std::string& key, std::string* value) {
  366. KALDI_ASSERT(value != NULL);
  367. std::map<std::string, std::pair<std::string, bool> >::iterator it =
  368. data_.begin();
  369. for (; it != data_.end(); ++it) {
  370. if (it->first == key) {
  371. *value = (it->second).first;
  372. (it->second).second = true;
  373. return true;
  374. }
  375. }
  376. return false;
  377. }
  378. bool ConfigLine::GetValue(const std::string& key, BaseFloat* value) {
  379. KALDI_ASSERT(value != NULL);
  380. std::map<std::string, std::pair<std::string, bool> >::iterator it =
  381. data_.begin();
  382. for (; it != data_.end(); ++it) {
  383. if (it->first == key) {
  384. if (!ConvertStringToReal((it->second).first, value)) return false;
  385. (it->second).second = true;
  386. return true;
  387. }
  388. }
  389. return false;
  390. }
  391. bool ConfigLine::GetValue(const std::string& key, int32* value) {
  392. KALDI_ASSERT(value != NULL);
  393. std::map<std::string, std::pair<std::string, bool> >::iterator it =
  394. data_.begin();
  395. for (; it != data_.end(); ++it) {
  396. if (it->first == key) {
  397. if (!ConvertStringToInteger((it->second).first, value)) return false;
  398. (it->second).second = true;
  399. return true;
  400. }
  401. }
  402. return false;
  403. }
  404. bool ConfigLine::GetValue(const std::string& key, std::vector<int32>* value) {
  405. KALDI_ASSERT(value != NULL);
  406. value->clear();
  407. std::map<std::string, std::pair<std::string, bool> >::iterator it =
  408. data_.begin();
  409. for (; it != data_.end(); ++it) {
  410. if (it->first == key) {
  411. if (!SplitStringToIntegers((it->second).first, ":,", true, value)) {
  412. // KALDI_WARN << "Bad option " << (it->second).first;
  413. return false;
  414. }
  415. (it->second).second = true;
  416. return true;
  417. }
  418. }
  419. return false;
  420. }
  421. bool ConfigLine::GetValue(const std::string& key, bool* value) {
  422. KALDI_ASSERT(value != NULL);
  423. std::map<std::string, std::pair<std::string, bool> >::iterator it =
  424. data_.begin();
  425. for (; it != data_.end(); ++it) {
  426. if (it->first == key) {
  427. if ((it->second).first.size() == 0) return false;
  428. switch (((it->second).first)[0]) {
  429. case 'F':
  430. case 'f':
  431. *value = false;
  432. break;
  433. case 'T':
  434. case 't':
  435. *value = true;
  436. break;
  437. default:
  438. return false;
  439. }
  440. (it->second).second = true;
  441. return true;
  442. }
  443. }
  444. return false;
  445. }
  446. bool ConfigLine::HasUnusedValues() const {
  447. std::map<std::string, std::pair<std::string, bool> >::const_iterator it =
  448. data_.begin();
  449. for (; it != data_.end(); ++it) {
  450. if (!(it->second).second) return true;
  451. }
  452. return false;
  453. }
  454. std::string ConfigLine::UnusedValues() const {
  455. std::string unused_str;
  456. std::map<std::string, std::pair<std::string, bool> >::const_iterator it =
  457. data_.begin();
  458. for (; it != data_.end(); ++it) {
  459. if (!(it->second).second) {
  460. if (unused_str == "")
  461. unused_str = it->first + "=" + (it->second).first;
  462. else
  463. unused_str += " " + it->first + "=" + (it->second).first;
  464. }
  465. }
  466. return unused_str;
  467. }
  468. // This is like ExpectToken but for two tokens, and it
  469. // will either accept token1 and then token2, or just token2.
  470. // This is useful in Read functions where the first token
  471. // may already have been consumed.
  472. // void ExpectOneOrTwoTokens(std::istream &is, bool binary,
  473. // const std::string &token1,
  474. // const std::string &token2) {
  475. // KALDI_ASSERT(token1 != token2);
  476. // std::string temp;
  477. // ReadToken(is, binary, &temp);
  478. // if (temp == token1) {
  479. // ExpectToken(is, binary, token2);
  480. // } else {
  481. // if (temp != token2) {
  482. // KALDI_ERR << "Expecting token " << token1 << " or " << token2
  483. // << " but got " << temp;
  484. // }
  485. // }
  486. // }
  487. bool IsValidName(const std::string& name) {
  488. if (name.size() == 0) return false;
  489. for (size_t i = 0; i < name.size(); i++) {
  490. if (i == 0 && !isalpha(name[i]) && name[i] != '_') return false;
  491. if (!isalnum(name[i]) && name[i] != '_' && name[i] != '-' && name[i] != '.')
  492. return false;
  493. }
  494. return true;
  495. }
  496. void ReadConfigLines(std::istream& is, std::vector<std::string>* lines) {
  497. KALDI_ASSERT(lines != NULL);
  498. std::string line;
  499. while (std::getline(is, line)) {
  500. if (line.size() == 0) continue;
  501. size_t start = line.find_first_not_of(" \t");
  502. size_t end = line.find_first_of('#');
  503. if (start == std::string::npos || start == end) continue;
  504. end = line.find_last_not_of(" \t", end - 1);
  505. KALDI_ASSERT(end >= start);
  506. lines->push_back(line.substr(start, end - start + 1));
  507. }
  508. }
  509. void ParseConfigLines(const std::vector<std::string>& lines,
  510. std::vector<ConfigLine>* config_lines) {
  511. config_lines->resize(lines.size());
  512. for (size_t i = 0; i < lines.size(); i++) {
  513. bool ret = (*config_lines)[i].ParseLine(lines[i]);
  514. if (!ret) {
  515. KALDI_ERR << "Error parsing config line: " << lines[i];
  516. }
  517. }
  518. }
  519. } // end namespace kaldi