├── .gitignore ├── LICENSE ├── README.md ├── nlohmann ├── json.hpp └── json_fwd.hpp ├── run_tests.py ├── tests └── input_texts │ ├── 1.txt │ ├── 2.txt │ ├── 3.txt │ ├── 4.txt │ ├── 5.txt │ └── 6.txt ├── tokenizer.cpp └── tokenizer.json /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | tokenizer -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HuggingFace WordPiece Tokenizer in C++ 2 | This is a C++ implementation of WordPiece (BERT) tokenizer inference. 3 | 4 | It expects from you a `.json` file in HuggingFace format that contains all the required information to setup the tokenizer. You can usually download this file from HuggingFace model hub. 5 | 6 | ## How to use it? 7 | 8 | Set the path to your **.json** file when creating the tokenizer: 9 | ``` 10 | WordPieceTokenizer tokenizer("tokenizer.json"); 11 | ``` 12 | ## Build: 13 | 14 | This implementation requires the **International Components for Unicode (ICU)** library to handle Unicode. Install it with: 15 | ``` 16 | sudo apt-get install libicu-dev 17 | ``` 18 | Compile the tokenizer: 19 | ``` 20 | g++ tokenizer.cpp -licuuc -o tokenizer 21 | ``` 22 | 23 | ## Run: 24 | Create a file `sample_file.txt` that contains all the text that you want to tokenize. Then run the following command to get the indices of the generated tokens on your `stdout`. 25 | ``` 26 | ./tokenizer sample_file.txt 27 | ``` 28 | 29 | ## Testing: 30 | If you would like to compare this tool’s token IDs to those from the native Python HuggingFace implementation automatically, you can do the following: 31 | 1. (Optionally) Add your test `.txt` files to `tests/input_texts` folder. 32 | 2. Run the following command to see if C++ implementation matches the HuggingFace implementation. 33 | ```bash 34 | python run_tests.py 35 | ``` 36 | If you find an example for which this tool fails, feel free to open an issue, and I'll look into it. -------------------------------------------------------------------------------- /nlohmann/json_fwd.hpp: -------------------------------------------------------------------------------- 1 | // __ _____ _____ _____ 2 | // __| | __| | | | JSON for Modern C++ 3 | // | | |__ | | | | | | version 3.11.2 4 | // |_____|_____|_____|_|___| https://github.com/nlohmann/json 5 | // 6 | // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann 7 | // SPDX-License-Identifier: MIT 8 | 9 | #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ 10 | #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ 11 | 12 | #include // int64_t, uint64_t 13 | #include // map 14 | #include // allocator 15 | #include // string 16 | #include // vector 17 | 18 | // #include 19 | // __ _____ _____ _____ 20 | // __| | __| | | | JSON for Modern C++ 21 | // | | |__ | | | | | | version 3.11.2 22 | // |_____|_____|_____|_|___| https://github.com/nlohmann/json 23 | // 24 | // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann 25 | // SPDX-License-Identifier: MIT 26 | 27 | 28 | 29 | // This file contains all macro definitions affecting or depending on the ABI 30 | 31 | #ifndef JSON_SKIP_LIBRARY_VERSION_CHECK 32 | #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) 33 | #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 2 34 | #warning "Already included a different version of the library!" 35 | #endif 36 | #endif 37 | #endif 38 | 39 | #define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) 40 | #define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum) 41 | #define NLOHMANN_JSON_VERSION_PATCH 2 // NOLINT(modernize-macro-to-enum) 42 | 43 | #ifndef JSON_DIAGNOSTICS 44 | #define JSON_DIAGNOSTICS 0 45 | #endif 46 | 47 | #ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 48 | #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 49 | #endif 50 | 51 | #if JSON_DIAGNOSTICS 52 | #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag 53 | #else 54 | #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS 55 | #endif 56 | 57 | #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 58 | #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp 59 | #else 60 | #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON 61 | #endif 62 | 63 | #ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION 64 | #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 65 | #endif 66 | 67 | // Construct the namespace ABI tags component 68 | #define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b 69 | #define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \ 70 | NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) 71 | 72 | #define NLOHMANN_JSON_ABI_TAGS \ 73 | NLOHMANN_JSON_ABI_TAGS_CONCAT( \ 74 | NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ 75 | NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) 76 | 77 | // Construct the namespace version component 78 | #define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ 79 | _v ## major ## _ ## minor ## _ ## patch 80 | #define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ 81 | NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) 82 | 83 | #if NLOHMANN_JSON_NAMESPACE_NO_VERSION 84 | #define NLOHMANN_JSON_NAMESPACE_VERSION 85 | #else 86 | #define NLOHMANN_JSON_NAMESPACE_VERSION \ 87 | NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ 88 | NLOHMANN_JSON_VERSION_MINOR, \ 89 | NLOHMANN_JSON_VERSION_PATCH) 90 | #endif 91 | 92 | // Combine namespace components 93 | #define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b 94 | #define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ 95 | NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) 96 | 97 | #ifndef NLOHMANN_JSON_NAMESPACE 98 | #define NLOHMANN_JSON_NAMESPACE \ 99 | nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ 100 | NLOHMANN_JSON_ABI_TAGS, \ 101 | NLOHMANN_JSON_NAMESPACE_VERSION) 102 | #endif 103 | 104 | #ifndef NLOHMANN_JSON_NAMESPACE_BEGIN 105 | #define NLOHMANN_JSON_NAMESPACE_BEGIN \ 106 | namespace nlohmann \ 107 | { \ 108 | inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ 109 | NLOHMANN_JSON_ABI_TAGS, \ 110 | NLOHMANN_JSON_NAMESPACE_VERSION) \ 111 | { 112 | #endif 113 | 114 | #ifndef NLOHMANN_JSON_NAMESPACE_END 115 | #define NLOHMANN_JSON_NAMESPACE_END \ 116 | } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ 117 | } // namespace nlohmann 118 | #endif 119 | 120 | 121 | /*! 122 | @brief namespace for Niels Lohmann 123 | @see https://github.com/nlohmann 124 | @since version 1.0.0 125 | */ 126 | NLOHMANN_JSON_NAMESPACE_BEGIN 127 | 128 | /*! 129 | @brief default JSONSerializer template argument 130 | 131 | This serializer ignores the template arguments and uses ADL 132 | ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) 133 | for serialization. 134 | */ 135 | template 136 | struct adl_serializer; 137 | 138 | /// a class to store JSON values 139 | /// @sa https://json.nlohmann.me/api/basic_json/ 140 | template class ObjectType = 141 | std::map, 142 | template class ArrayType = std::vector, 143 | class StringType = std::string, class BooleanType = bool, 144 | class NumberIntegerType = std::int64_t, 145 | class NumberUnsignedType = std::uint64_t, 146 | class NumberFloatType = double, 147 | template class AllocatorType = std::allocator, 148 | template class JSONSerializer = 149 | adl_serializer, 150 | class BinaryType = std::vector, // cppcheck-suppress syntaxError 151 | class CustomBaseClass = void> 152 | class basic_json; 153 | 154 | /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document 155 | /// @sa https://json.nlohmann.me/api/json_pointer/ 156 | template 157 | class json_pointer; 158 | 159 | /*! 160 | @brief default specialization 161 | @sa https://json.nlohmann.me/api/json/ 162 | */ 163 | using json = basic_json<>; 164 | 165 | /// @brief a minimal map-like container that preserves insertion order 166 | /// @sa https://json.nlohmann.me/api/ordered_map/ 167 | template 168 | struct ordered_map; 169 | 170 | /// @brief specialization that maintains the insertion order of object keys 171 | /// @sa https://json.nlohmann.me/api/ordered_json/ 172 | using ordered_json = basic_json; 173 | 174 | NLOHMANN_JSON_NAMESPACE_END 175 | 176 | #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ 177 | -------------------------------------------------------------------------------- /run_tests.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import unittest 3 | import os 4 | from transformers import PreTrainedTokenizerFast 5 | import sys 6 | 7 | class TokenizerTest(unittest.TestCase): 8 | @classmethod 9 | def setUpClass(cls): 10 | # Compile the C++ tokenizer 11 | print("Compiling C++ tokenizer...") 12 | compile_result = subprocess.run( 13 | ["g++", "tokenizer.cpp", "-licuuc", "-o", "tokenizer"], 14 | stdout=subprocess.PIPE, 15 | stderr=subprocess.PIPE, 16 | text=True 17 | ) 18 | 19 | if compile_result.returncode != 0: 20 | print("Compilation failed:", file=sys.stderr) 21 | print(compile_result.stderr, file=sys.stderr) 22 | sys.exit(1) 23 | 24 | print("Compilation successful!") 25 | 26 | # Load Hugging Face tokenizer 27 | cls.python_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json") 28 | cls.cpp_binary_path = "./tokenizer" # Path to compiled C++ tokenizer 29 | cls.input_dir = "tests/input_texts" # Directory containing input text files 30 | 31 | @classmethod 32 | def tearDownClass(cls): 33 | # Clean up compiled binary 34 | if os.path.exists(cls.cpp_binary_path): 35 | try: 36 | os.remove(cls.cpp_binary_path) 37 | except OSError as e: 38 | print(f"Warning: Could not remove compiled binary: {e}", file=sys.stderr) 39 | 40 | def run_cpp_tokenizer(self, input_text): 41 | """ 42 | Run the C++ tokenizer with input text and capture its output. 43 | """ 44 | input_file = "temp_input.txt" 45 | 46 | try: 47 | # Write input text to a temporary file 48 | with open(input_file, "w", encoding="utf-8") as f: 49 | f.write(input_text) 50 | 51 | # Run the C++ tokenizer binary with the input file as an argument 52 | result = subprocess.run( 53 | [self.cpp_binary_path, input_file], 54 | stdout=subprocess.PIPE, 55 | stderr=subprocess.PIPE, 56 | text=True, 57 | ) 58 | if result.returncode != 0: 59 | raise RuntimeError(f"C++ tokenizer failed: {result.stderr}") 60 | 61 | # Parse C++ output 62 | cpp_tokens = [] 63 | in_tokens_section = False 64 | for line in result.stdout.splitlines(): 65 | line = line.strip() 66 | if line == "===== TOKENS START=====": 67 | in_tokens_section = True 68 | elif line == "===== TOKENS END ======": 69 | in_tokens_section = False 70 | elif in_tokens_section: 71 | cpp_tokens.append(int(line)) 72 | 73 | return cpp_tokens 74 | 75 | finally: 76 | # Clean up temporary input file 77 | if os.path.exists(input_file): 78 | os.remove(input_file) 79 | 80 | def run_python_tokenizer(self, input_text): 81 | """ 82 | Run the Python Hugging Face tokenizer. 83 | """ 84 | return self.python_tokenizer.encode(input_text) 85 | 86 | def debug_tokenizer_mismatch(self, input_text, cpp_tokens, python_tokens): 87 | """ 88 | Debug mismatches between C++ and Python tokenizers. 89 | """ 90 | for i, (cpp_token, python_token) in enumerate(zip(cpp_tokens, python_tokens)): 91 | if cpp_token != python_token: 92 | # Find the substring around the mismatch 93 | start = max(0, i - 10) 94 | end = min(len(python_tokens), i + 10) 95 | context_tokens = python_tokens[start:end] 96 | context_string = self.python_tokenizer.decode(context_tokens, skip_special_tokens=False) 97 | 98 | print(f"\nMismatch detected at token index {i}:") 99 | print(f"Context string: \"{context_string}\"") 100 | print(f"C++ Token: {cpp_token} at position {i}") 101 | print(f"Python Token: {python_token} at position {i}") 102 | 103 | # Print token meanings if possible 104 | try: 105 | cpp_token_text = self.python_tokenizer.decode([cpp_token]) 106 | python_token_text = self.python_tokenizer.decode([python_token]) 107 | print(f"C++ Token text: \"{cpp_token_text}\"") 108 | print(f"Python Token text: \"{python_token_text}\"") 109 | except Exception as e: 110 | print(f"Could not decode tokens: {e}") 111 | break 112 | 113 | 114 | def create_test_method(file_name, input_dir): 115 | def test_method(self): 116 | file_path = os.path.join(input_dir, file_name) 117 | 118 | # Read input text from the file 119 | with open(file_path, "r", encoding="utf-8") as f: 120 | input_text = f.read().strip() 121 | 122 | cpp_tokens = self.run_cpp_tokenizer(input_text) 123 | python_tokens = self.run_python_tokenizer(input_text) 124 | 125 | if cpp_tokens != python_tokens: 126 | print(f"\nMismatch in file: {file_name}") 127 | print("Input text:", input_text) 128 | self.debug_tokenizer_mismatch(input_text, cpp_tokens, python_tokens) 129 | 130 | self.assertEqual( 131 | cpp_tokens, 132 | python_tokens, 133 | f"Token outputs do not match for file: {file_name}", 134 | ) 135 | 136 | return test_method 137 | 138 | 139 | # Dynamically add test methods to TokenizerTest 140 | input_dir = "tests/input_texts" 141 | if not os.path.exists(input_dir): 142 | os.makedirs(input_dir) 143 | print(f"Created directory: {input_dir}") 144 | print("Please add your test files to this directory") 145 | sys.exit(1) 146 | 147 | input_files = sorted([f for f in os.listdir(input_dir) if f.endswith(".txt")]) 148 | for idx, file_name in enumerate(input_files): 149 | test_name = f"test_file_{idx + 1}_{file_name.replace('.', '_')}" 150 | test_method = create_test_method(file_name, input_dir) 151 | setattr(TokenizerTest, test_name, test_method) 152 | 153 | if __name__ == "__main__": 154 | unittest.main(verbosity=2) -------------------------------------------------------------------------------- /tests/input_texts/1.txt: -------------------------------------------------------------------------------- 1 | Once upon a time, in a small village nestled at the foot of the mountains, people from all over the world gathered to share their stories. 🌍✨ 2 | 3 | こんにちは、旅人さん!この村には昔から伝わる物語がたくさんあります。時間があるなら、一緒に焚き火を囲んで話を聞いていきませんか?🔥 4 | 5 | "Bonjour, mes amis," said a French storyteller, "Je vais vous raconter l’histoire du renard et du corbeau. Un classique, mais toujours aussi fascinant." 🦊🐦 6 | 7 | ¡Hola, amigos! Aquí, en este pueblo mágico, se celebran las leyendas de nuestros ancestros. Escuchen cómo el sol y la luna bailaban juntos en el cielo. 🌞🌙 8 | 9 | 在这个宁静的村庄,每个人都有自己的故事。有人说,这里的星空下可以听见祖先的声音。你相信这样的传说吗?✨📜 10 | 11 | Привет, мои друзья! Я расскажу вам о русских народных сказках — о Бабе-Яге, Иванушке-дурачке и их приключениях в дремучем лесу. 🌲🎭 12 | 13 | सदियों पहले, इस गाँव में एक संत आया था जिसने प्रेम और सहिष्णुता का पाठ पढ़ाया। उसकी कहानियाँ आज भी हमें प्रेरणा देती हैं। 🕉️💫 14 | 15 | "Once, a wise owl perched upon the tallest oak tree in the forest," the storyteller continued, "and every creature, big or small, came to listen." 🦉🌳 16 | 17 | Meanwhile, children played games across languages and cultures. "123, ready or not, here I come!" shouted one child. "一、二、三,准备好了没?" echoed another. Laughter filled the air. 😂✨ 18 | 19 | --- 20 | 21 | Here’s a riddle for you: 22 | What belongs to you but is used by others? 🤔 23 | Hint: It's something that crosses every language and culture. 🎭 24 | 25 | --- 26 | 27 | Symbols of the world were scattered on the ground: 28 | ☀️🌧️🌈⚡❄️🌿🍎⚓🗿🎨🎵🔑📖✈️🕰️ 29 | Each one held a memory, a story waiting to be unlocked. 30 | 31 | --- 32 | 33 | The villagers believed that every word, symbol, and sound carried a hidden meaning. The stars twinkled above, whispering secrets in languages no one could understand but everyone could feel. 🌌✨ 34 | 35 | "And so," concluded the storyteller, "the journey never truly ends. It continues in the words we share, the lives we touch, and the dreams we chase." 36 | The fire crackled softly, and the night embraced the village with its quiet magic. 🌠 37 | -------------------------------------------------------------------------------- /tests/input_texts/2.txt: -------------------------------------------------------------------------------- 1 | Once upon a time, in a small village nestled at the foot of the mountains, people from all over the world gathered to share their stories. 🌍✨ 2 | 3 | こんにちは、旅人さん!この村には昔から伝わる物語がたくさんあります。時間があるなら、一緒に焚き火を囲んで話を聞いていきませんか?🔥 4 | 5 | "Bonjour, mes amis," said a French storyteller, "Je vais vous raconter l’histoire du renard et du corbeau. Un classique, mais toujours aussi fascinant." 🦊🐦 6 | 7 | ¡Hola, amigos! Aquí, en este pueblo mágico, se celebran las leyendas de nuestros ancestros. Escuchen cómo el sol y la luna bailaban juntos en el cielo. 🌞🌙 8 | 9 | 在这个宁静的村庄,每个人都有自己的故事。有人说,这里的星空下可以听见祖先的声音。你相信这样的传说吗?✨📜 10 | 11 | Привет, мои друзья! Я расскажу вам о русских народных сказках — о Бабе-Яге, Иванушке-дурачке и их приключениях в дремучем лесу. 🌲🎭 12 | 13 | सदियों पहले, इस गाँव में एक संत आया था जिसने प्रेम और सहिष्णुता का पाठ पढ़ाया। उसकी कहानियाँ आज भी हमें प्रेरणा देती हैं। 🕉️💫 14 | 15 | "Once, a wise owl perched upon the tallest oak tree in the forest," the storyteller continued, "and every creature, big or small, came to listen." 🦉🌳 16 | 17 | Meanwhile, children played games across languages and cultures. "123, ready or not, here I come!" shouted one child. "一、二、三,准备好了没?" echoed another. Laughter filled the air. 😂✨ 18 | 19 | --- 20 | 21 | Here’s a riddle for you: 22 | What belongs to you but is used by others? 🤔 23 | Hint: It's something that crosses every language and culture. 🎭 24 | 25 | --- 26 | 27 | Symbols of the world were scattered on the ground: 28 | ☀️🌧️🌈⚡❄️🌿🍎⚓🗿🎨🎵🔑📖✈️🕰️ 29 | Each one held a memory, a story waiting to be unlocked. 30 | 31 | --- 32 | 33 | The villagers believed that every word, symbol, and sound carried a hidden meaning. The stars twinkled above, whispering secrets in languages no one could understand but everyone could feel. 🌌✨ 34 | 35 | "And so," concluded the storyteller, "the journey never truly ends. It continues in the words we share, the lives we touch, and the dreams we chase." 36 | The fire crackled softly, and the night embraced the village with its quiet magic. 🌠 37 | -------------------------------------------------------------------------------- /tests/input_texts/3.txt: -------------------------------------------------------------------------------- 1 | Once upon a time, in a small village nestled at the foot of the mountains, people from all over the world gathered to share their stories. 🌍✨ 2 | 3 | こんにちは、旅人さん!この村には昔から伝わる物語がたくさんあります。時間があるなら、一緒に焚き火を囲んで話を聞いていきませんか?🔥 4 | 5 | "Bonjour, mes amis," said a French storyteller, "Je vais vous raconter l’histoire du renard et du corbeau. Un classique, mais toujours aussi fascinant." 🦊🐦 6 | 7 | "¡Hola, amigos! Aquí, en este pueblo mágico, se celebran las leyendas de nuestros ancestros. Escuchen cómo el sol y la luna bailaban juntos en el cielo." 🌞🌙 8 | 9 | Meanwhile, one of the villagers, a programmer, was busy writing code by the campfire. It looked something like this: 10 | 11 | ```cpp 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | template 20 | class MagicBox { 21 | public: 22 | explicit MagicBox(T value) : value_(std::move(value)) {} 23 | 24 | void display() const { 25 | if constexpr (std::is_same_v) { 26 | std::cout << "String Magic: " << value_ << '\n'; 27 | } else { 28 | std::cout << "Value: " << value_ << '\n'; 29 | } 30 | } 31 | 32 | std::optional getValue() const { 33 | return value_; 34 | } 35 | 36 | private: 37 | T value_; 38 | }; 39 | 40 | int main() { 41 | MagicBox box1(42); 42 | MagicBox box2("Hello, C++20!"); 43 | 44 | auto lambda = [](const auto& box) { 45 | box.display(); 46 | }; 47 | 48 | std::vector>> boxes; 49 | for (int i = 1; i <= 5; ++i) { 50 | boxes.push_back(std::make_unique>(i * 10)); 51 | } 52 | 53 | lambda(box1); 54 | lambda(box2); 55 | 56 | std::cout << "Iterating over boxes:\n"; 57 | for (const auto& b : boxes) { 58 | b->display(); 59 | } 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /tests/input_texts/4.txt: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """Tokenization classes for Bert.""" 16 | 17 | 18 | import collections 19 | import os 20 | import unicodedata 21 | from typing import List, Optional, Tuple 22 | 23 | from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace 24 | from ...utils import logging 25 | 26 | 27 | logger = logging.get_logger(__name__) 28 | 29 | VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"} 30 | 31 | 32 | def load_vocab(vocab_file): 33 | """Loads a vocabulary file into a dictionary.""" 34 | vocab = collections.OrderedDict() 35 | with open(vocab_file, "r", encoding="utf-8") as reader: 36 | tokens = reader.readlines() 37 | for index, token in enumerate(tokens): 38 | token = token.rstrip("\n") 39 | vocab[token] = index 40 | return vocab 41 | 42 | 43 | def whitespace_tokenize(text): 44 | """Runs basic whitespace cleaning and splitting on a piece of text.""" 45 | text = text.strip() 46 | if not text: 47 | return [] 48 | tokens = text.split() 49 | return tokens 50 | 51 | 52 | class BertTokenizer(PreTrainedTokenizer): 53 | r""" 54 | Construct a BERT tokenizer. Based on WordPiece. 55 | 56 | This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to 57 | this superclass for more information regarding those methods. 58 | 59 | Args: 60 | vocab_file (`str`): 61 | File containing the vocabulary. 62 | do_lower_case (`bool`, *optional*, defaults to `True`): 63 | Whether or not to lowercase the input when tokenizing. 64 | do_basic_tokenize (`bool`, *optional*, defaults to `True`): 65 | Whether or not to do basic tokenization before WordPiece. 66 | never_split (`Iterable`, *optional*): 67 | Collection of tokens which will never be split during tokenization. Only has an effect when 68 | `do_basic_tokenize=True` 69 | unk_token (`str`, *optional*, defaults to `"[UNK]"`): 70 | The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this 71 | token instead. 72 | sep_token (`str`, *optional*, defaults to `"[SEP]"`): 73 | The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for 74 | sequence classification or for a text and a question for question answering. It is also used as the last 75 | token of a sequence built with special tokens. 76 | pad_token (`str`, *optional*, defaults to `"[PAD]"`): 77 | The token used for padding, for example when batching sequences of different lengths. 78 | cls_token (`str`, *optional*, defaults to `"[CLS]"`): 79 | The classifier token which is used when doing sequence classification (classification of the whole sequence 80 | instead of per-token classification). It is the first token of the sequence when built with special tokens. 81 | mask_token (`str`, *optional*, defaults to `"[MASK]"`): 82 | The token used for masking values. This is the token used when training this model with masked language 83 | modeling. This is the token which the model will try to predict. 84 | tokenize_chinese_chars (`bool`, *optional*, defaults to `True`): 85 | Whether or not to tokenize Chinese characters. 86 | 87 | This should likely be deactivated for Japanese (see this 88 | [issue](https://github.com/huggingface/transformers/issues/328)). 89 | strip_accents (`bool`, *optional*): 90 | Whether or not to strip all accents. If this option is not specified, then it will be determined by the 91 | value for `lowercase` (as in the original BERT). 92 | """ 93 | 94 | vocab_files_names = VOCAB_FILES_NAMES 95 | 96 | def __init__( 97 | self, 98 | vocab_file, 99 | do_lower_case=True, 100 | do_basic_tokenize=True, 101 | never_split=None, 102 | unk_token="[UNK]", 103 | sep_token="[SEP]", 104 | pad_token="[PAD]", 105 | cls_token="[CLS]", 106 | mask_token="[MASK]", 107 | tokenize_chinese_chars=True, 108 | strip_accents=None, 109 | **kwargs, 110 | ): 111 | if not os.path.isfile(vocab_file): 112 | raise ValueError( 113 | f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained" 114 | " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`" 115 | ) 116 | self.vocab = load_vocab(vocab_file) 117 | self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()]) 118 | self.do_basic_tokenize = do_basic_tokenize 119 | if do_basic_tokenize: 120 | self.basic_tokenizer = BasicTokenizer( 121 | do_lower_case=do_lower_case, 122 | never_split=never_split, 123 | tokenize_chinese_chars=tokenize_chinese_chars, 124 | strip_accents=strip_accents, 125 | ) 126 | self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token)) 127 | 128 | 129 | super().__init__( 130 | do_lower_case=do_lower_case, 131 | do_basic_tokenize=do_basic_tokenize, 132 | never_split=never_split, 133 | unk_token=unk_token, 134 | sep_token=sep_token, 135 | pad_token=pad_token, 136 | cls_token=cls_token, 137 | mask_token=mask_token, 138 | tokenize_chinese_chars=tokenize_chinese_chars, 139 | strip_accents=strip_accents, 140 | **kwargs, 141 | ) 142 | 143 | @property 144 | def do_lower_case(self): 145 | return self.basic_tokenizer.do_lower_case 146 | 147 | @property 148 | def vocab_size(self): 149 | return len(self.vocab) 150 | 151 | def get_vocab(self): 152 | return dict(self.vocab, **self.added_tokens_encoder) 153 | 154 | def _tokenize(self, text, split_special_tokens=False): 155 | split_tokens = [] 156 | if self.do_basic_tokenize: 157 | #print(self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens if not split_special_tokens else None)) 158 | for token in self.basic_tokenizer.tokenize( 159 | text, never_split=self.all_special_tokens if not split_special_tokens else None 160 | ): 161 | # If the token is part of the never_split set 162 | if token in self.basic_tokenizer.never_split: 163 | split_tokens.append(token) 164 | else: 165 | split_tokens += self.wordpiece_tokenizer.tokenize(token) 166 | else: 167 | split_tokens = self.wordpiece_tokenizer.tokenize(text) 168 | return split_tokens 169 | 170 | def _convert_token_to_id(self, token): 171 | """Converts a token (str) in an id using the vocab.""" 172 | return self.vocab.get(token, self.vocab.get(self.unk_token)) 173 | 174 | def _convert_id_to_token(self, index): 175 | """Converts an index (integer) in a token (str) using the vocab.""" 176 | return self.ids_to_tokens.get(index, self.unk_token) 177 | 178 | def convert_tokens_to_string(self, tokens): 179 | """Converts a sequence of tokens (string) in a single string.""" 180 | out_string = " ".join(tokens).replace(" ##", "").strip() 181 | return out_string 182 | 183 | def build_inputs_with_special_tokens( 184 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None 185 | ) -> List[int]: 186 | """ 187 | Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and 188 | adding special tokens. A BERT sequence has the following format: 189 | 190 | - single sequence: `[CLS] X [SEP]` 191 | - pair of sequences: `[CLS] A [SEP] B [SEP]` 192 | 193 | Args: 194 | token_ids_0 (`List[int]`): 195 | List of IDs to which the special tokens will be added. 196 | token_ids_1 (`List[int]`, *optional*): 197 | Optional second list of IDs for sequence pairs. 198 | 199 | Returns: 200 | `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. 201 | """ 202 | if token_ids_1 is None: 203 | return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] 204 | cls = [self.cls_token_id] 205 | sep = [self.sep_token_id] 206 | return cls + token_ids_0 + sep + token_ids_1 + sep 207 | 208 | def get_special_tokens_mask( 209 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False 210 | ) -> List[int]: 211 | """ 212 | Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding 213 | special tokens using the tokenizer `prepare_for_model` method. 214 | 215 | Args: 216 | token_ids_0 (`List[int]`): 217 | List of IDs. 218 | token_ids_1 (`List[int]`, *optional*): 219 | Optional second list of IDs for sequence pairs. 220 | already_has_special_tokens (`bool`, *optional*, defaults to `False`): 221 | Whether or not the token list is already formatted with special tokens for the model. 222 | 223 | Returns: 224 | `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. 225 | """ 226 | 227 | if already_has_special_tokens: 228 | return super().get_special_tokens_mask( 229 | token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True 230 | ) 231 | 232 | if token_ids_1 is not None: 233 | return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1] 234 | return [1] + ([0] * len(token_ids_0)) + [1] 235 | 236 | def create_token_type_ids_from_sequences( 237 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None 238 | ) -> List[int]: 239 | """ 240 | Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence 241 | pair mask has the following format: 242 | 243 | ``` 244 | 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 245 | | first sequence | second sequence | 246 | ``` 247 | 248 | If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s). 249 | 250 | Args: 251 | token_ids_0 (`List[int]`): 252 | List of IDs. 253 | token_ids_1 (`List[int]`, *optional*): 254 | Optional second list of IDs for sequence pairs. 255 | 256 | Returns: 257 | `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s). 258 | """ 259 | sep = [self.sep_token_id] 260 | cls = [self.cls_token_id] 261 | if token_ids_1 is None: 262 | return len(cls + token_ids_0 + sep) * [0] 263 | return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] 264 | 265 | def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: 266 | index = 0 267 | if os.path.isdir(save_directory): 268 | vocab_file = os.path.join( 269 | save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] 270 | ) 271 | else: 272 | vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory 273 | with open(vocab_file, "w", encoding="utf-8") as writer: 274 | for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]): 275 | if index != token_index: 276 | logger.warning( 277 | f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." 278 | " Please check that the vocabulary is not corrupted!" 279 | ) 280 | index = token_index 281 | writer.write(token + "\n") 282 | index += 1 283 | return (vocab_file,) 284 | 285 | 286 | class BasicTokenizer(object): 287 | """ 288 | Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.). 289 | 290 | Args: 291 | do_lower_case (`bool`, *optional*, defaults to `True`): 292 | Whether or not to lowercase the input when tokenizing. 293 | never_split (`Iterable`, *optional*): 294 | Collection of tokens which will never be split during tokenization. Only has an effect when 295 | `do_basic_tokenize=True` 296 | tokenize_chinese_chars (`bool`, *optional*, defaults to `True`): 297 | Whether or not to tokenize Chinese characters. 298 | 299 | This should likely be deactivated for Japanese (see this 300 | [issue](https://github.com/huggingface/transformers/issues/328)). 301 | strip_accents (`bool`, *optional*): 302 | Whether or not to strip all accents. If this option is not specified, then it will be determined by the 303 | value for `lowercase` (as in the original BERT). 304 | do_split_on_punc (`bool`, *optional*, defaults to `True`): 305 | In some instances we want to skip the basic punctuation splitting so that later tokenization can capture 306 | the full context of the words, such as contractions. 307 | """ 308 | 309 | def __init__( 310 | self, 311 | do_lower_case=True, 312 | never_split=None, 313 | tokenize_chinese_chars=True, 314 | strip_accents=None, 315 | do_split_on_punc=True, 316 | ): 317 | if never_split is None: 318 | never_split = [] 319 | self.do_lower_case = do_lower_case 320 | self.never_split = set(never_split) 321 | self.tokenize_chinese_chars = tokenize_chinese_chars 322 | self.strip_accents = strip_accents 323 | self.do_split_on_punc = do_split_on_punc 324 | 325 | def tokenize(self, text, never_split=None): 326 | """ 327 | Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer. 328 | 329 | Args: 330 | never_split (`List[str]`, *optional*) 331 | Kept for backward compatibility purposes. Now implemented directly at the base class level (see 332 | [`PreTrainedTokenizer.tokenize`]) List of token not to split. 333 | """ 334 | # union() returns a new set by concatenating the two sets. 335 | never_split = self.never_split.union(set(never_split)) if never_split else self.never_split 336 | text = self._clean_text(text) 337 | 338 | # This was added on November 1st, 2018 for the multilingual and Chinese 339 | # models. This is also applied to the English models now, but it doesn't 340 | # matter since the English models were not trained on any Chinese data 341 | # and generally don't have any Chinese data in them (there are Chinese 342 | # characters in the vocabulary because Wikipedia does have some Chinese 343 | # words in the English Wikipedia.). 344 | if self.tokenize_chinese_chars: 345 | text = self._tokenize_chinese_chars(text) 346 | # prevents treating the same character with different unicode codepoints as different characters 347 | unicode_normalized_text = unicodedata.normalize("NFC", text) 348 | orig_tokens = whitespace_tokenize(unicode_normalized_text) 349 | split_tokens = [] 350 | for token in orig_tokens: 351 | if token not in never_split: 352 | if self.do_lower_case: 353 | token = token.lower() 354 | if self.strip_accents is not False: 355 | token = self._run_strip_accents(token) 356 | elif self.strip_accents: 357 | token = self._run_strip_accents(token) 358 | split_tokens.extend(self._run_split_on_punc(token, never_split)) 359 | 360 | output_tokens = whitespace_tokenize(" ".join(split_tokens)) 361 | return output_tokens 362 | 363 | def _run_strip_accents(self, text): 364 | """Strips accents from a piece of text.""" 365 | text = unicodedata.normalize("NFD", text) 366 | output = [] 367 | for char in text: 368 | cat = unicodedata.category(char) 369 | if cat == "Mn": 370 | continue 371 | output.append(char) 372 | return "".join(output) 373 | 374 | def _run_split_on_punc(self, text, never_split=None): 375 | """Splits punctuation on a piece of text.""" 376 | if not self.do_split_on_punc or (never_split is not None and text in never_split): 377 | return [text] 378 | chars = list(text) 379 | i = 0 380 | start_new_word = True 381 | output = [] 382 | while i < len(chars): 383 | char = chars[i] 384 | if _is_punctuation(char): 385 | output.append([char]) 386 | start_new_word = True 387 | else: 388 | if start_new_word: 389 | output.append([]) 390 | start_new_word = False 391 | output[-1].append(char) 392 | i += 1 393 | 394 | return ["".join(x) for x in output] 395 | 396 | def _tokenize_chinese_chars(self, text): 397 | """Adds whitespace around any CJK character.""" 398 | output = [] 399 | for char in text: 400 | cp = ord(char) 401 | if self._is_chinese_char(cp): 402 | output.append(" ") 403 | output.append(char) 404 | output.append(" ") 405 | else: 406 | output.append(char) 407 | return "".join(output) 408 | 409 | def _is_chinese_char(self, cp): 410 | """Checks whether CP is the codepoint of a CJK character.""" 411 | # This defines a "chinese character" as anything in the CJK Unicode block: 412 | # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) 413 | # 414 | # Note that the CJK Unicode block is NOT all Japanese and Korean characters, 415 | # despite its name. The modern Korean Hangul alphabet is a different block, 416 | # as is Japanese Hiragana and Katakana. Those alphabets are used to write 417 | # space-separated words, so they are not treated specially and handled 418 | # like the all of the other languages. 419 | if ( 420 | (cp >= 0x4E00 and cp <= 0x9FFF) 421 | or (cp >= 0x3400 and cp <= 0x4DBF) # 422 | or (cp >= 0x20000 and cp <= 0x2A6DF) # 423 | or (cp >= 0x2A700 and cp <= 0x2B73F) # 424 | or (cp >= 0x2B740 and cp <= 0x2B81F) # 425 | or (cp >= 0x2B820 and cp <= 0x2CEAF) # 426 | or (cp >= 0xF900 and cp <= 0xFAFF) 427 | or (cp >= 0x2F800 and cp <= 0x2FA1F) # 428 | ): # 429 | return True 430 | 431 | return False 432 | 433 | def _clean_text(self, text): 434 | """Performs invalid character removal and whitespace cleanup on text.""" 435 | output = [] 436 | for char in text: 437 | cp = ord(char) 438 | if cp == 0 or cp == 0xFFFD or _is_control(char): 439 | continue 440 | if _is_whitespace(char): 441 | output.append(" ") 442 | else: 443 | output.append(char) 444 | return "".join(output) 445 | 446 | 447 | class WordpieceTokenizer(object): 448 | """Runs WordPiece tokenization.""" 449 | 450 | def __init__(self, vocab, unk_token, max_input_chars_per_word=100): 451 | self.vocab = vocab 452 | self.unk_token = unk_token 453 | self.max_input_chars_per_word = max_input_chars_per_word 454 | 455 | def tokenize(self, text): 456 | """ 457 | Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform 458 | tokenization using the given vocabulary. 459 | 460 | For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`. 461 | 462 | Args: 463 | text: A single token or whitespace separated tokens. This should have 464 | already been passed through *BasicTokenizer*. 465 | 466 | Returns: 467 | A list of wordpiece tokens. 468 | """ 469 | 470 | output_tokens = [] 471 | for token in whitespace_tokenize(text): 472 | chars = list(token) 473 | if len(chars) > self.max_input_chars_per_word: 474 | output_tokens.append(self.unk_token) 475 | continue 476 | 477 | is_bad = False 478 | start = 0 479 | sub_tokens = [] 480 | while start < len(chars): 481 | end = len(chars) 482 | cur_substr = None 483 | while start < end: 484 | substr = "".join(chars[start:end]) 485 | if start > 0: 486 | substr = "##" + substr 487 | if substr in self.vocab: 488 | cur_substr = substr 489 | break 490 | end -= 1 491 | if cur_substr is None: 492 | is_bad = True 493 | break 494 | sub_tokens.append(cur_substr) 495 | start = end 496 | 497 | if is_bad: 498 | output_tokens.append(self.unk_token) 499 | else: 500 | output_tokens.extend(sub_tokens) 501 | return output_tokens 502 | -------------------------------------------------------------------------------- /tests/input_texts/5.txt: -------------------------------------------------------------------------------- 1 | 王明:这是什么? 2 | 李红:这是书。 3 | 王明:那是什么? 4 | 李红:那是钢笔。 5 | 王明:那是杂志吗? 6 | 李红:不,那不是杂志。那是字典。 7 | 8 | Wáng Míng: Zhè shì shěnme? 9 | Lǐ Hóng: Zhè shì shū. 10 | Wáng Míng: Nà shì shěnme? 11 | Lǐ Hóng: Nà shì gāngbǐ. 12 | Wáng Míng: Nà shì zázhì ma? 13 | Lǐ Hóng: Bù, nà bùshì zázhì. Nà shì zìdiǎn. 14 | 15 | Text 2 16 | Dialogue 1 17 | Duration: 14 seconds.0:14 18 | 王明是中国人。 19 | 王明是学生。 20 | 史密斯是美国人。 21 | 史密斯是王明的朋友。 22 | 史密斯是律师。 23 | 24 | Wáng Míng shì Zhōngguórén. 25 | Wáng Míng shì xuéshēng. 26 | Shīmìsī shì Měiguórén. 27 | Shīmìsī shì Wángmíng de péngyǒu. 28 | Shīmìsī shì lǜshī. 29 | 30 | Vocabulary 31 | 王明 (Wáng Míng) 32 | n. Wang Ming [personal name] [Wang= Family Name, Ming=First name/Personal name] 33 | 李红/李紅 (Lǐ Hóng) 34 | n. Li Hong [personal name] [Li= Family Name, Hong= First/Personal name] 35 | 这/這 (zhè) 36 | pron. this 37 | 是 (shì) 38 | v. to be (is/are) 39 | 什么/甚麼 (Mainland shénme 40 | and Taiwan shěme) 41 | pron. what 42 | 那 (nà) 43 | pron. that 44 | 笔 (bǐ) 45 | n. pen; a generic term for all pens 46 | 钢笔 (gāngbǐ) 47 | n. fountain pen 48 | 铅笔 (qiānbǐ) 49 | n. pencil 50 | 原子笔 (yuánzǐbǐ) 51 | n. ballpoint pen 52 | 毛笔 (máobǐ) 53 | n. brush (calligraphy pen) 54 | 杂志 (zázhì) 55 | n. magazine 56 | 报纸 (bàozhī) 57 | n. newspaper 58 | 书本 (shūběn) 59 | n. book 60 | 传单 (chuándān) 61 | n. pamphlet 62 | 吗 (ma) 63 | final interrogative particle used 64 | to form a question sentence 65 | 不 (bù) 66 | adv. no 67 | 字典 (zìdiǎn) 68 | n. dictionary 69 | 人 (rén) 70 | n. person/people 71 | 中国人 (Zhōngguórén) 72 | n. PRC Chinese (中国:China 人:people) 73 | 外国人 (Wàiguórén) 74 | n. Foreigners (外:Outside 国:Country 人:people) 75 | 日本人 (Rìběnrén) 76 | n. Japanese (日本:Japan 人:people) 77 | 英国人 (Yīngguórén) 78 | n. British (英国:United Kingdom 人:people) 79 | 新加坡人 (Xīnjiāpōrén) 80 | n. Singaporean (新加坡:Singapore) 81 | 美国人 (měiguórén) 82 | n. American 83 | 学生 (xuéshēng) 84 | n. student 85 | 老师 (lǎoshī) 86 | n. teacher 87 | 校长 (xiàozhǎng) 88 | n. principal 89 | 史密斯 (Shǐmìsī) 90 | n. Smith 91 | 美国人 (Měiguórén) 92 | n. American 93 | 朋友 (péngyǒu) 94 | n. friend 95 | 律师 (lǜshī) 96 | n. lawyer 97 | 笔记本/筆記本 (bǐjìběn) 98 | 铅笔/鉛筆 (qiānbǐ) 99 | 英国人/英國人 (Yīngguórén) 100 | 法国人/法國人 (Fǎguórén) 101 | 报纸/報紙 (bàozhǐ) 102 | 老师/老師 (lǎoshī) 103 | 作家 (zuòjiā) 104 | n. notepads 105 | n. pencil 106 | n. British people 107 | n. French people 108 | n. newspaper 109 | n. teacher 110 | n. writer 111 | 112 | Stroke orders 113 | 114 | 115 | 116 | More stroke orders will be added if it's helpful. 117 | 118 | Grammar 119 | Chinese Names 120 | In Chinese names, the family name comes before the given name. Family names are passed down paternally and usually have only one character. Chinese given names are usually two characters long, but may also be one character. 121 | Hence a man called 王明 (Wáng Míng) is addressed as Mr. Wang, not Mr. Ming. A woman called 李红 (Lǐ Hóng) is addressed as Mrs./Miss Li. 122 | 123 | However, if the person has a western personal name, it is presented in the GIVEN-NAME/FAMILY-NAME format, following the Western convention. Hence if 李红 (Lǐ Hóng) has a western-style personal name of Mary, she is usually introduced as "Mary Li" and not "Li Mary" 124 | 125 | 126 | 127 | In this lesson, we learn how to say "something is something" in Chinese. The first thing you need to know is that the sentence structure of Chinese is very similar to that of English in that they both follow the pattern of Subject-Verb-Object (SVO). But unlike many Western languages, verbs in Chinese aren't conjugated and noun and adjective endings don't change. They are never affected by things such as time or person. 128 | 129 | 这(/那)是什么? 130 | This sentence means "What's this/that?": 131 | 132 | 这是什么?(What's this?) 133 | 那是什么?(What's that?) 134 | The sentences, if broken down literally, shows that the ordering of words differs in English and Chinese: 135 | 136 | 这/那 是 什么 ? 137 | this/that is what ? 138 | The order of the sentences may seem a little bit tricky, but don't worry about that, we will discuss this later. 139 | 140 | A 是 B 141 | This sentence means "A is B." 142 | 143 | "是" (shì), the equational verb to be, can be used as the English is or equals. When used in a simple Subject-Verb-Object sentence, the subject defines the object. Since Chinese verbs never change, no other forms for shì exist such as was or am in English. Also, articles like a and the are absent in Chinese. They are not translated. 144 | 145 | For example: 146 | 147 | 这是书 (zhè shì shū): this is (a) book. 148 | 那是杂志 (nà shì zázhì): that is (a) magazine. 149 | A 不是 B 150 | This sentence means "A is not B." in which shì is negated when preceded by "不" (bu). "不" literally means "no", "not". 151 | 152 | For example: 153 | 154 | 这不是书 (zhè bú shì shū): this is not (a) book. 155 | Now, we come back to the "what's this/that?" questions. We already see that the order is a bit tricky comparing to the English question order. But comparing to the latter pattern "A 是 B", we find the similarity: their orders are identically the same. In fact, like particles, question words make statements into questions without changing the order of the sentence. To make one, simply substitute the QW in where the subject would be in the answer. 156 | 157 | Comparison: 158 | 159 | 这是书。(This is (a) book.) 160 | 这是什么?(This is what?) 161 | 那是杂志。(That is (a) magazine.) 162 | 那是什么?(That is what?) 163 | 吗 164 | "吗"(ma) is a final interrogative particle used to form a question sentence. Adding this character at the end of a statement transforms the sentence into a question. 165 | 166 | Example 1: 167 | 168 | 这是书 (zhè shì shū)。(This is (a) book.) 169 | ↓ 170 | 这是书吗 (zhè shì shū ma)?(Is this (a) book?) 171 | Example 2: 172 | 173 | 这不是杂志 (zhè bú shì zázhì)。(This is not (a) magazine.) 174 | ↓ 175 | 这不是杂志吗(zhè bú shì zázhì ma)?(Isn't this (a) magazine?) 176 | 是/不 177 | "是" (shì) can be used to answer a simple yes/no question. In this case, "是" means yes, whilst "不" (bú) or "不是" (bú shì) means no (literally, not is). 178 | 179 | How to answer yes/no questions correctly in Chinese? Usually, it's the same as in English, but pay attention if the questions are negative, like "Isn't this a book?". In Chinese, you answer to the questions, not the fact. If the question itself is a negative answer, use "不是" or simply "不", vice versa. For example: 180 | 181 | A: 这不是书吗?zhè bú shì shū ma? (Isn't this (a) book? = This is not a book, right?) 182 | B: 是,这不是书。shì, zhè bú shì shū. (No, this is not (a) book. = You are right; this is not a book.) 183 | B: 不,这是书。bù, zhè shì shū. (Yes, this is (a) book. = You're wrong; this is a book.) 184 | A asks if that's a book in a negative way. If the object is not a book, you should nevertheless approve A's saying first. So we use "是" to acknowledge that A is correct, and then say "this is not (a) book" to emphasis A is right; In the case of that is a book, you should deny A's saying first, using "不" (no) to point out A is wrong, then make a new statement by noting that "这是书" (this is (a) book). One more example: 185 | 186 | 他今天晚上不来参加宴会了,对吗?(He's not going to the party tonight, is he?) 187 | 不,他肯定要来。(Yes, he's definitely coming.) 188 | 是 啊,他很忙呢!(No, he's so busy!) 189 | 的 190 | Character "的" (de) indicates that the previous word has possession of the next one. In English it functions like 's or like the word of but with the position of possessor and possessee switched. For example: 191 | 192 | 史密斯(Shǐmìsī)的书(shū: book) <-> Smith's book 193 | 王明的钢笔 <-> Wang Ming's pen 194 | 约翰** (Yuēhàn: John)的朋友** (péngyǒu: friend) <-> John's friend or a friend of John's 195 | Exercise 196 | Replace the underline words, and practice. 197 | 史密斯是美国人。 198 | 英国人 199 | 法国人 200 | 这不是杂志。 201 | 书 202 | 笔记本* 203 | 铅笔 204 | Replace the underline words, and then answer the questions with both positive answers and negative answers. 205 | Example: 206 | 史密斯是法国人吗? 207 | 是,史密斯是法国人。 208 | 不,史密斯不是法国人。 209 | 那是杂志吗? 210 | 钢笔 211 | 铅笔 212 | 报纸* 213 | 王明是学生吗? 214 | 律师 215 | 老师* 216 | 作家* 217 | Translate the following English into Chinese. 218 | Wang Ming is not a teacher. Wang Ming is a student. Wang Ming is a Chinese. Wang Ming is not an American. 219 | Answer(答):Wang Ming不是老師。Wang Ming是學生。Wang Ming是中國人。Wang Ming不是美國人。 220 | Smith is a lawyer. Smith is not a writer. Smith is an American. Smith is not a French. 221 | Answer(答):Smith是律師。Smith不是作家。Smith是美國人。Smith不是法國人。 222 | This is Smith's book. That is Wang Ming's pen. 223 | Answer(答):這是Smith的書。那是Wang Ming的筆。 224 | Further reading 225 | Read the following article, and then answer the questions in Chinese. 226 | 227 | 你好(nǐhǎo, hello),我(wǒ, I)是王明。我是学生,我是中国人。这是史密斯。史密斯是我的1 朋友,史密斯是律师。那是史密斯的妻子(qīzi, wife),安娜(Ana)。安娜是我的英语(yīngyǔ, English language)老师。 228 | 1."我 的" means "my", we will discuss this in the next lesson. 229 | Questions: 230 | 231 | Who is "I"? 232 | What does Smith do? 233 | Who is Ana? 234 | What does Ana do? 235 | Useful phrases 236 | Greetings. How to greet people in Chinese? 237 | 你好!(nǐhǎo): Hello! 238 | 嗨!(hài): Hi! 239 | 幸會 (xìnghuì) Great to meet you! 240 | 你吃过饭了吗?(nǐ chīguofàn le ma?): Have you had your meal? (This is a causal greeting between friends etc. But it doesn't mean you are asked to a dinner! Another derivation of this phrase commonly used in Beijing is "你吃了吗?") 241 | 再见。(zàijiàn): Goodbye 242 | 拜拜。(bāibāi): Bye-bye 243 | 回头见。(huítóujiàn): See you later. 244 | Translation for the text 245 | Chinese characters Sentences breakdown English translation 246 | Text 1 247 | 王明:这是什么? 248 | (王明:這是什麼?) 249 | 李红:这是书。 250 | (李紅:這是書。) 251 | 王明:那是什么? 252 | (王明:那是什麼?) 253 | 李红:那是钢笔。 254 | (李紅:那是鋼筆。) 255 | 王明:那是杂志吗? 256 | (王明:那是雜誌嗎?) 257 | 李红:不,那不是杂志。那是字典。 258 | (李紅:不,那不是雜誌。那是字典。) 259 | 260 | Text 1 261 | Wang Ming: This is what? 262 | Li Hong: This is book. 263 | Wang Ming: That is what? 264 | Li Hong: That is pen. 265 | Wang Ming: That is magazine (final interrogative particle)? 266 | Li Hong: No, that not is magazine, this is dictionary. 267 | 268 | Text 1 269 | Wang Ming: What's this? 270 | Li Hong: This is a book. 271 | Wang Ming: What's that? 272 | Li Hong: That's a pen. 273 | Wang Ming: Is this a magazine? 274 | Li Hong: No, that's not a magazine. That's a dictionary. 275 | 276 | Text 2 277 | 王明是中国人。 278 | 王明是学生。 279 | 史密斯是美国人。 280 | 史密斯是王明 的 朋友。 281 | 史密斯是律师。 282 | 283 | Text 2 284 | Wang Ming is Chinese. 285 | Wang Ming is student. 286 | Smith is American. 287 | Smith is Wang Ming's friend. 288 | Smith is lawyer. 289 | 290 | Text 2 291 | Wang Ming is a Chinese. 292 | Wang Ming is a student. 293 | Smith is an American. 294 | Smith is Wang Ming's friend. 295 | Smith is a lawyer. -------------------------------------------------------------------------------- /tests/input_texts/6.txt: -------------------------------------------------------------------------------- 1 | 残内アヨ探45過ぐばど式待ノ権抜にんふ購待ふ日案ム持熊じリび比妨フク玲給投ケナ整哲分ヨカワ入進ンラぞ金治るうほめ焼披暑棚豆ほ。母リほド説2済どゆ迎決メ下術カテクシ伴球コ祉関ケキ事圧ラセ施健イごせ紀設世ふ局年ニホハソ前力ッ期情け際無ナ禁選老ごらこ査催が。県とん梨75丘甘礼窓6誘レネタイ兵定浦こ棒届イり健監投はン文制得リ曲黒やひ試8山材ゆがく。 2 | 3 | 投ルょ局木ドらフ転携事ぴルだ約代ゃンうろ土4覧でっ方間アネサ載82何ふら載間テミハ泉4本二っレゃを。面掲用わやべ通露たを身求ヱムルリ楽左ノヨセロ傷索ラ応賞ヒト解捕け車静コヒ有条むッごち態民様オ交図キワユツ発催もばめ。作ノヒ勢朝タヘオニ化限もりづく用名ヨリワネ当見ドせえ図性まスは米3公ヱモソ壁士止ロナレオ員初ヒネルレ夕意展あ療米具世ん野左ヘオミモ隆7継みばリわ者犯スずいの個喰杜椿ゃれた。 4 | 5 | 昨きはぞ官読スぶぎ録日圧ゅとを手応ふれイ事馬俊セキ変為なぐル色講セテ女掲ゆみ司1意まやク能4描災盗仁スく。棋ヲ気面ネヌオカ食東北っらむへ済毎てをえリ門微ぶレぱ器暮ろれひ伸時メシチハ違球スワセム畑夜ひラなっ実76半すだ鳥未汚犬ふ。生四ヒシチセ誰人ソマ仕損ヱムセ聞病ば能課コルニ対6視氏むすゆず財情りひだリ道員宿ノキコ少氏ソロ蹴保析毛や。 6 | 7 | 出うす了升ロサ元足こ員賞ばへせむ哲56康活リヘネミ文億43争フハラヱ番火れみき断競が議約図広ア定昨あにま難掘モヨヱ題語るは入切チツリセ海小レドぞょ挙準ざぼゃぽ。者中ルヒカ案険ヘセナタ多機きる止額ぱに険立ミハマ村領すょざ庫好員暮ッさしで新子ヘ総月べだ座満ゆもルッ養68今エヘチリ境正つびさル経見ウカ紙断イ急5唆寛怪沈としべフ。 8 | 9 | 2供ツナテヘ施林ねドに停西づ思6載馬いん機容ナトタ調将ヲリサ号鼻ばッぼえ養再ホク初要茨ック稚者まかク手唱ウ切欧聞ドン供記座ぱたド遣軍ひン題沢温レン。7戦ゅぶ分君企成ミコニ中目け馬当ア刊主フニサ録児ずーなび無島ンち遺整チ性産へを数条ルウク不霊こレろ付方ハ州3乗一フたン。 10 | 11 | 34呂ムソ断本ふレご名着加獲とまげ編毎昔ロセ童論闇君りべす策面ロカナコ密生すれク帯状オツ覚首純享凡っ。来テ見掲のーむ性新ぶ合核だねゆわ載円ヱスカヤ取案ぼ産友のみフ愛面ばすひ経91意せを持核がぐこ容木クやほ危転ぐ倒磨ーなレが帯入台ち。安う任前億き近月済キメマ関巨ヌウネ新線ニ影年セ億響レネワト行8養読ロク使速ナ調鳥い的3治ルカ郎際ミホ子抽ちぞひ。 12 | 13 | 絡感せぽあ最調が合発ノ容抗も資葉てう牛般之サクレ街撮エウ難由ヲスウ題間ずクふ伊堀間ひぞっレ詰心ミヱカノ害分媛緒波ばぐッ。2平ムエ方首ネラナ年都ノ成山そぼ想督元ちへ方流ロヨ児5和まレけぶ村愛っけゆゃ準年性ちいレフ無物ト社86抱診露7事あっる夫比の営乱げえッり。従名レサ応球6世ト理月実てきごぼ職童れめ社地やイゆ約員ひきり通旬トネイ講新冨コチヨ覚作けぴ零治カニ視議果ょ。 14 | 15 | 2自来げせ傾産もきスづ亡期ぼ統作ヤ条員ふば室票ヲヘヨハ競物ろこど日顔みねて野響クリキニ査歩シ国便岐盟共で。改エリ面8宅ぴし賛暮セ輪28陛いぼべ入無沿いそぎ越婚げじト項郁ルテ購推男フぎふド遠客意トアヱエ岐95始竜6刊はうつ島語きでぼず来派止色埼リらもぼ。競和強ミ考属懸ホヒツト閣案のてた郎月ノオユ袋同注げ抽月ワケチ縮東ろよ歓提ヌ宿牲人アニヲキ治康ヒヌノ任缶や愛納時げ。 16 | 17 | 通そしン断報進ツアム店掛ょ匠試れげ側録ざなゆで更5相表こけ長十と定70深そわひ砂7軽ぞト土画ホ必細ふう銃型ホ体趣カ万6聞チ百長形傘ゅ。万フキレ触最ちやれよ穫夏旅のー慎謝トソチ回装ヨモノ深賞でフず受盗症るこぞ現果マヘ夢態ソラ要愛イ越売輪ツヤ害後順ムクスヤ続覧ぴ物調討とや入囲県底しほ。 18 | 19 | 掲ふめフか際門ねざはの込日ノナエ権第ヱナユ萩告ドたやリ天知ワウラル儀央チシイテ局被ぞ済賞探ロテミ増速74供ろ断県じ催唱イ理索づゃぐ変遊ユオトハ降歩ゃレの。延エ傷幼ぞ暮多経ハヌ辞動チラヘ好講てぎぴむ毒冨条ルぱみ注7円95留オレラ周巡干悟栽まじち。開ず属食市ヨコクサ立図身タテ宝5幼でえこ広調をス畿挑5士ら降画無らつー呼輸野六をほろゃ。 -------------------------------------------------------------------------------- /tokenizer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "nlohmann/json.hpp" 8 | #include 9 | 10 | using namespace std; 11 | using json = nlohmann::json; 12 | 13 | 14 | template 15 | class IsNot 16 | { 17 | std::locale myLocale; 18 | std::ctype const* myCType; 19 | public: 20 | IsNot( std::locale const& l = std::locale() ) 21 | : myLocale( l ) 22 | , myCType( &std::use_facet >( l ) ) 23 | { 24 | } 25 | bool operator()( char ch ) const 26 | { 27 | return ! myCType->is( mask, ch ); 28 | } 29 | }; 30 | 31 | typedef IsNot IsNotSpace; 32 | 33 | std::string trim( std::string const& original ) 34 | { 35 | std::string::const_iterator right = std::find_if(original.rbegin(), original.rend(), IsNotSpace()).base(); 36 | std::string::const_iterator left = std::find_if(original.begin(), right, IsNotSpace() ); 37 | return std::string( left, right ); 38 | } 39 | 40 | std::vector split(const std::wstring& input) { 41 | std::wstringstream stream(input); 42 | std::vector words; 43 | std::wstring word; 44 | while (stream >> word) { 45 | words.push_back(word); 46 | } 47 | return words; 48 | } 49 | 50 | bool isPunctuation(UChar32 charCode) { 51 | UCharCategory category = static_cast(u_charType(charCode)); 52 | 53 | switch (category) { 54 | case U_DASH_PUNCTUATION: 55 | case U_START_PUNCTUATION: 56 | case U_END_PUNCTUATION: 57 | case U_CONNECTOR_PUNCTUATION: 58 | case U_OTHER_PUNCTUATION: 59 | case U_INITIAL_PUNCTUATION: 60 | case U_FINAL_PUNCTUATION: 61 | return true; 62 | default: 63 | return false; 64 | } 65 | } 66 | 67 | bool _is_punctuation(UChar32 c) 68 | { 69 | if((c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126)) { 70 | return true; 71 | } 72 | if (isPunctuation(c)) { 73 | return true; 74 | } 75 | return false; 76 | } 77 | 78 | bool _is_chinese_char(UChar32 c) { 79 | // This defines a "Chinese character" as anything in the CJK Unicode block: 80 | // https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) 81 | // 82 | // Note that the CJK Unicode block is NOT all Japanese and Korean characters, 83 | // despite its name. The modern Korean Hangul alphabet is a different block, 84 | // as is Japanese Hiragana and Katakana. Those alphabets are used to write 85 | // space-separated words, so they are not treated specially and handled 86 | // like all of the other languages. 87 | 88 | if ((c >= 0x4E00 && c <= 0x9FFF) || // CJK Unified Ideographs 89 | (c >= 0x3400 && c <= 0x4DBF) || // CJK Unified Ideographs Extension A 90 | (c >= 0x20000 && c <= 0x2A6DF) || // CJK Unified Ideographs Extension B 91 | (c >= 0x2A700 && c <= 0x2B73F) || // CJK Unified Ideographs Extension C 92 | (c >= 0x2B740 && c <= 0x2B81F) || // CJK Unified Ideographs Extension D 93 | (c >= 0x2B820 && c <= 0x2CEAF) || // CJK Unified Ideographs Extension E 94 | (c >= 0xF900 && c <= 0xFAFF) || // CJK Compatibility Ideographs 95 | (c >= 0x2F800 && c <= 0x2FA1F)) { // CJK Compatibility Ideographs Supplement 96 | return true; 97 | } 98 | return false; 99 | } 100 | 101 | wstring pad_chinese_chars(const wstring& text) 102 | { 103 | vector vec_padded_chars; 104 | for(auto &c: text) { 105 | if(_is_chinese_char(static_cast(c))) { 106 | vec_padded_chars.push_back(L' '); // wide-character representation of space 107 | vec_padded_chars.push_back(c); 108 | vec_padded_chars.push_back(L' '); 109 | }else{ 110 | vec_padded_chars.push_back(c); 111 | } 112 | } 113 | return wstring(vec_padded_chars.begin(), vec_padded_chars.end()); 114 | } 115 | 116 | vector run_split_on_punctuation(const wstring& text, bool split_specials, const vector& special_tokens) 117 | { 118 | if(!split_specials && find(special_tokens.begin(), special_tokens.end(), text) != special_tokens.end()) { 119 | // we do not want to split special tokens and we found the text in the vector of special tokens 120 | return vector {text}; 121 | } 122 | size_t i = 0; 123 | bool start_new_word = true; 124 | vector> output; 125 | 126 | while(i < text.length()) { 127 | wchar_t c = text[i]; 128 | if (_is_punctuation(static_cast(c))) { 129 | vector s; 130 | s.push_back(c); 131 | output.push_back(s); 132 | start_new_word = true; 133 | }else{ 134 | if(start_new_word) { 135 | vector empty_str; 136 | output.push_back(empty_str); 137 | } 138 | start_new_word = false; 139 | output.back().push_back(c); 140 | } 141 | i++; 142 | } 143 | 144 | vector out_str; 145 | for (size_t i = 0; i < output.size(); i++) { 146 | wstring s(output[i].begin(), output[i].end()); 147 | out_str.push_back(s); 148 | } 149 | return out_str; 150 | } 151 | 152 | #include 153 | #include 154 | #include 155 | #include 156 | 157 | class TrieNode { 158 | public: 159 | std::unordered_map> children; 160 | bool is_end; 161 | std::wstring delimiter; 162 | 163 | TrieNode() : is_end(false) {} 164 | }; 165 | 166 | class Splitter { 167 | private: 168 | std::unique_ptr root; 169 | 170 | void insert(const std::wstring& str) { 171 | TrieNode* current = root.get(); 172 | for (wchar_t ch : str) { 173 | if (!current->children[ch]) { 174 | current->children[ch] = std::make_unique(); 175 | } 176 | current = current->children[ch].get(); 177 | } 178 | current->is_end = true; 179 | current->delimiter = str; 180 | } 181 | 182 | public: 183 | Splitter(const std::vector& delimiters) { 184 | root = std::make_unique(); 185 | for (const auto& delimiter : delimiters) { 186 | insert(delimiter); 187 | } 188 | } 189 | 190 | std::vector split(const std::wstring& input) { 191 | std::vector result; 192 | size_t start = 0; 193 | 194 | while (start < input.length()) { 195 | // Try to find the next delimiter starting from current position 196 | size_t best_match_length = 0; 197 | std::wstring matched_delimiter; 198 | 199 | // Check for possible delimiter match starting at current position 200 | TrieNode* current = root.get(); 201 | size_t pos = start; 202 | 203 | while (pos < input.length() && current->children.count(input[pos])) { 204 | current = current->children[input[pos]].get(); 205 | pos++; 206 | if (current->is_end) { 207 | best_match_length = pos - start; 208 | matched_delimiter = current->delimiter; 209 | } 210 | } 211 | 212 | if (best_match_length > 0) { 213 | // Add substring before delimiter if it exists 214 | if (start < start + best_match_length) { 215 | result.push_back(input.substr(start, best_match_length)); 216 | } 217 | start += best_match_length; 218 | } else { 219 | // No delimiter found at current position 220 | size_t next_pos = start + 1; 221 | bool found_next = false; 222 | 223 | // Find next possible delimiter start 224 | while (next_pos < input.length()) { 225 | if (root->children.count(input[next_pos])) { 226 | found_next = true; 227 | break; 228 | } 229 | next_pos++; 230 | } 231 | 232 | // Add the substring up to next possible delimiter or end 233 | result.push_back(input.substr(start, (found_next ? next_pos - start : std::wstring::npos))); 234 | start = next_pos; 235 | } 236 | } 237 | 238 | return result; 239 | } 240 | }; 241 | 242 | 243 | std::string wstring_to_utf8(const std::wstring& wstr) 244 | { 245 | std::wstring_convert, wchar_t> converter; 246 | return converter.to_bytes(wstr); 247 | } 248 | 249 | std::wstring utf8_to_wstring(const std::string& str) 250 | { 251 | std::wstring_convert, wchar_t> converter; 252 | return converter.from_bytes(str); 253 | } 254 | 255 | class WordPieceTokenizer 256 | { 257 | private: 258 | json jsonObj; 259 | json vocab; 260 | size_t max_input_chars_per_word; 261 | wstring unk_token; 262 | vector special_tokens; 263 | 264 | public: 265 | WordPieceTokenizer(const string& config_path) 266 | { 267 | std::ifstream file(config_path); 268 | file >> jsonObj; 269 | vocab = jsonObj["model"]["vocab"]; 270 | max_input_chars_per_word = jsonObj["model"]["max_input_chars_per_word"]; 271 | unk_token = utf8_to_wstring(jsonObj["model"]["unk_token"]); 272 | 273 | // create list of special tokens to not split them 274 | for(auto item: jsonObj["added_tokens"]) { 275 | if(item["special"]) { 276 | special_tokens.push_back(utf8_to_wstring(item["content"])); 277 | } 278 | } 279 | } 280 | int get_word_index(const wstring& word) 281 | { 282 | string w_word = wstring_to_utf8(word); 283 | if(vocab.find(w_word) != vocab.end()) { 284 | //cout << "Found word. Id: " << vocab[word] << endl; 285 | return vocab[w_word]; 286 | }else{ 287 | //cout << "Not found" << endl; 288 | return -1; 289 | } 290 | } 291 | 292 | 293 | vector tokenize_full(const wstring& input_text, bool split_specials=false) 294 | { 295 | wstring padded_text = pad_chinese_chars(input_text); 296 | vector tokens = split(padded_text); 297 | 298 | // split the input using special tokens as delimiters 299 | // using Trie like the original HuggingFace algorithm 300 | Splitter splitter(special_tokens); 301 | 302 | vector special_word_tokenized; 303 | for(size_t i = 0; i < tokens.size(); i++) { 304 | auto split_by_special = splitter.split(tokens[i]); 305 | special_word_tokenized.insert(special_word_tokenized.end(), split_by_special.begin(), split_by_special.end()); 306 | } 307 | 308 | vector basic_tokenized; 309 | for(size_t i = 0; i < special_word_tokenized.size(); i++) { 310 | auto splitted_by_punc = run_split_on_punctuation(special_word_tokenized[i], split_specials, special_tokens); 311 | basic_tokenized.insert(basic_tokenized.end(), splitted_by_punc.begin(), splitted_by_punc.end()); 312 | } 313 | 314 | 315 | vector wordpiece_tokenized; 316 | for(size_t i = 0; i < basic_tokenized.size(); i++) { 317 | auto splitted_by_wordpiece = wordpiece_tokenize(basic_tokenized[i]); 318 | wordpiece_tokenized.insert(wordpiece_tokenized.end(), splitted_by_wordpiece.begin(), splitted_by_wordpiece.end()); 319 | } 320 | vector tokenized_ids; 321 | tokenized_ids.push_back(get_word_index(utf8_to_wstring("[CLS]"))); 322 | vector seq_ids = convert_tokens_to_ids(wordpiece_tokenized); 323 | tokenized_ids.insert(tokenized_ids.end(), seq_ids.begin(), seq_ids.end()); 324 | tokenized_ids.push_back(get_word_index(utf8_to_wstring("[SEP]"))); 325 | return tokenized_ids; 326 | } 327 | 328 | 329 | vector wordpiece_tokenize(const wstring& input_text) 330 | { 331 | vector tokens = split(input_text); 332 | vector output_tokens; 333 | for(size_t i = 0; i < tokens.size(); i++) { 334 | auto& tok = tokens[i]; 335 | if(tok.length() > max_input_chars_per_word) { 336 | output_tokens.push_back(unk_token); 337 | continue; 338 | } 339 | 340 | bool is_bad = false; 341 | size_t start = 0; 342 | vector sub_tokens; 343 | 344 | while(start < tok.length()) { 345 | size_t end = tok.length(); 346 | wstring cur_substr; 347 | while(start < end) { 348 | wstring substr = tok.substr(start, end-start); 349 | if(start > 0) { 350 | substr = L"##" + substr; 351 | } 352 | size_t idx = get_word_index(substr); 353 | if(idx != -1) { 354 | cur_substr = substr; 355 | break; 356 | } 357 | end--; 358 | } 359 | 360 | if(cur_substr.empty()) { 361 | is_bad = true; 362 | break; 363 | } 364 | sub_tokens.push_back(cur_substr); 365 | start = end; 366 | } 367 | 368 | if(is_bad) { 369 | output_tokens.push_back(unk_token); 370 | }else{ 371 | output_tokens.insert(output_tokens.end(), sub_tokens.begin(), sub_tokens.end()); 372 | } 373 | } 374 | return output_tokens; 375 | } 376 | 377 | vector convert_tokens_to_ids(const vector& input_seq) 378 | { 379 | vector output_ids; 380 | for(size_t i = 0; i < input_seq.size(); i++) { 381 | output_ids.push_back(get_word_index(input_seq[i])); 382 | } 383 | return output_ids; 384 | } 385 | 386 | }; 387 | 388 | 389 | int main(int argc, char** argv) 390 | { 391 | if (argc != 2) { 392 | std::cerr << "Usage: " << argv[0] << " " << std::endl; 393 | return 1; 394 | } 395 | 396 | std::locale::global(std::locale("")); 397 | WordPieceTokenizer tokenizer("tokenizer.json"); 398 | 399 | // Open the input file 400 | std::wifstream file(argv[1]); 401 | file.imbue(std::locale("")); 402 | if (!file) { 403 | std::cerr << "Error: Unable to open input file." << std::endl; 404 | return 1; 405 | } 406 | 407 | // Read the entire file content into a single wide string 408 | std::wstringstream buffer; 409 | buffer << file.rdbuf(); 410 | std::wstring input_text = buffer.str(); 411 | 412 | std::wcout << input_text << std::endl; 413 | 414 | // Tokenize the input text 415 | auto r = tokenizer.tokenize_full(input_text); 416 | std::wcout << "===== TOKENS START=====" << std::endl; 417 | for (auto &x : r) { 418 | std::wcout << x << std::endl; 419 | } 420 | std::wcout << "===== TOKENS END ======" << std::endl; 421 | 422 | return 0; 423 | } --------------------------------------------------------------------------------