| 563 | } |
| 564 | |
| 565 | void bert_tokenize( |
| 566 | const bark_vocab* vocab, |
| 567 | const char* text, |
| 568 | int32_t* tokens, |
| 569 | int32_t* n_tokens, |
| 570 | int32_t n_max_tokens) { |
| 571 | std::string str = text; |
| 572 | std::vector<std::string> words; |
| 573 | |
| 574 | int32_t t = 0; |
| 575 | |
| 576 | auto* token_map = &vocab->token_to_id; |
| 577 | |
| 578 | // split the text into words |
| 579 | { |
| 580 | str = strip_accents(text); |
| 581 | |
| 582 | std::string pat = R"([[:punct:]]|[[:alpha:]]+|[[:digit:]]+)"; |
| 583 | |
| 584 | std::regex re(pat); |
| 585 | std::smatch m; |
| 586 | |
| 587 | while (std::regex_search(str, m, re)) { |
| 588 | for (std::string x : m) |
| 589 | words.push_back(x); |
| 590 | str = m.suffix(); |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | // apply wordpiece |
| 595 | for (const auto& word : words) { |
| 596 | if (word.size() == 0) |
| 597 | continue; |
| 598 | |
| 599 | std::string prefix = ""; |
| 600 | int i = 0; |
| 601 | int n = word.size(); |
| 602 | |
| 603 | loop: |
| 604 | while (i < n) { |
| 605 | if (t >= n_max_tokens - 1) |
| 606 | break; |
| 607 | int j = n; |
| 608 | while (j > i) { |
| 609 | auto it = token_map->find(prefix + word.substr(i, j - i)); |
| 610 | if (it != token_map->end()) { |
| 611 | tokens[t++] = it->second; |
| 612 | i = j; |
| 613 | prefix = "##"; |
| 614 | goto loop; |
| 615 | } |
| 616 | --j; |
| 617 | } |
| 618 | if (j == i) { |
| 619 | fprintf(stderr, "%s: unknown token '%s'\n", __func__, word.substr(i, 1).data()); |
| 620 | prefix = "##"; |
| 621 | ++i; |
| 622 | } |
no test coverage detected